/// <summary> /// Initializes a new instance of the PopularMovieTabViewModel class. /// </summary> /// <param name="applicationService">Application state</param> /// <param name="movieService">Movie service</param> /// <param name="movieHistoryService">Movie history service</param> public PopularMovieTabViewModel(IApplicationService applicationService, IMovieService movieService, IMovieHistoryService movieHistoryService) : base(applicationService, movieService, movieHistoryService) { RegisterMessages(); RegisterCommands(); TabName = LocalizationProviderHelper.GetLocalizedValue <string>("PopularMovieTitleTab"); Movies = new ObservableCollection <MovieJson>(); }
/// <summary> /// When an unhandled exception domain has been thrown, handle it /// </summary> /// <param name="sender"><see cref="App"/> instance</param> /// <param name="e">UnhandledExceptionEventArgs args</param> private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is Exception ex) { Logger.Fatal(ex); Messenger.Default.Send( new UnhandledExceptionMessage( new PopcornException(LocalizationProviderHelper.GetLocalizedValue <string>("FatalError")))); } }
/// <summary> /// Display a dialog on unhandled exception /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event args</param> private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { var ex = e.ExceptionObject as Exception; if (ex != null) { Logger.Fatal(ex); ManageException(new Exception(LocalizationProviderHelper.GetLocalizedValue <string>("FatalError"))); } }
/// <summary> /// Initializes a new instance of the FavoritesMovieTabViewModel class. /// </summary> /// <param name="applicationService">Application state</param> /// <param name="movieService">Movie service</param> /// <param name="userService">Movie history service</param> public FavoritesMovieTabViewModel(IApplicationService applicationService, IMovieService movieService, IUserService userService) : base(applicationService, movieService, userService, () => LocalizationProviderHelper.GetLocalizedValue <string>("FavoritesTitleTab")) { Messenger.Default.Register <ChangeFavoriteMovieMessage>( this, async message => { await LoadMoviesAsync(); }); }
/// <summary> /// Create an instance of <see cref="PagesViewModel"/> /// </summary> /// <param name="moviePage">Movie page</param> /// <param name="animePage">Anime page</param> /// <param name="showPage">Show page</param> public PagesViewModel(MoviePageViewModel moviePage, AnimePageViewModel animePage, ShowPageViewModel showPage) { moviePage.Caption = LocalizationProviderHelper.GetLocalizedValue <string>("MoviesLabel"); animePage.Caption = LocalizationProviderHelper.GetLocalizedValue <string>("AnimesLabel"); showPage.Caption = LocalizationProviderHelper.GetLocalizedValue <string>("ShowsLabel"); Pages = new ObservableCollection <IPageViewModel> { moviePage, showPage, animePage }; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double number = (double)value; double min = 0; double max = 100; // Get the value limits from parameter try { string[] limits = (parameter as string).Split(new char[] { '|' }); min = double.Parse(limits[0], CultureInfo.InvariantCulture); max = double.Parse(limits[1], CultureInfo.InvariantCulture); } catch (Exception) { throw new ArgumentException("Parameter not valid. Enter in format: 'MinDouble|MaxDouble'"); } if (max <= min) { throw new ArgumentException("Parameter not valid. MaxDouble has to be greater then MinDouble."); } if (number >= min && number <= max) { if (number > 8) { return(LocalizationProviderHelper.GetLocalizedValue <string>("VeryGoodLabel")); } if (number > 6) { return(LocalizationProviderHelper.GetLocalizedValue <string>("GoodLabel")); } if (number > 4) { return(LocalizationProviderHelper.GetLocalizedValue <string>("AverageLabel")); } if (number > 2) { return(LocalizationProviderHelper.GetLocalizedValue <string>("BadLabel")); } if (number >= 0) { return(LocalizationProviderHelper.GetLocalizedValue <string>("VeryBadLabel")); } } return(LocalizationProviderHelper.GetLocalizedValue <string>("UnknownLabel")); }
/// <summary> /// Load movie's trailer asynchronously /// </summary> /// <param name="movie">The movie</param> /// <param name="ct">Cancellation token</param> public async Task LoadTrailerAsync(MovieJson movie, CancellationToken ct) { try { var trailer = await _movieService.GetMovieTrailerAsync(movie, ct); var trailerUrl = await _movieService.GetVideoTrailerUrlAsync(trailer.Results.FirstOrDefault()?.Key, ct); if (string.IsNullOrEmpty(trailerUrl)) { Logger.Error( $"Failed loading movie's trailer: {movie.Title}"); Messenger.Default.Send( new ManageExceptionMessage( new Exception( LocalizationProviderHelper.GetLocalizedValue <string>("TrailerNotAvailable")))); Messenger.Default.Send(new StopPlayingTrailerMessage()); return; } if (!ct.IsCancellationRequested) { Logger.Debug( $"Movie's trailer loaded: {movie.Title}"); Messenger.Default.Send(new PlayTrailerMessage(trailerUrl, movie.Title, () => { Messenger.Default.Send(new StopPlayingTrailerMessage()); }, () => { Messenger.Default.Send(new StopPlayingTrailerMessage()); })); } } catch (Exception exception) when(exception is TaskCanceledException) { Logger.Debug( "GetMovieTrailerAsync cancelled."); Messenger.Default.Send(new StopPlayingTrailerMessage()); } catch (Exception exception) { Logger.Error( $"GetMovieTrailerAsync: {exception.Message}"); Messenger.Default.Send( new ManageExceptionMessage( new Exception( LocalizationProviderHelper.GetLocalizedValue <string>( "TrailerNotAvailable")))); Messenger.Default.Send(new StopPlayingTrailerMessage()); } }
/// <summary> /// Register messages /// </summary> private void RegisterMessages() { Messenger.Default.Register <ChangeLanguageMessage>( this, language => { TabName = LocalizationProviderHelper.GetLocalizedValue <string>("FavoritesTitleTab"); }); Messenger.Default.Register <ChangeFavoriteMovieMessage>( this, async message => { await LoadMoviesAsync(); }); }
/// <summary> /// Display download progress /// </summary> private void DisplayDownloadProgress() { if (DownloadProgress >= 2.0) { DisplayText.Text = $"{LocalizationProviderHelper.GetLocalizedValue<string>("CurrentlyPlayingLabel")} : {MovieTitle}"; } else { DisplayText.Text = DownloadRate >= 1000.0 ? $"{LocalizationProviderHelper.GetLocalizedValue<string>("BufferingLabel")} : {Math.Round(DownloadProgress*50.0, 0)} % ({DownloadRate/1000.0} MB/s)" : $"{LocalizationProviderHelper.GetLocalizedValue<string>("BufferingLabel")} : {Math.Round(DownloadProgress*50.0, 0)} % ({DownloadRate} kB/s)"; } }
/// <summary> /// Load movie's trailer asynchronously /// </summary> /// <param name="show">The show</param> /// <param name="ct">Cancellation token</param> public async Task LoadTrailerAsync(ShowJson show, CancellationToken ct) { try { var trailer = await ShowService.GetShowTrailerAsync(show, ct); if (!ct.IsCancellationRequested && string.IsNullOrEmpty(trailer)) { Logger.Error( $"Failed loading show's trailer: {show.Title}"); Messenger.Default.Send( new ManageExceptionMessage( new PopcornException( LocalizationProviderHelper.GetLocalizedValue <string>("TrailerNotAvailable")))); Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Show)); return; } if (!ct.IsCancellationRequested) { Logger.Debug( $"Show's trailer loaded: {show.Title}"); Messenger.Default.Send(new PlayTrailerMessage(trailer, show.Title, () => { Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Show)); }, () => { Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Show)); }, Utils.MediaType.Show)); } } catch (Exception exception) when(exception is TaskCanceledException) { Logger.Debug( "LoadTrailerAsync cancelled."); Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Show)); } catch (Exception exception) { Logger.Error( $"LoadTrailerAsync: {exception.Message}"); Messenger.Default.Send( new ManageExceptionMessage( new PopcornException( LocalizationProviderHelper.GetLocalizedValue <string>( "TrailerNotAvailable")))); Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Show)); } }
private async Task SyncUser() { User = new Models.User.User(); try { var user = await BlobCache.UserAccount.GetObject <Models.User.User>("user"); if (user != null) { User = user; } } catch (Exception) { } if (User.Language == null) { User.Language = new Language(); } if (User.MovieHistory == null) { User.MovieHistory = new List <MovieHistory>(); } if (User.ShowHistory == null) { User.ShowHistory = new List <ShowHistory>(); } if (User.CacheLocation == null) { User.CacheLocation = Path.GetTempPath() + @"Popcorn"; } if (User.DefaultSubtitleSize == null) { User.DefaultSubtitleSize = new SubtitleSize { Size = 26, Label = LocalizationProviderHelper.GetLocalizedValue <string>("Normal") }; } if (string.IsNullOrEmpty(User.DefaultSubtitleColor)) { User.DefaultSubtitleColor = "#FFFFFF"; } }
/// <summary> /// Register commands /// </summary> /// <returns></returns> private void RegisterCommands() { SetFavoriteMovieCommand = new RelayCommand <MovieShort>(async movie => { await MovieHistoryService.SetFavoriteMovieAsync(movie); Messenger.Default.Send(new ChangeFavoriteMovieMessage()); }); ChangeMovieGenreCommand = new RelayCommand <MovieGenre>(genre => Genre = genre.TmdbGenre.Name == LocalizationProviderHelper.GetLocalizedValue <string>( "AllLabel") ? null : genre); }
public SubtitleDialogViewModel(IEnumerable <Subtitle> subtitles, OSDB.Subtitle currentSubtitle) { AvailableSubtitles = new ObservableCollection <Subtitle>(subtitles ?? new List <Subtitle>()); if (currentSubtitle != null) { SelectedSubtitle = AvailableSubtitles.FirstOrDefault(a => a.Sub.LanguageId == currentSubtitle.LanguageId); } else { SelectedSubtitle = AvailableSubtitles.FirstOrDefault(a => a.Sub.LanguageName == LocalizationProviderHelper.GetLocalizedValue <string>( "NoneLabel")); } }
/// <summary> /// Register messages /// </summary> private void RegisterMessages() => Messenger.Default.Register <DownloadMovieMessage>( this, message => { var reportDownloadProgress = new Progress <double>(ReportMovieDownloadProgress); var reportDownloadRate = new Progress <double>(ReportMovieDownloadRate); var reportNbPeers = new Progress <int>(ReportNbPeers); var reportNbSeeders = new Progress <int>(ReportNbSeeders); Task.Run(() => { try { if (message.Movie.SelectedSubtitle != null && message.Movie.SelectedSubtitle.Sub.LanguageName != LocalizationProviderHelper.GetLocalizedValue <string>("NoneLabel")) { var path = Path.Combine(Constants.Subtitles + message.Movie.ImdbCode); Directory.CreateDirectory(path); var subtitlePath = _subtitlesService.DownloadSubtitleToPath(path, message.Movie.SelectedSubtitle.Sub); DispatcherHelper.CheckBeginInvokeOnUI(() => { message.Movie.SelectedSubtitle.FilePath = subtitlePath; }); } } finally { DispatcherHelper.CheckBeginInvokeOnUI(async() => { try { await DownloadMovieAsync(message.Movie, reportDownloadProgress, reportDownloadRate, reportNbSeeders, reportNbPeers, _cancellationDownloadingMovie); } catch (Exception) { } }); } }); });
/// <summary> /// Initializes a new instance of the FavoritesMovieTabViewModel class. /// </summary> /// <param name="applicationService">Application state</param> /// <param name="showService">Show service</param> /// <param name="userService">User service</param> public FavoritesShowTabViewModel(IApplicationService applicationService, IShowService showService, IUserService userService) : base(applicationService, showService, userService, () => LocalizationProviderHelper.GetLocalizedValue <string>("FavoritesTitleTab")) { Messenger.Default.Register <ChangeFavoriteShowMessage>( this, message => { DispatcherHelper.CheckBeginInvokeOnUI(async() => { var movies = await UserService.GetFavoritesShows(Page); MaxNumberOfShows = movies.nbShows; _needSync = true; await LoadShowsAsync(); }); }); }
/// <summary> /// Initializes a new instance of the SeenMovieTabViewModel class. /// </summary> /// <param name="applicationService">Application state</param> /// <param name="movieService">Movie service</param> /// <param name="userService">Movie history service</param> public SeenMovieTabViewModel(IApplicationService applicationService, IMovieService movieService, IUserService userService) : base(applicationService, movieService, userService, () => LocalizationProviderHelper.GetLocalizedValue <string>("SeenTitleTab")) { Messenger.Default.Register <ChangeSeenMovieMessage>( this, message => { DispatcherHelper.CheckBeginInvokeOnUI(async() => { var movies = await UserService.GetSeenMovies(Page); MaxNumberOfMovies = movies.nbMovies; _needSync = true; await LoadMoviesAsync(); }); }); }
/// <summary> /// Load genres asynchronously /// </summary> public async Task LoadGenresAsync() { MovieGenres = new ObservableCollection <MovieGenre>( await _movieService.GetGenresAsync(_cancellationLoadingGenres.Token)); if (_cancellationLoadingGenres.IsCancellationRequested) { return; } MovieGenres?.Insert(0, new MovieGenre { TmdbGenre = new Genre { Id = int.MaxValue, Name = LocalizationProviderHelper.GetLocalizedValue <string>("AllLabel") }, EnglishName = string.Empty }); }
public async Task LoadChromecasts() { try { LoadingChromecasts = true; Chromecasts = new ObservableCollection <IReceiver>(await _chromecastService.FindReceiversAsync()); LoadingChromecasts = false; AnyChromecast = Chromecasts.Any(); ChooseChromecastDeviceCommand = new RelayCommand <IReceiver>(async device => { ConnectingToChromecast = true; _message.ChromecastReceiver = device; _message.CloseCastDialog = OnCloseAction; if (await _chromecastService.ConnectAsync(device)) { await _message.StartCast.Invoke(device); ConnectingToChromecast = false; ConnectedToChromecast = true; } else { LoadingChromecasts = false; ConnectedToChromecast = false; Messenger.Default.Send( new UnhandledExceptionMessage( new PopcornException($"Could not cast to device {device.FriendlyName}"))); } }); } catch (Exception ex) { ConnectedToChromecast = false; LoadingChromecasts = false; AnyChromecast = false; Logger.Error(ex); Messenger.Default.Send( new UnhandledExceptionMessage( new PopcornException(LocalizationProviderHelper.GetLocalizedValue <string>("CastFailed")))); CloseCommand.Execute(null); } }
public SubtitleDialogViewModel(IEnumerable <Subtitle> subtitles, OSDB.Subtitle currentSubtitle) { AvailableSubtitles = new ObservableCollection <Subtitle>(subtitles); if (currentSubtitle != null) { SelectedSubtitle = AvailableSubtitles.FirstOrDefault(a => a.Sub.LanguageId == currentSubtitle.LanguageId); } else { SelectedSubtitle = AvailableSubtitles.FirstOrDefault(a => a.Sub.LanguageName == LocalizationProviderHelper.GetLocalizedValue <string>( "NoneLabel")); } CloseCommand = new RelayCommand(() => { OnCloseAction.Invoke(); }); }
/// <summary> /// Initializes a new instance of the ApplicationSettingsViewModel class. /// </summary> /// <param name="userService">User service</param> /// <param name="subtitlesService">Subtitles service</param> public ApplicationSettingsViewModel(IUserService userService, ISubtitlesService subtitlesService) { _userService = userService; Version = Constants.AppVersion; RefreshCacheSize(); RegisterCommands(); SubtitlesColor = Color.FromRgb(255, 255, 255); Task.Run(async() => { DownloadLimit = await _userService.GetDownloadLimit(); UploadLimit = await _userService.GetUploadLimit(); var defaultSubtitleLanguage = await _userService.GetDefaultSubtitleLanguage(); DefaultHdQuality = await _userService.GetDefaultHdQuality(); try { AvailableSubtitlesLanguages = new ObservableRangeCollection <string>(); var languages = (await subtitlesService.GetSubLanguages()).Select(a => a.LanguageName) .OrderBy(a => a) .ToList(); DispatcherHelper.CheckBeginInvokeOnUI(() => { languages.Insert(0, LocalizationProviderHelper.GetLocalizedValue <string>("NoneLabel")); AvailableSubtitlesLanguages.AddRange( new ObservableRangeCollection <string>(languages)); DefaultSubtitleLanguage = AvailableSubtitlesLanguages.Any(a => a == defaultSubtitleLanguage) ? defaultSubtitleLanguage : LocalizationProviderHelper.GetLocalizedValue <string>("NoneLabel"); }); } catch (Exception ex) { Logger.Error(ex); } }); }
public async Task LoadChromecasts() { try { LoadingChromecasts = true; IChromecastLocator locator = new MdnsChromecastLocator(); Chromecasts = new ObservableCollection <ChromecastReceiver>(await locator.FindReceiversAsync()); LoadingChromecasts = false; AnyChromecast = Chromecasts.Any(); ChooseChromecastDeviceCommand = new RelayCommand <ChromecastReceiver>(device => { ConnectingToChromecast = true; _message.ChromecastReceiver = device; _message.CloseCastDialog = () => { ConnectingToChromecast = false; ConnectedToChromecast = true; CloseCommand.Execute(null); }; Task.Run(async() => { await _message.StartCast.Invoke(device); }); }); } catch (Exception ex) { LoadingChromecasts = false; AnyChromecast = false; Logger.Error(ex); Messenger.Default.Send( new UnhandledExceptionMessage( new PopcornException(LocalizationProviderHelper.GetLocalizedValue <string>("CastFailed")))); CloseCommand.Execute(null); } }
/// <summary> /// Initializes a new instance of the MediaPlayerViewModel class. /// </summary> /// <param name="chromecastService">The Chromecast service</param> /// <param name="subtitlesService"></param> /// <param name="cacheService">Caching service</param> /// <param name="mediaPath">Media path</param> /// <param name="mediaName">Media name</param> /// <param name="type">Media type</param> /// <param name="mediaStoppedAction">Media action to execute when media has been stopped</param> /// <param name="mediaEndedAction">Media action to execute when media has ended</param> /// <param name="playingProgress">Media playing progress</param> /// <param name="bufferProgress">The buffer progress</param> /// <param name="bandwidthRate">THe bandwidth rate</param> /// <param name="currentSubtitle">Subtitle</param> /// <param name="subtitles">Subtitles</param> public MediaPlayerViewModel(IChromecastService chromecastService, ISubtitlesService subtitlesService, ICacheService cacheService, string mediaPath, string mediaName, MediaType type, Action mediaStoppedAction, Action mediaEndedAction, IProgress <double> playingProgress = null, Progress <double> bufferProgress = null, Progress <BandwidthRate> bandwidthRate = null, Subtitle currentSubtitle = null, IEnumerable <Subtitle> subtitles = null) { Logger.Info( $"Loading media : {mediaPath}."); RegisterCommands(); _chromecastService = chromecastService; _chromecastService.StatusChanged += OnCastMediaStatusChanged; _subtitlesService = subtitlesService; _cacheService = cacheService; MediaPath = mediaPath; MediaName = mediaName; MediaType = type; _mediaStoppedAction = mediaStoppedAction; _mediaEndedAction = mediaEndedAction; BufferProgress = bufferProgress; BandwidthRate = bandwidthRate; ShowSubtitleButton = MediaType != MediaType.Trailer; Volume = 1d; _playingProgress = playingProgress; _subtitles = new ObservableCollection <Subtitle>(); if (subtitles != null) { _subtitles = new ObservableCollection <Subtitle>(subtitles); } if (currentSubtitle != null && currentSubtitle.LanguageName != LocalizationProviderHelper.GetLocalizedValue <string>("NoneLabel") && !string.IsNullOrEmpty(currentSubtitle.FilePath)) { CurrentSubtitle = currentSubtitle; } }
/// <summary> /// Initializes a new instance of the SearchMovieTabViewModel class. /// </summary> /// <param name="applicationService">Application state</param> /// <param name="showService">Show service</param> /// <param name="userService">The user service</param> public SearchShowTabViewModel(IApplicationService applicationService, IShowService showService, IUserService userService) : base(applicationService, showService, userService, () => LocalizationProviderHelper.GetLocalizedValue <string>("SearchTitleTab")) { }
/// <summary> /// Initializes a new instance of the RecommendationsMovieTabViewModel class. /// </summary> /// <param name="applicationService">Application state</param> /// <param name="movieService">Movie service</param> /// <param name="userService">Movie history service</param> public RecommendationsMovieTabViewModel(IApplicationService applicationService, IMovieService movieService, IUserService userService) : base(applicationService, movieService, userService, () => LocalizationProviderHelper.GetLocalizedValue <string>("RecommendationsTitleTab")) { }
/// <summary> /// Look for update then download and apply if any /// </summary> private async Task StartUpdateProcessAsync() { var watchStart = Stopwatch.StartNew(); Logger.Info( "Looking for updates..."); try { var updateInfo = await _updateManager.CheckForUpdate(); if (updateInfo == null) { Logger.Error( "Problem while trying to check new updates."); return; } if (updateInfo.ReleasesToApply.Any()) { Logger.Info( $"A new update has been found!\n Currently installed version: {updateInfo.CurrentlyInstalledVersion?.Version?.Version.Major}.{updateInfo.CurrentlyInstalledVersion?.Version?.Version.Minor}.{updateInfo.CurrentlyInstalledVersion?.Version?.Version.Build} - New update: {updateInfo.FutureReleaseEntry?.Version?.Version.Major}.{updateInfo.FutureReleaseEntry?.Version?.Version.Minor}.{updateInfo.FutureReleaseEntry?.Version?.Version.Build}"); await _updateManager.DownloadReleases(updateInfo.ReleasesToApply, x => Logger.Info( $"Downloading new update... {x}%")); await _updateManager.ApplyReleases(updateInfo, x => Logger.Info( $"Applying... {x}%")); Logger.Info( "A new update has been applied."); var releaseInfos = string.Empty; foreach (var releaseInfo in updateInfo.FetchReleaseNotes()) { var info = releaseInfo.Value; var pFrom = info.IndexOf("<p>", StringComparison.InvariantCulture) + "<p>".Length; var pTo = info.LastIndexOf("</p>", StringComparison.InvariantCulture); releaseInfos = string.Concat(releaseInfos, info.Substring(pFrom, pTo - pFrom), Environment.NewLine); } var updateDialog = new UpdateDialog( new UpdateDialogSettings( LocalizationProviderHelper.GetLocalizedValue <string>("NewUpdateLabel"), LocalizationProviderHelper.GetLocalizedValue <string>("NewUpdateDescriptionLabel"), releaseInfos)); await _dialogCoordinator.ShowMetroDialogAsync(this, updateDialog); var updateDialogResult = await updateDialog.WaitForButtonPressAsync(); await _dialogCoordinator.HideMetroDialogAsync(this, updateDialog); if (!updateDialogResult.Restart) { return; } Logger.Info( "Restarting..."); UpdateManager.RestartApp(); } else { Logger.Info( "No update available."); return; } } catch (Exception ex) { Logger.Error( $"Something went wrong when trying to update app. {ex.Message}"); } watchStart.Stop(); var elapsedStartMs = watchStart.ElapsedMilliseconds; Logger.Info( "Finished looking for updates.", elapsedStartMs); }
/// <summary> /// Get subtitles languages /// </summary> /// <returns>Languages</returns> public async Task <IEnumerable <OSDB.Models.Language> > GetSubLanguages() { var retryGetSubLanguagesPolicy = Policy .Handle <Exception>() .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) ); try { return(await retryGetSubLanguagesPolicy.ExecuteAsync(async() => { var osdb = new OsdbClient(); return await osdb.GetSubLanguages(); })); } catch (Exception) { Messenger.Default.Send(new ManageExceptionMessage(new PopcornException(LocalizationProviderHelper.GetLocalizedValue <string>("OpenSubtitlesNotAvailable")))); return(new List <OSDB.Models.Language>()); } }
/// <summary> /// Load movie's trailer asynchronously /// </summary> /// <param name="movie">The movie</param> /// <param name="ct">Cancellation token</param> public async Task LoadTrailerAsync(MovieJson movie, CancellationToken ct) { var timeoutPolicy = Policy.TimeoutAsync(Utils.Constants.DefaultRequestTimeoutInSecond, TimeoutStrategy.Pessimistic); try { await timeoutPolicy.ExecuteAsync(async cancellation => { try { var trailer = await MovieService.GetMovieTrailerAsync(movie, cancellation); if (!cancellation.IsCancellationRequested && string.IsNullOrEmpty(trailer)) { Logger.Error( $"Failed loading movie's trailer: {movie.Title}"); Messenger.Default.Send( new ManageExceptionMessage( new TrailerNotAvailableException( LocalizationProviderHelper.GetLocalizedValue <string>("TrailerNotAvailable")))); Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie)); return; } if (!cancellation.IsCancellationRequested) { Logger.Info( $"Movie's trailer loaded: {movie.Title}"); Messenger.Default.Send(new PlayTrailerMessage(trailer, movie.Title, () => { Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie)); }, () => { Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie)); }, Utils.MediaType.Movie)); } } catch (Exception exception) when(exception is TaskCanceledException) { Logger.Debug( "GetMovieTrailerAsync cancelled."); Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie)); } catch (Exception exception) { Logger.Error( $"GetMovieTrailerAsync: {exception.Message}"); Messenger.Default.Send( new ManageExceptionMessage( new TrailerNotAvailableException( LocalizationProviderHelper.GetLocalizedValue <string>( "TrailerNotAvailable")))); Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie)); } }, ct); } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Register messages /// </summary> private void RegisterMessages() { Messenger.Default.Register <ChangeLanguageMessage>( this, language => { TabName = LocalizationProviderHelper.GetLocalizedValue <string>("RecentTitleTab"); }); }
/// <summary> /// Initializes a new instance of the RecentTabViewModel class. /// </summary> public RecentTabViewModel() { RegisterMessages(); RegisterCommands(); TabName = LocalizationProviderHelper.GetLocalizedValue <string>("RecentTitleTab"); }
/// <summary> /// Initialize a new instance of DownloadMovieProgress /// </summary> public DownloadMovieProgress() { InitializeComponent(); DisplayText.Text = $"{LocalizationProviderHelper.GetLocalizedValue<string>("BufferingLabel")} : {Math.Round(DownloadProgress * 50, 0)} % ({DownloadRate} kB/s)"; }