Пример #1
0
        private static HttpRequestMessage GetRequest(Uri uri)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

            System.Globalization.CultureInfo currentCulture = HttpRandomAccessStream.GetCurrentCulture();
            System.Globalization.CultureInfo.CurrentCulture = HttpRandomAccessStream.EnglishCulture;

            request.Headers.Add(InstaApiConstants.HEADER_USER_AGENT, InstagramApiSharp.ExtensionHelper.GenerateUserAgent(Helper.InstaApi.GetCurrentDevice(), Helper.InstaApi.GetApiVersionInfo(), Helper.InstaApi));

            request.Headers.Add(InstaApiConstants.HEADER_ACCEPT_LANGUAGE, Helper.InstaApi.AcceptLanguage);

            request.Headers.Add(InstaApiConstants.HEADER_X_FB_HTTP_ENGINE, "Liger");

            request.Headers.Add(InstaApiConstants.HEADER_X_FB_HTTP_IP, "True");

            request.Headers.Add(InstaApiConstants.HEADER_X_FB_SERVER_CLUSTER, "True");


            System.Globalization.CultureInfo.CurrentCulture = currentCulture;
            return(request);
        }
Пример #2
0
        private async void SetSource(Uri uri)
        {
            try
            {
                if (uri == null)
                {
                    return;
                }
                if (string.IsNullOrEmpty(Tag?.ToString()) /*|| Tag?.ToString() == "WorkingOnImage"*/)
                {
                    Tag = "Working";
                    _httpRandomAccessStream = await HttpRandomAccessStream.CreateAsync(Helper.InstaApi, HttpNetHelper.Client, uri);

                    SetSource(_httpRandomAccessStream, _httpRandomAccessStream.ContentType);
                }
            }
            catch (Exception ex)
            {
                _ = ex.PrintException($"{GetType().FullName}.SetSource");
            }
        }
        public async Task <VideoCacheDownloadOperationCompleteState> DownloadAsync()
        {
            IRandomAccessStream downloadStream = null;

            try
            {
                var uri = await _dmcVideoStreamingSession.GetDownloadUrlAndSetupDownloadSession();

                downloadStream = await HttpRandomAccessStream.CreateAsync(_dmcVideoStreamingSession.NiconicoSession.ToolkitContext.HttpClient, uri);
            }
            catch
            {
                downloadStream?.Dispose();
                throw;
            }

            Started?.Invoke(this, EventArgs.Empty);

            _cancelAwaitTcs          = new TaskCompletionSource <bool>();
            _cancellationTokenSource = new CancellationTokenSource();
            _onwerShipReturnedCancellationTokenSource = new CancellationTokenSource();
            _pauseCancellationTokenSource             = new CancellationTokenSource();
            _linkedCancellationTokenSource            = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, _onwerShipReturnedCancellationTokenSource.Token, _pauseCancellationTokenSource.Token);

            _dmcVideoStreamingSession.StopStreamingFromOwnerShipReturned += _dmcVideoStreamingSession_StopStreamingFromOwnerShipReturned;

            try
            {
                var ct = _linkedCancellationTokenSource.Token;
                await Task.Run(async() => await _videoCacheDownloadOperationOutput.CopyStreamAsync(downloadStream.AsStreamForRead(), new _Progress(x => Progress?.Invoke(this, x)), ct), ct);
            }
            catch (OperationCanceledException)
            {
                // 削除操作、または視聴権を喪失した場合
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    return(VideoCacheDownloadOperationCompleteState.DownloadCanceledWithUser);
                }
                else if (_pauseCancellationTokenSource.IsCancellationRequested)
                {
                    return(VideoCacheDownloadOperationCompleteState.DownloadPaused);
                }
                else if (_onwerShipReturnedCancellationTokenSource.IsCancellationRequested)
                {
                    return(VideoCacheDownloadOperationCompleteState.ReturnDownloadSessionOwnership);
                }
                else
                {
                    throw;
                }
            }
            catch (FileLoadException)
            {
                throw;
            }
            catch (Exception)
            {
                // ニコ動サーバー側からタイムアウトで切られた場合は一時停止扱い
                return(VideoCacheDownloadOperationCompleteState.DownloadPaused);
            }
            finally
            {
                _cancelAwaitTcs.TrySetResult(true);
                _dmcVideoStreamingSession.StopStreamingFromOwnerShipReturned -= _dmcVideoStreamingSession_StopStreamingFromOwnerShipReturned;
                downloadStream.Dispose();
                _onwerShipReturnedCancellationTokenSource.Dispose();
                _pauseCancellationTokenSource.Dispose();
                _cancellationTokenSource.Dispose();
                _linkedCancellationTokenSource.Dispose();
                _cancellationTokenSource = null;
                Completed?.Invoke(this, EventArgs.Empty);
            }

            return(VideoCacheDownloadOperationCompleteState.Completed);
        }
