예제 #1
0
        internal async Task <RootObject> FetchMainResult(string id, int seasonNumber, int episodeNumber, string language, CancellationToken cancellationToken)
        {
            var url = string.Format(GetTvInfo3, id, seasonNumber.ToString(CultureInfo.InvariantCulture), episodeNumber, MovieDbProvider.ApiKey);

            if (!string.IsNullOrEmpty(language))
            {
                url += string.Format("&language={0}", language);
            }

            var includeImageLanguageParam = MovieDbProvider.GetImageLanguagesParam(language);

            // Get images in english and with no language
            url += "&include_image_language=" + includeImageLanguageParam;

            cancellationToken.ThrowIfCancellationRequested();

            using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken,
                AcceptHeader = MovieDbProvider.AcceptHeader
            }).ConfigureAwait(false))
            {
                return(_jsonSerializer.DeserializeFromStream <RootObject>(json));
            }
        }
        /// <summary>
        /// Retrieves the user data.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="key">The key.</param>
        /// <returns>Task{UserItemData}.</returns>
        private UserItemData RetrieveUserData(Guid userId, string key)
        {
            using (var cmd = _connection.CreateCommand())
            {
                cmd.CommandText = "select data from userdata where key = @key and userId=@userId";

                var idParam = cmd.Parameters.Add("@key", DbType.String);
                idParam.Value = key;

                var userIdParam = cmd.Parameters.Add("@userId", DbType.Guid);
                userIdParam.Value = userId;

                using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
                {
                    if (reader.Read())
                    {
                        using (var stream = reader.GetMemoryStream(0))
                        {
                            return(_jsonSerializer.DeserializeFromStream <UserItemData>(stream));
                        }
                    }
                }

                return(new UserItemData());
            }
        }
        public DateTimeOffset GetUpdateTime(Stream stream, IJsonSerializer json, ILogger <LiveTvService> logger)
        {
            var root = json.DeserializeFromStream <RootObject>(stream);

            UtilsHelper.DebugInformation(logger, string.Format("[NextPVR] LastUpdate Response: {0}", json.SerializeToString(root)));
            return(DateTimeOffset.FromUnixTimeSeconds(root.last_update));
        }
