forked from Puyodead1/udemy-downloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2006 lines (1800 loc) · 79.6 KB
/
main.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
# -*- coding: utf-8 -*-
import argparse
import json
import logging
import math
import os
import re
import subprocess
import sys
import time
from http.cookiejar import MozillaCookieJar
from pathlib import Path
from typing import IO, Union
import browser_cookie3
import demoji
import m3u8
import requests
import yt_dlp
from bs4 import BeautifulSoup
from coloredlogs import ColoredFormatter
from dotenv import load_dotenv
from pathvalidate import sanitize_filename
from requests.exceptions import ConnectionError as conn_error
from tqdm import tqdm
from constants import *
from tls import SSLCiphers
from utils import extract_kid
from vtt_to_srt import convert
DOWNLOAD_DIR = os.path.join(os.getcwd(), "out_dir")
retry = 3
downloader = None
logger: logging.Logger = None
dl_assets = False
dl_captions = False
dl_quizzes = False
skip_lectures = False
caption_locale = "en"
quality = None
bearer_token = None
portal_name = None
course_name = None
keep_vtt = False
skip_hls = False
concurrent_downloads = 10
save_to_file = None
load_from_file = None
course_url = None
info = None
keys = {}
id_as_course_name = False
is_subscription_course = False
use_h265 = False
h265_crf = 28
h265_preset = "medium"
use_nvenc = False
browser = None
cj = None
use_continuous_lecture_numbers = False
def deEmojify(inputStr: str):
return demoji.replace(inputStr, "")
# from https://stackoverflow.com/a/21978778/9785713
def log_subprocess_output(prefix: str, pipe: IO[bytes]):
if pipe:
for line in iter(lambda: pipe.read(1), ""):
logger.debug("[%s]: %r", prefix, line.decode("utf8").strip())
pipe.flush()
# this is the first function that is called, we parse the arguments, setup the logger, and ensure that required directories exist
def pre_run():
global dl_assets, dl_captions, dl_quizzes, skip_lectures, caption_locale, quality, bearer_token, course_name, keep_vtt, skip_hls, concurrent_downloads, load_from_file, save_to_file, bearer_token, course_url, info, logger, keys, id_as_course_name, LOG_LEVEL, use_h265, h265_crf, h265_preset, use_nvenc, browser, is_subscription_course, DOWNLOAD_DIR, use_continuous_lecture_numbers
# make sure the logs directory exists
if not os.path.exists(LOG_DIR_PATH):
os.makedirs(LOG_DIR_PATH, exist_ok=True)
parser = argparse.ArgumentParser(description="Udemy Downloader")
parser.add_argument(
"-c", "--course-url", dest="course_url", type=str, help="The URL of the course to download", required=True
)
parser.add_argument(
"-b",
"--bearer",
dest="bearer_token",
type=str,
help="The Bearer token to use",
)
parser.add_argument(
"-q",
"--quality",
dest="quality",
type=int,
help="Download specific video quality. If the requested quality isn't available, the closest quality will be used. If not specified, the best quality will be downloaded for each lecture",
)
parser.add_argument(
"-l",
"--lang",
dest="lang",
type=str,
help="The language to download for captions, specify 'all' to download all captions (Default is 'en')",
)
parser.add_argument(
"-cd",
"--concurrent-downloads",
dest="concurrent_downloads",
type=int,
help="The number of maximum concurrent downloads for segments (HLS and DASH, must be a number 1-30)",
)
parser.add_argument(
"--skip-lectures",
dest="skip_lectures",
action="store_true",
help="If specified, lectures won't be downloaded",
)
parser.add_argument(
"--download-assets",
dest="download_assets",
action="store_true",
help="If specified, lecture assets will be downloaded",
)
parser.add_argument(
"--download-captions",
dest="download_captions",
action="store_true",
help="If specified, captions will be downloaded",
)
parser.add_argument(
"--download-quizzes",
dest="download_quizzes",
action="store_true",
help="If specified, quizzes will be downloaded",
)
parser.add_argument(
"--keep-vtt",
dest="keep_vtt",
action="store_true",
help="If specified, .vtt files won't be removed",
)
parser.add_argument(
"--skip-hls",
dest="skip_hls",
action="store_true",
help="If specified, hls streams will be skipped (faster fetching) (hls streams usually contain 1080p quality for non-drm lectures)",
)
parser.add_argument(
"--info",
dest="info",
action="store_true",
help="If specified, only course information will be printed, nothing will be downloaded",
)
parser.add_argument(
"--id-as-course-name",
dest="id_as_course_name",
action="store_true",
help="If specified, the course id will be used in place of the course name for the output directory. This is a 'hack' to reduce the path length",
)
parser.add_argument(
"-sc",
"--subscription-course",
dest="is_subscription_course",
action="store_true",
help="Mark the course as a subscription based course, use this if you are having problems with the program auto detecting it",
)
parser.add_argument(
"--save-to-file",
dest="save_to_file",
action="store_true",
help="If specified, course content will be saved to a file that can be loaded later with --load-from-file, this can reduce processing time (Note that asset links expire after a certain amount of time)",
)
parser.add_argument(
"--load-from-file",
dest="load_from_file",
action="store_true",
help="If specified, course content will be loaded from a previously saved file with --save-to-file, this can reduce processing time (Note that asset links expire after a certain amount of time)",
)
parser.add_argument(
"--log-level",
dest="log_level",
type=str,
help="Logging level: one of DEBUG, INFO, ERROR, WARNING, CRITICAL (Default is INFO)",
)
parser.add_argument(
"--browser",
dest="browser",
help="The browser to extract cookies from",
choices=["chrome", "firefox", "opera", "edge", "brave", "chromium", "vivaldi", "safari", "file"],
)
parser.add_argument(
"--use-h265",
dest="use_h265",
action="store_true",
help="If specified, videos will be encoded with the H.265 codec",
)
parser.add_argument(
"--h265-crf",
dest="h265_crf",
type=int,
default=28,
help="Set a custom CRF value for H.265 encoding. FFMPEG default is 28",
)
parser.add_argument(
"--h265-preset",
dest="h265_preset",
type=str,
default="medium",
help="Set a custom preset value for H.265 encoding. FFMPEG default is medium",
)
parser.add_argument(
"--use-nvenc",
dest="use_nvenc",
action="store_true",
help="Whether to use the NVIDIA hardware transcoding for H.265. Only works if you have a supported NVIDIA GPU and ffmpeg with nvenc support",
)
parser.add_argument(
"--out",
"-o",
dest="out",
type=str,
help="Set the path to the output directory",
)
parser.add_argument(
"--continue-lecture-numbers",
"-n",
dest="use_continuous_lecture_numbers",
action="store_true",
help="Use continuous lecture numbering instead of per-chapter",
)
# parser.add_argument("-v", "--version", action="version", version="You are running version {version}".format(version=__version__))
args = parser.parse_args()
if args.download_assets:
dl_assets = True
if args.lang:
caption_locale = args.lang
if args.download_captions:
dl_captions = True
if args.download_quizzes:
dl_quizzes = True
if args.skip_lectures:
skip_lectures = True
if args.quality:
quality = args.quality
if args.keep_vtt:
keep_vtt = args.keep_vtt
if args.skip_hls:
skip_hls = args.skip_hls
if args.concurrent_downloads:
concurrent_downloads = args.concurrent_downloads
if concurrent_downloads <= 0:
# if the user gave a number that is less than or equal to 0, set cc to default of 10
concurrent_downloads = 10
elif concurrent_downloads > 30:
# if the user gave a number thats greater than 30, set cc to the max of 30
concurrent_downloads = 30
if args.load_from_file:
load_from_file = args.load_from_file
if args.save_to_file:
save_to_file = args.save_to_file
if args.bearer_token:
bearer_token = args.bearer_token
if args.course_url:
course_url = args.course_url
if args.info:
info = args.info
if args.use_h265:
use_h265 = True
if args.h265_crf:
h265_crf = args.h265_crf
if args.h265_preset:
h265_preset = args.h265_preset
if args.use_nvenc:
use_nvenc = True
if args.log_level:
if args.log_level.upper() == "DEBUG":
LOG_LEVEL = logging.DEBUG
elif args.log_level.upper() == "INFO":
LOG_LEVEL = logging.INFO
elif args.log_level.upper() == "ERROR":
LOG_LEVEL = logging.ERROR
elif args.log_level.upper() == "WARNING":
LOG_LEVEL = logging.WARNING
elif args.log_level.upper() == "CRITICAL":
LOG_LEVEL = logging.CRITICAL
else:
print(f"Invalid log level: {args.log_level}; Using INFO")
LOG_LEVEL = logging.INFO
if args.id_as_course_name:
id_as_course_name = args.id_as_course_name
if args.is_subscription_course:
is_subscription_course = args.is_subscription_course
if args.browser:
browser = args.browser
if args.out:
DOWNLOAD_DIR = os.path.abspath(args.out)
if args.use_continuous_lecture_numbers:
use_continuous_lecture_numbers = args.use_continuous_lecture_numbers
# setup a logger
logger = logging.getLogger(__name__)
logging.root.setLevel(LOG_LEVEL)
# create a colored formatter for the console
console_formatter = ColoredFormatter(LOG_FORMAT, datefmt=LOG_DATE_FORMAT)
# create a regular non-colored formatter for the log file
file_formatter = logging.Formatter(LOG_FORMAT, datefmt=LOG_DATE_FORMAT)
# create a handler for console logging
stream = logging.StreamHandler()
stream.setLevel(LOG_LEVEL)
stream.setFormatter(console_formatter)
# create a handler for file logging
file_handler = logging.FileHandler(LOG_FILE_PATH)
file_handler.setFormatter(file_formatter)
# construct the logger
logger = logging.getLogger("udemy-downloader")
logger.setLevel(LOG_LEVEL)
logger.addHandler(stream)
logger.addHandler(file_handler)
logger.info(f"Output directory set to {DOWNLOAD_DIR}")
Path(DOWNLOAD_DIR).mkdir(parents=True, exist_ok=True)
Path(SAVED_DIR).mkdir(parents=True, exist_ok=True)
# Get the keys
if os.path.exists(KEY_FILE_PATH):
with open(KEY_FILE_PATH, encoding="utf8", mode="r") as keyfile:
keys = json.loads(keyfile.read())
else:
logger.warning("> Keyfile not found! You won't be able to decrypt any encrypted videos!")
class Udemy:
def __init__(self, bearer_token):
global cj
self.session = None
self.bearer_token = None
self.auth = UdemyAuth(cache_session=False)
if not self.session:
self.session = self.auth.authenticate(bearer_token=bearer_token)
if not self.session:
if browser == None:
logger.error("No bearer token was provided, and no browser for cookie extraction was specified.")
sys.exit(1)
logger.warning("No bearer token was provided, attempting to use browser cookies.")
self.session = self.auth._session
if browser == "chrome":
cj = browser_cookie3.chrome()
elif browser == "firefox":
cj = browser_cookie3.firefox()
elif browser == "opera":
cj = browser_cookie3.opera()
elif browser == "edge":
cj = browser_cookie3.edge()
elif browser == "brave":
cj = browser_cookie3.brave()
elif browser == "chromium":
cj = browser_cookie3.chromium()
elif browser == "vivaldi":
cj = browser_cookie3.vivaldi()
elif browser == "file":
# load netscape cookies from file
cj = MozillaCookieJar("cookies.txt")
cj.load()
def _get_quiz(self, quiz_id):
self.session._headers.update(
{
"Host": "{portal_name}.udemy.com".format(portal_name=portal_name),
"Referer": "https://{portal_name}.udemy.com/course/{course_name}/learn/quiz/{quiz_id}".format(
portal_name=portal_name, course_name=course_name, quiz_id=quiz_id
),
}
)
url = QUIZ_URL.format(portal_name=portal_name, quiz_id=quiz_id)
try:
resp = self.session._get(url).json()
except conn_error as error:
logger.fatal(f"[-] Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
else:
return resp.get("results")
def _get_elem_value_or_none(self, elem, key):
return elem[key] if elem and key in elem else "(None)"
def _get_quiz_with_info(self, quiz_id):
resp = {"_class": None, "_type": None, "contents": None}
quiz_json = self._get_quiz(quiz_id)
is_only_one = len(quiz_json) == 1 and quiz_json[0]["_class"] == "assessment"
is_coding_assignment = quiz_json[0]["assessment_type"] == "coding-problem"
resp["_class"] = quiz_json[0]["_class"]
if is_only_one and is_coding_assignment:
assignment = quiz_json[0]
prompt = assignment["prompt"]
resp["_type"] = assignment["assessment_type"]
resp["contents"] = {
"instructions": self._get_elem_value_or_none(prompt, "instructions"),
"tests": self._get_elem_value_or_none(prompt, "test_files"),
"solutions": self._get_elem_value_or_none(prompt, "solution_files"),
}
resp["hasInstructions"] = False if resp["contents"]["instructions"] == "(None)" else True
resp["hasTests"] = False if isinstance(resp["contents"]["tests"], str) else True
resp["hasSolutions"] = False if isinstance(resp["contents"]["solutions"], str) else True
else: # Normal quiz
resp["_type"] = "normal-quiz"
resp["contents"] = quiz_json
return resp
def _extract_supplementary_assets(self, supp_assets, lecture_counter):
_temp = []
for entry in supp_assets:
title = sanitize_filename(entry.get("title"))
filename = entry.get("filename")
download_urls = entry.get("download_urls")
external_url = entry.get("external_url")
asset_type = entry.get("asset_type").lower()
id = entry.get("id")
if asset_type == "file":
if download_urls and isinstance(download_urls, dict):
extension = filename.rsplit(".", 1)[-1] if "." in filename else ""
download_url = download_urls.get("File", [])[0].get("file")
_temp.append(
{
"type": "file",
"title": title,
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": extension,
"download_url": download_url,
"id": id,
}
)
elif asset_type == "sourcecode":
if download_urls and isinstance(download_urls, dict):
extension = filename.rsplit(".", 1)[-1] if "." in filename else ""
download_url = download_urls.get("SourceCode", [])[0].get("file")
_temp.append(
{
"type": "source_code",
"title": title,
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": extension,
"download_url": download_url,
"id": id,
}
)
elif asset_type == "externallink":
_temp.append(
{
"type": "external_link",
"title": title,
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": "txt",
"download_url": external_url,
"id": id,
}
)
return _temp
def _extract_article(self, asset, id):
return [
{
"type": "article",
"body": asset.get("body"),
"extension": "html",
"id": id,
}
]
def _extract_ppt(self, asset, lecture_counter):
_temp = []
download_urls = asset.get("download_urls")
filename = asset.get("filename")
id = asset.get("id")
if download_urls and isinstance(download_urls, dict):
extension = filename.rsplit(".", 1)[-1] if "." in filename else ""
download_url = download_urls.get("Presentation", [])[0].get("file")
_temp.append(
{
"type": "presentation",
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": extension,
"download_url": download_url,
"id": id,
}
)
return _temp
def _extract_file(self, asset, lecture_counter):
_temp = []
download_urls = asset.get("download_urls")
filename = asset.get("filename")
id = asset.get("id")
if download_urls and isinstance(download_urls, dict):
extension = filename.rsplit(".", 1)[-1] if "." in filename else ""
download_url = download_urls.get("File", [])[0].get("file")
_temp.append(
{
"type": "file",
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": extension,
"download_url": download_url,
"id": id,
}
)
return _temp
def _extract_ebook(self, asset, lecture_counter):
_temp = []
download_urls = asset.get("download_urls")
filename = asset.get("filename")
id = asset.get("id")
if download_urls and isinstance(download_urls, dict):
extension = filename.rsplit(".", 1)[-1] if "." in filename else ""
download_url = download_urls.get("E-Book", [])[0].get("file")
_temp.append(
{
"type": "ebook",
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": extension,
"download_url": download_url,
"id": id,
}
)
return _temp
def _extract_audio(self, asset, lecture_counter):
_temp = []
download_urls = asset.get("download_urls")
filename = asset.get("filename")
id = asset.get("id")
if download_urls and isinstance(download_urls, dict):
extension = filename.rsplit(".", 1)[-1] if "." in filename else ""
download_url = download_urls.get("Audio", [])[0].get("file")
_temp.append(
{
"type": "audio",
"filename": "{0:03d} ".format(lecture_counter) + filename,
"extension": extension,
"download_url": download_url,
"id": id,
}
)
return _temp
def _extract_sources(self, sources, skip_hls):
_temp = []
if sources and isinstance(sources, list):
for source in sources:
label = source.get("label")
download_url = source.get("file")
if not download_url:
continue
if label.lower() == "audio":
continue
height = label if label else None
if height == "2160":
width = "3840"
elif height == "1440":
width = "2560"
elif height == "1080":
width = "1920"
elif height == "720":
width = "1280"
elif height == "480":
width = "854"
elif height == "360":
width = "640"
elif height == "240":
width = "426"
else:
width = "256"
if source.get("type") == "application/x-mpegURL" or "m3u8" in download_url:
if not skip_hls:
out = self._extract_m3u8(download_url)
if out:
_temp.extend(out)
else:
_type = source.get("type")
_temp.append(
{
"type": "video",
"height": height,
"width": width,
"extension": _type.replace("video/", ""),
"download_url": download_url,
}
)
return _temp
def _extract_media_sources(self, sources):
_temp = []
if sources and isinstance(sources, list):
for source in sources:
_type = source.get("type")
src = source.get("src")
if _type == "application/dash+xml":
out = self._extract_mpd(src)
if out:
_temp.extend(out)
return _temp
def _extract_subtitles(self, tracks):
_temp = []
if tracks and isinstance(tracks, list):
for track in tracks:
if not isinstance(track, dict):
continue
if track.get("_class") != "caption":
continue
download_url = track.get("url")
if not download_url or not isinstance(download_url, str):
continue
lang = (
track.get("language")
or track.get("srclang")
or track.get("label")
or track["locale_id"].split("_")[0]
)
ext = "vtt" if "vtt" in download_url.rsplit(".", 1)[-1] else "srt"
_temp.append(
{
"type": "subtitle",
"language": lang,
"extension": ext,
"download_url": download_url,
}
)
return _temp
def _extract_m3u8(self, url):
"""extracts m3u8 streams"""
asset_id_re = re.compile(r"assets/(?P<id>\d+)/")
_temp = []
# get temp folder
temp_path = Path(Path.cwd(), "temp")
# ensure the folder exists
temp_path.mkdir(parents=True, exist_ok=True)
# # extract the asset id from the url
asset_id = asset_id_re.search(url).group("id")
m3u8_path = Path(temp_path, f"index_{asset_id}.m3u8")
try:
r = self.session._get(url)
r.raise_for_status()
raw_data = r.text
# write to temp file for later
with open(m3u8_path, "w") as f:
f.write(r.text)
m3u8_object = m3u8.loads(raw_data)
playlists = m3u8_object.playlists
seen = set()
for pl in playlists:
resolution = pl.stream_info.resolution
codecs = pl.stream_info.codecs
if not resolution:
continue
if not codecs:
continue
width, height = resolution
if height in seen:
continue
# we need to save the individual playlists to disk also
playlist_path = Path(temp_path, f"index_{asset_id}_{width}x{height}.m3u8")
with open(playlist_path, "w") as f:
r = self.session._get(pl.uri)
r.raise_for_status()
f.write(r.text)
seen.add(height)
_temp.append(
{
"type": "hls",
"height": height,
"width": width,
"extension": "mp4",
"download_url": playlist_path.as_uri(),
}
)
except Exception as error:
logger.error(f"Udemy Says : '{error}' while fetching hls streams..")
return _temp
def _extract_mpd(self, url):
"""extracts mpd streams"""
asset_id_re = re.compile(r"assets/(?P<id>\d+)/")
_temp = []
# get temp folder
temp_path = Path(Path.cwd(), "temp")
# ensure the folder exists
temp_path.mkdir(parents=True, exist_ok=True)
# # extract the asset id from the url
asset_id = asset_id_re.search(url).group("id")
# download the mpd and save it to the temp file
mpd_path = Path(temp_path, f"index_{asset_id}.mpd")
try:
with open(mpd_path, "wb") as f:
r = self.session._get(url)
r.raise_for_status()
f.write(r.content)
ytdl = yt_dlp.YoutubeDL(
{"quiet": True, "no_warnings": True, "allow_unplayable_formats": True, "enable_file_urls": True}
)
results = ytdl.extract_info(mpd_path.as_uri(), download=False, force_generic_extractor=True)
format_id = results.get("format_id")
extension = results.get("ext")
height = results.get("height")
width = results.get("width")
_temp.append(
{
"type": "dash",
"height": str(height),
"width": str(width),
"format_id": format_id.replace("+", ","),
"extension": extension,
"download_url": mpd_path.as_uri(),
}
)
except Exception:
logger.exception(f"Error fetching MPD streams")
# We don't delete the mpd file yet because we can use it to download later
return _temp
def extract_course_name(self, url):
"""
@author r0oth3x49
"""
obj = re.search(
r"(?i)(?://(?P<portal_name>.+?).udemy.com/(?:course(/draft)*/)?(?P<name_or_id>[a-zA-Z0-9_-]+))",
url,
)
if obj:
return obj.group("portal_name"), obj.group("name_or_id")
def extract_portal_name(self, url):
obj = re.search(r"(?i)(?://(?P<portal_name>.+?).udemy.com)", url)
if obj:
return obj.group("portal_name")
def _subscribed_courses(self, portal_name, course_name):
results = []
self.session._headers.update(
{
"Host": "{portal_name}.udemy.com".format(portal_name=portal_name),
"Referer": "https://{portal_name}.udemy.com/home/my-courses/search/?q={course_name}".format(
portal_name=portal_name, course_name=course_name
),
}
)
url = COURSE_SEARCH.format(portal_name=portal_name, course_name=course_name)
try:
webpage = self.session._get(url).content
webpage = webpage.decode("utf8", "ignore")
webpage = json.loads(webpage)
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
logger.fatal(f"{error} on {url}")
time.sleep(0.8)
sys.exit(1)
else:
results = webpage.get("results", [])
return results
def _extract_course_info_json(self, url, course_id):
self.session._headers.update({"Referer": url})
url = COURSE_URL.format(portal_name=portal_name, course_id=course_id)
try:
resp = self.session._get(url).json()
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
else:
return resp
def _extract_course_curriculum(self, url, course_id, portal_name):
self.session._headers.update({"Referer": url})
url = CURRICULUM_ITEMS_URL.format(portal_name=portal_name, course_id=course_id)
page = 1
try:
data = self.session._get(url, CURRICULUM_ITEMS_PARAMS).json()
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
else:
_next = data.get("next")
_count = data.get("count")
est_page_count = math.ceil(_count / 100) # 100 is the max results per page
while _next:
logger.info(f"> Downloading course curriculum.. (Page {page + 1}/{est_page_count})")
try:
resp = self.session._get(_next)
if not resp.ok:
logger.error(f"Failed to fetch a page, will retry")
continue
resp = resp.json()
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
else:
_next = resp.get("next")
results = resp.get("results")
if results and isinstance(results, list):
for d in resp["results"]:
data["results"].append(d)
page = page + 1
return data
def _extract_course(self, response, course_name):
_temp = {}
if response:
for entry in response:
course_id = str(entry.get("id"))
published_title = entry.get("published_title")
if course_name in (published_title, course_id):
_temp = entry
break
return _temp
def _my_courses(self, portal_name):
results = []
try:
url = MY_COURSES_URL.format(portal_name=portal_name)
webpage = self.session._get(url).json()
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
logger.fatal(f"{error}")
time.sleep(0.8)
sys.exit(1)
else:
results = webpage.get("results", [])
return results
def _subscribed_collection_courses(self, portal_name):
url = COLLECTION_URL.format(portal_name=portal_name)
courses_lists = []
try:
webpage = self.session._get(url).json()
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
logger.fatal(f"{error}")
time.sleep(0.8)
sys.exit(1)
else:
results = webpage.get("results", [])
if results:
[courses_lists.extend(courses.get("courses", [])) for courses in results if courses.get("courses", [])]
return courses_lists
def _archived_courses(self, portal_name):
results = []
try:
url = MY_COURSES_URL.format(portal_name=portal_name)
url = f"{url}&is_archived=true"
webpage = self.session._get(url).json()
except conn_error as error:
logger.fatal(f"Connection error: {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
logger.fatal(f"{error}")
time.sleep(0.8)
sys.exit(1)
else:
results = webpage.get("results", [])
return results
def _extract_subscription_course_info(self, url):
course_html = self.session._get(url).text
soup = BeautifulSoup(course_html, "lxml")
data = soup.find("div", {"class": "ud-component--course-taking--app"})
if not data:
logger.fatal(
"Could not find course data. Possible causes are: Missing cookies.txt file, incorrect url (should end with /learn), not logged in to udemy in specified browser."
)
self.session.terminate()
sys.exit(1)
data_args = data.attrs["data-module-args"]
data_json = json.loads(data_args)
course_id = data_json.get("courseId", None)
return course_id
def _extract_course_info(self, url):
global portal_name
portal_name, course_name = self.extract_course_name(url)
course = {"portal_name": portal_name}
if not is_subscription_course:
results = self._subscribed_courses(portal_name=portal_name, course_name=course_name)
course = self._extract_course(response=results, course_name=course_name)
if not course:
results = self._my_courses(portal_name=portal_name)
course = self._extract_course(response=results, course_name=course_name)
if not course:
results = self._subscribed_collection_courses(portal_name=portal_name)
course = self._extract_course(response=results, course_name=course_name)
if not course:
results = self._archived_courses(portal_name=portal_name)
course = self._extract_course(response=results, course_name=course_name)
if not course or is_subscription_course:
course_id = self._extract_subscription_course_info(url)
course = self._extract_course_info_json(url, course_id)
if course:
return course.get("id"), course
if not course:
logger.fatal("Downloading course information, course id not found .. ")
logger.fatal(
"It seems either you are not enrolled or you have to visit the course atleast once while you are logged in.",
)
logger.info(
"Terminating Session...",
)
self.session.terminate()
logger.info(
"Session terminated.",
)
sys.exit(1)
def _parse_lecture(self, lecture: dict):
retVal = []
index = lecture.get("index") # this is lecture_counter
lecture_data = lecture.get("data")
asset = lecture_data.get("asset")
supp_assets = lecture_data.get("supplementary_assets")
if isinstance(asset, dict):
asset_type = asset.get("asset_type").lower() or asset.get("assetType").lower()
if asset_type == "article":
retVal.extend(self._extract_article(asset, index))
elif asset_type == "video":
pass
elif asset_type == "e-book":
retVal.extend(self._extract_ebook(asset, index))
elif asset_type == "file":
retVal.extend(self._extract_file(asset, index))
elif asset_type == "presentation":
retVal.extend(self._extract_ppt(asset, index))
elif asset_type == "audio":
retVal.extend(self._extract_audio(asset, index))
else:
logger.warning(f"Unknown asset type: {asset_type}")
if isinstance(supp_assets, list) and len(supp_assets) > 0:
retVal.extend(self._extract_supplementary_assets(supp_assets, index))