/// <summary> /// Obtiene el nombre del archivo local /// </summary> private string GetLocalFileName(TrackModel track) { string fileName = ""; // Obtiene el nombre de la Url if (!string.IsNullOrWhiteSpace(track.Url)) { string[] urlParts = track.Url.Split('/'); if (urlParts.Length > 0) { fileName = urlParts[urlParts.Length - 1]; } } // Si no se ha obtenido ningún nombre, lo coge del nombre del canal if (string.IsNullOrWhiteSpace(fileName)) { fileName = track.Title; } // Le añade la extensión if (!fileName.EndsWith(".xml", StringComparison.CurrentCultureIgnoreCase)) { fileName += ".xml"; } // Normaliza el nombre y lo devuelve return(LibCommonHelper.Files.HelperFiles.Normalize(fileName, false)); }
/// <summary> /// Pega un canal a un manager de canales /// </summary> private void PasteTrackToTrackManager(TrackModel track, TrackManagerModel manager) { TrackModel newTrack = track.Clone(); // Limpia el ID del canal newTrack.Id = null; // Limpia los IDs foreach (CategoryModel category in track.Categories) { // Limpia el ID de la categoría category.Id = null; // Limpia los IDs de las entradas foreach (EntryModel entry in category.Entries) { entry.Id = null; } } // Añade el nuevo canal manager.Tracks.Add(newTrack); // Borra el canal inicial si se debía cortar if (MustCut) { manager.Tracks.Remove(track); } }
/// <summary> /// Procesa los administradores de canales o canales /// </summary> private void ProcessTracks() { if (SelectedNode != null) { if (SelectedNode?.Tag is TrackManagerModel trackManager) { // Procesa todas las pistas ProcessTrackManager(trackManager); // Mensaje para el usuario DevConferencesViewModel.Instance.ControllerWindow.ShowMessage("Ha finalizado el proceso de los canales"); } else { TrackManagerModel trackNodeManager = GetParentNodeOfType <TrackManagerModel>(); if (trackNodeManager != null) { TrackModel track = GetParentNodeOfType <TrackModel>(); // Procesa la pista if (track != null) { ProcessTrack(trackNodeManager, track); } // Mensaje para el usuario DevConferencesViewModel.Instance.ControllerWindow.ShowMessage("Ha finalizado el proceso de los canales"); } } } }
private DownloadInfoModel GetDownloadUrl(TrackModel track) { var url = "http://hypem.com/serve/source/" + track.id + "/" + track.key; var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Referer = BaseUrl + "/" + Account + "/" + Page; httpWebRequest.UserAgent = UserAgent; httpWebRequest.Method = "GET"; httpWebRequest.CookieContainer = Cookies; httpWebRequest.ContentType = "application/json"; var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); var responseStream = httpWebResponse.GetResponseStream(); if (responseStream == null) { return(null); } var raw = new StreamReader(responseStream).ReadToEnd(); if (string.IsNullOrEmpty(raw)) { throw new Exception("No response"); } var downloadInfo = JsonConvert.DeserializeObject <DownloadInfoModel>(raw); if (downloadInfo == null) { throw new Exception("Could not parse download info"); } return(downloadInfo); }
public static void SetupTracks(TrackModel model) { using (var site = new SCBWIContext()) { site.Tracks.Add(new Track { Name = model.Track1, Presenters = model.Track1Presenters }); site.Tracks.Add(new Track { Name = model.Track2, Presenters = model.Track2Presenters }); site.Tracks.Add(new Track { Name = model.Track3, Presenters = model.Track3Presenters }); site.Tracks.Add(new Track { Name = model.Track4, Presenters = model.Track4Presenters }); site.Tracks.Add(new Track { Name = model.Track5, Presenters = model.Track5Presenters }); site.SaveChanges(); } }
public IActionResult GetTracks([FromQuery] int?take, [FromQuery] int?skip) { var userId = User.GetUserId(); var tracks = _trackService.GetTracks(userId, take, skip); var mappedTracks = new List <TrackModel>(); foreach (var track in tracks) { var mappedTrack = new TrackModel(); mappedTrack.Id = track.Id; mappedTrack.Name = track.Name; mappedTrack.CreatedAt = track.CreatedAt; try { mappedTrack.AllowedCustomizations = track.AllowedCustomizations.Select(c => c.ToString()).ToArray(); } catch { mappedTrack.AllowedCustomizations = Array.Empty <string>(); } mappedTracks.Add(mappedTrack); } var response = new GetTracksResponse() { Tracks = mappedTracks.ToArray(), }; return(Ok(response)); }
private void OnAddTrackItem(Type track) { TrackModel trackModel = ReflectionHelper.CreateInstance(track) as TrackModel; BaseSequenceView sequenceView = window.GetPartialView <BaseSequenceView>(); sequenceView.AddTrack(trackModel); }
public override void ReorderSelectedTracks(int drop_row) { // If the current_track is not playing, dropping tracks may change it. // If the selection is dropped above the current_track, the first pending // of the dropped tracks (if any) will become the new current_track. // If the tracks are dropped below the curren_track, // the first pending track not in the selection will become current. if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying(current_track)) { int current_index = TrackModel.IndexOf(current_track); bool above = drop_row <= current_index; int new_index = -1; for (int index = current_index; index < TrackModel.Count; index++) { if (above == TrackModel.Selection.Contains(index)) { new_index = index; break; } } if (new_index != current_index && new_index >= 0) { SetCurrentTrack(TrackModel[new_index] as DatabaseTrackInfo); } } base.ReorderSelectedTracks(drop_row); }
private static void SetParameters(TrackModel model, Dictionary <string, string> parameters) { parameters.Add("startdate", model.StartDate.ToString(CultureInfo.InvariantCulture)); parameters.Add("enddate", model.EndDate.ToString(CultureInfo.InvariantCulture)); parameters.Add("cash", model.InitialCapital.ToString(CultureInfo.InvariantCulture)); parameters.Add("resolution", model.Resolution.ToString()); if (!model.Symbols.IsNullOrEmpty()) { parameters.Add("symbols", string.Join(";", model.Symbols.Where(p => p.Active).Select(m => m.Name))); } foreach (ParameterModel parameter in model.Parameters) { string value; if (!parameters.TryGetValue(parameter.Name, out value)) { if (parameter.UseValue) { parameters.Add(parameter.Name, parameter.Value); } } } string parametersConfigString = JsonConvert.SerializeObject(parameters); Config.Set("parameters", parametersConfigString); }
private static Tuple <AlbumResponseModel, IEnumerable <TrackModel> > DeserializeResponse(string json, int outputId, int artistId, string genre) { dynamic obj = Json.Decode(json); string Artist = obj.artists[0].name; string albumName = obj.name; string release = obj.release_date; int releaseYear = int.Parse(release.Split('-')[0]); AlbumResponseModel album = new AlbumResponseModel { tytul = albumName, rok = releaseYear, _id = outputId, arists_id = artistId, gatunek = genre }; List <TrackModel> tracks = new List <TrackModel>(); foreach (var track in obj.tracks.items) { var model = new TrackModel { czas_trwania = track.duration_ms, pozycja = track.track_number, nazwa = track.name, albums_id = album._id }; tracks.Add(model); } return(new Tuple <AlbumResponseModel, IEnumerable <TrackModel> >(album, tracks)); }
private void IterateTrackModelUntilEndMatch(out long viewOrder, bool checkAlbum) { var t = TrackModel; bool in_match = false; long current_view_order = CurrentTrackViewOrder; int index = Math.Max(0, TrackModel.IndexOf(current_track)); string current_album = ServiceManager.PlayerEngine.CurrentTrack.AlbumTitle; string current_artist = ServiceManager.PlayerEngine.CurrentTrack.AlbumArtist; // view order will point to the last track that has the same album and artist of the // currently playing track. viewOrder = current_view_order; for (int i = index; i < t.Count; i++) { var track = t[i]; if (current_artist == track.AlbumArtist && (!checkAlbum || current_album == track.AlbumTitle)) { in_match = true; viewOrder++; } else if (!in_match) { continue; } else { viewOrder--; break; } } }
public void RunTest() { var provider = new ProviderModel() { Name = nameof(AccountModel.AccountType.Backtest) }; var account = new AccountModel() { Provider = provider }; var track = new TrackModel { Account = provider.Name, AlgorithmLanguage = Language.CSharp, AlgorithmLocation = Path.Combine(_exeFolder, "QuantConnect.Algorithm.CSharp.dll"), AlgorithmName = "BasicTemplateFrameworkAlgorithm", StartDate = new DateTime(2016, 01, 01) }; using var launcher = new LeanLauncher(); launcher.Run(track, account, _settings); Assert.IsTrue(track.Completed); Assert.IsFalse(track.Active); Assert.IsNotNull(track.Logs); Assert.IsTrue(track.Logs.Length > 0); Assert.IsNotNull(track.Result); Assert.IsTrue(track.Result.Length > 0); }
private void SaveTrack(StopTrackingDialog s, EventArgs ea) { FragmentTransaction ft = FragmentManager.BeginTransaction(); Fragment prev = FragmentManager.FindFragmentByTag("TrackNameDialog"); if (prev != null) { ft.Remove(prev); } ft.AddToBackStack(null); TrackNameDialog dialogBox = TrackNameDialog.NewInstance(null); dialogBox.Show(ft, "TrackNameDialog"); dialogBox.TrackNameDialogSave += (se, e) => { TrackModel tm = this.Tracker.GetOrInstantiateTrackModel(); tm.Name = e.TrackName; System.Console.WriteLine("____FAKETRACKGENERATIOSTRING____"); System.Console.WriteLine(tm.Track); Database.Database.GetInstance().InsertOrReplace(tm); this.Tracker.StopTracking(); this.UpdateStartStopPauseButton(); Toast.MakeText(this.Context, "Uw track is opgeslagen!", ToastLength.Short).Show(); se.Dismiss(); s.Dismiss(); }; }
private static bool SetConfig( IDictionary <string, string> config, TrackModel model, AccountModel account, SettingModel settings) { var parameters = new Dictionary <string, string>(); SetModel(config, model, settings); if (model.Account.Equals(AccountModel.AccountType.Backtest.ToString(), StringComparison.OrdinalIgnoreCase)) { SetBacktest(config); } else if (model.Account.Equals(AccountModel.AccountType.Paper.ToString(), StringComparison.OrdinalIgnoreCase)) { SetPaper(config); } else if (account == default) { Log.Error("No broker selected", true); return(false); } SetParameters(config, model, parameters); return(true); }
public void Run(TrackModel model, AccountModel account, SettingModel settings) { if (model == null) { throw new ArgumentNullException(nameof(model)); } Debug.Assert(model.Status == CompletionStatus.None); if (!model.Active) { return; } bool error = false; _process = new ConfigProcess( "QuantConnect.Lean.Launcher.exe", null, Directory.GetCurrentDirectory(), true, (line) => Log.Trace(line), (line) => { error = true; Log.Error(line, true); }); // Set Environment StringDictionary environment = _process.Environment; // Set config IDictionary <string, string> config = _process.Config; if (!SetConfig(config, model, account, settings)) { return; } // Start process try { if (model.AlgorithmLanguage.Equals(Language.Python)) { PythonSupport.SetupPython(_process.Environment); } _process.Start(); _process.WaitForExit(int.MaxValue, (folder) => PostProcess(folder, model)); model.Status = error ? CompletionStatus.Error : CompletionStatus.Success; } catch (Exception ex) { model.Status = CompletionStatus.Error; Log.Error($"{ex.GetType()}: {ex.Message}", true); } finally { _process.Dispose(); _process = null; model.Active = false; } }
public async Task <IActionResult> UpdateTrackAsync(int id, [FromBody] TrackModel trackModel) { try { var trackEntity = _mapper.Map <Track>(trackModel); if (id != trackEntity.Id) { return(BadRequest(new ProcessResult { Message = "Track id from URI and from model should be the same.", Result = false })); } else { await _trackService.UpdateTrackAsync(trackEntity); return(NoContent()); } } catch (Exception e) { return(BadRequest(new ProcessResult { Message = e.Message, Result = false })); } }
public void AddTrackToAlbum(TrackModel track) { var newtrack = mapper.Map <TrackEntity>(track); UnitOfWork.TrackRepository.Add(newtrack); UnitOfWork.Save(); }
public void Test1() { using var context = ApplicationDbContext.UseMySql(); var now = DateTime.Now; var model = new TrackModel { ForTrim = " 127.0.0.1 ", ForLower = "LinqSharp", ForUpper = "LinqSharp", ForCondensed = " Welcome to use LinqSharp ", }; context.TrackModels.Add(model); context.SaveChanges(); Assert.Equal("127.0.0.1", model.ForTrim); Assert.Equal("linqsharp", model.ForLower); Assert.Equal("LINQSHARP", model.ForUpper); Assert.Equal("Welcome to use LinqSharp", model.ForCondensed); Assert.Equal(now.StartOfDay(), model.CreationTime.StartOfDay()); Assert.Equal(now.StartOfDay(), model.LastWriteTime.StartOfDay()); Thread.Sleep(10); context.TrackModels.Update(model); context.SaveChanges(); Assert.True(model.LastWriteTime > model.CreationTime); context.TrackModels.Remove(model); context.SaveChanges(); }
private void AddTrackToPlaylistAndPlay(TrackModel trackItem) { TrackModel playlistTrackItem = AddTrackItemToPlaylist(trackItem, true); PlaylistTrackGrid.SelectedItem = playlistTrackItem; StopMusic(); PlayButtonClick(null, null); }
private void PlayTrack(TrackModel trackItem) { if (_showAlbumArt) UpdateAlbumArt(trackItem.Child); QueueTrack(trackItem); }
private static void SetParameters( IDictionary <string, string> config, TrackModel model, Dictionary <string, string> parameters) { parameters.Add("market", model.Market); parameters.Add("security", model.Security.ToStringInvariant()); parameters.Add("resolution", model.Resolution.ToStringInvariant()); if (!model.Symbols.IsNullOrEmpty()) { parameters.Add("symbols", string.Join(";", model.Symbols.Where(p => p.Active).Select(m => m.Id))); } foreach (ParameterModel parameter in model.Parameters) { if (!parameters.TryGetValue(parameter.Name, out string value)) { if (parameter.UseValue) { parameters.Add(parameter.Name, parameter.Value); } } } string parametersConfigString = JsonConvert.SerializeObject(parameters); config["parameters"] = parametersConfigString; }
public async Task AddFilesToDatabase(IEnumerable <string> filepaths, Action <string>?cb = null) { await Task.Run(async() => // Perform On Another Thread To Prevent Freezing UI { await Task.WhenAll(filepaths.Select(async file => // Allows Loop To Run In Parallel { cb?.Invoke($"Processing: {file}"); if (!SupportedFormats.Any(file.EndsWith)) { return; // Checks File Extension Is Supported } try { // Taglib api await db.SaveTrack(TrackModel.FromFile(File.Create(file))); // ATL api // await db.SaveTrack(Track.FromFile(file)); } catch (Exception e) { Debug.WriteLine(e.Message); } })); }); }
public AlbumModel GetAlbum(int albumId) { try { var albumModel = new AlbumModel(); using (var context = new sparrow_dbEntities()) { var album = context.SPRW_ALBUM.FirstOrDefault(i => i.ALBUM_ID == albumId); if (album != null) { albumModel.AlbumId = album.ALBUM_ID; albumModel.AlbumName = album.NAME; var tracks = new List <TrackModel>(); foreach (var track in album.SPRW_TRACK) { var trackModel = new TrackModel { TrackId = track.TRACK_ID, TrackName = track.NAME }; tracks.Add(trackModel); } albumModel.Tracks = tracks; } } return(albumModel); } catch (Exception e) { throw e; } }
private void dgvSoundRecordingsAndReleases_CellClick(object sender, DataGridViewCellEventArgs e) { int editIndex = 0; int deleteIndex = 1; if (e.ColumnIndex == editIndex) { TrackModel track = (TrackModel)dgvSoundRecordingsAndReleases.CurrentRow.DataBoundItem; if (track != null) { using (var frm = new ERN_382TrackReleaseForm((TrackModel)track.Copy())) { if (frm.ShowDialog() == DialogResult.OK) { track.CopyFromSource(frm.Model); } } } } else if (e.ColumnIndex == deleteIndex) { using (var f = new MRMessageBox("Želite li obrisati zapis?", MRMessageBox.eMessageBoxStyle.YesNo)) { if (f.ShowDialog() == DialogResult.Yes) { dgvSoundRecordingsAndReleases.Rows.RemoveAt(e.RowIndex); } } } }
public void SwitchView(int item) { Fragment f; Bundle b = new Bundle(); switch (item) { case MainActivity.TRACKER: f = new TrackerFragment(); b.PutParcelable("Tracker", new TrackerParcel(this.Tracker)); f.Arguments = b; break; case MainActivity.MYTRACKS: f = new MyTracksFragment(); b.PutParcelable("Tracks", new MyTracksParcel(TrackModel.GetAll(Database.Database.GetInstance()))); f.Arguments = b; break; default: return; } FragmentTransaction ft = this.FragmentManager.BeginTransaction(); ft.Replace(Resource.Id.content, f); ft.Commit(); }
private void StartTrackTimer(TrackModel selectedMusic) { if (selectedMusic.DurationSec == null) { Duration = StringFormatter.DurationFormat(selectedMusic.DurationMillisec); MaxProgressValue = Convert.ToDouble(selectedMusic.DurationMillisec); Device.StartTimer(TimeSpan.FromSeconds(0.2), () => { ProgressValue = (double)audioService.CurrentTrackProgressPosition(); Position = StringFormatter.DurationFormat(audioService.CurrentTrackProgressPosition().ToString()); return(true); }); } else { MaxProgressValue = Convert.ToDouble(selectedMusic.DurationSec); Duration = StringFormatter.DurationFormat((MaxProgressValue * 1000).ToString()); Device.StartTimer(TimeSpan.FromSeconds(0.2), () => { ProgressValue = (double)audioService.CurrentTrackProgressPosition(); Position = StringFormatter.DurationFormat((audioService.CurrentTrackProgressPosition() * 1000).ToString()); return(true); }); } }
public void Dispose() { int track_index = current_track == null ? Count : Math.Max(0, TrackModel.IndexOf(current_track)); DatabaseConfigurationClient.Client.Set(CurrentTrackSchema, track_index); ServiceManager.PlayerEngine.DisconnectEvent(OnPlayerEvent); ServiceManager.PlaybackController.TrackStarted -= OnTrackStarted; if (actions != null) { actions.Dispose(); } UninstallPreferences(); Properties.Remove("Nereid.SourceContents.HeaderWidget"); if (header_widget != null) { header_widget.Destroy(); header_widget = null; } if (ClearOnQuitSchema.Get()) { Clear(true); } }
public string Configure(string basePath, string targetFileExtension, TrackModel track) { basePath += (basePath.Last() != '\\') ? "\\" : ""; var completePath = basePath + track.Name.ValidateFileName(); if (track.Playlist == null) { return(completePath); } if (track.Playlist.Name.Length == 0) { return(completePath); } var playlistRepositoryDirectory = basePath + track.Playlist.Name.ValidateFileName() + "\\"; try { if (!Directory.Exists(playlistRepositoryDirectory)) { Directory.CreateDirectory(playlistRepositoryDirectory); } } catch (UnauthorizedAccessException exception) { throw new ConfigurationException(String.Format("Loadify is not authorized to create the download directory ({0})", playlistRepositoryDirectory), exception); } catch (Exception exception) { throw new ConfigurationException("An unhandled configuration error occured", exception); } completePath = playlistRepositoryDirectory + track.Name.ValidateFileName() + "." + targetFileExtension; return(completePath); }
/// <summary> /// Elimina un canal /// </summary> public void RemoveTrack(TrackModel track) { foreach (TrackManagerModel trackManager in TrackManagers) { trackManager.Tracks.Remove(track); } }
bool IBasicPlaybackController.Next(bool restart) { if (current_track != null && ServiceManager.PlayerEngine.CurrentTrack == current_track) { int index = TrackModel.IndexOf(current_track) + 1; SetCurrentTrack(index < Count ? TrackModel[index] as DatabaseTrackInfo : null); } if (current_track == null) { UpdatePlayQueue(); ServiceManager.PlaybackController.Source = PriorSource; if (was_playing) { ServiceManager.PlaybackController.PriorTrack = prior_playback_track; ServiceManager.PlaybackController.Next(restart); } else { ServiceManager.PlayerEngine.Close(); } return(true); } ServiceManager.PlayerEngine.OpenPlay(current_track); return(true); }
/// <summary> /// This method shows the use and the functionality of some repository methods. /// <c> /// Insert a new Track in the Database, Count all elements and the Load it all! Then delete a item and Load it all again /// </c> /// </summary> public static void InsertCountLoadAllDeleteAndLoadAgain() { ExampleHelper.ExampleMethodPrint("Insert a new Track in the Database, Count all elements and the Load it all!\n" + "Then delete a item and Load it all again", MethodInfo.GetCurrentMethod()); TrackModel track = new TrackModel(@"..\..\Resource\Garden.mp3"); ExampleHelper.DumpObjectProperties(track.GetAsDatabaseType()); Console.WriteLine("Save Response : " + _trackRep.Save(track)); Console.WriteLine("Count : " + _trackRep.Count <TrackModel.Track>()); List <TrackModel.Track> list = new List <TrackModel.Track>(); Console.WriteLine("GetAll Response : " + _trackRep.GetAll(list)); foreach (TrackModel.Track t in list) { ExampleHelper.DumpObjectProperties(t); } TrackModel anotherTrack = new TrackModel(); Console.WriteLine("Delete Response: " + _trackRep.Delete <TrackModel.Track>(list.First().Id)); list.Clear(); Console.WriteLine("GetAll Response : " + _trackRep.GetAll(list)); foreach (TrackModel.Track t in list) { ExampleHelper.DumpObjectProperties(t); } }
public async Task <string[]> getNameAndArtist(int trackId) { TrackModel track = await client.GetTrack(trackId); string[] info = { track.Title, track.Artist.Name }; return(info); }
private TrackModel AddTrackItemToPlaylist(TrackModel trackItem, bool playback = false, bool clear = true) { var playlistTrackItem = new TrackModel(); trackItem.CopyTo(playlistTrackItem); playlistTrackItem.Source = trackItem; playlistTrackItem.Duration = TimeSpan.FromSeconds(playlistTrackItem.Child.Duration); playlistTrackItem.PlaylistGuid = Guid.NewGuid(); if (playback) Dispatcher.Invoke(() => { if (clear) _playbackTrackItems.Clear(); _playbackTrackItems.Add(playlistTrackItem); }); else Dispatcher.Invoke(() => _playlistTrackItems.Add(playlistTrackItem)); return playlistTrackItem; }
private void QueueTrack(Task task, TrackModel trackItem) { switch (task.Status) { case TaskStatus.RanToCompletion: Dispatcher.Invoke(() => { DownloadStatusLabel.Content = string.Empty; Uri thisUri; _streamItems.TryDequeue(out thisUri); trackItem.Cached = IsTrackCached(trackItem.FileName, trackItem.Child); _caching = false; if (trackItem.Source != null) trackItem.Source.Cached = trackItem.Cached; //QueueTrack(thisUri, trackItem); }); break; } }
private void QueueTrackItemForPlayback(TrackModel trackItem, bool stream) { Dispatcher.Invoke(() => { try { StopMusic(); StreamProxy.SetTrackItem(trackItem); string dataSource = stream ? $"http://127.0.0.1:{StreamProxy.GetPort()}/{HttpUtility.UrlEncode(trackItem.FileName, Encoding.UTF8)}" : trackItem.FileName; if (stream) { _position = TimeSpan.FromSeconds(trackItem.Child.Duration); ProgressSlider.Minimum = 0; ProgressSlider.Maximum = _position.TotalMilliseconds; } MediaPlayer.Source = new Uri(dataSource); ProgressSlider.Value = 0; _nowPlayingTrack = trackItem; PlayMusic(); } catch (Exception ex) { MessageBox.Show($"Exception:\n\n{ex.Message}\n{ex.StackTrace}", AppName, MessageBoxButton.OK, MessageBoxImage.Error); } }); }
private void QueueTrack(TrackModel trackItem) { if (_streamItems == null) return; var child = trackItem.Child; var fileNameUri = new Uri(trackItem.FileName); if (_streamItems.All(s => s.OriginalString == trackItem.FileName) && trackItem.Cached) { // Use this to tell Subsonic we're playing back the track, this will result in the server indicating we have cancelled the data transfer, it isn't very nice. //SubsonicClient.StreamAsync(child.Id, trackItem.FileName, _maxBitrate == 0 ? null : (int?) _maxBitrate, null, null, null, null, GetCancellationToken("QueueTrack"), true); QueueTrackItemForPlayback(trackItem, false); if (_showAlbumArt) UpdateAlbumArt(child); } else { if (!_streamItems.Contains(fileNameUri)) _streamItems.Enqueue(fileNameUri); if (_showAlbumArt) UpdateAlbumArt(child); _caching = true; DownloadStatusLabel.Content = $"Caching: {child.Title}"; var streamTask = SubsonicClient.StreamAsync(child.Id, trackItem.FileName, _streamParameters, null, null, null, null, GetCancellationToken("QueueTrack")); QueueTrackItemForPlayback(trackItem, true); streamTask.ContinueWith(t => QueueTrack(t, trackItem)); //if (_useDiskCache) //{ // _caching = true; // DownloadStatusLabel.Content = string.Format("Caching: {0}", child.Title); // SubsonicClient.StreamAsync(child.Id, trackItem.FileName, _maxBitrate == 0 ? null : (int?)_maxBitrate, null, null, null, null, GetCancellationToken("QueueTrack")).ContinueWith(t => QueueTrack(t, trackItem)); //} //else //{ // QueueTrack(new Uri(SubsonicClient.BuildStreamUrl(child.Id)), trackItem); // Works with non-SSL servers //} } }
private void FinalizeCache(Task<long> task, TrackModel trackItem) { Dispatcher.Invoke(() => DownloadStatusLabel.Content = string.Empty); switch (task.Status) { case TaskStatus.RanToCompletion: Dispatcher.Invoke(() => { trackItem.Cached = IsTrackCached(trackItem.FileName, trackItem.Child); if (trackItem.Source != null) trackItem.Source.Cached = trackItem.Cached; _caching = false; }); break; } }
private Track GetLibraryTrack(TrackModel trackModel) { var track = Library.GetTrackByFilename(trackModel.Filename); if (track == null || !File.Exists(track.Filename)) { track = Library .GetTracksByDescription(trackModel.Description) .FirstOrDefault(t => File.Exists(t.Filename)); } return track; }
/// <summary> /// Removes a track. /// </summary> /// <param name="trackToRemove">The track to remove.</param> private void RemoveTrack(TrackModel trackToRemove) { if (trackToRemove == null) return; var tracksToRemove = new[] {trackToRemove}.ToList(); RemoveTracks(tracksToRemove); }