diff --git a/modules/archive/api.py b/modules/archive/api.py index 1f2eb4c0..29f7de0e 100644 --- a/modules/archive/api.py +++ b/modules/archive/api.py @@ -1,11 +1,13 @@ +import queue from http import HTTPStatus +from multiprocessing.sharedctypes import SynchronizedArray from sanic import response, Request, Blueprint from sanic_ext import validate from sanic_ext.extensions.openapi import openapi -from wrolpi.api_utils import json_response -from wrolpi.common import logger, wrol_mode_check, api_param_limiter +from wrolpi.api_utils import json_response, api_app +from wrolpi.common import logger, wrol_mode_check, api_param_limiter, TRACE_LEVEL from wrolpi.errors import ValidationError from wrolpi.events import Events from wrolpi.schema import JSONErrorResponse @@ -84,11 +86,21 @@ async def get_upload_singlefile(request: Request): @register_switch_handler('singlefile_upload_switch_handler') -async def singlefile_upload_switch_handler(singlefile): +async def singlefile_upload_switch_handler(url=None): """Used by `post_upload_singlefile` to upload a single file""" from wrolpi.downloader import download_manager, Download from . import ArchiveDownloader + trace_enabled = logger.isEnabledFor(TRACE_LEVEL) + if trace_enabled: + logger.trace(f'singlefile_upload_switch_handler called for {url}') + try: + singlefile = api_app.shared_ctx.archive_singlefiles.get_nowait() + except queue.Empty: + if trace_enabled: + logger.trace(f'singlefile_upload_switch_handler called on empty queue') + return + archive = await lib.singlefile_to_archive(singlefile) logger.info(f'Created Archive from upload: {archive}') name = archive.file_group.title or archive.file_group.url @@ -97,8 +109,13 @@ async def singlefile_upload_switch_handler(singlefile): if url and (download := Download.get_by_url(url)): if (download.is_failed or download.is_deferred) and download.downloader == ArchiveDownloader.name: # Download was attempted and failed, user manually archived the URL. + if trace_enabled: + logger.trace(f'singlefile_upload_switch_handler deleting incomplete download for {url}') download_manager.delete_download(download.id) + # Call this function again so any new singlefiles can be archived. + singlefile_upload_switch_handler.activate_switch() + singlefile_upload_switch_handler: ActivateSwitchMethod @@ -112,10 +129,11 @@ async def post_upload_singlefile(request: Request): singlefile = request.files['singlefile_contents'][0].body logger.info(f'Got Archive upload of {len(singlefile)} bytes for URL: {url}') - # Get the URL to ensure that the singlefile is valid. + # Extract the URL to ensure that the singlefile is valid. lib.get_url_from_singlefile(singlefile) # Send processing to background task so the extension can continue. - singlefile_upload_switch_handler.activate_switch(dict(singlefile=singlefile)) + api_app.shared_ctx.archive_singlefiles.put(singlefile) + singlefile_upload_switch_handler.activate_switch(context=dict(url=url)) # Return empty json response because SingleFile extension expects a JSON response. return json_response(dict(), status=HTTPStatus.OK) diff --git a/modules/videos/test/test_downloader.py b/modules/videos/test/test_downloader.py index 2b152663..de593af2 100644 --- a/modules/videos/test/test_downloader.py +++ b/modules/videos/test/test_downloader.py @@ -3,7 +3,6 @@ import json import shutil from copy import copy from http import HTTPStatus -from pathlib import Path from unittest import mock import pytest @@ -350,8 +349,6 @@ async def test_download_destination(test_session, test_directory, video_download """A Video can be downloaded to a directory other than it's Channel's directory.""" # yt-dlp would return the video json. mock_video_extract_info.return_value = example_video_json - # Download process is successful with no logs. - mock_video_process_runner.return_value = (0, {'stdout': '', 'stderr': ''}) # This result will be ignored during the test, we just need some value so the download does not fail. mock_video_prepare_filename.return_value = str(test_directory / 'test video.mp4') diff --git a/wrolpi/contexts.py b/wrolpi/contexts.py index ed737e40..90f1cb44 100644 --- a/wrolpi/contexts.py +++ b/wrolpi/contexts.py @@ -1,5 +1,6 @@ import ctypes import multiprocessing +import queue from sanic import Sanic @@ -54,6 +55,7 @@ def attach_shared_contexts(app: Sanic): app.shared_ctx.switches = manager.dict() app.shared_ctx.switches_lock = multiprocessing.Lock() app.shared_ctx.switches_changed = multiprocessing.Event() + app.shared_ctx.archive_singlefiles = multiprocessing.Queue() # Warnings app.shared_ctx.warn_once = manager.dict() @@ -110,6 +112,12 @@ def reset_shared_contexts(app: Sanic): # Switches app.shared_ctx.switches.clear() app.shared_ctx.switches_changed.clear() + while True: + # Clear out any pending singlefile archive switches. + try: + app.shared_ctx.archive_singlefiles.get_nowait() + except queue.Empty: + break # Events. app.shared_ctx.single_tasks_started.clear() diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index bef68960..9ca43aab 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -30,7 +30,7 @@ from wrolpi.common import get_media_directory, wrol_mode_check, logger, limit_co timer, chunks, unique_by_predicate, get_paths_in_media_directory, TRACE_LEVEL, get_relative_to_media_directory from wrolpi.dates import now, from_timestamp, months_selector_to_where, date_range_to_where from wrolpi.db import get_db_session, get_db_curs, mogrify, optional_session -from wrolpi.downloader import download_manager +from wrolpi.downloader import download_manager, Download from wrolpi.errors import InvalidFile, UnknownDirectory, UnknownFile, UnknownTag, FileConflict, FileGroupIsTagged, \ NoPrimaryFile, InvalidDirectory, IgnoredDirectoryError from wrolpi.events import Events @@ -999,23 +999,23 @@ def split_file_name_words(name: str) -> str: def get_file_statistics(): with get_db_curs() as curs: curs.execute(''' - SELECT - -- All items in file_group.files are real individual files. - SUM(json_array_length(files)) AS "total_count", - COUNT(id) FILTER (WHERE file_group.mimetype = 'application/pdf') AS "pdf_count", - COUNT(id) FILTER (WHERE file_group.mimetype = 'application/zip') AS "zip_count", - COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'video/%') AS "video_count", - COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'image/%') AS "image_count", - COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'audio/%') AS "audio_count", - COUNT(id) FILTER (WHERE file_group.mimetype = 'application/epub+zip' OR file_group.mimetype = 'application/x-mobipocket-ebook') AS "ebook_count", - (SELECT COUNT(DISTINCT tag_file.file_group_id) FROM tag_file) AS "tagged_files", - (SELECT COUNT(DISTINCT tag_zim.zim_entry) FROM tag_zim) AS "tagged_zims", - (SELECT COUNT(*) FROM tag) AS "tags_count", - SUM(size)::BIGINT AS "total_size", - (SELECT COUNT(*) FROM archive) AS archive_count - FROM - file_group - ''') + SELECT + -- All items in file_group.files are real individual files. + SUM(json_array_length(files)) AS "total_count", + COUNT(id) FILTER (WHERE file_group.mimetype = 'application/pdf') AS "pdf_count", + COUNT(id) FILTER (WHERE file_group.mimetype = 'application/zip') AS "zip_count", + COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'video/%') AS "video_count", + COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'image/%') AS "image_count", + COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'audio/%') AS "audio_count", + COUNT(id) FILTER (WHERE file_group.mimetype = 'application/epub+zip' OR file_group.mimetype = + 'application/x-mobipocket-ebook') AS "ebook_count", + (SELECT COUNT(DISTINCT tag_file.file_group_id) FROM tag_file) AS "tagged_files", + (SELECT COUNT(DISTINCT tag_zim.zim_entry) FROM tag_zim) AS "tagged_zims", + (SELECT COUNT(*) FROM tag) AS "tags_count", + SUM(size)::BIGINT AS "total_size", + (SELECT COUNT(*) FROM archive) AS archive_count + FROM file_group + ''') statistics = dict(curs.fetchall()[0]) statistics['total_count'] = statistics['total_count'] or 0 statistics['total_size'] = statistics['total_size'] or 0 @@ -1136,25 +1136,25 @@ def get_refresh_progress() -> RefreshProgress: idempotency = api_app.shared_ctx.refresh.get('idempotency') if idempotency: stmt = ''' - SELECT - -- Sum all the files in each FileGroup. - SUM(json_array_length(files)) FILTER (WHERE idempotency=%(idempotency)s) AS "total_file_groups", - COUNT(id) FILTER (WHERE indexed IS TRUE AND idempotency=%(idempotency)s) AS "indexed", - COUNT(id) FILTER (WHERE indexed IS FALSE) AS "unindexed", - COUNT(id) FILTER (WHERE model IS NOT NULL AND idempotency=%(idempotency)s) AS "modeled" - FROM file_group - ''' + SELECT + -- Sum all the files in each FileGroup. + SUM(json_array_length(files)) FILTER (WHERE idempotency = %(idempotency)s) AS "total_file_groups", + COUNT(id) FILTER (WHERE indexed IS TRUE AND idempotency = %(idempotency)s) AS "indexed", + COUNT(id) FILTER (WHERE indexed IS FALSE) AS "unindexed", + COUNT(id) FILTER (WHERE model IS NOT NULL AND idempotency = %(idempotency)s) AS "modeled" + FROM file_group \ + ''' else: # Idempotency has not yet been declared. stmt = ''' - SELECT - -- Sum all the files in each FileGroup. - SUM(json_array_length(files)) AS "total_file_groups", - COUNT(id) FILTER (WHERE indexed IS TRUE) AS "indexed", - COUNT(id) FILTER (WHERE indexed IS FALSE) AS "unindexed", - COUNT(id) FILTER (WHERE model IS NOT NULL) AS "modeled" - FROM file_group - ''' + SELECT + -- Sum all the files in each FileGroup. + SUM(json_array_length(files)) AS "total_file_groups", + COUNT(id) FILTER (WHERE indexed IS TRUE) AS "indexed", + COUNT(id) FILTER (WHERE indexed IS FALSE) AS "unindexed", + COUNT(id) FILTER (WHERE model IS NOT NULL) AS "modeled" + FROM file_group \ + ''' with get_db_curs() as curs: curs.execute(stmt, dict(idempotency=idempotency)) @@ -1610,10 +1610,16 @@ async def upsert_file(file: pathlib.Path | str, tag_names: List[str] = None) -> if PYTEST: raise - # If user uploads a file, then remove it from the skip list so comments can be downloaded. - url = file_group.url if file_group and file_group.url else None - if url and download_manager.is_skipped(url): - download_manager.remove_from_skip_list(url) + # If user uploads a file, then remove it from the download skip list so comments can be downloaded. + if url := file_group.url if file_group and file_group.url else None: + if download_manager.is_skipped(url): + download_manager.remove_from_skip_list(url) + with get_db_session() as session: + if download := Download.get_by_url(url, session): + # Mark download as completed + download.complete() + download.location = file_group.location + session.commit() upsert_directories([], file.parents)