Example #1
0
        public void UpdateNewSecondaryTile()
        {
            string      name               = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileName) as string;
            string      id                 = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileId) as string;
            string      type               = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileType) as string;
            XmlDocument tileXml            = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text02);
            XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");

            tileTextAttributes[0].InnerText = type;
            tileTextAttributes[1].InnerText = name;

            XmlDocument wideTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text09);
            XmlNodeList textAttr = wideTile.GetElementsByTagName("text");

            textAttr[0].InnerText = type;
            textAttr[1].InnerText = name;

            IXmlNode node = tileXml.ImportNode(wideTile.GetElementsByTagName("binding").Item(0), true);

            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

            TileNotification tileNotification = new TileNotification(tileXml);

            TileUpdateManager.CreateTileUpdaterForSecondaryTile(id).Update(tileNotification);
        }
Example #2
0
 private void StartPlayback()
 {
     try
     {
         if (Playlist.CurrentTrackName == string.Empty)
         {
             //If the task was cancelled we would have saved the current track and its position. We will try playback from there
             var currentTrackName     = ApplicationSettingsHelper.ReadResetSettingsValue(SharedStrings.BACKGROUND_AUDIO_CURRENT_TRACK);
             var currentTrackPosition = ApplicationSettingsHelper.ReadResetSettingsValue(SharedStrings.BACKGROUND_AUDIO_POSITION);
             if (currentTrackName != null)
             {
                 if (currentTrackPosition == null)
                 {
                     Playlist.StartTrackAt((string)currentTrackName);
                 }
                 else
                 {
                     Playlist.StartTrackAt((string)currentTrackName, TimeSpan.Parse((string)currentTrackPosition));
                 }
             }
             else
             {
                 Playlist.PlayAllTracks();
             }
         }
         else
         {
             BackgroundMediaPlayer.Current.Play();
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("CoffeeBackgroundAudioTask.StartPlayback: " + ex.ToString());
     }
 }
Example #3
0
        private void StartPlayback()
        {
            try
            {
                if (playbackStartedPreviously)
                {
                    BackgroundMediaPlayer.Current.Play();
                }
                else
                {
                    playbackStartedPreviously = true;

                    var currentTrackId       = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId);
                    var currentTrackPosition = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.Position);
                    if (currentTrackId == null)
                    {
                        BackgroundMediaPlayer.Current.Play();
                    }
                    else
                    {
                        var index = playbackList.Items.ToList().FindIndex(item =>
                                                                          GetTrackId(item) == (Uri)currentTrackId);

                        if (currentTrackPosition == null)
                        {
                            Debug.WriteLine("StartPlayback: Switching to track " + index);
                            playbackList.MoveTo((uint)index);

                            BackgroundMediaPlayer.Current.Play();
                        }
                        else
                        {
                            TypedEventHandler <MediaPlaybackList, CurrentMediaPlaybackItemChangedEventArgs> handler = null;
                            handler = (MediaPlaybackList list, CurrentMediaPlaybackItemChangedEventArgs args) =>
                            {
                                if (args.NewItem == playbackList.Items[index])
                                {
                                    playbackList.CurrentItemChanged -= handler;

                                    var position = (TimeSpan)currentTrackPosition;
                                    Debug.WriteLine("StartPlayback: Setting Position " + position);
                                    BackgroundMediaPlayer.Current.Position = position;

                                    BackgroundMediaPlayer.Current.Play();
                                }
                            };
                            playbackList.CurrentItemChanged += handler;

                            Debug.WriteLine("StartPlayback: Switching to track " + index);
                            playbackList.MoveTo((uint)index);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Example #4
0
        private void StartPlayback()
        {
            // If playback was already started once we can just resume playing.
            if (!playbackStartedPreviously)
            {
                playbackStartedPreviously = true;

                // If the task was cancelled we would have saved the current track and its position. We will try playback from there.
                string currentTrackId       = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId) as string;
                var    currentTrackPosition = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.Position);

                if (currentTrackId != null)
                {
                    // Find the index of the item by name
                    int index = playbackList.Items.ToList().FindIndex(item => GetTrackId(item) == currentTrackId);

                    if (currentTrackPosition == null)
                    {
                        // Play from start if we dont have position
                        playbackList.MoveTo((uint)index);
                        BackgroundMediaPlayer.Current.Play();
                    }
                    else
                    {
                        // Play from exact position otherwise
                        TypedEventHandler <MediaPlaybackList, CurrentMediaPlaybackItemChangedEventArgs> handler = null;
                        handler = (MediaPlaybackList list, CurrentMediaPlaybackItemChangedEventArgs args) =>
                        {
                            if (args.NewItem == playbackList.Items[index])
                            {
                                // Unsubscribe because this only had to run once for this item
                                playbackList.CurrentItemChanged -= handler;

                                // Set position
                                var position = TimeSpan.Parse((string)currentTrackPosition);
                                BackgroundMediaPlayer.Current.PlaybackSession.Position = position;

                                BackgroundMediaPlayer.Current.Play();
                            }
                        };
                        playbackList.CurrentItemChanged += handler;

                        // Switch to the track which will trigger an item changed event
                        playbackList.MoveTo((uint)index);
                    }
                }
                else
                {
                    BackgroundMediaPlayer.Current.Play();
                }
            }
            else
            {
                BackgroundMediaPlayer.Current.Play();
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine($"Background Audio Task {taskInstance.Task.Name} starting...");

            // Initialize SystemMediaTransportControls (SMTC) for integration with
            // the Universal Volume Control (UVC).
            //
            // The UI for the UVC must update even when the foreground process has been terminated
            // and therefore the SMTC is configured and updated from the background task.
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed    += smtc_ButtonPressed;
            smtc.PropertyChanged  += smtc_PropertyChanged;
            smtc.IsEnabled         = true;
            smtc.IsPauseEnabled    = true;
            smtc.IsPlayEnabled     = true;
            smtc.IsNextEnabled     = true;
            smtc.IsPreviousEnabled = true;

            // Read persisted state of foreground app
            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);

            if (value == null)
            {
                foregroundAppState = AppState.Unknown;
            }
            else
            {
                foregroundAppState = EnumHelper.Parse <AppState>(value.ToString());
            }

            // Add handlers for MediaPlayer
            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            // Initialize message channel
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            // Send information to foreground that background task has been started if app is active
            if (foregroundAppState != AppState.Suspended)
            {
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());
            }

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());

            deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)
            backgroundTaskStarted.Set();

            // Associate a cancellation and completed handlers with the background task.
            taskInstance.Task.Completed += TaskCompleted;
            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled); // event may raise immediately before continung thread excecution so must be at the end
        }
        private void PlayForFirstTime()
        {
            // If the task was cancelled we would have saved the current track and its position. We will try playback from there.
            var currentTrackId       = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId);
            var currentTrackPosition = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.Position);

            if (currentTrackId != null)
            {
                // Find the index of the item by name
                var index = playbackList.Items.ToList().FindIndex(item =>
                                                                  GetTrackId(item).ToString() == (string)currentTrackId);

                if (currentTrackPosition == null)
                {
                    // Play from start if we dont have position
                    Debug.WriteLine($"Switching to track {index}");
                    playbackList.MoveTo((uint)index);

                    // Begin playing
                    BackgroundMediaPlayer.Current.Play();
                }
                else
                {
                    // Play from exact position otherwise
                    TypedEventHandler <MediaPlaybackList, CurrentMediaPlaybackItemChangedEventArgs> handler = null;
                    handler = (MediaPlaybackList list, CurrentMediaPlaybackItemChangedEventArgs args) =>
                    {
                        if (args.NewItem == playbackList.Items[index])
                        {
                            // Unsubscribe because this only had to run once for this item
                            playbackList.CurrentItemChanged -= handler;

                            // Set position
                            var position = TimeSpan.Parse((string)currentTrackPosition);
                            Debug.WriteLine($"Setting Position {position}");
                            BackgroundMediaPlayer.Current.Position = position;

                            // Begin playing
                            BackgroundMediaPlayer.Current.Play();
                        }
                    };
                    playbackList.CurrentItemChanged += handler;

                    // Switch to the track which will trigger an item changed event
                    Debug.WriteLine($"Switching to track {index}");
                    playbackList.MoveTo((uint)index);
                }
            }
            else
            {
                BackgroundMediaPlayer.Current.Play();
            }
        }
