Skip to content

Commit

Permalink
feat: support multi course downloading and custom download path
Browse files Browse the repository at this point in the history
  • Loading branch information
itsHenry35 committed Jun 28, 2023
1 parent 01cf1c1 commit 70ba0b1
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 25 deletions.
49 changes: 34 additions & 15 deletions gui/download1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import importlib
from tkinter.filedialog import askdirectory
import tkinter.messagebox as mb

def get_course(uid, token):
url = "https://course-api-online.saasp.vdyoo.com/course/v1/student/course/list"
Expand All @@ -22,36 +24,53 @@ def get_course(uid, token):
response = requests.get(url, headers=headers)
return response.json()

def select_path():
global path
path = askdirectory()

def download1(uid, token):
def select_course():
selected_course = numlist[check_box_var1.get()]
returnlist['tutorid'] = courselist[selected_course]
returnlist['courseid'] = idlist[selected_course]
returnlist['name'] = selected_course
root.destroy()
returnlist['extensiveornot'] = 'True' if var.get() == 1 else 'False'
global path
def submit():
count = 0
for i, widget in enumerate(widgetlist):
if 'selected' in widget.state():
returnlist.append({})
returnlist[count]['tutorid'] = courselist[numlist[i]]
returnlist[count]['courseid'] = idlist[numlist[i]]
returnlist[count]['name'] = numlist[i]
returnlist[count]['extensiveornot'] = 'True' if var.get() == 1 else 'False'
count+=1
if count == 0:
mb.showwarning(title='警告', message='未选择课程')
else:
root.destroy()


root = ttk.Window(title='乐读视频下载器-下载', themename="morph")
root.geometry("")
data = get_course(uid, token)
courselist, idlist, numlist, returnlist = {}, {}, [], {}
courselist, idlist, numlist, returnlist = {}, {}, [], []
var = ttk.IntVar()
var.set(0)
path = ""

for course in data:
courselist[course['courseName']] = course['tutorId']
idlist[course['courseName']] = course['stdCourseId']

check_box_var1 = ttk.IntVar()
for index, course_name in enumerate(courselist):
widgetlist = []
for course_name in courselist:
numlist.append(course_name)
radiobutton = ttk.Radiobutton(text=course_name, bootstyle="primary-outline-toolbutton", variable=check_box_var1, value=index)
radiobutton.pack(anchor='w')
checkbutton = ttk.Checkbutton(text=course_name, bootstyle="round-toggle")
checkbutton.pack(anchor='w')
widgetlist.append(checkbutton)

extensiveornot = ttk.Checkbutton(text='延伸课程', bootstyle="default-round-toggle", variable=var)
extensiveornot = ttk.Checkbutton(text='延伸课程', bootstyle="default-square-toggle", variable=var)
extensiveornot.pack(anchor='w')
submit = ttk.Button(text='提交', bootstyle="primary", command=select_course)
submit = ttk.Button(text='提交', bootstyle="primary", command=submit)
submit.pack(anchor='w')
selectpath = ttk.Button(text='选择自定义路径(可不选,默认为程序所在目录)', bootstyle="primary-outline-toolbutton", command=select_path)
selectpath.pack(anchor='w')
root.mainloop()
importlib.reload(ttk.style)
return returnlist
return returnlist, path
44 changes: 37 additions & 7 deletions gui/download2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,25 @@
import os, sys
import subprocess
from pyaria2 import Aria2RPC
import ttkbootstrap as ttk
import ttkbootstrap as ttk, tkinter
import time
import threading
import importlib
import inspect, ctypes


def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)

def get_lecturers(course_list, user_id, access_token):
url = "https://course-api-online.saasp.vdyoo.com/course/v1/student/course/user-live-list"
Expand Down Expand Up @@ -126,14 +142,19 @@ def get_cram_class(course, user_id, access_token):
"errmsg": error_message,
}

