Inheritance: DataContext, INotifyPropertyChanged
        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 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();
                }
            }
        }
        internal void SetupNowPlayingView()
        {
            this.DataContext = null;

            m_playbackManager = PodcastPlaybackManager.getInstance();

            if (m_playbackManager.CurrentlyPlayingEpisode != null)
            {
                this.Visibility = Visibility.Visible;
            }
            else
            {
                this.Visibility = Visibility.Collapsed;
                return;
            }

            if (m_currentlyPlayingEpisodeId < 0 ||
                m_playbackManager.CurrentlyPlayingEpisode.EpisodeId != m_currentlyPlayingEpisodeId)
            {
                m_currentlyPlayingEpisodeId = m_playbackManager.CurrentlyPlayingEpisode.EpisodeId;
                using (var db = new PodcastSqlModel())
                {
                    PodcastSubscriptionModel s = db.Subscriptions.First(sub => sub.PodcastId == m_playbackManager.CurrentlyPlayingEpisode.PodcastId);
                    m_podcastLogo = getLogoForSubscription(s);
                }
            }

            this.DataContext        = m_playbackManager.CurrentlyPlayingEpisode;
            this.PodcastLogo.Source = m_podcastLogo;
        }
Beispiel #4
0
        public void startDefaultBehaviorPlayback()
        {
            using (PodcastSqlModel db = new PodcastSqlModel())
            {
                try
                {
                    PodcastEpisodeModel latestPlayed = db.Episodes.Where(ep => (ep.LastPlayed.HasValue == true && ep.LastPlayed.Value.Year > 2013)).OrderByDescending(ep => ep.LastPlayed).FirstOrDefault();
                    if (latestPlayed != null)
                    {
                        App.showNotificationToast("Playing recently played episode.");
                        play(latestPlayed);
                        return;
                    }
                }
                catch (InvalidOperationException)
                {
                    Debug.WriteLine("Could not find a suitable latest episode played.");
                }

                // Did not find a suitable episode that was previously played, so we have to start a "new" playback.
                // This playback is the latest published episode.
                PodcastEpisodeModel newestEpisode = db.Episodes.OrderByDescending(ep => ep.EpisodePublished).FirstOrDefault();
                if (newestEpisode != null)
                {
                    App.showNotificationToast("Playing newest episode.");
                    play(newestEpisode);
                }
                else
                {
                    Debug.WriteLine("Uups, cannot find a newest episode to play.");
                }
            }
        }
Beispiel #5
0
        public PodcastEpisodeModel updateCurrentlyPlayingEpisode()
        {
            PlaylistItem plItem = null;

            using (var playlistDb = new PlaylistDBContext())
            {
                if (playlistDb.Playlist.Count() == 0)
                {
                    return(null);
                }

                plItem = playlistDb.Playlist.Where(item => item.IsCurrent).FirstOrDefault();
            }

            if (plItem != null)
            {
                using (var db = new PodcastSqlModel())
                {
                    PodcastEpisodeModel currentEpisode = db.Episodes.Where(ep => ep.EpisodeId == plItem.EpisodeId).FirstOrDefault();
                    CurrentlyPlayingEpisode = currentEpisode;
                    return(currentEpisode);
                }
            }

            return(null);
        }
Beispiel #6
0
        private void processStoredQueuedTransfers()
        {
            List <PodcastEpisodeModel> queuedEpisodes = new List <PodcastEpisodeModel>();

            using (var db = new PodcastSqlModel())
            {
                queuedEpisodes = db.Episodes.Where(ep => (ep.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.Queued ||
                                                          ep.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.WaitingForWiFi ||
                                                          ep.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.WaitingForWifiAndPower)
                                                   ).ToList();

                foreach (PodcastEpisodeModel episode in queuedEpisodes)
                {
                    episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Queued;
                    m_episodeDownloadQueue.Enqueue(episode);
                }

                db.SubmitChanges();
            }


            if (m_currentBackgroundTransfer == null && m_episodeDownloadQueue.Count > 0)
            {
                startNextEpisodeDownload();
            }
        }
        private AudioTrack getAudioTrackForEpisode(PodcastEpisodeModel currentEpisode)
        {
            if (currentEpisode == null ||
                String.IsNullOrEmpty(currentEpisode.EpisodeFile))
            {
                return(null);
            }

            Uri episodeLocation;

            try
            {
                episodeLocation = new Uri(currentEpisode.EpisodeFile, UriKind.Relative);
            } catch (Exception) {
                return(null);
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel sub = db.Subscriptions.First(s => s.PodcastId == currentEpisode.PodcastId);
                return(new AudioTrack(episodeLocation,
                                      currentEpisode.EpisodeName,
                                      sub.PodcastName,
                                      "",
                                      new Uri(sub.PodcastLogoLocalLocation, UriKind.Relative)));
            }
        }
