Example #1
0
        public static string GetDocKey(object fileId, int fileVersion, DateTime modified)
        {
            var str = String.Format("teamlab_{0}_{1}_{2}_{3}",
                                    fileId,
                                    fileVersion,
                                    modified.GetHashCode(),
                                    Global.GetDocDbKey());

            var keyDoc = Encoding.UTF8.GetBytes(str)
                         .ToList()
                         .Concat(MachinePseudoKeys.GetMachineConstant())
                         .ToArray();

            return(DocumentServiceConnector.GenerateRevisionId(Hasher.Base64Hash(keyDoc, HashAlg.SHA256)));
        }
        private static bool Command(TrackMethod method, string docKeyForTrack, string fileId = null, string callbackUrl = null, string users = null, string status = null)
        {
            Global.Logger.DebugFormat("DocService command {0} fileId '{1}' docKey '{2}' callbackUrl '{3}' users '{4}' status '{5}'", method, fileId, docKeyForTrack, callbackUrl, users, status);
            try
            {
                var response = DocumentServiceConnector.CommandRequest(method.ToString().ToLower(CultureInfo.InvariantCulture), docKeyForTrack, callbackUrl, users, status);
                Global.Logger.DebugFormat("DocService command response: '{0}'", response);

                var jResponse = JObject.Parse(response);

                var result = (CommandResultTypes)jResponse.Value <int>("error");
                return(result == CommandResultTypes.NoError);
            }
            catch (Exception e)
            {
                Global.Logger.Error("DocService command error", e);
                return(false);
            }
        }
Example #3
0
        public bool RenameFile <T>(File <T> file, IFileDao <T> fileDao)
        {
            if (!FileUtility.CanWebView(file.Title) &&
                !FileUtility.CanWebEdit(file.Title) &&
                !FileUtility.CanWebReview(file.Title) &&
                !FileUtility.CanWebRestrictedEditing(file.Title) &&
                !FileUtility.CanWebComment(file.Title))
            {
                return(true);
            }

            var fileStable     = file.Forcesave == ForcesaveType.None ? file : fileDao.GetFileStable(file.ID, file.Version);
            var docKeyForTrack = GetDocKey(fileStable);

            var meta = new Web.Core.Files.DocumentService.MetaData {
                Title = file.Title
            };

            return(DocumentServiceConnector.Command(Web.Core.Files.DocumentService.CommandMethod.Meta, docKeyForTrack, file.ID, meta: meta));
        }
 public DocumentServiceTrackerHelper(
     SecurityContext securityContext,
     UserManager userManager,
     TenantManager tenantManager,
     FilesLinkUtility filesLinkUtility,
     EmailValidationKeyProvider emailValidationKeyProvider,
     BaseCommonLinkUtility baseCommonLinkUtility,
     SocketManager socketManager,
     GlobalStore globalStore,
     DisplayUserSettingsHelper displayUserSettingsHelper,
     IDaoFactory daoFactory,
     IOptionsMonitor <ILog> options,
     DocumentServiceHelper documentServiceHelper,
     EntryManager entryManager,
     FileShareLink fileShareLink,
     FilesMessageService filesMessageService,
     DocumentServiceConnector documentServiceConnector,
     NotifyClient notifyClient,
     MailMergeTaskRunner mailMergeTaskRunner,
     FileTrackerHelper fileTracker)
 {
     SecurityContext            = securityContext;
     UserManager                = userManager;
     TenantManager              = tenantManager;
     FilesLinkUtility           = filesLinkUtility;
     EmailValidationKeyProvider = emailValidationKeyProvider;
     BaseCommonLinkUtility      = baseCommonLinkUtility;
     SocketManager              = socketManager;
     GlobalStore                = globalStore;
     DisplayUserSettingsHelper  = displayUserSettingsHelper;
     DaoFactory               = daoFactory;
     DocumentServiceHelper    = documentServiceHelper;
     EntryManager             = entryManager;
     FileShareLink            = fileShareLink;
     FilesMessageService      = filesMessageService;
     DocumentServiceConnector = documentServiceConnector;
     NotifyClient             = notifyClient;
     MailMergeTaskRunner      = mailMergeTaskRunner;
     FileTracker              = fileTracker;
     Logger = options.CurrentValue;
 }
        public static bool HaveExternalIP()
        {
            if (!CoreContext.Configuration.Standalone)
            {
                return(true);
            }

            var checkExternalIp = FilesSettings.CheckHaveExternalIP;

            if (checkExternalIp.Value.AddDays(5) >= DateTime.UtcNow)
            {
                return(checkExternalIp.Key);
            }

            string convertUri;

            try
            {
                const string toExtension   = ".xlsx";
                var          fileName      = "new";
                var          fileExtension = FileUtility.GetInternalExtension(toExtension);
                fileName += fileExtension;

                var fileUri = CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo + "&" + CommonLinkUtility.FileTitle + "=" + fileName;
                fileUri = CommonLinkUtility.GetFullAbsolutePath(string.Format(fileUri, FileUtility.GetFileTypeByFileName(fileName)));

                DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, Guid.NewGuid().ToString(), false, out convertUri);
            }
            catch
            {
                convertUri = string.Empty;
            }

            var result = !string.IsNullOrEmpty(convertUri);

            FilesSettings.CheckHaveExternalIP = new KeyValuePair <bool, DateTime>(result, DateTime.UtcNow);
            return(result);
        }
