Example #1
0
 public AlbumViewModel(SynoItem album)
 {
     this.Album = album;
     this.Tracks = new ObservableCollection<TrackViewModel>();
     SelectedCommand = new DelegateCommand(OnSelected);
     SelectAllOrNoneCommand = new DelegateCommand(OnSelectAllOrNone,() => this.Tracks.Count > 0);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SearchResultItemViewModel"/> class.
 /// </summary>
 /// <param name="itemInfo">The item info.</param>
 /// <param name="eventAggregator">The event aggregator.</param>
 /// <param name="pageSwitchingService">The page switching service.</param>
 /// <param name="urlParameterToObjectsPlateHeater"></param>
 public SearchResultItemViewModel(SynoItem itemInfo, IEventAggregator eventAggregator, IPageSwitchingService pageSwitchingService, IUrlParameterToObjectsPlateHeater urlParameterToObjectsPlateHeater)
 {
     if (itemInfo == null) throw new ArgumentNullException("itemInfo");
     ItemSelectedCommand = new DelegateCommand(OnItemSelected);
     ItemInfo = itemInfo;
     _eventAggregator = eventAggregator;
     _pageSwitchingService = pageSwitchingService;
     _urlParameterToObjectsPlateHeater = urlParameterToObjectsPlateHeater;
 }
        public ArtistPanoramaViewModel(SynoItem artist, IEnumerable<AlbumViewModel> albums, int activePanelIndex, ISearchService searchService, IEventAggregator eventAggregator, IPageSwitchingService pageSwitchingService, INotificationService notificationService)
        {
            if (searchService == null)
            {
                throw new ArgumentNullException("searchService");
            }

            if (eventAggregator == null)
            {
                throw new ArgumentNullException("eventAggregator");
            }

            if (pageSwitchingService == null)
            {
                throw new ArgumentNullException("pageSwitchingService");
            }

            if (artist == null)
            {
                throw new ArgumentNullException("artist");
            }
            if (albums == null)
            {
                throw new ArgumentNullException("albums");
            }

            PlayLastCommand = new DelegateCommand(OnPlayLast);
            PlayCommand = new DelegateCommand(OnPlay);
            CurrentArtistItemIndex = activePanelIndex;
            _searchService = searchService;
            this._notificationService = notificationService;

            // TODO : Use IoC or Factory or whatever, but something to be able to inject our own implementation
            _panoramaItemSwitchingService = new PanoramaItemSwitchingService();

            _panoramaItemSwitchingService.ActiveItemChangeRequested += (s, e) => CurrentArtistItemIndex = e.NewItemIndex;
            _eventAggregator = eventAggregator;
            _pageSwitchingService = pageSwitchingService;
            this.ArtistAlbums = new ObservableCollection<AlbumViewModel>();
            foreach (var albumViewModel in albums)
            {
                this.ArtistAlbums.Add(albumViewModel);
            }

            this.ArtistAlbums.CollectionChanged += StartMonitoringElements;
            foreach (var album in this.ArtistAlbums)
            {
                album.PropertyChanged += UpdateBusyness;
            }

            ShowPlayQueueCommand = new DelegateCommand(OnShowPlayQueue);
            _artist = artist;
            ArtistName = _artist.Title;
        }
        private void OnArtistPanoramaViewLoaded(object sender, RoutedEventArgs e)
        {
            // the page is an humble object, and the navigatorService, its sole dependency.
            var navigator = IoC.Container.Get<INavigatorService>();
            navigator.ActivateNavigationService(NavigationService, true);

            if (DataContext == null)
            {
                var artistTicket = NavigationContext.QueryString["artistTicket"];
                var artistAlbumsTicket = NavigationContext.QueryString["albumsListTicket"];

                if (_newPageInstance && State.ContainsKey(ArtistPanoramaViewCurrentArtist))
                {
                    _artist = (SynoItem)this.State[ArtistPanoramaViewCurrentArtist];
                }
                else
                {
                    _artist = (SynoItem)navigator.UrlParameterToObjectsPlateHeater.GetObjectForTicket(artistTicket);
                }

                IEnumerable<SynoItem> artistItems = null;
                IEnumerable<AlbumViewModel> albumViewModels;
                if (_newPageInstance && State.ContainsKey(ArtistPanoramaViewItems))
                {
                    throw new NotImplementedException("deal with the viewmodels not with the synoitems anymore here");
                    artistItems = (IEnumerable<SynoItem>)this.State[ArtistPanoramaViewItems];
                    //artistPanoramaViewModel.BuildArtistItems(_artistItems);
                }
                else
                {
                    //artistPanoramaViewModel.QueryAndBuildArtistItems();
                    albumViewModels = (IEnumerable<AlbumViewModel>)navigator.UrlParameterToObjectsPlateHeater.GetObjectForTicket(artistAlbumsTicket);
                }
                var albumTicket = NavigationContext.QueryString["albumTicket"];

                int artistPanoramaViewActivePanelIndex = 0;

                if (_newPageInstance && State.ContainsKey(ArtistPanoramaViewCurrentArtist))
                {
                    artistPanoramaViewActivePanelIndex = (int)this.State[ArtistPanoramaViewActivePanelIndex];
                }
                else
                {
                    var album = (AlbumViewModel)navigator.UrlParameterToObjectsPlateHeater.GetObjectForTicket(albumTicket);
                    artistPanoramaViewActivePanelIndex = albumViewModels.ToList().IndexOf(album);

                }
                ArtistPanoramaViewModel artistPanoramaViewModel = IoC.Container.Get<ArtistPanoramaViewModelFactory>().Create(this._artist, albumViewModels,artistPanoramaViewActivePanelIndex);

                DataContext = artistPanoramaViewModel;
            }
        }
 public ArtistDetailViewModel(SynoItem artist, ISearchService searchService, AlbumViewModelFactory albumViewModelFactory, INavigatorService navigatorSevice, IPageSwitchingService pageSwitchingService, ITrackViewModelFactory trackViewModelFactory)
 {
     if (trackViewModelFactory == null) throw new ArgumentNullException("trackViewModelFactory");
     this.Albums = new ObservableCollection<AlbumViewModel>();
     this.ArtistName = artist.Title;
     this.SimilarArtists = new ObservableCollection<IArtistViewModel>();
     this._searchService = searchService;
     _albumViewModelFactory = albumViewModelFactory;
     _navigatorSevice = navigatorSevice;
     _pageSwitchingService = pageSwitchingService;
     _trackViewModelFactory = trackViewModelFactory;
     this.PopulateAlbumsAsync(artist);
     GetSimilarArtistsAsync(artist);
 }
        public static void ParseSynologyArtists(string result, out IEnumerable<SynoItem> artists, out long total, string urlBase)
        {
            JsonObject jObject = new JsonObject(result);
            artists = new List<SynoItem>();

            JsonArray jsonArtists = jObject["items"].GetArray();

            for (int i = 0; i < jsonArtists.Count; i++)
            {

                var synoArtist = new SynoItem
                      {
                          AlbumArtUrl = BuildAbsoluteAlbumArtUrl(urlBase, jsonArtists[i].GetObject()["albumArtURL"].GetString()),
                          Icon = jsonArtists[i].GetObject()["icon"].GetString(),
                          IsContainer = jsonArtists[i].GetObject()["is_container"].GetBoolean(),
                          IsTrack = jsonArtists[i].GetObject()["is_track"].GetBoolean(),
                          ItemID = jsonArtists[i].GetObject()["item_id"].GetString(),
                          ItemPid = jsonArtists[i].GetObject()["item_pid"].GetString(),
                          Sequence = (int)jsonArtists[i].GetObject()["sequence"].GetNumber(),
                          Support = jsonArtists[i].GetObject()["support"].GetBoolean(),
                          Title = jsonArtists[i].GetObject()["title"].GetString()
                      };
                ((List<SynoItem>)artists).Add(synoArtist);
            }

            //artists = (from album in albums
            //          select new SynoItem
            //          {
            //              //AlbumArtUrl = BuildAbsoluteAlbumArtUrl(urlBase, album.GetObject()["albumArtURL"].GetString()),
            //              //Icon = album.GetObject()["icon"].GetString(),
            //              //IsContainer = album.GetObject()["is_container"].GetBoolean(),
            //              //IsTrack = album.GetObject()["is_track"].GetBoolean(),
            //              //ItemID = album.GetObject()["item_id"].GetString(),
            //              //ItemPid = album.GetObject()["item_pid"].GetString(),
            //              //Sequence = (int)album.GetObject()["sequence"].GetNumber(),
            //              //Support = album.GetObject()["support"].GetBoolean(),
            //              Title = album.GetObject()["title"].GetString()
            //          }).ToArray();
            total = (long)jObject["total"].GetNumber();
        }
 public void GetTracksForAlbum(SynoItem album, Action<IEnumerable<SynoTrack>, long, SynoItem> callback, Action<Exception> callbackError)
 {
     throw new NotImplementedException();
 }
        private void GetAlbumsForArtistCallback(IEnumerable<SynoItem> albums, long totalAlbumsCount, SynoItem artist)
        {
            foreach (var album in albums)
            {
                AlbumViewModel albumViewModel = _albumViewModelFactory.Create(album);

                // prepare an empty track list
                albumViewModel.Tracks.Clear();

                // album is busy because its tracks are getting loaded.
                albumViewModel.IsBusy = true;

                _searchService.GetTracksForAlbum(album,(synoTracks,count, containingAlbum) =>
                    {
                        // Note - would it work, based on the synoitem instead of the ItemID ?
                        // Note - we rely on the fact that there each album is only present once in the artists discography ( based on its ItemID ) otherwise, it crashes !
                        var currentAlbumViewModel = Albums.Single(a => a.Album.ItemID == containingAlbum.ItemID);
                        currentAlbumViewModel.Tracks.Clear();
                        foreach (var track in synoTracks)
                        {
                            // track guid is empty for now : it will be filled when the track gets added to the playqueue
                            currentAlbumViewModel.Tracks.Add(this._trackViewModelFactory.Create(Guid.Empty, track, this._pageSwitchingService));
                        }
                        currentAlbumViewModel.IsBusy = false;

                    });

                // TODO : Register Selected event and on event handler : Load the album's tracks and navigate to its index in the artist's albums panorama.
                // Note : So far, the viewmodels are never removed from the list : that means we don't need to unregister that event. If this changes,
                // then it will be necessary to enregister the event for each view model removed from the collection.
                albumViewModel.Selected += (s, e) =>
                {
                    string albumId = ((AlbumViewModel)s).Album.ItemID;
                    _navigatorSevice.UrlParameterToObjectsPlateHeater.RegisterObject(albumId, s);
                    _navigatorSevice.UrlParameterToObjectsPlateHeater.RegisterObject(artist.ItemID, artist);
                    Guid albumsListTicket = Guid.NewGuid();
                    _navigatorSevice.UrlParameterToObjectsPlateHeater.RegisterObject(albumsListTicket.ToString(), this.Albums);
                    _pageSwitchingService.NavigateToArtistPanorama(artist.ItemID, albumId, albumsListTicket.ToString());

                };
                Albums.Add(albumViewModel);
            }
        }
Example #9
0
        public void GetAlbumsForArtist(SynoItem artist, Action<IEnumerable<SynoItem>, long, SynoItem> callback)
        {
            var results = new List<SynoItem>();
            // All music
            results.Add(new SynoItem
                {
                    AlbumArtUrl = "11-18-04.jpg",
                    Icon = "icon_container.png",
                    IsContainer = true,
                    IsTrack = false,
                    ItemID = "musiclib_music_artist",
                    ItemPid = "musiclib_music_aa/852502",
                    Sequence = 0,
                    Support = false,
                    Title = "All Music"
                });

            results.Add(new SynoItem
                {
                    AlbumArtUrl = "11-18-04.jpg",
                    Icon = "icon_container.png",
                    IsContainer = true,
                    IsTrack = false,
                    ItemID = "musiclib_music_aa/852502/852502",
                    ItemPid = "musiclib_music_aa/852502",
                    Sequence = 1,
                    Support = false,
                    Title = "Bleach"
                });

            results.Add(new SynoItem
                {
                    AlbumArtUrl = "11-18-04.jpg",
                    Icon = "icon_container.png",
                    IsContainer = true,
                    IsTrack = false,
                    ItemID = "musiclib_music_aa/852502/852553",
                    ItemPid = "musiclib_music_aa/852502",
                    Sequence = 2,
                    Support = false,
                    Title = "From the Muddy Banks of the Wi"
                });

            results.Add(new SynoItem
                {
                    AlbumArtUrl = "11-18-04.jpg",
                    Icon = "icon_container.png",
                    IsContainer = true,
                    IsTrack = false,
                    ItemID = "musiclib_music_aa/852502/852529",
                    ItemPid = "musiclib_music_aa/852502",
                    Sequence = 3,
                    Support = false,
                    Title = "In Utero"
                });

            results.Add(new SynoItem
                {
                    AlbumArtUrl = "11-18-04.jpg",
                    Icon = "icon_container.png",
                    IsContainer = true,
                    IsTrack = false,
                    ItemID = "musiclib_music_aa/852502/852515",
                    ItemPid = "musiclib_music_aa/852502",
                    Sequence = 4,
                    Support = false,
                    Title = "MTV Unplugged In New York"
                });

            results.Add(new SynoItem
                {
                    AlbumArtUrl = "11-18-04.jpg",
                    Icon = "icon_container.png",
                    IsContainer = true,
                    IsTrack = false,
                    ItemID = "musiclib_music_aa/852502/885030",
                    ItemPid = "musiclib_music_aa/852502",
                    Sequence = 5,
                    Support = false,
                    Title = "Nevermind"
                });

            callback(results, 6, artist);
        }
 public Task<IEnumerable<SynoItem>> GetAlbumsForArtistAsync(SynoItem artist)
 {
     throw new NotImplementedException();
 }
Example #11
0
        public Task<IEnumerable<SynoItem>> GetAlbumsForArtistAsync(SynoItem artist)
        {
            var tcs = new TaskCompletionSource<IEnumerable<SynoItem>>(artist);
            string urlBase = string.Format("http://{0}:{1}", this.Host, this.Port);
            var url = urlBase + "/webman/modules/AudioStation/webUI/audio_browse.cgi";
            HttpWebRequest request = BuildRequest(url);
            int limit = 100;

            string urlEncodedItemId = System.Uri.EscapeDataString(artist.ItemID);
            string postString = string.Format(@"action=browse&target={0}&server=musiclib_music_aa&category=&keyword=&start=0&sort=title&dir=ASC&limit={1}", urlEncodedItemId, limit);
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);
            var requestStreamAr = request.BeginGetRequestStream(ar =>
            {
                // Just make sure we retrieve the right web request : no access to modified closure.
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
                var requestStream = webRequest.EndGetRequestStream(ar);

                requestStream.Write(postBytes, 0, postBytes.Length);

                var getResponseAr = webRequest.BeginGetResponse(
                    responseAr =>
                    {
                        // Just make sure we retrieve the right web request : no access to modified closure.
                        var httpWebRequest = responseAr.AsyncState;
                        var webResponse = webRequest.EndGetResponse(responseAr);
                        var responseStream = webResponse.GetResponseStream();

                        if (webResponse.Headers["Content-Encoding"].Contains("gzip"))
                            responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                        else if (webResponse.Headers["Content-Encoding"].Contains("deflate"))
                            responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);

                        StreamReader reader = new StreamReader(responseStream);

                        var content = reader.ReadToEnd();
                        long count;
                        IEnumerable<SynoItem> albums;
                        SynologyJsonDeserializationHelper.ParseSynologyAlbums(content, out albums, out count, urlBase);
                        //var isOnUiThread = Deployment.Current.Dispatcher.CheckAccess();
                        //if (isOnUiThread)
                        //{
                        //    if (count > limit)
                        //    {
                        //        // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                        //    }
                        //    tcs.SetResult(albums);
                        //    // callback(tracks);
                        //}
                        //else
                        //{
                        //    Deployment.Current.Dispatcher.BeginInvoke(
                        //        () =>
                        //        {
                        //            if (count > limit)
                        //            {
                        //                // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                        //            }
                        tcs.SetResult(albums);
                        //        });
                        //}
                    },
                    webRequest);
            }, request);

            return tcs.Task;
        }
Example #12
0
        public void GetTracksForAlbum(SynoItem album, Action <IEnumerable <SynoTrack>, long, SynoItem> callback, Action <Exception> callbackError)
        {
            string urlBase = string.Format("http://{0}:{1}", this.Host, this.Port);

            var url = urlBase + this.versionDependentResourcesProvider.GetAudioSearchWebserviceRelativePath(this.DsmVersion);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Accept      = "*/*";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            // Not supported yet, but that would decrease the bandwidth usage from 1.3 Mb to 83 Kb ... Pretty dramatic, ain't it ?
            //request.Headers["Accept-Encoding"] = "gzip, deflate";

            request.UserAgent       = "OpenSyno";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.SetCookies(new Uri(url), this.Token);

            request.Method = "POST";

            int    limit      = 10000;
            string postString = string.Format(@"action=browse&target={0}&server=musiclib_music_aa&category=&keyword=&start=0&sort=title&dir=ASC&limit={1}", HttpUtility.UrlEncode(album.ItemID), limit);

            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);

            request.BeginGetRequestStream(ar =>
            {
                // Just make sure we retrieve the right web request : no access to modified closure.
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;

                var requestStream = webRequest.EndGetRequestStream(ar);
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();

                request.BeginGetResponse(
                    responseAr =>
                {
                    // Just make sure we retrieve the right web request : no access to modified closure.
                    var httpWebRequest = responseAr.AsyncState;
                    WebResponse webResponse;
                    try
                    {
                        webResponse = webRequest.EndGetResponse(responseAr);
                    }
                    catch (WebException exception)
                    {
                        throw new SynoNetworkException("The remote server did not respond to our request. Please, check that the sinal is strong enough and try again.", exception);
                    }
                    var responseStream = webResponse.GetResponseStream();
                    var reader         = new StreamReader(responseStream);
                    var content        = reader.ReadToEnd();

                    long total;
                    IEnumerable <SynoTrack> tracks;
                    SynologyJsonDeserializationHelper.ParseSynologyTracks(content, out tracks, out total, urlBase);

                    tracks = tracks.OrderBy(o => o.Track);

                    var isOnUiThread = Deployment.Current.Dispatcher.CheckAccess();
                    if (isOnUiThread)
                    {
                        if (total > limit)
                        {
                            // FIXME : Use an error handling service
                            // MessageBox.Show(string.Format("number of available albums ({0}) exceeds supported limit ({1})", total, limit));
                        }
                        callback(tracks, total, album);
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            if (total > limit)
                            {
                                // FIXME : Use an error handling service
                                // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", total, limit));
                            }
                            callback(tracks, total, album);
                        });
                    }
                },
                    webRequest);
            },
                                          request);
        }
Example #13
0
 public void GetTracksForAlbum(SynoItem album,  Action<IEnumerable<SynoTrack>, long, SynoItem> callback)
 {
     _audioStationSession.GetTracksForAlbum(album, callback, OnOperationReturnedWithError);
 }
Example #14
0
        public Task<IEnumerable<SynoTrack>> GetTracksForAlbumAsync(SynoItem album)
        {
            var tcs = new TaskCompletionSource<IEnumerable<SynoTrack>>(album);

            string urlBase = string.Format("http://{0}:{1}", this.Host, this.Port);
            // var url = urlBase + "/webman/modules/AudioStation/webUI/audio_browse.cgi";
            var url = urlBase + this.versionDependentResourcesProvider.GetAudioSearchWebserviceRelativePath(this.DsmVersion);

            HttpWebRequest request = BuildRequest(url);

            int limit = 100;
            string postString = string.Format(@"action=browse&target={0}&server=musiclib_music_aa&category=&keyword=&start=0&sort=title&dir=ASC&limit={1}", HttpUtility.UrlEncode(album.ItemID), limit);

            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);

            var requestStreamAr = request.BeginGetRequestStream(ar =>
            {
                // Just make sure we retrieve the right web request : no access to modified closure.
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;

                var requestStream = webRequest.EndGetRequestStream(ar);
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();

                var getResponseAr = webRequest.BeginGetResponse(
                    responseAr =>
                    {
                        // Just make sure we retrieve the right web request : no access to modified closure.
                        var httpWebRequest = responseAr.AsyncState;

                        var webResponse = webRequest.EndGetResponse(responseAr);
                        var responseStream = webResponse.GetResponseStream();
                        var reader = new StreamReader(responseStream);
                        var content = reader.ReadToEnd();

                        long count;
                        IEnumerable<SynoTrack> tracks;
                        SynologyJsonDeserializationHelper.ParseSynologyTracks(content, out tracks, out count, urlBase);

                        tracks = tracks.OrderBy(o => o.Track);

                        var isOnUiThread = Deployment.Current.Dispatcher.CheckAccess();
                        if (isOnUiThread)
                        {
                            if (count > limit)
                            {
                                // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                            }

                            tcs.SetResult(tracks);

                            // callback(tracks);
                        }
                        else
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    if (count > limit)
                                    {
                                        // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                                    }
                                    tcs.SetResult(tracks);
                                });
                        }
                    },
                    webRequest);

            }, request);

            //var getRequestStreamTask = Task.Factory.FromAsync(
            //    requestStreamAr,
            //    ar =>
            //        ,
            //    TaskCreationOptions.None,
            //    TaskScheduler.FromCurrentSynchronizationContext());

            return tcs.Task;
        }
