forked from Puyodead1/udemy-downloader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1797 lines (1653 loc) · 71.3 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
import argparse
import glob
import json
import os
import re
import subprocess
import sys
import time
import cloudscraper
import m3u8
import requests
import yt_dlp
from pathlib import Path
from html.parser import HTMLParser as compat_HTMLParser
from dotenv import load_dotenv
from requests.exceptions import ConnectionError as conn_error
from tqdm import tqdm
from utils import extract_kid
from vtt_to_srt import convert
from _version import __version__
from bs4 import BeautifulSoup
from pathvalidate import sanitize_filename
home_dir = os.getcwd()
download_dir = os.path.join(os.getcwd(), "out_dir")
saved_dir = os.path.join(os.getcwd(), "saved")
keyfile_path = os.path.join(os.getcwd(), "keyfile.json")
cookiefile_path = os.path.join(os.getcwd(), "cookies.txt")
retry = 3
cookies = ""
downloader = None
HEADERS = {
"Origin": "www.udemy.com",
# "User-Agent":
# "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0",
"Accept": "*/*",
"Accept-Encoding": None,
}
LOGIN_URL = "https://www.udemy.com/join/login-popup/?ref=&display_type=popup&loc"
LOGOUT_URL = "https://www.udemy.com/user/logout"
COURSE_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/cached-subscriber-curriculum-items?fields[asset]=results,title,external_url,time_estimation,download_urls,slide_urls,filename,asset_type,captions,media_license_token,course_is_drmed,media_sources,stream_urls,body&fields[chapter]=object_index,title,sort_order&fields[lecture]=id,title,object_index,asset,supplementary_assets,view_html&page_size=10000"
COURSE_INFO_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/"
COURSE_SEARCH = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title&page=1&page_size=500&search={course_name}"
SUBSCRIBED_COURSES = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses/?ordering=-last_accessed&fields[course]=id,title,url&page=1&page_size=12"
MY_COURSES_URL = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title&ordering=-last_accessed,-access_time&page=1&page_size=10000"
COLLECTION_URL = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses-collections/?collection_has_courses=True&course_limit=20&fields[course]=last_accessed_time,title,published_title&fields[user_has_subscribed_courses_collection]=@all&page=1&page_size=1000"
Path(download_dir).mkdir(parents=True, exist_ok=True)
Path(saved_dir).mkdir(parents=True, exist_ok=True)
# Get the keys
with open(keyfile_path, encoding="utf8", mode='r') as keyfile:
keyfile = keyfile.read()
keyfile = json.loads(keyfile)
# Read cookies from file
if os.path.exists(cookiefile_path):
with open(cookiefile_path, encoding="utf8", mode='r') as cookiefile:
cookies = cookiefile.read()
cookies = cookies.rstrip()
else:
print("No cookies.txt file was found, you won't be able to download subscription courses! You can ignore ignore this if you don't plan to download a course included in a subscription plan.")
class Udemy:
def __init__(self, access_token):
self.session = None
self.access_token = None
self.auth = UdemyAuth(cache_session=False)
if not self.session:
self.session, self.access_token = self.auth.authenticate(
access_token=access_token)
if self.session and self.access_token:
self.session._headers.update(
{"Authorization": "Bearer {}".format(self.access_token)})
self.session._headers.update({
"X-Udemy-Authorization":
"Bearer {}".format(self.access_token)
})
print("Login Success")
else:
print("Login Failure! You are probably missing an access token!")
sys.exit(1)
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_ppt(self, assets, lecture_counter):
_temp = []
download_urls = assets.get("download_urls")
filename = assets.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, assets, lecture_counter):
_temp = []
download_urls = assets.get("download_urls")
filename = assets.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, assets, lecture_counter):
_temp = []
download_urls = assets.get("download_urls")
filename = assets.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, assets, lecture_counter):
_temp = []
download_urls = assets.get("download_urls")
filename = assets.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"""
_temp = []
try:
resp = self.session._get(url)
resp.raise_for_status()
raw_data = resp.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
download_url = pl.uri
if height not in seen:
seen.add(height)
_temp.append({
"type": "hls",
"height": height,
"width": width,
"extension": "mp4",
"download_url": download_url,
})
except Exception as error:
print(f"Udemy Says : '{error}' while fetching hls streams..")
return _temp
def _extract_mpd(self, url):
"""extracts mpd streams"""
_temp = []
try:
ytdl = yt_dlp.YoutubeDL({
'quiet': True,
'no_warnings': True,
"allow_unplayable_formats": True
})
results = ytdl.extract_info(url,
download=False,
force_generic_extractor=True)
seen = set()
formats = results.get("formats")
format_id = results.get("format_id")
best_audio_format_id = format_id.split("+")[1]
best_audio = next((x for x in formats
if x.get("format_id") == best_audio_format_id),
None)
for f in formats:
if "video" in f.get("format_note"):
# is a video stream
format_id = f.get("format_id")
extension = f.get("ext")
height = f.get("height")
width = f.get("width")
if height and height not in seen:
seen.add(height)
_temp.append({
"type": "dash",
"height": str(height),
"width": str(width),
"format_id": f"{format_id},{best_audio_format_id}",
"extension": extension,
"download_url": f.get("manifest_url")
})
else:
# unknown format type
continue
except Exception as error:
print(f"Error fetching MPD streams: '{error}'")
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).json()
except conn_error as error:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {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, portal_name):
self.session._headers.update({"Referer": url})
url = COURSE_INFO_URL.format(
portal_name=portal_name, course_id=course_id)
try:
resp = self.session._get(url).json()
except conn_error as error:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
else:
return resp
def _extract_course_json(self, url, course_id, portal_name):
self.session._headers.update({"Referer": url})
url = COURSE_URL.format(portal_name=portal_name, course_id=course_id)
try:
resp = self.session._get(url)
if resp.status_code in [502, 503]:
print(
"> The course content is large, using large content extractor..."
)
resp = self._extract_large_course_content(url=url)
else:
resp = resp.json()
except conn_error as error:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception):
resp = self._extract_large_course_content(url=url)
return resp
else:
return resp
def _extract_large_course_content(self, url):
url = url.replace("10000", "50") if url.endswith("10000") else url
try:
data = self.session._get(url).json()
except conn_error as error:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
else:
_next = data.get("next")
while _next:
print("Downloading course information.. ")
try:
resp = self.session._get(_next).json()
except conn_error as error:
print(f"Udemy Says: 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)
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:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {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:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {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:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {error}")
time.sleep(0.8)
sys.exit(1)
else:
results = webpage.get("results", [])
return results
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:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {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:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {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:
print(f"Udemy Says: Connection error, {error}")
time.sleep(0.8)
sys.exit(1)
except (ValueError, Exception) as error:
print(f"Udemy Says: {error}")
time.sleep(0.8)
sys.exit(1)
else:
results = webpage.get("results", [])
return results
def _extract_course_info(self, url):
portal_name, course_name = self.extract_course_name(url)
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:
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:
print(
"Unable to extract arguments from course page! Make sure you have a cookies.txt file!")
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)
portal_name = self.extract_portal_name(url)
course = self._extract_course_info_json(
url, course_id, portal_name)
if course:
course.update({"portal_name": portal_name})
return course.get("id"), course
if not course:
print("Downloading course information, course id not found .. ")
print(
"It seems either you are not enrolled or you have to visit the course atleast once while you are logged in.",
)
print("Trying to logout now...", )
self.session.terminate()
print("Logged out successfully.", )
sys.exit(1)
class Session(object):
def __init__(self):
self._headers = HEADERS
self._session = requests.sessions.Session()
def _set_auth_headers(self, access_token=""):
self._headers["Authorization"] = "Bearer {}".format(access_token)
self._headers["X-Udemy-Authorization"] = "Bearer {}".format(
access_token)
self._headers[
"Cookie"] = cookies
def _get(self, url):
for i in range(10):
session = self._session.get(url, headers=self._headers)
if session.ok or session.status_code in [502, 503]:
return session
if not session.ok:
print('Failed request '+url)
print(
f"{session.status_code} {session.reason}, retrying (attempt {i} )...")
time.sleep(0.8)
def _post(self, url, data, redirect=True):
session = self._session.post(url,
data,
headers=self._headers,
allow_redirects=redirect)
if session.ok:
return session
if not session.ok:
raise Exception(f"{session.status_code} {session.reason}")
def terminate(self):
self._set_auth_headers()
return
# Thanks to a great open source utility youtube-dl ..
class HTMLAttributeParser(compat_HTMLParser): # pylint: disable=W
"""Trivial HTML parser to gather the attributes for a single element"""
def __init__(self):
self.attrs = {}
compat_HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
self.attrs = dict(attrs)
def extract_attributes(html_element):
"""Given a string for an HTML element such as
<el
a="foo" B="bar" c="&98;az" d=boz
empty= noval entity="&"
sq='"' dq="'"
>
Decode and return a dictionary of attributes.
{
'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
'empty': '', 'noval': None, 'entity': '&',
'sq': '"', 'dq': '\''
}.
NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
"""
parser = HTMLAttributeParser()
try:
parser.feed(html_element)
parser.close()
except Exception: # pylint: disable=W
pass
return parser.attrs
def hidden_inputs(html):
html = re.sub(r"<!--(?:(?!<!--).)*-->", "", html)
hidden_inputs = {} # pylint: disable=W
for entry in re.findall(r"(?i)(<input[^>]+>)", html):
attrs = extract_attributes(entry)
if not entry:
continue
if attrs.get("type") not in ("hidden", "submit"):
continue
name = attrs.get("name") or attrs.get("id")
value = attrs.get("value")
if name and value is not None:
hidden_inputs[name] = value
return hidden_inputs
def search_regex(pattern,
string,
name,
default=object(),
fatal=True,
flags=0,
group=None):
"""
Perform a regex search on the given string, using a single or a list of
patterns returning the first matching group.
In case of failure return a default value or raise a WARNING or a
RegexNotFoundError, depending on fatal, specifying the field name.
"""
if isinstance(pattern, str):
mobj = re.search(pattern, string, flags)
else:
for p in pattern:
mobj = re.search(p, string, flags)
if mobj:
break
_name = name
if mobj:
if group is None:
# return the first matching group
return next(g for g in mobj.groups() if g is not None)
else:
return mobj.group(group)
elif default is not object():
return default
elif fatal:
print("[-] Unable to extract %s" % _name)
exit(0)
else:
print("[-] unable to extract %s" % _name)
exit(0)
class UdemyAuth(object):
def __init__(self, username="", password="", cache_session=False):
self.username = username
self.password = password
self._cache = cache_session
self._session = Session()
self._cloudsc = cloudscraper.create_scraper()
def _form_hidden_input(self, form_id):
try:
resp = self._cloudsc.get(LOGIN_URL)
resp.raise_for_status()
webpage = resp.text
except conn_error as error:
raise error
else:
login_form = hidden_inputs(
search_regex(
r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>'
% form_id,
webpage,
"%s form" % form_id,
group="form",
))
login_form.update({
"email": self.username,
"password": self.password
})
return login_form
def authenticate(self, access_token=""):
if access_token:
self._session._set_auth_headers(access_token=access_token)
self._session._session.cookies.update(
{"access_token": access_token})
return self._session, access_token
else:
self._session._set_auth_headers()
return None, None
if not os.path.exists(download_dir):
os.makedirs(download_dir)
def durationtoseconds(period):
"""
@author Jayapraveen
"""
# Duration format in PTxDxHxMxS
if (period[:2] == "PT"):
period = period[2:]
day = int(period.split("D")[0] if 'D' in period else 0)
hour = int(period.split("H")[0].split("D")[-1] if 'H' in period else 0)
minute = int(
period.split("M")[0].split("H")[-1] if 'M' in period else 0)
second = period.split("S")[0].split("M")[-1]
print("Total time: " + str(day) + " days " + str(hour) + " hours " +
str(minute) + " minutes and " + str(second) + " seconds")
total_time = float(
str((day * 24 * 60 * 60) + (hour * 60 * 60) + (minute * 60) +
(int(second.split('.')[0]))) + '.' +
str(int(second.split('.')[-1])))
return total_time
else:
print("Duration Format Error")
return None
def cleanup(path):
"""
@author Jayapraveen
"""
leftover_files = glob.glob(path + '/*.mp4', recursive=True)
for file_list in leftover_files:
try:
os.remove(file_list)
except OSError:
print(f"Error deleting file: {file_list}")
os.removedirs(path)
def mux_process(video_title, video_filepath, audio_filepath, output_path):
"""
@author Jayapraveen
"""
if os.name == "nt":
command = "ffmpeg -y -i \"{}\" -i \"{}\" -acodec copy -vcodec copy -fflags +bitexact -map_metadata -1 -metadata title=\"{}\" \"{}\"".format(
video_filepath, audio_filepath, video_title, output_path)
else:
command = "nice -n 7 ffmpeg -y -i \"{}\" -i \"{}\" -acodec copy -vcodec copy -fflags +bitexact -map_metadata -1 -metadata title=\"{}\" \"{}\"".format(
video_filepath, audio_filepath, video_title, output_path)
os.system(command)
def decrypt(kid, in_filepath, out_filepath):
"""
@author Jayapraveen
"""
print("> Decrypting, this might take a minute...")
try:
key = keyfile[kid.lower()]
if (os.name == "nt"):
os.system(f"mp4decrypt --key 1:%s \"%s\" \"%s\"" %
(key, in_filepath, out_filepath))
else:
os.system(f"nice -n 7 mp4decrypt --key 1:%s \"%s\" \"%s\"" %
(key, in_filepath, out_filepath))
print("> Decryption complete")
except KeyError:
raise KeyError("Key not found")
def handle_segments(url, format_id, video_title,
output_path, lecture_file_name, concurrent_connections, chapter_dir, disable_ipv6):
os.chdir(os.path.join(chapter_dir))
file_name = lecture_file_name.replace("%", "").replace(".mp4", "")
video_filepath_enc = file_name + ".encrypted.mp4"
audio_filepath_enc = file_name + ".encrypted.m4a"
video_filepath_dec = file_name + ".decrypted.mp4"
audio_filepath_dec = file_name + ".decrypted.m4a"
print("> Downloading Lecture Tracks...")
args = [
"yt-dlp", "--force-generic-extractor", "--allow-unplayable-formats",
"--concurrent-fragments", f"{concurrent_connections}", "--downloader",
"aria2c", "--fixup", "never", "-k", "-o", f"{file_name}.encrypted.%(ext)s",
"-f", format_id, f"{url}"
]
if disable_ipv6:
args.append("--downloader-args")
args.append("aria2c:\"--disable-ipv6\"")
ret_code = subprocess.Popen(args).wait()
print("> Lecture Tracks Downloaded")
print("Return code: " + str(ret_code))
if ret_code != 0:
print("Return code from the downloader was non-0 (error), skipping!")
return
try:
video_kid = extract_kid(video_filepath_enc)
print("KID for video file is: " + video_kid)
except Exception as e:
print(f"Error extracting video kid: {e}")
return
try:
audio_kid = extract_kid(audio_filepath_enc)
print("KID for audio file is: " + audio_kid)
except Exception as e:
print(f"Error extracting audio kid: {e}")
return
try:
decrypt(video_kid, video_filepath_enc, video_filepath_dec)
decrypt(audio_kid, audio_filepath_enc, audio_filepath_dec)
mux_process(video_title, video_filepath_dec, audio_filepath_dec,
output_path)
os.remove(video_filepath_enc)
os.remove(audio_filepath_enc)
os.remove(video_filepath_dec)
os.remove(audio_filepath_dec)
os.chdir(home_dir)
except Exception as e:
print(f"Error: ", e)
def check_for_aria():
try:
subprocess.Popen(["aria2c", "-v"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).wait()
return True
except FileNotFoundError:
return False
except Exception as e:
print(
"> Unexpected exception while checking for Aria2c, please tell the program author about this! ",
e)
return True
def check_for_ffmpeg():
try:
subprocess.Popen(["ffmpeg"],
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL).wait()
return True
except FileNotFoundError:
return False
except Exception as e:
print(
"> Unexpected exception while checking for FFMPEG, please tell the program author about this! ",
e)
return True
def check_for_mp4decrypt():
try:
subprocess.Popen(["mp4decrypt"],
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL).wait()
return True
except FileNotFoundError:
return False
except Exception as e:
print(
"> Unexpected exception while checking for MP4Decrypt, please tell the program author about this! ",
e)
return True
def download(url, path, filename):
"""
@author Puyodead1
"""
file_size = int(requests.head(url).headers["Content-Length"])
if os.path.exists(path):
first_byte = os.path.getsize(path)
else:
first_byte = 0
if first_byte >= file_size:
return file_size
header = {"Range": "bytes=%s-%s" % (first_byte, file_size)}