Beispiel #8
0
        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 AudioTrack getAudioStreamForEpisode(PodcastEpisodeModel episode)
        {
            if (episode == null ||
                String.IsNullOrEmpty(episode.EpisodeDownloadUri))
            {
                return(null);
            }

            Uri episodeLocation;

            try
            {
                episodeLocation = new Uri(episode.EpisodeDownloadUri, UriKind.Absolute);
            }
            catch (Exception)
            {
                return(null);
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel sub = db.Subscriptions.First(s => s.PodcastId == episode.PodcastId);

                return(new AudioTrack(episodeLocation,
                                      episode.EpisodeName,
                                      sub.PodcastName,
                                      "",
                                      new Uri(sub.PodcastLogoLocalLocation, UriKind.Relative)));
            }
        }
        internal void SetupNowPlayingView()
        {
            PodcastPlaybackManager pm = PodcastPlaybackManager.getInstance();

            if (pm.CurrentlyPlayingEpisode != null)
            {
                this.Visibility = Visibility.Visible;
            }
            else
            {
                this.Visibility = Visibility.Collapsed;
                return;
            }

            if (m_currentlyPlayingEpisodeId < 0
                || pm.CurrentlyPlayingEpisode.EpisodeId != m_currentlyPlayingEpisodeId)
            {
                m_currentlyPlayingEpisodeId = pm.CurrentlyPlayingEpisode.EpisodeId;
                using (var db = new PodcastSqlModel())
                {
                    PodcastSubscriptionModel s = db.Subscriptions.First(sub => sub.PodcastId == pm.CurrentlyPlayingEpisode.PodcastId);
                    m_podcastLogo = getLogoForSubscription(s);
                }
            }

            this.DataContext = pm.CurrentlyPlayingEpisode;
            this.PodcastLogo.Source = m_podcastLogo;
        }
Beispiel #11
0
        public void playPlaylistItem(int tappedPlaylistItemId)
        {
            int episodeId = -1;

            using (var db = new PlaylistDBContext())
            {
                if (db.Playlist.Count() < 1)
                {
                    return;
                }

                episodeId = (int)db.Playlist.Where(item => item.ItemId == tappedPlaylistItemId).Select(item => item.EpisodeId).First();
            }

            PodcastEpisodeModel episode = null;

            using (var db = new PodcastSqlModel())
            {
                episode = db.Episodes.First(ep => ep.EpisodeId == episodeId);
            }

            if (episode != null)
            {
                play(episode, true);
            }
            else
            {
                Debug.WriteLine("Warning: Could not play episode: " + episodeId);
            }
        }
        private PodcastSubscriptionsManager()
        {
            m_podcastsSqlModel = PodcastSqlModel.getInstance();
            m_random = new Random();

            // Hook a callback method to the signal that we emit when the subscription has been added.
            // This way we can continue the synchronous execution.
            this.OnPodcastChannelFinished += new SubscriptionManagerHandler(PodcastSubscriptionsManager_OnPodcastAddedFinished);
        }
Beispiel #13
0
 public void play(PlaylistItem playlistItem)
 {
     using (PodcastSqlModel db = new PodcastSqlModel()) {
         PodcastEpisodeModel episode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == playlistItem.EpisodeId);
         if (episode != null)
         {
             play(episode);
         }
     }
 }
        void deleteSubscriptionFromDB(object sender, DoWorkEventArgs e)
        {
            PodcastSubscriptionModel podcastModel = e.Argument as PodcastSubscriptionModel;

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel dbSubscription = db.Subscriptions.First(s => s.PodcastId == podcastModel.PodcastId);
                dbSubscription.cleanupForDeletion();
                db.deleteSubscription(dbSubscription);
            }

            e.Result = podcastModel;
        }
Beispiel #15
0
        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);
            }
        }
Beispiel #16
0
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            //          IsolatedStorageExplorer.Explorer.Start("192.168.0.6");
            using (var db = new PodcastSqlModel())
            {
                db.createDB();
            }

            // Updates episodes from the audio agent.
            refreshEpisodesFromAudioAgent();

            // Diagnostics
            ApplicationUsageHelper.Init(App.AppVersion);
        }
Beispiel #17
0
        public void sortPlaylist(int sortOrder)
        {
            using (var playlistDB = new PlaylistDBContext())
            {
                if (playlistDB.Playlist.Count() <= 1)
                {
                    return;
                }

                PodcastSqlModel            sqlContext        = new PodcastSqlModel();
                IEnumerable <PlaylistItem> newSortOrderQuery = null;
                List <PlaylistItem>        newSortOrder      = new List <PlaylistItem>();

                var query = playlistDB.Playlist.AsEnumerable().Join(episodes(sqlContext),
                                                                    item => item.EpisodeId,
                                                                    episode => episode.EpisodeId,
                                                                    (item, episode) => new { PlaylistItem = item, PodcastEpisodeModel = episode });
                switch (sortOrder)
                {
                // Oldest first
                case 0:
                    newSortOrderQuery = query.OrderBy(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                        .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                    break;

                // Newest first.
                case 1:
                    newSortOrderQuery = query.OrderByDescending(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                        .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                    break;
                }

                int i = 0;
                foreach (PlaylistItem item in newSortOrderQuery)
                {
                    PlaylistItem newItem = item;
                    newItem.OrderNumber = i++;
                    newSortOrder.Add(newItem);
                }

                playlistDB.Playlist.DeleteAllOnSubmit(playlistDB.Playlist);
                playlistDB.Playlist.InsertAllOnSubmit(newSortOrder);
                playlistDB.SubmitChanges();
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                App.mainViewModels.PlayQueue = new ObservableCollection <PlaylistItem>();
            });
        }
        private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            PodcastEpisodeModel podcastEpisode = (sender as MenuItem).DataContext as PodcastEpisodeModel;
            podcastEpisode.deleteDownloadedEpisode();
            PodcastSubscriptionsManager.getInstance().removedPlayableEpisode(podcastEpisode);

            using (var db = new PodcastSqlModel())
            {
                m_episodeModel = db.episodeForEpisodeId(m_episodeModel.EpisodeId);
            }

            this.DataContext = null;
            this.DataContext = m_episodeModel;
        }
