#!/usr/bin/env python
#coding=utf-8
import re
import requests
import threadpool
import shutil
import os
import sys
import subprocess
def get_file(url):
global session
while True:
try: content = session.get(url, timeout = 60).content
except: sys.stderr.write('"' + url + '": download failed, retry!\n'); continue
break
return content
def get_base_url(url):
return re.search(r'^(.+?://.+?)/', url).group(1)
def get_list_full_path(url_list, base_url):
for i in range(len(url_list)):
url_list[i] = url_list[i] if re.search(r'^.+?://', url_list[i]) else base_url + url_list[i]
return url_list
def get_media_play_list(url):
play_list = get_file(url).decode()
master_play_list = re.findall(r'^.+\.m3u8$', play_list, re.MULTILINE)
if len(master_play_list) == 0: return play_list
master_play_list = get_list_full_path(master_play_list, get_base_url(url))
return get_file(master_play_list[0]).decode()
def get_ts_list(media_play_list):
return re.findall(r'^.+?://.+?\.ts$', media_play_list, re.MULTILINE)
def download_file(url, path):
filename = re.search(r'^.+/(.+)$', url).group(1)
with open(path + '/' + filename, 'wb') as f: f.write(get_file(url))
sys.stdout.write(path + ': ' + url + '\n')
def get_video_info(path):
ffprobe_cmd = ['ffprobe', '-protocol_whitelist', 'https,file,crypto,tls,tcp', '-show_streams', '-print_format', 'json', path]
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
ffprobe = subprocess.Popen(ffprobe_cmd, stdout = subprocess.PIPE, startupinfo = startupinfo)
ffprobe.wait()
return json.loads(ffprobe.stdout.read())
def convert_video_format(v1, v2):
ffmpeg_cmd = ['ffmpeg', '-y', '-protocol_whitelist', 'https,file,crypto,tls,tcp', '-i', v1, '-c:v', 'h264', v2]
ffmpeg = subprocess.Popen(ffmpeg_cmd)
ffmpeg.wait()
return ffmpeg.returncode
url = 'https://s1.zoubuting.com/20210731/F9EwiTg8/index.m3u8'
session = requests.Session()
path = 'download'
shutil.rmtree(path, True)
os.mkdir(path)
media_play_list = get_media_play_list(url)
ts_list = get_ts_list(media_play_list)
pool = threadpool.ThreadPool(8)
requests = threadpool.makeRequests(download_file, [((url, path), None) for url in ts_list])
[pool.putRequest(req) for req in requests]
pool.wait()
media_play_list = re.sub(r'^.+/(.+?\.ts)$', r'\1', media_play_list, flags = re.MULTILINE)
with open(path + '/index.m3u8', 'w') as f: f.write(media_play_list)
print(convert_video_format(path + '/index.m3u8', '31.mp4'))