Inheritance: INotifyPropertyChanged
Exemple #1
0
        private List <PodcastEpisodeModel> createPlayHistory()
        {
            List <PodcastEpisodeModel> playHistory = new List <PodcastEpisodeModel>();

            using (var db = new PodcastSqlModel())
            {
                var query = from LastPlayedEpisodeModel e in db.PlayHistory
                            orderby e.TimeStamp descending
                            select e;

                int itemsCount = 0;
                foreach (LastPlayedEpisodeModel e in query)
                {
                    PodcastEpisodeModel episode = db.episodeForEpisodeId(e.LastPlayedEpisodeId);
                    if (episode == null)
                    {
                        Debug.WriteLine("Got NULL episode for play history. This probably means the subscription has been deleted.");
                        continue;
                    }

                    playHistory.Add(episode);

                    itemsCount++;
                    if (itemsCount >= 4)
                    {
                        break;
                    }
                }

                return(playHistory);
            }
        }
 private void DownloadButton_Click(object sender, RoutedEventArgs e)
 {
     m_episodeModel = this.DataContext as PodcastEpisodeModel;
     PodcastEpisodesDownloadManager downloadManager = PodcastEpisodesDownloadManager.getInstance();
     PodcastEpisodesDownloadManager.notifyUserOfDownloadRestrictions(m_episodeModel);
     downloadManager.addEpisodeToDownloadQueue(m_episodeModel);
 }
 protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs naviArgs)
 {
     this.DownloadButton.Visibility = System.Windows.Visibility.Collapsed;
     try
     {
         int podcastEpisodeId = int.Parse(NavigationContext.QueryString["episodeId"]);
         using (var db = new PodcastSqlModel())
         {
             m_podcastEpisode = db.episodeForEpisodeId(podcastEpisodeId);
             if (m_podcastEpisode != null)
             {
                 this.DataContext = m_podcastEpisode;
                 if (m_podcastEpisode.isPlayable() && String.IsNullOrEmpty(m_podcastEpisode.EpisodeFile))
                 {
                     this.DownloadButton.Visibility = System.Windows.Visibility.Visible;
                 }
             }
             else
             {
                 Debug.WriteLine("Episode model is null. Cannot show description.");
             }
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine("Cannot get episode id. Error: " + e.Message);
      }
 }
 protected override T GetPropertyFromDB <T>(String propertyName)
 {
     using (var db = new PodcastSqlModel())
     {
         PodcastEpisodeModel dbEpisode = db.Episodes.First(ep => ep.EpisodeId == this.EpisodeId);
         PropertyInfo        property  = dbEpisode.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);
         return((T)property.GetValue(dbEpisode));
     }
 }
 protected override void StorePropertyToDB <T>(String propertyName, T value)
 {
     using (var db = new PodcastSqlModel())
     {
         PodcastEpisodeModel dbEpisode = db.Episodes.First(ep => ep.EpisodeId == this.EpisodeId);
         PropertyInfo        property  = dbEpisode.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);
         property.SetValue(dbEpisode, value);
         db.SubmitChanges();
     }
 }
        internal void initializeState(PodcastEpisodeModel podcastEpisodeModel)
        {
            EpisodePlayState     = podcastEpisodeModel.EpisodePlayState;
            EpisodeDownloadState = podcastEpisodeModel.EpisodeDownloadState;

            switch (podcastEpisodeModel.EpisodePlayState)
            {
            case EpisodePlayStateEnum.Playing:
            case EpisodePlayStateEnum.Streaming:
                setPlaying();
                break;
            }
        }
        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;
        }
