コード例 #1
0
        async Task INavigationHandler.ProcessResponseAsync(NavigationResponse response)
        {
            // It's possible that when processing the navigation response a new navigation is initiated
            // in the same handler (e.g. the navigation supporter/view model, while initializing triggers
            // a new navigation). If that's the case, we want to let the current navigation request to finish
            // processing before we process the new one, otherwise the control's internal state might get
            // messed up (because the ProcessResponseImplAsync usually sets some class properties).
            //
            // To do this we enqueue the requests and only start processing the queue if it's the first
            // request, so that we don't process a request multiple times. If processing a request triggers
            // a new navigation this method will be called again, a new item will be added to the queue,
            // it won't be processed in this stack frame, but will be processed by the initial stack frame after
            // it's done awaiting for the in-flight navigation to finish.
            this.processResponseQueue.Enqueue(response);

            if (this.processResponseQueue.Count == 1)
            {
                while (this.processResponseQueue.Any())
                {
                    var _nextResponseToProcess = this.processResponseQueue.Peek();

                    await ProcessResponseImplAsync(_nextResponseToProcess);

                    this.processResponseQueue.Dequeue();
                }
            }
        }
コード例 #2
0
 /// <summary>
 /// Sey Playlists Extended
 /// </summary>
 /// <param name="client">Spotify Sdk Client</param>
 /// <param name="response">Navigation Response of Playlist Response</param>
 public static void SetPlaylistsExtended(this ISpotifySdkClient client, NavigationResponse <PlaylistResponse> response)
 {
     if (response?.Items != null)
     {
         response.Items.ForEach(f => client.SetPlaylistExtended(f));
     }
 }
コード例 #3
0
        /// <summary>
        /// List Navigation Requests
        /// </summary>
        /// <param name="navigationResponse"></param>
        /// <returns>List of Navigation Request</returns>
        public static List <NavigationRequest> ListNavigationRequests <TResponse>(NavigationResponse <TResponse> navigationResponse)
        {
            List <NavigationRequest> navigationRequests = null;

            if (navigationResponse?.Total > 0 && navigationResponse?.Limit > 0)
            {
                navigationRequests = new List <NavigationRequest>();
                var total = navigationResponse.Total;
                var limit = navigationResponse.Limit;
                // Get Count
                var count = (int)Math.Ceiling((double)total / limit);
                for (int index = 0; index < count; index++)
                {
                    // Get Offset
                    var offset = index * limit;
                    NavigationRequest navigationRequest = new NavigationRequest()
                    {
                        Offset = offset,
                        Limit  = limit
                    };
                    navigationRequests.Add(navigationRequest);
                }
            }
            return(navigationRequests);
        }
コード例 #4
0
        public IObservable <IUrlResponse> GetResponse(IRoutingContext context)
        {
            Guard.ArgumentNotNull(context, "context");
            Guard.ArgumentIsType(context.Request, typeof(NavigationRequest), "context.Request");

            // we initialize a lazy observer that is initialized when subscribed too
            LazyRelayObservable <IUrlResponse> _relayObservable = null;

            _relayObservable = new LazyRelayObservable <IUrlResponse>((o) =>
            {
                // we get the response content, if it is empty we return
                Object _content = _responseResolver(context.ParsedParameters);
                if (_content == null)
                {
                    var _response = new NavigationResponse((NavigationRequest)context.Request,
                                                           ResponseStatus.UrlNotFound, _content, context.ParsedParameters);
                    o.OnNext(_response);

                    // need to specialize this exception
                    //_localObservable.OnError(new InvalidOperationException(string.Format(NO_PAGE_RESOLVED, context.Request.Url)));
                }
                else
                {
                    // we get the navigation response
                    var _response = new NavigationResponse((NavigationRequest)context.Request,
                                                           ResponseStatus.Success, _content, context.ParsedParameters);
                    _relayObservable.OnNext(_response);
                    _relayObservable.OnCompleted();
                }
            });

            // and return
            return(_relayObservable);
        }
コード例 #5
0
        private IEnumerator findRoute(string sourcePuid, string destPuid, string buid, int floor)
        {
            var jsonBody = Encoding.UTF8.GetBytes(string.Format(
                                                      "{{\"buid\":\"{0}\", \"floor_number\": \"{1}\", \"pois_from\": \"{2}\", \"pois_to\": \"{3}\"}",
                                                      buid, floor, sourcePuid, destPuid
                                                      ));
            var url = BASE_URL + "/anyplace/navigation/route";

            using (var webRequest = new UnityWebRequest(url))
            {
                webRequest.method          = UnityWebRequest.kHttpVerbPOST;
                webRequest.uploadHandler   = new UploadHandlerRaw(jsonBody);
                webRequest.downloadHandler = new DownloadHandlerBuffer();
                webRequest.SetRequestHeader("Content-Type", "application/json");
                yield return(webRequest.SendWebRequest());

                if (webRequest.isNetworkError)
                {
                    Debug.Log("OurError: " + webRequest.error + ", " + webRequest.responseCode);
                }
                else
                {
                    var responseBody = Encoding.UTF8.GetString(webRequest.downloadHandler.data);
                    Debug.Log("Received: " + responseBody);

                    NavigationResponse response = JsonUtility.FromJson <NavigationResponse>(responseBody);
                    AnyplacePoi[]      pois     = response.pois;
                    // Temporarily drawing path here as I'm temporarily doing a lot of shitty stuff
                    drawPath(pois.Select(poi => poi.puid).ToArray());
                }
            }
        }