예제 #4
0
        public static async Task<MBRegistrationRecord> GetRegistrationStatus(IHttpClient httpClient, IJsonSerializer jsonSerializer, string feature, string mb2Equivalent = null)
        {
            var mac = GetMacAddress();
            var data = new Dictionary<string, string> {{"feature", feature}, {"key",SupporterKey}, {"mac",mac}, {"mb2equiv",mb2Equivalent}, {"legacykey", LegacyKey} };

            var reg = new RegRecord();
            try
            {
                using (var json = await httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
                {
                    reg = jsonSerializer.DeserializeFromStream<RegRecord>(json);
                }

                if (reg.registered)
                {
                    LicenseFile.AddRegCheck(feature);
                }

            }
            catch (Exception)
            {
                //if we have trouble obtaining from web - allow it if we've validated in the past 30 days
                reg.registered = LicenseFile.LastChecked(feature) > DateTime.UtcNow.AddDays(-30);
            }

            return new MBRegistrationRecord {IsRegistered = reg.registered, ExpirationDate = reg.expDate, RegChecked = true};
        }
        public IEnumerable <ChannelInfo> GetChannels(Stream stream, IJsonSerializer json, ILogger <LiveTvService> logger)
        {
            var root = json.DeserializeFromStream <RootObject>(stream);

            if (root == null)
            {
                logger.LogError("Failed to download channel information.");
                throw new Exception("Failed to download channel information.");
            }

            if (root.channels != null)
            {
                UtilsHelper.DebugInformation(logger, string.Format("[NextPVR] ChannelResponse: {0}", json.SerializeToString(root)));
                return(root.channels.Select(i => new ChannelInfo
                {
                    Name = i.channelName,
                    Number = i.channelNumberFormated,
                    Id = i.channelId.ToString(_usCulture),
                    ImageUrl = string.Format("{0}/service?method=channel.icon&channel_id={1}", _baseUrl, i.channelId),
                    ChannelType = ChannelHelper.GetChannelType(i.channelType),
                    HasImage = i.channelIcon
                }));
            }

            return(new List <ChannelInfo>());
        }
예제 #6
0
        /// <summary>
        /// Retrieve all users from the database
        /// </summary>
        /// <returns>IEnumerable{User}.</returns>
        public IEnumerable <User> RetrieveAllUsers()
        {
            var list = new List <User>();

            using (var connection = CreateConnection(true).Result)
            {
                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = "select guid,data from users";

                    using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
                    {
                        while (reader.Read())
                        {
                            var id = reader.GetGuid(0);

                            using (var stream = reader.GetMemoryStream(1))
                            {
                                var user = _jsonSerializer.DeserializeFromStream <User>(stream);
                                user.Id = id;
                                list.Add(user);
                            }
                        }
                    }
                }
            }

            return(list);
        }
        private async Task <ChannelItemResult> GetStreams(string mainCategory, InternalChannelItemQuery query, CancellationToken cancellationToken)
        {
            var page  = new HtmlDocument();
            var items = new List <ChannelItemInfo>();

            using (var json = await _httpClient.Get(String.Format("http://www.ustream.tv/ajax-alwayscache/new/explore/{0}/all.json?subCategory={1}&type=live&location=anywhere&page={2}", mainCategory, query.FolderId, 1), CancellationToken.None).ConfigureAwait(false))
            {
                var reg = _jsonSerializer.DeserializeFromStream <RootObject>(json);

                page.LoadHtml(reg.pageContent);

                foreach (var node in page.DocumentNode.SelectNodes("//div[contains(@class, \"media-item\")]"))
                {
                    var url   = node.SelectSingleNode(".//img/parent::a").Attributes["href"].Value;
                    var title = node.SelectSingleNode(".//h4/a/text()").InnerText;
                    var thumb = node.SelectSingleNode(".//img").Attributes["src"].Value;

                    items.Add(new ChannelItemInfo
                    {
                        Name             = title,
                        ImageUrl         = thumb,
                        Id               = "stream_" + url,
                        Type             = ChannelItemType.Media,
                        ContentType      = ChannelMediaContentType.Clip,
                        IsInfiniteStream = true,
                        MediaType        = ChannelMediaType.Video,
                    });
                }
            }

            return(new ChannelItemResult
            {
                Items = items.ToList()
            });
        }
예제 #8
0
        public object Get(ReviewRequest request)
        {
            var parms = "?id=" + request.Id;

            if (request.MaxRating > 0)
            {
                parms += "&max=" + request.MaxRating;
            }
            if (request.MinRating > 0)
            {
                parms += "&min=" + request.MinRating;
            }
            if (request.MinRating > 0)
            {
                parms += "&limit=" + request.Limit;
            }
            if (request.ForceTitle)
            {
                parms += "&title=true";
            }

            var result = _httpClient.Get(Constants.MbAdminUrl + "/service/packageReview/retrieve" + parms, CancellationToken.None).Result;

            var reviews = _serializer.DeserializeFromStream <List <PackageReviewInfo> >(result);

            return(ToOptimizedResult(reviews));
        }