Example #15
0
 public void GetTracksForAlbum(SynoItem album, Action <IEnumerable <SynoTrack>, long, SynoItem> callback, Action <Exception> callbackError)
 {
     throw new NotImplementedException();
 }
Example #16
0
 public void GetAlbumsForArtist(SynoItem artist, Action<IEnumerable<SynoItem>, long, SynoItem> callback)
 {
     // an artist id looks like that (item_id): musiclib_music_aa/852502
     _audioStationSession.GetAlbumsForArtist(artist, callback, OnOperationReturnedWithError);
 }
Example #17
0
 public void GetAlbumsForArtist(SynoItem artist, Action <IEnumerable <SynoItem>, long, SynoItem> callback, Action <Exception> callbackError)
 {
     throw new NotImplementedException();
 }
Example #18
0
 public Task <IEnumerable <SynoTrack> > GetTracksForAlbumAsync(SynoItem album)
 {
     throw new NotImplementedException();
 }
Example #19
0
 public Task <IEnumerable <SynoItem> > GetAlbumsForArtistAsync(SynoItem artist)
 {
     throw new NotImplementedException();
 }
Example #20
0
        public void GetTracksForAlbum(SynoItem album, Action<IEnumerable<SynoTrack>, long, SynoItem> callback, Action<Exception> callbackError)
        {
            string urlBase = string.Format("http://{0}:{1}", this.Host, this.Port);

            var url = urlBase + "/audio/webUI/audio_browse.cgi";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Accept = "*/*";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            // Not supported yet, but that would decrease the bandwidth usage from 1.3 Mb to 83 Kb ... Pretty dramatic, ain't it ?
            //request.Headers["Accept-Encoding"] = "gzip, deflate";

            //request.UserAgent = "OpenSyno";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.SetCookies(new Uri(url), this.Token);

            request.Method = "POST";

            int limit = 10000;

            string urlEncodedItemId = System.Uri.EscapeDataString(album.ItemID);
            string postString = string.Format(@"action=browse&target={0}&server=musiclib_music_aa&category=&keyword=&start=0&sort=title&dir=ASC&limit={1}",urlEncodedItemId, limit);
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);

            request.BeginGetRequestStream(ar =>
            {
                // Just make sure we retrieve the right web request : no access to modified closure.
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;

                var requestStream = webRequest.EndGetRequestStream(ar);
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Dispose();

                request.BeginGetResponse(
                    responseAr =>
                    {
                        // Just make sure we retrieve the right web request : no access to modified closure.
                        var httpWebRequest = responseAr.AsyncState;

                        var webResponse = webRequest.EndGetResponse(responseAr);
                        var responseStream = webResponse.GetResponseStream();
                        var reader = new StreamReader(responseStream);
                        var content = reader.ReadToEnd();

                        long total;
                        IEnumerable<SynoTrack> tracks;
                        SynologyJsonDeserializationHelper.ParseSynologyTracks(content, out tracks, out total, urlBase);

                        tracks = tracks.OrderBy(o => o.Track);

                        //var isOnUiThread = Deployment.Current.Dispatcher.CheckAccess();
                        //if (isOnUiThread)
                        //{
                        //    if (total > limit)
                        //    {
                        //        MessageBox.Show(string.Format("number of available albums ({0}) exceeds supported limit ({1})", total, limit));
                        //    }
                        //    callback(tracks, total, album);
                        //}
                        //else
                        //{
                        //    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        //    {
                        //        if (total > limit)
                        //        {
                        //            MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", total, limit));
                        //        }
                        //        callback(tracks, total, album);
                        //    });
                        //}
                    },
                    webRequest);
            },
                request);
        }
 /// <summary>
 /// Workarounds the album art bug.
 /// </summary>
 /// <param name="albums">The albums.</param>
 /// <remarks>
 /// There a bug in Audio Station 3.0 where the AlbumArtUrl field does not point to an album art, but rather to an artist art. fixing the url on the client will work just fine untill they fix it.
 /// </remarks>
 private static IEnumerable<SynoItem> WorkaroundAlbumArtBug(SynoItem[] albums)
 {
     foreach (var synoItem in albums)
     {
         synoItem.AlbumArtUrl = synoItem.AlbumArtUrl.Replace("webUI/getcover.cgi/artist", "webUI/getcover.cgi/album");
     }
     return albums;
 }
 //public ArtistPanoramaViewModel Create(SynoItem artist, IEnumerable<SynoItem> artistItems)
 //{
 //    ArtistPanoramaViewModel artistPanoramaViewModel = new ArtistPanoramaViewModel(this._searchService, this._eventAggregator, this._pageSwitchingService, artist, this._notificationService);
 //    artistPanoramaViewModel.BuildArtistItems(artistItems);
 //    return artistPanoramaViewModel;
 //}
 public ArtistPanoramaViewModel Create(SynoItem artist, IEnumerable<AlbumViewModel> albumViewModels, int artistPanoramaViewActivePanelIndex)
 {
     var artistPanoramaViewModel = new ArtistPanoramaViewModel(artist, albumViewModels,artistPanoramaViewActivePanelIndex, this._searchService, this._eventAggregator, this._pageSwitchingService, this._notificationService);
     return artistPanoramaViewModel;
 }
 public AlbumViewModel Create(SynoItem album)
 {
     return new AlbumViewModel(album);
 }