Beispiel #19
0
        private void processOngoingTransfer()
        {
            // If key exists, we know we have need to process a download request.
            if (m_applicationSettings.Contains(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID))
            {
                Debug.WriteLine("Found a episode download that we need to process.");
                int downloadingEpisodeId = (int)m_applicationSettings[App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID];
                m_currentEpisodeDownload = null;
                using (var db = new PodcastSqlModel())
                {
                    m_currentEpisodeDownload = db.episodeForEpisodeId(downloadingEpisodeId);
                }

                if (m_currentEpisodeDownload == null)
                {
                    Debug.WriteLine("Something went wrong. Got NULL episode when asking for episode id " + downloadingEpisodeId);

                    m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID);
                    m_applicationSettings.Save();
                    return;
                }

                if (BackgroundTransferService.Requests.Count() > 0)
                {
                    // Found an ongoing request.
                    Debug.WriteLine("Found an ongoing transfer...");
                    m_currentBackgroundTransfer = BackgroundTransferService.Requests.ElementAt(0);
                    m_currentBackgroundTransfer.TransferStatusChanged += new EventHandler <BackgroundTransferEventArgs>(backgroundTransferStatusChanged);

                    m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloading;
                    m_currentEpisodeDownload.DownloadRequest      = m_currentBackgroundTransfer;

                    m_episodeDownloadQueue.Enqueue(m_currentEpisodeDownload);

                    ProcessTransfer(m_currentBackgroundTransfer);

                    saveEpisodeInfoToDB(m_currentEpisodeDownload);
                }
                else
                {
                    // No ongoing requests found. Then we need to process a finished request.
                    // Probably happened in the background while we were suspended.
                    Debug.WriteLine("Found a completed request.");
                    updateEpisodeWhenDownloaded(m_currentEpisodeDownload);
                    m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID);
                    m_applicationSettings.Save();
                }
            }
        }
Beispiel #20
0
        private void saveEpisodeInfoToDB(PodcastEpisodeModel m_currentEpisodeDownload)
        {
            if (m_currentEpisodeDownload == null)
            {
                return;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastEpisodeModel episode = db.Episodes.First(e => e.EpisodeId == m_currentEpisodeDownload.EpisodeId);
                episode.EpisodeDownloadState = m_currentEpisodeDownload.EpisodeDownloadState;
                episode.EpisodeFile          = m_currentEpisodeDownload.EpisodeFile;
                db.SubmitChanges();
            }
        }
Beispiel #21
0
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            //          IsolatedStorageExplorer.Explorer.Start("192.168.0.6");
            using (var db = new PodcastSqlModel())
            {
                db.createDB();
            }

            CheckLicense();

            // Updates episodes from the audio agent.
            refreshEpisodesFromAudioAgent();

            handleRemovingIconFiles();
        }
        private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            PodcastEpisodeModel podcastEpisode = (sender as MenuItem).DataContext as PodcastEpisodeModel;

            podcastEpisode.deleteDownloadedEpisode();
            PodcastSubscriptionsManager.getInstance().removedPlayableEpisode(podcastEpisode);

            using (var db = new PodcastSqlModel())
            {
                m_episodeModel = db.episodeForEpisodeId(m_episodeModel.EpisodeId);
            }

            this.DataContext = null;
            this.DataContext = m_episodeModel;
        }
