Compare commits

...

205 Commits

Author SHA1 Message Date
simon
f0874b2d02 add timeout for sponsorblock api requests, handle 503 2022-10-23 12:46:10 +07:00
simon
baacd3ee39 better message for running and indexing queue 2022-10-23 12:21:27 +07:00
simon
9cd23c3666 error handeling for playlist_thumbnail extraction 2022-10-23 11:50:26 +07:00
simon
0e17e2a6cf bump TA_VERSION to v0.2.3 2022-10-23 10:55:57 +07:00
simon
2dea0aa57b bump archivist-es 2022-10-23 10:55:14 +07:00
simon
ba1c8c15c4 fix missing build-arg for local deployment 2022-10-23 10:50:16 +07:00
simon
f16915be11 clarify filter only shows when more than 1 2022-10-23 10:49:26 +07:00
simon
858d437f3f simplify local production deployment 2022-10-23 00:11:03 +07:00
simon
de30ac302a add documentation for download channel filter 2022-10-23 00:10:38 +07:00
simon
dd8597307c fix wrong python version in final image 2022-10-22 23:30:44 +07:00
simon
608403c113 Download filter select, #build
Changed:
- added download filter dropdown
- fix for UnidentifiedImageError thumbnail error
- fix for _update_by_query channel missing watched_date
- fix for chrome compatibility text reveal
2022-10-22 22:55:38 +07:00
simon
40eff8e30e fix chrome compatibility issue for description text reveal, #327 2022-10-22 22:32:57 +07:00
simon
0bba36cbc3 add watched_date for _update_by_query mark as watched, #309 2022-10-22 22:00:35 +07:00
simon
a5788117de add dropdown channel agg for download page 2022-10-22 21:23:57 +07:00
simon
3f1075d0b2 bump python version 2022-10-22 20:24:58 +07:00
simon
dea2688b49 handle UnidentifiedImageError in ThumbManager, #325 2022-10-17 19:26:01 +07:00
simon
4f1daeb18c Downloads channel filter, #build
Changed:
- Added downloads channel filter to channel pages
- API: Filter download list view by channel
- Fixed: is_live status check
2022-10-17 19:01:59 +07:00
simon
927e6fa909 create channel parameter for downloads api view 2022-10-17 18:58:21 +07:00
simon
bd7cdb3942 append query parameters to pagination 2022-10-17 18:40:20 +07:00
simon
9dfd967a32 implement downloads filter per channel 2022-10-17 13:29:21 +07:00
simon
6eee762d3a add status for sub refresh 2022-10-14 11:27:27 +07:00
simon
a8c5773f81 fix is_live status check before adding to queue 2022-10-05 16:12:58 +02:00
simon
fbb52dc93f implement basic channel query string for downloads page 2022-10-05 15:47:17 +02:00
simon
c9e936da21 bump libraries 2022-10-05 15:46:44 +02:00
simon
c825e67f69 bump django and restframework 2022-09-30 18:02:44 +02:00
simon
bcb7b9443b bump tubearchivist-es 2022-09-19 15:52:22 +07:00
simon
896d166dcf add minimal system requirements documentation 2022-09-19 15:40:51 +07:00
simon
db6840639a update TA_VERSION to v0.2.2 2022-09-19 15:21:55 +07:00
simon
6af080ab6e remove unstable mention for TA_LDAP_DISABLE_CERT_CHECK 2022-09-19 15:14:22 +07:00
simon
f28c47323f cleanup channel info.json file after import 2022-09-19 15:10:41 +07:00
simon
73cd9a11f8 Consolidate downloads page UI, #build
Changed:
- use video styling from homepage also on download page
- configure grid items on download page
- fix reindex task trying to reindexing inactive videos
- better error handling with yt-dlp, timeout and retry
2022-09-17 11:32:31 +07:00
simon
19fed77218 bump python version 2022-09-17 10:53:43 +07:00
simon
b25818dbc3 extend timeout, add retry to YtWrap 2022-09-17 10:31:51 +07:00
simon
f2a8b070f2 add log output for add to queue 2022-09-17 10:30:27 +07:00
simon
dfacc3039a fix reindex task, skip inactive in _get_unrated_vids 2022-09-14 16:43:48 +07:00
simon
2b8ec1f8cf use grid_items for videos on download page 2022-09-13 16:47:31 +07:00
simon
265a53ace3 manual import fix, #build
Changed:
- fixed manual import errors, #311 #312
- fixed channel extraction to catch all alerts
- add LDAP disable cert check
- downgrade django, fix for DJANGO_DEBUG env var
2022-09-10 11:38:30 +07:00
simon
6d22e62642 downgrade django to fix django_debug env 2022-09-10 11:22:49 +07:00
simon
17c178c8bf add 400 response for wrong TA_HOST env var 2022-09-06 23:27:05 +07:00
simon
301a734905 fix DJANGO_DEBUG set to default empty string 2022-09-06 23:26:17 +07:00
simon
1c3febc49d force create thumb folder for manual import 2022-09-06 23:13:29 +07:00
simon
a6dd927860 fix channel extraction to catch all alerts, #312 2022-09-06 23:12:49 +07:00
simon
3c92de8e24 improved logging for manual import 2022-09-06 22:42:55 +07:00
simon
e51a662da9 fix manual import splitext matching invalid extensions, #311 2022-09-06 22:27:18 +07:00
simon
a7aead728c add roadmap link to FR template 2022-09-06 21:22:30 +07:00
simon
b2bf4ecc02 bump libs 2022-09-06 21:20:29 +07:00
simon
06795a014c explicitly set DJANGO_DEBUG env var on startup 2022-09-06 21:11:18 +07:00
simon
8f2794a141 Merge branch 'master' into testing 2022-09-03 15:17:06 +07:00
DanielBatteryStapler
396b6b80cd Add TA_LDAP_DISABLE_CERT_CHECK option (#314)
* add TA_LDAP_DISABLE_CERT_CHECK option

* add unstable disclaimer next to TA_LDAP_DISABLE_CERT_CHECK
2022-09-03 15:16:09 +07:00
simon
e467beb1c7 fix manual import cleanup metadata, #331 2022-08-26 17:07:55 +07:00
simon
c70942ff90 update old buildx command for reference 2022-08-20 15:26:28 +07:00
simon
f26d02919e revert faulty django update 2022-08-20 14:14:14 +07:00
simon
e65ba08ec6 untested offline import note 2022-08-20 13:42:31 +07:00
simon
09b75211c3 update roadmap 2022-08-20 08:51:29 +07:00
simon
6c019ba112 update installation wiki links and pages 2022-08-20 07:30:19 +07:00
simon
ac79ce91da verbose curl ES connection fail output 2022-08-19 18:51:16 +07:00
simon
20ff465b94 bump TA_VERSION to v0.2.1 2022-08-19 18:28:34 +07:00
simon
7d3a5cc699 add search api to readme 2022-08-19 18:26:27 +07:00
simon
93dc38e829 bump tubearchivist-es to 8.3.3 2022-08-19 18:20:58 +07:00
simon
17ddc95eb9 remove unstable mention from LDAP instructions 2022-08-19 18:20:25 +07:00
simon
1b22e61384 New search API endpoint, #build
Changed:
- Switched search form to API
- Additional validations for RYD
- Additional log output for curl ES startup check
2022-08-19 18:00:35 +07:00
simon
e6b673832f bump yt-dlp 2022-08-19 17:53:18 +07:00
PrivateGER
57a9fff82b Add API endpoint for searching (#303)
* Add API endpoint for searching + use it in frontend

* Fix linting warnings

* Remove multisearch API call

* Avoid 301 and fix up multiline comment
2022-08-19 17:52:37 +07:00
simon
1896e982b9 codespell lint fixes 2022-08-18 18:51:11 +07:00
simon
0e7e0a0560 fail open on ryd error 2022-08-18 18:45:46 +07:00
simon
115db944c8 add curl output for failed es connection 2022-08-18 18:35:09 +07:00
simon
650ac94e68 better wording for es permission error 2022-08-17 18:48:34 +07:00
simon
155439e228 add api Table of contents 2022-08-17 17:29:04 +07:00
simon
25877cf016 Lots of bug fixes, #build
Changed:
- fixed lots of small bugs
- fixed offline import mkv thumb extractor
2022-08-16 16:35:59 +07:00
lamusmaser
15996ea959 Update Installation documentation to include Synology Docker… (#282)
* Update Installation documentation to include Synology Docker instructions.

* Typo fix and adjustments.
2022-08-16 16:34:45 +07:00
simon
1a0421a45a update Manual Media Files Import docs 2022-08-16 16:29:17 +07:00
simon
0210a97b48 archive vtt files for offline import 2022-08-16 15:42:54 +07:00
simon
a4932b163b bump ryd 2022-08-16 15:42:26 +07:00
simon
0b41d288db fix mkv cover stream extractor 2022-08-16 12:19:27 +07:00
simon
21f3ee88b9 extract vtt from mkv and mp4 for import 2022-08-15 15:18:38 +07:00
simon
7727f533ee move subtitle to separate module 2022-08-15 13:55:24 +07:00
simon
41c71fde56 bump yt-dlp 2022-08-15 13:55:02 +07:00
simon
c27e446ec6 Merge branch 'master' into testing 2022-08-14 21:56:11 +07:00
simon
3d1561de75 better wording feature request help 2022-08-14 21:55:23 +07:00
simon
3df6eceb20 add issue templates 2022-08-14 19:43:00 +07:00
simon
81aa27e802 fix video-item.list vertical positioning 2022-08-13 16:20:38 +07:00
simon
bd4710ebdc improved wording for download form, subscription size, #300 2022-08-13 15:43:23 +07:00
simon
8a1ae1ef83 add protocoll to CSRF_TRUSTED_ORIGINS 2022-08-13 14:03:17 +07:00
simon
6afe25a4af fix empty subtitle download and index, #288 2022-08-12 15:53:20 +07:00
simon
cc40f46325 improved ryd error handeling, #283 2022-08-12 14:39:22 +07:00
simon
7c3bfa94f3 handle thumbnail download base exception, #281 2022-08-12 12:58:39 +07:00
simon
25f1539816 implement backup task lock, #278 2022-08-12 12:03:09 +07:00
simon
474ab22792 handle channel name redirect in UrlListParser, #276 2022-08-12 11:53:31 +07:00
simon
257f7a0287 add GH sponsor link 2022-08-12 06:19:36 +07:00
simon
c39ce61b2c offline import, #build
Changed:
- added offline import for videos and channels
- thumbnail manager rewrite
2022-08-12 05:36:54 +07:00
simon
980b99783b add sponsor info 2022-08-12 05:35:47 +07:00
simon
ececc3cedd bump yt-dlp 2022-08-11 19:57:12 +07:00
simon
0891c49620 implement offline channel import 2022-08-11 19:57:00 +07:00
simon
c26ef012c1 raise ValueError when not matching media files 2022-08-11 11:10:58 +07:00
simon
31061c0eb0 handle offline import without info.json fail 2022-08-10 22:38:17 +07:00
simon
994f7c2443 use user provided thumb for offline import 2022-08-10 22:31:15 +07:00
simon
7029441f89 use fallback thumb when no url passed 2022-08-10 22:24:02 +07:00
simon
35f1084cc2 download thumbnail for manual import 2022-08-10 21:47:26 +07:00
simon
44473a364f fix double download of playlist art 2022-08-10 21:20:58 +07:00
simon
fb4d6b7be3 major refactor ThumbManager 2022-08-10 21:03:54 +07:00
simon
b76fa69396 WIP: rewrite ManualImport, identify and archive 2022-08-08 19:18:27 +07:00
simon
8f711d359b implement youtube_meta and media_path overwritein YoutubeVideo 2022-08-08 18:28:32 +07:00
simon
9fd6f9c58b use absolute paths for manual import 2022-08-08 15:57:42 +07:00
simon
b70cbfa0a8 convert thumbnail to jpg for manual import 2022-08-08 14:52:33 +07:00
simon
d0675368f4 bump django 2022-08-08 14:52:06 +07:00
simon
195acd3246 WPI: dump thumbnails from mp4 and mkv 2022-07-31 00:02:09 +07:00
simon
5284975aa2 merge master into testing 2022-07-30 21:38:00 +07:00
simon
13018192f3 remove default funding sources 2022-07-30 21:17:12 +07:00
simon
07f50b6619 LDAP support, #build
Changed:
- configure LDAP over environment variables
- fix reverse proxy CSRF error
2022-07-30 21:13:13 +07:00
simon
36d0f08efb add FUNDING.yml 2022-07-30 21:08:57 +07:00
DanielBatteryStapler
fd75def6c3 implement LDAP as authentication backend support (#274) 2022-07-30 21:08:12 +07:00
simon
61da0c8af3 WIP: extract thumb from mkv 2022-07-30 21:07:31 +07:00
simon
91a169fa3e add FUNDING.yml 2022-07-30 21:07:31 +07:00
DanielBatteryStapler
e1c4702398 implement LDAP as authentication backend support (#274) 2022-07-30 21:05:10 +07:00
Aron Brown
5407d35779 Update settings.py (#284)
Add CSRF_TRUSTED_ORIGINS Django config settings and set it to environment variable TA_HOST.
This should fix login issues behind reverse proxies.
2022-07-30 21:03:58 +07:00
simon
26cc7846c6 WIP: new import folder parser for offline import 2022-07-26 19:51:47 +07:00
simon
36560735f2 better wording what TA_HOST represents, #275 2022-07-23 21:58:06 +07:00
simon
41972f64ad update roadmap 2022-07-23 19:57:25 +07:00
simon
83866a0d79 clarify scope 2022-07-23 17:32:59 +07:00
simon
aa0739bfbe bump TA_VERSION to v0.2.0 2022-07-23 16:35:18 +07:00
simon
d797f47bb8 remove synology link, remove security notification 2022-07-23 15:03:41 +07:00
simon
09f3ce0109 add TA_HOST and ES8 documentation 2022-07-23 14:38:50 +07:00
simon
2ba31a3937 add search help text 2022-07-23 14:10:16 +07:00
simon
31e2fcb322 update backup section for v0.2 2022-07-23 13:41:24 +07:00
simon
e69cd1129c add result size info 2022-07-23 13:41:07 +07:00
simon
8a59b66a0f finetune full text thumb width 2022-07-23 13:28:49 +07:00
simon
dcf7658972 add kibana quick start guide 2022-07-22 18:26:12 +07:00
simon
e79d64d707 update channel wiki page for v0.2 2022-07-22 18:15:27 +07:00
simon
503a4ed822 force es8 at startup 2022-07-22 17:22:06 +07:00
simon
f0a44678ed unset video max-height max-width for fullscreen webkit, #264 2022-07-22 14:50:53 +07:00
simon
4b1ebf44c9 handle filenotfounderror for manual cookie import 2022-07-21 23:01:32 +07:00
simon
eb229440d4 load config into redis on fresh install at startup 2022-07-21 23:01:01 +07:00
simon
88b412a2e9 keyword search, #build
Changed:
- added keyword search queries
- added fulltext search
- authenticate all user created media
- reduce docker log output
2022-07-21 20:15:15 +07:00
simon
14d3a7586d validate es8 at startup 2022-07-21 20:09:06 +07:00
simon
6ec65f9fe8 add search wiki page 2022-07-21 20:00:12 +07:00
simon
0ec6558282 jump to timestamp from full search 2022-07-21 17:15:36 +07:00
simon
52d31f9cca simplify createVideo player link building 2022-07-21 15:51:33 +07:00
simon
07016f2cc5 ignore full: result without highlight 2022-07-21 15:47:29 +07:00
simon
55a73995c8 implement source and lang keywords for full text search 2022-07-21 15:39:27 +07:00
simon
a40ebc7bbc tweak with for video-item.list 2022-07-21 15:36:36 +07:00
simon
e4dd47aed0 implement fulltext search keyword 2022-07-20 21:49:32 +07:00
simon
eb5a7338ab search with and operator, increase result size 2022-07-20 18:25:39 +07:00
simon
b77d50d4ed use queryType in populateMultiSearchResults to hide irrelevant 2022-07-20 18:01:57 +07:00
simon
b520a9bfb0 boost title result scores in multi_match 2022-07-20 16:20:23 +07:00
simon
242ca19586 return query_type from SearchParser 2022-07-20 16:10:57 +07:00
simon
6a6665bdf9 implement simple, aka none keyword query 2022-07-20 15:04:10 +07:00
simon
8e8c00af40 implement playlist keyword search, fix channel subscribed keyword 2022-07-20 14:58:04 +07:00
simon
ae3cf7eb80 add channel keyword search 2022-07-20 14:48:41 +07:00
simon
0a2b6ee90a add keyword search framework, implement video search 2022-07-19 19:23:59 +07:00
simon
d065b5b90a reduce uwsgi logging to errors only 2022-07-18 17:17:20 +07:00
simon
0528220b5e authenticate media and thumb requests 2022-07-18 14:10:34 +07:00
simon
f0850522a7 Merge branch 'master' into testing 2022-07-18 11:49:42 +07:00
simon
cc2fff8bef use info_dict for message, simplify cache template, #271 2022-07-18 11:37:43 +07:00
simon
2d13011866 bump yt-dlp 2022-07-18 11:29:28 +07:00
simon
146f17bf74 shutil.move fix take 2, #build
Changed:
- use shutil.copyfile for copy_function
- fixed typo
2022-07-17 07:48:54 +07:00
simon
b406250ae2 use shutil.copyfile for shutil.move calls 2022-07-17 07:47:27 +07:00
simon
ed9237b69d fix typo 2022-07-17 07:46:52 +07:00
simon
393e00866b Desc preview, nginx fix, #build
Changed:
- Requires new env var: TA_HOST, hostname of your application
- Showing preview for description text, by @p0358
- Fix nginx user permission, by @p0358
- Refactor IndexPaginate to take loop callback
- Fix backup for large index using loop callback
- Fix deactivating missing channels on reindex
2022-07-16 22:11:29 +07:00
p0358
411b09629a Better description view for videos and playlists (#272)
* draft

* proper implementation of description line clamping

* use a JS event that's potentially faster for text expand button visibility update

* remove desc title text, move show button after desc

Co-authored-by: simon <simobilleter@gmail.com>
2022-07-16 22:06:26 +07:00
p0358
79996f6838 Fix permission/mount issues from #268 (#270)
* make nginx run as root within the container (#268)

* move file to videos path with fallback to regular copy with no metadata copying (#268)

* use `copy_function=shutil.copy` everywhere with `shutil.move`
2022-07-16 21:54:39 +07:00
simon
6bb7f80ea2 Refactor IndexPaginate
- add callback function
- implement callback for ElasticBackup
2022-07-16 17:55:18 +07:00
simon
3b17c01c6d add TA_HOST env for ALLOWED_HOSTS 2022-07-14 17:26:10 +07:00
simon
91bccfd057 deactivate non existing channels on reindex 2022-07-12 11:41:03 +07:00
simon
8cca09e0ac remove ta_json backup file, keep only es_ndjson 2022-07-07 12:34:57 +07:00
simon
1479516689 Reimagining the channel pages, #build
Changed:
- Split the channel-id page into subpages
- Channel videos, channel playlist, channel about
- Disable es startup check to test ES8
2022-07-04 21:23:50 +07:00
simon
831e59a626 bump django 2022-07-04 21:23:32 +07:00
simon
6e012383ab toggle playlist subscribed filter 2022-07-04 21:12:54 +07:00
simon
e988192343 add channel_id_about subheading 2022-07-04 20:44:12 +07:00
simon
ef3abd01b1 implement channel_id_playlist, handle channel_id_about post 2022-07-04 20:25:52 +07:00
simon
e664338845 implement basic channel_id_about view 2022-07-04 16:44:37 +07:00
simon
63a1237683 temporarily disable es version check for testing 2022-07-04 16:43:13 +07:00
simon
6d59da4c86 remove redundant latest tags 2022-07-03 18:20:30 +07:00
simon
5bc67104ea set restart policy to unless-stopped 2022-07-03 17:23:02 +07:00
simon
72ec78e011 browser extension as prefered cookie sync method 2022-07-03 16:46:45 +07:00
simon
de8b7d6b43 bump ES version 2022-07-03 16:09:09 +07:00
simon
048409bb1e bump TA_VERSION to v0.1.7 2022-07-03 16:08:30 +07:00
simon
efff4cd96d change cookie documentation for v0.1.7 2022-07-03 16:06:28 +07:00
simon
78d7947a5c a note about subtitle refresh, #260 2022-07-03 15:36:21 +07:00
simon
c132a37f03 bump dependencies 2022-07-03 15:30:46 +07:00
simon
4678a7507b bump dependencies 2022-06-30 18:44:33 +07:00
simon
e8e240c89b Startup fix, cookie improvements, #build
Changed
- lock creating superuser at startup by @dshoreman
- auto validate cookie
- API: return cookie validation state for browser extension
- Finetuning CSS mobile layout
2022-06-27 10:14:59 +07:00
simon
1857ac44ca fix tablet css breakpoints and grid spacing 2022-06-27 09:48:36 +07:00
simon
8c07932071 delete cookie:valid key when revoking 2022-06-23 19:21:13 +07:00
simon
74d74d95a1 store validation result, return in API 2022-06-23 06:48:55 +07:00
simon
b4add20d10 bump yt-dlp 2022-06-22 19:30:38 +07:00
Dave Shoreman
e9619c1242 Fix repeated superuser creations after rename/removal (#263)
* Avoid creating superuser if variables are removed

Enables the removal of `TA_USERNAME` and/or `TA_PASSWORD` as a way of
preventing an additional superuser being created when another exists.

In the old code, `ELASTIC_USER` would never error due to the default, so
this replaces the loop with one requirement on `ELASTIC_PASSWORD`.

* Use .superuser_created to prevent re-creation

Creates an empty `.superuser_created` file after successful creation,
and uses this to skip the command on future runs. If the file doesn't
exist, then `TA_USERNAME` and `TA_PASSWORD` will also be required.

* The superuser password can't be empty

...well—it *can*—but the password input of the login form requires a
value so even though the account is created, you can't actually login.

* Parse createsuperuser output for 'exists' error

If a user already exists with the same name as the superuser being
created, the command fails with "Error: That name is already taken".

It's probably safe to assume that user is the one we expect. This parses
the output, treating it as successful so it can be skipped next time.

If it hits the catch-all, something probably failed so we exit.

* Use the cache for persistence

Updates the .superuser_created file to be placed in /cache so that it
gets persisted in a volume between config tweaks and container rebuilds.

Also makes `TA_PASSWORD` required always, because it seems to be needed
by tubearchivist/config/settings.py to generate a secret key.

* Let it work outside Docker

If /cache doesn't exist (i.e. when it's not running in Docker), this
falls back to a `cache` dir in the current working directory instead.

Also renames the file to 'initsu.lock' rather than having it hidden.

* Use flexible fallback path for `celery` command
2022-06-22 18:29:46 +07:00
simon
49d33a2765 Improved Cookie handeling, #build
Changed:
- Cookie: Use IO Stream from Redis directly for cookies
- Cookie: Don't load invalid cookie
- API: Import cookie with PUT request
- Redis: Don't expire Redis messages by default
- Redis: Connections expire automatically
2022-06-21 08:14:01 +07:00
simon
ecc58f6c11 API: note about release lagging behind 2022-06-21 08:10:00 +07:00
simon
e5f43e5fe9 API: implement cookie PUT request to import cookie 2022-06-21 08:06:38 +07:00
simon
499c47c7a1 move set_cookie to separate method for reusabliity 2022-06-21 08:01:33 +07:00
simon
2cf30e1127 refactor: default set_message in RedisArchivist to True 2022-06-16 10:37:46 +07:00
simon
ebfc4a349f center title and tiles 2022-06-15 18:30:06 +07:00
simon
150c1dc273 add tiles to readme 2022-06-15 18:18:52 +07:00
simon
30abbe9be7 rewrite cookie into redis from io stream, auto validate 2022-06-15 17:54:05 +07:00
simon
40e4ef0e05 auto expire redis connections after 3600secs 2022-06-15 16:36:41 +07:00
simon
2ceb1b701a consolidate config of cookie revoke 2022-06-15 15:39:24 +07:00
simon
2ad093a9a8 handle cookiejar.LoadError dont import invalid cookie 2022-06-15 10:39:48 +07:00
simon
09a94d0df5 set relative values directly with path arg 2022-06-15 10:27:29 +07:00
simon
f7f4ca7728 API update, #build
Changed:
- API: Added Task get view
- Added is_locked method for redis lock check
- Updaded base and libs
2022-06-15 09:24:01 +07:00
simon
83a90000c6 bump base image 2022-06-15 09:23:41 +07:00
lamusmaser
bbb16bb3c2 Update TaskAPIView with GET - #257 PR (#258)
* Initial commit for GET response for TaskAPIView.

* Update for missing space - linting issue.

* Additional linting fixes.

* add is_locked method to check if lock is set

* Update to use `.is_locked` method and add decorator.

* Fix linting issue.

* Fix doubled "rescan" call for locked file.
Removed call to ".owned()" under "is_locked".

* Commenting out GET call in TaskAPI view to revert change for testing.

* Commenting is_locked function to see if Server Response 500 is stopped.

* Reassert is_locked function within RedisArchivist class.

* Create test GET responder.

* Reverting simple GET response change.

* Reapplying simple GET response for `/api/task/`.

* Reapplying change with modification to lock key.

* Documentation update for new GET calls.

* README: fix returned value as `bool` instead of `str`.

* Updating the `is_locked` key reference to "rescan" and "downloading" to fix which key is being retrieved.

* Use dictionary keys, rather than line-by-line statements.

* Fix typo in README for Task View.

Co-authored-by: simon <simobilleter@gmail.com>
2022-06-15 09:15:59 +07:00
simon
4d9ee4494f bump requests 2022-06-14 14:26:49 +07:00
simon
eeeabca8c2 bump dependencies 2022-06-07 17:09:49 +07:00
simon
bb0f3dad1a update roadmap 2022-06-04 11:19:47 +07:00
simon
9c0c263fce new docker build for build server task 2022-06-04 11:16:46 +07:00
73 changed files with 3388 additions and 1334 deletions

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
github: bbilly1
ko_fi: bbilly1
custom: https://paypal.me/bbilly1

53
.github/ISSUE_TEMPLATE/BUG-REPORT.yml vendored Normal file
View File

@@ -0,0 +1,53 @@
name: Bug Report
description: File a bug report
title: "[Bug]: "
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to help improve this project!
- type: checkboxes
id: latest
attributes:
label: Latest and Greatest
options:
- label: I'm running the latest version of Tube Archivist and have read the [release notes](https://github.com/tubearchivist/tubearchivist/releases/latest).
required: true
- type: input
id: os
attributes:
label: Operating System
description: On what operating system are you running Tube Archivist on?
placeholder: ex. Linux, Unraid, Synology...
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: Your Bug Report
value: "## Describe the bug\n\n## Steps To Reproduce\n\n## Expected behavior"
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant Docker logs. This will be automatically formatted into code, so no need for backticks.
render: shell
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false

View File

@@ -0,0 +1,37 @@
name: Feature Request
description: Create a new feature request
title: "[Feature Request]: "
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to help improve this project!
- type: checkboxes
id: already
attributes:
label: Already implemented?
options:
- label: I have read through the [wiki](https://github.com/tubearchivist/tubearchivist/wiki).
required: true
- label: I understand the [scope](https://github.com/tubearchivist/tubearchivist/wiki/FAQ) of this project and am aware of the [known limitations](https://github.com/tubearchivist/tubearchivist#known-limitations) and my idea is not already on the [roadmap](https://github.com/tubearchivist/tubearchivist#roadmap).
required: true
- type: textarea
id: description
attributes:
label: Your Feature Request
value: "## Is your feature request related to a problem? Please describe.\n\n## Describe the solution you'd like\n\n## Additional context"
placeholder: Tell us what you see!
validations:
required: true
- type: checkboxes
id: help
attributes:
label: Your help is needed!
description: This project is ambitious as it is, please contribute.
options:
- label: Yes I can help with this feature request!
required: false

View File

@@ -0,0 +1,45 @@
name: Installation Help
description: There is an issue with installing or configuring Tube Archivist
title: "[Installation]: "
body:
- type: markdown
attributes:
value: |
This is most likely not the best place to ask for installation help. There is a helpful community on [Discord](https://github.com/tubearchivist/tubearchivist#connect).
- type: checkboxes
id: instructions
attributes:
label: Installation instructions
options:
- label: I have read and understand the [installation instructions](https://github.com/tubearchivist/tubearchivist#installing-and-updating).
required: true
- label: My issue is not described in the [potential pitfalls](https://github.com/tubearchivist/tubearchivist#potential-pitfalls) section.
required: true
- type: input
id: os
attributes:
label: Operating System
description: On what operating system do you want to install Tube Archivist on?
placeholder: ex. Linux, Unraid, Synology...
validations:
required: true
- type: textarea
id: description
attributes:
label: Your installation or setup question
placeholder: Describe your issue
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant Docker logs. This will be automatically formatted into code, so no need for backticks.
render: shell
validations:
required: true

View File

@@ -30,7 +30,25 @@ This is my setup I have landed on, YMMV:
- This `deploy.sh` script is not meant to be universally usable for every possible environment but could serve as an idea on how to automatically rebuild containers to test changes - customize to your liking. - This `deploy.sh` script is not meant to be universally usable for every possible environment but could serve as an idea on how to automatically rebuild containers to test changes - customize to your liking.
## Working with Elasticsearch ## Working with Elasticsearch
Additionally to the required services as listed in the example docker-compose file, the **Dev Tools** of [Kibana](https://www.elastic.co/guide/en/kibana/current/docker.html) are invaluable for running and testing Elasticsearch queries. Additionally to the required services as listed in the example docker-compose file, the **Dev Tools** of [Kibana](https://www.elastic.co/guide/en/kibana/current/docker.html) are invaluable for running and testing Elasticsearch queries.
**Quick start**
Generate your access token in Elasitcsearch:
```bash
bin/elasticsearch-service-tokens create elastic/kibana kibana
```
Example docker compose, use same version as for Elasticsearch:
```yml
kibana:
image: docker.elastic.co/kibana/kibana:0.0.0
container_name: kibana
environment:
- "ELASTICSEARCH_HOSTS=http://archivist-es:9200"
- "ELASTICSEARCH_SERVICEACCOUNTTOKEN=<your-token-here>"
ports:
- "5601:5601"
```
If you want to run queries on the Elasticsearch container directly from your host with for example `curl` or something like *postman*, you might want to **publish** the port 9200 instead of just **exposing** it. If you want to run queries on the Elasticsearch container directly from your host with for example `curl` or something like *postman*, you might want to **publish** the port 9200 instead of just **exposing** it.

View File

@@ -3,18 +3,18 @@
# First stage to build python wheel # First stage to build python wheel
FROM python:3.10.4-slim-bullseye AS builder FROM python:3.10.8-slim-bullseye AS builder
ARG TARGETPLATFORM ARG TARGETPLATFORM
RUN apt-get update RUN apt-get update
RUN apt-get install -y --no-install-recommends build-essential gcc RUN apt-get install -y --no-install-recommends build-essential gcc libldap2-dev libsasl2-dev libssl-dev
# install requirements # install requirements
COPY ./tubearchivist/requirements.txt /requirements.txt COPY ./tubearchivist/requirements.txt /requirements.txt
RUN pip install --user -r requirements.txt RUN pip install --user -r requirements.txt
# build final image # build final image
FROM python:3.10.4-slim-bullseye as tubearchivist FROM python:3.10.8-slim-bullseye as tubearchivist
ARG TARGETPLATFORM ARG TARGETPLATFORM
ARG INSTALL_DEBUG ARG INSTALL_DEBUG
@@ -54,12 +54,11 @@ RUN if [ "$INSTALL_DEBUG" ] ; then \
; fi ; fi
# make folders # make folders
RUN mkdir /cache RUN mkdir /cache /youtube /app
RUN mkdir /youtube
RUN mkdir /app
# copy config files # copy config files
COPY docker_assets/nginx.conf /etc/nginx/sites-available/default COPY docker_assets/nginx.conf /etc/nginx/sites-available/default
RUN sed -i 's/^user www\-data\;$/user root\;/' /etc/nginx/nginx.conf
# copy application into container # copy application into container
COPY ./tubearchivist /app COPY ./tubearchivist /app

View File

@@ -1,8 +1,11 @@
![Tube Archivist](assets/tube-archivist-banner.jpg?raw=true "Tube Archivist Banner") ![Tube Archivist](assets/tube-archivist-banner.jpg?raw=true "Tube Archivist Banner")
<center><h1>Your self hosted YouTube media server</h1></center> <h1 align="center">Your self hosted YouTube media server</h1>
<div align="center">
Tube Archivist has a new home: https://github.com/tubearchivist/tubearchivist <a href="https://github.com/bbilly1/tilefy" target="_blank"><img src="https://tiles.tilefy.me/t/tubearchivist-docker.png" alt="tubearchivist-docker" title="Tube Archivist Docker Pulls" height="50" width="200"/></a>
<a href="https://github.com/bbilly1/tilefy" target="_blank"><img src="https://tiles.tilefy.me/t/tubearchivist-github-star.png" alt="tubearchivist-github-star" title="Tube Archivist GitHub Stars" height="50" width="200"/></a>
<a href="https://github.com/bbilly1/tilefy" target="_blank"><img src="https://tiles.tilefy.me/t/tubearchivist-github-forks.png" alt="tubearchivist-github-forks" title="Tube Archivist GitHub Forks" height="50" width="200"/></a>
</div>
## Table of contents: ## Table of contents:
* [Wiki](https://github.com/tubearchivist/tubearchivist/wiki) with [FAQ](https://github.com/tubearchivist/tubearchivist/wiki/FAQ) * [Wiki](https://github.com/tubearchivist/tubearchivist/wiki) with [FAQ](https://github.com/tubearchivist/tubearchivist/wiki/FAQ)
@@ -60,6 +63,8 @@ Once your YouTube video collection grows, it becomes hard to search and find a s
## Installing and updating ## Installing and updating
Take a look at the example `docker-compose.yml` file provided. Use the *latest* or the named semantic version tag. The *unstable* tag is for intermediate testing and as the name implies, is **unstable** and not be used on your main installation but in a [testing environment](CONTRIBUTING.md). Take a look at the example `docker-compose.yml` file provided. Use the *latest* or the named semantic version tag. The *unstable* tag is for intermediate testing and as the name implies, is **unstable** and not be used on your main installation but in a [testing environment](CONTRIBUTING.md).
For minimal system requirements, the Tube Archivist stack needs around 2GB of available memory for a small testing setup and around 4GB of available memory for a mid to large sized installation.
Tube Archivist depends on three main components split up into separate docker containers: Tube Archivist depends on three main components split up into separate docker containers:
### Tube Archivist ### Tube Archivist
@@ -69,6 +74,7 @@ The main Python application that displays and serves your video collection, buil
- And another volume to save application data at **/cache**. - And another volume to save application data at **/cache**.
- The environment variables `ES_URL` and `REDIS_HOST` are needed to tell Tube Archivist where Elasticsearch and Redis respectively are located. - The environment variables `ES_URL` and `REDIS_HOST` are needed to tell Tube Archivist where Elasticsearch and Redis respectively are located.
- The environment variables `HOST_UID` and `HOST_GID` allows Tube Archivist to `chown` the video files to the main host system user instead of the container user. Those two variables are optional, not setting them will disable that functionality. That might be needed if the underlying filesystem doesn't support `chown` like *NFS*. - The environment variables `HOST_UID` and `HOST_GID` allows Tube Archivist to `chown` the video files to the main host system user instead of the container user. Those two variables are optional, not setting them will disable that functionality. That might be needed if the underlying filesystem doesn't support `chown` like *NFS*.
- Set the environment variable `TA_HOST` to match with the system running Tube Archivist. This can be a domain like *example.com*, a subdomain like *ta.example.com* or an IP address like *192.168.1.20*, add without the protocol and without the port. You can add multiple hostnames separated with a space. Any wrong configurations here will result in a `Bad Request (400)` response.
- Change the environment variables `TA_USERNAME` and `TA_PASSWORD` to create the initial credentials. - Change the environment variables `TA_USERNAME` and `TA_PASSWORD` to create the initial credentials.
- `ELASTIC_PASSWORD` is for the password for Elasticsearch. The environment variable `ELASTIC_USER` is optional, should you want to change the username from the default *elastic*. - `ELASTIC_PASSWORD` is for the password for Elasticsearch. The environment variable `ELASTIC_USER` is optional, should you want to change the username from the default *elastic*.
- For the scheduler to know what time it is, set your timezone with the `TZ` environment variable, defaults to *UTC*. - For the scheduler to know what time it is, set your timezone with the `TZ` environment variable, defaults to *UTC*.
@@ -82,8 +88,21 @@ Should that not be an option, the Tube Archivist container takes these two addit
Changing any of these two environment variables will change the files *nginx.conf* and *uwsgi.ini* at startup using `sed` in your container. Changing any of these two environment variables will change the files *nginx.conf* and *uwsgi.ini* at startup using `sed` in your container.
### LDAP Authentication
You can configure LDAP with the following environment variables:
- `TA_LDAP` (ex: `true`) Set to anything besides empty string to use LDAP authentication **instead** of local user authentication.
- `TA_LDAP_SERVER_URI` (ex: `ldap://ldap-server:389`) Set to the uri of your LDAP server.
- `TA_LDAP_DISABLE_CERT_CHECK` (ex: `true`) Set to anything besides empty string to disable certificate checking when connecting over LDAPS.
- `TA_LDAP_BIND_DN` (ex: `uid=search-user,ou=users,dc=your-server`) DN of the user that is able to perform searches on your LDAP account.
- `TA_LDAP_BIND_PASSWORD` (ex: `yoursecretpassword`) Password for the search user.
- `TA_LDAP_USER_BASE` (ex: `ou=users,dc=your-server`) Search base for user filter.
- `TA_LDAP_USER_FILTER` (ex: `(objectClass=user)`) Filter for valid users. Login usernames are automatically matched using `uid` and does not need to be specified in this filter.
When LDAP authentication is enabled, django passwords (e.g. the password defined in TA_PASSWORD), will not allow you to login, only the LDAP server is used.
### Elasticsearch ### Elasticsearch
**Note**: Newest Tube Archivist depends on Elasticsearch version 7.17 to provide an automatic updatepath in the future. **Note**: Tube Archivist depends on Elasticsearch 8.
Use `bbilly1/tubearchivist-es` to automatically get the recommended version, or use the official image with the version tag in the docker-compose file. Use `bbilly1/tubearchivist-es` to automatically get the recommended version, or use the official image with the version tag in the docker-compose file.
@@ -111,9 +130,8 @@ You will see the current version number of **Tube Archivist** in the footer of t
### Alternative installation instructions: ### Alternative installation instructions:
- **arm64**: The Tube Archivist container is multi arch, so is Elasticsearch. RedisJSON doesn't offer arm builds, you can use `bbilly1/rejson`, an unofficial rebuild for arm64. - **arm64**: The Tube Archivist container is multi arch, so is Elasticsearch. RedisJSON doesn't offer arm builds, you can use `bbilly1/rejson`, an unofficial rebuild for arm64.
- **Synology**: There is a [discussion thread](https://github.com/tubearchivist/tubearchivist/discussions/48) with Synology installation instructions.
- **Unraid**: The three containers needed are all in the Community Applications. First install `TubeArchivist RedisJSON` followed by `TubeArchivist ES`, and finally you can install `TubeArchivist`. If you have unraid specific issues, report those to the [support thread](https://forums.unraid.net/topic/114073-support-crocs-tube-archivist/ "support thread").
- **Helm Chart**: There is a Helm Chart available at https://github.com/insuusvenerati/helm-charts. Mostly self-explanatory but feel free to ask questions in the discord / subreddit. - **Helm Chart**: There is a Helm Chart available at https://github.com/insuusvenerati/helm-charts. Mostly self-explanatory but feel free to ask questions in the discord / subreddit.
- **Wiki**: There are additional helpful installation instructions in the [wiki](https://github.com/tubearchivist/tubearchivist/wiki/Installation) for Unraid, Truenas and Synology.
## Potential pitfalls ## Potential pitfalls
@@ -131,12 +149,12 @@ To apply the change permanently depends on your host operating system:
- On any other platform look up in the documentation on how to pass kernel parameters. - On any other platform look up in the documentation on how to pass kernel parameters.
### Permissions for elasticsearch ### Permissions for elasticsearch
If you see a message similar to `AccessDeniedException[/usr/share/elasticsearch/data/nodes]` when initially starting elasticsearch, that means the container is not allowed to write files to the volume. If you see a message similar to `failed to obtain node locks, tried [/usr/share/elasticsearch/data]` and `maybe these locations are not writable` when initially starting elasticsearch, that probably means the container is not allowed to write files to the volume.
That's most likely the case when you run `docker-compose` as an unprivileged user. To fix that issue, shutdown the container and on your host machine run: To fix that issue, shutdown the container and on your host machine run:
``` ```
chown 1000:0 /path/to/mount/point chown 1000:0 -R /path/to/mount/point
``` ```
This will match the permissions with the **UID** and **GID** of elasticsearch within the container and should fix the issue. This will match the permissions with the **UID** and **GID** of elasticsearch process within the container and should fix the issue.
### Disk usage ### Disk usage
The Elasticsearch index will turn to *read only* if the disk usage of the container goes above 95% until the usage drops below 90% again, you will see error messages like `disk usage exceeded flood-stage watermark`, [link](https://github.com/tubearchivist/tubearchivist#disk-usage). The Elasticsearch index will turn to *read only* if the disk usage of the container goes above 95% until the usage drops below 90% again, you will see error messages like `disk usage exceeded flood-stage watermark`, [link](https://github.com/tubearchivist/tubearchivist#disk-usage).
@@ -165,16 +183,16 @@ We have come far, nonetheless we are not short of ideas on how to improve and ex
- [ ] Show similar videos on video page - [ ] Show similar videos on video page
- [ ] Multi language support - [ ] Multi language support
- [ ] Show total video downloaded vs total videos available in channel - [ ] Show total video downloaded vs total videos available in channel
- [ ] Make items in grid row configurable to use more of the screen
- [ ] Add statistics of index - [ ] Add statistics of index
- [ ] Download speed schedule ([#198](https://github.com/tubearchivist/tubearchivist/issues/198)) - [ ] Download speed schedule ([#198](https://github.com/tubearchivist/tubearchivist/issues/198))
- [ ] Implement complete offline media file import from json file ([#138](https://github.com/tubearchivist/tubearchivist/issues/138))
- [ ] Filter and query in search form, search by url query ([#134](https://github.com/tubearchivist/tubearchivist/issues/134), [#139](https://github.com/tubearchivist/tubearchivist/issues/139))
- [ ] Auto ignore videos by keyword ([#163](https://github.com/tubearchivist/tubearchivist/issues/163)) - [ ] Auto ignore videos by keyword ([#163](https://github.com/tubearchivist/tubearchivist/issues/163))
- [ ] Custom searchable notes to videos, channels, playlists ([#144](https://github.com/tubearchivist/tubearchivist/issues/144)) - [ ] Custom searchable notes to videos, channels, playlists ([#144](https://github.com/tubearchivist/tubearchivist/issues/144))
- [ ] Download video comments - [ ] Download video comments
Implemented: Implemented:
- [X] Implement complete offline media file import from json file [2022-08-20]
- [X] Filter and query in search form, search by url query [2022-07-23]
- [X] Make items in grid row configurable to use more of the screen [2022-06-04]
- [X] Add passing browser cookies to yt-dlp [2022-05-08] - [X] Add passing browser cookies to yt-dlp [2022-05-08]
- [X] Add [SponsorBlock](https://sponsor.ajay.app/) integration [2022-04-16] - [X] Add [SponsorBlock](https://sponsor.ajay.app/) integration [2022-04-16]
- [X] Implement per channel settings [2022-03-26] - [X] Implement per channel settings [2022-03-26]
@@ -196,13 +214,22 @@ Implemented:
## Known limitations ## Known limitations
- Video files created by Tube Archivist need to be playable in your browser of choice. Not every codec is compatible with every browser and might require some testing with format selection. - Video files created by Tube Archivist need to be playable in your browser of choice. Not every codec is compatible with every browser and might require some testing with format selection.
- Every limitation of **yt-dlp** will also be present in Tube Archivist. If **yt-dlp** can't download or extract a video for any reason, Tube Archivist won't be able to either. - Every limitation of **yt-dlp** will also be present in Tube Archivist. If **yt-dlp** can't download or extract a video for any reason, Tube Archivist won't be able to either.
- For now this is meant to be run in a trusted network environment. Not everything is properly authenticated.
- There is currently no flexibility in naming of the media files. - There is currently no flexibility in naming of the media files.
## Donate ## Donate
The best donation to **Tube Archivist** is your time, take a look at the [contribution page](CONTRIBUTING.md) to get started. The best donation to **Tube Archivist** is your time, take a look at the [contribution page](CONTRIBUTING.md) to get started.
Second best way to support the development is to provide for caffeinated beverages: Second best way to support the development is to provide for caffeinated beverages:
* [GitHub Sponsor](https://github.com/sponsors/bbilly1) become a sponsor here on GitHub
* [Paypal.me](https://paypal.me/bbilly1) for a one time coffee * [Paypal.me](https://paypal.me/bbilly1) for a one time coffee
* [Paypal Subscription](https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-03770005GR991451KMFGVPMQ) for a monthly coffee * [Paypal Subscription](https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-03770005GR991451KMFGVPMQ) for a monthly coffee
* [ko-fi.com](https://ko-fi.com/bbilly1) for an alternative platform * [ko-fi.com](https://ko-fi.com/bbilly1) for an alternative platform
## Sponsor
Big thank you to [Digitalocean](https://www.digitalocean.com/) for generously donating credit for the tubearchivist.com VPS and buildserver.
<p>
<a href="https://www.digitalocean.com/">
<img src="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/PoweredByDO/DO_Powered_by_Badge_blue.svg" width="201px">
</a>
</p>

View File

@@ -18,11 +18,7 @@ set -e
function sync_blackhole { function sync_blackhole {
# docker commands need sudo, only build amd64
host="blackhole.local" host="blackhole.local"
read -sp 'Password: ' remote_pw
export PASS=$remote_pw
rsync -a --progress --delete-after \ rsync -a --progress --delete-after \
--exclude ".git" \ --exclude ".git" \
@@ -32,8 +28,8 @@ function sync_blackhole {
--exclude "db.sqlite3" \ --exclude "db.sqlite3" \
. -e ssh "$host":tubearchivist . -e ssh "$host":tubearchivist
echo "$PASS" | ssh "$host" 'sudo -S docker buildx build --platform linux/amd64 -t bbilly1/tubearchivist:latest tubearchivist --load 2>/dev/null' ssh "$host" 'docker build -t bbilly1/tubearchivist --build-arg TARGETPLATFORM="linux/amd64" tubearchivist'
echo "$PASS" | ssh "$host" 'sudo -S docker compose up -d 2>/dev/null' ssh "$host" 'docker compose up -d'
} }
@@ -144,6 +140,7 @@ function sync_unstable {
} }
# new function, sync only tag, build with build server
function sync_docker { function sync_docker {
# check things # check things
@@ -152,13 +149,40 @@ function sync_docker {
return return
fi fi
echo "latest tags:"
git tag | tail -n 5 | sort -r
printf "\ncreate new version:\n"
read -r VERSION
echo "push new tag: $VERSION?"
read -rn 1
# create release tag
echo "commits since last version:"
git log "$(git describe --tags --abbrev=0)"..HEAD --oneline
git tag -a "$VERSION" -m "new release version $VERSION"
git push origin "$VERSION"
}
# old builder, sync tag, build and push locally
function sync_docker_old {
# check things
if [[ $(git branch --show-current) != 'master' ]]; then
echo 'you are not on master, dummy!'
return
fi
if [[ $(systemctl is-active docker) != 'active' ]]; then if [[ $(systemctl is-active docker) != 'active' ]]; then
echo "starting docker" echo "starting docker"
sudo systemctl start docker sudo systemctl start docker
fi fi
echo "latest tags:" echo "latest tags:"
git tag | tail -n 10 git tag | tail -n 5 | sort -r
printf "\ncreate new version:\n" printf "\ncreate new version:\n"
read -r VERSION read -r VERSION
@@ -169,14 +193,15 @@ function sync_docker {
# start build # start build
sudo docker buildx build \ sudo docker buildx build \
--platform linux/amd64,linux/arm64 \ --platform linux/amd64,linux/arm64 \
-t bbilly1/tubearchivist:latest \ -t bbilly1/tubearchivist \
-t bbilly1/tubearchivist:unstable \
-t bbilly1/tubearchivist:"$VERSION" --push . -t bbilly1/tubearchivist:"$VERSION" --push .
# create release tag # create release tag
echo "commits since last version:" echo "commits since last version:"
git log "$(git describe --tags --abbrev=0)"..HEAD --oneline git log "$(git describe --tags --abbrev=0)"..HEAD --oneline
git tag -a "$VERSION" -m "new release version $VERSION" git tag -a "$VERSION" -m "new release version $VERSION"
git push all "$VERSION" git push origin "$VERSION"
} }
@@ -191,7 +216,6 @@ elif [[ $1 == "validate" ]]; then
validate "$2" validate "$2"
elif [[ $1 == "docker" ]]; then elif [[ $1 == "docker" ]]; then
sync_docker sync_docker
sync_unstable
elif [[ $1 == "unstable" ]]; then elif [[ $1 == "unstable" ]]; then
sync_unstable sync_unstable
elif [[ $1 == "es" ]]; then elif [[ $1 == "es" ]]; then

View File

@@ -3,8 +3,8 @@ version: '3.3'
services: services:
tubearchivist: tubearchivist:
container_name: tubearchivist container_name: tubearchivist
restart: always restart: unless-stopped
image: bbilly1/tubearchivist:latest image: bbilly1/tubearchivist
ports: ports:
- 8000:8000 - 8000:8000
volumes: volumes:
@@ -15,6 +15,7 @@ services:
- REDIS_HOST=archivist-redis # don't add protocol - REDIS_HOST=archivist-redis # don't add protocol
- HOST_UID=1000 - HOST_UID=1000
- HOST_GID=1000 - HOST_GID=1000
- TA_HOST=tubearchivist.local # set your host name
- TA_USERNAME=tubearchivist # your initial TA credentials - TA_USERNAME=tubearchivist # your initial TA credentials
- TA_PASSWORD=verysecret # your initial TA credentials - TA_PASSWORD=verysecret # your initial TA credentials
- ELASTIC_PASSWORD=verysecret # set password for Elasticsearch - ELASTIC_PASSWORD=verysecret # set password for Elasticsearch
@@ -23,9 +24,9 @@ services:
- archivist-es - archivist-es
- archivist-redis - archivist-redis
archivist-redis: archivist-redis:
image: redislabs/rejson:latest # for arm64 use bbilly1/rejson image: redislabs/rejson # for arm64 use bbilly1/rejson
container_name: archivist-redis container_name: archivist-redis
restart: always restart: unless-stopped
expose: expose:
- "6379" - "6379"
volumes: volumes:
@@ -33,9 +34,9 @@ services:
depends_on: depends_on:
- archivist-es - archivist-es
archivist-es: archivist-es:
image: bbilly1/tubearchivist-es # only for amd64, or use official es 7.17.3 image: bbilly1/tubearchivist-es # only for amd64, or use official es 8.4.3
container_name: archivist-es container_name: archivist-es
restart: always restart: unless-stopped
environment: environment:
- "xpack.security.enabled=true" - "xpack.security.enabled=true"
- "ELASTIC_PASSWORD=verysecret" # matching Elasticsearch password - "ELASTIC_PASSWORD=verysecret" # matching Elasticsearch password

View File

@@ -3,18 +3,22 @@ server {
listen 8000; listen 8000;
location /cache/videos/ { location /cache/videos/ {
auth_request /api/ping/;
alias /cache/videos/; alias /cache/videos/;
} }
location /cache/channels/ { location /cache/channels/ {
auth_request /api/ping/;
alias /cache/channels/; alias /cache/channels/;
} }
location /cache/playlists/ { location /cache/playlists/ {
auth_request /api/ping/;
alias /cache/playlists/; alias /cache/playlists/;
} }
location /media/ { location /media/ {
auth_request /api/ping/;
alias /youtube/; alias /youtube/;
types { types {
text/vtt vtt; text/vtt vtt;

View File

@@ -5,13 +5,15 @@ if [[ -z "$ELASTIC_USER" ]]; then
export ELASTIC_USER=elastic export ELASTIC_USER=elastic
fi fi
ENV_VARS=("TA_USERNAME" "TA_PASSWORD" "ELASTIC_PASSWORD" "ELASTIC_USER") cachedir=/cache
for each in "${ENV_VARS[@]}"; do [[ -d $cachedir ]] || cachedir=.
if ! [[ -v $each ]]; then lockfile=${cachedir}/initsu.lock
echo "missing environment variable $each"
exit 1 required="Missing required environment variable"
fi [[ -f $lockfile ]] || : "${TA_USERNAME:?$required}"
done : "${TA_PASSWORD:?$required}"
: "${ELASTIC_PASSWORD:?$required}"
: "${TA_HOST:?$required}"
# ugly nginx and uwsgi port overwrite with env vars # ugly nginx and uwsgi port overwrite with env vars
if [[ -n "$TA_PORT" ]]; then if [[ -n "$TA_PORT" ]]; then
@@ -31,6 +33,7 @@ until curl -u "$ELASTIC_USER":"$ELASTIC_PASSWORD" "$ES_URL" -fs; do
if [[ $counter -eq 12 ]]; then if [[ $counter -eq 12 ]]; then
# fail after 2 min # fail after 2 min
echo "failed to connect to elastic search, exiting..." echo "failed to connect to elastic search, exiting..."
curl -v -u "$ELASTIC_USER":"$ELASTIC_PASSWORD" "$ES_URL"?pretty
exit 1 exit 1
fi fi
sleep 10 sleep 10
@@ -39,12 +42,27 @@ done
# start python application # start python application
python manage.py makemigrations python manage.py makemigrations
python manage.py migrate python manage.py migrate
export DJANGO_SUPERUSER_PASSWORD=$TA_PASSWORD && \
python manage.py createsuperuser --noinput --name "$TA_USERNAME" if [[ -f $lockfile ]]; then
echo -e "\e[33;1m[WARNING]\e[0m This is not the first run! Skipping" \
"superuser creation.\nTo force it, remove $lockfile"
else
export DJANGO_SUPERUSER_PASSWORD=$TA_PASSWORD
output="$(python manage.py createsuperuser --noinput --name "$TA_USERNAME" 2>&1)"
case "$output" in
*"Superuser created successfully"*)
echo "$output" && touch $lockfile ;;
*"That name is already taken."*)
echo "Superuser already exists. Creation will be skipped on next start."
touch $lockfile ;;
*) echo "$output" && exit 1
esac
fi
python manage.py collectstatic --noinput -c python manage.py collectstatic --noinput -c
nginx & nginx &
celery -A home.tasks worker --loglevel=INFO & celery -A home.tasks worker --loglevel=INFO &
celery -A home beat --loglevel=INFO \ celery -A home beat --loglevel=INFO \
-s "${BEAT_SCHEDULE_PATH:-/cache/celerybeat-schedule}" & -s "${BEAT_SCHEDULE_PATH:-${cachedir}/celerybeat-schedule}" &
uwsgi --ini uwsgi.ini uwsgi --ini uwsgi.ini

View File

@@ -5,4 +5,7 @@ pidfile = /tmp/project-master.pid
vacuum = True vacuum = True
max-requests = 5000 max-requests = 5000
socket = :8080 socket = :8080
buffer-size = 8192 buffer-size = 8192
log-5xx = true
log-4xx = true
disable-logging = true

View File

@@ -17,16 +17,20 @@ The **Subscribe to Channels** button <img src="assets/icon-add.png?raw=true" alt
You can search your indexed channels by clicking on the search icon <img src="assets/icon-search.png?raw=true" alt="search icon" width="20px" style="margin:0 5px;">. This will open a dedicated page. You can search your indexed channels by clicking on the search icon <img src="assets/icon-search.png?raw=true" alt="search icon" width="20px" style="margin:0 5px;">. This will open a dedicated page.
## Channel Detail ## Channel Detail
Each channel will get a dedicated channel detail page accessible at `/channel/<channel-id>/` of your Tube Archivist. This page shows all the videos you have downloaded from this channel plus additional metadata. Each channel will get a dedicated channel detail page accessible at `/channel/<channel-id>/` of your Tube Archivist. This page shows all the videos you have downloaded from this channel.
- If you are subscribed to the channel, an *Unsubscribe* button will show, else the *Subscribe* button will show.
- You can *Show* the channel description, that matches with the *About* tab on YouTube.
- The **Mark as Watched** button will mark all videos of this channel as watched.
- The button **Delete Channel** will delete the channel plus all videos of this channel, both media files and metadata additionally this will also delete playlists metadata belonging to that channel.
- The button **Show Playlists** will go to the [playlists](Playlists) page and filter the list to only show playlists from this channel.
### Channel Customize - If you are subscribed to the channel, an *Unsubscribe* button will show, else the *Subscribe* button will show.
Clicking on the *Configure* button will open a form with options to configure settings on a per channel basis. Any configurations here will overwrite your settings from the [settings](Settings) page. - The **Mark as Watched** button will mark all videos of this channel as watched.
- **Download Format**: Overwrite the download qualities for videos from this channel.
Additionally there is a *Channel Playlist* page, accessible at `/channel/<channel-id>/playlist/` to show all indexed playlists from this channel.
On the *Channel About* page, accessible at `/channel/<channel-id>/about/`, you can see additional metadata.
- The button **Delete Channel** will delete the channel plus all videos of this channel, both media files and metadata additionally this will also delete playlists metadata belonging to that channel.
The channel customize form gives options to change settings on a per channel basis. Any configurations here will overwrite your configurations from the [settings](Settings) page.
- **Download Format**: Overwrite the download quality for videos from this channel.
- **Auto Delete**: Automatically delete watched videos from this channel after selected days. - **Auto Delete**: Automatically delete watched videos from this channel after selected days.
- **Index Playlists**: Automatically add all Playlists with at least a video downloaded to your index. Only do this for channels where you care about playlists as this will slow down indexing new videos for having to check which playlist this belongs to. - **Index Playlists**: Automatically add all Playlists with at least a video downloaded to your index. Only do this for channels where you care about playlists as this will slow down indexing new videos for having to check which playlist this belongs to.
- **SponsorBlock**: Using [SponsorBlock](https://sponsor.ajay.app/) to get and skip sponsored content. Customize per channel: You can *disable* or *enable* SponsorBlock for certain channels only to overwrite the behavior set on the [Settings](settings) page. Selecting *unset* will remove the overwrite and your setting will fall back to the default on the settings page. - **SponsorBlock**: Using [SponsorBlock](https://sponsor.ajay.app/) to get and skip sponsored content. Customize per channel: You can *disable* or *enable* SponsorBlock for certain channels only to overwrite the behavior set on the [Settings](settings) page. Selecting *unset* will remove the overwrite and your setting will fall back to the default on the settings page.
If you have any videos pending in the download queue, a *Downloads* link will show, bringing you directly to the [downloads](Downloads) page, filtering the list by the selected channel.

View File

@@ -29,6 +29,8 @@ The **Add to Download Queue** icon <img src="assets/icon-add.png?raw=true" alt="
## The Download Queue ## The Download Queue
Below the three buttons you find the download queue. New items will get added at the bottom of the queue, the next video to download once you click on **Start Download** will be the first in the list. Below the three buttons you find the download queue. New items will get added at the bottom of the queue, the next video to download once you click on **Start Download** will be the first in the list.
You can filter the download queue with the **filter** dropdown box, the filter will show once you have more than one channel in the download queue. Select the channel to filter by name, the number in parentheses indicates how many videos you have pending from this channel. Reset the filter by selecting *all* from the dropdown. This will generate links for the top 30 channels with pending videos.
Every video in the download queue has two buttons: Every video in the download queue has two buttons:
- **Ignore**: This will remove that video from the download queue and this video will not get added again, even when you **Rescan Subscriptions**. - **Ignore**: This will remove that video from the download queue and this video will not get added again, even when you **Rescan Subscriptions**.
- **Download now**: This will give priority to this video. If the download process is already running, the prioritized video will get downloaded as soon as the current video is finished. If there is no download process running, this will start downloading this single video and stop after that. - **Download now**: This will give priority to this video. If the download process is already running, the prioritized video will get downloaded as soon as the current video is finished. If there is no download process running, this will start downloading this single video and stop after that.

View File

@@ -15,7 +15,7 @@ Defining the scope is important for the success of any project:
- A too narrow scope will make this project uninteresting and will exclude audiences that could also benefit from this project. - A too narrow scope will make this project uninteresting and will exclude audiences that could also benefit from this project.
- Not defining a scope will easily lead to misunderstandings and false hopes of where this project tries to go. - Not defining a scope will easily lead to misunderstandings and false hopes of where this project tries to go.
Of course this is subject to change, as this project continues to grow and more people contribute. Of course this is subject to change: The scope can be expanded as this project continues to grow and more people contribute.
## 2. Emby/Plex/Jellyfin/Kodi integrations ## 2. Emby/Plex/Jellyfin/Kodi integrations
Although there are similarities between these excellent projects and Tube Archivist, they have a very different use case. Trying to fit the metadata relations and database structure of a YouTube archival project into these media servers that specialize in Movies and TV shows is always going to be limiting. Although there are similarities between these excellent projects and Tube Archivist, they have a very different use case. Trying to fit the metadata relations and database structure of a YouTube archival project into these media servers that specialize in Movies and TV shows is always going to be limiting.
@@ -29,6 +29,3 @@ So Docker is the only supported installation method. If you don't have any exper
## 4. Finetuning Elasticsearch ## 4. Finetuning Elasticsearch
A minimal configuration of Elasticsearch (ES) is provided in the example docker-compose.yml file. ES is highly configurable and very interesting to learn more about. Refer to the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) if you want to get into it. A minimal configuration of Elasticsearch (ES) is provided in the example docker-compose.yml file. ES is highly configurable and very interesting to learn more about. Refer to the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) if you want to get into it.
## 5. Advanced Authentication
If you like to use things like SSO, LDAP or 2FA to login, consider using something like Authelia as a reverse proxy so this project can focus on the core task. Tube Archivist has a *remember me* checkbox at login to extend your sessions lifetime in your browser.

View File

@@ -9,7 +9,8 @@ Table of contents:
* [Settings](Settings): All the configuration options * [Settings](Settings): All the configuration options
* [Video](Video): All details of a single video and playlist navigation. * [Video](Video): All details of a single video and playlist navigation.
* [Users](Users): User management admin interface * [Users](Users): User management admin interface
* [Installation](Installation): WIP - detailed installation instructions for various platforms. * [Search](Search): Search your archive
* [Installation](Installation): Detailed installation instructions for various platforms.
## Getting Started ## Getting Started
1. [Subscribe](Channels#channels-overview) to some of your favourite YouTube channels. 1. [Subscribe](Channels#channels-overview) to some of your favourite YouTube channels.

View File

@@ -1,5 +1,12 @@
# Detailed Installation Instructions for Various Platforms # Detailed Installation Instructions for Various Platforms
## Table of Contents
- [Unraid](#unraid)
- [Truenas Scale](#truenas-scale)
- [Synology](#synology)
These are beginners guides installation instructions for additional platforms generously provided by users of these platforms. When in doubt, verify the details with the [Readme](https://github.com/tubearchivist/tubearchivist#installing-and-updating). If you see any issues here while using these instructions, please contribute.
## Unraid ## Unraid
Tube Archivist, and all if it's dependencies are located in the [community applications](https://forums.unraid.net/topic/38582-plug-in-community-applications/) store. The three containers you will need are as follows: Tube Archivist, and all if it's dependencies are located in the [community applications](https://forums.unraid.net/topic/38582-plug-in-community-applications/) store. The three containers you will need are as follows:
@@ -67,3 +74,182 @@ However, there is a step by step guide available for it's users here:
https://heavysetup.info/applications/tube-archivist/dataset/ https://heavysetup.info/applications/tube-archivist/dataset/
- Ensure you are navigating the columns under `Tube Archivist` on the left hand side of the screen - Ensure you are navigating the columns under `Tube Archivist` on the left hand side of the screen
<br />
<br />
## Synology
There are several different methods to install TubeArchivist on Synology platforms. This will focus on the available `docker` package and `docker-compose` implementations.
### Prepare Directories/Folders
Before we setup TubeArchivist, we need to setup the directories/folders. You are assumed to be logged into the Synology NAS.
#### 1. Docker Base Folder
1. Open the `File Station` utility.
2. Click on the **Create🔽** button and choose *Create New Shared Folder*.
3. **Name** the folder "Docker".
4. Add a **Description**.
5. Select the **Volume Location**.
> Note: By default, this will be where all data is stored. Change the folders as best meets your requirements.
6. Select the appropriate options from the remaining checkbox configurations.
![Synology - Create Docker Folder](assets/Synology_0.2.0_Docker-Folder-Create.png)
7. Click the **Next** button.
8. If you are going to **Encrypt** your folder, check the appropriate box and provide the Encryption Key and its confirmation.
9. Click the **Next** button.
10. On the **Advanced Settings** page, you can select the *Enable data checksum for advanced data integrity* setting. This may cause a performance impact, but will allow for potential file self-healing. **This cannot be changed later.**
> Note: This is not recommended, as we will be hosting databases within this folder.
11. If you are enabling a quota for how large the folder can get, you can select the *Enabled shared folder quota* setting and choose the maximum size this folder can grow. This can be changed later.
12. Click the **Next** button.
13. Confirm the settings, then click the **Apply** button. This will create the folder.
#### 2. TubeArchivist Base Folder
1. Open the `File Station` utility.
2. Select the "Docker" folder on the left-hand side.
3. Click on the `Create🔽` button and choose *create Folder*.
4. **Name** the folder "TubeArchivist".
#### 3. Redis Data
1. Open the `File Station` utility.
2. Select the "Docker" folder on the left-hand side.
3. Select the "TubeArchivist" folder beneath "Docker".
4. Click on the `Create🔽` button and choose *create Folder*.
5. **Name** the folder "redis".
#### 4. Elastic Search Data
1. Open the `File Station` utility.
2. Select the "Docker" folder on the left-hand side.
3. Select the "TubeArchivist" folder beneath "Docker".
4. Click on the `Create🔽` button and choose *create Folder*.
5. **Name** the folder "es".
#### 5. TubeArchivist Cache
1. Open the `File Station` utility.
2. Select the "Docker" folder on the left-hand side.
3. Select the "TubeArchivist" folder beneath "Docker".
4. Click on the `Create🔽` button and choose *create Folder*.
5. **Name** the folder "cache".
#### 6. TubeArchivist Output
1. Open the `File Station` utility.
2. Select the "Docker" folder on the left-hand side.
3. Select the "TubeArchivist" folder beneath "Docker".
4. Click on the `Create🔽` button and choose *create Folder*.
5. **Name** the folder "media".
#### 7. Confirm Folder Structure
Once all of the folders have been created, it should have a folder structure within Docker\TubeArchivist that includes "cache", "es", "media", and "redis" folders.
![Synology - Docker Folder Structure](assets/Synology_0.2.0_Docker-Folder-Structure.png)
#### 8. Change Permissions - CLI Required
> If you do not have SSH access enabled for CLI, [enable it](https://kb.synology.com/en-sg/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) before continuing.
1. Open the SSH connection to the Synology. Login as your primary `Admin` user, or the user that was enabled for SSH access.
2. Elevate your access to `root`. Steps are provided [here](https://kb.synology.com/en-sg/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet).
3. Change directories to the **Volume** where the "Docker" folder resides.
</br>Example: `cd /volume1`
4. Change directories to the "Docker" folder.
</br>Example: `cd Docker`
5. Change directories to the "TubeArchivist" folder.
</br>Example: `cd TubeArchivist`
6. Change the owner of the "redis" folder. *If correct, this does not have an output.*
</br>Example: `chown 999:100 redis`
7. Change the owner of the "es" folder. *If correct, this does not have an output.*
</br>Example: `chown 1000:1000 es`
8. Confirm that the folders have the correct permissions.
</br>Example: `ls -hl`
![Synology - Docker Folder Permissions Command](assets/Synology_0.2.0_Docker-Folder-Permissions-Commands.png)
9. Logout from root.
</br>Example: `logout`
10. Disconnect from the SSH connection.
</br>Example: `exit`
### Docker Setup
1. Install the `Docker` Synology Package.
1. Log in to your Synology NAS.
2. Open the `Package Center` utility.
3. Search for `Docker`.
4. Click `Install`.
![Synology - Install Docker Utility](assets/Synology_0.2.0_Docker-Install.png)
2. After `Docker` is installed, open the `Docker` utility.
3. Go to the `Registry` tab.
4. Search for the following `images` and download them. Follow the recommended versions for each of the images.
- `redislabs/rejson`
![Synology - Redis Image Search](assets/Synology_0.2.0_Docker-Redis-Search.png)
- `bbilly1/tubearchivist-es`
![Synology - ElasticSearch Image Search](assets/Synology_0.2.0_Docker-ES-Search.png)
- `bbilly1/tubearchivist`
![Synology - TubeArchivist Image Search](assets/Synology_0.2.0_Docker-TA-Search.png)
5. Go to the `Image` tab. From here, create an container based on each image with the associated configurations below.
- ElasticSearch
1. Select the associated image.
2. Click the **Launch** button in the top.
3. Edit the **Container Name** to be "tubearchivist-es".
4. Click on the **Advanced Settings** button.
5. In the **Advanced Settings** tab, check the box for `Enable auto-restart`.
6. In the **Volume** tab, click the **Add Folder** button and select the "Docker/TubeArchivist/es" folder, then type in `/usr/share/elasticsearch/data` for the mount path.
7. In the **Network** tab, leave the default `bridge` Network (unless you have a specific Network design that you know how to implement).
8. In the **Port Settings** tab, replace the "Auto" entry under **Local Port** with the port that will be used to connect to ElasticSearch (default is 9200).
9. In the **Port Settings** tab, select the entryline for port 9300 and ** delete** the line. It is not needed for this container.
10. The **Links** tab does not require configuration for this container.
11. In the **Environment** tab, add in the following ElasticSearch specific environment variables that may apply.
- "discovery.type=single-node"
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- "UID=1000"
- "GID=0"
- "xpack.security.enabled=true"
- "ELASTIC_PASSWORD=verysecret"
> Do not use the default password as it is very insecure.
![Synology - ElasticSearch Environment Configurations](assets/Synology_0.2.0_Docker-ES-Env-Conf.png)
12. Click on the **Apply** button.
13. Back on the **Create Container** screen, click the **Next** button.
14. Review the settings to confirm, then click the **Apply** button.
- Redis
1. Select the associated image.
2. Click the **Launch** button in the top.
3. Edit the **Container Name** to be "tubearchivist-redis".
4. Click on the **Advanced Settings** button.
5. In the **Advanced Settings** tab, check the box for `Enable auto-restart`.
6. In the **Volume** tab, click the **Add Folder** button and select the "Docker/TubeArchivist/redis" folder, then type in `/data` for the mount path.
7. In the **Network** tab, leave the default `bridge` Network (unless you have a specific Network design that you know how to implement).
8. In the **Port Settings** tab, replace the "Auto" entry under **Local Port** with the port that will be used to connect to Redis (default is 6379).
9. In the **Links** tab, select the "tubearchivist-es" container from the **Container Name** dropdown and provide it the same alias, "tubearchivist-es".
10. In the **Environment** tab, add in any Redis specific environment variables that may apply (none by default).
11. Click on the **Apply** button.
12. Back on the **Create Container** screen, click the **Next** button.
13. Review the settings to confirm, then click the **Apply** button.
- TubeArchivist
1. Select the associated image.
2. Click the **Launch** button in the top.
3. Edit the **Container Name** to be "tubearchivist".
4. Click on the **Advanced Settings** button.
5. In the **Advanced Settings** tab, check the box for `Enable auto-restart`.
6. In the **Volume** tab, click the **Add Folder** button and select the "Docker/TubeArchivist/cache" folder, then type in `/cache` for the mount path.
7. In the **Volume** tab, click the **Add Folder** button and select the "Docker/TubeArchivist/media" folder, then type in `/youtube` for the mount path.
8. In the **Network** tab, leave the default `bridge` Network (unless you have a specific Network design that you know how to implement).
9. In the **Port Settings** tab, replace the "Auto" entry under **Local Port** with the port that will be used to connect to TubeArchivist (default is 8000).
10. In the **Links** tab, select the "tubearchivist-es" container from the **Container Name** dropdown and provide it the same alias, "tubearchivist-es".
11. In the **Links** tab, select the "tubearchivist-redis" container from the **Container Name** dropdown and provide it the same alias, "tubearchivist-redis".
12. In the **Environment** tab, add in the following TubeArchivist specific environment variables that may apply. **Change the variables as-is appropriate to your use case. Follow the [README section](https://github.com/tubearchivist/tubearchivist#tube-archivist) for details on what to set each variable.**
- "TA_HOST=synology.local"
- "ES_URL=http://tubearchivist-es:9200"
- "REDIS_HOST=tubearchivist-redis"
- "HOST_UID=1000"
- "HOST_GID=1000"
- "TA_USERNAME=tubearchivist"
- "TA_PASSWORD=verysecret"
- "ELASTIC_PASSWORD=verysecret"
- "TZ=America/New_York"
> Do not use the default password as it is very insecure.
> Ensure that ELASTIC_PASSWORD matches the password used on the tubearchivist-es container.
![Synology - TubeArchivist Environment Configurations](assets/Synology_0.2.0_Docker-TA-Env-Conf.png)
13. Click on the **Apply** button.
14. Back on the **Create Container** screen, click the **Next** button.
15. Review the settings to confirm, then click the **Apply** button.
6. After the containers have been configured and started, you can go to the **Container** tab and monitor the containers.
7. To review the logs to ensure that the system has started successfully, select the "tubearchivist" container and click on the **Details** button. In the new window, go to the **Log** tab. Monitor the logs until either an error occurs or the message `celery@tubearchivist ready.` is in the logs. This may take a few minutes, especially for a first time setup.
> Note: Synology Docker presents the logs in a pagination format. If you are not seeing the logs update, check if there are additional pages.
8. After it has started, go to the location in the `TA_HOST`. This should give you the standard TubeArchivist login screen.
<!--
### Docker-Compose Setup -->
<!-- This section is a Work In Progress -->
### From there, you should be able to start up your containers and you're good to go!
If you're still having trouble, join us on [discord](https://discord.gg/AFwz8nE7BK) and come to the #synology channel.

54
docs/Search.md Normal file
View File

@@ -0,0 +1,54 @@
# Search Page
Accessible at `/search/` of your **Tube Archivist**, search your archive for Videos, Channels and Playlists - or even full text search throughout your indexed subtitles.
- All your queries are case insensitive and are normalized to lowercase.
- All your queries are analyzed for the english language, this means *singular*, *plural* and word variations like *-ing*, *-ed*, *-able* etc are treated as synonyms.
- Fuzzy search is activated for all your searches. This can catch typos in your queries or in the matching documents with one to two letters difference, depending on the query length.
- All text searches are ranked, meaning the better a match the higher ranked the result. Unless otherwise stated, queries with multiple words are processed with the `and` operator, meaning all words need to match so each word will narrow down the result.
- This will return 30 results per query, pagination is not implemented yet.
Just start typing to start a *simple* search or start your query with a primary keyword to search for a specific type and narrow down the result with secondary keywords. Secondary keywords can be in any order. Use *yes* or *no* for boolean values.
## Simple
Start your query without a keyword to make a simple query. This will search in *video titles*, *channel names* and *playlist titles* and will return matching videos, channels and playlists. Keyword searches will return more results in a particular category due to the fact that more fields are searched for matches.
## Video
Start your query with the primary keyword `video:` to search for videos only. This will search through the *video titles*, *tags* and *category* fields. Narrow your search down with secondary keywords:
- `channel:` search for videos matching the channel name.
- `active:` is a boolean value, to search for videos that are still active on youtube or that are not active any more.
**Example**:
- `video:learn python channel:corey shafer active:yes`: This will return all videos with the term *Learn Python* from the channel *Corey Shafer* that are still *Active* on YouTube.
- `video: channel:tom scott active:no`: Note the omitted term after the primary key, this will show all videos from the channel *Tom Scott* that are no longer active on YouTube.
## Channel
Start with the `channel:` primary keyword to search for channels matching your query. This will search through the *channel name* and *channel description* fields. Narrow your search down with secondary keywords:
- `subscribed:` is a boolean value, search for channels that you are subscribed to or not.
- `active:` is a boolean value, to search for channels that are still active on YouTube or that are no longer active.
**Example**:
- `channel:linux subscribed:yes`: Search for channels with the term *Linux* that you are subscribed to.
- `channel: active:no`: Note the omitted term after the primary key, this will return all channels that are no longer active on YouTube.
## Playlist
Start your query with the primary keyword `playlist:` to search for playlists only. This will search through the *playlist title* and *playlist description* fields. Narrow down your search with these secondary keywords:
- `subscribed`: is a boolean value, search for playlists that you are subscribed to or not.
- `active:` is a boolean value, to search for playlists that are still active on YouTube or that are no longer active.
**Example**:
- `playlist:backend engineering subscribed:yes`: Search for playlists about *Backend Engineering* that you are subscribed to.
- `playlist: active:yes subscribed:yes`: Note the omitted primary search term, this will return all playlists active on YouTube that you are subscribed to.
- `playlist:html css active:yes`: Search for playlists containing *HTML CSS* that are still active on YouTube.
## Full
Start a full text search by beginning your query with the primary keyword `full:`. This will search through your indexed Subtitles showing segments with possible matches. This will only show any results if you have activated *subtitle download and index* on the settings page. The operator for full text searches is `or` meaning when searching for multiple words not all words need to match, but additional words will change the ranking of the result, the more words match and the better they match, the higher ranked the result. The matching words will get highlighted in the text preview.
Clicking the play button on the thumbnail will open the inplace player at the timestamp from where the segment starts. Same when clicking the video title, this will open the video page and put the player at the segment timestamp. This will overwrite any previous playback position.
Narrow down your search with these secondary keywords:
- `lang`: Search for matches only within a language. Use the same two letter ISO country code as you have set on the settings page.
- `source`: Can either be *auto* to search through auto generated subtitles only or *user* to search through user uploaded subtitles only.
**Example**:
- `full:contribute to open source lang:en` search for subtitle segments matching with the words *Contribute to Open Source* in the language *en*.
- `full:flight simulator cockpit source:user` to search for the words *Flight Simulator Cockpit* from *user* uploaded subtitle segments.

View File

@@ -36,15 +36,18 @@ Additional settings passed to yt-dlp.
Importing your YouTube Cookie into Tube Archivist allows yt-dlp to bypass age restrictions, gives access to private videos and your *watch later* or *liked videos*. Importing your YouTube Cookie into Tube Archivist allows yt-dlp to bypass age restrictions, gives access to private videos and your *watch later* or *liked videos*.
### Security concerns ### Security concerns
Cookies are used to store your session and contain your access token to your google account, this file can be used to take over your account. Treat that file with utmost care as you would any other password or credential. *Tube Archivist* stores your cookie in Redis and will automatically append it to yt-dlp for every request. Cookies are used to store your session and contain your access token to your google account, this information can be used to take over your account. Treat that data with utmost care as you would any other password or credential. *Tube Archivist* stores your cookie in Redis and will automatically append it to yt-dlp for every request.
### Export your cookie ### Auto import
Easiest way to import your cookie is to use the **Tube Archivist Companion** [browser extension](https://github.com/tubearchivist/browser-extension) for Firefox and Chrome.
### Alternative Manual Export your cookie
- Install **Cookies.txt** addon for [chrome](https://chrome.google.com/webstore/detail/get-cookiestxt/bgaddhkoddajcdgocldbbfleckgcbcid) or [firefox](https://addons.mozilla.org/firefox/addon/cookies-txt). - Install **Cookies.txt** addon for [chrome](https://chrome.google.com/webstore/detail/get-cookiestxt/bgaddhkoddajcdgocldbbfleckgcbcid) or [firefox](https://addons.mozilla.org/firefox/addon/cookies-txt).
- Visit YouTube and login with whichever YouTube account you wish to use to generate the cookies. - Visit YouTube and login with whichever YouTube account you wish to use to generate the cookies.
- Click on the extension icon in the toolbar - it will drop down showing the active cookies for YT. - Click on the extension icon in the toolbar - it will drop down showing the active cookies for YT.
- Click Export to export the cookies, filename is by default *cookies.google.txt*. - Click Export to export the cookies, filename is by default *cookies.google.txt*.
### Import your cookie ### Alternative Manual Import your cookie
Place the file *cookies.google.txt* into the *cache/import* folder of Tube Archivist and enable the cookie import. Once you click on *Update Application Configurations* to save your changes, your cookie will get imported and stored internally. Place the file *cookies.google.txt* into the *cache/import* folder of Tube Archivist and enable the cookie import. Once you click on *Update Application Configurations* to save your changes, your cookie will get imported and stored internally.
Once imported, a **Validate Cookie File** button will show, where you can confirm if your cookie is working or not. Once imported, a **Validate Cookie File** button will show, where you can confirm if your cookie is working or not.
@@ -95,7 +98,7 @@ That's the equivalent task as run from the downloads page looking through your c
Start downloading all videos currently in the download queue. Start downloading all videos currently in the download queue.
## Refresh Metadata ## Refresh Metadata
Rescan videos, channels and playlists on youtube and update metadata periodically. This will also deactivate an item and exclude it from future refreshes if the link on YouTube is no longer available. This task is meant to be run once per day, set your schedule accordingly. Rescan videos, channels and playlists on youtube and update metadata periodically. This will also refresh your subtitles based on your current settings. If an item is no longer available on YouTube, this will deactivate it and exclude it from future refreshes. This task is meant to be run once per day, set your schedule accordingly.
The field **Refresh older than x days** takes a number where TubeArchivist will consider an item as *outdated*. This value is used to calculate how many items need to be refreshed today based on the total indexed. This will spread out the requests to YouTube. Sensible value here is **90** days. The field **Refresh older than x days** takes a number where TubeArchivist will consider an item as *outdated*. This value is used to calculate how many items need to be refreshed today based on the total indexed. This will spread out the requests to YouTube. Sensible value here is **90** days.
@@ -113,25 +116,34 @@ Additional database functionality.
The button **Delete all queued** will delete all pending videos from the download queue. The button **Delete all ignored** will delete all videos you have previously ignored. The button **Delete all queued** will delete all pending videos from the download queue. The button **Delete all ignored** will delete all videos you have previously ignored.
## Manual Media Files Import ## Manual Media Files Import
So far this depends on the video you are trying to import to be still available on YouTube to get the metadata. Add the files you'd like to import to the */cache/import* folder. Then start the process from the settings page *Manual Media Files Import*. Make sure to follow one of the two methods below. Add the files you'd like to import to the */cache/import* folder. Only add files, don't add subdirectories. All files you are adding, need to have the same *base name* as the media file. Then start the process from the settings page *Manual Media Files Import*.
Valid media extensions are *.mp4*, *.mkv* or *.webm*. If you have other file extensions or incompatible codecs, convert them first to mp4. **Tube Archivist** can identify the videos with one of the following methods.
### Method 1: ### Method 1:
Add a matching *.json* file with the media file. Both files need to have the same base name, for example: Add a matching *.info.json* file with the media file. Both files need to have the same base name, for example:
- For the media file: \<base-name>.mp4 - For the media file: `<base-name>.mp4`
- For the JSON file: \<base-name>.info.json - For the JSON file: `<base-name>.info.json`
- Alternate JSON file: \<base-name>.json
**Tube Archivist** then looks for the 'id' key within the JSON file to identify the video. The import process then looks for the 'id' key within the JSON file to identify the video.
### Method 2: ### Method 2:
Detect the YouTube ID from filename, this accepts the default yt-dlp naming convention for file names like: Detect the YouTube ID from filename, this accepts the default yt-dlp naming convention for file names like:
- \<base-name>[\<youtube-id>].mp4 - `<base-name>[<youtube-id>].mp4`
- The YouTube ID in square brackets at the end of the filename is the crucial part. - The YouTube ID in square brackets at the end of the filename is the crucial part.
### Offline import:
**NOTE**: This is untested. Please provide feedback.
If the video you are trying to import is not available on YouTube any more, **Tube Archivist** can import the required metadata:
- The file `<base-name>.info.json` is required to extract the required information.
- Add the thumbnail as `<base-name>.<ext>`, where valid file extensions are *.jpg*, *.png* or *.webp*. If there is no thumbnail file, **Tube Archivist** will try to extract it from the media file or will fallback to a default thumbnail.
- Add subtitles as `<base-name>.<lang>.vtt` where *lang* is the two letter ISO country code. This will archive all subtitle files you add to the import folder, independent from your configurations. Subtitles can be archived and used in the player, but they can't be indexed or made searchable due to the fact, that they have a very different structure than the subtitles as **Tube Archivist** needs them.
- For videos, where the whole channel is not available any more, you can add the `<channel-id>.info.json` file as generated by *youtube-dl/yt-dlp* to get the full metadata. Alternatively **Tube Archivist** will extract as much info as possible from the video info.json file.
### Some notes: ### Some notes:
- This will **consume** the files you put into the import folder: Files will get converted to mp4 if needed (this might take a long time...) and moved to the archive, *.json* files will get deleted upon completion to avoid having duplicates on the next run. - This will **consume** the files you put into the import folder: Files will get converted to mp4 if needed (this might take a long time...) and moved to the archive, *.json* files will get deleted upon completion to avoid having duplicates on the next run.
- For best file transcoding quality, convert your media files with desired settings first before importing (#138). - For best file transcoding quality, convert your media files with desired settings first before importing.
- There should be no subdirectories added to */cache/import*, only video files. If your existing video library has video files inside subdirectories, you can get all the files into one directory by running `find ./ -mindepth 2 -type f -exec mv '{}' . \;` from the top-level directory of your existing video library. You can also delete any remaining empty subdirectories with `find ./ -mindepth 1 -type d -delete`.
- Maybe start with a subset of your files to import to make sure everything goes well... - Maybe start with a subset of your files to import to make sure everything goes well...
- Follow the logs to monitor progress and errors: `docker-compose logs -f tubearchivist`. - Follow the logs to monitor progress and errors: `docker-compose logs -f tubearchivist`.
@@ -139,7 +151,7 @@ Detect the YouTube ID from filename, this accepts the default yt-dlp naming conv
This will write or overwrite all thumbnails in the media file using the downloaded thumbnail. This is only necessary if you didn't download the files with the option *Embed Thumbnail* enabled or want to make sure all media files get the newest thumbnail. Follow the docker-compose logs to monitor progress. This will write or overwrite all thumbnails in the media file using the downloaded thumbnail. This is only necessary if you didn't download the files with the option *Embed Thumbnail* enabled or want to make sure all media files get the newest thumbnail. Follow the docker-compose logs to monitor progress.
## Backup Database ## Backup Database
This will backup your metadata into a zip file. The file will get stored at *cache/backup* and will contain the necessary files to restore the Elasticsearch index formatted **nd-json** files plus a complete export of the index in a set of conventional **json** files. This will backup your metadata into a zip file. The file will get stored at *cache/backup* and will contain the necessary files to restore the Elasticsearch index formatted **nd-json** files.
BE AWARE: This will **not** backup any media files, just the metadata from the Elasticsearch. BE AWARE: This will **not** backup any media files, just the metadata from the Elasticsearch.

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@@ -1,6 +1,40 @@
# TubeArchivist API # TubeArchivist API
Documentation of available API endpoints. Documentation of available API endpoints.
**Note: This is very early alpha and will change!**
Note:
- This is very early stages and will change!
- Check the commit history to see if a documented feature is already in your release
## Table of contents
- [Authentication](#authentication)
- [Pagination](#pagination)
**Video**
- [Video List](#video-list-view)
- [Video Single](#video-item-view)
- [Video Single Progress](#video-progress-view)
- [Video Single Sponsorblock](#sponsor-block-view) WIP
**Channel**
- [Channel List](#channel-list-view)
- [Channel Single](#channel-item-view)
- [Channel Video List](#channel-videos-view)
**Playlist**
- [Playlist List](#playlist-list-view)
- [Playlist Single](#playlist-item-view)
- [Playlist Videos List](#playlist-videos-view)
**Download queue**
- [Download Queue List](#download-queue-list-view)
- [Download Queue Single](#download-queue-item-view)
**Additional**
- [Login](#login-view)
- [Task](#task-view) WIP
- [Cookie](#cookie-view)
- [Search](#search-view)
- [Ping](#ping-view)
## Authentication ## Authentication
API token will get automatically created, accessible on the settings page. Token needs to be passed as an authorization header with every request. Additionally session based authentication is enabled too: When you are logged into your TubeArchivist instance, you'll have access to the api in the browser for testing. API token will get automatically created, accessible on the settings page. Token needs to be passed as an authorization header with every request. Additionally session based authentication is enabled too: When you are logged into your TubeArchivist instance, you'll have access to the api in the browser for testing.
@@ -22,35 +56,18 @@ response = requests.get(url, headers=headers)
## Pagination ## Pagination
The list views return a paginate object with the following keys: The list views return a paginate object with the following keys:
- page_size: int current page size set in config - page_size: *int* current page size set in config
- page_from: int first result idx - page_from: *int* first result idx
- prev_pages: array of ints of previous pages, if available - prev_pages: *array of ints* of previous pages, if available
- current_page: int current page from query - current_page: *int* current page from query
- max_hits: reached: bool if max of 10k results is reached - max_hits: *bool* if max of 10k results is reached
- last_page: int of last page link - params: *str* additional url encoded query parameters
- next_pages: array of ints of next pages - last_page: *int* of last page link
- total_hits: int total results - next_pages: *array of ints* of next pages
- total_hits: *int* total results
Pass page number as a query parameter: `page=2`. Defaults to *0*, `page=1` is redundant and falls back to *0*. If a page query doesn't return any results, you'll get `HTTP 404 Not Found`. Pass page number as a query parameter: `page=2`. Defaults to *0*, `page=1` is redundant and falls back to *0*. If a page query doesn't return any results, you'll get `HTTP 404 Not Found`.
## Login View
Return token and user ID for username and password:
POST /api/login
```json
{
"username": "tubearchivist",
"password": "verysecret"
}
```
after successful login returns
```json
{
"token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"user_id": 1
}
```
## Video List View ## Video List View
/api/video/ /api/video/
@@ -142,7 +159,7 @@ POST /api/channel/
## Playlist List View ## Playlist List View
/api/playlist/ /api/playlist/
## Playlists Item View ## Playlist Item View
/api/playlist/\<playlist_id>/ /api/playlist/\<playlist_id>/
## Playlist Videos View ## Playlist Videos View
@@ -153,6 +170,7 @@ GET /api/download/
Parameter: Parameter:
- filter: pending, ignore - filter: pending, ignore
- channel: channel-id
### Add list of videos to download queue ### Add list of videos to download queue
POST /api/download/ POST /api/download/
@@ -189,20 +207,40 @@ Add to queue previously ignored video:
DELETE /api/download/\<video_id>/ DELETE /api/download/\<video_id>/
Forget or delete from download queue Forget or delete from download queue
## Ping View ## Login View
Validate your connection with the API Return token and user ID for username and password:
GET /api/ping POST /api/login
When valid returns message with user id:
```json ```json
{ {
"response": "pong", "username": "tubearchivist",
"user": 1 "password": "verysecret"
}
```
after successful login returns
```json
{
"token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"user_id": 1
} }
``` ```
## Task View ## Task View
Start a background task GET /api/task/
POST /api/task/
Check if there is an ongoing task:
GET /api/task/
Returns:
```json
{
"rescan": false,
"downloading": false
}
```
Start a background task
POST /api/task/ POST /api/task/
```json ```json
{ {
@@ -216,11 +254,14 @@ List of valid task names:
## Cookie View ## Cookie View
Check your youtube cookie settings Check your youtube cookie settings, *status* turns to `true` if cookie has been validated.
GET /api/cookie/ GET /api/cookie/
```json ```json
{ {
"cookie_enabled": true "cookie_enabled": true,
"status": true,
"validated": <timestamp>,
"validated_str": "timestamp"
} }
``` ```
@@ -231,3 +272,42 @@ Send empty post request to validate cookie.
"cookie_validated": true "cookie_validated": true
} }
``` ```
PUT /api/cookie/
Send put request containing the cookie as a string:
```json
{
"cookie": "your-cookie-as-string"
}
```
Imports and validates cookie, returns on success:
```json
{
"cookie_import": "done",
"cookie_validated": true
}
```
Or returns status code 400 on failure:
```json
{
"cookie_import": "fail",
"cookie_validated": false
}
```
## Search View
GET /api/search/?query=\<query>
Returns search results from your query.
## Ping View
Validate your connection with the API
GET /api/ping
When valid returns message with user id:
```json
{
"response": "pong",
"user": 1
}
```

View File

@@ -22,7 +22,7 @@ class SearchProcess:
self.processed = False self.processed = False
def process(self): def process(self):
"""dedect type and process""" """detect type and process"""
if "_source" in self.response.keys(): if "_source" in self.response.keys():
# single # single
self.processed = self._process_result(self.response) self.processed = self._process_result(self.response)
@@ -37,7 +37,7 @@ class SearchProcess:
return self.processed return self.processed
def _process_result(self, result): def _process_result(self, result):
"""dedect which type of data to process""" """detect which type of data to process"""
index = result["_index"] index = result["_index"]
processed = False processed = False
if index == "ta_video": if index == "ta_video":
@@ -74,7 +74,7 @@ class SearchProcess:
media_url = urllib.parse.quote(video_dict["media_url"]) media_url = urllib.parse.quote(video_dict["media_url"])
vid_last_refresh = date_praser(video_dict["vid_last_refresh"]) vid_last_refresh = date_praser(video_dict["vid_last_refresh"])
published = date_praser(video_dict["published"]) published = date_praser(video_dict["published"])
vid_thumb_url = ThumbManager().vid_thumb_path(video_id) vid_thumb_url = ThumbManager(video_id).vid_thumb_path()
channel = self._process_channel(video_dict["channel"]) channel = self._process_channel(video_dict["channel"])
if "subtitles" in video_dict: if "subtitles" in video_dict:
@@ -113,7 +113,7 @@ class SearchProcess:
def _process_download(self, download_dict): def _process_download(self, download_dict):
"""run on single download item""" """run on single download item"""
video_id = download_dict["youtube_id"] video_id = download_dict["youtube_id"]
vid_thumb_url = ThumbManager().vid_thumb_path(video_id) vid_thumb_url = ThumbManager(video_id).vid_thumb_path()
published = date_praser(download_dict["published"]) published = date_praser(download_dict["published"])
download_dict.update( download_dict.update(

View File

@@ -50,5 +50,5 @@ class TaskHandler:
print("download pending") print("download pending")
running = download_pending.delay() running = download_pending.delay()
print("set task id: " + running.id) print("set task id: " + running.id)
RedisArchivist().set_message("dl_queue_id", running.id, expire=False) RedisArchivist().set_message("dl_queue_id", running.id)
return {"success": True} return {"success": True}

View File

@@ -12,6 +12,7 @@ from api.views import (
PlaylistApiListView, PlaylistApiListView,
PlaylistApiVideoView, PlaylistApiVideoView,
PlaylistApiView, PlaylistApiView,
SearchView,
TaskApiView, TaskApiView,
VideoApiListView, VideoApiListView,
VideoApiView, VideoApiView,
@@ -93,4 +94,9 @@ urlpatterns = [
CookieView.as_view(), CookieView.as_view(),
name="api-cookie", name="api-cookie",
), ),
path(
"search/",
SearchView.as_view(),
name="api-search",
),
] ]

View File

@@ -5,6 +5,7 @@ from api.src.task_processor import TaskHandler
from home.src.download.queue import PendingInteract from home.src.download.queue import PendingInteract
from home.src.download.yt_dlp_base import CookieHandler from home.src.download.yt_dlp_base import CookieHandler
from home.src.es.connect import ElasticWrap from home.src.es.connect import ElasticWrap
from home.src.frontend.searching import SearchForm
from home.src.index.generic import Pagination from home.src.index.generic import Pagination
from home.src.index.video import SponsorBlock from home.src.index.video import SponsorBlock
from home.src.ta.config import AppConfig from home.src.ta.config import AppConfig
@@ -52,9 +53,7 @@ class ApiBaseView(APIView):
def initiate_pagination(self, request): def initiate_pagination(self, request):
"""set initial pagination values""" """set initial pagination values"""
user_id = request.user.id self.pagination_handler = Pagination(request)
page_get = int(request.GET.get("page", 0))
self.pagination_handler = Pagination(page_get, user_id)
self.data.update( self.data.update(
{ {
"size": self.pagination_handler.pagination["page_size"], "size": self.pagination_handler.pagination["page_size"],
@@ -131,7 +130,7 @@ class VideoProgressView(ApiBaseView):
position = request.data.get("position", 0) position = request.data.get("position", 0)
key = f"{request.user.id}:progress:{video_id}" key = f"{request.user.id}:progress:{video_id}"
message = {"position": position, "youtube_id": video_id} message = {"position": position, "youtube_id": video_id}
RedisArchivist().set_message(key, message, expire=False) RedisArchivist().set_message(key, message)
self.response = request.data self.response = request.data
return Response(self.response) return Response(self.response)
@@ -367,13 +366,23 @@ class DownloadApiListView(ApiBaseView):
"""get request""" """get request"""
query_filter = request.GET.get("filter", False) query_filter = request.GET.get("filter", False)
self.data.update({"sort": [{"timestamp": {"order": "asc"}}]}) self.data.update({"sort": [{"timestamp": {"order": "asc"}}]})
must_list = []
if query_filter: if query_filter:
if query_filter not in self.valid_filter: if query_filter not in self.valid_filter:
message = f"invalid url query filder: {query_filter}" message = f"invalid url query filder: {query_filter}"
print(message) print(message)
return Response({"message": message}, status=400) return Response({"message": message}, status=400)
self.data["query"] = {"term": {"status": {"value": query_filter}}} must_list.append({"term": {"status": {"value": query_filter}}})
filter_channel = request.GET.get("channel", False)
if filter_channel:
must_list.append(
{"term": {"channel_id": {"value": filter_channel}}}
)
self.data["query"] = {"bool": {"must": must_list}}
self.get_document_list(request) self.get_document_list(request)
return Response(self.response) return Response(self.response)
@@ -452,9 +461,20 @@ class LoginApiView(ObtainAuthToken):
class TaskApiView(ApiBaseView): class TaskApiView(ApiBaseView):
"""resolves to /api/task/ """resolves to /api/task/
GET: check if ongoing background task
POST: start a new background task POST: start a new background task
""" """
@staticmethod
def get(request):
"""handle get request"""
# pylint: disable=unused-argument
response = {"rescan": False, "downloading": False}
for key in response.keys():
response[key] = RedisArchivist().is_locked(key)
return Response(response)
def post(self, request): def post(self, request):
"""handle post request""" """handle post request"""
@@ -469,6 +489,7 @@ class CookieView(ApiBaseView):
"""resolves to /api/cookie/ """resolves to /api/cookie/
GET: check if cookie is enabled GET: check if cookie is enabled
POST: verify validity of cookie POST: verify validity of cookie
PUT: import cookie
""" """
@staticmethod @staticmethod
@@ -476,9 +497,11 @@ class CookieView(ApiBaseView):
"""handle get request""" """handle get request"""
# pylint: disable=unused-argument # pylint: disable=unused-argument
config = AppConfig().config config = AppConfig().config
cookie_enabled = config["downloads"]["cookie_import"] valid = RedisArchivist().get_message("cookie:valid")
response = {"cookie_enabled": config["downloads"]["cookie_import"]}
response.update(valid)
return Response({"cookie_enabled": cookie_enabled}) return Response(response)
@staticmethod @staticmethod
def post(request): def post(request):
@@ -488,3 +511,46 @@ class CookieView(ApiBaseView):
validated = CookieHandler(config).validate() validated = CookieHandler(config).validate()
return Response({"cookie_validated": validated}) return Response({"cookie_validated": validated})
@staticmethod
def put(request):
"""handle put request"""
# pylint: disable=unused-argument
config = AppConfig().config
cookie = request.data.get("cookie")
if not cookie:
message = "missing cookie key in request data"
print(message)
return Response({"message": message}, status=400)
print(f"cookie preview:\n\n{cookie[:300]}")
handler = CookieHandler(config)
handler.set_cookie(cookie)
validated = handler.validate()
if not validated:
handler.revoke()
message = {"cookie_import": "fail", "cookie_validated": validated}
print(f"cookie: {message}")
return Response({"message": message}, status=400)
message = {"cookie_import": "done", "cookie_validated": validated}
return Response(message)
class SearchView(ApiBaseView):
"""resolves to /api/search/
GET: run a search with the string in the ?query parameter
"""
@staticmethod
def get(request):
"""handle get request
search through all indexes"""
search_query = request.GET.get("query", None)
if search_query is None:
return Response(
{"message": "no search query specified"}, status=400
)
print("searching for: " + search_query)
search_results = SearchForm().multi_search(search_query)
return Response(search_results)

View File

@@ -14,7 +14,9 @@ import hashlib
from os import environ, path from os import environ, path
from pathlib import Path from pathlib import Path
import ldap
from corsheaders.defaults import default_headers from corsheaders.defaults import default_headers
from django_auth_ldap.config import LDAPSearch
from home.src.ta.config import AppConfig from home.src.ta.config import AppConfig
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
@@ -30,7 +32,14 @@ SECRET_KEY = PW_HASH.hexdigest()
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(environ.get("DJANGO_DEBUG")) DEBUG = bool(environ.get("DJANGO_DEBUG"))
ALLOWED_HOSTS = ["*"] ALLOWED_HOSTS = [i.strip() for i in environ.get("TA_HOST").split()]
CSRF_TRUSTED_ORIGINS = []
for host in ALLOWED_HOSTS:
if host.startswith("http://") or host.startswith("https://"):
CSRF_TRUSTED_ORIGINS.append(host)
else:
CSRF_TRUSTED_ORIGINS.append(f"http://{host}")
# Application definition # Application definition
@@ -83,6 +92,41 @@ TEMPLATES = [
WSGI_APPLICATION = "config.wsgi.application" WSGI_APPLICATION = "config.wsgi.application"
if bool(environ.get("TA_LDAP")):
# pylint: disable=global-at-module-level
global AUTH_LDAP_SERVER_URI
AUTH_LDAP_SERVER_URI = environ.get("TA_LDAP_SERVER_URI")
global AUTH_LDAP_BIND_DN
AUTH_LDAP_BIND_DN = environ.get("TA_LDAP_BIND_DN")
global AUTH_LDAP_BIND_PASSWORD
AUTH_LDAP_BIND_PASSWORD = environ.get("TA_LDAP_BIND_PASSWORD")
global AUTH_LDAP_USER_SEARCH
# pylint: disable=no-member
AUTH_LDAP_USER_SEARCH = LDAPSearch(
environ.get("TA_LDAP_USER_BASE"),
ldap.SCOPE_SUBTREE,
"(&(uid=%(user)s)" + environ.get("TA_LDAP_USER_FILTER") + ")",
)
global AUTH_LDAP_USER_ATTR_MAP
AUTH_LDAP_USER_ATTR_MAP = {
"username": "uid",
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}
if bool(environ.get("TA_LDAP_DISABLE_CERT_CHECK")):
global AUTH_LDAP_GLOBAL_OPTIONS
AUTH_LDAP_GLOBAL_OPTIONS = {
ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER,
}
global AUTHENTICATION_BACKENDS
AUTHENTICATION_BACKENDS = ("django_auth_ldap.backend.LDAPBackend",)
# Database # Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
@@ -163,4 +207,4 @@ CORS_ALLOW_HEADERS = list(default_headers) + [
# TA application settings # TA application settings
TA_UPSTREAM = "https://github.com/tubearchivist/tubearchivist" TA_UPSTREAM = "https://github.com/tubearchivist/tubearchivist"
TA_VERSION = "v0.1.6" TA_VERSION = "v0.2.3"

View File

@@ -13,8 +13,8 @@ from home.src.ta.ta_redis import RedisArchivist
class StartupCheck: class StartupCheck:
"""checks to run at application startup""" """checks to run at application startup"""
MIN_MAJOR, MAX_MAJOR = 7, 7 MIN_MAJOR, MAX_MAJOR = 8, 8
MIN_MINOR = 17 MIN_MINOR = 0
def __init__(self): def __init__(self):
self.config_handler = ArchivistConfig() self.config_handler = ArchivistConfig()
@@ -28,6 +28,7 @@ class StartupCheck:
self.release_lock() self.release_lock()
index_check() index_check()
self.sync_redis_state() self.sync_redis_state()
self.set_redis_conf()
self.make_folders() self.make_folders()
self.set_has_run() self.set_has_run()
@@ -45,6 +46,10 @@ class StartupCheck:
print("sync redis") print("sync redis")
self.config_handler.load_new_defaults() self.config_handler.load_new_defaults()
def set_redis_conf(self):
"""set conf values for redis"""
self.redis_con.conn.config_set("timeout", 3600)
def make_folders(self): def make_folders(self):
"""make needed cache folders here so docker doesn't mess it up""" """make needed cache folders here so docker doesn't mess it up"""
folders = [ folders = [
@@ -72,6 +77,7 @@ class StartupCheck:
"dl_queue", "dl_queue",
"dl_queue_id", "dl_queue_id",
"rescan", "rescan",
"run_backup",
] ]
for lock in all_locks: for lock in all_locks:
response = self.redis_con.del_message(lock) response = self.redis_con.del_message(lock)

View File

@@ -36,7 +36,6 @@
"app_root": "/app", "app_root": "/app",
"cache_dir": "/cache", "cache_dir": "/cache",
"videos": "/youtube", "videos": "/youtube",
"file_template": "%(id)s_%(title)s.mp4",
"colors": "dark", "colors": "dark",
"enable_cast": false "enable_cast": false
}, },

View File

@@ -150,7 +150,7 @@ class PendingList(PendingIndex):
"title": "Adding to download queue.", "title": "Adding to download queue.",
"message": "Extracting lists", "message": "Extracting lists",
} }
RedisArchivist().set_message("message:add", mess_dict) RedisArchivist().set_message("message:add", mess_dict, expire=True)
self._process_entry(entry) self._process_entry(entry)
def _process_entry(self, entry): def _process_entry(self, entry):
@@ -161,10 +161,7 @@ class PendingList(PendingIndex):
self._parse_channel(entry["url"]) self._parse_channel(entry["url"])
elif entry["type"] == "playlist": elif entry["type"] == "playlist":
self._parse_playlist(entry["url"]) self._parse_playlist(entry["url"])
new_thumbs = PlaylistSubscription().process_url_str( PlaylistSubscription().process_url_str([entry], subscribed=False)
[entry], subscribed=False
)
ThumbManager().download_playlist(new_thumbs)
else: else:
raise ValueError(f"invalid url_type: {entry}") raise ValueError(f"invalid url_type: {entry}")
@@ -198,8 +195,8 @@ class PendingList(PendingIndex):
self.get_channels() self.get_channels()
bulk_list = [] bulk_list = []
thumb_handler = ThumbManager()
for idx, youtube_id in enumerate(self.missing_videos): for idx, youtube_id in enumerate(self.missing_videos):
print(f"{youtube_id}: add to download queue")
video_details = self.get_youtube_details(youtube_id) video_details = self.get_youtube_details(youtube_id)
if not video_details: if not video_details:
continue continue
@@ -209,8 +206,9 @@ class PendingList(PendingIndex):
bulk_list.append(json.dumps(action)) bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(video_details)) bulk_list.append(json.dumps(video_details))
thumb_needed = [(youtube_id, video_details["vid_thumb_url"])] url = video_details["vid_thumb_url"]
thumb_handler.download_vid(thumb_needed) ThumbManager(youtube_id).download_video_thumb(url)
self._notify_add(idx) self._notify_add(idx)
if bulk_list: if bulk_list:
@@ -229,10 +227,11 @@ class PendingList(PendingIndex):
"message": "Progress: " + progress, "message": "Progress: " + progress,
} }
if idx + 1 == len(self.missing_videos): if idx + 1 == len(self.missing_videos):
RedisArchivist().set_message("message:add", mess_dict, expire=4) expire = 4
else: else:
RedisArchivist().set_message("message:add", mess_dict) expire = True
RedisArchivist().set_message("message:add", mess_dict, expire=expire)
if idx + 1 % 25 == 0: if idx + 1 % 25 == 0:
print("adding to queue progress: " + progress) print("adding to queue progress: " + progress)
@@ -247,7 +246,7 @@ class PendingList(PendingIndex):
print(f"{youtube_id}: skipping premium video, id not matching") print(f"{youtube_id}: skipping premium video, id not matching")
return False return False
# stop if video is streaming live now # stop if video is streaming live now
if vid["is_live"]: if vid["live_status"] in ["is_upcoming", "is_live"]:
return False return False
return self._parse_youtube_details(vid) return self._parse_youtube_details(vid)

View File

@@ -5,6 +5,7 @@ Functionality:
""" """
from home.src.download import queue # partial import from home.src.download import queue # partial import
from home.src.download.thumbnails import ThumbManager
from home.src.download.yt_dlp_base import YtWrap from home.src.download.yt_dlp_base import YtWrap
from home.src.es.connect import IndexPaginate from home.src.es.connect import IndexPaginate
from home.src.index.channel import YoutubeChannel from home.src.index.channel import YoutubeChannel
@@ -62,6 +63,7 @@ class ChannelSubscription:
for idx, channel in enumerate(all_channels): for idx, channel in enumerate(all_channels):
channel_id = channel["channel_id"] channel_id = channel["channel_id"]
print(f"{channel_id}: find missing videos.")
last_videos = self.get_last_youtube_videos(channel_id) last_videos = self.get_last_youtube_videos(channel_id)
if last_videos: if last_videos:
@@ -76,11 +78,13 @@ class ChannelSubscription:
"message": f"Progress: {idx + 1}/{len(all_channels)}", "message": f"Progress: {idx + 1}/{len(all_channels)}",
} }
if idx + 1 == len(all_channels): if idx + 1 == len(all_channels):
RedisArchivist().set_message( expire = 4
"message:rescan", message=message, expire=4
)
else: else:
RedisArchivist().set_message("message:rescan", message=message) expire = True
RedisArchivist().set_message(
"message:rescan", message=message, expire=expire
)
return missing_videos return missing_videos
@@ -127,11 +131,9 @@ class PlaylistSubscription:
all_indexed = IndexPaginate("ta_video", data).get_results() all_indexed = IndexPaginate("ta_video", data).get_results()
all_youtube_ids = [i["youtube_id"] for i in all_indexed] all_youtube_ids = [i["youtube_id"] for i in all_indexed]
new_thumbs = []
for idx, playlist in enumerate(new_playlists): for idx, playlist in enumerate(new_playlists):
url_type = playlist["type"]
playlist_id = playlist["url"] playlist_id = playlist["url"]
if not url_type == "playlist": if not playlist["type"] == "playlist":
print(f"{playlist_id} not a playlist, skipping...") print(f"{playlist_id} not a playlist, skipping...")
continue continue
@@ -142,8 +144,11 @@ class PlaylistSubscription:
playlist_h.upload_to_es() playlist_h.upload_to_es()
playlist_h.add_vids_to_playlist() playlist_h.add_vids_to_playlist()
self.channel_validate(playlist_h.json_data["playlist_channel_id"]) self.channel_validate(playlist_h.json_data["playlist_channel_id"])
thumb = playlist_h.json_data["playlist_thumbnail"]
new_thumbs.append((playlist_id, thumb)) url = playlist_h.json_data["playlist_thumbnail"]
thumb = ThumbManager(playlist_id, item_type="playlist")
thumb.download_playlist_thumb(url)
# notify # notify
message = { message = {
"status": "message:subplaylist", "status": "message:subplaylist",
@@ -152,11 +157,9 @@ class PlaylistSubscription:
"message": f"Processing {idx + 1} of {len(new_playlists)}", "message": f"Processing {idx + 1} of {len(new_playlists)}",
} }
RedisArchivist().set_message( RedisArchivist().set_message(
"message:subplaylist", message=message "message:subplaylist", message=message, expire=True
) )
return new_thumbs
@staticmethod @staticmethod
def channel_validate(channel_id): def channel_validate(channel_id):
"""make sure channel of playlist is there""" """make sure channel of playlist is there"""
@@ -206,7 +209,9 @@ class PlaylistSubscription:
"title": "Scanning playlists: Looking for new videos.", "title": "Scanning playlists: Looking for new videos.",
"message": f"Progress: {idx + 1}/{len(all_playlists)}", "message": f"Progress: {idx + 1}/{len(all_playlists)}",
} }
RedisArchivist().set_message("message:rescan", message=message) RedisArchivist().set_message(
"message:rescan", message=message, expire=True
)
for video in all_missing: for video in all_missing:
youtube_id = video["youtube_id"] youtube_id = video["youtube_id"]

View File

@@ -6,136 +6,71 @@ functionality:
import base64 import base64
import os import os
from collections import Counter
from io import BytesIO from io import BytesIO
from time import sleep from time import sleep
import requests import requests
from home.src.download import queue # partial import from home.src.download import queue # partial import
from home.src.download import subscriptions # partial import from home.src.es.connect import IndexPaginate
from home.src.ta.config import AppConfig from home.src.ta.config import AppConfig
from home.src.ta.helper import ignore_filelist
from home.src.ta.ta_redis import RedisArchivist
from mutagen.mp4 import MP4, MP4Cover from mutagen.mp4 import MP4, MP4Cover
from PIL import Image, ImageFile, ImageFilter from PIL import Image, ImageFile, ImageFilter, UnidentifiedImageError
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
class ThumbManager: class ThumbManagerBase:
"""handle thumbnails related functions""" """base class for thumbnail management"""
CONFIG = AppConfig().config CONFIG = AppConfig().config
MEDIA_DIR = CONFIG["application"]["videos"]
CACHE_DIR = CONFIG["application"]["cache_dir"] CACHE_DIR = CONFIG["application"]["cache_dir"]
VIDEO_DIR = os.path.join(CACHE_DIR, "videos") VIDEO_DIR = os.path.join(CACHE_DIR, "videos")
CHANNEL_DIR = os.path.join(CACHE_DIR, "channels") CHANNEL_DIR = os.path.join(CACHE_DIR, "channels")
PLAYLIST_DIR = os.path.join(CACHE_DIR, "playlists") PLAYLIST_DIR = os.path.join(CACHE_DIR, "playlists")
def get_all_thumbs(self): def __init__(self, item_id, item_type, fallback=False):
"""get all video artwork already downloaded""" self.item_id = item_id
all_thumb_folders = ignore_filelist(os.listdir(self.VIDEO_DIR)) self.item_type = item_type
all_thumbs = [] self.fallback = fallback
for folder in all_thumb_folders:
folder_path = os.path.join(self.VIDEO_DIR, folder)
if os.path.isfile(folder_path):
self.update_path(folder)
all_thumbs.append(folder_path)
continue
# raise exemption here in a future version
# raise FileExistsError("video cache dir has files inside")
all_folder_thumbs = ignore_filelist(os.listdir(folder_path)) def download_raw(self, url):
all_thumbs.extend(all_folder_thumbs) """download thumbnail for video"""
if not url:
return self.get_fallback()
return all_thumbs for i in range(3):
try:
response = requests.get(url, stream=True, timeout=5)
if response.ok:
try:
return Image.open(response.raw)
except UnidentifiedImageError:
print(f"failed to open thumbnail: {url}")
return self.get_fallback()
def update_path(self, file_name): if response.status_code == 404:
"""reorganize thumbnails into folders as update path from v0.0.5""" return self.get_fallback()
folder_name = file_name[0].lower()
folder_path = os.path.join(self.VIDEO_DIR, folder_name)
old_file = os.path.join(self.VIDEO_DIR, file_name)
new_file = os.path.join(folder_path, file_name)
os.makedirs(folder_path, exist_ok=True)
os.rename(old_file, new_file)
def get_needed_thumbs(self, missing_only=False): except requests.exceptions.RequestException:
"""get a list of all missing thumbnails""" print(f"{self.item_id}: retry thumbnail download {url}")
all_thumbs = self.get_all_thumbs() sleep((i + 1) ** i)
pending = queue.PendingList() return False
pending.get_download()
pending.get_indexed()
needed_thumbs = [] def get_fallback(self):
for video in pending.all_videos: """get fallback thumbnail if not available"""
youtube_id = video["youtube_id"] if self.fallback:
thumb_url = video["vid_thumb_url"] img_raw = Image.open(self.fallback)
if missing_only: return img_raw
if youtube_id + ".jpg" not in all_thumbs:
needed_thumbs.append((youtube_id, thumb_url))
else:
needed_thumbs.append((youtube_id, thumb_url))
for video in pending.all_pending + pending.all_ignored: app_root = self.CONFIG["application"]["app_root"]
youtube_id = video["youtube_id"]
thumb_url = video["vid_thumb_url"]
if missing_only:
if youtube_id + ".jpg" not in all_thumbs:
needed_thumbs.append((youtube_id, thumb_url))
else:
needed_thumbs.append((youtube_id, thumb_url))
return needed_thumbs
def get_missing_channels(self):
"""get all channel artwork"""
all_channel_art = os.listdir(self.CHANNEL_DIR)
files = [i[0:24] for i in all_channel_art]
cached_channel_ids = [k for (k, v) in Counter(files).items() if v > 1]
channel_sub = subscriptions.ChannelSubscription()
channels = channel_sub.get_channels(subscribed_only=False)
missing_channels = []
for channel in channels:
channel_id = channel["channel_id"]
if channel_id not in cached_channel_ids:
channel_banner = channel["channel_banner_url"]
channel_thumb = channel["channel_thumb_url"]
missing_channels.append(
(channel_id, channel_thumb, channel_banner)
)
return missing_channels
def get_missing_playlists(self):
"""get all missing playlist artwork"""
all_downloaded = ignore_filelist(os.listdir(self.PLAYLIST_DIR))
all_ids_downloaded = [i.replace(".jpg", "") for i in all_downloaded]
playlist_sub = subscriptions.PlaylistSubscription()
playlists = playlist_sub.get_playlists(subscribed_only=False)
missing_playlists = []
for playlist in playlists:
playlist_id = playlist["playlist_id"]
if playlist_id not in all_ids_downloaded:
playlist_thumb = playlist["playlist_thumbnail"]
missing_playlists.append((playlist_id, playlist_thumb))
return missing_playlists
def get_raw_img(self, img_url, thumb_type):
"""get raw image from youtube and handle 404"""
try:
app_root = self.CONFIG["application"]["app_root"]
except KeyError:
# lazy keyerror fix to not have to deal with a strange startup
# racing contition between the threads in HomeConfig.ready()
app_root = "/app"
default_map = { default_map = {
"video": os.path.join( "video": os.path.join(
app_root, "static/img/default-video-thumb.jpg" app_root, "static/img/default-video-thumb.jpg"
), ),
"playlist": os.path.join(
app_root, "static/img/default-video-thumb.jpg"
),
"icon": os.path.join( "icon": os.path.join(
app_root, "static/img/default-channel-icon.jpg" app_root, "static/img/default-channel-icon.jpg"
), ),
@@ -143,112 +78,138 @@ class ThumbManager:
app_root, "static/img/default-channel-banner.jpg" app_root, "static/img/default-channel-banner.jpg"
), ),
} }
if img_url:
try: img_raw = Image.open(default_map[self.item_type])
response = requests.get(img_url, stream=True)
except ConnectionError:
sleep(5)
response = requests.get(img_url, stream=True)
if not response.ok and not response.status_code == 404:
print("retry thumbnail download for " + img_url)
sleep(5)
response = requests.get(img_url, stream=True)
else:
response = False
if not response or response.status_code == 404:
# use default
img_raw = Image.open(default_map[thumb_type])
else:
# use response
img_obj = response.raw
img_raw = Image.open(img_obj)
return img_raw return img_raw
def download_vid(self, missing_thumbs, notify=True):
"""download all missing thumbnails from list"""
print(f"downloading {len(missing_thumbs)} thumbnails")
for idx, (youtube_id, thumb_url) in enumerate(missing_thumbs):
folder_path = os.path.join(self.VIDEO_DIR, youtube_id[0].lower())
thumb_path = os.path.join(
self.CACHE_DIR, self.vid_thumb_path(youtube_id)
)
class ThumbManager(ThumbManagerBase):
"""handle thumbnails related functions"""
def __init__(self, item_id, item_type="video", fallback=False):
super().__init__(item_id, item_type, fallback=fallback)
def download(self, url):
"""download thumbnail"""
print(f"{self.item_id}: download {self.item_type} thumbnail")
if self.item_type == "video":
self.download_video_thumb(url)
elif self.item_type == "channel":
self.download_channel_art(url)
elif self.item_type == "playlist":
self.download_playlist_thumb(url)
def delete(self):
"""delete thumbnail file"""
print(f"{self.item_id}: delete {self.item_type} thumbnail")
if self.item_type == "video":
self.delete_video_thumb()
elif self.item_type == "channel":
self.delete_channel_thumb()
elif self.item_type == "playlist":
self.delete_playlist_thumb()
def download_video_thumb(self, url, skip_existing=False):
"""pass url for video thumbnail"""
folder_path = os.path.join(self.VIDEO_DIR, self.item_id[0].lower())
thumb_path = self.vid_thumb_path(absolute=True)
if skip_existing and os.path.exists(thumb_path):
return
os.makedirs(folder_path, exist_ok=True)
img_raw = self.download_raw(url)
width, height = img_raw.size
if not width / height == 16 / 9:
new_height = width / 16 * 9
offset = (height - new_height) / 2
img_raw = img_raw.crop((0, offset, width, height - offset))
img_raw.convert("RGB").save(thumb_path)
def vid_thumb_path(self, absolute=False, create_folder=False):
"""build expected path for video thumbnail from youtube_id"""
folder_name = self.item_id[0].lower()
folder_path = os.path.join("videos", folder_name)
thumb_path = os.path.join(folder_path, f"{self.item_id}.jpg")
if absolute:
thumb_path = os.path.join(self.CACHE_DIR, thumb_path)
if create_folder:
folder_path = os.path.join(self.CACHE_DIR, folder_path)
os.makedirs(folder_path, exist_ok=True) os.makedirs(folder_path, exist_ok=True)
img_raw = self.get_raw_img(thumb_url, "video")
width, height = img_raw.size return thumb_path
if not width / height == 16 / 9:
new_height = width / 16 * 9
offset = (height - new_height) / 2
img_raw = img_raw.crop((0, offset, width, height - offset))
img_raw.convert("RGB").save(thumb_path)
progress = f"{idx + 1}/{len(missing_thumbs)}" def download_channel_art(self, urls, skip_existing=False):
if notify: """pass tuple of channel thumbnails"""
mess_dict = { channel_thumb, channel_banner = urls
"status": "message:add", self._download_channel_thumb(channel_thumb, skip_existing)
"level": "info", self._download_channel_banner(channel_banner, skip_existing)
"title": "Processing Videos",
"message": "Downloading Thumbnails, Progress: " + progress,
}
if idx + 1 == len(missing_thumbs):
RedisArchivist().set_message(
"message:add", mess_dict, expire=4
)
else:
RedisArchivist().set_message("message:add", mess_dict)
if idx + 1 % 25 == 0: def _download_channel_thumb(self, channel_thumb, skip_existing):
print("thumbnail progress: " + progress) """download channel thumbnail"""
def download_chan(self, missing_channels): thumb_path = os.path.join(
"""download needed artwork for channels""" self.CHANNEL_DIR, f"{self.item_id}_thumb.jpg"
print(f"downloading {len(missing_channels)} channel artwork") )
for channel in missing_channels: self.item_type = "icon"
channel_id, channel_thumb, channel_banner = channel
thumb_path = os.path.join( if skip_existing and os.path.exists(thumb_path):
self.CHANNEL_DIR, channel_id + "_thumb.jpg" return
)
img_raw = self.get_raw_img(channel_thumb, "icon")
img_raw.convert("RGB").save(thumb_path)
banner_path = os.path.join( img_raw = self.download_raw(channel_thumb)
self.CHANNEL_DIR, channel_id + "_banner.jpg" img_raw.convert("RGB").save(thumb_path)
)
img_raw = self.get_raw_img(channel_banner, "banner")
img_raw.convert("RGB").save(banner_path)
mess_dict = { def _download_channel_banner(self, channel_banner, skip_existing):
"status": "message:download", """download channel banner"""
"level": "info",
"title": "Processing Channels",
"message": "Downloading Channel Art.",
}
RedisArchivist().set_message("message:download", mess_dict)
def download_playlist(self, missing_playlists): banner_path = os.path.join(
"""download needed artwork for playlists""" self.CHANNEL_DIR, self.item_id + "_banner.jpg"
print(f"downloading {len(missing_playlists)} playlist artwork") )
for playlist in missing_playlists: self.item_type = "banner"
playlist_id, playlist_thumb_url = playlist if skip_existing and os.path.exists(banner_path):
thumb_path = os.path.join(self.PLAYLIST_DIR, playlist_id + ".jpg") return
img_raw = self.get_raw_img(playlist_thumb_url, "video")
img_raw.convert("RGB").save(thumb_path)
mess_dict = { img_raw = self.download_raw(channel_banner)
"status": "message:download", img_raw.convert("RGB").save(banner_path)
"level": "info",
"title": "Processing Playlists",
"message": "Downloading Playlist Art.",
}
RedisArchivist().set_message("message:download", mess_dict)
def get_base64_blur(self, youtube_id): def download_playlist_thumb(self, url, skip_existing=False):
"""pass thumbnail url"""
thumb_path = os.path.join(self.PLAYLIST_DIR, f"{self.item_id}.jpg")
if skip_existing and os.path.exists(thumb_path):
return
img_raw = self.download_raw(url)
img_raw.convert("RGB").save(thumb_path)
def delete_video_thumb(self):
"""delete video thumbnail if exists"""
thumb_path = self.vid_thumb_path()
to_delete = os.path.join(self.CACHE_DIR, thumb_path)
if os.path.exists(to_delete):
os.remove(to_delete)
def delete_channel_thumb(self):
"""delete all artwork of channel"""
thumb = os.path.join(self.CHANNEL_DIR, f"{self.item_id}_thumb.jpg")
banner = os.path.join(self.CHANNEL_DIR, f"{self.item_id}_banner.jpg")
if os.path.exists(thumb):
os.remove(thumb)
if os.path.exists(banner):
os.remove(banner)
def delete_playlist_thumb(self):
"""delete playlist thumbnail"""
thumb_path = os.path.join(self.PLAYLIST_DIR, f"{self.item_id}.jpg")
if os.path.exists(thumb_path):
os.remove(thumb_path)
def get_vid_base64_blur(self):
"""return base64 encoded placeholder""" """return base64 encoded placeholder"""
img_path = self.vid_thumb_path(youtube_id) file_path = os.path.join(self.CACHE_DIR, self.vid_thumb_path())
file_path = os.path.join(self.CACHE_DIR, img_path)
img_raw = Image.open(file_path) img_raw = Image.open(file_path)
img_raw.thumbnail((img_raw.width // 20, img_raw.height // 20)) img_raw.thumbnail((img_raw.width // 20, img_raw.height // 20))
img_blur = img_raw.filter(ImageFilter.BLUR) img_blur = img_raw.filter(ImageFilter.BLUR)
@@ -260,40 +221,109 @@ class ThumbManager:
return data_url return data_url
@staticmethod
def vid_thumb_path(youtube_id):
"""build expected path for video thumbnail from youtube_id"""
folder_name = youtube_id[0].lower()
folder_path = os.path.join("videos", folder_name)
thumb_path = os.path.join(folder_path, youtube_id + ".jpg")
return thumb_path
def delete_vid_thumb(self, youtube_id): class ValidatorCallback:
"""delete video thumbnail if exists""" """handle callback validate thumbnails page by page"""
thumb_path = self.vid_thumb_path(youtube_id)
to_delete = os.path.join(self.CACHE_DIR, thumb_path)
if os.path.exists(to_delete):
os.remove(to_delete)
def delete_chan_thumb(self, channel_id): def __init__(self, source, index_name):
"""delete all artwork of channel""" self.source = source
thumb = os.path.join(self.CHANNEL_DIR, channel_id + "_thumb.jpg") self.index_name = index_name
banner = os.path.join(self.CHANNEL_DIR, channel_id + "_banner.jpg")
if os.path.exists(thumb):
os.remove(thumb)
if os.path.exists(banner):
os.remove(banner)
def cleanup_downloaded(self): def run(self):
"""find downloaded thumbnails without video indexed""" """run the task for page"""
all_thumbs = self.get_all_thumbs() print(f"{self.index_name}: validate artwork")
all_indexed = self.get_needed_thumbs() if self.index_name == "ta_video":
all_needed_thumbs = [i[0] + ".jpg" for i in all_indexed] self._validate_videos()
for thumb in all_thumbs: elif self.index_name == "ta_channel":
if thumb not in all_needed_thumbs: self._validate_channels()
# cleanup elif self.index_name == "ta_playlist":
youtube_id = thumb.rstrip(".jpg") self._validate_playlists()
self.delete_vid_thumb(youtube_id)
def _validate_videos(self):
"""check if video thumbnails are correct"""
for video in self.source:
url = video["_source"]["vid_thumb_url"]
handler = ThumbManager(video["_source"]["youtube_id"])
handler.download_video_thumb(url, skip_existing=True)
def _validate_channels(self):
"""check if all channel artwork is there"""
for channel in self.source:
urls = (
channel["_source"]["channel_thumb_url"],
channel["_source"]["channel_banner_url"],
)
handler = ThumbManager(channel["_source"]["channel_id"])
handler.download_channel_art(urls, skip_existing=True)
def _validate_playlists(self):
"""check if all playlist artwork is there"""
for playlist in self.source:
url = playlist["_source"]["playlist_thumbnail"]
handler = ThumbManager(playlist["_source"]["playlist_id"])
handler.download_playlist_thumb(url, skip_existing=True)
class ThumbValidator:
"""validate thumbnails"""
def download_missing(self):
"""download all missing artwork"""
self.download_missing_videos()
self.download_missing_channels()
self.download_missing_playlists()
def download_missing_videos(self):
"""get all missing video thumbnails"""
data = {
"query": {"term": {"active": {"value": True}}},
"sort": [{"youtube_id": {"order": "asc"}}],
"_source": ["vid_thumb_url", "youtube_id"],
}
paginate = IndexPaginate(
"ta_video", data, size=5000, callback=ValidatorCallback
)
_ = paginate.get_results()
def download_missing_channels(self):
"""get all missing channel thumbnails"""
data = {
"query": {"term": {"channel_active": {"value": True}}},
"sort": [{"channel_id": {"order": "asc"}}],
"_source": {
"excludes": ["channel_description", "channel_overwrites"]
},
}
paginate = IndexPaginate(
"ta_channel", data, callback=ValidatorCallback
)
_ = paginate.get_results()
def download_missing_playlists(self):
"""get all missing playlist artwork"""
data = {
"query": {"term": {"playlist_active": {"value": True}}},
"sort": [{"playlist_id": {"order": "asc"}}],
"_source": ["playlist_id", "playlist_thumbnail"],
}
paginate = IndexPaginate(
"ta_playlist", data, callback=ValidatorCallback
)
_ = paginate.get_results()
class ThumbFilesystem:
"""filesystem tasks for thumbnails"""
CONFIG = AppConfig().config
CACHE_DIR = CONFIG["application"]["cache_dir"]
MEDIA_DIR = CONFIG["application"]["videos"]
VIDEO_DIR = os.path.join(CACHE_DIR, "videos")
def sync(self):
"""embed thumbnails to mediafiles"""
video_list = self.get_thumb_list()
self._embed_thumbs(video_list)
def get_thumb_list(self): def get_thumb_list(self):
"""get list of mediafiles and matching thumbnails""" """get list of mediafiles and matching thumbnails"""
@@ -303,10 +333,10 @@ class ThumbManager:
video_list = [] video_list = []
for video in pending.all_videos: for video in pending.all_videos:
youtube_id = video["youtube_id"] video_id = video["youtube_id"]
media_url = os.path.join(self.MEDIA_DIR, video["media_url"]) media_url = os.path.join(self.MEDIA_DIR, video["media_url"])
thumb_path = os.path.join( thumb_path = os.path.join(
self.CACHE_DIR, self.vid_thumb_path(youtube_id) self.CACHE_DIR, ThumbManager(video_id).vid_thumb_path()
) )
video_list.append( video_list.append(
{ {
@@ -318,7 +348,7 @@ class ThumbManager:
return video_list return video_list
@staticmethod @staticmethod
def write_all_thumbs(video_list): def _embed_thumbs(video_list):
"""rewrite the thumbnail into media file""" """rewrite the thumbnail into media file"""
counter = 1 counter = 1
@@ -336,15 +366,3 @@ class ThumbManager:
if counter % 50 == 0: if counter % 50 == 0:
print(f"thumbnail write progress {counter}/{len(video_list)}") print(f"thumbnail write progress {counter}/{len(video_list)}")
counter = counter + 1 counter = counter + 1
def validate_thumbnails():
"""check if all thumbnails are there and organized correctly"""
handler = ThumbManager()
thumbs_to_download = handler.get_needed_thumbs(missing_only=True)
handler.download_vid(thumbs_to_download)
missing_channels = handler.get_missing_channels()
handler.download_chan(missing_channels)
missing_playlists = handler.get_missing_playlists()
handler.download_playlist(missing_playlists)
handler.cleanup_downloaded()

View File

@@ -5,6 +5,8 @@ functionality:
""" """
import os import os
from datetime import datetime
from http import cookiejar
from io import StringIO from io import StringIO
import yt_dlp import yt_dlp
@@ -18,7 +20,8 @@ class YtWrap:
"default_search": "ytsearch", "default_search": "ytsearch",
"quiet": True, "quiet": True,
"check_formats": "selected", "check_formats": "selected",
"socket_timeout": 2, "socket_timeout": 3,
"extractor_retries": 3,
} }
def __init__(self, obs_request, config=False): def __init__(self, obs_request, config=False):
@@ -54,9 +57,12 @@ class YtWrap:
"""make extract request""" """make extract request"""
try: try:
response = yt_dlp.YoutubeDL(self.obs).extract_info(url) response = yt_dlp.YoutubeDL(self.obs).extract_info(url)
except cookiejar.LoadError:
print("cookie file is invalid")
return False
except (yt_dlp.utils.ExtractorError, yt_dlp.utils.DownloadError): except (yt_dlp.utils.ExtractorError, yt_dlp.utils.DownloadError):
print(f"{url}: failed to get info from youtube") print(f"{url}: failed to get info from youtube")
response = False return False
return response return response
@@ -78,25 +84,74 @@ class CookieHandler:
"""import cookie from file""" """import cookie from file"""
cache_path = self.config["application"]["cache_dir"] cache_path = self.config["application"]["cache_dir"]
import_path = os.path.join(cache_path, "import", "cookies.google.txt") import_path = os.path.join(cache_path, "import", "cookies.google.txt")
with open(import_path, encoding="utf-8") as cookie_file:
cookie = cookie_file.read()
RedisArchivist().set_message("cookie", cookie, expire=False) try:
with open(import_path, encoding="utf-8") as cookie_file:
cookie = cookie_file.read()
except FileNotFoundError as err:
print(f"cookie: {import_path} file not found")
raise err
self.set_cookie(cookie)
os.remove(import_path) os.remove(import_path)
print("cookie: import successful") print("cookie: import successful")
def set_cookie(self, cookie):
"""set cookie str and activate in cofig"""
RedisArchivist().set_message("cookie", cookie)
path = ".downloads.cookie_import"
RedisArchivist().set_message("config", True, path=path)
self.config["downloads"]["cookie_import"] = True
print("cookie: activated and stored in Redis")
@staticmethod @staticmethod
def revoke(): def revoke():
"""revoke cookie""" """revoke cookie"""
RedisArchivist().del_message("cookie") RedisArchivist().del_message("cookie")
RedisArchivist().del_message("cookie:valid")
RedisArchivist().set_message(
"config", False, path=".downloads.cookie_import"
)
print("cookie: revoked") print("cookie: revoked")
def validate(self): def validate(self):
"""validate cookie using the liked videos playlist""" """validate cookie using the liked videos playlist"""
print("validating cookie")
obs_request = { obs_request = {
"skip_download": True, "skip_download": True,
"extract_flat": True, "extract_flat": True,
} }
response = YtWrap(obs_request, self.config).extract("LL") validator = YtWrap(obs_request, self.config)
return bool(response) response = bool(validator.extract("LL"))
self.store_validation(response)
# update in redis to avoid expiring
modified = validator.obs["cookiefile"].getvalue()
if modified:
RedisArchivist().set_message("cookie", modified)
if not response:
mess_dict = {
"status": "message:download",
"level": "error",
"title": "Cookie validation failed, exiting...",
"message": "",
}
RedisArchivist().set_message(
"message:download", mess_dict, expire=4
)
print("cookie validation failed, exiting...")
return response
@staticmethod
def store_validation(response):
"""remember last validation"""
now = datetime.now()
message = {
"status": response,
"validated": int(now.strftime("%s")),
"validated_str": now.strftime("%Y-%m-%d %H:%M"),
}
RedisArchivist().set_message("cookie:valid", message)

View File

@@ -12,7 +12,7 @@ from datetime import datetime
from home.src.download.queue import PendingList from home.src.download.queue import PendingList
from home.src.download.subscriptions import PlaylistSubscription from home.src.download.subscriptions import PlaylistSubscription
from home.src.download.yt_dlp_base import YtWrap from home.src.download.yt_dlp_base import CookieHandler, YtWrap
from home.src.es.connect import ElasticWrap, IndexPaginate from home.src.es.connect import ElasticWrap, IndexPaginate
from home.src.index.channel import YoutubeChannel from home.src.index.channel import YoutubeChannel
from home.src.index.playlist import YoutubePlaylist from home.src.index.playlist import YoutubePlaylist
@@ -125,18 +125,19 @@ class DownloadPostProcess:
+ f"{id_c + 1}/{len(self.download.channels)}" + f"{id_c + 1}/{len(self.download.channels)}"
) )
message = f"Progress: {id_p + 1}/{len(all_channel_playlist)}" message = f"Progress: {id_p + 1}/{len(all_channel_playlist)}"
key = "message:download"
mess_dict = { mess_dict = {
"status": "message:download", "status": key,
"level": "info", "level": "info",
"title": title, "title": title,
"message": message, "message": message,
} }
if id_p + 1 == len(all_channel_playlist): if id_p + 1 == len(all_channel_playlist):
RedisArchivist().set_message( expire = 4
"message:download", mess_dict, expire=4
)
else: else:
RedisArchivist().set_message("message:download", mess_dict) expire = True
RedisArchivist().set_message(key, mess_dict, expire=expire)
class VideoDownloader: class VideoDownloader:
@@ -145,6 +146,8 @@ class VideoDownloader:
if not initiated with list, take from queue if not initiated with list, take from queue
""" """
MSG = "message:download"
def __init__(self, youtube_id_list=False): def __init__(self, youtube_id_list=False):
self.obs = False self.obs = False
self.video_overwrites = False self.video_overwrites = False
@@ -155,10 +158,7 @@ class VideoDownloader:
def run_queue(self): def run_queue(self):
"""setup download queue in redis loop until no more items""" """setup download queue in redis loop until no more items"""
pending = PendingList() self._setup_queue()
pending.get_download()
pending.get_channels()
self.video_overwrites = pending.video_overwrites
queue = RedisQueue() queue = RedisQueue()
@@ -175,42 +175,66 @@ class VideoDownloader:
if not success: if not success:
continue continue
mess_dict = {
"status": self.MSG,
"level": "info",
"title": "Indexing....",
"message": "Add video metadata to index.",
}
RedisArchivist().set_message(self.MSG, mess_dict, expire=60)
vid_dict = index_new_video( vid_dict = index_new_video(
youtube_id, video_overwrites=self.video_overwrites youtube_id, video_overwrites=self.video_overwrites
) )
self.channels.add(vid_dict["channel"]["channel_id"]) self.channels.add(vid_dict["channel"]["channel_id"])
mess_dict = { mess_dict = {
"status": "message:download", "status": self.MSG,
"level": "info", "level": "info",
"title": "Moving....", "title": "Moving....",
"message": "Moving downloaded file to storage folder", "message": "Moving downloaded file to storage folder",
} }
RedisArchivist().set_message("message:download", mess_dict, False) RedisArchivist().set_message(self.MSG, mess_dict)
if queue.has_item():
message = "Continue with next video."
else:
message = "Download queue is finished."
self.move_to_archive(vid_dict) self.move_to_archive(vid_dict)
mess_dict = { mess_dict = {
"status": "message:download", "status": self.MSG,
"level": "info", "level": "info",
"title": "Completed", "title": "Completed",
"message": "", "message": message,
} }
RedisArchivist().set_message("message:download", mess_dict, 10) RedisArchivist().set_message(self.MSG, mess_dict, expire=10)
self._delete_from_pending(youtube_id) self._delete_from_pending(youtube_id)
# post processing # post processing
self._add_subscribed_channels() self._add_subscribed_channels()
DownloadPostProcess(self).run() DownloadPostProcess(self).run()
@staticmethod def _setup_queue(self):
def add_pending(): """setup required and validate"""
if self.config["downloads"]["cookie_import"]:
valid = CookieHandler(self.config).validate()
if not valid:
return
pending = PendingList()
pending.get_download()
pending.get_channels()
self.video_overwrites = pending.video_overwrites
def add_pending(self):
"""add pending videos to download queue""" """add pending videos to download queue"""
mess_dict = { mess_dict = {
"status": "message:download", "status": self.MSG,
"level": "info", "level": "info",
"title": "Looking for videos to download", "title": "Looking for videos to download",
"message": "Scanning your download queue.", "message": "Scanning your download queue.",
} }
RedisArchivist().set_message("message:download", mess_dict) RedisArchivist().set_message(self.MSG, mess_dict, expire=True)
pending = PendingList() pending = PendingList()
pending.get_download() pending.get_download()
to_add = [i["youtube_id"] for i in pending.all_pending] to_add = [i["youtube_id"] for i in pending.all_pending]
@@ -218,25 +242,20 @@ class VideoDownloader:
# there is nothing pending # there is nothing pending
print("download queue is empty") print("download queue is empty")
mess_dict = { mess_dict = {
"status": "message:download", "status": self.MSG,
"level": "error", "level": "error",
"title": "Download queue is empty", "title": "Download queue is empty",
"message": "Add some videos to the queue first.", "message": "Add some videos to the queue first.",
} }
RedisArchivist().set_message("message:download", mess_dict) RedisArchivist().set_message(self.MSG, mess_dict, expire=True)
return return
RedisQueue().add_list(to_add) RedisQueue().add_list(to_add)
@staticmethod def _progress_hook(self, response):
def _progress_hook(response):
"""process the progress_hooks from yt_dlp""" """process the progress_hooks from yt_dlp"""
# title title = "Downloading: " + response["info_dict"]["title"]
path = os.path.split(response["filename"])[-1][12:]
filename = os.path.splitext(os.path.splitext(path)[0])[0]
filename_clean = filename.replace("_", " ")
title = "Downloading: " + filename_clean
# message
try: try:
percent = response["_percent_str"] percent = response["_percent_str"]
size = response["_total_bytes_str"] size = response["_total_bytes_str"]
@@ -245,13 +264,14 @@ class VideoDownloader:
message = f"{percent} of {size} at {speed} - time left: {eta}" message = f"{percent} of {size} at {speed} - time left: {eta}"
except KeyError: except KeyError:
message = "processing" message = "processing"
mess_dict = { mess_dict = {
"status": "message:download", "status": self.MSG,
"level": "info", "level": "info",
"title": title, "title": title,
"message": message, "message": message,
} }
RedisArchivist().set_message("message:download", mess_dict) RedisArchivist().set_message(self.MSG, mess_dict, expire=True)
def _build_obs(self): def _build_obs(self):
"""collection to build all obs passed to yt-dlp""" """collection to build all obs passed to yt-dlp"""
@@ -264,11 +284,9 @@ class VideoDownloader:
self.obs = { self.obs = {
"default_search": "ytsearch", "default_search": "ytsearch",
"merge_output_format": "mp4", "merge_output_format": "mp4",
"restrictfilenames": True,
"outtmpl": ( "outtmpl": (
self.config["application"]["cache_dir"] self.config["application"]["cache_dir"]
+ "/download/" + "/download/%(id)s.mp4"
+ self.config["application"]["file_template"]
), ),
"progress_hooks": [self._progress_hook], "progress_hooks": [self._progress_hook],
"noprogress": True, "noprogress": True,
@@ -385,12 +403,12 @@ class VideoDownloader:
for file_str in all_cached: for file_str in all_cached:
if vid_dict["youtube_id"] in file_str: if vid_dict["youtube_id"] in file_str:
old_file = file_str old_file = file_str
old_file_path = os.path.join(cache_dir, "download", old_file) old_path = os.path.join(cache_dir, "download", old_file)
new_file_path = os.path.join(videos, vid_dict["media_url"]) new_path = os.path.join(videos, vid_dict["media_url"])
# move media file and fix permission # move media file and fix permission
shutil.move(old_file_path, new_file_path) shutil.move(old_path, new_path, copy_function=shutil.copyfile)
if host_uid and host_gid: if host_uid and host_gid:
os.chown(new_file_path, host_uid, host_gid) os.chown(new_path, host_uid, host_gid)
@staticmethod @staticmethod
def _delete_from_pending(youtube_id): def _delete_from_pending(youtube_id):

View File

@@ -91,16 +91,22 @@ class ElasticWrap:
class IndexPaginate: class IndexPaginate:
"""use search_after to go through whole index""" """use search_after to go through whole index
kwargs:
- size: int, overwrite DEFAULT_SIZE
- keep_source: bool, keep _source key from es resutls
- callback: obj, Class with run method collback for every loop
"""
DEFAULT_SIZE = 500 DEFAULT_SIZE = 500
def __init__(self, index_name, data, size=False, keep_source=False): def __init__(self, index_name, data, **kwargs):
self.index_name = index_name self.index_name = index_name
self.data = data self.data = data
self.pit_id = False self.pit_id = False
self.size = size self.size = kwargs.get("size")
self.keep_source = keep_source self.keep_source = kwargs.get("keep_source")
self.callback = kwargs.get("callback")
def get_results(self): def get_results(self):
"""get all results""" """get all results"""
@@ -122,14 +128,13 @@ class IndexPaginate:
print(self.data) print(self.data)
raise ValueError("missing sort key in data") raise ValueError("missing sort key in data")
size = self.size or self.DEFAULT_SIZE self.data["size"] = self.size or self.DEFAULT_SIZE
self.data["size"] = size
self.data["pit"] = {"id": self.pit_id, "keep_alive": "10m"} self.data["pit"] = {"id": self.pit_id, "keep_alive": "10m"}
def run_loop(self): def run_loop(self):
"""loop through results until last hit""" """loop through results until last hit"""
all_results = [] all_results = []
counter = 0
while True: while True:
response, _ = ElasticWrap("_search").get(data=self.data) response, _ = ElasticWrap("_search").get(data=self.data)
all_hits = response["hits"]["hits"] all_hits = response["hits"]["hits"]
@@ -139,10 +144,18 @@ class IndexPaginate:
source = hit source = hit
else: else:
source = hit["_source"] source = hit["_source"]
search_after = hit["sort"]
all_results.append(source) if not self.callback:
all_results.append(source)
if self.callback:
self.callback(all_hits, self.index_name).run()
if counter % 10 == 0:
print(f"{self.index_name}: processing page {counter}")
counter = counter + 1
# update search_after with last hit data # update search_after with last hit data
self.data["search_after"] = search_after self.data["search_after"] = all_hits[-1]["sort"]
else: else:
break break

View File

@@ -137,35 +137,24 @@ class ElasticIndex:
_, _ = ElasticWrap(f"ta_{self.index_name}").put(data) _, _ = ElasticWrap(f"ta_{self.index_name}").put(data)
class ElasticBackup: class BackupCallback:
"""dump index to nd-json files for later bulk import""" """handle backup ndjson writer as callback for IndexPaginate"""
def __init__(self, index_config, reason): def __init__(self, source, index_name):
self.config = AppConfig().config self.source = source
self.cache_dir = self.config["application"]["cache_dir"] self.index_name = index_name
self.index_config = index_config
self.reason = reason
self.timestamp = datetime.now().strftime("%Y%m%d") self.timestamp = datetime.now().strftime("%Y%m%d")
self.backup_files = []
@staticmethod def run(self):
def get_all_documents(index_name): """run the junk task"""
"""export all documents of a single index""" file_content = self._build_bulk()
data = { self._write_es_json(file_content)
"query": {"match_all": {}},
"sort": [{"_doc": {"order": "desc"}}],
}
paginate = IndexPaginate(f"ta_{index_name}", data, keep_source=True)
all_results = paginate.get_results()
return all_results def _build_bulk(self):
@staticmethod
def build_bulk(all_results):
"""build bulk query data from all_results""" """build bulk query data from all_results"""
bulk_list = [] bulk_list = []
for document in all_results: for document in self.source:
document_id = document["_id"] document_id = document["_id"]
es_index = document["_index"] es_index = document["_index"]
action = {"index": {"_index": es_index, "_id": document_id}} action = {"index": {"_index": es_index, "_id": document_id}}
@@ -179,40 +168,56 @@ class ElasticBackup:
return file_content return file_content
def write_es_json(self, file_content, index_name): def _write_es_json(self, file_content):
"""write nd-json file for es _bulk API to disk""" """write nd-json file for es _bulk API to disk"""
file_name = f"es_{index_name}-{self.timestamp}.json" cache_dir = AppConfig().config["application"]["cache_dir"]
file_path = os.path.join(self.cache_dir, "backup", file_name) file_name = f"es_{self.index_name.lstrip('ta_')}-{self.timestamp}.json"
with open(file_path, "w", encoding="utf-8") as f: file_path = os.path.join(cache_dir, "backup", file_name)
with open(file_path, "a+", encoding="utf-8") as f:
f.write(file_content) f.write(file_content)
self.backup_files.append(file_path)
def write_ta_json(self, all_results, index_name): class ElasticBackup:
"""write generic json file to disk""" """dump index to nd-json files for later bulk import"""
file_name = f"ta_{index_name}-{self.timestamp}.json"
file_path = os.path.join(self.cache_dir, "backup", file_name)
to_write = [i["_source"] for i in all_results]
file_content = json.dumps(to_write)
with open(file_path, "w", encoding="utf-8") as f:
f.write(file_content)
self.backup_files.append(file_path) def __init__(self, index_config, reason):
self.config = AppConfig().config
self.cache_dir = self.config["application"]["cache_dir"]
self.timestamp = datetime.now().strftime("%Y%m%d")
self.index_config = index_config
self.reason = reason
@staticmethod
def backup_index(index_name):
"""export all documents of a single index"""
data = {
"query": {"match_all": {}},
"sort": [{"_doc": {"order": "desc"}}],
}
paginate = IndexPaginate(
f"ta_{index_name}", data, keep_source=True, callback=BackupCallback
)
_ = paginate.get_results()
def zip_it(self): def zip_it(self):
"""pack it up into single zip file""" """pack it up into single zip file"""
file_name = f"ta_backup-{self.timestamp}-{self.reason}.zip" file_name = f"ta_backup-{self.timestamp}-{self.reason}.zip"
backup_folder = os.path.join(self.cache_dir, "backup") folder = os.path.join(self.cache_dir, "backup")
backup_file = os.path.join(backup_folder, file_name)
with zipfile.ZipFile( to_backup = []
backup_file, "w", compression=zipfile.ZIP_DEFLATED for file in os.listdir(folder):
) as zip_f: if file.endswith(".json"):
for backup_file in self.backup_files: to_backup.append(os.path.join(folder, file))
backup_file = os.path.join(folder, file_name)
comp = zipfile.ZIP_DEFLATED
with zipfile.ZipFile(backup_file, "w", compression=comp) as zip_f:
for backup_file in to_backup:
zip_f.write(backup_file, os.path.basename(backup_file)) zip_f.write(backup_file, os.path.basename(backup_file))
# cleanup # cleanup
for backup_file in self.backup_files: for backup_file in to_backup:
os.remove(backup_file) os.remove(backup_file)
def post_bulk_restore(self, file_name): def post_bulk_restore(self, file_name):
@@ -380,10 +385,7 @@ def backup_all_indexes(reason):
print(f"backup: export in progress for {index_name}") print(f"backup: export in progress for {index_name}")
if not backup_handler.index_exists(index_name): if not backup_handler.index_exists(index_name):
continue continue
all_results = backup_handler.get_all_documents(index_name) backup_handler.backup_index(index_name)
file_content = backup_handler.build_bulk(all_results)
backup_handler.write_es_json(file_content, index_name)
backup_handler.write_ta_json(all_results, index_name)
backup_handler.zip_it() backup_handler.zip_it()

View File

@@ -9,7 +9,6 @@ from home.src.download.subscriptions import (
ChannelSubscription, ChannelSubscription,
PlaylistSubscription, PlaylistSubscription,
) )
from home.src.frontend.searching import SearchForm
from home.src.frontend.watched import WatchState from home.src.frontend.watched import WatchState
from home.src.index.channel import YoutubeChannel from home.src.index.channel import YoutubeChannel
from home.src.index.playlist import YoutubePlaylist from home.src.index.playlist import YoutubePlaylist
@@ -74,7 +73,6 @@ class PostData:
"db-backup": self._db_backup, "db-backup": self._db_backup,
"db-restore": self._db_restore, "db-restore": self._db_restore,
"fs-rescan": self._fs_rescan, "fs-rescan": self._fs_rescan,
"multi_search": self._multi_search,
"delete-video": self._delete_video, "delete-video": self._delete_video,
"delete-channel": self._delete_channel, "delete-channel": self._delete_channel,
"delete-playlist": self._delete_playlist, "delete-playlist": self._delete_playlist,
@@ -98,7 +96,7 @@ class PostData:
origin, new_view = self.exec_val.split(":") origin, new_view = self.exec_val.split(":")
key = f"{self.current_user}:view:{origin}" key = f"{self.current_user}:view:{origin}"
print(f"change view: {key} to {new_view}") print(f"change view: {key} to {new_view}")
RedisArchivist().set_message(key, {"status": new_view}, expire=False) RedisArchivist().set_message(key, {"status": new_view})
return {"success": True} return {"success": True}
def _change_grid(self): def _change_grid(self):
@@ -109,7 +107,7 @@ class PostData:
key = f"{self.current_user}:grid_items" key = f"{self.current_user}:grid_items"
print(f"change grid items: {grid_items}") print(f"change grid items: {grid_items}")
RedisArchivist().set_message(key, {"status": grid_items}, expire=False) RedisArchivist().set_message(key, {"status": grid_items})
return {"success": True} return {"success": True}
@staticmethod @staticmethod
@@ -135,7 +133,7 @@ class PostData:
running = download_pending.delay() running = download_pending.delay()
task_id = running.id task_id = running.id
print(f"{task_id}: set task id") print(f"{task_id}: set task id")
RedisArchivist().set_message("dl_queue_id", task_id, expire=False) RedisArchivist().set_message("dl_queue_id", task_id)
return {"success": True} return {"success": True}
def _queue_handler(self): def _queue_handler(self):
@@ -187,11 +185,11 @@ class PostData:
sort_order = {"status": self.exec_val} sort_order = {"status": self.exec_val}
if self.exec_val in ["asc", "desc"]: if self.exec_val in ["asc", "desc"]:
RedisArchivist().set_message( RedisArchivist().set_message(
f"{self.current_user}:sort_order", sort_order, expire=False f"{self.current_user}:sort_order", sort_order
) )
else: else:
RedisArchivist().set_message( RedisArchivist().set_message(
f"{self.current_user}:sort_by", sort_order, expire=False f"{self.current_user}:sort_by", sort_order
) )
return {"success": True} return {"success": True}
@@ -200,7 +198,7 @@ class PostData:
key = f"{self.current_user}:hide_watched" key = f"{self.current_user}:hide_watched"
message = {"status": bool(int(self.exec_val))} message = {"status": bool(int(self.exec_val))}
print(f"toggle {key}: {message}") print(f"toggle {key}: {message}")
RedisArchivist().set_message(key, message, expire=False) RedisArchivist().set_message(key, message)
return {"success": True} return {"success": True}
def _show_subed_only(self): def _show_subed_only(self):
@@ -208,7 +206,7 @@ class PostData:
key = f"{self.current_user}:show_subed_only" key = f"{self.current_user}:show_subed_only"
message = {"status": bool(int(self.exec_val))} message = {"status": bool(int(self.exec_val))}
print(f"toggle {key}: {message}") print(f"toggle {key}: {message}")
RedisArchivist().set_message(key, message, expire=False) RedisArchivist().set_message(key, message)
return {"success": True} return {"success": True}
def _dlnow(self): def _dlnow(self):
@@ -218,7 +216,7 @@ class PostData:
running = download_single.delay(youtube_id=youtube_id) running = download_single.delay(youtube_id=youtube_id)
task_id = running.id task_id = running.id
print("set task id: " + task_id) print("set task id: " + task_id)
RedisArchivist().set_message("dl_queue_id", task_id, expire=False) RedisArchivist().set_message("dl_queue_id", task_id)
return {"success": True} return {"success": True}
def _show_ignored_only(self): def _show_ignored_only(self):
@@ -227,7 +225,7 @@ class PostData:
key = f"{self.current_user}:show_ignored_only" key = f"{self.current_user}:show_ignored_only"
value = {"status": show_value} value = {"status": show_value}
print(f"Filter download view ignored only: {show_value}") print(f"Filter download view ignored only: {show_value}")
RedisArchivist().set_message(key, value, expire=False) RedisArchivist().set_message(key, value)
return {"success": True} return {"success": True}
def _forget_ignore(self): def _forget_ignore(self):
@@ -286,13 +284,6 @@ class PostData:
rescan_filesystem.delay() rescan_filesystem.delay()
return {"success": True} return {"success": True}
def _multi_search(self):
"""search through all indexes"""
search_query = self.exec_val
print("searching for: " + search_query)
search_results = SearchForm().multi_search(search_query)
return search_results
def _delete_video(self): def _delete_video(self):
"""delete media file, metadata and thumb""" """delete media file, metadata and thumb"""
youtube_id = self.exec_val youtube_id = self.exec_val

View File

@@ -159,12 +159,14 @@ class MultiSearchForm(forms.Form):
class AddToQueueForm(forms.Form): class AddToQueueForm(forms.Form):
"""text area form to add to downloads""" """text area form to add to downloads"""
HELP_TEXT = "Enter at least one video, channel or playlist id/URL here..."
vid_url = forms.CharField( vid_url = forms.CharField(
label=False, label=False,
widget=forms.Textarea( widget=forms.Textarea(
attrs={ attrs={
"rows": 4, "rows": 4,
"placeholder": "Enter Video Urls or IDs here...", "placeholder": HELP_TEXT,
} }
), ),
) )

View File

@@ -119,7 +119,7 @@ class SearchHandler:
if "vid_thumb_url" in hit_keys: if "vid_thumb_url" in hit_keys:
youtube_id = hit["source"]["youtube_id"] youtube_id = hit["source"]["youtube_id"]
thumb_path = ThumbManager().vid_thumb_path(youtube_id) thumb_path = ThumbManager(youtube_id).vid_thumb_path()
hit["source"]["vid_thumb_url"] = thumb_path hit["source"]["vid_thumb_url"] = thumb_path
if "channel_last_refresh" in hit_keys: if "channel_last_refresh" in hit_keys:
@@ -136,6 +136,11 @@ class SearchHandler:
date_str = datetime.strftime(date_refresh, "%d %b, %Y") date_str = datetime.strftime(date_refresh, "%d %b, %Y")
hit["source"]["channel"]["channel_last_refresh"] = date_str hit["source"]["channel"]["channel_last_refresh"] = date_str
if "subtitle_fragment_id" in hit_keys:
youtube_id = hit["source"]["youtube_id"]
thumb_path = ThumbManager(youtube_id).vid_thumb_path()
hit["source"]["vid_thumb_url"] = f"/cache/{thumb_path}"
return hit return hit
@@ -146,38 +151,12 @@ class SearchForm:
def multi_search(self, search_query): def multi_search(self, search_query):
"""searching through index""" """searching through index"""
path = "ta_video,ta_channel,ta_playlist/_search" path, query, query_type = SearchParser(search_query).run()
data = { look_up = SearchHandler(path, config=self.CONFIG, data=query)
"size": 30,
"query": {
"multi_match": {
"query": search_query,
"type": "bool_prefix",
"operator": "and",
"fuzziness": "auto",
"fields": [
"category",
"channel_description",
"channel_name._2gram",
"channel_name._3gram",
"channel_name.search_as_you_type",
"playlist_description",
"playlist_name._2gram",
"playlist_name._3gram",
"playlist_name.search_as_you_type",
"tags",
"title._2gram",
"title._3gram",
"title.search_as_you_type",
],
}
},
}
look_up = SearchHandler(path, config=self.CONFIG, data=data)
search_results = look_up.get_data() search_results = look_up.get_data()
all_results = self.build_results(search_results) all_results = self.build_results(search_results)
return {"results": all_results} return {"results": all_results, "queryType": query_type}
@staticmethod @staticmethod
def build_results(search_results): def build_results(search_results):
@@ -185,6 +164,7 @@ class SearchForm:
video_results = [] video_results = []
channel_results = [] channel_results = []
playlist_results = [] playlist_results = []
fulltext_results = []
if search_results: if search_results:
for result in search_results: for result in search_results:
if result["_index"] == "ta_video": if result["_index"] == "ta_video":
@@ -193,11 +173,337 @@ class SearchForm:
channel_results.append(result) channel_results.append(result)
elif result["_index"] == "ta_playlist": elif result["_index"] == "ta_playlist":
playlist_results.append(result) playlist_results.append(result)
elif result["_index"] == "ta_subtitle":
fulltext_results.append(result)
all_results = { all_results = {
"video_results": video_results, "video_results": video_results,
"channel_results": channel_results, "channel_results": channel_results,
"playlist_results": playlist_results, "playlist_results": playlist_results,
"fulltext_results": fulltext_results,
} }
return all_results return all_results
class SearchParser:
"""handle structured searches"""
def __init__(self, search_query):
self.query_words = search_query.lower().split()
self.query_map = False
self.append_to = "term"
def run(self):
"""collection, return path and query dict for es"""
print(f"query words: {self.query_words}")
query_type = self._find_map()
self._run_words()
self._delete_unset()
self._match_data_types()
path, query = QueryBuilder(self.query_map, query_type).run()
return path, query, query_type
def _find_map(self):
"""find query in keyword map"""
first_word = self.query_words[0]
key_word_map = self._get_map()
if ":" in first_word:
index_match, query_string = first_word.split(":")
if index_match in key_word_map:
self.query_map = key_word_map.get(index_match)
self.query_words[0] = query_string
return index_match
self.query_map = key_word_map.get("simple")
print(f"query_map: {self.query_map}")
return "simple"
@staticmethod
def _get_map():
"""return map to build on"""
return {
"simple": {
"index": "ta_video,ta_channel,ta_playlist",
"term": [],
},
"video": {
"index": "ta_video",
"term": [],
"channel": [],
"active": [],
},
"channel": {
"index": "ta_channel",
"term": [],
"active": [],
"subscribed": [],
},
"playlist": {
"index": "ta_playlist",
"term": [],
"active": [],
"subscribed": [],
},
"full": {
"index": "ta_subtitle",
"term": [],
"lang": [],
"source": [],
},
}
def _run_words(self):
"""append word by word"""
for word in self.query_words:
if ":" in word:
keyword, search_string = word.split(":")
if keyword in self.query_map:
self.append_to = keyword
word = search_string
if word:
self.query_map[self.append_to].append(word)
def _delete_unset(self):
"""delete unset keys"""
new_query_map = {}
for key, value in self.query_map.items():
if value:
new_query_map.update({key: value})
self.query_map = new_query_map
def _match_data_types(self):
"""match values with data types"""
for key, value in self.query_map.items():
if key in ["term", "channel"]:
self.query_map[key] = " ".join(self.query_map[key])
if key in ["active", "subscribed"]:
self.query_map[key] = "yes" in value
class QueryBuilder:
"""build query for ES from form data"""
def __init__(self, query_map, query_type):
self.query_map = query_map
self.query_type = query_type
def run(self):
"""build query"""
path = self._build_path()
query = self.build_query()
print(f"es path: {path}")
print(f"query: {query}")
return path, query
def _build_path(self):
"""build es index search path"""
return f"{self.query_map.get('index')}/_search"
def build_query(self):
"""build query based on query_type"""
exec_map = {
"simple": self._build_simple,
"video": self._build_video,
"channel": self._build_channel,
"playlist": self._build_playlist,
"full": self._build_fulltext,
}
build_must_list = exec_map[self.query_type]
if self.query_type == "full":
query = build_must_list()
else:
query = {
"size": 30,
"query": {"bool": {"must": build_must_list()}},
}
return query
def _build_simple(self):
"""build simple cross index query"""
must_list = []
if (term := self.query_map.get("term")) is not None:
must_list.append(
{
"multi_match": {
"query": term,
"type": "bool_prefix",
"fuzziness": "auto",
"operator": "and",
"fields": [
"channel_name._2gram",
"channel_name._3gram",
"channel_name.search_as_you_type",
"playlist_name._2gram",
"playlist_name._3gram",
"playlist_name.search_as_you_type",
"title._2gram",
"title._3gram",
"title.search_as_you_type",
],
}
}
)
return must_list
def _build_video(self):
"""build video query"""
must_list = []
if (term := self.query_map.get("term")) is not None:
must_list.append(
{
"multi_match": {
"query": term,
"type": "bool_prefix",
"fuzziness": "auto",
"operator": "and",
"fields": [
"title._2gram^2",
"title._3gram^2",
"title.search_as_you_type^2",
"tags",
"category",
],
}
}
)
if (active := self.query_map.get("active")) is not None:
must_list.append({"term": {"active": {"value": active}}})
if (channel := self.query_map.get("channel")) is not None:
must_list.append(
{
"multi_match": {
"query": channel,
"type": "bool_prefix",
"fuzziness": "auto",
"operator": "and",
"fields": [
"channel.channel_name._2gram",
"channel.channel_name._3gram",
"channel.channel_name.search_as_you_type",
],
}
}
)
return must_list
def _build_channel(self):
"""build query for channel"""
must_list = []
if (term := self.query_map.get("term")) is not None:
must_list.append(
{
"multi_match": {
"query": term,
"type": "bool_prefix",
"fuzziness": "auto",
"operator": "and",
"fields": [
"channel_description",
"channel_name._2gram^2",
"channel_name._3gram^2",
"channel_name.search_as_you_type^2",
],
}
}
)
if (active := self.query_map.get("active")) is not None:
must_list.append({"term": {"channel_active": {"value": active}}})
if (subscribed := self.query_map.get("subscribed")) is not None:
must_list.append(
{"term": {"channel_subscribed": {"value": subscribed}}}
)
return must_list
def _build_playlist(self):
"""build query for playlist"""
must_list = []
if (term := self.query_map.get("term")) is not None:
must_list.append(
{
"multi_match": {
"query": term,
"type": "bool_prefix",
"fuzziness": "auto",
"operator": "and",
"fields": [
"playlist_description",
"playlist_name._2gram^2",
"playlist_name._3gram^2",
"playlist_name.search_as_you_type^2",
],
}
}
)
if (active := self.query_map.get("active")) is not None:
must_list.append({"term": {"playlist_active": {"value": active}}})
if (subscribed := self.query_map.get("subscribed")) is not None:
must_list.append(
{"term": {"playlist_subscribed": {"value": subscribed}}}
)
return must_list
def _build_fulltext(self):
"""build query for fulltext search"""
must_list = []
if (term := self.query_map.get("term")) is not None:
must_list.append(
{
"match": {
"subtitle_line": {
"query": term,
"fuzziness": "auto",
}
}
}
)
if (lang := self.query_map.get("lang")) is not None:
must_list.append({"term": {"subtitle_lang": {"value": lang[0]}}})
if (source := self.query_map.get("source")) is not None:
must_list.append(
{"term": {"subtitle_source": {"value": source[0]}}}
)
query = {
"size": 30,
"_source": {"excludes": "subtitle_line"},
"query": {"bool": {"must": must_list}},
"highlight": {
"fields": {
"subtitle_line": {
"number_of_fragments": 0,
"pre_tags": ['<span class="settings-current">'],
"post_tags": ["</span>"],
}
}
},
}
return query

View File

@@ -57,6 +57,14 @@ class WatchState:
print(response) print(response)
raise ValueError("failed to mark video as watched") raise ValueError("failed to mark video as watched")
def _get_source(self):
"""build source line for update_by_query script"""
source = [
"ctx._source.player['watched'] = true",
f"ctx._source.player['watched_date'] = {self.stamp}",
]
return "; ".join(source)
def mark_channel_watched(self): def mark_channel_watched(self):
"""change watched status of every video in channel""" """change watched status of every video in channel"""
path = "ta_video/_update_by_query" path = "ta_video/_update_by_query"
@@ -67,7 +75,7 @@ class WatchState:
data = { data = {
"query": {"bool": {"must": must_list}}, "query": {"bool": {"must": must_list}},
"script": { "script": {
"source": "ctx._source.player['watched'] = true", "source": self._get_source(),
"lang": "painless", "lang": "painless",
}, },
} }
@@ -87,7 +95,7 @@ class WatchState:
data = { data = {
"query": {"bool": {"must": must_list}}, "query": {"bool": {"must": must_list}},
"script": { "script": {
"source": "ctx._source.player['watched'] = true", "source": self._get_source(),
"lang": "painless", "lang": "painless",
}, },
} }

View File

@@ -37,6 +37,9 @@ class ChannelScraper:
"""main method to return channel dict""" """main method to return channel dict"""
self.get_soup() self.get_soup()
self._extract_yt_json() self._extract_yt_json()
if self._is_deactivated():
return False
self._parse_channel_main() self._parse_channel_main()
self._parse_channel_meta() self._parse_channel_meta()
return self.json_data return self.json_data
@@ -68,6 +71,17 @@ class ChannelScraper:
json_raw = script_content.rstrip(";</script>") json_raw = script_content.rstrip(";</script>")
self.yt_json = json.loads(json_raw) self.yt_json = json.loads(json_raw)
def _is_deactivated(self):
"""check if channel is deactivated"""
alerts = self.yt_json.get("alerts")
if not alerts:
return False
for alert in alerts:
alert_text = alert["alertRenderer"]["text"]["simpleText"]
print(f"{self.channel_id}: failed to extract, {alert_text}")
return True
def _parse_channel_main(self): def _parse_channel_main(self):
"""extract maintab values from scraped channel json data""" """extract maintab values from scraped channel json data"""
main_tab = self.yt_json["header"]["c4TabbedHeaderRenderer"] main_tab = self.yt_json["header"]["c4TabbedHeaderRenderer"]
@@ -153,36 +167,79 @@ class YoutubeChannel(YouTubeItem):
es_path = False es_path = False
index_name = "ta_channel" index_name = "ta_channel"
yt_base = "https://www.youtube.com/channel/" yt_base = "https://www.youtube.com/channel/"
msg = "message:playlistscan"
def __init__(self, youtube_id): def __init__(self, youtube_id):
super().__init__(youtube_id) super().__init__(youtube_id)
self.es_path = f"{self.index_name}/_doc/{youtube_id}" self.es_path = f"{self.index_name}/_doc/{youtube_id}"
self.all_playlists = False self.all_playlists = False
def build_json(self, upload=False): def build_json(self, upload=False, fallback=False):
"""get from es or from youtube""" """get from es or from youtube"""
self.get_from_es() self.get_from_es()
if self.json_data: if self.json_data:
return return
self.get_from_youtube() self.get_from_youtube(fallback)
if upload: if upload:
self.upload_to_es() self.upload_to_es()
return return
def get_from_youtube(self): def get_from_youtube(self, fallback=False):
"""use bs4 to scrape channel about page""" """use bs4 to scrape channel about page"""
self.json_data = ChannelScraper(self.youtube_id).get_json() self.json_data = ChannelScraper(self.youtube_id).get_json()
if not self.json_data and fallback:
self._video_fallback(fallback)
self.get_channel_art() self.get_channel_art()
def _video_fallback(self, fallback):
"""use video metadata as fallback"""
print(f"{self.youtube_id}: fallback to video metadata")
self.json_data = {
"channel_active": False,
"channel_last_refresh": int(datetime.now().strftime("%s")),
"channel_subs": fallback.get("channel_follower_count", 0),
"channel_name": fallback["uploader"],
"channel_banner_url": False,
"channel_tvart_url": False,
"channel_id": self.youtube_id,
"channel_subscribed": False,
"channel_description": False,
"channel_thumb_url": False,
"channel_views": 0,
}
self._info_json_fallback()
def _info_json_fallback(self):
"""read channel info.json for additional metadata"""
info_json = os.path.join(
self.config["application"]["cache_dir"],
"import",
f"{self.youtube_id}.info.json",
)
if os.path.exists(info_json):
print(f"{self.youtube_id}: read info.json file")
with open(info_json, "r", encoding="utf-8") as f:
content = json.loads(f.read())
self.json_data.update(
{
"channel_subs": content.get("channel_follower_count", 0),
"channel_description": content.get("description", False),
}
)
os.remove(info_json)
def get_channel_art(self): def get_channel_art(self):
"""download channel art for new channels""" """download channel art for new channels"""
channel_id = self.youtube_id urls = (
channel_thumb = self.json_data["channel_thumb_url"] self.json_data["channel_thumb_url"],
channel_banner = self.json_data["channel_banner_url"] self.json_data["channel_banner_url"],
ThumbManager().download_chan(
[(channel_id, channel_thumb, channel_banner)]
) )
ThumbManager(self.youtube_id, item_type="channel").download(urls)
def sync_to_videos(self): def sync_to_videos(self):
"""sync new channel_dict to all videos of channel""" """sync new channel_dict to all videos of channel"""
@@ -252,12 +309,12 @@ class YoutubeChannel(YouTubeItem):
self.get_from_es() self.get_from_es()
channel_name = self.json_data["channel_name"] channel_name = self.json_data["channel_name"]
mess_dict = { mess_dict = {
"status": "message:playlistscan", "status": self.msg,
"level": "info", "level": "info",
"title": "Looking for playlists", "title": "Looking for playlists",
"message": f"{channel_name}: Scanning channel in progress", "message": f"{channel_name}: Scanning channel in progress",
} }
RedisArchivist().set_message("message:playlistscan", mess_dict) RedisArchivist().set_message(self.msg, mess_dict, expire=True)
self.get_all_playlists() self.get_all_playlists()
if not self.all_playlists: if not self.all_playlists:
print(f"{self.youtube_id}: no playlists found.") print(f"{self.youtube_id}: no playlists found.")
@@ -272,12 +329,12 @@ class YoutubeChannel(YouTubeItem):
"""send notification""" """send notification"""
channel_name = self.json_data["channel_name"] channel_name = self.json_data["channel_name"]
mess_dict = { mess_dict = {
"status": "message:playlistscan", "status": self.msg,
"level": "info", "level": "info",
"title": f"{channel_name}: Scanning channel for playlists", "title": f"{channel_name}: Scanning channel for playlists",
"message": f"Progress: {idx + 1}/{len(self.all_playlists)}", "message": f"Progress: {idx + 1}/{len(self.all_playlists)}",
} }
RedisArchivist().set_message("message:playlistscan", mess_dict) RedisArchivist().set_message(self.msg, mess_dict, expire=True)
print("add playlist: " + playlist[1]) print("add playlist: " + playlist[1])
@staticmethod @staticmethod

View File

@@ -12,13 +12,17 @@ import shutil
import subprocess import subprocess
from home.src.download.queue import PendingList from home.src.download.queue import PendingList
from home.src.download.yt_dlp_handler import VideoDownloader from home.src.download.thumbnails import ThumbManager
from home.src.es.connect import ElasticWrap from home.src.es.connect import ElasticWrap
from home.src.index.reindex import Reindex from home.src.index.reindex import Reindex
from home.src.index.video import index_new_video from home.src.index.video import YoutubeVideo, index_new_video
from home.src.ta.config import AppConfig from home.src.ta.config import AppConfig
from home.src.ta.helper import clean_string, ignore_filelist from home.src.ta.helper import clean_string, ignore_filelist
from home.src.ta.ta_redis import RedisArchivist from home.src.ta.ta_redis import RedisArchivist
from PIL import Image, ImageFile
from yt_dlp.utils import ISO639Utils
ImageFile.LOAD_TRUNCATED_IMAGES = True
class FilesystemScanner: class FilesystemScanner:
@@ -157,63 +161,152 @@ class FilesystemScanner:
_, _ = ElasticWrap(path).delete() _, _ = ElasticWrap(path).delete()
class ManualImport: class ImportFolderScanner:
"""import and indexing existing video files""" """import and indexing existing video files
- identify all media files belonging to a video
- identify youtube id
- convert if needed
"""
CONFIG = AppConfig().config CONFIG = AppConfig().config
CACHE_DIR = CONFIG["application"]["cache_dir"] CACHE_DIR = CONFIG["application"]["cache_dir"]
IMPORT_DIR = os.path.join(CACHE_DIR, "import") IMPORT_DIR = os.path.join(CACHE_DIR, "import")
EXT_MAP = {
"media": [".mp4", ".mkv", ".webm"],
"metadata": [".json"],
"thumb": [".jpg", ".png", ".webp"],
"subtitle": [".vtt"],
}
def __init__(self): def __init__(self):
self.identified = self.import_folder_parser() self.to_import = False
def import_folder_parser(self): def scan(self):
"""detect files in import folder""" """scan and match media files"""
import_files = os.listdir(self.IMPORT_DIR) all_files = self.get_all_files()
to_import = ignore_filelist(import_files) self.match_files(all_files)
to_import.sort() self.process_videos()
video_files = [i for i in to_import if not i.endswith(".json")]
identified = [] return self.to_import
for file_path in video_files: def get_all_files(self):
"""get all files in /import"""
rel_paths = ignore_filelist(os.listdir(self.IMPORT_DIR))
all_files = [os.path.join(self.IMPORT_DIR, i) for i in rel_paths]
all_files.sort()
file_dict = {"video_file": file_path} return all_files
file_name, _ = os.path.splitext(file_path)
matching_json = [
i
for i in to_import
if i.startswith(file_name) and i.endswith(".json")
]
if matching_json:
json_file = matching_json[0]
youtube_id = self.extract_id_from_json(json_file)
file_dict.update({"json_file": json_file})
else:
youtube_id = self.extract_id_from_filename(file_name)
file_dict.update({"json_file": False})
file_dict.update({"youtube_id": youtube_id})
identified.append(file_dict)
return identified
@staticmethod @staticmethod
def extract_id_from_filename(file_name): def _get_template():
"""base dict for video"""
return {
"media": False,
"video_id": False,
"metadata": False,
"thumb": False,
"subtitle": [],
}
def match_files(self, all_files):
"""loop through all files, join what matches"""
self.to_import = []
current_video = self._get_template()
last_base = False
for file_path in all_files:
base_name, ext = self._detect_base_name(file_path)
key, file_path = self._detect_type(file_path, ext)
if not key or not file_path:
continue
if base_name != last_base:
if last_base:
print(f"manual import: {current_video}")
self.to_import.append(current_video)
current_video = self._get_template()
last_base = base_name
if key == "subtitle":
current_video["subtitle"].append(file_path)
else:
current_video[key] = file_path
if current_video.get("media"):
print(f"manual import: {current_video}")
self.to_import.append(current_video)
def _detect_base_name(self, file_path):
"""extract base_name and ext for matching"""
base_name_raw, ext = os.path.splitext(file_path)
base_name, ext2 = os.path.splitext(base_name_raw)
if ext2:
if ISO639Utils.short2long(ext2.strip(".")) or ext2 == ".info":
# valid secondary extension
return base_name, ext
return base_name_raw, ext
def _detect_type(self, file_path, ext):
"""detect metadata type for file"""
for key, value in self.EXT_MAP.items():
if ext in value:
return key, file_path
return False, False
def process_videos(self):
"""loop through all videos"""
for current_video in self.to_import:
if not current_video["media"]:
print(f"{current_video}: no matching media file found.")
raise ValueError
self._detect_youtube_id(current_video)
self._dump_thumb(current_video)
self._convert_thumb(current_video)
self._get_subtitles(current_video)
self._convert_video(current_video)
print(f"manual import: {current_video}")
ManualImport(current_video, self.CONFIG).run()
def _detect_youtube_id(self, current_video):
"""find video id from filename or json"""
youtube_id = self._extract_id_from_filename(current_video["media"])
if youtube_id:
current_video["video_id"] = youtube_id
return
youtube_id = self._extract_id_from_json(current_video["metadata"])
if youtube_id:
current_video["video_id"] = youtube_id
return
raise ValueError("failed to find video id")
@staticmethod
def _extract_id_from_filename(file_name):
""" """
look at the file name for the youtube id look at the file name for the youtube id
expects filename ending in [<youtube_id>].<ext> expects filename ending in [<youtube_id>].<ext>
""" """
id_search = re.search(r"\[([a-zA-Z0-9_-]{11})\]$", file_name) base_name, _ = os.path.splitext(file_name)
id_search = re.search(r"\[([a-zA-Z0-9_-]{11})\]$", base_name)
if id_search: if id_search:
youtube_id = id_search.group(1) youtube_id = id_search.group(1)
return youtube_id return youtube_id
print("failed to extract youtube id for: " + file_name) print(f"id extraction failed from filename: {file_name}")
raise Exception
def extract_id_from_json(self, json_file): return False
def _extract_id_from_json(self, json_file):
"""open json file and extract id""" """open json file and extract id"""
json_path = os.path.join(self.CACHE_DIR, "import", json_file) json_path = os.path.join(self.CACHE_DIR, "import", json_file)
with open(json_path, "r", encoding="utf-8") as f: with open(json_path, "r", encoding="utf-8") as f:
@@ -223,66 +316,276 @@ class ManualImport:
return youtube_id return youtube_id
def process_import(self): def _dump_thumb(self, current_video):
"""go through identified media files""" """extract embedded thumb before converting"""
if current_video["thumb"]:
return
all_videos_added = [] media_path = current_video["media"]
_, ext = os.path.splitext(media_path)
for media_file in self.identified: new_path = False
json_file = media_file["json_file"] if ext == ".mkv":
video_file = media_file["video_file"] idx, thumb_type = self._get_mkv_thumb_stream(media_path)
youtube_id = media_file["youtube_id"] if idx is not None:
new_path = self.dump_mpv_thumb(media_path, idx, thumb_type)
video_path = os.path.join(self.CACHE_DIR, "import", video_file) elif ext == ".mp4":
thumb_type = self.get_mp4_thumb_type(media_path)
if thumb_type:
new_path = self.dump_mp4_thumb(media_path, thumb_type)
self.move_to_cache(video_path, youtube_id) if new_path:
current_video["thumb"] = new_path
# identify and archive def _get_mkv_thumb_stream(self, media_path):
vid_dict = index_new_video(youtube_id) """get stream idx of thumbnail for mkv files"""
VideoDownloader([youtube_id]).move_to_archive(vid_dict) streams = self._get_streams(media_path)
youtube_id = vid_dict["youtube_id"] attachments = [
thumb_url = vid_dict["vid_thumb_url"] i for i in streams["streams"] if i["codec_type"] == "attachment"
all_videos_added.append((youtube_id, thumb_url)) ]
# cleanup for idx, stream in enumerate(attachments):
if os.path.exists(video_path): tags = stream["tags"]
os.remove(video_path) if "mimetype" in tags and tags["filename"].startswith("cover"):
if json_file: _, ext = os.path.splitext(tags["filename"])
json_path = os.path.join(self.CACHE_DIR, "import", json_file) return idx, ext
os.remove(json_path)
return all_videos_added return None, None
def move_to_cache(self, video_path, youtube_id): @staticmethod
"""move identified video file to cache, convert to mp4""" def dump_mpv_thumb(media_path, idx, thumb_type):
file_name = os.path.split(video_path)[-1] """write cover to disk for mkv"""
video_file, ext = os.path.splitext(file_name) _, media_ext = os.path.splitext(media_path)
new_path = f"{media_path.rstrip(media_ext)}{thumb_type}"
subprocess.run(
[
"ffmpeg",
"-v",
"quiet",
f"-dump_attachment:t:{idx}",
new_path,
"-i",
media_path,
],
check=False,
)
# make sure youtube_id is in filename return new_path
if youtube_id not in video_file:
video_file = f"{video_file}_{youtube_id}"
# move, convert if needed def get_mp4_thumb_type(self, media_path):
"""detect filetype of embedded thumbnail"""
streams = self._get_streams(media_path)
for stream in streams["streams"]:
if stream["codec_name"] in ["png", "jpg"]:
return stream["codec_name"]
return False
def _convert_thumb(self, current_video):
"""convert all thumbnails to jpg"""
if not current_video["thumb"]:
return
thumb_path = current_video["thumb"]
base_path, ext = os.path.splitext(thumb_path)
if ext == ".jpg":
return
new_path = f"{base_path}.jpg"
img_raw = Image.open(thumb_path)
img_raw.convert("RGB").save(new_path)
os.remove(thumb_path)
current_video["thumb"] = new_path
def _get_subtitles(self, current_video):
"""find all subtitles in media file"""
if current_video["subtitle"]:
return
media_path = current_video["media"]
streams = self._get_streams(media_path)
base_path, ext = os.path.splitext(media_path)
if ext == ".webm":
print(f"{media_path}: subtitle extract from webm not supported")
return
for idx, stream in enumerate(streams["streams"]):
if stream["codec_type"] == "subtitle":
lang = ISO639Utils.long2short(stream["tags"]["language"])
sub_path = f"{base_path}.{lang}.vtt"
self._dump_subtitle(idx, media_path, sub_path)
current_video["subtitle"].append(sub_path)
@staticmethod
def _dump_subtitle(idx, media_path, sub_path):
"""extract subtitle from media file"""
subprocess.run(
["ffmpeg", "-i", media_path, "-map", f"0:{idx}", sub_path],
check=True,
)
@staticmethod
def _get_streams(media_path):
"""return all streams from media_path"""
streams_raw = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-show_streams",
"-print_format",
"json",
media_path,
],
capture_output=True,
check=True,
)
streams = json.loads(streams_raw.stdout.decode())
return streams
@staticmethod
def dump_mp4_thumb(media_path, thumb_type):
"""save cover to disk"""
_, ext = os.path.splitext(media_path)
new_path = f"{media_path.rstrip(ext)}.{thumb_type}"
subprocess.run(
[
"ffmpeg",
"-i",
media_path,
"-map",
"0:v",
"-map",
"-0:V",
"-c",
"copy",
new_path,
],
check=True,
)
return new_path
def _convert_video(self, current_video):
"""convert if needed"""
current_path = current_video["media"]
base_path, ext = os.path.splitext(current_path)
if ext == ".mp4": if ext == ".mp4":
new_file = video_file + ext return
dest_path = os.path.join(self.CACHE_DIR, "download", new_file)
shutil.move(video_path, dest_path) new_path = base_path + ".mp4"
subprocess.run(
[
"ffmpeg",
"-i",
current_path,
new_path,
"-loglevel",
"warning",
"-stats",
],
check=True,
)
current_video["media"] = new_path
os.remove(current_path)
class ManualImport:
"""import single identified video"""
def __init__(self, current_video, config):
self.current_video = current_video
self.config = config
def run(self):
"""run all"""
json_data = self.index_metadata()
self._move_to_archive(json_data)
self._cleanup(json_data)
def index_metadata(self):
"""get metadata from yt or json"""
video_id = self.current_video["video_id"]
video = YoutubeVideo(video_id)
video.build_json(
youtube_meta_overwrite=self._get_info_json(),
media_path=self.current_video["media"],
)
if not video.json_data:
print(f"{video_id}: manual import failed, and no metadata found.")
raise ValueError
video.check_subtitles(subtitle_files=self.current_video["subtitle"])
video.upload_to_es()
if video.offline_import and self.current_video["thumb"]:
old_path = self.current_video["thumb"]
thumbs = ThumbManager(video_id)
new_path = thumbs.vid_thumb_path(absolute=True, create_folder=True)
shutil.move(old_path, new_path, copy_function=shutil.copyfile)
else: else:
print(f"processing with ffmpeg: {video_file}") url = video.json_data["vid_thumb_url"]
new_file = video_file + ".mp4" ThumbManager(video_id).download_video_thumb(url)
dest_path = os.path.join(self.CACHE_DIR, "download", new_file)
subprocess.run( return video.json_data
[
"ffmpeg", def _get_info_json(self):
"-i", """read info_json from file"""
video_path, if not self.current_video["metadata"]:
dest_path, return False
"-loglevel",
"warning", with open(self.current_video["metadata"], "r", encoding="utf-8") as f:
"-stats", info_json = json.loads(f.read())
],
check=True, return info_json
)
def _move_to_archive(self, json_data):
"""move identified media file to archive"""
videos = self.config["application"]["videos"]
channel, file = os.path.split(json_data["media_url"])
channel_folder = os.path.join(videos, channel)
if not os.path.exists(channel_folder):
os.makedirs(channel_folder)
old_path = self.current_video["media"]
new_path = os.path.join(channel_folder, file)
shutil.move(old_path, new_path, copy_function=shutil.copyfile)
base_name, _ = os.path.splitext(new_path)
for old_path in self.current_video["subtitle"]:
lang = old_path.split(".")[-2]
new_path = f"{base_name}.{lang}.vtt"
shutil.move(old_path, new_path, copy_function=shutil.copyfile)
def _cleanup(self, json_data):
"""cleanup leftover files"""
meta_data = self.current_video["metadata"]
if meta_data and os.path.exists(meta_data):
os.remove(meta_data)
thumb = self.current_video["thumb"]
if thumb and os.path.exists(thumb):
os.remove(thumb)
for subtitle_file in self.current_video["subtitle"]:
if os.path.exists(subtitle_file):
os.remove(subtitle_file)
channel_info = os.path.join(
self.config["application"]["cache_dir"],
"import",
f"{json_data['channel']['channel_id']}.info.json",
)
if os.path.exists(channel_info):
os.remove(channel_info)
def scan_filesystem(): def scan_filesystem():
@@ -310,4 +613,4 @@ def reindex_old_documents():
handler = Reindex() handler = Reindex()
handler.check_outdated() handler.check_outdated()
handler.reindex() handler.reindex()
RedisArchivist().set_message("last_reindex", handler.now, expire=False) RedisArchivist().set_message("last_reindex", handler.now)

View File

@@ -73,16 +73,25 @@ class Pagination:
figure out the pagination based on page size and total_hits figure out the pagination based on page size and total_hits
""" """
def __init__(self, page_get, user_id, search_get=False): def __init__(self, request):
self.user_id = user_id self.request = request
self.page_get = False
self.params = False
self.get_params()
self.page_size = self.get_page_size() self.page_size = self.get_page_size()
self.page_get = page_get
self.search_get = search_get
self.pagination = self.first_guess() self.pagination = self.first_guess()
def get_params(self):
"""process url query parameters"""
query_dict = self.request.GET.copy()
self.page_get = int(query_dict.get("page", 0))
_ = query_dict.pop("page", False)
self.params = query_dict.urlencode()
def get_page_size(self): def get_page_size(self):
"""get default or user modified page_size""" """get default or user modified page_size"""
key = f"{self.user_id}:page_size" key = f"{self.request.user.id}:page_size"
page_size = RedisArchivist().get_message(key)["status"] page_size = RedisArchivist().get_message(key)["status"]
if not page_size: if not page_size:
config = AppConfig().config config = AppConfig().config
@@ -108,9 +117,9 @@ class Pagination:
"prev_pages": prev_pages, "prev_pages": prev_pages,
"current_page": page_get, "current_page": page_get,
"max_hits": False, "max_hits": False,
"params": self.params,
} }
if self.search_get:
pagination.update({"search_get": self.search_get})
return pagination return pagination
def validate(self, total_hits): def validate(self, total_hits):

View File

@@ -41,18 +41,23 @@ class YoutubePlaylist(YouTubeItem):
self.process_youtube_meta() self.process_youtube_meta()
self.get_entries() self.get_entries()
self.json_data["playlist_entries"] = self.all_members self.json_data["playlist_entries"] = self.all_members
self.get_playlist_art()
self.json_data["playlist_subscribed"] = subscribed self.json_data["playlist_subscribed"] = subscribed
def process_youtube_meta(self): def process_youtube_meta(self):
"""extract relevant fields from youtube""" """extract relevant fields from youtube"""
try:
playlist_thumbnail = self.youtube_meta["thumbnails"][-1]["url"]
except IndexError:
print(f"{self.youtube_id}: thumbnail extraction failed")
playlist_thumbnail = False
self.json_data = { self.json_data = {
"playlist_id": self.youtube_id, "playlist_id": self.youtube_id,
"playlist_active": True, "playlist_active": True,
"playlist_name": self.youtube_meta["title"], "playlist_name": self.youtube_meta["title"],
"playlist_channel": self.youtube_meta["channel"], "playlist_channel": self.youtube_meta["channel"],
"playlist_channel_id": self.youtube_meta["channel_id"], "playlist_channel_id": self.youtube_meta["channel_id"],
"playlist_thumbnail": self.youtube_meta["thumbnails"][-1]["url"], "playlist_thumbnail": playlist_thumbnail,
"playlist_description": self.youtube_meta["description"] or False, "playlist_description": self.youtube_meta["description"] or False,
"playlist_last_refresh": int(datetime.now().strftime("%s")), "playlist_last_refresh": int(datetime.now().strftime("%s")),
} }
@@ -81,12 +86,10 @@ class YoutubePlaylist(YouTubeItem):
self.all_members = all_members self.all_members = all_members
@staticmethod def get_playlist_art(self):
def get_playlist_art():
"""download artwork of playlist""" """download artwork of playlist"""
thumbnails = ThumbManager() url = self.json_data["playlist_thumbnail"]
missing_playlists = thumbnails.get_missing_playlists() ThumbManager(self.youtube_id, item_type="playlist").download(url)
thumbnails.download_playlist(missing_playlists)
def add_vids_to_playlist(self): def add_vids_to_playlist(self):
"""sync the playlist id to videos""" """sync the playlist id to videos"""
@@ -145,17 +148,15 @@ class YoutubePlaylist(YouTubeItem):
previous_item = False previous_item = False
else: else:
previous_item = all_entries[current_idx - 1] previous_item = all_entries[current_idx - 1]
prev_thumb = ThumbManager().vid_thumb_path( prev_id = previous_item["youtube_id"]
previous_item["youtube_id"] previous_item["vid_thumb"] = ThumbManager(prev_id).vid_thumb_path()
)
previous_item["vid_thumb"] = prev_thumb
if current_idx == len(all_entries) - 1: if current_idx == len(all_entries) - 1:
next_item = False next_item = False
else: else:
next_item = all_entries[current_idx + 1] next_item = all_entries[current_idx + 1]
next_thumb = ThumbManager().vid_thumb_path(next_item["youtube_id"]) next_id = next_item["youtube_id"]
next_item["vid_thumb"] = next_thumb next_item["vid_thumb"] = ThumbManager(next_id).vid_thumb_path()
self.nav = { self.nav = {
"playlist_meta": { "playlist_meta": {

View File

@@ -12,6 +12,7 @@ from time import sleep
from home.src.download.queue import PendingList from home.src.download.queue import PendingList
from home.src.download.thumbnails import ThumbManager from home.src.download.thumbnails import ThumbManager
from home.src.download.yt_dlp_base import CookieHandler
from home.src.download.yt_dlp_handler import VideoDownloader from home.src.download.yt_dlp_handler import VideoDownloader
from home.src.es.connect import ElasticWrap from home.src.es.connect import ElasticWrap
from home.src.index.channel import YoutubeChannel from home.src.index.channel import YoutubeChannel
@@ -40,6 +41,13 @@ class Reindex:
self.all_channel_ids = False self.all_channel_ids = False
self.all_playlist_ids = False self.all_playlist_ids = False
def check_cookie(self):
"""validate cookie if enabled"""
if self.config["downloads"]["cookie_import"]:
valid = CookieHandler(self.config).validate()
if not valid:
return
def _get_daily(self): def _get_daily(self):
"""get daily refresh values""" """get daily refresh values"""
total_videos = self._get_total_hits("ta_video") total_videos = self._get_total_hits("ta_video")
@@ -64,14 +72,11 @@ class Reindex:
def _get_unrated_vids(self): def _get_unrated_vids(self):
"""get max 200 videos without rating if ryd integration is enabled""" """get max 200 videos without rating if ryd integration is enabled"""
data = { must_not_list = [
"size": 200, {"exists": {"field": "stats.average_rating"}},
"query": { {"term": {"active": {"value": False}}},
"bool": { ]
"must_not": [{"exists": {"field": "stats.average_rating"}}] data = {"size": 200, "query": {"bool": {"must_not": must_not_list}}}
}
},
}
response, _ = ElasticWrap("ta_video/_search").get(data=data) response, _ = ElasticWrap("ta_video/_search").get(data=data)
missing_rating = [i["_id"] for i in response["hits"]["hits"]] missing_rating = [i["_id"] for i in response["hits"]["hits"]]
@@ -173,10 +178,10 @@ class Reindex:
video.upload_to_es() video.upload_to_es()
thumb_handler = ThumbManager() thumb_handler = ThumbManager(youtube_id)
thumb_handler.delete_vid_thumb(youtube_id) thumb_handler.delete_video_thumb()
to_download = (youtube_id, video.json_data["vid_thumb_url"]) thumb_handler.download_video_thumb(video.json_data["vid_thumb_url"])
thumb_handler.download_vid([to_download], notify=False)
return return
@staticmethod @staticmethod
@@ -187,6 +192,10 @@ class Reindex:
subscribed = channel.json_data["channel_subscribed"] subscribed = channel.json_data["channel_subscribed"]
overwrites = channel.json_data.get("channel_overwrites", False) overwrites = channel.json_data.get("channel_overwrites", False)
channel.get_from_youtube() channel.get_from_youtube()
if not channel.json_data:
channel.deactivate()
return
channel.json_data["channel_subscribed"] = subscribed channel.json_data["channel_subscribed"] = subscribed
if overwrites: if overwrites:
channel.json_data["channel_overwrites"] = overwrites channel.json_data["channel_overwrites"] = overwrites
@@ -293,9 +302,9 @@ class ChannelUrlFixer:
"""fix filepath""" """fix filepath"""
print(f"{self.youtube_id}: fixing channel rename.") print(f"{self.youtube_id}: fixing channel rename.")
cache_dir = self.config["application"]["cache_dir"] cache_dir = self.config["application"]["cache_dir"]
new_file_path = os.path.join( new_path = os.path.join(
cache_dir, "download", self.youtube_id + ".mp4" cache_dir, "download", self.youtube_id + ".mp4"
) )
shutil.move(video_path_is, new_file_path) shutil.move(video_path_is, new_path, copy_function=shutil.copyfile)
VideoDownloader().move_to_archive(self.video.json_data) VideoDownloader().move_to_archive(self.video.json_data)
self.video.update_media_url() self.video.update_media_url()

View File

@@ -0,0 +1,321 @@
"""
functionality:
- download subtitles
- parse subtitles into it's cues
- index dubtitles
"""
import json
import os
from datetime import datetime
import requests
from home.src.es.connect import ElasticWrap
from home.src.ta.helper import requests_headers
class YoutubeSubtitle:
"""handle video subtitle functionality"""
def __init__(self, video):
self.video = video
self.languages = False
def _sub_conf_parse(self):
"""add additional conf values to self"""
languages_raw = self.video.config["downloads"]["subtitle"]
if languages_raw:
self.languages = [i.strip() for i in languages_raw.split(",")]
def get_subtitles(self):
"""check what to do"""
self._sub_conf_parse()
if not self.languages:
# no subtitles
return False
relevant_subtitles = []
for lang in self.languages:
user_sub = self._get_user_subtitles(lang)
if user_sub:
relevant_subtitles.append(user_sub)
continue
if self.video.config["downloads"]["subtitle_source"] == "auto":
auto_cap = self._get_auto_caption(lang)
if auto_cap:
relevant_subtitles.append(auto_cap)
return relevant_subtitles
def _get_auto_caption(self, lang):
"""get auto_caption subtitles"""
print(f"{self.video.youtube_id}-{lang}: get auto generated subtitles")
all_subtitles = self.video.youtube_meta.get("automatic_captions")
if not all_subtitles:
return False
video_media_url = self.video.json_data["media_url"]
media_url = video_media_url.replace(".mp4", f".{lang}.vtt")
all_formats = all_subtitles.get(lang)
if not all_formats:
return False
subtitle = [i for i in all_formats if i["ext"] == "json3"][0]
subtitle.update(
{"lang": lang, "source": "auto", "media_url": media_url}
)
return subtitle
def _normalize_lang(self):
"""normalize country specific language keys"""
all_subtitles = self.video.youtube_meta.get("subtitles")
if not all_subtitles:
return False
all_keys = list(all_subtitles.keys())
for key in all_keys:
lang = key.split("-")[0]
old = all_subtitles.pop(key)
if lang == "live_chat":
continue
all_subtitles[lang] = old
return all_subtitles
def _get_user_subtitles(self, lang):
"""get subtitles uploaded from channel owner"""
print(f"{self.video.youtube_id}-{lang}: get user uploaded subtitles")
all_subtitles = self._normalize_lang()
if not all_subtitles:
return False
video_media_url = self.video.json_data["media_url"]
media_url = video_media_url.replace(".mp4", f".{lang}.vtt")
all_formats = all_subtitles.get(lang)
if not all_formats:
# no user subtitles found
return False
subtitle = [i for i in all_formats if i["ext"] == "json3"][0]
subtitle.update(
{"lang": lang, "source": "user", "media_url": media_url}
)
return subtitle
def download_subtitles(self, relevant_subtitles):
"""download subtitle files to archive"""
videos_base = self.video.config["application"]["videos"]
indexed = []
for subtitle in relevant_subtitles:
dest_path = os.path.join(videos_base, subtitle["media_url"])
source = subtitle["source"]
lang = subtitle.get("lang")
response = requests.get(
subtitle["url"], headers=requests_headers()
)
if not response.ok:
print(f"{self.video.youtube_id}: failed to download subtitle")
print(response.text)
continue
parser = SubtitleParser(response.text, lang, source)
parser.process()
if not parser.all_cues:
continue
subtitle_str = parser.get_subtitle_str()
self._write_subtitle_file(dest_path, subtitle_str)
if self.video.config["downloads"]["subtitle_index"]:
query_str = parser.create_bulk_import(self.video, source)
self._index_subtitle(query_str)
indexed.append(subtitle)
return indexed
@staticmethod
def _write_subtitle_file(dest_path, subtitle_str):
"""write subtitle file to disk"""
# create folder here for first video of channel
os.makedirs(os.path.split(dest_path)[0], exist_ok=True)
with open(dest_path, "w", encoding="utf-8") as subfile:
subfile.write(subtitle_str)
@staticmethod
def _index_subtitle(query_str):
"""send subtitle to es for indexing"""
_, _ = ElasticWrap("_bulk").post(data=query_str, ndjson=True)
def delete(self, subtitles=False):
"""delete subtitles from index and filesystem"""
youtube_id = self.video.youtube_id
videos_base = self.video.config["application"]["videos"]
# delete files
if subtitles:
files = [i["media_url"] for i in subtitles]
else:
if not self.video.json_data.get("subtitles"):
return
files = [i["media_url"] for i in self.video.json_data["subtitles"]]
for file_name in files:
file_path = os.path.join(videos_base, file_name)
try:
os.remove(file_path)
except FileNotFoundError:
print(f"{youtube_id}: {file_path} failed to delete")
# delete from index
path = "ta_subtitle/_delete_by_query?refresh=true"
data = {"query": {"term": {"youtube_id": {"value": youtube_id}}}}
_, _ = ElasticWrap(path).post(data=data)
class SubtitleParser:
"""parse subtitle str from youtube"""
def __init__(self, subtitle_str, lang, source):
self.subtitle_raw = json.loads(subtitle_str)
self.lang = lang
self.source = source
self.all_cues = False
def process(self):
"""extract relevant que data"""
self.all_cues = []
all_events = self.subtitle_raw.get("events")
if not all_events:
return
if self.source == "auto":
all_events = self._flat_auto_caption(all_events)
for idx, event in enumerate(all_events):
if "dDurationMs" not in event or "segs" not in event:
# some events won't have a duration or segs
print(f"skipping subtitle event without content: {event}")
continue
cue = {
"start": self._ms_conv(event["tStartMs"]),
"end": self._ms_conv(event["tStartMs"] + event["dDurationMs"]),
"text": "".join([i.get("utf8") for i in event["segs"]]),
"idx": idx + 1,
}
self.all_cues.append(cue)
@staticmethod
def _flat_auto_caption(all_events):
"""flatten autocaption segments"""
flatten = []
for event in all_events:
if "segs" not in event.keys():
continue
text = "".join([i.get("utf8") for i in event.get("segs")])
if not text.strip():
continue
if flatten:
# fix overlapping retiming issue
last = flatten[-1]
if "dDurationMs" not in last or "segs" not in last:
# some events won't have a duration or segs
print(f"skipping subtitle event without content: {event}")
continue
last_end = last["tStartMs"] + last["dDurationMs"]
if event["tStartMs"] < last_end:
joined = last["segs"][0]["utf8"] + "\n" + text
last["segs"][0]["utf8"] = joined
continue
event.update({"segs": [{"utf8": text}]})
flatten.append(event)
return flatten
@staticmethod
def _ms_conv(ms):
"""convert ms to timestamp"""
hours = str((ms // (1000 * 60 * 60)) % 24).zfill(2)
minutes = str((ms // (1000 * 60)) % 60).zfill(2)
secs = str((ms // 1000) % 60).zfill(2)
millis = str(ms % 1000).zfill(3)
return f"{hours}:{minutes}:{secs}.{millis}"
def get_subtitle_str(self):
"""create vtt text str from cues"""
subtitle_str = f"WEBVTT\nKind: captions\nLanguage: {self.lang}"
for cue in self.all_cues:
stamp = f"{cue.get('start')} --> {cue.get('end')}"
cue_text = f"\n\n{cue.get('idx')}\n{stamp}\n{cue.get('text')}"
subtitle_str = subtitle_str + cue_text
return subtitle_str
def create_bulk_import(self, video, source):
"""subtitle lines for es import"""
documents = self._create_documents(video, source)
bulk_list = []
for document in documents:
document_id = document.get("subtitle_fragment_id")
action = {"index": {"_index": "ta_subtitle", "_id": document_id}}
bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(document))
bulk_list.append("\n")
query_str = "\n".join(bulk_list)
return query_str
def _create_documents(self, video, source):
"""process documents"""
documents = self._chunk_list(video.youtube_id)
channel = video.json_data.get("channel")
meta_dict = {
"youtube_id": video.youtube_id,
"title": video.json_data.get("title"),
"subtitle_channel": channel.get("channel_name"),
"subtitle_channel_id": channel.get("channel_id"),
"subtitle_last_refresh": int(datetime.now().strftime("%s")),
"subtitle_lang": self.lang,
"subtitle_source": source,
}
_ = [i.update(meta_dict) for i in documents]
return documents
def _chunk_list(self, youtube_id):
"""join cues for bulk import"""
chunk_list = []
chunk = {}
for cue in self.all_cues:
if chunk:
text = f"{chunk.get('subtitle_line')} {cue.get('text')}\n"
chunk["subtitle_line"] = text
else:
idx = len(chunk_list) + 1
chunk = {
"subtitle_index": idx,
"subtitle_line": cue.get("text"),
"subtitle_start": cue.get("start"),
}
chunk["subtitle_fragment_id"] = f"{youtube_id}-{self.lang}-{idx}"
if cue["idx"] % 5 == 0:
chunk["subtitle_end"] = cue.get("end")
chunk_list.append(chunk)
chunk = {}
return chunk_list

View File

@@ -4,7 +4,6 @@ functionality:
- index and update in es - index and update in es
""" """
import json
import os import os
from datetime import datetime from datetime import datetime
@@ -14,311 +13,12 @@ from home.src.es.connect import ElasticWrap
from home.src.index import channel as ta_channel from home.src.index import channel as ta_channel
from home.src.index import playlist as ta_playlist from home.src.index import playlist as ta_playlist
from home.src.index.generic import YouTubeItem from home.src.index.generic import YouTubeItem
from home.src.ta.helper import ( from home.src.index.subtitle import YoutubeSubtitle
DurationConverter, from home.src.ta.helper import DurationConverter, clean_string, randomizor
clean_string,
randomizor,
requests_headers,
)
from home.src.ta.ta_redis import RedisArchivist from home.src.ta.ta_redis import RedisArchivist
from ryd_client import ryd_client from ryd_client import ryd_client
class YoutubeSubtitle:
"""handle video subtitle functionality"""
def __init__(self, video):
self.video = video
self.languages = False
def _sub_conf_parse(self):
"""add additional conf values to self"""
languages_raw = self.video.config["downloads"]["subtitle"]
if languages_raw:
self.languages = [i.strip() for i in languages_raw.split(",")]
def get_subtitles(self):
"""check what to do"""
self._sub_conf_parse()
if not self.languages:
# no subtitles
return False
relevant_subtitles = []
for lang in self.languages:
user_sub = self._get_user_subtitles(lang)
if user_sub:
relevant_subtitles.append(user_sub)
continue
if self.video.config["downloads"]["subtitle_source"] == "auto":
auto_cap = self._get_auto_caption(lang)
if auto_cap:
relevant_subtitles.append(auto_cap)
return relevant_subtitles
def _get_auto_caption(self, lang):
"""get auto_caption subtitles"""
print(f"{self.video.youtube_id}-{lang}: get auto generated subtitles")
all_subtitles = self.video.youtube_meta.get("automatic_captions")
if not all_subtitles:
return False
video_media_url = self.video.json_data["media_url"]
media_url = video_media_url.replace(".mp4", f".{lang}.vtt")
all_formats = all_subtitles.get(lang)
if not all_formats:
return False
subtitle = [i for i in all_formats if i["ext"] == "json3"][0]
subtitle.update(
{"lang": lang, "source": "auto", "media_url": media_url}
)
return subtitle
def _normalize_lang(self):
"""normalize country specific language keys"""
all_subtitles = self.video.youtube_meta.get("subtitles")
if not all_subtitles:
return False
all_keys = list(all_subtitles.keys())
for key in all_keys:
lang = key.split("-")[0]
old = all_subtitles.pop(key)
if lang == "live_chat":
continue
all_subtitles[lang] = old
return all_subtitles
def _get_user_subtitles(self, lang):
"""get subtitles uploaded from channel owner"""
print(f"{self.video.youtube_id}-{lang}: get user uploaded subtitles")
all_subtitles = self._normalize_lang()
if not all_subtitles:
return False
video_media_url = self.video.json_data["media_url"]
media_url = video_media_url.replace(".mp4", f".{lang}.vtt")
all_formats = all_subtitles.get(lang)
if not all_formats:
# no user subtitles found
return False
subtitle = [i for i in all_formats if i["ext"] == "json3"][0]
subtitle.update(
{"lang": lang, "source": "user", "media_url": media_url}
)
return subtitle
def download_subtitles(self, relevant_subtitles):
"""download subtitle files to archive"""
videos_base = self.video.config["application"]["videos"]
for subtitle in relevant_subtitles:
dest_path = os.path.join(videos_base, subtitle["media_url"])
source = subtitle["source"]
lang = subtitle.get("lang")
response = requests.get(
subtitle["url"], headers=requests_headers()
)
if not response.ok:
print(f"{self.video.youtube_id}: failed to download subtitle")
print(response.text)
continue
parser = SubtitleParser(response.text, lang, source)
parser.process()
subtitle_str = parser.get_subtitle_str()
self._write_subtitle_file(dest_path, subtitle_str)
if self.video.config["downloads"]["subtitle_index"]:
query_str = parser.create_bulk_import(self.video, source)
self._index_subtitle(query_str)
@staticmethod
def _write_subtitle_file(dest_path, subtitle_str):
"""write subtitle file to disk"""
# create folder here for first video of channel
os.makedirs(os.path.split(dest_path)[0], exist_ok=True)
with open(dest_path, "w", encoding="utf-8") as subfile:
subfile.write(subtitle_str)
@staticmethod
def _index_subtitle(query_str):
"""send subtitle to es for indexing"""
_, _ = ElasticWrap("_bulk").post(data=query_str, ndjson=True)
def delete(self, subtitles=False):
"""delete subtitles from index and filesystem"""
youtube_id = self.video.youtube_id
videos_base = self.video.config["application"]["videos"]
# delete files
if subtitles:
files = [i["media_url"] for i in subtitles]
else:
if not self.video.json_data.get("subtitles"):
return
files = [i["media_url"] for i in self.video.json_data["subtitles"]]
for file_name in files:
file_path = os.path.join(videos_base, file_name)
try:
os.remove(file_path)
except FileNotFoundError:
print(f"{youtube_id}: {file_path} failed to delete")
# delete from index
path = "ta_subtitle/_delete_by_query?refresh=true"
data = {"query": {"term": {"youtube_id": {"value": youtube_id}}}}
_, _ = ElasticWrap(path).post(data=data)
class SubtitleParser:
"""parse subtitle str from youtube"""
def __init__(self, subtitle_str, lang, source):
self.subtitle_raw = json.loads(subtitle_str)
self.lang = lang
self.source = source
self.all_cues = False
def process(self):
"""extract relevant que data"""
all_events = self.subtitle_raw.get("events")
if self.source == "auto":
all_events = self._flat_auto_caption(all_events)
self.all_cues = []
for idx, event in enumerate(all_events):
if "dDurationMs" not in event or "segs" not in event:
# some events won't have a duration or segs
print(f"skipping subtitle event without content: {event}")
continue
cue = {
"start": self._ms_conv(event["tStartMs"]),
"end": self._ms_conv(event["tStartMs"] + event["dDurationMs"]),
"text": "".join([i.get("utf8") for i in event["segs"]]),
"idx": idx + 1,
}
self.all_cues.append(cue)
@staticmethod
def _flat_auto_caption(all_events):
"""flatten autocaption segments"""
flatten = []
for event in all_events:
if "segs" not in event.keys():
continue
text = "".join([i.get("utf8") for i in event.get("segs")])
if not text.strip():
continue
if flatten:
# fix overlapping retiming issue
last = flatten[-1]
if "dDurationMs" not in last or "segs" not in last:
# some events won't have a duration or segs
print(f"skipping subtitle event without content: {event}")
continue
last_end = last["tStartMs"] + last["dDurationMs"]
if event["tStartMs"] < last_end:
joined = last["segs"][0]["utf8"] + "\n" + text
last["segs"][0]["utf8"] = joined
continue
event.update({"segs": [{"utf8": text}]})
flatten.append(event)
return flatten
@staticmethod
def _ms_conv(ms):
"""convert ms to timestamp"""
hours = str((ms // (1000 * 60 * 60)) % 24).zfill(2)
minutes = str((ms // (1000 * 60)) % 60).zfill(2)
secs = str((ms // 1000) % 60).zfill(2)
millis = str(ms % 1000).zfill(3)
return f"{hours}:{minutes}:{secs}.{millis}"
def get_subtitle_str(self):
"""create vtt text str from cues"""
subtitle_str = f"WEBVTT\nKind: captions\nLanguage: {self.lang}"
for cue in self.all_cues:
stamp = f"{cue.get('start')} --> {cue.get('end')}"
cue_text = f"\n\n{cue.get('idx')}\n{stamp}\n{cue.get('text')}"
subtitle_str = subtitle_str + cue_text
return subtitle_str
def create_bulk_import(self, video, source):
"""subtitle lines for es import"""
documents = self._create_documents(video, source)
bulk_list = []
for document in documents:
document_id = document.get("subtitle_fragment_id")
action = {"index": {"_index": "ta_subtitle", "_id": document_id}}
bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(document))
bulk_list.append("\n")
query_str = "\n".join(bulk_list)
return query_str
def _create_documents(self, video, source):
"""process documents"""
documents = self._chunk_list(video.youtube_id)
channel = video.json_data.get("channel")
meta_dict = {
"youtube_id": video.youtube_id,
"title": video.json_data.get("title"),
"subtitle_channel": channel.get("channel_name"),
"subtitle_channel_id": channel.get("channel_id"),
"subtitle_last_refresh": int(datetime.now().strftime("%s")),
"subtitle_lang": self.lang,
"subtitle_source": source,
}
_ = [i.update(meta_dict) for i in documents]
return documents
def _chunk_list(self, youtube_id):
"""join cues for bulk import"""
chunk_list = []
chunk = {}
for cue in self.all_cues:
if chunk:
text = f"{chunk.get('subtitle_line')} {cue.get('text')}\n"
chunk["subtitle_line"] = text
else:
idx = len(chunk_list) + 1
chunk = {
"subtitle_index": idx,
"subtitle_line": cue.get("text"),
"subtitle_start": cue.get("start"),
}
chunk["subtitle_fragment_id"] = f"{youtube_id}-{self.lang}-{idx}"
if cue["idx"] % 5 == 0:
chunk["subtitle_end"] = cue.get("end")
chunk_list.append(chunk)
chunk = {}
return chunk_list
class SponsorBlock: class SponsorBlock:
"""handle sponsor block integration""" """handle sponsor block integration"""
@@ -339,7 +39,7 @@ class SponsorBlock:
sb_id = RedisArchivist().get_message(key) sb_id = RedisArchivist().get_message(key)
if not sb_id["status"]: if not sb_id["status"]:
sb_id = {"status": randomizor(32)} sb_id = {"status": randomizor(32)}
RedisArchivist().set_message(key, sb_id, expire=False) RedisArchivist().set_message(key, sb_id)
return sb_id return sb_id
@@ -348,9 +48,17 @@ class SponsorBlock:
url = f"{self.API}/skipSegments?videoID={youtube_id}" url = f"{self.API}/skipSegments?videoID={youtube_id}"
headers = {"User-Agent": self.user_agent} headers = {"User-Agent": self.user_agent}
print(f"{youtube_id}: get sponsorblock timestamps") print(f"{youtube_id}: get sponsorblock timestamps")
response = requests.get(url, headers=headers) try:
response = requests.get(url, headers=headers, timeout=10)
except requests.ReadTimeout:
print(f"{youtube_id}: sponsorblock API timeout")
return False
if not response.ok: if not response.ok:
print(f"{youtube_id}: sponsorblock failed: {response.text}") print(f"{youtube_id}: sponsorblock failed: {response.status_code}")
if response.status_code == 503:
return False
sponsor_dict = { sponsor_dict = {
"last_refresh": self.last_refresh, "last_refresh": self.last_refresh,
"is_enabled": True, "is_enabled": True,
@@ -425,18 +133,23 @@ class YoutubeVideo(YouTubeItem, YoutubeSubtitle):
self.channel_id = False self.channel_id = False
self.video_overwrites = video_overwrites self.video_overwrites = video_overwrites
self.es_path = f"{self.index_name}/_doc/{youtube_id}" self.es_path = f"{self.index_name}/_doc/{youtube_id}"
self.offline_import = False
def build_json(self): def build_json(self, youtube_meta_overwrite=False, media_path=False):
"""build json dict of video""" """build json dict of video"""
self.get_from_youtube() self.get_from_youtube()
if not self.youtube_meta: if not self.youtube_meta and not youtube_meta_overwrite:
return return
if not self.youtube_meta:
self.youtube_meta = youtube_meta_overwrite
self.offline_import = True
self._process_youtube_meta() self._process_youtube_meta()
self._add_channel() self._add_channel()
self._add_stats() self._add_stats()
self.add_file_path() self.add_file_path()
self.add_player() self.add_player(media_path)
if self.config["downloads"]["integrate_ryd"]: if self.config["downloads"]["integrate_ryd"]:
self._get_ryd_stats() self._get_ryd_stats()
@@ -487,7 +200,7 @@ class YoutubeVideo(YouTubeItem, YoutubeSubtitle):
def _add_channel(self): def _add_channel(self):
"""add channel dict to video json_data""" """add channel dict to video json_data"""
channel = ta_channel.YoutubeChannel(self.channel_id) channel = ta_channel.YoutubeChannel(self.channel_id)
channel.build_json(upload=True) channel.build_json(upload=True, fallback=self.youtube_meta)
self.json_data.update({"channel": channel.json_data}) self.json_data.update({"channel": channel.json_data})
def _add_stats(self): def _add_stats(self):
@@ -495,13 +208,14 @@ class YoutubeVideo(YouTubeItem, YoutubeSubtitle):
# likes # likes
like_count = self.youtube_meta.get("like_count", 0) like_count = self.youtube_meta.get("like_count", 0)
dislike_count = self.youtube_meta.get("dislike_count", 0) dislike_count = self.youtube_meta.get("dislike_count", 0)
average_rating = self.youtube_meta.get("average_rating", 0)
self.json_data.update( self.json_data.update(
{ {
"stats": { "stats": {
"view_count": self.youtube_meta["view_count"], "view_count": self.youtube_meta["view_count"],
"like_count": like_count, "like_count": like_count,
"dislike_count": dislike_count, "dislike_count": dislike_count,
"average_rating": self.youtube_meta["average_rating"], "average_rating": average_rating,
} }
} }
) )
@@ -518,8 +232,28 @@ class YoutubeVideo(YouTubeItem, YoutubeSubtitle):
raise FileNotFoundError raise FileNotFoundError
def add_player(self): def add_player(self, media_path=False):
"""add player information for new videos""" """add player information for new videos"""
vid_path = self._get_vid_path(media_path)
duration_handler = DurationConverter()
duration = duration_handler.get_sec(vid_path)
duration_str = duration_handler.get_str(duration)
self.json_data.update(
{
"player": {
"watched": False,
"duration": duration,
"duration_str": duration_str,
}
}
)
def _get_vid_path(self, media_path=False):
"""get path of media file"""
if media_path:
return media_path
try: try:
# when indexing from download task # when indexing from download task
vid_path = self.build_dl_cache_path() vid_path = self.build_dl_cache_path()
@@ -535,18 +269,7 @@ class YoutubeVideo(YouTubeItem, YoutubeSubtitle):
else: else:
raise FileNotFoundError("could not find video file") from err raise FileNotFoundError("could not find video file") from err
duration_handler = DurationConverter() return vid_path
duration = duration_handler.get_sec(vid_path)
duration_str = duration_handler.get_str(duration)
self.json_data.update(
{
"player": {
"watched": False,
"duration": duration,
"duration_str": duration_str,
}
}
)
def add_file_path(self): def add_file_path(self):
"""build media_url for where file will be located""" """build media_url for where file will be located"""
@@ -605,37 +328,60 @@ class YoutubeVideo(YouTubeItem, YoutubeSubtitle):
def _get_ryd_stats(self): def _get_ryd_stats(self):
"""get optional stats from returnyoutubedislikeapi.com""" """get optional stats from returnyoutubedislikeapi.com"""
# pylint: disable=broad-except
try: try:
print(f"{self.youtube_id}: get ryd stats") print(f"{self.youtube_id}: get ryd stats")
result = ryd_client.get(self.youtube_id) result = ryd_client.get(self.youtube_id)
except requests.exceptions.ConnectionError: except Exception as err:
print(f"{self.youtube_id}: failed to query ryd api, skipping") print(f"{self.youtube_id}: failed to query ryd api {err}")
return False return
if result["status"] == 404: if result["status"] == 404:
return False return
dislikes = { dislikes = {
"dislike_count": result["dislikes"], "dislike_count": result.get("dislikes", 0),
"average_rating": result["rating"], "average_rating": result.get("rating", 0),
} }
self.json_data["stats"].update(dislikes) self.json_data["stats"].update(dislikes)
return True
def _get_sponsorblock(self): def _get_sponsorblock(self):
"""get optional sponsorblock timestamps from sponsor.ajay.app""" """get optional sponsorblock timestamps from sponsor.ajay.app"""
sponsorblock = SponsorBlock().get_timestamps(self.youtube_id) sponsorblock = SponsorBlock().get_timestamps(self.youtube_id)
if sponsorblock: if sponsorblock:
self.json_data["sponsorblock"] = sponsorblock self.json_data["sponsorblock"] = sponsorblock
def check_subtitles(self): def check_subtitles(self, subtitle_files=False):
"""optionally add subtitles""" """optionally add subtitles"""
if self.offline_import and subtitle_files:
indexed = self._offline_subtitles(subtitle_files)
self.json_data["subtitles"] = indexed
return
handler = YoutubeSubtitle(self) handler = YoutubeSubtitle(self)
subtitles = handler.get_subtitles() subtitles = handler.get_subtitles()
if subtitles: if subtitles:
self.json_data["subtitles"] = subtitles indexed = handler.download_subtitles(relevant_subtitles=subtitles)
handler.download_subtitles(relevant_subtitles=subtitles) self.json_data["subtitles"] = indexed
def _offline_subtitles(self, subtitle_files):
"""import offline subtitles"""
base_name, _ = os.path.splitext(self.json_data["media_url"])
subtitles = []
for subtitle in subtitle_files:
lang = subtitle.split(".")[-2]
subtitle_media_url = f"{base_name}.{lang}.vtt"
to_add = {
"ext": "vtt",
"url": False,
"name": lang,
"lang": lang,
"source": "file",
"media_url": subtitle_media_url,
}
subtitles.append(to_add)
return subtitles
def update_media_url(self): def update_media_url(self):
"""update only media_url in es for reindex channel rename""" """update only media_url in es for reindex channel rename"""

View File

@@ -99,7 +99,7 @@ class AppConfig:
self.config[config_dict][config_value] = to_write self.config[config_dict][config_value] = to_write
updated.append((config_value, to_write)) updated.append((config_value, to_write))
RedisArchivist().set_message("config", self.config, expire=False) RedisArchivist().set_message("config", self.config)
return updated return updated
@staticmethod @staticmethod
@@ -111,7 +111,7 @@ class AppConfig:
message = {"status": value} message = {"status": value}
redis_key = f"{user_id}:{key}" redis_key = f"{user_id}:{key}"
RedisArchivist().set_message(redis_key, message, expire=False) RedisArchivist().set_message(redis_key, message)
def get_colors(self): def get_colors(self):
"""overwrite config if user has set custom values""" """overwrite config if user has set custom values"""
@@ -133,6 +133,8 @@ class AppConfig:
# check for customizations # check for customizations
if not redis_config: if not redis_config:
config = self.get_config()
RedisArchivist().set_message("config", config)
return return
needs_update = False needs_update = False
@@ -151,7 +153,7 @@ class AppConfig:
needs_update = True needs_update = True
if needs_update: if needs_update:
RedisArchivist().set_message("config", redis_config, expire=False) RedisArchivist().set_message("config", redis_config)
class ScheduleBuilder: class ScheduleBuilder:
@@ -165,6 +167,7 @@ class ScheduleBuilder:
"run_backup": "0 18 0", "run_backup": "0 18 0",
} }
CONFIG = ["check_reindex_days", "run_backup_rotate"] CONFIG = ["check_reindex_days", "run_backup_rotate"]
MSG = "message:setting"
def __init__(self): def __init__(self):
self.config = AppConfig().config self.config = AppConfig().config
@@ -180,25 +183,27 @@ class ScheduleBuilder:
except ValueError: except ValueError:
print(f"failed: {key} {value}") print(f"failed: {key} {value}")
mess_dict = { mess_dict = {
"status": "message:setting", "status": self.MSG,
"level": "error", "level": "error",
"title": "Scheduler update failed.", "title": "Scheduler update failed.",
"message": "Invalid schedule input", "message": "Invalid schedule input",
} }
RedisArchivist().set_message("message:setting", mess_dict) RedisArchivist().set_message(
self.MSG, mess_dict, expire=True
)
return return
redis_config["scheduler"][key] = to_write redis_config["scheduler"][key] = to_write
if key in self.CONFIG and value: if key in self.CONFIG and value:
redis_config["scheduler"][key] = int(value) redis_config["scheduler"][key] = int(value)
RedisArchivist().set_message("config", redis_config, expire=False) RedisArchivist().set_message("config", redis_config)
mess_dict = { mess_dict = {
"status": "message:setting", "status": self.MSG,
"level": "info", "level": "info",
"title": "Scheduler changed.", "title": "Scheduler changed.",
"message": "Please restart container for changes to take effect", "message": "Please restart container for changes to take effect",
} }
RedisArchivist().set_message("message:setting", mess_dict) RedisArchivist().set_message(self.MSG, mess_dict, expire=True)
def value_builder(self, key, value): def value_builder(self, key, value):
"""validate single cron form entry and return cron dict""" """validate single cron form entry and return cron dict"""

View File

@@ -105,6 +105,18 @@ def date_praser(timestamp):
return datetime.strftime(date_obj, "%d %b, %Y") return datetime.strftime(date_obj, "%d %b, %Y")
def time_parser(timestamp):
"""return seconds from timestamp, false on empty"""
if not timestamp:
return False
if timestamp.isnumeric():
return int(timestamp)
hours, minutes, seconds = timestamp.split(":", maxsplit=3)
return int(hours) * 60 * 60 + int(minutes) * 60 + float(seconds)
class UrlListParser: class UrlListParser:
"""take a multi line string and detect valid youtube ids""" """take a multi line string and detect valid youtube ids"""
@@ -146,12 +158,12 @@ class UrlListParser:
if parsed.query: if parsed.query:
# detect from query string # detect from query string
query_parsed = parse_qs(parsed.query) query_parsed = parse_qs(parsed.query)
if "v" in query_parsed.keys(): if "v" in query_parsed:
youtube_id = query_parsed["v"][0] youtube_id = query_parsed["v"][0]
_ = self.find_valid_id(youtube_id) _ = self.find_valid_id(youtube_id)
return youtube_id, "video" return youtube_id, "video"
if "list" in query_parsed.keys(): if "list" in query_parsed:
youtube_id = query_parsed["list"][0] youtube_id = query_parsed["list"][0]
return youtube_id, "playlist" return youtube_id, "playlist"
@@ -161,13 +173,13 @@ class UrlListParser:
_ = self.find_valid_id(youtube_id) _ = self.find_valid_id(youtube_id)
return youtube_id, "channel" return youtube_id, "channel"
# dedect channel with yt_dlp # detect channel with yt_dlp
youtube_id = self.extract_channel_name(parsed.geturl()) youtube_id = self.extract_channel_name(parsed.geturl())
return youtube_id, "channel" return youtube_id, "channel"
@staticmethod @staticmethod
def find_valid_id(id_str): def find_valid_id(id_str):
"""dedect valid id from length of string""" """detect valid id from length of string"""
str_len = len(id_str) str_len = len(id_str)
if str_len == 11: if str_len == 11:
id_type = "video" id_type = "video"
@@ -190,13 +202,19 @@ class UrlListParser:
"playlistend": 0, "playlistend": 0,
} }
url_info = YtWrap(obs_request).extract(url) url_info = YtWrap(obs_request).extract(url)
try: channel_id = url_info.get("channel_id", False)
channel_id = url_info["channel_id"] if channel_id:
except KeyError as error: return channel_id
print(f"failed to extract channel id from {url}")
raise ValueError from error
return channel_id url = url_info.get("url", False)
if url:
# handle old channel name redirect with url path split
channel_id = urlparse(url).path.strip("/").split("/")[1]
return channel_id
print(f"failed to extract channel id from {url}")
raise ValueError
class DurationConverter: class DurationConverter:

View File

@@ -34,10 +34,10 @@ class RedisArchivist(RedisBase):
"setting", "setting",
] ]
def set_message(self, key, message, expire=True): def set_message(self, key, message, path=".", expire=False):
"""write new message to redis""" """write new message to redis"""
self.conn.execute_command( self.conn.execute_command(
"JSON.SET", self.NAME_SPACE + key, ".", json.dumps(message) "JSON.SET", self.NAME_SPACE + key, path, json.dumps(message)
) )
if expire: if expire:
@@ -80,6 +80,12 @@ class RedisArchivist(RedisBase):
redis_lock = self.conn.lock(self.NAME_SPACE + lock_key) redis_lock = self.conn.lock(self.NAME_SPACE + lock_key)
return redis_lock return redis_lock
def is_locked(self, lock_key):
"""check if lock is set"""
lock_name = self.NAME_SPACE + lock_key
lock_status = bool(self.conn.execute_command("GET", lock_name))
return lock_status
def get_progress(self): def get_progress(self):
"""get a list of all progress messages""" """get a list of all progress messages"""
all_messages = [] all_messages = []
@@ -137,3 +143,8 @@ class RedisQueue(RedisBase):
def trim(self, size): def trim(self, size):
"""trim the queue based on settings amount""" """trim the queue based on settings amount"""
self.conn.execute_command("LTRIM", self.key, 0, size) self.conn.execute_command("LTRIM", self.key, 0, size)
def has_item(self):
"""check if queue as at least one pending item"""
result = self.conn.execute_command("LRANGE", self.key, 0, 0)
return bool(result)

View File

@@ -15,12 +15,12 @@ from home.src.download.subscriptions import (
ChannelSubscription, ChannelSubscription,
PlaylistSubscription, PlaylistSubscription,
) )
from home.src.download.thumbnails import ThumbManager, validate_thumbnails from home.src.download.thumbnails import ThumbFilesystem, ThumbValidator
from home.src.download.yt_dlp_handler import VideoDownloader from home.src.download.yt_dlp_handler import VideoDownloader
from home.src.es.index_setup import backup_all_indexes, restore_from_backup from home.src.es.index_setup import backup_all_indexes, restore_from_backup
from home.src.index.channel import YoutubeChannel from home.src.index.channel import YoutubeChannel
from home.src.index.filesystem import ( from home.src.index.filesystem import (
ManualImport, ImportFolderScanner,
reindex_old_documents, reindex_old_documents,
scan_filesystem, scan_filesystem,
) )
@@ -48,7 +48,7 @@ def update_subscribed():
"title": "Rescanning channels and playlists.", "title": "Rescanning channels and playlists.",
"message": "Looking for new videos.", "message": "Looking for new videos.",
} }
RedisArchivist().set_message("message:rescan", message) RedisArchivist().set_message("message:rescan", message, expire=True)
have_lock = False have_lock = False
my_lock = RedisArchivist().get_lock("rescan") my_lock = RedisArchivist().get_lock("rescan")
@@ -108,13 +108,14 @@ def download_single(youtube_id):
try: try:
have_lock = my_lock.acquire(blocking=False) have_lock = my_lock.acquire(blocking=False)
if have_lock: if have_lock:
key = "message:download"
mess_dict = { mess_dict = {
"status": "message:download", "status": key,
"level": "info", "level": "info",
"title": "Download single video", "title": "Download single video",
"message": "processing", "message": "processing",
} }
RedisArchivist().set_message("message:download", mess_dict) RedisArchivist().set_message(key, mess_dict, expire=True)
VideoDownloader().run_queue() VideoDownloader().run_queue()
else: else:
print("Download queue already running.") print("Download queue already running.")
@@ -149,10 +150,7 @@ def run_manual_import():
try: try:
have_lock = my_lock.acquire(blocking=False) have_lock = my_lock.acquire(blocking=False)
if have_lock: if have_lock:
import_handler = ManualImport() ImportFolderScanner().scan()
if import_handler.identified:
all_videos_added = import_handler.process_import()
ThumbManager().download_vid(all_videos_added)
else: else:
print("Did not acquire lock form import.") print("Did not acquire lock form import.")
@@ -164,8 +162,19 @@ def run_manual_import():
@shared_task(name="run_backup") @shared_task(name="run_backup")
def run_backup(reason="auto"): def run_backup(reason="auto"):
"""called from settings page, dump backup to zip file""" """called from settings page, dump backup to zip file"""
backup_all_indexes(reason) have_lock = False
print("backup finished") my_lock = RedisArchivist().get_lock("run_backup")
try:
have_lock = my_lock.acquire(blocking=False)
if have_lock:
backup_all_indexes(reason)
else:
print("Did not acquire lock for backup task.")
finally:
if have_lock:
my_lock.release()
print("backup finished")
@shared_task @shared_task
@@ -196,28 +205,26 @@ def kill_dl(task_id):
"title": "Canceling download process", "title": "Canceling download process",
"message": "Canceling download queue now.", "message": "Canceling download queue now.",
} }
RedisArchivist().set_message("message:download", mess_dict) RedisArchivist().set_message("message:download", mess_dict, expire=True)
@shared_task @shared_task
def rescan_filesystem(): def rescan_filesystem():
"""check the media folder for mismatches""" """check the media folder for mismatches"""
scan_filesystem() scan_filesystem()
validate_thumbnails() ThumbValidator().download_missing()
@shared_task(name="thumbnail_check") @shared_task(name="thumbnail_check")
def thumbnail_check(): def thumbnail_check():
"""validate thumbnails""" """validate thumbnails"""
validate_thumbnails() ThumbValidator().download_missing()
@shared_task @shared_task
def re_sync_thumbs(): def re_sync_thumbs():
"""sync thumbnails to mediafiles""" """sync thumbnails to mediafiles"""
handler = ThumbManager() ThumbFilesystem().sync()
video_list = handler.get_thumb_list()
handler.write_all_thumbs(video_list)
@shared_task @shared_task
@@ -228,9 +235,7 @@ def subscribe_to(url_str):
for item in to_subscribe_list: for item in to_subscribe_list:
to_sub_id = item["url"] to_sub_id = item["url"]
if item["type"] == "playlist": if item["type"] == "playlist":
new_thumbs = PlaylistSubscription().process_url_str([item]) PlaylistSubscription().process_url_str([item])
if new_thumbs:
ThumbManager().download_playlist(new_thumbs)
continue continue
if item["type"] == "video": if item["type"] == "video":
@@ -245,13 +250,14 @@ def subscribe_to(url_str):
channel_id_sub, channel_subscribed=True channel_id_sub, channel_subscribed=True
) )
# notify for channels # notify for channels
key = "message:subchannel"
message = { message = {
"status": "message:subchannel", "status": key,
"level": "info", "level": "info",
"title": "Subscribing to Channels", "title": "Subscribing to Channels",
"message": f"Processing {counter} of {len(to_subscribe_list)}", "message": f"Processing {counter} of {len(to_subscribe_list)}",
} }
RedisArchivist().set_message("message:subchannel", message=message) RedisArchivist().set_message(key, message=message, expire=True)
counter = counter + 1 counter = counter + 1
@@ -260,13 +266,14 @@ def index_channel_playlists(channel_id):
"""add all playlists of channel to index""" """add all playlists of channel to index"""
channel = YoutubeChannel(channel_id) channel = YoutubeChannel(channel_id)
# notify # notify
key = "message:playlistscan"
mess_dict = { mess_dict = {
"status": "message:playlistscan", "status": key,
"level": "info", "level": "info",
"title": "Looking for playlists", "title": "Looking for playlists",
"message": f'Scanning channel "{channel.youtube_id}" in progress', "message": f'Scanning channel "{channel.youtube_id}" in progress',
} }
RedisArchivist().set_message("message:playlistscan", mess_dict) RedisArchivist().set_message(key, mess_dict, expire=True)
channel.index_channel_playlists() channel.index_channel_playlists()

View File

@@ -79,16 +79,16 @@
<div class="pagination"> <div class="pagination">
{% if pagination %} {% if pagination %}
{% if pagination.current_page > 1 %} {% if pagination.current_page > 1 %}
{% if pagination.search_get %} {% if pagination.params %}
<a class="pagination-item" href="{{ request.path }}?search={{ pagination.search_get }}">First</a> <a class="pagination-item" href="{{ request.path }}?{{ pagination.params }}">First</a>
{% else %} {% else %}
<a class="pagination-item" href="{{ request.path }}">First</a> <a class="pagination-item" href="{{ request.path }}">First</a>
{% endif %} {% endif %}
{% endif %} {% endif %}
{% if pagination.prev_pages %} {% if pagination.prev_pages %}
{% for page in pagination.prev_pages %} {% for page in pagination.prev_pages %}
{% if pagination.search_get %} {% if pagination.params %}
<a class="pagination-item" href="?page={{ page }}&search={{ pagination.search_get }}">{{ page }}</a> <a class="pagination-item" href="?page={{ page }}&{{ pagination.params }}">{{ page }}</a>
{% else %} {% else %}
<a class="pagination-item" href="?page={{ page }}">{{ page }}</a> <a class="pagination-item" href="?page={{ page }}">{{ page }}</a>
{% endif %} {% endif %}
@@ -100,16 +100,16 @@
{% if pagination.next_pages %} {% if pagination.next_pages %}
<span> ></span> <span> ></span>
{% for page in pagination.next_pages %} {% for page in pagination.next_pages %}
{% if pagination.search_get %} {% if pagination.params %}
<a class="pagination-item" href="?page={{ page }}&search={{ pagination.search_get }}">{{ page }}</a> <a class="pagination-item" href="?page={{ page }}&{{ pagination.params }}">{{ page }}</a>
{% else %} {% else %}
<a class="pagination-item" href="?page={{ page }}">{{ page }}</a> <a class="pagination-item" href="?page={{ page }}">{{ page }}</a>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% endif %} {% endif %}
{% if pagination.last_page > 0 %} {% if pagination.last_page > 0 %}
{% if pagination.search_get %} {% if pagination.params %}
<a class="pagination-item" href="?page={{ pagination.last_page }}&search={{ pagination.search_get }}"> <a class="pagination-item" href="?page={{ pagination.last_page }}&{{ pagination.params }}">
{% if pagination.max_hits %} {% if pagination.max_hits %}
Max ({{ pagination.last_page }}) Max ({{ pagination.last_page }})
{% else %} {% else %}

View File

@@ -6,8 +6,16 @@
<div class="channel-banner"> <div class="channel-banner">
<a href="/channel/{{ channel_info.channel_id }}/"><img src="/cache/channels/{{ channel_info.channel_id }}_banner.jpg" alt="channel_banner"></a> <a href="/channel/{{ channel_info.channel_id }}/"><img src="/cache/channels/{{ channel_info.channel_id }}_banner.jpg" alt="channel_banner"></a>
</div> </div>
<div class="info-box-item channel-nav">
<a href="{% url 'channel_id' channel_info.channel_id %}"><h3>Videos</h3></a>
<a href="{% url 'channel_id_playlist' channel_info.channel_id %}"><h3>Playlists</h3></a>
<a href="{% url 'channel_id_about' channel_info.channel_id %}"><h3>About</h3></a>
{% if has_pending %}
<a href="{% url 'downloads' %}?channel={{ channel_info.channel_id }}"><h3>Downloads</h3></a>
{% endif %}
</div>
<div id="notifications" data="channel_id"></div> <div id="notifications" data="channel_id"></div>
<div class="info-box info-box-3"> <div class="info-box info-box-2">
<div class="info-box-item"> <div class="info-box-item">
<div class="round-img"> <div class="round-img">
<a href="{% url 'channel_id' channel_info.channel_id %}"> <a href="{% url 'channel_id' channel_info.channel_id %}">
@@ -30,88 +38,13 @@
</div> </div>
<div class="info-box-item"> <div class="info-box-item">
<div> <div>
<p>Last refreshed: {{ channel_info.channel_last_refresh }}</p>
{% if channel_info.channel_active %}
<p>Youtube: <a href="https://www.youtube.com/channel/{{ channel_info.channel_id }}" target="_blank">Active</a></p>
{% else %}
<p>Youtube: Deactivated</p>
{% endif %}
<button onclick="deleteConfirm()" id="delete-item">Delete Channel</button>
<div class="delete-confirm" id="delete-button">
<span>Delete {{ channel_info.channel_name }} including all videos? </span><button class="danger-button" onclick="deleteChannel(this)" data-id="{{ channel_info.channel_id }}">Delete</button> <button onclick="cancelDelete()">Cancel</button>
</div>
</div>
</div>
<div class="info-box-item">
<div>
{% if channel_info.channel_views >= 1000000 %}
<p>Channel views: {{ channel_info.channel_views|intword }}</p>
{% elif channel_info.channel_views > 0 %}
<p>Channel views: {{ channel_info.channel_views|intcomma }}</p>
{% endif %}
{% if max_hits %} {% if max_hits %}
<p>Total Videos archived: {{ max_hits }}</p> <p>Total Videos: {{ max_hits }}</p>
<p>Watched: <button title="Mark all videos from {{ channel_info.channel_name }} as watched" type="button" id="watched-button" data-id="{{ channel_info.channel_id }}" onclick="isWatchedButton(this)">Mark as watched</button></p> <button title="Mark all videos from {{ channel_info.channel_name }} as watched" type="button" id="watched-button" data-id="{{ channel_info.channel_id }}" onclick="isWatchedButton(this)">Mark as watched</button>
{% endif %} {% endif %}
<button {% if channel_info.channel_overwrites %} class="danger-button"{% endif %} onclick="showOverwrite()" title="Overwrite settings for channel {{ channel_info.channel_name }}">Configure</button>
<a href="/playlist/?search={{ channel_info.channel_id }}" title="Show all playlists belonging to {{ channel_info.channel_name }}"><button>Show Playlists</button></a>
</div> </div>
</div> </div>
</div> </div>
<div id="overwrite-form" class="info-box{% if not channel_info.channel_overwrites %} hidden-overwrite{% endif %}">
<div class="info-box-item">
<form class="overwrite-form" action="/channel/{{ channel_info.channel_id }}/" method="POST">
{% csrf_token %}
<div class="overwrite-form-item">
<p>Download format: <span class="settings-current">
{% if channel_info.channel_overwrites.download_format %}
{{ channel_info.channel_overwrites.download_format }}
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.download_format }}<br>
</div>
<div class="overwrite-form-item">
<p>Auto delete watched videos after x days: <span class="settings-current">
{% if channel_info.channel_overwrites.autodelete_days %}
{{ channel_info.channel_overwrites.autodelete_days }}
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.autodelete_days }}<br>
</div>
<div class="overwrite-form-item">
<p>Index playlists: <span class="settings-current">
{% if channel_info.channel_overwrites.index_playlists %}
{{ channel_info.channel_overwrites.index_playlists }}
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.index_playlists }}<br>
</div>
<div class="overwrite-form-item">
<p>Enable <a href="https://sponsor.ajay.app/" target="_blank">SponsorBlock</a>: <span class="settings-current">
{% if channel_info.channel_overwrites.integrate_sponsorblock %}
{{ channel_info.channel_overwrites.integrate_sponsorblock }}
{% elif channel_info.channel_overwrites.integrate_sponsorblock == False %}
Disabled
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.integrate_sponsorblock }}<br>
</div>
<button type="submit">Save Channel Overwrites</button>
</form>
</div>
</div>
{% if channel_info.channel_description %}
<div class="info-box-item description-box">
<p>Description: <button onclick="textReveal()" id="text-reveal-button">Show</button></p>
<div id="text-reveal" class="description-text">
{{ channel_info.channel_description|linebreaks }}
</div>
</div>
{% endif %}
</div> </div>
<div class="boxed-content {% if view_style == "grid" %}boxed-{{ grid_items }}{% endif %}"> <div class="boxed-content {% if view_style == "grid" %}boxed-{{ grid_items }}{% endif %}">
<div class="view-controls"> <div class="view-controls">

View File

@@ -0,0 +1,115 @@
{% extends "home/base.html" %}
{% block content %}
{% load static %}
{% load humanize %}
<div class="boxed-content">
<div class="channel-banner">
<a href="{% url 'channel_id' channel_info.channel_id %}"><img src="{{ channel_info.channel_banner_url }}" alt="channel_banner"></a>
</div>
<div class="info-box-item channel-nav">
<a href="{% url 'channel_id' channel_info.channel_id %}"><h3>Videos</h3></a>
<a href="{% url 'channel_id_playlist' channel_info.channel_id %}"><h3>Playlists</h3></a>
<a href="{% url 'channel_id_about' channel_info.channel_id %}"><h3>About</h3></a>
{% if has_pending %}
<a href="{% url 'downloads' %}?channel={{ channel_info.channel_id }}"><h3>Downloads</h3></a>
{% endif %}
</div>
<div class="info-box info-box-3">
<div class="info-box-item">
<div class="round-img">
<a href="{% url 'channel_id' channel_info.channel_id %}">
<img src="{{ channel_info.channel_thumb_url }}" alt="channel-thumb">
</a>
</div>
<div>
<h3><a href="{% url 'channel_id' channel_info.channel_id %}">{{ channel_info.channel_name }}</a></h3>
{% if channel_info.channel_subs >= 1000000 %}
<p>Subscribers: {{ channel_info.channel_subs|intword }}</p>
{% else %}
<p>Subscribers: {{ channel_info.channel_subs|intcomma }}</p>
{% endif %}
</div>
</div>
<div class="info-box-item">
<div>
<p>Last refreshed: {{ channel_info.channel_last_refresh }}</p>
{% if channel_info.channel_active %}
<p>Youtube: <a href="https://www.youtube.com/channel/{{ channel_info.channel_id }}" target="_blank">Active</a></p>
{% else %}
<p>Youtube: Deactivated</p>
{% endif %}
</div>
</div>
<div class="info-box-item">
<div>
{% if channel_info.channel_views >= 1000000 %}
<p>Channel views: {{ channel_info.channel_views|intword }}</p>
{% elif channel_info.channel_views > 0 %}
<p>Channel views: {{ channel_info.channel_views|intcomma }}</p>
{% endif %}
<button onclick="deleteConfirm()" id="delete-item">Delete Channel</button>
<div class="delete-confirm" id="delete-button">
<span>Delete {{ channel_info.channel_name }} including all videos? </span><button class="danger-button" onclick="deleteChannel(this)" data-id="{{ channel_info.channel_id }}">Delete</button> <button onclick="cancelDelete()">Cancel</button>
</div>
</div>
</div>
</div>
{% if channel_info.channel_description %}
<div class="description-box">
<p id="text-expand" class="description-text">
{{ channel_info.channel_description|linebreaksbr|urlizetrunc:50 }}
</p>
<button onclick="textExpand()" id="text-expand-button">Show more</button>
</div>
{% endif %}
<div class="description-box">
<h2>Customize {{ channel_info.channel_name }}</h2>
</div>
<div id="overwrite-form" class="info-box">
<div class="info-box-item">
<form class="overwrite-form" action="/channel/{{ channel_info.channel_id }}/about/" method="POST">
{% csrf_token %}
<div class="overwrite-form-item">
<p>Download format: <span class="settings-current">
{% if channel_info.channel_overwrites.download_format %}
{{ channel_info.channel_overwrites.download_format }}
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.download_format }}<br>
</div>
<div class="overwrite-form-item">
<p>Auto delete watched videos after x days: <span class="settings-current">
{% if channel_info.channel_overwrites.autodelete_days %}
{{ channel_info.channel_overwrites.autodelete_days }}
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.autodelete_days }}<br>
</div>
<div class="overwrite-form-item">
<p>Index playlists: <span class="settings-current">
{% if channel_info.channel_overwrites.index_playlists %}
{{ channel_info.channel_overwrites.index_playlists }}
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.index_playlists }}<br>
</div>
<div class="overwrite-form-item">
<p>Enable <a href="https://sponsor.ajay.app/" target="_blank">SponsorBlock</a>: <span class="settings-current">
{% if channel_info.channel_overwrites.integrate_sponsorblock %}
{{ channel_info.channel_overwrites.integrate_sponsorblock }}
{% elif channel_info.channel_overwrites.integrate_sponsorblock == False %}
Disabled
{% else %}
False
{% endif %}</span></p>
{{ channel_overwrite_form.integrate_sponsorblock }}<br>
</div>
<button type="submit">Save Channel Overwrites</button>
</form>
</div>
</div>
</div>
{% endblock content %}

View File

@@ -0,0 +1,60 @@
{% extends "home/base.html" %}
{% block content %}
{% load static %}
{% load humanize %}
<div class="boxed-content">
<div class="channel-banner">
<a href="{% url 'channel_id' channel_info.channel_id %}"><img src="{{ channel_info.channel_banner_url }}" alt="channel_banner"></a>
</div>
<div class="info-box-item channel-nav">
<a href="{% url 'channel_id' channel_info.channel_id %}"><h3>Videos</h3></a>
<a href="{% url 'channel_id_playlist' channel_info.channel_id %}"><h3>Playlists</h3></a>
<a href="{% url 'channel_id_about' channel_info.channel_id %}"><h3>About</h3></a>
{% if has_pending %}
<a href="{% url 'downloads' %}?channel={{ channel_info.channel_id }}"><h3>Downloads</h3></a>
{% endif %}
</div>
<div class="view-controls">
<div class="toggle">
<span>Show subscribed only:</span>
<div class="toggleBox">
<input id="show_subed_only" onclick="toggleCheckbox(this)" type="checkbox" {% if show_subed_only %}checked{% endif %}>
{% if not show_subed_only %}
<label for="" class="ofbtn">Off</label>
{% else %}
<label for="" class="onbtn">On</label>
{% endif %}
</div>
</div>
<div class="view-icons">
<img src="{% static 'img/icon-gridview.svg' %}" onclick="changeView(this)" data-origin="playlist" data-value="grid" alt="grid view">
<img src="{% static 'img/icon-listview.svg' %}" onclick="changeView(this)" data-origin="playlist" data-value="list" alt="list view">
</div>
</div>
<div class="playlist-list {{ view_style }}">
{% if results %}
{% for playlist in results %}
<div class="playlist-item {{ view_style }}">
<div class="playlist-thumbnail">
<a href="{% url 'playlist_id' playlist.source.playlist_id %}">
<img src="/cache/playlists/{{ playlist.source.playlist_id }}.jpg" alt="{{ playlist.source.playlist_id }}-thumbnail">
</a>
</div>
<div class="playlist-desc {{ view_style }}">
<a href="{% url 'channel_id' playlist.source.playlist_channel_id %}"><h3>{{ playlist.source.playlist_channel }}</h3></a>
<a href="{% url 'playlist_id' playlist.source.playlist_id %}"><h2>{{ playlist.source.playlist_name }}</h2></a>
<p>Last refreshed: {{ playlist.source.playlist_last_refresh }}</p>
{% if playlist.source.playlist_subscribed %}
<button class="unsubscribe" type="button" id="{{ playlist.source.playlist_id }}" onclick="unsubscribe(this.id)" title="Unsubscribe from {{ playlist.source.playlist_name }}">Unsubscribe</button>
{% else %}
<button type="button" id="{{ playlist.source.playlist_id }}" onclick="subscribe(this.id)" title="Subscribe to {{ playlist.source.playlist_name }}">Subscribe</button>
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<h2>No playlists found...</h2>
{% endif %}
</div>
</div>
{% endblock content %}

View File

@@ -3,7 +3,7 @@
{% block content %} {% block content %}
<div class="boxed-content"> <div class="boxed-content">
<div class="title-bar"> <div class="title-bar">
<h1>Downloads</h1> <h1>Downloads {% if channel_filter_id %} for {{ channel_filter_name }}{% endif %}</h1>
</div> </div>
<div id="notifications" data="download"></div> <div id="notifications" data="download"></div>
<div id="downloadControl"></div> <div id="downloadControl"></div>
@@ -41,38 +41,65 @@
</div> </div>
</div> </div>
<div class="view-icons"> <div class="view-icons">
{% if channel_agg_list|length > 1 %}
<span>Filter:</span>
<select name="channel_filter" id="channel_filter" onchange="channelFilterDownload(this.value)">
<option value="all" {% if not channel_filter_id %}selected{% endif %}>all</option>
{% for channel in channel_agg_list %}
<option {% if channel_filter_id == channel.id %}selected{% endif %} value="{{ channel.id }}">{{ channel.name }} ({{channel.count}})</option>
{% endfor %}
</select>
{% endif %}
{% if view_style == "grid" %}
<div class="grid-count">
{% if grid_items < 7 %}
<img src="{% static 'img/icon-add.svg' %}" onclick="changeGridItems(this)" data-value="{{ grid_items|add:"1"}}" alt="grid plus row">
{% endif %}
{% if grid_items > 3 %}
<img src="{% static 'img/icon-substract.svg' %}" onclick="changeGridItems(this)" data-value="{{ grid_items|add:"-1"}}" alt="grid minus row">
{% endif %}
</div>
{% endif %}
<img src="{% static 'img/icon-gridview.svg' %}" onclick="changeView(this)" data-origin="downloads" data-value="grid" alt="grid view"> <img src="{% static 'img/icon-gridview.svg' %}" onclick="changeView(this)" data-origin="downloads" data-value="grid" alt="grid view">
<img src="{% static 'img/icon-listview.svg' %}" onclick="changeView(this)" data-origin="downloads" data-value="list" alt="list view"> <img src="{% static 'img/icon-listview.svg' %}" onclick="changeView(this)" data-origin="downloads" data-value="list" alt="list view">
</div> </div>
</div> </div>
<h3>Total videos: {{ max_hits }}{% if max_hits == 10000 %}+{% endif %}</h3> <h3>Total videos: {{ max_hits }}{% if max_hits == 10000 %}+{% endif %} {% if channel_filter_id %} - from channel <i>{{ channel_filter_name }}</i>{% endif %}</h3>
<div class="dl-list {{ view_style }}"> </div>
<div class="boxed-content {% if view_style == "grid" %}boxed-{{ grid_items }}{% endif %}">
<div class="video-list {{ view_style }} {% if view_style == "grid" %}grid-{{ grid_items }}{% endif %}">
{% if results %} {% if results %}
{% for video in results %} {% for video in results %}
<div class="dl-item {{ view_style }}" id="dl-{{ video.source.youtube_id }}"> <div class="video-item {{ view_style }}" id="dl-{{ video.source.youtube_id }}">
<div class="dl-thumb {{ view_style }}"> <div class="video-thumb-wrap {{ view_style }}">
<img src="/cache/{{ video.source.vid_thumb_url }}" alt="video_thumb"> <div class="video-thumb">
{% if show_ignored_only %} <img src="/cache/{{ video.source.vid_thumb_url }}" alt="video_thumb">
<span>ignored</span> {% if show_ignored_only %}
{% else %} <span>ignored</span>
<span>queued</span> {% else %}
{% endif %} <span>queued</span>
{% endif %}
</div>
</div> </div>
<div class="dl-desc {{ view_style }}"> <div class="video-desc {{ view_style }}">
<h3>{{ video.source.title }}</h3> <div>
{% if video.source.channel_indexed %} {% if video.source.channel_indexed %}
<a href="{% url 'channel_id' video.source.channel_id %}">{{ video.source.channel_name }}</a> <a href="{% url 'channel_id' video.source.channel_id %}">{{ video.source.channel_name }}</a>
{% else %} {% else %}
<span>{{ video.source.channel_name }}</span> <span>{{ video.source.channel_name }}</span>
{% endif %} {% endif %}
<h3>{{ video.source.title }}</h3>
</div>
<p>Published: {{ video.source.published }} | Duration: {{ video.source.duration }} | {{ video.source.youtube_id }}</p> <p>Published: {{ video.source.published }} | Duration: {{ video.source.duration }} | {{ video.source.youtube_id }}</p>
{% if show_ignored_only %} <div>
<button data-id="{{ video.source.youtube_id }}" onclick="forgetIgnore(this)">Forget</button> {% if show_ignored_only %}
<button data-id="{{ video.source.youtube_id }}" onclick="addSingle(this)">Add to queue</button> <button data-id="{{ video.source.youtube_id }}" onclick="forgetIgnore(this)">Forget</button>
{% else %} <button data-id="{{ video.source.youtube_id }}" onclick="addSingle(this)">Add to queue</button>
<button data-id="{{ video.source.youtube_id }}" onclick="toIgnore(this)">Ignore</button> {% else %}
<button id="{{ video.source.youtube_id }}" data-id="{{ video.source.youtube_id }}" onclick="downloadNow(this)">Download now</button> <button data-id="{{ video.source.youtube_id }}" onclick="toIgnore(this)">Ignore</button>
{% endif %} <button id="{{ video.source.youtube_id }}" data-id="{{ video.source.youtube_id }}" onclick="downloadNow(this)">Download now</button>
{% endif %}
</div>
</div> </div>
</div> </div>
{% endfor %} {% endfor %}

View File

@@ -56,11 +56,11 @@
</div> </div>
</div> </div>
{% if playlist_info.playlist_description %} {% if playlist_info.playlist_description %}
<div class="info-box-item description-box"> <div class="description-box">
<p>Description: <button onclick="textReveal()" id="text-reveal-button">Show</button></p> <p id="text-expand" class="description-text">
<div id="text-reveal" class="description-text"> {{ playlist_info.playlist_description|linebreaksbr|urlizetrunc:50 }}
{{ playlist_info.playlist_description|linebreaks }} </p>
</div> <button onclick="textExpand()" id="text-expand-button">Show more</button>
</div> </div>
{% endif %} {% endif %}
</div> </div>

View File

@@ -7,6 +7,7 @@
</div> </div>
<div class="multi-search-box"> <div class="multi-search-box">
{{ search_form }} {{ search_form }}
<p>Start typing or use <span class="settings-current">video:</span>, <span class="settings-current">channel:</span>, <span class="settings-current">playlist:</span> or <span class="settings-current">full:</span> keywords for advanced queries. <a href="https://github.com/tubearchivist/tubearchivist/wiki/Search" target="_blank">Learn more</a>.</p>
</div> </div>
<div class="multi-search-result"> <div class="multi-search-result">
<h2>Video Results</h2> <h2>Video Results</h2>
@@ -26,5 +27,11 @@
<p>No playlists found.</p> <p>No playlists found.</p>
</div> </div>
</div> </div>
<div class="multi-search-result">
<h2>Fulltext Results</h2>
<div id="fulltext-results" class="video-list list">
<p>No fulltext results found.</p>
</div>
</div>
</div> </div>
{% endblock content %} {% endblock content %}

View File

@@ -34,8 +34,8 @@
<div class="settings-group"> <div class="settings-group">
<h2 id="subscriptions">Subscriptions</h2> <h2 id="subscriptions">Subscriptions</h2>
<div class="settings-item"> <div class="settings-item">
<p>Current page size: <span class="settings-current">{{ config.subscriptions.channel_size }}</span></p> <p>YouTube page size: <span class="settings-current">{{ config.subscriptions.channel_size }}</span></p>
<i>Recent videos for channels and playlist to check when running <b>Rescan subscriptions</b>, max recommended 50.</i><br> <i>Videos to scan to find new items for the <b>Rescan subscriptions</b> task, max recommended 50.</i><br>
{{ app_form.subscriptions_channel_size }} {{ app_form.subscriptions_channel_size }}
</div> </div>
</div> </div>
@@ -118,7 +118,8 @@
<h2 id="format">Cookie</h2> <h2 id="format">Cookie</h2>
<div class="settings-item"> <div class="settings-item">
<p>Import YouTube cookie: <span class="settings-current">{{ config.downloads.cookie_import }}</span><br></p> <p>Import YouTube cookie: <span class="settings-current">{{ config.downloads.cookie_import }}</span><br></p>
<i>Place your cookie file named <span class="settings-current">cookies.google.txt</span> in <span class="settings-current">cache/import</span> before enabling. Instructions in the <a href="https://github.com/tubearchivist/tubearchivist/wiki/Settings" target="_blank">Wiki.</a></i><br> <p>For automatic cookie import use <b>Tube Archivist Companion</b> <a href="https://github.com/tubearchivist/browser-extension" target="_blank">browser extension</a>.</p>
<i>For manual cookie import, place your cookie file named <span class="settings-current">cookies.google.txt</span> in <span class="settings-current">cache/import</span> before enabling. Instructions in the <a href="https://github.com/tubearchivist/tubearchivist/wiki/Settings" target="_blank">Wiki.</a></i><br>
{{ app_form.downloads_cookie_import }}<br> {{ app_form.downloads_cookie_import }}<br>
{% if config.downloads.cookie_import %} {% if config.downloads.cookie_import %}
<div id="cookieMessage"> <div id="cookieMessage">

View File

@@ -77,11 +77,11 @@
</div> </div>
</div> </div>
{% if video.description %} {% if video.description %}
<div class="info-box-item description-box"> <div class="description-box">
<p>Description: <button onclick="textReveal()" id="text-reveal-button">Show</button></p> <p id="text-expand" class="description-text">
<div id="text-reveal" class="description-text"> {{ video.description|linebreaksbr|urlizetrunc:50 }}
{{ video.description|linebreaks }} </p>
</div> <button onclick="textExpand()" id="text-expand-button">Show more</button>
</div> </div>
{% endif %} {% endif %}
{% if playlist_nav %} {% if playlist_nav %}
@@ -125,7 +125,11 @@
<script> <script>
var videoData = getVideoData('{{ video.youtube_id }}'); var videoData = getVideoData('{{ video.youtube_id }}');
sponsorBlock = videoData.data.sponsorblock; sponsorBlock = videoData.data.sponsorblock;
var videoProgress = getVideoProgress('{{ video.youtube_id }}').position; {% if position %}
var videoProgress = {{ position }}
{% else %}
var videoProgress = getVideoProgress('{{ video.youtube_id }}').position;
{% endif %}
window.onload = insertVideoTag(videoData, videoProgress); window.onload = insertVideoTag(videoData, videoProgress);
</script> </script>
{% endblock content %} {% endblock content %}

View File

@@ -6,6 +6,8 @@ from django.contrib.auth.views import LogoutView
from django.urls import path from django.urls import path
from home.views import ( from home.views import (
AboutView, AboutView,
ChannelIdAboutView,
ChannelIdPlaylistView,
ChannelIdView, ChannelIdView,
ChannelView, ChannelView,
DownloadView, DownloadView,
@@ -42,6 +44,16 @@ urlpatterns = [
login_required(ChannelIdView.as_view()), login_required(ChannelIdView.as_view()),
name="channel_id", name="channel_id",
), ),
path(
"channel/<slug:channel_id>/about/",
login_required(ChannelIdAboutView.as_view()),
name="channel_id_about",
),
path(
"channel/<slug:channel_id>/playlist/",
login_required(ChannelIdPlaylistView.as_view()),
name="channel_id_playlist",
),
path( path(
"video/<slug:video_id>/", "video/<slug:video_id>/",
login_required(VideoView.as_view()), login_required(VideoView.as_view()),

View File

@@ -8,6 +8,7 @@ import json
import urllib.parse import urllib.parse
from time import sleep from time import sleep
from api.src.search_processor import SearchProcess
from django.conf import settings from django.conf import settings
from django.contrib.auth import login from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import AuthenticationForm
@@ -15,6 +16,7 @@ from django.http import JsonResponse
from django.shortcuts import redirect, render from django.shortcuts import redirect, render
from django.views import View from django.views import View
from home.src.download.yt_dlp_base import CookieHandler from home.src.download.yt_dlp_base import CookieHandler
from home.src.es.connect import ElasticWrap
from home.src.es.index_setup import get_available_backups from home.src.es.index_setup import get_available_backups
from home.src.frontend.api_calls import PostData from home.src.frontend.api_calls import PostData
from home.src.frontend.forms import ( from home.src.frontend.forms import (
@@ -29,11 +31,11 @@ from home.src.frontend.forms import (
UserSettingsForm, UserSettingsForm,
) )
from home.src.frontend.searching import SearchHandler from home.src.frontend.searching import SearchHandler
from home.src.index.channel import channel_overwrites from home.src.index.channel import YoutubeChannel, channel_overwrites
from home.src.index.generic import Pagination from home.src.index.generic import Pagination
from home.src.index.playlist import YoutubePlaylist from home.src.index.playlist import YoutubePlaylist
from home.src.ta.config import AppConfig, ScheduleBuilder from home.src.ta.config import AppConfig, ScheduleBuilder
from home.src.ta.helper import UrlListParser from home.src.ta.helper import UrlListParser, time_parser
from home.src.ta.ta_redis import RedisArchivist from home.src.ta.ta_redis import RedisArchivist
from home.tasks import extrac_dl, index_channel_playlists, subscribe_to from home.tasks import extrac_dl, index_channel_playlists, subscribe_to
from rest_framework.authtoken.models import Token from rest_framework.authtoken.models import Token
@@ -235,14 +237,10 @@ class ArchivistResultsView(ArchivistViewConfig):
def initiate_vars(self, request): def initiate_vars(self, request):
"""search in es for vidoe hits""" """search in es for vidoe hits"""
page_get = int(request.GET.get("page", 0))
self.user_id = request.user.id self.user_id = request.user.id
self.config_builder(self.user_id) self.config_builder(self.user_id)
self.search_get = request.GET.get("search", False) self.search_get = request.GET.get("search", False)
search_encoded = self._url_encode(self.search_get) self.pagination_handler = Pagination(request)
self.pagination_handler = Pagination(
page_get=page_get, user_id=self.user_id, search_get=search_encoded
)
self.sort_by = self._sort_by_overwrite() self.sort_by = self._sort_by_overwrite()
self._initial_data() self._initial_data()
@@ -360,29 +358,80 @@ class DownloadView(ArchivistResultsView):
def get(self, request): def get(self, request):
"""handle get request""" """handle get request"""
self.initiate_vars(request) self.initiate_vars(request)
self._update_view_data() self._update_view_data(request)
self.find_results() self.find_results()
self.context.update( self.context.update(
{ {
"title": "Downloads", "title": "Downloads",
"add_form": AddToQueueForm(), "add_form": AddToQueueForm(),
"channel_agg_list": self._get_channel_agg(),
} }
) )
return render(request, "home/downloads.html", self.context) return render(request, "home/downloads.html", self.context)
def _update_view_data(self): def _update_view_data(self, request):
"""update downloads view specific data dict""" """update downloads view specific data dict"""
if self.context["show_ignored_only"]: if self.context["show_ignored_only"]:
filter_view = "ignore" filter_view = "ignore"
else: else:
filter_view = "pending" filter_view = "pending"
must_list = [{"term": {"status": {"value": filter_view}}}]
channel_filter = request.GET.get("channel", False)
if channel_filter:
must_list.append(
{"term": {"channel_id": {"value": channel_filter}}}
)
channel = YoutubeChannel(channel_filter)
channel.get_from_es()
self.context.update(
{
"channel_filter_id": channel_filter,
"channel_filter_name": channel.json_data["channel_name"],
}
)
self.data.update( self.data.update(
{ {
"query": {"term": {"status": {"value": filter_view}}}, "query": {"bool": {"must": must_list}},
"sort": [{"timestamp": {"order": "asc"}}], "sort": [{"timestamp": {"order": "asc"}}],
} }
) )
def _get_channel_agg(self):
"""get pending channel with count"""
data = {
"size": 0,
"query": {"term": {"status": {"value": "pending"}}},
"aggs": {
"channel_downloads": {
"multi_terms": {
"size": 30,
"terms": [
{"field": "channel_name.keyword"},
{"field": "channel_id"},
],
"order": {"_count": "desc"},
}
}
},
}
response, _ = ElasticWrap(self.es_search).get(data=data)
buckets = response["aggregations"]["channel_downloads"]["buckets"]
buckets_sorted = []
for i in buckets:
bucket = {
"name": i["key"][0],
"id": i["key"][1],
"count": i["doc_count"],
}
buckets_sorted.append(bucket)
return buckets_sorted
@staticmethod @staticmethod
def post(request): def post(request):
"""handle post requests""" """handle post requests"""
@@ -394,14 +443,15 @@ class DownloadView(ArchivistResultsView):
youtube_ids = UrlListParser(url_str).process_list() youtube_ids = UrlListParser(url_str).process_list()
except ValueError: except ValueError:
# failed to process # failed to process
key = "message:add"
print(f"failed to parse: {url_str}") print(f"failed to parse: {url_str}")
mess_dict = { mess_dict = {
"status": "message:add", "status": key,
"level": "error", "level": "error",
"title": "Failed to extract links.", "title": "Failed to extract links.",
"message": "Not a video, channel or playlist ID or URL", "message": "Not a video, channel or playlist ID or URL",
} }
RedisArchivist().set_message("message:add", mess_dict) RedisArchivist().set_message(key, mess_dict, expire=True)
return redirect("downloads") return redirect("downloads")
print(youtube_ids) print(youtube_ids)
@@ -411,7 +461,37 @@ class DownloadView(ArchivistResultsView):
return redirect("downloads", permanent=True) return redirect("downloads", permanent=True)
class ChannelIdView(ArchivistResultsView): class ChannelIdBaseView(ArchivistResultsView):
"""base class for all channel-id views"""
def get_channel_meta(self, channel_id):
"""get metadata for channel"""
path = f"ta_channel/_doc/{channel_id}"
response, _ = ElasticWrap(path).get()
channel_info = SearchProcess(response).process()
return channel_info
def channel_has_pending(self, channel_id):
"""check if channel has pending videos in queue"""
path = "ta_download/_search"
data = {
"size": 1,
"query": {
"bool": {
"must": [
{"term": {"status": {"value": "pending"}}},
{"term": {"channel_id": {"value": channel_id}}},
]
}
},
}
response, _ = ElasticWrap(path).get(data=data)
self.context.update({"has_pending": bool(response["hits"]["hits"])})
class ChannelIdView(ChannelIdBaseView):
"""resolves to /channel/<channel-id>/ """resolves to /channel/<channel-id>/
display single channel page from channel_id display single channel page from channel_id
""" """
@@ -425,6 +505,7 @@ class ChannelIdView(ArchivistResultsView):
self._update_view_data(channel_id) self._update_view_data(channel_id)
self.find_results() self.find_results()
self.match_progress() self.match_progress()
self.channel_has_pending(channel_id)
if self.context["results"]: if self.context["results"]:
channel_info = self.context["results"][0]["source"]["channel"] channel_info = self.context["results"][0]["source"]["channel"]
@@ -439,7 +520,6 @@ class ChannelIdView(ArchivistResultsView):
{ {
"title": "Channel: " + channel_name, "title": "Channel: " + channel_name,
"channel_info": channel_info, "channel_info": channel_info,
"channel_overwrite_form": ChannelOverwriteForm,
} }
) )
@@ -476,6 +556,87 @@ class ChannelIdView(ArchivistResultsView):
return redirect("channel_id", channel_id, permanent=True) return redirect("channel_id", channel_id, permanent=True)
class ChannelIdAboutView(ChannelIdBaseView):
"""resolves to /channel/<channel-id>/about/
show metadata, handle per channel conf
"""
view_origin = "channel"
def get(self, request, channel_id):
"""handle get request"""
self.initiate_vars(request)
self.channel_has_pending(channel_id)
path = f"ta_channel/_doc/{channel_id}"
response, _ = ElasticWrap(path).get()
channel_info = SearchProcess(response).process()
channel_name = channel_info["channel_name"]
self.context.update(
{
"title": "Channel: About " + channel_name,
"channel_info": channel_info,
"channel_overwrite_form": ChannelOverwriteForm,
}
)
return render(request, "home/channel_id_about.html", self.context)
@staticmethod
def post(request, channel_id):
"""handle post request"""
print(f"handle post from {channel_id}")
channel_overwrite_form = ChannelOverwriteForm(request.POST)
if channel_overwrite_form.is_valid():
overwrites = channel_overwrite_form.cleaned_data
print(f"{channel_id}: set overwrites {overwrites}")
channel_overwrites(channel_id, overwrites=overwrites)
if overwrites.get("index_playlists") == "1":
index_channel_playlists.delay(channel_id)
sleep(1)
return redirect("channel_id_about", channel_id, permanent=True)
class ChannelIdPlaylistView(ChannelIdBaseView):
"""resolves to /channel/<channel-id>/playlist/
show all playlists of channel
"""
view_origin = "playlist"
es_search = "ta_playlist/_search"
def get(self, request, channel_id):
"""handle get request"""
self.initiate_vars(request)
self._update_view_data(channel_id)
self.find_results()
self.channel_has_pending(channel_id)
channel_info = self.get_channel_meta(channel_id)
channel_name = channel_info["channel_name"]
self.context.update(
{
"title": "Channel: Playlists " + channel_name,
"channel_info": channel_info,
}
)
return render(request, "home/channel_id_playlist.html", self.context)
def _update_view_data(self, channel_id):
"""update view specific data dict"""
self.data["sort"] = [{"playlist_name.keyword": {"order": "asc"}}]
must_list = [{"match": {"playlist_channel_id": channel_id}}]
if self.context["show_subed_only"]:
must_list.append({"match": {"playlist_subscribed": True}})
self.data["query"] = {"bool": {"must": must_list}}
class ChannelView(ArchivistResultsView): class ChannelView(ArchivistResultsView):
"""resolves to /channel/ """resolves to /channel/
handle functionality for channel overview page, subscribe to channel, handle functionality for channel overview page, subscribe to channel,
@@ -512,13 +673,14 @@ class ChannelView(ArchivistResultsView):
"""handle http post requests""" """handle http post requests"""
subscribe_form = SubscribeToChannelForm(data=request.POST) subscribe_form = SubscribeToChannelForm(data=request.POST)
if subscribe_form.is_valid(): if subscribe_form.is_valid():
key = "message:subchannel"
message = { message = {
"status": "message:subchannel", "status": key,
"level": "info", "level": "info",
"title": "Subscribing to Channels", "title": "Subscribing to Channels",
"message": "Parsing form data", "message": "Parsing form data",
} }
RedisArchivist().set_message("message:subchannel", message=message) RedisArchivist().set_message(key, message=message, expire=True)
url_str = request.POST.get("subscribe") url_str = request.POST.get("subscribe")
print(url_str) print(url_str)
subscribe_to.delay(url_str) subscribe_to.delay(url_str)
@@ -659,15 +821,14 @@ class PlaylistView(ArchivistResultsView):
if subscribe_form.is_valid(): if subscribe_form.is_valid():
url_str = request.POST.get("subscribe") url_str = request.POST.get("subscribe")
print(url_str) print(url_str)
key = "message:subplaylist"
message = { message = {
"status": "message:subplaylist", "status": key,
"level": "info", "level": "info",
"title": "Subscribing to Playlists", "title": "Subscribing to Playlists",
"message": "Parsing form data", "message": "Parsing form data",
} }
RedisArchivist().set_message( RedisArchivist().set_message(key, message=message, expire=True)
"message:subplaylist", message=message
)
subscribe_to.delay(url_str) subscribe_to.delay(url_str)
sleep(1) sleep(1)
@@ -682,6 +843,7 @@ class VideoView(View):
def get(self, request, video_id): def get(self, request, video_id):
"""get single video""" """get single video"""
config_handler = AppConfig(request.user.id) config_handler = AppConfig(request.user.id)
position = time_parser(request.GET.get("t"))
path = f"ta_video/_doc/{video_id}" path = f"ta_video/_doc/{video_id}"
look_up = SearchHandler(path, config=False) look_up = SearchHandler(path, config=False)
video_hit = look_up.get_data() video_hit = look_up.get_data()
@@ -707,6 +869,7 @@ class VideoView(View):
"cast": config_handler.config["application"]["enable_cast"], "cast": config_handler.config["application"]["enable_cast"],
"version": settings.TA_VERSION, "version": settings.TA_VERSION,
"config": config_handler.config, "config": config_handler.config,
"position": position,
} }
return render(request, "home/video.html", context) return render(request, "home/video.html", context)
@@ -829,18 +992,45 @@ class SettingsView(View):
sleep(1) sleep(1)
return redirect("settings", permanent=True) return redirect("settings", permanent=True)
@staticmethod def post_process_updated(self, updated, config):
def post_process_updated(updated, config):
"""apply changes for config""" """apply changes for config"""
if not updated: if not updated:
return return
for config_value, updated_value in updated: for config_value, updated_value in updated:
if config_value == "cookie_import": if config_value == "cookie_import":
if updated_value: self.process_cookie(config, updated_value)
CookieHandler(config).import_cookie()
else: def process_cookie(self, config, updated_value):
CookieHandler(config).revoke() """import and validate cookie"""
handler = CookieHandler(config)
if updated_value:
try:
handler.import_cookie()
except FileNotFoundError:
print("cookie: import failed, file not found")
handler.revoke()
self._fail_message("Cookie file not found.")
return
valid = handler.validate()
if not valid:
handler.revoke()
self._fail_message("Failed to validate cookie file.")
else:
handler.revoke()
@staticmethod
def _fail_message(message_line):
"""notify our failure"""
key = "message:setting"
message = {
"status": key,
"level": "error",
"title": "Cookie import failed",
"message": message_line,
}
RedisArchivist().set_message(key, message=message, expire=True)
def progress(request): def progress(request):

View File

@@ -1,12 +1,13 @@
beautifulsoup4==4.11.1 beautifulsoup4==4.11.1
celery==5.2.7 celery==5.2.7
Django==4.0.4 Django==4.1.2
django-cors-headers==3.12.0 django-auth-ldap==4.1.0
djangorestframework==3.13.1 django-cors-headers==3.13.0
Pillow==9.1.1 djangorestframework==3.14.0
redis==4.3.1 Pillow==9.2.0
requests==2.27.1 redis==4.3.4
ryd-client==0.0.3 requests==2.28.1
ryd-client==0.0.6
uWSGI==2.0.20 uWSGI==2.0.20
whitenoise==6.1.0 whitenoise==6.2.0
yt_dlp==2022.5.18 yt_dlp==2022.10.4

View File

@@ -1,6 +1,6 @@
function initializeCastApi() { function initializeCastApi() {
cast.framework.CastContext.getInstance().setOptions({ cast.framework.CastContext.getInstance().setOptions({
receiverApplicationId: chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, // Use built in reciver app on cast device, see https://developers.google.com/cast/docs/styled_receiver if you want to be able to add a theme, splash screen or watermark. Has a $5 one time fee. receiverApplicationId: chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, // Use built in receiver app on cast device, see https://developers.google.com/cast/docs/styled_receiver if you want to be able to add a theme, splash screen or watermark. Has a $5 one time fee.
autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED
}); });

View File

@@ -344,6 +344,7 @@ button:hover {
.grid-count { .grid-count {
display: flex; display: flex;
justify-content: end; justify-content: end;
align-items: center;
} }
.view-icons img { .view-icons img {
@@ -365,10 +366,17 @@ button:hover {
} }
#text-reveal { #text-reveal {
height: 0px; height: 0;
overflow: hidden; overflow: hidden;
} }
#text-expand {
overflow: hidden;
display: -webkit-inline-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 4;
}
/* video player */ /* video player */
.player-wrapper { .player-wrapper {
@@ -408,6 +416,12 @@ button:hover {
margin: 10px 10px 10px 0; margin: 10px 10px 10px 0;
} }
/* fix for safari full screen not scaling full */
video:-webkit-full-screen {
max-height: unset !important;
max-width: unset !important;
}
/* video list */ /* video list */
.video-list { .video-list {
display: grid; display: grid;
@@ -443,9 +457,15 @@ button:hover {
overflow: hidden; overflow: hidden;
} }
.video-item:hover .video-thumb span {
opacity: 1;
}
.video-item.list { .video-item.list {
display: grid; display: grid;
grid-template-columns: 25% auto; grid-template-columns: 26% auto;
background-color: var(--highlight-bg);
align-items: center;
} }
.video-progress-bar { .video-progress-bar {
@@ -461,6 +481,16 @@ button:hover {
position: relative; position: relative;
} }
.video-thumb span {
position: absolute;
top: 5px;
left: 5px;
background-color: var(--accent-font-light);
padding: 5px;
opacity: 0;
transition: 300ms ease-in-out;
}
.video-play img { .video-play img {
width: 40px; width: 40px;
filter: var(--img-filter); filter: var(--img-filter);
@@ -495,10 +525,9 @@ button:hover {
.video-desc.list { .video-desc.list {
padding: 10px; padding: 10px;
height: unset; height: 100%;
background-color: var(--highlight-bg);
display: flex; display: flex;
flex-wrap: wrap-reverse; flex-wrap: wrap;
align-content: center; align-content: center;
} }
@@ -591,6 +620,8 @@ button:hover {
.description-box { .description-box {
margin-top: 1rem; margin-top: 1rem;
padding: 15px;
background-color: var(--highlight-bg);
} }
.info-box-3 { .info-box-3 {
@@ -772,6 +803,10 @@ button:hover {
} }
/* multi search page */ /* multi search page */
.multi-search-box {
padding-right: 20px;
}
.multi-search-box input { .multi-search-box input {
width: 100%; width: 100%;
} }
@@ -817,6 +852,18 @@ button:hover {
transform: translateX(-30%); transform: translateX(-30%);
} }
.info-box-item.channel-nav {
justify-content: center;
}
.info-box-item.channel-nav a {
padding: 0 1rem;
}
.info-box-item.channel-nav a:hover {
text-decoration: underline;
}
/* playlist overview page */ /* playlist overview page */
.playlist-list.list { .playlist-list.list {
display: grid; display: grid;
@@ -875,73 +922,6 @@ button:hover {
cursor: pointer; cursor: pointer;
} }
.dl-list.list {
display: block;
}
.dl-list.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 1rem;
}
.dl-item.list {
display: flex;
margin: 15px 0;
align-items: center;
background-color: var(--highlight-bg);
}
.dl-item.grid {
display: flex;
flex-wrap: wrap;
background-color: var(--highlight-bg);
}
.dl-check {
width: 30px;
}
.dl-item:hover > .dl-thumb span {
opacity: 1;
}
.dl-thumb {
position: relative;
}
.dl-thumb span {
position: absolute;
top: 5px;
left: 5px;
background-color: var(--accent-font-light);
padding: 5px;
opacity: 0;
transition: 300ms ease-in-out;
}
.dl-thumb.list {
width: 25%;
}
.dl-thumb.grid {
width: 100%;
}
.dl-item img {
width: 100%;
}
.dl-desc.list {
padding: 0 15px;
width: 75%;
}
.dl-desc.grid {
padding: 15px;
width: 100%;
}
.dl-control-icons { .dl-control-icons {
display: flex; display: flex;
justify-content: center; justify-content: center;
@@ -1086,8 +1066,12 @@ button:hover {
} }
/* tablet */ /* tablet */
@media screen and (max-width: 1000px) { @media screen and (max-width: 1000px), screen and (max-height: 850px) {
.boxed-content { .boxed-content,
.boxed-content.boxed-4,
.boxed-content.boxed-5,
.boxed-content.boxed-6,
.boxed-content.boxed-7 {
width: 90%; width: 90%;
} }
.video-list.grid.grid-3, .video-list.grid.grid-3,
@@ -1095,14 +1079,10 @@ button:hover {
.video-list.grid.grid-5, .video-list.grid.grid-5,
.video-list.grid.grid-6, .video-list.grid.grid-6,
.video-list.grid.grid-7, .video-list.grid.grid-7,
.dl-list.grid,
.channel-list.grid, .channel-list.grid,
.playlist-list.grid { .playlist-list.grid {
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
} }
.dl-thumb.list {
width: 35%;
}
.video-item.list, .video-item.list,
.playlist-item.list { .playlist-item.list {
display: grid; display: grid;
@@ -1146,7 +1126,6 @@ button:hover {
.video-list.grid.grid-5, .video-list.grid.grid-5,
.video-list.grid.grid-6, .video-list.grid.grid-6,
.video-list.grid.grid-7, .video-list.grid.grid-7,
.dl-list.grid,
.channel-list.grid, .channel-list.grid,
.video-item.list, .video-item.list,
.playlist-list.list, .playlist-list.list,
@@ -1195,15 +1174,6 @@ button:hover {
.description-box { .description-box {
display: block; display: block;
} }
.dl-item {
display: block;
}
.dl-thumb {
width: 100%;
}
.dl-desc {
padding: 15px;
}
.backup-grid-row { .backup-grid-row {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;

View File

@@ -140,7 +140,7 @@ function toggleCheckbox(checkbox) {
var payload = JSON.stringify(payloadDict); var payload = JSON.stringify(payloadDict);
sendPost(payload); sendPost(payload);
setTimeout(function(){ setTimeout(function(){
var currPage = window.location.pathname; var currPage = window.location.pathname + window.location.search;
window.location.replace(currPage); window.location.replace(currPage);
return false; return false;
}, 500); }, 500);
@@ -336,10 +336,18 @@ function cancelDelete() {
document.getElementById("delete-item").style.display = 'block'; document.getElementById("delete-item").style.display = 'block';
} }
// get seconds from hh:mm:ss.ms timestamp
function getSeconds(timestamp) {
var elements = timestamp.split(":", 3);
var secs = parseInt(elements[0]) * 60 * 60 + parseInt(elements[1]) * 60 + parseFloat(elements[2])
return secs
}
// player // player
var sponsorBlock = []; var sponsorBlock = [];
function createPlayer(button) { function createPlayer(button) {
var videoId = button.getAttribute('data-id'); var videoId = button.getAttribute('data-id');
var videoPosition = button.getAttribute('data-position');
var videoData = getVideoData(videoId); var videoData = getVideoData(videoId);
var sponsorBlockElements = ''; var sponsorBlockElements = '';
@@ -363,8 +371,11 @@ function createPlayer(button) {
} else { } else {
sponsorBlock = null; sponsorBlock = null;
} }
if (videoPosition) {
var videoProgress = getVideoProgress(videoId).position; var videoProgress = getSeconds(videoPosition)
} else {
var videoProgress = getVideoProgress(videoId).position;
}
var videoName = videoData.data.title; var videoName = videoData.data.title;
var videoTag = createVideoTag(videoData, videoProgress); var videoTag = createVideoTag(videoData, videoProgress);
@@ -761,7 +772,9 @@ function removePlayer() {
playerElement.innerHTML = ''; playerElement.innerHTML = '';
// append played status // append played status
var videoInfo = document.getElementById('video-info-' + youtubeId); var videoInfo = document.getElementById('video-info-' + youtubeId);
videoInfo.insertBefore(playedStatus, videoInfo.firstChild); if (videoInfo) {
videoInfo.insertBefore(playedStatus, videoInfo.firstChild);
}
} }
} }
@@ -790,18 +803,17 @@ function searchMulti(query) {
clearTimeout(searchTimeout); clearTimeout(searchTimeout);
searchTimeout = setTimeout(function () { searchTimeout = setTimeout(function () {
if (query.length > 1) { if (query.length > 1) {
var payload = JSON.stringify({'multi_search': query});
var http = new XMLHttpRequest(); var http = new XMLHttpRequest();
http.onreadystatechange = function() { http.onreadystatechange = function() {
if (http.readyState === 4) { if (http.readyState === 4) {
allResults = JSON.parse(http.response).results; response = JSON.parse(http.response);
populateMultiSearchResults(allResults); populateMultiSearchResults(response.results, response.queryType);
} }
}; };
http.open("POST", "/process/", true); http.open("GET", `/api/search/?query=${query}`, true);
http.setRequestHeader("X-CSRFToken", getCookie("csrftoken")); http.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
http.setRequestHeader("Content-type", "application/json"); http.setRequestHeader("Content-type", "application/json");
http.send(payload); http.send();
} }
}, 500); }, 500);
} }
@@ -811,36 +823,83 @@ function getViewDefaults(view) {
return defaultView; return defaultView;
} }
function populateMultiSearchResults(allResults) { function populateMultiSearchResults(allResults, queryType) {
// videos // videos
var defaultVideo = getViewDefaults("home"); var defaultVideo = getViewDefaults("home");
var allVideos = allResults.video_results; var allVideos = allResults.video_results;
var videoBox = document.getElementById("video-results"); var videoBox = document.getElementById("video-results");
videoBox.innerHTML = ""; videoBox.innerHTML = "";
for (let index = 0; index < allVideos.length; index++) { videoBox.parentElement.style.display = "block";
const video = allVideos[index].source; if (allVideos.length > 0) {
const videoDiv = createVideo(video, defaultVideo); for (let index = 0; index < allVideos.length; index++) {
videoBox.appendChild(videoDiv); const video = allVideos[index].source;
const videoDiv = createVideo(video, defaultVideo);
videoBox.appendChild(videoDiv);
}
} else {
if (queryType === "simple" || queryType == "video") {
videoBox.innerHTML = "<p>No videos found.</p>";
} else {
videoBox.parentElement.style.display = "none";
}
} }
// channels // channels
var defaultChannel = getViewDefaults("channel"); var defaultChannel = getViewDefaults("channel");
var allChannels = allResults.channel_results; var allChannels = allResults.channel_results;
var channelBox = document.getElementById("channel-results"); var channelBox = document.getElementById("channel-results");
channelBox.innerHTML = ""; channelBox.innerHTML = "";
for (let index = 0; index < allChannels.length; index++) { channelBox.parentElement.style.display = "block";
const channel = allChannels[index].source; if (allChannels.length > 0) {
const channelDiv = createChannel(channel, defaultChannel); for (let index = 0; index < allChannels.length; index++) {
channelBox.appendChild(channelDiv); const channel = allChannels[index].source;
const channelDiv = createChannel(channel, defaultChannel);
channelBox.appendChild(channelDiv);
}
} else {
if (queryType === "simple" || queryType == "channel") {
channelBox.innerHTML = "<p>No channels found.</p>";
} else {
channelBox.parentElement.style.display = "none";
}
} }
// playlists // playlists
var defaultPlaylist = getViewDefaults("playlist"); var defaultPlaylist = getViewDefaults("playlist");
var allPlaylists = allResults.playlist_results; var allPlaylists = allResults.playlist_results;
var playlistBox = document.getElementById("playlist-results"); var playlistBox = document.getElementById("playlist-results");
playlistBox.innerHTML = ""; playlistBox.innerHTML = "";
for (let index = 0; index < allPlaylists.length; index++) { playlistBox.parentElement.style.display = "block";
const playlist = allPlaylists[index].source; if (allPlaylists.length > 0) {
const playlistDiv = createPlaylist(playlist, defaultPlaylist); for (let index = 0; index < allPlaylists.length; index++) {
playlistBox.appendChild(playlistDiv); const playlist = allPlaylists[index].source;
const playlistDiv = createPlaylist(playlist, defaultPlaylist);
playlistBox.appendChild(playlistDiv);
}
} else {
if (queryType === "simple" || queryType == "playlist") {
playlistBox.innerHTML = "<p>No playlists found.</p>";
} else {
playlistBox.parentElement.style.display = "none";
}
}
// fulltext
var allFullText = allResults.fulltext_results;
var fullTextBox = document.getElementById("fulltext-results");
fullTextBox.innerHTML = "";
fullTextBox.parentElement.style.display = "block";
if (allFullText.length > 0) {
for (let i = 0; i < allFullText.length; i++) {
const fullText = allFullText[i];
if ("highlight" in fullText) {
const fullTextDiv = createFulltext(fullText);
fullTextBox.appendChild(fullTextDiv);
}
}
} else {
if (queryType === "simple" || queryType == "full") {
fullTextBox.innerHTML = "<p>No fulltext items found.</p>";
} else {
fullTextBox.parentElement.style.display = "none";
}
} }
} }
@@ -862,7 +921,7 @@ function createVideo(video, viewStyle) {
const channelName = video.channel.channel_name; const channelName = video.channel.channel_name;
// build markup // build markup
const markup = ` const markup = `
<a href="#player" data-src="/media/${mediaUrl}" data-thumb="${thumbUrl}" data-title="${videoTitle}" data-channel="${channelName}" data-channel-id="${channelId}" data-id="${videoId}" onclick="createPlayer(this)"> <a href="#player" data-id="${videoId}" onclick="createPlayer(this)">
<div class="video-thumb-wrap ${viewStyle}"> <div class="video-thumb-wrap ${viewStyle}">
<div class="video-thumb"> <div class="video-thumb">
<img src="${thumbUrl}" alt="video-thumb"> <img src="${thumbUrl}" alt="video-thumb">
@@ -965,8 +1024,43 @@ function createPlaylist(playlist, viewStyle) {
return playlistDiv; return playlistDiv;
} }
function createFulltext(fullText) {
const videoId = fullText.source.youtube_id;
const videoTitle = fullText.source.title;
const thumbUrl = fullText.source.vid_thumb_url;
const channelId = fullText.source.subtitle_channel_id;
const channelName = fullText.source.subtitle_channel;
const subtitleLine = fullText.highlight.subtitle_line[0];
const subtitle_start = fullText.source.subtitle_start.split(".")[0];
const subtitle_end = fullText.source.subtitle_end.split(".")[0];
const markup = `
<a href="#player" data-id="${videoId}" data-position="${subtitle_start}" onclick="createPlayer(this)">
<div class="video-thumb-wrap list">
<div class="video-thumb">
<img src="${thumbUrl}" alt="video-thumb">
</div>
<div class="video-play">
<img src="/static/img/icon-play.svg" alt="play-icon">
</div>
</div>
</a>
<div class="video-desc list">
<p>${subtitle_start} - ${subtitle_end}</p>
<p>${subtitleLine}</p>
<div>
<a href="/channel/${channelId}/"><h3>${channelName}</h3></a>
<a class="video-more" href="/video/${videoId}/?t=${subtitle_start}"><h2>${videoTitle}</h2></a>
</div>
</div>
`
const fullTextDiv = document.createElement("div");
fullTextDiv.setAttribute("class", "video-item list");
fullTextDiv.innerHTML = markup;
return fullTextDiv
}
// generic // generic
function sendPost(payload) { function sendPost(payload) {
var http = new XMLHttpRequest(); var http = new XMLHttpRequest();
http.open("POST", "/process/", true); http.open("POST", "/process/", true);
@@ -991,19 +1085,58 @@ function getCookie(c_name) {
// animations // animations
function textReveal() { function textReveal() {
var textBox = document.getElementById('text-reveal'); var textBox = document.getElementById("text-reveal");
var button = document.getElementById('text-reveal-button'); var button = document.getElementById("text-reveal-button");
var textBoxHeight = textBox.style.height; var textBoxHeight = textBox.style.height;
if (textBoxHeight === 'unset') { if (textBoxHeight === "unset") {
textBox.style.height = '0px'; textBox.style.height = "0px";
button.innerText = 'Show'; button.innerText = "Show";
} else { } else {
textBox.style.height = 'unset'; textBox.style.height = "unset";
button.innerText = 'Hide'; button.innerText = "Hide";
} }
} }
function textExpand() {
var textBox = document.getElementById("text-expand");
var button = document.getElementById("text-expand-button");
var style = window.getComputedStyle(textBox)
if (style.webkitLineClamp === "none") {
textBox.style["-webkit-line-clamp"] = "4";
button.innerText = "Show more";
} else {
textBox.style["-webkit-line-clamp"] = "unset";
button.innerText = "Show less";
}
}
// hide "show more" button if all text is already visible
function textExpandButtonVisibilityUpdate() {
var textBox = document.getElementById("text-expand");
var button = document.getElementById("text-expand-button");
if (!textBox || !button)
return;
var styles = window.getComputedStyle(textBox);
var textBoxLineClamp = styles.webkitLineClamp;
if (textBoxLineClamp === "unset")
return; // text box is in revealed state
if (textBox.offsetHeight < textBox.scrollHeight
|| textBox.offsetWidth < textBox.scrollWidth) {
// the element has an overflow, show read more button
button.style.display = "inline-block";
} else {
// the element doesn't have overflow
button.style.display = "none";
}
}
document.addEventListener("readystatechange", textExpandButtonVisibilityUpdate);
window.addEventListener("resize", textExpandButtonVisibilityUpdate);
function showForm() { function showForm() {
var formElement = document.getElementById('hidden-form'); var formElement = document.getElementById('hidden-form');
var displayStyle = formElement.style.display; var displayStyle = formElement.style.display;
@@ -1015,6 +1148,14 @@ function showForm() {
animate('animate-icon', 'pulse-img'); animate('animate-icon', 'pulse-img');
} }
function channelFilterDownload(value) {
if (value === "all") {
window.location = "/downloads/";
} else {
window.location.search = "?channel=" + value;
}
}
function showOverwrite() { function showOverwrite() {
var overwriteDiv = document.getElementById("overwrite-form"); var overwriteDiv = document.getElementById("overwrite-form");
if (overwriteDiv.classList.contains("hidden-overwrite")) { if (overwriteDiv.classList.contains("hidden-overwrite")) {