Пример #1
0
        protected async void UpdateIfUriIsInCache(Uri uri, TextBlock cacheStatusTextBlock)
        {
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.OnlyFromCache;

            var httpClient = new Windows.Web.Http.HttpClient(filter);
            var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri);

            try
            {
                await httpClient.SendRequestAsync(request);
                cacheStatusTextBlock.Text = "Yes";
                cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Green);
            }
            catch
            {
                cacheStatusTextBlock.Text = "No";
                cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red); 
            }
        }
Пример #2
0
        private async Task<RTHttpRequestMessage> ConvertRequestAsync(HttpRequestMessage request)
        {
            RTHttpRequestMessage rtRequest = new RTHttpRequestMessage(new RTHttpMethod(request.Method.Method), request.RequestUri);

            // We can only control the Version on the first request message since the WinRT API
            // has this property designed as a filter/handler property. In addition the overall design
            // of HTTP/2.0 is such that once the first request is using it, all the other requests
            // to the same endpoint will use it as well.
            if (Interlocked.Exchange(ref _filterMaxVersionSet, 1) == 0)
            {
                    _next.MaxVersion = RTHttpVersion.Http11;
            }

            // Headers
            foreach (KeyValuePair<string, IEnumerable<string>> headerPair in request.Headers)
            {
                foreach (string value in headerPair.Value)
                {
                    bool success = rtRequest.Headers.TryAppendWithoutValidation(headerPair.Key, value);
                    Debug.Assert(success);
                }
            }

            // Properties
            foreach (KeyValuePair<string, object> propertyPair in request.Properties)
            {
                rtRequest.Properties.Add(propertyPair.Key, propertyPair.Value);
            }

            // Content
            if (request.Content != null)
            {
                rtRequest.Content = await CreateRequestContentAsync(request, rtRequest.Headers).ConfigureAwait(false);
            }

            return rtRequest;
        }
Пример #3
0
        /// <summary>
        /// Called when the download of a DASH or HLS chunk is requested
        /// </summary>

        private async void AdaptiveMediaSource_DownloadRequested(Windows.Media.Streaming.Adaptive.AdaptiveMediaSource sender, Windows.Media.Streaming.Adaptive.AdaptiveMediaSourceDownloadRequestedEventArgs args)
        {
//            LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString());
            
            var deferral = args.GetDeferral();
            if (deferral != null)
            {
                args.Result.ResourceUri = args.ResourceUri;
                args.Result.ContentType = args.ResourceType.ToString();
                var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
                using (var httpClient = new Windows.Web.Http.HttpClient(filter))
                {
                    try
                    {
                        Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, args.Result.ResourceUri);
                        Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request);
                       // args.Result.ExtendedStatus = (uint)response.StatusCode;
                        if (response.IsSuccessStatusCode)
                        {
                            //args.Result.ExtendedStatus = (uint)response.StatusCode;
                            args.Result.InputStream = await response.Content.ReadAsInputStreamAsync();

                        }
                        else
                            LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " error: " + response.StatusCode.ToString());
                    }
                    catch (Exception e)
                    {
                        LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " exception: " + e.Message);

                    }
//                    LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " done");
                    deferral.Complete();
                }
            }
            
        }
        public static async Task<GameDescriptionAndRating> GetGameConfigFomServer(AppDataContext appDataContext)
        {
            JsonObject jsonParameter = ToJsonForGetExpansions(appDataContext);
            string parameter = jsonParameter.Stringify();

            var fullUrl = new System.Text.StringBuilder();
            fullUrl.Append(WebService.webUrl);
            fullUrl.Append("?action=GET&values=");
            fullUrl.Append(parameter.Replace(" ", "%20"));

            try
            {
                using (var client = new Windows.Web.Http.HttpClient())
                using (var request = new Windows.Web.Http.HttpRequestMessage())
                {
                    request.RequestUri = new System.Uri(fullUrl.ToString());                    
                    using (Windows.Web.Http.HttpResponseMessage responseMessage = await client.SendRequestAsync(request).AsTask())
                    {
                        if (responseMessage.IsSuccessStatusCode)
                        {
                            string strResult = await responseMessage.Content.ReadAsStringAsync().AsTask();
                            GameDescriptionAndRating description = WebService.GetGameDescriptionFromJson(strResult);
                            System.Diagnostics.Debug.WriteLine("Get Response from server:");
                            System.Diagnostics.Debug.WriteLine(strResult);
                            return description;
                        }
                    }
                }
            } catch (System.Exception)
            {

            }
            return null;
        }
        public static async Task SendGameConfigToServer(AppDataContext appDataContext)
        {
            GameDescription gameDescription = appDataContext.GetGameConfig().gameDescription;

            JsonObject json = WebService.ToJson(gameDescription, appDataContext.DeckRating.Value);
            string parameter = json.Stringify();

            var fullUrl = new System.Text.StringBuilder();
            fullUrl.Append(WebService.webUrl);
            fullUrl.Append("?action=RECORD&values=");
            fullUrl.Append(parameter.Replace(" ", "%20"));

            try
            {
                using (var client = new Windows.Web.Http.HttpClient())
                using (var request = new Windows.Web.Http.HttpRequestMessage())
                {
                    request.RequestUri = new System.Uri(fullUrl.ToString());
                    using (Windows.Web.Http.HttpResponseMessage responseMessage = await client.SendRequestAsync(request).AsTask())
                    {
                        if (responseMessage.IsSuccessStatusCode)
                        {
                            string strResult = await responseMessage.Content.ReadAsStringAsync().AsTask();
                            System.Diagnostics.Debug.WriteLine("RECORD Reponse from server:");
                            System.Diagnostics.Debug.WriteLine(strResult);
                        }
                    }
                }
            }
            catch (System.Exception)
            { }
        }
