Search in sources :

Example 1 with NewznabResponse

use of org.nzbhydra.mapping.newznab.NewznabResponse in project nzbhydra2 by theotherp.

the class ExternalApi method transformResults.

protected NewznabResponse transformResults(SearchResult searchResult, NewznabParameters params, SearchRequest searchRequest) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    NewznabResponse response;
    int total = searchResult.getNumberOfTotalAvailableResults() - searchResult.getNumberOfRejectedResults() - searchResult.getNumberOfRemovedDuplicates();
    if (params.getO() == OutputType.JSON) {
        response = newznabJsonTransformer.transformToRoot(searchResult.getSearchResultItems(), params.getOffset(), total, searchRequest);
    } else {
        response = newznabXmlTransformer.getRssRoot(searchResult.getSearchResultItems(), params.getOffset(), total, searchRequest);
    }
    logger.debug(LoggingMarkers.PERFORMANCE, "Transforming results took {}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    return response;
}
Also used : Stopwatch(com.google.common.base.Stopwatch) NewznabResponse(org.nzbhydra.mapping.newznab.NewznabResponse)

Example 2 with NewznabResponse

use of org.nzbhydra.mapping.newznab.NewznabResponse in project nzbhydra2 by theotherp.

the class ExternalApi method handleCachingSearch.

protected ResponseEntity<?> handleCachingSearch(NewznabParameters params) {
    // Remove old entries
    cache.entrySet().removeIf(x -> x.getValue().getLastUpdate().isBefore(clock.instant().minus(MAX_CACHE_AGE_HOURS, ChronoUnit.HOURS)));
    CacheEntryValue cacheEntryValue;
    if (cache.containsKey(params.cacheKey())) {
        cacheEntryValue = cache.get(params.cacheKey());
        if (cacheEntryValue.getLastUpdate().isAfter(clock.instant().minus(params.getCachetime(), ChronoUnit.MINUTES))) {
            Instant nextUpdate = cacheEntryValue.getLastUpdate().plus(params.getCachetime(), ChronoUnit.MINUTES);
            logger.info("Returning cached search result. Next update of search will be done at {}", nextUpdate);
            return new ResponseEntity<>(cacheEntryValue.getSearchResult(), HttpStatus.OK);
        } else {
            logger.info("Updating search because cache time is exceeded");
        }
    }
    // Remove oldest entry when max size is reached
    if (cache.size() == MAX_CACHE_SIZE) {
        Optional<Entry<Integer, CacheEntryValue>> keyToEvict = cache.entrySet().stream().min(Comparator.comparing(o -> o.getValue().getLastUpdate()));
        // Should always be the case anyway
        logger.info("Removing oldest entry from cache because its limit of {} is reached", MAX_CACHE_SIZE);
        keyToEvict.ifPresent(newznabParametersCacheEntryValueEntry -> cache.remove(newznabParametersCacheEntryValueEntry.getKey()));
    }
    NewznabResponse searchResult = search(params);
    logger.info("Putting search result into cache");
    cache.put(params.cacheKey(), new CacheEntryValue(params, clock.instant(), searchResult));
    return new ResponseEntity<>(searchResult, HttpStatus.OK);
}
Also used : java.util(java.util) Stopwatch(com.google.common.base.Stopwatch) LoggerFactory(org.slf4j.LoggerFactory) InvalidSearchResultIdException(org.nzbhydra.downloading.InvalidSearchResultIdException) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) SearchRequestFactory(org.nzbhydra.searching.searchrequests.SearchRequestFactory) ClientAbortException(org.apache.catalina.connector.ClientAbortException) ConcurrentMap(java.util.concurrent.ConcurrentMap) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) org.nzbhydra.mapping.newznab.caps(org.nzbhydra.mapping.newznab.caps) SearchSource(org.nzbhydra.searching.searchrequests.SearchRequest.SearchSource) ConfigProvider(org.nzbhydra.config.ConfigProvider) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) Searcher(org.nzbhydra.searching.Searcher) NewznabParameters(org.nzbhydra.mapping.newznab.NewznabParameters) SearchRequest(org.nzbhydra.searching.searchrequests.SearchRequest) CategoriesConfig(org.nzbhydra.config.CategoriesConfig) Logger(org.slf4j.Logger) NewznabXmlError(org.nzbhydra.mapping.newznab.xml.NewznabXmlError) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Throwables(com.google.common.base.Throwables) IdType(org.nzbhydra.mediainfo.InfoProvider.IdType) OutputType(org.nzbhydra.mapping.newznab.OutputType) DownloadResult(org.nzbhydra.downloading.DownloadResult) SearchResult(org.nzbhydra.searching.SearchResult) SessionStorage(org.nzbhydra.web.SessionStorage) Instant(java.time.Instant) RestController(org.springframework.web.bind.annotation.RestController) ActionAttribute(org.nzbhydra.mapping.newznab.ActionAttribute) CategoryProvider(org.nzbhydra.searching.CategoryProvider) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) FileHandler(org.nzbhydra.downloading.FileHandler) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) SearchType(org.nzbhydra.searching.SearchType) Data(lombok.Data) Entry(java.util.Map.Entry) Clock(java.time.Clock) ResponseEntity(org.springframework.http.ResponseEntity) AllArgsConstructor(lombok.AllArgsConstructor) LoggingMarkers(org.nzbhydra.logging.LoggingMarkers) NewznabResponse(org.nzbhydra.mapping.newznab.NewznabResponse) ResponseEntity(org.springframework.http.ResponseEntity) Entry(java.util.Map.Entry) Instant(java.time.Instant) NewznabResponse(org.nzbhydra.mapping.newznab.NewznabResponse)

