Наследование: Crystal.Dynamic.AutoIPNotifyingBaseModel
Пример #1
0
        private async void LoadSongHistory(Station station)
        {
            IsBusy = true;

            var url = BackgroundAudioPlayer.Instance.Track.Tag.Split('$').Last();
            var songData = await Hanasu.Tools.Shoutcast.ShoutcastService.GetShoutcastStationSongHistory(station, url);
            SongHistory = songData;

            IsBusy = false;
        }
Пример #2
0
        static internal SongData ParseSongData(string songData, Station station)
        {
            var a = new SongData();

            songData = CleanSongDataStr(songData);
            var bits = songData.Split(new string[] { " - " }, 2, StringSplitOptions.None);

            a.Artist = bits[0];
            a.TrackTitle = bits[1];

            return a;
        }
Пример #3
0
        public static async Task<ObservableCollection<ShoutcastSongHistoryItem>> GetShoutcastStationSongHistory(Station station, string url)
        {
            var items = await GetShoutcastStationSongHistoryOld(station, url);

            var coll = new ObservableCollection<ShoutcastSongHistoryItem>();

            foreach (var item in items)
                coll.Add(new ShoutcastSongHistoryItem() { Time = DateTime.Parse(item.Key), Song = item.Value });


            return coll;
        }
Пример #4
0
        public NowPlayingViewModel()
        {
            if (!IsDesignMode)
            {
                IsPlaying = true;
                CurrentStation = new Station() { Title = "XAMFM", ImageUrl = "https://si0.twimg.com/profile_images/1104224483/logo_transbkgr.png" };
                CurrentTrack = "Uprising";
                CurrentArtist = "Pieman";
            }

            PlaybackEngine.Engine.MetadataChanged += Engine_MetadataChanged;
            PlaybackEngine.Engine.PlaybackStatusChanged += Engine_PlaybackStatusChanged;

            CurrentArtist = PlaybackEngine.CurrentArtist;
            CurrentTrack = PlaybackEngine.CurrentTrack;
        }
Пример #5
0
        public static async Task<bool> IsSongTitle(string name, Station currentStation)
        {
            //cheap way to check if its a song title. not perfect and doesn't work 100% of the time.

            return await Task.Run(() =>
                {
                    bool res = false;

                    if (name.Contains(" - "))
                    {
                        res = name.ToLower().Contains(currentStation.Title.ToLower()) == false && name.Split(' ').Length > 1;
                    }
                    else if (System.Text.RegularExpressions.Regex.IsMatch(name.ToLower(), @"(^)?(http\://)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?($|\W)?"))
                        res = false;

                    return res;
                });
        }