コード例 #6
0
ファイル: NavigationService.cs プロジェクト: cipjota/Chronos
        /// <summary>
        /// Process the given <see cref="NavigationResponse"/> instance
        /// </summary>
        /// <param name="response"></param>
        void INavigationHandler.ProcessResponse(NavigationResponse response)
        {
            // basic check
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            // we check if the navigation was successfull or not
            if (response.Status != ResponseStatus.Success)
            {
                this.PublishNavigationFailedInfo(response.Request);

                IShowMessageViewService showMessageService = ViewServiceLocator.GetViewService<IShowMessageViewService>();

                showMessageService.ButtonSetup  = DialogButton.Ok;
                showMessageService.Caption      = "Chronos - Error en la navegación";
                showMessageService.Text         =
                    ((response.Error != null) ? response.Error.Message : String.Format("No ha sido posible resolver la navegación solicitada ({0})", response.Request.RequestUrl));

                showMessageService.ShowMessage();
            }
            else
            {
                Application.Current.Dispatcher.BeginInvoke
                (
                    DispatcherPriority.Background,
                    new ThreadStart
                    (
                        () =>
                        {
                            WindowElement window = response.Content as WindowElement;

                            if (response.ResponseParameters != null &&
                                response.ResponseParameters.Count > 0)
                            {
                                ISupportNavigationLifecycle supporter = nRoute.Navigation.NavigationService.GetSupporter<ISupportNavigationLifecycle>(response.Content);

                                if (supporter != null)
                                {
                                    supporter.Initialize(response.ResponseParameters);
                                }
                            }

                            this.PublishNavigatedInfo(window.Title, response);

                            if (response.Request.NavigationMode == NavigateMode.Modal)
                            {
                                ServiceLocator.GetService<IVirtualDesktopManager>().ShowDialog(window);
                            }
                            else
                            {
                                ServiceLocator.GetService<IVirtualDesktopManager>().Show(window);
                            }
                        }
                    )
                );
            }
        }
コード例 #7
0
        /// <summary>
        /// Process the given <see cref="NavigationResponse"/> instance
        /// </summary>
        /// <param name="response"></param>
        void INavigationHandler.ProcessResponse(NavigationResponse response)
        {
            // basic check
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            // we check if the navigation was successfull or not
            if (response.Status != ResponseStatus.Success)
            {
                this.PublishNavigationFailedInfo(response.Request);

                IShowMessageViewService showMessageService = ViewServiceLocator.GetViewService <IShowMessageViewService>();

                showMessageService.ButtonSetup = DialogButton.Ok;
                showMessageService.Caption     = "Chronos - Error en la navegación";
                showMessageService.Text        =
                    ((response.Error != null) ? response.Error.Message : String.Format("No ha sido posible resolver la navegación solicitada ({0})", response.Request.RequestUrl));

                showMessageService.ShowMessage();
            }
            else
            {
                Application.Current.Dispatcher.BeginInvoke
                (
                    DispatcherPriority.Background,
                    new ThreadStart
                    (
                        () =>
                {
                    WindowElement window = response.Content as WindowElement;

                    if (response.ResponseParameters != null &&
                        response.ResponseParameters.Count > 0)
                    {
                        ISupportNavigationLifecycle supporter = nRoute.Navigation.NavigationService.GetSupporter <ISupportNavigationLifecycle>(response.Content);

                        if (supporter != null)
                        {
                            supporter.Initialize(response.ResponseParameters);
                        }
                    }

                    this.PublishNavigatedInfo(window.Title, response);

                    if (response.Request.NavigationMode == NavigateMode.Modal)
                    {
                        ServiceLocator.GetService <IVirtualDesktopManager>().ShowDialog(window);
                    }
                    else
                    {
                        ServiceLocator.GetService <IVirtualDesktopManager>().Show(window);
                    }
                }
                    )
                );
            }
        }
コード例 #8
0
 /// <summary>
 /// Get Bool Response
 /// </summary>
 /// <param name="navigationResponse">Navigation Response of bool</param>
 /// <returns>Bool Response</returns>
 public static BoolResponse GetBoolResponse(NavigationResponse <bool> navigationResponse) =>
 navigationResponse == null
     ? null
     : new BoolResponse()
 {
     Error = navigationResponse?.Error,
     Value = navigationResponse?.Items?.FirstOrDefault() ?? false
 };
