From 6e16ad9a234b13784a9b9439db267fed2986d651 Mon Sep 17 00:00:00 2001 From: Roland Date: Fri, 31 Dec 2021 20:14:14 -0700 Subject: [PATCH] Archives can be searched by their contents. --- .../31896cc29b71_archive_contents_search.py | 42 +++++++++++ modules/archive/api.py | 28 +++++++- modules/archive/conftest.py | 3 +- modules/archive/lib.py | 51 ++++++++++++-- modules/archive/models.py | 32 ++++++++- modules/archive/schema.py | 12 ++++ modules/archive/test/test_lib.py | 70 ++++++++++++++++++- modules/videos/video/lib.py | 12 +--- wrolpi/db.py | 14 +++- 9 files changed, 240 insertions(+), 24 deletions(-) create mode 100644 alembic/versions/31896cc29b71_archive_contents_search.py diff --git a/alembic/versions/31896cc29b71_archive_contents_search.py b/alembic/versions/31896cc29b71_archive_contents_search.py new file mode 100644 index 00000000..89fe8c50 --- /dev/null +++ b/alembic/versions/31896cc29b71_archive_contents_search.py @@ -0,0 +1,42 @@ +"""Archive contents search. + +Revision ID: 31896cc29b71 +Revises: bddb5e95a91e +Create Date: 2021-12-31 18:53:25.326674 + +""" +import os + +from alembic import op +from sqlalchemy.orm import Session + +# revision identifiers, used by Alembic. +revision = '31896cc29b71' +down_revision = 'bddb5e95a91e' +branch_labels = None +depends_on = None + +DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False + + +def upgrade(): + bind = op.get_bind() + session = Session(bind=bind) + session.execute('ALTER TABLE archive ADD COLUMN contents TEXT') + session.execute(''' + ALTER TABLE archive + ADD COLUMN textsearch tsvector + GENERATED ALWAYS AS ( + setweight(to_tsvector('english'::regconfig, title), 'A') || + setweight(to_tsvector('english'::regconfig, contents), 'D') + ) STORED + ''') + session.execute('CREATE INDEX IF NOT EXISTS archive_textsearch_idx ON archive USING GIN(textsearch)') + + +def downgrade(): + bind = op.get_bind() + session = Session(bind=bind) + session.execute('DROP INDEX IF EXISTS archive_textsearch_idx') + session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS contents') + session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS textsearch') diff --git a/modules/archive/api.py b/modules/archive/api.py index e7b35a9f..6a861a91 100644 --- a/modules/archive/api.py +++ b/modules/archive/api.py @@ -5,10 +5,12 @@ from requests import Request from sanic import response from wrolpi.common import logger, wrol_mode_check +from wrolpi.errors import ValidationError from wrolpi.root_api import get_blueprint, json_response from wrolpi.schema import validate_doc, JSONErrorResponse from . import lib -from .schema import RetrieveURLsRequest, RetrieveURLsResponse, PostArchiveRequest +from .schema import RetrieveURLsRequest, RetrieveURLsResponse, PostArchiveRequest, ArchiveSearchRequest, \ + ArchiveSearchResponse NAME = 'archive' @@ -43,13 +45,13 @@ async def delete_url(_: Request, url_id: int): return response.empty() -@bp.post('/search') +@bp.post('/urls') @validate_doc( 'Get a list of URLs', RetrieveURLsRequest, RetrieveURLsResponse, ) -async def search_archives(_: Request, data: dict): +async def get_urls(_: Request, data: dict): try: limit = abs(int(data.get('limit', 20))) offset = abs(int(data.get('offset', 0))) @@ -75,3 +77,23 @@ async def refresh_archives(_: Request): async def fetch_domains(_: Request): domains = lib.get_domains() return json_response({'domains': domains, 'totals': {'domains': len(domains)}}) + + +@bp.post('/search') +@validate_doc( + 'Search archive contents and titles', + consumes=ArchiveSearchRequest, + produces=ArchiveSearchResponse, +) +async def search_archives(_: Request, data: dict): + try: + search_str = data.get('search_str') + domain = data.get('domain') + limit = int(data.get('limit', 20)) + offset = int(data.get('offset', 0)) + except Exception as e: + raise ValidationError('Unable to validate search queries') from e + + archives, total = lib.search(search_str, domain, limit, offset) + ret = dict(archives=archives, totals=dict(archives=total)) + return json_response(ret) diff --git a/modules/archive/conftest.py b/modules/archive/conftest.py index 52dc6aab..8f6ed2d1 100644 --- a/modules/archive/conftest.py +++ b/modules/archive/conftest.py @@ -49,7 +49,7 @@ def archive_factory(test_session, archive_directory): if not domain: domain = Domain( - domain=domain, + domain=domain_dir.name, directory=domain_dir, ) test_session.add(domain) @@ -73,6 +73,7 @@ def archive_factory(test_session, archive_directory): status='complete', title=title, url_id=url_.id, + domain_id=domain.id, ) test_session.add(archive) test_session.commit() diff --git a/modules/archive/lib.py b/modules/archive/lib.py index 847fc8f4..276c4250 100644 --- a/modules/archive/lib.py +++ b/modules/archive/lib.py @@ -14,7 +14,7 @@ from sqlalchemy.orm import Session from modules.archive.models import URL, Domain, Archive from wrolpi.common import get_media_directory, logger, chunks, extract_domain from wrolpi.dates import now, strptime_ms, strftime_ms -from wrolpi.db import get_db_session, get_db_curs +from wrolpi.db import get_db_session, get_db_curs, get_ranked_models from wrolpi.errors import InvalidDomain, UnknownURL, PendingArchive, InvalidArchive from wrolpi.vars import PYTEST @@ -409,14 +409,25 @@ def _refresh_archives(): curs.execute(stmt) urls = list(map(dict, curs.fetchall())) stmt = ''' - DELETE FROM domains WHERE id NOT IN ( - select distinct domain_id from url - ) RETURNING domains.id + DELETE FROM domains WHERE + id NOT IN (select distinct domain_id from url) + AND id NOT IN (select distinct domain_id from archive) + RETURNING domains.id ''' curs.execute(stmt) domains = list(map(dict, curs.fetchall())) logger.info(f'Deleted {len(urls)} URLS and {len(domains)} Domains') + with get_db_session(commit=True) as session: + # Get all archives that have no text contents, but have txt files. + archives = session.query(Archive).filter( + Archive.contents == None, # noqa + Archive.readability_txt_path != None, + ).all() + for archive in archives: + with archive.readability_txt_path.path.open('rt') as fh: + archive.contents = fh.read() + async def refresh_archives(): _refresh_archives() @@ -475,3 +486,35 @@ def get_domains(): curs.execute(stmt) domains = list(map(dict, curs.fetchall())) return domains + + +def search(search_str: str, domain: str, limit: int, offset: int): + with get_db_curs() as curs: + wheres = '' + params = dict(search_str=search_str, offset=offset, limit=limit) + + if domain: + curs.execute('SELECT id FROM domains WHERE domain=%s', (domain,)) + domain_id = curs.fetchone()[0] + params['domain_id'] = domain_id + wheres += 'AND domain_id = %(domain_id)s' + + # TODO handle different Archive search orders. + stmt = f''' + SELECT id, ts_rank_cd(textsearch, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total + FROM archive + WHERE + textsearch @@ websearch_to_tsquery(%(search_str)s) + {wheres} + ORDER BY 2 DESC, 1 ASC + OFFSET %(offset)s + LIMIT %(limit)s + ''' + curs.execute(stmt, params) + results = [dict(i) for i in curs.fetchall()] + total = results[0]['total'] if results else 0 + ranked_ids = [i['id'] for i in results] + + results = get_ranked_models(ranked_ids, Archive) + + return results, total diff --git a/modules/archive/models.py b/modules/archive/models.py index 7ba82ffa..188ae6ce 100644 --- a/modules/archive/models.py +++ b/modules/archive/models.py @@ -1,10 +1,10 @@ from typing import Generator -from sqlalchemy import Column, Integer, String, ForeignKey +from sqlalchemy import Column, Integer, String, ForeignKey, Computed from sqlalchemy.orm import relationship from sqlalchemy.orm.collections import InstrumentedList -from wrolpi.common import ModelHelper, Base +from wrolpi.common import ModelHelper, Base, tsvector from wrolpi.dates import TZDateTime from wrolpi.media_path import MediaPathType @@ -27,6 +27,10 @@ class Archive(Base, ModelHelper): title = Column(String) archive_datetime = Column(TZDateTime) status = Column(String) + contents = Column(String) + + textsearch = Column(tsvector, Computed('''setweight(to_tsvector('english'::regconfig, title), 'A') || + setweight(to_tsvector('english'::regconfig, contents), 'D')''')) def __repr__(self): return f'' @@ -60,6 +64,30 @@ class Archive(Base, ModelHelper): return self.archive_datetime > other.archive_datetime + def __json__(self): + url = None + if self.url: + url = dict( + url=self.url.url, + id=self.url.id, + ) + d = dict( + archive_datetime=self.archive_datetime, + domain=self.domain.dict() if self.domain else None, + domain_id=self.domain_id, + id=self.id, + readability_json_path=self.readability_json_path.path if self.readability_json_path else None, + readability_path=self.readability_path.path if self.readability_path else None, + readability_txt_path=self.readability_txt_path.path if self.readability_txt_path else None, + screenshot_path=self.screenshot_path.path if self.screenshot_path else None, + singlefile_path=self.singlefile_path.path if self.singlefile_path else None, + status=self.status, + title=self.title, + url=url, + url_id=self.url_id, + ) + return d + class URL(Base, ModelHelper): __tablename__ = 'url' diff --git a/modules/archive/schema.py b/modules/archive/schema.py index b3524236..3ef79b7a 100644 --- a/modules/archive/schema.py +++ b/modules/archive/schema.py @@ -42,3 +42,15 @@ class RetrieveURLsResponse: class PostArchiveRequest: url = doc.String(required=True) + + +class ArchiveSearchRequest: + search_str = doc.String() + domain = doc.String() + offset = doc.Integer() + limit = doc.Integer() + + +class ArchiveSearchResponse: + videos = doc.List(ArchiveDict) + totals = doc.Dictionary() diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index e8598871..3a2ff7c0 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -1,6 +1,7 @@ import json import pathlib from datetime import datetime +from http import HTTPStatus import mock @@ -322,6 +323,9 @@ class TestArchive(TestAPI): def test_archive_refresh_deleted_archive(test_session, archive_directory, archive_factory): + """ + Archives/URLs/Domains should be deleted when archive files are deleted. + """ archive1 = archive_factory('example.com', 'https://example.com/1') archive2 = archive_factory('example.com', 'https://example.com/1') archive3 = archive_factory('example.com') @@ -338,15 +342,15 @@ def test_archive_refresh_deleted_archive(test_session, archive_directory, archiv assert test_session.query(Domain).count() == domain_count # All 3 archives are already in the DB. - check_counts(archive_count=5, url_count=4, domain_count=5) + check_counts(archive_count=5, url_count=4, domain_count=3) _refresh_archives() - check_counts(archive_count=5, url_count=4, domain_count=4) + check_counts(archive_count=5, url_count=4, domain_count=3) # Delete archive2's files, it's the latest for 'https://example.com/1' for path in archive2.my_paths(): path.unlink() _refresh_archives() - check_counts(archive_count=4, url_count=4, domain_count=4) + check_counts(archive_count=4, url_count=4, domain_count=3) # Delete archive1's files, now the URL is empty. for path in archive1.my_paths(): @@ -367,3 +371,63 @@ def test_archive_refresh_deleted_archive(test_session, archive_directory, archiv path.unlink() _refresh_archives() check_counts(archive_count=0, url_count=0, domain_count=0) + + +def test_refresh_archives_search(test_session, archive_directory, archive_factory, test_client): + """ + Archives can be searched. An Archive missing `contents` will be filled using the readability txt file. + """ + archive1 = archive_factory('example.com', 'https://example.com/one') + archive2 = archive_factory('example.com', 'https://example.com/one') + archive3 = archive_factory('example.org') + archive_factory('example.org') # has no contents + + contents_title_archive = [ + ('foo bar qux', 'my archive', archive1), + ('foo baz qux qux', 'other archive', archive2), + ('baz qux qux qux', 'archive third', archive3), + ] + for contents, title, archive in contents_title_archive: + with archive.readability_txt_path.path.open('wt') as fh: + archive.title = title + fh.write(contents) + test_session.commit() + + _refresh_archives() + + def check_results(data, ids): + request, response = test_client.post('/api/archive/search', content=json.dumps(data)) + assert response.status_code == HTTPStatus.OK, response.json + assert [i['id'] for i in response.json['archives']] == ids + + # 1 and 2 contain "foo". + data = {'search_str': 'foo'} + check_results(data, [1, 2]) + + # 2 and 3 contain "baz". + data = {'search_str': 'baz'} + check_results(data, [2, 3]) + + # 1 contains "bar". + data = {'search_str': 'bar'} + check_results(data, [1, ]) + + # No archives contain "huzzah" + data = {'search_str': 'huzzah'} + check_results(data, []) + + # Only 3 contains "baz" and is in domain "example.org" + data = {'search_str': 'baz', 'domain': 'example.org'} + check_results(data, [3, ]) + + # 1's title contains "my", this is ignored by Postgres. + data = {'search_str': 'my'} + check_results(data, []) + + # 3's title contains "third". + data = {'search_str': 'third'} + check_results(data, [3, ]) + + # All titles contain "qux", but they contain different amounts. They are ordered by the amount. + data = {'search_str': 'qux'} + check_results(data, [3, 2, 1]) diff --git a/modules/videos/video/lib.py b/modules/videos/video/lib.py index 3dbc8212..37edcdca 100644 --- a/modules/videos/video/lib.py +++ b/modules/videos/video/lib.py @@ -6,9 +6,8 @@ from sqlalchemy.orm import Session from sqlalchemy.orm.exc import NoResultFound from wrolpi.common import run_after, logger -from wrolpi.db import get_db_session, get_db_curs +from wrolpi.db import get_db_session, get_db_curs, get_ranked_models from wrolpi.errors import UnknownVideo -from wrolpi.vars import PYTEST from ..lib import save_channels_config from ..models import Video @@ -140,13 +139,8 @@ def video_search( total = results[0]['total'] if results else 0 ranked_ids = [i['id'] for i in results] - with get_db_session() as session: - results = [] - if ranked_ids: - results = session.query(Video).filter(Video.id.in_(ranked_ids)).all() - results = sorted(results, key=lambda r: ranked_ids.index(r.id)) - - results = [i.__json__() for i in results] + results = get_ranked_models(ranked_ids, Video) + results = [i.__json__() for i in results] return results, total diff --git a/wrolpi/db.py b/wrolpi/db.py index 9123dcdc..b2ef2804 100644 --- a/wrolpi/db.py +++ b/wrolpi/db.py @@ -1,5 +1,5 @@ from contextlib import contextmanager -from typing import ContextManager, Tuple +from typing import ContextManager, Tuple, List import psycopg2 import sqlalchemy.exc @@ -7,7 +7,7 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, Session from sqlalchemy.pool import NullPool -from wrolpi.common import logger +from wrolpi.common import logger, Base from wrolpi.vars import DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DOCKERIZED, PYTEST logger = logger.getChild(__name__) @@ -111,3 +111,13 @@ def get_db_curs(commit: bool = False): # Rollback only if a transaction hasn't been committed. if session.transaction.is_active: connection.rollback() + + +def get_ranked_models(ranked_ids: List[int], model: Base) -> List[Base]: + """ + Get all objects whose ids are in the `ranked_ids`, order them by their position in `ranked_ids`. + """ + with get_db_session() as session: + results = session.query(model).filter(model.id.in_(ranked_ids)).all() + results = sorted(results, key=lambda i: ranked_ids.index(i.id)) + return results