Beispiel #1
0
        private IEnumerable <IndexerRequest> GetMovieRequest(MovieSearchCriteria searchCriteria)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Accept(HttpAccept.Json);

            requestBuilder.AddQueryParam("passkey", Settings.Passkey);

            if (!string.IsNullOrWhiteSpace(Settings.User))
            {
                requestBuilder.AddQueryParam("user", Settings.User);
            }
            else
            {
                requestBuilder.AddQueryParam("user", "");
            }

            if (searchCriteria.Movie.ImdbId.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("imdbid", searchCriteria.Movie.ImdbId);
            }
            else
            {
                requestBuilder.AddQueryParam("search", $"{searchCriteria.Movie.Title} {searchCriteria.Movie.Year}");
            }

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
Beispiel #2
0
        private IEnumerable <IndexerRequest> GetPagedRequests(string mode, int?tvdbId, string query, params object[] args)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Resource("/pubapi_v2.php")
                                 .Accept(HttpAccept.Json);

            requestBuilder.AddQueryParam("mode", mode);

            if (tvdbId.HasValue)
            {
                requestBuilder.AddQueryParam("search_tvdb", tvdbId.Value);
            }

            if (query.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("search_string", string.Format(query, args));
            }

            if (!Settings.RankedOnly)
            {
                requestBuilder.AddQueryParam("ranked", "0");
            }

            requestBuilder.AddQueryParam("category", "18;41");
            requestBuilder.AddQueryParam("limit", "100");
            requestBuilder.AddQueryParam("token", _tokenProvider.GetToken(Settings));
            requestBuilder.AddQueryParam("format", "json_extended");
            requestBuilder.AddQueryParam("app_id", "Sonarr");

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
Beispiel #3
0
        private List <PreDBResult> GetResults(string category = "", string search = "")
        {
            return(new List <PreDBResult>());

            var builder = new HttpRequestBuilder("http://predb.me").AddQueryParam("rss", "1");

            if (category.IsNotNullOrWhiteSpace())
            {
                builder.AddQueryParam("cats", category);
            }

            if (search.IsNotNullOrWhiteSpace())
            {
                builder.AddQueryParam("search", search);
            }

            var request = builder.Build();

            request.AllowAutoRedirect = true;
            request.SuppressHttpError = true;

            var response = _httpClient.Get(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                _logger.Warn("Non 200 StatusCode {0} encountered while searching PreDB.", response.StatusCode);
                return(new List <PreDBResult>());
            }

            try
            {
                var reader = XmlReader.Create(new StringReader(response.Content));

                var items = SyndicationFeed.Load(reader);

                var results = new List <PreDBResult>();

                foreach (SyndicationItem item in items.Items)
                {
                    var result = new PreDBResult();
                    result.Title = item.Title.Text;
                    result.Link  = item.Links[0].Uri.ToString();
                    results.Add(result);
                }

                return(results);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error while searching PreDB.");
            }

            return(new List <PreDBResult>());
        }
