Search in sources :

Example 1 with DownloaderException

use of org.nzbhydra.downloading.exceptions.DownloaderException in project nzbhydra2 by theotherp.

the class Downloader method addBySearchResultIds.

@Transactional
public AddNzbsResponse addBySearchResultIds(List<AddFilesRequest.SearchResult> searchResults, String category) {
    NzbAddingType addingType = downloaderConfig.getNzbAddingType();
    List<Long> addedNzbs = new ArrayList<>();
    try {
        for (AddFilesRequest.SearchResult entry : searchResults) {
            Long guid = Long.valueOf(entry.getSearchResultId());
            String categoryToSend;
            if (Strings.isNullOrEmpty(category) && !"N/A".equals(entry.getOriginalCategory())) {
                categoryToSend = entry.getOriginalCategory();
            } else {
                categoryToSend = category;
            }
            if (addingType == NzbAddingType.UPLOAD) {
                // Uploading NZBs can only be done via proxying
                DownloadResult result = nzbHandler.getFileByGuid(guid, FileDownloadAccessType.PROXY, SearchSource.INTERNAL);
                String externalId = addNzb(result.getContent(), result.getTitle(), categoryToSend);
                result.getDownloadEntity().setExternalId(externalId);
                nzbHandler.updateStatusByEntity(result.getDownloadEntity(), FileDownloadStatus.NZB_ADDED);
            } else {
                SearchResultEntity searchResultEntity = searchResultRepository.getOne(guid);
                addLink(nzbHandler.getDownloadLink(guid, false, DownloadType.NZB), searchResultEntity.getTitle(), categoryToSend);
            }
            addedNzbs.add(guid);
        }
    } catch (InvalidSearchResultIdException | DownloaderException | EntityNotFoundException e) {
        String message;
        if (e instanceof DownloaderException) {
            message = "Error while adding NZB(s) to downloader: " + e.getMessage();
        } else if (e instanceof EntityNotFoundException) {
            message = "Unable to find the search result in the database. Unable to download";
        } else {
            message = e.getMessage();
        }
        logger.error(message);
        if (!addedNzbs.isEmpty()) {
            message += ".\n" + addedNzbs.size() + " were added successfully";
        }
        Set<Long> searchResultIds = Sets.newHashSet(searchResults.stream().map(x -> Long.valueOf(x.getSearchResultId())).collect(Collectors.toSet()));
        searchResultIds.removeAll(addedNzbs);
        return new AddNzbsResponse(false, message, addedNzbs, searchResultIds);
    }
    return new AddNzbsResponse(true, null, addedNzbs, Collections.emptyList());
}
Also used : Iterables(com.google.common.collect.Iterables) java.util(java.util) Stopwatch(com.google.common.base.Stopwatch) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) DownloaderException(org.nzbhydra.downloading.exceptions.DownloaderException) Strings(com.google.common.base.Strings) GenericResponse(org.nzbhydra.GenericResponse) SearchSource(org.nzbhydra.searching.searchrequests.SearchRequest.SearchSource) EntityNotFoundException(javax.persistence.EntityNotFoundException) NzbAddingType(org.nzbhydra.config.NzbAddingType) SearchResultEntity(org.nzbhydra.searching.SearchResultEntity) Logger(org.slf4j.Logger) SearchResultRepository(org.nzbhydra.searching.SearchResultRepository) MoreObjects(com.google.common.base.MoreObjects) Instant(java.time.Instant) DownloadType(org.nzbhydra.searching.SearchResultItem.DownloadType) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) FileDownloadAccessType(org.nzbhydra.config.FileDownloadAccessType) org.nzbhydra.downloading(org.nzbhydra.downloading) Component(org.springframework.stereotype.Component) Data(lombok.Data) DownloaderConfig(org.nzbhydra.config.DownloaderConfig) AllArgsConstructor(lombok.AllArgsConstructor) LoggingMarkers(org.nzbhydra.logging.LoggingMarkers) NoArgsConstructor(lombok.NoArgsConstructor) Transactional(org.springframework.transaction.annotation.Transactional) DownloaderException(org.nzbhydra.downloading.exceptions.DownloaderException) EntityNotFoundException(javax.persistence.EntityNotFoundException) SearchResultEntity(org.nzbhydra.searching.SearchResultEntity) NzbAddingType(org.nzbhydra.config.NzbAddingType) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with DownloaderException

use of org.nzbhydra.downloading.exceptions.DownloaderException in project nzbhydra2 by theotherp.

the class Downloader method checkForStatusUpdates.