Beispiel #23
0
        private void workerSortPlaylist(object sender, DoWorkEventArgs args)
        {
            int selectedSortOrderIndex = (int)args.Argument;

            using (var playlistDB = new PlaylistDBContext())
            {
                if (playlistDB.Playlist.Count() <= 1)
                {
                    return;
                }

                PodcastSqlModel            sqlContext        = new PodcastSqlModel();
                IEnumerable <PlaylistItem> newSortOrderQuery = null;
                List <PlaylistItem>        newSortOrder      = new List <PlaylistItem>();

                var query = playlistDB.Playlist.AsEnumerable().Join(episodes(sqlContext),
                                                                    item => item.EpisodeId,
                                                                    episode => episode.EpisodeId,
                                                                    (item, episode) => new { PlaylistItem = item, PodcastEpisodeModel = episode });
                switch (selectedSortOrderIndex)
                {
                // Oldest first
                case 0:
                    newSortOrderQuery = query.OrderBy(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                        .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                    break;

                // Newest first.
                case 1:
                    newSortOrderQuery = query.OrderByDescending(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                        .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                    break;
                }

                int i = 0;
                foreach (PlaylistItem item in newSortOrderQuery)
                {
                    PlaylistItem newItem = item;
                    newItem.OrderNumber = i++;
                    newSortOrder.Add(newItem);
                }

                playlistDB.Playlist.DeleteAllOnSubmit(playlistDB.Playlist);
                playlistDB.Playlist.InsertAllOnSubmit(newSortOrder);
                playlistDB.SubmitChanges();
            }
        }
Beispiel #24
0
        public async void deleteSubscription(PodcastSubscriptionModel podcastSubscriptionModel)
        {
            OnPodcastChannelDeleteStarted(this, null);

            await Task.Run(() =>
            {
                using (var db = new PodcastSqlModel())
                {
                    PodcastSubscriptionModel dbSubscription = db.Subscriptions.First(s => s.PodcastId == podcastSubscriptionModel.PodcastId);
                    dbSubscription.cleanupForDeletion();
                    db.deleteSubscription(dbSubscription);
                }
            });

            OnPodcastChannelDeleteFinished(this, null);
            OnPodcastChannelRemoved(podcastSubscriptionModel);
        }
Beispiel #25
0
        public void playPlaylistItem(int tappedPlaylistItemId)
        {
            int episodeId = -1;

            using (var db = new PlaylistDBContext())
            {
                if (db.Playlist.Count() < 1)
                {
                    return;
                }

                // Did we tap the item that is currently playing?
                PlaylistItem current = db.Playlist.FirstOrDefault(item => item.IsCurrent == true);
                if (current != null &&
                    current.ItemId == tappedPlaylistItemId)
                {
                    Debug.WriteLine("Tapped on the currently playing episode. I am not changing the track...");

                    // Always open the player UI when playlist item is tapped.
                    var handler = OnOpenPodcastPlayer;
                    if (handler != null)
                    {
                        OnOpenPodcastPlayer(this, new EventArgs());
                    }
                    return;
                }

                episodeId = (int)db.Playlist.Where(item => item.ItemId == tappedPlaylistItemId).Select(item => item.EpisodeId).First();
            }

            PodcastEpisodeModel episode = null;

            using (var db = new PodcastSqlModel())
            {
                episode = db.Episodes.First(ep => ep.EpisodeId == episodeId);
            }

            if (episode != null)
            {
                play(episode, true);
            }
            else
            {
                Debug.WriteLine("Warning: Could not play episode: " + episodeId);
            }
        }
Beispiel #26
0
        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);
            }
        }
Beispiel #27
0
        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);
        }
Beispiel #28
0
        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);
        }
        private void updateEpisodeWhenDownloaded(PodcastEpisodeModel episode)
        {
            Debug.WriteLine("Updating episode information for episode when download completed: " + episode.EpisodeName);
            episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloaded;

            using (var db = new PodcastSqlModel())
            {
                Debug.WriteLine(" * Downloaded file name: " + episode.EpisodeFile);

                PodcastEpisodeModel e = db.episodeForEpisodeId(episode.EpisodeId);
                e.EpisodeFile          = episode.EpisodeFile;
                e.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloaded;
                e.EpisodePlayState     = PodcastEpisodeModel.EpisodePlayStateEnum.Downloaded;

                db.SubmitChanges();

                PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(e.PodcastSubscription);
            }
        }
