utils.py 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import errno
  13. import functools
  14. import gzip
  15. import io
  16. import itertools
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import socket
  26. import ssl
  27. import subprocess
  28. import sys
  29. import tempfile
  30. import traceback
  31. import xml.etree.ElementTree
  32. import zlib
  33. from .compat import (
  34. compat_HTMLParser,
  35. compat_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_html_entities_html5,
  40. compat_http_client,
  41. compat_kwargs,
  42. compat_parse_qs,
  43. compat_shlex_quote,
  44. compat_socket_create_connection,
  45. compat_str,
  46. compat_struct_pack,
  47. compat_struct_unpack,
  48. compat_urllib_error,
  49. compat_urllib_parse,
  50. compat_urllib_parse_urlencode,
  51. compat_urllib_parse_urlparse,
  52. compat_urllib_parse_unquote_plus,
  53. compat_urllib_request,
  54. compat_urlparse,
  55. compat_xpath,
  56. )
  57. from .socks import (
  58. ProxyType,
  59. sockssocket,
  60. )
  61. def register_socks_protocols():
  62. # "Register" SOCKS protocols
  63. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  64. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  65. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  66. if scheme not in compat_urlparse.uses_netloc:
  67. compat_urlparse.uses_netloc.append(scheme)
  68. # This is not clearly defined otherwise
  69. compiled_regex_type = type(re.compile(''))
  70. std_headers = {
  71. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)',
  72. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  73. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  74. 'Accept-Encoding': 'gzip, deflate',
  75. 'Accept-Language': 'en-us,en;q=0.5',
  76. }
  77. NO_DEFAULT = object()
  78. ENGLISH_MONTH_NAMES = [
  79. 'January', 'February', 'March', 'April', 'May', 'June',
  80. 'July', 'August', 'September', 'October', 'November', 'December']
  81. FRENCH_MONTH_NAMES = [
  82. 'janvier', 'fevrier', 'mars', 'avril', 'mai', 'juin',
  83. 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'decembre']
  84. KNOWN_EXTENSIONS = (
  85. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  86. 'flv', 'f4v', 'f4a', 'f4b',
  87. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  88. 'mkv', 'mka', 'mk3d',
  89. 'avi', 'divx',
  90. 'mov',
  91. 'asf', 'wmv', 'wma',
  92. '3gp', '3g2',
  93. 'mp3',
  94. 'flac',
  95. 'ape',
  96. 'wav',
  97. 'f4f', 'f4m', 'm3u8', 'smil')
  98. # needed for sanitizing filenames in restricted mode
  99. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  100. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUYP', ['ss'],
  101. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuypy')))
  102. DATE_FORMATS = (
  103. '%d %B %Y',
  104. '%d %b %Y',
  105. '%B %d %Y',
  106. '%b %d %Y',
  107. '%b %dst %Y %I:%M',
  108. '%b %dnd %Y %I:%M',
  109. '%b %dth %Y %I:%M',
  110. '%Y %m %d',
  111. '%Y-%m-%d',
  112. '%Y/%m/%d',
  113. '%Y/%m/%d %H:%M',
  114. '%Y/%m/%d %H:%M:%S',
  115. '%Y-%m-%d %H:%M:%S',
  116. '%Y-%m-%d %H:%M:%S.%f',
  117. '%d.%m.%Y %H:%M',
  118. '%d.%m.%Y %H.%M',
  119. '%Y-%m-%dT%H:%M:%SZ',
  120. '%Y-%m-%dT%H:%M:%S.%fZ',
  121. '%Y-%m-%dT%H:%M:%S.%f0Z',
  122. '%Y-%m-%dT%H:%M:%S',
  123. '%Y-%m-%dT%H:%M:%S.%f',
  124. '%Y-%m-%dT%H:%M',
  125. )
  126. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  127. DATE_FORMATS_DAY_FIRST.extend([
  128. '%d-%m-%Y',
  129. '%d.%m.%Y',
  130. '%d.%m.%y',
  131. '%d/%m/%Y',
  132. '%d/%m/%y',
  133. '%d/%m/%Y %H:%M:%S',
  134. ])
  135. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  136. DATE_FORMATS_MONTH_FIRST.extend([
  137. '%m-%d-%Y',
  138. '%m.%d.%Y',
  139. '%m/%d/%Y',
  140. '%m/%d/%y',
  141. '%m/%d/%Y %H:%M:%S',
  142. ])
  143. def preferredencoding():
  144. """Get preferred encoding.
  145. Returns the best encoding scheme for the system, based on
  146. locale.getpreferredencoding() and some further tweaks.
  147. """
  148. try:
  149. pref = locale.getpreferredencoding()
  150. 'TEST'.encode(pref)
  151. except Exception:
  152. pref = 'UTF-8'
  153. return pref
  154. def write_json_file(obj, fn):
  155. """ Encode obj as JSON and write it to fn, atomically if possible """
  156. fn = encodeFilename(fn)
  157. if sys.version_info < (3, 0) and sys.platform != 'win32':
  158. encoding = get_filesystem_encoding()
  159. # os.path.basename returns a bytes object, but NamedTemporaryFile
  160. # will fail if the filename contains non ascii characters unless we
  161. # use a unicode object
  162. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  163. # the same for os.path.dirname
  164. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  165. else:
  166. path_basename = os.path.basename
  167. path_dirname = os.path.dirname
  168. args = {
  169. 'suffix': '.tmp',
  170. 'prefix': path_basename(fn) + '.',
  171. 'dir': path_dirname(fn),
  172. 'delete': False,
  173. }
  174. # In Python 2.x, json.dump expects a bytestream.
  175. # In Python 3.x, it writes to a character stream
  176. if sys.version_info < (3, 0):
  177. args['mode'] = 'wb'
  178. else:
  179. args.update({
  180. 'mode': 'w',
  181. 'encoding': 'utf-8',
  182. })
  183. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  184. try:
  185. with tf:
  186. json.dump(obj, tf)
  187. if sys.platform == 'win32':
  188. # Need to remove existing file on Windows, else os.rename raises
  189. # WindowsError or FileExistsError.
  190. try:
  191. os.unlink(fn)
  192. except OSError:
  193. pass
  194. os.rename(tf.name, fn)
  195. except Exception:
  196. try:
  197. os.remove(tf.name)
  198. except OSError:
  199. pass
  200. raise
  201. if sys.version_info >= (2, 7):
  202. def find_xpath_attr(node, xpath, key, val=None):
  203. """ Find the xpath xpath[@key=val] """
  204. assert re.match(r'^[a-zA-Z_-]+$', key)
  205. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  206. return node.find(expr)
  207. else:
  208. def find_xpath_attr(node, xpath, key, val=None):
  209. for f in node.findall(compat_xpath(xpath)):
  210. if key not in f.attrib:
  211. continue
  212. if val is None or f.attrib.get(key) == val:
  213. return f
  214. return None
  215. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  216. # the namespace parameter
  217. def xpath_with_ns(path, ns_map):
  218. components = [c.split(':') for c in path.split('/')]
  219. replaced = []
  220. for c in components:
  221. if len(c) == 1:
  222. replaced.append(c[0])
  223. else:
  224. ns, tag = c
  225. replaced.append('{%s}%s' % (ns_map[ns], tag))
  226. return '/'.join(replaced)
  227. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  228. def _find_xpath(xpath):
  229. return node.find(compat_xpath(xpath))
  230. if isinstance(xpath, (str, compat_str)):
  231. n = _find_xpath(xpath)
  232. else:
  233. for xp in xpath:
  234. n = _find_xpath(xp)
  235. if n is not None:
  236. break
  237. if n is None:
  238. if default is not NO_DEFAULT:
  239. return default
  240. elif fatal:
  241. name = xpath if name is None else name
  242. raise ExtractorError('Could not find XML element %s' % name)
  243. else:
  244. return None
  245. return n
  246. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  247. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  248. if n is None or n == default:
  249. return n
  250. if n.text is None:
  251. if default is not NO_DEFAULT:
  252. return default
  253. elif fatal:
  254. name = xpath if name is None else name
  255. raise ExtractorError('Could not find XML element\'s text %s' % name)
  256. else:
  257. return None
  258. return n.text
  259. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  260. n = find_xpath_attr(node, xpath, key)
  261. if n is None:
  262. if default is not NO_DEFAULT:
  263. return default
  264. elif fatal:
  265. name = '%s[@%s]' % (xpath, key) if name is None else name
  266. raise ExtractorError('Could not find XML attribute %s' % name)
  267. else:
  268. return None
  269. return n.attrib[key]
  270. def get_element_by_id(id, html):
  271. """Return the content of the tag with the specified ID in the passed HTML document"""
  272. return get_element_by_attribute('id', id, html)
  273. def get_element_by_class(class_name, html):
  274. return get_element_by_attribute(
  275. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  276. html, escape_value=False)
  277. def get_element_by_attribute(attribute, value, html, escape_value=True):
  278. """Return the content of the tag with the specified attribute in the passed HTML document"""
  279. value = re.escape(value) if escape_value else value
  280. m = re.search(r'''(?xs)
  281. <([a-zA-Z0-9:._-]+)
  282. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  283. \s+%s=['"]?%s['"]?
  284. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  285. \s*>
  286. (?P<content>.*?)
  287. </\1>
  288. ''' % (re.escape(attribute), value), html)
  289. if not m:
  290. return None
  291. res = m.group('content')
  292. if res.startswith('"') or res.startswith("'"):
  293. res = res[1:-1]
  294. return unescapeHTML(res)
  295. class HTMLAttributeParser(compat_HTMLParser):
  296. """Trivial HTML parser to gather the attributes for a single element"""
  297. def __init__(self):
  298. self.attrs = {}
  299. compat_HTMLParser.__init__(self)
  300. def handle_starttag(self, tag, attrs):
  301. self.attrs = dict(attrs)
  302. def extract_attributes(html_element):
  303. """Given a string for an HTML element such as
  304. <el
  305. a="foo" B="bar" c="&98;az" d=boz
  306. empty= noval entity="&amp;"
  307. sq='"' dq="'"
  308. >
  309. Decode and return a dictionary of attributes.
  310. {
  311. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  312. 'empty': '', 'noval': None, 'entity': '&',
  313. 'sq': '"', 'dq': '\''
  314. }.
  315. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  316. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  317. """
  318. parser = HTMLAttributeParser()
  319. parser.feed(html_element)
  320. parser.close()
  321. return parser.attrs
  322. def clean_html(html):
  323. """Clean an HTML snippet into a readable string"""
  324. if html is None: # Convenience for sanitizing descriptions etc.
  325. return html
  326. # Newline vs <br />
  327. html = html.replace('\n', ' ')
  328. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  329. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  330. # Strip html tags
  331. html = re.sub('<.*?>', '', html)
  332. # Replace html entities
  333. html = unescapeHTML(html)
  334. return html.strip()
  335. def sanitize_open(filename, open_mode):
  336. """Try to open the given filename, and slightly tweak it if this fails.
  337. Attempts to open the given filename. If this fails, it tries to change
  338. the filename slightly, step by step, until it's either able to open it
  339. or it fails and raises a final exception, like the standard open()
  340. function.
  341. It returns the tuple (stream, definitive_file_name).
  342. """
  343. try:
  344. if filename == '-':
  345. if sys.platform == 'win32':
  346. import msvcrt
  347. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  348. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  349. stream = open(encodeFilename(filename), open_mode)
  350. return (stream, filename)
  351. except (IOError, OSError) as err:
  352. if err.errno in (errno.EACCES,):
  353. raise
  354. # In case of error, try to remove win32 forbidden chars
  355. alt_filename = sanitize_path(filename)
  356. if alt_filename == filename:
  357. raise
  358. else:
  359. # An exception here should be caught in the caller
  360. stream = open(encodeFilename(alt_filename), open_mode)
  361. return (stream, alt_filename)
  362. def timeconvert(timestr):
  363. """Convert RFC 2822 defined time string into system timestamp"""
  364. timestamp = None
  365. timetuple = email.utils.parsedate_tz(timestr)
  366. if timetuple is not None:
  367. timestamp = email.utils.mktime_tz(timetuple)
  368. return timestamp
  369. def sanitize_filename(s, restricted=False, is_id=False):
  370. """Sanitizes a string so it could be used as part of a filename.
  371. If restricted is set, use a stricter subset of allowed characters.
  372. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  373. """
  374. def replace_insane(char):
  375. if restricted and char in ACCENT_CHARS:
  376. return ACCENT_CHARS[char]
  377. if char == '?' or ord(char) < 32 or ord(char) == 127:
  378. return ''
  379. elif char == '"':
  380. return '' if restricted else '\''
  381. elif char == ':':
  382. return '_-' if restricted else ' -'
  383. elif char in '\\/|*<>':
  384. return '_'
  385. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  386. return '_'
  387. if restricted and ord(char) > 127:
  388. return '_'
  389. return char
  390. # Handle timestamps
  391. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  392. result = ''.join(map(replace_insane, s))
  393. if not is_id:
  394. while '__' in result:
  395. result = result.replace('__', '_')
  396. result = result.strip('_')
  397. # Common case of "Foreign band name - English song title"
  398. if restricted and result.startswith('-_'):
  399. result = result[2:]
  400. if result.startswith('-'):
  401. result = '_' + result[len('-'):]
  402. result = result.lstrip('.')
  403. if not result:
  404. result = '_'
  405. return result
  406. def sanitize_path(s):
  407. """Sanitizes and normalizes path on Windows"""
  408. if sys.platform != 'win32':
  409. return s
  410. drive_or_unc, _ = os.path.splitdrive(s)
  411. if sys.version_info < (2, 7) and not drive_or_unc:
  412. drive_or_unc, _ = os.path.splitunc(s)
  413. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  414. if drive_or_unc:
  415. norm_path.pop(0)
  416. sanitized_path = [
  417. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
  418. for path_part in norm_path]
  419. if drive_or_unc:
  420. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  421. return os.path.join(*sanitized_path)
  422. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  423. # unwanted failures due to missing protocol
  424. def sanitize_url(url):
  425. return 'http:%s' % url if url.startswith('//') else url
  426. def sanitized_Request(url, *args, **kwargs):
  427. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  428. def orderedSet(iterable):
  429. """ Remove all duplicates from the input iterable """
  430. res = []
  431. for el in iterable:
  432. if el not in res:
  433. res.append(el)
  434. return res
  435. def _htmlentity_transform(entity_with_semicolon):
  436. """Transforms an HTML entity to a character."""
  437. entity = entity_with_semicolon[:-1]
  438. # Known non-numeric HTML entity
  439. if entity in compat_html_entities.name2codepoint:
  440. return compat_chr(compat_html_entities.name2codepoint[entity])
  441. # TODO: HTML5 allows entities without a semicolon. For example,
  442. # '&Eacuteric' should be decoded as 'Éric'.
  443. if entity_with_semicolon in compat_html_entities_html5:
  444. return compat_html_entities_html5[entity_with_semicolon]
  445. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  446. if mobj is not None:
  447. numstr = mobj.group(1)
  448. if numstr.startswith('x'):
  449. base = 16
  450. numstr = '0%s' % numstr
  451. else:
  452. base = 10
  453. # See https://github.com/rg3/youtube-dl/issues/7518
  454. try:
  455. return compat_chr(int(numstr, base))
  456. except ValueError:
  457. pass
  458. # Unknown entity in name, return its literal representation
  459. return '&%s;' % entity
  460. def unescapeHTML(s):
  461. if s is None:
  462. return None
  463. assert type(s) == compat_str
  464. return re.sub(
  465. r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  466. def get_subprocess_encoding():
  467. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  468. # For subprocess calls, encode with locale encoding
  469. # Refer to http://stackoverflow.com/a/9951851/35070
  470. encoding = preferredencoding()
  471. else:
  472. encoding = sys.getfilesystemencoding()
  473. if encoding is None:
  474. encoding = 'utf-8'
  475. return encoding
  476. def encodeFilename(s, for_subprocess=False):
  477. """
  478. @param s The name of the file
  479. """
  480. assert type(s) == compat_str
  481. # Python 3 has a Unicode API
  482. if sys.version_info >= (3, 0):
  483. return s
  484. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  485. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  486. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  487. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  488. return s
  489. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  490. if sys.platform.startswith('java'):
  491. return s
  492. return s.encode(get_subprocess_encoding(), 'ignore')
  493. def decodeFilename(b, for_subprocess=False):
  494. if sys.version_info >= (3, 0):
  495. return b
  496. if not isinstance(b, bytes):
  497. return b
  498. return b.decode(get_subprocess_encoding(), 'ignore')
  499. def encodeArgument(s):
  500. if not isinstance(s, compat_str):
  501. # Legacy code that uses byte strings
  502. # Uncomment the following line after fixing all post processors
  503. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  504. s = s.decode('ascii')
  505. return encodeFilename(s, True)
  506. def decodeArgument(b):
  507. return decodeFilename(b, True)
  508. def decodeOption(optval):
  509. if optval is None:
  510. return optval
  511. if isinstance(optval, bytes):
  512. optval = optval.decode(preferredencoding())
  513. assert isinstance(optval, compat_str)
  514. return optval
  515. def formatSeconds(secs):
  516. if secs > 3600:
  517. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  518. elif secs > 60:
  519. return '%d:%02d' % (secs // 60, secs % 60)
  520. else:
  521. return '%d' % secs
  522. def make_HTTPS_handler(params, **kwargs):
  523. opts_no_check_certificate = params.get('nocheckcertificate', False)
  524. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  525. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  526. if opts_no_check_certificate:
  527. context.check_hostname = False
  528. context.verify_mode = ssl.CERT_NONE
  529. try:
  530. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  531. except TypeError:
  532. # Python 2.7.8
  533. # (create_default_context present but HTTPSHandler has no context=)
  534. pass
  535. if sys.version_info < (3, 2):
  536. return YoutubeDLHTTPSHandler(params, **kwargs)
  537. else: # Python < 3.4
  538. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  539. context.verify_mode = (ssl.CERT_NONE
  540. if opts_no_check_certificate
  541. else ssl.CERT_REQUIRED)
  542. context.set_default_verify_paths()
  543. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  544. def bug_reports_message():
  545. if ytdl_is_updateable():
  546. update_cmd = 'type youtube-dl -U to update'
  547. else:
  548. update_cmd = 'see https://yt-dl.org/update on how to update'
  549. msg = '; please report this issue on https://yt-dl.org/bug .'
  550. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  551. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  552. return msg
  553. class ExtractorError(Exception):
  554. """Error during info extraction."""
  555. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  556. """ tb, if given, is the original traceback (so that it can be printed out).
  557. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  558. """
  559. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  560. expected = True
  561. if video_id is not None:
  562. msg = video_id + ': ' + msg
  563. if cause:
  564. msg += ' (caused by %r)' % cause
  565. if not expected:
  566. msg += bug_reports_message()
  567. super(ExtractorError, self).__init__(msg)
  568. self.traceback = tb
  569. self.exc_info = sys.exc_info() # preserve original exception
  570. self.cause = cause
  571. self.video_id = video_id
  572. def format_traceback(self):
  573. if self.traceback is None:
  574. return None
  575. return ''.join(traceback.format_tb(self.traceback))
  576. class UnsupportedError(ExtractorError):
  577. def __init__(self, url):
  578. super(UnsupportedError, self).__init__(
  579. 'Unsupported URL: %s' % url, expected=True)
  580. self.url = url
  581. class RegexNotFoundError(ExtractorError):
  582. """Error when a regex didn't match"""
  583. pass
  584. class DownloadError(Exception):
  585. """Download Error exception.
  586. This exception may be thrown by FileDownloader objects if they are not
  587. configured to continue on errors. They will contain the appropriate
  588. error message.
  589. """
  590. def __init__(self, msg, exc_info=None):
  591. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  592. super(DownloadError, self).__init__(msg)
  593. self.exc_info = exc_info
  594. class SameFileError(Exception):
  595. """Same File exception.
  596. This exception will be thrown by FileDownloader objects if they detect
  597. multiple files would have to be downloaded to the same file on disk.
  598. """
  599. pass
  600. class PostProcessingError(Exception):
  601. """Post Processing exception.
  602. This exception may be raised by PostProcessor's .run() method to
  603. indicate an error in the postprocessing task.
  604. """
  605. def __init__(self, msg):
  606. self.msg = msg
  607. class MaxDownloadsReached(Exception):
  608. """ --max-downloads limit has been reached. """
  609. pass
  610. class UnavailableVideoError(Exception):
  611. """Unavailable Format exception.
  612. This exception will be thrown when a video is requested
  613. in a format that is not available for that video.
  614. """
  615. pass
  616. class ContentTooShortError(Exception):
  617. """Content Too Short exception.
  618. This exception may be raised by FileDownloader objects when a file they
  619. download is too small for what the server announced first, indicating
  620. the connection was probably interrupted.
  621. """
  622. def __init__(self, downloaded, expected):
  623. # Both in bytes
  624. self.downloaded = downloaded
  625. self.expected = expected
  626. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  627. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  628. # expected HTTP responses to meet HTTP/1.0 or later (see also
  629. # https://github.com/rg3/youtube-dl/issues/6727)
  630. if sys.version_info < (3, 0):
  631. kwargs[b'strict'] = True
  632. hc = http_class(*args, **kwargs)
  633. source_address = ydl_handler._params.get('source_address')
  634. if source_address is not None:
  635. sa = (source_address, 0)
  636. if hasattr(hc, 'source_address'): # Python 2.7+
  637. hc.source_address = sa
  638. else: # Python 2.6
  639. def _hc_connect(self, *args, **kwargs):
  640. sock = compat_socket_create_connection(
  641. (self.host, self.port), self.timeout, sa)
  642. if is_https:
  643. self.sock = ssl.wrap_socket(
  644. sock, self.key_file, self.cert_file,
  645. ssl_version=ssl.PROTOCOL_TLSv1)
  646. else:
  647. self.sock = sock
  648. hc.connect = functools.partial(_hc_connect, hc)
  649. return hc
  650. def handle_youtubedl_headers(headers):
  651. filtered_headers = headers
  652. if 'Youtubedl-no-compression' in filtered_headers:
  653. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  654. del filtered_headers['Youtubedl-no-compression']
  655. return filtered_headers
  656. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  657. """Handler for HTTP requests and responses.
  658. This class, when installed with an OpenerDirector, automatically adds
  659. the standard headers to every HTTP request and handles gzipped and
  660. deflated responses from web servers. If compression is to be avoided in
  661. a particular request, the original request in the program code only has
  662. to include the HTTP header "Youtubedl-no-compression", which will be
  663. removed before making the real request.
  664. Part of this code was copied from:
  665. http://techknack.net/python-urllib2-handlers/
  666. Andrew Rowls, the author of that code, agreed to release it to the
  667. public domain.
  668. """
  669. def __init__(self, params, *args, **kwargs):
  670. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  671. self._params = params
  672. def http_open(self, req):
  673. conn_class = compat_http_client.HTTPConnection
  674. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  675. if socks_proxy:
  676. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  677. del req.headers['Ytdl-socks-proxy']
  678. return self.do_open(functools.partial(
  679. _create_http_connection, self, conn_class, False),
  680. req)
  681. @staticmethod
  682. def deflate(data):
  683. try:
  684. return zlib.decompress(data, -zlib.MAX_WBITS)
  685. except zlib.error:
  686. return zlib.decompress(data)
  687. @staticmethod
  688. def addinfourl_wrapper(stream, headers, url, code):
  689. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  690. return compat_urllib_request.addinfourl(stream, headers, url, code)
  691. ret = compat_urllib_request.addinfourl(stream, headers, url)
  692. ret.code = code
  693. return ret
  694. def http_request(self, req):
  695. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  696. # always respected by websites, some tend to give out URLs with non percent-encoded
  697. # non-ASCII characters (see telemb.py, ard.py [#3412])
  698. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  699. # To work around aforementioned issue we will replace request's original URL with
  700. # percent-encoded one
  701. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  702. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  703. url = req.get_full_url()
  704. url_escaped = escape_url(url)
  705. # Substitute URL if any change after escaping
  706. if url != url_escaped:
  707. req = update_Request(req, url=url_escaped)
  708. for h, v in std_headers.items():
  709. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  710. # The dict keys are capitalized because of this bug by urllib
  711. if h.capitalize() not in req.headers:
  712. req.add_header(h, v)
  713. req.headers = handle_youtubedl_headers(req.headers)
  714. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  715. # Python 2.6 is brain-dead when it comes to fragments
  716. req._Request__original = req._Request__original.partition('#')[0]
  717. req._Request__r_type = req._Request__r_type.partition('#')[0]
  718. return req
  719. def http_response(self, req, resp):
  720. old_resp = resp
  721. # gzip
  722. if resp.headers.get('Content-encoding', '') == 'gzip':
  723. content = resp.read()
  724. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  725. try:
  726. uncompressed = io.BytesIO(gz.read())
  727. except IOError as original_ioerror:
  728. # There may be junk add the end of the file
  729. # See http://stackoverflow.com/q/4928560/35070 for details
  730. for i in range(1, 1024):
  731. try:
  732. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  733. uncompressed = io.BytesIO(gz.read())
  734. except IOError:
  735. continue
  736. break
  737. else:
  738. raise original_ioerror
  739. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  740. resp.msg = old_resp.msg
  741. del resp.headers['Content-encoding']
  742. # deflate
  743. if resp.headers.get('Content-encoding', '') == 'deflate':
  744. gz = io.BytesIO(self.deflate(resp.read()))
  745. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  746. resp.msg = old_resp.msg
  747. del resp.headers['Content-encoding']
  748. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  749. # https://github.com/rg3/youtube-dl/issues/6457).
  750. if 300 <= resp.code < 400:
  751. location = resp.headers.get('Location')
  752. if location:
  753. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  754. if sys.version_info >= (3, 0):
  755. location = location.encode('iso-8859-1').decode('utf-8')
  756. else:
  757. location = location.decode('utf-8')
  758. location_escaped = escape_url(location)
  759. if location != location_escaped:
  760. del resp.headers['Location']
  761. if sys.version_info < (3, 0):
  762. location_escaped = location_escaped.encode('utf-8')
  763. resp.headers['Location'] = location_escaped
  764. return resp
  765. https_request = http_request
  766. https_response = http_response
  767. def make_socks_conn_class(base_class, socks_proxy):
  768. assert issubclass(base_class, (
  769. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  770. url_components = compat_urlparse.urlparse(socks_proxy)
  771. if url_components.scheme.lower() == 'socks5':
  772. socks_type = ProxyType.SOCKS5
  773. elif url_components.scheme.lower() in ('socks', 'socks4'):
  774. socks_type = ProxyType.SOCKS4
  775. elif url_components.scheme.lower() == 'socks4a':
  776. socks_type = ProxyType.SOCKS4A
  777. def unquote_if_non_empty(s):
  778. if not s:
  779. return s
  780. return compat_urllib_parse_unquote_plus(s)
  781. proxy_args = (
  782. socks_type,
  783. url_components.hostname, url_components.port or 1080,
  784. True, # Remote DNS
  785. unquote_if_non_empty(url_components.username),
  786. unquote_if_non_empty(url_components.password),
  787. )
  788. class SocksConnection(base_class):
  789. def connect(self):
  790. self.sock = sockssocket()
  791. self.sock.setproxy(*proxy_args)
  792. if type(self.timeout) in (int, float):
  793. self.sock.settimeout(self.timeout)
  794. self.sock.connect((self.host, self.port))
  795. if isinstance(self, compat_http_client.HTTPSConnection):
  796. if hasattr(self, '_context'): # Python > 2.6
  797. self.sock = self._context.wrap_socket(
  798. self.sock, server_hostname=self.host)
  799. else:
  800. self.sock = ssl.wrap_socket(self.sock)
  801. return SocksConnection
  802. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  803. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  804. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  805. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  806. self._params = params
  807. def https_open(self, req):
  808. kwargs = {}
  809. conn_class = self._https_conn_class
  810. if hasattr(self, '_context'): # python > 2.6
  811. kwargs['context'] = self._context
  812. if hasattr(self, '_check_hostname'): # python 3.x
  813. kwargs['check_hostname'] = self._check_hostname
  814. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  815. if socks_proxy:
  816. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  817. del req.headers['Ytdl-socks-proxy']
  818. return self.do_open(functools.partial(
  819. _create_http_connection, self, conn_class, True),
  820. req, **kwargs)
  821. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  822. def __init__(self, cookiejar=None):
  823. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  824. def http_response(self, request, response):
  825. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  826. # characters in Set-Cookie HTTP header of last response (see
  827. # https://github.com/rg3/youtube-dl/issues/6769).
  828. # In order to at least prevent crashing we will percent encode Set-Cookie
  829. # header before HTTPCookieProcessor starts processing it.
  830. # if sys.version_info < (3, 0) and response.headers:
  831. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  832. # set_cookie = response.headers.get(set_cookie_header)
  833. # if set_cookie:
  834. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  835. # if set_cookie != set_cookie_escaped:
  836. # del response.headers[set_cookie_header]
  837. # response.headers[set_cookie_header] = set_cookie_escaped
  838. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  839. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  840. https_response = http_response
  841. def extract_timezone(date_str):
  842. m = re.search(
  843. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  844. date_str)
  845. if not m:
  846. timezone = datetime.timedelta()
  847. else:
  848. date_str = date_str[:-len(m.group('tz'))]
  849. if not m.group('sign'):
  850. timezone = datetime.timedelta()
  851. else:
  852. sign = 1 if m.group('sign') == '+' else -1
  853. timezone = datetime.timedelta(
  854. hours=sign * int(m.group('hours')),
  855. minutes=sign * int(m.group('minutes')))
  856. return timezone, date_str
  857. def parse_iso8601(date_str, delimiter='T', timezone=None):
  858. """ Return a UNIX timestamp from the given date """
  859. if date_str is None:
  860. return None
  861. date_str = re.sub(r'\.[0-9]+', '', date_str)
  862. if timezone is None:
  863. timezone, date_str = extract_timezone(date_str)
  864. try:
  865. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  866. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  867. return calendar.timegm(dt.timetuple())
  868. except ValueError:
  869. pass
  870. def date_formats(day_first=True):
  871. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  872. def unified_strdate(date_str, day_first=True):
  873. """Return a string with the date in the format YYYYMMDD"""
  874. if date_str is None:
  875. return None
  876. upload_date = None
  877. # Replace commas
  878. date_str = date_str.replace(',', ' ')
  879. # Remove AM/PM + timezone
  880. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  881. _, date_str = extract_timezone(date_str)
  882. for expression in date_formats(day_first):
  883. try:
  884. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  885. except ValueError:
  886. pass
  887. if upload_date is None:
  888. timetuple = email.utils.parsedate_tz(date_str)
  889. if timetuple:
  890. try:
  891. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  892. except ValueError:
  893. pass
  894. if upload_date is not None:
  895. return compat_str(upload_date)
  896. def unified_timestamp(date_str, day_first=True):
  897. if date_str is None:
  898. return None
  899. date_str = date_str.replace(',', ' ')
  900. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  901. timezone, date_str = extract_timezone(date_str)
  902. # Remove AM/PM + timezone
  903. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  904. for expression in date_formats(day_first):
  905. try:
  906. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  907. return calendar.timegm(dt.timetuple())
  908. except ValueError:
  909. pass
  910. timetuple = email.utils.parsedate_tz(date_str)
  911. if timetuple:
  912. return calendar.timegm(timetuple) + pm_delta * 3600
  913. def determine_ext(url, default_ext='unknown_video'):
  914. if url is None:
  915. return default_ext
  916. guess = url.partition('?')[0].rpartition('.')[2]
  917. if re.match(r'^[A-Za-z0-9]+$', guess):
  918. return guess
  919. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  920. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  921. return guess.rstrip('/')
  922. else:
  923. return default_ext
  924. def subtitles_filename(filename, sub_lang, sub_format):
  925. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  926. def date_from_str(date_str):
  927. """
  928. Return a datetime object from a string in the format YYYYMMDD or
  929. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  930. today = datetime.date.today()
  931. if date_str in ('now', 'today'):
  932. return today
  933. if date_str == 'yesterday':
  934. return today - datetime.timedelta(days=1)
  935. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  936. if match is not None:
  937. sign = match.group('sign')
  938. time = int(match.group('time'))
  939. if sign == '-':
  940. time = -time
  941. unit = match.group('unit')
  942. # A bad approximation?
  943. if unit == 'month':
  944. unit = 'day'
  945. time *= 30
  946. elif unit == 'year':
  947. unit = 'day'
  948. time *= 365
  949. unit += 's'
  950. delta = datetime.timedelta(**{unit: time})
  951. return today + delta
  952. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  953. def hyphenate_date(date_str):
  954. """
  955. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  956. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  957. if match is not None:
  958. return '-'.join(match.groups())
  959. else:
  960. return date_str
  961. class DateRange(object):
  962. """Represents a time interval between two dates"""
  963. def __init__(self, start=None, end=None):
  964. """start and end must be strings in the format accepted by date"""
  965. if start is not None:
  966. self.start = date_from_str(start)
  967. else:
  968. self.start = datetime.datetime.min.date()
  969. if end is not None:
  970. self.end = date_from_str(end)
  971. else:
  972. self.end = datetime.datetime.max.date()
  973. if self.start > self.end:
  974. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  975. @classmethod
  976. def day(cls, day):
  977. """Returns a range that only contains the given day"""
  978. return cls(day, day)
  979. def __contains__(self, date):
  980. """Check if the date is in the range"""
  981. if not isinstance(date, datetime.date):
  982. date = date_from_str(date)
  983. return self.start <= date <= self.end
  984. def __str__(self):
  985. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  986. def platform_name():
  987. """ Returns the platform name as a compat_str """
  988. res = platform.platform()
  989. if isinstance(res, bytes):
  990. res = res.decode(preferredencoding())
  991. assert isinstance(res, compat_str)
  992. return res
  993. def _windows_write_string(s, out):
  994. """ Returns True if the string was written using special methods,
  995. False if it has yet to be written out."""
  996. # Adapted from http://stackoverflow.com/a/3259271/35070
  997. import ctypes
  998. import ctypes.wintypes
  999. WIN_OUTPUT_IDS = {
  1000. 1: -11,
  1001. 2: -12,
  1002. }
  1003. try:
  1004. fileno = out.fileno()
  1005. except AttributeError:
  1006. # If the output stream doesn't have a fileno, it's virtual
  1007. return False
  1008. except io.UnsupportedOperation:
  1009. # Some strange Windows pseudo files?
  1010. return False
  1011. if fileno not in WIN_OUTPUT_IDS:
  1012. return False
  1013. GetStdHandle = ctypes.WINFUNCTYPE(
  1014. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  1015. (b'GetStdHandle', ctypes.windll.kernel32))
  1016. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  1017. WriteConsoleW = ctypes.WINFUNCTYPE(
  1018. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  1019. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  1020. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  1021. written = ctypes.wintypes.DWORD(0)
  1022. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  1023. FILE_TYPE_CHAR = 0x0002
  1024. FILE_TYPE_REMOTE = 0x8000
  1025. GetConsoleMode = ctypes.WINFUNCTYPE(
  1026. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  1027. ctypes.POINTER(ctypes.wintypes.DWORD))(
  1028. (b'GetConsoleMode', ctypes.windll.kernel32))
  1029. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  1030. def not_a_console(handle):
  1031. if handle == INVALID_HANDLE_VALUE or handle is None:
  1032. return True
  1033. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  1034. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  1035. if not_a_console(h):
  1036. return False
  1037. def next_nonbmp_pos(s):
  1038. try:
  1039. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  1040. except StopIteration:
  1041. return len(s)
  1042. while s:
  1043. count = min(next_nonbmp_pos(s), 1024)
  1044. ret = WriteConsoleW(
  1045. h, s, count if count else 2, ctypes.byref(written), None)
  1046. if ret == 0:
  1047. raise OSError('Failed to write string')
  1048. if not count: # We just wrote a non-BMP character
  1049. assert written.value == 2
  1050. s = s[1:]
  1051. else:
  1052. assert written.value > 0
  1053. s = s[written.value:]
  1054. return True
  1055. def write_string(s, out=None, encoding=None):
  1056. if out is None:
  1057. out = sys.stderr
  1058. assert type(s) == compat_str
  1059. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  1060. if _windows_write_string(s, out):
  1061. return
  1062. if ('b' in getattr(out, 'mode', '') or
  1063. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  1064. byt = s.encode(encoding or preferredencoding(), 'ignore')
  1065. out.write(byt)
  1066. elif hasattr(out, 'buffer'):
  1067. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1068. byt = s.encode(enc, 'ignore')
  1069. out.buffer.write(byt)
  1070. else:
  1071. out.write(s)
  1072. out.flush()
  1073. def bytes_to_intlist(bs):
  1074. if not bs:
  1075. return []
  1076. if isinstance(bs[0], int): # Python 3
  1077. return list(bs)
  1078. else:
  1079. return [ord(c) for c in bs]
  1080. def intlist_to_bytes(xs):
  1081. if not xs:
  1082. return b''
  1083. return compat_struct_pack('%dB' % len(xs), *xs)
  1084. # Cross-platform file locking
  1085. if sys.platform == 'win32':
  1086. import ctypes.wintypes
  1087. import msvcrt
  1088. class OVERLAPPED(ctypes.Structure):
  1089. _fields_ = [
  1090. ('Internal', ctypes.wintypes.LPVOID),
  1091. ('InternalHigh', ctypes.wintypes.LPVOID),
  1092. ('Offset', ctypes.wintypes.DWORD),
  1093. ('OffsetHigh', ctypes.wintypes.DWORD),
  1094. ('hEvent', ctypes.wintypes.HANDLE),
  1095. ]
  1096. kernel32 = ctypes.windll.kernel32
  1097. LockFileEx = kernel32.LockFileEx
  1098. LockFileEx.argtypes = [
  1099. ctypes.wintypes.HANDLE, # hFile
  1100. ctypes.wintypes.DWORD, # dwFlags
  1101. ctypes.wintypes.DWORD, # dwReserved
  1102. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1103. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1104. ctypes.POINTER(OVERLAPPED) # Overlapped
  1105. ]
  1106. LockFileEx.restype = ctypes.wintypes.BOOL
  1107. UnlockFileEx = kernel32.UnlockFileEx
  1108. UnlockFileEx.argtypes = [
  1109. ctypes.wintypes.HANDLE, # hFile
  1110. ctypes.wintypes.DWORD, # dwReserved
  1111. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1112. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1113. ctypes.POINTER(OVERLAPPED) # Overlapped
  1114. ]
  1115. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1116. whole_low = 0xffffffff
  1117. whole_high = 0x7fffffff
  1118. def _lock_file(f, exclusive):
  1119. overlapped = OVERLAPPED()
  1120. overlapped.Offset = 0
  1121. overlapped.OffsetHigh = 0
  1122. overlapped.hEvent = 0
  1123. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1124. handle = msvcrt.get_osfhandle(f.fileno())
  1125. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1126. whole_low, whole_high, f._lock_file_overlapped_p):
  1127. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1128. def _unlock_file(f):
  1129. assert f._lock_file_overlapped_p
  1130. handle = msvcrt.get_osfhandle(f.fileno())
  1131. if not UnlockFileEx(handle, 0,
  1132. whole_low, whole_high, f._lock_file_overlapped_p):
  1133. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1134. else:
  1135. # Some platforms, such as Jython, is missing fcntl
  1136. try:
  1137. import fcntl
  1138. def _lock_file(f, exclusive):
  1139. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1140. def _unlock_file(f):
  1141. fcntl.flock(f, fcntl.LOCK_UN)
  1142. except ImportError:
  1143. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1144. def _lock_file(f, exclusive):
  1145. raise IOError(UNSUPPORTED_MSG)
  1146. def _unlock_file(f):
  1147. raise IOError(UNSUPPORTED_MSG)
  1148. class locked_file(object):
  1149. def __init__(self, filename, mode, encoding=None):
  1150. assert mode in ['r', 'a', 'w']
  1151. self.f = io.open(filename, mode, encoding=encoding)
  1152. self.mode = mode
  1153. def __enter__(self):
  1154. exclusive = self.mode != 'r'
  1155. try:
  1156. _lock_file(self.f, exclusive)
  1157. except IOError:
  1158. self.f.close()
  1159. raise
  1160. return self
  1161. def __exit__(self, etype, value, traceback):
  1162. try:
  1163. _unlock_file(self.f)
  1164. finally:
  1165. self.f.close()
  1166. def __iter__(self):
  1167. return iter(self.f)
  1168. def write(self, *args):
  1169. return self.f.write(*args)
  1170. def read(self, *args):
  1171. return self.f.read(*args)
  1172. def get_filesystem_encoding():
  1173. encoding = sys.getfilesystemencoding()
  1174. return encoding if encoding is not None else 'utf-8'
  1175. def shell_quote(args):
  1176. quoted_args = []
  1177. encoding = get_filesystem_encoding()
  1178. for a in args:
  1179. if isinstance(a, bytes):
  1180. # We may get a filename encoded with 'encodeFilename'
  1181. a = a.decode(encoding)
  1182. quoted_args.append(pipes.quote(a))
  1183. return ' '.join(quoted_args)
  1184. def smuggle_url(url, data):
  1185. """ Pass additional data in a URL for internal use. """
  1186. url, idata = unsmuggle_url(url, {})
  1187. data.update(idata)
  1188. sdata = compat_urllib_parse_urlencode(
  1189. {'__youtubedl_smuggle': json.dumps(data)})
  1190. return url + '#' + sdata
  1191. def unsmuggle_url(smug_url, default=None):
  1192. if '#__youtubedl_smuggle' not in smug_url:
  1193. return smug_url, default
  1194. url, _, sdata = smug_url.rpartition('#')
  1195. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1196. data = json.loads(jsond)
  1197. return url, data
  1198. def format_bytes(bytes):
  1199. if bytes is None:
  1200. return 'N/A'
  1201. if type(bytes) is str:
  1202. bytes = float(bytes)
  1203. if bytes == 0.0:
  1204. exponent = 0
  1205. else:
  1206. exponent = int(math.log(bytes, 1024.0))
  1207. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1208. converted = float(bytes) / float(1024 ** exponent)
  1209. return '%.2f%s' % (converted, suffix)
  1210. def lookup_unit_table(unit_table, s):
  1211. units_re = '|'.join(re.escape(u) for u in unit_table)
  1212. m = re.match(
  1213. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1214. if not m:
  1215. return None
  1216. num_str = m.group('num').replace(',', '.')
  1217. mult = unit_table[m.group('unit')]
  1218. return int(float(num_str) * mult)
  1219. def parse_filesize(s):
  1220. if s is None:
  1221. return None
  1222. # The lower-case forms are of course incorrect and unofficial,
  1223. # but we support those too
  1224. _UNIT_TABLE = {
  1225. 'B': 1,
  1226. 'b': 1,
  1227. 'bytes': 1,
  1228. 'KiB': 1024,
  1229. 'KB': 1000,
  1230. 'kB': 1024,
  1231. 'Kb': 1000,
  1232. 'kb': 1000,
  1233. 'kilobytes': 1000,
  1234. 'kibibytes': 1024,
  1235. 'MiB': 1024 ** 2,
  1236. 'MB': 1000 ** 2,
  1237. 'mB': 1024 ** 2,
  1238. 'Mb': 1000 ** 2,
  1239. 'mb': 1000 ** 2,
  1240. 'megabytes': 1000 ** 2,
  1241. 'mebibytes': 1024 ** 2,
  1242. 'GiB': 1024 ** 3,
  1243. 'GB': 1000 ** 3,
  1244. 'gB': 1024 ** 3,
  1245. 'Gb': 1000 ** 3,
  1246. 'gb': 1000 ** 3,
  1247. 'gigabytes': 1000 ** 3,
  1248. 'gibibytes': 1024 ** 3,
  1249. 'TiB': 1024 ** 4,
  1250. 'TB': 1000 ** 4,
  1251. 'tB': 1024 ** 4,
  1252. 'Tb': 1000 ** 4,
  1253. 'tb': 1000 ** 4,
  1254. 'terabytes': 1000 ** 4,
  1255. 'tebibytes': 1024 ** 4,
  1256. 'PiB': 1024 ** 5,
  1257. 'PB': 1000 ** 5,
  1258. 'pB': 1024 ** 5,
  1259. 'Pb': 1000 ** 5,
  1260. 'pb': 1000 ** 5,
  1261. 'petabytes': 1000 ** 5,
  1262. 'pebibytes': 1024 ** 5,
  1263. 'EiB': 1024 ** 6,
  1264. 'EB': 1000 ** 6,
  1265. 'eB': 1024 ** 6,
  1266. 'Eb': 1000 ** 6,
  1267. 'eb': 1000 ** 6,
  1268. 'exabytes': 1000 ** 6,
  1269. 'exbibytes': 1024 ** 6,
  1270. 'ZiB': 1024 ** 7,
  1271. 'ZB': 1000 ** 7,
  1272. 'zB': 1024 ** 7,
  1273. 'Zb': 1000 ** 7,
  1274. 'zb': 1000 ** 7,
  1275. 'zettabytes': 1000 ** 7,
  1276. 'zebibytes': 1024 ** 7,
  1277. 'YiB': 1024 ** 8,
  1278. 'YB': 1000 ** 8,
  1279. 'yB': 1024 ** 8,
  1280. 'Yb': 1000 ** 8,
  1281. 'yb': 1000 ** 8,
  1282. 'yottabytes': 1000 ** 8,
  1283. 'yobibytes': 1024 ** 8,
  1284. }
  1285. return lookup_unit_table(_UNIT_TABLE, s)
  1286. def parse_count(s):
  1287. if s is None:
  1288. return None
  1289. s = s.strip()
  1290. if re.match(r'^[\d,.]+$', s):
  1291. return str_to_int(s)
  1292. _UNIT_TABLE = {
  1293. 'k': 1000,
  1294. 'K': 1000,
  1295. 'm': 1000 ** 2,
  1296. 'M': 1000 ** 2,
  1297. 'kk': 1000 ** 2,
  1298. 'KK': 1000 ** 2,
  1299. }
  1300. return lookup_unit_table(_UNIT_TABLE, s)
  1301. def month_by_name(name, lang='en'):
  1302. """ Return the number of a month by (locale-independently) English name """
  1303. name_list = ENGLISH_MONTH_NAMES
  1304. if lang == 'fr':
  1305. name_list = FRENCH_MONTH_NAMES
  1306. try:
  1307. return name_list.index(name) + 1
  1308. except ValueError:
  1309. return None
  1310. def month_by_abbreviation(abbrev):
  1311. """ Return the number of a month by (locale-independently) English
  1312. abbreviations """
  1313. try:
  1314. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1315. except ValueError:
  1316. return None
  1317. def fix_xml_ampersands(xml_str):
  1318. """Replace all the '&' by '&amp;' in XML"""
  1319. return re.sub(
  1320. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1321. '&amp;',
  1322. xml_str)
  1323. def setproctitle(title):
  1324. assert isinstance(title, compat_str)
  1325. # ctypes in Jython is not complete
  1326. # http://bugs.jython.org/issue2148
  1327. if sys.platform.startswith('java'):
  1328. return
  1329. try:
  1330. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1331. except OSError:
  1332. return
  1333. title_bytes = title.encode('utf-8')
  1334. buf = ctypes.create_string_buffer(len(title_bytes))
  1335. buf.value = title_bytes
  1336. try:
  1337. libc.prctl(15, buf, 0, 0, 0)
  1338. except AttributeError:
  1339. return # Strange libc, just skip this
  1340. def remove_start(s, start):
  1341. return s[len(start):] if s is not None and s.startswith(start) else s
  1342. def remove_end(s, end):
  1343. return s[:-len(end)] if s is not None and s.endswith(end) else s
  1344. def remove_quotes(s):
  1345. if s is None or len(s) < 2:
  1346. return s
  1347. for quote in ('"', "'", ):
  1348. if s[0] == quote and s[-1] == quote:
  1349. return s[1:-1]
  1350. return s
  1351. def url_basename(url):
  1352. path = compat_urlparse.urlparse(url).path
  1353. return path.strip('/').split('/')[-1]
  1354. class HEADRequest(compat_urllib_request.Request):
  1355. def get_method(self):
  1356. return 'HEAD'
  1357. class PUTRequest(compat_urllib_request.Request):
  1358. def get_method(self):
  1359. return 'PUT'
  1360. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1361. if get_attr:
  1362. if v is not None:
  1363. v = getattr(v, get_attr, None)
  1364. if v == '':
  1365. v = None
  1366. if v is None:
  1367. return default
  1368. try:
  1369. return int(v) * invscale // scale
  1370. except ValueError:
  1371. return default
  1372. def str_or_none(v, default=None):
  1373. return default if v is None else compat_str(v)
  1374. def str_to_int(int_str):
  1375. """ A more relaxed version of int_or_none """
  1376. if int_str is None:
  1377. return None
  1378. int_str = re.sub(r'[,\.\+]', '', int_str)
  1379. return int(int_str)
  1380. def float_or_none(v, scale=1, invscale=1, default=None):
  1381. if v is None:
  1382. return default
  1383. try:
  1384. return float(v) * invscale / scale
  1385. except ValueError:
  1386. return default
  1387. def strip_or_none(v):
  1388. return None if v is None else v.strip()
  1389. def parse_duration(s):
  1390. if not isinstance(s, compat_basestring):
  1391. return None
  1392. s = s.strip()
  1393. days, hours, mins, secs, ms = [None] * 5
  1394. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?$', s)
  1395. if m:
  1396. days, hours, mins, secs, ms = m.groups()
  1397. else:
  1398. m = re.match(
  1399. r'''(?ix)(?:P?T)?
  1400. (?:
  1401. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1402. )?
  1403. (?:
  1404. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1405. )?
  1406. (?:
  1407. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1408. )?
  1409. (?:
  1410. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1411. )?$''', s)
  1412. if m:
  1413. days, hours, mins, secs, ms = m.groups()
  1414. else:
  1415. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)$', s)
  1416. if m:
  1417. hours, mins = m.groups()
  1418. else:
  1419. return None
  1420. duration = 0
  1421. if secs:
  1422. duration += float(secs)
  1423. if mins:
  1424. duration += float(mins) * 60
  1425. if hours:
  1426. duration += float(hours) * 60 * 60
  1427. if days:
  1428. duration += float(days) * 24 * 60 * 60
  1429. if ms:
  1430. duration += float(ms)
  1431. return duration
  1432. def prepend_extension(filename, ext, expected_real_ext=None):
  1433. name, real_ext = os.path.splitext(filename)
  1434. return (
  1435. '{0}.{1}{2}'.format(name, ext, real_ext)
  1436. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1437. else '{0}.{1}'.format(filename, ext))
  1438. def replace_extension(filename, ext, expected_real_ext=None):
  1439. name, real_ext = os.path.splitext(filename)
  1440. return '{0}.{1}'.format(
  1441. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1442. ext)
  1443. def check_executable(exe, args=[]):
  1444. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1445. args can be a list of arguments for a short output (like -version) """
  1446. try:
  1447. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1448. except OSError:
  1449. return False
  1450. return exe
  1451. def get_exe_version(exe, args=['--version'],
  1452. version_re=None, unrecognized='present'):
  1453. """ Returns the version of the specified executable,
  1454. or False if the executable is not present """
  1455. try:
  1456. out, _ = subprocess.Popen(
  1457. [encodeArgument(exe)] + args,
  1458. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1459. except OSError:
  1460. return False
  1461. if isinstance(out, bytes): # Python 2.x
  1462. out = out.decode('ascii', 'ignore')
  1463. return detect_exe_version(out, version_re, unrecognized)
  1464. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1465. assert isinstance(output, compat_str)
  1466. if version_re is None:
  1467. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1468. m = re.search(version_re, output)
  1469. if m:
  1470. return m.group(1)
  1471. else:
  1472. return unrecognized
  1473. class PagedList(object):
  1474. def __len__(self):
  1475. # This is only useful for tests
  1476. return len(self.getslice())
  1477. class OnDemandPagedList(PagedList):
  1478. def __init__(self, pagefunc, pagesize, use_cache=False):
  1479. self._pagefunc = pagefunc
  1480. self._pagesize = pagesize
  1481. self._use_cache = use_cache
  1482. if use_cache:
  1483. self._cache = {}
  1484. def getslice(self, start=0, end=None):
  1485. res = []
  1486. for pagenum in itertools.count(start // self._pagesize):
  1487. firstid = pagenum * self._pagesize
  1488. nextfirstid = pagenum * self._pagesize + self._pagesize
  1489. if start >= nextfirstid:
  1490. continue
  1491. page_results = None
  1492. if self._use_cache:
  1493. page_results = self._cache.get(pagenum)
  1494. if page_results is None:
  1495. page_results = list(self._pagefunc(pagenum))
  1496. if self._use_cache:
  1497. self._cache[pagenum] = page_results
  1498. startv = (
  1499. start % self._pagesize
  1500. if firstid <= start < nextfirstid
  1501. else 0)
  1502. endv = (
  1503. ((end - 1) % self._pagesize) + 1
  1504. if (end is not None and firstid <= end <= nextfirstid)
  1505. else None)
  1506. if startv != 0 or endv is not None:
  1507. page_results = page_results[startv:endv]
  1508. res.extend(page_results)
  1509. # A little optimization - if current page is not "full", ie. does
  1510. # not contain page_size videos then we can assume that this page
  1511. # is the last one - there are no more ids on further pages -
  1512. # i.e. no need to query again.
  1513. if len(page_results) + startv < self._pagesize:
  1514. break
  1515. # If we got the whole page, but the next page is not interesting,
  1516. # break out early as well
  1517. if end == nextfirstid:
  1518. break
  1519. return res
  1520. class InAdvancePagedList(PagedList):
  1521. def __init__(self, pagefunc, pagecount, pagesize):
  1522. self._pagefunc = pagefunc
  1523. self._pagecount = pagecount
  1524. self._pagesize = pagesize
  1525. def getslice(self, start=0, end=None):
  1526. res = []
  1527. start_page = start // self._pagesize
  1528. end_page = (
  1529. self._pagecount if end is None else (end // self._pagesize + 1))
  1530. skip_elems = start - start_page * self._pagesize
  1531. only_more = None if end is None else end - start
  1532. for pagenum in range(start_page, end_page):
  1533. page = list(self._pagefunc(pagenum))
  1534. if skip_elems:
  1535. page = page[skip_elems:]
  1536. skip_elems = None
  1537. if only_more is not None:
  1538. if len(page) < only_more:
  1539. only_more -= len(page)
  1540. else:
  1541. page = page[:only_more]
  1542. res.extend(page)
  1543. break
  1544. res.extend(page)
  1545. return res
  1546. def uppercase_escape(s):
  1547. unicode_escape = codecs.getdecoder('unicode_escape')
  1548. return re.sub(
  1549. r'\\U[0-9a-fA-F]{8}',
  1550. lambda m: unicode_escape(m.group(0))[0],
  1551. s)
  1552. def lowercase_escape(s):
  1553. unicode_escape = codecs.getdecoder('unicode_escape')
  1554. return re.sub(
  1555. r'\\u[0-9a-fA-F]{4}',
  1556. lambda m: unicode_escape(m.group(0))[0],
  1557. s)
  1558. def escape_rfc3986(s):
  1559. """Escape non-ASCII characters as suggested by RFC 3986"""
  1560. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1561. s = s.encode('utf-8')
  1562. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1563. def escape_url(url):
  1564. """Escape URL as suggested by RFC 3986"""
  1565. url_parsed = compat_urllib_parse_urlparse(url)
  1566. return url_parsed._replace(
  1567. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1568. path=escape_rfc3986(url_parsed.path),
  1569. params=escape_rfc3986(url_parsed.params),
  1570. query=escape_rfc3986(url_parsed.query),
  1571. fragment=escape_rfc3986(url_parsed.fragment)
  1572. ).geturl()
  1573. def read_batch_urls(batch_fd):
  1574. def fixup(url):
  1575. if not isinstance(url, compat_str):
  1576. url = url.decode('utf-8', 'replace')
  1577. BOM_UTF8 = '\xef\xbb\xbf'
  1578. if url.startswith(BOM_UTF8):
  1579. url = url[len(BOM_UTF8):]
  1580. url = url.strip()
  1581. if url.startswith(('#', ';', ']')):
  1582. return False
  1583. return url
  1584. with contextlib.closing(batch_fd) as fd:
  1585. return [url for url in map(fixup, fd) if url]
  1586. def urlencode_postdata(*args, **kargs):
  1587. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1588. def update_url_query(url, query):
  1589. if not query:
  1590. return url
  1591. parsed_url = compat_urlparse.urlparse(url)
  1592. qs = compat_parse_qs(parsed_url.query)
  1593. qs.update(query)
  1594. return compat_urlparse.urlunparse(parsed_url._replace(
  1595. query=compat_urllib_parse_urlencode(qs, True)))
  1596. def update_Request(req, url=None, data=None, headers={}, query={}):
  1597. req_headers = req.headers.copy()
  1598. req_headers.update(headers)
  1599. req_data = data or req.data
  1600. req_url = update_url_query(url or req.get_full_url(), query)
  1601. req_get_method = req.get_method()
  1602. if req_get_method == 'HEAD':
  1603. req_type = HEADRequest
  1604. elif req_get_method == 'PUT':
  1605. req_type = PUTRequest
  1606. else:
  1607. req_type = compat_urllib_request.Request
  1608. new_req = req_type(
  1609. req_url, data=req_data, headers=req_headers,
  1610. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1611. if hasattr(req, 'timeout'):
  1612. new_req.timeout = req.timeout
  1613. return new_req
  1614. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1615. if isinstance(key_or_keys, (list, tuple)):
  1616. for key in key_or_keys:
  1617. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1618. continue
  1619. return d[key]
  1620. return default
  1621. return d.get(key_or_keys, default)
  1622. def try_get(src, getter, expected_type=None):
  1623. try:
  1624. v = getter(src)
  1625. except (AttributeError, KeyError, TypeError, IndexError):
  1626. pass
  1627. else:
  1628. if expected_type is None or isinstance(v, expected_type):
  1629. return v
  1630. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1631. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1632. US_RATINGS = {
  1633. 'G': 0,
  1634. 'PG': 10,
  1635. 'PG-13': 13,
  1636. 'R': 16,
  1637. 'NC': 18,
  1638. }
  1639. TV_PARENTAL_GUIDELINES = {
  1640. 'TV-Y': 0,
  1641. 'TV-Y7': 7,
  1642. 'TV-G': 0,
  1643. 'TV-PG': 0,
  1644. 'TV-14': 14,
  1645. 'TV-MA': 17,
  1646. }
  1647. def parse_age_limit(s):
  1648. if type(s) == int:
  1649. return s if 0 <= s <= 21 else None
  1650. if not isinstance(s, compat_basestring):
  1651. return None
  1652. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1653. if m:
  1654. return int(m.group('age'))
  1655. if s in US_RATINGS:
  1656. return US_RATINGS[s]
  1657. return TV_PARENTAL_GUIDELINES.get(s)
  1658. def strip_jsonp(code):
  1659. return re.sub(
  1660. r'(?s)^[a-zA-Z0-9_.$]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1661. def js_to_json(code):
  1662. def fix_kv(m):
  1663. v = m.group(0)
  1664. if v in ('true', 'false', 'null'):
  1665. return v
  1666. elif v.startswith('/*') or v == ',':
  1667. return ""
  1668. if v[0] in ("'", '"'):
  1669. v = re.sub(r'(?s)\\.|"', lambda m: {
  1670. '"': '\\"',
  1671. "\\'": "'",
  1672. '\\\n': '',
  1673. '\\x': '\\u00',
  1674. }.get(m.group(0), m.group(0)), v[1:-1])
  1675. INTEGER_TABLE = (
  1676. (r'^(0[xX][0-9a-fA-F]+)\s*:?$', 16),
  1677. (r'^(0+[0-7]+)\s*:?$', 8),
  1678. )
  1679. for regex, base in INTEGER_TABLE:
  1680. im = re.match(regex, v)
  1681. if im:
  1682. i = int(im.group(1), base)
  1683. return '"%d":' % i if v.endswith(':') else '%d' % i
  1684. return '"%s"' % v
  1685. return re.sub(r'''(?sx)
  1686. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1687. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1688. /\*.*?\*/|,(?=\s*[\]}])|
  1689. [a-zA-Z_][.a-zA-Z_0-9]*|
  1690. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
  1691. [0-9]+(?=\s*:)
  1692. ''', fix_kv, code)
  1693. def qualities(quality_ids):
  1694. """ Get a numeric quality value out of a list of possible values """
  1695. def q(qid):
  1696. try:
  1697. return quality_ids.index(qid)
  1698. except ValueError:
  1699. return -1
  1700. return q
  1701. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1702. def limit_length(s, length):
  1703. """ Add ellipses to overly long strings """
  1704. if s is None:
  1705. return None
  1706. ELLIPSES = '...'
  1707. if len(s) > length:
  1708. return s[:length - len(ELLIPSES)] + ELLIPSES
  1709. return s
  1710. def version_tuple(v):
  1711. return tuple(int(e) for e in re.split(r'[-.]', v))
  1712. def is_outdated_version(version, limit, assume_new=True):
  1713. if not version:
  1714. return not assume_new
  1715. try:
  1716. return version_tuple(version) < version_tuple(limit)
  1717. except ValueError:
  1718. return not assume_new
  1719. def ytdl_is_updateable():
  1720. """ Returns if youtube-dl can be updated with -U """
  1721. from zipimport import zipimporter
  1722. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1723. def args_to_str(args):
  1724. # Get a short string representation for a subprocess command
  1725. return ' '.join(compat_shlex_quote(a) for a in args)
  1726. def error_to_compat_str(err):
  1727. err_str = str(err)
  1728. # On python 2 error byte string must be decoded with proper
  1729. # encoding rather than ascii
  1730. if sys.version_info[0] < 3:
  1731. err_str = err_str.decode(preferredencoding())
  1732. return err_str
  1733. def mimetype2ext(mt):
  1734. if mt is None:
  1735. return None
  1736. ext = {
  1737. 'audio/mp4': 'm4a',
  1738. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1739. # it's the most popular one
  1740. 'audio/mpeg': 'mp3',
  1741. }.get(mt)
  1742. if ext is not None:
  1743. return ext
  1744. _, _, res = mt.rpartition('/')
  1745. res = res.split(';')[0].strip().lower()
  1746. return {
  1747. '3gpp': '3gp',
  1748. 'smptett+xml': 'tt',
  1749. 'srt': 'srt',
  1750. 'ttaf+xml': 'dfxp',
  1751. 'ttml+xml': 'ttml',
  1752. 'vtt': 'vtt',
  1753. 'x-flv': 'flv',
  1754. 'x-mp4-fragmented': 'mp4',
  1755. 'x-ms-wmv': 'wmv',
  1756. 'mpegurl': 'm3u8',
  1757. 'x-mpegurl': 'm3u8',
  1758. 'vnd.apple.mpegurl': 'm3u8',
  1759. 'dash+xml': 'mpd',
  1760. 'f4m': 'f4m',
  1761. 'f4m+xml': 'f4m',
  1762. 'hds+xml': 'f4m',
  1763. 'vnd.ms-sstr+xml': 'ism',
  1764. 'quicktime': 'mov',
  1765. }.get(res, res)
  1766. def parse_codecs(codecs_str):
  1767. # http://tools.ietf.org/html/rfc6381
  1768. if not codecs_str:
  1769. return {}
  1770. splited_codecs = list(filter(None, map(
  1771. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  1772. vcodec, acodec = None, None
  1773. for full_codec in splited_codecs:
  1774. codec = full_codec.split('.')[0]
  1775. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v'):
  1776. if not vcodec:
  1777. vcodec = full_codec
  1778. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3'):
  1779. if not acodec:
  1780. acodec = full_codec
  1781. else:
  1782. write_string('WARNING: Unknown codec %s' % full_codec, sys.stderr)
  1783. if not vcodec and not acodec:
  1784. if len(splited_codecs) == 2:
  1785. return {
  1786. 'vcodec': vcodec,
  1787. 'acodec': acodec,
  1788. }
  1789. elif len(splited_codecs) == 1:
  1790. return {
  1791. 'vcodec': 'none',
  1792. 'acodec': vcodec,
  1793. }
  1794. else:
  1795. return {
  1796. 'vcodec': vcodec or 'none',
  1797. 'acodec': acodec or 'none',
  1798. }
  1799. return {}
  1800. def urlhandle_detect_ext(url_handle):
  1801. getheader = url_handle.headers.get
  1802. cd = getheader('Content-Disposition')
  1803. if cd:
  1804. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1805. if m:
  1806. e = determine_ext(m.group('filename'), default_ext=None)
  1807. if e:
  1808. return e
  1809. return mimetype2ext(getheader('Content-Type'))
  1810. def encode_data_uri(data, mime_type):
  1811. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1812. def age_restricted(content_limit, age_limit):
  1813. """ Returns True iff the content should be blocked """
  1814. if age_limit is None: # No limit set
  1815. return False
  1816. if content_limit is None:
  1817. return False # Content available for everyone
  1818. return age_limit < content_limit
  1819. def is_html(first_bytes):
  1820. """ Detect whether a file contains HTML by examining its first bytes. """
  1821. BOMS = [
  1822. (b'\xef\xbb\xbf', 'utf-8'),
  1823. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1824. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1825. (b'\xff\xfe', 'utf-16-le'),
  1826. (b'\xfe\xff', 'utf-16-be'),
  1827. ]
  1828. for bom, enc in BOMS:
  1829. if first_bytes.startswith(bom):
  1830. s = first_bytes[len(bom):].decode(enc, 'replace')
  1831. break
  1832. else:
  1833. s = first_bytes.decode('utf-8', 'replace')
  1834. return re.match(r'^\s*<', s)
  1835. def determine_protocol(info_dict):
  1836. protocol = info_dict.get('protocol')
  1837. if protocol is not None:
  1838. return protocol
  1839. url = info_dict['url']
  1840. if url.startswith('rtmp'):
  1841. return 'rtmp'
  1842. elif url.startswith('mms'):
  1843. return 'mms'
  1844. elif url.startswith('rtsp'):
  1845. return 'rtsp'
  1846. ext = determine_ext(url)
  1847. if ext == 'm3u8':
  1848. return 'm3u8'
  1849. elif ext == 'f4m':
  1850. return 'f4m'
  1851. return compat_urllib_parse_urlparse(url).scheme
  1852. def render_table(header_row, data):
  1853. """ Render a list of rows, each as a list of values """
  1854. table = [header_row] + data
  1855. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1856. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1857. return '\n'.join(format_str % tuple(row) for row in table)
  1858. def _match_one(filter_part, dct):
  1859. COMPARISON_OPERATORS = {
  1860. '<': operator.lt,
  1861. '<=': operator.le,
  1862. '>': operator.gt,
  1863. '>=': operator.ge,
  1864. '=': operator.eq,
  1865. '!=': operator.ne,
  1866. }
  1867. operator_rex = re.compile(r'''(?x)\s*
  1868. (?P<key>[a-z_]+)
  1869. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1870. (?:
  1871. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1872. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1873. )
  1874. \s*$
  1875. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1876. m = operator_rex.search(filter_part)
  1877. if m:
  1878. op = COMPARISON_OPERATORS[m.group('op')]
  1879. if m.group('strval') is not None:
  1880. if m.group('op') not in ('=', '!='):
  1881. raise ValueError(
  1882. 'Operator %s does not support string values!' % m.group('op'))
  1883. comparison_value = m.group('strval')
  1884. else:
  1885. try:
  1886. comparison_value = int(m.group('intval'))
  1887. except ValueError:
  1888. comparison_value = parse_filesize(m.group('intval'))
  1889. if comparison_value is None:
  1890. comparison_value = parse_filesize(m.group('intval') + 'B')
  1891. if comparison_value is None:
  1892. raise ValueError(
  1893. 'Invalid integer value %r in filter part %r' % (
  1894. m.group('intval'), filter_part))
  1895. actual_value = dct.get(m.group('key'))
  1896. if actual_value is None:
  1897. return m.group('none_inclusive')
  1898. return op(actual_value, comparison_value)
  1899. UNARY_OPERATORS = {
  1900. '': lambda v: v is not None,
  1901. '!': lambda v: v is None,
  1902. }
  1903. operator_rex = re.compile(r'''(?x)\s*
  1904. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1905. \s*$
  1906. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1907. m = operator_rex.search(filter_part)
  1908. if m:
  1909. op = UNARY_OPERATORS[m.group('op')]
  1910. actual_value = dct.get(m.group('key'))
  1911. return op(actual_value)
  1912. raise ValueError('Invalid filter part %r' % filter_part)
  1913. def match_str(filter_str, dct):
  1914. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1915. return all(
  1916. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1917. def match_filter_func(filter_str):
  1918. def _match_func(info_dict):
  1919. if match_str(filter_str, info_dict):
  1920. return None
  1921. else:
  1922. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1923. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1924. return _match_func
  1925. def parse_dfxp_time_expr(time_expr):
  1926. if not time_expr:
  1927. return
  1928. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1929. if mobj:
  1930. return float(mobj.group('time_offset'))
  1931. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1932. if mobj:
  1933. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1934. def srt_subtitles_timecode(seconds):
  1935. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1936. def dfxp2srt(dfxp_data):
  1937. _x = functools.partial(xpath_with_ns, ns_map={
  1938. 'ttml': 'http://www.w3.org/ns/ttml',
  1939. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1940. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1941. })
  1942. class TTMLPElementParser(object):
  1943. out = ''
  1944. def start(self, tag, attrib):
  1945. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1946. self.out += '\n'
  1947. def end(self, tag):
  1948. pass
  1949. def data(self, data):
  1950. self.out += data
  1951. def close(self):
  1952. return self.out.strip()
  1953. def parse_node(node):
  1954. target = TTMLPElementParser()
  1955. parser = xml.etree.ElementTree.XMLParser(target=target)
  1956. parser.feed(xml.etree.ElementTree.tostring(node))
  1957. return parser.close()
  1958. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1959. out = []
  1960. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  1961. if not paras:
  1962. raise ValueError('Invalid dfxp/TTML subtitle')
  1963. for para, index in zip(paras, itertools.count(1)):
  1964. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1965. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1966. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1967. if begin_time is None:
  1968. continue
  1969. if not end_time:
  1970. if not dur:
  1971. continue
  1972. end_time = begin_time + dur
  1973. out.append('%d\n%s --> %s\n%s\n\n' % (
  1974. index,
  1975. srt_subtitles_timecode(begin_time),
  1976. srt_subtitles_timecode(end_time),
  1977. parse_node(para)))
  1978. return ''.join(out)
  1979. def cli_option(params, command_option, param):
  1980. param = params.get(param)
  1981. if param:
  1982. param = compat_str(param)
  1983. return [command_option, param] if param is not None else []
  1984. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1985. param = params.get(param)
  1986. assert isinstance(param, bool)
  1987. if separator:
  1988. return [command_option + separator + (true_value if param else false_value)]
  1989. return [command_option, true_value if param else false_value]
  1990. def cli_valueless_option(params, command_option, param, expected_value=True):
  1991. param = params.get(param)
  1992. return [command_option] if param == expected_value else []
  1993. def cli_configuration_args(params, param, default=[]):
  1994. ex_args = params.get(param)
  1995. if ex_args is None:
  1996. return default
  1997. assert isinstance(ex_args, list)
  1998. return ex_args
  1999. class ISO639Utils(object):
  2000. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  2001. _lang_map = {
  2002. 'aa': 'aar',
  2003. 'ab': 'abk',
  2004. 'ae': 'ave',
  2005. 'af': 'afr',
  2006. 'ak': 'aka',
  2007. 'am': 'amh',
  2008. 'an': 'arg',
  2009. 'ar': 'ara',
  2010. 'as': 'asm',
  2011. 'av': 'ava',
  2012. 'ay': 'aym',
  2013. 'az': 'aze',
  2014. 'ba': 'bak',
  2015. 'be': 'bel',
  2016. 'bg': 'bul',
  2017. 'bh': 'bih',
  2018. 'bi': 'bis',
  2019. 'bm': 'bam',
  2020. 'bn': 'ben',
  2021. 'bo': 'bod',
  2022. 'br': 'bre',
  2023. 'bs': 'bos',
  2024. 'ca': 'cat',
  2025. 'ce': 'che',
  2026. 'ch': 'cha',
  2027. 'co': 'cos',
  2028. 'cr': 'cre',
  2029. 'cs': 'ces',
  2030. 'cu': 'chu',
  2031. 'cv': 'chv',
  2032. 'cy': 'cym',
  2033. 'da': 'dan',
  2034. 'de': 'deu',
  2035. 'dv': 'div',
  2036. 'dz': 'dzo',
  2037. 'ee': 'ewe',
  2038. 'el': 'ell',
  2039. 'en': 'eng',
  2040. 'eo': 'epo',
  2041. 'es': 'spa',
  2042. 'et': 'est',
  2043. 'eu': 'eus',
  2044. 'fa': 'fas',
  2045. 'ff': 'ful',
  2046. 'fi': 'fin',
  2047. 'fj': 'fij',
  2048. 'fo': 'fao',
  2049. 'fr': 'fra',
  2050. 'fy': 'fry',
  2051. 'ga': 'gle',
  2052. 'gd': 'gla',
  2053. 'gl': 'glg',
  2054. 'gn': 'grn',
  2055. 'gu': 'guj',
  2056. 'gv': 'glv',
  2057. 'ha': 'hau',
  2058. 'he': 'heb',
  2059. 'hi': 'hin',
  2060. 'ho': 'hmo',
  2061. 'hr': 'hrv',
  2062. 'ht': 'hat',
  2063. 'hu': 'hun',
  2064. 'hy': 'hye',
  2065. 'hz': 'her',
  2066. 'ia': 'ina',
  2067. 'id': 'ind',
  2068. 'ie': 'ile',
  2069. 'ig': 'ibo',
  2070. 'ii': 'iii',
  2071. 'ik': 'ipk',
  2072. 'io': 'ido',
  2073. 'is': 'isl',
  2074. 'it': 'ita',
  2075. 'iu': 'iku',
  2076. 'ja': 'jpn',
  2077. 'jv': 'jav',
  2078. 'ka': 'kat',
  2079. 'kg': 'kon',
  2080. 'ki': 'kik',
  2081. 'kj': 'kua',
  2082. 'kk': 'kaz',
  2083. 'kl': 'kal',
  2084. 'km': 'khm',
  2085. 'kn': 'kan',
  2086. 'ko': 'kor',
  2087. 'kr': 'kau',
  2088. 'ks': 'kas',
  2089. 'ku': 'kur',
  2090. 'kv': 'kom',
  2091. 'kw': 'cor',
  2092. 'ky': 'kir',
  2093. 'la': 'lat',
  2094. 'lb': 'ltz',
  2095. 'lg': 'lug',
  2096. 'li': 'lim',
  2097. 'ln': 'lin',
  2098. 'lo': 'lao',
  2099. 'lt': 'lit',
  2100. 'lu': 'lub',
  2101. 'lv': 'lav',
  2102. 'mg': 'mlg',
  2103. 'mh': 'mah',
  2104. 'mi': 'mri',
  2105. 'mk': 'mkd',
  2106. 'ml': 'mal',
  2107. 'mn': 'mon',
  2108. 'mr': 'mar',
  2109. 'ms': 'msa',
  2110. 'mt': 'mlt',
  2111. 'my': 'mya',
  2112. 'na': 'nau',
  2113. 'nb': 'nob',
  2114. 'nd': 'nde',
  2115. 'ne': 'nep',
  2116. 'ng': 'ndo',
  2117. 'nl': 'nld',
  2118. 'nn': 'nno',
  2119. 'no': 'nor',
  2120. 'nr': 'nbl',
  2121. 'nv': 'nav',
  2122. 'ny': 'nya',
  2123. 'oc': 'oci',
  2124. 'oj': 'oji',
  2125. 'om': 'orm',
  2126. 'or': 'ori',
  2127. 'os': 'oss',
  2128. 'pa': 'pan',
  2129. 'pi': 'pli',
  2130. 'pl': 'pol',
  2131. 'ps': 'pus',
  2132. 'pt': 'por',
  2133. 'qu': 'que',
  2134. 'rm': 'roh',
  2135. 'rn': 'run',
  2136. 'ro': 'ron',
  2137. 'ru': 'rus',
  2138. 'rw': 'kin',
  2139. 'sa': 'san',
  2140. 'sc': 'srd',
  2141. 'sd': 'snd',
  2142. 'se': 'sme',
  2143. 'sg': 'sag',
  2144. 'si': 'sin',
  2145. 'sk': 'slk',
  2146. 'sl': 'slv',
  2147. 'sm': 'smo',
  2148. 'sn': 'sna',
  2149. 'so': 'som',
  2150. 'sq': 'sqi',
  2151. 'sr': 'srp',
  2152. 'ss': 'ssw',
  2153. 'st': 'sot',
  2154. 'su': 'sun',
  2155. 'sv': 'swe',
  2156. 'sw': 'swa',
  2157. 'ta': 'tam',
  2158. 'te': 'tel',
  2159. 'tg': 'tgk',
  2160. 'th': 'tha',
  2161. 'ti': 'tir',
  2162. 'tk': 'tuk',
  2163. 'tl': 'tgl',
  2164. 'tn': 'tsn',
  2165. 'to': 'ton',
  2166. 'tr': 'tur',
  2167. 'ts': 'tso',
  2168. 'tt': 'tat',
  2169. 'tw': 'twi',
  2170. 'ty': 'tah',
  2171. 'ug': 'uig',
  2172. 'uk': 'ukr',
  2173. 'ur': 'urd',
  2174. 'uz': 'uzb',
  2175. 've': 'ven',
  2176. 'vi': 'vie',
  2177. 'vo': 'vol',
  2178. 'wa': 'wln',
  2179. 'wo': 'wol',
  2180. 'xh': 'xho',
  2181. 'yi': 'yid',
  2182. 'yo': 'yor',
  2183. 'za': 'zha',
  2184. 'zh': 'zho',
  2185. 'zu': 'zul',
  2186. }
  2187. @classmethod
  2188. def short2long(cls, code):
  2189. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2190. return cls._lang_map.get(code[:2])
  2191. @classmethod
  2192. def long2short(cls, code):
  2193. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2194. for short_name, long_name in cls._lang_map.items():
  2195. if long_name == code:
  2196. return short_name
  2197. class ISO3166Utils(object):
  2198. # From http://data.okfn.org/data/core/country-list
  2199. _country_map = {
  2200. 'AF': 'Afghanistan',
  2201. 'AX': 'Åland Islands',
  2202. 'AL': 'Albania',
  2203. 'DZ': 'Algeria',
  2204. 'AS': 'American Samoa',
  2205. 'AD': 'Andorra',
  2206. 'AO': 'Angola',
  2207. 'AI': 'Anguilla',
  2208. 'AQ': 'Antarctica',
  2209. 'AG': 'Antigua and Barbuda',
  2210. 'AR': 'Argentina',
  2211. 'AM': 'Armenia',
  2212. 'AW': 'Aruba',
  2213. 'AU': 'Australia',
  2214. 'AT': 'Austria',
  2215. 'AZ': 'Azerbaijan',
  2216. 'BS': 'Bahamas',
  2217. 'BH': 'Bahrain',
  2218. 'BD': 'Bangladesh',
  2219. 'BB': 'Barbados',
  2220. 'BY': 'Belarus',
  2221. 'BE': 'Belgium',
  2222. 'BZ': 'Belize',
  2223. 'BJ': 'Benin',
  2224. 'BM': 'Bermuda',
  2225. 'BT': 'Bhutan',
  2226. 'BO': 'Bolivia, Plurinational State of',
  2227. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2228. 'BA': 'Bosnia and Herzegovina',
  2229. 'BW': 'Botswana',
  2230. 'BV': 'Bouvet Island',
  2231. 'BR': 'Brazil',
  2232. 'IO': 'British Indian Ocean Territory',
  2233. 'BN': 'Brunei Darussalam',
  2234. 'BG': 'Bulgaria',
  2235. 'BF': 'Burkina Faso',
  2236. 'BI': 'Burundi',
  2237. 'KH': 'Cambodia',
  2238. 'CM': 'Cameroon',
  2239. 'CA': 'Canada',
  2240. 'CV': 'Cape Verde',
  2241. 'KY': 'Cayman Islands',
  2242. 'CF': 'Central African Republic',
  2243. 'TD': 'Chad',
  2244. 'CL': 'Chile',
  2245. 'CN': 'China',
  2246. 'CX': 'Christmas Island',
  2247. 'CC': 'Cocos (Keeling) Islands',
  2248. 'CO': 'Colombia',
  2249. 'KM': 'Comoros',
  2250. 'CG': 'Congo',
  2251. 'CD': 'Congo, the Democratic Republic of the',
  2252. 'CK': 'Cook Islands',
  2253. 'CR': 'Costa Rica',
  2254. 'CI': 'Côte d\'Ivoire',
  2255. 'HR': 'Croatia',
  2256. 'CU': 'Cuba',
  2257. 'CW': 'Curaçao',
  2258. 'CY': 'Cyprus',
  2259. 'CZ': 'Czech Republic',
  2260. 'DK': 'Denmark',
  2261. 'DJ': 'Djibouti',
  2262. 'DM': 'Dominica',
  2263. 'DO': 'Dominican Republic',
  2264. 'EC': 'Ecuador',
  2265. 'EG': 'Egypt',
  2266. 'SV': 'El Salvador',
  2267. 'GQ': 'Equatorial Guinea',
  2268. 'ER': 'Eritrea',
  2269. 'EE': 'Estonia',
  2270. 'ET': 'Ethiopia',
  2271. 'FK': 'Falkland Islands (Malvinas)',
  2272. 'FO': 'Faroe Islands',
  2273. 'FJ': 'Fiji',
  2274. 'FI': 'Finland',
  2275. 'FR': 'France',
  2276. 'GF': 'French Guiana',
  2277. 'PF': 'French Polynesia',
  2278. 'TF': 'French Southern Territories',
  2279. 'GA': 'Gabon',
  2280. 'GM': 'Gambia',
  2281. 'GE': 'Georgia',
  2282. 'DE': 'Germany',
  2283. 'GH': 'Ghana',
  2284. 'GI': 'Gibraltar',
  2285. 'GR': 'Greece',
  2286. 'GL': 'Greenland',
  2287. 'GD': 'Grenada',
  2288. 'GP': 'Guadeloupe',
  2289. 'GU': 'Guam',
  2290. 'GT': 'Guatemala',
  2291. 'GG': 'Guernsey',
  2292. 'GN': 'Guinea',
  2293. 'GW': 'Guinea-Bissau',
  2294. 'GY': 'Guyana',
  2295. 'HT': 'Haiti',
  2296. 'HM': 'Heard Island and McDonald Islands',
  2297. 'VA': 'Holy See (Vatican City State)',
  2298. 'HN': 'Honduras',
  2299. 'HK': 'Hong Kong',
  2300. 'HU': 'Hungary',
  2301. 'IS': 'Iceland',
  2302. 'IN': 'India',
  2303. 'ID': 'Indonesia',
  2304. 'IR': 'Iran, Islamic Republic of',
  2305. 'IQ': 'Iraq',
  2306. 'IE': 'Ireland',
  2307. 'IM': 'Isle of Man',
  2308. 'IL': 'Israel',
  2309. 'IT': 'Italy',
  2310. 'JM': 'Jamaica',
  2311. 'JP': 'Japan',
  2312. 'JE': 'Jersey',
  2313. 'JO': 'Jordan',
  2314. 'KZ': 'Kazakhstan',
  2315. 'KE': 'Kenya',
  2316. 'KI': 'Kiribati',
  2317. 'KP': 'Korea, Democratic People\'s Republic of',
  2318. 'KR': 'Korea, Republic of',
  2319. 'KW': 'Kuwait',
  2320. 'KG': 'Kyrgyzstan',
  2321. 'LA': 'Lao People\'s Democratic Republic',
  2322. 'LV': 'Latvia',
  2323. 'LB': 'Lebanon',
  2324. 'LS': 'Lesotho',
  2325. 'LR': 'Liberia',
  2326. 'LY': 'Libya',
  2327. 'LI': 'Liechtenstein',
  2328. 'LT': 'Lithuania',
  2329. 'LU': 'Luxembourg',
  2330. 'MO': 'Macao',
  2331. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2332. 'MG': 'Madagascar',
  2333. 'MW': 'Malawi',
  2334. 'MY': 'Malaysia',
  2335. 'MV': 'Maldives',
  2336. 'ML': 'Mali',
  2337. 'MT': 'Malta',
  2338. 'MH': 'Marshall Islands',
  2339. 'MQ': 'Martinique',
  2340. 'MR': 'Mauritania',
  2341. 'MU': 'Mauritius',
  2342. 'YT': 'Mayotte',
  2343. 'MX': 'Mexico',
  2344. 'FM': 'Micronesia, Federated States of',
  2345. 'MD': 'Moldova, Republic of',
  2346. 'MC': 'Monaco',
  2347. 'MN': 'Mongolia',
  2348. 'ME': 'Montenegro',
  2349. 'MS': 'Montserrat',
  2350. 'MA': 'Morocco',
  2351. 'MZ': 'Mozambique',
  2352. 'MM': 'Myanmar',
  2353. 'NA': 'Namibia',
  2354. 'NR': 'Nauru',
  2355. 'NP': 'Nepal',
  2356. 'NL': 'Netherlands',
  2357. 'NC': 'New Caledonia',
  2358. 'NZ': 'New Zealand',
  2359. 'NI': 'Nicaragua',
  2360. 'NE': 'Niger',
  2361. 'NG': 'Nigeria',
  2362. 'NU': 'Niue',
  2363. 'NF': 'Norfolk Island',
  2364. 'MP': 'Northern Mariana Islands',
  2365. 'NO': 'Norway',
  2366. 'OM': 'Oman',
  2367. 'PK': 'Pakistan',
  2368. 'PW': 'Palau',
  2369. 'PS': 'Palestine, State of',
  2370. 'PA': 'Panama',
  2371. 'PG': 'Papua New Guinea',
  2372. 'PY': 'Paraguay',
  2373. 'PE': 'Peru',
  2374. 'PH': 'Philippines',
  2375. 'PN': 'Pitcairn',
  2376. 'PL': 'Poland',
  2377. 'PT': 'Portugal',
  2378. 'PR': 'Puerto Rico',
  2379. 'QA': 'Qatar',
  2380. 'RE': 'Réunion',
  2381. 'RO': 'Romania',
  2382. 'RU': 'Russian Federation',
  2383. 'RW': 'Rwanda',
  2384. 'BL': 'Saint Barthélemy',
  2385. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2386. 'KN': 'Saint Kitts and Nevis',
  2387. 'LC': 'Saint Lucia',
  2388. 'MF': 'Saint Martin (French part)',
  2389. 'PM': 'Saint Pierre and Miquelon',
  2390. 'VC': 'Saint Vincent and the Grenadines',
  2391. 'WS': 'Samoa',
  2392. 'SM': 'San Marino',
  2393. 'ST': 'Sao Tome and Principe',
  2394. 'SA': 'Saudi Arabia',
  2395. 'SN': 'Senegal',
  2396. 'RS': 'Serbia',
  2397. 'SC': 'Seychelles',
  2398. 'SL': 'Sierra Leone',
  2399. 'SG': 'Singapore',
  2400. 'SX': 'Sint Maarten (Dutch part)',
  2401. 'SK': 'Slovakia',
  2402. 'SI': 'Slovenia',
  2403. 'SB': 'Solomon Islands',
  2404. 'SO': 'Somalia',
  2405. 'ZA': 'South Africa',
  2406. 'GS': 'South Georgia and the South Sandwich Islands',
  2407. 'SS': 'South Sudan',
  2408. 'ES': 'Spain',
  2409. 'LK': 'Sri Lanka',
  2410. 'SD': 'Sudan',
  2411. 'SR': 'Suriname',
  2412. 'SJ': 'Svalbard and Jan Mayen',
  2413. 'SZ': 'Swaziland',
  2414. 'SE': 'Sweden',
  2415. 'CH': 'Switzerland',
  2416. 'SY': 'Syrian Arab Republic',
  2417. 'TW': 'Taiwan, Province of China',
  2418. 'TJ': 'Tajikistan',
  2419. 'TZ': 'Tanzania, United Republic of',
  2420. 'TH': 'Thailand',
  2421. 'TL': 'Timor-Leste',
  2422. 'TG': 'Togo',
  2423. 'TK': 'Tokelau',
  2424. 'TO': 'Tonga',
  2425. 'TT': 'Trinidad and Tobago',
  2426. 'TN': 'Tunisia',
  2427. 'TR': 'Turkey',
  2428. 'TM': 'Turkmenistan',
  2429. 'TC': 'Turks and Caicos Islands',
  2430. 'TV': 'Tuvalu',
  2431. 'UG': 'Uganda',
  2432. 'UA': 'Ukraine',
  2433. 'AE': 'United Arab Emirates',
  2434. 'GB': 'United Kingdom',
  2435. 'US': 'United States',
  2436. 'UM': 'United States Minor Outlying Islands',
  2437. 'UY': 'Uruguay',
  2438. 'UZ': 'Uzbekistan',
  2439. 'VU': 'Vanuatu',
  2440. 'VE': 'Venezuela, Bolivarian Republic of',
  2441. 'VN': 'Viet Nam',
  2442. 'VG': 'Virgin Islands, British',
  2443. 'VI': 'Virgin Islands, U.S.',
  2444. 'WF': 'Wallis and Futuna',
  2445. 'EH': 'Western Sahara',
  2446. 'YE': 'Yemen',
  2447. 'ZM': 'Zambia',
  2448. 'ZW': 'Zimbabwe',
  2449. }
  2450. @classmethod
  2451. def short2full(cls, code):
  2452. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2453. return cls._country_map.get(code.upper())
  2454. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2455. def __init__(self, proxies=None):
  2456. # Set default handlers
  2457. for type in ('http', 'https'):
  2458. setattr(self, '%s_open' % type,
  2459. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2460. meth(r, proxy, type))
  2461. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2462. def proxy_open(self, req, proxy, type):
  2463. req_proxy = req.headers.get('Ytdl-request-proxy')
  2464. if req_proxy is not None:
  2465. proxy = req_proxy
  2466. del req.headers['Ytdl-request-proxy']
  2467. if proxy == '__noproxy__':
  2468. return None # No Proxy
  2469. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  2470. req.add_header('Ytdl-socks-proxy', proxy)
  2471. # youtube-dl's http/https handlers do wrapping the socket with socks
  2472. return None
  2473. return compat_urllib_request.ProxyHandler.proxy_open(
  2474. self, req, proxy, type)
  2475. def ohdave_rsa_encrypt(data, exponent, modulus):
  2476. '''
  2477. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2478. Input:
  2479. data: data to encrypt, bytes-like object
  2480. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2481. Output: hex string of encrypted data
  2482. Limitation: supports one block encryption only
  2483. '''
  2484. payload = int(binascii.hexlify(data[::-1]), 16)
  2485. encrypted = pow(payload, exponent, modulus)
  2486. return '%x' % encrypted
  2487. def encode_base_n(num, n, table=None):
  2488. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2489. if not table:
  2490. table = FULL_TABLE[:n]
  2491. if n > len(table):
  2492. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2493. if num == 0:
  2494. return table[0]
  2495. ret = ''
  2496. while num:
  2497. ret = table[num % n] + ret
  2498. num = num // n
  2499. return ret
  2500. def decode_packed_codes(code):
  2501. mobj = re.search(
  2502. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2503. code)
  2504. obfucasted_code, base, count, symbols = mobj.groups()
  2505. base = int(base)
  2506. count = int(count)
  2507. symbols = symbols.split('|')
  2508. symbol_table = {}
  2509. while count:
  2510. count -= 1
  2511. base_n_count = encode_base_n(count, base)
  2512. symbol_table[base_n_count] = symbols[count] or base_n_count
  2513. return re.sub(
  2514. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2515. obfucasted_code)
  2516. def parse_m3u8_attributes(attrib):
  2517. info = {}
  2518. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  2519. if val.startswith('"'):
  2520. val = val[1:-1]
  2521. info[key] = val
  2522. return info
  2523. def urshift(val, n):
  2524. return val >> n if val >= 0 else (val + 0x100000000) >> n
  2525. # Based on png2str() written by @gdkchan and improved by @yokrysty
  2526. # Originally posted at https://github.com/rg3/youtube-dl/issues/9706
  2527. def decode_png(png_data):
  2528. # Reference: https://www.w3.org/TR/PNG/
  2529. header = png_data[8:]
  2530. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  2531. raise IOError('Not a valid PNG file.')
  2532. int_map = {1: '>B', 2: '>H', 4: '>I'}
  2533. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  2534. chunks = []
  2535. while header:
  2536. length = unpack_integer(header[:4])
  2537. header = header[4:]
  2538. chunk_type = header[:4]
  2539. header = header[4:]
  2540. chunk_data = header[:length]
  2541. header = header[length:]
  2542. header = header[4:] # Skip CRC
  2543. chunks.append({
  2544. 'type': chunk_type,
  2545. 'length': length,
  2546. 'data': chunk_data
  2547. })
  2548. ihdr = chunks[0]['data']
  2549. width = unpack_integer(ihdr[:4])
  2550. height = unpack_integer(ihdr[4:8])
  2551. idat = b''
  2552. for chunk in chunks:
  2553. if chunk['type'] == b'IDAT':
  2554. idat += chunk['data']
  2555. if not idat:
  2556. raise IOError('Unable to read PNG data.')
  2557. decompressed_data = bytearray(zlib.decompress(idat))
  2558. stride = width * 3
  2559. pixels = []
  2560. def _get_pixel(idx):
  2561. x = idx % stride
  2562. y = idx // stride
  2563. return pixels[y][x]
  2564. for y in range(height):
  2565. basePos = y * (1 + stride)
  2566. filter_type = decompressed_data[basePos]
  2567. current_row = []
  2568. pixels.append(current_row)
  2569. for x in range(stride):
  2570. color = decompressed_data[1 + basePos + x]
  2571. basex = y * stride + x
  2572. left = 0
  2573. up = 0
  2574. if x > 2:
  2575. left = _get_pixel(basex - 3)
  2576. if y > 0:
  2577. up = _get_pixel(basex - stride)
  2578. if filter_type == 1: # Sub
  2579. color = (color + left) & 0xff
  2580. elif filter_type == 2: # Up
  2581. color = (color + up) & 0xff
  2582. elif filter_type == 3: # Average
  2583. color = (color + ((left + up) >> 1)) & 0xff
  2584. elif filter_type == 4: # Paeth
  2585. a = left
  2586. b = up
  2587. c = 0
  2588. if x > 2 and y > 0:
  2589. c = _get_pixel(basex - stride - 3)
  2590. p = a + b - c
  2591. pa = abs(p - a)
  2592. pb = abs(p - b)
  2593. pc = abs(p - c)
  2594. if pa <= pb and pa <= pc:
  2595. color = (color + a) & 0xff
  2596. elif pb <= pc:
  2597. color = (color + b) & 0xff
  2598. else:
  2599. color = (color + c) & 0xff
  2600. current_row.append(color)
  2601. return width, height, pixels