Пример #6
0
        private async Task<RTHttpRequestMessage> ConvertRequestAsync(HttpRequestMessage request)
        {
            RTHttpRequestMessage rtRequest = new RTHttpRequestMessage(new RTHttpMethod(request.Method.Method), request.RequestUri);

            // We can only control the Version on the first request message since the WinRT API
            // has this property designed as a filter/handler property. In addition the overall design
            // of HTTP/2.0 is such that once the first request is using it, all the other requests
            // to the same endpoint will use it as well.
            if (Interlocked.Exchange(ref _filterMaxVersionSet, 1) == 0)
            {
                RTHttpVersion maxVersion;
                if (request.Version == HttpVersionInternal.Version20)
                {
                    maxVersion = RTHttpVersion.Http20;
                }
                else if (request.Version == HttpVersionInternal.Version11)
                {
                    maxVersion = RTHttpVersion.Http11;
                }
                else if (request.Version == HttpVersionInternal.Version10)
                {
                    maxVersion = RTHttpVersion.Http10;
                }
                else
                {
                    // TODO (#7878): We need to throw an exception here similar to .NET Desktop
                    // throw new ArgumentException(SR.GetString(SR.net_wrongversion), "value");
                    //
                    // But we need to do that checking in the HttpClientHandler object itself.
                    // and we have that bug as well for the WinHttpHandler version also.
                    maxVersion = RTHttpVersion.Http11;
                }
                
                // The default for WinRT HttpBaseProtocolFilter.MaxVersion is HttpVersion.Http20.
                // So, we only have to change it if we don't want HTTP/2.0.
                if (maxVersion !=  RTHttpVersion.Http20)
                {
                    _next.MaxVersion = maxVersion;
                }
            }
            
            // Headers
            foreach (KeyValuePair<string, IEnumerable<string>> headerPair in request.Headers)
            {
                foreach (string value in headerPair.Value)
                {
                    bool success = rtRequest.Headers.TryAppendWithoutValidation(headerPair.Key, value);
                    Debug.Assert(success);
                }
            }

            // Properties
            foreach (KeyValuePair<string, object> propertyPair in request.Properties)
            {
                rtRequest.Properties.Add(propertyPair.Key, propertyPair.Value);
            }

            // Content
            if (request.Content != null)
            {
                rtRequest.Content = await CreateRequestContentAsync(request, rtRequest.Headers).ConfigureAwait(false);
            }

            return rtRequest;
        }