Example #24
0
        public void GetAlbumsForArtist(SynoItem artist, Action<IEnumerable<SynoItem>, long, SynoItem> callback, Action<Exception> callbackError)
        {
            string urlBase = string.Format("http://{0}:{1}", this.Host, this.Port);
            var url = urlBase + this.versionDependentResourcesProvider.GetAudioSearchWebserviceRelativePath(this.DsmVersion);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Accept = "*/*";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            // Not supported yet, but that would decrease the bandwidth usage from 1.3 Mb to 83 Kb ... Pretty dramatic, ain't it ?
            //request.Headers["Accept-Encoding"] = "gzip, deflate";

            request.UserAgent = "OpenSyno";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.SetCookies(new Uri(url), this.Token);

            request.Method = "POST";

            int limit = 10000;
            string postString = string.Format(@"action=browse&target={0}&server=musiclib_music_aa&category=&keyword=&start=0&sort=title&dir=ASC&limit={1}", HttpUtility.UrlEncode(artist.ItemID), limit);
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);

            request.BeginGetRequestStream(ar =>
            {
                // Just make sure we retrieve the right web request : no access to modified closure.
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;

                var requestStream = webRequest.EndGetRequestStream(ar);
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();

                request.BeginGetResponse(
                    responseAr =>
                    {
                        // Just make sure we retrieve the right web request : no access to modified closure.
                        var httpWebRequest = responseAr.AsyncState;

                        var webResponse = webRequest.EndGetResponse(responseAr);
                        var responseStream = webResponse.GetResponseStream();
                        var reader = new StreamReader(responseStream);
                        var content = reader.ReadToEnd();

                        long count;
                        IEnumerable<SynoItem> albums;
                        SynologyJsonDeserializationHelper.ParseSynologyAlbums(content, out albums, out count, urlBase);

                        var isOnUiThread = Deployment.Current.Dispatcher.CheckAccess();
                        if (isOnUiThread)
                        {
                            if (count > limit)
                            {
                                // FIXME : Use an error handling service
                                // MessageBox.Show(string.Format("number of available albums ({0}) exceeds supported limit ({1})", count, limit));
                            }
                            callback(albums, count, artist);
                        }
                        else
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                if (count > limit)
                                {
                                    // FIXME : Use an error handling service
                                    // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                                }
                                callback(albums, count, artist);
                            });
                        }
                    },
                    webRequest);
            },
                request);
        }
 public Task<IEnumerable<SynoTrack>> GetTracksForAlbumAsync(SynoItem album)
 {
     throw new NotImplementedException();
 }