Example #6
0
        public static bool HaveExternalIP()
        {
            if (!CoreContext.Configuration.Standalone)
            {
                return(true);
            }

            var checkExternalIp = FilesSettings.CheckHaveExternalIP;

            if (checkExternalIp.Value.AddDays(5) >= DateTime.UtcNow)
            {
                return(checkExternalIp.Key);
            }

            string convertUri;

            try
            {
                const string toExtension   = ".docx";
                var          fileExtension = FileUtility.GetInternalExtension(toExtension);
                var          storeTemplate = Global.GetStoreTemplate();
                var          fileUri       = storeTemplate.GetUri("", FileConstant.NewDocPath + "default/new" + fileExtension).ToString();

                fileUri = DocumentServiceConnector.ReplaceCommunityAdress(CommonLinkUtility.GetFullAbsolutePath(fileUri));
                DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, Guid.NewGuid().ToString(), false, out convertUri);
            }
            catch
            {
                convertUri = string.Empty;
            }

            var result = !string.IsNullOrEmpty(convertUri);

            Global.Logger.Info("HaveExternalIP result " + result);
            FilesSettings.CheckHaveExternalIP = new KeyValuePair <bool, DateTime>(result, DateTime.UtcNow);
            return(result);
        }
        public static string GetExternalUri(File file)
        {
            try
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                    using (var fileStream = fileDao.GetFileStream(file))
                    {
                        var docKey = GetDocKey(file.ID, file.Version, file.ModifiedOn);

                        var uri = CacheUri.Get(docKey) as string;
                        if (string.IsNullOrEmpty(uri))
                        {
                            uri = DocumentServiceConnector.GetExternalUri(fileStream, MimeMapping.GetMimeMapping(file.Title), docKey);
                        }
                        CacheUri.Insert(docKey, uri, DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                        return(uri);
                    }
            }
            catch (Exception exception)
            {
                Global.Logger.Error("Get external uri: ", exception);
            }
            return(null);
        }
 public bool DropUser(string docKeyForTrack, string[] users, object fileId = null)
 {
     return(DocumentServiceConnector.Command(Web.Core.Files.DocumentService.CommandMethod.Drop, docKeyForTrack, fileId, null, users));
 }
