protected override void BeforeExecute(HttpRequestOptions options) { options.RequestHeaders.Add("ClientId", "95add99f-9445-49f4-aa85-5ef3f77ac032"); options.UserAgent = "TouTvApp/2.0.13,(iPad3.1; iOS/8.1.2; fr-ca)"; options.AcceptHeader = "application/json"; base.BeforeExecute(options); }
private async Task DownloadNews(string path) { DateTime? lastUpdate = null; if (_fileSystem.FileExists(path)) { lastUpdate = _fileSystem.GetLastWriteTimeUtc(path); } var requestOptions = new HttpRequestOptions { Url = "http://emby.media/community/index.php?/blog/rss/1-media-browser-developers-blog", Progress = new Progress<double>(), UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.42 Safari/537.36", BufferContent = false }; using (var stream = await _httpClient.Get(requestOptions).ConfigureAwait(false)) { var doc = new XmlDocument(); doc.Load(stream); var news = ParseRssItems(doc).ToList(); _json.SerializeToFile(news, path); await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false); } }
public async Task GetDeviceInfo(CancellationToken cancellationToken) { var httpOptions = new HttpRequestOptions() { Url = string.Format("{0}/", getWebUrl()), CancellationToken = cancellationToken }; using (var stream = await _httpClient.Get(httpOptions)) { using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8)) { while (!sr.EndOfStream) { string line = StringHelper.StripXML(sr.ReadLine()); if (line.StartsWith("Model:")) { model = line.Replace("Model: ", ""); } if (line.StartsWith("Device ID:")) { deviceID = line.Replace("Device ID: ", ""); } if (line.StartsWith("Firmware:")) { firmware = line.Replace("Firmware: ", ""); } } if (String.IsNullOrWhiteSpace(model)) { throw new ApplicationException("Failed to locate the tuner host."); } } } }
private async Task DownloadNews(string path) { DateTime? lastUpdate = null; if (File.Exists(path)) { lastUpdate = _fileSystem.GetLastWriteTimeUtc(path); } var requestOptions = new HttpRequestOptions { Url = "http://emby.media/community/index.php?/blog/rss/1-media-browser-developers-blog", Progress = new Progress<double>() }; using (var stream = await _httpClient.Get(requestOptions).ConfigureAwait(false)) { var doc = new XmlDocument(); doc.Load(stream); var news = ParseRssItems(doc).ToList(); _json.SerializeToFile(news, path); await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false); } }
/// <summary> /// Initiate the nextPvr session /// </summary> private async Task InitiateSession(CancellationToken cancellationToken) { _logger.Info("[NextPvr] Start InitiateSession"); var baseUrl = Plugin.Instance.Configuration.WebServiceUrl; var options = new HttpRequestOptions { CancellationToken = cancellationToken, Url = string.Format("{0}/public/Util/NPVR/Client/Instantiate", baseUrl) }; using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) { var clientKeys = new InstantiateResponse().GetClientKeys(stream, _jsonSerializer, _logger); var sid = clientKeys.sid; var salt = clientKeys.salt; _logger.Info(string.Format("[NextPvr] Sid: {0}", sid)); var loggedIn = await Login(sid, salt, cancellationToken).ConfigureAwait(false); if (loggedIn) { _logger.Info("[NextPvr] Session initiated."); Sid = sid; } } }
public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { var httpRequestOptions = new HttpRequestOptions() { Url = mediaSource.Path }; httpRequestOptions.BufferContent = false; using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) { _logger.Info("Opened recording stream from tuner provider"); using (var output = _fileSystem.GetFileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { onStarted(); _logger.Info("Copying recording stream to file {0}", targetFile); // The media source if infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; await CopyUntilCancelled(response.Content, output, cancellationToken).ConfigureAwait(false); } } _logger.Info("Recording completed to file {0}", targetFile); }
public async Task SubscribeAsync(string url, string ip, int port, string localIp, int eventport, int timeOut = 3600) { var options = new HttpRequestOptions { Url = url, UserAgent = USERAGENT, LogRequest = _config.Configuration.DlnaOptions.EnableDebugLogging }; options.RequestHeaders["HOST"] = ip + ":" + port.ToString(_usCulture); options.RequestHeaders["CALLBACK"] = "<" + localIp + ":" + eventport.ToString(_usCulture) + ">"; options.RequestHeaders["NT"] = "upnp:event"; options.RequestHeaders["TIMEOUT"] = "Second-" + timeOut.ToString(_usCulture); // TODO: Method should be SUBSCRIBE // https://github.com/stormboy/node-upnp-controlpoint/blob/master/lib/upnp-service.js#L106 using (await _httpClient.Get(options).ConfigureAwait(false)) { } }
public async Task<DynamicImageResponse> GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken) { var channelItem = (IChannelItem)item; var imageResponse = new DynamicImageResponse(); if (!string.IsNullOrEmpty(channelItem.OriginalImageUrl)) { var options = new HttpRequestOptions { CancellationToken = cancellationToken, Url = channelItem.OriginalImageUrl }; var response = await _httpClient.GetResponse(options).ConfigureAwait(false); if (response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { imageResponse.HasImage = true; imageResponse.Stream = response.Content; imageResponse.SetFormatFromMimeType(response.ContentType); } else { _logger.Error("Provider did not return an image content type."); } } return imageResponse; }
public async Task<IEnumerable<ChannelItemInfo>> Refresh(IProviderManager providerManager, IHttpClient httpClient, string url, INotificationManager notificationManager, CancellationToken cancellationToken) { var options = new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, // Seeing some deflate stream errors EnableHttpCompression = false }; using (Stream stream = await httpClient.Get(options).ConfigureAwait(false)) { using (var reader = new StreamReader(stream)) { XDocument document = XDocument.Parse(reader.ReadToEnd()); var x = from c in document.Root.Element("channel").Elements("item") select c; return x.Select(CreatePodcast).Where(i => i != null); } } }
protected override async Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken) { var options = new HttpRequestOptions { Url = string.Format("{0}/lineup.json", GetApiUrl(info, false)), CancellationToken = cancellationToken }; using (var stream = await _httpClient.Get(options)) { var root = JsonSerializer.DeserializeFromStream<List<Channels>>(stream); if (root != null) { var result = root.Select(i => new ChannelInfo { Name = i.GuideName, Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture), Id = ChannelIdPrefix + i.GuideNumber.ToString(CultureInfo.InvariantCulture), IsFavorite = i.Favorite }); if (info.ImportFavoritesOnly) { result = result.Where(i => (i.IsFavorite ?? true)).ToList(); } return result; } return new List<ChannelInfo>(); } }
public async Task<CheckForUpdateResult> CheckForUpdateResult(string organzation, string repository, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken) { var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository); var options = new HttpRequestOptions { Url = url, EnableKeepAlive = false, CancellationToken = cancellationToken, UserAgent = "Emby/3.0" }; if (_cacheLength.Ticks > 0) { options.CacheMode = CacheMode.Unconditional; options.CacheLength = _cacheLength; } using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) { var obj = _jsonSerializer.DeserializeFromStream<RootObject[]>(stream); return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); } }
public async Task<IEnumerable<ChannelInfo>> GetChannels(CancellationToken cancellationToken) { ChannelList = new List<ChannelInfo>(); var options = new HttpRequestOptions() { Url = string.Format("http://{0}/LiveTv/Channels?api_key={1}", Url,ApiKey), CancellationToken = cancellationToken, AcceptHeader = "application/json" }; using (var stream = await _httpClient.Get(options)) { var root = _jsonSerializer.DeserializeFromStream<ChannelResponse>(stream); channels = root.Items; _logger.Info("Found " + root.Items.Count() + "channels on host: " ); if (root.Items != null) { ChannelList = root.Items.Select(i => new ChannelInfo { Name = i.Name, Number = i.Number, Id = i.Number }).ToList(); } return ChannelList; } }
public async Task<DynamicImageResponse> GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken) { var liveTvItem = (LiveTvProgram)item; var imageResponse = new DynamicImageResponse(); if (!string.IsNullOrEmpty(liveTvItem.ProviderImagePath)) { imageResponse.Path = liveTvItem.ProviderImagePath; imageResponse.HasImage = true; } else if (!string.IsNullOrEmpty(liveTvItem.ProviderImageUrl)) { var options = new HttpRequestOptions { CancellationToken = cancellationToken, Url = liveTvItem.ProviderImageUrl }; var response = await _httpClient.GetResponse(options).ConfigureAwait(false); if (response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { imageResponse.HasImage = true; imageResponse.Stream = response.Content; imageResponse.SetFormatFromMimeType(response.ContentType); } else { _logger.Error("Provider did not return an image content type."); } } else if (liveTvItem.HasProviderImage ?? true) { var service = _liveTvManager.Services.FirstOrDefault(i => string.Equals(i.Name, liveTvItem.ServiceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { try { var channel = _liveTvManager.GetInternalChannel(liveTvItem.ChannelId); var response = await service.GetProgramImageAsync(liveTvItem.ExternalId, channel.ExternalId, cancellationToken).ConfigureAwait(false); if (response != null) { imageResponse.HasImage = true; imageResponse.Stream = response.Stream; imageResponse.Format = response.Format; } } catch (NotImplementedException) { } } } return imageResponse; }
protected override void BeforeExecute(HttpRequestOptions options) { var authorization = "Bearer " + AccessToken; options.RequestHeaders.Add("Authorization", authorization); options.UserAgent = "TouTvApp/2.0.13,(iPad3.1; iOS/8.1.2; fr-ca)"; options.AcceptHeader = "application/json"; base.BeforeExecute(options); }
public async Task RecordInternal(MediaSourceInfo mediaSource, string tempFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { var httpRequestOptions = new HttpRequestOptions() { Url = mediaSource.Path }; httpRequestOptions.BufferContent = false; using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) { _logger.Info("Opened recording stream from tuner provider"); Directory.CreateDirectory(Path.GetDirectoryName(tempFile)); using (var output = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { //onStarted(); _logger.Info("Copying recording stream to file {0}", tempFile); var bufferMs = 5000; if (mediaSource.RunTimeTicks.HasValue) { // The media source already has a fixed duration // But add another stop 1 minute later just in case the recording gets stuck for any reason var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1))); cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; } else { // The media source if infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMilliseconds(bufferMs))); cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; } var tempFileTask = response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken); // Give the temp file a little time to build up await Task.Delay(bufferMs, cancellationToken).ConfigureAwait(false); var recordTask = Task.Run(() => RecordFromFile(mediaSource, tempFile, targetFile, duration, onStarted, cancellationToken), cancellationToken); await tempFileTask.ConfigureAwait(false); await recordTask.ConfigureAwait(false); } } _logger.Info("Recording completed to file {0}", targetFile); }
public async Task<QueryResult<ChannelItemInfo>> Browse(ContentDirectoryBrowseRequest request, CancellationToken cancellationToken) { var options = new HttpRequestOptions { CancellationToken = cancellationToken, UserAgent = "Emby", RequestContentType = "text/xml; charset=\"utf-8\"", LogErrorResponseBody = true, Url = request.ContentDirectoryUrl, BufferContent = false }; options.RequestHeaders["SOAPACTION"] = "urn:schemas-upnp-org:service:ContentDirectory:1#Browse"; options.RequestContent = GetRequestBody(request); var response = await _httpClient.SendAsync(options, "POST"); using (var reader = new StreamReader(response.Content)) { var doc = XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); var queryResult = new QueryResult<ChannelItemInfo>(); if (doc.Document == null) return queryResult; var responseElement = doc.Document.Descendants(UNamespace + "BrowseResponse").ToList(); var countElement = responseElement.Select(i => i.Element("TotalMatches")).FirstOrDefault(i => i != null); var countValue = countElement == null ? null : countElement.Value; int count; if (!string.IsNullOrWhiteSpace(countValue) && int.TryParse(countValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out count)) { queryResult.TotalRecordCount = count; var resultElement = responseElement.Select(i => i.Element("Result")).FirstOrDefault(i => i != null); var resultString = (string)resultElement; if (resultElement != null) { var xElement = XElement.Parse(resultString); } } return queryResult; } }
public async Task<RootObject> GetEpisodeList(int offset, InternalChannelItemQuery query, CancellationToken cancellationToken) { var options = new HttpRequestOptions { Url = String.Format("http://revision3.com/api/getEpisodes.json?api_key=0b1faede6785d04b78735b139ddf2910f34ad601&show_id={0}&offset={1}&limit={2}", query.FolderId, offset, query.Limit), CancellationToken = cancellationToken, // Seeing errors about block length with this enabled EnableHttpCompression = false }; using (var json = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { return _jsonSerializer.DeserializeFromStream<RootObject>(json.Content); } }
public async Task<RootObject> GetLatestEpisodeList(CancellationToken cancellationToken) { var options = new HttpRequestOptions { Url = "http://revision3.com/api/getEpisodes.json?api_key=0b1faede6785d04b78735b139ddf2910f34ad601&grouping=latest", CancellationToken = cancellationToken, // Seeing errors about block length with this enabled EnableHttpCompression = false }; using (var json = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) { return _jsonSerializer.DeserializeFromStream<RootObject>(json.Content); } }
public static async Task DownloadVideo(IHttpClient httpClient, HttpRequestOptions httpRequestOptions, ILogger logger, string filePath, CancellationToken cancellationToken) { //string filePath = Path.GetTempPath()+"/test.ts"; httpRequestOptions.BufferContent = false; httpRequestOptions.CancellationToken = cancellationToken; logger.Info("Writing file to path: " + filePath); using (var response = await httpClient.SendAsync(httpRequestOptions, "GET")) { using (var output = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { await response.Content.CopyToAsync(output, 4096, cancellationToken); } } }
public async Task ReportServerUsage(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var data = new Dictionary<string, string> { { "feature", _applicationHost.Name }, { "mac", _applicationHost.SystemId }, { "serverid", _applicationHost.SystemId }, { "deviceid", _applicationHost.SystemId }, { "ver", _applicationHost.ApplicationVersion.ToString() }, { "platform", _applicationHost.OperatingSystemDisplayName }, { "isservice", _applicationHost.IsRunningAsService.ToString().ToLower()} }; var users = _userManager.Users.ToList(); data["localusers"] = users.Count(i => !i.ConnectLinkType.HasValue).ToString(CultureInfo.InvariantCulture); data["guests"] = users.Count(i => i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest).ToString(CultureInfo.InvariantCulture); data["linkedusers"] = users.Count(i => i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.LinkedUser).ToString(CultureInfo.InvariantCulture); data["plugins"] = string.Join(",", _applicationHost.Plugins.Select(i => i.Id).ToArray()); var logErrors = false; #if DEBUG logErrors = true; #endif var options = new HttpRequestOptions { Url = MbAdminUrl + "service/registration/ping", CancellationToken = cancellationToken, // Seeing block length errors EnableHttpCompression = false, LogRequest = false, LogErrors = logErrors, BufferContent = false }; options.SetPostData(data); using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)) { } }
private async Task DownloadNews(string path) { var requestOptions = new HttpRequestOptions { Url = "http://mediabrowser3.com/community/index.php?/blog/rss/1-media-browser-developers-blog", Progress = new Progress<double>() }; using (var stream = await _httpClient.Get(requestOptions).ConfigureAwait(false)) { var doc = new XmlDocument(); doc.Load(stream); var news = ParseRssItems(doc).ToList(); _json.SerializeToFile(news, path); } }
public async Task RespondAsync(Uri url, string ip, int port, string localIp, int eventport, int timeOut = 20000) { var options = new HttpRequestOptions { Url = url.ToString(), UserAgent = USERAGENT }; options.RequestHeaders["HOST"] = ip + ":" + port; options.RequestHeaders["CALLBACK"] = "<" + localIp + ":" + eventport + ">"; options.RequestHeaders["NT"] = "upnp:event"; options.RequestHeaders["TIMEOUT"] = "Second - 3600"; //request.CookieContainer = Container; using (await _httpClient.Get(options).ConfigureAwait(false)) { } }
private async Task<IEnumerable<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken) { var options = new HttpRequestOptions { Url = string.Format("{0}/lineup.json", GetApiUrl(info, false)), CancellationToken = cancellationToken }; using (var stream = await _httpClient.Get(options)) { var lineup = JsonSerializer.DeserializeFromStream<List<Channels>>(stream) ?? new List<Channels>(); if (info.ImportFavoritesOnly) { lineup = lineup.Where(i => i.Favorite).ToList(); } return lineup.Where(i => !i.DRM).ToList(); } }
public async Task<XDocument> GetDataAsync(string url) { var options = new HttpRequestOptions { Url = url, UserAgent = USERAGENT, LogRequest = _config.GetDlnaConfiguration().EnableDebugLogging, LogErrorResponseBody = true }; options.RequestHeaders["FriendlyName.DLNA.ORG"] = FriendlyName; using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace); } } }
public async Task SubscribeAsync(string url, string ip, int port, string localIp, int eventport, int timeOut = 3600) { var options = new HttpRequestOptions { Url = url, UserAgent = USERAGENT, LogErrorResponseBody = true }; options.RequestHeaders["HOST"] = ip + ":" + port.ToString(_usCulture); options.RequestHeaders["CALLBACK"] = "<" + localIp + ":" + eventport.ToString(_usCulture) + ">"; options.RequestHeaders["NT"] = "upnp:event"; options.RequestHeaders["TIMEOUT"] = "Second-" + timeOut.ToString(_usCulture); await _httpClient.SendAsync(options, "SUBSCRIBE").ConfigureAwait(false); }
public Task SendNotification(UserNotification request, CancellationToken cancellationToken) { var options = GetOptions(request.User); var parameters = new Dictionary<string, string> { // {"device_iden", options.DeviceId}, {"type", "note"}, {"title", request.Name}, {"body", request.Description} }; _logger.Debug("PushBullet to Token : {0} - {1} - {2}", options.Token, options.DeviceId, request.Description); var _httpRequest = new HttpRequestOptions(); string authInfo = options.Token; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); _httpRequest.RequestHeaders["Authorization"] = "Basic " + authInfo; _httpRequest.Url = "https://api.pushbullet.com/v2/pushes"; return _httpClient.Post(_httpRequest, parameters); }
public async Task Record(MediaSourceInfo mediaSource, string targetFile, Action onStarted, CancellationToken cancellationToken) { var httpRequestOptions = new HttpRequestOptions() { Url = mediaSource.Path }; httpRequestOptions.BufferContent = false; using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) { _logger.Info("Opened recording stream from tuner provider"); using (var output = _fileSystem.GetFileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { onStarted(); _logger.Info("Copying recording stream to file stream"); await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false); } } }
public object Post(TestNotification request) { var options = GetOptions(request.UserID); var parameters = new Dictionary<string, string> { {"type", "note"}, {"title", "Test Notification" }, {"body", "This is a test notification from MediaBrowser"} }; var _httpRequest = new HttpRequestOptions(); //Create Basic HTTP Auth Header... string authInfo = options.Token; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); _httpRequest.RequestHeaders["Authorization"] = "Basic " + authInfo; _httpRequest.Url = "https://api.pushbullet.com/v2/pushes"; return _httpClient.Post(_httpRequest, parameters); }
private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options) { var statusCode = response.StatusCode; var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299; if (!isSuccessful) { if (options.LogErrorResponseBody) { try { using (var stream = response.GetResponseStream()) { if (stream != null) { using (var reader = new StreamReader(stream)) { var msg = reader.ReadToEnd(); _logger.Error(msg); } } } } catch { } } throw new HttpException(response.StatusDescription) { StatusCode = response.StatusCode }; } }
/// <summary> /// Throws the cancellation exception. /// </summary> /// <param name="options">The options.</param> /// <param name="client">The client.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="exception">The exception.</param> /// <returns>Exception.</returns> private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception) { // If the HttpClient's timeout is reached, it will cancel the Task internally if (!cancellationToken.IsCancellationRequested) { var msg = string.Format("Connection to {0} timed out", options.Url); if (options.LogErrors) { _logger.Error(msg); } client.LastTimeout = DateTime.UtcNow; // Throw an HttpException so that the caller doesn't think it was cancelled by user code return new HttpException(msg, exception) { IsTimedOut = true }; } return exception; }