Exemple #8
0
        public void addEpisodeToPlayHistory(PodcastEpisodeModel episode)
        {
            if (episode == null)
            {
                Debug.WriteLine("Warning: Trying to add NULL episode to play history.");
                return;
            }

            LastPlayedEpisodeModel existingItem = (from LastPlayedEpisodeModel e in PlayHistory
                                                   where e.LastPlayedEpisodeId == episode.EpisodeId
                                                   select e).FirstOrDefault();

            // Episode is already in play history. Just update the timestamp instead of adding a duplicate one.
            if (existingItem != null)
            {
                Debug.WriteLine("Found episode already in history. Updating timestamp. Name: " + episode.EpisodeName);
                existingItem.TimeStamp = DateTime.Now;
                existingItem.LastPlayedEpisodeId = episode.EpisodeId;
                SubmitChanges();
                return;
            }

            // Clean old history items (if we have more than 10).
            if (PlayHistory.Count() >= 10)
            {
                var oldestHistoryItems = (from LastPlayedEpisodeModel e in PlayHistory
                                         orderby e.TimeStamp descending
                                         select e).Skip(10);

                if (oldestHistoryItems != null)
                {
                    Debug.WriteLine("Cleaning old episode from history.");
                    PlayHistory.DeleteAllOnSubmit(oldestHistoryItems);
                }
            }

            // Add a new item.
            LastPlayedEpisodeModel newHistoryItem = new LastPlayedEpisodeModel();
            newHistoryItem.LastPlayedEpisodeId = episode.EpisodeId;
            newHistoryItem.TimeStamp = DateTime.Now;

            Debug.WriteLine("Inserting episode to history: " + episode.EpisodeName);

            PlayHistory.InsertOnSubmit(newHistoryItem);
            SubmitChanges();
        }
        private void resetEpisodeInDB()
        {
            using (var db = new PodcastSqlModel())
            {
                PodcastEpisodeModel e = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == EpisodeId);
                if (e == null)
                {
                    Debug.WriteLine("Episode NULL. Probably alrady deleted.");
                    return;
                }

                e.SavedPlayPos         = SavedPlayPos;
                e.TotalLengthTicks     = TotalLengthTicks;
                e.EpisodeFile          = "";
                e.EpisodeDownloadState = EpisodeDownloadStateEnum.Idle;
                e.EpisodePlayState     = EpisodePlayStateEnum.Idle;
                e.SavedPlayPos         = 0;

                db.SubmitChanges();

                PodcastSubscriptionsManager.getInstance().podcastPlaystateChanged(e.PodcastSubscription);
            }
        }
        internal void markAsListened(bool deleteListened)
        {
            Debug.WriteLine("Episode '" + EpisodeName + "' marked as listened.");

            SavedPlayPos     = 0;
            EpisodePlayState = EpisodePlayStateEnum.Listened;

            using (var db = new PodcastSqlModel())
            {
                PodcastEpisodeModel e = db.Episodes.FirstOrDefault(ep => ep.EpisodeId == EpisodeId);
                if (e != null)
                {
                    e.SavedPlayPos     = SavedPlayPos;
                    e.EpisodePlayState = EpisodePlayState;
                    db.SubmitChanges();
                }
            }

            if (deleteListened && String.IsNullOrEmpty(EpisodeFile) == false)
            {
                deleteDownloadedEpisode();
            }
        }
 void PodcastDownloadControl_Loaded(object sender, RoutedEventArgs e)
 {
     m_episodeModel = this.DataContext as PodcastEpisodeModel;
     this.PodcastLogo.Source = m_episodeModel.PodcastLogo;
 }
 private void videoStreaming(PodcastEpisodeModel podcastEpisode)
 {
     MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();
     mediaPlayerLauncher.Media = new Uri(podcastEpisode.EpisodeDownloadUri, UriKind.Absolute);
     mediaPlayerLauncher.Controls = MediaPlaybackControls.All;
     mediaPlayerLauncher.Location = MediaLocationType.Data;
     mediaPlayerLauncher.Show();
 }
 private void initializeCurrentlyPlayingEpisode()
 {
     // If we have an episodeId stored in local cache, this means we returned to the app and
     // have that episode playing. Hence, here we need to reload the episode data from the SQL.
     CurrentlyPlayingEpisode = updateCurrentlyPlayingEpisode();
     if (CurrentlyPlayingEpisode != null)
     {
         CurrentlyPlayingEpisode.setPlaying();
     }
 }
        private void addToPlayqueue(PodcastEpisodeModel e, PlaylistDBContext dbContext)
        {
            PlaylistItem existingItem = dbContext.Playlist.FirstOrDefault(item => item.EpisodeId == e.EpisodeId);
            if (existingItem != null)
            {
                Debug.WriteLine("Item already in playlist.");
                return;
            }

            dbContext.Playlist.InsertOnSubmit(new PlaylistItem
            {
                EpisodeId = e.EpisodeId,
                EpisodeName = e.EpisodeName,
                EpisodeLocation = (!String.IsNullOrEmpty(e.EpisodeFile) ? e.EpisodeFile : e.EpisodeDownloadUri),
                PodcastLogoLocation = e.PodcastSubscriptionInstance.PodcastLogoLocalLocation,
                PodcastName = e.PodcastSubscriptionInstance.PodcastName
            });
        }
 public void removeFromPlayqueue(PodcastEpisodeModel episode)
 {
     using (var db = new PlaylistDBContext())
     {
         PlaylistItem plItem = db.Playlist.FirstOrDefault(item => item.EpisodeId == episode.EpisodeId);
         if (plItem != null)
         {
             removeFromPlayqueue(plItem);
         }
     }
 }
        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 cleanupEpisodeDownload(BackgroundTransferRequest transferRequest)
        {
            m_currentBackgroundTransfer.TransferStatusChanged -= new EventHandler<BackgroundTransferEventArgs>(backgroundTransferStatusChanged);

            // Remove the transfer request in order to make room in the
            // queue for more transfers. Transfers are not automatically
            // removed by the system.
            RemoveTransferRequest(transferRequest);

            // Update state of the finished episode.
            //  - Remove the settings key that denoted that this episode is download (in case the app is restarted while this downloads).
            //  - Set currently downloading episode to NULL.
            //  - Remove this episode from the download queue.
            m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID);
            m_episodeDownloadQueue.Dequeue();

            m_currentBackgroundTransfer = null;
            transferRequest = null;

            // Clean episode data.
            m_currentEpisodeDownload.DownloadRequest = null;
            m_currentEpisodeDownload = null;
        }
        private bool canAllowCellularDownload(PodcastEpisodeModel m_currentEpisodeDownload)
        {
            if (m_currentEpisodeDownload.EpisodeDownloadSize == 0)
            {
                return true;
            }

            long downloadSizeLimit = App.MAX_SIZE_FOR_WIFI_DOWNLOAD_NO_POWER;
            long episodeDownloadSize = m_currentEpisodeDownload.EpisodeDownloadSize;

            if (episodeDownloadSize < downloadSizeLimit)
            {
                return true;
            }

            return false;
        }
        public void cancelEpisodeDownload(PodcastEpisodeModel episode)
        {
            // Update new episode state.
            episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle;
            saveEpisodeInfoToDB(episode);

            // Get the transfer request that we should cancel.
            BackgroundTransferRequest thisRequest = episode.DownloadRequest;

            // We canceled a queued episode that wasn't downloading yet.
            if (thisRequest == null)
            {
                removeEpisodeFromDownloadQueue(episode);
                return;
            }
            else
            {
                // We canceled current download.
                RemoveTransferRequest(thisRequest);
            }

            episode.DownloadRequest = null;
            PodcastSubscriptionsManager.getInstance().removedPlayableEpisode(episode);
        }
        public void addEpisodeToDownloadQueue(PodcastEpisodeModel episode)
        {
            episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Queued;
            episode.DownloadPercentage = 0;
            m_episodeDownloadQueue.Enqueue(episode);
            saveEpisodeInfoToDB(episode);
            PodcastSubscriptionsManager.getInstance().newDownloadedEpisode(episode);

            if (m_currentEpisodeDownload == null)
            {
                startNextEpisodeDownload();
            }
        }
        public static void notifyUserOfDownloadRestrictions(PodcastEpisodeModel episode)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            // Notify about >100 MB downloads
            if (!settings.Contains(App.LSKEY_NOTIFY_DOWNLOADING_WITH_WIFI)
                && episode.EpisodeDownloadSize > App.MAX_SIZE_FOR_WIFI_DOWNLOAD_NO_POWER)
            {

                if (MessageBox.Show("You are about to download a file over 100 MB in size. " +
                                    "Please note that Windows Phone allows downloading this kind of files only if " +
                                    "you are connected to a WiFi network and connected to an external power source.",
                    "Attention",
                    MessageBoxButton.OK) == MessageBoxResult.OK)
                {
                    settings.Add(App.LSKEY_NOTIFY_DOWNLOADING_WITH_WIFI, true);
                    return;
                }
            }

            // Notify about >20 MB downloads
            if (!settings.Contains(App.LSKEY_NOTIFY_DOWNLOADING_WITH_CELLULAR)
                && episode.EpisodeDownloadSize > App.MAX_SIZE_FOR_CELLULAR_DOWNLOAD)
            {

                if (MessageBox.Show("You are about to download a file over 20 MB in size. Please " +
                                    "note that Windows Phone allows downloading this kind of files only if you are " +
                                    "connected to a WiFi network.",
                    "Attention",
                    MessageBoxButton.OK) == MessageBoxResult.OK)
                {
                    settings.Add(App.LSKEY_NOTIFY_DOWNLOADING_WITH_CELLULAR, true);
                    return;
                }
            }
        }
