private static string GetUrlToFile(Stream docxStream)
        {
            var externalUri = Files.Classes.PathProvider.GetTempUrl(docxStream, FormatDocx);

            externalUri = DocumentServiceConnector.ReplaceCommunityAdress(externalUri);
            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri);

            var    revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());
            string urlToFile;

            DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile);

            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile);
            return(urlToFile);
        }
Esempio n. 2
0
        private static string GetUrlToFile(Stream docxStream)
        {
            var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());

            var externalUri = DocumentServiceConnector.GetExternalUri(docxStream, "text/plain", revisionId);

            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri);

            string urlToFile;

            DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile);

            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile);
            return(urlToFile);
        }
Esempio n. 3
0
        private static string ConvertFile(string downloadUrl, string fromExt, Token token)
        {
            Global.Logger.Debug("GoogleDriveApp: convert file");

            if (string.IsNullOrEmpty(downloadUrl))
            {
                Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
                throw new Exception("downloadUrl is null");
            }

            var request = (HttpWebRequest)WebRequest.Create(downloadUrl);

            request.Method = "GET";
            request.Headers.Add("Authorization", "Bearer " + token);

            try
            {
                using (var response = request.GetResponse())
                    using (var fileStream = new ResponseStream(response))
                    {
                        Global.Logger.Debug("GoogleDriveApp: GetExternalUri - " + downloadUrl);

                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                        downloadUrl = DocumentServiceConnector.GetExternalUri(fileStream, response.ContentType, key);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetExternalUri", e);
                request.Abort();
            }

            var toExt = FileUtility.GetInternalExtension(fromExt);

            try
            {
                Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl);

                var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl);
            }
            catch (Exception e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e);
            }

            return(downloadUrl);
        }
Esempio n. 4
0
        public object GetDocServiceUrl(bool version)
        {
            var url = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.DocServiceApiUrl);

            if (!version)
            {
                return(url);
            }

            var dsVersion = DocumentServiceConnector.GetVersion();

            return(new
            {
                version = dsVersion,
                docServiceUrlApi = url,
            });
        }
Esempio n. 5
0
        public PdfCreator(IOptionsMonitor <ILog> logger,
                          Files.Classes.PathProvider filesPathProvider,
                          DocumentServiceConnector documentServiceConnector,
                          IServiceProvider serviceProvider,
                          OrganisationLogoManager organisationLogoManager,
                          DaoFactory daoFactory,
                          InvoiceFormattedData invoiceFormattedData)
        {
            _filesPathProvider = filesPathProvider;

            _logger = logger.Get("ASC.CRM");

            _documentServiceConnector = documentServiceConnector;
            _serviceProvider          = serviceProvider;
            _organisationLogoManager  = organisationLogoManager;
            _daoFactory           = daoFactory;
            _invoiceFormattedData = invoiceFormattedData;
        }
Esempio n. 6
0
        private string GetUrlToFile(Stream docxStream)
        {
            var externalUri = _filesPathProvider.GetTempUrl(docxStream, FormatDocx);

            externalUri = _documentServiceConnector.ReplaceCommunityAdress(externalUri);

            _logger.DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri);

            var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());

            string urlToFile;

            _documentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, null, null, null, false, out urlToFile);

            _logger.DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile);

            return(urlToFile);
        }
Esempio n. 7
0
        private bool GetThumbnailUrl(File file, string toExtension, out string url)
        {
            var fileUri = PathProvider.GetFileStreamUrl(file);

            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);

            var fileExtension = file.ConvertedExtension;
            var docKey        = DocumentServiceHelper.GetDocKey(file);

            var thumbnailAspect   = config.ThumbnailAspect;
            var thumbnail         = GetThumbnailData(thumbnailAspect);
            var spreadsheetLayout = GetSpreadsheetLayout(thumbnailAspect);

            var operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, null, thumbnail, spreadsheetLayout, false, out url);

            operationResultProgress = Math.Min(operationResultProgress, 100);
            return(operationResultProgress == 100);
        }
Esempio n. 8
0
        private static void TimerCallback(object obj)
        {
            lock (Locker)
            {
                var keys = Queue.Keys.ToList();

                foreach (var key in keys)
                {
                    try
                    {
                        Dictionary <string, string> urls;
                        var builderKey = DocumentServiceConnector.DocbuilderRequest(Queue[key].BuilderKey, null, true, out urls);

                        if (builderKey == null)
                        {
                            throw new Exception(CRMReportResource.ErrorNullDocbuilderResponse);
                        }

                        Queue[key].BuilderKey = builderKey;
                        SetCacheValue(Queue[key]);

                        if (urls != null && urls.ContainsKey(TmpFileName))
                        {
                            SaveReportFile(Queue[key], urls[TmpFileName]);
                            Queue.Remove(key);
                        }
                    }
                    catch (Exception ex)
                    {
                        Queue[key].IsCompleted = true;
                        Queue[key].Percentage  = 100;
                        Queue[key].Status      = ReportTaskStatus.Failed;
                        Queue[key].ErrorText   = ex.Message;
                        SetCacheValue(Queue[key]);
                        Queue.Remove(key);
                    }
                }

                if (Queue.Any())
                {
                    RunTimer(1000);
                }
            }
        }
        public static ConverterData StartCreationFileAsync(Invoice data)
        {
            using (var docxStream = GetStreamDocx(data))
            {
                var externalUri = Files.Classes.PathProvider.GetTempUrl(docxStream, FormatDocx);
                externalUri = DocumentServiceConnector.ReplaceCommunityAdress(externalUri);

                var    revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());
                string urlToFile;
                DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile);

                return(new ConverterData
                {
                    StorageUrl = externalUri,
                    RevisionId = revisionId,
                    InvoiceId = data.ID,
                });
            }
        }