예제 #9
0
        public static async Task<MBRegistrationRecord> GetRegistrationStatus(IHttpClient httpClient, IJsonSerializer jsonSerializer, string feature, string mb2Equivalent = null, string version = null)
        {
            //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 {registered = LicenseFile.LastChecked(feature) > DateTime.UtcNow.AddDays(-30)};

            if (!reg.registered)
            {
                var mac = _networkManager.GetMacAddress();
                var data = new Dictionary<string, string> { { "feature", feature }, { "key", SupporterKey }, { "mac", mac }, { "mb2equiv", mb2Equivalent }, { "legacykey", LegacyKey }, { "ver", version }, { "platform", Environment.OSVersion.VersionString } };

                try
                {
                    using (var json = await httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
                    {
                        reg = jsonSerializer.DeserializeFromStream<RegRecord>(json);
                    }

                    if (reg.registered)
                    {
                        LicenseFile.AddRegCheck(feature);
                    }
                    else
                    {
                        LicenseFile.RemoveRegCheck(feature);
                    }

                }
                catch (Exception e)
                {
                    _logger.ErrorException("Error checking registration status of {0}", e, feature);
                }
            }

            return new MBRegistrationRecord {IsRegistered = reg.registered, ExpirationDate = reg.expDate, RegChecked = true};
        }
예제 #10
0
        /// <summary>
        /// Gets the display preferences.
        /// </summary>
        /// <param name="displayPreferencesId">The display preferences id.</param>
        /// <param name="userId">The user id.</param>
        /// <param name="client">The client.</param>
        /// <returns>Task{DisplayPreferences}.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, Guid userId, string client)
        {
            if (string.IsNullOrWhiteSpace(displayPreferencesId))
            {
                throw new ArgumentNullException("displayPreferencesId");
            }

            var guidId = displayPreferencesId.GetMD5();

            var cmd = _connection.CreateCommand();

            cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client";

            cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value       = guidId;
            cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value   = userId;
            cmd.Parameters.Add(cmd, "@client", DbType.String).Value = client;

            using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
            {
                if (reader.Read())
                {
                    using (var stream = reader.GetMemoryStream(0))
                    {
                        return(_jsonSerializer.DeserializeFromStream <DisplayPreferences>(stream));
                    }
                }
            }

            return(new DisplayPreferences
            {
                Id = guidId.ToString("N")
            });
        }
예제 #11
0
        private BaseItem GetItem(IDataReader reader)
        {
            var typeString = reader.GetString(0);

            var type = _typeMapper.GetType(typeString);

            if (type == null)
            {
                _logger.Debug("Unknown type {0}", typeString);

                return(null);
            }

            using (var stream = reader.GetMemoryStream(1))
            {
                try
                {
                    return(_jsonSerializer.DeserializeFromStream(stream, type) as BaseItem);
                }
                catch (SerializationException ex)
                {
                    _logger.ErrorException("Error deserializing item", ex);
                    return(null);
                }
            }
        }
예제 #12
0
        private async void AddDevice(string url)
        {
            await _semaphore.WaitAsync().ConfigureAwait(false);

            try
            {
                var options = GetConfiguration();

                if (options.TunerHosts.Any(i =>
                                           string.Equals(i.Type, HdHomerunHost.DeviceType, StringComparison.OrdinalIgnoreCase) &&
                                           UriEquals(i.Url, url)))
                {
                    return;
                }

                // Strip off the port
                url = new Uri(url).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped).TrimEnd('/');

                // Test it by pulling down the lineup
                using (var stream = await _httpClient.Get(new HttpRequestOptions
                {
                    Url = string.Format("{0}/discover.json", url),
                    CancellationToken = CancellationToken.None,
                    BufferContent = false
                }))
                {
                    var response = _json.DeserializeFromStream <HdHomerunHost.DiscoverResponse>(stream);

                    var existing = GetConfiguration().TunerHosts
                                   .FirstOrDefault(i => string.Equals(i.Type, HdHomerunHost.DeviceType, StringComparison.OrdinalIgnoreCase) && string.Equals(i.DeviceId, response.DeviceID, StringComparison.OrdinalIgnoreCase));

                    if (existing == null)
                    {
                        await _liveTvManager.SaveTunerHost(new TunerHostInfo
                        {
                            Type        = HdHomerunHost.DeviceType,
                            Url         = url,
                            DataVersion = 1,
                            DeviceId    = response.DeviceID
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        if (!string.Equals(existing.Url, url, StringComparison.OrdinalIgnoreCase))
                        {
                            existing.Url = url;
                            await _liveTvManager.SaveTunerHost(existing).ConfigureAwait(false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error saving device", ex);
            }
            finally
            {
                _semaphore.Release();
            }
        }
예제 #13
0
        public IEnumerable <ChannelInfo> GetChannels(Stream stream, IJsonSerializer json, ILogger logger)
        {
            logger.Info("[VDR] Start GetChannels");
            var root = json.DeserializeFromStream <RootObject>(stream);

            logger.Info("[VDR] got Root Object");
//	    logger.Info(string.Format("[VDR] Display Root Object: {0}", json.SerializeToString(root)));
//      List<ChannelInfo> channels = new List<ChannelInfo>();
            if (root != null && root.Channels != null)
            {
                logger.Info("[VDR] Parse Channel Response");
                UtilsHelper.DebugInformation(logger, string.Format("[VDR] ChannelResponse: {0}", json.SerializeToString(root)));
                return(root.Channels.Select(i => new ChannelInfo
                {
                    Name = i.name,
                    ChannelType = i.is_radio ? ChannelType.Radio : ChannelType.TV,
                    Number = i.number.ToString(_usCulture),
                    Id = i.channel_id,
                    ImageUrl = i.image ? string.Format("{0}/channels/image/{1}", _baseUrl, i.channel_id) : null,
                    HasImage = i.image
                }));
            }
            else
            {
                logger.Info("[VDR] Parse Channel Response failed");
                logger.Info(string.Format("[VDR] ChannelResponse: {0}", json.SerializeToString(root)));
            }
            return(new List <ChannelInfo>());
        }
예제 #14
0
        public IEnumerable<ChannelInfo> GetChannels(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.channelsJSONObject.rtn != null && root.channelsJSONObject.rtn.Error)
            {
                logger.Error(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
                throw new ApplicationException(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
            }

            if (root.channelsJSONObject != null && root.channelsJSONObject.Channels != null)
            {
                UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] ChannelResponse: {0}", json.SerializeToString(root)));
                return root.channelsJSONObject.Channels.Select(i => new ChannelInfo
                {
                    Name = i.channel.channelName,
                    Number = i.channel.channelFormattedNumber.ToString(_usCulture),
                    Id = i.channel.channelOID.ToString(_usCulture),
                    ImageUrl = string.IsNullOrEmpty(i.channel.channelIcon) ? null : (_baseUrl + "/" + i.channel.channelIcon),
                    HasImage = !string.IsNullOrEmpty(i.channel.channelIcon)
                });
            }

            return new List<ChannelInfo>();
        }
예제 #15
0
        public async Task <object> Get(ReviewRequest request)
        {
            var parms = "?id=" + request.Id;

            if (request.MaxRating > 0)
            {
                parms += "&max=" + request.MaxRating;
            }
            if (request.MinRating > 0)
            {
                parms += "&min=" + request.MinRating;
            }
            if (request.MinRating > 0)
            {
                parms += "&limit=" + request.Limit;
            }
            if (request.ForceTitle)
            {
                parms += "&title=true";
            }

            using (var result = await _httpClient.Get(MbAdminUrl + "/service/packageReview/retrieve" + parms, CancellationToken.None)
                                .ConfigureAwait(false))
            {
                var reviews = _serializer.DeserializeFromStream <List <PackageReviewInfo> >(result);

                return(ToOptimizedResult(reviews));
            }
        }
예제 #16
0
        /// <summary>
        /// Retrieve all users from the database
        /// </summary>
        /// <returns>IEnumerable{User}.</returns>
        public IEnumerable <User> RetrieveAllUsers()
        {
            var list = new List <User>();

            using (WriteLock.Read())
            {
                using (var connection = CreateConnection(true))
                {
                    foreach (var row in connection.Query("select guid,data from users"))
                    {
                        var id = row[0].ReadGuidFromBlob();

                        using (var stream = _memoryStreamProvider.CreateNew(row[1].ToBlob()))
                        {
                            stream.Position = 0;
                            var user = _jsonSerializer.DeserializeFromStream <User>(stream);
                            user.Id = id;
                            list.Add(user);
                        }
                    }
                }
            }

            return(list);
        }
예제 #17
0
        /// <summary>
        /// Called when [receive].
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        private void OnReceiveInternal(byte[] bytes)
        {
            LastActivityDate = DateTime.UtcNow;

            if (OnReceive == null)
            {
                return;
            }
            try
            {
                WebSocketMessageInfo info;

                using (var memoryStream = new MemoryStream(bytes))
                {
                    var stub = (WebSocketMessage <object>)_jsonSerializer.DeserializeFromStream(memoryStream, typeof(WebSocketMessage <object>));

                    info = new WebSocketMessageInfo
                    {
                        MessageType = stub.MessageType,
                        Data        = stub.Data == null ? null : stub.Data.ToString()
                    };
                }

                info.Connection = this;

                OnReceive(info);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error processing web socket message", ex);
            }
        }
예제 #18
0
        private async Task EnsureData(CancellationToken cancellationToken)
        {
            if (_items == null)
            {
                _logger.Debug("Getting {0} from {1}", string.Join(MediaSync.PathSeparatorString, GetRemotePath().ToArray()), _provider.Name);

                var fileResult = await _provider.GetFiles(new FileQuery
                {
                    FullPath = GetRemotePath().ToArray()

                }, _target, cancellationToken).ConfigureAwait(false);

                if (fileResult.Items.Length > 0)
                {
                    using (var stream = await _provider.GetFile(fileResult.Items[0].Id, _target, new Progress<double>(), cancellationToken))
                    {
                        _items = _json.DeserializeFromStream<List<LocalItem>>(stream);
                    }
                }
                else
                {
                    _items = new List<LocalItem>();
                }
            }
        }
예제 #19
0
        public static CaptureCardList ParseCaptureCardList(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream <RootCaptureObject>(stream);

            UtilsHelper.DebugInformation(logger, string.Format("[MythTV] ParseCaptureCardList Response: {0}", json.SerializeToString(root)));
            return(root.CaptureCardList);
        }
예제 #20
0
        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>());
            }
        }
예제 #21
0
        public async Task <IEnumerable <ChannelInfo> > GetChannels(CancellationToken cancellationToken)
        {
            ChannelList = new List <ChannelInfo>();
            var options = new HttpRequestOptions
            {
                Url = string.Format("{0}/lineup.json", getWebUrl()),
                CancellationToken = cancellationToken
            };

            using (var stream = await _httpClient.Get(options))
            {
                var root = _jsonSerializer.DeserializeFromStream <List <Channels> >(stream);
                _logger.Info("Found " + root.Count() + "channels on host: " + Url);
                _logger.Info("Only Favorites?" + OnlyFavorites);
                if (Convert.ToBoolean(_onlyFavorites))
                {
                    root.RemoveAll(x => x.Favorite == false);
                }
                //root.RemoveAll(i => i.DRM);
                if (root != null)
                {
                    ChannelList = root.Select(i => new ChannelInfo
                    {
                        Name   = i.GuideName,
                        Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture),
                        Id     = i.GuideNumber.ToString(CultureInfo.InvariantCulture),
                    }).ToList();
                }
                else
                {
                    ChannelList = new List <ChannelInfo>();
                }
                return(ChannelList);
            }
        }
예제 #22
0
        public static async Task <MBRegistrationRecord> GetRegistrationStatus(IHttpClient httpClient, IJsonSerializer jsonSerializer, string feature, string mb2Equivalent = null)
        {
            var mac  = _networkManager.GetMacAddress();
            var data = new Dictionary <string, string> {
                { "feature", feature }, { "key", SupporterKey }, { "mac", mac }, { "mb2equiv", mb2Equivalent }, { "legacykey", LegacyKey }
            };

            var reg = new RegRecord();

            try
            {
                using (var json = await httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false))
                {
                    reg = jsonSerializer.DeserializeFromStream <RegRecord>(json);
                }

                if (reg.registered)
                {
                    LicenseFile.AddRegCheck(feature);
                }
            }
            catch (Exception)
            {
                //if we have trouble obtaining from web - allow it if we've validated in the past 30 days
                reg.registered = LicenseFile.LastChecked(feature) > DateTime.UtcNow.AddDays(-30);
            }

            return(new MBRegistrationRecord {
                IsRegistered = reg.registered, ExpirationDate = reg.expDate, RegChecked = true
            });
        }
예제 #23
0
        public IEnumerable <ChannelInfo> GetChannels(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream <RootObject>(stream);

            if (root.channelsJSONObject.rtn != null && root.channelsJSONObject.rtn.Error)
            {
                logger.Error(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
                throw new ApplicationException(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
            }

            if (root.channelsJSONObject != null && root.channelsJSONObject.Channels != null)
            {
                UtilsHelper.DebugInformation(logger, string.Format("[NextPvr] ChannelResponse: {0}", json.SerializeToString(root)));
                return(root.channelsJSONObject.Channels.Select(i => new ChannelInfo
                {
                    Name = i.channel.channelName,
                    Number = i.channel.channelFormattedNumber.ToString(_usCulture),
                    Id = i.channel.channelOID.ToString(_usCulture),
                    ImageUrl = string.IsNullOrEmpty(i.channel.channelIcon) ? null : (_baseUrl + "/" + i.channel.channelIcon),
                    HasImage = !string.IsNullOrEmpty(i.channel.channelIcon)
                }));
            }

            return(new List <ChannelInfo>());
        }
예제 #24
0
        private RecRule GetOneRecRule(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream <RecRuleRoot>(stream);

            logger.Debug(string.Format("[MythTV] GetOneRecRule Response: {0}",
                                       json.SerializeToString(root)));
            return(root.RecRule);
        }
예제 #25
0
        protected async Task <T> ExecuteRequest <T>(string url, CancellationToken cancellationToken)
        {
            var httpRequest = await PrepareHttpRequestOptions(url, cancellationToken);

            var result = await _httpClient.Get(httpRequest);

            return(_jsonSerializer.DeserializeFromStream <T>(result));
        }
예제 #26
0
        public IEnumerable <SeriesTimerInfo> GetSeriesTimers(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream <RecRuleListRoot>(stream);

            return(root.RecRuleList.RecRules
                   .Where(rule => rule.Type.Equals("Record All"))
                   .Select(i => RecRuleToSeriesTimerInfo(i)));
        }
예제 #27
0
        /// <summary>
        /// Gets all available packages.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="packageType">Type of the package.</param>
        /// <param name="applicationVersion">The application version.</param>
        /// <returns>Task{List{PackageInfo}}.</returns>
        public async Task <IEnumerable <PackageInfo> > GetAvailablePackages(CancellationToken cancellationToken,
                                                                            PackageType?packageType    = null,
                                                                            Version applicationVersion = null)
        {
            var data = new Dictionary <string, string> {
                { "key", _securityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() }
            };

            using (var json = await _httpClient.Post(Constants.Constants.MbAdminUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
            {
                cancellationToken.ThrowIfCancellationRequested();

                var packages = _jsonSerializer.DeserializeFromStream <List <PackageInfo> >(json).ToList();

                return(FilterPackages(packages, packageType, applicationVersion));
            }
        }
예제 #28
0
 private DisplayPreferences Get(IReadOnlyList <IResultSetValue> row)
 {
     using (var stream = new MemoryStream(row[0].ToBlob()))
     {
         stream.Position = 0;
         return(_jsonSerializer.DeserializeFromStream <DisplayPreferences>(stream));
     }
 }
예제 #29
0
        public List <string> GetRecGroupList(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream <RootRecGroupList>(stream);
            var ans  = root.StringList;

            ans.Add("Deleted");
            return(ans);
        }
        private async Task <UpdateInfoData> Do(GetUpdateInfo request)
        {
            var r = new UpdateInfoData()
            {
                LoadedVersion      = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                PendingLoadVersion = GetPendingLoadVersion(),
            };

            try
            {
                var resp = await client.GetAsync("https://api.github.com/repos/JavScraper/Emby.Plugins.JavScraper/releases/latest");

                if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var data = jsonSerializer.DeserializeFromStream <Rootobject>(await resp.Content.ReadAsStreamAsync());
                    r.UpdateMessage = data.body;

                    foreach (var v in data.assets.Where(o => o.name.IndexOf("JavScraper", StringComparison.OrdinalIgnoreCase) >= 0 && o.name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)))
                    {
                        var m = regexVersion.Match(v.name);
                        if (m.Success)
                        {
                            r.LatestVersion = m.ToString();
                            r.LatestUrl     = v.browser_download_url;
                            break;
                        }
                    }
                }
                else
                {
                    r.ErrorMessage = "获取新版下失败。";
                    return(r);
                }
            }
            catch (Exception ex)
            {
                r.ErrorMessage = ex.Message;
                return(r);
            }

            //r.PendingLoadVersion = "1.0.0";
            if (request.update == true && r.HasNewVersion)
            {
                try
                {
                    var ms = await client.GetStreamAsync(r.LatestUrl);

                    zipClient.ExtractAllFromZip(ms, appPaths.PluginsPath, true);
                    r.PendingLoadVersion = GetPendingLoadVersion();
                }
                catch (Exception ex)
                {
                    r.ErrorMessage = $"更新失败:{ex.Message}";
                }
            }

            return(r);
        }
예제 #31
0
        protected async Task <TResponse> Post <TRequest, TResponse>(TRequest request) where TRequest : BaseAuthedRequest where TResponse : BaseResponse
        {
            var data = request.ToDictionary();

            //Append the signature
            Helpers.AppendSignature(ref data);

            var options = new HttpRequestOptions
            {
                Url                   = BuildPostUrl(request.Secure),
                ResourcePool          = Plugin.LastfmResourcePool,
                RequestContentType    = "application/json",
                CancellationToken     = CancellationToken.None,
                TimeoutMs             = 120000,
                LogErrorResponseBody  = false,
                LogRequest            = true,
                BufferContent         = false,
                EnableHttpCompression = false,
                EnableKeepAlive       = false
            };

            options.SetPostData(data);

            using (var httpResponseInfo = await _httpClient.Post(options))
            {
                try
                {
                    var result = _jsonSerializer.DeserializeFromStream <TResponse>(httpResponseInfo.Content);

                    //Lets Log the error here to ensure all errors are logged
                    if (result.IsError())
                    {
                        Plugin.Logger.Error(result.message);
                    }

                    return(result);
                }
                catch (Exception e)
                {
                    Plugin.Logger.Debug(e.Message);
                }

                return(null);
            }
        }
예제 #32
0
        private async Task <ChannelItemResult> GetShowList(InternalChannelItemQuery query, CancellationToken cancellationToken)
        {
            var items = new List <ChannelItemInfo>();

            using (var site = await _httpClient.Get(new HttpRequestOptions()
            {
                Url = String.Format("http://www.cbs.com/carousels/showsByCategory/{0}/offset/0/limit/99/", query.FolderId),
                CancellationToken = CancellationToken.None
            }).ConfigureAwait(false))
            {
                var showList = _jsonSerializer.DeserializeFromStream <ShowList>(site);

                foreach (var c in showList.result.data)
                {
                    if ((c.filepath_ipad == "") || (c.filepath_show_logo == ""))
                    {
                        continue;
                    }
                    if ((c.title == "Live On Letterman") || (c.title == "The CBS Dream Team...It's Epic"))
                    {
                        continue;
                    }

                    var url = c.link;
                    if (!url.Contains("/video"))
                    {
                        url = url + "video";
                    }
                    var thumb = c.filepath_ipad;

                    items.Add(new ChannelItemInfo
                    {
                        Name     = c.title,
                        ImageUrl = thumb,
                        Id       = "category!_" + url,
                        Type     = ChannelItemType.Folder
                    });
                }
            }

            return(new ChannelItemResult
            {
                Items = items.ToList()
            });
        }
예제 #33
0
        public void Post(UpdateNamedConfiguration request)
        {
            var key = GetPathValue(2);

            var configurationType = _configurationManager.GetConfigurationType(key);
            var configuration     = _jsonSerializer.DeserializeFromStream(request.RequestStream, configurationType);

            _configurationManager.SaveConfiguration(key, configuration);
        }
        public IEnumerable<ProgramInfo> GetPrograms(Stream stream, IJsonSerializer json, string channelId, ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);
            logger.Debug("[NextPvr] GetPrograms Response: {0}",json.SerializeToString(root));

            var listings = root.Guide.Listings;

            return listings.Where(i => string.Equals(i.Channel.channelOID.ToString(_usCulture), channelId, StringComparison.OrdinalIgnoreCase))
                .SelectMany(i => i.EPGEvents.Select(e => GetProgram(i.Channel, e.epgEventJSONObject.epgEvent)));
        }
        public bool? RecordingError(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.epgEventJSONObject != null && root.epgEventJSONObject.rtn != null)
            {
                UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] RecordingError Response: {0}", json.SerializeToString(root)));
                return root.epgEventJSONObject.rtn.Error;
            }
            return null;
        }
        public bool LoggedIn(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.SIDValidation != null)
            {
                logger.Debug("[NextPvr] connection validation: {0}", json.SerializeToString(root));
                return root.SIDValidation.validated;
            }
            logger.Error("[NextPvr] Failed to validate your connection with NextPvr.");
            throw new ApplicationException("Failed to validate your connection with NextPvr.");
        }