Example 3 with NewznabResponse

use of org.nzbhydra.mapping.newznab.NewznabResponse in project nzbhydra2 by theotherp.

the class ExternalApi method search.

protected NewznabResponse search(NewznabParameters params) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    SearchRequest searchRequest = buildBaseSearchRequest(params);
    if (isTorznabCall()) {
        searchRequest.setDownloadType(org.nzbhydra.searching.DownloadType.TORRENT);
    } else {
        searchRequest.setDownloadType(org.nzbhydra.searching.DownloadType.NZB);
    }
    SearchResult searchResult = searcher.search(searchRequest);
    NewznabResponse transformedResults = transformResults(searchResult, params, searchRequest);
    logger.info("Search took {}ms. Returning {} results", stopwatch.elapsed(TimeUnit.MILLISECONDS), searchResult.getSearchResultItems().size());
    return transformedResults;
}
Also used : SearchRequest(org.nzbhydra.searching.searchrequests.SearchRequest) Stopwatch(com.google.common.base.Stopwatch) SearchResult(org.nzbhydra.searching.SearchResult) NewznabResponse(org.nzbhydra.mapping.newznab.NewznabResponse)

Example 4 with NewznabResponse

use of org.nzbhydra.mapping.newznab.NewznabResponse in project nzbhydra2 by theotherp.

the class ExternalApi method api.

@RequestMapping(value = { "/api", "/rss", "/torznab/api" }, consumes = MediaType.ALL_VALUE)
public ResponseEntity<? extends Object> api(NewznabParameters params) throws Exception {
    logger.info("Received external {}API call: {}", (isTorznabCall() ? "torznab " : ""), params);
    if (!noApiKeyNeeded && !Objects.equals(params.getApikey(), configProvider.getBaseConfig().getMain().getApiKey())) {
        logger.error("Received API call with wrong API key");
        throw new WrongApiKeyException("Wrong api key");
    }
    if (Stream.of(ActionAttribute.SEARCH, ActionAttribute.BOOK, ActionAttribute.TVSEARCH, ActionAttribute.MOVIE).anyMatch(x -> x == params.getT())) {
        if (params.getCachetime() != null) {
            return handleCachingSearch(params);
        }
        NewznabResponse searchResult = search(params);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.CONTENT_TYPE, searchResult.getContentHeader());
        if (params.getO() != OutputType.JSON) {
            searchResult.setSearchType(isTorznabCall() ? "torznab" : "newznab");
        }
        return new ResponseEntity<>(searchResult, httpHeaders, HttpStatus.OK);
    }
    if (params.getT() == ActionAttribute.GET) {
        return getNzb(params);
    }
    if (params.getT() == ActionAttribute.CAPS) {
        return getCaps();
    }
    logger.error("Incorrect API request: {}", params);
    NewznabXmlError error = new NewznabXmlError("200", "Unknown or incorrect parameter");
    return new ResponseEntity<Object>(error, HttpStatus.OK);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) NewznabXmlError(org.nzbhydra.mapping.newznab.xml.NewznabXmlError) NewznabResponse(org.nzbhydra.mapping.newznab.NewznabResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

NewznabResponse (org.nzbhydra.mapping.newznab.NewznabResponse)4 Stopwatch (com.google.common.base.Stopwatch)3 NewznabXmlError (org.nzbhydra.mapping.newznab.xml.NewznabXmlError)2 SearchResult (org.nzbhydra.searching.SearchResult)2 SearchRequest (org.nzbhydra.searching.searchrequests.SearchRequest)2 Strings (com.google.common.base.Strings)1 Throwables (com.google.common.base.Throwables)1 Clock (java.time.Clock)1 Instant (java.time.Instant)1 ChronoUnit (java.time.temporal.ChronoUnit)1 java.util (java.util)1 Entry (java.util.Map.Entry)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 TimeUnit (java.util.concurrent.TimeUnit)1 Stream (java.util.stream.Stream)1 AllArgsConstructor (lombok.AllArgsConstructor)1 Data (lombok.Data)1 ClientAbortException (org.apache.catalina.connector.ClientAbortException)1 CategoriesConfig (org.nzbhydra.config.CategoriesConfig)1