Esempio n. 10
0
        public static ConverterData StartCreationFileAsync(Invoice data)
        {
            using (var docxStream = GetStreamDocx(data))
            {
                var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());

                var externalUri = DocumentServiceConnector.GetExternalUri(docxStream, MimeMapping.GetMimeMapping(FormatDocx), revisionId);

                string urlToFile;
                DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile);

                return(new ConverterData
                {
                    StorageUrl = externalUri,
                    RevisionId = revisionId,
                    InvoiceId = data.ID,
                });
            }
        }
Esempio n. 11
0
 public FileConverter(
     FileUtility fileUtility,
     FilesLinkUtility filesLinkUtility,
     IDaoFactory daoFactory,
     SetupInfo setupInfo,
     PathProvider pathProvider,
     FileSecurity fileSecurity,
     FileMarker fileMarker,
     TenantManager tenantManager,
     AuthContext authContext,
     EntryManager entryManager,
     FilesSettingsHelper filesSettingsHelper,
     GlobalFolderHelper globalFolderHelper,
     FilesMessageService filesMessageService,
     FileShareLink fileShareLink,
     DocumentServiceHelper documentServiceHelper,
     DocumentServiceConnector documentServiceConnector,
     FileTrackerHelper fileTracker,
     BaseCommonLinkUtility baseCommonLinkUtility,
     EntryStatusManager entryStatusManager,
     IServiceProvider serviceProvider)
 {
     FileUtility              = fileUtility;
     FilesLinkUtility         = filesLinkUtility;
     DaoFactory               = daoFactory;
     SetupInfo                = setupInfo;
     PathProvider             = pathProvider;
     FileSecurity             = fileSecurity;
     FileMarker               = fileMarker;
     TenantManager            = tenantManager;
     AuthContext              = authContext;
     EntryManager             = entryManager;
     FilesSettingsHelper      = filesSettingsHelper;
     GlobalFolderHelper       = globalFolderHelper;
     FilesMessageService      = filesMessageService;
     FileShareLink            = fileShareLink;
     DocumentServiceHelper    = documentServiceHelper;
     DocumentServiceConnector = documentServiceConnector;
     FileTracker              = fileTracker;
     BaseCommonLinkUtility    = baseCommonLinkUtility;
     EntryStatusManager       = entryStatusManager;
     ServiceProvider          = serviceProvider;
 }
Esempio n. 12
0
 public Builder(
     Common.Utils.ConfigurationExtension configurationExtension,
     TenantManager tenantManager,
     IDaoFactory daoFactory,
     DocumentServiceConnector documentServiceConnector,
     DocumentServiceHelper documentServiceHelper,
     Global global,
     PathProvider pathProvider,
     IOptionsMonitor <ILog> log)
 {
     this.config              = ThumbnailSettings.GetInstance(configurationExtension);
     TenantManager            = tenantManager;
     DaoFactory               = daoFactory;
     DocumentServiceConnector = documentServiceConnector;
     DocumentServiceHelper    = documentServiceHelper;
     Global       = global;
     PathProvider = pathProvider;
     logger       = log.Get("ASC.Files.ThumbnailBuilder");
 }
Esempio n. 13
0
        public static File GetConvertedFile(ConverterData data, DaoFactory daoFactory)
        {
            if (string.IsNullOrEmpty(data.StorageUrl) || string.IsNullOrEmpty(data.RevisionId))
            {
                return(null);
            }

            string urlToFile;

            DocumentServiceConnector.GetConvertedUri(data.StorageUrl, FormatDocx, FormatPdf, data.RevisionId, true, out urlToFile);

            if (string.IsNullOrEmpty(urlToFile))
            {
                return(null);
            }

            var invoice = daoFactory.InvoiceDao.GetByID(data.InvoiceId);

            return(SaveFile(invoice, urlToFile, daoFactory));
        }
Esempio n. 14
0
        private bool GetThumbnailUrl(File <T> file, string toExtension, out string url)
        {
            var fileUri = PathProvider.GetFileStreamUrl(file);

            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);

            var fileExtension = file.ConvertedExtension;
            var docKey        = DocumentServiceHelper.GetDocKey(file);
            var thumbnail     = new DocumentService.ThumbnailData
            {
                Aspect = 2,
                First  = true,
                //Height = config.ThumbnaillHeight,
                //Width = config.ThumbnaillWidth
            };
            var spreadsheetLayout = new DocumentService.SpreadsheetLayout
            {
                IgnorePrintArea = true,
                //Orientation = "landscape", // "297mm" x "210mm"
                FitToHeight = 0,
                FitToWidth  = 1,
                Headings    = false,
                GridLines   = false,
                Margins     = new DocumentService.SpreadsheetLayout.LayoutMargins
                {
                    Top    = "0mm",
                    Right  = "0mm",
                    Bottom = "0mm",
                    Left   = "0mm"
                },
                PageSize = new DocumentService.SpreadsheetLayout.LayoutPageSize
                {
                    Width  = (config.ThumbnaillWidth * 1.5) + "mm", // 192 * 1.5 = "288mm",
                    Height = (config.ThumbnaillHeight * 1.5) + "mm" // 128 * 1.5 = "192mm"
                }
            };
            var operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, thumbnail, spreadsheetLayout, false, out url);

            operationResultProgress = Math.Min(operationResultProgress, 100);
            return(operationResultProgress == 100);
        }
