/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Generates ArcGIS online server token. /// </summary> /// <param name="tokenServiceURL"> /// Token service URL. /// </param> /// <param name="credentials"> /// Credentials required to generate token. /// </param> /// <returns> /// Token string. /// </returns> public static Token GetServerToken(string tokenServiceURL, NetworkCredential credentials) { Debug.Assert(tokenServiceURL != null); Debug.Assert(credentials != null); HttpRequestOptions opt = new HttpRequestOptions(); opt.Method = HttpMethod.Get; opt.UseGZipEncoding = false; opt.Timeout = GET_TOKEN_TIMEOUT; var response = WebHelper.SendRequest(tokenServiceURL, _GetTokenCommonQueryString(credentials), opt); return _ParseTokenResponse(response); }
private async Task <UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request) { var connectUsername = request.ConnectUserName; var sendingUserId = request.SendingUserId; if (string.IsNullOrWhiteSpace(connectUsername)) { throw new ArgumentNullException("connectUsername"); } if (string.IsNullOrWhiteSpace(ConnectServerId)) { throw new ArgumentNullException("ConnectServerId"); } var sendingUser = GetUser(sendingUserId); var requesterUserName = sendingUser.ConnectUserName; if (string.IsNullOrWhiteSpace(requesterUserName)) { throw new ArgumentException("A Connect account is required in order to send invitations."); } string connectUserId = null; var result = new UserLinkResult(); try { var connectUser = await GetConnectUser(new ConnectUserQuery { NameOrEmail = connectUsername }, CancellationToken.None).ConfigureAwait(false); if (!connectUser.IsActive) { throw new ArgumentException("The Emby account is not active. Please ensure the account has been activated by following the instructions within the email confirmation."); } connectUserId = connectUser.Id; result.GuestDisplayName = connectUser.Name; } catch (HttpException ex) { if (!ex.StatusCode.HasValue) { throw; } // If they entered a username, then whatever the error is just throw it, for example, user not found if (!Validator.EmailIsValid(connectUsername)) { if (ex.StatusCode.Value == HttpStatusCode.NotFound) { throw new ResourceNotFoundException(); } throw; } if (ex.StatusCode.Value != HttpStatusCode.NotFound) { throw; } } if (string.IsNullOrWhiteSpace(connectUserId)) { return(await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false)); } var url = GetConnectUrl("ServerAuthorizations"); var options = new HttpRequestOptions { Url = url, CancellationToken = CancellationToken.None }; var accessToken = Guid.NewGuid().ToString("N"); var postData = new Dictionary <string, string> { { "serverId", ConnectServerId }, { "userId", connectUserId }, { "userType", "Guest" }, { "accessToken", accessToken }, { "requesterUserName", requesterUserName } }; options.SetPostData(postData); SetServerAccessToken(options); SetApplicationHeader(options); // No need to examine the response using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content) { var response = _json.DeserializeFromStream <ServerUserAuthorizationResponse>(stream); result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase); _data.PendingAuthorizations.Add(new ConnectAuthorizationInternal { ConnectUserId = response.UserId, Id = response.Id, ImageUrl = response.UserImageUrl, UserName = response.UserName, EnabledLibraries = request.EnabledLibraries, EnabledChannels = request.EnabledChannels, EnableLiveTv = request.EnableLiveTv, AccessToken = accessToken }); CacheData(); } await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false); return(result); }
protected virtual void BeforeExecute(HttpRequestOptions options) { // Do nothing }
protected override void BeforeExecute(HttpRequestOptions options) { options.AcceptHeader = "application/vnd.twitchtv.v2+json"; }
public override async Task Open(CancellationToken openCancellationToken) { LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested(); var mediaSource = OriginalMediaSource; var url = mediaSource.Path; FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); var typeName = GetType().Name; Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); var httpRequestOptions = new HttpRequestOptions { Url = url, CancellationToken = CancellationToken.None, BufferContent = false, // Increase a little bit TimeoutMs = 30000, EnableHttpCompression = false, LogResponse = true, LogResponseHeaders = true }; foreach (var header in mediaSource.RequiredHttpHeaders) { httpRequestOptions.RequestHeaders[header.Key] = header.Value; } var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false); var extension = "ts"; var requiresRemux = false; var contentType = response.ContentType ?? string.Empty; if (contentType.IndexOf("matroska", StringComparison.OrdinalIgnoreCase) != -1) { requiresRemux = true; } else if (contentType.IndexOf("mp4", StringComparison.OrdinalIgnoreCase) != -1 || contentType.IndexOf("dash", StringComparison.OrdinalIgnoreCase) != -1 || contentType.IndexOf("mpegURL", StringComparison.OrdinalIgnoreCase) != -1 || contentType.IndexOf("text/", StringComparison.OrdinalIgnoreCase) != -1) { requiresRemux = true; } // Close the stream without any sharing features if (requiresRemux) { using (response) { return; } } SetTempFilePath(extension); var taskCompletionSource = new TaskCompletionSource <bool>(); var now = DateTime.UtcNow; StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token); //OpenedMediaSource.Protocol = MediaProtocol.File; //OpenedMediaSource.Path = tempFile; //OpenedMediaSource.ReadAtNativeFramerate = true; MediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts"; MediaSource.Protocol = MediaProtocol.Http; //OpenedMediaSource.Path = TempFilePath; //OpenedMediaSource.Protocol = MediaProtocol.File; //OpenedMediaSource.Path = _tempFilePath; //OpenedMediaSource.Protocol = MediaProtocol.File; //OpenedMediaSource.SupportsDirectPlay = false; //OpenedMediaSource.SupportsDirectStream = true; //OpenedMediaSource.SupportsTranscoding = true; await taskCompletionSource.Task.ConfigureAwait(false); }
public async Task <HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options) { ValidateParams(options); _fileSystem.CreateDirectory(_appPaths.TempDirectory); var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp"); if (options.Progress == null) { throw new ArgumentException("Options did not have a Progress value.", nameof(options)); } options.CancellationToken.ThrowIfCancellationRequested(); var httpWebRequest = GetRequest(options, "GET"); if (options.ResourcePool != null) { await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false); } options.Progress.Report(0); if (options.LogRequest) { if (options.LogRequestAsDebug) { _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url); } else { _logger.LogInformation("HttpClientManager.GetTempFileResponse url: {0}", options.Url); } } var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression); try { options.CancellationToken.ThrowIfCancellationRequested(); using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false)) { var httpResponse = (HttpWebResponse)response; EnsureSuccessStatusCode(client, httpResponse, options); options.CancellationToken.ThrowIfCancellationRequested(); var contentLength = GetContentLength(httpResponse); if (contentLength.HasValue) { using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) { await httpResponse.GetResponseStream().CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); } } else { // We're not able to track progress using (var stream = httpResponse.GetResponseStream()) using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) { await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); } } options.Progress.Report(100); return(GetResponseInfo(httpResponse, tempFile, contentLength)); } } catch (Exception ex) { DeleteTempFile(tempFile); throw GetException(ex, options, client); } finally { options.ResourcePool?.Release(); } }
/// <summary> /// Gets the movie db response. /// </summary> internal Task <Stream> GetMovieDbResponse(HttpRequestOptions options) { options.ResourcePool = MovieDbResourcePool; return(_httpClient.Get(options)); }
private async Task <MBRegistrationRecord> GetRegistrationStatusInternal(string feature, string mb2Equivalent = null, string version = null) { var lastChecked = LicenseFile.LastChecked(feature); //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho var reg = new RegRecord { // Cache the result for up to a week registered = lastChecked > DateTime.UtcNow.AddDays(-7) }; var success = reg.registered; if (!(lastChecked > DateTime.UtcNow.AddDays(-1))) { var data = new Dictionary <string, string> { { "feature", feature }, { "key", SupporterKey }, { "mac", _appHost.SystemId }, { "systemid", _appHost.SystemId }, { "mb2equiv", mb2Equivalent }, { "ver", version }, { "platform", _appHost.OperatingSystemDisplayName }, { "isservice", _appHost.IsRunningAsService.ToString().ToLower() } }; try { var options = new HttpRequestOptions { Url = MBValidateUrl, // Seeing block length errors EnableHttpCompression = false }; options.SetPostData(data); using (var json = (await _httpClient.Post(options).ConfigureAwait(false)).Content) { reg = _jsonSerializer.DeserializeFromStream <RegRecord>(json); success = true; } if (reg.registered) { LicenseFile.AddRegCheck(feature); } else { LicenseFile.RemoveRegCheck(feature); } } catch (Exception e) { _logger.ErrorException("Error checking registration status of {0}", e, feature); } } var record = new MBRegistrationRecord { IsRegistered = reg.registered, ExpirationDate = reg.expDate, RegChecked = true, RegError = !success }; record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered); record.IsValid = !record.RegChecked || (record.IsRegistered || record.TrialVersion); return(record); }
public async Task AddMetadata(ListingsProviderInfo info, List <ChannelInfo> channels, CancellationToken cancellationToken) { var listingsId = info.ListingsId; if (string.IsNullOrWhiteSpace(listingsId)) { throw new Exception("ListingsId required"); } var token = await GetToken(info, cancellationToken); if (string.IsNullOrWhiteSpace(token)) { throw new Exception("token required"); } ClearPairCache(listingsId); var httpOptions = new HttpRequestOptions() { Url = ApiUrl + "/lineups/" + listingsId, UserAgent = UserAgent, CancellationToken = cancellationToken, LogErrorResponseBody = true, // The data can be large so give it some extra time TimeoutMs = 60000 }; httpOptions.RequestHeaders["token"] = token; using (var response = await Get(httpOptions, true, info).ConfigureAwait(false)) { var root = _jsonSerializer.DeserializeFromStream <ScheduleDirect.Channel>(response); _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); _logger.Info("Mapping Stations to Channel"); foreach (ScheduleDirect.Map map in root.map) { var channelNumber = map.logicalChannelNumber; if (string.IsNullOrWhiteSpace(channelNumber)) { channelNumber = map.channel; } if (string.IsNullOrWhiteSpace(channelNumber)) { channelNumber = map.atscMajor + "." + map.atscMinor; } channelNumber = channelNumber.TrimStart('0'); _logger.Debug("Found channel: " + channelNumber + " in Schedules Direct"); var schChannel = root.stations.FirstOrDefault(item => item.stationID == map.stationID); AddToChannelPairCache(listingsId, channelNumber, schChannel); } _logger.Info("Added " + GetChannelPairCacheCount(listingsId) + " channels to the dictionary"); foreach (ChannelInfo channel in channels) { var station = GetStation(listingsId, channel.Number, channel.Name); if (station != null) { if (station.logo != null) { channel.ImageUrl = station.logo.URL; channel.HasImage = true; } string channelName = station.name; channel.Name = channelName; } else { _logger.Info("Schedules Direct doesnt have data for channel: " + channel.Number + " " + channel.Name); } } } }
public Task <HttpResponseInfo> Post(HttpRequestOptions options) { throw new NotImplementedException(); }
// Must have constructor with this signature, otherwise exception at run time public ODataMiddleware(RequestDelegate next, IConfiguration config, IOptions <HttpRequestOptions> requestOptions) { _next = next; _appConfig = config; _requestOptions = requestOptions?.Value ?? new HttpRequestOptions(); }
public Task <HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod) { throw new NotImplementedException(); }
public Task <HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options) { throw new NotImplementedException(); }
public Task <String> GetTempFile(HttpRequestOptions options) { throw new NotImplementedException(); }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public RouteSolveResponse Solve( RouteSolveRequest request, IEnumerable<Type> knownTypes) { Debug.Assert(request != null); var context = new RequestContext(_server.OpenConnection(), knownTypes); var url = UriHelper.Concat(context.Connection.Url, _baseUrl); string query = RestHelper.BuildQueryString(request, knownTypes, false); HttpRequestOptions opt = new HttpRequestOptions(); opt.Method = HttpMethod.Post; opt.UseGZipEncoding = true; opt.Timeout = DEFAULT_REQ_TIMEOUT; return _restService.SendRequest<RouteSolveResponse>(context, url, query, opt); }
public async Task <IEnumerable <ProgramInfo> > GetProgramsAsync(ListingsProviderInfo info, string channelNumber, string channelName, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) { List <ProgramInfo> programsInfo = new List <ProgramInfo>(); var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(token)) { _logger.Warn("SchedulesDirect token is empty, returning empty program list"); return(programsInfo); } if (string.IsNullOrWhiteSpace(info.ListingsId)) { _logger.Warn("ListingsId is null, returning empty program list"); return(programsInfo); } var dates = GetScheduleRequestDates(startDateUtc, endDateUtc); ScheduleDirect.Station station = GetStation(info.ListingsId, channelNumber, channelName); if (station == null) { _logger.Info("No Schedules Direct Station found for channel {0} with name {1}", channelNumber, channelName); return(programsInfo); } string stationID = station.stationID; _logger.Info("Channel Station ID is: " + stationID); List <ScheduleDirect.RequestScheduleForChannel> requestList = new List <ScheduleDirect.RequestScheduleForChannel>() { new ScheduleDirect.RequestScheduleForChannel() { stationID = stationID, date = dates } }; var requestString = _jsonSerializer.SerializeToString(requestList); _logger.Debug("Request string for schedules is: " + requestString); var httpOptions = new HttpRequestOptions() { Url = ApiUrl + "/schedules", UserAgent = UserAgent, CancellationToken = cancellationToken, // The data can be large so give it some extra time TimeoutMs = 60000, LogErrorResponseBody = true }; httpOptions.RequestHeaders["token"] = token; httpOptions.RequestContent = requestString; using (var response = await Post(httpOptions, true, info).ConfigureAwait(false)) { StreamReader reader = new StreamReader(response.Content); string responseString = reader.ReadToEnd(); var dailySchedules = _jsonSerializer.DeserializeFromString <List <ScheduleDirect.Day> >(responseString); _logger.Debug("Found " + dailySchedules.Count + " programs on " + channelNumber + " ScheduleDirect"); httpOptions = new HttpRequestOptions() { Url = ApiUrl + "/programs", UserAgent = UserAgent, CancellationToken = cancellationToken, LogErrorResponseBody = true, // The data can be large so give it some extra time TimeoutMs = 60000 }; httpOptions.RequestHeaders["token"] = token; List <string> programsID = new List <string>(); programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList(); var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]"; httpOptions.RequestContent = requestBody; using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false)) { StreamReader innerReader = new StreamReader(innerResponse.Content); responseString = innerReader.ReadToEnd(); var programDetails = _jsonSerializer.DeserializeFromString <List <ScheduleDirect.ProgramDetails> >( responseString); var programDict = programDetails.ToDictionary(p => p.programID, y => y); var images = await GetImageForPrograms(info, programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID).ToList(), cancellationToken); var schedules = dailySchedules.SelectMany(d => d.programs); foreach (ScheduleDirect.Program schedule in schedules) { //_logger.Debug("Proccesing Schedule for statio ID " + stationID + // " which corresponds to channel " + channelNumber + " and program id " + // schedule.programID + " which says it has images? " + // programDict[schedule.programID].hasImageArtwork); if (images != null) { var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10)); if (imageIndex > -1) { programDict[schedule.programID].images = GetProgramLogo(ApiUrl, images[imageIndex]); } } programsInfo.Add(GetProgram(channelNumber, schedule, programDict[schedule.programID])); } _logger.Info("Finished with EPGData"); } } return(programsInfo); }
public Task <Stream> Get(HttpRequestOptions options) { throw new NotImplementedException(); }
/// <summary> /// Performs a GET request and returns the resulting stream /// </summary> /// <param name="options">The options.</param> /// <returns>Task{Stream}.</returns> /// <exception cref="HttpException"></exception> /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception> public async Task <Stream> Get(HttpRequestOptions options) { ValidateParams(options.Url, options.CancellationToken); options.CancellationToken.ThrowIfCancellationRequested(); var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression); if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < 30) { throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url)) { IsTimedOut = true }; } using (var message = GetHttpRequestMessage(options)) { if (options.ResourcePool != null) { await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false); } if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < 30) { if (options.ResourcePool != null) { options.ResourcePool.Release(); } throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true }; } _logger.Info("HttpClientManager.Get url: {0}", options.Url); try { options.CancellationToken.ThrowIfCancellationRequested(); var response = await client.HttpClient.SendAsync(message, HttpCompletionOption.ResponseContentRead, options.CancellationToken).ConfigureAwait(false); EnsureSuccessStatusCode(response); options.CancellationToken.ThrowIfCancellationRequested(); return(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); } catch (OperationCanceledException ex) { var exception = GetCancellationException(options.Url, options.CancellationToken, ex); var httpException = exception as HttpException; if (httpException != null && httpException.IsTimedOut) { client.LastTimeout = DateTime.UtcNow; } throw exception; } catch (HttpRequestException ex) { _logger.ErrorException("Error getting response from " + options.Url, ex); throw new HttpException(ex.Message, ex); } catch (Exception ex) { _logger.ErrorException("Error getting response from " + options.Url, ex); throw; } finally { if (options.ResourcePool != null) { options.ResourcePool.Release(); } } } }
private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options) { var statusCode = response.StatusCode; var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299; if (isSuccessful) { return; } if (options.LogErrorResponseBody) { try { using (var stream = response.GetResponseStream()) { if (stream != null) { using (var reader = new StreamReader(stream)) { var msg = reader.ReadToEnd(); _logger.LogError(msg); } } } } catch { } } throw new HttpException(response.StatusDescription) { StatusCode = response.StatusCode }; }
public async Task <HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options) { ValidateParams(options.Url, options.CancellationToken); var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp"); if (options.Progress == null) { throw new ArgumentNullException("progress"); } options.CancellationToken.ThrowIfCancellationRequested(); if (options.ResourcePool != null) { await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false); } options.Progress.Report(0); _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", options.Url, tempFile); try { options.CancellationToken.ThrowIfCancellationRequested(); using (var message = GetHttpRequestMessage(options)) { using (var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).HttpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false)) { EnsureSuccessStatusCode(response); options.CancellationToken.ThrowIfCancellationRequested(); var contentLength = GetContentLength(response); if (!contentLength.HasValue) { // We're not able to track progress using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true)) { await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); } } } else { using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), options.Progress.Report, contentLength.Value)) { using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true)) { await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); } } } options.Progress.Report(100); return(new HttpResponseInfo { TempFilePath = tempFile, StatusCode = response.StatusCode, ContentType = response.Content.Headers.ContentType.MediaType }); } } } catch (Exception ex) { throw GetTempFileException(ex, options, tempFile); } finally { if (options.ResourcePool != null) { options.ResourcePool.Release(); } } }
private async Task SendRequest(HttpRequestOptions options) { using (var response = await _httpClient.Post(options).ConfigureAwait(false)) { } }
private WebRequest GetRequest(HttpRequestOptions options, string method) { string url = options.Url; Uri uriAddress = new Uri(url); string userInfo = uriAddress.UserInfo; if (!string.IsNullOrWhiteSpace(userInfo)) { _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url); url = url.Replace(userInfo + "@", string.Empty); } WebRequest request = CreateWebRequest(url); if (request is HttpWebRequest httpWebRequest) { AddRequestHeaders(httpWebRequest, options); if (options.EnableHttpCompression) { httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate; if (options.DecompressionMethod.HasValue && options.DecompressionMethod.Value == CompressionMethod.Gzip) { httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip; } } else { httpWebRequest.AutomaticDecompression = DecompressionMethods.None; } httpWebRequest.KeepAlive = options.EnableKeepAlive; if (!string.IsNullOrEmpty(options.Host)) { httpWebRequest.Host = options.Host; } if (!string.IsNullOrEmpty(options.Referer)) { httpWebRequest.Referer = options.Referer; } } request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); request.Method = method; request.Timeout = options.TimeoutMs; if (!string.IsNullOrWhiteSpace(userInfo)) { var parts = userInfo.Split(':'); if (parts.Length == 2) { request.Credentials = GetCredential(url, parts[0], parts[1]); // TODO: .net core ?? request.PreAuthenticate = true; } } return(request); }
protected async Task <T> PutRequest <T>(HttpRequestOptions httpRequest, CancellationToken cancellationToken) { var result = await _httpClient.SendAsync(httpRequest, "PUT"); return(_jsonSerializer.DeserializeFromStream <T>(result.Content)); }
/// <summary> /// Gets the response internal. /// </summary> /// <param name="options">The options.</param> /// <returns>Task{HttpResponseInfo}.</returns> public Task <HttpResponseInfo> GetResponse(HttpRequestOptions options) { return(SendAsync(options, "GET")); }
private async Task <UserLinkResult> LinkUserInternal(string userId, string connectUsername) { if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentNullException("userId"); } if (string.IsNullOrWhiteSpace(connectUsername)) { throw new ArgumentNullException("connectUsername"); } if (string.IsNullOrWhiteSpace(ConnectServerId)) { throw new ArgumentNullException("ConnectServerId"); } var connectUser = await GetConnectUser(new ConnectUserQuery { NameOrEmail = connectUsername }, CancellationToken.None).ConfigureAwait(false); if (!connectUser.IsActive) { throw new ArgumentException("The Emby account has been disabled."); } var user = GetUser(userId); if (!string.IsNullOrWhiteSpace(user.ConnectUserId)) { await RemoveConnect(user, connectUser.Id).ConfigureAwait(false); } var url = GetConnectUrl("ServerAuthorizations"); var options = new HttpRequestOptions { Url = url, CancellationToken = CancellationToken.None }; var accessToken = Guid.NewGuid().ToString("N"); var postData = new Dictionary <string, string> { { "serverId", ConnectServerId }, { "userId", connectUser.Id }, { "userType", "Linked" }, { "accessToken", accessToken } }; options.SetPostData(postData); SetServerAccessToken(options); SetApplicationHeader(options); var result = new UserLinkResult(); // No need to examine the response using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content) { var response = _json.DeserializeFromStream <ServerUserAuthorizationResponse>(stream); result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase); } user.ConnectAccessKey = accessToken; user.ConnectUserName = connectUser.Name; user.ConnectUserId = connectUser.Id; user.ConnectLinkType = UserLinkType.LinkedUser; await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false); await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration); await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false); return(result); }
/// <summary> /// Performs a GET request and returns the resulting stream /// </summary> /// <param name="options">The options.</param> /// <returns>Task{Stream}.</returns> public async Task <Stream> Get(HttpRequestOptions options) { var response = await GetResponse(options).ConfigureAwait(false); return(response.Content); }
private void SetApplicationHeader(HttpRequestOptions options) { options.RequestHeaders.Add("X-Application", XApplicationValue); }
private async Task <HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod) { ValidateParams(options); options.CancellationToken.ThrowIfCancellationRequested(); var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression); if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds) { throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url)) { IsTimedOut = true }; } var httpWebRequest = GetRequest(options, httpMethod); if (options.RequestContentBytes != null || !string.IsNullOrEmpty(options.RequestContent) || string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase)) { try { var bytes = options.RequestContentBytes ?? Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty); var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded"; if (options.AppendCharsetToMimeType) { contentType = contentType.TrimEnd(';') + "; charset=\"utf-8\""; } httpWebRequest.ContentType = contentType; httpWebRequest.ContentLength = bytes.Length; (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length); } catch (Exception ex) { throw new HttpException(ex.Message) { IsTimedOut = true }; } } if (options.ResourcePool != null) { await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false); } if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds) { options.ResourcePool?.Release(); throw new HttpException($"Connection to {options.Url} timed out") { IsTimedOut = true }; } if (options.LogRequest) { if (options.LogRequestAsDebug) { _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); } else { _logger.LogInformation("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); } } try { options.CancellationToken.ThrowIfCancellationRequested(); if (!options.BufferContent) { var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false); var httpResponse = (HttpWebResponse)response; EnsureSuccessStatusCode(client, httpResponse, options); options.CancellationToken.ThrowIfCancellationRequested(); return(GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse)); } using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false)) { var httpResponse = (HttpWebResponse)response; EnsureSuccessStatusCode(client, httpResponse, options); options.CancellationToken.ThrowIfCancellationRequested(); using (var stream = httpResponse.GetResponseStream()) { var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Position = 0; return(GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null)); } } } catch (OperationCanceledException ex) { throw GetCancellationException(options, client, options.CancellationToken, ex); } catch (Exception ex) { throw GetException(ex, options, client); } finally { options.ResourcePool?.Release(); } }
/// <summary> /// Create a recurrent recording /// </summary> /// <param name="info">The recurrend program info</param> /// <param name="cancellationToken">The CancelationToken</param> /// <returns></returns> public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken) { _logger.Info(string.Format("[NextPvr] Start CreateSeriesTimer Async for ChannelId: {0} & Name: {1}", info.ChannelId, info.Name)); await EnsureConnectionAsync(cancellationToken).ConfigureAwait(false); var baseUrl = Plugin.Instance.Configuration.WebServiceUrl; var options = new HttpRequestOptions { CancellationToken = cancellationToken, Url = string.Format("{0}/public/ScheduleService/Record?sid={1}", baseUrl, Sid) }; var timerSettings = await GetDefaultScheduleSettings(cancellationToken).ConfigureAwait(false); timerSettings.allChannels = info.RecordAnyChannel; timerSettings.onlyNew = info.RecordNewOnly; timerSettings.recurringName = info.Name; timerSettings.recordAnyTimeslot = info.RecordAnyTime; if (!info.RecordAnyTime) { timerSettings.startDate = info.StartDate.ToString(_usCulture); timerSettings.endDate = info.EndDate.ToString(_usCulture); timerSettings.recordThisTimeslot = true; } if (info.Days.Count == 1) { timerSettings.recordThisDay = true; } if (info.Days.Count > 1 && info.Days.Count < 7) { timerSettings.recordSpecificdays = true; } timerSettings.recordAnyDay = info.Days.Count == 7; timerSettings.daySunday = info.Days.Contains(DayOfWeek.Sunday); timerSettings.dayMonday = info.Days.Contains(DayOfWeek.Monday); timerSettings.dayTuesday = info.Days.Contains(DayOfWeek.Tuesday); timerSettings.dayWednesday = info.Days.Contains(DayOfWeek.Wednesday); timerSettings.dayThursday = info.Days.Contains(DayOfWeek.Thursday); timerSettings.dayFriday = info.Days.Contains(DayOfWeek.Friday); timerSettings.daySaturday = info.Days.Contains(DayOfWeek.Saturday); if (!info.RecordAnyChannel) { timerSettings.ChannelOID = int.Parse(info.ChannelId, _usCulture); } if (!string.IsNullOrEmpty(info.ProgramId)) { timerSettings.epgeventOID = int.Parse(info.ProgramId, _usCulture); } timerSettings.post_padding_min = info.PostPaddingSeconds / 60; timerSettings.pre_padding_min = info.PrePaddingSeconds / 60; var postContent = _jsonSerializer.SerializeToString(timerSettings); UtilsHelper.DebugInformation(_logger, string.Format("[NextPvr] TimerSettings CreateSeriesTimer: {0} for ChannelId: {1} & Name: {2}", postContent, info.ChannelId, info.Name)); options.RequestContent = postContent; options.RequestContentType = "application/json"; try { await _httpClient.Post(options).ConfigureAwait((false)); } catch (HttpException ex) { _logger.Error(string.Format("[NextPvr] CreateSeries async with exception: {0} ", ex.Message)); throw new LiveTvConflictException(); } }
public Task <HttpResponseInfo> Post(HttpRequestOptions options) { return(SendAsync(options, "POST")); }
/// <summary> /// Get server token using request where "referer" is specified. /// </summary> /// <param name="tokenServiceURL">Token service URL.</param> /// <param name="credentials">Credentials to get token.</param> /// <returns>Token from service.</returns> public static Token GetServerTokenUsingReferer(string tokenServiceURL, NetworkCredential credentials) { Debug.Assert(tokenServiceURL != null); Debug.Assert(credentials != null); StringBuilder query = new StringBuilder(_GetTokenCommonQueryString(credentials)); RestHelper.AddQueryParam(QUERY_EXPIRATION, EXPIRATION_IN_MINUTES, query, true); RestHelper.AddQueryParam(QUERY_CLIENT, REFERER_PARAMETER_NAME, query, true); RestHelper.AddQueryParam(REFERER_PARAMETER_NAME, RefererValue, query, true); HttpRequestOptions opt = new HttpRequestOptions(); opt.Method = HttpMethod.Get; opt.UseGZipEncoding = false; opt.Timeout = GET_TOKEN_TIMEOUT; var response = WebHelper.SendRequest(tokenServiceURL, query.ToString(), opt); return _ParseTokenResponse(response); }
/// <summary> /// Downloads the contents of a given url into a temporary location /// </summary> /// <param name="options">The options.</param> /// <returns>Task{System.String}.</returns> public async Task <string> GetTempFile(HttpRequestOptions options) { var response = await GetTempFileResponse(options).ConfigureAwait(false); return(response.TempFilePath); }
private void _DoHttpAuth(string serviceUrl, NetworkCredential credentials) { Debug.Assert(serviceUrl != null); try { var options = new HttpRequestOptions() { Method = HttpMethod.Get, Timeout = HTTP_REQ_TIMEOUT, UseGZipEncoding = true, }; WebHelper.SendRequest(serviceUrl, "wsdl", options); } catch (WebException e) { var response = e.Response as HttpWebResponse; if (response == null || response.StatusCode != HttpStatusCode.Unauthorized) { throw; } // HTTP_STATUS_DENIED (401): // The requested resource requires user authentication. throw new AuthenticationException(); } }
private void SetServerAccessToken(HttpRequestOptions options) { options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey); }