Exemple #22
0
        public void deleteEpisodeFromDB(PodcastEpisodeModel episode)
        {
            var queryDelEpisode = (from e in Episodes
                                   where episode.EpisodeId.Equals(episode.EpisodeId)
                                   select episode).FirstOrDefault();

            Episodes.DeleteOnSubmit(queryDelEpisode);
            SubmitChanges();
        }
        public static bool isAudioPodcast(PodcastEpisodeModel episode)
        {
            bool audio = false;

            // We have to treat empty as an audio, because that was what the previous
            // version had for mime type and we don't want to break the functionality.
            if (String.IsNullOrEmpty(episode.EpisodeFileMimeType))
            {
                return true;
            }

            switch (episode.EpisodeFileMimeType)
            {
                case "audio/mpeg":
                case "audio/mp3":
                case "audio/x-mp3":
                case "audio/mpeg3":
                case "audio/x-mpeg3":
                case "audio/mpg":
                case "audio/x-mpg":
                case "audio/x-mpegaudio":
                case "audio/x-m4a":
                case "audio/mpegaudio":
                case "audio/m4a":
                case "audio/x-mpeg":
                case "media/mpeg":
                case "x-audio/mp3":
                case "audio/x-mpegurl":
                    audio = true;
                    break;
            }

            return audio;
        }
 public void addSilentlyToPlayqueue(PodcastEpisodeModel episode)
 {
     addToPlayqueue(episode, false);
 }
        private string generateLocalEpisodeFileName(PodcastEpisodeModel podcastEpisode)
        {
            // Parse the filename of the logo from the remote URL.
            string localPath = new Uri(podcastEpisode.EpisodeDownloadUri).LocalPath;
            string podcastEpisodeFilename = localPath.Substring(localPath.LastIndexOf('/') + 1);

            podcastEpisodeFilename = PodcastSubscriptionsManager.sanitizeFilename(podcastEpisodeFilename);
            podcastEpisodeFilename = String.Format("{0}_{1}", DateTime.Now.Millisecond, podcastEpisodeFilename);

            string localPodcastEpisodeFilename = App.PODCAST_DL_DIR + "/" + podcastEpisodeFilename;
            Debug.WriteLine("Found episode filename: " + localPodcastEpisodeFilename);

            return localPodcastEpisodeFilename;
        }
        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.
        }
        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();
                }
            }
        }
        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;
        }
            public void updatePodcastEpisodes()
            {
                Debug.WriteLine("Updating episodes for podcast: " + m_subscriptionModel.PodcastName);

                bool subscriptionAddedNow = true;

                List <PodcastEpisodeModel> episodes = null;

                using (var db = new PodcastSqlModel())
                {
                    episodes = db.episodesForSubscription(m_subscriptionModel);
                }

                DateTime latestEpisodePublishDate = new DateTime();

                if (episodes.Count > 0)
                {
                    // The episodes are in descending order as per publish date.
                    // So take the first episode and we have the latest known publish date.
                    latestEpisodePublishDate = episodes[0].EpisodePublished;

                    // If we already have episodes, this subscription is not being added now.
                    subscriptionAddedNow = false;
                }

                episodes = null;

                Debug.WriteLine("\nStarting to parse episodes for podcast: " + m_subscriptionModel.PodcastName);
                List <PodcastEpisodeModel> newPodcastEpisodes = PodcastFactory.newPodcastEpisodes(m_subscriptionModel.CachedPodcastRSSFeed, latestEpisodePublishDate);

                m_subscriptionModel.CachedPodcastRSSFeed = "";

                if (newPodcastEpisodes == null)
                {
                    Debug.WriteLine("WARNING: Got null list of new episodes.");
                    return;
                }

                using (var db = new PodcastSqlModel())
                {
                    PodcastSubscriptionModel sub = db.Subscriptions.FirstOrDefault(s => s.PodcastId == m_subscriptionModel.PodcastId);
                    if (sub == null)
                    {
                        Debug.WriteLine("Subscription NULL. Probably already deleted.");
                        return;
                    }

                    PodcastEpisodeModel[] newEpisodesSet = new PodcastEpisodeModel[newPodcastEpisodes.Count];
                    newPodcastEpisodes.CopyTo(newEpisodesSet);

                    // Let's check for duplicate episode names. This can happen if the subscription updates the "pubDate"
                    // of the most recent episode in the feed, in which case the most recent one (at least) can become a duplicate entry.
                    foreach (PodcastEpisodeModel newEpisode in newEpisodesSet.AsEnumerable())
                    {
                        if (sub.Episodes.OrderByDescending(ep => ep.EpisodePublished).Take(10).ToArray().FirstOrDefault(ep => ep.EpisodeName == newEpisode.EpisodeName) != null)
                        {
                            Debug.WriteLine("Episode already found in the subscription, removing: " + newEpisode.EpisodeName);
                            newPodcastEpisodes.Remove(newEpisode);
                        }
                    }

                    db.insertEpisodesForSubscription(m_subscriptionModel, newPodcastEpisodes);

                    // Indicate new episodes to the UI only when we are not adding the feed.
                    // I.e. we want to show new episodes only when we refresh the feed at restart.
                    if (subscriptionAddedNow == false)
                    {
                        int numOfNewPodcasts = newPodcastEpisodes.Count;

                        Debug.WriteLine("Got {0} new episodes.", numOfNewPodcasts);
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            m_subscriptionModel.addNumOfNewEpisodes(numOfNewPodcasts);
                        });

                        sub.addNumOfNewEpisodes(numOfNewPodcasts);

                        db.SubmitChanges();
                    }
                }

                if (m_subscriptionModel.IsAutoDownload &&
                    newPodcastEpisodes.Count > 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        PodcastEpisodesDownloadManager.getInstance().addEpisodesToDownloadQueue(newPodcastEpisodes);
                    });
                }

                if (newPodcastEpisodes.Count > 0)
                {
                    // Update subscription's information if it's pinned to home screen.
                    updatePinnedInformation();

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        // This will call the setter for episode model in the UI that will notify the UI that the content has changed.
                        m_subscriptionModel.EpisodesPublishedDescending = new ObservableCollection <PodcastEpisodeModel>();
                    });
                }
            }
 private void audioStreaming(PodcastEpisodeModel podcastEpisode)
 {
     PodcastPlayerControl player = PodcastPlayerControl.getIntance();
     player.streamEpisode(podcastEpisode);
 }
        private void saveEpisodeInfoToDB(PodcastEpisodeModel m_currentEpisodeDownload)
        {
            if (m_currentEpisodeDownload == null)
            {
                return;
            }

            m_currentEpisodeDownload.StoreProperty<PodcastEpisodeModel.EpisodeDownloadStateEnum>("EpisodeDownloadState", m_currentEpisodeDownload.EpisodeDownloadState);
            m_currentEpisodeDownload.StoreProperty<String>("EpisodeFile", m_currentEpisodeDownload.EpisodeFile);
        }
        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 sendDownloadStateChangedEvent(PodcastEpisodeModel episode, PodcastEpisodeModel.EpisodeDownloadStateEnum state)
 {
     if (OnPodcastEpisodeDownloadStateChanged != null)
     {
         this.OnPodcastEpisodeDownloadStateChanged(this, new PodcastDownloadManagerArgs() { downloadState = state, episodeId = episode.EpisodeId });
     }
 }
 private void Page_Loaded(object sender, RoutedEventArgs e)
 {
     m_episodeModel = this.DataContext as PodcastEpisodeModel;
 }
        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 removeEpisodeFromDownloadQueue(PodcastEpisodeModel episode)
 {
     m_episodeDownloadQueue.RemoveItem(episode);
     episode.EpisodeDownloadState = PodcastEpisodeModel.EpisodeDownloadStateEnum.Idle;
     saveEpisodeInfoToDB(episode);
 }
        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);
            }
        }