internal void ParsePlayListSong(SongModel song, HtmlNode tr) { var name = tr.SelectSingleNode("./td[@class='song_name']"); foreach (var item in name.ChildNodes) { if(item.Name == "a") { if (item.Element("b") != null) { var mvlink = item.GetAttributeValue("href", "/0"); song.MV = MVModel.GetNew(mvlink.Substring(mvlink.LastIndexOf('/') + 1)); } else if (item.GetAttributeValue("class", "") == "show_zhcn") song.Description = item.InnerText; else song.Name = item.InnerText; } else { string t = item.InnerText.Trim(); if (t.Length > 0) song.TrackArtist = t; } } }
public IHttpActionResult Create(SongModel song) { if (!this.ModelState.IsValid) { return BadRequest(this.ModelState); } if (this.data.Artists.All().FirstOrDefault(a => a.ArtistId == song.ArtistId) == null) { return BadRequest("The song can not be added to this artist, because the artist with id: " + song.SongId + " does not exists."); } var newSong = new Song() { Title = song.Title, Year = song.Year, Producer = song.Producer, ArtistId = song.ArtistId }; this.data.Songs.Add(newSong); this.data.SaveChanges(); song.SongId = newSong.SongId; return Ok(song); }
public IHttpActionResult Update(int id, SongModel song) { if (!this.ModelState.IsValid) { return BadRequest(this.ModelState); } var songToUpdate = this.data.Songs .All() .FirstOrDefault(s => s.SongId == id); if (songToUpdate == null) { return BadRequest("The song with id: " + id + " does not exists."); } songToUpdate.Title = song.Title; songToUpdate.Year = song.Year; songToUpdate.Producer = song.Producer; songToUpdate.ArtistId = song.ArtistId; this.data.SaveChanges(); song.SongId = songToUpdate.SongId; return Ok(song); }
public ActionResult Create(SongModel song, int savedCdId) { try { song.CdId = savedCdId; SongData.SaveSong(song); return(RedirectToAction("Create", new { savedCdId })); } catch { return(View()); } }
void AddNewMessage(JObject message) { try { if (Variables.NowPlaying != null) { previousSong = Variables.NowPlaying; } string id = message.GetValue("SongId").ToString(); string title = message.GetValue("SongTitle").ToString(); string artist = message.GetValue("ArtistName").ToString(); string album = message.GetValue("AlbumTitle").ToString(); string length = message.GetValue("SongLength").ToString(); string songUrl = message.GetValue("SongUrl").ToString(); string artistId = message.GetValue("ArtistId").ToString(); string twitter = message.GetValue("ArtistTwitterUrl").ToString(); string facebook = message.GetValue("ArtistFacebookUrl").ToString(); string albumImage = message.GetValue("AlbumImage").ToString(); Variables.NowPlaying = new SongModel { Id = id, SongTitle = title, ArtistName = artist, AlbumTitle = album, SongLength = length, SongUrl = songUrl, ArtistId = artistId, ArtistTwitterUrl = twitter, ArtistFacebookUrl = facebook, AlbumImage = albumImage, }; if (previousSong != null) { if (previousSong != Variables.NowPlaying) { Variables.PreviouslyPlayed.Insert(0, Variables.NowPlaying); Variables.PreviouslyPlayed.RemoveAt(Variables.PreviouslyPlayed.Count - 1); } } //App.STVM.CurrentSong = Variables.CurrentSong; SongChanged?.Invoke(this, Variables.NowPlaying); } catch (Exception e) { Console.WriteLine("Sig R Obj Creation error" + e.Message); } Console.WriteLine(Variables.NowPlaying.SongTitle); }
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) { SongModel article = (SongModel)e.Item.DataItem; string url = bll_article.GetUrl(article); ((HtmlTableCell)e.Item.FindControl("Eval_Title")).InnerHtml = article.Title; string sex = "女"; if (article.Sex == 1) { sex = "男"; } ((HtmlTableCell)e.Item.FindControl("Eval_Sex")).InnerHtml = sex; ((HtmlTableCell)e.Item.FindControl("Eval_CreateTime")).InnerText = DateHelper.ToShortDate(article.CreateTime); }
public AddPlayListForm(SongModel song) { InitializeComponent(); ToggleForm(); AddPLFormVM = new AddPlaylistFormViewModel(song); AddPLFormVM.ListPlaylistChange += AddPLFormVM_ListPlaylistChange; AddPLFormVM.ButtonStatusChange += AddPLFormVM_ButtonStatusChange; this.DataContext = AddPLFormVM; this.Closing += AddPlayListForm_Closing; timer.Tick += Timer_Tick; timerUpdateButtonAddToPL.Tick += TimerUpdateButtonAddToPL_Tick; timer.Start(); }
public IHttpActionResult Add(SongModel songModel) { if (!this.ModelState.IsValid) { return(BadRequest(ModelState)); } var newAtist = SongModel.ToSong(songModel); this.data.Songs.Add(newAtist); this.data.SaveChanges(); songModel.ID = newAtist.ID; return(Ok(songModel)); }
public ActionResult Delete(int id) { SongModel model = context.Songs.Where(some => some.Id == id).Select(some => new SongModel() { Id = some.Id, Title = some.Title, Singer = some.Singer, Year = some.Year, Writer = some.Writer, GenreName = some.Genre.Name }).SingleOrDefault(); return(View(model)); }
public async Task LoadSongsAsync() { var getSongsResponse = await _songService.GetSongsAsync(); if (getSongsResponse.HasError) { await _modalService.ShowAsync("Erreur lors du chargement des musiques", getSongsResponse.ErrorMessage); } else { Songs = getSongsResponse.Content; FilteredSongs = Songs; CurrentSong = getSongsResponse.Content.FirstOrDefault(); } }
public SongModel[] FindSongsLongerThan(SongModel[] songs, int seconds) { SongModel[] resultSongs = new SongModel[0]; foreach (SongModel song in songs) { if (song.Length > seconds) { Array.Resize(ref resultSongs, resultSongs.Length + 1); resultSongs[resultSongs.Length - 1] = song; } } return(resultSongs); }
public void Update(int id, SongModel song) { var result = _context.Songs.SingleOrDefault(x => x.Id == id); if (result != null) { result.Title = song.Title; result.Album = song.Album; result.Artist = song.Artist; result.Length = song.Length; result.Description = song.Description; _context.SaveChanges(); } }
public void ForHighlyRatedSongs_FillsSongsCorrectly() { // Arrange var song1 = new SongModel(); var song2 = new SongModel(); // Act var target = AdvisedPlaylist.ForHighlyRatedSongs(new[] { song1, song2 }); // Assert target.Songs.Should().BeEquivalentTo(new[] { song1, song2 }, x => x.WithStrictOrdering()); }
public IHttpActionResult Add(SongModel songModel) { if (!this.ModelState.IsValid) { return BadRequest(ModelState); } var newAtist = SongModel.ToSong(songModel); this.data.Songs.Add(newAtist); this.data.SaveChanges(); songModel.ID = newAtist.ID; return Ok(songModel); }
public IHttpActionResult Update(int id, SongModel song) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var existingSong = this.data.Songs.All().FirstOrDefault(s => s.Id == id); if (existingSong == null) { return(this.BadRequest("Such song does not exists!")); } existingSong.Title = song.Title; if (song.Genre != null) { existingSong.Genre = song.Genre; } if (song.Length != null) { existingSong.Length = song.Length; } if (song.Year != null) { existingSong.Year = song.Year; } this.data.SaveChanges(); song.Id = existingSong.Id; song.Genre = existingSong.Genre; song.Length = existingSong.Length; song.Title = existingSong.Title; var newSong = new { Id = existingSong.Id, Genre = existingSong.Genre, Length = existingSong.Length, Title = existingSong.Title }; return(this.Ok(newSong)); }
/// <summary> /// Updates playlist changes /// </summary> /// <param name="files">lists of audio file paths</param> /// <param name="playListBox">Playlist listbox</param> /// <param name="MediaPlayer">Media Player</param> /// <returns>Updated list of song objects</returns> public static List <SongModel> UpdatePlaylist(string[] files, ListBox playListBox, AxWindowsMediaPlayer MediaPlayer) { List <SongModel> updatedSongs = new List <SongModel>(); foreach (string file in files) // gets file paths { IWMPMedia mediaItem = MediaPlayer.newMedia((file)); // creates media files SongModel song = new SongModel(mediaItem); MediaPlayer.currentPlaylist.appendItem(song.MediaFile); // player.PlayStateChange playListBox.Items.Add(song.MediaFile.getItemInfo("Title")); updatedSongs.Add(song); } return(updatedSongs); }
// GET: Song/Edit/5 public ActionResult Edit(int id) { SongModel model = context.Songs.Where(some => some.Id == id).Select( some => new SongModel() { Id = some.Id, Title = some.Title, Singer = some.Singer, Writer = some.Writer, Year = some.Year, GenreID = some.GenreId }).SingleOrDefault(); PreparePublisher(model); return(View(model)); }
public async Task <ActionResult> PostCompleteSongUpload([FromForm] string qquuid, [FromForm] string qqfilename) { if (!uploadChunkCache.TryGetValue(qquuid, out MemoryStream stream)) { return(BadRequest()); } var addSongResult = await libraryService.AddSongAsync(stream, qqfilename); if (!addSongResult.Success) { return(BadRequest()); } return(Ok(new { success = true, song = SongModel.FromSong(addSongResult.Song) })); }
// POST api/Songs public HttpResponseMessage PostSong(SongModel song) { if (song == null) { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Song should be not null!"); return(errResponse); } Song songToAdd = song.ToSong(); var entity = this.repository.Add(songToAdd); var response = this.Request.CreateResponse(HttpStatusCode.Created, entity); response.Headers.Location = new Uri(this.Request.RequestUri + song.SongId.ToString(CultureInfo.InvariantCulture)); return(response); }
public void ToolTipGetter_ForActiveSong_ReturnsNull() { // Arrange var song = new SongModel(); var target = new SongListItem(song); // Act var toolTip = target.ToolTip; // Assert toolTip.Should().BeNull(); }
public IHttpActionResult Post([FromBody] SongModel song) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } else { var result = Mapper.Map <Song>(song); this.songs.Add(result); this.songs.SaveChanges(); return(this.Created(this.Url.ToString(), result)); } }
/// <summary> /// 通过<see cref="SystemMediaTransportControls"/>的API更新Universal Volume Control (UVC) /// </summary> private void UpdateUVCOnNewTrack(SongModel item) { if (item == null) { smtc.PlaybackStatus = MediaPlaybackStatus.Stopped; smtc.DisplayUpdater.MusicProperties.Title = string.Empty; smtc.DisplayUpdater.Update(); return; } smtc.PlaybackStatus = MediaPlaybackStatus.Playing; smtc.DisplayUpdater.Type = MediaPlaybackType.Music; smtc.DisplayUpdater.MusicProperties.Title = item.Name; smtc.DisplayUpdater.Thumbnail = RandomAccessStreamReference.CreateFromUri(item.Album.ArtLarge); DebugWrite(item.Album.ArtLarge.ToString()); smtc.DisplayUpdater.Update(); }
public async Task NextSongAsync(bool isRandom) { if (isRandom) { await RandomSong(); await Task.CompletedTask; } if (!IsEndList) { CurrentSongIndex++; CurrentSong = Songs.ToArray()[CurrentSongIndex]; } await Task.CompletedTask; }
public ActionResult SongEditor(int ArtistPageId) { if (ArtistPageId == 0) { return(RedirectToRoute("HomePage")); } var model = new SongModel() { ArtistPageId = ArtistPageId, DateCreated = DateTime.Now, DateUpdated = DateTime.Now }; return(View(ControllerUtil.MobSocialViewsFolder + "/SongPage/SongEditor.cshtml", model)); }
public static Song Add(SongModel song) { HttpResponseMessage responseMessage = client.PostAsJsonAsync("api/songs", song).Result; var mySong = responseMessage.Content.ReadAsAsync <Song>().Result; if (responseMessage.IsSuccessStatusCode) { Console.WriteLine("Song added: {0}", song.Title); } else { Console.WriteLine("{0} ({1})", (int)responseMessage.StatusCode, responseMessage.ReasonPhrase); } return(mySong); }
public async Task PreviousSongAsync(bool isRandom) { if (isRandom) { await RandomSong(); await Task.CompletedTask; } if (!IsBeginList) { CurrentSongIndex--; CurrentSong = Songs.ToArray()[CurrentSongIndex]; } await Task.CompletedTask; }
public IHttpActionResult Delete(int id) { var existingSong = this.data.Songs.Get(id); if (existingSong == null) { return(BadRequest(BabRequestMessage)); } var songModel = SongModel.FromSong(existingSong); this.data.Songs.Delete(existingSong); this.data.SaveChanges(); return(Ok(songModel)); }
public ActionResult SongEditor(int ArtistPageId) { if (ArtistPageId == 0) { return(RedirectToRoute("HomePage")); } var model = new SongModel() { ArtistPageId = ArtistPageId, DateCreated = DateTime.Now, DateUpdated = DateTime.Now }; return(View("mobSocial/SongPage/SongEditor", model)); }
public ActionResult SaveSong(HttpPostedFileBase[] file) { if (file == null) { return(RedirectToAction("Index")); } TagLib.File tagFile; foreach (var f in file) { if (f != null) { tagFile = TagLib.File.Create(f.FileName); SongModel NewSong = new SongModel(); NewSong.name = tagFile.Tag.Title; if (NewSong.name == null) { NewSong.name = f.FileName.Split('\\')[f.FileName.Split('\\').Length - 1].Replace(".mp3", ""); } try { if (Singleton.Data.Playlist[NewSong.name] != null) { //of this form, the songs, are upload one. } } catch { string artist = ""; for (int i = 0; i < tagFile.Tag.Artists.Length; i++) { artist = " " + artist + " " + tagFile.Tag.Artists[i] + "."; } NewSong.singer = artist.Trim(); NewSong.durationSeconds = tagFile.Properties.Duration; NewSong.duration = tagFile.Properties.Duration.ToString(); NewSong.SoundPath = f.FileName; Singleton.Data.Playlist.Add(NewSong.name, NewSong); } } } return(RedirectToAction("Index")); }
public void PlayDisc_SendsPlaySongsListEventForActiveDiscSongs() { // Arrange var disc = new DiscModel { Id = new ItemId("Some Disc") }; var discFolder = new FolderModel { Id = new ItemId("Some Folder") }; discFolder.AddDiscs(disc); var activeSong1 = new SongModel { Id = new ItemId("Active Song 1") }; var activeSong2 = new SongModel { Id = new ItemId("Active Song 2") }; var deletedSong = new SongModel { Id = new ItemId("Deleted Songs"), DeleteDate = new DateTime(2021, 07, 25) }; disc.AddSongs(activeSong1, deletedSong, activeSong2); var mocker = new AutoMocker(); var target = mocker.CreateInstance <LibraryExplorerViewModel>(); PlaySongsListEventArgs playSongsListEvent = null; Messenger.Default.Register <PlaySongsListEventArgs>(this, e => e.RegisterEvent(ref playSongsListEvent)); // Act target.PlayDisc(disc); // Assert var expectedSongs = new[] { activeSong1, activeSong2, }; playSongsListEvent.Should().NotBeNull(); playSongsListEvent.Songs.Should().BeEquivalentTo(expectedSongs, x => x.WithStrictOrdering()); }
public ICollection <SongModel> Bind(ICollection <Song> song) { ICollection <SongModel> songModelList = new List <SongModel>(); foreach (Song item in song) { SongModel songModel = new SongModel(); songModel.Id = item.Id; songModel.Name = item.Name; songModel.AlbumId = item.AlbumId; songModel.AlbumName = item.Album.Name; songModel.StyleName = item.Style.Name; songModelList.Add(songModel); } return(songModelList); }
public ActionResult OnGet(int?id) { if (id == null) { return(NotFound()); } else { sSong = factory.GetOneRecord(id); } if (sSong == null) { return(NotFound()); } return(Page()); }
/* 换用别的传递内容或者返回新的List减少内存占用?listnode的引用会导致GC无法清理HtmlDocument? * 实测发现返回换成返回一个新List也没有减少内存占用。。 */ internal IEnumerable <SongModel> ParseAlbumSongs(HtmlNode listnode, AlbumModel album) { foreach (var node in listnode.ChildNodes) { if (node.NodeType != HtmlNodeType.Element) { continue; } uint songID = uint.Parse(node.SelectSingleNode("./span").GetAttributeValue("rel", "0")); SongModel song = SongModel.GetNew(songID); song.Name = node.SelectSingleNode("./div/a").InnerText; song.TrackArtist = node.SelectSingleNode("./div/span")?.InnerText; song.PlayCount = int.Parse(node.SelectSingleNode("./div[2]/span").InnerText); song.Album = album; yield return(song); } }
void InitializeSongs() { // Album art attribution // Ring01.jpg | Autumn Yellow Leaves | George Hodan // Ring02.jpg | Abstract Background | Larisa Koshkina // Ring03Part1.jpg | Snow Covered Mountains | Petr Kratochvil // Ring03Part2.jpg | Tropical Beach With Palm Trees | Petr Kratochvil // Ring03Part3.jpg | Alyssum Background | Anne Lowe // Initialize the playlist data/view model. // In a production app your data would be sourced from a data store or service. // Add complete tracks var song1 = new SongModel(); song1.Title = "Ring 1"; song1.MediaUri = new Uri("ms-appx:///Assets/Media/Ring01.wma"); song1.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring01.jpg"); playlistView.Songs.Add(song1); var song2 = new SongModel(); song2.Title = "Ring 2"; song2.MediaUri = new Uri("ms-appx:///Assets/Media/Ring02.wma"); song2.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring02.jpg"); playlistView.Songs.Add(song2); // Add gapless for (int i = 1; i <= 3; ++i) { var segment = new SongModel(); segment.Title = "Ring 3 Part " + i; segment.MediaUri = new Uri("ms-appx:///Assets/Media/Ring03Part" + i + ".wma"); segment.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring03Part" + i + ".jpg"); playlistView.Songs.Add(segment); } // Pre-cache all album art to facilitate smooth gapless transitions. // A production app would have a more sophisticated object cache. foreach (var song in playlistView.Songs) { var bitmap = new BitmapImage(); bitmap.UriSource = song.AlbumArtUri; albumArtCache[song.AlbumArtUri.ToString()] = bitmap; } }
public static SongModel Convert(Song song) { SongModel model = new SongModel { SongId = song.SongId, SongTitle = song.SongTitle, SongYear = song.SongYear, SongGenre = song.SongGenre, Description = song.Description, Artist = new ArtistModel { ArtistId = song.SongArtist.ArtistId, Name = song.SongArtist.Name, DateOfBirth = song.SongArtist.DateOfBirth, Country = song.SongArtist.Country } }; return model; }
/// <summary> /// 播放指定歌曲 /// </summary> /// <param name="song">需要播放的歌曲,如果不在列表中的话将加入列表</param> public async void PlayTrack(SongModel song) { if (_isPlayingRadio) throw new InvalidOperationException("在播放歌曲前应停止电台播放"); if (string.IsNullOrEmpty(song.Album?.Art?.Host)) await Net.WebApi.Instance.GetSongInfo(song); if (!PlaylistService.Instance.Contains(song)) { PlaylistService.Instance.Add(song); PlayTrack(PlaylistService.Instance.Count - 1); } else PlayTrack(PlaylistService.Instance.IndexOf(song)); }
public void Add(SongModel model) { _session.Add(model); }
public IAsyncAction GetSongInfo(SongModel song, bool cover = true) { if (song.XiamiID == 0) throw new ArgumentException("SongModel未设置ID"); return Run(async token => { try { LogService.DebugWrite($"Get info of Song {song.XiamiID}", nameof(WebApi)); var gettask = HttpHelper.GetAsync($"http://www.xiami.com/song/{song.XiamiID}"); token.Register(() => gettask.Cancel()); var content = await gettask; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(content); var body = doc.DocumentNode.SelectSingleNode("/html/body/div[@id='page']"); List<Task> process = new List<Task>(); process.Add(Task.Run(() => { if (song.RelatedLovers == null || cover) song.RelatedLovers = new PageItemsCollection<UserModel>(ParseSongRelateUsers(body.SelectSingleNode(".//div[@id='song_fans_block']/div/ul")).ToList()); }, token)); process.Add(Task.Run(() => { if (song.RelateHotSongs == null || cover) song.RelateHotSongs = ParseSongRelateSongs(body.SelectSingleNode(".//div[@id='relate_song']/div/table")).ToList(); }, token)); process.Add(Task.Run(() => { if (song.Tags == null || cover) song.Tags = ParseTags(body.SelectSingleNode(".//div[@id='song_tags_block']/div")).ToList(); }, token)); var title = body.SelectSingleNode(".//h1"); if (song.Name == null || cover) song.Name = title.FirstChild.InnerText; var mva = title.SelectSingleNode("./a"); if ((mva != null) && (song.MV == null || cover)) song.MV = MVModel.GetNew(ParseXiamiIDString(mva.GetAttributeValue("href", "/0"))); if (song.Description == null || cover) if (title.LastChild.Name == "span") song.Description = title.LastChild.InnerText; var loveop = body.SelectSingleNode(".//ul/li[1]"); song.IsLoved = loveop.GetAttributeValue("style", "") == "display:none"; if (loveop.ParentNode.ParentNode.ParentNode.InnerText.IndexOf("单曲下架") != -1) song.Available = false; var detail = body.SelectSingleNode(".//table"); foreach (var item in detail.SelectNodes("./tr")) { switch (item.ChildNodes[1].InnerText) { case "所属专辑:": var linknode = item.SelectSingleNode(".//a"); var id = uint.Parse(linknode.GetAttributeValue("href", "/album/0").Substring(7)); if ((song.Album == null) || cover) { var album = song.Album ?? AlbumModel.GetNew(id); album.Name = linknode.InnerText; if (album.Art.Host == "") { var art = detail.ParentNode.SelectSingleNode(".//img").GetAttributeValue("src", AlbumModel.SmallDefaultUri); album.Art = new Uri(art.Replace("_2", "_1")); album.ArtFull = new Uri(art.Replace("_2", "")); } song.Album = album; } break; case "演唱者:": song.TrackArtist = item.SelectSingleNode(".//a").InnerText; break; case "作词:": song.Lyricist = item.SelectSingleNode(".//div").InnerText; break; case "作曲:": song.Composer = item.SelectSingleNode(".//div").InnerText; break; case "编曲:": song.Arranger = item.SelectSingleNode(".//div").InnerText; break; } } await Task.WhenAll(process); LogService.DebugWrite($"Finish Getting info of Song {song.XiamiID}", nameof(WebApi)); } catch (Exception e) { LogService.ErrorWrite(e, nameof(WebApi)); throw e; } }); }
/// <returns>是否成功开始播放</returns> private bool PlayTrackInternal(SongModel song) { PlaybackOperated?.Invoke(song, null); // Start the background task if it wasn't running //if (!IsBackgroundTaskRunning || MediaPlayerState.Closed == CurrentPlayer.CurrentState) if (!IsBackgroundTaskRunning) { // First update the persisted start track SettingsService.Playback.Write("TrackId", song.MediaUri.ToString()); SettingsService.Playback.Write("Position", new TimeSpan().ToString()); // Start task StartBackgroundAudioTask(); return false; } else { //TODO: 增加如果播放不成功则刷新地址 if (song.MediaUri == null) ExtensionMethods.InvokeAndWait(async () => song.MediaUri = new Uri(await Net.DataApi.GetDownloadLink(song, false))); MessageService.SendMediaMessageToBackground(MediaMessageTypes.SetSong, song); MessageService.SendMediaMessageToBackground(MediaMessageTypes.StartPlayback); return true; } }
public void Delete(SongModel model) { _session.Delete(model); }
private SongViewModel LookupSong(SongModel song) { if (song == null) return null; if (SongLookupMap.ContainsKey(song.SongId)) { return SongLookupMap[song.SongId]; } else { ArtistViewModel artist = LookupArtistById(song.ArtistId); AlbumViewModel album = LookupAlbumById(song.AlbumId); SongViewModel newSongViewModel = new SongViewModel(song, artist, album); SongLookupMap.Add(newSongViewModel.SongId, newSongViewModel); SongCollection.Add(newSongViewModel, newSongViewModel.SortName); FlatSongCollection.Add(newSongViewModel); if (LibraryLoaded) { NotifyPropertyChanged(Properties.IsEmpty); } return newSongViewModel; } }
public SongModel LookupSongById(int songId) { if (songLookupDictionary.ContainsKey(songId)) { return songLookupDictionary[songId]; } else { SongTable songTable = DatabaseManager.Current.LookupSongById(songId); if (songTable == null) { return null; } else { SongModel songModel = new SongModel(songTable); _allSongs.Add(songModel); songLookupDictionary.Add(songModel.SongId, songModel); return songModel; } } }
public SongModel AddNewSong(string artist, string album, string albumArtist, string title, string path, SongOriginSource origin, long duration, uint rating, uint trackNumber) { ArtistModel artistModel = LookupArtistByName(artist); ArtistModel albumArtistModel = LookupArtistByName(albumArtist); AlbumModel albumModel = LookupAlbumByName(album, albumArtistModel.ArtistId); SongModel currentTableEntry = LookupSongByPath(path); if (currentTableEntry == null) { SongTable newSong = new SongTable(albumModel.AlbumId, artistModel.ArtistId, duration, 0, title, origin, 0, rating, path, trackNumber); DatabaseManager.Current.AddSong(newSong); SongModel songModel = new SongModel(newSong); _allSongs.Add(songModel); songLookupDictionary.Add(songModel.SongId, songModel); return songModel; } return null; }
private SongModel LookupSongByPath(string path) { SongTable songTable = DatabaseManager.Current.LookupSongByPath(path); if (songTable == null) return null; if (songLookupDictionary.ContainsKey(songTable.SongId)) return songLookupDictionary[songTable.SongId]; SongModel songModel = new SongModel(songTable); _allSongs.Add(songModel); songLookupDictionary.Add(songModel.SongId, songModel); return songModel; }
private void LoadCollection() { PerfTracer perfTracer = new PerfTracer("LibraryModel Loading"); IEnumerable<SongTable> allSongs = DatabaseManager.Current.FetchSongs(); foreach (SongTable songEntry in allSongs) { SongModel songModel = new SongModel(songEntry); _allSongs.Add(songModel); songLookupDictionary.Add(songModel.SongId, songModel); } perfTracer.Trace("Songs Added"); IEnumerable<AlbumTable> allAlbums = DatabaseManager.Current.FetchAlbums(); foreach (AlbumTable albumEntry in allAlbums) { AlbumModel albumModel = new AlbumModel(albumEntry); _allAlbums.Add(albumModel); albumLookupDictionary.Add(albumModel.AlbumId, albumModel); } perfTracer.Trace("Albums Added"); IEnumerable<ArtistTable> allArtists = DatabaseManager.Current.FetchArtists(); foreach (ArtistTable artistEntry in allArtists) { ArtistModel artistModel = new ArtistModel(artistEntry); _allArtists.Add(artistModel); artistLookupDictionary.Add(artistModel.ArtistId, artistModel); } perfTracer.Trace("Artists Added"); IEnumerable<PlaylistTable> allPlaylists = DatabaseManager.Current.FetchPlaylists(); foreach (PlaylistTable playlistEntry in allPlaylists) { PlaylistModel playlistModel = new PlaylistModel(playlistEntry); Playlists.Add(playlistModel); playlistLookupDictionary.Add(playlistModel.PlaylistId, playlistModel); playlistModel.Populate(); } perfTracer.Trace("Playlists Added"); IEnumerable<MixTable> allMixes = DatabaseManager.Current.FetchMixes(); foreach (MixTable mixEntry in allMixes) { MixModel mixModel = new MixModel(mixEntry); Mixes.Add(mixModel); mixLookupDictionary.Add(mixModel.MixId, mixModel); mixModel.Populate(); } perfTracer.Trace("Mixes Added"); }
//TODO: 判断歌曲是否被喜爱 /// <summary> /// 通过SongId获取歌曲的信息(不含取媒体地址) /// </summary> /// <param name="cover">是否覆盖已存在的Album和Artist信息</param> public IAsyncAction GetSongInfo(SongModel song, bool cover = false) { if (song.XiamiID == 0) throw new ArgumentException("SongModel未设置ID"); return Run(async token => { try { LogService.DebugWrite($"Get info of Song {song.XiamiID}", nameof(WapApi)); var gettask = HttpHelper.GetAsync($"http://www.xiami.com/app/xiating/song?id={song.XiamiID}"); token.Register(() => gettask.Cancel()); var content = await gettask; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(content); HtmlNode root = doc.DocumentNode; var logo = root.SelectSingleNode("//img[1]"); var detail = root.SelectSingleNode("//ul[1]"); var detailgrade = root.SelectSingleNode("//div[1]/ul[1]"); if (song.Name == null) song.Name = logo.GetAttributeValue("title", "UnKnown"); song.PlayCount = int.Parse(detailgrade.SelectSingleNode(".//span[1]").InnerText); song.ShareCount = int.Parse(detailgrade.SelectSingleNode("./li[3]/span[1]").InnerText); var additionnodes = detail.SelectNodes("./li[position()>2]"); foreach (var node in additionnodes) switch (node.FirstChild.InnerText) { case "作词:": song.Lyricist = node.LastChild.InnerText; break; case "作曲:": song.Composer = node.LastChild.InnerText; break; case "编曲:": song.Arranger = node.LastChild.InnerText; break; } if ((song.Album == null) || cover) { var albumtag = detail.SelectSingleNode("./li[1]/a[1]"); var idtext = albumtag.GetAttributeValue("href", "/app/xiating/album?id=0"); var addrlength = "/app/xiating/album?id=".Length; uint albumID = uint.Parse(idtext.Substring(addrlength, idtext.IndexOf("&", addrlength) - addrlength)); AlbumModel album = song.Album ?? AlbumModel.GetNew(albumID); if (album.Art.Host == "") { var art = logo.GetAttributeValue("src", AlbumModel.SmallDefaultUri); album.Art = new Uri(art.Replace("_2", "_1")); album.ArtFull = new Uri(art.Replace("_2", "")); } album.Name = albumtag.InnerText; song.Album = album; } if ((song.Album?.Artist == null) || cover) { var artisttag = detail.SelectSingleNode("./li[2]/a[1]"); var idtext = artisttag.GetAttributeValue("href", "/app/xiating/artist?id=0"); var addrlength = "/app/xiating/artist?id=".Length; uint artistID = uint.Parse(idtext.Substring(addrlength, idtext.IndexOf("&", addrlength) - addrlength)); ArtistModel artist = song.Album?.Artist ?? ArtistModel.GetNew(artistID); artist.Name = artisttag.InnerText; song.Album.Artist = artist; } LogService.DebugWrite($"Finish Getting info of Song {song.Name}", nameof(WapApi)); } catch (Exception e) { LogService.ErrorWrite(e, nameof(WapApi)); throw e; } }); }
public void Edit(SongModel model) { var record = _session.Single<Song>(x=>x.Id == model.Id); record.Update(model); _session.CommitChanges(); }
public IHttpActionResult Update(int id, SongModel songModel) { if (!this.ModelState.IsValid) { return BadRequest(ModelState); } var existingSong = this.data.Songs.Get(id); if (existingSong == null) { return BadRequest(BabRequestMessage); } SongModel.ToSong(songModel, existingSong); this.data.Songs.Update(existingSong); this.data.SaveChanges(); return Ok(songModel); }