mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 20:59:56 -05:00
Creating a new Collection model for use in organizing FileGroups.
Replacing Channels and Domains with Collection. Moving downloading relationships from Channel to Collection. Created domains.yaml config to manage tagged domain collections. Adding turn-key upgrade solution in the UI.
This commit is contained in:
parent
1f7b1c8744
commit
4fae4ae1b4
115 changed files with 13309 additions and 986 deletions
|
|
@ -75,18 +75,19 @@ def video_cleanup():
|
|||
with get_db_curs(commit=True) as curs:
|
||||
# Delete all Videos if the FileModel no longer contains a video.
|
||||
curs.execute('''
|
||||
WITH deleted AS
|
||||
(UPDATE file_group SET model=null WHERE model='video' AND mimetype NOT LIKE 'video/%' RETURNING id)
|
||||
DELETE FROM video WHERE file_group_id = ANY(select id from deleted)
|
||||
''')
|
||||
WITH deleted AS
|
||||
(UPDATE file_group SET model = null WHERE model = 'video' AND mimetype NOT LIKE 'video/%' RETURNING id)
|
||||
DELETE
|
||||
FROM video
|
||||
WHERE file_group_id = ANY (select id from deleted)
|
||||
''')
|
||||
# Claim all Videos in a Channel's directory for that Channel. But, only if they have not yet been claimed.
|
||||
curs.execute('''
|
||||
UPDATE video v
|
||||
SET
|
||||
channel_id = c.id
|
||||
FROM channel c
|
||||
LEFT JOIN file_group fg ON fg.primary_path LIKE c.directory || '/%'::VARCHAR
|
||||
WHERE
|
||||
v.channel_id IS NULL
|
||||
AND fg.id = v.file_group_id
|
||||
''')
|
||||
UPDATE video v
|
||||
SET channel_id = c.id
|
||||
FROM channel c
|
||||
INNER JOIN collection col ON col.id = c.collection_id
|
||||
LEFT JOIN file_group fg ON fg.primary_path LIKE col.directory || '/%'::VARCHAR
|
||||
WHERE v.channel_id IS NULL
|
||||
AND fg.id = v.file_group_id
|
||||
''')
|
||||
|
|
|
|||
|
|
@ -1,16 +1,18 @@
|
|||
import pathlib
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Union
|
||||
from typing import List, Union
|
||||
|
||||
from sqlalchemy import or_, func, desc, asc
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from wrolpi import flags
|
||||
from wrolpi.collections import Collection
|
||||
from wrolpi.common import logger, \
|
||||
get_media_directory, wrol_mode_check, background_task
|
||||
from wrolpi.db import get_db_curs, optional_session, get_db_session
|
||||
from wrolpi.downloader import save_downloads_config, download_manager, Download
|
||||
from wrolpi.errors import APIError, ValidationError, RefreshConflict
|
||||
from wrolpi.tags import Tag
|
||||
from wrolpi.vars import PYTEST
|
||||
from .. import schema
|
||||
from ..common import check_for_channel_conflicts
|
||||
|
|
@ -30,15 +32,16 @@ async def get_minimal_channels() -> List[dict]:
|
|||
# one that will consume the most resources.
|
||||
stmt = '''
|
||||
SELECT c.id,
|
||||
c.name AS "name",
|
||||
c.directory,
|
||||
col.name AS "name",
|
||||
col.directory,
|
||||
c.url,
|
||||
t.name AS "tag_name",
|
||||
t.name AS "tag_name",
|
||||
c.video_count,
|
||||
c.total_size,
|
||||
c.minimum_frequency
|
||||
FROM channel AS c
|
||||
LEFT JOIN tag t ON t.id = c.tag_id
|
||||
INNER JOIN collection col ON col.id = c.collection_id
|
||||
LEFT JOIN tag t ON t.id = col.tag_id
|
||||
'''
|
||||
curs.execute(stmt)
|
||||
logger.debug(stmt)
|
||||
|
|
@ -60,19 +63,22 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
|
|||
"""
|
||||
channel: COD = None # noqa
|
||||
# Try to find the channel by the most reliable methods first.
|
||||
# Always eagerly load Collection to ensure name/directory/tag_id are available
|
||||
if channel_id:
|
||||
channel = session.query(Channel).filter_by(id=channel_id).one_or_none()
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(id=channel_id).one_or_none()
|
||||
if not channel and source_id:
|
||||
channel = session.query(Channel).filter_by(source_id=source_id).one_or_none()
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(
|
||||
source_id=source_id).one_or_none()
|
||||
if not channel and url:
|
||||
channel = session.query(Channel).filter_by(url=url).one_or_none()
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(url=url).one_or_none()
|
||||
if not channel and directory:
|
||||
directory = Path(directory)
|
||||
if not directory.is_absolute():
|
||||
directory = get_media_directory() / directory
|
||||
channel = session.query(Channel).filter_by(directory=directory).one_or_none()
|
||||
channel = session.query(Channel).join(Collection).filter(
|
||||
Collection.directory == str(directory)).one_or_none()
|
||||
if not channel and name:
|
||||
channel = session.query(Channel).filter_by(name=name).one_or_none()
|
||||
channel = session.query(Channel).join(Collection).filter(Collection.name == name).one_or_none()
|
||||
|
||||
if not channel:
|
||||
raise UnknownChannel(f'No channel matches {channel_id=} {source_id=} {url=} {directory=}')
|
||||
|
|
@ -147,7 +153,17 @@ def create_channel(session: Session, data: schema.ChannelPostRequest, return_dic
|
|||
directory = get_media_directory() / directory if not directory.is_absolute() else directory
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
channel = Channel()
|
||||
# Create Collection first
|
||||
collection = Collection(
|
||||
name=data.name,
|
||||
kind='channel',
|
||||
directory=directory,
|
||||
)
|
||||
session.add(collection)
|
||||
session.flush([collection])
|
||||
|
||||
# Create Channel linked to Collection
|
||||
channel = Channel(collection_id=collection.id)
|
||||
session.add(channel)
|
||||
session.flush([channel])
|
||||
# Apply the changes now that we've OK'd them
|
||||
|
|
@ -179,22 +195,24 @@ async def search_channels_by_name(name: str, limit: int = 5, session: Session =
|
|||
name_no_spaces = ''.join(name.split(' '))
|
||||
if order_by_video_count:
|
||||
stmt = session.query(Channel, func.count(Video.id).label('video_count')) \
|
||||
.join(Collection) \
|
||||
.filter(or_(
|
||||
Channel.name.ilike(f'%{name}%'),
|
||||
Channel.name.ilike(f'%{name_no_spaces}%'),
|
||||
Collection.name.ilike(f'%{name}%'),
|
||||
Collection.name.ilike(f'%{name_no_spaces}%'),
|
||||
)) \
|
||||
.outerjoin(Video, Video.channel_id == Channel.id) \
|
||||
.group_by(Channel.id, Channel.name) \
|
||||
.order_by(desc('video_count'), asc(Channel.name)) \
|
||||
.group_by(Channel.id, Collection.id, Collection.name) \
|
||||
.order_by(desc('video_count'), asc(Collection.name)) \
|
||||
.limit(limit)
|
||||
channels = [i[0] for i in stmt]
|
||||
else:
|
||||
stmt = session.query(Channel) \
|
||||
.join(Collection) \
|
||||
.filter(or_(
|
||||
Channel.name.ilike(f'%{name}%'),
|
||||
Channel.name.ilike(f'%{name_no_spaces}%'),
|
||||
Collection.name.ilike(f'%{name}%'),
|
||||
Collection.name.ilike(f'%{name_no_spaces}%'),
|
||||
)) \
|
||||
.order_by(asc(Channel.name)) \
|
||||
.order_by(asc(Collection.name)) \
|
||||
.limit(limit)
|
||||
channels = stmt.all()
|
||||
return channels
|
||||
|
|
@ -270,6 +288,5 @@ async def tag_channel(tag_name: str | None, directory: pathlib.Path | None, chan
|
|||
@optional_session
|
||||
async def search_channels(tag_names: List[str], session: Session) -> List[Channel]:
|
||||
"""Search Tagged Channels."""
|
||||
from wrolpi.tags import Tag
|
||||
channels = session.query(Channel).join(Tag).filter(Tag.name.in_(tag_names)).all()
|
||||
channels = session.query(Channel).join(Collection).join(Tag).filter(Tag.name.in_(tag_names)).all()
|
||||
return channels
|
||||
|
|
|
|||
|
|
@ -21,16 +21,18 @@ from wrolpi.files.models import Directory
|
|||
from wrolpi.test.common import assert_dict_contains
|
||||
|
||||
|
||||
def test_get_channels(test_directory, channel_factory, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_channels(test_directory, channel_factory, async_client):
|
||||
channel_factory()
|
||||
channel_factory()
|
||||
channel_factory()
|
||||
request, response = test_client.get('/api/videos/channels')
|
||||
request, response = await async_client.get('/api/videos/channels')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['channels']) == 3
|
||||
|
||||
|
||||
def test_get_video(test_client, test_session, simple_channel, video_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_video(async_client, test_session, simple_channel, video_factory):
|
||||
"""Test that you get can information about a video. Test that video file can be gotten."""
|
||||
now_ = now()
|
||||
video1 = video_factory(channel_id=simple_channel.id, title='vid1')
|
||||
|
|
@ -40,14 +42,14 @@ def test_get_video(test_client, test_session, simple_channel, video_factory):
|
|||
test_session.commit()
|
||||
|
||||
# Test that a 404 is returned when no video exists
|
||||
_, response = test_client.get('/api/videos/video/10')
|
||||
_, response = await async_client.get('/api/videos/video/10')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, response.json
|
||||
assert response.json == {'code': 'UNKNOWN_VIDEO',
|
||||
'error': 'Cannot find Video with id 10',
|
||||
'message': 'The video could not be found.'}
|
||||
|
||||
# Get the video info we inserted
|
||||
_, response = test_client.get('/api/videos/video/1')
|
||||
_, response = await async_client.get('/api/videos/video/1')
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert_dict_contains(response.json['file_group'], {'title': 'vid1'})
|
||||
|
||||
|
|
@ -92,9 +94,10 @@ async def test_channel_no_download_frequency(async_client, test_session, test_di
|
|||
assert test_session.query(Channel).count() == 1
|
||||
|
||||
|
||||
def test_video_file_name(test_session, simple_video, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_file_name(test_session, simple_video, async_client):
|
||||
"""If a Video has no title, the front-end can use the file name as the title."""
|
||||
_, resp = test_client.get(f'/api/videos/video/{simple_video.id}')
|
||||
_, resp = await async_client.get(f'/api/videos/video/{simple_video.id}')
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json['file_group']['video']['video_path'] == 'simple_video.mp4'
|
||||
assert resp.json['file_group']['video'].get('stem') == 'simple_video'
|
||||
|
|
@ -165,20 +168,21 @@ async def test_channel_conflicts(async_client, test_session, test_directory):
|
|||
'message': 'Could not validate the contents of the request'}
|
||||
|
||||
|
||||
def test_channel_empty_url_doesnt_conflict(test_client, test_session, test_directory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_empty_url_doesnt_conflict(async_client, test_session, test_directory):
|
||||
"""Two channels with empty URLs shouldn't conflict"""
|
||||
channel_directory = tempfile.TemporaryDirectory(dir=test_directory).name
|
||||
pathlib.Path(channel_directory).mkdir()
|
||||
|
||||
new_channel = dict(name='Fooz', directory=channel_directory)
|
||||
request, response = test_client.post('/api/videos/channels', json=new_channel)
|
||||
request, response = await async_client.post('/api/videos/channels', json=new_channel)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.json
|
||||
location = response.headers['Location']
|
||||
|
||||
channel_directory2 = tempfile.TemporaryDirectory(dir=test_directory).name
|
||||
pathlib.Path(channel_directory2).mkdir()
|
||||
new_channel = dict(name='Barz', directory=channel_directory2)
|
||||
request, response = test_client.post('/api/videos/channels', json=new_channel)
|
||||
request, response = await async_client.post('/api/videos/channels', json=new_channel)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.json
|
||||
assert location != response.headers['Location']
|
||||
|
||||
|
|
@ -235,11 +239,12 @@ async def test_channel_download_requires_refresh(
|
|||
assert list(events_history) == []
|
||||
|
||||
|
||||
def test_channel_post_directory(test_session, test_client, test_directory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_post_directory(test_session, async_client, test_directory):
|
||||
"""A Channel can be created with or without an existing directory."""
|
||||
# Channel can be created with a directory which is not on disk.
|
||||
data = dict(name='foo', directory='foo')
|
||||
request, response = test_client.post('/api/videos/channels', content=json.dumps(data))
|
||||
request, response = await async_client.post('/api/videos/channels', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
directory = test_session.query(Channel).filter_by(id=1).one().directory
|
||||
assert (test_directory / 'foo') == directory
|
||||
|
|
@ -247,8 +252,9 @@ def test_channel_post_directory(test_session, test_client, test_directory):
|
|||
assert directory.is_absolute()
|
||||
|
||||
|
||||
def test_channel_by_id(test_session, test_client, simple_channel, simple_video):
|
||||
request, response = test_client.get(f'/api/videos/channels/{simple_channel.id}')
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_by_id(test_session, async_client, simple_channel, simple_video):
|
||||
request, response = await async_client.get(f'/api/videos/channels/{simple_channel.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
|
||||
|
|
@ -334,10 +340,20 @@ async def test_change_channel_url(async_client, test_session, test_download_mana
|
|||
assert channel.url == 'https://example.com/new-url', "Channel's URL was not changed."
|
||||
|
||||
|
||||
def test_search_videos_channel(test_client, test_session, video_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_videos_channel(async_client, test_session, video_factory, test_directory):
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
channel1 = Channel(name='Foo')
|
||||
channel2 = Channel(name='Bar')
|
||||
# Create Collections first
|
||||
collection1 = Collection(name='Foo', kind='channel', directory=test_directory / 'foo')
|
||||
collection2 = Collection(name='Bar', kind='channel', directory=test_directory / 'bar')
|
||||
session.add_all([collection1, collection2])
|
||||
session.flush()
|
||||
|
||||
# Create Channels linked to Collections
|
||||
channel1 = Channel(collection_id=collection1.id)
|
||||
channel2 = Channel(collection_id=collection2.id)
|
||||
session.add(channel1)
|
||||
session.add(channel2)
|
||||
session.flush()
|
||||
|
|
@ -346,7 +362,7 @@ def test_search_videos_channel(test_client, test_session, video_factory):
|
|||
|
||||
# Channels don't have videos yet
|
||||
d = dict(channel_id=channel1.id)
|
||||
request, response = test_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
request, response = await async_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['file_groups']) == 0
|
||||
|
||||
|
|
@ -357,19 +373,19 @@ def test_search_videos_channel(test_client, test_session, video_factory):
|
|||
session.add(vid2)
|
||||
|
||||
# Videos are gotten by their respective channels
|
||||
request, response = test_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
request, response = await async_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['file_groups']) == 1
|
||||
assert response.json['totals']['file_groups'] == 1
|
||||
assert_dict_contains(response.json['file_groups'][0],
|
||||
dict(primary_path='vid2.mp4', video=dict(channel_id=channel1.id)))
|
||||
dict(primary_path='foo/vid2.mp4', video=dict(channel_id=channel1.id)))
|
||||
|
||||
d = dict(channel_id=channel2.id)
|
||||
request, response = test_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
request, response = await async_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['file_groups']) == 1
|
||||
assert_dict_contains(response.json['file_groups'][0],
|
||||
dict(primary_path='vid1.mp4', video=dict(channel_id=channel2.id)))
|
||||
dict(primary_path='bar/vid1.mp4', video=dict(channel_id=channel2.id)))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -413,35 +429,37 @@ async def test_channel_download_id(async_client, test_session, tag_factory, simp
|
|||
urls=['https://example.com/channel1'],
|
||||
tag_names=[tag.name],
|
||||
downloader=test_downloader.name,
|
||||
settings=dict(channel_id=simple_channel.id),
|
||||
settings=dict(),
|
||||
collection_id=simple_channel.collection_id,
|
||||
frequency=120,
|
||||
)
|
||||
request, response = await async_client.post(f'/api/download', json=body)
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
download = test_session.query(Download).one()
|
||||
assert download.url == 'https://example.com/channel1'
|
||||
assert download.channel_id == simple_channel.id
|
||||
assert download.collection_id == simple_channel.collection_id
|
||||
|
||||
# A Channel relationship can be removed from a Download.
|
||||
# A Collection relationship can be removed from a Download.
|
||||
body = dict(
|
||||
urls=['https://example.com/channel1'],
|
||||
tag_names=[tag.name],
|
||||
downloader=test_downloader.name,
|
||||
settings=dict(),
|
||||
collection_id=None,
|
||||
frequency=240,
|
||||
)
|
||||
request, response = await async_client.put(f'/api/download/{download.id}', json=body)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
download = test_session.query(Download).one()
|
||||
assert download.channel_id is None
|
||||
assert download.collection_id is None
|
||||
assert download.frequency == 240
|
||||
|
||||
# A once-Download cannot be associated with a Channel.
|
||||
# A once-Download cannot be associated with a Collection.
|
||||
body = dict(
|
||||
urls=['https://example.com/channel1'],
|
||||
tag_names=[tag.name],
|
||||
downloader=test_downloader.name,
|
||||
settings=dict(channel_id=simple_channel.id),
|
||||
collection_id=simple_channel.collection_id,
|
||||
)
|
||||
request, response = await async_client.put(f'/api/download/{download.id}', json=body)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ from modules.videos.models import Video
|
|||
from wrolpi.downloader import Download, DownloadFrequency
|
||||
|
||||
|
||||
def test_delete_channel_no_url(test_session, test_client, channel_factory):
|
||||
def test_delete_channel_no_url(test_session, channel_factory):
|
||||
"""
|
||||
A Channel can be deleted even if it has no URL.
|
||||
"""
|
||||
|
|
@ -104,8 +104,16 @@ async def test_channel_download_relationships(test_session, download_channel):
|
|||
|
||||
|
||||
def test_channel_info_json(test_session, test_directory):
|
||||
channel = Channel(name='new channel')
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
# Create Collection first without directory
|
||||
collection = Collection(name='new channel', kind='channel')
|
||||
test_session.add(collection)
|
||||
test_session.flush()
|
||||
|
||||
channel = Channel(collection_id=collection.id)
|
||||
test_session.add(channel)
|
||||
test_session.flush()
|
||||
|
||||
with pytest.raises(FileNotFoundError) as e:
|
||||
# Cannot get info json because directory is not defined.
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ from wrolpi.dates import seconds_to_timestamp
|
|||
from wrolpi.db import get_db_session, get_db_curs
|
||||
from wrolpi.vars import DEFAULT_FILE_PERMISSIONS
|
||||
from .errors import ChannelNameConflict, ChannelURLConflict, ChannelDirectoryConflict, ChannelSourceIdConflict
|
||||
from .models import Channel
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
|
@ -52,6 +51,8 @@ def check_for_channel_conflicts(session: Session, id_=None, url=None, name=None,
|
|||
"""
|
||||
Search for any channels that conflict with the provided args, raise a relevant exception if any conflicts are found.
|
||||
"""
|
||||
from .models import Channel
|
||||
|
||||
if not any([id_, url, name, directory]):
|
||||
raise Exception('Cannot search for channel with no arguments')
|
||||
|
||||
|
|
@ -68,11 +69,13 @@ def check_for_channel_conflicts(session: Session, id_=None, url=None, name=None,
|
|||
if list(conflicts):
|
||||
raise ChannelURLConflict()
|
||||
if name:
|
||||
conflicts = base_where.filter(Channel.name == name)
|
||||
from wrolpi.collections import Collection
|
||||
conflicts = base_where.join(Collection).filter(Collection.name == name)
|
||||
if list(conflicts):
|
||||
raise ChannelNameConflict()
|
||||
if directory:
|
||||
conflicts = base_where.filter(Channel.directory == directory)
|
||||
from wrolpi.collections import Collection
|
||||
conflicts = base_where.join(Collection).filter(Collection.directory == directory)
|
||||
if list(conflicts):
|
||||
raise ChannelDirectoryConflict()
|
||||
if source_id:
|
||||
|
|
@ -269,6 +272,8 @@ def extract_video_duration(video_path: Path) -> Optional[int]:
|
|||
async def update_view_counts_and_censored(channel_id: int):
|
||||
"""Update view_count for all Videos in a channel using its info_json file. Also sets FileGroup.censored
|
||||
if Video is no longer available on the Channel."""
|
||||
from .models import Channel
|
||||
|
||||
with get_db_session() as session:
|
||||
channel: Channel = session.query(Channel).filter_by(id=channel_id).one()
|
||||
channel_name = channel.name
|
||||
|
|
@ -284,13 +289,14 @@ async def update_view_counts_and_censored(channel_id: int):
|
|||
with get_db_curs(commit=True) as curs:
|
||||
# Update the view_count for each video.
|
||||
stmt = '''
|
||||
WITH source AS (select * from json_to_recordset(%s::json) as (id text, view_count int))
|
||||
UPDATE video
|
||||
SET view_count = s.view_count
|
||||
FROM source as s
|
||||
WHERE source_id=s.id AND channel_id=%s
|
||||
RETURNING video.id AS updated_ids
|
||||
'''
|
||||
WITH source AS (select * from json_to_recordset(%s::json) as (id text, view_count int))
|
||||
UPDATE video
|
||||
SET view_count = s.view_count
|
||||
FROM source as s
|
||||
WHERE source_id = s.id
|
||||
AND channel_id = %s
|
||||
RETURNING video.id AS updated_ids \
|
||||
'''
|
||||
curs.execute(stmt, (view_counts_str, channel_id))
|
||||
count = len(curs.fetchall())
|
||||
logger.info(f'Updated {count} view counts in DB for {channel_name}.')
|
||||
|
|
@ -299,13 +305,13 @@ async def update_view_counts_and_censored(channel_id: int):
|
|||
with get_db_curs(commit=True) as curs:
|
||||
# Set FileGroup.censored if the video is no longer on the Channel.
|
||||
stmt = '''
|
||||
UPDATE file_group fg
|
||||
SET censored = NOT (v.source_id = ANY(%(source_ids)s))
|
||||
FROM video v
|
||||
WHERE v.file_group_id = fg.id
|
||||
AND v.channel_id = %(channel_id)s
|
||||
RETURNING fg.id, fg.censored
|
||||
'''
|
||||
UPDATE file_group fg
|
||||
SET censored = NOT (v.source_id = ANY (%(source_ids)s))
|
||||
FROM video v
|
||||
WHERE v.file_group_id = fg.id
|
||||
AND v.channel_id = %(channel_id)s
|
||||
RETURNING fg.id, fg.censored \
|
||||
'''
|
||||
curs.execute(stmt, {'channel_id': channel_id, 'source_ids': source_ids})
|
||||
censored = len([i for i in curs.fetchall() if i['censored']])
|
||||
logger.info(f'Set {censored} censored videos for {channel_name}.')
|
||||
|
|
|
|||
|
|
@ -22,11 +22,23 @@ from wrolpi.vars import PROJECT_DIR
|
|||
@pytest.fixture
|
||||
def simple_channel(test_session, test_directory) -> Channel:
|
||||
"""Get a Channel with the minimum properties. This Channel has no download!"""
|
||||
channel = Channel(
|
||||
directory=test_directory,
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
# Create Collection first
|
||||
collection = Collection(
|
||||
name='Simple Channel',
|
||||
kind='channel',
|
||||
directory=test_directory,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
# Create Channel linked to Collection
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/channel1',
|
||||
)
|
||||
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
return channel
|
||||
|
|
@ -36,21 +48,32 @@ def simple_channel(test_session, test_directory) -> Channel:
|
|||
def channel_factory(test_session, test_directory):
|
||||
"""Create a random Channel with a directory, and Download."""
|
||||
from wrolpi.tags import Tag
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
def factory(source_id: str = None, download_frequency: DownloadFrequency = None, url: str = None, name: str = None,
|
||||
directory: pathlib.Path = None, tag_name: str = None):
|
||||
name = name or str(uuid4())
|
||||
tag = Tag.find_by_name(tag_name) if tag_name else None
|
||||
channel = Channel(
|
||||
tag_name = tag.name if tag else None
|
||||
directory = directory or format_videos_destination(name, tag_name, url or f'https://example.com/{name}')
|
||||
directory.mkdir(exist_ok=True, parents=True)
|
||||
|
||||
# Create Collection first
|
||||
collection = Collection(
|
||||
name=name,
|
||||
url=url or f'https://example.com/{name}',
|
||||
source_id=source_id,
|
||||
tag=tag,
|
||||
kind='channel',
|
||||
directory=directory,
|
||||
tag_id=tag.id if tag else None,
|
||||
)
|
||||
tag_name = tag.name if tag else None
|
||||
channel.directory = directory or format_videos_destination(name, tag_name, channel.url)
|
||||
channel.directory.mkdir(exist_ok=True, parents=True)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
# Create Channel linked to Collection
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url=url or f'https://example.com/{name}',
|
||||
source_id=source_id,
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.flush([channel])
|
||||
test_session.add(Directory(path=channel.directory, name=channel.directory.name))
|
||||
|
|
@ -68,11 +91,25 @@ def channel_factory(test_session, test_directory):
|
|||
@pytest.fixture
|
||||
def download_channel(test_session, test_directory, video_download_manager) -> Channel:
|
||||
"""Get a test Channel that has a download frequency."""
|
||||
# Add a frequency to the test channel, then give it a download.
|
||||
channel = Channel(directory=test_directory, name='Download Channel', url='https://example.com/channel1',
|
||||
source_id='channel1')
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
# Create Collection first
|
||||
collection = Collection(
|
||||
name='Download Channel',
|
||||
kind='channel',
|
||||
directory=test_directory,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
# Create Channel linked to Collection
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/channel1',
|
||||
source_id='channel1',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.flush([channel, ])
|
||||
test_session.flush([channel])
|
||||
assert channel and channel.id and channel.url
|
||||
download = channel.get_or_create_download(channel.url, 60, test_session)
|
||||
assert download.url == channel.url
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import logging
|
|||
import os.path
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import traceback
|
||||
from abc import ABC
|
||||
from datetime import timedelta
|
||||
|
|
@ -208,7 +207,7 @@ class ChannelDownloader(Downloader, ABC):
|
|||
# The settings to send to the VideoDownloader.
|
||||
settings = dict()
|
||||
if channel:
|
||||
settings.update(dict(channel_id=channel.id, channel_url=download.url))
|
||||
settings.update(dict(collection_id=channel.collection_id, channel_url=download.url))
|
||||
if download.destination:
|
||||
destination = get_absolute_media_path(download.destination)
|
||||
settings['destination'] = str(destination) # Need str for JSON conversion
|
||||
|
|
@ -622,14 +621,20 @@ class VideoDownloader(Downloader, ABC):
|
|||
except UnknownChannel:
|
||||
# Destination must not be a channel.
|
||||
pass
|
||||
channel_id = download.channel_id
|
||||
# Look up Channel via Collection or channel_url from settings
|
||||
collection_id = download.collection_id
|
||||
channel_url = settings.get('channel_url')
|
||||
if not channel and (channel_id or channel_url):
|
||||
if not channel and (collection_id or channel_url):
|
||||
# Could not find Channel via yt-dlp info_json, use info from ChannelDownloader if it created this Download.
|
||||
logger.info(f'Using download.settings to find channel')
|
||||
try:
|
||||
channel = get_channel(channel_id=channel_id, url=channel_url, return_dict=False)
|
||||
logger.debug(f'Found channel with channel url {channel=}')
|
||||
# Find Channel by collection_id or URL
|
||||
if collection_id:
|
||||
with get_db_session() as session:
|
||||
channel = session.query(Channel).filter_by(collection_id=collection_id).one_or_none()
|
||||
if not channel and channel_url:
|
||||
channel = get_channel(url=channel_url, return_dict=False)
|
||||
logger.debug(f'Found channel with collection_id or channel url {channel=}')
|
||||
except UnknownChannel:
|
||||
# We do not need a Channel if we have a destination directory.
|
||||
if not destination:
|
||||
|
|
|
|||
|
|
@ -252,7 +252,6 @@ class ChannelsConfig(ConfigFile):
|
|||
self.update({'channels': value})
|
||||
|
||||
def import_config(self, file: pathlib.Path = None, send_events=False):
|
||||
from modules.videos.channel.lib import get_channel
|
||||
super().import_config()
|
||||
try:
|
||||
channels = self.channels
|
||||
|
|
@ -268,31 +267,8 @@ class ChannelsConfig(ConfigFile):
|
|||
for option in (i for i in REQUIRED_OPTIONS if i not in data):
|
||||
raise ConfigError(f'Channel "{directory}" is required to have "{option}"')
|
||||
|
||||
# Try to find Channel by directory because it is unique.
|
||||
channel = Channel.get_by_path(directory, session)
|
||||
if not channel:
|
||||
try:
|
||||
# Try to find Channel using other attributes before creating new Channel.
|
||||
channel = get_channel(
|
||||
session,
|
||||
source_id=data.get('source_id'),
|
||||
url=data.get('url'),
|
||||
directory=str(directory),
|
||||
return_dict=False,
|
||||
)
|
||||
except UnknownChannel:
|
||||
# Channel not yet in the DB, add it.
|
||||
channel = Channel(directory=directory)
|
||||
session.add(channel)
|
||||
channel.flush()
|
||||
# TODO refresh the files in the channel.
|
||||
logger.warning(f'Creating new Channel from config: {directory}')
|
||||
|
||||
# Copy existing channel data, update all values from the config. This is necessary to clear out
|
||||
# values not in the config.
|
||||
full_data = channel.dict()
|
||||
full_data.update(data)
|
||||
channel.update(full_data)
|
||||
# Create or update Channel from config (handles Collection creation)
|
||||
channel = Channel.from_config(data, session=session)
|
||||
updated_channel_ids.add(channel.id)
|
||||
|
||||
if not channel.source_id and channel.url and flags.have_internet.is_set():
|
||||
|
|
@ -519,8 +495,9 @@ def set_test_downloader_config(enabled: bool):
|
|||
|
||||
def get_channels_config_from_db(session: Session) -> dict:
|
||||
"""Create a dictionary that contains all the Channels from the DB."""
|
||||
channels = session.query(Channel).order_by(Channel.directory).all()
|
||||
channels = sorted((i.config_view() for i in channels), key=lambda i: i['directory'])
|
||||
from wrolpi.collections import Collection
|
||||
channels = session.query(Channel).join(Collection).order_by(Collection.directory).all()
|
||||
channels = sorted((i.config_view() for i in channels), key=lambda i: i['directory'] if i['directory'] else '')
|
||||
return dict(channels=channels)
|
||||
|
||||
|
||||
|
|
@ -572,9 +549,12 @@ def import_channels_config():
|
|||
|
||||
|
||||
def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel, download_: Type[Base] = Download):
|
||||
"""Create any missing Downloads for any Channel.url/Channel.directory that has a Download. Associate any Download
|
||||
related to a Channel."""
|
||||
# Only Downloads with a frequency can be a Channel Download.
|
||||
"""Associate any Download related to a Channel via its Collection.
|
||||
|
||||
Downloads are linked to Collections (via collection_id) rather than directly to Channels.
|
||||
This function finds Channels and links their Downloads to the Channel's Collection.
|
||||
"""
|
||||
# Only Downloads with a frequency can be a Collection Download.
|
||||
downloads = list(session.query(download_).filter(download_.frequency.isnot(None)).all())
|
||||
# Download.url is unique and cannot be null.
|
||||
downloads_by_url = {i.url: i for i in downloads}
|
||||
|
|
@ -586,26 +566,27 @@ def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel,
|
|||
for channel in channels:
|
||||
directory = str(channel.directory)
|
||||
for download in downloads_with_destination:
|
||||
if download.settings['destination'] == directory and not download.channel_id:
|
||||
download.channel_id = channel.id
|
||||
if download.settings['destination'] == directory and not download.collection_id:
|
||||
download.collection_id = channel.collection_id
|
||||
need_commit = True
|
||||
|
||||
download = downloads_by_url.get(channel.url)
|
||||
if download and not download.channel_id:
|
||||
download.channel_id = channel.id
|
||||
if download and not download.collection_id:
|
||||
download.collection_id = channel.collection_id
|
||||
need_commit = True
|
||||
|
||||
# Get any Downloads for a Channel's RSS feed.
|
||||
rss_url = channel.get_rss_url()
|
||||
if rss_url and (download := downloads_by_url.get(rss_url)):
|
||||
download.channel_id = channel.id
|
||||
need_commit = True
|
||||
if not download.collection_id:
|
||||
download.collection_id = channel.collection_id
|
||||
need_commit = True
|
||||
|
||||
# Associate any Download which shares a Channel's URL.
|
||||
for download in downloads:
|
||||
channel = channel_.get_by_url(download.url, session)
|
||||
if channel and not download.channel_id:
|
||||
download.channel_id = channel.id
|
||||
if channel and not download.collection_id:
|
||||
download.collection_id = channel.collection_id
|
||||
need_commit = True
|
||||
|
||||
if need_commit:
|
||||
|
|
@ -676,10 +657,11 @@ async def get_statistics():
|
|||
if monthly_videos else 0
|
||||
|
||||
curs.execute('''
|
||||
SELECT COUNT(c.id) AS "channels",
|
||||
COUNT(c.id) FILTER ( WHERE c.tag_id IS NOT NULL ) AS "tagged_channels"
|
||||
SELECT COUNT(c.id) AS "channels",
|
||||
COUNT(c.id) FILTER ( WHERE col.tag_id IS NOT NULL ) AS "tagged_channels"
|
||||
FROM channel c
|
||||
LEFT JOIN public.tag t on t.id = c.tag_id
|
||||
LEFT JOIN collection col on col.id = c.collection_id
|
||||
LEFT JOIN public.tag t on t.id = col.tag_id
|
||||
''')
|
||||
channel_stats = dict(curs.fetchone())
|
||||
ret = dict(statistics=dict(
|
||||
|
|
|
|||
|
|
@ -531,9 +531,8 @@ class Video(ModelHelper, Base):
|
|||
class Channel(ModelHelper, Base):
|
||||
__tablename__ = 'channel'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String)
|
||||
# name and directory are stored in Collection, accessed via properties
|
||||
url = Column(String, unique=True) # will only be downloaded if related Download exists.
|
||||
directory: pathlib.Path = Column(MediaPathType)
|
||||
generate_posters = Column(Boolean, default=False) # generating posters may delete files, and can be slow.
|
||||
calculate_duration = Column(Boolean, default=True) # use ffmpeg to extract duration (slower than info json).
|
||||
download_missing_data = Column(Boolean, default=True) # fetch missing data like `source_id` and video comments.
|
||||
|
|
@ -549,16 +548,65 @@ class Channel(ModelHelper, Base):
|
|||
info_date = Column(Date)
|
||||
|
||||
videos: InstrumentedList = relationship('Video', primaryjoin='Channel.id==Video.channel_id')
|
||||
downloads: InstrumentedList = relationship('Download', primaryjoin='Download.channel_id==Channel.id')
|
||||
tag_id = Column(Integer, ForeignKey('tag.id', ondelete='CASCADE'))
|
||||
tag = relationship('Tag', primaryjoin='Channel.tag_id==Tag.id')
|
||||
collection_id = Column(Integer, ForeignKey('collection.id', ondelete='CASCADE'))
|
||||
collection = relationship('Collection', foreign_keys=[collection_id])
|
||||
|
||||
@property
|
||||
def downloads(self) -> InstrumentedList:
|
||||
"""Get downloads from associated Collection."""
|
||||
return self.collection.downloads if self.collection else []
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Channel id={self.id} name={repr(self.name)} url={self.url} directory={self.directory}>'
|
||||
|
||||
@property
|
||||
def name(self) -> str | None:
|
||||
"""Delegate name to Collection"""
|
||||
return self.collection.name if self.collection else None
|
||||
|
||||
@name.setter
|
||||
def name(self, value: str):
|
||||
"""Set name on Collection"""
|
||||
if self.collection:
|
||||
self.collection.name = value
|
||||
|
||||
@property
|
||||
def directory(self) -> pathlib.Path | None:
|
||||
"""Delegate directory to Collection"""
|
||||
return self.collection.directory if self.collection else None
|
||||
|
||||
@directory.setter
|
||||
def directory(self, value: pathlib.Path | str):
|
||||
"""Set directory on Collection"""
|
||||
if self.collection:
|
||||
self.collection.directory = value
|
||||
|
||||
@property
|
||||
def tag(self):
|
||||
"""Delegate tag to Collection"""
|
||||
return self.collection.tag if self.collection else None
|
||||
|
||||
@tag.setter
|
||||
def tag(self, value):
|
||||
"""Set tag on Collection"""
|
||||
if self.collection:
|
||||
self.collection.tag = value
|
||||
|
||||
@property
|
||||
def tag_id(self) -> int | None:
|
||||
"""Delegate tag_id to Collection"""
|
||||
return self.collection.tag_id if self.collection else None
|
||||
|
||||
@tag_id.setter
|
||||
def tag_id(self, value: int):
|
||||
"""Set tag_id on Collection"""
|
||||
if self.collection:
|
||||
self.collection.tag_id = value
|
||||
|
||||
@property
|
||||
def tag_name(self) -> str | None:
|
||||
return self.tag.name if self.tag else None
|
||||
"""Delegate tag_name to Collection"""
|
||||
return self.collection.tag_name if self.collection else None
|
||||
|
||||
@property
|
||||
def location(self) -> str:
|
||||
|
|
@ -597,7 +645,7 @@ class Channel(ModelHelper, Base):
|
|||
data = data.copy()
|
||||
|
||||
# URL should not be empty string.
|
||||
url = data.pop('url')
|
||||
url = data.pop('url', None)
|
||||
self.url = url or None
|
||||
|
||||
session: Session = Session.object_session(self)
|
||||
|
|
@ -637,7 +685,7 @@ class Channel(ModelHelper, Base):
|
|||
continue
|
||||
|
||||
download = self.get_or_create_download(url, frequency, session=session, reset_attempts=True)
|
||||
download.channel_id = channel_id
|
||||
download.collection_id = self.collection_id
|
||||
session.add(download)
|
||||
|
||||
def config_view(self) -> dict:
|
||||
|
|
@ -657,13 +705,62 @@ class Channel(ModelHelper, Base):
|
|||
)
|
||||
return config
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, data: dict, session: Session = None) -> 'Channel':
|
||||
"""
|
||||
Create or update a Channel from config data. This also creates/updates the Collection.
|
||||
|
||||
Args:
|
||||
data: Config dict containing channel metadata (name, directory, url, source_id, etc.)
|
||||
session: Database session
|
||||
|
||||
Returns:
|
||||
The created or updated Channel
|
||||
"""
|
||||
from wrolpi.collections import Collection
|
||||
from wrolpi.db import get_db_session
|
||||
|
||||
if session is None:
|
||||
session = get_db_session()
|
||||
|
||||
# Ensure this is treated as a channel collection
|
||||
data = data.copy()
|
||||
data['kind'] = 'channel'
|
||||
|
||||
# Create or update the Collection first
|
||||
collection = Collection.from_config(data, session=session)
|
||||
|
||||
# Extract Channel-specific fields
|
||||
url = data.get('url')
|
||||
source_id = data.get('source_id')
|
||||
|
||||
# Find existing Channel by collection_id or create new one
|
||||
channel = session.query(cls).filter_by(collection_id=collection.id).one_or_none()
|
||||
|
||||
if not channel:
|
||||
# Create new Channel
|
||||
channel = cls(
|
||||
collection_id=collection.id,
|
||||
url=url,
|
||||
source_id=source_id,
|
||||
)
|
||||
session.add(channel)
|
||||
session.flush([channel])
|
||||
|
||||
# Use the update() method to handle all fields including downloads
|
||||
channel.update(data)
|
||||
|
||||
return channel
|
||||
|
||||
@staticmethod
|
||||
def get_by_path(path: pathlib.Path, session: Session) -> Optional['Channel']:
|
||||
if not path:
|
||||
raise RuntimeError('Must provide path to get Channel')
|
||||
path = pathlib.Path(path) if isinstance(path, str) else path
|
||||
path = str(path.absolute()) if path.is_absolute() else str(get_media_directory() / path)
|
||||
channel = session.query(Channel).filter_by(directory=path).one_or_none()
|
||||
# Query through Collection relationship since directory is now on Collection
|
||||
from wrolpi.collections import Collection
|
||||
channel = session.query(Channel).join(Collection).filter(Collection.directory == path).one_or_none()
|
||||
return channel
|
||||
|
||||
def __json__(self) -> dict:
|
||||
|
|
@ -679,6 +776,8 @@ class Channel(ModelHelper, Base):
|
|||
|
||||
def dict(self, with_statistics: bool = False, with_downloads: bool = True) -> dict:
|
||||
d = super(Channel, self).dict()
|
||||
# Add Collection-delegated properties
|
||||
d['name'] = self.name
|
||||
d['tag_name'] = self.tag_name
|
||||
d['rss_url'] = self.get_rss_url()
|
||||
d['directory'] = \
|
||||
|
|
@ -777,26 +876,17 @@ class Channel(ModelHelper, Base):
|
|||
reset_attempts: bool = False) -> Download:
|
||||
"""Get a Download record, if it does not exist, create it. Create a Download if necessary
|
||||
which goes into this Channel's directory.
|
||||
"""
|
||||
if not isinstance(url, str) or not url:
|
||||
raise InvalidDownload(f'Cannot get Download without url')
|
||||
if not frequency:
|
||||
raise InvalidDownload('Download for Channel must have a frequency')
|
||||
|
||||
Delegates to Collection.get_or_create_download() with Channel-specific downloaders.
|
||||
"""
|
||||
from modules.videos.downloader import ChannelDownloader, VideoDownloader
|
||||
|
||||
download = Download.get_by_url(url, session=session)
|
||||
if not download:
|
||||
download = download_manager.recurring_download(url, frequency, ChannelDownloader.name, session=session,
|
||||
sub_downloader_name=VideoDownloader.name,
|
||||
destination=self.directory,
|
||||
reset_attempts=reset_attempts,
|
||||
)
|
||||
if reset_attempts:
|
||||
download.attempts = 0
|
||||
download.channel_id = self.id
|
||||
|
||||
return download
|
||||
return self.collection.get_or_create_download(
|
||||
url, frequency, session=session,
|
||||
reset_attempts=reset_attempts,
|
||||
downloader_name=ChannelDownloader.name,
|
||||
sub_downloader_name=VideoDownloader.name
|
||||
)
|
||||
|
||||
def get_rss_url(self) -> str | None:
|
||||
"""Return the RSS Feed URL for this Channel, if any is possible."""
|
||||
|
|
|
|||
|
|
@ -43,8 +43,9 @@ async def test_refresh_videos_index(async_client, test_session, test_directory,
|
|||
assert not video.file_group.d_text, 'Video captions were not removed'
|
||||
|
||||
|
||||
def test_refresh_videos(test_client, test_session, test_directory, simple_channel, video_factory, video_file_factory,
|
||||
image_bytes_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_videos(async_client, test_session, test_directory, simple_channel, video_factory,
|
||||
video_file_factory, image_bytes_factory):
|
||||
subdir = test_directory / 'subdir'
|
||||
subdir.mkdir()
|
||||
|
||||
|
|
@ -81,7 +82,7 @@ def test_refresh_videos(test_client, test_session, test_directory, simple_channe
|
|||
stmt = "INSERT INTO video (file_group_id) values (%(video_id)s)"
|
||||
curs.execute(stmt, {'video_id': str(video4_id)})
|
||||
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
|
||||
test_session.expire_all()
|
||||
|
||||
|
|
@ -104,12 +105,13 @@ def test_refresh_videos(test_client, test_session, test_directory, simple_channe
|
|||
# Remove video1's poster, video1 should be updated.
|
||||
video1_video_path = str(video1.video_path)
|
||||
video1.poster_path.unlink()
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
video1 = Video.get_by_path(video1_video_path, test_session)
|
||||
assert not video1.poster_path
|
||||
|
||||
|
||||
def test_channels_with_videos(test_session, test_client, test_directory, channel_factory, video_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_channels_with_videos(test_session, async_client, test_directory, channel_factory, video_factory):
|
||||
channel1 = channel_factory('channel1', name='channel1')
|
||||
channel2 = channel_factory('channel2', name='channel2')
|
||||
vid1 = video_factory(channel_id=channel1.id, with_video_file=True)
|
||||
|
|
@ -132,10 +134,12 @@ def test_channels_with_videos(test_session, test_client, test_directory, channel
|
|||
assert vid2_path.is_file(), 'Video file was deleted'
|
||||
assert vid3_path.is_file(), 'Video file was deleted'
|
||||
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
|
||||
assert test_session.query(Video).count() == 3, 'Did not find correct amount of video files.'
|
||||
assert {i[0] for i in test_session.query(Channel.name)} == {'channel1', 'channel2'}, 'Channels were changed.'
|
||||
from wrolpi.collections import Collection
|
||||
assert {i[0] for i in test_session.query(Collection.name).join(Channel).filter(Collection.kind == 'channel')} == {
|
||||
'channel1', 'channel2'}, 'Channels were changed.'
|
||||
|
||||
vid1 = Video.get_by_path(vid1_path)
|
||||
vid2 = Video.get_by_path(vid2_path)
|
||||
|
|
@ -146,11 +150,12 @@ def test_channels_with_videos(test_session, test_client, test_directory, channel
|
|||
assert vid3.channel is None
|
||||
|
||||
|
||||
def test_api_download(test_session, test_client, test_directory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_download(test_session, async_client, test_directory):
|
||||
"""A video can be downloaded."""
|
||||
content = dict(urls=['https://example.com/video1', ], downloader='video', destination='dest',
|
||||
settings=dict(excluded_urls='example.com'))
|
||||
request, response = test_client.post('/api/download', content=json.dumps(content))
|
||||
request, response = await async_client.post('/api/download', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
|
|
@ -364,7 +369,8 @@ async def test_video_file_format(async_client, test_session, fake_now):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_upload_file_tracking(test_session, async_client, video_factory, await_switches, make_multipart_form,
|
||||
async def test_video_upload_file_tracking(test_session, async_client, video_factory, await_switches,
|
||||
make_multipart_form,
|
||||
image_bytes_factory):
|
||||
"""Test that uploading info.json, poster, and caption files via /api/files/upload properly tracks them in Video and FileGroup."""
|
||||
from wrolpi.common import get_relative_to_media_directory
|
||||
|
|
|
|||
|
|
@ -257,6 +257,11 @@ async def test_import_channel_delete_missing_channels(await_switches, test_sessi
|
|||
channel1 = channel_factory(source_id='foo')
|
||||
channel2 = channel_factory(source_id='bar')
|
||||
test_session.commit()
|
||||
|
||||
# Capture directory values before deletion (channels will be detached after deletion)
|
||||
channel1_dir = str(channel1.directory)
|
||||
channel2_dir = str(channel2.directory)
|
||||
|
||||
# Write Channels to the config file.
|
||||
save_channels_config()
|
||||
test_session.delete(channel1)
|
||||
|
|
@ -267,29 +272,29 @@ async def test_import_channel_delete_missing_channels(await_switches, test_sessi
|
|||
# Importing the config creates two Channels.
|
||||
import_channels_config()
|
||||
assert len(test_session.query(Channel).all()) == 2
|
||||
assert str(channel1.directory) in test_channels_config.read_text()
|
||||
assert str(channel2.directory) in test_channels_config.read_text()
|
||||
assert channel1_dir in test_channels_config.read_text()
|
||||
assert channel2_dir in test_channels_config.read_text()
|
||||
|
||||
# Delete channel2 from the config file.
|
||||
config = get_channels_config()
|
||||
config_dict = config.dict()
|
||||
config_dict['channels'] = [i for i in config.channels if i['directory'] != str(channel2.directory)]
|
||||
config_dict['channels'] = [i for i in config.channels if i['directory'] != channel2_dir]
|
||||
config.update(config_dict)
|
||||
await await_switches()
|
||||
assert str(channel1.directory) in test_channels_config.read_text()
|
||||
assert str(channel2.directory) not in test_channels_config.read_text()
|
||||
assert channel1_dir in test_channels_config.read_text()
|
||||
assert channel2_dir not in test_channels_config.read_text()
|
||||
|
||||
# Importing the config deletes the Channel record.
|
||||
import_channels_config()
|
||||
assert len(test_session.query(Channel).all()) == 1
|
||||
assert str(channel1.directory) in test_channels_config.read_text()
|
||||
assert str(channel2.directory) not in test_channels_config.read_text()
|
||||
assert channel1_dir in test_channels_config.read_text()
|
||||
assert channel2_dir not in test_channels_config.read_text()
|
||||
|
||||
# Saving and importing does not change anything.
|
||||
save_channels_config()
|
||||
import_channels_config()
|
||||
assert str(channel1.directory) in test_channels_config.read_text()
|
||||
assert str(channel2.directory) not in test_channels_config.read_text()
|
||||
assert channel1_dir in test_channels_config.read_text()
|
||||
assert channel2_dir not in test_channels_config.read_text()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
|
|||
|
|
@ -173,7 +173,7 @@ async def test_download_channel(test_session, test_directory, simple_channel, vi
|
|||
downloads = video_download_manager.get_once_downloads(test_session)
|
||||
assert {i.url for i in downloads} == {'https://youtube.com/watch?v=video_2_url'}
|
||||
assert downloads[0].settings == {
|
||||
'channel_id': 1,
|
||||
'collection_id': simple_channel.collection_id,
|
||||
'channel_url': 'https://www.youtube.com/c/LearningSelfReliance/videos',
|
||||
'destination': str(test_directory),
|
||||
}
|
||||
|
|
@ -191,7 +191,7 @@ async def test_download_channel(test_session, test_directory, simple_channel, vi
|
|||
downloads = video_download_manager.get_once_downloads(test_session)
|
||||
assert {i.url for i in downloads} == {'https://youtube.com/watch?v=video_1_url'}
|
||||
assert downloads[0].settings == {
|
||||
'channel_id': 1,
|
||||
'collection_id': simple_channel.collection_id,
|
||||
'channel_url': 'https://www.youtube.com/c/LearningSelfReliance/videos',
|
||||
'destination': str(test_directory),
|
||||
}
|
||||
|
|
@ -203,13 +203,23 @@ async def test_get_or_create_channel(async_client, test_session, test_directory,
|
|||
|
||||
Attempt to use an existing Channel if we can match it.
|
||||
"""
|
||||
from wrolpi.collections import Collection
|
||||
one, two = await tag_factory(), await tag_factory()
|
||||
|
||||
c1 = Channel(name='foo', source_id='foo', url='https://example.com')
|
||||
c2 = Channel(name='bar', source_id='bar')
|
||||
c3 = Channel(name='baz', source_id='baz', url='https://example.net')
|
||||
c4 = Channel(name='qux')
|
||||
test_session.add_all([c1, c2, c3, c4])
|
||||
# Create Collections for each Channel
|
||||
def create_channel_with_collection(name, source_id=None, url=None):
|
||||
collection = Collection(name=name, kind='channel')
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
channel = Channel(collection_id=collection.id, source_id=source_id, url=url)
|
||||
test_session.add(channel)
|
||||
test_session.flush([channel])
|
||||
return channel
|
||||
|
||||
c1 = create_channel_with_collection('foo', source_id='foo', url='https://example.com')
|
||||
c2 = create_channel_with_collection('bar', source_id='bar')
|
||||
c3 = create_channel_with_collection('baz', source_id='baz', url='https://example.net')
|
||||
c4 = create_channel_with_collection('qux')
|
||||
test_session.commit()
|
||||
|
||||
# All existing channels should be used.
|
||||
|
|
@ -549,7 +559,8 @@ def test_normalize_video_file_names(test_directory, video_download_manager):
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_download_cookies(test_session, test_directory, mock_video_extract_info, await_switches,
|
||||
video_download_manager, mock_video_process_runner, image_file, test_videos_downloader_config):
|
||||
video_download_manager, mock_video_process_runner, image_file,
|
||||
test_videos_downloader_config):
|
||||
config = get_videos_downloader_config()
|
||||
|
||||
config.browser_profile = str(test_directory / 'firefox/some directory')
|
||||
|
|
@ -577,7 +588,8 @@ async def test_video_download_cookies(test_session, test_directory, mock_video_e
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_download_always_use_cookies(test_session, test_directory, mock_video_extract_info, await_switches,
|
||||
video_download_manager, mock_video_process_runner, image_file, test_videos_downloader_config):
|
||||
video_download_manager, mock_video_process_runner, image_file,
|
||||
test_videos_downloader_config):
|
||||
config = get_videos_downloader_config()
|
||||
|
||||
config.always_use_browser_profile = True
|
||||
|
|
|
|||
|
|
@ -191,13 +191,13 @@ def test_link_channel_and_downloads(test_session, channel_factory, test_download
|
|||
test_session.add_all([download1, download2, download3])
|
||||
test_session.commit()
|
||||
assert test_session.query(Download).count() == 3
|
||||
assert not any(i.channel_id for i in test_download_manager.get_downloads(test_session))
|
||||
assert not any(i.collection_id for i in test_download_manager.get_downloads(test_session))
|
||||
|
||||
# `link_channel_and_downloads` creates missing Downloads.
|
||||
# `link_channel_and_downloads` links Downloads to Collections.
|
||||
lib.link_channel_and_downloads(session=test_session)
|
||||
assert test_session.query(Download).count() == 3
|
||||
assert all(i.channel_id for i in test_download_manager.get_recurring_downloads(test_session))
|
||||
assert not any(i.channel_id for i in test_download_manager.get_once_downloads(test_session))
|
||||
assert all(i.collection_id for i in test_download_manager.get_recurring_downloads(test_session))
|
||||
assert not any(i.collection_id for i in test_download_manager.get_once_downloads(test_session))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -233,13 +233,13 @@ def test_link_channel_and_downloads_migration(async_client, test_session, channe
|
|||
assert test_session.query(Download).count() == 4
|
||||
d1, d2a, d2b, d2c = test_session.query(Download).order_by(Download.url).all()
|
||||
assert d1.url == channel1.url == 'https://example.com/channel1' and d1.frequency == 1
|
||||
assert d1.channel_id
|
||||
assert d1.collection_id == channel1.collection_id
|
||||
assert d2a.url == 'https://example.com/channel2' and d2a.frequency == 1
|
||||
assert d2a.channel_id
|
||||
assert d2a.collection_id == channel2.collection_id
|
||||
assert d2b.url == 'https://example.com/channel2/rss' and d2b.frequency == 1
|
||||
assert d2b.channel_id
|
||||
assert d2b.collection_id == channel2.collection_id
|
||||
assert d2c.url == 'https://example.com/channel2/video/1' and d2c.frequency is None
|
||||
assert not d2c.channel_id
|
||||
assert not d2c.collection_id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue