-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1839 lines (1711 loc) · 85.7 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import platform; print(platform.python_version())
import os
import re
import sys
import glob
import math
import time
import json
import magic
import redis
import shutil
import inspect
import difflib
import pymongo
import hashlib
import logging
import zipfile
import tempfile
import requests
import functools
import threading
import subprocess
import validators
import meilisearch
import flask_login
import urllib.request
from PIL import Image
from queue import Queue
from flask_sse import sse
from threading import Lock
from threading import Thread
from datetime import datetime
from dotenv import load_dotenv
from json import JSONDecodeError
from pymongo import MongoClient
from meilisearch import Client
from subprocess import TimeoutExpired
from urllib.parse import urlparse
from urllib.parse import quote, unquote
from bson.objectid import ObjectId
from werkzeug.urls import url_encode
from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import Flask, request, render_template, session, redirect, url_for, send_file, send_from_directory, make_response, Response, json, g, jsonify, abort, flash
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
# Print current working directory
print("Current Working Directory:", os.getcwd())
# Print files in /app directory
print("Files in /app directory:", os.listdir('/app'))
# Lots of configuration, touch nothing here
# Any docker_* variable can be modifed within the .env file
# Start of .env
load_dotenv()
meili_master_key = os.getenv('MEILI_MASTER_KEY')
secret_key = os.getenv('SECRET_KEY')
docker_ytdl = os.getenv('DOCKER_YTDL')
docker_ytdldb = os.getenv('DOCKER_YTDLDB')
docker_ytdlmeili = os.getenv('DOCKER_YTDLMEILI')
docker_ytdlredis = os.getenv('DOCKER_YTDLREDIS')
docker_port_ytdl = os.getenv('DOCKER_PORT_YTDL')
docker_port_ytdldb = os.getenv('DOCKER_PORT_YTDLDB')
docker_port_ytdlredis = os.getenv('DOCKER_PORT_YTDLREDIS')
docker_port_ytdlmeili = os.getenv('DOCKER_PORT_YTDLMEILI')
docker_max_concurrent_conversions = int(os.getenv('MAX_CONCURRENT_CONVERSIONS', '1'))
docker_max_workers = int(os.getenv('MAX_WORKERS', '1'))
docker_mainpath = os.getenv('MAINPATH')
# End of .env
conversion_queue = Queue(maxsize=docker_max_workers) # Initialize the queue
ongoing_conversions = {} # This dictionary tracks ongoing conversions to prevent duplicate tasks
conversion_lock = Lock() # Thread locking
ffmpeg_lock = Lock() # Dedicated conversion lock for ffmpeg execution
meilisearch_url = f'http://meilisearch:7700'
pagedisplaylimit = os.getenv('PAGENUMDISPLAYLIMIT')
UPLOAD_FOLDER = 'uploads' # For uploading backups back to mongodb
ALLOWED_EXTENSIONS = {'zip'} # For uploading backups back to mongodb
app = Flask(__name__, static_folder='static')
r = redis.Redis(host=f'{docker_ytdlredis}', port=6379, db=0) # adjust these parameters to your Redis configuration
app.register_blueprint(sse, url_prefix='/stream')
app.config["REDIS_URL"] = "redis://redis:6379"
app.config['PREFERRED_URL_SCHEME'] = 'https'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
os.environ['PATH'] += os.pathsep + '/app' # Set system default path to /app
logging.basicConfig(filename='app.log', filemode='w', datefmt='%Y-%m-%d %H:%M:%S', format='%(asctime)s - %(levelname)-8s %(message)s', level=logging.INFO) # Set up logging
logger = logging.getLogger(__name__)
app.logger.addHandler(logging.StreamHandler(sys.stdout))
bdir = os.path.dirname(os.path.realpath(__file__)) # Base directory where this application is located
HLS_FILES_DIR = os.path.join(bdir, 'data', 'hls/') # HLS variables and dictionaries
ongoing_conversions = {}
app.secret_key = secret_key # app secret
lock = Lock() # Create a lock
client = MongoClient(f'mongodb://{docker_ytdldb}:27017/') # Create mongoDB connection
db = client['yt-dlp']
collection = db['downloads'] # Create a new collection for downloads,
global_pool = db['global_pool'] # global_pool,
admin_settings = db['settings'] # and settings
meili_client = Client(f'http://{docker_ytdlmeili}:{docker_port_ytdlmeili}', meili_master_key) # Create meilisearch connection
meiliproxy = f'http://{docker_ytdlmeili}:7700' # meili_url for reverse proxy
admsettings = { # Set default admin config options for admin panel
'volumes': ["/app"],
'strategy': "roundrobin", # or highwatermark
'lastUsedVolumeIndex': "0",
'theme': "dark",
'sortby': "download_date",
'itemsperpage': 20,
'pagenumdisplaylimit': 15,
'maxconcurrentconversions': 0
}
def log_with_line_no(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Get the caller's frame
frame = inspect.currentframe().f_back
line_no = frame.f_lineno
# Append line number to the message
if 'extra' in kwargs:
kwargs['extra']['line_no'] = line_no
else:
kwargs['extra'] = {'line_no': line_no}
return func(*args, **kwargs)
return wrapper
# Enhance the logger functions
logging.info = log_with_line_no(logging.info)
logging.debug = log_with_line_no(logging.debug)
logging.warning = log_with_line_no(logging.warning)
logging.error = log_with_line_no(logging.error)
logging.critical = log_with_line_no(logging.critical)
def printline(*args, **kwargs):
frame = inspect.currentframe().f_back
line_number = frame.f_lineno
print(f"Line {line_number}:", *args, **kwargs)
def set_default_settings():
current_settings = admin_settings.find_one({})
if not current_settings:
admin_settings.insert_one(admsettings)
else:
# Check for each key in admsettings if it exists in current_settings
updates = {key: value for key, value in admsettings.items() if key not in current_settings}
if updates:
# If there are keys missing in current_settings, update the document
admin_settings.update_one({}, {'$set': updates})
set_default_settings()
def get_selected_volumes():
settings_document = admin_settings.find_one({}, {'volumes': 1, '_id': 0})
if settings_document:
return settings_document.get('volumes', [])
return []
selected_volumes = get_selected_volumes()
defcookiesfp = 'cookies.txt' # Set cookies file path variable, default is main directory /app
VIDEO_EXTENSIONS = ['mp4', 'mkv', 'webm', 'flv', 'mov', 'avi', 'wmv'] # video extensions global
# logging.debug()
# logging.info()
# logging.warning()
# logging.error()
# logging.critical()
# Things left to add
# High Priority
# - customizable items ordered by duration, size, download date (ID), posted date
# - configurable public item automatic deletion, cookie file, themes
# Low Priority
# - calender filter for searching between dates
# - multi-user login
# - filter function
# - normal vs reverse order
# Completed
# - create video player page (pull data with _id as URL) ✅
# - grab thumbnails for various downloads such as reddit ✅
# - append IDs to filenames so no overwriting is possible ✅
# - design new file structure ✅
# - connect mongodb ✅
# - grab thumbnails ✅
# - sanitize URLs for useless cookies for global mongoDB pool ✅
# - Stylize home page ✅
# - Progress bar ✅
# - customizable number of items displayed (kinda) ✅
# - search function ✅
os.makedirs('/app', exist_ok=True) # Create a directory for the executables if it doesn't exist
urllib.request.urlretrieve('https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/latest/download/yt-dlp', '/app/yt-dlp') # Download yt-dlp
os.chmod('/app/yt-dlp', 0o755) # Make yt-dlp executable
urllib.request.urlretrieve('https://github.com/ffbinaries/ffbinaries-prebuilt/releases/download/v6.1/ffmpeg-6.1-linux-64.zip', '/app/ffmpeg-6.1-linux-64.zip') # Download and extract ffmpeg
with zipfile.ZipFile('/app/ffmpeg-6.1-linux-64.zip', 'r') as zip_ref:
zip_ref.extractall('/app')
os.remove('/app/ffmpeg-6.1-linux-64.zip')
os.chmod('/app/ffmpeg', 0o755) # Make ffmpeg executable
urllib.request.urlretrieve('https://github.com/ffbinaries/ffbinaries-prebuilt/releases/download/v6.1/ffprobe-6.1-linux-64.zip', '/app/ffprobe-6.1-linux-64.zip') # Download and extract ffprobe
with zipfile.ZipFile('/app/ffprobe-6.1-linux-64.zip', 'r') as zip_ref:
zip_ref.extractall('/app')
os.remove('/app/ffprobe-6.1-linux-64.zip')
os.chmod('/app/ffprobe', 0o755) # Make ffprobe executable
login_manager = LoginManager() # Set up Flask-Login
login_manager.init_app(app)
def monitor_system():
while True:
# Log the current conversion queue size
logging.info(f"HLS: Current conversion queue size: {conversion_queue.qsize()}")
# add extra shit to monitor
time.sleep(60)
#############################################################
######################## MeiliSearch ########################
#############################################################
def get_meilisearch_public_key():
url = f'{meilisearch_url}/keys'
headers = {'Authorization': f'Bearer {meili_master_key}'}
response = requests.get(url, headers=headers)
if response.status_code == 200:
keys = response.json().get('results', [])
for key in keys:
if key.get('description') == 'Use it to search from the frontend':
return key.get('key')
return None
def ensure_meilisearch_index(index_name):
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {meili_master_key}'
}
get_indexes_endpoint = f'{meiliproxy}/indexes'
response = requests.get(get_indexes_endpoint, headers=headers)
if response.status_code != 200:
logging.error(f'Failed to fetch indexes: {response.content}')
return False
try:
indexes_response = response.json()
indexes = indexes_response.get('results', [])
logging.info(f'Fetched indexes: {indexes}')
index_names = [index['uid'] for index in indexes]
except Exception as e:
logging.error(f'Error parsing indexes: {e}')
return False
if index_name not in index_names:
logging.info(f'Index "{index_name}" not found. Creating it...')
create_index_endpoint = f'{meiliproxy}/indexes'
create_index_data = {
'uid': index_name,
'primaryKey': 'id'
}
create_response = requests.post(create_index_endpoint, headers=headers, data=json.dumps(create_index_data))
if create_response.status_code == 201:
logging.info(f'Index "{index_name}" created successfully.')
return True
else:
logging.error(f'Failed to create index: {create_response.content}')
return False
else:
logging.info(f'Index "{index_name}" already exists.')
return True
def clear_meilisearch_index(index_name):
try:
logging.info(f'Clearing MeiliSearch index: {index_name}')
headers = {
'Authorization': f'Bearer {meili_master_key}'
}
delete_endpoint = f'{meiliproxy}/indexes/{index_name}'
response = requests.delete(delete_endpoint, headers=headers)
if response.status_code == 204:
logging.info(f'Successfully cleared the index: {index_name}')
return True
else:
logging.error(f'Failed to clear the index: {index_name}. Response: {response.content}')
return False
except Exception as e:
logging.error(f'An error occurred while clearing the MeiliSearch index: {e}')
return False
def reset_processed_status_in_mongodb():
try:
logging.info('Resetting processed status for all MongoDB entries...')
result = collection.update_many({}, {'$set': {'processed': False}})
logging.info(f'Successfully reset processed status for {result.modified_count} items.')
return True
except Exception as e:
logging.error(f'An error occurred while resetting processed status: {e}')
return False
def reindex_meilisearch_data():
try:
logging.info('Reindexing MeiliSearch data...')
# Fetch all items for reindexing
unprocessed_items = collection.find({})
documents = []
for video_info in unprocessed_items:
doc = {
'id': video_info['index'],
'primaryKey': video_info['id'],
'title': video_info.get('title', ''),
'date_posted': video_info.get('date_posted', ''),
'archive_date': video_info.get('archive_date', '').isoformat() if isinstance(video_info.get('archive_date'), datetime) else video_info.get('archive_date', ''),
'user': video_info.get('user', ''),
'video_url': video_info.get('video_url', ''),
'tmbfp': video_info.get('tmbfp', '')
}
documents.append(doc)
mheaders = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {meili_master_key}'
}
add_documents_endpoint = f'{meiliproxy}/indexes/{index_name}/documents'
mresponse = requests.post(add_documents_endpoint, headers=mheaders, data=json.dumps(documents))
if mresponse.status_code == 202:
logging.info('Documents reindexed successfully.')
# Update MongoDB to set 'processed' to True
for video_info in unprocessed_items:
collection.update_one({'id': video_info['id']}, {'$set': {'processed': True}})
processed_count += 1
percentage_completed = (processed_count / total_items) * 100
logging.info(f"MeiliSearch Progress: {percentage_completed:.2f}% of {processed_count}/{total_items}")
else:
logging.error(f'Failed to reindex documents: {mresponse.content}')
logging.error(f'If MDB_CORRUPTED: If you are trying to use an NFS mount as meili data storage, it will not work')
except Exception as e:
logging.error(f'An error occurred during reindexing: {e}')
logging.error(f'If MDB_CORRUPTED: If you are trying to use an NFS mount as meili data storage, it will not work')
def handle_mdb_corrupted_error():
logging.error('Handling MDB_CORRUPTED error. Attempting to clear and reindex MeiliSearch.')
index_name = 'yt-dlp_index'
# Step 1: Clear the MeiliSearch index
if clear_meilisearch_index(index_name):
# Step 2: Reset 'processed' status in MongoDB
if reset_processed_status_in_mongodb():
# Step 3: Reindex the data
reindex_meilisearch_data()
else:
logging.error('Failed to reset processed status in MongoDB. Aborting reindexing.')
else:
logging.error('Failed to clear the MeiliSearch index. Aborting reindexing.')
def process_and_add_to_meilisearch():
logging.info('MeiliSearch: Fetching unprocessed items from MongoDB')
total_items = collection.count_documents({
"processed": {"$ne": True}
})
logging.info(f'MeiliSearch: total_items = {total_items}')
processed_count = 0
if total_items == 0:
logging.info("No unprocessed items found in the database.")
return
index_name = 'yt-dlp_index'
if not ensure_meilisearch_index(index_name):
logging.error(f'Failed to ensure the index "{index_name}" exists.')
return
unprocessed_items = collection.find({"processed": {"$ne": True}})
for video_info in unprocessed_items:
try:
logging.info(f"Current video_info data: {video_info}")
video_index = video_info.get('index')
video_id = video_info.get('id')
if video_index is not None:
logging.info(f"process_and_add_to_meilisearch: Video Index: {video_index}")
else:
logging.info("process_and_add_to_meilisearch: Video Index is missing or null")
if video_id is not None:
logging.info(f"process_and_add_to_meilisearch: Video Id: {video_id}")
else:
logging.info("process_and_add_to_meilisearch: Video Id is missing or null")
meili_title = video_info.get('title', '')
meili_dateposted = video_info.get('date_posted', '')
meili_archivedate = video_info.get('archive_date', '')
if isinstance(meili_archivedate, datetime):
meili_archivedate = meili_archivedate.isoformat()
meili_user = video_info.get('user', '')
meili_url = video_info.get('video_url', '')
meili_tmbfp = video_info.get('tmbfp', '')
doc = { # Preparing the document for MeiliSearch
'id': video_info['index'],
'primaryKey': video_info['id'],
'title': meili_title,
'date_posted': meili_dateposted,
'archive_date': meili_archivedate,
'user': meili_user,
'video_url': meili_url,
'tmbfp': meili_tmbfp
}
logging.info(f'Document to add to MeiliSearch: {doc}')
mheaders = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {meili_master_key}'
}
add_documents_endpoint = f'{meiliproxy}/indexes/{index_name}/documents'
mresponse = requests.post(add_documents_endpoint, headers=mheaders, data=json.dumps([doc]))
if mresponse.status_code == 202:
logging.info(f'Documents added successfully: {mresponse.json()}')
# Mark the document as processed in MongoDB
collection.update_one({'id': video_info['id']}, {'$set': {'processed': True}})
processed_count += 1
percentage_completed = (processed_count / total_items) * 100
logging.info(f"MeiliSearch Progress: {percentage_completed:.2f}% of {processed_count}/{total_items}")
else:
logging.error(f'Failed to add documents: {mresponse.content}')
if b'MDB_CORRUPTED' in mresponse.content:
logging.error(f'MDB_CORRUPTED error encountered. Details: {mresponse.content}')
# Handle the MDB_CORRUPTED error
handle_mdb_corrupted_error()
break # Stop processing further to handle corruption
continue
except KeyError as e:
logging.error(f"Key error: {str(e)} - some required video information is missing")
logging.info(f"Failed video_info: {video_info}")
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
logging.info(f"An error occurred: {str(e)}")
def meilisearch_bg_process():
while True:
process_and_add_to_meilisearch()
time.sleep(1800)
@app.route('/search', methods=['POST'])
def search():
# Get the query from the frontend
srchdata = request.json
query = srchdata.get('query', '')
# Prepare the MeiliSearch request
srchurl = f'{meiliproxy}/indexes/yt-dlp_index/search'
srchheaders = {
'Authorization': f'Bearer {meili_master_key}'
}
payload = {
'q': query
}
# Send the request to MeiliSearch
srchresponse = requests.post(srchurl, headers=srchheaders, json=payload)
# Return the results to the frontend
return jsonify(srchresponse.json())
class User(UserMixin):
def __init__(self, username, password):
self.id = username
self.username = username
self.password = password
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
elif isinstance(o, ObjectId):
return str(o) # convert ObjectId to string
return super(DateTimeEncoder, self).default(o)
@app.route('/meili', defaults={'path', ''}, methods=['GET', 'PUT', 'POST', 'DELETE'])
@app.route('/meili/<path:path>', methods=['GET', 'POST', 'DELETE'])
def proxy_to_meili(path):
# Forward the request to MeiliSearch
resp = requests.request(
method=request.method,
url=f"{meiliproxy}/{path}",
headers={key: value for (key, value) in request.headers if key != 'Host'},
data=request.get_data(),
params=request.args,
cookies=request.cookies,
allow_redirects=False)
# Return the response from MeiliSearch
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
response = Response(resp.content, resp.status_code, headers)
return response
#############################################################
########################### Users ###########################
#############################################################
@login_manager.user_loader
def load_user(user_id):
# Fetch the user from the database using the user_id
user_record = fetch_user_from_database(user_id) # You need to implement this function
# Create a User object using the username and password from the user_record
if user_record is None:
return None
user = User(user_record['username'], user_record['password'])
return user
#############################################################
############## HLS Segments / Queue and convert #############
#############################################################
def convert_to_hls(video_id, input_filepath, max_retries=3):
logging.info('HLS: 01')
output_dir = os.path.join(HLS_FILES_DIR, video_id)
os.makedirs(output_dir, exist_ok=True)
output_playlist = os.path.join(output_dir, f"{video_id}.m3u8")
logging.info('Convert_to_HLS: %s', f"{output_playlist}")
logging.info(f"HLS: 02")
printline(f'{input_filepath}')
printline(f'{output_playlist}')
command = [
"ffmpeg",
"-i", input_filepath,
"-c:v", "libx264",
"-c:a", "aac",
"-start_number", "0",
"-hls_time", "10",
"-hls_list_size", "0",
"-f", "hls",
output_playlist
]
retries = 0
while retries <= max_retries:
try:
with ffmpeg_lock:
# Attempt to run ffmpeg with a timeout
logging.info(f"HLS: 03 Starting ffmpeg version for {video_id}")
subprocess.run(command, check=True, timeout=3600)
logging.info(f"HLS: 03 ffmpeg command for video_id {video_id} completed successfully.")
break # Break out of the loop if unsuccessful
except TimeoutExpired:
logging.info(f"HLS: 03.0 ffmpeg command for video_id {video_id} timed out. Attempt {retries + 1} of {max_retries}.")
retries += 1
except Exception as e:
logging.info(f"HLS: 03.1 ffmpeg command for video_id {video_id} failed with error {e}")
break
def conversion_worker():
while True:
video_id, input_filepath = conversion_queue.get()
logging.info(f"HLS: 06")
logging.info(f"HLS: 06.0 Worker started processing task for video_id {video_id}")
try:
with conversion_lock: # Acquire lock
if video_id not in ongoing_conversions:
ongoing_conversions[video_id] = True
logging.info(f"HLS: 07")
# Perform conversion outside the lock to not block other operations
logging.info(f"HLS: 06.1 Worker started processing task for video_id {video_id}")
logging.info(f"HLS: 08.0 convert_to_hls() started")
convert_to_hls(video_id, input_filepath)
logging.info(f"HLS: 08.1 convert_to_hls() complete")
except Exception as e:
logging.info(f"HLS 08.2 Conversion failed for {video_id} with error {e}")
finally:
with conversion_lock: # Acquire lock again to update dictionary
logging.info(f"HLS: 09.0")
ongoing_conversions.pop(video_id, None)
logging.info(f"HLS: 09.1")
logging.info(f"HLS: 10.0")
conversion_queue.task_done()
logging.info(f"HLS: 10.1")
logging.info(f'HLS: 10.2 Task masked as finished for video_id: {video_id}')
def initialize_workers():
num_workers = max(1, docker_max_workers)
logging.info(f"HLS: 11 Initializing {num_workers} worker threads.")
for _ in range(num_workers):
logging.info(f"HLS: 11.1 Starting a new worker thread")
worker = threading.Thread(target=conversion_worker, daemon=True)
logging.info(f"HLS: 11.2 Configured threading worker")
worker.start()
logging.info(f"HLS: 11.3 Worker started")
initialize_workers()
def async_convert_to_hls(video_id, input_filepath):
with conversion_lock: # Acquire lock to check and update dictionary
if video_id in ongoing_conversions:
printline(f"Conversion for video_id {video_id} is already in progress.")
return
# Add the task to the queue without holding the lock to avoid blocking
logging.info(f'HLS: 13.1 Adding to conversion queue video_id: {video_id}')
conversion_queue.put((video_id, input_filepath))
logging.info(f'HLS: 13.2 Task added to conversion queue video_id: {video_id}')
@app.route('/serve_hls/<video_id>/<filename>')
def serve_hls_segment(video_id, filename):
return send_from_directory(os.path.join(HLS_FILES_DIR, video_id), filename)
@app.route('/serve_hls/<video_id>/<path:filename>')
def serve_hls(video_id, filename):
logging.info('Serving HLS segment for video_id: %s, filename: %s', video_id, filename)
# Determine the full path to the requested file within the video_id directory
file_path = os.path.join(HLS_FILES_DIR, video_id, filename)
# Check if the requested file exists
if not os.path.exists(file_path):
logging.info('Error serving HLS segment for video_id: %s, filename: %s', video_id, filename)
abort(404, description="File not found")
# Serve the requested file
return send_from_directory(os.path.join(HLS_FILES_DIR, video_id), filename)
# Delivers /videos/ID video page for a single video (player)
@app.route('/videos/<video_id>')
def video_page(video_id):
# Fetch the video data from MongoDB using the provided ID
video = collection.find_one({"id": video_id})
logging.info('Loading video page for video_id: %s', video_id)
if not video:
return "Video not found", 404
# Fix data to pass to videos.html for <meta> tags
video['filename'] = video['filename'].replace(docker_mainpath, '/app/')
video['filename'] = video['filename'].replace('/appdata/public/', '/app/data/public/')
video['filename'] = video['filename'].replace('/app/data/', 'data/')
video['tmbfp'] = video['tmbfp'].replace('/data/data/public/', '/data/public/')
# Construct the HLS playlist path
hls_playlist_path = os.path.join(HLS_FILES_DIR, video_id, f'{video_id}.m3u8')
# Check if the HLS playlist exists and is ready
if os.path.exists(hls_playlist_path):
# HLS playlist exists, render the video page directly
playlist_url = url_for('serve_hls', video_id=video_id, filename=f'{video_id}.m3u8', _external=True)
logging.info('Serving video.html with HLS playlist URL')
return render_template('video.html', video_id=video_id, video=video, bdir=bdir, hls_playlist=playlist_url)
else:
# HLS playlist does not exist, initiate conversion if not already in progress
with conversion_lock:
if video_id not in ongoing_conversions:
ongoing_conversions[video_id] = True
try:
conversion_queue.put((video_id, video['filename']))
logging.info(f'HLS: 22.1 Conversion initiated for video_id {video_id}, {video["filename"]}')
printline(f"Conversion initiated for video_id {video_id}, {video['filename']}.")
except Queue.Full:
logging.info(f"HLS: 22.2 Conversion queue is full. Cannot add task for video_id {video_id}")
else:
logging.info(f"HLS: 22.3 Conversion for video_id {video_id} is already in progress or queued")
# Render a loading page while conversion is in progress
# Note: The loading page should periodically check for conversion completion.
logging.info(f'HLS: 23.4 video_page app route: choosing loading.html')
return render_template('loading.html', video_id=video_id, video=video, bdir=bdir)
@app.route('/check_hls/<video_id>')
def check_hls(video_id):
logging.info(f"HLS: 24 Check_hls start")
hls_playlist_path = os.path.join(HLS_FILES_DIR, video_id, f'{video_id}.m3u8')
if os.path.exists(hls_playlist_path):
# Construct the relative URL path for the playlist (removes /app)
playlist_url = url_for('serve_hls', video_id=video_id, filename=f'{video_id}.m3u8', _external=True)
return jsonify({'status': 'ready', 'playlist': playlist_url})
logging.info(f'check_hls: playlist is ready')
logging.info(f"HLS: 25 Check_hls is READY")
else:
logging.info(f"HLS: 26 Check_hls processing")
logging.info(f'check_hls: playlist is processing')
return jsonify({'status': 'processing'})
@app.route('/player')
def player():
filename = request.args.get('filename')
if not filename:
return "Filename not provided", 400
filename = filename.replace('data/', '', 1)
# Determine the content type based on the file extension
file_extension = filename.split('.')[-1].lower()
content_type = "video/mp4" if file_extension == "mp4" else "video/webm"
# Pass both filename and content_type to the player.html template
return render_template('player.html', filename=filename, content_type=content_type)
#############################################################
######################### Admin Page ########################
#############################################################
def get_directory_structure(startpath, excluded_dirs=None):
"""
Recursively fetches the directory structure, excluding specified directories.
:param startpath: The base directory path to start the search from.
:param excluded_dirs: A list of directory names to exclude from the structure.
:return: A nested dictionary representing the folder structure of startpath.
"""
if excluded_dirs is None:
excluded_dirs = ['bin', 'boot', 'dev', 'etc', 'home', 'lib', 'lib64', 'media', 'opt', 'proc', 'root', 'run', 'sbin', 'srv', 'sys', 'tmp', 'usr', 'var']
tree = {}
for root, dirs, files in os.walk(startpath, topdown=True):
# Exclude specified directories
dirs[:] = [d for d in dirs if d not in excluded_dirs]
# Trim the part of the path that precedes the base directory
trimmed_path = root[len(startpath):].lstrip(os.path.sep)
subtree = tree
# Recursively navigate down the dictionary and add new dictionaries for subdirectories
for part in trimmed_path.split(os.path.sep):
subtree = subtree.setdefault(part, {})
subtree["_files"] = files # Optionally store files in the "_files" key, or ignore if not needed
return tree
def update_document_paths(newpathprefix, dry_run=True):
# Define the old path prefix that will be replaced
oldpathprefix = docker_mainpath
# Fetch all documents that need their paths updated
documents = global_pool.find({"download_path": {"$regex": oldpathprefix}})
# Counter for how many paths would be updated (for dry run reporting)
update_count = 0
for doc in documents:
old_path = doc["download_path"] # Extract the current download_path
# Generate the new download_path by replacing the old prefix with the new one
new_path = old_path.replace(oldpathprefix, newpathprefix)
if dry_run: # If dry run, just print what would be done
printline(f"Dry run: Would update from {old_path} to {new_path}")
else: # If not a dry run, perform the update in the database
# collection.update_one({"_id": doc["_id"]}, {"$set": {"download_path": new_path}})
printline(f"Updated {doc['_id']} path to {new_path}")
update_count += 1
if dry_run:
printline(f"Dry run complete: {update_count} paths would be updated.")
else:
printline(f"Update complete: {update_count} paths updated.")
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/restore_all', methods=['GET', 'POST'])
def restore_all():
if request.method == 'POST':
# Check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
zip_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(zip_path)
# Extract the zip file
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(app.config['UPLOAD_FOLDER'])
# Restore the data from the extracted files
for collection_name in os.listdir(app.config['UPLOAD_FOLDER']):
collection_path = os.path.join(app.config['UPLOAD_FOLDER'], collection_name)
if os.path.isfile(collection_path) and collection_name.endswith('.json'):
with open(collection_path, 'r') as file:
data = json.load(file)
collection_name = collection_name.rsplit('.', 1)[0] # Remove .json extension
collection = db[collection_name]
collection.delete_many({}) # Clear existing data
collection.insert_many(data)
flash('Restore completed successfully')
return redirect(url_for('admin_page'))
@app.route('/backup_all')
def backup_all():
with tempfile.TemporaryDirectory() as tmp_backup_dir:
for collection_name in db.list_collection_names():
collection = db[collection_name]
if collection_name == 'downloads':
# For the downloads collection, keep the '_id' field
data = list(collection.find({}))
else:
# For other collections, exclude the '_id' field
data = list(collection.find({}, {'_id': False}))
for item in data:
# Convert ObjectId to string for the downloads collection
if collection_name == 'downloads':
item['_id'] = str(item['_id'])
backup_path = os.path.join(tmp_backup_dir, f'{collection_name}.json')
with open(backup_path, 'w') as file:
json.dump(data, file, indent=4)
final_backup_dir = 'backups'
if not os.path.exists(final_backup_dir):
os.makedirs(final_backup_dir)
zip_filename = 'mongodb_backup.zip'
zip_path = os.path.join(final_backup_dir, zip_filename)
shutil.make_archive(base_name=zip_path, format='zip', root_dir=tmp_backup_dir)
return send_file(f'{zip_path}.zip', as_attachment=True, download_name=zip_filename)
def get_volume_usages(volumes):
volume_usages = []
for volume in volumes:
volume_path = volume if volume.startswith("/") else f"/{volume}"
try:
total, used, free = shutil.disk_usage(volume_path)
volume_usages.append({
'path': volume_path,
'free_gb': round(free / (1024**3), 2), # Convert bytes to GB
'total_gb': round(total / (1024**3), 2) # Convert bytes to GB
})
except Exception as e:
printline(f"Error retrieving disk usage for {volume_path}: {e}")
return volume_usages
def get_next_volume():
# Fetch the current settings
settings_doc = admin_settings.find_one()
volumes = settings_doc.get("volumes", [])
current_strategy = admin_settings_doc.get("strategy", "round_robin")
last_used_index = admin_settings_doc.get("lastUsedVolumeIndex", 0)
# Ensure the strategy is round_robin before proceeding
if current_strategy != "round_robin" or not volumes:
# Handle the case where the strategy is not round_robin or no volumes are defined
raise ValueError("Strategy is not round_robin or no volumes defined")
# Calculate the next index based on round_robin strategy
next_index = (last_used_index + 1) % len(volumes)
# Update the last used volume index in MongoDB
printline(f'Updating admin settings with {next_index} to "lastUsedVolumeIndex"')
# admin_settings.update_one({}, {'$set': {'lastUsedVolumeIndex': next_index}})
# Return the next volume path
return volumes[next_index]
def get_last_used_volume_index():
settings_document = admin_settings.find_one({}, {'lastUsedVolumeIndex': 1, '_id': 0})
if settings_document and 'lastUsedVolumeIndex' in settings_document:
return settings_document['lastUsedVolumeIndex']
else:
return -1
def set_last_used_volume_index(index):
printline(f'Updating admin settings with {index} to "lastUsedVolumeIndex"')
admin_settings.update_one({}, {'$set': {'lastUsedVolumeIndex': index}}, upsert=True)
def find_best_matching_file(directory, base_name):
# Step 1: Construct a pattern to find files that start with the base_name, regardless of their extension.
pattern = f"{base_name}"
# Step 2: Use glob to find files matching the pattern.
files = glob.glob(pattern)
printline(f"Pattern {pattern}, Files: {files}")
# Step 3: Ensure 'file_bases' is defined by extracting the base part (without extension) of each file found.
file_bases = [os.path.splitext(os.path.basename(f))[0] for f in files]
# Step 4: Use 'file_bases' in 'difflib.get_close_matches' to find the best match.
best_matches = difflib.get_close_matches(base_name, file_bases, n=1, cutoff=0.8)
# Step 5: If a match is found, return the corresponding full path from the 'files' list.
if best_matches:
best_match_base = best_matches[0]
for f in files:
if os.path.splitext(os.path.basename(f))[0] == best_match_base:
return f # Return the full path of the matched file
return None # If no match is found, return None
def prepare_files_to_move():
files_to_move = []
cursor = global_pool.find({})
for doc in cursor:
video_path = doc['download_path']
printline(f"video_path: {video_path}")
base_filename = os.path.basename(video_path)
printline(f"base_filename: {base_filename}")
base_name, _ = os.path.splitext(base_filename)
printline(f"base_name: {base_name}")
thumbnail_directory = video_path.replace('/videos/', '/thumbnails/').replace(base_filename, f"{base_name}")
printline(f"thumbnail_directory: {thumbnail_directory}")
thumbnail_path = find_best_matching_file(thumbnail_directory, base_name)
json_path = video_path.replace('/videos/', '/json/').replace(base_filename, f"{base_name}.json")
if thumbnail_path:
files_to_move.append({
'video': video_path,
'thumbnail': thumbnail_path,
'json': json_path
})
return files_to_move
def move_data(files_to_move):
volumes = get_selected_volumes()
last_used_index = int(get_last_used_volume_index())
for file_group in files_to_move:
last_used_index = (last_used_index + 1) % len(volumes)
new_volume_base_path = os.path.join('/mnt/', volumes[last_used_index], 'docker/anomaly-ytdlp/data')
for file_type, file_path in file_group.items():
target_subdir = {'video': 'public/videos', 'thumbnail': 'public/thumbnails', 'json': 'public/json'}[file_type]
new_file_path = os.path.join(new_volume_base_path, target_subdir, os.path.basename(file_path))
printline(f'Moving {os.path.basename(file_path)} to {new_file_path}')
# shutil.move(file_path, new_file_path)
set_last_used_volume_index(last_used_index)
@app.route("/test-move-data", methods=["POST"])
def test_move_data():
printline("Received test move data request")
files_to_move = prepare_files_to_move()
move_data(files_to_move)
return jsonify({'message': 'Move data test initiated'})
@app.route("/save-settings", methods=["POST"])
def save_settings():
settings_data = request.json
# Update the settings in the settings collection
admin_settings.update_one(
{},
{'$set': settings_data},
upsert=True
)
return jsonify({"message": "Settings updated successfully"})
@app.route('/admin69420847', methods=['GET', 'POST'])
def admin_page():
directory_structure = get_directory_structure("/")
# Load statistics.json data
with open('statistics.json', 'r') as file:
statistics = json.load(file)
set_default_settings() # Ensure default settings are set
selected_volumes = get_selected_volumes()
volume_usages = get_volume_usages(selected_volumes)
if request.method == 'POST':
newpathprefix = request.form.get('newPath')
dry_run = 'dryRun' in request.form
update_document_paths(newpathprefix, dry_run)
updated_settings = admin_settings.find_one({})
return render_template('admin.html', volume_usages=volume_usages, selected_volumes=selected_volumes, statistics=statistics, settings=updated_settings, update_success=True, dry_run=dry_run, newpathprefix=newpathprefix, bdir=bdir, docker_port_ytdl=docker_port_ytdl, docker_port_ytdldb=docker_port_ytdldb, docker_port_ytdlredis=docker_port_ytdlredis, docker_port_ytdlmeili=docker_port_ytdlmeili, directory_structure=directory_structure)
# Variables like bdir, docker_port_ytdl, etc., should be defined or fetched before passing to the template
updated_settings = admin_settings.find_one({})
return render_template('admin.html', volume_usages=volume_usages, selected_volumes=selected_volumes, statistics=statistics, settings=updated_settings, bdir=bdir, docker_port_ytdl=docker_port_ytdl, docker_port_ytdldb=docker_port_ytdldb, docker_port_ytdlredis=docker_port_ytdlredis, docker_port_ytdlmeili=docker_port_ytdlmeili, directory_structure=directory_structure)
#############################################################
#################### Login & Registration ###################
#############################################################
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# Validate the username and password
user = User()
user.id = username
login_user(user)
session['user_id'] = username # Set the 'user_id' session variable
return redirect(url_for('home'))
else:
return render_template('login.html') # render a login form
@app.route('/logout')
@login_required
def logout():
logout_user()
return 'Logged out'
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# Validate the username and password
# hash the password before storing it.
if not username or not password:
return 'Invalid username or password', 400
# Store the username and password
session['username'] = username
session['password'] = password
return redirect(url_for('home')) # redirect to the home page after registration
else:
return render_template('register.html')
#############################################################
#################### Fetch User from DB #####################
def fetch_user_from_database(username):
# Connect to your MongoDB client
client = MongoClient(f'mongodb://{docker_ytdldb}:27017/')
# Select your database
db = client['yt-dlp']
# Select your collection (table)
users = db['users']
# Query for the user with the given username
user_record = users.find_one({'username': username})
# Return the user record
return user_record
#############################################################
##################### Update Statistics #####################
def update_statistics(url):
stats_file = 'statistics.json'
if os.path.exists(stats_file):
with open(stats_file, 'r') as f:
if f is None:
stats = {'total_downloads': 0, 'domains': {}}
else:
stats = json.load(f)
else:
stats = {'total_downloads': 0, 'domains': {}}
stats['total_downloads'] += 1
logging.info('Step 07: Incrementing total_downloads by 1')
domain = urlparse(url).netloc
if domain not in stats['domains']:
stats['domains'][domain] = 0
stats['domains'][domain] += 1
with open(stats_file, 'w') as f:
json.dump(stats, f)
logging.info('Step 07: Dumping stats from update_statistics')
return stats['total_downloads'], stats['domains'][domain]
#############################################################
##################### Sanitize Filename #####################
def sanitize_filename(filename, max_length=180):
invalid_chars = '\“\”!*()[].\'%&@$/<>:"/\\|?*#;^%~`,'
for char in invalid_chars:
filename = filename.replace(char, '_') # remove illegal characters
filename = re.sub(' +', ' ', filename) # remove consecutive spaces
# Truncate and hash the filename if it's too long
if len(filename) > max_length:
filename_hash = hashlib.md5(filename.encode()).hexdigest()
filename = filename[:max_length - len(filename_hash)] # + filename_hash
logging.info('Returning filename from sanitize_filename: %s', filename)
return filename