コード例 #9
0
 /// <summary>
 /// Set Type
 /// </summary>
 /// <typeparam name="TResponse"></typeparam>
 /// <param name="navigationResponse"></param>
 /// <param name="navigationType">Navigation Type</param>
 /// <param name="responseType">Response Type</param>
 public static void SetTypes <TResponse>(this NavigationResponse <TResponse> navigationResponse, NavigationType navigationType, object responseType)
 {
     if (navigationResponse != null)
     {
         navigationResponse.NavigationType = navigationType;
         navigationResponse.Type           = responseType;
     }
 }
コード例 #10
0
 /// <summary>
 /// Attach List Artists Commands
 /// </summary>
 /// <param name="client">Spotify Sdk Client</param>
 /// <param name="responses">Artist Responses</param>
 public static void AttachListArtistsCommands(
     this ISpotifySdkClient client,
     NavigationResponse <ArtistResponse> responses)
 {
     if (client.Config.IsAttachListArtistsCommands && responses?.Items != null)
     {
         responses.Items.ForEach(item => client.AttachGetArtistCommands(item, client.Config.IsAttachListArtistsCommands));
     }
 }
コード例 #11
0
 /// <summary>
 /// Attach List Episodes Toggles
 /// </summary>
 /// <param name="client">Spotify Sdk Client</param>
 /// <param name="response">Navigation Response of Episode Response</param>
 public async static Task AttachListEpisodesToggles(
     this ISpotifySdkClient client,
     NavigationResponse <EpisodeResponse> response)
 {
     if (client.Config.IsAttachListEpisodesToggles && response?.Items != null)
     {
         await client.AttachEpisodesToggles(response.Items);
     }
 }
コード例 #12
0
        protected async virtual Task ProcessResponseImplAsync(NavigationResponse response)
        {
            Guard.ArgumentNotNull(response, "response");

            // we won't handle it the response, if it is not the active request!
            if (!response.Request.Equals(ActiveNavigationRequest))
            {
                return;
            }

            // we check if the navigation was successful or not
            if (response.Status != ResponseStatus.Success)
            {
                // if cancelled then return to normal state, else we inform the error
                if (response.Status == ResponseStatus.Cancelled)
                {
                    TransitionToNavigationState(Controls.NavigationState.Navigated);
                    return;
                }
                ShowFailedNavigationState(response.Request, response.Status, response.Error);
                return;
            }

            // we save our supporters and use them - note_ we need to save this to access later
            CurrentNavigationLifecycleSupporter     = NavigationService.GetSupporter <ISupportNavigationLifecycle>(response.Content);
            CurrentNavigationViewLifecycleSupporter = NavigationService.GetSupporter <ISupportNavigationViewLifecycle>(response.Content);
            CurrentNavigationStateSupporter         = NavigationService.GetSupporter <ISupportNavigationState>(response.Content);
            CurrentNavigationViewStateSupporter     = NavigationService.GetSupporter <ISupportNavigationViewState>(response.Content);

            // we save the url and the content
            CurrentNavigationRequest = response.Request;
            SetValue(ContentProperty, response.Content);

            // if the content support navigation, we pass in the request/response merged parameters
            if (this.CurrentNavigationLifecycleSupporter != null)
            {
                CurrentNavigationLifecycleSupporter.Initialize(response.ResponseParameters);
                await CurrentNavigationLifecycleSupporter.InitializeAsync(response.ResponseParameters);

                Title = CurrentNavigationLifecycleSupporter.Title ??
                        nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }
            else
            {
                Title = nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }

            TransitionToNavigationState(Controls.NavigationState.Navigated);

            // and once we have set the transition state, then we call the view's initialize
            if (CurrentNavigationViewLifecycleSupporter != null)
            {
                CurrentNavigationViewLifecycleSupporter.Initialize(response);
            }
        }
コード例 #13
0
 public List <TDestination> Convert(NavigationResponse <TSource> source,
                                    List <TDestination> destination,
                                    ResolutionContext context)
 {
     if (source != null)
     {
         var response = context.Mapper.Map <IEnumerable <TSource>, IEnumerable <TDestination> >(source.Items);
         return(response.ToList());
     }
     return(null);
 }