Example #26
0
        public Task <IEnumerable <SynoTrack> > GetTracksForAlbumAsync(SynoItem album)
        {
            var tcs = new TaskCompletionSource <IEnumerable <SynoTrack> >(album);

            string urlBase = string.Format("http://{0}:{1}", this.Host, this.Port);
            // var url = urlBase + "/webman/modules/AudioStation/webUI/audio_browse.cgi";
            var url = urlBase + this.versionDependentResourcesProvider.GetAudioSearchWebserviceRelativePath(this.DsmVersion);

            HttpWebRequest request = BuildRequest(url);

            int    limit      = 100;
            string postString = string.Format(@"action=browse&target={0}&server=musiclib_music_aa&category=&keyword=&start=0&sort=title&dir=ASC&limit={1}", HttpUtility.UrlEncode(album.ItemID), limit);


            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);

            var requestStreamAr = request.BeginGetRequestStream(ar =>
            {
                // Just make sure we retrieve the right web request : no access to modified closure.
                HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;

                var requestStream = webRequest.EndGetRequestStream(ar);
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();

                var getResponseAr = webRequest.BeginGetResponse(
                    responseAr =>
                {
                    // Just make sure we retrieve the right web request : no access to modified closure.
                    var httpWebRequest = responseAr.AsyncState;

                    var webResponse    = webRequest.EndGetResponse(responseAr);
                    var responseStream = webResponse.GetResponseStream();
                    var reader         = new StreamReader(responseStream);
                    var content        = reader.ReadToEnd();

                    long count;
                    IEnumerable <SynoTrack> tracks;
                    SynologyJsonDeserializationHelper.ParseSynologyTracks(content, out tracks, out count, urlBase);

                    tracks = tracks.OrderBy(o => o.Track);

                    var isOnUiThread = Deployment.Current.Dispatcher.CheckAccess();
                    if (isOnUiThread)
                    {
                        if (count > limit)
                        {
                            // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                        }

                        tcs.SetResult(tracks);

                        // callback(tracks);
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(
                            () =>
                        {
                            if (count > limit)
                            {
                                // MessageBox.Show(string.Format("number of available artists ({0}) exceeds supported limit ({1})", count, limit));
                            }
                            tcs.SetResult(tracks);
                        });
                    }
                },
                    webRequest);
            }, request);



            //var getRequestStreamTask = Task.Factory.FromAsync(
            //    requestStreamAr,
            //    ar =>
            //        ,
            //    TaskCreationOptions.None,
            //    TaskScheduler.FromCurrentSynchronizationContext());

            return(tcs.Task);
        }