Example #7
0
        /// <summary>
        /// Read persisted current track information from application settings
        /// </summary>
        private int GetCurrentTrackIdAfterAppResume()
        {
            object value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId);

            if (value != null)
            {
                return((int)value);
            }
            else
            {
                return(0);
            }
        }
Example #8
0
        private Uri GetCurrentTrackIdAfterAppResume()
        {
            object value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId);

            if (value != null)
            {
                return(new Uri((String)value));
            }
            else
            {
                return(null);
            }
        }
Example #9
0
 internal void DeleteCurrentAccount()
 {
     if (CurrentAccount == null)
     {
         return;
     }
     accountDataRepository?.Delete(CurrentAccount);
     if (ApplicationSettingsHelper.Contains(nameof(CurrentAccount.Pseudo), false) &&
         ApplicationSettingsHelper.ReadSettingsValue(nameof(CurrentAccount.Pseudo), false).ToString() == CurrentAccount.Pseudo)
     {
         ApplicationSettingsHelper.ReadResetSettingsValue(nameof(CurrentAccount.Pseudo), false);
         ApplicationSettingsHelper.ReadResetSettingsValue(nameof(CurrentAccount.Password), false);
     }
     CurrentAccount = null;
 }
Example #10
0
        public static void SaveFromSettingsToFile()
        {
            var a = ApplicationSettingsHelper.ReadResetSettingsValue("temperror");

            if (a != null)
            {
                try
                {
                    Save(a as string);
                    SaveToFile();
                }
                catch (Exception ex)
                {
                }
            }
        }
