public void exportSubscriptions() { List <PodcastSubscriptionModel> subscriptions = App.mainViewModels.PodcastSubscriptions.ToList(); if (subscriptions.Count == 0) { MessageBox.Show("No subscriptions to export."); return; } using (var db = new PodcastSqlModel()) { if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportToSkyDrive) { if (liveConnect == null) { loginUserToSkyDrive(); } else { DoOPMLExport(); } } else if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportViaEmail) { DoOPMLExport(); } } }
private void startNewPlayback(PodcastEpisodeModel episodeModel, bool streaming) { m_currentPlayerEpisode = episodeModel; setupPlayerUIContent(episodeModel); updatePrimary(episodeModel); if (episodeModel.SavedPlayPos > 0) { bool alwaysContinuePlayback = false; using (var db = new PodcastSqlModel()) { alwaysContinuePlayback = db.settings().IsAutomaticContinuedPlayback; } if (alwaysContinuePlayback) { startPlayback(episodeModel, new TimeSpan(episodeModel.SavedPlayPos), streaming); } else { askForContinueEpisodePlaying(episodeModel, streaming); } } else { startPlayback(episodeModel, TimeSpan.Zero, streaming); } }
public void removeFromPlayqueue(int itemId) { using (var db = new PlaylistDBContext()) { PlaylistItem itemToRemove = db.Playlist.FirstOrDefault(item => item.ItemId == itemId); if (itemToRemove != null) { PodcastEpisodeModel episode = null; using (var episodeDb = new PodcastSqlModel()) { episode = episodeDb.episodeForPlaylistItem(itemToRemove); if (episode != null) { if (episode.isListened()) { episode.markAsListened(episodeDb.settings().IsAutoDelete); } } else { Debug.WriteLine("Warning: Could not get episode for item id: " + itemToRemove.ItemId); } } db.Playlist.DeleteOnSubmit(itemToRemove); db.SubmitChanges(); App.mainViewModels.PlayQueue = new ObservableCollection <PlaylistItem>(); } } }
private void ExportSubscriptionsMenuItem_Click(object sender, EventArgs e) { String exportNotificationText = ""; using (var db = new PodcastSqlModel()) { if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportToSkyDrive) { exportNotificationText = "This will export your podcast subscriptions information in OPML format to your SkyDrive account. Do you want to continue?"; } else if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportViaEmail) { exportNotificationText = "This will export your podcast subscriptions information in OPML format via email. Do you want to continue?"; } } if (MessageBox.Show(exportNotificationText, "Export subscriptions in OPML format", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { PodcastSubscriptionsManager.getInstance().exportSubscriptions(); } }
private void PlayOrderChanged(object sender, SelectionChangedEventArgs e) { ListPickerItem selectedItem = (sender as ListPicker).SelectedItem as ListPickerItem; if (selectedItem == null) { return; } using (var db = new PodcastSqlModel()) { PodcastPlaybackManager.getInstance().sortPlaylist(db.settings().PlaylistSortOrder); } }
public void addToPlayqueue(PodcastEpisodeModel episode, bool showNotification = true) { using (var db = new PlaylistDBContext()) { addToPlayqueue(episode, db); db.SubmitChanges(); } using (var db = new PodcastSqlModel()) { sortPlaylist(db.settings().PlaylistSortOrder); } if (showNotification) { showAddedNotification(1); } }
internal static PodcastEpisodeModel refreshEpisodeFromAudioAgent(PodcastEpisodeModel episode) { List <PlaylistItem> playlistItems = null; using (var playlistdb = new PlaylistDBContext()) { playlistItems = playlistdb.Playlist.ToList(); } PodcastEpisodeModel e = null; using (var db = new PodcastSqlModel()) { e = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == episode.EpisodeId); bool deleteListened = false; if (playlistItems.Count > 0) { deleteListened = db.settings().IsAutoDelete; } foreach (PlaylistItem i in playlistItems) { if (i.EpisodeId != episode.EpisodeId) { continue; } Debug.WriteLine("Updating episode '" + e.EpisodeName + "' playpos to: " + i.SavedPlayPosTick); e.SavedPlayPos = i.SavedPlayPosTick; // Update play state to listened as appropriate. if (e.isListened()) { e.markAsListened(deleteListened); } db.SubmitChanges(); } } return(e); }
public void addToPlayqueue(Collection <PodcastEpisodeModel> episodes) { using (var db = new PlaylistDBContext()) { foreach (PodcastEpisodeModel e in episodes) { addToPlayqueue(e, db); } db.SubmitChanges(); } using (var db = new PodcastSqlModel()) { sortPlaylist(db.settings().PlaylistSortOrder); } App.mainViewModels.PlayQueue = new ObservableCollection <PlaylistItem>(); showAddedNotification(episodes.Count); }
public void cleanListenedEpisodes(PodcastSubscriptionModel podcastSubscriptionModel) { using (var db = new PodcastSqlModel()) { float listenedEpisodeThreshold = 0.0F; listenedEpisodeThreshold = (float)db.settings().ListenedThreashold / (float)100.0; var queryDelEpisodes = db.Episodes.Where(episode => episode.PodcastId == podcastSubscriptionModel.PodcastId).AsEnumerable() .Where(ep => (ep.EpisodePlayState == PodcastEpisodeModel.EpisodePlayStateEnum.Listened || (ep.EpisodeFile != "" && ((ep.TotalLengthTicks > 0 && ep.SavedPlayPos > 0) && ((float)((float)ep.SavedPlayPos / (float)ep.TotalLengthTicks) > listenedEpisodeThreshold)))) ).AsEnumerable(); foreach (var episode in queryDelEpisodes) { episode.deleteDownloadedEpisode(); } } }
private void MenuItemMarkAsListened_Click(object sender, RoutedEventArgs e) { PodcastEpisodeModel podcastEpisode = this.DataContext as PodcastEpisodeModel; PodcastSubscriptionModel subscription = null; // We need this to update the play states for this subscription. bool delete = false; using (var db = new PodcastSqlModel()) { PodcastEpisodeModel sqlepisode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == podcastEpisode.EpisodeId); subscription = db.Subscriptions.FirstOrDefault(sub => sub.PodcastId == sqlepisode.PodcastId); PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(subscription); delete = db.settings().IsAutoDelete; sqlepisode.SavedPlayPos = 0; sqlepisode.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Listened; db.SubmitChanges(); } podcastEpisode.markAsListened(delete); }
private void completePodcastDownload(BackgroundTransferRequest transferRequest) { // If the status code of a completed transfer is 200 or 206, the // transfer was successful if (transferRequest.TransferError == null && (transferRequest.StatusCode == 200 || transferRequest.StatusCode == 206)) { Debug.WriteLine("Transfer request completed succesfully."); updateEpisodeWhenDownloaded(m_currentEpisodeDownload); // Add downloaded episode to play queue, if set. using (var db = new PodcastSqlModel()) { if (db.settings().IsAddDownloadsToPlayQueue) { PodcastPlaybackManager.getInstance().addSilentlyToPlayqueue(m_currentEpisodeDownload); } } } else { Debug.WriteLine("Transfer request completed with error code: " + transferRequest.StatusCode + ", " + transferRequest.TransferError); switch (transferRequest.StatusCode) { case 0: Debug.WriteLine("Request canceled."); break; // If error code is 200 but we still got an error, this means the max. transfer size exceeded. // This is because the podcast feed announced a different download size than what the file actually is. // If user wants, we can try again with larger file download size policy. case 200: Debug.WriteLine("Maxiumum download size exceeded. Shall we try again?"); if (MessageBox.Show("Podcast feed announced wrong file size. Do you want to download again with larger file download settings?", "Podcast download failed", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { if (MessageBox.Show("Please connect your phone to an external power source and to a WiFi network.", "Attention", MessageBoxButton.OK) == MessageBoxResult.OK) { Debug.WriteLine("Download the same episode again, with preferences None."); // We download the same file again, but this time we force the TransferPrefernces to be None. startNextEpisodeDownload(TransferPreferences.None); return; } } break; case 301: App.showErrorToast("WP8 cannot download from this location."); break; default: App.showErrorToast("Could not download the episode\nfrom the server."); break; } if (m_currentEpisodeDownload != null) { m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle; m_currentEpisodeDownload.deleteDownloadedEpisode(); } } saveEpisodeInfoToDB(m_currentEpisodeDownload); cleanupEpisodeDownload(transferRequest); // And start a next round of downloading. startNextEpisodeDownload(); }
private void startNewPlayback(PodcastEpisodeModel episodeModel, bool streaming) { m_currentPlayerEpisode = episodeModel; setupPlayerUIContent(episodeModel); updatePrimary(episodeModel); if (episodeModel.SavedPlayPos > 0) { bool alwaysContinuePlayback = false; using (var db = new PodcastSqlModel()) { alwaysContinuePlayback = db.settings().IsAutomaticContinuedPlayback; } if (alwaysContinuePlayback) { startPlayback(episodeModel, new TimeSpan(episodeModel.SavedPlayPos), streaming); } else { askForContinueEpisodePlaying(episodeModel, streaming); } } else { startPlayback(episodeModel, TimeSpan.Zero, streaming); } }
private void DoOPMLExport() { String dateCreated = DateTime.Now.ToString("r"); String opmlExportFileName = String.Format("PodcatcherSubscriptions_{0}.opml.xml", DateTime.Now.ToString("dd_MM_yyyy")); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(opmlExportFileName, FileMode.Create, myIsolatedStorage); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(isoStream, settings)) { /** OPML root */ writer.WriteStartElement("opml"); writer.WriteAttributeString("version", "2.0"); /** Head */ writer.WriteStartElement("head"); // title writer.WriteStartElement("title"); writer.WriteString("My subscriptions from Podcatcher"); writer.WriteEndElement(); // dateCreated writer.WriteStartElement("dateCreated"); writer.WriteString(dateCreated); writer.WriteEndElement(); /** End Head */ writer.WriteEndElement(); /** Body */ writer.WriteStartElement("body"); // Each outline List<PodcastSubscriptionModel> subscriptions = App.mainViewModels.PodcastSubscriptions.ToList(); foreach (PodcastSubscriptionModel s in subscriptions) { writer.WriteStartElement("outline"); writer.WriteAttributeString("title", s.PodcastName); writer.WriteAttributeString("xmlUrl", s.PodcastRSSUrl); writer.WriteAttributeString("type", "rss"); writer.WriteAttributeString("text", s.PodcastDescription); writer.WriteEndElement(); } /** End Body */ writer.WriteEndElement(); // Finish the document writer.WriteEndDocument(); writer.Flush(); } isoStream.Seek(0, SeekOrigin.Begin); using (var db = new PodcastSqlModel()) { if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportToOneDrive) { SubscriptionManagerArgs args = new SubscriptionManagerArgs(); args.state = SubscriptionsState.StartedOneDriveExport; OnOPMLExportToOneDriveChanged(this, args); exportToOneDrive(opmlExportFileName, isoStream); } else if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportViaEmail) { exportViaEmail(isoStream); } } } }
public void cleanListenedEpisodes(PodcastSubscriptionModel podcastSubscriptionModel) { using (var db = new PodcastSqlModel()) { float listenedEpisodeThreshold = 0.0F; listenedEpisodeThreshold = (float)db.settings().ListenedThreashold / (float)100.0; var queryDelEpisodes = db.Episodes.Where(episode => episode.PodcastId == podcastSubscriptionModel.PodcastId).AsEnumerable() .Where(ep => (ep.EpisodePlayState == PodcastEpisodeModel.EpisodePlayStateEnum.Listened || (ep.EpisodeFile != "" && ((ep.TotalLengthTicks > 0 && ep.SavedPlayPos > 0) && ((float)((float)ep.SavedPlayPos / (float)ep.TotalLengthTicks) > listenedEpisodeThreshold)))) ).AsEnumerable(); foreach (var episode in queryDelEpisodes) { episode.deleteDownloadedEpisode(); } } }
private void DoOPMLExport() { String dateCreated = DateTime.Now.ToString("r"); String opmlExportFileName = String.Format("PodcatcherSubscriptions_{0}.opml.xml", DateTime.Now.ToString("dd_MM_yyyy")); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(opmlExportFileName, FileMode.Create, myIsolatedStorage); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(isoStream, settings)) { /** OPML root */ writer.WriteStartElement("opml"); writer.WriteAttributeString("version", "2.0"); /** Head */ writer.WriteStartElement("head"); // title writer.WriteStartElement("title"); writer.WriteString("My subscriptions from Podcatcher"); writer.WriteEndElement(); // dateCreated writer.WriteStartElement("dateCreated"); writer.WriteString(dateCreated); writer.WriteEndElement(); /** End Head */ writer.WriteEndElement(); /** Body */ writer.WriteStartElement("body"); // Each outline List <PodcastSubscriptionModel> subscriptions = App.mainViewModels.PodcastSubscriptions.ToList(); foreach (PodcastSubscriptionModel s in subscriptions) { writer.WriteStartElement("outline"); writer.WriteAttributeString("title", s.PodcastName); writer.WriteAttributeString("xmlUrl", s.PodcastRSSUrl); writer.WriteAttributeString("type", "rss"); writer.WriteAttributeString("text", s.PodcastDescription); writer.WriteEndElement(); } /** End Body */ writer.WriteEndElement(); // Finish the document writer.WriteEndDocument(); writer.Flush(); } isoStream.Seek(0, SeekOrigin.Begin); using (var db = new PodcastSqlModel()) { if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportToOneDrive) { SubscriptionManagerArgs args = new SubscriptionManagerArgs(); args.state = SubscriptionsState.StartedOneDriveExport; OnOPMLExportToOneDriveChanged(this, args); exportToOneDrive(opmlExportFileName, isoStream); } else if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportViaEmail) { exportViaEmail(isoStream); } } } }
internal static PodcastEpisodeModel refreshEpisodeFromAudioAgent(PodcastEpisodeModel episode) { List<PlaylistItem> playlistItems = null; using (var playlistdb = new PlaylistDBContext()) { playlistItems = playlistdb.Playlist.ToList(); } PodcastEpisodeModel e = null; using (var db = new PodcastSqlModel()) { e = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == episode.EpisodeId); bool deleteListened = false; if (playlistItems.Count > 0) { deleteListened = db.settings().IsAutoDelete; } foreach (PlaylistItem i in playlistItems) { if (i.EpisodeId != episode.EpisodeId) { continue; } Debug.WriteLine("Updating episode '" + e.EpisodeName + "' playpos to: " + i.SavedPlayPosTick); e.SavedPlayPos = i.SavedPlayPosTick; // Update play state to listened as appropriate. if (e.isListened()) { e.markAsListened(deleteListened); } db.SubmitChanges(); } } return e; }
private void startNextEpisodeDownload(TransferPreferences useTransferPreferences = TransferPreferences.AllowCellularAndBattery) { if (BackgroundTransferService.Requests.Count() > 0) { // For some reason there are still old requests in the background transfer service. // Let's clean everything and start over. foreach (BackgroundTransferRequest t in BackgroundTransferService.Requests.AsEnumerable()) { BackgroundTransferService.Remove(t); } } if (m_episodeDownloadQueue.Count > 0) { m_currentEpisodeDownload = m_episodeDownloadQueue.Peek(); Uri downloadUri; try { downloadUri = new Uri(m_currentEpisodeDownload.EpisodeDownloadUri, UriKind.Absolute); } catch (Exception e) { App.showErrorToast("Cannot download the episode."); Debug.WriteLine("Cannot download the episode. URI exception: " + e.Message); m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle; m_episodeDownloadQueue.Dequeue(); saveEpisodeInfoToDB(m_currentEpisodeDownload); startNextEpisodeDownload(); return; } m_currentEpisodeDownload.EpisodeFile = generateLocalEpisodeFileName(m_currentEpisodeDownload); if (string.IsNullOrEmpty(m_currentEpisodeDownload.EpisodeFile)) { App.showErrorToast("Cannot download the episode."); Debug.WriteLine("Cannot download the episode. Episode file name is null or empty."); m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle; m_episodeDownloadQueue.Dequeue(); saveEpisodeInfoToDB(m_currentEpisodeDownload); startNextEpisodeDownload(); return; } // Create a new background transfer request for the podcast episode download. m_currentBackgroundTransfer = new BackgroundTransferRequest(downloadUri, new Uri(m_currentEpisodeDownload.EpisodeFile, UriKind.Relative)); if (useTransferPreferences == TransferPreferences.None) { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.None; } else if (canAllowCellularDownload(m_currentEpisodeDownload)) { bool settingsAllowCellular = false; using (var db = new PodcastSqlModel()) { settingsAllowCellular = db.settings().IsUseCellularData; } Debug.WriteLine("Settings: Allow cellular download: " + settingsAllowCellular); if (settingsAllowCellular && canDownloadOverCellular()) { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.AllowCellularAndBattery; } else { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.AllowBattery; } } else { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.None; } Debug.WriteLine("m_currentBackgroundTransfer.TransferPreferences = " + m_currentBackgroundTransfer.TransferPreferences.ToString()); m_currentBackgroundTransfer.TransferStatusChanged += new EventHandler <BackgroundTransferEventArgs>(backgroundTransferStatusChanged); // Store request to the episode. m_currentEpisodeDownload.DownloadRequest = m_currentBackgroundTransfer; m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID); m_applicationSettings.Add(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID, m_currentEpisodeDownload.EpisodeId); m_applicationSettings.Save(); try { BackgroundTransferService.Add(m_currentBackgroundTransfer); } catch (InvalidOperationException) { foreach (BackgroundTransferRequest r in BackgroundTransferService.Requests) { BackgroundTransferService.Remove(r); } BackgroundTransferService.Add(m_currentBackgroundTransfer); } } }
private void completePodcastDownload(BackgroundTransferRequest transferRequest) { // If the status code of a completed transfer is 200 or 206, the // transfer was successful if (transferRequest.TransferError == null && (transferRequest.StatusCode == 200 || transferRequest.StatusCode == 206)) { Debug.WriteLine("Transfer request completed succesfully."); updateEpisodeWhenDownloaded(m_currentEpisodeDownload); // Add downloaded episode to play queue, if set. using (var db = new PodcastSqlModel()) { if (db.settings().IsAddDownloadsToPlayQueue) { PodcastPlaybackManager.getInstance().addSilentlyToPlayqueue(m_currentEpisodeDownload); } } } else { Debug.WriteLine("Transfer request completed with error code: " + transferRequest.StatusCode + ", " + transferRequest.TransferError); switch (transferRequest.StatusCode) { case 0: Debug.WriteLine("Request canceled."); break; // If error code is 200 but we still got an error, this means the max. transfer size exceeded. // This is because the podcast feed announced a different download size than what the file actually is. // If user wants, we can try again with larger file download size policy. case 200: Debug.WriteLine("Maxiumum download size exceeded. Shall we try again?"); if (MessageBox.Show("Podcast feed announced wrong file size. Do you want to download again with larger file download settings?", "Podcast download failed", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { if (MessageBox.Show("Please connect your phone to an external power source and to a WiFi network.", "Attention", MessageBoxButton.OK) == MessageBoxResult.OK) { Debug.WriteLine("Download the same episode again, with preferences None."); // We download the same file again, but this time we force the TransferPrefernces to be None. startNextEpisodeDownload(TransferPreferences.None); return; } } break; case 301: App.showErrorToast("WP8 cannot download from this location."); break; default: App.showErrorToast("Could not download the episode\nfrom the server."); break; } if (m_currentEpisodeDownload != null) { m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle; m_currentEpisodeDownload.deleteDownloadedEpisode(); } } saveEpisodeInfoToDB(m_currentEpisodeDownload); cleanupEpisodeDownload(transferRequest); // And start a next round of downloading. startNextEpisodeDownload(); }
private void PlayStateChanged(object sender, EventArgs e) { EventHandler handlerStoppedPlaying = null; switch (BackgroundAudioPlayer.Instance.PlayerState) { case PlayState.Playing: PodcastEpisodeModel currentEpisode = updateCurrentlyPlayingEpisode(); if (currentEpisode == null) { Debug.WriteLine("Error: No playing episode in DB."); return; } if (CurrentlyPlayingEpisode == null) { CurrentlyPlayingEpisode = currentEpisode; } else if (currentEpisode.EpisodeId != CurrentlyPlayingEpisode.EpisodeId) { CurrentlyPlayingEpisode = currentEpisode; CurrentlyPlayingEpisode.setPlaying(); } if (CurrentlyPlayingEpisode.TotalLengthTicks == 0) { CurrentlyPlayingEpisode.TotalLengthTicks = BackgroundAudioPlayer.Instance.Track.Duration.Ticks; using (var db = new PodcastSqlModel()) { PodcastEpisodeModel episode = db.episodeForEpisodeId(CurrentlyPlayingEpisode.EpisodeId); if (episode == null) { Debug.WriteLine("Warning: Got NULL episode from DB when trying to update this episode."); return; } episode.TotalLengthTicks = CurrentlyPlayingEpisode.TotalLengthTicks; db.SubmitChanges(); PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(episode.PodcastSubscription); } } break; case PlayState.Paused: BackgroundAudioPlayer playerPaused = BackgroundAudioPlayer.Instance; if (CurrentlyPlayingEpisode != null) { CurrentlyPlayingEpisode = App.refreshEpisodeFromAudioAgent(CurrentlyPlayingEpisode); CurrentlyPlayingEpisode.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Paused; using (var db = new PodcastSqlModel()) { PodcastEpisodeModel updatedEpisode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == CurrentlyPlayingEpisode.EpisodeId); updatedEpisode.EpisodePlayState = CurrentlyPlayingEpisode.EpisodePlayState; db.SubmitChanges(); } handlerStoppedPlaying = OnPodcastStoppedPlaying; if (handlerStoppedPlaying != null) { OnPodcastStoppedPlaying(this, new EventArgs()); } } else { Debug.WriteLine("SHOULD NOT HAPPEND! Cannot save episode state to paused!"); } break; case PlayState.Stopped: case PlayState.Shutdown: case PlayState.TrackEnded: if (CurrentlyPlayingEpisode == null) { // We didn't have a track playing. return; } // F**K YOU WINDOWS PHONE!! /** * This is so horrible that I can't find other words to describe how bad the BackgroundAudioPlayer * is in Windows Phone! * * First of all the events are fired totally differently between Windows Phone 7 and Windows Phone 8. * Secondly the events related to when tracks end arae totally wrong and horrible! Let me explain: * - We get here the PlayState.Stopped event when the track ends. * - We get the event here BEFORE the AudioAgent gets any events. * - AudioAgent correctly gets the PlayState.TrackEnded event, but it gets it after we have received the * event here. * - We NEVER get the the PlayState.TrackEnded event here. * - Which is not the case for Windows Phone 7, because it first fires PlayState.TrackEnded. * * So this code here is a horrible kludge that just guesses that Windows Phone means "track did end" * when the state is stopped and the play position is still 0. * * Johan, when you return from the future to this piece of code, don't even try to change it or "fix it". **/ long playpos = 0; if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.TrackEnded) { playpos = CurrentlyPlayingEpisode.TotalLengthTicks; } else if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Stopped && BackgroundAudioPlayer.Instance.Position.Ticks == 0) { playpos = CurrentlyPlayingEpisode.TotalLengthTicks; } else { try { playpos = BackgroundAudioPlayer.Instance.Position.Ticks; } catch (Exception) { Debug.WriteLine("Warning: Player didn't return us a play pos!"); } } CurrentlyPlayingEpisode.SavedPlayPos = playpos; CurrentlyPlayingEpisode.setNoPlaying(); using (var db = new PodcastSqlModel()) { PodcastEpisodeModel savingEpisode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == CurrentlyPlayingEpisode.EpisodeId); if (savingEpisode != null) { savingEpisode.SavedPlayPos = CurrentlyPlayingEpisode.SavedPlayPos; // Update play state to listened as appropriate. if (savingEpisode.isListened()) { savingEpisode.markAsListened(db.settings().IsAutoDelete); removeFromPlayqueue(savingEpisode); } else { savingEpisode.EpisodePlayState = CurrentlyPlayingEpisode.EpisodePlayState; } db.SubmitChanges(); PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(savingEpisode.PodcastSubscription); } } PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(CurrentlyPlayingEpisode.PodcastSubscriptionInstance); handlerStoppedPlaying = OnPodcastStoppedPlaying; if (handlerStoppedPlaying != null) { OnPodcastStoppedPlaying(this, new EventArgs()); } // Cleanup CurrentlyPlayingEpisode = null; break; case PlayState.TrackReady: break; case PlayState.Unknown: // Unknown? WTF. break; } App.mainViewModels.PlayQueue = new System.Collections.ObjectModel.ObservableCollection<PlaylistItem>(); if (CurrentlyPlayingEpisode != null) { PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(CurrentlyPlayingEpisode.PodcastSubscriptionInstance); } }
public void addToPlayqueue(PodcastEpisodeModel episode, bool showNotification = true) { using (var db = new PlaylistDBContext()) { addToPlayqueue(episode, db); db.SubmitChanges(); } using (var db = new PodcastSqlModel()) { sortPlaylist(db.settings().PlaylistSortOrder); } if (showNotification) { showAddedNotification(1); } }
private void PlayOrderChanged(object sender, SelectionChangedEventArgs e) { ListPickerItem selectedItem = (sender as ListPicker).SelectedItem as ListPickerItem; if (selectedItem == null) { return; } using (var db = new PodcastSqlModel()) { PodcastPlaybackManager.getInstance().sortPlaylist(db.settings().PlaylistSortOrder); } }
private void ExportSubscriptionsMenuItem_Click(object sender, EventArgs e) { String exportNotificationText = ""; using (var db = new PodcastSqlModel()) { if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportToOneDrive) { exportNotificationText = "This will export your podcast subscriptions information in OPML format to your OneDrive account. Do you want to continue?"; } else if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportViaEmail) { exportNotificationText = "This will export your podcast subscriptions information in OPML format via email. Do you want to continue?"; } } if (MessageBox.Show(exportNotificationText, "Export subscriptions in OPML format", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { PodcastSubscriptionsManager.getInstance().exportSubscriptions(); } }
public static void refreshEpisodesFromAudioAgent() { Debug.WriteLine("Refreshing episode information that has been updated from AudioPlayer."); using (var playlistdb = new PlaylistDBContext()) { int playlistItemsCount = 0; int listenedItemsCount = 0; List<PlaylistItem> playlistItems = playlistdb.Playlist.ToList(); playlistItemsCount = playlistItems.Count; using (var db = new PodcastSqlModel()) { bool deleteListened = false; if (playlistItems.Count > 0) { deleteListened = db.settings().IsAutoDelete; } foreach (PlaylistItem i in playlistItems) { PodcastEpisodeModel e = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == i.EpisodeId); if (e == null) { Debug.WriteLine("Warning: Could not fetch episode with ID: " + i.EpisodeId); continue; } if (i.SavedPlayPosTick > 0) { Debug.WriteLine("Updating episode '" + e.EpisodeName + "' playpos to: " + i.SavedPlayPosTick); e.SavedPlayPos = i.SavedPlayPosTick; try { db.SubmitChanges(); } catch (ChangeConflictException) { Debug.WriteLine("ChangeConflictException: Could not submit changes"); } // Update play state to listened as appropriate. if (e.isListened()) { e.markAsListened(deleteListened); PodcastPlaybackManager.getInstance().removeFromPlayqueue(e); listenedItemsCount++; } e.PodcastSubscription.reloadPartiallyPlayedEpisodes(); e.PodcastSubscription.reloadUnplayedPlayedEpisodes(); } } } // If all items in the play queue were listened, then we shouldn't show an episodep laying anymore. if (playlistItemsCount == listenedItemsCount) { PodcastPlaybackManager.getInstance().CurrentlyPlayingEpisode = null; } } }
private void startNextEpisodeDownload(TransferPreferences useTransferPreferences = TransferPreferences.AllowCellularAndBattery) { if (BackgroundTransferService.Requests.Count() > 0) { // For some reason there are still old requests in the background transfer service. // Let's clean everything and start over. foreach (BackgroundTransferRequest t in BackgroundTransferService.Requests.AsEnumerable()) { BackgroundTransferService.Remove(t); } } if (m_episodeDownloadQueue.Count > 0) { m_currentEpisodeDownload = m_episodeDownloadQueue.Peek(); Uri downloadUri; try { downloadUri = new Uri(m_currentEpisodeDownload.EpisodeDownloadUri, UriKind.Absolute); } catch (Exception e) { App.showErrorToast("Cannot download the episode."); Debug.WriteLine("Cannot download the episode. URI exception: " + e.Message); m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle; m_episodeDownloadQueue.Dequeue(); saveEpisodeInfoToDB(m_currentEpisodeDownload); startNextEpisodeDownload(); return; } m_currentEpisodeDownload.EpisodeFile = generateLocalEpisodeFileName(m_currentEpisodeDownload); if (string.IsNullOrEmpty(m_currentEpisodeDownload.EpisodeFile)) { App.showErrorToast("Cannot download the episode."); Debug.WriteLine("Cannot download the episode. Episode file name is null or empty."); m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle; m_episodeDownloadQueue.Dequeue(); saveEpisodeInfoToDB(m_currentEpisodeDownload); startNextEpisodeDownload(); return; } // Create a new background transfer request for the podcast episode download. m_currentBackgroundTransfer = new BackgroundTransferRequest(downloadUri, new Uri(m_currentEpisodeDownload.EpisodeFile, UriKind.Relative)); if (useTransferPreferences == TransferPreferences.None) { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.None; } else if (canAllowCellularDownload(m_currentEpisodeDownload)) { bool settingsAllowCellular = false; using (var db = new PodcastSqlModel()) { settingsAllowCellular = db.settings().IsUseCellularData; } Debug.WriteLine("Settings: Allow cellular download: " + settingsAllowCellular); if (settingsAllowCellular && canDownloadOverCellular()) { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.AllowCellularAndBattery; } else { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.AllowBattery; } } else { m_currentBackgroundTransfer.TransferPreferences = TransferPreferences.None; } Debug.WriteLine("m_currentBackgroundTransfer.TransferPreferences = " + m_currentBackgroundTransfer.TransferPreferences.ToString()); m_currentBackgroundTransfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(backgroundTransferStatusChanged); // Store request to the episode. m_currentEpisodeDownload.DownloadRequest = m_currentBackgroundTransfer; m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID); m_applicationSettings.Add(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID, m_currentEpisodeDownload.EpisodeId); m_applicationSettings.Save(); try { BackgroundTransferService.Add(m_currentBackgroundTransfer); } catch (InvalidOperationException) { foreach (BackgroundTransferRequest r in BackgroundTransferService.Requests) { BackgroundTransferService.Remove(r); } BackgroundTransferService.Add(m_currentBackgroundTransfer); } } }
public void addToPlayqueue(Collection<PodcastEpisodeModel> episodes) { using (var db = new PlaylistDBContext()) { foreach (PodcastEpisodeModel e in episodes) { addToPlayqueue(e, db); } db.SubmitChanges(); } using (var db = new PodcastSqlModel()) { sortPlaylist(db.settings().PlaylistSortOrder); } App.mainViewModels.PlayQueue = new ObservableCollection<PlaylistItem>(); showAddedNotification(episodes.Count); }
public static void refreshEpisodesFromAudioAgent() { Debug.WriteLine("Refreshing episode information that has been updated from AudioPlayer."); using (var playlistdb = new PlaylistDBContext()) { int playlistItemsCount = 0; int listenedItemsCount = 0; List <PlaylistItem> playlistItems = playlistdb.Playlist.ToList(); playlistItemsCount = playlistItems.Count; using (var db = new PodcastSqlModel()) { bool deleteListened = false; if (playlistItems.Count > 0) { deleteListened = db.settings().IsAutoDelete; } foreach (PlaylistItem i in playlistItems) { PodcastEpisodeModel e = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == i.EpisodeId); if (e == null) { Debug.WriteLine("Warning: Could not fetch episode with ID: " + i.EpisodeId); continue; } if (i.SavedPlayPosTick > 0) { Debug.WriteLine("Updating episode '" + e.EpisodeName + "' playpos to: " + i.SavedPlayPosTick); e.SavedPlayPos = i.SavedPlayPosTick; try { db.SubmitChanges(); } catch (ChangeConflictException) { Debug.WriteLine("ChangeConflictException: Could not submit changes"); } // Update play state to listened as appropriate. if (e.isListened()) { e.markAsListened(deleteListened); PodcastPlaybackManager.getInstance().removeFromPlayqueue(e); listenedItemsCount++; } e.PodcastSubscription.reloadPartiallyPlayedEpisodes(); e.PodcastSubscription.reloadUnplayedPlayedEpisodes(); } } } // If all items in the play queue were listened, then we shouldn't show an episodep laying anymore. if (playlistItemsCount == listenedItemsCount) { PodcastPlaybackManager.getInstance().CurrentlyPlayingEpisode = null; } } }
public void removeFromPlayqueue(int itemId) { using (var db = new PlaylistDBContext()) { PlaylistItem itemToRemove = db.Playlist.FirstOrDefault(item => item.ItemId == itemId); if (itemToRemove != null) { PodcastEpisodeModel episode = null; using (var episodeDb = new PodcastSqlModel()) { episode = episodeDb.episodeForPlaylistItem(itemToRemove); if (episode != null) { if (episode.isListened()) { episode.markAsListened(episodeDb.settings().IsAutoDelete); } } else { Debug.WriteLine("Warning: Could not get episode for item id: " + itemToRemove.ItemId); } } db.Playlist.DeleteOnSubmit(itemToRemove); db.SubmitChanges(); App.mainViewModels.PlayQueue = new ObservableCollection<PlaylistItem>(); } } }
private void PlayStateChanged(object sender, EventArgs e) { EventHandler handlerStoppedPlaying = null; switch (BackgroundAudioPlayer.Instance.PlayerState) { case PlayState.Playing: PodcastEpisodeModel currentEpisode = updateCurrentlyPlayingEpisode(); if (currentEpisode == null) { Debug.WriteLine("Error: No playing episode in DB."); return; } if (CurrentlyPlayingEpisode == null) { CurrentlyPlayingEpisode = currentEpisode; } else if (currentEpisode.EpisodeId != CurrentlyPlayingEpisode.EpisodeId) { CurrentlyPlayingEpisode = currentEpisode; } if (CurrentlyPlayingEpisode.TotalLengthTicks == 0) { CurrentlyPlayingEpisode.StoreProperty <long>("TotalLengthTicks", BackgroundAudioPlayer.Instance.Track.Duration.Ticks); PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(CurrentlyPlayingEpisode.getSubscriptionModel()); } break; case PlayState.Paused: BackgroundAudioPlayer playerPaused = BackgroundAudioPlayer.Instance; if (CurrentlyPlayingEpisode != null) { CurrentlyPlayingEpisode = App.refreshEpisodeFromAudioAgent(CurrentlyPlayingEpisode); CurrentlyPlayingEpisode.StoreProperty <PodcastEpisodeModel.EpisodePlayStateEnum>("EpisodePlayState", PodcastEpisodeModel.EpisodePlayStateEnum.Paused); } else { Debug.WriteLine("SHOULD NOT HAPPEND! Cannot save episode state to paused!"); } break; case PlayState.Stopped: case PlayState.Shutdown: case PlayState.TrackEnded: if (CurrentlyPlayingEpisode == null) { // We didn't have a track playing. return; } // F**K YOU WINDOWS PHONE!! /** * This is so horrible that I can't find other words to describe how bad the BackgroundAudioPlayer * is in Windows Phone! * * First of all the events are fired totally differently between Windows Phone 7 and Windows Phone 8. * Secondly the events related to when tracks end arae totally wrong and horrible! Let me explain: * - We get here the PlayState.Stopped event when the track ends. * - We get the event here BEFORE the AudioAgent gets any events. * - AudioAgent correctly gets the PlayState.TrackEnded event, but it gets it after we have received the * event here. * - We NEVER get the the PlayState.TrackEnded event here. * - Which is not the case for Windows Phone 7, because it first fires PlayState.TrackEnded. * * So this code here is a horrible kludge that just guesses that Windows Phone means "track did end" * when the state is stopped and the play position is still 0. * * Johan, when you return from the future to this piece of code, don't even try to change it or "fix it". **/ long playpos = 0; if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.TrackEnded) { playpos = CurrentlyPlayingEpisode.TotalLengthTicks; } else if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Stopped && BackgroundAudioPlayer.Instance.Position.Ticks == 0) { playpos = CurrentlyPlayingEpisode.TotalLengthTicks; } else { try { playpos = BackgroundAudioPlayer.Instance.Position.Ticks; } catch (Exception) { Debug.WriteLine("Warning: Player didn't return us a play pos!"); } } CurrentlyPlayingEpisode.SavedPlayPos = playpos; CurrentlyPlayingEpisode.setNoPlaying(); using (var db = new PodcastSqlModel()) { PodcastEpisodeModel savingEpisode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == CurrentlyPlayingEpisode.EpisodeId); if (savingEpisode != null) { savingEpisode.SavedPlayPos = CurrentlyPlayingEpisode.SavedPlayPos; // Update play state to listened as appropriate. if (savingEpisode.isListened()) { savingEpisode.markAsListened(db.settings().IsAutoDelete); removeFromPlayqueue(savingEpisode); } else { savingEpisode.EpisodePlayState = CurrentlyPlayingEpisode.EpisodePlayState; } db.SubmitChanges(); PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(savingEpisode.PodcastSubscription); } } PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(CurrentlyPlayingEpisode.getSubscriptionModel()); handlerStoppedPlaying = OnPodcastStoppedPlaying; if (handlerStoppedPlaying != null) { OnPodcastStoppedPlaying(this, new EventArgs()); } // Cleanup CurrentlyPlayingEpisode = null; break; case PlayState.TrackReady: break; case PlayState.Unknown: // Unknown? WTF. break; } App.mainViewModels.PlayQueue = new System.Collections.ObjectModel.ObservableCollection <PlaylistItem>(); if (CurrentlyPlayingEpisode != null) { PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(CurrentlyPlayingEpisode.PodcastSubscriptionInstance); } }
private void MenuItemMarkAsListened_Click(object sender, RoutedEventArgs e) { PodcastEpisodeModel podcastEpisode = this.DataContext as PodcastEpisodeModel; PodcastSubscriptionModel subscription = null; // We need this to update the play states for this subscription. bool delete = false; using (var db = new PodcastSqlModel()) { PodcastEpisodeModel sqlepisode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == podcastEpisode.EpisodeId); subscription = db.Subscriptions.FirstOrDefault(sub => sub.PodcastId == sqlepisode.PodcastId); PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(subscription); delete = db.settings().IsAutoDelete; sqlepisode.SavedPlayPos = 0; sqlepisode.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Listened; db.SubmitChanges(); } podcastEpisode.markAsListened(delete); }
public void exportSubscriptions() { List<PodcastSubscriptionModel> subscriptions = App.mainViewModels.PodcastSubscriptions.ToList(); if (subscriptions.Count == 0) { MessageBox.Show("No subscriptions to export."); return; } using (var db = new PodcastSqlModel()) { if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportToSkyDrive) { if (liveConnect == null) { loginUserToSkyDrive(); } else { DoOPMLExport(); } } else if (db.settings().SelectedExportIndex == (int)SettingsModel.ExportMode.ExportViaEmail) { DoOPMLExport(); } } }