-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.py
412 lines (349 loc) · 12 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
import argparse
import base64
import glob
import hashlib
import json
import logging
import os
import shutil
import subprocess
import sys
from os.path import abspath, join, isdir, splitext, basename, dirname
from pathlib import Path
from urllib.parse import urlparse, urlunparse, urlencode, parse_qsl
import m3u8
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
def clean(*globs):
for g in globs:
if isdir(g):
shutil.rmtree(g)
else:
for delete in glob.glob(g):
os.remove(delete)
def get_absolute_paths(directory):
for absolute, _, filenames in os.walk(directory):
for filename in sorted(filenames):
yield abspath(join(absolute, filename))
class WingFox:
def __init__(
self,
video_id: str,
cookie: str
):
"""
WingFox Downloader
Author: github.com/DevLARLEY
"""
self.video_id = video_id
self.cookie = cookie
def get_video_vid(self) -> str | None:
vid_request = requests.get(
'https://api.wingfox.com/api/album/get_video_url',
params={
'play_video_id': self.video_id
},
cookies={
'yiihuu_s_c_d': self.cookie
}
)
if vid_request.status_code != 200:
logging.error(f"Unable to request video_vid ({vid_request.status_code}): {vid_request.text}")
exit(-1)
return vid_request.json().get('data', {}).get('video_vid')
@staticmethod
def get_hls_seed_url(
video_vid: str
) -> dict | None:
video_request = requests.get(
url=f"https://player.polyv.net/secure/{video_vid}.json"
)
if video_request.status_code != 200:
logging.error(f"Unable to request video json ({video_request.status_code}): {video_request.text}")
exit(-1)
hashed = hashlib.md5(video_vid.encode('utf-8')).hexdigest()
key, iv = hashed[:16].encode(), hashed[16:].encode()
aes_cipher = AES.new(key, AES.MODE_CBC, iv=iv)
decrypted = aes_cipher.decrypt(
bytes.fromhex(video_request.json().get('body'))
).rstrip(b'\x0c')
decrypted_json = json.loads(base64.b64decode(decrypted).decode())
if decrypted_json.get("hls"):
return decrypted_json
@staticmethod
def get_m3u8(
body: dict
) -> str | None:
manifest_url = body.get('hls')[-1]
hls_request = requests.get(
url=manifest_url,
params={
'device': 'desktop',
},
headers={
'Referer': 'https://www.wingfox.com/',
}
)
if hls_request.status_code != 200:
logging.error(f"Unable to request m3u8 data ({hls_request.status_code}): {hls_request.text}")
exit(-1)
if splitext(urlparse(manifest_url).path)[-1] == ".m3u8":
return hls_request.text
enc_m3u8 = hls_request.json()['body']
secret = f"NTQ1ZjhmY2QtMzk3OS00NWZhLTkxNjktYzk3NTlhNDNhNTQ4#{body.get('seed_const')}"
iv = bytes([1, 1, 2, 3, 5, 8, 13, 21, 34, 21, 13, 8, 5, 3, 2, 1])
if body.get('hlsPrivate') == 2:
secret = f"OWtjN9xcDcc2cwXKxECpRgKw7piD4RwCdfOUlyNHFdSV0gHi={body.get('seed_const')}"
iv = bytes([13, 22, 8, 12, 7, 6, 13, 1, 50, 11, 12, 8, 5, 16, 4, 1])
aes_key = hashlib.md5(secret.encode()).hexdigest()[1:17].encode()
cipher = AES.new(
aes_key,
AES.MODE_CBC,
iv=iv
)
dec = cipher.decrypt(base64.b64decode(enc_m3u8))
return unpad(dec, 16).decode()
def get_key_token(self) -> str | None:
token_request = requests.get(
url="https://www.wingfox.com/polyv/polyv_get_token.php",
params={
'video_id': self.video_id
},
cookies={
"yiihuu_s_c_d": self.cookie
}
)
if token_request.status_code != 200:
logging.error(f"Unable to request token ({token_request.status_code}): {token_request.text}")
exit(-1)
return token_request.text
@staticmethod
def _update_key(
uri: str,
token: str,
version: int,
hls_level: str
) -> str:
parse_result = urlparse(uri)
query = dict(parse_qsl(parse_result.query))
query.update({
"token": token
})
if hls_level == "app" or version == 2:
path = f"/playsafe/v{version + 11}" + parse_result.path
return urlunparse(
# dangerous
parse_result._replace(path=path, query=urlencode(query))
)
elif hls_level == "web":
return urlunparse(
# dangerous
parse_result._replace(query=urlencode(query))
)
def implant_token(
self,
m3u8_data: str,
token: str,
version: int,
hls_level: str
) -> str:
parsed = m3u8.loads(m3u8_data)
if keys := parsed.keys:
for key in keys:
if hls_level == "app" or version == 2:
key.uri, key.iv, key.method = "", "", ""
elif hls_level == "web":
key.uri = self._update_key(
uri=key.uri,
token=token,
version=version,
hls_level=hls_level
)
return parsed.dumps()
@staticmethod
def download(
hls_level: str
):
command = [
join("" if sys.platform == "win32" else ".", "N_m3u8DL-RE-WingFox"),
m3u8_file,
"--no-log",
"--wingfox-decrypt",
"1",
]
if hls_level == "app" or version == 2:
command.extend([
"--skip-merge"
])
subprocess.run(
command,
shell=False
)
def get_decrypt_info(
self,
m3u8_data: str,
version: int,
hls_level: str,
token: str
) -> tuple[str, str, str]:
parsed = m3u8.loads(m3u8_data)
key = parsed.keys[0]
key_request = requests.get(
url=self._update_key(
uri=key.uri,
token=token,
version=version,
hls_level=hls_level
)
)
if key_request.status_code != 200:
logging.error(f"Unable to request key ({key_request.status_code}): {key_request.text}")
exit(1)
return (
key_request.content.hex(),
key.iv[2:],
token
)
@staticmethod
def save_subtitles(
srt_data: list,
output: str
):
if srt_data:
for srt in srt_data:
logging.info(f"Saving subtitle {srt.get('title')}...")
srt_request = requests.get(
url=srt.get('url')
)
if srt_request.status_code != 200:
logging.error(f"Unable to request subtitle ({srt_request.status_code}): {srt_request.text}")
continue
file_name = splitext(basename(output))[0]
open(
join(dirname(output), f"{file_name}_{srt.get('title')}.srt"),
"w",
encoding="utf-8"
).write(srt_request.text)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
prog="WingFox Downloader",
description=(
"""
Author: github.com/DevLARLEY
Credits: github.com/gyozaaaa
"""
)
)
parser.add_argument(
"--id",
type=int,
help=(
"""
WingFox Video ID
Example: wingfox.com/p/<course_id>/<video_id>
Shall be obtained from the 'get_video_url' request if not present in the URL
"""
),
required=True
)
parser.add_argument(
"--cookie",
type=str,
help="WingFox yiihuu_s_c_d/PHPSESSID Cookie",
required=True
)
parser.add_argument(
"--output",
type=str,
help="Output file name",
required=False
)
parser.add_argument(
"--subtitles",
action="store_true",
default=False,
help="Save subtitles",
required=False
)
parser.add_argument(
"--debug", "--d",
action="store_true",
default=False,
help="Print debug information",
required=False
)
args = parser.parse_args()
logging.basicConfig(format='[%(levelname)s]: %(message)s', level=logging.DEBUG if args.debug else logging.INFO)
# lib_players:
# https://player.polyv.net/resp/vod-player-drm/canary/lib_player.js
# https://player.polyv.net/resp/vod-player-drm/canary/next/lib_player.js
dl = WingFox(
video_id=args.id,
cookie=args.cookie
)
vid = dl.get_video_vid()
decrypted_body = dl.get_hls_seed_url(vid)
output_name = f"{decrypted_body.get('title')}_{args.id}.mkv"
if args.output:
output_name = args.output
Path(dirname(output_name)).mkdir(parents=True, exist_ok=True)
print('seed_const =>', seed := decrypted_body.get('seed_const'))
print('hlsLevel =>', hls_level := decrypted_body.get('hlsLevel'))
print('hlsPrivate =>', version := decrypted_body.get('hlsPrivate'))
manifest_data = dl.get_m3u8(decrypted_body)
key_token = dl.get_key_token()
modified_data = dl.implant_token(
m3u8_data=manifest_data,
token=key_token,
version=version,
hls_level=hls_level
)
m3u8_file = f'{args.id}.m3u8'
with open(m3u8_file, 'w') as f:
f.write(modified_data)
dl.download(
hls_level=hls_level
)
if hls_level == "app" or version == 2:
key, iv, token = dl.get_decrypt_info(
m3u8_data=manifest_data,
version=version,
hls_level=hls_level,
token=key_token
)
with open("filelist.txt", "w") as f:
for idx, file in enumerate(get_absolute_paths(join(str(args.id), "0"))):
if not file.endswith(".ts"):
continue
logging.info(f"Decrypting fragment {idx}...")
try:
subprocess.check_output(command := [
"node", f"decrypt_{version}.js",
file, f"fragment_{idx}.mkv",
key, iv,
token, str(seed),
str(idx)
], shell=False)
logging.debug(' '.join(command))
except Exception:
logging.error("Error while decrypting fragment")
clean("fragment_*.mkv", "filelist.txt", f"{args.id}.m3u8", str(args.id))
exit(1)
if os.path.exists(f"fragment_{idx}.mkv"):
f.write(f"file fragment_{idx}.mkv\n")
logging.info("Muxing all segments...")
subprocess.check_output([
"ffmpeg", "-y", "-loglevel", "error",
"-f", "concat",
"-safe", "0",
"-i", "filelist.txt",
"-c", "copy",
output_name
])
if args.subtitles:
dl.save_subtitles(
srt_data=decrypted_body.get('srt'),
output=output_name
)
clean("fragment_*.mkv", "filelist.txt", f"{args.id}.m3u8", str(args.id))