コード例 #14
0
        protected async override Task ProcessResponseImplAsync(NavigationResponse response)
        {
            Guard.ArgumentNotNull(response, "response");

            // we won't handle it the response, if it is not the active request!
            if (!response.Request.Equals(base.ActiveNavigationRequest))
            {
                return;
            }

            // we check if the navigation was successful or not
            if (response.Status != ResponseStatus.Success)
            {
                // we raise navigation failed and return - note for cancelled it returns to navigated state
                var _failedEventArgs = new NavigationFailedEventArgs(this, response.Request, response.Status, response.Error);
                OnNavigatingFailed(_failedEventArgs);
                return;
            }

            // we save our supporters and use them - note_ we need to save this to access later
            CurrentNavigationLifecycleSupporter     = NavigationService.GetSupporter <ISupportNavigationLifecycle>(response.Content);
            CurrentNavigationViewLifecycleSupporter = NavigationService.GetSupporter <ISupportNavigationViewLifecycle>(response.Content);
            CurrentNavigationStateSupporter         = NavigationService.GetSupporter <ISupportNavigationState>(response.Content);
            CurrentNavigationViewStateSupporter     = NavigationService.GetSupporter <ISupportNavigationViewState>(response.Content);

            // we save the url and the content
            CurrentNavigationRequest = response.Request;
            SetValue(ContentProperty, response.Content);

            // if the content support navigation, we pass in the request/response merged parameters
            if (this.CurrentNavigationLifecycleSupporter != null)
            {
                CurrentNavigationLifecycleSupporter.Initialize(response.ResponseParameters);
                await CurrentNavigationLifecycleSupporter.InitializeAsync(response.ResponseParameters);

                Title = CurrentNavigationLifecycleSupporter.Title ??
                        nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }
            else
            {
                Title = nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }


            // we raise completed
            OnNavigationCompleted(new NavigatedEventArgs(this, response.Request));

            // and once we have set the transition state, then we call the view's initialize
            if (CurrentNavigationViewLifecycleSupporter != null)
            {
                CurrentNavigationViewLifecycleSupporter.Initialize(response);
            }
        }
コード例 #15
0
 private void PublishNavigatedInfo(string title, NavigationResponse response)
 {
     Channel <NavigatedInfo> .Public.OnNext
     (
         new NavigatedInfo
         (
             response.Request,
             title,
             (response.Content as WindowElement).Id
         ),
         true
     );
 }
コード例 #16
0
        public IObservable <IUrlResponse> GetResponse(IRoutingContext context)
        {
            Guard.ArgumentNotNull(context, "context");
            if (!typeof(NavigationRequest).IsAssignableFrom(context.Request.GetType()))
            {
                throw new InvalidOperationException(REQUEST_TYPE_REQUIRED);
            }

            // lazily create the observer
            var _relayObservable = new LazyRelayObservable <IUrlResponse>((s) =>
            {
                Object _content = null;
                try
                {
                    // we get the assembly, not assuming that if not specified we take the application's assembly
                    var _assemblyName = (!string.IsNullOrEmpty(_resourceAssemblyName)) ?
                                        _resourceAssemblyName : GetApplicationAssemblyName();

                    // and we try and load thew resource
                    var _streamResourceInfo = System.Windows.Application.GetResourceStream(
                        new Uri(string.Format(RESOURCE_PATH_FORMAT, _assemblyName, _resourcePath), UriKind.Relative));

                    // we load the content
                    _content = _resourceLoader(_streamResourceInfo.Stream);
                }
                catch (Exception ex)
                {
                    s.OnError(ex);
                    return;
                }

                if (_content == null)
                {
                    // todo: need to specialize this exception
                    s.OnError(new InvalidOperationException(string.Format(NO_PAGE_RESOLVED, context.Request.RequestUrl)));
                }
                else
                {
                    // we get the navigation response
                    var _response = new NavigationResponse((NavigationRequest)context.Request, ResponseStatus.Success, _content, context.ParsedParameters);

                    // and return and close
                    s.OnNext(_response);
                    s.OnCompleted();
                }
            });

            // and return
            return(_relayObservable);
        }
 public NavigationResponse <bool> Convert(Bools source, NavigationResponse <bool> destination, ResolutionContext context)
 {
     if (source != null)
     {
         var items    = context.Mapper.Map <List <bool> >(source);
         var response = new NavigationResponse <bool>
         {
             Items = items,
             Total = items?.Count ?? 0,
             Error = context.Mapper.Map <ErrorResponse>(source.Error)
         };
         return(response);
     }
     return(null);
 }
コード例 #18
0
 public NavigationResponse <TDestination> Convert(List <TSource> source,
                                                  NavigationResponse <TDestination> destination,
                                                  ResolutionContext context)
 {
     if (source != null)
     {
         var itemMapping = context.Mapper.Map <IEnumerable <TSource>, IEnumerable <TDestination> >(source);
         var response    = new NavigationResponse <TDestination>
         {
             Items = itemMapping.ToList(),
             Total = source?.Count() ?? 0
         };
         return(response);
     }
     return(null);
 }
コード例 #19
0
        /// <summary>
        /// Is Navigation Valid
        /// </summary>
        /// <typeparam name="TResponse">Response Type</typeparam>
        /// <param name="navigationResponse">Navigation Response</param>
        /// <param name="navigateType">Navigate Type</param>
        /// <returns>True if Valid, False if Not</returns>
        public static bool IsNavigationValid <TResponse>(
            NavigationResponse <TResponse> navigationResponse,
            NavigateType navigateType)
        {
            switch (navigateType)
            {
            case NavigateType.Previous:
                return(navigationResponse.Back != null);

            case NavigateType.Next:
                return(navigationResponse.Next != null);

            default:
                return(navigationResponse.Href != null);
            }
        }