Beispiel #30
0
        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 setupPlayerUIContent(PodcastEpisodeModel currentEpisode)
        {
            if (currentEpisode == null)
            {
                return;
            }

            Debug.WriteLine("Setting up player UI.");
            if (currentEpisode.EpisodeName == PodcastEpisodeName.Text)
            {
                return;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel s = db.Subscriptions.Where(sub => sub.PodcastId == currentEpisode.PodcastId).FirstOrDefault();
                PodcastLogo.Source      = s.PodcastLogo;
                PodcastEpisodeName.Text = currentEpisode.EpisodeName;
            }
        }
        private void PlayHistoryItemTapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            PodcastEpisodeModel episode = DataContext as PodcastEpisodeModel;
            if (episode == null)
            {
                App.showNotificationToast("You don't subscribe to the podcast anymore.");
                return;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel sub = db.Subscriptions.FirstOrDefault(s => s.PodcastId == episode.PodcastId);
                if (sub == null)
                {
                    App.showNotificationToast("You don't subscribe to the podcast anymore.");
                    return;
                }
            }

            (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri(string.Format("/Views/PodcastEpisodes.xaml?podcastId={0}", episode.PodcastId), UriKind.Relative));
        }
        private void updatePrimary(PodcastEpisodeModel currentEpisode)
        {
            ShellTile PrimaryTile = ShellTile.ActiveTiles.First();

            if (PrimaryTile != null)
            {
                StandardTileData tile = new StandardTileData();
                String           tileImageLocation        = "";
                String           podcastLogoLocalLocation = "";

                // Copy the logo file to tile's shared location.
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var db = new PodcastSqlModel())
                    {
                        PodcastSubscriptionModel sub = db.Subscriptions.First(s => s.PodcastId == currentEpisode.PodcastId);
                        podcastLogoLocalLocation = sub.PodcastLogoLocalLocation;
                        tile.BackTitle           = sub.PodcastName;
                    }

                    if (myIsolatedStorage.FileExists(podcastLogoLocalLocation) == false)
                    {
                        // Cover art does not exist, we cannot do anything. Give up, don't put it to Live tile.
                        Debug.WriteLine("Podcasts cover art not found.");
                        return;
                    }

                    tileImageLocation = "Shared/ShellContent/" + podcastLogoLocalLocation.Split('/')[1];

                    if (myIsolatedStorage.FileExists(tileImageLocation) == false)
                    {
                        myIsolatedStorage.CopyFile(podcastLogoLocalLocation,
                                                   tileImageLocation);
                    }
                }

                tile.BackBackgroundImage = new Uri("isostore:/" + tileImageLocation, UriKind.Absolute);
                PrimaryTile.Update(tile);
            }
        }
        private void PlayHistoryItemTapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            PodcastEpisodeModel episode = DataContext as PodcastEpisodeModel;

            if (episode == null)
            {
                App.showNotificationToast("You don't subscribe to the podcast anymore.");
                return;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel sub = db.Subscriptions.FirstOrDefault(s => s.PodcastId == episode.PodcastId);
                if (sub == null)
                {
                    App.showNotificationToast("You don't subscribe to the podcast anymore.");
                    return;
                }
            }

            (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri(string.Format("/Views/PodcastEpisodes.xaml?podcastId={0}", episode.PodcastId), UriKind.Relative));
        }
        private void updateEpisodeWhenDownloaded(PodcastEpisodeModel episode)
        {
            Debug.WriteLine("Updating episode information for episode when download completed: " + episode.EpisodeName);
            episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloaded;

            using (var db = new PodcastSqlModel())
            {
                Debug.WriteLine(" * Downloaded file name: " + episode.EpisodeFile);

                PodcastEpisodeModel e = db.episodeForEpisodeId(episode.EpisodeId);
                e.EpisodeFile = episode.EpisodeFile;
                e.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloaded;
                e.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Downloaded;

                db.SubmitChanges();

                PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(e.PodcastSubscription);
            }
        }
        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 processStoredQueuedTransfers()
        {
            List<PodcastEpisodeModel> queuedEpisodes = new List<PodcastEpisodeModel>();
            using (var db = new PodcastSqlModel())
            {
                queuedEpisodes = db.Episodes.Where(ep => (ep.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.Queued
                                                          || ep.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.WaitingForWiFi
                                                          || ep.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.WaitingForWifiAndPower)
                                                  ).ToList();

                foreach (PodcastEpisodeModel episode in queuedEpisodes)
                {
                    episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Queued;
                    m_episodeDownloadQueue.Enqueue(episode);
                }

                db.SubmitChanges();
            }

            if (m_currentBackgroundTransfer == null && m_episodeDownloadQueue.Count > 0)
            {
                startNextEpisodeDownload();
            }
        }
        private void setupPlayerUIContent(PodcastEpisodeModel currentEpisode)
        {
            if (currentEpisode == null)
            {
                return;
            }

            Debug.WriteLine("Setting up player UI.");
            if (currentEpisode.EpisodeName == PodcastEpisodeName.Text)
            {
                return;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel s = db.Subscriptions.Where(sub => sub.PodcastId == currentEpisode.PodcastId).FirstOrDefault();
                PodcastLogo.Source = s.PodcastLogo;
                PodcastEpisodeName.Text = currentEpisode.EpisodeName;
            }
        }
        private void updatePrimary(PodcastEpisodeModel currentEpisode)
        {
            ShellTile PrimaryTile = ShellTile.ActiveTiles.First();

            if (PrimaryTile != null)
            {
                StandardTileData tile = new StandardTileData();
                String tileImageLocation = "";
                String podcastLogoLocalLocation = "";

                // Copy the logo file to tile's shared location.
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var db = new PodcastSqlModel())
                    {
                        PodcastSubscriptionModel sub = db.Subscriptions.First(s => s.PodcastId == currentEpisode.PodcastId);
                        podcastLogoLocalLocation = sub.PodcastLogoLocalLocation;
                        tile.BackTitle = sub.PodcastName;
                    }

                    if (myIsolatedStorage.FileExists(podcastLogoLocalLocation) == false)
                    {
                        // Cover art does not exist, we cannot do anything. Give up, don't put it to Live tile.
                        Debug.WriteLine("Podcasts cover art not found.");
                        return;
                    }

                    tileImageLocation = "Shared/ShellContent/" + podcastLogoLocalLocation.Split('/')[1];

                    if (myIsolatedStorage.FileExists(tileImageLocation) == false)
                    {
                        myIsolatedStorage.CopyFile(podcastLogoLocalLocation,
                                                   tileImageLocation);
                    }
                }

                tile.BackBackgroundImage = new Uri("isostore:/" + tileImageLocation, UriKind.Absolute);
                PrimaryTile.Update(tile);
            }
        }
        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>();
                }
            }
        }
        public void play(PodcastEpisodeModel episode, bool startedFromPlayQueue = false)
        {
            if (episode == null)
            {
                Debug.WriteLine("Warning: Trying to play a NULL episode.");
                return;
            }

            Debug.WriteLine("Starting playback for episode: ");
            Debug.WriteLine(" Name: " + episode.EpisodeName);
            Debug.WriteLine(" File: " + episode.EpisodeFile);
            Debug.WriteLine(" Location: " + episode.EpisodeDownloadUri);

            // We have another episode currently playing, and we switch the episode that we are playing.
            if (CurrentlyPlayingEpisode != null
                && (episode.EpisodeId != CurrentlyPlayingEpisode.EpisodeId))
            {
                CurrentlyPlayingEpisode.setNoPlaying();

                try
                {
                    CurrentlyPlayingEpisode.SavedPlayPos = BackgroundAudioPlayer.Instance.Position.Ticks;
                }
                catch (Exception)
                {
                    Debug.WriteLine("Could not set saved play pos; not available.");
                    CurrentlyPlayingEpisode.SavedPlayPos = 0;
                }

                using (var db = new PodcastSqlModel())
                {
                    PodcastEpisodeModel savingEpisode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == CurrentlyPlayingEpisode.EpisodeId);
                    savingEpisode.SavedPlayPos = CurrentlyPlayingEpisode.SavedPlayPos;
                    db.SubmitChanges();
                }
            }

            if (startedFromPlayQueue)
            {
                if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Paused
                    || (CurrentlyPlayingEpisode != null
                        && CurrentlyPlayingEpisode.EpisodeId != episode.EpisodeId))
                {
                    CurrentlyPlayingEpisode = episode;
                }
            }
            else
            {
                CurrentlyPlayingEpisode = episode;

                // Clear play queue (yes) when we start playback from episode listing.
                // And we clear the queue after the current episode is being set, so that we don't delete the currently
                // playing one.
                clearPlayQueue();
            }

            // Play locally from a downloaded file.
            if (CurrentlyPlayingEpisode != null
                && CurrentlyPlayingEpisode.EpisodeDownloadState == PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloaded)
            {
                PodcastPlayerControl player = PodcastPlayerControl.getIntance();
                CurrentlyPlayingEpisode.setPlaying();
                CurrentlyPlayingEpisode.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Playing;
                player.playEpisode(CurrentlyPlayingEpisode);
            }
            else
            {
                // Stream it if not downloaded.
                if (isAudioPodcast(CurrentlyPlayingEpisode))
                {
                    CurrentlyPlayingEpisode.setPlaying();
                    audioStreaming(CurrentlyPlayingEpisode);
                    CurrentlyPlayingEpisode.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Streaming;
                }
                else
                {
                    PodcastPlayerControl player = PodcastPlayerControl.getIntance();
                    player.StopPlayback();
                    videoStreaming(episode);
                    CurrentlyPlayingEpisode.EpisodePlayState = PodcastEpisodeModel.EpisodePlayStateEnum.Streaming;
                }
            }

            // Always open the player view.
            var handler = OnOpenPodcastPlayer;
            if (handler != null)
            {
                OnOpenPodcastPlayer(this, new EventArgs());
            }

            var handlerStartedPlaying = OnPodcastStartedPlaying;
            if (handlerStartedPlaying != null)
            {
                if (isAudioPodcast(episode))
                {
                    OnPodcastStartedPlaying(this, new EventArgs());
                }
            }

            App.mainViewModels.PlayQueue = new System.Collections.ObjectModel.ObservableCollection<PlaylistItem>(); // Notify playlist changed.
        }
        public void startDefaultBehaviorPlayback()
        {
            using (PodcastSqlModel db = new PodcastSqlModel())
            {
                try
                {
                    PodcastEpisodeModel latestPlayed = db.Episodes.Where(ep => (ep.LastPlayed.HasValue == true && ep.LastPlayed.Value.Year > 2013)).OrderByDescending(ep => ep.LastPlayed).FirstOrDefault();
                    if (latestPlayed != null)
                    {
                        App.showNotificationToast("Playing recently played episode.");
                        play(latestPlayed);
                        return;
                    }
                }
                catch (InvalidOperationException)
                {
                    Debug.WriteLine("Could not find a suitable latest episode played.");
                }

                // Did not find a suitable episode that was previously played, so we have to start a "new" playback.
                // This playback is the latest published episode.
                PodcastEpisodeModel newestEpisode = db.Episodes.OrderByDescending(ep => ep.EpisodePublished).FirstOrDefault();
                if (newestEpisode != null)
                {
                    App.showNotificationToast("Playing newest episode.");
                    play(newestEpisode);
                }
                else
                {
                    Debug.WriteLine("Uups, cannot find a newest episode to play.");
                }

            }
        }
        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 sortPlaylist(int sortOrder)
        {
            using (var playlistDB = new PlaylistDBContext())
            {
                if (playlistDB.Playlist.Count() <= 1)
                {
                    return;
                }

                PodcastSqlModel sqlContext = new PodcastSqlModel();
                IEnumerable<PlaylistItem> newSortOrderQuery = null;
                List<PlaylistItem> newSortOrder = new List<PlaylistItem>();

                var query = playlistDB.Playlist.AsEnumerable().Join(episodes(sqlContext),
                                                                    item => item.EpisodeId,
                                                                    episode => episode.EpisodeId,
                                                                    (item, episode) => new { PlaylistItem = item, PodcastEpisodeModel = episode });
                switch (sortOrder)
                {
                    // Oldest first
                    case 0:
                        newSortOrderQuery = query.OrderBy(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                            .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                        break;
                    // Newest first.
                    case 1:
                        newSortOrderQuery = query.OrderByDescending(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                            .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                        break;
                }

                int i = 0;
                foreach (PlaylistItem item in newSortOrderQuery)
                {
                    PlaylistItem newItem = item;
                    newItem.OrderNumber = i++;
                    newSortOrder.Add(newItem);
                }

                playlistDB.Playlist.DeleteAllOnSubmit(playlistDB.Playlist);
                playlistDB.Playlist.InsertAllOnSubmit(newSortOrder);
                playlistDB.SubmitChanges();
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                App.mainViewModels.PlayQueue = new ObservableCollection<PlaylistItem>();
            });
        }
        public void playPlaylistItem(int tappedPlaylistItemId)
        {
            int episodeId = -1;
            using (var db = new PlaylistDBContext())
            {
                if (db.Playlist.Count() < 1)
                {
                    return;
                }

                episodeId = (int)db.Playlist.Where(item => item.ItemId == tappedPlaylistItemId).Select(item => item.EpisodeId).First();
            }

            PodcastEpisodeModel episode = null;
            using (var db = new PodcastSqlModel())
            {
                episode = db.Episodes.First(ep => ep.EpisodeId == episodeId);
            }

            if (episode != null)
            {
                play(episode, true);
            }
            else
            {
                Debug.WriteLine("Warning: Could not play episode: " + episodeId);
            }
        }
 public void play(PlaylistItem playlistItem)
 {
     using (PodcastSqlModel db = new PodcastSqlModel()) {
         PodcastEpisodeModel episode = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == playlistItem.EpisodeId);
         if (episode != null)
         {
             play(episode);
         }
     }
 }
        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);
        }