Example #9
0
        private static string ProcessMailMerge(string fileId, TrackerData fileData)
        {
            Guid userId;

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            var sended = false;

            try
            {
                SecurityContext.AuthenticateMe(userId);

                if (string.IsNullOrEmpty(fileData.Url))
                {
                    throw new ArgumentException("emptry url");
                }

                if (fileData.MailMerge == null)
                {
                    throw new ArgumentException("MailMerge is null");
                }

                var    message = fileData.MailMerge.Message;
                Stream attach  = null;
                switch (fileData.MailMerge.Type)
                {
                case MailMergeType.AttachDocx:
                case MailMergeType.AttachPdf:
                    var downloadRequest = (HttpWebRequest)WebRequest.Create(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));

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

                    using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
                    {
                        const int bufferSize = 2048;
                        var       buffer     = new byte[bufferSize];
                        int       readed;
                        attach = new MemoryStream();
                        while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                        {
                            attach.Write(buffer, 0, readed);
                        }
                        attach.Position = 0;
                    }

                    if (string.IsNullOrEmpty(fileData.MailMerge.Title))
                    {
                        fileData.MailMerge.Title = "Attach";
                    }

                    var attachExt = fileData.MailMerge.Type == MailMergeType.AttachDocx ? ".docx" : ".pdf";
                    var curExt    = FileUtility.GetFileExtension(fileData.MailMerge.Title);
                    if (curExt != attachExt)
                    {
                        fileData.MailMerge.Title += attachExt;
                    }

                    break;

                case MailMergeType.Html:
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));

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

                    using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                        using (var stream = httpWebResponse.GetResponseStream())
                            if (stream != null)
                            {
                                using (var reader = new StreamReader(stream, Encoding.GetEncoding(Encoding.UTF8.WebName)))
                                {
                                    message = reader.ReadToEnd();
                                }
                            }
                    break;
                }

                using (var mailMergeTask =
                           new MailMergeTask
                {
                    From = fileData.MailMerge.From,
                    Subject = fileData.MailMerge.Subject,
                    To = fileData.MailMerge.To,
                    Message = message,
                    AttachTitle = fileData.MailMerge.Title,
                    Attach = attach
                })
                {
                    var response = mailMergeTask.Run();
                    Global.Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}",
                                             fileData.MailMerge.RecordIndex + 1, fileData.MailMerge.RecordCount, response);
                }
                sended = true;
            }
            catch (Exception ex)
            {
                Global.Logger.Error(
                    string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}",
                                  (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount),
                                  userId, fileData.Url),
                    ex);
            }

            if (fileData.MailMerge != null &&
                fileData.MailMerge.RecordIndex == fileData.MailMerge.RecordCount - 1)
            {
                var errorCount = fileData.MailMerge.RecordErrorCount;
                if (!sended)
                {
                    errorCount++;
                }

                NotifyClient.SendMailMergeEnd(userId, fileData.MailMerge.RecordCount, errorCount);
            }

            return(sended
                       ? "0"   //error:0 - sended
                       : "1"); //error:1 - some error
        }
Example #10
0
        private static string ProcessSave(string fileId, TrackerData fileData)
        {
            Guid userId;
            var  comments = new List <string>();

            if (fileData.Status == TrackerStatus.Corrupted)
            {
                comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted);
            }

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            try
            {
                SecurityContext.AuthenticateMe(userId);
            }
            catch (Exception ex)
            {
                Global.Logger.Info("DocService save error: anonymous author - " + userId, ex);
                if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous);
                }
            }

            File file  = null;
            var  saved = false;

            FileTracker.Remove(fileId);

            if (string.IsNullOrEmpty(fileData.Url))
            {
                try
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost);

                    file = EntryManager.CompleteVersionFile(fileId, 0, false, false);

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                    {
                        fileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments));
                    }
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex);
                }
            }
            else
            {
                try
                {
                    file  = EntryManager.SaveEditing(fileId, null, DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url), null, string.Empty, string.Join("; ", comments), false);
                    saved = fileData.Status == TrackerStatus.MustSave;
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex);

                    StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));
                }
            }

            if (file != null)
            {
                var user = CoreContext.UserManager.GetUsers(userId);
                if (user != null)
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false), file.Title);
                }

                SaveHistory(file, (fileData.History ?? "").ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.ChangesUrl));
            }

            Global.SocketManager.FilesChangeEditors(fileId, true);

            return(saved
                       ? "0"   //error:0 - saved
                       : "1"); //error:1 - some error
        }
Example #11
0
        public static bool StartTrack(string fileId, string docKeyForTrack)
        {
            var callbackUrl = GetCallbackUrl(fileId);

            return(DocumentServiceConnector.Command(CommandMethod.Info, docKeyForTrack, fileId, callbackUrl));
        }
