// ************************************** // DeleteCatalog // ************************************** public static void DeleteCatalog(int catalogId) { using (var ctx = new SongSearchContext()) { ctx.DeleteCatalog(catalogId); ctx.SaveChanges(); } }
// ************************************** // CreateNewInvitation // ************************************** public static Guid CreateNewInvitation(string inviteEmailAddress) { using (var ctx = new SongSearchContext()) { inviteEmailAddress = inviteEmailAddress.ToLower(); var userId = Account.User().UserId; var inv = ctx.Invitations.SingleOrDefault( i => i.InvitationEmailAddress.ToLower() == inviteEmailAddress.ToLower() && i.InvitationStatus == (int)InvitationStatusCodes.Open && i.InvitedByUserId == userId); if (inv == null) { inv = new Invitation { InvitationId = Guid.NewGuid(), InvitationEmailAddress = inviteEmailAddress, ExpirationDate = DateTime.Now.AddDays(30).Date, InvitedByUserId = userId, InvitationStatus = (int)InvitationStatusCodes.Open, IsPlanInvitation = !Account.User().IsSuperAdmin() //if it's a member admin, count against their user quota }; ctx.Invitations.AddObject(inv); } else {//extend expiration date //inv.InvitationStatus = (int)InvitationStatusCodes.Open; inv.ExpirationDate = DateTime.Now.AddDays(30).Date; } ctx.SaveChanges(); return inv.InvitationId; } }
// ************************************** // RegisterUser // ************************************** public static User RegisterUser(User user, Guid invitationCode) { using (var ctx = new SongSearchContext()) { var existing = ctx.GetUser(user); if (existing != null) { return existing; } else { var inv = ctx.Invitations.SingleOrDefault(i => i.InvitationId.Equals(invitationCode) && i.InvitationEmailAddress.Equals(user.UserName)); var pricingPlan = ctx.PricingPlans.SingleOrDefault(x => x.PricingPlanId == user.PricingPlanId); if (inv == null) { throw new ArgumentOutOfRangeException(String.Format("Invalid invitation {0}", inv.InvitationId), innerException: null); } else { // ---------------------------------- // CREATE USER // ---------------------------------- var newUser = ctx.Create(user, inv, pricingPlan); ctx.SaveChanges(); // ---------------------------------- // GET / CREATE PLAN SUBSCRIPTION // ---------------------------------- if (!inv.IsPlanInvitation) { // ---------------------------------- // GET / CREATE PLAN BALANCE // ---------------------------------- var balance = ctx.SubscribeUserTo(newUser, pricingPlan); } else { newUser.PlanBalanceId = inv.InvitedByUser.PlanBalance.PlanBalanceId; newUser.PlanUserId = inv.InvitedByUser.UserId; ctx.AddToUserBalance(newUser); ctx.AddToAdminBalance(newUser); } // ---------------------------------- // CATALOG ACCESS // ---------------------------------- // Get parent users catalog where parent user is at least a plugger and assign to new user in client role var catalogs = ctx.UserCatalogRoles.Where(x => x.UserId == inv.InvitedByUserId && x.RoleId <= (int)Roles.Admin); catalogs.ForEach(c => newUser.UserCatalogRoles.Add(new UserCatalogRole() { CatalogId = c.CatalogId, RoleId = (int)Roles.Client }) ); inv.InvitationStatus = (int)InvitationStatusCodes.Registered; ctx.SaveChanges(); inv = null; return newUser; } } } }
// ************************************** // AddToMyActiveCart // ************************************** public static void AddToMyActiveCart(int contentId) { using (var ctx = new SongSearchContext()) { var content = ctx.Contents.SingleOrDefault(c => c.ContentId == contentId); if (content == null) { throw new ArgumentException(SystemErrors.ItemDoesNotExist); } // Check if open cart exists and if needed create new cart var cart = ctx.GetActiveCart() ?? EmptyCart(); if (cart != null) { if (cart.Contents.Any(i => i.ContentId == contentId)) { return; } } else { cart = EmptyCart(); ctx.Carts.AddObject(cart); } if (cart.Contents.Count() < 100) { cart.Contents.Add(content); } else { throw new ArgumentOutOfRangeException("You cart already contains the maximum number of items (100)"); } ctx.SaveChanges(); } }
public static void AddToMyActiveCart(int[] contentIds) { // Check if open cart exists and if needed create new cart using (var ctx = new SongSearchContext()) { var cart = ctx.GetActiveCart() ?? EmptyCart(); if (cart.CartId == 0) { ctx.Carts.AddObject(cart); } if (cart.Contents.Count() + contentIds.Count() > 100) { throw new ArgumentOutOfRangeException("You cart already contains the maximum number of items (100)"); } var contents = ctx.Contents.Where(c => contentIds.Contains(c.ContentId)).ToList(); foreach (var contentId in contentIds) { if (!cart.Contents.Any(i => i.ContentId == contentId)) { var content = contents.SingleOrDefault(c => c.ContentId == contentId); if (content == null) { throw new ArgumentException(SystemErrors.ItemDoesNotExist); } cart.Contents.Add(content); } } ctx.SaveChanges(); } }
// ************************************** // Delete // ************************************** public static void Delete(int contentId) { using (var ctx = new SongSearchContext()) { ctx.DeleteContent(contentId); ctx.SaveChanges(); } }
// ---------------------------------------------------------------------------- // (Public) // ---------------------------------------------------------------------------- // ************************************** // AddToUserBalance // ************************************** public static void AddToUserBalance(this User user) { using (var ctx = new SongSearchContext()) { ctx.AddToUserBalance(user); ctx.SaveChanges(); } }
// ************************************** // GetCatalog // ************************************** public static Catalog GetCatalogDetail(int catalogId) { if (!Account.User().IsAtLeastInCatalogRole(Roles.Admin, catalogId)) { return null; } using (var ctx = new SongSearchContext()) { return ctx.GetCatalogGraph(catalogId); } }
// ************************************** // DeleteTag // ************************************** public static void DeleteTag(int tagId) { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { var tag = ctx.Tags.SingleOrDefault(t => t.TagId == tagId && t.CreatedByUserId == userId); if (tag != null) { ctx.Tags.DeleteObject(tag); ctx.SaveChanges(); } } }
public static void Delete(int[] contentIds) { using (var ctx = new SongSearchContext()) { foreach (var contentId in contentIds) { ctx.DeleteContent(contentId); } ctx.SaveChanges(); } }
// ************************************** // DeleteUser // ************************************** public static void DeleteUser(int userId, bool takeOwnerShip = false) { using (var ctx = new SongSearchContext()) { var user = ctx.Users.SingleOrDefault(x => x.UserId == userId); if (user != null) { if (user.UserId == Account.User().UserId) { throw new ArgumentException("You cannot delete yourself"); } if (user.IsSuperAdmin() && GetNumberOfUsersByAccessLevel(Roles.SuperAdmin) <= 1) { throw new ArgumentException("You cannot delete the last SuperAdmin"); } else { //if (takeOwnerShip) { // ctx.TakeOwnerShip(user); //} ctx.ReParentOrphans(user, user.ParentUser); if (user.CreatedCatalogs.Count() > 0) { var userCats = user.CreatedCatalogs.ToList(); foreach (var cat in userCats) { ctx.DeleteCatalog(cat.CatalogId); } } if (user.Invitation != null) { ctx.Invitations.DeleteObject(user.Invitation); } //handled via cascade in db //user.ActiveCartContents.ToList().ForEach(x => user.ActiveCartContents.Remove(x)); //user.UserCatalogRoles.ToList().ForEach(x => user.UserCatalogRoles.Remove(x)); var balance = user.PlanBalance; // ctx.PlanBalances.SingleOrDefault(x => x.PlanBalanceId == user.PlanBalanceId); if (balance != null) { balance.Users.Remove(user); if (balance.Users.Count() == 0) { ctx.Delete(balance); } else { ctx.RemoveFromUserBalance(user); if (user.IsAnyAdmin()) { ctx.RemoveFromAdminBalance(user); } } } ctx.Users.DeleteObject(user); ctx.SaveChanges(); } } } }
public static SiteProfile SiteProfile(string profileName, bool cached = true) { if (cached) { return CacheService .SiteProfiles() .SingleOrDefault(s => s.ProfileName.Equals(profileName, StringComparison.InvariantCultureIgnoreCase)); } else { using (var ctx = new SongSearchContext()) { var profile = ctx.SiteProfiles .Include("Contacts") .SingleOrDefault(s => s.ProfileName.Equals(profileName, StringComparison.InvariantCultureIgnoreCase)); return profile; } } }
public static SiteProfile SiteProfile(int profileId, bool cached = true) { if (cached) { return CacheService .SiteProfiles() .SingleOrDefault(s => s.ProfileId == profileId); } else { using (var ctx = new SongSearchContext()) { var profile = ctx.SiteProfiles .Include("Contacts") .SingleOrDefault(s => s.ProfileId == profileId); return profile; } } }
// ************************************** // UpdateMediaRemoteStatus // ************************************** public static void UpdateContentMedia(bool checkSize = false) { using (var ctx = new SongSearchContext()) { var contents = ctx.Contents.ToList(); var remoteList = GetRemoteFileList(new MediaVersion[] { MediaVersion.Preview, MediaVersion.Full }); //var remoteFolder = AmazonCloudService.GetContentPrefix(version); foreach (var content in contents.AsParallel()) { var dbContent = ctx.Contents.SingleOrDefault(c => c.ContentId == content.ContentId); foreach (var media in dbContent.ContentMedia.AsParallel()) { var key = AmazonCloudService.GetContentKey(media); var remoteMedia = remoteList[(MediaVersion)media.MediaVersion]; var filePath = Path.Combine((MediaVersion)media.MediaVersion == MediaVersion.Full ? SystemConfig.MediaPathFull : SystemConfig.MediaPathPreview, String.Concat(content.ContentId, SystemConfig.MediaDefaultExtension) ); var file = new FileInfo(filePath); if (file.Exists) { var hasRemoteFile = checkSize ? remoteMedia.Any(x => x.Key == key && x.Size == file.Length) : remoteMedia.Any(x => x.Key == key); media.IsRemote = hasRemoteFile; UpdateContentId3Tag(content, file); UpdateMediaId3info(media, file); } else { // media.IsRemote = false; dbContent.ContentMedia.Remove(media); } } ctx.SaveChanges(); } // DataSession.CommitChanges(); } Log.Debug("Done syncing"); }
// ************************************** // DownloadMissingFiles // ************************************** public static void DownloadMissingFiles() { using (var ctx = new SongSearchContext()) { var contents = ctx.Contents.Include("ContentMedia").ToList(); var remoteList = GetRemoteFileList(new MediaVersion[] { MediaVersion.Preview, MediaVersion.Full }); //var remoteFolder = AmazonCloudService.GetContentPrefix(version); foreach (var content in contents) { foreach (var media in content.ContentMedia) { var key = AmazonCloudService.GetContentKey(media); var remoteMedia = remoteList[(MediaVersion)media.MediaVersion]; var filePath = content.Media((MediaVersion)media.MediaVersion).MediaFilePath(true); var file = new FileInfo(filePath); // there's supposed to be a local file if (!file.Exists) { var remoteFile = remoteMedia.SingleOrDefault(x => x.Key == key); // let's see if we have it on the remote server if (remoteFile != null) { try { AmazonCloudService.GetContentMedia(file.FullName, media); Log.Debug(file.FullName + " downloaded"); } catch (Exception ex) { Log.Error(ex); } } else { Log.Debug(file.FullName + " can't be found!"); } } } } //DataSession.CommitChanges(); } Log.Debug("Done downloading"); }
// ************************************** // CreateCatalog // ************************************** public static int CreateCatalog(Catalog catalog) { using (var ctx = new SongSearchContext()) { var cat = ctx.GetCatalog(catalog.CatalogName); var user = Account.User(); if (cat == null) { cat = new Catalog { CatalogName = catalog.CatalogName }; ctx.Catalogs.AddObject(cat); ctx.SaveChanges(); UserManagementService.UpdateUserCatalogRole(user.UserId, cat.CatalogId, (int)Roles.Admin); } else if (!user.IsAtLeastInCatalogRole(Roles.Admin, cat.CatalogId)) { throw new AccessViolationException("You do not have admin rights to this catalog"); } return cat.CatalogId; } }
// ************************************** // SaveMetaDataToFile // ************************************** public static void SaveMetaDataToFile(int contentId) { using (var ctx = new SongSearchContext()) { var content = ctx.Contents.SingleOrDefault(c => c.ContentId == contentId); if (content != null) { var filePath = content.ContentMedia.PreviewVersion().MediaFilePath(true); //var file = new FileInfo(filePath); if (File.Exists(filePath)) { var tag = ID3v2Helper.CreateID3v2(filePath); tag.Title = content.Title; tag.Artist = content.Artist; tag.Year = content.ReleaseYear.HasValue ? content.ReleaseYear.Value.ToString() : tag.Year; IdSharp.Tagging.ID3v1.ID3v1Helper.RemoveTag(filePath); ID3v2Helper.RemoveTag(filePath); tag.Save(filePath); } } } }
// ************************************** // UpdateProfile // ************************************** public static bool ChangePassword(User user, string newPassword) { using (var ctx = new SongSearchContext()) { var dbuser = ctx.GetUser(user); if (dbuser == null) { return false; } if (!String.IsNullOrEmpty(newPassword)) { if (PasswordHashMatches(dbuser.Password, user.Password)) { dbuser.Password = newPassword.PasswordHashString(); } else { throw new ArgumentException("Passwords do not match"); } } else { throw new ArgumentNullException("New password cannot be blank"); } ctx.SaveChanges(); dbuser = null; return true; } }
// ************************************** // DeletedExpiredArchivedCarts // ************************************** public static void DeletedExpiredArchivedCarts() { using (var ctx = new SongSearchContext()) { var cutOffDate = DateTime.Now.AddDays(-DAYS_TO_DELETE); var expiredCarts = ctx.Carts .Where(c => c.CartStatus == (int)CartStatusCodes.Downloaded && c.LastUpdatedOn < cutOffDate) .ToList(); foreach (var cart in expiredCarts) { string path = cart.ArchivePath(); ctx.Carts.DeleteObject(cart); ctx.SaveChanges(); FileSystem.SafeDelete(path, false); } expiredCarts = null; } }
// ************************************** // Zip // ************************************** private static void CompressCart(int cartId, IList<ContentUserDownloadable> contentNames) { using (var ctx = new SongSearchContext()) { ctx.ContextOptions.LazyLoadingEnabled = false; try { var cart = ctx.Carts .Include("User") .Include("Contents") .Include("Contents.ContentMedia") .SingleOrDefault(c => c.CartId == cartId); if (cart != null) { var user = cart.User;// Account.User(cart.UserId); string zipPath = cart.ArchivePath(); string signature = user.IsAnyAdmin() ? user.Signature : user.ParentSignature(); var contents = cart.Contents.ToList(); using (var zip = new ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed; foreach (var content in contents) { if (content.HasMediaFullVersion) { var nameUserOverride = contentNames != null && contentNames.Any(x => x.ContentId == content.ContentId) ? contentNames.Where(x => x.ContentId == content.ContentId).Single().DownloadableName : null; var downloadName = nameUserOverride ?? (content.UserDownloadableName ?? MediaService.GetContentMediaFileName(content.ContentId)); try { byte[] asset = MediaService.GetContentMedia(content.ContentMedia.FullVersion()); asset = MediaService.WriteMediaSignature(asset, content, user); zip.AddEntry(String.Format("{0}\\{1}{2}", cart.ArchiveName.Replace(".zip", ""), downloadName, SystemConfig.MediaDefaultExtension), asset); } catch (Exception ex) { Log.Error(ex); Log.Debug(String.Concat(content.ContentId, " has an error/is missing.")); } } } zip.Save(zipPath); } } } catch (Exception ex) { Log.Error(ex); throw ex; } } }
public static void RemoveFromMyActiveCart(int[] contentIds) { using (var ctx = new SongSearchContext()) { var cart = ctx.GetActiveCart(); if (cart != null) { foreach (var contentId in contentIds) { var content = cart.Contents.Where(c => c.ContentId == contentId).SingleOrDefault(); if (content != null) { cart.Contents.Remove(content); } } ctx.SaveChanges(); } cart = null; } }
// ---------------------------------------------------------------------------- // (Properties) // ---------------------------------------------------------------------------- // ************************************** // MyCarts // ************************************** public static IList<Cart> MyCarts() { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { ctx.ContextOptions.LazyLoadingEnabled = false; var carts = ctx.Carts .Include("Contents") .Include("Contents.ContentMedia") .Where(c => c.UserId == userId).ToList(); return AddUserDownloadableNames(carts); } }
// ************************************** // MyActiveCartContents // ************************************** public static Cart MyActiveCartContents() { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { ctx.ContextOptions.LazyLoadingEnabled = false; return ctx.Carts .Include("Contents").Include("Contents.ContentMedia") .SingleOrDefault(c => c.UserId == userId && c.CartStatus == (int)CartStatusCodes.Active); } }
// ************************************** // MyActiveCart // ************************************** public static Cart MyActiveCart() { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { return ctx.GetActiveCart(); } }
// ************************************** // DownloadPackagedCart // ************************************** public static Cart DownloadCompressedCart(int cartId) { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { var cart = ctx.Carts.SingleOrDefault(c => c.UserId == userId && c.CartId == cartId); if (cart == null) { throw new ArgumentOutOfRangeException(); } cart.MarkAsDownloaded(); ctx.SaveChanges(); return cart; } }
// ************************************** // DeleteCart // ************************************** public static void DeleteCart(int cartId) { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { var cart = ctx.Carts.SingleOrDefault(c => c.UserId == userId && c.CartId == cartId); if (cart == null) { throw new ArgumentOutOfRangeException(); } string path = cart.ArchivePath(); ctx.Carts.DeleteObject(cart); ctx.SaveChanges(); cart = null; FileSystem.SafeDelete(path, false); } }
// // ATTENTION: This seems to require the Application Pool to run as an admin or some account with elevated privileges, have to check... // public static void CompressMyActiveCartOffline(string userArchiveName = null, IList<ContentUserDownloadable> contentNames = null) { //mark as processing try { using (var ctx = new SongSearchContext()) { var userId = Account.User().UserId; var cart = ctx.Carts //.Include("Contents").Include("Contents.ContentMedia") .SingleOrDefault(c => c.UserId == userId && c.CartStatus == (int)CartStatusCodes.Active); if (cart != null && cart.Contents.Count() > 0) { cart.ArchiveName = cart.ArchiveDownloadName(userArchiveName); cart.CartStatus = (int)CartStatusCodes.Processing; ctx.SaveChanges(); //hand off compression work CompressCartDelegate compressDelegate = new CompressCartDelegate(CompressCart); // Define the AsyncCallback delegate. AsyncCallback callBack = new AsyncCallback(CompressCartCallback); compressDelegate.BeginInvoke(cart.CartId, contentNames, callBack, cart.CartId ); } cart = null; } } catch (Exception ex) { Log.Error(ex); throw ex; } }
// ************************************** // CompressMyActiveCart // ************************************** public static void CompressMyActiveCart(string userArchiveName = null, IList<ContentUserDownloadable> contentNames = null) { using (var ctx = new SongSearchContext()) { var cart = ctx.GetActiveCart(); if (cart != null && cart.Contents.Count() > 0) { string zipName = cart.ArchiveDownloadName(userArchiveName); cart.ArchiveName = zipName; CompressCart(cart.CartId, contentNames); cart.MarkAsCompressed(); ctx.SaveChanges(); SessionService.Session().SessionUpdate(cart.CartId, "ProcessingCartId"); cart = null; } } }
public static void CompressCartCallback(IAsyncResult asyncResult) { // Extract the delegate from the // System.Runtime.Remoting.Messaging.AsyncResult. using (var ctx = new SongSearchContext()) { try { CompressCartDelegate compressDelegate = (CompressCartDelegate)((AsyncResult)asyncResult).AsyncDelegate; int cartId = (int)asyncResult.AsyncState; compressDelegate.EndInvoke(asyncResult); var cart = ctx .Carts .Include("Contents")//.Include("Contents.ContentMedia") .SingleOrDefault(c => c.CartId == cartId); if (cart != null && cart.Contents.Count() > 0) { cart.MarkAsCompressed(); ctx.SaveChanges(); cart = null; } } catch (Exception ex) { Log.Error(ex); } } }
// ************************************** // ArchiveExpiredCarts // ************************************** public static void ArchiveExpiredCarts() { using (var ctx = new SongSearchContext()) { var cutOffDate = DateTime.Now.AddDays(-DAYS_TO_EXPIRE); var expiredCarts = ctx.Carts .Where(c => c.CartStatus == (int)CartStatusCodes.Compressed && c.LastUpdatedOn < cutOffDate); foreach (var cart in expiredCarts) { cart.CartStatus = (int)CartStatusCodes.Downloaded; cart.LastUpdatedOn = DateTime.Now; } ctx.SaveChanges(); expiredCarts = null; } }