Example #11
0
        public async void UpdateNewSecondaryTile()
        {
            string name = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileName) as string;

            string[] s        = ParamConvert.ToStringArray(name);
            string   id       = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileId) as string;
            string   type     = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileType) as string;
            string   hasImage = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TileImage) as string;

            XmlDocument tileXml;

            //XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text02);
            //string imagePath = "ms-appx:///Assets/AppImages/Logo/Logo.png";

            if (hasImage == "no")
            {
                tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text02);
            }
            else
            {
                tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText02);
                var tileImageAttributes = tileXml.GetElementsByTagName("image");
                tileImageAttributes[0].Attributes.GetNamedItem("src").NodeValue = "ms-appdata:///local/" + id + ".jpg";
                //tileImageAttributes[0].Attributes.GetNamedItem("alt").NodeValue = "album cover";
            }

            XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");

            tileTextAttributes[0].InnerText = type;
            tileTextAttributes[1].InnerText = s[0] + "\n" + s[1];


            XmlDocument wideTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text09);
            XmlNodeList textAttr = wideTile.GetElementsByTagName("text");

            textAttr[0].InnerText = type;
            textAttr[1].InnerText = s[0] + "\n" + s[1];

            IXmlNode node = tileXml.ImportNode(wideTile.GetElementsByTagName("binding").Item(0), true);

            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

            TileNotification tileNotification = new TileNotification(tileXml);

            TileUpdateManager.CreateTileUpdaterForSecondaryTile(id).Update(tileNotification);
        }