Esempio n. 15
0
 public FileConverter(
     FileUtility fileUtility,
     FilesLinkUtility filesLinkUtility,
     IDaoFactory daoFactory,
     SetupInfo setupInfo,
     PathProvider pathProvider,
     FileSecurity fileSecurity,
     FileMarker fileMarker,
     TenantManager tenantManager,
     AuthContext authContext,
     EntryManager entryManager,
     IOptionsMonitor <ILog> options,
     FilesSettingsHelper filesSettingsHelper,
     GlobalFolderHelper globalFolderHelper,
     FilesMessageService filesMessageService,
     FileShareLink fileShareLink,
     DocumentServiceHelper documentServiceHelper,
     DocumentServiceConnector documentServiceConnector,
     IServiceProvider serviceProvider)
 {
     FileUtility              = fileUtility;
     FilesLinkUtility         = filesLinkUtility;
     DaoFactory               = daoFactory;
     SetupInfo                = setupInfo;
     PathProvider             = pathProvider;
     FileSecurity             = fileSecurity;
     FileMarker               = fileMarker;
     TenantManager            = tenantManager;
     AuthContext              = authContext;
     EntryManager             = entryManager;
     FilesSettingsHelper      = filesSettingsHelper;
     GlobalFolderHelper       = globalFolderHelper;
     FilesMessageService      = filesMessageService;
     FileShareLink            = fileShareLink;
     DocumentServiceHelper    = documentServiceHelper;
     DocumentServiceConnector = documentServiceConnector;
     ServiceProvider          = serviceProvider;
     Logger = options.CurrentValue;
     cache  = AscCache.Memory;
 }
Esempio n. 16
0
        private static string ConvertFile(string fileId, string fromExt)
        {
            Global.Logger.Debug("GoogleDriveApp: convert file");

            var downloadUrl = GetFileStreamUrl(fileId);

            var toExt = FileUtility.GetInternalExtension(fromExt);

            try
            {
                Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl);

                var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl);
            }
            catch (Exception e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e);
            }

            return(downloadUrl);
        }
Esempio n. 17
0
        public static Stream Exec(File file, string toExtension)
        {
            if (file.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            var fileExtension = file.ConvertedExtension;

            var requiredFormat = fileExtension.Trim('.').Equals(toExtension.Trim('.'), StringComparison.OrdinalIgnoreCase);

            if (!EnableConvert(file, toExtension) ||
                requiredFormat)
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    return(fileDao.GetFileStream(file));
                }
            }

            var fileUri = PathProvider.GetFileStreamUrl(file);

            var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

            string convertUri;

            DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            return(new ResponseStream(WebRequest.Create(convertUri).GetResponse()));
        }