Пример #4
0
        private async Task BindMediaSourceAsync(MediaBinder sender, MediaBindingEventArgs args)
        {
            var deferal = args.GetDeferral();

            // Get the track data
            var track = JsonConvert.DeserializeObject <BaseTrack>(args.MediaBinder.Token);

            try
            {
                // Only run if the track exists
                if (track != null)
                {
                    switch (track.ServiceType)
                    {
                    case ServiceTypes.YouTube:
                        var youTubeAudioUrl = await track.GetAudioStreamAsync(_youTubeClient);

                        if (!string.IsNullOrEmpty(youTubeAudioUrl))
                        {
                            if (track.IsLive)
                            {
                                var source = await AdaptiveMediaSource.CreateFromUriAsync(new Uri(youTubeAudioUrl));

                                if (source.Status == AdaptiveMediaSourceCreationStatus.Success)
                                {
                                    args.SetAdaptiveMediaSource(source.MediaSource);
                                }
                            }
                            else
                            {
                                args.SetUri(new Uri(youTubeAudioUrl));
                            }
                        }
                        break;

                    case ServiceTypes.SoundCloud:
                    case ServiceTypes.SoundCloudV2:
                        // Build the url for soundcloud
                        var soundcloudStreamUrl = await track.GetAudioStreamAsync(_youTubeClient);

                        // SoundCloud now requires auth feeds

                        var scConnected = SoundByteService.Current.IsServiceConnected(ServiceTypes.SoundCloud);
                        if (!scConnected)
                        {
                            throw new Exception("You must be logged into your SoundCloud account to play music from SoundCloud!");
                        }

                        // Get scheme and token
                        var scheme = SoundByteService.Current.Services.FirstOrDefault(x => x.Service == ServiceTypes.SoundCloud)?.AuthenticationScheme;
                        var token  = SoundByteService.Current.Services.FirstOrDefault(x => x.Service == ServiceTypes.SoundCloud)?.UserToken?.AccessToken;

                        // Client with Auth
                        var client = new Windows.Web.Http.HttpClient();
                        client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue(scheme, token);

                        var stream = await HttpRandomAccessStream.CreateAsync(client, new Uri(soundcloudStreamUrl));

                        args.SetStream(stream, stream.ContentType);

                        break;

                    case ServiceTypes.Local:
                        var fileToken = track.CustomProperties["file_token"].ToString();
                        var file      = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);

                        args.SetStorageFile(file);
                        break;

                    case ServiceTypes.ITunesPodcast:
                        args.SetUri(new Uri(track.AudioStreamUrl));
                        break;

                    default:
                        // Get the audio stream url for this track
                        var audioStreamUrl = await track.GetAudioStreamAsync(_youTubeClient);

                        if (!string.IsNullOrEmpty(audioStreamUrl))
                        {
                            // Set generic stream url.
                            args.SetUri(new Uri(audioStreamUrl));
                        }
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // So we know an error has occured
                _telemetryService.TrackEvent("Media Item Load Fail", new Dictionary <string, string> {
                    { "Message", e.Message },
                    { "Service Type", track.ServiceType.ToString() },
                    { "Item ID", track.TrackId }
                });

                if (!(DeviceHelper.IsBackground || DeviceHelper.IsXbox))
                {
                    await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
                    {
                        App.NotificationManager?.Show("An error occurred while trying to play or preload the track '" + track?.Title + "' (" + track?.ServiceType + ").\n\nError message: " + e.Message, 6500);
                    });
                }
            }

            deferal.Complete();
        }