网上的TS流视频文件下载,解密,合成一个文件的python方法(转的别人大佬的,自己存一份~~)

2019-08-13
 1 # -*- coding:utf-8 -*- 
 2 import os
 3 import sys
 4 import requests
 5 import datetime
 6 from Crypto.Cipher import AES
 7 from binascii import b2a_hex, a2b_hex
 8 
 9 # reload(sys)
10 # sys.setdefaultencoding(‘utf-8‘)
11 
12 import importlib
13 importlib.reload(sys)
14 
15 def download(url):
16   download_path = os.getcwd() + "\download"
17   if not os.path.exists(download_path):
18     os.mkdir(download_path)
19    
20   #新建日期文件夹
21   download_path = os.path.join(download_path, datetime.datetime.now().strftime(%Y%m%d_%H%M%S))
22   #print download_path
23   os.mkdir(download_path)
24    
25   all_content = requests.get(url).text # 获取第一层M3U8文件内容
26   if "#EXTM3U" not in all_content:
27     raise BaseException("非M3U8的链接")
28 
29   if "EXT-X-STREAM-INF" in all_content: # 第一层
30     file_line = all_content.split("\n")
31     for line in file_line:
32       if .m3u8 in line:
33         url = url.rsplit("/", 1)[0] + "/" + line # 拼出第二层m3u8的URL
34         all_content = requests.get(url).text
35 
36   file_line = all_content.split("\n")
37 
38   unknow = True
39   key = ""
40   for index, line in enumerate(file_line): # 第二层
41     if "#EXT-X-KEY" in line: # 找解密Key
42       method_pos = line.find("METHOD")
43       comma_pos = line.find(",")
44       method = line[method_pos:comma_pos].split(=)[1]
45       print("Decode Method:", method)
46      
47       uri_pos = line.find("URI")
48       quotation_mark_pos = line.rfind(")
49       key_path = line[uri_pos:quotation_mark_pos].split(")[1]
50      
51       key_url = url.rsplit("/", 1)[0] + "/" + key_path # 拼出key解密密钥URL
52       res = requests.get(key_url)
53       key = res.content
54       print( "key:" , key)
55      
56     if "EXTINF" in line: # 找ts地址并下载
57       unknow = False
58       pd_url = url.rsplit("/", 1)[0] + "/" + file_line[index + 1] # 拼出ts片段的URL
59       #print pd_url
60      
61       res = requests.get(pd_url)
62       c_fule_name = file_line[index + 1].rsplit("/", 1)[-1]
63      
64       if len(key): # AES 解密
65         cryptor = AES.new(key, AES.MODE_CBC, key) 
66         with open(os.path.join(download_path, c_fule_name + ".mp4"), ab) as f:
67           f.write(cryptor.decrypt(res.content))
68       else:
69         with open(os.path.join(download_path, c_fule_name), ab) as f:
70           f.write(res.content)
71           f.flush()
72   if unknow:
73     raise BaseException("未找到对应的下载链接")
74   else:
75     print( "下载完成")
76   # merge_file(download_path)
77 
78 def merge_file(path):
79   os.chdir(path)
80   cmd = "copy /b * new.tmp"
81   os.system(cmd)
82   os.system(del /Q *.ts)
83   os.system(del /Q *.mp4)
84   os.rename("new.tmp", "new.mp4")
85  
86 if __name__ == __main__:
87   url = input("please input the url of index.m3u8 file")
88   download(url)