Example #12
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            transportControl = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            if (transportControl != null)
            {
                transportControl.ButtonPressed    += transportControl_ButtonPressed;
                transportControl.PropertyChanged  += transportControl_PropertyChanged;
                transportControl.IsEnabled         = true;
                transportControl.IsPauseEnabled    = true;
                transportControl.IsPlayEnabled     = true;
                transportControl.IsNextEnabled     = true;
                transportControl.IsPreviousEnabled = true;
            }

            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled);
            taskInstance.Task.Completed += Taskcompleted;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(SharedStrings.BACKGROUND_AUDIO_APP_STATE);

            if (value == null)
            {
                foregroundAppState = ForegroundAppStatus.Unknown;
            }
            else
            {
                foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString());
            }

            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
            Playlist.TrackChanged += playList_TrackChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            //Send information to foreground that background task has been started if app is active
            if (foregroundAppState != ForegroundAppStatus.Suspended)
            {
                ValueSet message = new ValueSet();
                message.Add(SharedStrings.BACKGROUND_AUDIO_STARTED, "");
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }
            backgroundTaskStarted.Set();
            backgroundTaskRunning = true;

            ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_STATE, SharedStrings.BACKGROUND_AUDIO_RUNNING);
            deferral = taskInstance.GetDeferral();
        }
Example #13
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            nowPlayingManager = new NowPlayingManager();

            systemControls = SystemMediaTransportControls.GetForCurrentView();
            systemControls.ButtonPressed    += HandleButtonPressed;
            systemControls.PropertyChanged  += HandlePropertyChanged;
            systemControls.IsEnabled         = true;
            systemControls.IsPauseEnabled    = true;
            systemControls.IsPlayEnabled     = true;
            systemControls.IsPreviousEnabled = true;
            systemControls.IsNextEnabled     = true;

            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled);
            taskInstance.Task.Completed += HandleTaskCompleted;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.AppState);

            if (value == null)
            {
                foregroundTaskStatus = ForegroundTaskStatus.Unknown;
            }
            else
            {
                foregroundTaskStatus = (ForegroundTaskStatus)Enum.Parse(typeof(ForegroundTaskStatus), value.ToString());
            }

            BackgroundMediaPlayer.Current.CurrentStateChanged   += BGCurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += MessageReceivedFromForeground;

            //taskInstance.Task.Progress += HandleTaskProgress;

            if (foregroundTaskStatus != ForegroundTaskStatus.Suspended)
            {
                ValueSet message = new ValueSet();
                message.Add(AppConstants.BackgroundTaskStarted, "");
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }

            backgroundTaskStarted.Set();
            backgroundTaskStatus = true;
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.BackgroundTaskState, AppConstants.BackgroundTaskRunning);
            shutdown = false;
            deferral = taskInstance.GetDeferral();
        }
Example #14
0
        private void UpdateDB()
        {
            //var settings = ApplicationData.Current.LocalSettings;

            //if (!settings.Values.ContainsKey(AppConstants.DBVersion))
            //{
            //    DatabaseManager.UpdateDBToVersion2();
            //    settings.Values.Add(AppConstants.DBVersion, "2");
            //}
            int v = (int)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.DBVersion);

            if (v == 2)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.DBVersion, 3);
                ApplicationSettingsHelper.ReadResetSettingsValue("savelaterlyrics");
                DatabaseManager.UpdateDBToVersion3();
            }
        }
Example #15
0
        public void Activate(object parameter, Dictionary <string, object> state)
        {
            //NextPlayerDataLayer.Diagnostics.Logger.Save("FG Main activate");
            //NextPlayerDataLayer.Diagnostics.Logger.SaveToFile();
            int index = CurrentSongIndex;

            if (index > -1 && Library.Current.NowPlayingList.Count > 0)
            {
                SongItem song = Library.Current.NowPlayingList.ElementAt(index);
                Title  = song.Title;
                Artist = song.Artist;
                SetCover(song.Path);
            }
            else
            {
                Title  = "-";
                Artist = "-";
                SetDefaultCover();
            }
            //StartBackgroundAudioTask(AppConstants.StartPlayback, CurrentSongIndex);
            if (IsMyBackgroundTaskRunning)
            {
                AddMediaPlayerEventHandlers();
            }
            else
            {
                //StartBackgroundAudioTask(AppConstants.StartPlayback, CurrentSongIndex);
            }

            if (ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.TilePlay) != null)
            {
                if (IsMyBackgroundTaskRunning)
                {
                    SendMessage(AppConstants.NowPlayingListChanged);
                    SendMessage(AppConstants.StartPlayback, 0);
                }
                else
                {
                    StartBackgroundAudioTask(AppConstants.StartPlayback, CurrentSongIndex);
                }
            }
        }