Example #12
0
        private static TrackResponse ProcessSave(string fileId, TrackerData fileData)
        {
            Guid userId;
            var  comments = new List <string>();

            if (fileData.Status == TrackerStatus.Corrupted ||
                fileData.Status == TrackerStatus.CorruptedForceSave)
            {
                comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted);
            }

            var forcesave = fileData.Status == TrackerStatus.ForceSave || fileData.Status == TrackerStatus.CorruptedForceSave;

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app == null)
            {
                File fileStable;
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    fileStable = fileDao.GetFileStable(fileId);
                }

                var docKey = DocumentServiceHelper.GetDocKey(fileStable);
                if (!fileData.Key.Equals(docKey))
                {
                    Global.Logger.ErrorFormat("DocService saving file {0} ({1}) with key {2}", fileId, docKey, fileData.Key);

                    StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));
                    return(new TrackResponse {
                        Message = "Expected key " + docKey
                    });
                }
            }

            UserInfo user = null;

            try
            {
                SecurityContext.AuthenticateMe(userId);

                user = CoreContext.UserManager.GetUsers(userId);
                var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }
            catch (Exception ex)
            {
                Global.Logger.Info("DocService save error: anonymous author - " + userId, ex);
                if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous);
                }
            }

            File file        = null;
            var  saveMessage = "Not saved";

            if (string.IsNullOrEmpty(fileData.Url))
            {
                try
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost);

                    file = EntryManager.CompleteVersionFile(fileId, 0, false, false);

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                    {
                        fileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments));
                    }

                    file = null;
                    Global.Logger.ErrorFormat("DocService save error. Empty url. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex);
                }
            }
            else
            {
                if (fileData.Encrypted)
                {
                    comments.Add(FilesCommonResource.CommentEditEncrypt);
                }

                var forcesaveType = ForcesaveType.None;
                if (forcesave)
                {
                    switch (fileData.ForceSaveType)
                    {
                    case TrackerData.ForceSaveInitiator.Command:
                        forcesaveType = ForcesaveType.Command;
                        break;

                    case TrackerData.ForceSaveInitiator.Timer:
                        forcesaveType = ForcesaveType.Timer;
                        break;

                    case TrackerData.ForceSaveInitiator.User:
                        forcesaveType = ForcesaveType.User;
                        break;
                    }
                    comments.Add(fileData.ForceSaveType == TrackerData.ForceSaveInitiator.User
                                     ? FilesCommonResource.CommentForcesave
                                     : FilesCommonResource.CommentAutosave);
                }

                try
                {
                    file        = EntryManager.SaveEditing(fileId, null, DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url), null, string.Empty, string.Join("; ", comments), false, fileData.Encrypted, forcesaveType);
                    saveMessage = fileData.Status == TrackerStatus.MustSave || fileData.Status == TrackerStatus.ForceSave ? null : "Status " + fileData.Status;
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex);
                    saveMessage = ex.Message;

                    StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));
                }
            }

            if (!forcesave)
            {
                FileTracker.Remove(fileId);
            }

            if (file != null)
            {
                if (user != null)
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false), file.Title);
                }

                if (!forcesave)
                {
                    SaveHistory(file, (fileData.History ?? "").ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.ChangesUrl));
                }
            }

            Global.SocketManager.FilesChangeEditors(fileId, !forcesave);

            var result = new TrackResponse {
                Message = saveMessage
            };

            if (string.IsNullOrEmpty(saveMessage) && file != null && file.Encrypted)
            {
                result.Addresses = EncryptionAddress.GetAddresses(file.ID.ToString()).ToArray();
            }
            return(result);
        }
        public static bool Drop(string docKeyForTrack, List <Guid> users, object fileId = null)
        {
            var dropString = "[\"" + string.Join("\",\"", users) + "\"]";

            return(DocumentServiceConnector.Command(CommandMethod.Drop, docKeyForTrack, fileId, null, dropString));
        }
Example #14
0
        public void GenerateReport(DistributedTask task, CancellationToken cancellationToken)
        {
            try
            {
                Status = ReportStatus.Started;
                PublishTaskInfo();

                if (HttpContext.Current == null && !WorkContext.IsMono && !string.IsNullOrEmpty(ContextUrl))
                {
                    HttpContext.Current = new HttpContext(
                        new HttpRequest("hack", ContextUrl, string.Empty),
                        new HttpResponse(new System.IO.StringWriter()));
                }

                CoreContext.TenantManager.SetCurrentTenant(TenantId);
                SecurityContext.CurrentUser = UserId;

                Dictionary <string, string> urls;
                BuilderKey = DocumentServiceConnector.DocbuilderRequest(null, Script, true, out urls);

                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }

                    Task.Delay(1500, cancellationToken).Wait(cancellationToken);
                    var builderKey = DocumentServiceConnector.DocbuilderRequest(BuilderKey, null, true, out urls);
                    if (builderKey == null)
                    {
                        throw new NullReferenceException();
                    }

                    if (urls != null && !urls.Any())
                    {
                        throw new Exception("Empty response");
                    }

                    if (urls != null && urls.ContainsKey(TmpFileName))
                    {
                        break;
                    }
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                SaveFileAction(this, urls[TmpFileName]);

                Status = ReportStatus.Done;
            }
            catch (Exception e)
            {
                Global.Logger.Error("DocbuilderReportsUtility error", e);
                Exception = e.Message;
                Status    = ReportStatus.Failed;
            }

            PublishTaskInfo();
        }
 public static bool DropUser(string docKeyForTrack, List <Guid> users, object fileId = null)
 {
     return(DocumentServiceConnector.Command(Web.Core.Files.DocumentService.CommandMethod.Drop, docKeyForTrack, fileId, null, users.Select(u => u.ToString()).ToArray()));
 }