Esempio n. 18
0
        private void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                using var scope = ServiceProvider.CreateScope();
                var logger          = scope.ServiceProvider.GetService <IOptionsMonitor <ILog> >().CurrentValue;
                var tenantManager   = scope.ServiceProvider.GetService <TenantManager>();
                var userManager     = scope.ServiceProvider.GetService <UserManager>();
                var securityContext = scope.ServiceProvider.GetService <SecurityContext>();
                var daoFactory      = scope.ServiceProvider.GetService <IDaoFactory>();

                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => string.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    var fileSecurity = FileSecurity;
                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;

                        try
                        {
                            int      tenantId;
                            IAccount account;
                            string   password;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;
                                password = operationResult.Password;

                                //if (HttpContext.Current == null && !WorkContext.IsMono)
                                //{
                                //    HttpContext.Current = new HttpContext(
                                //        new HttpRequest("hack", operationResult.Url, string.Empty),
                                //        new HttpResponse(new StringWriter()));
                                //}

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                            }

                            tenantManager.SetCurrentTenant(tenantId);
                            securityContext.AuthenticateMe(account);

                            var user    = userManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file);

                            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, password, true, out convertedFileUrl);
                        }
                        catch (Exception exception)
                        {
                            var password = exception.InnerException != null &&
                                           (exception.InnerException is DocumentService.DocumentServiceException documentServiceException) &&
                                           documentServiceException.Code == DocumentService.DocumentServiceException.ErrorCode.ConvertPassword;

                            logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = exception.Message;
                                        if (password)
                                        {
                                            operationResult.Result = "password";
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                            continue;
                        }

                        operationResultProgress = Math.Min(operationResultProgress, 100);
                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];

                                    if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10))
                                    {
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = FilesCommonResource.ErrorMassage_ConvertTimeout;
                                        logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString);
                                    }
                                    else
                                    {
                                        operationResult.Processed = "";
                                    }
                                    operationResult.Progress = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                }
                            }

                            logger.Debug("CheckConvertFilesStatus iteration continue");
                            continue;
                        }

                        File newFile = null;
                        var  operationResultError = string.Empty;

                        try
                        {
                            newFile = SaveConvertedFile(file, convertedFileUrl);
                        }
                        catch (Exception e)
                        {
                            operationResultError = e.Message;

                            logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", operationResultError, convertedFileUrl, fileUri, e);
                            continue;
                        }
                        finally
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        if (newFile != null)
                                        {
                                            var folderDao   = daoFactory.FolderDao;
                                            var folder      = folderDao.GetFolder(newFile.FolderID);
                                            var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null;
                                            operationResult.Result = FileJsonSerializer(newFile, folderTitle);
                                        }

                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Processed    = "1";
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                        }

                        logger.Debug("CheckConvertFilesStatus iteration end");
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
Esempio n. 19
0
 public GoogleDriveApp(
     PathProvider pathProvider,
     TenantUtil tenantUtil,
     AuthContext authContext,
     SecurityContext securityContext,
     UserManager userManager,
     UserManagerWrapper userManagerWrapper,
     CookiesManager cookiesManager,
     MessageService messageService,
     Global global,
     GlobalStore globalStore,
     EmailValidationKeyProvider emailValidationKeyProvider,
     FilesLinkUtility filesLinkUtility,
     SettingsManager settingsManager,
     PersonalSettingsHelper personalSettingsHelper,
     BaseCommonLinkUtility baseCommonLinkUtility,
     IOptionsMonitor <ILog> option,
     FileUtility fileUtility,
     FilesSettingsHelper filesSettingsHelper,
     IOptionsSnapshot <AccountLinker> snapshot,
     SetupInfo setupInfo,
     GoogleLoginProvider googleLoginProvider,
     TokenHelper tokenHelper,
     DocumentServiceConnector documentServiceConnector,
     ThirdPartyAppHandlerService thirdPartyAppHandlerService,
     IServiceProvider serviceProvider,
     TenantManager tenantManager,
     CoreBaseSettings coreBaseSettings,
     CoreSettings coreSettings,
     IConfiguration configuration,
     ICacheNotify <ConsumerCacheItem> cache,
     ConsumerFactory consumerFactory,
     string name, int order, Dictionary <string, string> additional)
     : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional)
 {
     Logger                      = option.CurrentValue;
     PathProvider                = pathProvider;
     TenantUtil                  = tenantUtil;
     AuthContext                 = authContext;
     SecurityContext             = securityContext;
     UserManager                 = userManager;
     UserManagerWrapper          = userManagerWrapper;
     CookiesManager              = cookiesManager;
     MessageService              = messageService;
     Global                      = global;
     GlobalStore                 = globalStore;
     EmailValidationKeyProvider  = emailValidationKeyProvider;
     FilesLinkUtility            = filesLinkUtility;
     SettingsManager             = settingsManager;
     PersonalSettingsHelper      = personalSettingsHelper;
     BaseCommonLinkUtility       = baseCommonLinkUtility;
     FileUtility                 = fileUtility;
     FilesSettingsHelper         = filesSettingsHelper;
     Snapshot                    = snapshot;
     SetupInfo                   = setupInfo;
     GoogleLoginProvider         = googleLoginProvider;
     TokenHelper                 = tokenHelper;
     DocumentServiceConnector    = documentServiceConnector;
     ThirdPartyAppHandlerService = thirdPartyAppHandlerService;
     ServiceProvider             = serviceProvider;
 }
        public static File ExecDuplicate(File file, string shareLinkKey)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    if (!Global.GetFilesSecurity().CanRead(file))
                    {
                        var readLink = FileShareLink.Check(shareLinkKey, true, fileDao, out file);

                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }

                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }

                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!Global.GetFilesSecurity().CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var    fileUri       = PathProvider.GetFileStreamUrl(file);
                    var    fileExtension = file.ConvertedExtension;
                    var    toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var    docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);
                    string convertUri;
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension)
                    };

                    var req = (HttpWebRequest)WebRequest.Create(convertUri);
                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;

                        newFile = fileDao.SaveFile(newFile, editedFileStream);
                    }

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }
        public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false, ForcesaveType?forcesave = null)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, newExtension, downloadUri, stream);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(doc, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                var fileSecurity = Global.GetFilesSecurity();
                if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentExt = file.ConvertedExtension;
                if (string.IsNullOrEmpty(newExtension))
                {
                    newExtension = FileUtility.GetInternalExtension(file.Title);
                }

                var replaceVersion = false;
                if (file.Forcesave != ForcesaveType.None)
                {
                    if (file.Forcesave == ForcesaveType.User && FilesSettings.StoreForcesave)
                    {
                        file.Version++;
                    }
                    else
                    {
                        replaceVersion = true;
                    }
                }
                else
                {
                    if (file.Version != 1)
                    {
                        file.VersionGroup++;
                    }
                    else
                    {
                        var storeTemplate = Global.GetStoreTemplate();

                        var path = FileConstant.NewDocPath + Thread.CurrentThread.CurrentCulture + "/";
                        if (!storeTemplate.IsDirectory(path))
                        {
                            path = FileConstant.NewDocPath + "default/";
                        }
                        path += "new" + FileUtility.GetInternalExtension(file.Title);

                        //todo: think about the criteria for saving after creation
                        if (file.ContentLength != storeTemplate.GetFileSize("", path))
                        {
                            file.VersionGroup++;
                        }
                    }
                    file.Version++;
                }
                file.Forcesave = forcesave.HasValue ? forcesave.Value : ForcesaveType.None;

                if (string.IsNullOrEmpty(comment))
                {
                    comment = FilesCommonResource.CommentEdit;
                }

                file.Encrypted = encrypted;

                file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null;

                if (file.ProviderEntry && !newExtension.Equals(currentExt))
                {
                    if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) &&
                        FileUtility.ExtsConvertible[newExtension].Contains(currentExt))
                    {
                        if (stream != null)
                        {
                            downloadUri = PathProvider.GetTempUrl(stream, newExtension);
                            downloadUri = DocumentServiceConnector.ReplaceCommunityAdress(downloadUri);
                        }

                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri);
                        DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, null, false, out downloadUri);

                        stream = null;
                    }
                    else
                    {
                        file.ID    = null;
                        file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension);
                    }

                    file.ConvertedType = null;
                }

                using (var tmpStream = new MemoryStream())
                {
                    if (stream != null)
                    {
                        stream.CopyTo(tmpStream);
                    }
                    else
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                        using (var editedFileStream = new ResponseStream(req.GetResponse()))
                        {
                            editedFileStream.CopyTo(tmpStream);
                        }
                    }
                    tmpStream.Position = 0;

                    file.ContentLength = tmpStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? null : comment;
                    if (replaceVersion)
                    {
                        file = fileDao.ReplaceFileVersion(file, tmpStream);
                    }
                    else
                    {
                        file = fileDao.SaveFile(file, tmpStream);
                    }
                }
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
Esempio n. 22
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Logger.Debug("BoxApp: save file stream " + fileId +
                         (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId.ToString());

            var token = TokenHelper.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId.ToString(), token);

            if (boxFile == null)
            {
                Logger.Error("BoxApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile    = JObject.Parse(boxFile);
            var title       = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name"));
            var currentType = FileUtility.GetFileExtension(title);

            if (!fileType.Equals(currentType))
            {
                try
                {
                    if (stream != null)
                    {
                        downloadUrl = PathProvider.GetTempUrl(stream, fileType);
                        downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl);
                    }

                    Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, null, null, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Logger.Error("BoxApp: Error convert", e);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(BoxUrlUpload.Replace("{fileId}", fileId));

            using (var tmpStream = new MemoryStream())
            {
                var boundary = DateTime.UtcNow.Ticks.ToString("x");

                var metadata     = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title);
                var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata);
                var bytes        = Encoding.UTF8.GetBytes(metadataPart);
                tmpStream.Write(bytes, 0, bytes.Length);

                if (stream != null)
                {
                    stream.CopyTo(tmpStream);
                }
                else
                {
                    var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
                    using var downloadStream = new ResponseStream(downloadRequest.GetResponse());
                    downloadStream.CopyTo(tmpStream);
                }

                var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary);
                bytes = Encoding.UTF8.GetBytes(mediaPartEnd);
                tmpStream.Write(bytes, 0, bytes.Length);

                request.Method = "POST";
                request.Headers.Add("Authorization", "Bearer " + token);
                request.ContentType   = "multipart/form-data; boundary=" + boundary;
                request.ContentLength = tmpStream.Length;
                Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length);

                const int bufferSize = 2048;
                var       buffer     = new byte[bufferSize];
                int       readed;
                tmpStream.Seek(0, SeekOrigin.Begin);
                while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }

            try
            {
                using var response       = request.GetResponse();
                using var responseStream = response.GetResponseStream();
                string result = null;
                if (responseStream != null)
                {
                    using var readStream = new StreamReader(responseStream);
                    result = readStream.ReadToEnd();
                }

                Logger.Debug("BoxApp: save file response - " + result);
            }
            catch (WebException e)
            {
                Logger.Error("BoxApp: Error save file", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
Esempio n. 23
0
        public void SaveFile(string fileId, string downloadUrl)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + " from - " + downloadUrl);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.Logger.Error("GoogleDriveApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile = JObject.Parse(driveFile);
            var curExt   = GetCorrectExt(jsonFile);
            var newExt   = FileUtility.GetFileExtension(downloadUrl);

            if (curExt != newExt)
            {
                try
                {
                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + newExt + " to " + curExt + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, newExt, curExt, key, false, out downloadUrl);
                }
                catch (Exception e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error convert", e);
                }
            }

            var downloadRequest = WebRequest.Create(downloadUrl);

            using (var downloadResponse = downloadRequest.GetResponse())
                using (var downloadStream = new ResponseStream(downloadResponse))
                {
                    var request = (HttpWebRequest)WebRequest.Create(GoogleUrlUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));
                    request.Method = "PUT";
                    request.Headers.Add("Authorization", "Bearer " + token.AccessToken);
                    request.ContentType   = downloadResponse.ContentType;
                    request.ContentLength = downloadResponse.ContentLength;

                    const int bufferSize = 2048;
                    var       buffer     = new byte[bufferSize];
                    int       readed;
                    while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                    {
                        request.GetRequestStream().Write(buffer, 0, readed);
                    }

                    try
                    {
                        using (var response = request.GetResponse())
                            using (var stream = response.GetResponseStream())
                            {
                                var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;

                                Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                            }
                    }
                    catch (WebException e)
                    {
                        Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                        request.Abort();
                        var httpResponse = (HttpWebResponse)e.Response;
                        if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                        }
                        throw;
                    }
                }
        }