Example #16
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");

            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed    += smtc_ButtonPressed;
            smtc.PropertyChanged  += smtc_PropertyChanged;
            smtc.IsEnabled         = true;
            smtc.IsPauseEnabled    = true;
            smtc.IsPlayEnabled     = true;
            smtc.IsNextEnabled     = true;
            smtc.IsPreviousEnabled = true;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);

            if (value == null)
            {
                foregroundAppState = AppState.Unknow;
            }
            else
            {
                foregroundAppState = (AppState)value;
            }

            BackgroundMediaPlayer.Current.CurrentStateChanged   += Current_CurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            if (foregroundAppState != AppState.Suspended)
            {
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());
            }

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running);

            deferral = taskInstance.GetDeferral();

            backgroundTaskStarted.Set();

            taskInstance.Task.Completed += Task_Completed;
            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled);
        }
Example #17
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed    += OnSmtcButtonPressed;
            smtc.PropertyChanged  += OnSmtcPropertyChanged;
            smtc.IsEnabled         = true;
            smtc.IsPauseEnabled    = true;
            smtc.IsPlayEnabled     = true;
            smtc.IsNextEnabled     = true;
            smtc.IsPreviousEnabled = true;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);

            if (value == null)
            {
                foregroundAppState = AppState.Unknown;
            }
            else
            {
                foregroundAppState = EnumHelper.Parse <AppState>(value.ToString());
            }

            BackgroundMediaPlayer.Current.CurrentStateChanged   += OnMediaPlayerCurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += OnMessageFromForegroundReceived;

            if (foregroundAppState != AppState.Suspended)
            {
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());
            }

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());

            deferral = taskInstance.GetDeferral();

            backgroundTaskStarted.Set();

            taskInstance.Task.Completed += (s, a) => deferral.Complete();
            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled);
        }
Example #18
0
        void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Logger.SaveInSettings(e.Exception.ToString() + "\nMessage:\n" + e.Message);

            if (e != null)
            {
                Exception exception = e.Exception;
                if (exception is NullReferenceException && exception.ToString().ToUpper().Contains("SOMA"))
                {
                    Debug.WriteLine("Handled Smaato null reference exception {0}", exception);
                    e.Handled = true;
                    return;
                }
                else if (exception.ToString().Contains("AdDuplex"))
                {
                    e.Handled = true;
                    return;
                }
            }

            ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.MediaScan);
            int i   = ApplicationSettingsHelper.ReadSongIndex();
            int npc = Library.Current.NowPlayingList.Count;

            if (i >= 0 && npc > 0 && npc > i)
            {
                ApplicationSettingsHelper.SaveSongIndex(i);
            }
            else
            {
                ApplicationSettingsHelper.SaveSongIndex(-1);
                if (npc >= 0)
                {
                    ApplicationSettingsHelper.SaveSongIndex(0);
                }
            }
            DiagnosticHelper.TrackTrace("Unhandled Exception " + e.Exception.ToString() + "\n" + e.Message, Microsoft.HockeyApp.SeverityLevel.Error);
        }