public List<FileDownloadEntity> checkForStatusUpdates(List<FileDownloadEntity> downloads, StatusCheckType statusCheckType) {
    logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Checking {} history for updates to downloaded statuses", downloaderConfig.getName());
    Stopwatch stopwatch = Stopwatch.createStarted();
    if (downloads.isEmpty()) {
        return Collections.emptyList();
    }
    Instant earliestDownload = Iterables.getLast(downloads).getTime();
    List<FileDownloadEntity> updatedDownloads = new ArrayList<>();
    try {
        List<DownloaderEntry> downloaderEntries;
        if (statusCheckType == StatusCheckType.HISTORY) {
            downloaderEntries = getHistory(earliestDownload);
        } else {
            downloaderEntries = getQueue(earliestDownload);
        }
        for (FileDownloadEntity download : downloads) {
            for (DownloaderEntry entry : downloaderEntries) {
                if (download.getSearchResult() == null) {
                    continue;
                }
                if (isDownloadMatchingDownloaderEntry(download, entry)) {
                    logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Found match between download and downloader entry with title", entry.getNzbName());
                    FileDownloadStatus newStatus = getDownloadStatusFromDownloaderEntry(entry, statusCheckType);
                    if (newStatus == null) {
                        // Could be any status that we're not prepared for
                        logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Unable to map downloader status {}", entry.getStatus());
                        continue;
                    }
                    if ((download.getStatus() == FileDownloadStatus.NONE || download.getStatus() == FileDownloadStatus.REQUESTED) && download.getExternalId() == null && statusCheckType == StatusCheckType.QUEUE) {
                        logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Current download status is {} and no downloader ID was set. Setting ID {} now", entry.getStatus(), entry.getNzbId());
                        // Setting the external ID will make it better identifiable in the history later and make false positives less likely
                        download.setExternalId(String.valueOf(entry.getNzbId()));
                    }
                    if (newStatus.canUpdate(download.getStatus())) {
                        download.setStatus(newStatus);
                        updatedDownloads.add(download);
                        logger.info("Updating download status for {} to {}", entry.getNzbName(), newStatus);
                    }
                }
            }
        }
        logger.debug(LoggingMarkers.PERFORMANCE, "Took {}ms to check download status updates for {} downloads in the database and {} entries from {} {}", stopwatch.elapsed(TimeUnit.MILLISECONDS), downloads.size(), downloaderEntries.size(), downloaderConfig.getName(), statusCheckType);
    } catch (DownloaderException e) {
        logger.warn(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Unable to contact downloader {}: ", downloaderConfig.getName(), e.getMessage());
    } catch (Throwable throwable) {
        logger.error("Error while trying to update download statuses", throwable);
    }
    return updatedDownloads;
}
Also used : DownloaderException(org.nzbhydra.downloading.exceptions.DownloaderException) Instant(java.time.Instant) Stopwatch(com.google.common.base.Stopwatch)

Example 3 with DownloaderException

use of org.nzbhydra.downloading.exceptions.DownloaderException in project nzbhydra2 by theotherp.

the class Sabnzbd method addNzb.

@Override
public String addNzb(byte[] fileContent, String title, String category) throws DownloaderException {
    // Using OKHTTP here because RestTemplate wouldn't work
    logger.debug("Uploading NZB {} to sabnzbd", title);
    UriComponentsBuilder urlBuilder = getBaseUrl();
    urlBuilder.queryParam("mode", "addfile").queryParam("nzbname", title).queryParam("priority", "-100");
    if (!Strings.isNullOrEmpty(category)) {
        urlBuilder.queryParam("cat", category);
    }
    RequestBody formBody = new MultipartBody.Builder().addFormDataPart("name", title, RequestBody.create(MediaType.parse(org.springframework.http.MediaType.APPLICATION_XML_VALUE), fileContent)).build();
    Request request = new Request.Builder().url(urlBuilder.toUriString()).post(formBody).build();
    OkHttpClient client = requestFactory.getOkHttpClientBuilder(urlBuilder.build().encode().toUri()).build();
    try (Response response = client.newCall(request).execute();
        ResponseBody body = response.body()) {
        if (!response.isSuccessful()) {
            throw new DownloaderException("Downloader returned status code " + response.code() + " and message " + response.message());
        }
        AddNzbResponse addNzbResponse = objectMapper.readValue(body.string(), AddNzbResponse.class);
        if (addNzbResponse.getNzoIds().isEmpty()) {
            throw new DownloaderException("Sabnzbd says NZB was added successfully but didn't return an NZO ID");
        }
        if (addNzbResponse.getNzoIds().isEmpty()) {
            throw new DownloaderException("Sabnzbd says NZB was added successfully but didn't return an NZO ID");
        }
        String nzoId = addNzbResponse.getNzoIds().get(0);
        logger.info("Successfully added NZB \"{}\" to sabnzbd queue with ID {}", title, nzoId);
        return nzoId;
    } catch (IOException e) {
        throw new DownloaderException("Error while communicating with downloader: " + e.getMessage());
    }
}
Also used : GenericResponse(org.nzbhydra.GenericResponse) DownloaderException(org.nzbhydra.downloading.exceptions.DownloaderException) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) IOException(java.io.IOException)

Aggregations

DownloaderException (org.nzbhydra.downloading.exceptions.DownloaderException)3 Stopwatch (com.google.common.base.Stopwatch)2 Instant (java.time.Instant)2 GenericResponse (org.nzbhydra.GenericResponse)2 MoreObjects (com.google.common.base.MoreObjects)1 Strings (com.google.common.base.Strings)1 Iterables (com.google.common.collect.Iterables)1 Sets (com.google.common.collect.Sets)1 IOException (java.io.IOException)1 java.util (java.util)1 TimeUnit (java.util.concurrent.TimeUnit)1 Collectors (java.util.stream.Collectors)1 EntityNotFoundException (javax.persistence.EntityNotFoundException)1 AllArgsConstructor (lombok.AllArgsConstructor)1 Data (lombok.Data)1 NoArgsConstructor (lombok.NoArgsConstructor)1 DownloaderConfig (org.nzbhydra.config.DownloaderConfig)1 FileDownloadAccessType (org.nzbhydra.config.FileDownloadAccessType)1 NzbAddingType (org.nzbhydra.config.NzbAddingType)1 org.nzbhydra.downloading (org.nzbhydra.downloading)1