Пример #6
0
        public MainPageNowPlayingViewModel()
        {
            try
            {
                if (!IsDesignMode)
                {
                    BackgroundAudioPlayer.Instance.PlayStateChanged += Instance_PlayStateChanged;

                    if (App.Current != null)
                        ((HanasuWP8.App)App.Current).Exit2 += MainPageNowPlayingViewModel_Exit2;

                    if (timer == null)
                        timer = new DispatcherTimer();

                    timer.Tick += timer_Tick;
                    timer.Interval = new TimeSpan(0, 0, 3);

                    SongHistoryCommand = CommandManager.CreateCommand(x =>
                        {
                            NavigationService.NavigateTo<SongHistoryViewModel>(new KeyValuePair<string, string>("Station", CurrentStation.Title));
                        }, y => CurrentStation != null && CurrentStation.ServerType.ToLower() == "shoutcast");

                    SynchronizeBAPStatus();
                }
                else
                {
                    //False data for the design view.
                    IsPlaying = true;
                    CurrentCover = "https://si0.twimg.com/profile_images/1104224483/logo_transbkgr.png";
                    CurrentTrack = "Super-moo!";
                    CurrentArtist = "Amrykid";
                    CurrentStation = new Station() { Title = "AmryFM" };
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>().ShowMessage("Exception", ex.ToString());
#endif
            }
        }
Пример #7
0
        public static async Task<SongData> GetShoutcastStationCurrentSong(Station station, string url)
        {

            var html = await HtmlTextUtility.GetHtmlFromUrl2(url.ToString().Replace("\r",""));
            var songtable = Regex.Matches(html, "<table.+?>.+?</table>", RegexOptions.Singleline)[2];
            var entries = Regex.Matches(songtable.Value,
                "<tr>.+?</tr>",
                RegexOptions.Singleline);

            var songEntry = entries[entries.Count - 1];
            var songData = Regex.Match(songEntry.Value, "<b>.+?</b>", RegexOptions.Singleline).Value;
            songData = Regex.Replace(songData, "<.+?>", "", RegexOptions.Singleline).Trim();
            songData = SongService.CleanSongDataStr(songData);

            //Uri lyrics = null;
            //if (GlobalHanasuCore.SongService.IsSongAvailable(songData, station, out lyrics))
            //    return GlobalHanasuCore.SongService.GetSongData(songData, station);
            //else
            if (await SongService.IsSongTitle(songData, station))
                return SongService.ParseSongData(songData, station);
            else throw new Exception();
        }
Пример #8
0
        public static async Task<Dictionary<string, string>> GetShoutcastStationSongHistoryOld(Station station, string url)
        {
           
            if (url.EndsWith("/") == false)
                url += "/";
            url += "played.html";

            var html = await Hanasu.Core.Utilities.HtmlTextUtility.GetHtmlFromUrl2(url);

            var songtable = Regex.Matches(html, "<table.+?>.+?</table>", RegexOptions.Singleline)[1];
            var entries = Regex.Matches(songtable.Value,
                "<tr>.+?</tr>",
                RegexOptions.Singleline);

            var his = new Dictionary<string, string>();

            await Task.Run(() =>
                {
                    for (int i = 1; i < entries.Count; i++)
                    {
                        var entry = entries[i];
                        var bits = Regex.Matches(
                                Regex.Replace(
                                    entry.Value, "<b>Current Song</b>", "", RegexOptions.Singleline),
                            "<td>.+?(</td>|</tr>)", RegexOptions.Singleline);

                        var key = Regex.Replace(bits[0].Value, "<.+?>", "", RegexOptions.Singleline).Trim();
                        var val = Regex.Replace(bits[1].Value, "<.+?>", "", RegexOptions.Singleline).Trim();
                        if (his.ContainsKey(key) == false)
                            his.Add(key,
                                val);
                    }
                });

            return his;
        }
Пример #9
0
        private async Task PlayStation(Station y)
        {
            //if (IsBusy) return;

            if (!playCommandLock.WaitOne(5000)) return;

            Microsoft.Xna.Framework.FrameworkDispatcher.Update();
            if (!Microsoft.Xna.Framework.Media.MediaPlayer.GameHasControl && BackgroundAudioPlayer.Instance.Track == null)
                if (ServiceManager.Resolve<IMessageBoxService>()
                        .ShowOkayCancelMessage("Playing Media", "By proceeding, your current media will stop and the selected station will be played instead.") == false)
                {
                    playCommandLock.Set();
                    return;
                }


            //try
            //{
            //    if (App.IsPlaying)
            //    {
            //        IsBusy = true;

            //        Status = "Working...";

            //        try
            //        {
            //            //BackgroundAudioPlayer.Instance.Stop();
            //            //BackgroundAudioPlayer.Instance.Track = null;
            //            BackgroundAudioPlayer.Instance.Close();
            //            //BAPClosed = true;
            //        }
            //        catch (Exception) { }

            //        //await Task.Delay(2000);
            //    }
            //}
            //catch (Exception) { }

            Status = "Connecting...";

            IsBusy = true;
            AreStationsChoosable = false;

            Station station = (Station)y;

            var url = station.StreamUrl.Trim();

            if (BackgroundAudioPlayer.Instance.Volume != 0.5)
                BackgroundAudioPlayer.Instance.Volume = 0.5;

            bool preprocessingNeeded = false;
            try
            {
                if (preprocessingNeeded = await PreprocessorService.CheckIfPreprocessingIsNeeded(url))
                    url = (await PreprocessorService.GetProcessor(new Uri(url)).Process(new Uri(url))).ToString().Replace("\r/", "");
            }
            catch (Exception)
            {
                url = null;

                ServiceManager.Resolve<IMessageBoxService>().ShowMessage("Uh-oh!",
                        "Unable to retrieve this station's streaming url.");
            }

            if (url != null)
            {
                BackgroundAudioPlayer.Instance.Track = new AudioTrack(station.ServerType.ToLower() == "raw" ? new Uri(url) : null, station.Title, null, null, new Uri(station.ImageUrl),
                    "Hanasu$" + string.Join("$", station.Title, station.ServerType, url), EnabledPlayerControls.Pause);

                if (BAPClosed)
                {
                    BackgroundAudioPlayer.Instance.Play();
                    BAPClosed = false;
                }

                bool openedEvents = false;
                if (connectedEvent == null)
                {
                    await OpenEvents();

                    if (connectedEvent == null || errorEvent == null)
                        openedEvents = false;
                    else
                        openedEvents = true;
                }


                var playTask = connectedEvent.WaitAsync().AsTask();
                var errorTask = errorEvent.WaitAsync().AsTask();

                var timeoutTask = Task.Delay(System.Diagnostics.Debugger.IsAttached ? 12000 : 7000);

                var what = await Task.WhenAny(playTask, timeoutTask, errorTask);

                if ((what == timeoutTask || what == errorTask || !openedEvents) && !App.IsPlaying)
                {
                    ServiceManager.Resolve<IMessageBoxService>().ShowMessage("Uh-oh!",
                        what == timeoutTask ? "Unable to connect in a timely fashion!" : what == errorTask ? "An error occurred while connecting." : "Something bad happened!");

#if DEBUG
                    var error = BackgroundAudioPlayer.Instance.Error;
                    if (System.Diagnostics.Debugger.IsAttached && error != null)
                    {
                        System.Diagnostics.Debugger.Log(4, "Exception", error.ToString());
                        System.Diagnostics.Debugger.Break();
                    }
#endif

                    BackgroundAudioPlayer.Instance.Stop();
                    //BackgroundAudioPlayer.Instance.Close();

                    //Status = "Rewinding state...";
                    //await Task.Delay(5000);

                    //BAPClosed = true;
                }
                else
                {
                    //Station is playing... or it should be.

                    Messenger.PushMessage(this, "SwitchTab", 0);
                }
            }

            Status = null;

            IsBusy = false;

            AreStationsChoosable = true;

            playCommandLock.Set();
        }
Пример #10
0
 public static void StartPlaying(Station station)
 {
     //check if preprocessing is needed?
     //engine.Play(station.StreamUrl);
 }
Пример #11
0
        public async void PlayStation(Station s, Windows.UI.Xaml.Controls.MediaElement me, bool navigate = true)
        {
            if (s == null) return;

            if (!NetworkCostController.IsConnectedToInternet) //makes sure Hanasu is connected to the internet.
            {
                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                    .ShowMessage(
                        LocalizationManager.GetLocalizedValue("InternetConnectionHeader"),
                        LocalizationManager.GetLocalizedValue("NoInternetConnectionMsg"));
                return;
            }

            if (NetworkCostController.CurrentNetworkingBehavior == NetworkingBehavior.Opt_In) //if the user is roaming and/or over the data limit, notify them
            {
                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                    .ShowMessage(
                        LocalizationManager.GetLocalizedValue("DataConstraintsHeader"),
                        LocalizationManager.GetLocalizedValue("StreamingDisabled2Msg"));

                return;
            }

            // Reset things things are ready to be played.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                {
                    SetMediaElement(ref me);

                    CurrentStation = s;
                    CurrentStationSongData = null;
                    CurrentStationStreamedUri = null;
                });

            StorageFile albumFile = await GetStationAlbumFromCache(); //Grab the current station's logo from the cache.

            if (albumFile != null)
                MediaControl.AlbumArt = new Uri("ms-appdata:///local/Hanasu/" + albumFile.DisplayName); //Set the logo in the media control.
            MediaControl.ArtistName = CurrentStation.Title; //set the station's name
            MediaControl.IsPlaying = true;

            try
            {

                if (me.CurrentState == MediaElementState.Playing || me.CurrentState == MediaElementState.Opening || me.CurrentState == MediaElementState.Buffering)
                {
                    me.Pause();
                    await Task.Delay(1000);
                    me.Stop();
                }

                Uri finalUri = new Uri(s.StreamUrl, UriKind.Absolute);

                if (await Hanasu.Core.Preprocessor.PreprocessorService.CheckIfPreprocessingIsNeeded(finalUri, s.PreprocessorFormat))
                    finalUri = await Hanasu.Core.Preprocessor.PreprocessorService.GetProcessor(finalUri, s.PreprocessorFormat).Process(finalUri);

                CurrentStationStreamedUri = finalUri;

                //if (CurrentStation.ServerType.ToLower() == "shoutcast")
                //{
                //    var str = await ShoutcastService.GetShoutcastStream(finalUri);
                //    mediaElement.SetSource(str, str.Content_Type);

                //    mediaElement.Play();
                //}
                //else
                //{

                //finalUri = new Uri(finalUri.ToString() + ";stream.nsv", UriKind.Absolute);

                try
                {
                    System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();

                    var openTask = mediaElement.OpenAsync(finalUri, cts.Token);
                    var timeoutTask = Task.Delay(10000); //Wait for a connection for 10 seconds.

                    var successful = await Task.WhenAny(openTask, timeoutTask);

                    if (successful == timeoutTask)
                    {
                        //timeout. inform the user and back out.

                        IsPlaying = false;

                        Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                            .ShowMessage(
                                 LocalizationManager.GetLocalizedValue("StreamingErrorHeader"),
                                 LocalizationManager.GetLocalizedValue("StreamingConnectionTimeoutMsg"));

                        cts.Cancel();
                        cts.Dispose();

                        ResetStationInfo();

                        return;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is TaskCanceledException) return;

                    throw ex;
                }

                if (navigate && IsPlaying)
                    NavigateToNowPlayingPage(finalUri);

                try
                {
                    if (!PlayToController.IsConnectedViaPlayTo)
                    {
                        var playTask = mediaElement.PlayAsync(System.Threading.CancellationToken.None);
                        IsPlaying = true;
                        await playTask;
                    }
                    else
                        IsPlaying = true;
                }
                catch (Exception ex)
                {
                    if (ex is TaskCanceledException) return;

                    throw ex;
                }

                //}
            }
            catch (Exception ex)
            {
                if (mediaElement.CurrentState == MediaElementState.Playing || mediaElement.CurrentState == MediaElementState.Opening) return; //Ignorable error. Probably nothing.

                IsPlaying = false;

                Crystal.Services.ServiceManager.Resolve<Crystal.Services.IMessageBoxService>()
                    .ShowMessage(
                        LocalizationManager.GetLocalizedValue("StreamingErrorHeader"),
                        LocalizationManager.GetLocalizedValue("StreamingErrorMsg"));
            }

        }
Пример #12
0
        public void PlayStation(Station s)
        {
            if (mediaElement == null)
                mediaElement = ((App)App.Current).MediaElement;

            PlayStation(s, mediaElement);
        }