Example #27
0
        private void GetSimilarArtistsAsync(SynoItem artist)
        {
            // TODO : Look on last.fm
            LastFmApi api = new LastFmApi();
            var t = api.GetSimilarArtistsAsync(artist.Title);

            t.ContinueWith(o =>
                               {
                                   SimilarArtists.Clear();
                                   foreach (var lastFmArtist in o.Result)
                                   {
                                       // FIXME : USe a factory.
                                       SimilarArtists.Add(new ArtistViewModel(lastFmArtist.Name, lastFmArtist.Mbid, lastFmArtist.Url, lastFmArtist.Match, lastFmArtist.Images));
                                   }
                               }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Example #28
0
 public void GetTracksForAlbum(SynoItem album, Action<IEnumerable<SynoTrack>, long, SynoItem> callback)
 {
     var tracks = new List<SynoTrack>();
     tracks.Add(new SynoTrack { Album = "Alice", Artist = "Tom Waits", Title = "Alice" });
     tracks.Add(new SynoTrack { Album = "Alice", Artist = "Tom Waits", Title = "Flower's grave" });
     tracks.Add(new SynoTrack { Album = "Alice", Artist = "Tom Waits", Title = "Kommeniedzuspedt" });
     tracks.Add(new SynoTrack { Album = "Alice", Artist = "Tom Waits", Title = "Poor Edward" });
     tracks.Add(new SynoTrack { Album = "Alice", Artist = "Tom Waits", Title = "Bacarole" });
     tracks.Add(new SynoTrack { Album = "Alice", Artist = "Tom Waits", Title = "Fawn" });
     callback(tracks, tracks.Count, album);
 }
Example #29
0
        private void PopulateAlbumsAsync(SynoItem artist)
        {
            // TODO : request albums.

            _searchService.GetAlbumsForArtist(artist, GetAlbumsForArtistCallback);
        }
 public ArtistDetailViewModel Create(SynoItem artist)
 {
     return new ArtistDetailViewModel(artist, _searchService, _albumViewModelFactory,this._navigatorSevice, this._pageSwitchingService, this._session);
 }
 public void GetAlbumsForArtist(SynoItem artist, Action<IEnumerable<SynoItem>, long, SynoItem> callback, Action<Exception> callbackError)
 {
     throw new NotImplementedException();
 }
 // Eventaggregator needs to be moved to .ctor
 public SearchResultItemViewModel Create(SynoItem result, IEventAggregator eventAggregator, IPageSwitchingService pageSwitchingService)
 {
     return new SearchResultItemViewModel(result, eventAggregator, pageSwitchingService, _urlParameterToObjectsPlateHeater);
 }
Example #33
0
 public ArtistViewModel(SynoItem synoItem)
 {
     Artist = synoItem;
 }