Beispiel #4
0
        private IEnumerable <IndexerRequest> GetMovieRequest(MovieSearchCriteria searchCriteria)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Resource("/pubapi_v2.php")
                                 .Accept(HttpAccept.Json);

            if (Settings.CaptchaToken.IsNotNullOrWhiteSpace())
            {
                requestBuilder.UseSimplifiedUserAgent = true;
                requestBuilder.SetCookie("cf_clearance", Settings.CaptchaToken);
            }

            requestBuilder.AddQueryParam("mode", "search");

            requestBuilder.AddQueryParam("search_imdb", searchCriteria.Movie.ImdbId);

            if (!Settings.RankedOnly)
            {
                requestBuilder.AddQueryParam("ranked", "0");
            }

            requestBuilder.AddQueryParam("category", "movies");
            requestBuilder.AddQueryParam("limit", "100");
            requestBuilder.AddQueryParam("token", _tokenProvider.GetToken(Settings));
            requestBuilder.AddQueryParam("format", "json_extended");
            requestBuilder.AddQueryParam("app_id", "Bonarr");

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
        private HttpRequestBuilder BuildRequest(DownloadStationSettings settings, DiskStationApiInfo apiInfo, string methodName, int apiVersion, HttpMethod httpVerb = null)
        {
            httpVerb ??= HttpMethod.Get;

            var requestBuilder = new HttpRequestBuilder(settings.UseSsl, settings.Host, settings.Port).Resource($"webapi/{apiInfo.Path}");

            requestBuilder.Method              = httpVerb;
            requestBuilder.LogResponseContent  = true;
            requestBuilder.SuppressHttpError   = true;
            requestBuilder.AllowAutoRedirect   = false;
            requestBuilder.Headers.ContentType = "application/json";

            if (apiVersion < apiInfo.MinVersion || apiVersion > apiInfo.MaxVersion)
            {
                throw new ArgumentOutOfRangeException(nameof(apiVersion));
            }

            if (httpVerb == HttpMethod.Post)
            {
                if (apiInfo.NeedsAuthentication)
                {
                    if (_apiType == DiskStationApi.DownloadStation2Task)
                    {
                        requestBuilder.AddQueryParam("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
                    }
                    else
                    {
                        requestBuilder.AddFormParameter("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
                    }
                }

                requestBuilder.AddFormParameter("api", apiInfo.Name);
                requestBuilder.AddFormParameter("version", apiVersion);
                requestBuilder.AddFormParameter("method", methodName);
            }
            else
            {
                if (apiInfo.NeedsAuthentication)
                {
                    requestBuilder.AddQueryParam("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
                }

                requestBuilder.AddQueryParam("api", apiInfo.Name);
                requestBuilder.AddQueryParam("version", apiVersion);
                requestBuilder.AddQueryParam("method", methodName);
            }

            return(requestBuilder);
        }
        private HttpRequest BuildRequest(LazyLibrarianSettings settings, string resource, string command, HttpMethod method, Dictionary <string, string> parameters = null)
        {
            var baseUrl = settings.BaseUrl.TrimEnd('/');

            var requestBuilder = new HttpRequestBuilder(baseUrl).Resource(resource)
                                 .AddQueryParam("cmd", command)
                                 .AddQueryParam("apikey", settings.ApiKey);

            if (parameters != null)
            {
                foreach (var param in parameters)
                {
                    requestBuilder.AddQueryParam(param.Key, param.Value);
                }
            }

            var request = requestBuilder.Build();

            request.Headers.ContentType = "application/json";

            request.Method            = method;
            request.AllowAutoRedirect = true;

            return(request);
        }
Beispiel #7
0
        public HttpRequest GetWatchlist(string authToken)
        {
            var clientIdentifier = _configService.PlexClientIdentifier;

            var requestBuilder = new HttpRequestBuilder("https://metadata.provider.plex.tv/library/sections/watchlist/all")
                                 .Accept(HttpAccept.Json)
                                 .AddQueryParam("clientID", clientIdentifier)
                                 .AddQueryParam("context[device][product]", BuildInfo.AppName)
                                 .AddQueryParam("context[device][platform]", "Windows")
                                 .AddQueryParam("context[device][platformVersion]", "7")
                                 .AddQueryParam("context[device][version]", BuildInfo.Version.ToString())
                                 .AddQueryParam("includeFields", "title,type,year,ratingKey")
                                 .AddQueryParam("includeElements", "Guid")
                                 .AddQueryParam("sort", "watchlistedAt:desc")
                                 .AddQueryParam("type", (int)PlexMediaType.Show);

            if (!string.IsNullOrWhiteSpace(authToken))
            {
                requestBuilder.AddQueryParam("X-Plex-Token", authToken);
            }

            var request = requestBuilder.Build();

            return(request);
        }
Beispiel #8
0
        private HttpResponse <T> GetPaged <T>(HttpRequestBuilder builder, int count, int offset)
            where T : new()
        {
            builder.AddQueryParam("num", count, replace: true);
            builder.AddQueryParam("offset", offset, replace: true);

            var request = builder.Build();

            try
            {
                return(_httpClient.Get <T>(request));
            }
            catch (HttpException ex)
            {
                throw new CalibreException("Unable to connect to Calibre library: {0}", ex, ex.Message);
            }
        }
Beispiel #9
0
        private IEnumerable <IndexerRequest> GetPagedRequests(string mode, int?tvdbId, string query, params object[] args)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Accept(HttpAccept.Json);

            requestBuilder.AddQueryParam("passkey", Settings.Passkey);
            if (!string.IsNullOrWhiteSpace(Settings.User))
            {
                requestBuilder.AddQueryParam("user", Settings.User);
            }
            else
            {
                requestBuilder.AddQueryParam("user", "");
            }

            requestBuilder.AddQueryParam("search", "-");

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
Beispiel #10
0
        private IEnumerable <IndexerRequest> GetMovieRequest(MovieSearchCriteria searchCriteria)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Resource("/pubapi_v2.php")
                                 .Accept(HttpAccept.Json);

            if (Settings.CaptchaToken.IsNotNullOrWhiteSpace())
            {
                requestBuilder.UseSimplifiedUserAgent = true;
                requestBuilder.SetCookie("cf_clearance", Settings.CaptchaToken);
            }

            requestBuilder.AddQueryParam("mode", "search");

            if (searchCriteria.Movie.ImdbId.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("search_imdb", searchCriteria.Movie.ImdbId);
            }
            else if (searchCriteria.Movie.TmdbId > 0)
            {
                requestBuilder.AddQueryParam("search_themoviedb", searchCriteria.Movie.TmdbId);
            }
            else
            {
                requestBuilder.AddQueryParam("search_string", $"{searchCriteria.Movie.Title} {searchCriteria.Movie.Year}");
            }

            if (!Settings.RankedOnly)
            {
                requestBuilder.AddQueryParam("ranked", "0");
            }

            var categoryParam = string.Join(";", Settings.Categories.Distinct());

            requestBuilder.AddQueryParam("category", categoryParam);
            requestBuilder.AddQueryParam("limit", "100");
            requestBuilder.AddQueryParam("token", _tokenProvider.GetToken(Settings));
            requestBuilder.AddQueryParam("format", "json_extended");
            requestBuilder.AddQueryParam("app_id", BuildInfo.AppName);

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
        private HttpRequest BuildRequest(DownloadStationSettings settings, DiskStationApi api, Dictionary <string, object> arguments, HttpMethod method)
        {
            if (!Resources.ContainsKey(api))
            {
                GetApiVersion(settings, api);
            }

            var requestBuilder = new HttpRequestBuilder(settings.UseSsl, settings.Host, settings.Port).Resource($"webapi/{Resources[api]}");

            requestBuilder.Method             = method;
            requestBuilder.LogResponseContent = true;
            requestBuilder.SuppressHttpError  = true;
            requestBuilder.AllowAutoRedirect  = false;

            if (requestBuilder.Method == HttpMethod.POST)
            {
                if (api == DiskStationApi.DownloadStationTask && arguments.ContainsKey("file"))
                {
                    requestBuilder.Headers.ContentType = "multipart/form-data";

                    foreach (var arg in arguments)
                    {
                        if (arg.Key == "file")
                        {
                            Dictionary <string, object> file = (Dictionary <string, object>)arg.Value;
                            requestBuilder.AddFormUpload(arg.Key, file["name"].ToString(), (byte[])file["data"]);
                        }
                        else
                        {
                            requestBuilder.AddFormParameter(arg.Key, arg.Value);
                        }
                    }
                }
                else
                {
                    requestBuilder.Headers.ContentType = "application/json";
                }
            }
            else
            {
                foreach (var arg in arguments)
                {
                    requestBuilder.AddQueryParam(arg.Key, arg.Value);
                }
            }

            return(requestBuilder.Build());
        }
Beispiel #12
0
        private IEnumerable <IndexerRequest> GetPagedRequests(string mode, int?imdbId, string query, params object[] args)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Resource("/pubapi_v2.php")
                                 .Accept(HttpAccept.Json);

            if (Settings.CaptchaToken.IsNotNullOrWhiteSpace())
            {
                requestBuilder.UseSimplifiedUserAgent = true;
                requestBuilder.SetCookie("cf_clearance", Settings.CaptchaToken);
            }

            requestBuilder.AddQueryParam("mode", mode);

            if (imdbId.HasValue)
            {
                requestBuilder.AddQueryParam("search_imdb", imdbId.Value);
            }

            if (query.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("search_string", string.Format(query, args));
            }

            if (!Settings.RankedOnly)
            {
                requestBuilder.AddQueryParam("ranked", "0");
            }

            var categoryParam = string.Join(";", Settings.Categories.Distinct());

            requestBuilder.AddQueryParam("category", categoryParam);
            requestBuilder.AddQueryParam("limit", "100");
            requestBuilder.AddQueryParam("token", _tokenProvider.GetToken(Settings));
            requestBuilder.AddQueryParam("format", "json_extended");
            requestBuilder.AddQueryParam("app_id", "Radarr");

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
        private HttpRequestBuilder GetSubsonicServerRequest(string resource, HttpMethod method, SubsonicSettings settings)
        {
            var client = new HttpRequestBuilder(GetBaseUrl(settings, "rest"));

            client.Resource(resource);

            if (settings.Username.IsNotNullOrWhiteSpace())
            {
                client.AddQueryParam("u", settings.Username)
                .AddQueryParam("p", settings.Password)
                .AddQueryParam("c", "Lidarr")
                .AddQueryParam("v", "1.15.0");
            }

            client.Method = method;

            return(client);
        }
Beispiel #14
0
        private void AuthenticateClient(HttpRequestBuilder requestBuilder, NzbVortexSettings settings, bool reauthenticate = false)
        {
            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.ApiKey);

            var sessionId = _authSessionIdCache.Find(authKey);

            if (sessionId == null || reauthenticate)
            {
                _authSessionIdCache.Remove(authKey);

                var nonceRequest  = BuildRequest(settings).Resource("auth/nonce").Build();
                var nonceResponse = _httpClient.Execute(nonceRequest);

                var nonce = Json.Deserialize <NzbVortexAuthNonceResponse>(nonceResponse.Content).AuthNonce;

                var cnonce = Guid.NewGuid().ToString();

                var hashString = string.Format("{0}:{1}:{2}", nonce, cnonce, settings.ApiKey);
                var hash       = Convert.ToBase64String(hashString.SHA256Hash().HexToByteArray());

                var authRequest = BuildRequest(settings).Resource("auth/login")
                                  .AddQueryParam("nonce", nonce)
                                  .AddQueryParam("cnonce", cnonce)
                                  .AddQueryParam("hash", hash)
                                  .Build();
                var authResponse = _httpClient.Execute(authRequest);
                var authResult   = Json.Deserialize <NzbVortexAuthResponse>(authResponse.Content);

                if (authResult.LoginResult == NzbVortexLoginResultType.Failed)
                {
                    throw new NzbVortexAuthenticationException("Authentication failed, check your API Key");
                }

                sessionId = authResult.SessionId;

                _authSessionIdCache.Set(authKey, sessionId);
            }

            requestBuilder.AddQueryParam("sessionid", sessionId);
        }
Beispiel #15
0
        private HttpRequestBuilder BuildRequest(string resource, HttpMethod method, PlexServerSettings settings)
        {
            var scheme         = settings.UseSsl ? "https" : "http";
            var requestBuilder = new HttpRequestBuilder($"{scheme}://{settings.Host}:{settings.Port}")
                                 .Accept(HttpAccept.Json)
                                 .AddQueryParam("X-Plex-Client-Identifier", _configService.PlexClientIdentifier)
                                 .AddQueryParam("X-Plex-Product", BuildInfo.AppName)
                                 .AddQueryParam("X-Plex-Platform", "Windows")
                                 .AddQueryParam("X-Plex-Platform-Version", "7")
                                 .AddQueryParam("X-Plex-Device-Name", BuildInfo.AppName)
                                 .AddQueryParam("X-Plex-Version", BuildInfo.Version.ToString());

            if (settings.AuthToken.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("X-Plex-Token", settings.AuthToken);
            }

            requestBuilder.ResourceUrl = resource;
            requestBuilder.Method      = method;

            return(requestBuilder);
        }
Beispiel #16
0
        private IEnumerable <IndexerRequest> GetRequest(string term, int[] categories, string imdbId = null, int?tmdbId = null, int?tvdbId = null)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Resource("/pubapi_v2.php")
                                 .Accept(HttpAccept.Json);

            if (Settings.CaptchaToken.IsNotNullOrWhiteSpace())
            {
                requestBuilder.UseSimplifiedUserAgent = true;
                requestBuilder.SetCookie("cf_clearance", Settings.CaptchaToken);
            }

            requestBuilder.AddQueryParam("mode", "search");

            if (imdbId.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("search_imdb", imdbId);
            }
            else if (tmdbId.HasValue && tmdbId > 0)
            {
                requestBuilder.AddQueryParam("search_themoviedb", tmdbId);
            }
            else if (tvdbId.HasValue && tmdbId > 0)
            {
                requestBuilder.AddQueryParam("search_tvdb", tvdbId);
            }

            if (term.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("search_string", $"{term}");
            }

            if (!Settings.RankedOnly)
            {
                requestBuilder.AddQueryParam("ranked", "0");
            }

            var cats = Categories.MapTorznabCapsToTrackers(categories);

            if (cats != null && cats.Count > 0)
            {
                var categoryParam = string.Join(";", cats.Distinct());
                requestBuilder.AddQueryParam("category", categoryParam);
            }

            requestBuilder.AddQueryParam("limit", "100");
            requestBuilder.AddQueryParam("token", _tokenProvider.GetToken(Settings, Settings.BaseUrl));
            requestBuilder.AddQueryParam("format", "json_extended");
            requestBuilder.AddQueryParam("app_id", BuildInfo.AppName);

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
Beispiel #17
0
        private void SendNotification(string title, string message, HttpMethod method, JoinSettings settings)
        {
            var requestBuilder = new HttpRequestBuilder(URL);

            if (settings.DeviceNames.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("deviceNames", settings.DeviceNames);
            }
            else if (settings.DeviceIds.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("deviceIds", settings.DeviceIds);
            }
            else
            {
                requestBuilder.AddQueryParam("deviceId", "group.all");
            }

            var request = requestBuilder.AddQueryParam("apikey", settings.ApiKey)
                          .AddQueryParam("title", title)
                          .AddQueryParam("text", message)
                          .AddQueryParam("icon", "https://cdn.rawgit.com/Sonarr/Sonarr/main/Logo/256.png")                   // Use the Sonarr logo.
                          .AddQueryParam("smallicon", "https://cdn.rawgit.com/Sonarr/Sonarr/main/Logo/96-Outline-White.png") // 96x96px with outline at 88x88px on a transparent background.
                          .AddQueryParam("priority", settings.Priority)
                          .Build();

            request.Method = method;

            var response = _httpClient.Execute(request);
            var res      = Json.Deserialize <JoinResponseModel>(response.Content);

            if (res.success)
            {
                return;
            }

            if (res.userAuthError)
            {
                throw new JoinAuthException("Authentication failed.");
            }

            if (res.errorMessage != null)
            {
                // Unfortunately hard coding this string here is the only way to determine that there aren't any devices to send to.
                // There isn't an enum or flag contained in the response that can be used instead.
                if (res.errorMessage.Equals("No devices to send to"))
                {
                    throw new JoinInvalidDeviceException(res.errorMessage);
                }
                // Oddly enough, rather than give us an "Invalid API key", the Join API seems to assume the key is valid,
                // but fails when doing a device lookup associated with that key.
                // In our case we are using "deviceIds" rather than "deviceId" so when the singular form error shows up
                // we know the API key was the fault.
                else if (res.errorMessage.Equals("No device to send message to"))
                {
                    throw new JoinAuthException("Authentication failed.");
                }
                throw new JoinException(res.errorMessage);
            }

            throw new JoinException("Unknown error. Join message failed to send.");
        }