def download2(course_list, user_id, access_token, aria2_path):
def download2(course_list, user_id, access_token, aria2_path, custom_down_path, final):
global aria2process
if custom_down_path == '':
custom_down_path = "乐读-下载"
gid_group = {}
def aria2_download(link, path, filename):
options = {"dir": path, "out": filename}
download_ = jsonrpc.addUri([link], options=options)
gid_group[filename] = download_
def update_download_status():
global aria2process
while True:
all_success = True
for filename in gid_group:
stat = jsonrpc.tellStatus(gid=str(gid_group[filename]))
if stat['status'] != 'complete':
Expand All @@ -143,15 +164,24 @@ def update_download_status():
tkinterlist[filename]['progress'].update()
tkinterlist[filename]['percentage'].configure(text=str("%.2f"%((int(stat['completedLength']) / int(stat['totalLength']) * 100))) + '%')
tkinterlist[filename]['speed'].configure(text='下载速度:' + str(round(int(stat['downloadSpeed'])/1024/1024, 2)) + 'MB/s')
all_success = False
if stat['status'] == 'complete':
tkinterlist[filename]['progress']['value'] = 100
tkinterlist[filename]['progress'].update()
tkinterlist[filename]['percentage'].configure(text='100%')
tkinterlist[filename]['speed'].configure(text='已完成')
if all_success:
if not final:
root.destroy()
if final:
jsonrpc.shutdown()
aria2process.terminate()
stop_thread(thread)
time.sleep(0.1)
root = ttk.Window(title='乐读视频下载器-下载', themename="morph")
root.geometry("")
aria2process = subprocess.Popen(aria2_path + ' --enable-rpc --rpc-listen-port=6800 --max-connection-per-server=16 --file-allocation=none --max-concurrent-downloads=64', shell=True)
if not final:
aria2process = subprocess.Popen(aria2_path + ' --enable-rpc --rpc-listen-port=6800 --max-connection-per-server=16 --file-allocation=none --max-concurrent-downloads=64', shell=True)
time.sleep(1)
jsonrpc = Aria2RPC()
lecturers = get_lecturers(course_list, user_id, access_token)
Expand All @@ -169,7 +199,7 @@ def update_download_status():
count += 1
count = 2
tkinterlist = {}
text = ttk.Label(text='下载中~')
text = ttk.Label(text='当前正在下载课程:' + course_name)
text.grid(row=1, column=0)
for filename in download_urls:
text = ttk.Label(text=filename)
Expand All @@ -188,7 +218,7 @@ def update_download_status():
'speed': text1,
}
count += 1
download_path = os.path.join('乐读-下载', course_name)
download_path = os.path.join(custom_down_path, course_name)
if not os.path.exists(download_path):
os.makedirs(download_path)
open_path_button = ttk.Button(text='打开下载目录', command=lambda: os.startfile(download_path))
Expand All @@ -200,8 +230,8 @@ def update_download_status():
tkinterlist[filename]['percentage'].configure(text='下载失败')
tkinterlist[filename]['speed'].configure(text=download_urls[filename]['errmsg'])
thread = threading.Thread(target=update_download_status)
thread.setDaemon(True)
thread.start()
root.mainloop()
aria2process.kill()
importlib.reload(ttk.style)
importlib.reload(tkinter)
return
11 changes: 8 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,14 @@ def login():
set_alldata(datanext['data'])

def download():
result = download1(uid, token)
path__ = get_platform_info()
download2(result, uid, token, path__)
result, custom_down_path = download1(uid, token)
aria2_path = get_platform_info()
for count, course in enumerate(result):
if count == len(result) - 1:
final = True
else:
final = False
download2(course, uid, token, aria2_path, custom_down_path, final)

def get_platform_info():
bundle_dir = sys._MEIPASS if getattr(sys, 'frozen', False) else os.path.dirname(os.path.abspath(__file__))
Expand Down

0 comments on commit 70ba0b1

Please sign in to comment.