DocSpace-buildtools/common/ASC.Data.Storage/StaticUploader.cs

346 lines
13 KiB
C#
Raw Normal View History

2019-06-04 14:43:20 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
namespace ASC.Data.Storage
{
2020-10-22 17:57:18 +00:00
[Scope(Additional = typeof(StaticUploaderExtension))]
2019-06-04 14:43:20 +00:00
public class StaticUploader
{
protected readonly DistributedTaskQueue Queue;
private ICache _cache;
private static readonly TaskScheduler s_scheduler;
private static readonly CancellationTokenSource s_tokenSource;
private static readonly object s_locker;
private readonly IServiceProvider _serviceProvider;
private readonly TenantManager _tenantManager;
private readonly SettingsManager _settingsManager;
private readonly StorageSettingsHelper _storageSettingsHelper;
2019-11-06 15:03:09 +00:00
2019-06-04 14:43:20 +00:00
static StaticUploader()
{
s_scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 4).ConcurrentScheduler;
s_locker = new object();
s_tokenSource = new CancellationTokenSource();
2019-06-04 14:43:20 +00:00
}
2019-11-06 15:03:09 +00:00
2020-02-17 08:58:14 +00:00
public StaticUploader(
IServiceProvider serviceProvider,
TenantManager tenantManager,
SettingsManager settingsManager,
StorageSettingsHelper storageSettingsHelper,
ICache cache,
2020-09-29 13:02:47 +00:00
DistributedTaskQueueOptionsManager options)
2019-11-06 15:03:09 +00:00
{
_cache = cache;
_serviceProvider = serviceProvider;
_tenantManager = tenantManager;
_settingsManager = settingsManager;
_storageSettingsHelper = storageSettingsHelper;
Queue = options.Get<UploadOperationProgress>();
2019-11-06 15:03:09 +00:00
}
2019-06-04 14:43:20 +00:00
2019-09-13 11:18:27 +00:00
public string UploadFile(string relativePath, string mappedPath, Action<string> onComplete = null)
2019-06-04 14:43:20 +00:00
{
2022-02-10 11:06:37 +00:00
if (s_tokenSource.Token.IsCancellationRequested)
{
return null;
}
if (!CanUpload())
{
return null;
}
if (!File.Exists(mappedPath))
{
return null;
}
var tenantId = _tenantManager.GetCurrentTenant().TenantId;
2019-06-04 14:43:20 +00:00
UploadOperation uploadOperation;
var key = GetCacheKey(tenantId.ToString(), relativePath);
lock (s_locker)
2019-06-04 14:43:20 +00:00
{
uploadOperation = _cache.Get<UploadOperation>(key);
2019-06-04 14:43:20 +00:00
if (uploadOperation != null)
{
return !string.IsNullOrEmpty(uploadOperation.Result) ? uploadOperation.Result : string.Empty;
}
uploadOperation = new UploadOperation(_serviceProvider, tenantId, relativePath, mappedPath);
_cache.Insert(key, uploadOperation, DateTime.MaxValue);
2019-06-04 14:43:20 +00:00
}
2019-11-06 15:03:09 +00:00
uploadOperation.DoJob();
2019-08-15 15:08:40 +00:00
onComplete?.Invoke(uploadOperation.Result);
2019-06-04 14:43:20 +00:00
return uploadOperation.Result;
}
2019-09-13 11:18:27 +00:00
public Task<string> UploadFileAsync(string relativePath, string mappedPath, Action<string> onComplete = null)
2019-06-04 14:43:20 +00:00
{
var tenantId = _tenantManager.GetCurrentTenant().TenantId;
2019-06-04 14:43:20 +00:00
var task = new Task<string>(() =>
2019-11-06 15:03:09 +00:00
{
using var scope = _serviceProvider.CreateScope();
2020-08-31 08:18:07 +00:00
var scopeClass = scope.ServiceProvider.GetService<StaticUploaderScope>();
2020-10-02 07:19:02 +00:00
var (tenantManager, staticUploader, _, _, _) = scopeClass;
tenantManager.SetCurrentTenant(tenantId);
2019-09-17 08:07:46 +00:00
return staticUploader.UploadFile(relativePath, mappedPath, onComplete);
2019-06-04 14:43:20 +00:00
}, TaskCreationOptions.LongRunning);
task.ConfigureAwait(false);
task.Start(s_scheduler);
2019-06-04 14:43:20 +00:00
return task;
}
2021-06-16 15:00:27 +00:00
public void UploadDir(string relativePath, string mappedPath)
2019-06-04 14:43:20 +00:00
{
2022-02-10 11:06:37 +00:00
if (!CanUpload())
{
return;
}
if (!Directory.Exists(mappedPath))
{
return;
}
var tenant = _tenantManager.GetCurrentTenant();
2019-06-04 14:43:20 +00:00
var key = typeof(UploadOperationProgress).FullName + tenant.TenantId;
UploadOperationProgress uploadOperation;
lock (s_locker)
2019-06-04 14:43:20 +00:00
{
2020-09-29 13:02:47 +00:00
uploadOperation = Queue.GetTask<UploadOperationProgress>(key);
2022-02-10 11:06:37 +00:00
if (uploadOperation != null)
{
return;
}
uploadOperation = new UploadOperationProgress(_serviceProvider, key, tenant.TenantId, relativePath, mappedPath);
2020-10-02 07:19:02 +00:00
Queue.QueueTask(uploadOperation);
2019-06-04 14:43:20 +00:00
}
}
2019-09-13 11:18:27 +00:00
public bool CanUpload()
2019-06-04 14:43:20 +00:00
{
var current = _storageSettingsHelper.DataStoreConsumer(_settingsManager.Load<CdnStorageSettings>());
2019-06-04 14:43:20 +00:00
if (current == null || !current.IsSet || (string.IsNullOrEmpty(current["cnamessl"]) && string.IsNullOrEmpty(current["cname"])))
{
return false;
}
return true;
}
public static void Stop()
{
s_tokenSource.Cancel();
2019-06-04 14:43:20 +00:00
}
2020-10-02 07:19:02 +00:00
public UploadOperationProgress GetProgress(int tenantId)
2019-06-04 14:43:20 +00:00
{
lock (s_locker)
2019-06-04 14:43:20 +00:00
{
var key = typeof(UploadOperationProgress).FullName + tenantId;
2020-10-02 07:19:02 +00:00
return Queue.GetTask<UploadOperationProgress>(key);
2019-06-04 14:43:20 +00:00
}
}
private static string GetCacheKey(string tenantId, string path)
{
return typeof(UploadOperation).FullName + tenantId + path;
}
}
public class UploadOperation
{
public string Result { get; private set; }
private readonly ILog _logger;
private readonly int _tenantId;
private readonly string _path;
private readonly string _mappedPath;
private readonly IServiceProvider _serviceProvider;
2019-11-06 15:03:09 +00:00
2019-09-09 12:56:33 +00:00
public UploadOperation(IServiceProvider serviceProvider, int tenantId, string path, string mappedPath)
2019-11-06 15:03:09 +00:00
{
_serviceProvider = serviceProvider;
_logger = _serviceProvider.GetService<IOptionsMonitor<ILog>>().CurrentValue;
_tenantId = tenantId;
_path = path.TrimStart('/');
_mappedPath = mappedPath;
2019-06-04 14:43:20 +00:00
Result = string.Empty;
}
public string DoJob()
{
try
2019-11-06 15:03:09 +00:00
{
using var scope = _serviceProvider.CreateScope();
2020-08-31 08:18:07 +00:00
var scopeClass = scope.ServiceProvider.GetService<StaticUploaderScope>();
2020-09-07 12:01:15 +00:00
var (tenantManager, _, securityContext, settingsManager, storageSettingsHelper) = scopeClass;
var tenant = tenantManager.GetTenant(_tenantId);
2019-11-06 15:03:09 +00:00
tenantManager.SetCurrentTenant(tenant);
2021-08-18 14:04:16 +00:00
securityContext.AuthenticateMeWithoutCookie(tenant.OwnerId);
2019-11-06 15:03:09 +00:00
2020-08-31 08:18:07 +00:00
var dataStore = storageSettingsHelper.DataStore(settingsManager.Load<CdnStorageSettings>());
2019-06-04 14:43:20 +00:00
if (File.Exists(_mappedPath))
2019-06-04 14:43:20 +00:00
{
if (!dataStore.IsFile(_path))
2019-06-04 14:43:20 +00:00
{
using var stream = File.OpenRead(_mappedPath);
dataStore.Save(_path, stream);
2019-06-04 14:43:20 +00:00
}
Result = dataStore.GetInternalUri("", _path, TimeSpan.Zero, null).AbsoluteUri.ToLower();
_logger.DebugFormat("UploadFile {0}", Result);
2019-06-04 14:43:20 +00:00
return Result;
}
}
catch (Exception e)
{
_logger.Error(e);
}
2019-06-04 14:43:20 +00:00
return null;
}
}
2021-05-18 18:24:22 +00:00
[Transient]
2020-10-02 07:19:02 +00:00
public class UploadOperationProgress : DistributedTaskProgress
{
2020-09-29 13:02:47 +00:00
public int TenantId { get; }
private readonly string _relativePath;
private readonly string _mappedPath;
private readonly IEnumerable<string> _directoryFiles;
private readonly IServiceProvider _serviceProvider;
2020-09-29 13:02:47 +00:00
public UploadOperationProgress(IServiceProvider serviceProvider, string key, int tenantId, string relativePath, string mappedPath)
2020-09-29 13:02:47 +00:00
{
_serviceProvider = serviceProvider;
2020-09-29 13:02:47 +00:00
Id = key;
Status = DistributedTaskStatus.Created;
2020-10-02 07:19:02 +00:00
2020-09-29 13:02:47 +00:00
TenantId = tenantId;
_relativePath = relativePath;
_mappedPath = mappedPath;
2019-06-04 14:43:20 +00:00
var extensions = ".png|.jpeg|.jpg|.gif|.ico|.swf|.mp3|.ogg|.eot|.svg|.ttf|.woff|.woff2|.css|.less|.js";
var extensionsArray = extensions.Split('|');
_directoryFiles = Directory.GetFiles(mappedPath, "*", SearchOption.AllDirectories)
2019-06-04 14:43:20 +00:00
.Where(r => extensionsArray.Contains(Path.GetExtension(r)))
.ToList();
StepCount = _directoryFiles.Count();
2019-06-04 14:43:20 +00:00
}
2020-10-02 07:19:02 +00:00
protected override void DoJob()
2020-09-29 13:02:47 +00:00
{
using var scope = _serviceProvider.CreateScope();
2020-09-29 13:02:47 +00:00
var tenantManager = scope.ServiceProvider.GetService<TenantManager>();
2020-10-02 07:19:02 +00:00
var staticUploader = scope.ServiceProvider.GetService<StaticUploader>();
2020-09-29 13:02:47 +00:00
var tenant = tenantManager.GetTenant(TenantId);
tenantManager.SetCurrentTenant(tenant);
tenant.SetStatus(TenantStatus.Migrating);
tenantManager.SaveTenant(tenant);
2020-10-02 07:19:02 +00:00
PublishChanges();
2020-09-29 13:02:47 +00:00
foreach (var file in _directoryFiles)
2019-06-04 14:43:20 +00:00
{
var filePath = file.Substring(_mappedPath.TrimEnd('/').Length);
staticUploader.UploadFile(CrossPlatform.PathCombine(_relativePath, filePath), file, (res) => StepDone());
2020-09-29 13:02:47 +00:00
}
tenant.SetStatus(TenantStatus.Active);
2020-09-29 13:02:47 +00:00
tenantManager.SaveTenant(tenant);
}
public object Clone()
{
return MemberwiseClone();
}
}
[Scope]
public class StaticUploaderScope
{
private readonly TenantManager _tenantManager;
private readonly StaticUploader _staticUploader;
private readonly SecurityContext _securityContext;
private readonly SettingsManager _settingsManager;
private readonly StorageSettingsHelper _storageSettingsHelper;
public StaticUploaderScope(TenantManager tenantManager,
StaticUploader staticUploader,
SecurityContext securityContext,
SettingsManager settingsManager,
StorageSettingsHelper storageSettingsHelper)
{
_tenantManager = tenantManager;
_staticUploader = staticUploader;
_securityContext = securityContext;
_settingsManager = settingsManager;
_storageSettingsHelper = storageSettingsHelper;
}
public void Deconstruct(
out TenantManager tenantManager,
out StaticUploader staticUploader,
out SecurityContext securityContext,
out SettingsManager settingsManager,
out StorageSettingsHelper storageSettingsHelper)
{
tenantManager = _tenantManager;
staticUploader = _staticUploader;
securityContext = _securityContext;
settingsManager = _settingsManager;
storageSettingsHelper = _storageSettingsHelper;
}
2019-11-06 15:03:09 +00:00
}
public static class StaticUploaderExtension
{
2020-10-22 17:57:18 +00:00
public static void Register(DIHelper services)
2019-11-06 15:03:09 +00:00
{
2020-10-22 17:57:18 +00:00
services.TryAdd<StaticUploaderScope>();
services.AddDistributedTaskQueueService<UploadOperationProgress>(1);
2019-11-06 15:03:09 +00:00
}
2019-06-04 14:43:20 +00:00
}
}