mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 20:06:22 -05:00
* Squashed commit of the following:
commit c527475fcb4d4906457be5c10f0e9c6dee7fedc1
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 22:16:36 2021 -0700
Only saving a favorite video to the config if it has a source_id.
commit ae8b712ebeaef467b8d5a5b87ca0f4f276373a0d
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 22:14:26 2021 -0700
Ading description and changing Save button to Download.
commit 03a72be6dfdfa383915950a80e3f1ee9febf6705
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 22:09:44 2021 -0700
Removing uploader for now.
commit 5d0231284bf84e459687f6ab903b06bf4e3762bd
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 22:07:17 2021 -0700
Removing unique data from example info.
commit 9cc721a32d4715d9d6433e51db3b35e039c78d68
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 22:02:33 2021 -0700
Updating downloader tests.
commit 8e193b03349ae4613f105418cd3e8176c7101304
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 21:53:31 2021 -0700
Toasting error when WROL Mode is enabled. Disabling new downloads during WROL Mode.
commit 48c4311c31db8f2d2c8dd0a65f979a5f0a49a911
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 21:45:06 2021 -0700
Raising error if download exits without a 0. Clearing kill event when starting a new download.
commit 54ba3a890d59facc837410d34bf7afb40db3b685
Author: Roland <roland@learningselfreliance.com>
Date: Tue Dec 14 21:16:46 2021 -0700
Downloads can be restarted and killed.
commit bd60751262247259c3e9ceb5116e017d6314c219
Author: Roland <roland@learningselfreliance.com>
Date: Mon Dec 13 16:28:18 2021 -0700
Downloads can be started again. Downloads are sorted on Downloads page.
commit ea7f39231b92982ae0b263b76c5bd1902cc8169d
Author: Roland <roland@learningselfreliance.com>
Date: Sat Dec 11 21:24:16 2021 -0700
Building Downloads tab.
commit d3321872ac3743ff6df781b07ef0fb537f1d4c98
Author: Roland <roland@learningselfreliance.com>
Date: Sat Dec 11 20:41:46 2021 -0700
Not scheduling channels withtout a URL/frequency.
commit 84f268a0d4f58c85f86b6377900492e0766f6619
Author: Roland <roland@learningselfreliance.com>
Date: Sat Dec 11 19:56:08 2021 -0700
Channel downloads will be spread out when each channel is created.
commit 26fa6beea38ef3f8d6b7bf218f18222a51a87a60
Author: Roland <roland@learningselfreliance.com>
Date: Sat Dec 11 13:08:11 2021 -0700
Recurring downloads are renewed on startup.
commit fc2ab850533f1c3ad073f4692c7dea2be43e85d6
Author: Roland <roland@learningselfreliance.com>
Date: Fri Dec 10 17:03:57 2021 -0700
Fetching download again after do_download.
commit fdadad327fc09c17a49eb63b11e632fb72cc3195
Author: Roland <roland@learningselfreliance.com>
Date: Fri Dec 10 16:20:51 2021 -0700
Fixing error with test. Mock was not being reset.
commit 070dee238e53377acd22097c63cf3794e68ed423
Author: Roland <roland@learningselfreliance.com>
Date: Fri Dec 10 15:36:39 2021 -0700
Fixed bug in date handling (big surprise).
commit e53a8992268d68620c679455adaec3a590f20602
Author: Roland <roland@learningselfreliance.com>
Date: Wed Dec 1 16:48:36 2021 -0700
Using chunks for regular channel refresh.
commit 3bd60c58d1bef0226325f321978c0434b36b3be5
Author: Roland <roland@learningselfreliance.com>
Date: Wed Dec 1 15:22:02 2021 -0700
Reformatting.
commit 4fdc325f25a32c311ca6543fe321624b2bd564b2
Author: Roland <roland@learningselfreliance.com>
Date: Wed Dec 1 15:13:34 2021 -0700
Creating function that refreshes NO CHANNEL videos.
commit d67feafb6c2994f5a4a1295920a70db369cc6816
Author: Roland <roland@learningselfreliance.com>
Date: Wed Dec 1 14:35:54 2021 -0700
Removing unused functions.
commit 6b3918e4e78fbac64920f85c4de0df873ec366a1
Author: Roland <roland@learningselfreliance.com>
Date: Wed Dec 1 14:31:48 2021 -0700
Removing reporter and events. This will be replaced in the future with some sort of SSE.
commit 54fa1b0f5e93ca25c80b780dcdc3876b700273b1
Author: Roland <roland@learningselfreliance.com>
Date: Sun Nov 28 17:55:43 2021 -0700
Better error handling for archive button.
commit c31d124e511b27f626ed2df71486d47302b396f3
Author: Roland <roland@learningselfreliance.com>
Date: Sun Nov 28 17:29:43 2021 -0700
Displaying View Count in a human readable format.
commit 0ee2bd65588fd93b475cad6144e76f1b45191b39
Author: Roland <roland@learningselfreliance.com>
Date: Sat Nov 27 09:29:41 2021 -0700
Fixing tests.
commit e64aff32bab95c311ea3747e1a21b58b99750d5e
Author: Roland <roland@learningselfreliance.com>
Date: Sat Nov 27 08:59:51 2021 -0700
Handling when a Video has no Channel in UI.
commit b9549ecd5aac03c002adca7b7667f0a7189b662a
Author: Roland <roland@learningselfreliance.com>
Date: Fri Nov 26 08:35:36 2021 -0700
Downloaders can raise UnrecoverableDownloadError to signal a downlaod should not be retried.
commit da88798e2584d3e84900a70e34166c8c208c64fb
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 20:40:29 2021 -0700
Downloaders can refuse a download, which will then be deleted.
commit b865d856121db5ec8a3660c5d3c13b9846fde688
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 19:35:43 2021 -0700
Removing relative path handling.
commit 6d7757870b02ba030d78b3ef7e43f28b906eea61
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 19:28:27 2021 -0700
Using __json__ for Video and Channel models.
commit 649e4d6a61608272759d1e7ee02b490bb5c20b3e
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 18:23:38 2021 -0700
Fixing video links in UI.
commit 9d081af12742070b8519bd752812130cb5dbe393
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 14:42:38 2021 -0700
Fixing docs.
commit 1202cbe0f9ae744d7801b53a5071cded8ea39924
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 14:40:36 2021 -0700
Fixing wrolpi tests.
commit 3f6af8cc1123f2f63a3fc0f21ec4d994c642cf13
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 24 14:13:35 2021 -0700
Fixing tests to use MediaPath.
commit faec04f2a5e4c267a502c03884940a9c5bcfe387
Author: Roland <roland@learningselfreliance.com>
Date: Fri Nov 19 10:21:20 2021 -0700
Testing when a video has no channel.
commit cbf22aad7a0b72e61685e0236e843554b57c4af1
Author: Roland <roland@learningselfreliance.com>
Date: Thu Nov 18 16:24:03 2021 -0700
Using MediaPath for Video and Channel models. Testing VideoDownloader.do_download.
commit 7916ed61e43439e6cd60f23ce3fdf6c1a75bf02d
Author: Roland <roland@learningselfreliance.com>
Date: Thu Nov 18 12:43:44 2021 -0700
Channels/Videos downloaders can get gotten.
commit 808ef796cec01db6e7009065f9e26d25d9500ce2
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 17 21:45:19 2021 -0700
Upgrading to Sanic 21.9.1.
commit ea32813be28e78393ac456ee782a7245c098188f
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 17 20:29:01 2021 -0700
Creating Downloader and DownloaderManager classes which handle downloading URLs.
commit e859a77a77277ddf8b6e221ec9c9383c8ab91d66
Author: Roland <roland@learningselfreliance.com>
Date: Wed Nov 17 12:41:39 2021 -0700
Creating UI segement which allows the download/upload of media.
* Displaying all recurring downloads.
* Not downloading channels with empty url.
* Showing positive row for recurring downloads.
* Removing default last_successful_download.
* Only displaying Last Successful Download when there is one.
* Refreshing videos before finding missing videos.
* Using short video path name for log.
* Removing download history feature in favor of new Downloads page.
* Only showing info date if it exists.
* Making get_or_create_channel more reliable.
* Allowing null for channel download frequency.
* Logging when searching for channel.
* Storing channel's source_id in config.
* Importing using link instead of name.
* Getting channel id when importing channels.
* Removing redunant parentheses from repr.
* Preserving database channel values if there are not values in the config.
* Only highlighting pending downloads.
* Deleting old downloads periodically.
* Sorting recurring by next_download/frequency.
* Creating fixtures for channels, media directory and db session.
* Removing unused function. Wrapping config for tests.
* Deleting channel download when deleting a channel.
* Testing that a channel's download is deleted when the channel is deleted.
* Updating youtube-dl
* Switching from youtube-dl in favor of yt-dlp.
* Sorting once-downlaods by last_successful_download then id.
* Adding special handling to video_url_resolver for full urls.
* Consolidating downloader methods and functions. Reversing once-download sort order so the most recently downloaded are at the top.
* Getting session if one is not provided.
* Adding test for create_downloads.
* Not passing format option when getting filename.
* Linting
Signed-off-by: Roland <roland@learningselfreliance.com>
603 lines
25 KiB
Python
603 lines
25 KiB
Python
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
from datetime import timedelta
|
|
from http import HTTPStatus
|
|
from queue import Empty
|
|
|
|
import mock
|
|
import pytest
|
|
|
|
from modules.videos.api import refresh_queue
|
|
from modules.videos.channel.lib import spread_channel_downloads, delete_channel
|
|
from modules.videos.lib import upsert_video
|
|
from modules.videos.models import Channel, Video
|
|
from modules.videos.test.common import create_channel_structure
|
|
from wrolpi.dates import now
|
|
from wrolpi.db import get_db_session
|
|
from wrolpi.downloader import download_manager, Download
|
|
from wrolpi.errors import UnknownFile
|
|
from wrolpi.root_api import api_app
|
|
from wrolpi.test.common import wrap_test_db, TestAPI
|
|
|
|
|
|
class TestVideoAPI(TestAPI):
|
|
|
|
@wrap_test_db
|
|
@create_channel_structure(
|
|
{
|
|
'Foo': ['vid1.mp4'],
|
|
'Bar': ['vid2.mp4'],
|
|
'Baz': [],
|
|
}
|
|
)
|
|
def test_get_channels(self, tempdir):
|
|
request, response = api_app.test_client.get('/api/videos/channels')
|
|
assert response.status_code == HTTPStatus.OK
|
|
# Channels are sorted by name
|
|
self.assertDictContains(response.json['channels'][0], {'id': 2, 'name': 'Bar', 'video_count': 1})
|
|
self.assertDictContains(response.json['channels'][1], {'id': 3, 'name': 'Baz', 'video_count': 0})
|
|
self.assertDictContains(response.json['channels'][2], {'id': 1, 'name': 'Foo', 'video_count': 1})
|
|
|
|
@wrap_test_db
|
|
def test_channel(self):
|
|
channel_directory = tempfile.TemporaryDirectory(dir=self.tmp_dir.name).name
|
|
channel_directory_name = channel_directory.split('/')[-1]
|
|
pathlib.Path(channel_directory).mkdir()
|
|
|
|
new_channel = dict(
|
|
directory=channel_directory,
|
|
match_regex='asdf',
|
|
name='Example Channel 1',
|
|
url='https://example.com/channel1',
|
|
)
|
|
|
|
# Channel doesn't exist
|
|
request, response = api_app.test_client.get('/api/videos/channels/examplechannel1')
|
|
assert response.status_code == HTTPStatus.NOT_FOUND, f'Channel exists: {response.json}'
|
|
|
|
# Create it
|
|
request, response = api_app.test_client.post('/api/videos/channels', data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
location = response.headers['Location']
|
|
request, response = api_app.test_client.get(location)
|
|
created = response.json['channel']
|
|
self.assertIsNotNone(created)
|
|
self.assertIsNotNone(created['id'])
|
|
|
|
# Channel directory should be relative to the media directory
|
|
assert not pathlib.Path(created['directory']).is_absolute(), \
|
|
f'Channel directory is absolute: {created["directory"]}'
|
|
|
|
# Get the link that was computed
|
|
new_channel['link'] = response.json['channel']['link']
|
|
assert new_channel['link']
|
|
|
|
# Can't create it again
|
|
request, response = api_app.test_client.post('/api/videos/channels', data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
# Update it
|
|
new_channel['name'] = 'Example Channel 2'
|
|
new_channel['directory'] = str(new_channel['directory'])
|
|
request, response = api_app.test_client.put(location, data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
|
|
request, response = api_app.test_client.get(location)
|
|
assert response.status_code == HTTPStatus.OK
|
|
self.assertDictContains(response.json['channel'], {
|
|
'id': 1,
|
|
'name': 'Example Channel 2',
|
|
'directory': channel_directory_name,
|
|
'match_regex': 'asdf',
|
|
'url': 'https://example.com/channel1',
|
|
})
|
|
|
|
# Patch it
|
|
patch = {'name': 'new name'}
|
|
request, response = api_app.test_client.patch(location, data=json.dumps(patch))
|
|
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
|
|
request, response = api_app.test_client.get(location)
|
|
assert response.status_code == HTTPStatus.OK
|
|
self.assertDictContains(response.json['channel'], {
|
|
'id': 1,
|
|
'name': 'new name',
|
|
'directory': channel_directory_name,
|
|
'match_regex': 'asdf',
|
|
'url': 'https://example.com/channel1',
|
|
})
|
|
|
|
# Can't update channel that doesn't exist
|
|
request, response = api_app.test_client.put('/api/videos/channels/doesnt_exist',
|
|
data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
# Delete the new channel
|
|
request, response = api_app.test_client.delete(location)
|
|
assert response.status_code == HTTPStatus.NO_CONTENT
|
|
|
|
# Cant delete it again
|
|
request, response = api_app.test_client.delete(location)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
@wrap_test_db
|
|
def test_channel_conflicts(self):
|
|
with tempfile.TemporaryDirectory() as media_dir, \
|
|
mock.patch('wrolpi.common.get_media_directory', lambda: pathlib.Path(media_dir)):
|
|
channel_directory = tempfile.TemporaryDirectory(dir=media_dir).name
|
|
pathlib.Path(channel_directory).mkdir()
|
|
new_channel = dict(
|
|
directory=channel_directory,
|
|
match_regex='asdf',
|
|
name='Example Channel 1',
|
|
url='https://example.com/channel1',
|
|
)
|
|
|
|
def _post_channel(channel):
|
|
return api_app.test_client.post('/api/videos/channels', data=json.dumps(channel))
|
|
|
|
# Create it
|
|
request, response = _post_channel(new_channel)
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
|
|
# Name is an exact match
|
|
channel_directory2 = tempfile.TemporaryDirectory(dir=media_dir).name
|
|
pathlib.Path(channel_directory2).mkdir()
|
|
new_channel = dict(
|
|
directory=channel_directory2,
|
|
name='Example Channel 1',
|
|
)
|
|
request, response = _post_channel(new_channel)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
|
|
'cause': {'error': 'The channel name is already taken.', 'code': 5}}
|
|
|
|
# Name matches when converted to link
|
|
channel_directory2 = tempfile.TemporaryDirectory(dir=media_dir).name
|
|
pathlib.Path(channel_directory2).mkdir()
|
|
new_channel = dict(
|
|
directory=channel_directory2,
|
|
name='Example channel 1',
|
|
)
|
|
request, response = _post_channel(new_channel)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
|
|
'cause': {'code': 11, 'error': 'Channel link already used by another channel'}}
|
|
|
|
# Directory was already used
|
|
new_channel = dict(
|
|
directory=channel_directory,
|
|
name='name is fine',
|
|
)
|
|
request, response = _post_channel(new_channel)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
|
|
'cause': {'code': 7, 'error': 'The directory is already used by another channel.'}}
|
|
|
|
# URL is already used
|
|
channel_directory3 = tempfile.TemporaryDirectory(dir=media_dir).name
|
|
pathlib.Path(channel_directory3).mkdir()
|
|
new_channel = dict(
|
|
directory=channel_directory3,
|
|
name='name is fine',
|
|
url='https://example.com/channel1',
|
|
)
|
|
request, response = _post_channel(new_channel)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
|
|
'cause': {'code': 6, 'error': 'The URL is already used by another channel.'}}
|
|
|
|
@wrap_test_db
|
|
def test_channel_empty_url_doesnt_conflict(self):
|
|
"""Two channels with empty URLs shouldn't conflict"""
|
|
with tempfile.TemporaryDirectory() as media_dir, \
|
|
mock.patch('wrolpi.common.get_media_directory', lambda: pathlib.Path(media_dir)):
|
|
channel_directory = tempfile.TemporaryDirectory(dir=media_dir).name
|
|
pathlib.Path(channel_directory).mkdir()
|
|
|
|
new_channel = {
|
|
'name': 'Fooz',
|
|
'directory': channel_directory,
|
|
}
|
|
request, response = api_app.test_client.post('/api/videos/channels', data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.CREATED, response.json
|
|
location = response.headers['Location']
|
|
|
|
channel_directory2 = tempfile.TemporaryDirectory(dir=media_dir).name
|
|
pathlib.Path(channel_directory2).mkdir()
|
|
new_channel = {
|
|
'name': 'Barz',
|
|
'directory': channel_directory2,
|
|
}
|
|
request, response = api_app.test_client.post('/api/videos/channels', data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.CREATED, response.json
|
|
assert location != response.headers['Location']
|
|
|
|
@wrap_test_db
|
|
def test_refresh_no_channel(self):
|
|
with get_db_session() as session:
|
|
videos_path = pathlib.Path(self.tmp_dir.name) / 'videos'
|
|
videos_path.mkdir()
|
|
|
|
# A regular user-defined channel
|
|
channel1_path = videos_path / 'channel1'
|
|
channel1_path.mkdir()
|
|
vid1 = channel1_path / 'MyChannelName_20000101_abcdefghijk_title1.mp4'
|
|
vid1.touch()
|
|
vid2 = channel1_path / 'MyChannelName_20000101_abcdefghijk_title2.mp4'
|
|
vid2.touch()
|
|
|
|
channel1 = Channel(name='channel1', link='channel1', directory=channel1_path)
|
|
session.add(channel1)
|
|
session.commit()
|
|
|
|
# The special NO CHANNEL directory.
|
|
from modules.videos.downloader import get_no_channel_directory
|
|
no_channel_path = get_no_channel_directory()
|
|
no_channel_path.mkdir()
|
|
vid3 = no_channel_path / 'some video.mp4'
|
|
vid3.touch()
|
|
no_channel_subdir = no_channel_path / 'subdir'
|
|
no_channel_subdir.mkdir()
|
|
vid4 = no_channel_subdir / 'other video.mp4'
|
|
vid4.touch()
|
|
|
|
api_app.test_client.post('/api/videos/refresh')
|
|
|
|
videos = session.query(Video).order_by(Video.title).all()
|
|
self.assertEqual(len(videos), 4)
|
|
|
|
# Add some fake videos, they should be removed.
|
|
session.add(Video(title='vid5'))
|
|
session.add(Video(title='vid6', channel_id=channel1.id))
|
|
session.commit()
|
|
|
|
videos = session.query(Video).order_by(Video.title).all()
|
|
self.assertEqual(len(videos), 6)
|
|
|
|
api_app.test_client.post('/api/videos/refresh')
|
|
|
|
videos = session.query(Video).order_by(Video.title).all()
|
|
self.assertEqual(len(videos), 4)
|
|
|
|
@wrap_test_db
|
|
def test_refresh_videos(self):
|
|
# There should be no messages until a refresh is called.
|
|
pytest.raises(Empty, refresh_queue.get_nowait)
|
|
|
|
# Setup a fake channel directory.
|
|
with get_db_session() as session:
|
|
channel_path = pathlib.Path(self.tmp_dir.name)
|
|
|
|
# Files in subdirectories should be found and handled properly.
|
|
subdir = channel_path / 'subdir'
|
|
subdir.mkdir()
|
|
|
|
# These are the types of files that will be found first.
|
|
vid1 = subdir / 'channel name_20000101_abcdefghijk_title.mp4'
|
|
vid1.touch()
|
|
vid2 = channel_path / 'channel name_20000102_bcdefghijkl_title.webm'
|
|
vid2.touch()
|
|
|
|
# This video is named the same as vid1, except for the file extension. Its possible that this was
|
|
# downloaded later, or maybe the old video format has fallen out of favor. WROLPi should ignore this
|
|
# duplicate file.
|
|
vid1_alt = subdir / 'channel name_20000101_abcdefghijk_title.webm'
|
|
vid1_alt.touch()
|
|
|
|
# These files are associated with the video files above, and should be found "near" them.
|
|
poster1 = subdir / 'channel name_20000101_abcdefghijk_title.jpg'
|
|
poster1.touch()
|
|
poster2 = channel_path / 'channel name_20000102_bcdefghijkl_title.jpg'
|
|
poster2.touch()
|
|
|
|
# Create a channel, associate videos with it.
|
|
channel = Channel(directory=channel_path, link='foo', name='foo')
|
|
session.add(channel)
|
|
session.flush()
|
|
session.refresh(channel)
|
|
video1 = upsert_video(session, vid1, channel)
|
|
video2 = upsert_video(session, vid2, channel)
|
|
session.commit()
|
|
self.assertEqual({str(i.video_path.path) for i in channel.videos},
|
|
{f'{channel_path}/subdir/{vid1.name}', f'{channel_path}/{vid2.name}'})
|
|
|
|
# Poster files were found.
|
|
self.assertEqual(video1.poster_path.path, subdir / poster1.name)
|
|
self.assertEqual(video2.poster_path.path, channel_path / poster2.name)
|
|
|
|
# Add a bogus file, this should be removed during the refresh
|
|
self.assertNotIn('foo', {i.video_path.path for i in channel.videos})
|
|
session.add(Video(video_path='foo', channel_id=channel.id))
|
|
session.flush()
|
|
session.refresh(channel)
|
|
self.assertIn(f'{self.tmp_dir.name}/foo', {str(i.video_path.path) for i in channel.videos})
|
|
self.assertEqual(len(channel.videos), 3)
|
|
|
|
# Add a video that isn't in the DB, it should be found and any meta files associated with it
|
|
vid3 = pathlib.Path(channel_path / 'channel name_20000103_cdefghijklm_title.flv')
|
|
vid3.touch()
|
|
description3 = pathlib.Path(channel_path / 'channel name_20000103_cdefghijklm_title.description')
|
|
description3.touch()
|
|
|
|
# An orphan meta-file should be ignored. This shouldn't show up anywhere. But, it shouldn't be deleted.
|
|
poster3 = pathlib.Path(channel_path / 'channel name_20000104_defghijklmn_title.jpg')
|
|
poster3.touch()
|
|
|
|
# Finally, call the refresh. Again, it should remove the "foo" video, then discover this 3rd video
|
|
# file and it's description.
|
|
api_app.test_client.post('/api/videos/refresh')
|
|
|
|
# Bogus file was removed
|
|
self.assertNotIn(f'{self.tmp_dir.name}/foo', {i.video_path.path for i in channel.videos})
|
|
|
|
# Final channel video list we built
|
|
expected = {
|
|
('subdir/' + vid1.name, 'subdir/' + poster1.name, None), # in a subdirectory, no description
|
|
(vid2.name, poster2.name, None), # no description
|
|
(vid3.name, None, description3.name), # no poster
|
|
}
|
|
|
|
def str_or_none(i):
|
|
return str(i.__json__()) if i else None
|
|
|
|
self.assertEqual(
|
|
{(str_or_none(i.video_path), str_or_none(i.poster_path), str_or_none(i.description_path))
|
|
for i in channel.videos},
|
|
expected
|
|
)
|
|
|
|
assert poster3.is_file(), 'Orphan jpg file was deleted!'
|
|
|
|
@wrap_test_db
|
|
def test_get_channel_videos(self):
|
|
with get_db_session(commit=True) as session:
|
|
channel1 = Channel(name='Foo', link='foo')
|
|
channel2 = Channel(name='Bar', link='bar')
|
|
session.add(channel1)
|
|
session.add(channel2)
|
|
session.flush()
|
|
session.refresh(channel1)
|
|
session.refresh(channel2)
|
|
|
|
# Channels don't have videos yet
|
|
d = dict(channel_link=channel1.link)
|
|
request, response = api_app.test_client.post(f'/api/videos/search', data=json.dumps(d))
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert len(response.json['videos']) == 0
|
|
|
|
with get_db_session(commit=True) as session:
|
|
vid1 = Video(title='vid1', channel_id=channel2.id, video_path='foo')
|
|
vid2 = Video(title='vid2', channel_id=channel1.id, video_path='foo')
|
|
session.add(vid1)
|
|
session.add(vid2)
|
|
|
|
# Videos are gotten by their respective channels
|
|
request, response = api_app.test_client.post(f'/api/videos/search', data=json.dumps(d))
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert len(response.json['videos']) == 1
|
|
assert response.json['totals']['videos'] == 1
|
|
self.assertDictContains(response.json['videos'][0], dict(id=2, title='vid2', channel_id=channel1.id))
|
|
|
|
d = dict(channel_link=channel2.link)
|
|
request, response = api_app.test_client.post(f'/api/videos/search', data=json.dumps(d))
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert len(response.json['videos']) == 1
|
|
self.assertDictContains(response.json['videos'][0], dict(id=1, title='vid1', channel_id=channel2.id))
|
|
|
|
@wrap_test_db
|
|
def test_get_video(self):
|
|
"""
|
|
Test that you get can information about a video. Test that video file can be gotten.
|
|
"""
|
|
|
|
def raise_unknown_file(_):
|
|
raise UnknownFile()
|
|
|
|
with get_db_session(commit=True) as session, \
|
|
mock.patch('modules.videos.common.get_absolute_video_info_json', raise_unknown_file):
|
|
channel = Channel(name='Foo', link='foo')
|
|
session.add(channel)
|
|
session.flush()
|
|
session.refresh(channel)
|
|
now_ = now()
|
|
session.add(Video(title='vid1', channel_id=channel.id, upload_date=now_))
|
|
session.add(Video(title='vid2', channel_id=channel.id, upload_date=now_ + timedelta(seconds=1)))
|
|
|
|
# Test that a 404 is returned when no video exists
|
|
_, response = api_app.test_client.get('/api/videos/video/10')
|
|
assert response.status_code == HTTPStatus.NOT_FOUND, response.json
|
|
assert response.json == {'code': 1, 'api_error': 'The video could not be found.', 'message': ''}
|
|
|
|
# Get the video info we inserted
|
|
_, response = api_app.test_client.get('/api/videos/video/1')
|
|
assert response.status_code == HTTPStatus.OK, response.json
|
|
self.assertDictContains(response.json['video'], {'title': 'vid1'})
|
|
|
|
# The next video is included.
|
|
self.assertIsNone(response.json['prev'])
|
|
self.assertDictContains(response.json['next'], {'title': 'vid2'})
|
|
|
|
@wrap_test_db
|
|
def test_get_channel_videos_pagination(self):
|
|
with get_db_session(commit=True) as session:
|
|
channel1 = Channel(name='Foo', link='foo')
|
|
session.add(channel1)
|
|
session.flush()
|
|
session.refresh(channel1)
|
|
|
|
for i in range(50):
|
|
session.add(Video(title=f'Foo.Video{i}', channel_id=channel1.id, video_path='foo'))
|
|
|
|
channel2 = Channel(name='Bar', link='bar')
|
|
session.add(channel2)
|
|
session.flush()
|
|
session.refresh(channel2)
|
|
session.add(Video(title='vid2', channel_id=channel2.id, video_path='foo'))
|
|
|
|
# Get first, second, third, and empty pages of videos.
|
|
tests = [
|
|
# (offset, video_count)
|
|
(0, 20),
|
|
(20, 20),
|
|
(40, 10),
|
|
(50, 0),
|
|
]
|
|
last_ids = []
|
|
for offset, video_count in tests:
|
|
d = dict(channel_link=channel1.link, order_by='id', offset=offset)
|
|
_, response = api_app.test_client.post(f'/api/videos/search', data=json.dumps(d))
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert len(response.json['videos']) == video_count
|
|
current_ids = [i['id'] for i in response.json['videos']]
|
|
assert current_ids != last_ids, f'IDs are unchanged current_ids={current_ids}'
|
|
last_ids = current_ids
|
|
|
|
@wrap_test_db
|
|
def test_video_search(self):
|
|
"""
|
|
Test that videos can be searched and that their order is by their textsearch rank.
|
|
"""
|
|
# These captions have repeated letters so they will be higher in the ranking
|
|
videos = [
|
|
('1', 'b b b b e d d'),
|
|
('2', '2 b b b d'),
|
|
('3', 'b b'),
|
|
('4', 'b e e'),
|
|
('5', ''),
|
|
]
|
|
with get_db_session(commit=True) as session:
|
|
for title, caption in videos:
|
|
session.add(Video(title=title, caption=caption, video_path='foo'))
|
|
|
|
def do_search(search_str, limit=20):
|
|
d = json.dumps({'search_str': search_str, 'limit': limit})
|
|
_, resp = api_app.test_client.post('/api/videos/search', data=d)
|
|
return resp
|
|
|
|
def search_is_as_expected(resp, expected):
|
|
assert resp.status_code == HTTPStatus.OK
|
|
response_ids = [i['id'] for i in resp.json['videos']]
|
|
assert response_ids == expected
|
|
assert resp.json['totals']['videos'] == len(expected)
|
|
|
|
# Repeated runs should return the same result
|
|
for _ in range(2):
|
|
# Only videos with a b are returned, ordered by the amount of b's
|
|
response = do_search('b')
|
|
search_is_as_expected(response, [1, 2, 3, 4])
|
|
|
|
# Only two captions have e
|
|
response = do_search('e')
|
|
search_is_as_expected(response, [4, 1])
|
|
|
|
# Only two captions have d
|
|
response = do_search('d')
|
|
search_is_as_expected(response, [1, 2])
|
|
|
|
# 5 can be gotten by it's title
|
|
response = do_search('5')
|
|
search_is_as_expected(response, [5])
|
|
|
|
# only video 1 has e and d
|
|
response = do_search('e d')
|
|
search_is_as_expected(response, [1])
|
|
|
|
# video 1 and 4 have b and e, but 1 has more
|
|
response = do_search('b e')
|
|
search_is_as_expected(response, [1, 4])
|
|
|
|
# Check totals are correct even with a limit
|
|
response = do_search('b', 2)
|
|
assert [i['id'] for i in response.json['videos']] == [1, 2]
|
|
assert response.json['totals']['videos'] == 4
|
|
|
|
@wrap_test_db
|
|
def test_channel_no_download_frequency(self):
|
|
"""
|
|
A channel does not require a download frequency.
|
|
"""
|
|
channel_directory = tempfile.TemporaryDirectory(dir=self.tmp_dir.name).name
|
|
os.mkdir(channel_directory)
|
|
|
|
new_channel = dict(
|
|
directory=channel_directory,
|
|
name='Example Channel 1',
|
|
url='https://example.com/channel1',
|
|
download_frequency=None,
|
|
)
|
|
|
|
# Create the Channel
|
|
request, response = api_app.test_client.post('/api/videos/channels', data=json.dumps(new_channel))
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
location = response.headers['Location']
|
|
|
|
# No downloads are scheduled.
|
|
spread_channel_downloads()
|
|
with get_db_session() as session:
|
|
downloads = list(download_manager.get_new_downloads(session))
|
|
self.assertEqual(len(downloads), 0)
|
|
|
|
# Get the Channel
|
|
request, response = api_app.test_client.get(location)
|
|
channel = response.json['channel']
|
|
self.assertEqual(channel['download_frequency'], None)
|
|
|
|
# Update the Channel with a frequency.
|
|
new_channel = dict(
|
|
directory=channel['directory'],
|
|
name=channel['name'],
|
|
url=channel['url'],
|
|
download_frequency=10,
|
|
)
|
|
request, response = api_app.test_client.put(f'/api/videos/channels/{channel["link"]}',
|
|
data=json.dumps(new_channel))
|
|
self.assertEqual(response.status_code, 204, response.json)
|
|
|
|
# Remove the frequency.
|
|
new_channel = dict(
|
|
directory=channel['directory'],
|
|
name=channel['name'],
|
|
url=channel['url'],
|
|
download_frequency=None,
|
|
)
|
|
request, response = api_app.test_client.put(f'/api/videos/channels/{channel["link"]}',
|
|
data=json.dumps(new_channel))
|
|
self.assertEqual(response.status_code, 204, response.json)
|
|
|
|
|
|
def test_channel_frequency_update(download_channel, test_client, test_session):
|
|
"""
|
|
A Channel's Download record is updated when the Channel's frequency is updated.
|
|
"""
|
|
old_frequency = download_channel.get_download().frequency
|
|
assert old_frequency
|
|
|
|
data = dict(
|
|
directory=str(download_channel.directory.path),
|
|
name=download_channel.name,
|
|
url=download_channel.url,
|
|
download_frequency=100,
|
|
)
|
|
request, response = test_client.put(f'/api/videos/channels/{download_channel.link}', json=data)
|
|
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
|
|
|
|
download = download_channel.get_download()
|
|
assert download.frequency == 100
|
|
|
|
# Only one download
|
|
downloads = test_session.query(Download).all()
|
|
assert len(list(downloads)) == 1
|
|
|
|
|
|
def test_delete_channel_delete_download(download_channel, test_session):
|
|
"""
|
|
Deleting a Channel deletes it's Download.
|
|
"""
|
|
downloads = test_session.query(Download).all()
|
|
assert all(i.url == download_channel.url for i in downloads)
|
|
|
|
delete_channel(download_channel.link)
|
|
|
|
downloads = test_session.query(Download).all()
|
|
assert not list(downloads)
|