コード例 #20
0
 public NavigationResponse <RecommendationGenreResponse> Convert(AvailableGenreSeeds source,
                                                                 NavigationResponse <RecommendationGenreResponse> destination,
                                                                 ResolutionContext context)
 {
     if (source != null)
     {
         var list        = source.Genres;
         var itemMapping = context.Mapper.Map <List <RecommendationGenreResponse> >(list);
         var response    = new NavigationResponse <RecommendationGenreResponse>
         {
             Items = itemMapping,
             Total = itemMapping.Count
         };
         return(response);
     }
     return(null);
 }
 public NavigationResponse <TrackResponse> Convert(RecommendationsResponse source,
                                                   NavigationResponse <TrackResponse> destination,
                                                   ResolutionContext context)
 {
     if (source != null)
     {
         var itemMapping = context.Mapper.Map <List <TrackResponse> >(source.Tracks);
         itemMapping.ForEach(f => f.Seeds = context.Mapper.Map <List <RecommendationSeedResponse> >(source.Seeds));
         var response = new NavigationResponse <TrackResponse>
         {
             Items = itemMapping,
             Total = itemMapping.Count
         };
         return(response);
     }
     return(null);
 }
コード例 #22
0
 /// <summary>
 /// Get Favourites
 /// </summary>
 /// <typeparam name="TResponse">Response Type: AlbumResponse, ArtistResponse, TrackResponse, ShowResponse, EpisodeResponse</typeparam>
 /// <param name="client">Spotify Sdk Client</param>
 /// <param name="mapper">Mapper</param>
 /// <param name="response">Navigation Response of Response Type</param>
 /// <param name="multipleIds">Multiple Ids</param>
 /// <param name="market">Market</param>
 /// <returns>Navigation Response of Response Type</returns>
 public static async Task <NavigationResponse <TResponse> > GetFavouritesAsync <TResponse>(
     this ISpotifySdkClient client,
     IMapper mapper,
     NavigationResponse <TResponse> response,
     List <string> multipleIds,
     string market = null)
 {
     if (response != null && multipleIds != null)
     {
         var take    = client.GetTake();
         var total   = multipleIds.Count();
         var skip    = response.Offset += take;
         var itemIds = multipleIds.Skip(skip).Take(take).ToList();
         return(await client.GetFavouritesAsync <TResponse>(
                    mapper, itemIds, total, skip, take, market));
     }
     return(null);
 }
