public override void Init() { context = new ProductContext { MasterPageFile = String.Concat(PathProvider.BaseVirtualPath, "Masters/BasicTemplate.Master"), DisabledIconFileName = "product_disabled_logo.png", IconFileName = "product_logo.png", LargeIconFileName = "product_logolarge.png", SubscriptionManager = new ProductSubscriptionManager(), DefaultSortOrder = 20, SpaceUsageStatManager = new ProjectsSpaceUsageStatManager(), AdminOpportunities = () => ProjectsCommonResource.ProductAdminOpportunities.Split('|').ToList(), UserOpportunities = () => ProjectsCommonResource.ProductUserOpportunities.Split('|').ToList(), HasComplexHierarchyOfAccessRights = true, }; FilesIntegration.RegisterFileSecurityProvider("projects", "project", new SecurityAdapterProvider()); SearchHandlerManager.Registry(new SearchHandler()); var securityInterceptor = new SendInterceptorSkeleton( "ProjectInterceptorSecurity", InterceptorPlace.DirectSend, InterceptorLifetime.Global, (r, p) => { HttpContext.Current = null; try { HttpContext.Current = new HttpContext( new HttpRequest("hack", CommonLinkUtility.GetFullAbsolutePath("/"), string.Empty), new HttpResponse(new StringWriter())); var data = r.ObjectID.Split('_'); var entityType = data[0]; var entityId = Convert.ToInt32(data[1]); var projectId = 0; if (data.Length == 3) { projectId = Convert.ToInt32(r.ObjectID.Split('_')[2]); } switch (entityType) { case "Task": var task = Global.EngineFactory.GetTaskEngine().GetByID(entityId, false); if (task == null && projectId != 0) { var project = Global.EngineFactory.GetProjectEngine().GetByID(projectId, false); return(!ProjectSecurity.CanRead(project, new Guid(r.Recipient.ID))); } return(!ProjectSecurity.CanRead(task, new Guid(r.Recipient.ID))); case "Message": var discussion = Global.EngineFactory.GetMessageEngine().GetByID(entityId, false); if (discussion == null && projectId != 0) { var project = Global.EngineFactory.GetProjectEngine().GetByID(projectId, false); return(!ProjectSecurity.CanRead(project, new Guid(r.Recipient.ID))); } return(!ProjectSecurity.CanRead(discussion, new Guid(r.Recipient.ID))); case "Milestone": var milestone = Global.EngineFactory.GetMilestoneEngine().GetByID(entityId, false); if (milestone == null && projectId != 0) { var project = Global.EngineFactory.GetProjectEngine().GetByID(projectId, false); return(!ProjectSecurity.CanRead(project, new Guid(r.Recipient.ID))); } return(!ProjectSecurity.CanRead(milestone, new Guid(r.Recipient.ID))); } } catch (Exception ex) { LogManager.GetLogger("ASC.Projects.Tasks").Error("Send", ex); } finally { if (HttpContext.Current != null) { new DisposableHttpContext(HttpContext.Current).Dispose(); HttpContext.Current = null; } } return(false); }); NotifyClient.Instance.Client.AddInterceptor(securityInterceptor); }
private IEnumerable <Guid> WhoCan <T>(FileEntry <T> entry, FilesSecurityActions action) { var shares = GetShares(entry); FileShareRecord defaultShareRecord; switch (entry.RootFolderType) { case FolderType.COMMON: defaultShareRecord = new FileShareRecord { Level = int.MaxValue, EntryId = entry.ID, EntryType = entry.FileEntryType, Share = DefaultCommonShare, Subject = Constants.GroupEveryone.ID, Tenant = TenantManager.GetCurrentTenant().TenantId, Owner = AuthContext.CurrentAccount.ID }; if (!shares.Any()) { if ((defaultShareRecord.Share == FileShare.Read && action == FilesSecurityActions.Read) || (defaultShareRecord.Share == FileShare.ReadWrite)) { return(UserManager.GetUsersByGroup(defaultShareRecord.Subject) .Where(x => x.Status == EmployeeStatus.Active).Select(y => y.ID).Distinct()); } return(Enumerable.Empty <Guid>()); } break; case FolderType.USER: defaultShareRecord = new FileShareRecord { Level = int.MaxValue, EntryId = entry.ID, EntryType = entry.FileEntryType, Share = DefaultMyShare, Subject = entry.RootFolderCreator, Tenant = TenantManager.GetCurrentTenant().TenantId, Owner = entry.RootFolderCreator }; if (!shares.Any()) { return new List <Guid> { entry.RootFolderCreator } } ; break; case FolderType.BUNCH: if (action == FilesSecurityActions.Read) { var folderDao = daoFactory.GetFolderDao <T>(); var root = folderDao.GetFolder(entry.RootFolderId); if (root != null) { var path = folderDao.GetBunchObjectID(root.ID); var adapter = FilesIntegration.GetFileSecurity(path); if (adapter != null) { return(adapter.WhoCanRead(entry)); } } } // TODO: For Projects and other defaultShareRecord = null; break; default: defaultShareRecord = null; break; } if (defaultShareRecord != null) { shares = shares.Concat(new[] { defaultShareRecord }); } return(shares.SelectMany(x => { var groupInfo = UserManager.GetGroupInfo(x.Subject); if (groupInfo.ID != Constants.LostGroupInfo.ID) { return UserManager.GetUsersByGroup(groupInfo.ID) .Where(p => p.Status == EmployeeStatus.Active) .Select(y => y.ID); } return new[] { x.Subject }; }) .Distinct() .Where(x => Can(entry, x, action)) .ToList()); }
private IEnumerable <FileEntry <T> > Filter <T>(IEnumerable <FileEntry <T> > entries, FilesSecurityActions action, Guid userId) { if (entries == null || !entries.Any()) { return(Enumerable.Empty <FileEntry <T> >()); } var user = UserManager.GetUsers(userId); var isOutsider = user.IsOutsider(UserManager); if (isOutsider && action != FilesSecurityActions.Read) { return(Enumerable.Empty <FileEntry <T> >()); } entries = entries.Where(f => f != null).ToList(); var result = new List <FileEntry <T> >(entries.Count()); // save entries order var order = entries.Select((f, i) => new { Id = f.UniqID, Pos = i }).ToDictionary(e => e.Id, e => e.Pos); // common or my files Func <FileEntry <T>, bool> filter = f => f.RootFolderType == FolderType.COMMON || f.RootFolderType == FolderType.USER || f.RootFolderType == FolderType.SHARE || f.RootFolderType == FolderType.Projects; var isVisitor = user.IsVisitor(UserManager); if (entries.Any(filter)) { var subjects = GetUserSubjects(userId); List <FileShareRecord> shares = null; foreach (var e in entries.Where(filter)) { if (!AuthManager.GetAccountByID(TenantManager.GetCurrentTenant().TenantId, userId).IsAuthenticated&& userId != FileConstant.ShareLinkId) { continue; } if (isOutsider && (e.RootFolderType == FolderType.USER || e.RootFolderType == FolderType.SHARE || e.RootFolderType == FolderType.TRASH)) { continue; } if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.Projects) { // Root Projects folder read-only continue; } if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.SHARE) { // Root Share folder read-only continue; } if (isVisitor && e.ProviderEntry) { continue; } if (e.RootFolderType == FolderType.USER && e.RootFolderCreator == userId && !isVisitor) { // user has all right in his folder result.Add(e); continue; } if (DefaultCommonShare == FileShare.Read && action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.COMMON) { // all can read Common folder result.Add(e); continue; } if (action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.SHARE) { // all can read Share folder result.Add(e); continue; } if (e.RootFolderType == FolderType.COMMON && FileSecurityCommon.IsAdministrator(userId)) { // administrator in Common has all right result.Add(e); continue; } if (shares == null) { shares = GetShares(entries).Join(subjects, r => r.Subject, s => s, (r, s) => r).ToList(); // shares ordered by level } FileShareRecord ace; if (e.FileEntryType == FileEntryType.File) { ace = shares .OrderBy(r => r, new SubjectComparer(subjects)) .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer()) .FirstOrDefault(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.File); if (ace == null) { // share on parent folders ace = shares.Where(r => Equals(r.EntryId, ((File <T>)e).FolderID) && r.EntryType == FileEntryType.Folder) .OrderBy(r => r, new SubjectComparer(subjects)) .ThenBy(r => r.Level) .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer()) .FirstOrDefault(); } } else { ace = shares.Where(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.Folder) .OrderBy(r => r, new SubjectComparer(subjects)) .ThenBy(r => r.Level) .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer()) .FirstOrDefault(); } var defaultShare = e.RootFolderType == FolderType.USER ? DefaultMyShare : DefaultCommonShare; e.Access = ace != null ? ace.Share : defaultShare; if (action == FilesSecurityActions.Read && e.Access != FileShare.Restrict) { result.Add(e); } else if (action == FilesSecurityActions.Comment && (e.Access == FileShare.Comment || e.Access == FileShare.Review || e.Access == FileShare.ReadWrite)) { result.Add(e); } else if (action == FilesSecurityActions.FillForms && (e.Access == FileShare.FillForms || e.Access == FileShare.Review || e.Access == FileShare.ReadWrite)) { result.Add(e); } else if (action == FilesSecurityActions.Review && (e.Access == FileShare.Review || e.Access == FileShare.ReadWrite)) { result.Add(e); } else if (action == FilesSecurityActions.Edit && e.Access == FileShare.ReadWrite) { result.Add(e); } else if (action == FilesSecurityActions.Create && e.Access == FileShare.ReadWrite) { result.Add(e); } else if (e.Access != FileShare.Restrict && e.CreateBy == userId && (e.FileEntryType == FileEntryType.File || ((Folder <T>)e).FolderType != FolderType.COMMON)) { result.Add(e); } if (e.CreateBy == userId) { e.Access = FileShare.None; //HACK: for client } } } // files in bunch filter = f => f.RootFolderType == FolderType.BUNCH; if (entries.Any(filter)) { var folderDao = daoFactory.GetFolderDao <T>(); var filteredEntries = entries.Where(filter).ToList(); var roots = filteredEntries .Select(r => r.RootFolderId) .ToArray(); var rootsFolders = folderDao.GetFolders(roots); var bunches = folderDao.GetBunchObjectIDs(rootsFolders.Select(r => r.ID).ToList()); var findedAdapters = FilesIntegration.GetFileSecurity(bunches); foreach (var e in filteredEntries) { var adapter = findedAdapters[e.RootFolderId.ToString()]; if (adapter == null) { continue; } if (adapter.CanRead(e, userId) && adapter.CanCreate(e, userId) && adapter.CanEdit(e, userId) && adapter.CanDelete(e, userId)) { e.Access = FileShare.None; result.Add(e); } else if (action == FilesSecurityActions.Comment && adapter.CanComment(e, userId)) { e.Access = FileShare.Comment; result.Add(e); } else if (action == FilesSecurityActions.FillForms && adapter.CanFillForms(e, userId)) { e.Access = FileShare.FillForms; result.Add(e); } else if (action == FilesSecurityActions.Review && adapter.CanReview(e, userId)) { e.Access = FileShare.Review; result.Add(e); } else if (action == FilesSecurityActions.Create && adapter.CanCreate(e, userId)) { e.Access = FileShare.ReadWrite; result.Add(e); } else if (action == FilesSecurityActions.Delete && adapter.CanDelete(e, userId)) { e.Access = FileShare.ReadWrite; result.Add(e); } else if (action == FilesSecurityActions.Read && adapter.CanRead(e, userId)) { if (adapter.CanCreate(e, userId) || adapter.CanDelete(e, userId) || adapter.CanEdit(e, userId)) { e.Access = FileShare.ReadWrite; } else { e.Access = FileShare.Read; } result.Add(e); } else if (action == FilesSecurityActions.Edit && adapter.CanEdit(e, userId)) { e.Access = FileShare.ReadWrite; result.Add(e); } } } // files in trash filter = f => f.RootFolderType == FolderType.TRASH; if ((action == FilesSecurityActions.Read || action == FilesSecurityActions.Delete) && entries.Any(filter)) { var folderDao = daoFactory.GetFolderDao <T>(); var mytrashId = folderDao.GetFolderIDTrash(false, userId); if (!Equals(mytrashId, 0)) { result.AddRange(entries.Where(filter).Where(e => Equals(e.RootFolderId, mytrashId))); } } if (FileSecurityCommon.IsAdministrator(userId)) { // administrator can work with crashed entries (crash in files_folder_tree) filter = f => f.RootFolderType == FolderType.DEFAULT; result.AddRange(entries.Where(filter)); } // restore entries order result.Sort((x, y) => order[x.UniqID].CompareTo(order[y.UniqID])); return(result); }
public IEnumerable <SearchItem> Search(string searchText, int projectId = 0) { var queryResult = DaoFactory.SearchDao.Search(searchText, projectId); foreach (var r in queryResult) { switch (r.EntityType) { case EntityType.Project: var project = (Project)r; if (ProjectSecurity.CanRead(project)) { searchItems.Add(new SearchItem(project)); } continue; case EntityType.Milestone: var milestone = (Milestone)r; if (ProjectSecurity.CanRead(milestone)) { searchItems.Add(new SearchItem(milestone)); } continue; case EntityType.Message: var message = (Message)r; if (ProjectSecurity.CanRead(message)) { searchItems.Add(new SearchItem(message)); } continue; case EntityType.Task: var task = (Task)r; if (ProjectSecurity.CanRead(task)) { searchItems.Add(new SearchItem(task)); } continue; case EntityType.Comment: var comment = (Comment)r; var entity = CommentEngine.GetEntityByTargetUniqId(comment); if (entity == null) { continue; } searchItems.Add(new SearchItem(comment.EntityType, comment.ID.ToString(CultureInfo.InvariantCulture), HtmlUtil.GetText(comment.Content), comment.CreateOn, new SearchItem(entity))); continue; case EntityType.SubTask: var subtask = (Subtask)r; var parentTask = TaskEngine.GetByID(subtask.Task); if (parentTask == null) { continue; } searchItems.Add(new SearchItem(subtask.EntityType, subtask.ID.ToString(CultureInfo.InvariantCulture), subtask.Title, subtask.CreateOn, new SearchItem(parentTask))); continue; } } try { // search in files var fileEntries = new List <Files.Core.FileEntry>(); using (var folderDao = FilesIntegration.GetFolderDao()) using (var fileDao = FilesIntegration.GetFileDao()) { fileEntries.AddRange(folderDao.Search(searchText, Files.Core.FolderType.BUNCH)); fileEntries.AddRange(fileDao.Search(searchText, Files.Core.FolderType.BUNCH)); var projectIds = projectId != 0 ? new List <int> { projectId } : fileEntries.GroupBy(f => f.RootFolderId) .Select(g => folderDao.GetFolder(g.Key)) .Select(f => f != null ? folderDao.GetBunchObjectID(f.RootFolderId).Split('/').Last() : null) .Where(s => !string.IsNullOrEmpty(s)) .Select(int.Parse); var rootProject = projectIds.ToDictionary(id => FilesIntegration.RegisterBunch("projects", "project", id.ToString(CultureInfo.InvariantCulture))); fileEntries.RemoveAll(f => !rootProject.ContainsKey(f.RootFolderId)); var security = FilesIntegration.GetFileSecurity(); fileEntries.RemoveAll(f => !security.CanRead(f)); foreach (var f in fileEntries) { var id = rootProject[f.RootFolderId]; var project = DaoFactory.ProjectDao.GetById(id); if (ProjectSecurity.CanReadFiles(project)) { var itemId = f.FileEntryType == FileEntryType.File ? FilesLinkUtility.GetFileWebPreviewUrl(f.Title, f.ID) : Web.Files.Classes.PathProvider.GetFolderUrl((Files.Core.Folder)f, project.ID); searchItems.Add(new SearchItem(EntityType.File, itemId, f.Title, f.CreateOn, new SearchItem(project), itemPath: "{2}")); } } } } catch (Exception err) { LogManager.GetLogger("ASC.Web").Error(err); } return(searchItems); }
public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, IFileDao fileDao, Folder parent, FilterType filter, Guid subjectId, OrderBy orderBy, String searchText, int from, int count, out int total) { total = 0; if (parent == null) { throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound); } var fileSecurity = Global.GetFilesSecurity(); var entries = Enumerable.Empty <FileEntry>(); if (parent.FolderType == FolderType.Projects && parent.ID.Equals(Global.FolderProjects)) { var apiServer = new ASC.Api.ApiServer(); var apiUrl = string.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl); var responseBody = apiServer.GetApiResponse(apiUrl, "GET"); if (responseBody != null) { var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody))); var projectLastModified = responseApi["response"].Value <String>(); const string projectLastModifiedCacheKey = "documents/projectFolders/projectLastModified"; if (HttpRuntime.Cache.Get(projectLastModifiedCacheKey) == null || !HttpRuntime.Cache.Get(projectLastModifiedCacheKey).Equals(projectLastModified)) { HttpRuntime.Cache.Remove(projectLastModifiedCacheKey); HttpRuntime.Cache.Insert(projectLastModifiedCacheKey, projectLastModified); } var projectListCacheKey = string.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID); var fromCache = HttpRuntime.Cache.Get(projectListCacheKey); if (fromCache == null || !string.IsNullOrEmpty(searchText)) { apiUrl = string.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open&fields=id,title,security,projectFolder", SetupInfo.WebApiBaseUrl); responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); var responseData = responseApi["response"]; if (!(responseData is JArray)) { return(entries.ToList()); } var folderIDProjectTitle = new Dictionary <object, KeyValuePair <int, string> >(); foreach (JObject projectInfo in responseData.Children()) { var projectID = projectInfo["id"].Value <int>(); var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value <String>()); int projectFolderID; JToken projectSecurityJToken; if (projectInfo.TryGetValue("security", out projectSecurityJToken)) { var projectSecurity = projectInfo["security"].Value <JObject>(); JToken projectCanFileReadJToken; if (projectSecurity.TryGetValue("canReadFiles", out projectCanFileReadJToken)) { if (!projectSecurity["canReadFiles"].Value <bool>()) { continue; } } } JToken projectFolderIDJToken; if (projectInfo.TryGetValue("projectFolder", out projectFolderIDJToken)) { projectFolderID = projectInfo["projectFolder"].Value <int>(); } else { projectFolderID = (int)FilesIntegration.RegisterBunch("projects", "project", projectID.ToString()); } if (!folderIDProjectTitle.ContainsKey(projectFolderID)) { folderIDProjectTitle.Add(projectFolderID, new KeyValuePair <int, string>(projectID, projectTitle)); } AscCache.Default.Remove("documents/folders/" + projectFolderID.ToString()); AscCache.Default.Insert("documents/folders/" + projectFolderID.ToString(), projectTitle, TimeSpan.FromMinutes(30)); } var folders = folderDao.GetFolders(folderIDProjectTitle.Keys.ToArray(), searchText, !string.IsNullOrEmpty(searchText), false); folders.ForEach(x => { x.Title = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title; x.FolderUrl = PathProvider.GetFolderUrl(x, folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Key : 0); }); folders = fileSecurity.FilterRead(folders).ToList(); entries = entries.Concat(folders); if (!string.IsNullOrEmpty(searchText)) { var files = fileDao.GetFiles(folderIDProjectTitle.Keys.ToArray(), searchText, !string.IsNullOrEmpty(searchText)).ToList(); files = fileSecurity.FilterRead(files).ToList(); entries = entries.Concat(files); } if (entries.Any() && string.IsNullOrEmpty(searchText)) { HttpRuntime.Cache.Remove(projectListCacheKey); HttpRuntime.Cache.Insert(projectListCacheKey, entries, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15)); } } else { entries = entries.Concat((IEnumerable <FileEntry>)fromCache); } } entries = FilterEntries(entries, filter, subjectId, searchText); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else if (parent.FolderType == FolderType.SHARE) { //share var shared = (IEnumerable <FileEntry>)fileSecurity.GetSharesForMe(searchText); shared = FilterEntries(shared, filter, subjectId, searchText); entries = entries.Concat(shared); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else { var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectId, searchText, !string.IsNullOrEmpty(searchText) && parent.FolderType != FolderType.TRASH).Cast <FileEntry>(); folders = fileSecurity.FilterRead(folders); entries = entries.Concat(folders); var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectId, searchText, withSubfolders: !string.IsNullOrEmpty(searchText) && parent.FolderType != FolderType.TRASH).Cast <FileEntry>(); files = fileSecurity.FilterRead(files); entries = entries.Concat(files); if (filter == FilterType.None || filter == FilterType.FoldersOnly) { var folderList = GetThirpartyFolders(parent, searchText); var thirdPartyFolder = FilterEntries(folderList, filter, subjectId, searchText); entries = entries.Concat(thirdPartyFolder); } } if (orderBy.SortedBy != SortedByType.New) { entries = SortEntries(entries, orderBy); total = entries.Count(); if (0 < from) { entries = entries.Skip(from); } if (0 < count) { entries = entries.Take(count); } } entries = FileMarker.SetTagsNew(folderDao, parent, entries); //sorting after marking if (orderBy.SortedBy == SortedByType.New) { entries = SortEntries(entries, orderBy); total = entries.Count(); if (0 < from) { entries = entries.Skip(from); } if (0 < count) { entries = entries.Take(count); } } SetFileStatus(entries.Where(r => r != null && r.ID != null && r.FileEntryType == FileEntryType.File).Select(r => r as File).ToList()); return(entries); }
public List <SearchGroup> Search(String searchText, int projectId) { var queryResult = _searchDao.Search(searchText, projectId); var groups = new Dictionary <int, SearchGroup>(); foreach (var r in queryResult) { var projId = 0; SearchItem item = null; if (r is Project) { var p = (Project)r; if (ProjectSecurity.CanRead(p)) { projId = p.ID; if (!groups.ContainsKey(projId)) { groups[projId] = new SearchGroup(projId, p.Title); } item = new SearchItem(EntityType.Project, p.ID, p.Title, p.Description, p.CreateOn); } } else { if (r is Milestone) { var m = (Milestone)r; if (ProjectSecurity.CanRead(m)) { projId = m.Project.ID; if (!groups.ContainsKey(projId)) { groups[projId] = new SearchGroup(projId, m.Project.Title); } item = new SearchItem(EntityType.Milestone, m.ID, m.Title, null, m.CreateOn); } } else if (r is Message) { var m = (Message)r; if (ProjectSecurity.CanReadMessages(m.Project)) { projId = m.Project.ID; if (!groups.ContainsKey(projId)) { groups[projId] = new SearchGroup(projId, m.Project.Title); } item = new SearchItem(EntityType.Message, m.ID, m.Title, m.Content, m.CreateOn); } } else if (r is Task) { var t = (Task)r; if (ProjectSecurity.CanRead(t)) { projId = t.Project.ID; if (!groups.ContainsKey(projId)) { groups[projId] = new SearchGroup(projId, t.Project.Title); } item = new SearchItem(EntityType.Task, t.ID, t.Title, t.Description, t.CreateOn); } } } if (0 < projId && item != null) { groups[projId].Items.Add(item); } } try { // search in files var fileEntries = new List <Files.Core.FileEntry>(); using (var folderDao = FilesIntegration.GetFolderDao()) using (var fileDao = FilesIntegration.GetFileDao()) { fileEntries.AddRange(folderDao.Search(searchText, Files.Core.FolderType.BUNCH).Cast <Files.Core.FileEntry>()); fileEntries.AddRange(fileDao.Search(searchText, Files.Core.FolderType.BUNCH).Cast <Files.Core.FileEntry>()); var projectIds = projectId != 0 ? new List <int> { projectId } : fileEntries.GroupBy(f => f.RootFolderId) .Select(g => folderDao.GetFolder(g.Key)) .Select(f => f != null ? folderDao.GetBunchObjectID(f.RootFolderId).Split('/').Last() : null) .Where(s => !string.IsNullOrEmpty(s)) .Select(s => int.Parse(s)); var rootProject = projectIds.ToDictionary(id => FilesIntegration.RegisterBunch("projects", "project", id.ToString())); fileEntries.RemoveAll(f => !rootProject.ContainsKey(f.RootFolderId)); var security = FilesIntegration.GetFileSecurity(); fileEntries.RemoveAll(f => !security.CanRead(f)); foreach (var f in fileEntries) { var id = rootProject[f.RootFolderId]; if (!groups.ContainsKey(id)) { var project = _projDao.GetById(id); if (project != null && ProjectSecurity.CanRead(project) && ProjectSecurity.CanReadFiles(project)) { groups[id] = new SearchGroup(id, project.Title); } else { continue; } } var item = new SearchItem { EntityType = EntityType.File, ID = f is Files.Core.File ? ((Files.Core.File)f).ViewUrl : string.Format("{0}tmdocs.aspx?prjID={1}#{2}", VirtualPathUtility.ToAbsolute("~/products/projects/"), id, f.ID), Title = f.Title, CreateOn = f.CreateOn, }; groups[id].Items.Add(item); } } } catch (Exception err) { LogManager.GetLogger("ASC.Web").Error(err); } return(new List <SearchGroup>(groups.Values)); }
public object GetRoot(int projectId) { return(FilesIntegration.RegisterBunch("projects", "project", projectId.ToString())); }
public object GetRoot(int projectId) { return(FilesIntegration.RegisterBunch(Module, Bunch, projectId.ToString(CultureInfo.InvariantCulture))); }
public IEnumerable <object> GetRoots(IEnumerable <int> projectIds) { return(FilesIntegration.RegisterBunchFolders(Module, Bunch, projectIds.Select(id => id.ToString(CultureInfo.InvariantCulture)))); }
public object GetMy() { return(FilesIntegration.RegisterBunch("files", "my", SecurityContext.CurrentAccount.ID.ToString())); }
public static void RegisterFileSecurityProvider() { FilesIntegration.RegisterFileSecurityProvider(Module, Bunch, new SecurityAdapterProvider()); }
public object GetRoot() { return(FilesIntegration.RegisterBunch("crm", "crm_common", "")); }
public void RunJob() { using (var smtpClient = GetSmtpClient()) { CoreContext.TenantManager.SetCurrentTenant(_tenantID); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser)); var contactCount = _contactID.Count; if (contactCount == 0) { Complete(); return; } var from = new MailAddress(_smtpSetting.SenderEmailAddress, _smtpSetting.SenderDisplayName, Encoding.UTF8); var filePaths = new List <String>(); using (var fileDao = FilesIntegration.GetFileDao()) { foreach (var fileID in _fileID) { var fileObj = fileDao.GetFile(fileID); if (fileObj == null) { continue; } using (var fileStream = fileDao.GetFileStream(fileObj)) { var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var filePath = Path.Combine(directoryPath, fileObj.Title); using (var newFileStream = File.Create(filePath)) { fileStream.StreamCopyTo(newFileStream); } filePaths.Add(filePath); } } } var templateManager = new MailTemplateManager(_daoFactory); var deliveryCount = 0; try { if (smtpClient.EnableSsl && WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback = (s, c, h, e) => { return(true); }; } Error = String.Empty; foreach (var contactID in _contactID) { if (IsCompleted) { break; // User selected cancel } var contactInfoDao = _daoFactory.GetContactInfoDao(); var startDate = DateTime.Now; var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true); if (contactEmails.Count == 0) { continue; } var recipientEmail = contactEmails[0].Data; if (!IsValidMail(recipientEmail)) { Error += String.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>"; continue; } var to = new MailAddress(recipientEmail); using (var message = new MailMessage(from, to)) { try { message.Subject = _subject; message.Body = templateManager.Apply(_bodyTempate, contactID); message.SubjectEncoding = Encoding.UTF8; message.BodyEncoding = Encoding.UTF8; message.IsBodyHtml = true; foreach (var filePath in filePaths) { message.Attachments.Add(new Attachment(filePath)); } _log.Debug(GetLoggerRow(message)); smtpClient.Send(message); if (_storeInHistory) { AddToHistory(contactID, String.Format(CRMCommonResource.MailHistoryEventTemplate, message.Subject)); } var endDate = DateTime.Now; var waitInterval = endDate.Subtract(startDate); deliveryCount++; var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount)); Status = new { RecipientCount = _contactID.Count, EstimatedTime = estimatedTime.ToString(), DeliveryCount = deliveryCount }; } catch (SmtpFailedRecipientsException ex) { for (var i = 0; i < ex.InnerExceptions.Length; i++) { var status = ex.InnerExceptions[i].StatusCode; if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) { Error = String.Format(CRMCommonResource.MailSender_MailboxBusyException, 5); _log.Error(Error, ex); Thread.Sleep(TimeSpan.FromSeconds(5)); smtpClient.Send(message); deliveryCount++; } else { Error += String.Format(CRMCommonResource.MailSender_FailedDeliverException, ex.InnerExceptions[i].FailedRecipient) + "<br/>"; _log.Error(Error, ex); } } } _exactPercentageValue += 100.0 / contactCount; Percentage = Math.Round(_exactPercentageValue); if (Percentage > 100) { Percentage = 100; } } } } finally { if (smtpClient.EnableSsl && WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback = null; } foreach (var filePath in filePaths) { if (File.Exists(filePath)) { File.Delete(filePath); } } } Status = new { RecipientCount = _contactID.Count, EstimatedTime = TimeSpan.Zero.ToString(), DeliveryCount = deliveryCount }; } Complete(); }
public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, Folder parent, FilterType filter, Guid subjectId, OrderBy orderBy, String searchText, int from, int count, out int total) { total = 0; if (parent == null) { throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound); } var fileSecurity = Global.GetFilesSecurity(); var entries = Enumerable.Empty <FileEntry>(); if (parent.FolderType == FolderType.Projects && parent.ID.Equals(Global.FolderProjects)) { var apiServer = new ASC.Api.ApiServer(); var apiUrl = String.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl); var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); var projectLastModified = responseApi["response"].Value <String>(); const string projectLastModifiedCacheKey = "documents/projectFolders/projectLastModified"; if (HttpRuntime.Cache.Get(projectLastModifiedCacheKey) == null || !HttpRuntime.Cache.Get(projectLastModifiedCacheKey).Equals(projectLastModified)) { HttpRuntime.Cache.Insert(projectLastModifiedCacheKey, projectLastModified); } var projectListCacheKey = String.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID); var fromCache = HttpRuntime.Cache.Get(projectListCacheKey); if (fromCache == null) { apiUrl = String.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending", SetupInfo.WebApiBaseUrl); responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); var responseData = responseApi["response"]; if (!(responseData is JArray)) { return(entries.ToList()); } var folderIDProjectTitle = new Dictionary <object, String>(); foreach (JObject projectInfo in responseData.Children()) { var projectID = projectInfo["id"].Value <String>(); var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value <String>()); int projectFolderID; JToken projectSecurityJToken; if (projectInfo.TryGetValue("security", out projectSecurityJToken)) { var projectSecurity = projectInfo["security"].Value <JObject>(); JToken projectCanFileReadJToken; if (projectSecurity.TryGetValue("canReadFiles", out projectCanFileReadJToken)) { if (!projectSecurity["canReadFiles"].Value <bool>()) { continue; } } } JToken projectFolderIDJToken; if (projectInfo.TryGetValue("projectFolder", out projectFolderIDJToken)) { projectFolderID = projectInfo["projectFolder"].Value <int>(); } else { projectFolderID = (int)FilesIntegration.RegisterBunch("projects", "project", projectID); } if (!folderIDProjectTitle.ContainsKey(projectFolderID)) { folderIDProjectTitle.Add(projectFolderID, projectTitle); } HttpRuntime.Cache.Insert("documents/folders/" + projectFolderID.ToString(), projectTitle, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30)); } var folders = folderDao.GetFolders(folderIDProjectTitle.Keys.ToArray()); folders.ForEach(x => { x.Title = folderIDProjectTitle[x.ID]; x.Access = FileShare.ReadWrite; x.FolderUrl = PathProvider.GetFolderUrl(x); }); entries = entries.Concat(folders); if (entries.Any()) { HttpRuntime.Cache.Insert(projectListCacheKey, entries, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15)); } } else { entries = entries.Concat((IEnumerable <FileEntry>)fromCache); } entries = FilterEntries(entries, filter, subjectId, searchText); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else if (parent.FolderType == FolderType.SHARE) { //share var shared = (IEnumerable <FileEntry>)fileSecurity.GetSharesForMe(); shared = FilterEntries(shared, filter, subjectId, searchText) .Where(f => f.CreateBy != SecurityContext.CurrentAccount.ID && // don't show my files f.RootFolderType == FolderType.USER); // don't show common files (common files can read) entries = entries.Concat(shared); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else { var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectId, searchText).Cast <FileEntry>(); folders = fileSecurity.FilterRead(folders); entries = entries.Concat(folders); var files = folderDao.GetFiles(parent.ID, orderBy, filter, subjectId, searchText).Cast <FileEntry>(); files = fileSecurity.FilterRead(files); entries = entries.Concat(files); if ((parent.ID.Equals(Global.FolderMy) || parent.ID.Equals(Global.FolderCommon)) && ImportConfiguration.SupportInclusion && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor() && (Global.IsAdministrator || CoreContext.Configuration.Personal || FilesSettings.EnableThirdParty)) { using (var securityDao = Global.DaoFactory.GetSecurityDao()) using (var providerDao = Global.DaoFactory.GetProviderDao()) { var providers = providerDao.GetProvidersInfo(parent.RootFolderType); var folderList = providers .Select(providerInfo => //Fake folder. Don't send request to third party new Folder { ID = providerInfo.RootFolderId, ParentFolderID = parent.ID, CreateBy = providerInfo.Owner, CreateOn = providerInfo.CreateOn, FolderType = FolderType.DEFAULT, ModifiedBy = providerInfo.Owner, ModifiedOn = providerInfo.CreateOn, ProviderId = providerInfo.ID, ProviderKey = providerInfo.ProviderKey, RootFolderCreator = providerInfo.Owner, RootFolderId = providerInfo.RootFolderId, RootFolderType = providerInfo.RootFolderType, Shareable = false, Title = providerInfo.CustomerTitle, TotalFiles = 0, TotalSubFolders = 0 } ) .Where(fileSecurity.CanRead).ToList(); if (folderList.Any()) { securityDao.GetPureShareRecords(folderList.Cast <FileEntry>().ToArray()) .Where(x => x.Owner == SecurityContext.CurrentAccount.ID) .Select(x => x.EntryId).Distinct().ToList() .ForEach(id => { folderList.First(y => y.ID.Equals(id)).SharedByMe = true; }); } var thirdPartyFolder = FilterEntries(folderList, filter, subjectId, searchText); entries = entries.Concat(thirdPartyFolder); } } } if (orderBy.SortedBy != SortedByType.New) { entries = SortEntries(entries, orderBy); total = entries.Count(); if (0 < from) { entries = entries.Skip(from); } if (0 < count) { entries = entries.Take(count); } } entries = FileMarker.SetTagsNew(folderDao, parent, entries); SetFileStatus(entries.Select(r => r as File).Where(r => r != null && r.ID != null)); //sorting after marking if (orderBy.SortedBy == SortedByType.New) { entries = SortEntries(entries, orderBy); total = entries.Count(); if (0 < from) { entries = entries.Skip(from); } if (0 < count) { entries = entries.Take(count); } } return(entries); }
public MailAttachment AttachFileFromDocuments(int tenant, string user, int messageId, string fileId, string version, string shareLink) { MailAttachment result; using (var fileDao = FilesIntegration.GetFileDao()) { File file; var checkLink = FileShareLink.Check(shareLink, true, fileDao, out file); if (!checkLink && file == null) { file = String.IsNullOrEmpty(version) ? fileDao.GetFile(fileId) : fileDao.GetFile(fileId, Convert.ToInt32(version)); } if (file == null) { throw new AttachmentsException(AttachmentsException.Types.DocumentNotFound, "File not found."); } if (!checkLink && !FilesIntegration.GetFileSecurity().CanRead(file)) { throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied."); } if (!fileDao.IsExistOnStorage(file)) { throw new AttachmentsException(AttachmentsException.Types.DocumentNotFound, "File not exists on storage."); } _log.Info("Original file id: {0}", file.ID); _log.Info("Original file name: {0}", file.Title); var fileExt = FileUtility.GetFileExtension(file.Title); var curFileType = FileUtility.GetFileTypeByFileName(file.Title); _log.Info("File converted type: {0}", file.ConvertedType); if (file.ConvertedType != null) { switch (curFileType) { case FileType.Image: fileExt = file.ConvertedType == ".zip" ? ".pptt" : file.ConvertedType; break; case FileType.Spreadsheet: fileExt = file.ConvertedType != ".xlsx" ? ".xlst" : file.ConvertedType; break; default: if (file.ConvertedType == ".doct" || file.ConvertedType == ".xlst" || file.ConvertedType == ".pptt") { fileExt = file.ConvertedType; } break; } } var convertToExt = string.Empty; switch (curFileType) { case FileType.Document: if (fileExt == ".doct") { convertToExt = ".docx"; } break; case FileType.Spreadsheet: if (fileExt == ".xlst") { convertToExt = ".xlsx"; } break; case FileType.Presentation: if (fileExt == ".pptt") { convertToExt = ".pptx"; } break; } if (!string.IsNullOrEmpty(convertToExt) && fileExt != convertToExt) { var fileName = Path.ChangeExtension(file.Title, convertToExt); _log.Info("Changed file name - {0} for file {1}:", fileName, file.ID); using (var readStream = FileConverter.Exec(file, convertToExt)) { if (readStream == null) { throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied."); } using (var memStream = new MemoryStream()) { readStream.StreamCopyTo(memStream); result = AttachFile(tenant, user, messageId, fileName, memStream); _log.Info("Attached attachment: ID - {0}, Name - {1}, StoredUrl - {2}", result.fileName, result.fileName, result.storedFileUrl); } } } else { using (var readStream = fileDao.GetFileStream(file)) { if (readStream == null) { throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied."); } result = AttachFile(tenant, user, messageId, file.Title, readStream); _log.Info("Attached attachment: ID - {0}, Name - {1}, StoredUrl - {2}", result.fileName, result.fileName, result.storedFileUrl); } } } return(result); }
private IEnumerable <FileEntry> Filter(IEnumerable <FileEntry> entries, FilesSecurityActions action, Guid userId) { if (entries == null || !entries.Any()) { return(Enumerable.Empty <FileEntry>()); } entries = entries.Where(f => f != null); var result = new List <FileEntry>(entries.Count()); // save entries order var order = entries.Select((f, i) => new { Id = f.UniqID, Pos = i }).ToDictionary(e => e.Id, e => e.Pos); // common or my files Func <FileEntry, bool> filter = f => f.RootFolderType == FolderType.COMMON || f.RootFolderType == FolderType.USER || f.RootFolderType == FolderType.SHARE || f.RootFolderType == FolderType.Projects; var isVisitor = CoreContext.UserManager.GetUsers(userId).IsVisitor(); if (entries.Any(filter)) { var subjects = GetUserSubjects(userId); List <FileShareRecord> shares = null; foreach (var e in entries.Where(filter)) { if (!CoreContext.Authentication.GetAccountByID(userId).IsAuthenticated&& userId != FileConstant.ShareLinkId) { continue; } if (action != FilesSecurityActions.Read && e is Folder && ((Folder)e).FolderType == FolderType.Projects) { // Root Projects folder read-only continue; } if (action != FilesSecurityActions.Read && e is Folder && ((Folder)e).FolderType == FolderType.SHARE) { // Root Share folder read-only continue; } if (e.RootFolderType == FolderType.USER && e.RootFolderCreator == userId && !isVisitor) { // user has all right in his folder result.Add(e); continue; } if (DefaultCommonShare == FileShare.Read && action == FilesSecurityActions.Read && e is Folder && ((Folder)e).FolderType == FolderType.COMMON) { // all can read Common folder result.Add(e); continue; } if (action == FilesSecurityActions.Read && e is Folder && ((Folder)e).FolderType == FolderType.SHARE) { // all can read Share folder result.Add(e); continue; } if (e.RootFolderType == FolderType.COMMON && IsAdministrator(userId)) { // administrator in Common has all right result.Add(e); continue; } if (shares == null) { shares = GetShares(entries.ToArray()).Join(subjects, r => r.Subject, s => s, (r, s) => r).ToList(); // shares ordered by level } FileShareRecord ace; if (e is File) { ace = shares .OrderBy(r => r, new SubjectComparer(subjects)) .ThenByDescending(r => r.Share) .FirstOrDefault(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.File); if (ace == null) { // share on parent folders ace = shares.Where(r => Equals(r.EntryId, ((File)e).FolderID) && r.EntryType == FileEntryType.Folder) .OrderBy(r => r, new SubjectComparer(subjects)) .ThenBy(r => r.Level) .ThenByDescending(r => r.Share) .FirstOrDefault(); } } else { ace = shares.Where(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.Folder) .OrderBy(r => r, new SubjectComparer(subjects)) .ThenBy(r => r.Level) .ThenByDescending(r => r.Share) .FirstOrDefault(); } var defaultShare = e.RootFolderType == FolderType.USER ? DefaultMyShare : DefaultCommonShare; e.Access = ace != null ? ace.Share : defaultShare; if (action == FilesSecurityActions.Read && e.Access <= FileShare.Read) { result.Add(e); } else if (action == FilesSecurityActions.Edit && e.Access <= FileShare.ReadWrite) { result.Add(e); } else if (action == FilesSecurityActions.Create && e.Access <= FileShare.ReadWrite) { result.Add(e); } // can't delete in My other people's files else if (action == FilesSecurityActions.Delete && e.Access <= FileShare.ReadWrite && e.RootFolderType == FolderType.COMMON) { result.Add(e); } else if (e.Access <= FileShare.Read && e.CreateBy == userId && (e is File || ((Folder)e).FolderType != FolderType.COMMON)) { result.Add(e); } if (e.CreateBy == userId) { e.Access = FileShare.None; //HACK: for client } } } // files in bunch filter = f => f.RootFolderType == FolderType.BUNCH; if (entries.Any(filter)) { using (var folderDao = daoFactory.GetFolderDao()) { var findedAdapters = new Dictionary <object, IFileSecurity>(); foreach (var e in entries.Where(filter)) { IFileSecurity adapter = null; if (!findedAdapters.ContainsKey(e.RootFolderId)) { var root = folderDao.GetFolder(e.RootFolderId); if (root != null) { var path = folderDao.GetBunchObjectID(root.ID); adapter = FilesIntegration.GetFileSecurity(path); } findedAdapters[e.RootFolderId] = adapter; } adapter = findedAdapters[e.RootFolderId]; if (adapter == null) { continue; } if (adapter.CanRead(e, userId) && adapter.CanCreate(e, userId) && adapter.CanEdit(e, userId) && adapter.CanDelete(e, userId)) { e.Access = FileShare.None; result.Add(e); } else if (action == FilesSecurityActions.Create && adapter.CanCreate(e, userId)) { e.Access = FileShare.ReadWrite; result.Add(e); } else if (action == FilesSecurityActions.Delete && adapter.CanDelete(e, userId)) { e.Access = FileShare.ReadWrite; result.Add(e); } else if (action == FilesSecurityActions.Read && adapter.CanRead(e, userId)) { if (adapter.CanCreate(e, userId) || adapter.CanDelete(e, userId) || adapter.CanEdit(e, userId)) { e.Access = FileShare.ReadWrite; } else { e.Access = FileShare.Read; } result.Add(e); } else if (action == FilesSecurityActions.Edit && adapter.CanEdit(e, userId)) { e.Access = FileShare.ReadWrite; result.Add(e); } } } } // files in trash filter = f => f.RootFolderType == FolderType.TRASH; if (entries.Any(filter)) { using (var folderDao = daoFactory.GetFolderDao()) { var mytrashId = folderDao.GetFolderID(FileConstant.ModuleId, "trash", userId.ToString(), false); foreach (var e in entries.Where(filter)) { // only in my trash if (Equals(e.RootFolderId, mytrashId)) { result.Add(e); } } } } if (IsAdministrator(userId)) { // administrator can work with crashed entries (crash in files_folder_tree) filter = f => f.RootFolderType == FolderType.DEFAULT; result.AddRange(entries.Where(filter)); } // restore entries order result.Sort((x, y) => order[x.UniqID].CompareTo(order[y.UniqID])); return(result); }
public void RunJob() { SmtpClient smtpClient = null; try { CoreContext.TenantManager.SetCurrentTenant(_tenantID); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser)); smtpClient = GetSmtpClient(); using (var scope = DIHelper.Resolve()) { var _daoFactory = scope.Resolve <DaoFactory>(); var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture(); Thread.CurrentThread.CurrentCulture = userCulture; Thread.CurrentThread.CurrentUICulture = userCulture; var contactCount = _contactID.Count; if (contactCount == 0) { Complete(); return; } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); var from = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress); var filePaths = new List <string>(); using (var fileDao = FilesIntegration.GetFileDao()) { foreach (var fileID in _fileID) { var fileObj = fileDao.GetFile(fileID); if (fileObj == null) { continue; } using (var fileStream = fileDao.GetFileStream(fileObj)) { var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var filePath = Path.Combine(directoryPath, fileObj.Title); using (var newFileStream = File.Create(filePath)) { fileStream.StreamCopyTo(newFileStream); } filePaths.Add(filePath); } } } var templateManager = new MailTemplateManager(_daoFactory); var deliveryCount = 0; try { Error = string.Empty; foreach (var contactID in _contactID) { _exactPercentageValue += 100.0 / contactCount; Percentage = Math.Round(_exactPercentageValue); if (IsCompleted) { break; // User selected cancel } var contactInfoDao = _daoFactory.ContactInfoDao; var startDate = DateTime.Now; var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true); if (contactEmails.Count == 0) { continue; } var recipientEmail = contactEmails[0].Data; if (!recipientEmail.TestEmailRegex()) { Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>"; continue; } var to = new MailboxAddress(recipientEmail); var mimeMessage = new MimeMessage { Subject = _subject }; mimeMessage.From.Add(from); mimeMessage.To.Add(to); var bodyBuilder = new BodyBuilder { HtmlBody = templateManager.Apply(_bodyTempate, contactID) }; foreach (var filePath in filePaths) { bodyBuilder.Attachments.Add(filePath); } mimeMessage.Body = bodyBuilder.ToMessageBody(); mimeMessage.Headers.Add("Auto-Submitted", "auto-generated"); _log.Debug(GetLoggerRow(mimeMessage)); var success = false; try { smtpClient.Send(mimeMessage); success = true; } catch (SmtpCommandException ex) { _log.Error(Error, ex); Error += string.Format(CRMCommonResource.MailSender_FailedDeliverException, recipientEmail) + "<br/>"; } if (success) { if (_storeInHistory) { AddToHistory(contactID, string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject), _daoFactory); } var endDate = DateTime.Now; var waitInterval = endDate.Subtract(startDate); deliveryCount++; var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount)); Status = new { RecipientCount = _contactID.Count, EstimatedTime = estimatedTime.ToString(), DeliveryCount = deliveryCount }; } if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); if (Percentage > 100) { Percentage = 100; if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); } } } catch (OperationCanceledException) { _log.Debug("cancel mail sender"); } finally { foreach (var filePath in filePaths) { if (File.Exists(filePath)) { File.Delete(filePath); } } } Status = new { RecipientCount = _contactID.Count, EstimatedTime = TimeSpan.Zero.ToString(), DeliveryCount = deliveryCount }; } } catch (SocketException e) { Error = e.Message; _log.Error(Error); } finally { if (smtpClient != null) { smtpClient.Dispose(); } Complete(); } }
public virtual void DeleteBatchContact(int[] contactID) { if (contactID == null || contactID.Length == 0) { return; } // Delete relative keys _cache.Insert(_contactCacheKey, String.Empty); var contacts = GetContacts(contactID).Where(CRMSecurity.CanAccessTo).ToList(); if (contacts.Count == 0) { return; } var personsID = new List <int>(); var companyID = new List <int>(); var newContactID = new List <int>(); foreach (var contact in contacts) { newContactID.Add(contact.ID); if (contact is Company) { companyID.Add(contact.ID); } else { personsID.Add(contact.ID); } } contactID = newContactID.ToArray(); using (var tx = DbManager.BeginTransaction()) { DbManager.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.In("entity_id", contactID) & Exp.In("entity_type", new[] { (int)EntityType.Contact, (int)EntityType.Person, (int)EntityType.Company }))); DbManager.ExecuteNonQuery(Delete("crm_task").Where(Exp.In("contact_id", contactID))); DbManager.ExecuteNonQuery(new SqlDelete("crm_entity_tag") .Where(Exp.In("entity_id", contactID) & Exp.Eq("entity_type", (int)EntityType.Contact))); DbManager.ExecuteNonQuery(Delete("crm_relationship_event").Where(Exp.In("contact_id", contactID))); DbManager.ExecuteNonQuery(Update("crm_deal").Set("contact_id", 0).Where(Exp.In("contact_id", contactID))); if (companyID.Count > 0) { DbManager.ExecuteNonQuery(Update("crm_contact").Set("company_id", 0).Where(Exp.In("company_id", companyID))); } if (personsID.Count > 0) { RemoveRelative(null, EntityType.Person, personsID.ToArray()); } RemoveRelative(contactID, EntityType.Any, null); DbManager.ExecuteNonQuery(Delete("crm_contact_info").Where(Exp.In("contact_id", contactID))); DbManager.ExecuteNonQuery(Delete("crm_contact").Where(Exp.In("id", contactID))); tx.Commit(); } contacts.ForEach(contact => CoreContext.AuthorizationManager.RemoveAllAces(contact)); using (var tagdao = FilesIntegration.GetTagDao()) using (var filedao = FilesIntegration.GetFileDao()) { var tagNames = DbManager.ExecuteList(Query("crm_relationship_event").Select("id").Where(Exp.In("contact_id", contactID) & Exp.Eq("have_files", true))) .Select(row => String.Format("RelationshipEvent{0}", row[0])).ToArray(); if (tagNames.Length == 0) { return; } var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray(); var store = FilesIntegration.GetStore(); foreach (var filesID in filesIDs) { filedao.DeleteFolder(filesID); filedao.DeleteFile(filesID); } } }