Example #19
0
        public async static Task ImportAndUpdateDatabase(IProgress <int> progress)
        {
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.MediaScan, true);
            IReadOnlyList <StorageFile> list = await KnownFolders.MusicLibrary.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName);

            int all   = list.Count;
            int count = 1;
            Tuple <int, int> tuple;
            Dictionary <string, Tuple <int, int> > dict = DatabaseManager.GetFilePaths();

            int w1;
            int w2;

            List <int>      toAvailable = new List <int>();//lista songId
            List <SongData> newSongs    = new List <SongData>();

            foreach (var file in list)
            {
                string type = file.FileType.ToLower();
                if (type == ".mp3" || type == ".m4a" || type == ".wma" ||
                    type == ".wav" || type == ".aac" || type == ".asf" ||
                    type == ".adt" || type == ".adts" || type == ".amr")
                {
                    //Windows.Storage.FileProperties.BasicProperties bp = await file.GetBasicPropertiesAsync();
                    // Sprawdzanie rozmiaru nie dziaƂa
                    if (dict.TryGetValue(file.Path, out tuple))
                    {
                        if (tuple.Item1 == 0)//zaznaczony jako niedostepny
                        {
                            toAvailable.Add(tuple.Item2);
                        }
                        else//zaznaczony jako dostepny
                        {
                            toAvailable.Add(tuple.Item2);
                        }
                    }
                    else
                    {
                        SongData song = await CreateSongFromFile(file);

                        newSongs.Add(song);
                    }
                }
                w1 = (100 * count / all);
                w2 = (100 * (count - 1) / all);

                if (progress != null && w1 != w2)
                {
                    progress.Report(w1);
                }
                count++;
            }
            progress.Report(99);
            DatabaseManager.ChangeAvailability(toAvailable);
            Library.Current.CheckNPAfterUpdate(toAvailable);
            await DatabaseManager.InsertSongsAsync(newSongs);

            ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.MediaScan);
            OnMediaImported("Update");
            SendToast();
        }
Example #20
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            initialization = true;
            if (e.PageState != null && e.PageState.ContainsKey("pivotIndex"))
            {
                PivotSettings.SelectedIndex = (int)e.PageState["pivotIndex"];
            }

            //General Settings
            //Library scan
            var a = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.MediaScan);

            if (a != null)
            {
                DisableControls();
            }
            //Timer
            var d = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TimerTime);

            var t = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TimerOn);

            if (t == null)
            {
                isTimerOn = false;
            }
            else
            {
                isTimerOn = (bool)t;
            }

            if (isTimerOn)
            {
                timerPicker.IsEnabled  = true;
                timerToggleSwitch.IsOn = true;

                if (d != null)
                {
                    loading          = true;
                    timerPicker.Time = TimeSpan.FromTicks((long)d);
                }
            }
            else
            {
                timerPicker.IsEnabled  = false;
                timerToggleSwitch.IsOn = false;
            }
            //Transparent tile
            string isTr = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TileAppTransparent) as string;

            if (isTr == "yes")
            {
                transparentToggleSwitch.IsOn = true;
            }

            //Personalize
            //Color accent
            bool isPhoneAccent = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsPhoneAccentSet);

            if (isPhoneAccent)
            {
                phoneAccentToggleSwitch.IsOn = true;
            }
            //Theme
            string appTheme = (string)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.AppTheme);

            if (appTheme.Equals(AppThemeEnum.Dark.ToString()))
            {
                RBDark.IsChecked = true;
            }
            else if (appTheme.Equals(AppThemeEnum.Light.ToString()))
            {
                RBLight.IsChecked = true;
            }
            //Background image
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsBGImageSet))
            {
                ShowBGImage_ToggleSwitch.IsOn = true;
                //SelectImage_Button.IsEnabled = true;
            }
            else
            {
                ShowBGImage_ToggleSwitch.IsOn = false;
                //SelectImage_Button.IsEnabled = false;
            }
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.ShowCoverAsBackground))
            {
                ShowAlbumCover_ToggleSwitch.IsOn = true;
            }

            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmSendNP))
            {
                ToggleSwitchSendNP.IsOn = true;
            }
            else
            {
                ToggleSwitchSendNP.IsOn = false;
            }
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmRateSongs))
            {
                ToggleSwitchLoveTrack.IsOn = true;
            }
            else
            {
                ToggleSwitchLoveTrack.IsOn = false;
            }
            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmPassword).ToString() == "")
            {
                LFMLogoutButton.Visibility = Visibility.Collapsed;
                LFMLoginButton.Visibility  = Visibility.Visible;
            }
            else
            {
                LFMLoginButton.Visibility  = Visibility.Collapsed;
                LFMLogoutButton.Visibility = Visibility.Visible;

                TBLogin.Visibility          = Visibility.Collapsed;
                TBPassword.Visibility       = Visibility.Collapsed;
                TBYouAreLoggedIn.Visibility = Visibility.Visible;

                LFMPassword.Visibility = Visibility.Collapsed;
                LFMLogin.Visibility    = Visibility.Collapsed;
            }
            int love   = Int32.Parse(ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.LfmLove).ToString());
            int unlove = Int32.Parse(ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.LfmUnLove).ToString());

            MaxUnLove.SelectedIndex = unlove - 1;
            MinLove.SelectedIndex   = love - 1;


            var navigableViewModel = this.DataContext as INavigable;

            if (navigableViewModel != null)
            {
                navigableViewModel.Activate(e.NavigationParameter, e.PageState);
            }
            initialization = false;
            //App.TelemetryClient.TrackEvent("Settings page open");
        }
