public int CreateSongListFromWVR(string url, bool parseAll) { PermissionContext.VerifyPermission(PermissionToken.EditProfile); var parsed = new NNDWVRParser().GetSongs(url, parseAll); return(HandleTransaction(session => { var user = GetLoggedUser(session); var list = new SongList("Weekly Vocaloid ranking #" + parsed.WVRId, user) { Description = parsed.Name, FeaturedCategory = SongListFeaturedCategory.VocaloidRanking }; session.Save(list); foreach (var entry in parsed.Songs) { var song = session.Query <PVForSong>() .Where(p => p.Service == PVService.NicoNicoDouga && p.PVId == entry.NicoId) .First().Song; session.Save(list.AddSong(song)); } AuditLog(string.Format("created {0}", EntryLinkFactory.CreateEntryLink(list)), session, user); return list.Id; })); }
public void UpdateSongRating(int userId, int songId, SongVoteRating rating) { PermissionContext.VerifyPermission(PermissionToken.EditProfile); HandleTransaction(session => { var existing = session.Query <FavoriteSongForUser>().FirstOrDefault(f => f.User.Id == userId && f.Song.Id == songId); var user = session.Load <User>(userId); var song = session.Load <Song>(songId); var agent = new AgentLoginData(user); if (existing != null) { if (rating != SongVoteRating.Nothing) { existing.SetRating(rating); session.Update(existing); } else { existing.Delete(); session.Delete(existing); } } else if (rating != SongVoteRating.Nothing) { var link = user.AddSongToFavorites(song, rating); session.Save(link); } session.Update(song); AuditLog(string.Format("rating {0} as '{1}'.", EntryLinkFactory.CreateEntryLink(song), rating), session, agent); }, string.Format("Unable to rate song with ID '{0}'.", songId)); }
/* * [Obsolete("Integrated to saving properties")] * public PVContract CreatePV(int albumId, string pvUrl, PVType pvType) { * * ParamIs.NotNullOrEmpty(() => pvUrl); * * VerifyManageDatabase(); * * var result = VideoServiceHelper.ParseByUrl(pvUrl); * * if (!result.IsOk) * throw result.Exception; * * return HandleTransaction(session => { * * var album = session.Load<Album>(albumId); * AuditLog(string.Format("creating a PV for {0}", EntryLinkFactory.CreateEntryLink(album)), session); * * var pv = album.CreatePV(result.Service, result.Id, pvType, string.Empty); * session.Save(pv); * * return new PVContract(pv); * * }); * * }*/ public bool CreateReport(int albumId, AlbumReportType reportType, string hostname, string notes) { ParamIs.NotNull(() => hostname); ParamIs.NotNull(() => notes); return(HandleTransaction(session => { var loggedUserId = PermissionContext.LoggedUserId; var existing = session.Query <AlbumReport>() .FirstOrDefault(r => r.Album.Id == albumId && ((loggedUserId != 0 && r.User.Id == loggedUserId) || r.Hostname == hostname)); if (existing != null) { return false; } var album = session.Load <Album>(albumId); var report = new AlbumReport(album, reportType, GetLoggedUserOrDefault(session), hostname, notes.Truncate(200)); var msg = string.Format("reported {0} as {1} ({2})", EntryLinkFactory.CreateEntryLink(album), reportType, HttpUtility.HtmlEncode(notes)); AuditLog(msg.Truncate(200), session, new AgentLoginData(GetLoggedUserOrDefault(session), hostname)); session.Save(report); return true; }, IsolationLevel.ReadUncommitted)); }
public ArtistForAlbumContract AddAlbum(int artistId, int albumId) { VerifyManageDatabase(); return(HandleTransaction(session => { var artist = session.Load <Artist>(artistId); var album = session.Load <Album>(albumId); NHibernateUtil.Initialize(artist.Picture); NHibernateUtil.Initialize(album.CoverPictureData); var hasAlbum = session.Query <ArtistForAlbum>().Any(a => a.Artist.Id == artistId && a.Album.Id == albumId); if (hasAlbum) { throw new LinkAlreadyExistsException(string.Format("{0} already has {1}", artist, album)); } AuditLog(string.Format("adding {0} for {1}", EntryLinkFactory.CreateEntryLink(album), EntryLinkFactory.CreateEntryLink(artist)), session); var artistForAlbum = artist.AddAlbum(album); session.Save(artistForAlbum); album.UpdateArtistString(); session.Update(album); return new ArtistForAlbumContract(artistForAlbum, PermissionContext.LanguagePreference); })); }
public void UpdateUser(UserWithPermissionsContract contract) { ParamIs.NotNull(() => contract); UpdateEntity <User>(contract.Id, (session, user) => { if (!EntryPermissionManager.CanEditUser(PermissionContext, user.GroupId)) { var loggedUser = GetLoggedUser(session); var msg = string.Format("{0} (level {1}) not allowed to edit {2}", loggedUser, loggedUser.GroupId, user); log.Error(msg); throw new NotAllowedException(msg); } if (EntryPermissionManager.CanEditGroupTo(PermissionContext, contract.GroupId)) { user.GroupId = contract.GroupId; } if (EntryPermissionManager.CanEditAdditionalPermissions(PermissionContext)) { user.AdditionalPermissions = new PermissionCollection(contract.AdditionalPermissions.Select(p => PermissionToken.GetById(p.Id))); } var diff = OwnedArtistForUser.Sync(user.AllOwnedArtists, contract.OwnedArtistEntries, a => user.AddOwnedArtist(session.Load <Artist>(a.Artist.Id))); SessionHelper.Sync(session, diff); user.Active = contract.Active; AuditLog(string.Format("updated {0}", EntryLinkFactory.CreateEntryLink(user)), session); }, PermissionToken.ManageUserPermissions, skipLog: true); }
/*public SongContract Create(CreateSongContract contract) { * * ParamIs.NotNull(() => contract); * * if (contract.Names == null || !contract.Names.Any()) * throw new ArgumentException("Song needs at least one name", "contract"); * * VerifyManageDatabase(); * * return HandleTransaction(session => { * * var pvResult = ParsePV(session, contract.PVUrl); * var reprintPvResult = ParsePV(session, contract.ReprintPVUrl); * * SysLog(string.Format("creating a new song with name '{0}'", contract.Names.First().Value)); * * var song = new Song { * SongType = contract.SongType, * Status = contract.Draft ? EntryStatus.Draft : EntryStatus.Finished * }; * * song.Names.Init(contract.Names, song); * * session.Save(song); * * foreach (var artistContract in contract.Artists) { * var artist = session.Load<Artist>(artistContract.Id); * if (!song.HasArtist(artist)) * session.Save(song.AddArtist(artist)); * } * * if (pvResult != null) { * session.Save(song.CreatePV(new PVContract(pvResult, PVType.Original))); * } * * if (reprintPvResult != null) { * session.Save(song.CreatePV(new PVContract(reprintPvResult, PVType.Reprint))); * } * * song.UpdateArtistString(); * Archive(session, song, SongArchiveReason.Created); * session.Update(song); * * AuditLog(string.Format("created song {0} ({1})", EntryLinkFactory.CreateEntryLink(song), song.SongType), session); * AddEntryEditedEntry(session, song, EntryEditEvent.Created); * * return new SongContract(song, PermissionContext.LanguagePreference); * * }); * * }*/ public void Delete(int id) { UpdateEntity <Song>(id, (session, a) => { AuditLog(string.Format("deleting song {0}", EntryLinkFactory.CreateEntryLink(a)), session); a.Delete(); }, PermissionToken.DeleteEntries, skipLog: true); }
public void Delete(int id) { UpdateEntity <Album>(id, (session, a) => { AuditLog(string.Format("deleting album {0}", EntryLinkFactory.CreateEntryLink(a)), session); NHibernateUtil.Initialize(a.CoverPictureData); a.Delete(); }, PermissionToken.DeleteEntries, skipLog: true); }
public void Delete(int id) { UpdateEntity <Album>(id, (session, a) => { AuditLog(string.Format("deleting {0}", EntryLinkFactory.CreateEntryLink(a)), session); //ArchiveArtist(session, permissionContext, a); a.Delete(); }, PermissionToken.DeleteEntries, skipLog: true); }
public void Restore(int songId) { PermissionContext.VerifyPermission(PermissionToken.DeleteEntries); HandleTransaction(session => { var song = session.Load <Song>(songId); song.Deleted = false; AuditLog("restored " + EntryLinkFactory.CreateEntryLink(song), session); }); }
public void Restore(int albumId) { PermissionContext.VerifyPermission(PermissionToken.DeleteEntries); HandleTransaction(session => { var album = session.Load <Album>(albumId); album.Deleted = false; AuditLog("restored " + EntryLinkFactory.CreateEntryLink(album), session); }); }
public void Delete(int id, string notes) { UpdateEntity <Song>(id, (session, song) => { EntryPermissionManager.VerifyDelete(PermissionContext, song); AuditLog(string.Format("deleting song {0}", EntryLinkFactory.CreateEntryLink(song)), session); song.Delete(); Archive(session, song, new SongDiff(false), SongArchiveReason.Deleted, notes); }, PermissionToken.Nothing, skipLog: true); }
public void Delete(int id, string notes) { UpdateEntity <Album>(id, (session, a) => { EntryPermissionManager.VerifyDelete(PermissionContext, a); AuditLog(string.Format("deleting album {0}", EntryLinkFactory.CreateEntryLink(a)), session); NHibernateUtil.Initialize(a.CoverPictureData); a.Delete(); Archive(session, a, new AlbumDiff(false), AlbumArchiveReason.Deleted, notes); }, PermissionToken.Nothing, skipLog: true); }
public void Delete(int id, string notes) { UpdateEntity <Artist>(id, (session, a) => { EntryPermissionManager.VerifyDelete(PermissionContext, a); AuditLog(string.Format("deleting artist {0}{1}", EntryLinkFactory.CreateEntryLink(a), !string.IsNullOrEmpty(notes) ? " " + notes : string.Empty), session); NHibernateUtil.Initialize(a.Picture); a.Delete(); Archive(session, a, new ArtistDiff(false), ArtistArchiveReason.Deleted, notes); }, PermissionToken.Nothing, skipLog: true); }
public void Restore(int artistId) { PermissionContext.VerifyPermission(PermissionToken.DeleteEntries); HandleTransaction(session => { var artist = session.Load <Artist>(artistId); NHibernateUtil.Initialize(artist.Picture); artist.Deleted = false; session.Update(artist); AuditLog("restored " + EntryLinkFactory.CreateEntryLink(artist), session); }); }
public UserContract UpdateUserSettings(UpdateUserSettingsContract contract) { ParamIs.NotNull(() => contract); PermissionContext.VerifyPermission(PermissionToken.EditProfile); return(HandleTransaction(session => { var user = session.Load <User>(contract.Id); SysLog(string.Format("Updating settings for {0}", user)); VerifyResourceAccess(user); if (!string.IsNullOrEmpty(contract.NewPass)) { var oldHashed = (!string.IsNullOrEmpty(user.Password) ? LoginManager.GetHashedPass(user.NameLC, contract.OldPass, user.Salt) : string.Empty); if (user.Password != oldHashed) { throw new InvalidPasswordException(); } var newHashed = LoginManager.GetHashedPass(user.NameLC, contract.NewPass, user.Salt); user.Password = newHashed; } user.Options.AboutMe = contract.AboutMe; user.AnonymousActivity = contract.AnonymousActivity; user.Culture = contract.Culture; user.DefaultLanguageSelection = contract.DefaultLanguageSelection; user.EmailOptions = contract.EmailOptions; user.Language = contract.Language; user.Options.Location = contract.Location; user.PreferredVideoService = contract.PreferredVideoService; user.Options.PublicRatings = contract.PublicRatings; user.SetEmail(contract.Email); var webLinkDiff = WebLink.Sync(user.WebLinks, contract.WebLinks, user); SessionHelper.Sync(session, webLinkDiff); session.Update(user); AuditLog(string.Format("updated settings for {0}", EntryLinkFactory.CreateEntryLink(user)), session); return new UserContract(user); })); }
public ArtistContract Create(CreateArtistContract contract) { ParamIs.NotNull(() => contract); if (contract.Names == null || !contract.Names.Any()) { throw new ArgumentException("Artist needs at least one name", "contract"); } VerifyManageDatabase(); return(HandleTransaction(session => { SysLog(string.Format("creating a new artist with name '{0}'", contract.Names.First().Value)); var artist = new Artist { ArtistType = contract.ArtistType, Description = contract.Description.Trim(), Status = contract.Draft ? EntryStatus.Draft : EntryStatus.Finished }; artist.Names.Init(contract.Names, artist); if (contract.PictureData != null) { artist.Picture = new PictureData(contract.PictureData); } if (contract.WebLink != null) { artist.CreateWebLink(contract.WebLink.Description, contract.WebLink.Url, contract.WebLink.Category); } session.Save(artist); Archive(session, artist, ArtistArchiveReason.Created); session.Update(artist); AuditLog(string.Format("created {0}", EntryLinkFactory.CreateEntryLink(artist)), session); AddEntryEditedEntry(session, artist, EntryEditEvent.Created); return new ArtistContract(artist, PermissionContext.LanguagePreference); })); }
public void DeleteEntryReports(int[] reportIds) { ParamIs.NotNull(() => reportIds); PermissionContext.VerifyPermission(PermissionToken.ManageEntryReports); HandleTransaction(session => { var reports = session.Query <EntryReport>().Where(r => reportIds.Contains(r.Id)).ToArray(); foreach (var report in reports) { AuditLog(string.Format("deleted entry report {0}{1} for {2}", report.TranslatedReportTypeName(enumTranslations, CultureInfo.DefaultThreadCurrentCulture), !string.IsNullOrEmpty(report.Notes) ? " (" + report.Notes + ")" : string.Empty, EntryLinkFactory.CreateEntryLink(report.EntryBase)), session); session.Delete(report); } }); }
public TagUsageContract[] SaveTags(int albumId, string[] tags) { ParamIs.NotNull(() => tags); VerifyManageDatabase(); return(HandleTransaction(session => { tags = tags.Distinct(new CaseInsensitiveStringComparer()).ToArray(); var user = session.Load <User>(PermissionContext.LoggedUser.Id); var album = session.Load <Album>(albumId); AuditLog(string.Format("tagging {0} with {1}", EntryLinkFactory.CreateEntryLink(album), string.Join(", ", tags)), session, user); var existingTags = TagHelpers.GetTags(session, tags); album.Tags.SyncVotes(user, tags, existingTags, new TagFactory(session, new AgentLoginData(user)), new AlbumTagUsageFactory(session, album)); return album.Tags.Usages.OrderByDescending(u => u.Count).Select(t => new TagUsageContract(t)).ToArray(); })); }
public CommentContract CreateComment(int albumId, string message) { ParamIs.NotNullOrEmpty(() => message); PermissionContext.VerifyPermission(PermissionToken.CreateComments); message = message.Trim(); return(HandleTransaction(session => { var album = session.Load <Album>(albumId); var agent = SessionHelper.CreateAgentLoginData(session, PermissionContext); AuditLog(string.Format("creating comment for {0}: '{1}'", EntryLinkFactory.CreateEntryLink(album), HttpUtility.HtmlEncode(message)), session, agent.User); var comment = album.CreateComment(message, agent); session.Save(comment); return new CommentContract(comment); })); }
public TagUsageContract[] SaveTags(int songId, string[] tags) { ParamIs.NotNull(() => tags); VerifyManageDatabase(); return(HandleTransaction(session => { tags = tags.Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray(); var user = session.Load <User>(PermissionContext.LoggedUser.Id); var song = session.Load <Song>(songId); AuditLog(string.Format("tagging {0} with {1}", EntryLinkFactory.CreateEntryLink(song), string.Join(", ", tags)), session, user); var existingTags = TagHelpers.GetTags(session, tags); song.Tags.SyncVotes(user, tags, existingTags, new TagFactory(session, new AgentLoginData(user)), new SongTagUsageFactory(session, song)); return song.Tags.Usages.OrderByDescending(u => u.Count).Select(t => new TagUsageContract(t)).ToArray(); })); }
public CommentContract CreateComment(int artistId, string message) { ParamIs.NotNullOrEmpty(() => message); PermissionContext.VerifyPermission(PermissionToken.CreateComments); message = message.Trim(); return(HandleTransaction(session => { var artist = session.Load <Artist>(artistId); var author = GetLoggedUser(session); AuditLog(string.Format("creating comment for {0}: '{1}'", EntryLinkFactory.CreateEntryLink(artist), HttpUtility.HtmlEncode(message.Truncate(60))), session, author); var comment = artist.CreateComment(message, author); session.Save(comment); return new CommentContract(comment); })); }
public AlbumContract Create(CreateAlbumContract contract) { ParamIs.NotNull(() => contract); if (contract.Names == null || !contract.Names.Any()) { throw new ArgumentException("Album needs at least one name", "contract"); } VerifyManageDatabase(); return(HandleTransaction(session => { SysLog(string.Format("creating a new album with name '{0}'", contract.Names.First().Value)); var album = new Album { DiscType = contract.DiscType }; album.Names.Init(contract.Names, album); session.Save(album); foreach (var artist in contract.Artists) { session.Save(session.Load <Artist>(artist.Id).AddAlbum(album)); } album.UpdateArtistString(); Archive(session, album, AlbumArchiveReason.Created); session.Update(album); AuditLog(string.Format("created {0}", EntryLinkFactory.CreateEntryLink(album)), session); AddEntryEditedEntry(session, album, EntryEditEvent.Created); return new AlbumContract(album, PermissionContext.LanguagePreference); })); }
public AlbumForEditContract UpdateBasicProperties(AlbumForEditContract properties, PictureDataContract pictureData) { ParamIs.NotNull(() => properties); return(HandleQuery(session => { using (var tx = session.BeginTransaction()) { var album = session.Load <Album>(properties.Id); VerifyEntryEdit(album); var diff = new AlbumDiff(DoSnapshot(album.ArchivedVersionsManager.GetLatestVersion(), GetLoggedUser(session))); SysLog(string.Format("updating properties for {0}", album)); if (album.DiscType != properties.DiscType) { album.DiscType = properties.DiscType; album.UpdateArtistString(); diff.DiscType = true; } if (album.Description != properties.Description) { album.Description = properties.Description; diff.Description = true; } if (album.TranslatedName.DefaultLanguage != properties.TranslatedName.DefaultLanguage) { album.TranslatedName.DefaultLanguage = properties.TranslatedName.DefaultLanguage; diff.OriginalName = true; } var validNames = properties.Names.AllNames; var nameDiff = album.Names.Sync(validNames, album); SessionHelper.Sync(session, nameDiff); album.Names.UpdateSortNames(); if (nameDiff.Changed) { diff.Names = true; } var validWebLinks = properties.WebLinks.Where(w => !string.IsNullOrEmpty(w.Url)); var webLinkDiff = WebLink.Sync(album.WebLinks, validWebLinks, album); SessionHelper.Sync(session, webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks = true; } var newOriginalRelease = (properties.OriginalRelease != null ? new AlbumRelease(properties.OriginalRelease) : new AlbumRelease()); if (album.OriginalRelease == null) { album.OriginalRelease = new AlbumRelease(); } if (!album.OriginalRelease.Equals(newOriginalRelease)) { album.OriginalRelease = newOriginalRelease; diff.OriginalRelease = true; } NHibernateUtil.Initialize(album.CoverPictureData); if (pictureData != null) { album.CoverPictureData = new PictureData(pictureData); diff.Cover = true; } if (album.Status != properties.Status) { album.Status = properties.Status; diff.Status = true; } var songGetter = new Func <SongInAlbumEditContract, Song>(contract => { if (contract.SongId != 0) { return session.Load <Song>(contract.SongId); } else { SysLog(string.Format("creating a new song '{0}' to {1}", contract.SongName, album)); var song = new Song(new LocalizedString(contract.SongName, ContentLanguageSelection.Unspecified)); session.Save(song); Services.Songs.Archive(session, song, SongArchiveReason.Created, string.Format("Created for album '{0}'", album.DefaultName)); AuditLog(string.Format("created {0} for {1}", EntryLinkFactory.CreateEntryLink(song), EntryLinkFactory.CreateEntryLink(album)), session); AddEntryEditedEntry(session, song, EntryEditEvent.Created); return song; } }); var tracksDiff = album.SyncSongs(properties.Songs, songGetter); SessionHelper.Sync(session, tracksDiff); if (tracksDiff.Changed) { var add = string.Join(", ", tracksDiff.Added.Select(i => i.Song.ToString())); var rem = string.Join(", ", tracksDiff.Removed.Select(i => i.Song.ToString())); var edit = string.Join(", ", tracksDiff.Edited.Select(i => i.Song.ToString())); var str = string.Format("edited tracks (added: {0}, removed: {1}, reordered: {2})", add, rem, edit) .Truncate(300); AuditLog(str, session); diff.Tracks = true; } var picsDiff = album.Pictures.SyncPictures(properties.Pictures, GetLoggedUser(session), album.CreatePicture); SessionHelper.Sync(session, picsDiff); ImageHelper.GenerateThumbsAndMoveImages(picsDiff.Added); if (picsDiff.Changed) { diff.Pictures = true; } var pvDiff = album.SyncPVs(properties.PVs); SessionHelper.Sync(session, pvDiff); if (pvDiff.Changed) { diff.PVs = true; } var logStr = string.Format("updated properties for {0} ({1})", EntryLinkFactory.CreateEntryLink(album), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); AuditLog(logStr, session); AddEntryEditedEntry(session, album, EntryEditEvent.Updated); Archive(session, album, diff, AlbumArchiveReason.PropertiesUpdated, properties.UpdateNotes); session.Update(album); tx.Commit(); return new AlbumForEditContract(album, PermissionContext.LanguagePreference); } })); }
public EntryRevertedContract RevertToVersion(int archivedAlbumVersionId) { PermissionContext.VerifyPermission(PermissionToken.RestoreRevisions); return(HandleTransaction(session => { var archivedVersion = session.Load <ArchivedAlbumVersion>(archivedAlbumVersionId); var album = archivedVersion.Album; SysLog("reverting " + album + " to version " + archivedVersion.Version); var fullProperties = ArchivedAlbumContract.GetAllProperties(archivedVersion); var warnings = new List <string>(); album.Description = fullProperties.Description; album.DiscType = fullProperties.DiscType; album.TranslatedName.DefaultLanguage = fullProperties.TranslatedName.DefaultLanguage; // Picture var versionWithPic = archivedVersion.GetLatestVersionWithField(AlbumEditableFields.Cover); if (versionWithPic != null) { album.CoverPictureData = versionWithPic.CoverPicture; } // Original release album.OriginalRelease = (fullProperties.OriginalRelease != null ? new AlbumRelease(fullProperties.OriginalRelease) : null); // Artists SessionHelper.RestoreObjectRefs <ArtistForAlbum, Artist, ArchivedArtistForAlbumContract>( session, warnings, album.AllArtists, fullProperties.Artists, (a1, a2) => (a1.Artist != null && a1.Artist.Id == a2.Id) || (a1.Artist == null && a2.Id == 0 && a1.Name == a2.NameHint), (artist, albumRef) => RestoreArtistRef(album, artist, albumRef), albumForArtist => albumForArtist.Delete()); // Songs SessionHelper.RestoreObjectRefs <SongInAlbum, Song, SongInAlbumRefContract>( session, warnings, album.AllSongs, fullProperties.Songs, (a1, a2) => (a1.Song.Id == a2.Id), (song, songRef) => (!album.HasSong(song) ? album.AddSong(song, songRef.TrackNumber, Math.Min(songRef.DiscNumber, 1)) : null), songInAlbum => songInAlbum.Delete()); // Names if (fullProperties.Names != null) { var nameDiff = album.Names.SyncByContent(fullProperties.Names, album); SessionHelper.Sync(session, nameDiff); } // Weblinks if (fullProperties.WebLinks != null) { var webLinkDiff = WebLink.SyncByValue(album.WebLinks, fullProperties.WebLinks, album); SessionHelper.Sync(session, webLinkDiff); } // PVs if (fullProperties.PVs != null) { var pvDiff = CollectionHelper.Diff(album.PVs, fullProperties.PVs, (p1, p2) => (p1.PVId == p2.PVId && p1.Service == p2.Service)); foreach (var pv in pvDiff.Added) { session.Save(album.CreatePV(new PVContract(pv))); } foreach (var pv in pvDiff.Removed) { pv.OnDelete(); session.Delete(pv); } } album.UpdateArtistString(); album.UpdateRatingTotals(); Archive(session, album, AlbumArchiveReason.Reverted); AuditLog("reverted " + EntryLinkFactory.CreateEntryLink(album) + " to revision " + archivedVersion.Version, session); return new EntryRevertedContract(album, warnings); })); }
public void UpdateBasicProperties(ArtistForEditContract properties, PictureDataContract pictureData, IUserPermissionContext permissionContext) { ParamIs.NotNull(() => properties); ParamIs.NotNull(() => permissionContext); HandleTransaction(session => { var artist = session.Load <Artist>(properties.Id); VerifyEntryEdit(artist); var diff = new ArtistDiff(DoSnapshot(artist.GetLatestVersion(), GetLoggedUser(session))); SysLog(string.Format("updating properties for {0}", artist)); if (artist.ArtistType != properties.ArtistType) { artist.ArtistType = properties.ArtistType; diff.ArtistType = true; } if (artist.Description != properties.Description) { artist.Description = properties.Description; diff.Description = true; } if (artist.TranslatedName.DefaultLanguage != properties.TranslatedName.DefaultLanguage) { artist.TranslatedName.DefaultLanguage = properties.TranslatedName.DefaultLanguage; diff.OriginalName = true; } NHibernateUtil.Initialize(artist.Picture); if (pictureData != null) { artist.Picture = new PictureData(pictureData); diff.Picture = true; } if (artist.Status != properties.Status) { artist.Status = properties.Status; diff.Status = true; } var nameDiff = artist.Names.Sync(properties.Names.AllNames, artist); SessionHelper.Sync(session, nameDiff); if (nameDiff.Changed) { diff.Names = true; } var validWebLinks = properties.WebLinks.Where(w => !string.IsNullOrEmpty(w.Url)); var webLinkDiff = WebLink.Sync(artist.WebLinks, validWebLinks, artist); SessionHelper.Sync(session, webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks = true; } if (diff.ArtistType || diff.Names) { foreach (var song in artist.Songs) { song.Song.UpdateArtistString(); session.Update(song); } } var groupsDiff = CollectionHelper.Diff(artist.Groups, properties.Groups, (i, i2) => (i.Id == i2.Id)); foreach (var grp in groupsDiff.Removed) { grp.Delete(); session.Delete(grp); } foreach (var grp in groupsDiff.Added) { var link = artist.AddGroup(session.Load <Artist>(grp.Group.Id)); session.Save(link); } if (groupsDiff.Changed) { diff.Groups = true; } var picsDiff = artist.Pictures.SyncPictures(properties.Pictures, GetLoggedUser(session), artist.CreatePicture); SessionHelper.Sync(session, picsDiff); ImageHelper.GenerateThumbsAndMoveImages(picsDiff.Added); if (picsDiff.Changed) { diff.Pictures = true; } /* * var albumGetter = new Func<AlbumForArtistEditContract, Album>(contract => { * * Album album; * * if (contract.AlbumId != 0) { * * album = session.Load<Album>(contract.AlbumId); * * } else { * * AuditLog(string.Format("creating a new album '{0}' to {1}", contract.AlbumName, artist)); * * album = new Album(contract.AlbumName); * session.Save(album); * * Services.Albums.Archive(session, album, AlbumArchiveReason.Created, * string.Format("Created for artist '{0}'", artist.DefaultName)); * * AuditLog(string.Format("created {0} for {1}", * EntryLinkFactory.CreateEntryLink(album), EntryLinkFactory.CreateEntryLink(artist)), session); * AddEntryEditedEntry(session, album, EntryEditEvent.Created); * * } * * return album; * * }); * * if (properties.AlbumLinks != null * && !properties.TooManyAlbums * && (properties.AlbumLinks.Any() || artist.Albums.Count() < ArtistForEditContract.MaxAlbums / 2) * && artist.Albums.Count() <= ArtistForEditContract.MaxAlbums) { * * var albumDiff = artist.SyncAlbums(properties.AlbumLinks, albumGetter); * * SessionHelper.Sync(session, albumDiff); * * if (albumDiff.Changed) { * * diff.Albums = true; * * var add = string.Join(", ", albumDiff.Added.Select(i => i.Album.ToString())); * var rem = string.Join(", ", albumDiff.Removed.Select(i => i.Album.ToString())); * * var str = string.Format("edited albums (added: {0}, removed: {1})", add, rem) * .Truncate(300); * * AuditLog(str, session); * * } * * }*/ var logStr = string.Format("updated properties for {0} ({1})", EntryLinkFactory.CreateEntryLink(artist), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); AuditLog(logStr, session); AddEntryEditedEntry(session, artist, EntryEditEvent.Updated); Archive(session, artist, diff, ArtistArchiveReason.PropertiesUpdated, properties.UpdateNotes); session.Update(artist); return(true); }); }
public void Merge(int sourceId, int targetId) { PermissionContext.VerifyPermission(PermissionToken.MergeEntries); if (sourceId == targetId) { throw new ArgumentException("Source and target albums can't be the same", "targetId"); } HandleTransaction(session => { var source = session.Load <Album>(sourceId); var target = session.Load <Album>(targetId); AuditLog(string.Format("Merging {0} to {1}", EntryLinkFactory.CreateEntryLink(source), EntryLinkFactory.CreateEntryLink(target)), session); foreach (var n in source.Names.Names.Where(n => !target.HasName(n))) { var name = target.CreateName(n.Value, n.Language); session.Save(name); } foreach (var w in source.WebLinks.Where(w => !target.HasWebLink(w.Url))) { var link = target.CreateWebLink(w.Description, w.Url, w.Category); session.Save(link); } var artists = source.Artists.Where(a => !target.HasArtistForAlbum(a)).ToArray(); foreach (var a in artists) { a.Move(target); session.Update(a); } var songs = source.Songs.Where(s => !target.HasSong(s.Song)).ToArray(); foreach (var s in songs) { s.Move(target); session.Update(s); } var pictures = source.Pictures.ToArray(); foreach (var p in pictures) { p.Move(target); session.Update(p); } var userCollections = source.UserCollections.Where(a => !target.IsInUserCollection(a.User)).ToArray(); foreach (var u in userCollections) { u.Move(target); session.Update(u); } if (target.Description == string.Empty) { target.Description = source.Description; } if (target.OriginalRelease == null) { target.OriginalRelease = new AlbumRelease(); } if (string.IsNullOrEmpty(target.OriginalRelease.CatNum) && source.OriginalRelease != null) { target.OriginalRelease.CatNum = source.OriginalRelease.CatNum; } if (string.IsNullOrEmpty(target.OriginalRelease.EventName) && source.OriginalRelease != null) { target.OriginalRelease.EventName = source.OriginalRelease.EventName; } if (target.OriginalRelease.ReleaseDate == null) { target.OriginalRelease.ReleaseDate = new OptionalDateTime(); } if (target.OriginalReleaseDate.Year == null && source.OriginalRelease != null) { target.OriginalReleaseDate.Year = source.OriginalReleaseDate.Year; } if (target.OriginalReleaseDate.Month == null && source.OriginalRelease != null) { target.OriginalReleaseDate.Month = source.OriginalReleaseDate.Month; } if (target.OriginalReleaseDate.Day == null && source.OriginalRelease != null) { target.OriginalReleaseDate.Day = source.OriginalReleaseDate.Day; } source.Deleted = true; target.UpdateArtistString(); target.Names.UpdateSortNames(); Archive(session, target, AlbumArchiveReason.Merged, string.Format("Merged from {0}", source)); session.Update(source); session.Update(target); }); }
protected string CreateEntryLink(IEntryBase entry) { return(EntryLinkFactory.CreateEntryLink(entry)); }
public void Merge(int sourceId, int targetId) { PermissionContext.VerifyPermission(PermissionToken.MergeEntries); if (sourceId == targetId) { throw new ArgumentException("Source and target artists can't be the same", "targetId"); } HandleTransaction(session => { var source = session.Load <Artist>(sourceId); var target = session.Load <Artist>(targetId); AuditLog(string.Format("Merging {0} to {1}", EntryLinkFactory.CreateEntryLink(source), EntryLinkFactory.CreateEntryLink(target)), session); NHibernateUtil.Initialize(source.Picture); NHibernateUtil.Initialize(target.Picture); foreach (var n in source.Names.Names.Where(n => !target.HasName(n))) { var name = target.CreateName(n.Value, n.Language); session.Save(name); } foreach (var w in source.WebLinks.Where(w => !target.HasWebLink(w.Url))) { var link = target.CreateWebLink(w.Description, w.Url, w.Category); session.Save(link); } var groups = source.Groups.Where(g => !target.HasGroup(g.Parent)).ToArray(); foreach (var g in groups) { g.MoveToMember(target); session.Update(g); } var members = source.Members.Where(m => !m.Member.HasGroup(target)).ToArray(); foreach (var m in members) { m.MoveToGroup(target); session.Update(m); } var albums = source.Albums.Where(a => !target.HasAlbum(a.Album)).ToArray(); foreach (var a in albums) { a.Move(target); session.Update(a); } var songs = source.Songs.Where(s => !target.HasSong(s.Song)).ToArray(); foreach (var s in songs) { s.Move(target); session.Update(s); } var ownerUsers = source.OwnerUsers.Where(s => !target.HasOwnerUser(s.User)).ToArray(); foreach (var u in ownerUsers) { u.Move(target); session.Update(u); } var pictures = source.Pictures.ToArray(); foreach (var p in pictures) { p.Move(target); session.Update(p); } var users = source.Users.ToArray(); foreach (var u in users) { u.Move(target); session.Update(u); } target.Description.CopyIfEmpty(source.Description); // Create merge record var mergeEntry = new ArtistMergeRecord(source, target); session.Save(mergeEntry); source.Deleted = true; Archive(session, source, ArtistArchiveReason.Deleted, string.Format("Merged to {0}", target)); Archive(session, target, ArtistArchiveReason.Merged, string.Format("Merged from '{0}'", source)); NHibernateUtil.Initialize(source.Picture); NHibernateUtil.Initialize(target.Picture); session.Update(source); session.Update(target); }); }
public EntryRevertedContract RevertToVersion(int archivedSongVersionId) { PermissionContext.VerifyPermission(PermissionToken.RestoreRevisions); return(HandleTransaction(session => { var archivedVersion = session.Load <ArchivedSongVersion>(archivedSongVersionId); var song = archivedVersion.Song; SysLog("reverting " + song + " to version " + archivedVersion.Version); var fullProperties = ArchivedSongContract.GetAllProperties(archivedVersion); var warnings = new List <string>(); song.LengthSeconds = fullProperties.LengthSeconds; song.NicoId = fullProperties.NicoId; song.Notes.Original = fullProperties.Notes; song.Notes.English = fullProperties.NotesEng; song.SongType = fullProperties.SongType; song.TranslatedName.DefaultLanguage = fullProperties.TranslatedName.DefaultLanguage; // Artists SessionHelper.RestoreObjectRefs <ArtistForSong, Artist, ArchivedArtistForSongContract>( session, warnings, song.AllArtists, fullProperties.Artists, (a1, a2) => (a1.Artist != null && a1.Artist.Id == a2.Id) || (a1.Artist == null && a2.Id == 0 && a1.Name == a2.NameHint), (artist, artistRef) => RestoreArtistRef(song, artist, artistRef), artistForSong => artistForSong.Delete()); // Names if (fullProperties.Names != null) { var nameDiff = song.Names.SyncByContent(fullProperties.Names, song); SessionHelper.Sync(session, nameDiff); } // Weblinks if (fullProperties.WebLinks != null) { var webLinkDiff = WebLink.SyncByValue(song.WebLinks, fullProperties.WebLinks, song); SessionHelper.Sync(session, webLinkDiff); } // Lyrics if (fullProperties.Lyrics != null) { var lyricsDiff = CollectionHelper.Diff(song.Lyrics, fullProperties.Lyrics, (p1, p2) => (p1.Id == p2.Id)); foreach (var lyrics in lyricsDiff.Added) { session.Save(song.CreateLyrics(lyrics.Language, lyrics.Value, lyrics.Source)); } foreach (var lyrics in lyricsDiff.Removed) { song.Lyrics.Remove(lyrics); session.Delete(lyrics); } foreach (var lyrics in lyricsDiff.Unchanged) { var newLyrics = fullProperties.Lyrics.First(l => l.Id == lyrics.Id); lyrics.Language = newLyrics.Language; lyrics.Source = newLyrics.Source; lyrics.Value = newLyrics.Value; session.Update(lyrics); } } // PVs if (fullProperties.PVs != null) { var pvDiff = CollectionHelper.Diff(song.PVs, fullProperties.PVs, (p1, p2) => (p1.PVId == p2.PVId && p1.Service == p2.Service)); foreach (var pv in pvDiff.Added) { session.Save(song.CreatePV(new PVContract(pv))); } foreach (var pv in pvDiff.Removed) { pv.OnDelete(); session.Delete(pv); } } song.UpdateFavoritedTimes(); Archive(session, song, SongArchiveReason.Reverted, string.Format("Reverted to version {0}", archivedVersion.Version)); AuditLog(string.Format("reverted {0} to revision {1}", EntryLinkFactory.CreateEntryLink(song), archivedVersion.Version), session); return new EntryRevertedContract(song, warnings); })); }
public void DeleteEntryReports(int[] reportIds) { ParamIs.NotNull(() => reportIds); PermissionContext.VerifyPermission(PermissionToken.ManageEntryReports); HandleTransaction(session => { var reports = session.Query <EntryReport>().Where(r => reportIds.Contains(r.Id)).ToArray(); foreach (var report in reports) { AuditLog($"closed entry report {report.TranslatedReportTypeName(_enumTranslations, CultureInfo.DefaultThreadCurrentCulture)}{(!string.IsNullOrEmpty(report.Notes) ? " (" + report.Notes + ")" : string.Empty)} for {EntryLinkFactory.CreateEntryLink(report.EntryBase)}", session); report.Status = ReportStatus.Closed; report.ClosedBy = GetLoggedUser(session); report.ClosedAt = DateTime.UtcNow; session.Update(report); } }); }