Пример #7
0
        /// <summary>
        /// SetAudioVideoUrl
        /// Prepare the MediaElement to play audio or video content 
        /// </summary>
        /// <param name="content">Url string of the content to play </param>
        /// <returns>true if success</returns>
        private async System.Threading.Tasks.Task<bool> SetAudioVideoUrl(string Content)
        {
            try
            {
                if (IsLocalFile(Content))
                {
                    Windows.Storage.StorageFile file = await GetFileFromLocalPathUrl(Content);
                    if (file != null)
                    {
                        mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromStorageFile(file);
                        /*
                        var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                        if (fileStream != null)
                        {
                            mediaPlayer.SetStreamSource(fileStream);
                            mediaPlayer.SetFileSource(file);
                            return true;
                        }*/
                    }
                    else
                        LogMessage("Failed to load media file: " + Content);
                }
                else if (!IsAdaptiveStreaming(Content))
                {
                    if (httpHeaders != null)
                    {
                        try
                        {
                            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

                            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, new Uri(Content));
                            SetHttpHeaders(httpHeaders, request.Headers);
                            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request, Windows.Web.Http.HttpCompletionOption.ResponseHeadersRead);
                            if (response.IsSuccessStatusCode)
                            {
                                string contentType = "video/mp4";
                                if (response.Content.Headers.ContainsKey("Content-Type"))
                                {
                                    contentType = response.Content.Headers["Content-Type"];
                                }
                                var inputStream = await response.Content.ReadAsInputStreamAsync();

                                var memStream = new MemoryStream();
                                await inputStream.AsStreamForRead().CopyToAsync(memStream);

                                mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromStream(memStream.AsRandomAccessStream(), contentType);
                            }
                            else
                                LogMessage("DownloadRequested for uri: " + Content.ToString() + " error: " + response.StatusCode.ToString());
                        }
                        catch (Exception e)
                        {
                            LogMessage("DownloadRequested for uri: " + Content.ToString() + " exception: " + e.Message);

                        }
                    }
                    else
                    {
                        mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromUri(new Uri(Content));
                    }
                    return true;
                }
                else
                {

                    // If SMOOTH stream
                    if (IsSmoothStreaming(Content))
                    {
                        mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromUri(new Uri(Content));
                        return true;
                    }
                    else
                    {
                        // If DASH or HLS content
                        // Create the AdaptiveMediaSource
                        Windows.Media.Streaming.Adaptive.AdaptiveMediaSourceCreationResult result = null;
                        if (httpHeaders != null)
                        {
                            try
                            {
                                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
                                SetHttpHeaders(httpHeaders, httpClient.DefaultRequestHeaders);
                                result = await Windows.Media.Streaming.Adaptive.AdaptiveMediaSource.CreateFromUriAsync(new Uri(Content), httpClient);
                            }
                            catch (Exception e)
                            {
                                LogMessage("Exception while downloading DASH or HLS manifest: " + e.Message);
                            }
                        }
                        else
                            result = await Windows.Media.Streaming.Adaptive.AdaptiveMediaSource.CreateFromUriAsync(new Uri(Content));
                        if (result.Status == Windows.Media.Streaming.Adaptive.AdaptiveMediaSourceCreationStatus.Success)
                        {
                            if (adaptiveMediaSource != null)
                            {
                                adaptiveMediaSource.DownloadBitrateChanged -= AdaptiveMediaSource_DownloadBitrateChanged;
                                adaptiveMediaSource.DownloadCompleted -= AdaptiveMediaSource_DownloadCompleted;
                                adaptiveMediaSource.DownloadFailed -= AdaptiveMediaSource_DownloadFailed;
                                adaptiveMediaSource.DownloadRequested -= AdaptiveMediaSource_DownloadRequested;
                                adaptiveMediaSource.PlaybackBitrateChanged -= AdaptiveMediaSource_PlaybackBitrateChanged;
                            }
                            adaptiveMediaSource = result.MediaSource;
                            adaptiveMediaSource.DownloadBitrateChanged += AdaptiveMediaSource_DownloadBitrateChanged;
                            adaptiveMediaSource.DownloadCompleted += AdaptiveMediaSource_DownloadCompleted;
                            adaptiveMediaSource.DownloadFailed += AdaptiveMediaSource_DownloadFailed;
                            adaptiveMediaSource.DownloadRequested += AdaptiveMediaSource_DownloadRequested;
                            adaptiveMediaSource.PlaybackBitrateChanged += AdaptiveMediaSource_PlaybackBitrateChanged;

                            LogMessage("Available bitrates: ");
                            uint startupBitrate = 0;
                            foreach (var b in adaptiveMediaSource.AvailableBitrates)
                            {
                                LogMessage("bitrate: " + b.ToString() + " b/s ");
                                if ((startupBitrate == 0) &&
                                    (b >= MinBitRate) &&
                                    (b <= MaxBitRate))
                                    startupBitrate = b;
                            }
                            // Set bitrate range for HLS and DASH
                            if(startupBitrate>0)
                                adaptiveMediaSource.InitialBitrate = startupBitrate;
                            adaptiveMediaSource.DesiredMaxBitrate = MaxBitRate;
                            adaptiveMediaSource.DesiredMinBitrate = MinBitRate;

                            mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
                            return true;
                        }
                        else
                            LogMessage("Failed to create AdaptiveMediaSource: " + result.Status.ToString());

                    }
                }
            }
            catch (Exception ex)
            {
                LogMessage("Exception Playing: " + ex.Message.ToString());
                CurrentMediaUrl = string.Empty;
                CurrentPosterUrl = string.Empty;
            }
            return false;
        }
        public void loadURL(string url, Dictionary<string, object> options)
        {
            var httpReferrer = options.itemOrDefault<string>("httpReferrer");
            var userAgent = options.itemOrDefault<string>("userAgent");
            var extraHeaders = options.itemOrDefault<Dictionary<string, object>>("extraHeaders");
            var uri = new Uri(url);

            var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri);
            if ((userAgent) != null)
                  request.Headers["User-Agent"] = userAgent;

            if ((httpReferrer) != null)
                request.Headers["Referrer"] = httpReferrer;

            if ((extraHeaders) != null)
            {
                foreach (var item in extraHeaders)
                {
                    request.Headers[item.Key] = item.Value as string;
                }
            }

            webView.NavigateWithHttpRequestMessage(request);
        }