]>
code.delx.au - webdl/blob - common.py
18 USER_AGENT
= "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0"
22 autosocks
.try_autosocks()
28 format
= "%(levelname)s %(message)s",
29 level
= logging
.INFO
if os
.environ
.get("DEBUG", None) is None else logging
.DEBUG
,
33 CACHE_FILE
= os
.path
.join(
34 os
.environ
.get("XDG_CACHE_HOME", os
.path
.expanduser("~/.cache")),
38 if not os
.path
.isdir(os
.path
.dirname(CACHE_FILE
)):
39 os
.makedirs(os
.path
.dirname(CACHE_FILE
))
41 requests_cache
.install_cache(CACHE_FILE
, backend
='sqlite', expire_after
=3600)
45 def __init__(self
, title
, parent
=None):
48 parent
.children
.append(self
)
51 self
.can_download
= False
53 def get_children(self
):
56 self
.children
= natural_sort(self
.children
, key
=lambda node
: node
.title
)
59 def fill_children(self
):
67 root_node
= Node("Root")
70 iview
.fill_nodes(root_node
)
73 sbs
.fill_nodes(root_node
)
76 ten
.fill_nodes(root_node
)
80 valid_chars
= frozenset("-_.()!@#%^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
81 def sanify_filename(filename
):
82 filename
= "".join(c
for c
in filename
if c
in valid_chars
)
83 assert len(filename
) > 0
86 def ensure_scheme(url
):
87 parts
= urllib
.parse
.urlparse(url
)
92 return urllib
.parse
.urlunparse(parts
)
94 http_session
= requests
.Session()
95 http_session
.headers
["User-Agent"] = USER_AGENT
98 logging
.debug("grab_text(%r)", url
)
99 request
= http_session
.prepare_request(requests
.Request("GET", url
))
100 response
= http_session
.send(request
)
104 logging
.debug("grab_html(%r)", url
)
105 request
= http_session
.prepare_request(requests
.Request("GET", url
))
106 response
= http_session
.send(request
)
107 doc
= lxml
.html
.parse(io
.BytesIO(response
.content
), lxml
.html
.HTMLParser(encoding
="utf-8", recover
=True))
112 logging
.debug("grab_xml(%r)", url
)
113 request
= http_session
.prepare_request(requests
.Request("GET", url
))
114 response
= http_session
.send(request
)
115 doc
= lxml
.etree
.parse(io
.BytesIO(response
.content
), lxml
.etree
.XMLParser(encoding
="utf-8", recover
=True))
120 logging
.debug("grab_json(%r)", url
)
121 request
= http_session
.prepare_request(requests
.Request("GET", url
))
122 response
= http_session
.send(request
)
123 return response
.json()
125 def exec_subprocess(cmd
):
126 logging
.debug("Executing: %s", cmd
)
128 p
= subprocess
.Popen(cmd
)
131 logging
.error("%s exited with error code: %s", cmd
[0], ret
)
136 logging
.error("Failed to run: %s -- %s", cmd
[0], e
)
137 except KeyboardInterrupt:
138 logging
.info("Cancelled: %s", cmd
)
142 except KeyboardInterrupt:
143 p
.send_signal(signal
.SIGKILL
)
148 def check_command_exists(cmd
):
150 subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
)
155 def get_duration(filename
):
159 "-show_entries", "format=duration",
162 output
= subprocess
.check_output(cmd
).decode("utf-8")
163 for line
in output
.split("\n"):
164 m
= re
.search(R
"([0-9]+)", line
)
167 duration
= m
.group(1)
168 if duration
.isdigit():
172 logging
.debug("Falling back to full decode to find duration: %s % filename")
180 output
= subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
).decode("utf-8")
182 for line
in re
.split(R
"[\r\n]", output
):
183 m
= re
.search(R
"time=([0-9:]*)\.", line
)
186 [h
, m
, s
] = m
.group(1).split(":")
187 # ffmpeg prints the duration as it reads the file, we want the last one
188 duration
= int(h
) * 3600 + int(m
) * 60 + int(s
)
193 raise Exception("Unable to determine video duration of " + filename
)
195 def check_video_durations(flv_filename
, mp4_filename
):
196 flv_duration
= get_duration(flv_filename
)
197 mp4_duration
= get_duration(mp4_filename
)
199 if abs(flv_duration
- mp4_duration
) > 1:
201 "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
202 mp4_filename
, flv_duration
, mp4_duration
208 def remux(infile
, outfile
):
209 logging
.info("Converting %s to mp4", infile
)
214 "-bsf:a", "aac_adtstoasc",
220 if not exec_subprocess(cmd
):
223 if not check_video_durations(infile
, outfile
):
229 def convert_to_mp4(filename
):
230 with
open(filename
, "rb") as f
:
232 basename
, ext
= os
.path
.splitext(filename
)
234 if ext
== ".mp4" and fourcc
== b
"FLV\x01":
235 os
.rename(filename
, basename
+ ".flv")
237 filename
= basename
+ ext
239 if ext
in (".flv", ".ts"):
240 filename_mp4
= basename
+ ".mp4"
241 return remux(filename
, filename_mp4
)
246 def download_hds(filename
, video_url
, pvswf
=None):
247 filename
= sanify_filename(filename
)
248 logging
.info("Downloading: %s", filename
)
250 video_url
= "hds://" + video_url
252 param
= "%s pvswf=%s" % (video_url
, pvswf
)
259 "--output", filename
,
263 if exec_subprocess(cmd
):
264 return convert_to_mp4(filename
)
268 def download_hls(filename
, video_url
):
269 filename
= sanify_filename(filename
)
270 video_url
= "hlsvariant://" + video_url
271 logging
.info("Downloading: %s", filename
)
275 "--http-header", "User-Agent=" + USER_AGENT
,
277 "--output", filename
,
281 if exec_subprocess(cmd
):
282 return convert_to_mp4(filename
)
286 def download_mpd(filename
, video_url
):
287 filename
= sanify_filename(filename
)
288 video_url
= "dash://" + video_url
289 logging
.info("Downloading: %s", filename
)
294 "--output", filename
,
298 if exec_subprocess(cmd
):
299 return convert_to_mp4(filename
)
303 def download_http(filename
, video_url
):
304 filename
= sanify_filename(filename
)
305 logging
.info("Downloading: %s", filename
)
309 "--fail", "--retry", "3",
313 if exec_subprocess(cmd
):
314 return convert_to_mp4(filename
)
318 def natural_sort(l
, key
=None):
319 ignore_list
= ["a", "the"]
325 for c
in re
.split("([0-9]+)", k
):
328 newk
.append(c
.zfill(5))
330 for subc
in c
.split():
331 if subc
not in ignore_list
:
335 return sorted(l
, key
=key_func
)
337 def append_to_qs(url
, params
):
338 r
= list(urllib
.parse
.urlsplit(url
))
339 qs
= urllib
.parse
.parse_qs(r
[3])
340 for k
, v
in params
.items():
345 r
[3] = urllib
.parse
.urlencode(sorted(qs
.items()), True)
346 url
= urllib
.parse
.urlunsplit(r
)