예제 #37
0
        public VLCObj GetVLCResponse(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.JSONVlcObject.VLC_Obj != null && root.JSONVlcObject.VLC_Obj.isVlcAvailable == true)
            {
                UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] VLC Response: {0}", json.SerializeToString(root)));
                return root.JSONVlcObject.VLC_Obj;
            }
            logger.Error("[NextPvr] Failed to load the VLC from NEWA");
            throw new ApplicationException("Failed to load the VLC from NEWA.");
        }
        public ClientKeys GetClientKeys(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.clientKeys != null && root.clientKeys.sid != null && root.clientKeys.salt != null)
            {
                logger.Debug("[NextPvr] ClientKeys: {0}", json.SerializeToString(root));
                return root.clientKeys;
            }
            logger.Error("[NextPvr] Failed to load the ClientKeys from NextPvr.");
            throw new ApplicationException("Failed to load the ClientKeys from NextPvr.");
        }
        public IEnumerable<SeriesTimerInfo> GetSeriesTimers(Stream stream, IJsonSerializer json,ILogger logger)
        {
            if (stream == null)
            {
                logger.Error("[NextPvr] GetSeriesTimers stream == null");
                throw new ArgumentNullException("stream");
            }

            var root = json.DeserializeFromStream<RootObject>(stream);
            UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] GetSeriesTimers Response: {0}", json.SerializeToString(root)));

            return root.ManageResults
                .EPGEvents
                .Select(i => i.epgEventJSONObject)

                // Seeing epgEventJSONObject coming back null for some responses
                .Where(i => i != null)

                // Seeing recurring parents coming back with these reponses, for some reason
                .Where(i => i.recurr != null)
                .Select(GetSeriesTimerInfo);
        }