コード例 #23
0
        /// <summary>
        /// Attach List Artists Toggles
        /// </summary>
        /// <param name="client">Spotify Sdk Client</param>
        /// <param name="response">Navigation Response of Artist Response</param>
        public async static Task AttachListArtistsToggles(
            this ISpotifySdkClient client,
            NavigationResponse <ArtistResponse> response)
        {
            if (client.Config.IsAttachListArtistsToggles && response?.Items != null)
            {
                foreach (var batch in response.Items.Batch(max_toggles))
                {
                    var multipleIds = batch.Select(s => s.Id).ToList();
                    // Toggle Favourites
                    var toggleFavourites = await client.ListTogglesAsync(
                        ToggleType.Favourites,
                        multipleIds,
                        null,
                        (byte)FavouriteType.Artist);

                    if (toggleFavourites != null)
                    {
                        int index = 0;
                        foreach (var item in batch)
                        {
                            item.ToggleFavourite = toggleFavourites[index];
                            index++;
                        }
                    }
                    // Toggle Follow
                    var toggleFollow = await client.ListTogglesAsync(
                        ToggleType.Follow,
                        multipleIds,
                        null,
                        (byte)FollowType.Artist);

                    if (toggleFollow != null)
                    {
                        int index = 0;
                        foreach (var item in batch)
                        {
                            item.ToggleFollow = toggleFollow[index];
                            index++;
                        }
                    }
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Attach List Shows Toggles
        /// </summary>
        /// <param name="client">Spotify Sdk Client</param>
        /// <param name="response">Navigation Response of Show Response</param>
        public async static Task AttachListShowsToggles(
            this ISpotifySdkClient client,
            NavigationResponse <ShowResponse> response)
        {
            if (client.Config.IsAttachListShowsToggles && response?.Items != null)
            {
                foreach (var batch in response.Items.Batch(max_toggles))
                {
                    var multipleIds = batch.Select(s => s.Id).ToList();
                    // Toggle Favourites
                    var toggleFavourites = await client.ListTogglesAsync(
                        ToggleType.Favourites,
                        multipleIds,
                        null,
                        (byte)FavouriteType.Show);

                    if (toggleFavourites != null)
                    {
                        var index = 0;
                        foreach (var item in batch)
                        {
                            item.ToggleFavourite = toggleFavourites[index];
                            index++;
                        }
                    }
                    // Toggle Saved
                    var toggleSaved = await client.ListTogglesAsync(
                        ToggleType.Saved,
                        multipleIds,
                        null,
                        (byte)SavedType.Show);

                    if (toggleSaved != null)
                    {
                        var index = 0;
                        foreach (var item in batch)
                        {
                            item.ToggleSaved = toggleSaved[index];
                            index++;
                        }
                    }
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// Attach List Tracks Audio Features
        /// </summary>
        /// <param name="client">Spotify Sdk Client</param>
        /// <param name="response">Navigation Response of Track Response</param>
        public async static Task AttachListTracksAudioFeatures(
            this ISpotifySdkClient client,
            NavigationResponse <TrackResponse> response)
        {
            if (client.Config.IsAttachListTracksAudioFeatures && response?.Items != null)
            {
                // Get Audio Features for Several Tracks
                var features = await client.ListAudioFeaturesAsync(new AudioFeaturesRequest()
                {
                    MultipleTrackIds = response.Items.Select(s => s.Id).ToList()
                });

                if (features != null)
                {
                    for (int i = 0; i < response.Items.Count(); i++)
                    {
                        response.Items[i].AudioFeatures = features.Items[i];
                    }
                }
            }
        }
コード例 #26
0
        /// <summary>
        /// Attach List Playlist Item Toggles
        /// </summary>
        /// <param name="client">Spotify Sdk Client</param>
        /// <param name="response">Navigation Response of Play Item Response</param>
        public async static Task AttachListPlaylistItemsToggles(
            this ISpotifySdkClient client,
            NavigationResponse <PlaylistItemResponse> response)
        {
            if (client.Config.IsAttachListPlaylistItemsToggles && response != null)
            {
                // Track Toggles
                var tracks = response?.Items?
                             .Where(w => w.Track != null)?
                             .Select(s => s.Track)?
                             .ToList();
                await client.AttachTracksToggles(tracks);

                // Episode Toggles
                var episodes = response?.Items?
                               .Where(w => w.Episode != null)?
                               .Select(s => s.Episode)?
                               .ToList();
                await client.AttachEpisodesToggles(episodes);
            }
        }
 public CursorPaging <TDestination> Convert(NavigationResponse <TSource> source,
                                            CursorPaging <TDestination> destination,
                                            ResolutionContext context)
 {
     if (source != null)
     {
         var list        = source.Items.ToList();
         var itemMapping = context.Mapper.Map <IEnumerable <TSource>, IEnumerable <TDestination> >(list);
         var response    = new CursorPaging <TDestination>
         {
             Href   = source.Href,
             Before = source.Back,
             Items  = itemMapping.ToList(),
             Error  = context.Mapper.Map <Responses.ErrorResponse>(source.Error),
             Limit  = source.Limit,
             Next   = source.Next,
             Offset = source.Offset,
             Total  = source.Total
         };
         return(response);
     }
     return(null);
 }
コード例 #28
0
        private void MapRoute(NavigationResponse routeResponse, IEnumerable<GeoCoordinate> navPoints)
        {
            if (routeResponse == null)
                return;

            travelDuration = GetTravelDuration(routeResponse, config, out travelDistance);
            var points = from pt in routeResponse.Route.RoutePath.Points
                            select new GeoCoordinate
                            {
                                Latitude = pt.Latitude,
                                Longitude = pt.Longitude
                            };

            MapRoute(points, navPoints);
        }
コード例 #29
0
    private IEnumerator GetDirectionsInternal(GPSLocation pStart, GPSLocation pEnd)
    {
        string request = String.Format("foot-walking?api_key={0}&start={1}&end={2}", apiKey, pStart, pEnd);

        using (UnityWebRequest webRequest = UnityWebRequest.Get(baseURI + request))
        {
            // In case we will ever switch to JSON POSTs, we would need to use an authorization key instead of ?api_key=
            //webRequest.SetRequestHeader("Authorization", apiKey);

            yield return(webRequest.SendWebRequest());

            if (webRequest.isNetworkError)
            {
                Debug.Log("Error receiving navigation: " + webRequest.error);
            }
            else
            {
                // Parse JSON to class
                NavigationResponse response = JsonConvert.DeserializeObject <NavigationResponse>(webRequest.downloadHandler.text);
                // Store received path and apply it to the line renderer

                if (response == null)
                {
                    Debug.LogError("The web request response was null");
                    yield break;
                }

                if (response.features == null)
                {
                    Debug.LogError("The features was null, make sure a valid API key is in use");
                    yield break;
                }

                if (response.features != null && response.features.Count <= 0)
                {
                    Debug.LogError("Features list was empty");
                    yield break;
                }

                _receivedPath = GeometryToVector3(response.features[0]);

                Vector3 destinationPos = GetWorldPosFromGPS(pEnd.latitude, pEnd.longitude);

                InitializePathLineRenderers(destinationPos);

                if (_strayDetectionRoutine != null)
                {
                    StopCoroutine(_strayDetectionRoutine);
                }

                if (_lineRendererUpdateRoutine != null)
                {
                    StopCoroutine(_lineRendererUpdateRoutine);
                }

                _strayDetectionRoutine     = StartCoroutine(StrayDetectionRoutine());
                _lineRendererUpdateRoutine = StartCoroutine(LineRendererUpdateRoutine());
            }
        }

        _directionRoutine = null;
    }
コード例 #30
0
 public static double GetTravelDuration(NavigationResponse routeResponse, SystemConfig config)
 {
     double travelDist;
     return GetTravelDuration(routeResponse, config, out travelDist);
 }
コード例 #31
0
        protected async override Task ProcessResponseImplAsync(NavigationResponse response)
        {
            Guard.ArgumentNotNull(response, "response");

            // we won't handle it the response, if it is not the active request!
            if (!response.Request.Equals(base.ActiveNavigationRequest))
            {
                return;
            }

            // we check if the navigation was not successful we let the base class handle it
            if (response.Status != ResponseStatus.Success)
            {
                await base.ProcessResponseImplAsync(response);

                return;
            }

            // note_ we don't send this request to the base class, hereon
            // we add to the journal the current page info
            if (base.CurrentNavigationRequest != null)
            {
                if (_states.ContainsKey(base.CurrentNavigationRequest.RequestUrl))
                {
                    _states[base.CurrentNavigationRequest.RequestUrl] = GetCurrentPageContentState();
                }
                else
                {
                    _states.Add(base.CurrentNavigationRequest.RequestUrl, GetCurrentPageContentState());
                    base.NotifyPropertyChanged(() => CanPurgeJournal);
                }
            }

            // we save our supporters and use them - note_ we need to save this to access later
            CurrentNavigationLifecycleSupporter     = NavigationService.GetSupporter <ISupportNavigationLifecycle>(response.Content);
            CurrentNavigationViewLifecycleSupporter = NavigationService.GetSupporter <ISupportNavigationViewLifecycle>(response.Content);
            CurrentNavigationStateSupporter         = NavigationService.GetSupporter <ISupportNavigationState>(response.Content);
            CurrentNavigationViewStateSupporter     = NavigationService.GetSupporter <ISupportNavigationViewState>(response.Content);

            // we save the url and the content
            CurrentNavigationRequest = response.Request;
            SetValue(ContentProperty, response.Content);

            // if the content support navigation, we pass in the request/response merged parameters
            if (this.CurrentNavigationLifecycleSupporter != null)
            {
                CurrentNavigationLifecycleSupporter.Initialize(response.ResponseParameters);
                await CurrentNavigationLifecycleSupporter.InitializeAsync(response.ResponseParameters);

                Title = CurrentNavigationLifecycleSupporter.Title ??
                        nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }
            else
            {
                Title = nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }

            // we get the page state manager and restore the state
            if (CurrentNavigationStateSupporter != null)
            {
                // restore state, if we have a state
                if (_states.ContainsKey(response.Request.RequestUrl))
                {
                    CurrentNavigationStateSupporter.RestoreState(_states[response.Request.RequestUrl].State);  // note_ with stored state
                }
            }

            // if the content supports view state, and we are navigating back/forward
            if (CurrentNavigationViewStateSupporter != null)
            {
                if (_states.ContainsKey(response.Request.RequestUrl))
                {
                    CurrentNavigationViewStateSupporter.RestoreState(_states[response.Request.RequestUrl].VisualState);  // note_ with stored state
                }
            }


            // and raise the event navigation completed
            OnNavigationCompleted(new NavigatedEventArgs(this, response.Request));

            // and once we have set the transition state, then we call the view's initialize
            if (CurrentNavigationViewLifecycleSupporter != null)
            {
                CurrentNavigationViewLifecycleSupporter.Initialize(response);
            }
        }
コード例 #32
0
 public static double GetTravelDuration(NavigationResponse routeResponse, SystemConfig config, out double travelDistance)
 {
     travelDistance = 1000 * routeResponse.Route.TravelDistance;
     var travelDuration = routeResponse.Route.TravelDuration;
     if (routeResponse.Route.RouteLegs != null)
     {
         var routeLegs = routeResponse.Route.RouteLegs;
         if (routeLegs.Count == 1 || routeLegs.Count == 3)
         {
             var walkingDistance = routeLegs[0].TravelDistance;
             if (routeLegs.Count == 3)
                 walkingDistance += routeLegs[2].TravelDistance;
             var walkingSpeed = LocationHelper.GetTravelSpeed(TravelType.Walking, config.WalkingSpeed, false);
             travelDuration = 3600 * walkingDistance / walkingSpeed;
             if (routeLegs.Count == 3)
             {
                 var cyclingDistance = routeLegs[1].TravelDistance;
                 var cyclingSpeed = LocationHelper.GetTravelSpeed(TravelType.Cycling, config.CyclingSpeed, false);
                 travelDuration += 3600 * cyclingDistance / cyclingSpeed;
             }
             travelDuration = (int)travelDuration;
         }
     }
     return travelDuration;
 }
コード例 #33
0
ファイル: NavigationService.cs プロジェクト: cipjota/Chronos
 private void PublishNavigatedInfo(string title, NavigationResponse response)
 {
     Channel<NavigatedInfo>.Public.OnNext
     (
         new NavigatedInfo
         (
             response.Request,
             title,
             (response.Content as WindowElement).Id
         ),
         true
     );
 }
コード例 #34
0
        protected override async Task ProcessResponseImplAsync(NavigationResponse response)
        {
            Guard.ArgumentNotNull(response, "response");

            // we won't handle it the response, if it is not the active request!
            if (!response.Request.Equals(base.ActiveNavigationRequest))
            {
                return;
            }

            // we check if the navigation was successful or not
            if (response.Status != ResponseStatus.Success)
            {
                // we raise navigation failed and return
                await base.ProcessResponseImplAsync(response);

                return;
            }

            // note_ we don't send this request to the base class, hereon

            // we get the current page info, as in the current page before being navigated
            var _currentPageInfo = GetCurrentPageContentState();
            var _nextPageInfo    = default(PageContentState);

            // else as per the navigation mode we change the stacks
            switch (response.Request.NavigationMode)
            {
            // we treat new and unknown alike
            case NavigateMode.New:
            case NavigateMode.Unknown:

                // we check if we were to record
                if (_currentPageInfo != null)
                {
                    _backStack.Push(_currentPageInfo);
                }

                // we also clear the forward stack
                _forwardStack.Clear();

                // and we say history changed
                RaiseHistoryChanged();
                break;

            case NavigateMode.Back:
                if (CanNavigateBack)
                {
                    // we push the current item into the forward stack
                    _forwardStack.Push(_currentPageInfo);

                    // we remove one item
                    _nextPageInfo = _backStack.Pop();

                    // and we say history changed
                    RaiseHistoryChanged();
                }

                break;

            case NavigateMode.Forward:

                // we push the current item into the back stack
                _backStack.Push(_currentPageInfo);

                // and we remove one item
                _nextPageInfo = _forwardStack.Pop();

                // and we say history changed and return
                RaiseHistoryChanged();
                break;

            case NavigateMode.Refresh:

                // we don't need to do anything here, as the history remains the same
                _nextPageInfo = _currentPageInfo;
                break;
            }

            // we save our supporters and use them - note_ we need to save this to access later
            CurrentNavigationLifecycleSupporter     = NavigationService.GetSupporter <ISupportNavigationLifecycle>(response.Content);
            CurrentNavigationViewLifecycleSupporter = NavigationService.GetSupporter <ISupportNavigationViewLifecycle>(response.Content);
            CurrentNavigationStateSupporter         = NavigationService.GetSupporter <ISupportNavigationState>(response.Content);
            CurrentNavigationViewStateSupporter     = NavigationService.GetSupporter <ISupportNavigationViewState>(response.Content);

            // we save the url and the content
            CurrentNavigationRequest = response.Request;
            SetValue(ContentProperty, response.Content);

            // if the content support navigation, we pass in the request/response merged parameters
            if (this.CurrentNavigationLifecycleSupporter != null)
            {
                CurrentNavigationLifecycleSupporter.Initialize(response.ResponseParameters);
                await CurrentNavigationLifecycleSupporter.InitializeAsync(response.ResponseParameters);

                Title = CurrentNavigationLifecycleSupporter?.Title ??
                        nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }
            else
            {
                Title = nRoute.Navigation.Navigation.GetTitle(response.Content as DependencyObject);
            }

            // if the content supports state, and we are navigating back/forward
            if (CurrentNavigationStateSupporter != null)
            {
                // if we are navigating back  or forward, and we are to - also we treat the unknown state to be like a New navigation
                if (response.Request.NavigationMode != NavigateMode.New) // && response.Request.NavigationMode != NavigateMode.Unknown)
                {
                    CurrentNavigationStateSupporter.RestoreState(_nextPageInfo != null ? _nextPageInfo.State : null);
                }
            }

            // if the content supports view state, and we are navigating back/forward
            if (CurrentNavigationViewStateSupporter != null)
            {
                // if we are navigating back  or forward, and we are to - also we treat the unknown state to be like a New navigation
                if (response.Request.NavigationMode != NavigateMode.New)
                {
                    CurrentNavigationViewStateSupporter.RestoreState(_nextPageInfo != null ? _nextPageInfo.VisualState : null);
                }
            }

            // and raise the event navigation completed
            OnNavigationCompleted(new NavigatedEventArgs(this, response.Request));

            // and once we have set the transition state, then we call the view's initialize
            if (CurrentNavigationViewLifecycleSupporter != null)
            {
                CurrentNavigationViewLifecycleSupporter.Initialize(response);
            }
        }
コード例 #35
0
 /// <summary>
 /// Get Current Device Id
 /// </summary>
 /// <param name="devicesResponse"></param>
 /// <returns></returns>
 public static string GetCurrentDeviceId(this NavigationResponse <DeviceResponse> devicesResponse)
 => devicesResponse?.Items?.FirstOrDefault(w => w.IsActive)?.Id;