Example #21
0
        public void Activate(object parameter, Dictionary <string, object> state)
        {
            //App.Current.Suspending += ForegroundApp_Suspending;
            //App.Current.Resuming += ForegroundApp_Resuming;

            index = CurrentSongIndex;
            if (index > -1)
            {
                SongItem song = Library.Current.NowPlayingList.ElementAt(index);
                CurrentNr  = index + 1;
                SongsCount = Library.Current.NowPlayingList.Count;
                songId     = song.SongId;
                Title      = song.Title;
                Artist     = song.Artist;
                Album      = song.Album;
                fromDB     = true;
                Rating     = song.Rating;
                //PlaybackRate = 100.0;
                SetCover(song.Path);

                SetupTimer();

                RepeatButtonContent     = Repeat.CurrentStateContent();
                RepeatButtonForeground  = Repeat.CurrentStateColor();
                ShuffleButtonForeground = Shuffle.CurrentStateColor();

                if (IsMyBackgroundTaskRunning)
                {
                    //Library.Current.Save("BG running");

                    AddMediaPlayerEventHandlers();

                    if (BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Playing)
                    {
                        PlayButtonContent = "\uE17e\uE103";//pause
                    }

                    object r = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.ResumePlayback);
                    if (r != null)
                    {
                        SendMessage(AppConstants.ResumePlayback);
                        TimeSpan t        = BackgroundMediaPlayer.Current.NaturalDuration;
                        double   absvalue = (int)Math.Round(t.TotalSeconds - 0.5, MidpointRounding.AwayFromZero);
                        ProgressBarMaxValue = absvalue;
                        EndTime             = BackgroundMediaPlayer.Current.NaturalDuration;
                        PlaybackRate        = BackgroundMediaPlayer.Current.PlaybackRate * 100.0;
                    }
                    else if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("lyrics"))//mozna chyba zmienic na Dict<> state
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("lyrics");
                    }
                    else if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("nplist"))//mozna chyba zmienic na Dict<> state
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("nplist");
                    }
                    else if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("mainpage"))//mozna chyba zmienic na Dict<> state
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("mainpage");

                        TimeSpan t        = BackgroundMediaPlayer.Current.NaturalDuration;
                        double   absvalue = (int)Math.Round(t.TotalSeconds - 0.5, MidpointRounding.AwayFromZero);
                        ProgressBarMaxValue = absvalue;
                        EndTime             = BackgroundMediaPlayer.Current.NaturalDuration;
                        PlaybackRate        = BackgroundMediaPlayer.Current.PlaybackRate * 100.0;
                    }
                    else
                    {
                        SendMessage(AppConstants.NowPlayingListChanged);
                        SendMessage(AppConstants.StartPlayback, CurrentSongIndex);
                    }
                }
                else
                {
                    if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("mainpage"))
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("mainpage");
                    }
                    object r = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.ResumePlayback);
                    //if (r != null)
                    //{
                    //    StartBackgroundAudioTask(AppConstants.ResumePlayback, CurrentSongIndex);
                    //}
                    //else
                    //{
                    StartBackgroundAudioTask(AppConstants.StartPlayback, CurrentSongIndex);
                    //}
                }
                StartTimer();
            }
            else
            {
                navigationService.NavigateTo(ViewNames.MainView);
            }
            //if (parameter != null)
            //{

            //    if (parameter.GetType() == typeof(int))
            //    {
            //        songId = (int)parameter;
            //    }
            //}
        }