예제 #40
0
        public TunerResponse(Stream stream, IJsonSerializer json)
        {
            _root = json.DeserializeFromStream<RootObject>(stream);

        }
예제 #41
0
        public VersionCheckResponse(Stream stream, IJsonSerializer json)
        {
           _root = json.DeserializeFromStream<RootObject>(stream);

        }
 public ScheduleSettings GetScheduleSettings(Stream stream, IJsonSerializer json)
 {
     return json.DeserializeFromStream<ScheduleSettings>(stream);
 }
예제 #43
0
 public static CaptureCardList ParseCaptureCardList(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = json.DeserializeFromStream<RootCaptureObject>(stream);
     UtilsHelper.DebugInformation(logger, string.Format("[MythTV] ParseCaptureCardList Response: {0}", json.SerializeToString(root)));
     return root.CaptureCardList;
 }
예제 #44
0
        /// <summary>
        /// Gets all user data.
        /// </summary>
        /// <param name="oldDatabase">The old database.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <returns>IEnumerable{UserItemData}.</returns>
        private static IEnumerable<UserItemData> GetAllUserData(IDbConnection oldDatabase, IJsonSerializer jsonSerializer)
        {
            using (var cmd = oldDatabase.CreateCommand())
            {
                cmd.CommandText = "select userId,key,data from userdata";

                using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
                {
                    while (reader.Read())
                    {
                        var userId = reader.GetGuid(0);
                        var key = reader.GetString(1);

                        using (var stream = reader.GetMemoryStream(2))
                        {
                            var userData = jsonSerializer.DeserializeFromStream<UserItemData>(stream);

                            userData.UserId = userId;
                            userData.Key = key;

                            yield return userData;
                        }
                    }
                }
            }
        }
예제 #45
0
 private static RecRuleListRoot ParseRecRules(Stream stream, IJsonSerializer json)
 {
     return json.DeserializeFromStream<RecRuleListRoot>(stream);
 }
예제 #46
0
 internal static Program ParseRecorded(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = json.DeserializeFromStream<RootProgramObject>(stream);
     return root.Program;
 }
예제 #47
0
 public Rtn GetVLCReturn(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = json.DeserializeFromStream<RootObject>(stream);
     UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] VLC Return: {0}", json.SerializeToString(root)));
     return root.JSONVlcObject.rtn;
 }
예제 #48
0
 public static RecordId ParseRecordId(Stream stream, IJsonSerializer json)
 {
     return json.DeserializeFromStream<RecordId>(stream);
 }
예제 #49
0
 public static ProgramList ParseProgramList(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = json.DeserializeFromStream<RootProgramListObject>(stream);
     return root.ProgramList;
 }