Beispiel #48
0
        /************************************* Public implementations *******************************/
        public static PodcastSqlModel getInstance()
        {
            if (m_instance == null)
            {
                m_instance = new PodcastSqlModel();
            }

            return m_instance;
        }
        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 static IEnumerable<PodcastEpisodeModel> episodes(PodcastSqlModel sqlContext)
 {
     return sqlContext.Episodes.AsQueryable();
 }
        public void playPlaylistItem(int tappedPlaylistItemId)
        {
            int episodeId = -1;
            using (var db = new PlaylistDBContext())
            {
                if (db.Playlist.Count() < 1)
                {
                    return;
                }

                // Did we tap the item that is currently playing?
                PlaylistItem current = db.Playlist.FirstOrDefault(item => item.IsCurrent == true);
                if (current != null
                    && current.ItemId == tappedPlaylistItemId)
                {
                    Debug.WriteLine("Tapped on the currently playing episode. I am not changing the track...");

                    // Always open the player UI when playlist item is tapped.
                    var handler = OnOpenPodcastPlayer;
                    if (handler != null)
                    {
                        OnOpenPodcastPlayer(this, new EventArgs());
                    }
                    return;
                }

                episodeId = (int)db.Playlist.Where(item => item.ItemId == tappedPlaylistItemId).Select(item => item.EpisodeId).First();
            }

            PodcastEpisodeModel episode = null;
            using (var db = new PodcastSqlModel())
            {
                episode = db.Episodes.First(ep => ep.EpisodeId == episodeId);
            }

            if (episode != null)
            {
                play(episode, true);
            }
            else
            {
                Debug.WriteLine("Warning: Could not play episode: " + episodeId);
            }
        }
        private void workerSortPlaylist(object sender, DoWorkEventArgs args)
        {
            int selectedSortOrderIndex = (int)args.Argument;
            using (var playlistDB = new PlaylistDBContext())
            {
                if (playlistDB.Playlist.Count() <= 1)
                {
                    return;
                }

                PodcastSqlModel sqlContext = new PodcastSqlModel();
                IEnumerable<PlaylistItem> newSortOrderQuery = null;
                List<PlaylistItem> newSortOrder = new List<PlaylistItem>();

                var query = playlistDB.Playlist.AsEnumerable().Join(episodes(sqlContext),
                                                                    item => item.EpisodeId,
                                                                    episode => episode.EpisodeId,
                                                                    (item, episode) => new { PlaylistItem = item, PodcastEpisodeModel = episode });
                switch (selectedSortOrderIndex)
                {
                    // Oldest first
                    case 0:
                        newSortOrderQuery = query.OrderBy(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                            .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                        break;
                    // Newest first.
                    case 1:
                        newSortOrderQuery = query.OrderByDescending(newPlaylistItem => newPlaylistItem.PodcastEpisodeModel.EpisodePublished)
                                            .Select(newPlaylistItem => newPlaylistItem.PlaylistItem).AsEnumerable();
                        break;
                }

                int i = 0;
                foreach (PlaylistItem item in newSortOrderQuery)
                {
                    PlaylistItem newItem = item;
                    newItem.OrderNumber = i++;
                    newSortOrder.Add(newItem);
                }

                playlistDB.Playlist.DeleteAllOnSubmit(playlistDB.Playlist);
                playlistDB.Playlist.InsertAllOnSubmit(newSortOrder);
                playlistDB.SubmitChanges();
            }
        }
        public PodcastEpisodeModel updateCurrentlyPlayingEpisode()
        {
            PlaylistItem plItem = null;
            using (var playlistDb = new PlaylistDBContext())
            {
                if (playlistDb.Playlist.Count() == 0)
                {
                    return null;
                }

                plItem = playlistDb.Playlist.Where(item => item.IsCurrent).FirstOrDefault();
            }

            if (plItem != null)
            {
                using (var db = new PodcastSqlModel())
                {
                    PodcastEpisodeModel currentEpisode = db.Episodes.Where(ep => ep.EpisodeId == plItem.EpisodeId).FirstOrDefault();
                    CurrentlyPlayingEpisode = currentEpisode;
                    return currentEpisode;
                }
            }

            return null;
        }
        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 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);
            }
        }
        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 processOngoingTransfer()
        {
            // If key exists, we know we have need to process a download request.
            if (m_applicationSettings.Contains(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID))
            {
                Debug.WriteLine("Found a episode download that we need to process.");
                int downloadingEpisodeId = (int)m_applicationSettings[App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID];
                m_currentEpisodeDownload = null;
                using (var db = new PodcastSqlModel())
                {
                    m_currentEpisodeDownload = db.episodeForEpisodeId(downloadingEpisodeId);
                }

                if (m_currentEpisodeDownload == null)
                {
                    Debug.WriteLine("Something went wrong. Got NULL episode when asking for episode id " + downloadingEpisodeId);

                    m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID);
                    m_applicationSettings.Save();
                    return;
                }

                if (BackgroundTransferService.Requests.Count() > 0)
                {
                    // Found an ongoing request.
                    Debug.WriteLine("Found an ongoing transfer...");
                    m_currentBackgroundTransfer = BackgroundTransferService.Requests.ElementAt(0);
                    m_currentBackgroundTransfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(backgroundTransferStatusChanged);

                    m_currentEpisodeDownload.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Downloading;
                    m_currentEpisodeDownload.DownloadRequest = m_currentBackgroundTransfer;

                    m_episodeDownloadQueue.Enqueue(m_currentEpisodeDownload);

                    ProcessTransfer(m_currentBackgroundTransfer);

                    saveEpisodeInfoToDB(m_currentEpisodeDownload);
                }
                else
                {
                    // No ongoing requests found. Then we need to process a finished request.
                    // Probably happened in the background while we were suspended.
                    Debug.WriteLine("Found a completed request.");
                    updateEpisodeWhenDownloaded(m_currentEpisodeDownload);
                    m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID);
                    m_applicationSettings.Save();
                }
            }
        }
        private AudioTrack getAudioTrackForEpisode(PodcastEpisodeModel currentEpisode)
        {
            if (currentEpisode == null ||
                String.IsNullOrEmpty(currentEpisode.EpisodeFile))
            {
                return null;
            }

            Uri episodeLocation;
            try
            {
                episodeLocation = new Uri(currentEpisode.EpisodeFile, UriKind.Relative);
            } catch(Exception) {
                return null;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel sub = db.Subscriptions.First(s => s.PodcastId == currentEpisode.PodcastId);
                return new AudioTrack(episodeLocation,
                            currentEpisode.EpisodeName,
                            sub.PodcastName,
                            "",
                            new Uri(sub.PodcastLogoLocalLocation, UriKind.Relative));
            }
        }
        private AudioTrack getAudioStreamForEpisode(PodcastEpisodeModel episode)
        {
            if (episode == null ||
                String.IsNullOrEmpty(episode.EpisodeDownloadUri))
            {
                return null;
            }

            Uri episodeLocation;
            try
            {
                episodeLocation = new Uri(episode.EpisodeDownloadUri, UriKind.Absolute);
            }
            catch (Exception)
            {
                return null;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastSubscriptionModel sub = db.Subscriptions.First(s => s.PodcastId == episode.PodcastId);

                return new AudioTrack(episodeLocation,
                            episode.EpisodeName,
                            sub.PodcastName,
                            "",
                            new Uri(sub.PodcastLogoLocalLocation, UriKind.Relative));
            }
        }
        private void saveEpisodeInfoToDB(PodcastEpisodeModel m_currentEpisodeDownload)
        {
            if (m_currentEpisodeDownload == null)
            {
                return;
            }

            using (var db = new PodcastSqlModel())
            {
                PodcastEpisodeModel episode = db.Episodes.First(e => e.EpisodeId == m_currentEpisodeDownload.EpisodeId);
                episode.EpisodeDownloadState = m_currentEpisodeDownload.EpisodeDownloadState;
                episode.EpisodeFile = m_currentEpisodeDownload.EpisodeFile;
                db.SubmitChanges();
            }
        }