Esempio n. 24
0
        public static File ExecDuplicate(File file, string doc)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    var fileSecurity = Global.GetFilesSecurity();
                    if (!fileSecurity.CanRead(file))
                    {
                        var readLink = FileShareLink.Check(doc, true, fileDao, out file);
                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }
                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }
                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!fileSecurity.CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var fileUri       = PathProvider.GetFileStreamUrl(file);
                    var fileExtension = file.ConvertedExtension;
                    var toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var docKey        = DocumentServiceHelper.GetDocKey(file);

                    string convertUri;
                    fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension),
                        Comment  = string.Format(FilesCommonResource.CommentConvert, file.Title),
                    };

                    var req = (HttpWebRequest)WebRequest.Create(convertUri);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;
                        newFile = fileDao.SaveFile(newFile, editedFileStream);
                    }

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }
Esempio n. 25
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId +
                                (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.Logger.Error("GoogleDriveApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile    = JObject.Parse(driveFile);
            var currentType = GetCorrectExt(jsonFile);

            if (!fileType.Equals(currentType))
            {
                try
                {
                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl ?? Guid.NewGuid().ToString());
                    if (stream != null)
                    {
                        using (var tmpStream = new MemoryStream())
                        {
                            stream.CopyTo(tmpStream);

                            Global.Logger.Debug("GoogleDriveApp: GetExternalUri format: " + fileType);
                            downloadUrl = DocumentServiceConnector.GetExternalUri(tmpStream, fileType, key);
                        }
                    }

                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error convert", e);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));

            request.Method = "PATCH";
            request.Headers.Add("Authorization", "Bearer " + token);
            request.ContentType = MimeMapping.GetMimeMapping(currentType);

            if (stream != null)
            {
                request.ContentLength = stream.Length;

                const int bufferSize = 2048;
                var       buffer     = new byte[bufferSize];
                int       readed;
                while ((readed = stream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }
            else
            {
                var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
                using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
                {
                    request.ContentLength = downloadStream.Length;

                    const int bufferSize = 2048;
                    var       buffer     = new byte[bufferSize];
                    int       readed;
                    while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                    {
                        request.GetRequestStream().Write(buffer, 0, readed);
                    }
                }
            }

            try
            {
                using (var response = request.GetResponse())
                    using (var responseStream = response.GetResponseStream())
                    {
                        string result = null;
                        if (responseStream != null)
                        {
                            using (var readStream = new StreamReader(responseStream))
                            {
                                result = readStream.ReadToEnd();
                            }
                        }

                        Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
        private static void CheckConvertFilesStatus(Object obj)
        {
            lock (LockerTimer)
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
            try
            {
                List <File> filesIsConverting;

                lock (LockerStatus)
                {
                    ConversionFileStatus.Where(x => ((!String.IsNullOrEmpty(x.Value.Processed) &&
                                                      DateTime.Now.Subtract(x.Value.StopDateTime) > TimeSpan.FromMinutes(30))))
                    .ToList().ForEach(x => ConversionFileStatus.Remove(x));

                    filesIsConverting = ConversionFileStatus.Where(x => String.IsNullOrEmpty(x.Value.Processed)).Select(x => x.Key).ToList();
                }

                if (filesIsConverting.Count == 0)
                {
                    lock (LockerTimer)
                    {
                        _timer.Dispose();
                        _timer = null;
                    }
                    return;
                }

                foreach (var file in filesIsConverting)
                {
                    var    fileUri = file.ID.ToString();
                    string convetedFileUrl;
                    int    operationResultProgress;
                    object folderId;
                    var    currentFolder = false;

                    try
                    {
                        int      tenantId;
                        IAccount account;

                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult == null)
                            {
                                continue;
                            }
                            tenantId = operationResult.TenantId;
                            account  = operationResult.Account;
                        }

                        CoreContext.TenantManager.SetCurrentTenant(tenantId);
                        SecurityContext.AuthenticateMe(account);

                        var user    = CoreContext.UserManager.GetUsers(account.ID);
                        var culture = string.IsNullOrEmpty(user.CultureName)
                                          ? CoreContext.TenantManager.GetCurrentTenant().GetCulture()
                                          : CultureInfo.GetCultureInfo(user.CultureName);
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var fileSecurity = Global.GetFilesSecurity();
                        if (!fileSecurity.CanRead(file) &&
                            file.RootFolderType != FolderType.BUNCH)    //No rights in CRM after upload before attach
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        if (file.ContentLength > SetupInfo.AvailableFileSize)
                        {
                            throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                        }

                        folderId = Global.FolderMy;
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var parent = folderDao.GetFolder(file.FolderID);
                            if (parent != null &&
                                fileSecurity.CanCreate(parent))
                            {
                                folderId      = parent.ID;
                                currentFolder = true;
                            }
                        }
                        if (Equals(folderId, 0))
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                        }

                        fileUri = PathProvider.GetFileStreamUrl(file);

                        var toExtension   = FileUtility.GetInternalExtension(file.Title);
                        var fileExtension = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                        var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                        operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convetedFileUrl);
                    }
                    catch (Exception exception)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                if (operationResult.Delete)
                                {
                                    ConversionFileStatus.Remove(file);
                                }
                                else
                                {
                                    operationResult.Result       = FileJsonSerializer(file);
                                    operationResult.Processed    = "1";
                                    operationResult.StopDateTime = DateTime.Now;
                                    operationResult.Error        = exception.Message;
                                }
                            }
                        }

                        var strExc = exception.Message + " in file " + fileUri;
                        Global.Logger.Error(strExc, exception);

                        continue;
                    }

                    if (operationResultProgress < 100)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                operationResult.Progress = operationResultProgress;
                            }
                        }
                        continue;
                    }

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                            File newFile = null;
                            if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                            {
                                newFile = fileDao.GetFile(folderId, newFileTitle);
                                if (newFile != null &&
                                    Global.GetFilesSecurity().CanEdit(newFile) &&
                                    !EntryManager.FileLockedForMe(newFile.ID) &&
                                    !FileTracker.IsEditing(newFile.ID))
                                {
                                    newFile.Version++;
                                }
                                else
                                {
                                    newFile = null;
                                }
                            }

                            if (newFile == null)
                            {
                                newFile = new File {
                                    FolderID = folderId
                                }
                            }
                            ;

                            newFile.Title         = newFileTitle;
                            newFile.ConvertedType = FileUtility.GetInternalExtension(file.Title);

                            var operationResultError = string.Empty;
                            try
                            {
                                var req = (HttpWebRequest)WebRequest.Create(convetedFileUrl);

                                using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                {
                                    newFile.ContentLength = convertedFileStream.Length;
                                    newFile.Comment       = string.Empty;
                                    newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                }

                                FileMarker.MarkAsNew(newFile);

                                using (var tagDao = Global.DaoFactory.GetTagDao())
                                {
                                    var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                    if (tags.Any())
                                    {
                                        tags.ForEach(r => r.EntryId = newFile.ID);
                                        tagDao.SaveTags(tags.ToArray());
                                    }
                                }

                                operationResultProgress = 100;
                            }
                            catch (WebException e)
                            {
                                using (var response = e.Response)
                                {
                                    var httpResponse = (HttpWebResponse)response;
                                    var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                    if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                    {
                                        using (var data = response.GetResponseStream())
                                        {
                                            var text = new StreamReader(data).ReadToEnd();
                                            errorString += String.Format(" Error message: {0}", text);
                                        }
                                    }

                                    operationResultError = errorString;

                                    Global.Logger.Error(errorString + "  ConvertUrl : " + convetedFileUrl + "    fromUrl : " + fileUri, e);
                                    throw new Exception(errorString);
                                }
                            }
                            finally
                            {
                                var fileSecurity   = Global.GetFilesSecurity();
                                var removeOriginal = !FilesSettings.StoreOriginalFiles &&
                                                     fileSecurity.CanDelete(file) &&
                                                     currentFolder &&
                                                     !EntryManager.FileLockedForMe(file.ID);

                                var folderTitle = folderDao.GetFolder(newFile.FolderID).Title;

                                lock (LockerStatus)
                                {
                                    var operationResult = ConversionFileStatus[file];

                                    if (operationResult.Delete)
                                    {
                                        ConversionFileStatus.Remove(file);
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                        operationResult.Processed    = "1";
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Progress     = operationResultProgress;
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                    }
                                }

                                if (removeOriginal)
                                {
                                    FileMarker.RemoveMarkAsNewForAll(file);
                                    fileDao.DeleteFile(file.ID);
                                }
                            }
                        }
                }

                lock (LockerTimer)
                {
                    _timer.Change(0, TimerConvertPeriod);
                }
            }
            catch (Exception exception)
            {
                Global.Logger.Error(exception.Message, exception);
                lock (LockerTimer)
                {
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }
Esempio n. 27
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            if (!ItsTry)
            {
                try
                {
                    if (string.IsNullOrEmpty(RequestFileUrl))
                    {
                        _fileNew = (Request["new"] ?? "") == "true";

                        var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                        if (app == null)
                        {
                            var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);

                            file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                            _fileNew = _fileNew && file.Version == 1 && file.ConvertedType != null && file.CreateOn == file.ModifiedOn;
                        }
                        else
                        {
                            isExtenral = true;

                            bool editable;
                            ThirdPartyApp = true;
                            file          = app.GetFile(RequestFileId, out editable);
                            file          = DocumentServiceHelper.GetParams(file, true, true, true, editable, editable, editable, out _docParams);

                            _docParams.FileUri   = app.GetFileStreamUrl(file);
                            _docParams.FolderUrl = string.Empty;
                        }
                    }
                    else
                    {
                        isExtenral = true;

                        fileUri = RequestFileUrl;
                        var fileTitle = Request[FilesLinkUtility.FileTitle];
                        if (string.IsNullOrEmpty(fileTitle))
                        {
                            fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                        }

                        if (CoreContext.Configuration.Standalone)
                        {
                            try
                            {
                                var webRequest = WebRequest.Create(RequestFileUrl);
                                using (var response = webRequest.GetResponse())
                                    using (var responseStream = new ResponseStream(response))
                                    {
                                        var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                        fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                                    }
                            }
                            catch (Exception error)
                            {
                                Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                            }
                        }

                        file = new File
                        {
                            ID    = RequestFileUrl,
                            Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                        };

                        file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                        _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                        _editByUrl         = true;

                        _docParams.FileUri = fileUri;
                    }
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[FilesLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var path = "demo";
                if (!IsMobile)
                {
                    path = FileConstant.NewDocPath + CultureInfo.CurrentUICulture.TwoLetterISOLanguageName + "/";
                    if (!Global.GetStoreTemplate().IsDirectory(path))
                    {
                        path = FileConstant.NewDocPath + "default/";
                    }

                    path += "new";
                }

                path += FileUtility.InternalExtension[tryType];

                var store = Global.GetStoreTemplate();
                fileUri = store.GetUri("", path).ToString();

                var fileTitle = "Demo" + FileUtility.InternalExtension[tryType];
                file = new File
                {
                    ID    = Guid.NewGuid(),
                    Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                };

                file = DocumentServiceHelper.GetParams(file, true, true, true, editPossible, editPossible, true, out _docParams);

                _docParams.FileUri = CommonLinkUtility.GetFullAbsolutePath(fileUri);
                _editByUrl         = true;
                _docParams.Lang    = CultureInfo.CurrentUICulture.Name;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams    = null;
                    _errorMessage = e.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = HeaderStringHelper.GetPageTitle(file.Title);

            _newScheme = FileUtility.ExtsNewService.Contains(FileUtility.GetFileExtension(file.Title));
            if (_newScheme)
            {
                DocServiceApiUrl = FilesLinkUtility.DocServiceApiUrlNew;
            }

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                if (!ItsTry)
                {
                    FileMarker.RemoveMarkAsNew(file);
                }
            }

            if (_docParams.ModeWrite)
            {
                _tabId        = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion = FileTracker.FixedVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : FileConverter.MustConvert(_docParams.File) || _newScheme
                                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.Personal && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }
Esempio n. 28
0
 /// <summary>
 /// </summary>
 /// <param name="context"></param>
 /// <param name="fileStorageService"></param>
 public FilesControllerHelper(
     ApiContext context,
     FileStorageService <T> fileStorageService,
     FileWrapperHelper fileWrapperHelper,
     FilesSettingsHelper filesSettingsHelper,
     FilesLinkUtility filesLinkUtility,
     FileUploader fileUploader,
     DocumentServiceHelper documentServiceHelper,
     TenantManager tenantManager,
     SecurityContext securityContext,
     FolderWrapperHelper folderWrapperHelper,
     FileOperationWraperHelper fileOperationWraperHelper,
     FileShareWrapperHelper fileShareWrapperHelper,
     FileShareParamsHelper fileShareParamsHelper,
     EntryManager entryManager,
     UserManager userManager,
     WebItemSecurity webItemSecurity,
     CoreBaseSettings coreBaseSettings,
     ThirdpartyConfiguration thirdpartyConfiguration,
     MessageService messageService,
     CommonLinkUtility commonLinkUtility,
     DocumentServiceConnector documentServiceConnector,
     FolderContentWrapperHelper folderContentWrapperHelper,
     WordpressToken wordpressToken,
     WordpressHelper wordpressHelper,
     ConsumerFactory consumerFactory,
     EasyBibHelper easyBibHelper,
     ChunkedUploadSessionHelper chunkedUploadSessionHelper,
     IOptionsMonitor <ILog> optionMonitor)
 {
     ApiContext                 = context;
     FileStorageService         = fileStorageService;
     FileWrapperHelper          = fileWrapperHelper;
     FilesSettingsHelper        = filesSettingsHelper;
     FilesLinkUtility           = filesLinkUtility;
     FileUploader               = fileUploader;
     DocumentServiceHelper      = documentServiceHelper;
     TenantManager              = tenantManager;
     SecurityContext            = securityContext;
     FolderWrapperHelper        = folderWrapperHelper;
     FileOperationWraperHelper  = fileOperationWraperHelper;
     FileShareWrapperHelper     = fileShareWrapperHelper;
     FileShareParamsHelper      = fileShareParamsHelper;
     EntryManager               = entryManager;
     UserManager                = userManager;
     WebItemSecurity            = webItemSecurity;
     CoreBaseSettings           = coreBaseSettings;
     ThirdpartyConfiguration    = thirdpartyConfiguration;
     ConsumerFactory            = consumerFactory;
     BoxLoginProvider           = ConsumerFactory.Get <BoxLoginProvider>();
     DropboxLoginProvider       = ConsumerFactory.Get <DropboxLoginProvider>();
     GoogleLoginProvider        = ConsumerFactory.Get <GoogleLoginProvider>();
     OneDriveLoginProvider      = ConsumerFactory.Get <OneDriveLoginProvider>();
     MessageService             = messageService;
     CommonLinkUtility          = commonLinkUtility;
     DocumentServiceConnector   = documentServiceConnector;
     FolderContentWrapperHelper = folderContentWrapperHelper;
     WordpressToken             = wordpressToken;
     WordpressHelper            = wordpressHelper;
     EasyBibHelper              = easyBibHelper;
     ChunkedUploadSessionHelper = chunkedUploadSessionHelper;
     Logger = optionMonitor.Get("ASC.Files");
 }
Esempio n. 29
0
        private static void GenareteReport(ReportTaskState state, ReportType reportType, ReportTimePeriod timePeriod,
                                           Guid[] managers)
        {
            state.Status     = ReportTaskStatus.Started;
            state.Percentage = 10;
            SetCacheValue(state);

            var reportData = GetReportData(reportType, timePeriod, managers);

            if (reportData != null)
            {
                state.Percentage = 50;
            }
            else
            {
                state.Percentage  = 100;
                state.IsCompleted = true;
                state.ErrorText   = CRMReportResource.ErrorNullReportData;
                state.Status      = ReportTaskStatus.Failed;
            }

            SetCacheValue(state);

            if (state.Status == ReportTaskStatus.Failed)
            {
                return;
            }

            var script = GetReportScript(reportData, reportType);

            if (!string.IsNullOrEmpty(script))
            {
                state.Percentage = 60;
            }
            else
            {
                state.Percentage  = 100;
                state.IsCompleted = true;
                state.ErrorText   = CRMReportResource.ErrorNullReportScript;
                state.Status      = ReportTaskStatus.Failed;
            }

            SetCacheValue(state);

            if (state.Status == ReportTaskStatus.Failed)
            {
                return;
            }

            try
            {
                Dictionary <string, string> urls;
                state.BuilderKey = DocumentServiceConnector.DocbuilderRequest(null, script, true, out urls);

                state.Percentage = 80;
            }
            catch (Exception ex)
            {
                state.Percentage  = 100;
                state.IsCompleted = true;
                state.ErrorText   = ex.Message;
                state.Status      = ReportTaskStatus.Failed;
            }

            SetCacheValue(state);

            if (state.Status == ReportTaskStatus.Failed)
            {
                return;
            }

            InsertItem(state);
        }
Esempio n. 30
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);
                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, editPossible, !RequestView, true, out _configuration);
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = (HttpWebRequest)WebRequest.Create(RequestFileUrl);

                            // hack. http://ubuntuforums.org/showthread.php?t=1841740
                            if (WorkContext.IsMono)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                            }

                            using (var response = webRequest.GetResponse())
                                using (var responseStream = new ResponseStream(response))
                                {
                                    var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                    fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                                }
                        }
                        catch (Exception error)
                        {
                            Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                        }
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _editByUrl = true;

                    _configuration.Document.Url = fileUri;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _configuration.EditorConfig.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);
                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _configuration.EditorConfig.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }
        }