├── .gitignore
├── LICENSE
├── assets
└── image-20240403163924034.png
├── gui.py
├── m3u8dl.py
├── main.py
├── readme.md
├── requirements.txt
└── yanhekt.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.zip
2 | __pycache__
3 | .vscode/
4 |
5 | temp/
6 | output/
7 |
8 | test.sh
9 |
10 | releases/
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Mozilla Public License Version 2.0
2 | ==================================
3 |
4 | 1. Definitions
5 | --------------
6 |
7 | 1.1. "Contributor"
8 | means each individual or legal entity that creates, contributes to
9 | the creation of, or owns Covered Software.
10 |
11 | 1.2. "Contributor Version"
12 | means the combination of the Contributions of others (if any) used
13 | by a Contributor and that particular Contributor's Contribution.
14 |
15 | 1.3. "Contribution"
16 | means Covered Software of a particular Contributor.
17 |
18 | 1.4. "Covered Software"
19 | means Source Code Form to which the initial Contributor has attached
20 | the notice in Exhibit A, the Executable Form of such Source Code
21 | Form, and Modifications of such Source Code Form, in each case
22 | including portions thereof.
23 |
24 | 1.5. "Incompatible With Secondary Licenses"
25 | means
26 |
27 | (a) that the initial Contributor has attached the notice described
28 | in Exhibit B to the Covered Software; or
29 |
30 | (b) that the Covered Software was made available under the terms of
31 | version 1.1 or earlier of the License, but not also under the
32 | terms of a Secondary License.
33 |
34 | 1.6. "Executable Form"
35 | means any form of the work other than Source Code Form.
36 |
37 | 1.7. "Larger Work"
38 | means a work that combines Covered Software with other material, in
39 | a separate file or files, that is not Covered Software.
40 |
41 | 1.8. "License"
42 | means this document.
43 |
44 | 1.9. "Licensable"
45 | means having the right to grant, to the maximum extent possible,
46 | whether at the time of the initial grant or subsequently, any and
47 | all of the rights conveyed by this License.
48 |
49 | 1.10. "Modifications"
50 | means any of the following:
51 |
52 | (a) any file in Source Code Form that results from an addition to,
53 | deletion from, or modification of the contents of Covered
54 | Software; or
55 |
56 | (b) any new file in Source Code Form that contains any Covered
57 | Software.
58 |
59 | 1.11. "Patent Claims" of a Contributor
60 | means any patent claim(s), including without limitation, method,
61 | process, and apparatus claims, in any patent Licensable by such
62 | Contributor that would be infringed, but for the grant of the
63 | License, by the making, using, selling, offering for sale, having
64 | made, import, or transfer of either its Contributions or its
65 | Contributor Version.
66 |
67 | 1.12. "Secondary License"
68 | means either the GNU General Public License, Version 2.0, the GNU
69 | Lesser General Public License, Version 2.1, the GNU Affero General
70 | Public License, Version 3.0, or any later versions of those
71 | licenses.
72 |
73 | 1.13. "Source Code Form"
74 | means the form of the work preferred for making modifications.
75 |
76 | 1.14. "You" (or "Your")
77 | means an individual or a legal entity exercising rights under this
78 | License. For legal entities, "You" includes any entity that
79 | controls, is controlled by, or is under common control with You. For
80 | purposes of this definition, "control" means (a) the power, direct
81 | or indirect, to cause the direction or management of such entity,
82 | whether by contract or otherwise, or (b) ownership of more than
83 | fifty percent (50%) of the outstanding shares or beneficial
84 | ownership of such entity.
85 |
86 | 2. License Grants and Conditions
87 | --------------------------------
88 |
89 | 2.1. Grants
90 |
91 | Each Contributor hereby grants You a world-wide, royalty-free,
92 | non-exclusive license:
93 |
94 | (a) under intellectual property rights (other than patent or trademark)
95 | Licensable by such Contributor to use, reproduce, make available,
96 | modify, display, perform, distribute, and otherwise exploit its
97 | Contributions, either on an unmodified basis, with Modifications, or
98 | as part of a Larger Work; and
99 |
100 | (b) under Patent Claims of such Contributor to make, use, sell, offer
101 | for sale, have made, import, and otherwise transfer either its
102 | Contributions or its Contributor Version.
103 |
104 | 2.2. Effective Date
105 |
106 | The licenses granted in Section 2.1 with respect to any Contribution
107 | become effective for each Contribution on the date the Contributor first
108 | distributes such Contribution.
109 |
110 | 2.3. Limitations on Grant Scope
111 |
112 | The licenses granted in this Section 2 are the only rights granted under
113 | this License. No additional rights or licenses will be implied from the
114 | distribution or licensing of Covered Software under this License.
115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a
116 | Contributor:
117 |
118 | (a) for any code that a Contributor has removed from Covered Software;
119 | or
120 |
121 | (b) for infringements caused by: (i) Your and any other third party's
122 | modifications of Covered Software, or (ii) the combination of its
123 | Contributions with other software (except as part of its Contributor
124 | Version); or
125 |
126 | (c) under Patent Claims infringed by Covered Software in the absence of
127 | its Contributions.
128 |
129 | This License does not grant any rights in the trademarks, service marks,
130 | or logos of any Contributor (except as may be necessary to comply with
131 | the notice requirements in Section 3.4).
132 |
133 | 2.4. Subsequent Licenses
134 |
135 | No Contributor makes additional grants as a result of Your choice to
136 | distribute the Covered Software under a subsequent version of this
137 | License (see Section 10.2) or under the terms of a Secondary License (if
138 | permitted under the terms of Section 3.3).
139 |
140 | 2.5. Representation
141 |
142 | Each Contributor represents that the Contributor believes its
143 | Contributions are its original creation(s) or it has sufficient rights
144 | to grant the rights to its Contributions conveyed by this License.
145 |
146 | 2.6. Fair Use
147 |
148 | This License is not intended to limit any rights You have under
149 | applicable copyright doctrines of fair use, fair dealing, or other
150 | equivalents.
151 |
152 | 2.7. Conditions
153 |
154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155 | in Section 2.1.
156 |
157 | 3. Responsibilities
158 | -------------------
159 |
160 | 3.1. Distribution of Source Form
161 |
162 | All distribution of Covered Software in Source Code Form, including any
163 | Modifications that You create or to which You contribute, must be under
164 | the terms of this License. You must inform recipients that the Source
165 | Code Form of the Covered Software is governed by the terms of this
166 | License, and how they can obtain a copy of this License. You may not
167 | attempt to alter or restrict the recipients' rights in the Source Code
168 | Form.
169 |
170 | 3.2. Distribution of Executable Form
171 |
172 | If You distribute Covered Software in Executable Form then:
173 |
174 | (a) such Covered Software must also be made available in Source Code
175 | Form, as described in Section 3.1, and You must inform recipients of
176 | the Executable Form how they can obtain a copy of such Source Code
177 | Form by reasonable means in a timely manner, at a charge no more
178 | than the cost of distribution to the recipient; and
179 |
180 | (b) You may distribute such Executable Form under the terms of this
181 | License, or sublicense it under different terms, provided that the
182 | license for the Executable Form does not attempt to limit or alter
183 | the recipients' rights in the Source Code Form under this License.
184 |
185 | 3.3. Distribution of a Larger Work
186 |
187 | You may create and distribute a Larger Work under terms of Your choice,
188 | provided that You also comply with the requirements of this License for
189 | the Covered Software. If the Larger Work is a combination of Covered
190 | Software with a work governed by one or more Secondary Licenses, and the
191 | Covered Software is not Incompatible With Secondary Licenses, this
192 | License permits You to additionally distribute such Covered Software
193 | under the terms of such Secondary License(s), so that the recipient of
194 | the Larger Work may, at their option, further distribute the Covered
195 | Software under the terms of either this License or such Secondary
196 | License(s).
197 |
198 | 3.4. Notices
199 |
200 | You may not remove or alter the substance of any license notices
201 | (including copyright notices, patent notices, disclaimers of warranty,
202 | or limitations of liability) contained within the Source Code Form of
203 | the Covered Software, except that You may alter any license notices to
204 | the extent required to remedy known factual inaccuracies.
205 |
206 | 3.5. Application of Additional Terms
207 |
208 | You may choose to offer, and to charge a fee for, warranty, support,
209 | indemnity or liability obligations to one or more recipients of Covered
210 | Software. However, You may do so only on Your own behalf, and not on
211 | behalf of any Contributor. You must make it absolutely clear that any
212 | such warranty, support, indemnity, or liability obligation is offered by
213 | You alone, and You hereby agree to indemnify every Contributor for any
214 | liability incurred by such Contributor as a result of warranty, support,
215 | indemnity or liability terms You offer. You may include additional
216 | disclaimers of warranty and limitations of liability specific to any
217 | jurisdiction.
218 |
219 | 4. Inability to Comply Due to Statute or Regulation
220 | ---------------------------------------------------
221 |
222 | If it is impossible for You to comply with any of the terms of this
223 | License with respect to some or all of the Covered Software due to
224 | statute, judicial order, or regulation then You must: (a) comply with
225 | the terms of this License to the maximum extent possible; and (b)
226 | describe the limitations and the code they affect. Such description must
227 | be placed in a text file included with all distributions of the Covered
228 | Software under this License. Except to the extent prohibited by statute
229 | or regulation, such description must be sufficiently detailed for a
230 | recipient of ordinary skill to be able to understand it.
231 |
232 | 5. Termination
233 | --------------
234 |
235 | 5.1. The rights granted under this License will terminate automatically
236 | if You fail to comply with any of its terms. However, if You become
237 | compliant, then the rights granted under this License from a particular
238 | Contributor are reinstated (a) provisionally, unless and until such
239 | Contributor explicitly and finally terminates Your grants, and (b) on an
240 | ongoing basis, if such Contributor fails to notify You of the
241 | non-compliance by some reasonable means prior to 60 days after You have
242 | come back into compliance. Moreover, Your grants from a particular
243 | Contributor are reinstated on an ongoing basis if such Contributor
244 | notifies You of the non-compliance by some reasonable means, this is the
245 | first time You have received notice of non-compliance with this License
246 | from such Contributor, and You become compliant prior to 30 days after
247 | Your receipt of the notice.
248 |
249 | 5.2. If You initiate litigation against any entity by asserting a patent
250 | infringement claim (excluding declaratory judgment actions,
251 | counter-claims, and cross-claims) alleging that a Contributor Version
252 | directly or indirectly infringes any patent, then the rights granted to
253 | You by any and all Contributors for the Covered Software under Section
254 | 2.1 of this License shall terminate.
255 |
256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257 | end user license agreements (excluding distributors and resellers) which
258 | have been validly granted by You or Your distributors under this License
259 | prior to termination shall survive termination.
260 |
261 | ************************************************************************
262 | * *
263 | * 6. Disclaimer of Warranty *
264 | * ------------------------- *
265 | * *
266 | * Covered Software is provided under this License on an "as is" *
267 | * basis, without warranty of any kind, either expressed, implied, or *
268 | * statutory, including, without limitation, warranties that the *
269 | * Covered Software is free of defects, merchantable, fit for a *
270 | * particular purpose or non-infringing. The entire risk as to the *
271 | * quality and performance of the Covered Software is with You. *
272 | * Should any Covered Software prove defective in any respect, You *
273 | * (not any Contributor) assume the cost of any necessary servicing, *
274 | * repair, or correction. This disclaimer of warranty constitutes an *
275 | * essential part of this License. No use of any Covered Software is *
276 | * authorized under this License except under this disclaimer. *
277 | * *
278 | ************************************************************************
279 |
280 | ************************************************************************
281 | * *
282 | * 7. Limitation of Liability *
283 | * -------------------------- *
284 | * *
285 | * Under no circumstances and under no legal theory, whether tort *
286 | * (including negligence), contract, or otherwise, shall any *
287 | * Contributor, or anyone who distributes Covered Software as *
288 | * permitted above, be liable to You for any direct, indirect, *
289 | * special, incidental, or consequential damages of any character *
290 | * including, without limitation, damages for lost profits, loss of *
291 | * goodwill, work stoppage, computer failure or malfunction, or any *
292 | * and all other commercial damages or losses, even if such party *
293 | * shall have been informed of the possibility of such damages. This *
294 | * limitation of liability shall not apply to liability for death or *
295 | * personal injury resulting from such party's negligence to the *
296 | * extent applicable law prohibits such limitation. Some *
297 | * jurisdictions do not allow the exclusion or limitation of *
298 | * incidental or consequential damages, so this exclusion and *
299 | * limitation may not apply to You. *
300 | * *
301 | ************************************************************************
302 |
303 | 8. Litigation
304 | -------------
305 |
306 | Any litigation relating to this License may be brought only in the
307 | courts of a jurisdiction where the defendant maintains its principal
308 | place of business and such litigation shall be governed by laws of that
309 | jurisdiction, without reference to its conflict-of-law provisions.
310 | Nothing in this Section shall prevent a party's ability to bring
311 | cross-claims or counter-claims.
312 |
313 | 9. Miscellaneous
314 | ----------------
315 |
316 | This License represents the complete agreement concerning the subject
317 | matter hereof. If any provision of this License is held to be
318 | unenforceable, such provision shall be reformed only to the extent
319 | necessary to make it enforceable. Any law or regulation which provides
320 | that the language of a contract shall be construed against the drafter
321 | shall not be used to construe this License against a Contributor.
322 |
323 | 10. Versions of the License
324 | ---------------------------
325 |
326 | 10.1. New Versions
327 |
328 | Mozilla Foundation is the license steward. Except as provided in Section
329 | 10.3, no one other than the license steward has the right to modify or
330 | publish new versions of this License. Each version will be given a
331 | distinguishing version number.
332 |
333 | 10.2. Effect of New Versions
334 |
335 | You may distribute the Covered Software under the terms of the version
336 | of the License under which You originally received the Covered Software,
337 | or under the terms of any subsequent version published by the license
338 | steward.
339 |
340 | 10.3. Modified Versions
341 |
342 | If you create software not governed by this License, and you want to
343 | create a new license for such software, you may create and use a
344 | modified version of this License if you rename the license and remove
345 | any references to the name of the license steward (except to note that
346 | such modified license differs from this License).
347 |
348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary
349 | Licenses
350 |
351 | If You choose to distribute Source Code Form that is Incompatible With
352 | Secondary Licenses under the terms of this version of the License, the
353 | notice described in Exhibit B of this License must be attached.
354 |
355 | Exhibit A - Source Code Form License Notice
356 | -------------------------------------------
357 |
358 | This Source Code Form is subject to the terms of the Mozilla Public
359 | License, v. 2.0. If a copy of the MPL was not distributed with this
360 | file, You can obtain one at http://mozilla.org/MPL/2.0/.
361 |
362 | If it is not possible or desirable to put the notice in a particular
363 | file, then You may include the notice in a location (such as a LICENSE
364 | file in a relevant directory) where a recipient would be likely to look
365 | for such a notice.
366 |
367 | You may add additional accurate notices of copyright ownership.
368 |
369 | Exhibit B - "Incompatible With Secondary Licenses" Notice
370 | ---------------------------------------------------------
371 |
372 | This Source Code Form is "Incompatible With Secondary Licenses", as
373 | defined by the Mozilla Public License, v. 2.0.
374 |
--------------------------------------------------------------------------------
/assets/image-20240403163924034.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GDDG08/YanHeKT_Downloader/698bf350dabd3bb69fc65d7d28bba234ef1a0671/assets/image-20240403163924034.png
--------------------------------------------------------------------------------
/gui.py:
--------------------------------------------------------------------------------
1 | '''
2 | Project :
3 | FilePath : \OPENSOURCE\gui.py
4 | Descripttion :
5 | Author : GDDG08
6 | Date : 2024-04-03 12:53:30
7 | LastEditors : GDDG08
8 | LastEditTime : 2024-04-04 00:55:12
9 | '''
10 | import re
11 | import threading
12 | from yanhekt import YanHeKT
13 | import PySimpleGUI as sg
14 |
15 |
16 | class GUI:
17 | def __init__(self):
18 | self.window = None
19 | self.init_ui()
20 | self.yanhekt = None
21 | self.td = None
22 |
23 | def init_ui(self):
24 | # sg.theme('DarkAmber') # Set a theme for the GUI
25 | sg.theme('DarkTeal7')
26 |
27 | frame_course_info = [
28 |
29 | [
30 | sg.Column([
31 | [sg.Text('Web Link:', expand_x=True), sg.Input(key='WEB_LINK',
32 | default_text="https://www.yanhekt.cn/course/11111", enable_events=True, size=(35, 2), expand_x=True)],
33 | [sg.Text('Course ID:', expand_x=True), sg.Input(key='COURSE_ID', enable_events=True, size=(35, 2), expand_x=True)]
34 | ]),
35 | sg.Column([
36 | # [sg.Button('Get Course ID', expand_x=True, disabled=True)],
37 | [sg.Button('Get Course Info', expand_x=True, disabled=True)]
38 | ])
39 | ],
40 | [sg.HorizontalSeparator()],
41 | [
42 | sg.Column([
43 | [sg.Text('Course Name:'), sg.Text('', key='COURSE_NAME'), sg.Text('Professor:'), sg.Text('', key='PROFESSOR')],
44 | [sg.Listbox(values=[], size=(50, 8), expand_x=True, key='LESSON_LIST',
45 | enable_events=True, select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED)],
46 | [sg.Text('use Ctrl or Shift or Drag to select multiple')],
47 | [sg.Text('Ctrl + A to select all')],
48 | ], pad=(25, 0), expand_x=True, element_justification='center')],
49 | ]
50 |
51 | # frame_lesson_selection = [
52 | # [sg.Radio('All', group_id="Selection", key='ALL', default=True)],
53 | # [sg.Radio('List', group_id="Selection", key='LIST')],
54 | # [sg.Checkbox('Lesson 1', key='LESSON_1'), sg.Checkbox('Lesson 2', key='LESSON_2'), sg.Checkbox('Lesson 3', key='LESSON_3')],
55 | # [sg.Radio('Range', group_id="Selection", key='RANGE')],
56 | # [sg.Text('from'), sg.Spin([i for i in range(1, 10)], initial_value=0, key='RANGE_START'),
57 | # sg.Text('to'), sg.Spin([i for i in range(1, 10)], initial_value=1, key='RANGE_END')],
58 |
59 | # ]
60 |
61 | frame_settings = [
62 | [sg.Text('Video Type:'), sg.Radio('Dual', group_id="RADIO_VIDEO_TYPE", key='DUAL', default=True), sg.Radio(
63 | 'VGA', group_id="RADIO_VIDEO_TYPE", key='VGA'), sg.Radio('Video', group_id="RADIO_VIDEO_TYPE", key='VIDEO')],
64 | [sg.Text('Output Directory:'), sg.Input("./Downloads", size=(30, 2), key="OUTPUT_DIR", expand_x=True),
65 | sg.FolderBrowse(key='OUTPUT_DIR_BROWSE', initial_folder="./")],
66 | [sg.Checkbox('Skip Existing', default=True, key='SKIP_EXISTING')],
67 | ]
68 |
69 | # Layout definition
70 | layout = [
71 | [sg.Frame('Course Information', frame_course_info, expand_x=True)],
72 | # [sg.Frame('Lesson Selection', frame_lesson_selection)],
73 | [sg.Frame('Settings', frame_settings, expand_x=True)],
74 |
75 | [sg.Column([
76 | [sg.Button('Download Lessons', disabled=True)],
77 | [sg.Output(size=(60, 10), expand_x=True, key='OUTPUT')],
78 | [sg.ProgressBar(100, orientation='h', size=(40, 10), expand_x=True, key='PROGRESS_BAR')]
79 | ], expand_x=True, element_justification='center')]
80 |
81 | ]
82 |
83 | # Create the Window
84 | self.window = sg.Window('YanHeKT Downloader', layout)
85 |
86 | def event_loop(self):
87 | while True:
88 | event, values = self.window.read()
89 | if event == sg.WIN_CLOSED: # If user closes window
90 | if self.td:
91 | self.td.join()
92 | break
93 | try:
94 | # if event == 'Get Course ID':
95 | # courseID = values['WEB_LINK'].split('/')[-1]
96 | # if (courseID.isdigit()):
97 | # self.window['COURSE_ID'].update(courseID)
98 | # self.window['Get Course Info'].update(disabled=False)
99 | if event == 'Get Course Info':
100 | if not values['COURSE_ID'].isdigit():
101 | sg.popup_error("Invalid Course ID")
102 | continue
103 | else:
104 | self.window['Download Lessons'].update(disabled=True)
105 |
106 | self.yanhekt = YanHeKT(values['COURSE_ID'])
107 | courseInfo, lessonList = self.yanhekt.getCourseInfo()
108 | self.window['COURSE_NAME'].update(courseInfo['name_zh'])
109 | self.window['PROFESSOR'].update(courseInfo['professors'][0]['name'])
110 |
111 | lessonTitles = [lesson['title'] for lesson in lessonList]
112 | self.window['LESSON_LIST'].update(values=[tittle for tittle in lessonTitles])
113 | elif event == 'Download Lessons':
114 | self.window['Download Lessons'].update(disabled=True)
115 | self.window['PROGRESS_BAR'].update(0)
116 |
117 | self.window['OUTPUT'].update("Downloading...\n\n")
118 | # print(values)
119 | lessonTitles = [lesson['title'] for lesson in self.yanhekt.lessonList]
120 |
121 | selected_lessons = [i for i, tittle in enumerate(lessonTitles) if tittle in values['LESSON_LIST']]
122 | self.yanhekt.updateArgs(_all=False, _list=selected_lessons, _range=False,
123 | _dual=values['DUAL'], _vga=values['VGA'], _video=values['VIDEO'], _skip=values['SKIP_EXISTING'], _dir=values['OUTPUT_DIR'])
124 | self.do_download()
125 | elif event == 'WEB_LINK':
126 | # print(values['WEB_LINK'])
127 | if values['WEB_LINK']:
128 | # self.window['Get Course ID'].update(disabled=False)
129 |
130 | rex = re.search(r'(?<=course/)(\d+)', values['WEB_LINK'])
131 |
132 | if (rex):
133 | self.window['COURSE_ID'].update(rex.group(0))
134 | self.window['Get Course Info'].update(disabled=False)
135 | else:
136 | self.window['COURSE_ID'].update("")
137 | self.window['Get Course Info'].update(disabled=True)
138 | # else:
139 | # self.window['Get Course ID'].update(disabled=True)
140 | elif event == 'COURSE_ID':
141 | if values['COURSE_ID']:
142 | self.window['Get Course Info'].update(disabled=False)
143 | else:
144 | self.window['Get Course Info'].update(disabled=True)
145 | elif event == 'LESSON_LIST':
146 | if (len(values['LESSON_LIST']) > 0):
147 | self.window['Download Lessons'].update(disabled=False)
148 | else:
149 | self.window['Download Lessons'].update(disabled=True)
150 |
151 | except Exception as e:
152 | sg.popup_error(f'An error occurred: {str(e)}')
153 |
154 | self.window.close()
155 |
156 | def do_download(self):
157 | # new thread
158 | self.td = threading.Thread(target=self.yanhekt.download, args=(self.callback_download, self.callback_progress))
159 | self.td.start()
160 |
161 | def callback_download(self, isFinished):
162 | self.window['Download Lessons'].update(disabled=False)
163 | # self.window['OUTPUT'].update(f"Download success? {isFinished}\n\n")
164 |
165 | def callback_progress(self, current, total):
166 | self.window['PROGRESS_BAR'].update(current/total*100)
167 |
168 | if __name__ == '__main__':
169 | gui = GUI()
170 | gui.event_loop()
--------------------------------------------------------------------------------
/m3u8dl.py:
--------------------------------------------------------------------------------
1 | '''
2 | Project :
3 | FilePath : \OPENSOURCE\m3u8dl.py
4 | Descripttion :
5 | Author : GDDG08
6 | Date : 2022-11-07 12:09:26
7 | LastEditors : GDDG08
8 | LastEditTime : 2024-04-03 15:39:46
9 | '''
10 | import os
11 | import re
12 | import sys
13 | import queue
14 | import base64
15 | import platform
16 | import requests
17 | import urllib3
18 | import time
19 | from concurrent.futures import ThreadPoolExecutor
20 | from hashlib import md5
21 |
22 |
23 | class ThreadPoolExecutorWithQueueSizeLimit(ThreadPoolExecutor):
24 | """
25 | 实现多线程有界队列
26 | 队列数为线程数的2倍
27 | """
28 |
29 | def __init__(self, max_workers=None, *args, **kwargs):
30 | super().__init__(max_workers, *args, **kwargs)
31 | self._work_queue = queue.Queue(max_workers * 2)
32 |
33 |
34 | def make_sum():
35 | ts_num = 0
36 | while True:
37 | yield ts_num
38 | ts_num += 1
39 |
40 |
41 | class M3u8Download:
42 | """
43 | :param url: 完整的m3u8文件链接 如"https://www.bilibili.com/example/index.m3u8"
44 | :param name: 保存m3u8的文件名 如"index"
45 | :param max_workers: 多线程最大线程数
46 | :param num_retries: 重试次数
47 | :param base64_key: base64编码的字符串
48 | """
49 |
50 | def __init__(self, url, workDir, name, max_workers=64, num_retries=16, base64_key=None, callback_progress=None):
51 |
52 | self._url = url
53 | self._token = None
54 | self._name = name
55 | self._max_workers = max_workers
56 | self._num_retries = num_retries
57 | self._workDir = os.path.join(workDir, self._name)
58 | self._file_path = os.path.join(os.getcwd(), "temp", self._name)
59 | self._front_url = None
60 | self._ts_url_list = []
61 | self._success_sum = 0
62 | self._ts_sum = 0
63 | self._key = base64.b64decode(base64_key.encode()) if base64_key else None
64 | self._headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52',
65 | 'Origin': 'https://www.yanhekt.cn',
66 | 'referer': 'https://www.yanhekt.cn',
67 | }
68 | self._callback_progress = callback_progress
69 |
70 | urllib3.disable_warnings()
71 |
72 | self.sign_prefix = "1tJrMwNq3h0yLgx86Rued2J1tFc"
73 | self._url = self.encryptURL(self._url)
74 | # self.refreshSignature()
75 |
76 | self.get_m3u8_info(self._url, self._num_retries)
77 | # print('Downloading: %s' % self._name, 'Save path: %s' % self._file_path, sep='\n')
78 | with ThreadPoolExecutorWithQueueSizeLimit(self._max_workers) as pool:
79 | for k, ts_url in enumerate(self._ts_url_list):
80 | pool.submit(self.download_ts, ts_url, os.path.join(self._file_path, str(k)), self._num_retries)
81 | if self._success_sum == self._ts_sum:
82 | self.output_mp4()
83 | self.delete_file()
84 | print("SUCCESS")
85 |
86 | def getSignature(self):
87 | timestamp = str(int(time.time()))
88 | sign_org = "_".join([self.sign_prefix, 'v1', timestamp])
89 | signature = md5(sign_org.encode()).hexdigest()
90 | # print(timestamp, signature)
91 | return timestamp, signature
92 |
93 | def refreshSignature(self):
94 | self.token = self.getToken()
95 | self.timestamp, self.signature = self.getSignature()
96 |
97 | def encryptURL(self, url):
98 | sign_org = "_".join([self.sign_prefix, '100'])
99 | signature = md5(sign_org.encode()).hexdigest()
100 |
101 | index = url.rfind('/')
102 | if index > -1:
103 | l = url[:index]
104 | r = url[index:]
105 | return l + '/' + signature + r
106 | return url
107 |
108 | def getToken(self):
109 | if self._token == None:
110 | headers = {
111 | "Xdomain-Client": "web_user",
112 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52',
113 | 'Origin': 'https://www.yanhekt.cn',
114 | }
115 |
116 | req = requests.get("https://cbiz.yanhekt.cn/v1/auth/video/token?id=0",
117 | headers=headers)
118 | data = req.json()['data']
119 | self._token = data['token']
120 | return self._token
121 |
122 | def get_m3u8_info(self, m3u8_url, num_retries):
123 | """
124 | 获取m3u8信息
125 | """
126 | self.refreshSignature()
127 | url = m3u8_url+"?Xvideo_Token="+self.token+"&Xclient_Timestamp=" + self.timestamp+"&Xclient_Signature=" + \
128 | self.signature+"&Xclient_Version=v1&Platform=yhkt_user"
129 | try:
130 | with requests.get(url, timeout=(3, 30), verify=False, headers=self._headers) as res:
131 | self._front_url = res.url.split(res.request.path_url)[0]
132 | if "EXT-X-STREAM-INF" in res.text: # 判定为顶级M3U8文件
133 | for line in res.text.split('\n'):
134 | if "#" in line:
135 | continue
136 | elif line.startswith('http'):
137 | self._url = line
138 | elif line.startswith('/'):
139 | self._url = self._front_url + line
140 | else:
141 | self._url = self._url.rsplit("/", 1)[0] + '/' + line
142 | self.get_m3u8_info(self._url, self._num_retries)
143 | else:
144 | m3u8_text_str = res.text
145 | self.get_ts_url(m3u8_text_str)
146 | except Exception as e:
147 | print(e)
148 | if num_retries > 0:
149 | self.get_m3u8_info(m3u8_url, num_retries - 1)
150 |
151 | def get_ts_url(self, m3u8_text_str):
152 | """
153 | 获取每一个ts文件的链接
154 | """
155 | if not os.path.exists(self._file_path):
156 | os.makedirs(self._file_path)
157 | new_m3u8_str = ''
158 | ts = make_sum()
159 | for line in m3u8_text_str.split('\n'):
160 | if "#" in line:
161 | if "EXT-X-KEY" in line and "URI=" in line:
162 | if os.path.exists(os.path.join(self._file_path, 'key')):
163 | continue
164 | key = self.download_key(line, 5)
165 | if key:
166 | new_m3u8_str += f'{key}\n'
167 | continue
168 | new_m3u8_str += f'{line}\n'
169 | if "EXT-X-ENDLIST" in line:
170 | break
171 | else:
172 | if line.startswith('http'):
173 | self._ts_url_list.append(line)
174 | elif line.startswith('/'):
175 | self._ts_url_list.append(self._front_url + line)
176 | else:
177 | self._ts_url_list.append(self._url.rsplit("/", 1)[0] + '/' + line)
178 | new_m3u8_str += (os.path.join(self._file_path, str(next(ts))) + '\n')
179 | self._ts_sum = next(ts)
180 | with open(self._file_path + '.m3u8', "wb") as f:
181 | if platform.system() == 'Windows':
182 | # f.write(new_m3u8_str.encode('gbk'))
183 | f.write(new_m3u8_str.encode('utf-8'))
184 | else:
185 | f.write(new_m3u8_str.encode('utf-8'))
186 |
187 | def download_ts(self, ts_url, name, num_retries):
188 | """
189 | 下载 .ts 文件
190 | """
191 |
192 | self.refreshSignature()
193 | ts_url = ts_url.split('\n')[0]+"?Xvideo_Token="+self.token+"&Xclient_Timestamp=" + \
194 | self.timestamp+"&Xclient_Signature="+self.signature+"&Xclient_Version=v1&Platform=yhkt_user"
195 | try:
196 | if not os.path.exists(name):
197 | with requests.get(ts_url, stream=True, timeout=(5, 60), verify=False, headers=self._headers) as res:
198 | if res.status_code == 200:
199 | with open(name, "wb") as ts:
200 | for chunk in res.iter_content(chunk_size=1024):
201 | if chunk:
202 | ts.write(chunk)
203 | self._success_sum += 1
204 | # sys.stdout.write('\r[%-25s](%d/%d)' % ("*" * (100 * self._success_sum // self._ts_sum // 4),
205 | # self._success_sum, self._ts_sum))
206 | # sys.stdout.flush()
207 | if self._callback_progress:
208 | self._callback_progress(self._success_sum, self._ts_sum)
209 | else:
210 | self.refreshSignature()
211 | self.download_ts(ts_url, name, num_retries - 1)
212 | else:
213 | self._success_sum += 1
214 | except Exception:
215 | if os.path.exists(name):
216 | print(name)
217 | os.remove(name)
218 | if num_retries > 0:
219 | self.download_ts(ts_url, name, num_retries - 1)
220 |
221 | def download_key(self, key_line, num_retries):
222 | """
223 | 下载key文件
224 | """
225 | mid_part = re.search(r"URI=[\'|\"].*?[\'|\"]", key_line).group()
226 | may_key_url = mid_part[5:-1]
227 | if self._key:
228 | with open(os.path.join(self._file_path, 'key'), 'wb') as f:
229 | f.write(self._key)
230 | return f'{key_line.split(mid_part)[0]}URI="./{self._name}/key"'
231 | if may_key_url.startswith('http'):
232 | true_key_url = may_key_url
233 | elif may_key_url.startswith('/'):
234 | true_key_url = self._front_url + may_key_url
235 | else:
236 | true_key_url = self._url.rsplit("/", 1)[0] + '/' + may_key_url
237 | try:
238 | with requests.get(true_key_url, timeout=(5, 30), verify=False, headers=self._headers) as res:
239 | with open(os.path.join(self._file_path, 'key'), 'wb') as f:
240 | f.write(res.content)
241 | return f'{key_line.split(mid_part)[0]}URI="./{self._name}/key"{key_line.split(mid_part)[-1]}'
242 | except Exception as e:
243 | print(e)
244 | if os.path.exists(os.path.join(self._file_path, 'key')):
245 | os.remove(os.path.join(self._file_path, 'key'))
246 | print("加密视频,无法加载key,揭秘失败")
247 | if num_retries > 0:
248 | self.download_key(key_line, num_retries - 1)
249 |
250 | def output_mp4(self):
251 | """
252 | 合并.ts文件,输出mp4格式视频,需要ffmpeg
253 | """
254 | #
255 | cmd = f'''ffmpeg -y -loglevel quiet -allowed_extensions ALL -i "{self._file_path}.m3u8" -acodec \
256 | copy -vcodec copy -f mp4 "{self._workDir}.mp4"'''
257 | # print(cmd)
258 | os.system(cmd)
259 |
260 | def delete_file(self):
261 | file = os.listdir(self._file_path)
262 | for item in file:
263 | os.remove(os.path.join(self._file_path, item))
264 | os.removedirs(self._file_path)
265 | os.remove(self._file_path + '.m3u8')
266 |
267 |
268 | if __name__ == "__main__":
269 | # url_list = input("输入url,若同时输入多个url时要用空格分开:").split()
270 | # name_list = input("输入name,若同时输入多个name要用空格分开:").split()
271 | # # 如果M3U8_URL的数量 ≠ SAVE_NAME的数量
272 | # # 下载一部电视剧时,只需要输入一个name就可以了
273 | # sta = len(url_list) == len(name_list)
274 | # for i, u in enumerate(url_list):
275 | # M3u8Download(u,
276 | # name_list[i] if sta else f"{name_list[0]}{i + 1:02}",
277 | # max_workers=64,
278 | # num_retries=10,
279 | # # base64_key='5N12sDHDVcx1Hqnagn4NJg=='
280 | # )
281 | pass
282 | # M3u8Download("https://*.m3u8", "./", "test.mp4")
283 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | '''
2 | Project :
3 | FilePath : \OPENSOURCE\main.py
4 | Descripttion :
5 | Author : GDDG08
6 | Date : 2022-11-08 02:07:44
7 | LastEditors : GDDG08
8 | LastEditTime : 2024-04-03 16:10:23
9 | '''
10 | import sys
11 | import argparse
12 | from gui import GUI
13 | from yanhekt import YanHeKT
14 |
15 |
16 | def configArgs():
17 | parser = argparse.ArgumentParser(description='GDDG08/YanHeKT_Downloader')
18 | parser.add_argument('courseID', type=int, help='Course ID of YanHeKT')
19 |
20 | group_lession = parser.add_argument_group('Lesson Selection', 'IF NONE, PRINT LESSON LIST AND EXIT.')
21 | group_lession_exc = group_lession.add_mutually_exclusive_group()
22 | group_lession_exc.add_argument('-A', '--all', action='store_true', help='Download all lessons')
23 | group_lession_exc.add_argument('-L', '--list', type=int, nargs='+', metavar='i', help='Select of lesson index (e.g., --list 1 2 4)')
24 | group_lession_exc.add_argument('-R', '--range', type=int, nargs=2, action='append', metavar='i',
25 | help='Select range of lessons (e.g., --range 3 5 for [3,5))')
26 |
27 | group_video = parser.add_argument_group('Video Type')
28 | group_video_exc = group_video.add_mutually_exclusive_group()
29 | group_video_exc.add_argument('-D', '--dual', action='store_true', help='Download both VGA(PC) and Video (default)')
30 | group_video_exc.add_argument('-G', '--vga', action='store_true', help='Download VGA(PC) only')
31 | group_video_exc.add_argument('-V', '--video', action='store_true', help='Download Video only')
32 |
33 | group_config = parser.add_argument_group('Configurations')
34 | group_config.add_argument('-S', '--skip', action='store_true', help='Skip existing files')
35 | group_config.add_argument('--dir', type=str, default='./', help='Output directory (e.g., --dir ./output)')
36 | group_config.add_argument('--max-workers', type=int, default=32, metavar='num', help='Max workers for downloading (default: 32)')
37 |
38 | return parser
39 |
40 |
41 | def parseArgs(parser):
42 | # force to show help message if no arguments provided
43 | if len(sys.argv) == 1:
44 | parser.print_help()
45 | sys.exit(1)
46 | else:
47 | args = parser.parse_args()
48 | # merge list and range arguments
49 | if not (args.vga or args.video):
50 | args.dual = True
51 |
52 | return args
53 |
54 |
55 | def printArgs(args):
56 | print("="*10+" YanHeKT_Downloader "+"="*10)
57 | print(f"Course ID: {args.courseID}")
58 | print(f"Lesson Selection: {'ALL' if args.all else args.list or args.range}")
59 | print(f"Video Type: {'VGA & Video' if args.dual else 'VGA' if args.vga else 'Video'}")
60 | print(f"Skip existing files: {args.skip}")
61 | print(f"Output Directory: {args.dir}")
62 | print("="*40+"\n")
63 |
64 |
65 | def progressPrint(current, total):
66 | sys.stdout.write('\r[%-25s](%d/%d)' % ("*" * (100 * current // total // 4),
67 | current, total))
68 | sys.stdout.flush()
69 |
70 |
71 | def runCli():
72 | parser = configArgs()
73 | args = parseArgs(parser)
74 | printArgs(args)
75 |
76 | yanhekt = YanHeKT(args.courseID, args.all, args.list, args.range, args.dual, args.vga, args.video, args.skip, args.dir, args.max_workers)
77 | yanhekt.download(callback_prog=progressPrint)
78 |
79 |
80 | def runGui():
81 | gui = GUI()
82 | gui.event_loop()
83 |
84 |
85 | def main():
86 | # judge whether to run in GUI mode
87 | if len(sys.argv) > 1 and sys.argv[1] == 'gui':
88 | runGui()
89 | else:
90 | runCli()
91 |
92 |
93 | if __name__ == "__main__":
94 | main()
95 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # 北理工延河课堂视频下载
2 |
3 | 欢迎Star🌟!欢迎提Issue
4 |
5 | 本项目在 网协2023“十行代码”比赛 荣获**特等奖**🎉 指路👉[Github](https://github.com/BITNP/poems-2023/)
6 |
7 | ## 功能介绍
8 |
9 | 下载[延河课堂](https://www.yanhekt.cn/)的录播视频
10 |
11 | - 支持下载非选课班级的课程
12 | - 支持多线程批量下载
13 | - 支持下载电脑视频或教室录像
14 | - 按课程名分类文件夹保存
15 |
16 | ## 更新日志
17 |
18 | - 2023-4-10 同步延河课堂接口更改
19 | - 2023-4-20 更改js执行方式,无需安装nodejs
20 | - 2023-11-12 签名效率优化,优化下载速度
21 | - 理论可以跑满千兆有线网,可以根据电脑性能修改max_workers数量
22 | - **2024-4-2 (🌟)更改signature实现方式**
23 | - 放弃js执行,不再使用js2py,提升兼容性 [issue#5](https://github.com/GDDG08/YanHeKT_Downloader/issues/5)
24 | - 现在时间sign和url后缀 都是py原生
25 | - 2024-4-2 (🌟)更改交互方式,添加完整的**命令行参数**
26 | - 支持一次下载全部课时,感谢@ZJC-GH同学的建议和pr
27 | - 支持分别或同时下载VGA和Video
28 | - 支持增量下载,自动跳过已下载文件
29 | - 更改临时文件存储位置,放在`temp`中
30 | - 可以自定义输出文件夹位置
31 | - **详见 #食用方法**
32 | - 优化ffmpeg输出
33 | - 2024-4-3 (🌟🌟)添加了GUI交互界面
34 | - 基于PySimpleGUI4,可以跨平台运行
35 |
36 | ## 使用前准备
37 |
38 | ### 方法〇:Windows发行(推荐)
39 |
40 | - 下载 [Releases](https://github.com/GDDG08/YanHeKT_Downloader/releases/latest)中的exe文件
41 | - 建议下载带有ffmpeg版本,如`yanhekt-x.x.x-gui-ffmpeg.exe`
42 | - 直接运行,略过后边的部分
43 |
44 | ### 方法一:现已通过Pypi发布
45 |
46 | https://pypi.org/project/yanhekt/
47 |
48 | - 安装`yanhekt`
49 |
50 | ```shell
51 | pip install yanhekt
52 | ```
53 |
54 | - **确保命令行环境有ffmpeg**
55 | - 相关安装请自行搜索
56 | - Windows下载后,添加环境变量即可
57 | - 如果最终视频没有合并,说明ffmpeg环境存在问题
58 |
59 | ### 方法二:使用源代码
60 |
61 | 1. 下载/克隆本仓库或下载 [Releases](https://github.com/GDDG08/YanHeKT_Downloader/releases/latest)
62 |
63 | 2. 安装python依赖包
64 |
65 | ```shell
66 | pip install -r requirements.txt
67 | # (其实就一个requests)
68 | ```
69 |
70 | 3. **确保命令行环境(或者代码文件夹内)有ffmpeg**
71 |
72 | - 本仓库的release附带了ffmpeg(仅exe)
73 | - 相关安装请自行搜索
74 | - Windows简单的方法:下载后拷贝到代码文件夹内
75 |
76 | - 如果最终视频没有合并,说明ffmpeg环境存在问题
77 |
78 | ## 食用方法(GUI)
79 |
80 | 1. 开启方法
81 |
82 | 0. 若release exe,直接打开
83 |
84 | 1. 若使用pip安装
85 |
86 | ```shell
87 | yanhekt-gui
88 | yanhekt gui
89 | ```
90 |
91 | 2. 若源码运行
92 |
93 | ```shell
94 | python main.py gui
95 | ```
96 |
97 | 2. 开箱即食
98 |
99 |
100 |
101 | - 扔进链接或者courseID(可Ctrl-C V)
102 | - 获取课程信息
103 | - 随意选择课时(Ctrl、Shift、鼠标拖拽都可多选)
104 | - 设置一些参数,比如要下载什么视频
105 | - 开下!
106 |
107 |
108 | ## 食用方法(命令行)
109 |
110 | ***注意:如果使用[本地源代码](#方法二:使用源代码)安装,请将本节中的`yanhekt`或`yanhekt-cli`替换为`python main.py`***
111 |
112 | 1. 获取课程ID
113 |
114 | 在课程详情页,**注意不是视频播放页**,如`https://www.yanhekt.cn/course/11111`,
115 |
116 | 从url中获得课程id,如`11111`
117 |
118 | 2. 命令行参数
119 |
120 | - **指定课程的ID**
121 |
122 | - ``,直接给出
123 |
124 | ```shell
125 | # 例:查看课程信息及视频列表
126 | yanhekt 11111
127 | ```
128 |
129 | - **选择下载的课时序号**
130 |
131 | - `--all`,下载全部课时
132 | - `--list 0 2 4 `,下载选定的课时列表
133 | - `--range 3 5`,下载一个范围内的课时
134 | ```shell
135 | # 例:下载第3-8节课
136 | yanhekt 11111 --range 3 9
137 | yanhekt 11111 -L 3 9
138 | ```
139 |
140 | - **选择下载的视频类型**
141 |
142 | - `--dual`,同时下载电脑录屏和教室视频**(默认)**
143 | - `--vga `,仅下载电脑录屏
144 | - `--video`,仅下载教室视频
145 | ```shell
146 | # 例:下载第3-8节课,仅下载电脑录屏
147 | yanhekt 11111 --range 3 9 --vga
148 | ```
149 |
150 | - 增量下载
151 |
152 | - `--skip`,跳过已下载,仅下载新上传的视频
153 | ```shell
154 | # 例:定期更新课程全部视频
155 | yanhekt 11111 --all --skip
156 | ```
157 |
158 | 3. 更多高级用法请参考命令行提示
159 |
160 | ```shell
161 | !yanhekt --help
162 |
163 | # usage: main.py [-h] [-A | -L i [i ...] | -R i i] [-D | -G | -V] [-S] [--dir DIR] [--max-workers num] courseID
164 |
165 | # GDDG08/YanHeKT_Downloader
166 |
167 | # positional arguments:
168 | # courseID Course ID of YanHeKT
169 |
170 | # options:
171 | # -h, --help show this help message and exit
172 |
173 | # Lesson Selection:
174 | # IF NONE, PRINT LESSON LIST AND EXIT.
175 |
176 | # -A, --all Download all lessons
177 | # -L i [i ...], --list i [i ...]
178 | # Select of lesson index (e.g., --list 1 2 4)
179 | # -R i i, --range i i Select range of lessons (e.g., --range 3 5 for [3,5))
180 |
181 | # Video Type:
182 | # -D, --dual Download both VGA(PC) and Video (default)
183 | # -G, --vga Download VGA(PC) only
184 | # -V, --video Download Video only
185 |
186 | # Configurations:
187 | # -S, --skip Skip existing files
188 | # --dir DIR Output directory (e.g., --dir ./output)
189 | # --max-workers num Max workers for downloading (default: 32)
190 |
191 | ```
192 |
193 | 4. **ENJOY !**
194 |
195 |
196 |
197 | ## 作为python包使用
198 |
199 | 仍处于初期开发阶段,欢迎提功能需求和PR
200 |
201 | ```python
202 | from yanhekt import YanHeKT
203 |
204 | yanhekt = YanHeKT(25555, _all=True, _dual=True, _skip=True, _dir='./')
205 | yanhekt.download()
206 | ```
207 |
208 |
209 |
210 | ## Todo(画大饼)
211 |
212 | - ~~@ZJC-GH 同学添加了批量下载功能~~
213 | - ~~有需要的同学可以到[这个仓库](https://github.com/ZJC-GH/YanHeKT_Downloader) release中下载使用~~
214 | - ~~目前已合并到dev分支~~
215 | - ~~计划使用`argparse`完善命令行参数,优化下交互体验~~(2.2.0已实现)
216 | - ~~(超大饼)在参数写完后整个简单的gui~~
217 |
218 |
219 | ## 致谢
220 |
221 | - [M3u8Download](https://github.com/anwenzen/M3u8Download)
222 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests
2 | PySimpleGUI<=4.55.1
--------------------------------------------------------------------------------
/yanhekt.py:
--------------------------------------------------------------------------------
1 | '''
2 | Project :
3 | FilePath : \OPENSOURCE\yanhekt.py
4 | Descripttion :
5 | Author : GDDG08
6 | Date : 2022-11-08 02:07:44
7 | LastEditors : GDDG08
8 | LastEditTime : 2024-04-03 23:12:54
9 | '''
10 | import requests
11 | from m3u8dl import M3u8Download
12 | import os
13 |
14 | headers = {
15 | 'Origin': 'https://www.yanhekt.cn',
16 | "xdomain-client": "web_user",
17 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.26'
18 | }
19 |
20 |
21 | class YanHeKT():
22 | def __init__(self, _courseID, _all=False, _list=None, _range=None, _dual=True, _vga=False, _video=False, _skip=False, _dir='./', _max_workers=32) -> None:
23 | self.courseID = _courseID
24 | self.lessonList = None
25 | self.courseInfo = None
26 |
27 | self.updateArgs(_all, _list, _range, _dual, _vga, _video, _skip, _dir, _max_workers)
28 |
29 | def updateArgs(self, _all=False, _list=None, _range=None, _dual=True, _vga=False, _video=False, _skip=False, _dir='./', _max_workers=32):
30 | self.all = _all
31 | self.list = _list
32 | self.range = _range
33 | self.dual = _dual
34 | self.vga = _vga
35 | self.video = _video
36 | self.skip = _skip
37 | self.dir = _dir
38 | self.max_workers = _max_workers
39 |
40 | def getCourseInfo(self):
41 | print("----Getting Course Information----")
42 |
43 | rqt_course = requests.get(f'https://cbiz.yanhekt.cn/v1/course?id={self.courseID}&with_professor_badges=true', headers=headers)
44 | courseInfo = rqt_course.json()['data']
45 |
46 | print(courseInfo['name_zh'])
47 |
48 | print("-----Getting Lesson List-----")
49 | rqt_list = requests.get(f'https://cbiz.yanhekt.cn/v2/course/session/list?course_id={self.courseID}', headers=headers)
50 | lessonList = rqt_list.json()['data']
51 |
52 | for i, lesson in enumerate(lessonList):
53 | print(f"[{i}] ", lesson['title'])
54 |
55 | self.courseInfo = courseInfo
56 | self.lessonList = lessonList
57 | return courseInfo, lessonList
58 |
59 | def download(self, callback=None, callback_prog=None):
60 | if not self.lessonList or not self.courseInfo:
61 | self.getCourseInfo()
62 |
63 | print("------Start Downloading------")
64 |
65 | selectList = []
66 | if self.all:
67 | selectList = list(range(len(self.lessonList)))
68 | elif self.list:
69 | selectList = self.list
70 | elif self.range:
71 | selectList += list(range(self.range[0][0], self.range[0][1]))
72 | else:
73 | print("[Error] No lesson selected in args.")
74 | print("Please use -A/--all, -L/--list, or -R/--range to select lessons.")
75 | print("Example:")
76 | print(f"\tpython main.py {self.courseID} --all")
77 | print(f"\tpython main.py {self.courseID} --list 0 2 4")
78 | print(f"\tpython main.py {self.courseID} --range 3 5")
79 |
80 | if callback:
81 | callback(False)
82 | return
83 |
84 | courseFullName = '-'.join([str(self.courseID), self.courseInfo['name_zh'], self.courseInfo['professors'][0]['name']])
85 | dirName = os.path.join(self.dir, courseFullName)
86 |
87 | if not os.path.exists(dirName):
88 | os.makedirs(dirName)
89 |
90 | for i in selectList:
91 | video = self.lessonList[i]
92 | fileName = video['title'].replace("/", "-") # 防止文件名中的/导致路径错误
93 |
94 | print(f"Downloading {fileName} --->")
95 |
96 | videos = video['videos'][0]
97 | # 下载投影录屏
98 | if self.vga or self.dual:
99 | if 'vga' in videos and videos['vga']: # 检查是否存在vga链接
100 | if self.skip and os.path.exists(f"{dirName}/{fileName}-VGA.mp4"):
101 | print(f"VGA seems already done. Skipping...")
102 | else:
103 | print("VGA -->")
104 | M3u8Download(videos['vga'], dirName, fileName + '-VGA', max_workers=self.max_workers, callback_progress=callback_prog)
105 | else:
106 | print(f"No VGA found.")
107 |
108 | # 下载视频
109 | if self.video or self.dual:
110 | if 'main' in videos and videos['main']: # 检查是否存在main链接
111 | if self.skip and os.path.exists(f"{dirName}/{fileName}-Video.mp4"):
112 | print(f"Video seems already done. Skipping...")
113 | else:
114 | print("Video -->")
115 | M3u8Download(videos['main'], dirName, fileName + '-Video', max_workers=self.max_workers, callback_progress=callback_prog)
116 | else:
117 | print(f"No Video found.")
118 |
119 | if callback:
120 | callback(True)
121 | return
122 |
123 |
124 | if __name__ == '__main__':
125 | # main()
126 | # yanhekt = YanHeKT(12345, _all=True, _dir='./')
127 | # yanhekt.download(callback_prog=progressPrint)
128 | pass
129 |
--------------------------------------------------------------------------------