Example #22
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            HockeyClient.Current.Configure("");

            //App.Current.RequestedTheme = ApplicationTheme.Dark;
            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
            ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.MediaScan);
            var settings = ApplicationData.Current.LocalSettings;

            if (FirstRun())
            {
                //jesli jest DB jest tworzone po wersji 1.5.1.0 przy tworzeniu bazy trzeba zapisac jej wersje
                Library.Current.SetDB();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.AppTheme, AppThemeEnum.Dark.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.IsPhoneAccentSet, true);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.AppAccent, "#FF008A00");
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.IsBGImageSet, false);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.BackgroundImagePath, "");
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.ShowCoverAsBackground, true);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileAppTransparent, "yes");
                //DiagnosticHelper.TrackTrace("New instalation",Microsoft.HockeyApp.SeverityLevel.Information);
            }
            else
            {
                ManageSecondaryTileImages();

                if (!settings.Values.ContainsKey(AppConstants.BackgroundImagePath))
                {
                    settings.Values.Add(AppConstants.BackgroundImagePath, "");
                }
                if (!settings.Values.ContainsKey(AppConstants.IsBGImageSet))
                {
                    settings.Values.Add(AppConstants.IsBGImageSet, false);
                }
                if (!settings.Values.ContainsKey(AppConstants.AppTheme))
                {
                    settings.Values.Add(AppConstants.AppTheme, AppThemeEnum.Dark.ToString());
                }
                if (!settings.Values.ContainsKey(AppConstants.IsPhoneAccentSet))
                {
                    settings.Values.Add(AppConstants.IsPhoneAccentSet, true);
                }
                if (!settings.Values.ContainsKey(AppConstants.AppAccent))
                {
                    settings.Values.Add(AppConstants.AppAccent, "#FF008A00");
                }
                if (!settings.Values.ContainsKey(AppConstants.ShowCoverAsBackground))
                {
                    settings.Values.Add(AppConstants.ShowCoverAsBackground, true);
                }

                string theme = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.AppTheme) as string;
                if (theme.Equals(AppThemeEnum.Dark.ToString()))
                {
                    App.Current.RequestedTheme = ApplicationTheme.Dark;
                }
                else if (theme.Equals(AppThemeEnum.Light.ToString()))
                {
                    App.Current.RequestedTheme = ApplicationTheme.Light;
                }

                SendLogs();

                //SaveLater.Current.SaveAllNow();
                UpdateDB();
                Logger.SaveFromSettingsToFile();
                CreateTask();
            }
            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TileAppTransparent) == null)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileAppTransparent, "yes");
            }
            #region LastFm

            //aplikacja jest uruchomiona 1 raz lub po aktualizacji
            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmRateSongs) == null)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmRateSongs, true);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmLove, 5);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmUnLove, 1);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmSendNP, false);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmLogin, "");
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmPassword, "");
            }

            LastFmLove   = Int32.Parse(ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmLove).ToString());
            LastFmUnLove = Int32.Parse(ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmUnLove).ToString());
            LastFmRateOn = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmRateSongs);
            LastFmSendNP = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmSendNP);

            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LastFmDBVersion) == null)
            {
                DatabaseManager.CreateLastFmDB();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LastFmDBVersion, 1);
            }
            else if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LastFmDBVersion).ToString() == "1")
            {
                DatabaseManager.DeleteLastFmDB();
                DatabaseManager.CreateLastFmDB();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LastFmDBVersion, 2);
            }

            #endregion LastFm

            UnhandledException += App_UnhandledException;
        }