You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5706 lines
164 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  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 collections
  9. import contextlib
  10. import ctypes
  11. import datetime
  12. import email.utils
  13. import email.header
  14. import errno
  15. import functools
  16. import gzip
  17. import io
  18. import itertools
  19. import json
  20. import locale
  21. import math
  22. import operator
  23. import os
  24. import platform
  25. import random
  26. import re
  27. import socket
  28. import ssl
  29. import subprocess
  30. import sys
  31. import tempfile
  32. import time
  33. import traceback
  34. import xml.etree.ElementTree
  35. import zlib
  36. from .compat import (
  37. compat_HTMLParseError,
  38. compat_HTMLParser,
  39. compat_basestring,
  40. compat_chr,
  41. compat_cookiejar,
  42. compat_ctypes_WINFUNCTYPE,
  43. compat_etree_fromstring,
  44. compat_expanduser,
  45. compat_html_entities,
  46. compat_html_entities_html5,
  47. compat_http_client,
  48. compat_integer_types,
  49. compat_kwargs,
  50. compat_os_name,
  51. compat_parse_qs,
  52. compat_shlex_quote,
  53. compat_str,
  54. compat_struct_pack,
  55. compat_struct_unpack,
  56. compat_urllib_error,
  57. compat_urllib_parse,
  58. compat_urllib_parse_urlencode,
  59. compat_urllib_parse_urlparse,
  60. compat_urllib_parse_unquote_plus,
  61. compat_urllib_request,
  62. compat_urlparse,
  63. compat_xpath,
  64. )
  65. from .socks import (
  66. ProxyType,
  67. sockssocket,
  68. )
  69. def register_socks_protocols():
  70. # "Register" SOCKS protocols
  71. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  72. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  73. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  74. if scheme not in compat_urlparse.uses_netloc:
  75. compat_urlparse.uses_netloc.append(scheme)
  76. # This is not clearly defined otherwise
  77. compiled_regex_type = type(re.compile(''))
  78. def random_user_agent():
  79. _USER_AGENT_TPL = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
  80. _CHROME_VERSIONS = (
  81. '74.0.3729.129',
  82. '76.0.3780.3',
  83. '76.0.3780.2',
  84. '74.0.3729.128',
  85. '76.0.3780.1',
  86. '76.0.3780.0',
  87. '75.0.3770.15',
  88. '74.0.3729.127',
  89. '74.0.3729.126',
  90. '76.0.3779.1',
  91. '76.0.3779.0',
  92. '75.0.3770.14',
  93. '74.0.3729.125',
  94. '76.0.3778.1',
  95. '76.0.3778.0',
  96. '75.0.3770.13',
  97. '74.0.3729.124',
  98. '74.0.3729.123',
  99. '73.0.3683.121',
  100. '76.0.3777.1',
  101. '76.0.3777.0',
  102. '75.0.3770.12',
  103. '74.0.3729.122',
  104. '76.0.3776.4',
  105. '75.0.3770.11',
  106. '74.0.3729.121',
  107. '76.0.3776.3',
  108. '76.0.3776.2',
  109. '73.0.3683.120',
  110. '74.0.3729.120',
  111. '74.0.3729.119',
  112. '74.0.3729.118',
  113. '76.0.3776.1',
  114. '76.0.3776.0',
  115. '76.0.3775.5',
  116. '75.0.3770.10',
  117. '74.0.3729.117',
  118. '76.0.3775.4',
  119. '76.0.3775.3',
  120. '74.0.3729.116',
  121. '75.0.3770.9',
  122. '76.0.3775.2',
  123. '76.0.3775.1',
  124. '76.0.3775.0',
  125. '75.0.3770.8',
  126. '74.0.3729.115',
  127. '74.0.3729.114',
  128. '76.0.3774.1',
  129. '76.0.3774.0',
  130. '75.0.3770.7',
  131. '74.0.3729.113',
  132. '74.0.3729.112',
  133. '74.0.3729.111',
  134. '76.0.3773.1',
  135. '76.0.3773.0',
  136. '75.0.3770.6',
  137. '74.0.3729.110',
  138. '74.0.3729.109',
  139. '76.0.3772.1',
  140. '76.0.3772.0',
  141. '75.0.3770.5',
  142. '74.0.3729.108',
  143. '74.0.3729.107',
  144. '76.0.3771.1',
  145. '76.0.3771.0',
  146. '75.0.3770.4',
  147. '74.0.3729.106',
  148. '74.0.3729.105',
  149. '75.0.3770.3',
  150. '74.0.3729.104',
  151. '74.0.3729.103',
  152. '74.0.3729.102',
  153. '75.0.3770.2',
  154. '74.0.3729.101',
  155. '75.0.3770.1',
  156. '75.0.3770.0',
  157. '74.0.3729.100',
  158. '75.0.3769.5',
  159. '75.0.3769.4',
  160. '74.0.3729.99',
  161. '75.0.3769.3',
  162. '75.0.3769.2',
  163. '75.0.3768.6',
  164. '74.0.3729.98',
  165. '75.0.3769.1',
  166. '75.0.3769.0',
  167. '74.0.3729.97',
  168. '73.0.3683.119',
  169. '73.0.3683.118',
  170. '74.0.3729.96',
  171. '75.0.3768.5',
  172. '75.0.3768.4',
  173. '75.0.3768.3',
  174. '75.0.3768.2',
  175. '74.0.3729.95',
  176. '74.0.3729.94',
  177. '75.0.3768.1',
  178. '75.0.3768.0',
  179. '74.0.3729.93',
  180. '74.0.3729.92',
  181. '73.0.3683.117',
  182. '74.0.3729.91',
  183. '75.0.3766.3',
  184. '74.0.3729.90',
  185. '75.0.3767.2',
  186. '75.0.3767.1',
  187. '75.0.3767.0',
  188. '74.0.3729.89',
  189. '73.0.3683.116',
  190. '75.0.3766.2',
  191. '74.0.3729.88',
  192. '75.0.3766.1',
  193. '75.0.3766.0',
  194. '74.0.3729.87',
  195. '73.0.3683.115',
  196. '74.0.3729.86',
  197. '75.0.3765.1',
  198. '75.0.3765.0',
  199. '74.0.3729.85',
  200. '73.0.3683.114',
  201. '74.0.3729.84',
  202. '75.0.3764.1',
  203. '75.0.3764.0',
  204. '74.0.3729.83',
  205. '73.0.3683.113',
  206. '75.0.3763.2',
  207. '75.0.3761.4',
  208. '74.0.3729.82',
  209. '75.0.3763.1',
  210. '75.0.3763.0',
  211. '74.0.3729.81',
  212. '73.0.3683.112',
  213. '75.0.3762.1',
  214. '75.0.3762.0',
  215. '74.0.3729.80',
  216. '75.0.3761.3',
  217. '74.0.3729.79',
  218. '73.0.3683.111',
  219. '75.0.3761.2',
  220. '74.0.3729.78',
  221. '74.0.3729.77',
  222. '75.0.3761.1',
  223. '75.0.3761.0',
  224. '73.0.3683.110',
  225. '74.0.3729.76',
  226. '74.0.3729.75',
  227. '75.0.3760.0',
  228. '74.0.3729.74',
  229. '75.0.3759.8',
  230. '75.0.3759.7',
  231. '75.0.3759.6',
  232. '74.0.3729.73',
  233. '75.0.3759.5',
  234. '74.0.3729.72',
  235. '73.0.3683.109',
  236. '75.0.3759.4',
  237. '75.0.3759.3',
  238. '74.0.3729.71',
  239. '75.0.3759.2',
  240. '74.0.3729.70',
  241. '73.0.3683.108',
  242. '74.0.3729.69',
  243. '75.0.3759.1',
  244. '75.0.3759.0',
  245. '74.0.3729.68',
  246. '73.0.3683.107',
  247. '74.0.3729.67',
  248. '75.0.3758.1',
  249. '75.0.3758.0',
  250. '74.0.3729.66',
  251. '73.0.3683.106',
  252. '74.0.3729.65',
  253. '75.0.3757.1',
  254. '75.0.3757.0',
  255. '74.0.3729.64',
  256. '73.0.3683.105',
  257. '74.0.3729.63',
  258. '75.0.3756.1',
  259. '75.0.3756.0',
  260. '74.0.3729.62',
  261. '73.0.3683.104',
  262. '75.0.3755.3',
  263. '75.0.3755.2',
  264. '73.0.3683.103',
  265. '75.0.3755.1',
  266. '75.0.3755.0',
  267. '74.0.3729.61',
  268. '73.0.3683.102',
  269. '74.0.3729.60',
  270. '75.0.3754.2',
  271. '74.0.3729.59',
  272. '75.0.3753.4',
  273. '74.0.3729.58',
  274. '75.0.3754.1',
  275. '75.0.3754.0',
  276. '74.0.3729.57',
  277. '73.0.3683.101',
  278. '75.0.3753.3',
  279. '75.0.3752.2',
  280. '75.0.3753.2',
  281. '74.0.3729.56',
  282. '75.0.3753.1',
  283. '75.0.3753.0',
  284. '74.0.3729.55',
  285. '73.0.3683.100',
  286. '74.0.3729.54',
  287. '75.0.3752.1',
  288. '75.0.3752.0',
  289. '74.0.3729.53',
  290. '73.0.3683.99',
  291. '74.0.3729.52',
  292. '75.0.3751.1',
  293. '75.0.3751.0',
  294. '74.0.3729.51',
  295. '73.0.3683.98',
  296. '74.0.3729.50',
  297. '75.0.3750.0',
  298. '74.0.3729.49',
  299. '74.0.3729.48',
  300. '74.0.3729.47',
  301. '75.0.3749.3',
  302. '74.0.3729.46',
  303. '73.0.3683.97',
  304. '75.0.3749.2',
  305. '74.0.3729.45',
  306. '75.0.3749.1',
  307. '75.0.3749.0',
  308. '74.0.3729.44',
  309. '73.0.3683.96',
  310. '74.0.3729.43',
  311. '74.0.3729.42',
  312. '75.0.3748.1',
  313. '75.0.3748.0',
  314. '74.0.3729.41',
  315. '75.0.3747.1',
  316. '73.0.3683.95',
  317. '75.0.3746.4',
  318. '74.0.3729.40',
  319. '74.0.3729.39',
  320. '75.0.3747.0',
  321. '75.0.3746.3',
  322. '75.0.3746.2',
  323. '74.0.3729.38',
  324. '75.0.3746.1',
  325. '75.0.3746.0',
  326. '74.0.3729.37',
  327. '73.0.3683.94',
  328. '75.0.3745.5',
  329. '75.0.3745.4',
  330. '75.0.3745.3',
  331. '75.0.3745.2',
  332. '74.0.3729.36',
  333. '75.0.3745.1',
  334. '75.0.3745.0',
  335. '75.0.3744.2',
  336. '74.0.3729.35',
  337. '73.0.3683.93',
  338. '74.0.3729.34',
  339. '75.0.3744.1',
  340. '75.0.3744.0',
  341. '74.0.3729.33',
  342. '73.0.3683.92',
  343. '74.0.3729.32',
  344. '74.0.3729.31',
  345. '73.0.3683.91',
  346. '75.0.3741.2',
  347. '75.0.3740.5',
  348. '74.0.3729.30',
  349. '75.0.3741.1',
  350. '75.0.3741.0',
  351. '74.0.3729.29',
  352. '75.0.3740.4',
  353. '73.0.3683.90',
  354. '74.0.3729.28',
  355. '75.0.3740.3',
  356. '73.0.3683.89',
  357. '75.0.3740.2',
  358. '74.0.3729.27',
  359. '75.0.3740.1',
  360. '75.0.3740.0',
  361. '74.0.3729.26',
  362. '73.0.3683.88',
  363. '73.0.3683.87',
  364. '74.0.3729.25',
  365. '75.0.3739.1',
  366. '75.0.3739.0',
  367. '73.0.3683.86',
  368. '74.0.3729.24',
  369. '73.0.3683.85',
  370. '75.0.3738.4',
  371. '75.0.3738.3',
  372. '75.0.3738.2',
  373. '75.0.3738.1',
  374. '75.0.3738.0',
  375. '74.0.3729.23',
  376. '73.0.3683.84',
  377. '74.0.3729.22',
  378. '74.0.3729.21',
  379. '75.0.3737.1',
  380. '75.0.3737.0',
  381. '74.0.3729.20',
  382. '73.0.3683.83',
  383. '74.0.3729.19',
  384. '75.0.3736.1',
  385. '75.0.3736.0',
  386. '74.0.3729.18',
  387. '73.0.3683.82',
  388. '74.0.3729.17',
  389. '75.0.3735.1',
  390. '75.0.3735.0',
  391. '74.0.3729.16',
  392. '73.0.3683.81',
  393. '75.0.3734.1',
  394. '75.0.3734.0',
  395. '74.0.3729.15',
  396. '73.0.3683.80',
  397. '74.0.3729.14',
  398. '75.0.3733.1',
  399. '75.0.3733.0',
  400. '75.0.3732.1',
  401. '74.0.3729.13',
  402. '74.0.3729.12',
  403. '73.0.3683.79',
  404. '74.0.3729.11',
  405. '75.0.3732.0',
  406. '74.0.3729.10',
  407. '73.0.3683.78',
  408. '74.0.3729.9',
  409. '74.0.3729.8',
  410. '74.0.3729.7',
  411. '75.0.3731.3',
  412. '75.0.3731.2',
  413. '75.0.3731.0',
  414. '74.0.3729.6',
  415. '73.0.3683.77',
  416. '73.0.3683.76',
  417. '75.0.3730.5',
  418. '75.0.3730.4',
  419. '73.0.3683.75',
  420. '74.0.3729.5',
  421. '73.0.3683.74',
  422. '75.0.3730.3',
  423. '75.0.3730.2',
  424. '74.0.3729.4',
  425. '73.0.3683.73',
  426. '73.0.3683.72',
  427. '75.0.3730.1',
  428. '75.0.3730.0',
  429. '74.0.3729.3',
  430. '73.0.3683.71',
  431. '74.0.3729.2',
  432. '73.0.3683.70',
  433. '74.0.3729.1',
  434. '74.0.3729.0',
  435. '74.0.3726.4',
  436. '73.0.3683.69',
  437. '74.0.3726.3',
  438. '74.0.3728.0',
  439. '74.0.3726.2',
  440. '73.0.3683.68',
  441. '74.0.3726.1',
  442. '74.0.3726.0',
  443. '74.0.3725.4',
  444. '73.0.3683.67',
  445. '73.0.3683.66',
  446. '74.0.3725.3',
  447. '74.0.3725.2',
  448. '74.0.3725.1',
  449. '74.0.3724.8',
  450. '74.0.3725.0',
  451. '73.0.3683.65',
  452. '74.0.3724.7',
  453. '74.0.3724.6',
  454. '74.0.3724.5',
  455. '74.0.3724.4',
  456. '74.0.3724.3',
  457. '74.0.3724.2',
  458. '74.0.3724.1',
  459. '74.0.3724.0',
  460. '73.0.3683.64',
  461. '74.0.3723.1',
  462. '74.0.3723.0',
  463. '73.0.3683.63',
  464. '74.0.3722.1',
  465. '74.0.3722.0',
  466. '73.0.3683.62',
  467. '74.0.3718.9',
  468. '74.0.3702.3',
  469. '74.0.3721.3',
  470. '74.0.3721.2',
  471. '74.0.3721.1',
  472. '74.0.3721.0',
  473. '74.0.3720.6',
  474. '73.0.3683.61',
  475. '72.0.3626.122',
  476. '73.0.3683.60',
  477. '74.0.3720.5',
  478. '72.0.3626.121',
  479. '74.0.3718.8',
  480. '74.0.3720.4',
  481. '74.0.3720.3',
  482. '74.0.3718.7',
  483. '74.0.3720.2',
  484. '74.0.3720.1',
  485. '74.0.3720.0',
  486. '74.0.3718.6',
  487. '74.0.3719.5',
  488. '73.0.3683.59',
  489. '74.0.3718.5',
  490. '74.0.3718.4',
  491. '74.0.3719.4',
  492. '74.0.3719.3',
  493. '74.0.3719.2',
  494. '74.0.3719.1',
  495. '73.0.3683.58',
  496. '74.0.3719.0',
  497. '73.0.3683.57',
  498. '73.0.3683.56',
  499. '74.0.3718.3',
  500. '73.0.3683.55',
  501. '74.0.3718.2',
  502. '74.0.3718.1',
  503. '74.0.3718.0',
  504. '73.0.3683.54',
  505. '74.0.3717.2',
  506. '73.0.3683.53',
  507. '74.0.3717.1',
  508. '74.0.3717.0',
  509. '73.0.3683.52',
  510. '74.0.3716.1',
  511. '74.0.3716.0',
  512. '73.0.3683.51',
  513. '74.0.3715.1',
  514. '74.0.3715.0',
  515. '73.0.3683.50',
  516. '74.0.3711.2',
  517. '74.0.3714.2',
  518. '74.0.3713.3',
  519. '74.0.3714.1',
  520. '74.0.3714.0',
  521. '73.0.3683.49',
  522. '74.0.3713.1',
  523. '74.0.3713.0',
  524. '72.0.3626.120',
  525. '73.0.3683.48',
  526. '74.0.3712.2',
  527. '74.0.3712.1',
  528. '74.0.3712.0',
  529. '73.0.3683.47',
  530. '72.0.3626.119',
  531. '73.0.3683.46',
  532. '74.0.3710.2',
  533. '72.0.3626.118',
  534. '74.0.3711.1',
  535. '74.0.3711.0',
  536. '73.0.3683.45',
  537. '72.0.3626.117',
  538. '74.0.3710.1',
  539. '74.0.3710.0',
  540. '73.0.3683.44',
  541. '72.0.3626.116',
  542. '74.0.3709.1',
  543. '74.0.3709.0',
  544. '74.0.3704.9',
  545. '73.0.3683.43',
  546. '72.0.3626.115',
  547. '74.0.3704.8',
  548. '74.0.3704.7',
  549. '74.0.3708.0',
  550. '74.0.3706.7',
  551. '74.0.3704.6',
  552. '73.0.3683.42',
  553. '72.0.3626.114',
  554. '74.0.3706.6',
  555. '72.0.3626.113',
  556. '74.0.3704.5',
  557. '74.0.3706.5',
  558. '74.0.3706.4',
  559. '74.0.3706.3',
  560. '74.0.3706.2',
  561. '74.0.3706.1',
  562. '74.0.3706.0',
  563. '73.0.3683.41',
  564. '72.0.3626.112',
  565. '74.0.3705.1',
  566. '74.0.3705.0',
  567. '73.0.3683.40',
  568. '72.0.3626.111',
  569. '73.0.3683.39',
  570. '74.0.3704.4',
  571. '73.0.3683.38',
  572. '74.0.3704.3',
  573. '74.0.3704.2',
  574. '74.0.3704.1',
  575. '74.0.3704.0',
  576. '73.0.3683.37',
  577. '72.0.3626.110',
  578. '72.0.3626.109',
  579. '74.0.3703.3',
  580. '74.0.3703.2',
  581. '73.0.3683.36',
  582. '74.0.3703.1',
  583. '74.0.3703.0',
  584. '73.0.3683.35',
  585. '72.0.3626.108',
  586. '74.0.3702.2',
  587. '74.0.3699.3',
  588. '74.0.3702.1',
  589. '74.0.3702.0',
  590. '73.0.3683.34',
  591. '72.0.3626.107',
  592. '73.0.3683.33',
  593. '74.0.3701.1',
  594. '74.0.3701.0',
  595. '73.0.3683.32',
  596. '73.0.3683.31',
  597. '72.0.3626.105',
  598. '74.0.3700.1',
  599. '74.0.3700.0',
  600. '73.0.3683.29',
  601. '72.0.3626.103',
  602. '74.0.3699.2',
  603. '74.0.3699.1',
  604. '74.0.3699.0',
  605. '73.0.3683.28',
  606. '72.0.3626.102',
  607. '73.0.3683.27',
  608. '73.0.3683.26',
  609. '74.0.3698.0',
  610. '74.0.3696.2',
  611. '72.0.3626.101',
  612. '73.0.3683.25',
  613. '74.0.3696.1',
  614. '74.0.3696.0',
  615. '74.0.3694.8',
  616. '72.0.3626.100',
  617. '74.0.3694.7',
  618. '74.0.3694.6',
  619. '74.0.3694.5',
  620. '74.0.3694.4',
  621. '72.0.3626.99',
  622. '72.0.3626.98',
  623. '74.0.3694.3',
  624. '73.0.3683.24',
  625. '72.0.3626.97',
  626. '72.0.3626.96',
  627. '72.0.3626.95',
  628. '73.0.3683.23',
  629. '72.0.3626.94',
  630. '73.0.3683.22',
  631. '73.0.3683.21',
  632. '72.0.3626.93',
  633. '74.0.3694.2',
  634. '72.0.3626.92',
  635. '74.0.3694.1',
  636. '74.0.3694.0',
  637. '74.0.3693.6',
  638. '73.0.3683.20',
  639. '72.0.3626.91',
  640. '74.0.3693.5',
  641. '74.0.3693.4',
  642. '74.0.3693.3',
  643. '74.0.3693.2',
  644. '73.0.3683.19',
  645. '74.0.3693.1',
  646. '74.0.3693.0',
  647. '73.0.3683.18',
  648. '72.0.3626.90',
  649. '74.0.3692.1',
  650. '74.0.3692.0',
  651. '73.0.3683.17',
  652. '72.0.3626.89',
  653. '74.0.3687.3',
  654. '74.0.3691.1',
  655. '74.0.3691.0',
  656. '73.0.3683.16',
  657. '72.0.3626.88',
  658. '72.0.3626.87',
  659. '73.0.3683.15',
  660. '74.0.3690.1',
  661. '74.0.3690.0',
  662. '73.0.3683.14',
  663. '72.0.3626.86',
  664. '73.0.3683.13',
  665. '73.0.3683.12',
  666. '74.0.3689.1',
  667. '74.0.3689.0',
  668. '73.0.3683.11',
  669. '72.0.3626.85',
  670. '73.0.3683.10',
  671. '72.0.3626.84',
  672. '73.0.3683.9',
  673. '74.0.3688.1',
  674. '74.0.3688.0',
  675. '73.0.3683.8',
  676. '72.0.3626.83',
  677. '74.0.3687.2',
  678. '74.0.3687.1',
  679. '74.0.3687.0',
  680. '73.0.3683.7',
  681. '72.0.3626.82',
  682. '74.0.3686.4',
  683. '72.0.3626.81',
  684. '74.0.3686.3',
  685. '74.0.3686.2',
  686. '74.0.3686.1',
  687. '74.0.3686.0',
  688. '73.0.3683.6',
  689. '72.0.3626.80',
  690. '74.0.3685.1',
  691. '74.0.3685.0',
  692. '73.0.3683.5',
  693. '72.0.3626.79',
  694. '74.0.3684.1',
  695. '74.0.3684.0',
  696. '73.0.3683.4',
  697. '72.0.3626.78',
  698. '72.0.3626.77',
  699. '73.0.3683.3',
  700. '73.0.3683.2',
  701. '72.0.3626.76',
  702. '73.0.3683.1',
  703. '73.0.3683.0',
  704. '72.0.3626.75',
  705. '71.0.3578.141',
  706. '73.0.3682.1',
  707. '73.0.3682.0',
  708. '72.0.3626.74',
  709. '71.0.3578.140',
  710. '73.0.3681.4',
  711. '73.0.3681.3',
  712. '73.0.3681.2',
  713. '73.0.3681.1',
  714. '73.0.3681.0',
  715. '72.0.3626.73',
  716. '71.0.3578.139',
  717. '72.0.3626.72',
  718. '72.0.3626.71',
  719. '73.0.3680.1',
  720. '73.0.3680.0',
  721. '72.0.3626.70',
  722. '71.0.3578.138',
  723. '73.0.3678.2',
  724. '73.0.3679.1',
  725. '73.0.3679.0',
  726. '72.0.3626.69',
  727. '71.0.3578.137',
  728. '73.0.3678.1',
  729. '73.0.3678.0',
  730. '71.0.3578.136',
  731. '73.0.3677.1',
  732. '73.0.3677.0',
  733. '72.0.3626.68',
  734. '72.0.3626.67',
  735. '71.0.3578.135',
  736. '73.0.3676.1',
  737. '73.0.3676.0',
  738. '73.0.3674.2',
  739. '72.0.3626.66',
  740. '71.0.3578.134',
  741. '73.0.3674.1',
  742. '73.0.3674.0',
  743. '72.0.3626.65',
  744. '71.0.3578.133',
  745. '73.0.3673.2',
  746. '73.0.3673.1',
  747. '73.0.3673.0',
  748. '72.0.3626.64',
  749. '71.0.3578.132',
  750. '72.0.3626.63',
  751. '72.0.3626.62',
  752. '72.0.3626.61',
  753. '72.0.3626.60',
  754. '73.0.3672.1',
  755. '73.0.3672.0',
  756. '72.0.3626.59',
  757. '71.0.3578.131',
  758. '73.0.3671.3',
  759. '73.0.3671.2',
  760. '73.0.3671.1',
  761. '73.0.3671.0',
  762. '72.0.3626.58',
  763. '71.0.3578.130',
  764. '73.0.3670.1',
  765. '73.0.3670.0',
  766. '72.0.3626.57',
  767. '71.0.3578.129',
  768. '73.0.3669.1',
  769. '73.0.3669.0',
  770. '72.0.3626.56',
  771. '71.0.3578.128',
  772. '73.0.3668.2',
  773. '73.0.3668.1',
  774. '73.0.3668.0',
  775. '72.0.3626.55',
  776. '71.0.3578.127',
  777. '73.0.3667.2',
  778. '73.0.3667.1',
  779. '73.0.3667.0',
  780. '72.0.3626.54',
  781. '71.0.3578.126',
  782. '73.0.3666.1',
  783. '73.0.3666.0',
  784. '72.0.3626.53',
  785. '71.0.3578.125',
  786. '73.0.3665.4',
  787. '73.0.3665.3',
  788. '72.0.3626.52',
  789. '73.0.3665.2',
  790. '73.0.3664.4',
  791. '73.0.3665.1',
  792. '73.0.3665.0',
  793. '72.0.3626.51',
  794. '71.0.3578.124',
  795. '72.0.3626.50',
  796. '73.0.3664.3',
  797. '73.0.3664.2',
  798. '73.0.3664.1',
  799. '73.0.3664.0',
  800. '73.0.3663.2',
  801. '72.0.3626.49',
  802. '71.0.3578.123',
  803. '73.0.3663.1',
  804. '73.0.3663.0',
  805. '72.0.3626.48',
  806. '71.0.3578.122',
  807. '73.0.3662.1',
  808. '73.0.3662.0',
  809. '72.0.3626.47',
  810. '71.0.3578.121',
  811. '73.0.3661.1',
  812. '72.0.3626.46',
  813. '73.0.3661.0',
  814. '72.0.3626.45',
  815. '71.0.3578.120',
  816. '73.0.3660.2',
  817. '73.0.3660.1',
  818. '73.0.3660.0',
  819. '72.0.3626.44',
  820. '71.0.3578.119',
  821. '73.0.3659.1',
  822. '73.0.3659.0',
  823. '72.0.3626.43',
  824. '71.0.3578.118',
  825. '73.0.3658.1',
  826. '73.0.3658.0',
  827. '72.0.3626.42',
  828. '71.0.3578.117',
  829. '73.0.3657.1',
  830. '73.0.3657.0',
  831. '72.0.3626.41',
  832. '71.0.3578.116',
  833. '73.0.3656.1',
  834. '73.0.3656.0',
  835. '72.0.3626.40',
  836. '71.0.3578.115',
  837. '73.0.3655.1',
  838. '73.0.3655.0',
  839. '72.0.3626.39',
  840. '71.0.3578.114',
  841. '73.0.3654.1',
  842. '73.0.3654.0',
  843. '72.0.3626.38',
  844. '71.0.3578.113',
  845. '73.0.3653.1',
  846. '73.0.3653.0',
  847. '72.0.3626.37',
  848. '71.0.3578.112',
  849. '73.0.3652.1',
  850. '73.0.3652.0',
  851. '72.0.3626.36',
  852. '71.0.3578.111',
  853. '73.0.3651.1',
  854. '73.0.3651.0',
  855. '72.0.3626.35',
  856. '71.0.3578.110',
  857. '73.0.3650.1',
  858. '73.0.3650.0',
  859. '72.0.3626.34',
  860. '71.0.3578.109',
  861. '73.0.3649.1',
  862. '73.0.3649.0',
  863. '72.0.3626.33',
  864. '71.0.3578.108',
  865. '73.0.3648.2',
  866. '73.0.3648.1',
  867. '73.0.3648.0',
  868. '72.0.3626.32',
  869. '71.0.3578.107',
  870. '73.0.3647.2',
  871. '73.0.3647.1',
  872. '73.0.3647.0',
  873. '72.0.3626.31',
  874. '71.0.3578.106',
  875. '73.0.3635.3',
  876. '73.0.3646.2',
  877. '73.0.3646.1',
  878. '73.0.3646.0',
  879. '72.0.3626.30',
  880. '71.0.3578.105',
  881. '72.0.3626.29',
  882. '73.0.3645.2',
  883. '73.0.3645.1',
  884. '73.0.3645.0',
  885. '72.0.3626.28',
  886. '71.0.3578.104',
  887. '72.0.3626.27',
  888. '72.0.3626.26',
  889. '72.0.3626.25',
  890. '72.0.3626.24',
  891. '73.0.3644.0',
  892. '73.0.3643.2',
  893. '72.0.3626.23',
  894. '71.0.3578.103',
  895. '73.0.3643.1',
  896. '73.0.3643.0',
  897. '72.0.3626.22',
  898. '71.0.3578.102',
  899. '73.0.3642.1',
  900. '73.0.3642.0',
  901. '72.0.3626.21',
  902. '71.0.3578.101',
  903. '73.0.3641.1',
  904. '73.0.3641.0',
  905. '72.0.3626.20',
  906. '71.0.3578.100',
  907. '72.0.3626.19',
  908. '73.0.3640.1',
  909. '73.0.3640.0',
  910. '72.0.3626.18',
  911. '73.0.3639.1',
  912. '71.0.3578.99',
  913. '73.0.3639.0',
  914. '72.0.3626.17',
  915. '73.0.3638.2',
  916. '72.0.3626.16',
  917. '73.0.3638.1',
  918. '73.0.3638.0',
  919. '72.0.3626.15',
  920. '71.0.3578.98',
  921. '73.0.3635.2',
  922. '71.0.3578.97',
  923. '73.0.3637.1',
  924. '73.0.3637.0',
  925. '72.0.3626.14',
  926. '71.0.3578.96',
  927. '71.0.3578.95',
  928. '72.0.3626.13',
  929. '71.0.3578.94',
  930. '73.0.3636.2',
  931. '71.0.3578.93',
  932. '73.0.3636.1',
  933. '73.0.3636.0',
  934. '72.0.3626.12',
  935. '71.0.3578.92',
  936. '73.0.3635.1',
  937. '73.0.3635.0',
  938. '72.0.3626.11',
  939. '71.0.3578.91',
  940. '73.0.3634.2',
  941. '73.0.3634.1',
  942. '73.0.3634.0',
  943. '72.0.3626.10',
  944. '71.0.3578.90',
  945. '71.0.3578.89',
  946. '73.0.3633.2',
  947. '73.0.3633.1',
  948. '73.0.3633.0',
  949. '72.0.3610.4',
  950. '72.0.3626.9',
  951. '71.0.3578.88',
  952. '73.0.3632.5',
  953. '73.0.3632.4',
  954. '73.0.3632.3',
  955. '73.0.3632.2',
  956. '73.0.3632.1',
  957. '73.0.3632.0',
  958. '72.0.3626.8',
  959. '71.0.3578.87',
  960. '73.0.3631.2',
  961. '73.0.3631.1',
  962. '73.0.3631.0',
  963. '72.0.3626.7',
  964. '71.0.3578.86',
  965. '72.0.3626.6',
  966. '73.0.3630.1',
  967. '73.0.3630.0',
  968. '72.0.3626.5',
  969. '71.0.3578.85',
  970. '72.0.3626.4',
  971. '73.0.3628.3',
  972. '73.0.3628.2',
  973. '73.0.3629.1',
  974. '73.0.3629.0',
  975. '72.0.3626.3',
  976. '71.0.3578.84',
  977. '73.0.3628.1',
  978. '73.0.3628.0',
  979. '71.0.3578.83',
  980. '73.0.3627.1',
  981. '73.0.3627.0',
  982. '72.0.3626.2',
  983. '71.0.3578.82',
  984. '71.0.3578.81',
  985. '71.0.3578.80',
  986. '72.0.3626.1',
  987. '72.0.3626.0',
  988. '71.0.3578.79',
  989. '70.0.3538.124',
  990. '71.0.3578.78',
  991. '72.0.3623.4',
  992. '72.0.3625.2',
  993. '72.0.3625.1',
  994. '72.0.3625.0',
  995. '71.0.3578.77',
  996. '70.0.3538.123',
  997. '72.0.3624.4',
  998. '72.0.3624.3',
  999. '72.0.3624.2',
  1000. '71.0.3578.76',
  1001. '72.0.3624.1',
  1002. '72.0.3624.0',
  1003. '72.0.3623.3',
  1004. '71.0.3578.75',
  1005. '70.0.3538.122',
  1006. '71.0.3578.74',
  1007. '72.0.3623.2',
  1008. '72.0.3610.3',
  1009. '72.0.3623.1',
  1010. '72.0.3623.0',
  1011. '72.0.3622.3',
  1012. '72.0.3622.2',
  1013. '71.0.3578.73',
  1014. '70.0.3538.121',
  1015. '72.0.3622.1',
  1016. '72.0.3622.0',
  1017. '71.0.3578.72',
  1018. '70.0.3538.120',
  1019. '72.0.3621.1',
  1020. '72.0.3621.0',
  1021. '71.0.3578.71',
  1022. '70.0.3538.119',
  1023. '72.0.3620.1',
  1024. '72.0.3620.0',
  1025. '71.0.3578.70',
  1026. '70.0.3538.118',
  1027. '71.0.3578.69',
  1028. '72.0.3619.1',
  1029. '72.0.3619.0',
  1030. '71.0.3578.68',
  1031. '70.0.3538.117',
  1032. '71.0.3578.67',
  1033. '72.0.3618.1',
  1034. '72.0.3618.0',
  1035. '71.0.3578.66',
  1036. '70.0.3538.116',
  1037. '72.0.3617.1',
  1038. '72.0.3617.0',
  1039. '71.0.3578.65',
  1040. '70.0.3538.115',
  1041. '72.0.3602.3',
  1042. '71.0.3578.64',
  1043. '72.0.3616.1',
  1044. '72.0.3616.0',
  1045. '71.0.3578.63',
  1046. '70.0.3538.114',
  1047. '71.0.3578.62',
  1048. '72.0.3615.1',
  1049. '72.0.3615.0',
  1050. '71.0.3578.61',
  1051. '70.0.3538.113',
  1052. '72.0.3614.1',
  1053. '72.0.3614.0',
  1054. '71.0.3578.60',
  1055. '70.0.3538.112',
  1056. '72.0.3613.1',
  1057. '72.0.3613.0',
  1058. '71.0.3578.59',
  1059. '70.0.3538.111',
  1060. '72.0.3612.2',
  1061. '72.0.3612.1',
  1062. '72.0.3612.0',
  1063. '70.0.3538.110',
  1064. '71.0.3578.58',
  1065. '70.0.3538.109',
  1066. '72.0.3611.2',
  1067. '72.0.3611.1',
  1068. '72.0.3611.0',
  1069. '71.0.3578.57',
  1070. '70.0.3538.108',
  1071. '72.0.3610.2',
  1072. '71.0.3578.56',
  1073. '71.0.3578.55',
  1074. '72.0.3610.1',
  1075. '72.0.3610.0',
  1076. '71.0.3578.54',
  1077. '70.0.3538.107',
  1078. '71.0.3578.53',
  1079. '72.0.3609.3',
  1080. '71.0.3578.52',
  1081. '72.0.3609.2',
  1082. '71.0.3578.51',
  1083. '72.0.3608.5',
  1084. '72.0.3609.1',
  1085. '72.0.3609.0',
  1086. '71.0.3578.50',
  1087. '70.0.3538.106',
  1088. '72.0.3608.4',
  1089. '72.0.3608.3',
  1090. '72.0.3608.2',
  1091. '71.0.3578.49',
  1092. '72.0.3608.1',
  1093. '72.0.3608.0',
  1094. '70.0.3538.105',
  1095. '71.0.3578.48',
  1096. '72.0.3607.1',
  1097. '72.0.3607.0',
  1098. '71.0.3578.47',
  1099. '70.0.3538.104',
  1100. '72.0.3606.2',
  1101. '72.0.3606.1',
  1102. '72.0.3606.0',
  1103. '71.0.3578.46',
  1104. '70.0.3538.103',
  1105. '70.0.3538.102',
  1106. '72.0.3605.3',
  1107. '72.0.3605.2',
  1108. '72.0.3605.1',
  1109. '72.0.3605.0',
  1110. '71.0.3578.45',
  1111. '70.0.3538.101',
  1112. '71.0.3578.44',
  1113. '71.0.3578.43',
  1114. '70.0.3538.100',
  1115. '70.0.3538.99',
  1116. '71.0.3578.42',
  1117. '72.0.3604.1',
  1118. '72.0.3604.0',
  1119. '71.0.3578.41',
  1120. '70.0.3538.98',
  1121. '71.0.3578.40',
  1122. '72.0.3603.2',
  1123. '72.0.3603.1',
  1124. '72.0.3603.0',
  1125. '71.0.3578.39',
  1126. '70.0.3538.97',
  1127. '72.0.3602.2',
  1128. '71.0.3578.38',
  1129. '71.0.3578.37',
  1130. '72.0.3602.1',
  1131. '72.0.3602.0',
  1132. '71.0.3578.36',
  1133. '70.0.3538.96',
  1134. '72.0.3601.1',
  1135. '72.0.3601.0',
  1136. '71.0.3578.35',
  1137. '70.0.3538.95',
  1138. '72.0.3600.1',
  1139. '72.0.3600.0',
  1140. '71.0.3578.34',
  1141. '70.0.3538.94',
  1142. '72.0.3599.3',
  1143. '72.0.3599.2',
  1144. '72.0.3599.1',
  1145. '72.0.3599.0',
  1146. '71.0.3578.33',
  1147. '70.0.3538.93',
  1148. '72.0.3598.1',
  1149. '72.0.3598.0',
  1150. '71.0.3578.32',
  1151. '70.0.3538.87',
  1152. '72.0.3597.1',
  1153. '72.0.3597.0',
  1154. '72.0.3596.2',
  1155. '71.0.3578.31',
  1156. '70.0.3538.86',
  1157. '71.0.3578.30',
  1158. '71.0.3578.29',
  1159. '72.0.3596.1',
  1160. '72.0.3596.0',
  1161. '71.0.3578.28',
  1162. '70.0.3538.85',
  1163. '72.0.3595.2',
  1164. '72.0.3591.3',
  1165. '72.0.3595.1',
  1166. '72.0.3595.0',
  1167. '71.0.3578.27',
  1168. '70.0.3538.84',
  1169. '72.0.3594.1',
  1170. '72.0.3594.0',
  1171. '71.0.3578.26',
  1172. '70.0.3538.83',
  1173. '72.0.3593.2',
  1174. '72.0.3593.1',
  1175. '72.0.3593.0',
  1176. '71.0.3578.25',
  1177. '70.0.3538.82',
  1178. '72.0.3589.3',
  1179. '72.0.3592.2',
  1180. '72.0.3592.1',
  1181. '72.0.3592.0',
  1182. '71.0.3578.24',
  1183. '72.0.3589.2',
  1184. '70.0.3538.81',
  1185. '70.0.3538.80',
  1186. '72.0.3591.2',
  1187. '72.0.3591.1',
  1188. '72.0.3591.0',
  1189. '71.0.3578.23',
  1190. '70.0.3538.79',
  1191. '71.0.3578.22',
  1192. '72.0.3590.1',
  1193. '72.0.3590.0',
  1194. '71.0.3578.21',
  1195. '70.0.3538.78',
  1196. '70.0.3538.77',
  1197. '72.0.3589.1',
  1198. '72.0.3589.0',
  1199. '71.0.3578.20',
  1200. '70.0.3538.76',
  1201. '71.0.3578.19',
  1202. '70.0.3538.75',
  1203. '72.0.3588.1',
  1204. '72.0.3588.0',
  1205. '71.0.3578.18',
  1206. '70.0.3538.74',
  1207. '72.0.3586.2',
  1208. '72.0.3587.0',
  1209. '71.0.3578.17',
  1210. '70.0.3538.73',
  1211. '72.0.3586.1',
  1212. '72.0.3586.0',
  1213. '71.0.3578.16',
  1214. '70.0.3538.72',
  1215. '72.0.3585.1',
  1216. '72.0.3585.0',
  1217. '71.0.3578.15',
  1218. '70.0.3538.71',
  1219. '71.0.3578.14',
  1220. '72.0.3584.1',
  1221. '72.0.3584.0',
  1222. '71.0.3578.13',
  1223. '70.0.3538.70',
  1224. '72.0.3583.2',
  1225. '71.0.3578.12',
  1226. '72.0.3583.1',
  1227. '72.0.3583.0',
  1228. '71.0.3578.11',
  1229. '70.0.3538.69',
  1230. '71.0.3578.10',
  1231. '72.0.3582.0',
  1232. '72.0.3581.4',
  1233. '71.0.3578.9',
  1234. '70.0.3538.67',
  1235. '72.0.3581.3',
  1236. '72.0.3581.2',
  1237. '72.0.3581.1',
  1238. '72.0.3581.0',
  1239. '71.0.3578.8',
  1240. '70.0.3538.66',
  1241. '72.0.3580.1',
  1242. '72.0.3580.0',
  1243. '71.0.3578.7',
  1244. '70.0.3538.65',
  1245. '71.0.3578.6',
  1246. '72.0.3579.1',
  1247. '72.0.3579.0',
  1248. '71.0.3578.5',
  1249. '70.0.3538.64',
  1250. '71.0.3578.4',
  1251. '71.0.3578.3',
  1252. '71.0.3578.2',
  1253. '71.0.3578.1',
  1254. '71.0.3578.0',
  1255. '70.0.3538.63',
  1256. '69.0.3497.128',
  1257. '70.0.3538.62',
  1258. '70.0.3538.61',
  1259. '70.0.3538.60',
  1260. '70.0.3538.59',
  1261. '71.0.3577.1',
  1262. '71.0.3577.0',
  1263. '70.0.3538.58',
  1264. '69.0.3497.127',
  1265. '71.0.3576.2',
  1266. '71.0.3576.1',
  1267. '71.0.3576.0',
  1268. '70.0.3538.57',
  1269. '70.0.3538.56',
  1270. '71.0.3575.2',
  1271. '70.0.3538.55',
  1272. '69.0.3497.126',
  1273. '70.0.3538.54',
  1274. '71.0.3575.1',
  1275. '71.0.3575.0',
  1276. '71.0.3574.1',
  1277. '71.0.3574.0',
  1278. '70.0.3538.53',
  1279. '69.0.3497.125',
  1280. '70.0.3538.52',
  1281. '71.0.3573.1',
  1282. '71.0.3573.0',
  1283. '70.0.3538.51',
  1284. '69.0.3497.124',
  1285. '71.0.3572.1',
  1286. '71.0.3572.0',
  1287. '70.0.3538.50',
  1288. '69.0.3497.123',
  1289. '71.0.3571.2',
  1290. '70.0.3538.49',
  1291. '69.0.3497.122',
  1292. '71.0.3571.1',
  1293. '71.0.3571.0',
  1294. '70.0.3538.48',
  1295. '69.0.3497.121',
  1296. '71.0.3570.1',
  1297. '71.0.3570.0',
  1298. '70.0.3538.47',
  1299. '69.0.3497.120',
  1300. '71.0.3568.2',
  1301. '71.0.3569.1',
  1302. '71.0.3569.0',
  1303. '70.0.3538.46',
  1304. '69.0.3497.119',
  1305. '70.0.3538.45',
  1306. '71.0.3568.1',
  1307. '71.0.3568.0',
  1308. '70.0.3538.44',
  1309. '69.0.3497.118',
  1310. '70.0.3538.43',
  1311. '70.0.3538.42',
  1312. '71.0.3567.1',
  1313. '71.0.3567.0',
  1314. '70.0.3538.41',
  1315. '69.0.3497.117',
  1316. '71.0.3566.1',
  1317. '71.0.3566.0',
  1318. '70.0.3538.40',
  1319. '69.0.3497.116',
  1320. '71.0.3565.1',
  1321. '71.0.3565.0',
  1322. '70.0.3538.39',
  1323. '69.0.3497.115',
  1324. '71.0.3564.1',
  1325. '71.0.3564.0',
  1326. '70.0.3538.38',
  1327. '69.0.3497.114',
  1328. '71.0.3563.0',
  1329. '71.0.3562.2',
  1330. '70.0.3538.37',
  1331. '69.0.3497.113',
  1332. '70.0.3538.36',
  1333. '70.0.3538.35',
  1334. '71.0.3562.1',
  1335. '71.0.3562.0',
  1336. '70.0.3538.34',
  1337. '69.0.3497.112',
  1338. '70.0.3538.33',
  1339. '71.0.3561.1',
  1340. '71.0.3561.0',
  1341. '70.0.3538.32',
  1342. '69.0.3497.111',
  1343. '71.0.3559.6',
  1344. '71.0.3560.1',
  1345. '71.0.3560.0',
  1346. '71.0.3559.5',
  1347. '71.0.3559.4',
  1348. '70.0.3538.31',
  1349. '69.0.3497.110',
  1350. '71.0.3559.3',
  1351. '70.0.3538.30',
  1352. '69.0.3497.109',
  1353. '71.0.3559.2',
  1354. '71.0.3559.1',
  1355. '71.0.3559.0',
  1356. '70.0.3538.29',
  1357. '69.0.3497.108',
  1358. '71.0.3558.2',
  1359. '71.0.3558.1',
  1360. '71.0.3558.0',
  1361. '70.0.3538.28',
  1362. '69.0.3497.107',
  1363. '71.0.3557.2',
  1364. '71.0.3557.1',
  1365. '71.0.3557.0',
  1366. '70.0.3538.27',
  1367. '69.0.3497.106',
  1368. '71.0.3554.4',
  1369. '70.0.3538.26',
  1370. '71.0.3556.1',
  1371. '71.0.3556.0',
  1372. '70.0.3538.25',
  1373. '71.0.3554.3',
  1374. '69.0.3497.105',
  1375. '71.0.3554.2',
  1376. '70.0.3538.24',
  1377. '69.0.3497.104',
  1378. '71.0.3555.2',
  1379. '70.0.3538.23',
  1380. '71.0.3555.1',
  1381. '71.0.3555.0',
  1382. '70.0.3538.22',
  1383. '69.0.3497.103',
  1384. '71.0.3554.1',
  1385. '71.0.3554.0',
  1386. '70.0.3538.21',
  1387. '69.0.3497.102',
  1388. '71.0.3553.3',
  1389. '70.0.3538.20',
  1390. '69.0.3497.101',
  1391. '71.0.3553.2',
  1392. '69.0.3497.100',
  1393. '71.0.3553.1',
  1394. '71.0.3553.0',
  1395. '70.0.3538.19',
  1396. '69.0.3497.99',
  1397. '69.0.3497.98',
  1398. '69.0.3497.97',
  1399. '71.0.3552.6',
  1400. '71.0.3552.5',
  1401. '71.0.3552.4',
  1402. '71.0.3552.3',
  1403. '71.0.3552.2',
  1404. '71.0.3552.1',
  1405. '71.0.3552.0',
  1406. '70.0.3538.18',
  1407. '69.0.3497.96',
  1408. '71.0.3551.3',
  1409. '71.0.3551.2',
  1410. '71.0.3551.1',
  1411. '71.0.3551.0',
  1412. '70.0.3538.17',
  1413. '69.0.3497.95',
  1414. '71.0.3550.3',
  1415. '71.0.3550.2',
  1416. '71.0.3550.1',
  1417. '71.0.3550.0',
  1418. '70.0.3538.16',
  1419. '69.0.3497.94',
  1420. '71.0.3549.1',
  1421. '71.0.3549.0',
  1422. '70.0.3538.15',
  1423. '69.0.3497.93',
  1424. '69.0.3497.92',
  1425. '71.0.3548.1',
  1426. '71.0.3548.0',
  1427. '70.0.3538.14',
  1428. '69.0.3497.91',
  1429. '71.0.3547.1',
  1430. '71.0.3547.0',
  1431. '70.0.3538.13',
  1432. '69.0.3497.90',
  1433. '71.0.3546.2',
  1434. '69.0.3497.89',
  1435. '71.0.3546.1',
  1436. '71.0.3546.0',
  1437. '70.0.3538.12',
  1438. '69.0.3497.88',
  1439. '71.0.3545.4',
  1440. '71.0.3545.3',
  1441. '71.0.3545.2',
  1442. '71.0.3545.1',
  1443. '71.0.3545.0',
  1444. '70.0.3538.11',
  1445. '69.0.3497.87',
  1446. '71.0.3544.5',
  1447. '71.0.3544.4',
  1448. '71.0.3544.3',
  1449. '71.0.3544.2',
  1450. '71.0.3544.1',
  1451. '71.0.3544.0',
  1452. '69.0.3497.86',
  1453. '70.0.3538.10',
  1454. '69.0.3497.85',
  1455. '70.0.3538.9',
  1456. '69.0.3497.84',
  1457. '71.0.3543.4',
  1458. '70.0.3538.8',
  1459. '71.0.3543.3',
  1460. '71.0.3543.2',
  1461. '71.0.3543.1',
  1462. '71.0.3543.0',
  1463. '70.0.3538.7',
  1464. '69.0.3497.83',
  1465. '71.0.3542.2',
  1466. '71.0.3542.1',
  1467. '71.0.3542.0',
  1468. '70.0.3538.6',
  1469. '69.0.3497.82',
  1470. '69.0.3497.81',
  1471. '71.0.3541.1',
  1472. '71.0.3541.0',
  1473. '70.0.3538.5',
  1474. '69.0.3497.80',
  1475. '71.0.3540.1',
  1476. '71.0.3540.0',
  1477. '70.0.3538.4',
  1478. '69.0.3497.79',
  1479. '70.0.3538.3',
  1480. '71.0.3539.1',
  1481. '71.0.3539.0',
  1482. '69.0.3497.78',
  1483. '68.0.3440.134',
  1484. '69.0.3497.77',
  1485. '70.0.3538.2',
  1486. '70.0.3538.1',
  1487. '70.0.3538.0',
  1488. '69.0.3497.76',
  1489. '68.0.3440.133',
  1490. '69.0.3497.75',
  1491. '70.0.3537.2',
  1492. '70.0.3537.1',
  1493. '70.0.3537.0',
  1494. '69.0.3497.74',
  1495. '68.0.3440.132',
  1496. '70.0.3536.0',
  1497. '70.0.3535.5',
  1498. '70.0.3535.4',
  1499. '70.0.3535.3',
  1500. '69.0.3497.73',
  1501. '68.0.3440.131',
  1502. '70.0.3532.8',
  1503. '70.0.3532.7',
  1504. '69.0.3497.72',
  1505. '69.0.3497.71',
  1506. '70.0.3535.2',
  1507. '70.0.3535.1',
  1508. '70.0.3535.0',
  1509. '69.0.3497.70',
  1510. '68.0.3440.130',
  1511. '69.0.3497.69',
  1512. '68.0.3440.129',
  1513. '70.0.3534.4',
  1514. '70.0.3534.3',
  1515. '70.0.3534.2',
  1516. '70.0.3534.1',
  1517. '70.0.3534.0',
  1518. '69.0.3497.68',
  1519. '68.0.3440.128',
  1520. '70.0.3533.2',
  1521. '70.0.3533.1',
  1522. '70.0.3533.0',
  1523. '69.0.3497.67',
  1524. '68.0.3440.127',
  1525. '70.0.3532.6',
  1526. '70.0.3532.5',
  1527. '70.0.3532.4',
  1528. '69.0.3497.66',
  1529. '68.0.3440.126',
  1530. '70.0.3532.3',
  1531. '70.0.3532.2',
  1532. '70.0.3532.1',
  1533. '69.0.3497.60',
  1534. '69.0.3497.65',
  1535. '69.0.3497.64',
  1536. '70.0.3532.0',
  1537. '70.0.3531.0',
  1538. '70.0.3530.4',
  1539. '70.0.3530.3',
  1540. '70.0.3530.2',
  1541. '69.0.3497.58',
  1542. '68.0.3440.125',
  1543. '69.0.3497.57',
  1544. '69.0.3497.56',
  1545. '69.0.3497.55',
  1546. '69.0.3497.54',
  1547. '70.0.3530.1',
  1548. '70.0.3530.0',
  1549. '69.0.3497.53',
  1550. '68.0.3440.124',
  1551. '69.0.3497.52',
  1552. '70.0.3529.3',
  1553. '70.0.3529.2',
  1554. '70.0.3529.1',
  1555. '70.0.3529.0',
  1556. '69.0.3497.51',
  1557. '70.0.3528.4',
  1558. '68.0.3440.123',
  1559. '70.0.3528.3',
  1560. '70.0.3528.2',
  1561. '70.0.3528.1',
  1562. '70.0.3528.0',
  1563. '69.0.3497.50',
  1564. '68.0.3440.122',
  1565. '70.0.3527.1',
  1566. '70.0.3527.0',
  1567. '69.0.3497.49',
  1568. '68.0.3440.121',
  1569. '70.0.3526.1',
  1570. '70.0.3526.0',
  1571. '68.0.3440.120',
  1572. '69.0.3497.48',
  1573. '69.0.3497.47',
  1574. '68.0.3440.119',
  1575. '68.0.3440.118',
  1576. '70.0.3525.5',
  1577. '70.0.3525.4',
  1578. '70.0.3525.3',
  1579. '68.0.3440.117',
  1580. '69.0.3497.46',
  1581. '70.0.3525.2',
  1582. '70.0.3525.1',
  1583. '70.0.3525.0',
  1584. '69.0.3497.45',
  1585. '68.0.3440.116',
  1586. '70.0.3524.4',
  1587. '70.0.3524.3',
  1588. '69.0.3497.44',
  1589. '70.0.3524.2',
  1590. '70.0.3524.1',
  1591. '70.0.3524.0',
  1592. '70.0.3523.2',
  1593. '69.0.3497.43',
  1594. '68.0.3440.115',
  1595. '70.0.3505.9',
  1596. '69.0.3497.42',
  1597. '70.0.3505.8',
  1598. '70.0.3523.1',
  1599. '70.0.3523.0',
  1600. '69.0.3497.41',
  1601. '68.0.3440.114',
  1602. '70.0.3505.7',
  1603. '69.0.3497.40',
  1604. '70.0.3522.1',
  1605. '70.0.3522.0',
  1606. '70.0.3521.2',
  1607. '69.0.3497.39',
  1608. '68.0.3440.113',
  1609. '70.0.3505.6',
  1610. '70.0.3521.1',
  1611. '70.0.3521.0',
  1612. '69.0.3497.38',
  1613. '68.0.3440.112',
  1614. '70.0.3520.1',
  1615. '70.0.3520.0',
  1616. '69.0.3497.37',
  1617. '68.0.3440.111',
  1618. '70.0.3519.3',
  1619. '70.0.3519.2',
  1620. '70.0.3519.1',
  1621. '70.0.3519.0',
  1622. '69.0.3497.36',
  1623. '68.0.3440.110',
  1624. '70.0.3518.1',
  1625. '70.0.3518.0',
  1626. '69.0.3497.35',
  1627. '69.0.3497.34',
  1628. '68.0.3440.109',
  1629. '70.0.3517.1',
  1630. '70.0.3517.0',
  1631. '69.0.3497.33',
  1632. '68.0.3440.108',
  1633. '69.0.3497.32',
  1634. '70.0.3516.3',
  1635. '70.0.3516.2',
  1636. '70.0.3516.1',
  1637. '70.0.3516.0',
  1638. '69.0.3497.31',
  1639. '68.0.3440.107',
  1640. '70.0.3515.4',
  1641. '68.0.3440.106',
  1642. '70.0.3515.3',
  1643. '70.0.3515.2',
  1644. '70.0.3515.1',
  1645. '70.0.3515.0',
  1646. '69.0.3497.30',
  1647. '68.0.3440.105',
  1648. '68.0.3440.104',
  1649. '70.0.3514.2',
  1650. '70.0.3514.1',
  1651. '70.0.3514.0',
  1652. '69.0.3497.29',
  1653. '68.0.3440.103',
  1654. '70.0.3513.1',
  1655. '70.0.3513.0',
  1656. '69.0.3497.28',
  1657. )
  1658. return _USER_AGENT_TPL % random.choice(_CHROME_VERSIONS)
  1659. std_headers = {
  1660. 'User-Agent': random_user_agent(),
  1661. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  1662. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  1663. 'Accept-Encoding': 'gzip, deflate',
  1664. 'Accept-Language': 'en-us,en;q=0.5',
  1665. }
  1666. USER_AGENTS = {
  1667. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  1668. }
  1669. NO_DEFAULT = object()
  1670. ENGLISH_MONTH_NAMES = [
  1671. 'January', 'February', 'March', 'April', 'May', 'June',
  1672. 'July', 'August', 'September', 'October', 'November', 'December']
  1673. MONTH_NAMES = {
  1674. 'en': ENGLISH_MONTH_NAMES,
  1675. 'fr': [
  1676. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  1677. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  1678. }
  1679. KNOWN_EXTENSIONS = (
  1680. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  1681. 'flv', 'f4v', 'f4a', 'f4b',
  1682. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  1683. 'mkv', 'mka', 'mk3d',
  1684. 'avi', 'divx',
  1685. 'mov',
  1686. 'asf', 'wmv', 'wma',
  1687. '3gp', '3g2',
  1688. 'mp3',
  1689. 'flac',
  1690. 'ape',
  1691. 'wav',
  1692. 'f4f', 'f4m', 'm3u8', 'smil')
  1693. # needed for sanitizing filenames in restricted mode
  1694. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  1695. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
  1696. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
  1697. DATE_FORMATS = (
  1698. '%d %B %Y',
  1699. '%d %b %Y',
  1700. '%B %d %Y',
  1701. '%B %dst %Y',
  1702. '%B %dnd %Y',
  1703. '%B %drd %Y',
  1704. '%B %dth %Y',
  1705. '%b %d %Y',
  1706. '%b %dst %Y',
  1707. '%b %dnd %Y',
  1708. '%b %drd %Y',
  1709. '%b %dth %Y',
  1710. '%b %dst %Y %I:%M',
  1711. '%b %dnd %Y %I:%M',
  1712. '%b %drd %Y %I:%M',
  1713. '%b %dth %Y %I:%M',
  1714. '%Y %m %d',
  1715. '%Y-%m-%d',
  1716. '%Y/%m/%d',
  1717. '%Y/%m/%d %H:%M',
  1718. '%Y/%m/%d %H:%M:%S',
  1719. '%Y-%m-%d %H:%M',
  1720. '%Y-%m-%d %H:%M:%S',
  1721. '%Y-%m-%d %H:%M:%S.%f',
  1722. '%d.%m.%Y %H:%M',
  1723. '%d.%m.%Y %H.%M',
  1724. '%Y-%m-%dT%H:%M:%SZ',
  1725. '%Y-%m-%dT%H:%M:%S.%fZ',
  1726. '%Y-%m-%dT%H:%M:%S.%f0Z',
  1727. '%Y-%m-%dT%H:%M:%S',
  1728. '%Y-%m-%dT%H:%M:%S.%f',
  1729. '%Y-%m-%dT%H:%M',
  1730. '%b %d %Y at %H:%M',
  1731. '%b %d %Y at %H:%M:%S',
  1732. '%B %d %Y at %H:%M',
  1733. '%B %d %Y at %H:%M:%S',
  1734. )
  1735. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  1736. DATE_FORMATS_DAY_FIRST.extend([
  1737. '%d-%m-%Y',
  1738. '%d.%m.%Y',
  1739. '%d.%m.%y',
  1740. '%d/%m/%Y',
  1741. '%d/%m/%y',
  1742. '%d/%m/%Y %H:%M:%S',
  1743. ])
  1744. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  1745. DATE_FORMATS_MONTH_FIRST.extend([
  1746. '%m-%d-%Y',
  1747. '%m.%d.%Y',
  1748. '%m/%d/%Y',
  1749. '%m/%d/%y',
  1750. '%m/%d/%Y %H:%M:%S',
  1751. ])
  1752. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  1753. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  1754. def preferredencoding():
  1755. """Get preferred encoding.
  1756. Returns the best encoding scheme for the system, based on
  1757. locale.getpreferredencoding() and some further tweaks.
  1758. """
  1759. try:
  1760. pref = locale.getpreferredencoding()
  1761. 'TEST'.encode(pref)
  1762. except Exception:
  1763. pref = 'UTF-8'
  1764. return pref
  1765. def write_json_file(obj, fn):
  1766. """ Encode obj as JSON and write it to fn, atomically if possible """
  1767. fn = encodeFilename(fn)
  1768. if sys.version_info < (3, 0) and sys.platform != 'win32':
  1769. encoding = get_filesystem_encoding()
  1770. # os.path.basename returns a bytes object, but NamedTemporaryFile
  1771. # will fail if the filename contains non ascii characters unless we
  1772. # use a unicode object
  1773. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  1774. # the same for os.path.dirname
  1775. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  1776. else:
  1777. path_basename = os.path.basename
  1778. path_dirname = os.path.dirname
  1779. args = {
  1780. 'suffix': '.tmp',
  1781. 'prefix': path_basename(fn) + '.',
  1782. 'dir': path_dirname(fn),
  1783. 'delete': False,
  1784. }
  1785. # In Python 2.x, json.dump expects a bytestream.
  1786. # In Python 3.x, it writes to a character stream
  1787. if sys.version_info < (3, 0):
  1788. args['mode'] = 'wb'
  1789. else:
  1790. args.update({
  1791. 'mode': 'w',
  1792. 'encoding': 'utf-8',
  1793. })
  1794. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  1795. try:
  1796. with tf:
  1797. json.dump(obj, tf)
  1798. if sys.platform == 'win32':
  1799. # Need to remove existing file on Windows, else os.rename raises
  1800. # WindowsError or FileExistsError.
  1801. try:
  1802. os.unlink(fn)
  1803. except OSError:
  1804. pass
  1805. try:
  1806. mask = os.umask(0)
  1807. os.umask(mask)
  1808. os.chmod(tf.name, 0o666 & ~mask)
  1809. except OSError:
  1810. pass
  1811. os.rename(tf.name, fn)
  1812. except Exception:
  1813. try:
  1814. os.remove(tf.name)
  1815. except OSError:
  1816. pass
  1817. raise
  1818. if sys.version_info >= (2, 7):
  1819. def find_xpath_attr(node, xpath, key, val=None):
  1820. """ Find the xpath xpath[@key=val] """
  1821. assert re.match(r'^[a-zA-Z_-]+$', key)
  1822. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  1823. return node.find(expr)
  1824. else:
  1825. def find_xpath_attr(node, xpath, key, val=None):
  1826. for f in node.findall(compat_xpath(xpath)):
  1827. if key not in f.attrib:
  1828. continue
  1829. if val is None or f.attrib.get(key) == val:
  1830. return f
  1831. return None
  1832. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  1833. # the namespace parameter
  1834. def xpath_with_ns(path, ns_map):
  1835. components = [c.split(':') for c in path.split('/')]
  1836. replaced = []
  1837. for c in components:
  1838. if len(c) == 1:
  1839. replaced.append(c[0])
  1840. else:
  1841. ns, tag = c
  1842. replaced.append('{%s}%s' % (ns_map[ns], tag))
  1843. return '/'.join(replaced)
  1844. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1845. def _find_xpath(xpath):
  1846. return node.find(compat_xpath(xpath))
  1847. if isinstance(xpath, (str, compat_str)):
  1848. n = _find_xpath(xpath)
  1849. else:
  1850. for xp in xpath:
  1851. n = _find_xpath(xp)
  1852. if n is not None:
  1853. break
  1854. if n is None:
  1855. if default is not NO_DEFAULT:
  1856. return default
  1857. elif fatal:
  1858. name = xpath if name is None else name
  1859. raise ExtractorError('Could not find XML element %s' % name)
  1860. else:
  1861. return None
  1862. return n
  1863. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1864. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  1865. if n is None or n == default:
  1866. return n
  1867. if n.text is None:
  1868. if default is not NO_DEFAULT:
  1869. return default
  1870. elif fatal:
  1871. name = xpath if name is None else name
  1872. raise ExtractorError('Could not find XML element\'s text %s' % name)
  1873. else:
  1874. return None
  1875. return n.text
  1876. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  1877. n = find_xpath_attr(node, xpath, key)
  1878. if n is None:
  1879. if default is not NO_DEFAULT:
  1880. return default
  1881. elif fatal:
  1882. name = '%s[@%s]' % (xpath, key) if name is None else name
  1883. raise ExtractorError('Could not find XML attribute %s' % name)
  1884. else:
  1885. return None
  1886. return n.attrib[key]
  1887. def get_element_by_id(id, html):
  1888. """Return the content of the tag with the specified ID in the passed HTML document"""
  1889. return get_element_by_attribute('id', id, html)
  1890. def get_element_by_class(class_name, html):
  1891. """Return the content of the first tag with the specified class in the passed HTML document"""
  1892. retval = get_elements_by_class(class_name, html)
  1893. return retval[0] if retval else None
  1894. def get_element_by_attribute(attribute, value, html, escape_value=True):
  1895. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  1896. return retval[0] if retval else None
  1897. def get_elements_by_class(class_name, html):
  1898. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  1899. return get_elements_by_attribute(
  1900. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  1901. html, escape_value=False)
  1902. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  1903. """Return the content of the tag with the specified attribute in the passed HTML document"""
  1904. value = re.escape(value) if escape_value else value
  1905. retlist = []
  1906. for m in re.finditer(r'''(?xs)
  1907. <([a-zA-Z0-9:._-]+)
  1908. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1909. \s+%s=['"]?%s['"]?
  1910. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1911. \s*>
  1912. (?P<content>.*?)
  1913. </\1>
  1914. ''' % (re.escape(attribute), value), html):
  1915. res = m.group('content')
  1916. if res.startswith('"') or res.startswith("'"):
  1917. res = res[1:-1]
  1918. retlist.append(unescapeHTML(res))
  1919. return retlist
  1920. class HTMLAttributeParser(compat_HTMLParser):
  1921. """Trivial HTML parser to gather the attributes for a single element"""
  1922. def __init__(self):
  1923. self.attrs = {}
  1924. compat_HTMLParser.__init__(self)
  1925. def handle_starttag(self, tag, attrs):
  1926. self.attrs = dict(attrs)
  1927. def extract_attributes(html_element):
  1928. """Given a string for an HTML element such as
  1929. <el
  1930. a="foo" B="bar" c="&98;az" d=boz
  1931. empty= noval entity="&amp;"
  1932. sq='"' dq="'"
  1933. >
  1934. Decode and return a dictionary of attributes.
  1935. {
  1936. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  1937. 'empty': '', 'noval': None, 'entity': '&',
  1938. 'sq': '"', 'dq': '\''
  1939. }.
  1940. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  1941. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  1942. """
  1943. parser = HTMLAttributeParser()
  1944. try:
  1945. parser.feed(html_element)
  1946. parser.close()
  1947. # Older Python may throw HTMLParseError in case of malformed HTML
  1948. except compat_HTMLParseError:
  1949. pass
  1950. return parser.attrs
  1951. def clean_html(html):
  1952. """Clean an HTML snippet into a readable string"""
  1953. if html is None: # Convenience for sanitizing descriptions etc.
  1954. return html
  1955. # Newline vs <br />
  1956. html = html.replace('\n', ' ')
  1957. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  1958. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  1959. # Strip html tags
  1960. html = re.sub('<.*?>', '', html)
  1961. # Replace html entities
  1962. html = unescapeHTML(html)
  1963. return html.strip()
  1964. def sanitize_open(filename, open_mode):
  1965. """Try to open the given filename, and slightly tweak it if this fails.
  1966. Attempts to open the given filename. If this fails, it tries to change
  1967. the filename slightly, step by step, until it's either able to open it
  1968. or it fails and raises a final exception, like the standard open()
  1969. function.
  1970. It returns the tuple (stream, definitive_file_name).
  1971. """
  1972. try:
  1973. if filename == '-':
  1974. if sys.platform == 'win32':
  1975. import msvcrt
  1976. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  1977. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  1978. stream = open(encodeFilename(filename), open_mode)
  1979. return (stream, filename)
  1980. except (IOError, OSError) as err:
  1981. if err.errno in (errno.EACCES,):
  1982. raise
  1983. # In case of error, try to remove win32 forbidden chars
  1984. alt_filename = sanitize_path(filename)
  1985. if alt_filename == filename:
  1986. raise
  1987. else:
  1988. # An exception here should be caught in the caller
  1989. stream = open(encodeFilename(alt_filename), open_mode)
  1990. return (stream, alt_filename)
  1991. def timeconvert(timestr):
  1992. """Convert RFC 2822 defined time string into system timestamp"""
  1993. timestamp = None
  1994. timetuple = email.utils.parsedate_tz(timestr)
  1995. if timetuple is not None:
  1996. timestamp = email.utils.mktime_tz(timetuple)
  1997. return timestamp
  1998. def sanitize_filename(s, restricted=False, is_id=False):
  1999. """Sanitizes a string so it could be used as part of a filename.
  2000. If restricted is set, use a stricter subset of allowed characters.
  2001. Set is_id if this is not an arbitrary string, but an ID that should be kept
  2002. if possible.
  2003. """
  2004. def replace_insane(char):
  2005. if restricted and char in ACCENT_CHARS:
  2006. return ACCENT_CHARS[char]
  2007. if char == '?' or ord(char) < 32 or ord(char) == 127:
  2008. return ''
  2009. elif char == '"':
  2010. return '' if restricted else '\''
  2011. elif char == ':':
  2012. return '_-' if restricted else ' -'
  2013. elif char in '\\/|*<>':
  2014. return '_'
  2015. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  2016. return '_'
  2017. if restricted and ord(char) > 127:
  2018. return '_'
  2019. return char
  2020. # Handle timestamps
  2021. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  2022. result = ''.join(map(replace_insane, s))
  2023. if not is_id:
  2024. while '__' in result:
  2025. result = result.replace('__', '_')
  2026. result = result.strip('_')
  2027. # Common case of "Foreign band name - English song title"
  2028. if restricted and result.startswith('-_'):
  2029. result = result[2:]
  2030. if result.startswith('-'):
  2031. result = '_' + result[len('-'):]
  2032. result = result.lstrip('.')
  2033. if not result:
  2034. result = '_'
  2035. return result
  2036. def sanitize_path(s):
  2037. """Sanitizes and normalizes path on Windows"""
  2038. if sys.platform != 'win32':
  2039. return s
  2040. drive_or_unc, _ = os.path.splitdrive(s)
  2041. if sys.version_info < (2, 7) and not drive_or_unc:
  2042. drive_or_unc, _ = os.path.splitunc(s)
  2043. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  2044. if drive_or_unc:
  2045. norm_path.pop(0)
  2046. sanitized_path = [
  2047. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  2048. for path_part in norm_path]
  2049. if drive_or_unc:
  2050. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  2051. return os.path.join(*sanitized_path)
  2052. def sanitize_url(url):
  2053. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  2054. # the number of unwanted failures due to missing protocol
  2055. if url.startswith('//'):
  2056. return 'http:%s' % url
  2057. # Fix some common typos seen so far
  2058. COMMON_TYPOS = (
  2059. # https://github.com/ytdl-org/youtube-dl/issues/15649
  2060. (r'^httpss://', r'https://'),
  2061. # https://bx1.be/lives/direct-tv/
  2062. (r'^rmtp([es]?)://', r'rtmp\1://'),
  2063. )
  2064. for mistake, fixup in COMMON_TYPOS:
  2065. if re.match(mistake, url):
  2066. return re.sub(mistake, fixup, url)
  2067. return url
  2068. def sanitized_Request(url, *args, **kwargs):
  2069. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  2070. def expand_path(s):
  2071. """Expand shell variables and ~"""
  2072. return os.path.expandvars(compat_expanduser(s))
  2073. def orderedSet(iterable):
  2074. """ Remove all duplicates from the input iterable """
  2075. res = []
  2076. for el in iterable:
  2077. if el not in res:
  2078. res.append(el)
  2079. return res
  2080. def _htmlentity_transform(entity_with_semicolon):
  2081. """Transforms an HTML entity to a character."""
  2082. entity = entity_with_semicolon[:-1]
  2083. # Known non-numeric HTML entity
  2084. if entity in compat_html_entities.name2codepoint:
  2085. return compat_chr(compat_html_entities.name2codepoint[entity])
  2086. # TODO: HTML5 allows entities without a semicolon. For example,
  2087. # '&Eacuteric' should be decoded as 'Éric'.
  2088. if entity_with_semicolon in compat_html_entities_html5:
  2089. return compat_html_entities_html5[entity_with_semicolon]
  2090. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  2091. if mobj is not None:
  2092. numstr = mobj.group(1)
  2093. if numstr.startswith('x'):
  2094. base = 16
  2095. numstr = '0%s' % numstr
  2096. else:
  2097. base = 10
  2098. # See https://github.com/ytdl-org/youtube-dl/issues/7518
  2099. try:
  2100. return compat_chr(int(numstr, base))
  2101. except ValueError:
  2102. pass
  2103. # Unknown entity in name, return its literal representation
  2104. return '&%s;' % entity
  2105. def unescapeHTML(s):
  2106. if s is None:
  2107. return None
  2108. assert type(s) == compat_str
  2109. return re.sub(
  2110. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  2111. def get_subprocess_encoding():
  2112. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2113. # For subprocess calls, encode with locale encoding
  2114. # Refer to http://stackoverflow.com/a/9951851/35070
  2115. encoding = preferredencoding()
  2116. else:
  2117. encoding = sys.getfilesystemencoding()
  2118. if encoding is None:
  2119. encoding = 'utf-8'
  2120. return encoding
  2121. def encodeFilename(s, for_subprocess=False):
  2122. """
  2123. @param s The name of the file
  2124. """
  2125. assert type(s) == compat_str
  2126. # Python 3 has a Unicode API
  2127. if sys.version_info >= (3, 0):
  2128. return s
  2129. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  2130. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  2131. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  2132. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2133. return s
  2134. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  2135. if sys.platform.startswith('java'):
  2136. return s
  2137. return s.encode(get_subprocess_encoding(), 'ignore')
  2138. def decodeFilename(b, for_subprocess=False):
  2139. if sys.version_info >= (3, 0):
  2140. return b
  2141. if not isinstance(b, bytes):
  2142. return b
  2143. return b.decode(get_subprocess_encoding(), 'ignore')
  2144. def encodeArgument(s):
  2145. if not isinstance(s, compat_str):
  2146. # Legacy code that uses byte strings
  2147. # Uncomment the following line after fixing all post processors
  2148. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  2149. s = s.decode('ascii')
  2150. return encodeFilename(s, True)
  2151. def decodeArgument(b):
  2152. return decodeFilename(b, True)
  2153. def decodeOption(optval):
  2154. if optval is None:
  2155. return optval
  2156. if isinstance(optval, bytes):
  2157. optval = optval.decode(preferredencoding())
  2158. assert isinstance(optval, compat_str)
  2159. return optval
  2160. def formatSeconds(secs):
  2161. if secs > 3600:
  2162. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  2163. elif secs > 60:
  2164. return '%d:%02d' % (secs // 60, secs % 60)
  2165. else:
  2166. return '%d' % secs
  2167. def make_HTTPS_handler(params, **kwargs):
  2168. opts_no_check_certificate = params.get('nocheckcertificate', False)
  2169. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  2170. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  2171. if opts_no_check_certificate:
  2172. context.check_hostname = False
  2173. context.verify_mode = ssl.CERT_NONE
  2174. try:
  2175. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2176. except TypeError:
  2177. # Python 2.7.8
  2178. # (create_default_context present but HTTPSHandler has no context=)
  2179. pass
  2180. if sys.version_info < (3, 2):
  2181. return YoutubeDLHTTPSHandler(params, **kwargs)
  2182. else: # Python < 3.4
  2183. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  2184. context.verify_mode = (ssl.CERT_NONE
  2185. if opts_no_check_certificate
  2186. else ssl.CERT_REQUIRED)
  2187. context.set_default_verify_paths()
  2188. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2189. def bug_reports_message():
  2190. if ytdl_is_updateable():
  2191. update_cmd = 'type youtube-dl -U to update'
  2192. else:
  2193. update_cmd = 'see https://yt-dl.org/update on how to update'
  2194. msg = '; please report this issue on https://yt-dl.org/bug .'
  2195. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  2196. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  2197. return msg
  2198. class YoutubeDLError(Exception):
  2199. """Base exception for YoutubeDL errors."""
  2200. pass
  2201. class ExtractorError(YoutubeDLError):
  2202. """Error during info extraction."""
  2203. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  2204. """ tb, if given, is the original traceback (so that it can be printed out).
  2205. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  2206. """
  2207. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  2208. expected = True
  2209. if video_id is not None:
  2210. msg = video_id + ': ' + msg
  2211. if cause:
  2212. msg += ' (caused by %r)' % cause
  2213. if not expected:
  2214. msg += bug_reports_message()
  2215. super(ExtractorError, self).__init__(msg)
  2216. self.traceback = tb
  2217. self.exc_info = sys.exc_info() # preserve original exception
  2218. self.cause = cause
  2219. self.video_id = video_id
  2220. def format_traceback(self):
  2221. if self.traceback is None:
  2222. return None
  2223. return ''.join(traceback.format_tb(self.traceback))
  2224. class UnsupportedError(ExtractorError):
  2225. def __init__(self, url):
  2226. super(UnsupportedError, self).__init__(
  2227. 'Unsupported URL: %s' % url, expected=True)
  2228. self.url = url
  2229. class RegexNotFoundError(ExtractorError):
  2230. """Error when a regex didn't match"""
  2231. pass
  2232. class GeoRestrictedError(ExtractorError):
  2233. """Geographic restriction Error exception.
  2234. This exception may be thrown when a video is not available from your
  2235. geographic location due to geographic restrictions imposed by a website.
  2236. """
  2237. def __init__(self, msg, countries=None):
  2238. super(GeoRestrictedError, self).__init__(msg, expected=True)
  2239. self.msg = msg
  2240. self.countries = countries
  2241. class DownloadError(YoutubeDLError):
  2242. """Download Error exception.
  2243. This exception may be thrown by FileDownloader objects if they are not
  2244. configured to continue on errors. They will contain the appropriate
  2245. error message.
  2246. """
  2247. def __init__(self, msg, exc_info=None):
  2248. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  2249. super(DownloadError, self).__init__(msg)
  2250. self.exc_info = exc_info
  2251. class SameFileError(YoutubeDLError):
  2252. """Same File exception.
  2253. This exception will be thrown by FileDownloader objects if they detect
  2254. multiple files would have to be downloaded to the same file on disk.
  2255. """
  2256. pass
  2257. class PostProcessingError(YoutubeDLError):
  2258. """Post Processing exception.
  2259. This exception may be raised by PostProcessor's .run() method to
  2260. indicate an error in the postprocessing task.
  2261. """
  2262. def __init__(self, msg):
  2263. super(PostProcessingError, self).__init__(msg)
  2264. self.msg = msg
  2265. class MaxDownloadsReached(YoutubeDLError):
  2266. """ --max-downloads limit has been reached. """
  2267. pass
  2268. class UnavailableVideoError(YoutubeDLError):
  2269. """Unavailable Format exception.
  2270. This exception will be thrown when a video is requested
  2271. in a format that is not available for that video.
  2272. """
  2273. pass
  2274. class ContentTooShortError(YoutubeDLError):
  2275. """Content Too Short exception.
  2276. This exception may be raised by FileDownloader objects when a file they
  2277. download is too small for what the server announced first, indicating
  2278. the connection was probably interrupted.
  2279. """
  2280. def __init__(self, downloaded, expected):
  2281. super(ContentTooShortError, self).__init__(
  2282. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  2283. )
  2284. # Both in bytes
  2285. self.downloaded = downloaded
  2286. self.expected = expected
  2287. class XAttrMetadataError(YoutubeDLError):
  2288. def __init__(self, code=None, msg='Unknown error'):
  2289. super(XAttrMetadataError, self).__init__(msg)
  2290. self.code = code
  2291. self.msg = msg
  2292. # Parsing code and msg
  2293. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  2294. or 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  2295. self.reason = 'NO_SPACE'
  2296. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  2297. self.reason = 'VALUE_TOO_LONG'
  2298. else:
  2299. self.reason = 'NOT_SUPPORTED'
  2300. class XAttrUnavailableError(YoutubeDLError):
  2301. pass
  2302. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  2303. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  2304. # expected HTTP responses to meet HTTP/1.0 or later (see also
  2305. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  2306. if sys.version_info < (3, 0):
  2307. kwargs['strict'] = True
  2308. hc = http_class(*args, **compat_kwargs(kwargs))
  2309. source_address = ydl_handler._params.get('source_address')
  2310. if source_address is not None:
  2311. # This is to workaround _create_connection() from socket where it will try all
  2312. # address data from getaddrinfo() including IPv6. This filters the result from
  2313. # getaddrinfo() based on the source_address value.
  2314. # This is based on the cpython socket.create_connection() function.
  2315. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  2316. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  2317. host, port = address
  2318. err = None
  2319. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  2320. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  2321. ip_addrs = [addr for addr in addrs if addr[0] == af]
  2322. if addrs and not ip_addrs:
  2323. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  2324. raise socket.error(
  2325. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  2326. % (ip_version, source_address[0]))
  2327. for res in ip_addrs:
  2328. af, socktype, proto, canonname, sa = res
  2329. sock = None
  2330. try:
  2331. sock = socket.socket(af, socktype, proto)
  2332. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  2333. sock.settimeout(timeout)
  2334. sock.bind(source_address)
  2335. sock.connect(sa)
  2336. err = None # Explicitly break reference cycle
  2337. return sock
  2338. except socket.error as _:
  2339. err = _
  2340. if sock is not None:
  2341. sock.close()
  2342. if err is not None:
  2343. raise err
  2344. else:
  2345. raise socket.error('getaddrinfo returns an empty list')
  2346. if hasattr(hc, '_create_connection'):
  2347. hc._create_connection = _create_connection
  2348. sa = (source_address, 0)
  2349. if hasattr(hc, 'source_address'): # Python 2.7+
  2350. hc.source_address = sa
  2351. else: # Python 2.6
  2352. def _hc_connect(self, *args, **kwargs):
  2353. sock = _create_connection(
  2354. (self.host, self.port), self.timeout, sa)
  2355. if is_https:
  2356. self.sock = ssl.wrap_socket(
  2357. sock, self.key_file, self.cert_file,
  2358. ssl_version=ssl.PROTOCOL_TLSv1)
  2359. else:
  2360. self.sock = sock
  2361. hc.connect = functools.partial(_hc_connect, hc)
  2362. return hc
  2363. def handle_youtubedl_headers(headers):
  2364. filtered_headers = headers
  2365. if 'Youtubedl-no-compression' in filtered_headers:
  2366. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  2367. del filtered_headers['Youtubedl-no-compression']
  2368. return filtered_headers
  2369. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  2370. """Handler for HTTP requests and responses.
  2371. This class, when installed with an OpenerDirector, automatically adds
  2372. the standard headers to every HTTP request and handles gzipped and
  2373. deflated responses from web servers. If compression is to be avoided in
  2374. a particular request, the original request in the program code only has
  2375. to include the HTTP header "Youtubedl-no-compression", which will be
  2376. removed before making the real request.
  2377. Part of this code was copied from:
  2378. http://techknack.net/python-urllib2-handlers/
  2379. Andrew Rowls, the author of that code, agreed to release it to the
  2380. public domain.
  2381. """
  2382. def __init__(self, params, *args, **kwargs):
  2383. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  2384. self._params = params
  2385. def http_open(self, req):
  2386. conn_class = compat_http_client.HTTPConnection
  2387. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2388. if socks_proxy:
  2389. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2390. del req.headers['Ytdl-socks-proxy']
  2391. return self.do_open(functools.partial(
  2392. _create_http_connection, self, conn_class, False),
  2393. req)
  2394. @staticmethod
  2395. def deflate(data):
  2396. try:
  2397. return zlib.decompress(data, -zlib.MAX_WBITS)
  2398. except zlib.error:
  2399. return zlib.decompress(data)
  2400. def http_request(self, req):
  2401. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  2402. # always respected by websites, some tend to give out URLs with non percent-encoded
  2403. # non-ASCII characters (see telemb.py, ard.py [#3412])
  2404. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  2405. # To work around aforementioned issue we will replace request's original URL with
  2406. # percent-encoded one
  2407. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  2408. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  2409. url = req.get_full_url()
  2410. url_escaped = escape_url(url)
  2411. # Substitute URL if any change after escaping
  2412. if url != url_escaped:
  2413. req = update_Request(req, url=url_escaped)
  2414. for h, v in std_headers.items():
  2415. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  2416. # The dict keys are capitalized because of this bug by urllib
  2417. if h.capitalize() not in req.headers:
  2418. req.add_header(h, v)
  2419. req.headers = handle_youtubedl_headers(req.headers)
  2420. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  2421. # Python 2.6 is brain-dead when it comes to fragments
  2422. req._Request__original = req._Request__original.partition('#')[0]
  2423. req._Request__r_type = req._Request__r_type.partition('#')[0]
  2424. return req
  2425. def http_response(self, req, resp):
  2426. old_resp = resp
  2427. # gzip
  2428. if resp.headers.get('Content-encoding', '') == 'gzip':
  2429. content = resp.read()
  2430. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  2431. try:
  2432. uncompressed = io.BytesIO(gz.read())
  2433. except IOError as original_ioerror:
  2434. # There may be junk add the end of the file
  2435. # See http://stackoverflow.com/q/4928560/35070 for details
  2436. for i in range(1, 1024):
  2437. try:
  2438. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  2439. uncompressed = io.BytesIO(gz.read())
  2440. except IOError:
  2441. continue
  2442. break
  2443. else:
  2444. raise original_ioerror
  2445. resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  2446. resp.msg = old_resp.msg
  2447. del resp.headers['Content-encoding']
  2448. # deflate
  2449. if resp.headers.get('Content-encoding', '') == 'deflate':
  2450. gz = io.BytesIO(self.deflate(resp.read()))
  2451. resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  2452. resp.msg = old_resp.msg
  2453. del resp.headers['Content-encoding']
  2454. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  2455. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  2456. if 300 <= resp.code < 400:
  2457. location = resp.headers.get('Location')
  2458. if location:
  2459. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  2460. if sys.version_info >= (3, 0):
  2461. location = location.encode('iso-8859-1').decode('utf-8')
  2462. else:
  2463. location = location.decode('utf-8')
  2464. location_escaped = escape_url(location)
  2465. if location != location_escaped:
  2466. del resp.headers['Location']
  2467. if sys.version_info < (3, 0):
  2468. location_escaped = location_escaped.encode('utf-8')
  2469. resp.headers['Location'] = location_escaped
  2470. return resp
  2471. https_request = http_request
  2472. https_response = http_response
  2473. def make_socks_conn_class(base_class, socks_proxy):
  2474. assert issubclass(base_class, (
  2475. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  2476. url_components = compat_urlparse.urlparse(socks_proxy)
  2477. if url_components.scheme.lower() == 'socks5':
  2478. socks_type = ProxyType.SOCKS5
  2479. elif url_components.scheme.lower() in ('socks', 'socks4'):
  2480. socks_type = ProxyType.SOCKS4
  2481. elif url_components.scheme.lower() == 'socks4a':
  2482. socks_type = ProxyType.SOCKS4A
  2483. def unquote_if_non_empty(s):
  2484. if not s:
  2485. return s
  2486. return compat_urllib_parse_unquote_plus(s)
  2487. proxy_args = (
  2488. socks_type,
  2489. url_components.hostname, url_components.port or 1080,
  2490. True, # Remote DNS
  2491. unquote_if_non_empty(url_components.username),
  2492. unquote_if_non_empty(url_components.password),
  2493. )
  2494. class SocksConnection(base_class):
  2495. def connect(self):
  2496. self.sock = sockssocket()
  2497. self.sock.setproxy(*proxy_args)
  2498. if type(self.timeout) in (int, float):
  2499. self.sock.settimeout(self.timeout)
  2500. self.sock.connect((self.host, self.port))
  2501. if isinstance(self, compat_http_client.HTTPSConnection):
  2502. if hasattr(self, '_context'): # Python > 2.6
  2503. self.sock = self._context.wrap_socket(
  2504. self.sock, server_hostname=self.host)
  2505. else:
  2506. self.sock = ssl.wrap_socket(self.sock)
  2507. return SocksConnection
  2508. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  2509. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  2510. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  2511. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  2512. self._params = params
  2513. def https_open(self, req):
  2514. kwargs = {}
  2515. conn_class = self._https_conn_class
  2516. if hasattr(self, '_context'): # python > 2.6
  2517. kwargs['context'] = self._context
  2518. if hasattr(self, '_check_hostname'): # python 3.x
  2519. kwargs['check_hostname'] = self._check_hostname
  2520. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2521. if socks_proxy:
  2522. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2523. del req.headers['Ytdl-socks-proxy']
  2524. return self.do_open(functools.partial(
  2525. _create_http_connection, self, conn_class, True),
  2526. req, **kwargs)
  2527. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  2528. """
  2529. See [1] for cookie file format.
  2530. 1. https://curl.haxx.se/docs/http-cookies.html
  2531. """
  2532. _HTTPONLY_PREFIX = '#HttpOnly_'
  2533. _ENTRY_LEN = 7
  2534. _HEADER = '''# Netscape HTTP Cookie File
  2535. # This file is generated by youtube-dl. Do not edit.
  2536. '''
  2537. _CookieFileEntry = collections.namedtuple(
  2538. 'CookieFileEntry',
  2539. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  2540. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  2541. """
  2542. Save cookies to a file.
  2543. Most of the code is taken from CPython 3.8 and slightly adapted
  2544. to support cookie files with UTF-8 in both python 2 and 3.
  2545. """
  2546. if filename is None:
  2547. if self.filename is not None:
  2548. filename = self.filename
  2549. else:
  2550. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2551. # Store session cookies with `expires` set to 0 instead of an empty
  2552. # string
  2553. for cookie in self:
  2554. if cookie.expires is None:
  2555. cookie.expires = 0
  2556. with io.open(filename, 'w', encoding='utf-8') as f:
  2557. f.write(self._HEADER)
  2558. now = time.time()
  2559. for cookie in self:
  2560. if not ignore_discard and cookie.discard:
  2561. continue
  2562. if not ignore_expires and cookie.is_expired(now):
  2563. continue
  2564. if cookie.secure:
  2565. secure = 'TRUE'
  2566. else:
  2567. secure = 'FALSE'
  2568. if cookie.domain.startswith('.'):
  2569. initial_dot = 'TRUE'
  2570. else:
  2571. initial_dot = 'FALSE'
  2572. if cookie.expires is not None:
  2573. expires = compat_str(cookie.expires)
  2574. else:
  2575. expires = ''
  2576. if cookie.value is None:
  2577. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  2578. # with no name, whereas http.cookiejar regards it as a
  2579. # cookie with no value.
  2580. name = ''
  2581. value = cookie.name
  2582. else:
  2583. name = cookie.name
  2584. value = cookie.value
  2585. f.write(
  2586. '\t'.join([cookie.domain, initial_dot, cookie.path,
  2587. secure, expires, name, value]) + '\n')
  2588. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  2589. """Load cookies from a file."""
  2590. if filename is None:
  2591. if self.filename is not None:
  2592. filename = self.filename
  2593. else:
  2594. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2595. def prepare_line(line):
  2596. if line.startswith(self._HTTPONLY_PREFIX):
  2597. line = line[len(self._HTTPONLY_PREFIX):]
  2598. # comments and empty lines are fine
  2599. if line.startswith('#') or not line.strip():
  2600. return line
  2601. cookie_list = line.split('\t')
  2602. if len(cookie_list) != self._ENTRY_LEN:
  2603. raise compat_cookiejar.LoadError('invalid length %d' % len(cookie_list))
  2604. cookie = self._CookieFileEntry(*cookie_list)
  2605. if cookie.expires_at and not cookie.expires_at.isdigit():
  2606. raise compat_cookiejar.LoadError('invalid expires at %s' % cookie.expires_at)
  2607. return line
  2608. cf = io.StringIO()
  2609. with io.open(filename, encoding='utf-8') as f:
  2610. for line in f:
  2611. try:
  2612. cf.write(prepare_line(line))
  2613. except compat_cookiejar.LoadError as e:
  2614. write_string(
  2615. 'WARNING: skipping cookie file entry due to %s: %r\n'
  2616. % (e, line), sys.stderr)
  2617. continue
  2618. cf.seek(0)
  2619. self._really_load(cf, filename, ignore_discard, ignore_expires)
  2620. # Session cookies are denoted by either `expires` field set to
  2621. # an empty string or 0. MozillaCookieJar only recognizes the former
  2622. # (see [1]). So we need force the latter to be recognized as session
  2623. # cookies on our own.
  2624. # Session cookies may be important for cookies-based authentication,
  2625. # e.g. usually, when user does not check 'Remember me' check box while
  2626. # logging in on a site, some important cookies are stored as session
  2627. # cookies so that not recognizing them will result in failed login.
  2628. # 1. https://bugs.python.org/issue17164
  2629. for cookie in self:
  2630. # Treat `expires=0` cookies as session cookies
  2631. if cookie.expires == 0:
  2632. cookie.expires = None
  2633. cookie.discard = True
  2634. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  2635. def __init__(self, cookiejar=None):
  2636. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  2637. def http_response(self, request, response):
  2638. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  2639. # characters in Set-Cookie HTTP header of last response (see
  2640. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  2641. # In order to at least prevent crashing we will percent encode Set-Cookie
  2642. # header before HTTPCookieProcessor starts processing it.
  2643. # if sys.version_info < (3, 0) and response.headers:
  2644. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  2645. # set_cookie = response.headers.get(set_cookie_header)
  2646. # if set_cookie:
  2647. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  2648. # if set_cookie != set_cookie_escaped:
  2649. # del response.headers[set_cookie_header]
  2650. # response.headers[set_cookie_header] = set_cookie_escaped
  2651. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  2652. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  2653. https_response = http_response
  2654. class YoutubeDLRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  2655. if sys.version_info[0] < 3:
  2656. def redirect_request(self, req, fp, code, msg, headers, newurl):
  2657. # On python 2 urlh.geturl() may sometimes return redirect URL
  2658. # as byte string instead of unicode. This workaround allows
  2659. # to force it always return unicode.
  2660. return compat_urllib_request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, compat_str(newurl))
  2661. def extract_timezone(date_str):
  2662. m = re.search(
  2663. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  2664. date_str)
  2665. if not m:
  2666. timezone = datetime.timedelta()
  2667. else:
  2668. date_str = date_str[:-len(m.group('tz'))]
  2669. if not m.group('sign'):
  2670. timezone = datetime.timedelta()
  2671. else:
  2672. sign = 1 if m.group('sign') == '+' else -1
  2673. timezone = datetime.timedelta(
  2674. hours=sign * int(m.group('hours')),
  2675. minutes=sign * int(m.group('minutes')))
  2676. return timezone, date_str
  2677. def parse_iso8601(date_str, delimiter='T', timezone=None):
  2678. """ Return a UNIX timestamp from the given date """
  2679. if date_str is None:
  2680. return None
  2681. date_str = re.sub(r'\.[0-9]+', '', date_str)
  2682. if timezone is None:
  2683. timezone, date_str = extract_timezone(date_str)
  2684. try:
  2685. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  2686. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  2687. return calendar.timegm(dt.timetuple())
  2688. except ValueError:
  2689. pass
  2690. def date_formats(day_first=True):
  2691. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  2692. def unified_strdate(date_str, day_first=True):
  2693. """Return a string with the date in the format YYYYMMDD"""
  2694. if date_str is None:
  2695. return None
  2696. upload_date = None
  2697. # Replace commas
  2698. date_str = date_str.replace(',', ' ')
  2699. # Remove AM/PM + timezone
  2700. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2701. _, date_str = extract_timezone(date_str)
  2702. for expression in date_formats(day_first):
  2703. try:
  2704. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  2705. except ValueError:
  2706. pass
  2707. if upload_date is None:
  2708. timetuple = email.utils.parsedate_tz(date_str)
  2709. if timetuple:
  2710. try:
  2711. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  2712. except ValueError:
  2713. pass
  2714. if upload_date is not None:
  2715. return compat_str(upload_date)
  2716. def unified_timestamp(date_str, day_first=True):
  2717. if date_str is None:
  2718. return None
  2719. date_str = re.sub(r'[,|]', '', date_str)
  2720. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  2721. timezone, date_str = extract_timezone(date_str)
  2722. # Remove AM/PM + timezone
  2723. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2724. # Remove unrecognized timezones from ISO 8601 alike timestamps
  2725. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2726. if m:
  2727. date_str = date_str[:-len(m.group('tz'))]
  2728. # Python only supports microseconds, so remove nanoseconds
  2729. m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
  2730. if m:
  2731. date_str = m.group(1)
  2732. for expression in date_formats(day_first):
  2733. try:
  2734. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  2735. return calendar.timegm(dt.timetuple())
  2736. except ValueError:
  2737. pass
  2738. timetuple = email.utils.parsedate_tz(date_str)
  2739. if timetuple:
  2740. return calendar.timegm(timetuple) + pm_delta * 3600
  2741. def determine_ext(url, default_ext='unknown_video'):
  2742. if url is None or '.' not in url:
  2743. return default_ext
  2744. guess = url.partition('?')[0].rpartition('.')[2]
  2745. if re.match(r'^[A-Za-z0-9]+$', guess):
  2746. return guess
  2747. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  2748. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  2749. return guess.rstrip('/')
  2750. else:
  2751. return default_ext
  2752. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  2753. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  2754. def date_from_str(date_str):
  2755. """
  2756. Return a datetime object from a string in the format YYYYMMDD or
  2757. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  2758. today = datetime.date.today()
  2759. if date_str in ('now', 'today'):
  2760. return today
  2761. if date_str == 'yesterday':
  2762. return today - datetime.timedelta(days=1)
  2763. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  2764. if match is not None:
  2765. sign = match.group('sign')
  2766. time = int(match.group('time'))
  2767. if sign == '-':
  2768. time = -time
  2769. unit = match.group('unit')
  2770. # A bad approximation?
  2771. if unit == 'month':
  2772. unit = 'day'
  2773. time *= 30
  2774. elif unit == 'year':
  2775. unit = 'day'
  2776. time *= 365
  2777. unit += 's'
  2778. delta = datetime.timedelta(**{unit: time})
  2779. return today + delta
  2780. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  2781. def hyphenate_date(date_str):
  2782. """
  2783. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  2784. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  2785. if match is not None:
  2786. return '-'.join(match.groups())
  2787. else:
  2788. return date_str
  2789. class DateRange(object):
  2790. """Represents a time interval between two dates"""
  2791. def __init__(self, start=None, end=None):
  2792. """start and end must be strings in the format accepted by date"""
  2793. if start is not None:
  2794. self.start = date_from_str(start)
  2795. else:
  2796. self.start = datetime.datetime.min.date()
  2797. if end is not None:
  2798. self.end = date_from_str(end)
  2799. else:
  2800. self.end = datetime.datetime.max.date()
  2801. if self.start > self.end:
  2802. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  2803. @classmethod
  2804. def day(cls, day):
  2805. """Returns a range that only contains the given day"""
  2806. return cls(day, day)
  2807. def __contains__(self, date):
  2808. """Check if the date is in the range"""
  2809. if not isinstance(date, datetime.date):
  2810. date = date_from_str(date)
  2811. return self.start <= date <= self.end
  2812. def __str__(self):
  2813. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  2814. def platform_name():
  2815. """ Returns the platform name as a compat_str """
  2816. res = platform.platform()
  2817. if isinstance(res, bytes):
  2818. res = res.decode(preferredencoding())
  2819. assert isinstance(res, compat_str)
  2820. return res
  2821. def _windows_write_string(s, out):
  2822. """ Returns True if the string was written using special methods,
  2823. False if it has yet to be written out."""
  2824. # Adapted from http://stackoverflow.com/a/3259271/35070
  2825. import ctypes
  2826. import ctypes.wintypes
  2827. WIN_OUTPUT_IDS = {
  2828. 1: -11,
  2829. 2: -12,
  2830. }
  2831. try:
  2832. fileno = out.fileno()
  2833. except AttributeError:
  2834. # If the output stream doesn't have a fileno, it's virtual
  2835. return False
  2836. except io.UnsupportedOperation:
  2837. # Some strange Windows pseudo files?
  2838. return False
  2839. if fileno not in WIN_OUTPUT_IDS:
  2840. return False
  2841. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  2842. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  2843. ('GetStdHandle', ctypes.windll.kernel32))
  2844. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  2845. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  2846. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  2847. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  2848. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  2849. written = ctypes.wintypes.DWORD(0)
  2850. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  2851. FILE_TYPE_CHAR = 0x0002
  2852. FILE_TYPE_REMOTE = 0x8000
  2853. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  2854. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  2855. ctypes.POINTER(ctypes.wintypes.DWORD))(
  2856. ('GetConsoleMode', ctypes.windll.kernel32))
  2857. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  2858. def not_a_console(handle):
  2859. if handle == INVALID_HANDLE_VALUE or handle is None:
  2860. return True
  2861. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  2862. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  2863. if not_a_console(h):
  2864. return False
  2865. def next_nonbmp_pos(s):
  2866. try:
  2867. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  2868. except StopIteration:
  2869. return len(s)
  2870. while s:
  2871. count = min(next_nonbmp_pos(s), 1024)
  2872. ret = WriteConsoleW(
  2873. h, s, count if count else 2, ctypes.byref(written), None)
  2874. if ret == 0:
  2875. raise OSError('Failed to write string')
  2876. if not count: # We just wrote a non-BMP character
  2877. assert written.value == 2
  2878. s = s[1:]
  2879. else:
  2880. assert written.value > 0
  2881. s = s[written.value:]
  2882. return True
  2883. def write_string(s, out=None, encoding=None):
  2884. if out is None:
  2885. out = sys.stderr
  2886. assert type(s) == compat_str
  2887. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  2888. if _windows_write_string(s, out):
  2889. return
  2890. if ('b' in getattr(out, 'mode', '')
  2891. or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  2892. byt = s.encode(encoding or preferredencoding(), 'ignore')
  2893. out.write(byt)
  2894. elif hasattr(out, 'buffer'):
  2895. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  2896. byt = s.encode(enc, 'ignore')
  2897. out.buffer.write(byt)
  2898. else:
  2899. out.write(s)
  2900. out.flush()
  2901. def bytes_to_intlist(bs):
  2902. if not bs:
  2903. return []
  2904. if isinstance(bs[0], int): # Python 3
  2905. return list(bs)
  2906. else:
  2907. return [ord(c) for c in bs]
  2908. def intlist_to_bytes(xs):
  2909. if not xs:
  2910. return b''
  2911. return compat_struct_pack('%dB' % len(xs), *xs)
  2912. # Cross-platform file locking
  2913. if sys.platform == 'win32':
  2914. import ctypes.wintypes
  2915. import msvcrt
  2916. class OVERLAPPED(ctypes.Structure):
  2917. _fields_ = [
  2918. ('Internal', ctypes.wintypes.LPVOID),
  2919. ('InternalHigh', ctypes.wintypes.LPVOID),
  2920. ('Offset', ctypes.wintypes.DWORD),
  2921. ('OffsetHigh', ctypes.wintypes.DWORD),
  2922. ('hEvent', ctypes.wintypes.HANDLE),
  2923. ]
  2924. kernel32 = ctypes.windll.kernel32
  2925. LockFileEx = kernel32.LockFileEx
  2926. LockFileEx.argtypes = [
  2927. ctypes.wintypes.HANDLE, # hFile
  2928. ctypes.wintypes.DWORD, # dwFlags
  2929. ctypes.wintypes.DWORD, # dwReserved
  2930. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2931. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2932. ctypes.POINTER(OVERLAPPED) # Overlapped
  2933. ]
  2934. LockFileEx.restype = ctypes.wintypes.BOOL
  2935. UnlockFileEx = kernel32.UnlockFileEx
  2936. UnlockFileEx.argtypes = [
  2937. ctypes.wintypes.HANDLE, # hFile
  2938. ctypes.wintypes.DWORD, # dwReserved
  2939. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2940. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2941. ctypes.POINTER(OVERLAPPED) # Overlapped
  2942. ]
  2943. UnlockFileEx.restype = ctypes.wintypes.BOOL
  2944. whole_low = 0xffffffff
  2945. whole_high = 0x7fffffff
  2946. def _lock_file(f, exclusive):
  2947. overlapped = OVERLAPPED()
  2948. overlapped.Offset = 0
  2949. overlapped.OffsetHigh = 0
  2950. overlapped.hEvent = 0
  2951. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  2952. handle = msvcrt.get_osfhandle(f.fileno())
  2953. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  2954. whole_low, whole_high, f._lock_file_overlapped_p):
  2955. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  2956. def _unlock_file(f):
  2957. assert f._lock_file_overlapped_p
  2958. handle = msvcrt.get_osfhandle(f.fileno())
  2959. if not UnlockFileEx(handle, 0,
  2960. whole_low, whole_high, f._lock_file_overlapped_p):
  2961. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  2962. else:
  2963. # Some platforms, such as Jython, is missing fcntl
  2964. try:
  2965. import fcntl
  2966. def _lock_file(f, exclusive):
  2967. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  2968. def _unlock_file(f):
  2969. fcntl.flock(f, fcntl.LOCK_UN)
  2970. except ImportError:
  2971. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  2972. def _lock_file(f, exclusive):
  2973. raise IOError(UNSUPPORTED_MSG)
  2974. def _unlock_file(f):
  2975. raise IOError(UNSUPPORTED_MSG)
  2976. class locked_file(object):
  2977. def __init__(self, filename, mode, encoding=None):
  2978. assert mode in ['r', 'a', 'w']
  2979. self.f = io.open(filename, mode, encoding=encoding)
  2980. self.mode = mode
  2981. def __enter__(self):
  2982. exclusive = self.mode != 'r'
  2983. try:
  2984. _lock_file(self.f, exclusive)
  2985. except IOError:
  2986. self.f.close()
  2987. raise
  2988. return self
  2989. def __exit__(self, etype, value, traceback):
  2990. try:
  2991. _unlock_file(self.f)
  2992. finally:
  2993. self.f.close()
  2994. def __iter__(self):
  2995. return iter(self.f)
  2996. def write(self, *args):
  2997. return self.f.write(*args)
  2998. def read(self, *args):
  2999. return self.f.read(*args)
  3000. def get_filesystem_encoding():
  3001. encoding = sys.getfilesystemencoding()
  3002. return encoding if encoding is not None else 'utf-8'
  3003. def shell_quote(args):
  3004. quoted_args = []
  3005. encoding = get_filesystem_encoding()
  3006. for a in args:
  3007. if isinstance(a, bytes):
  3008. # We may get a filename encoded with 'encodeFilename'
  3009. a = a.decode(encoding)
  3010. quoted_args.append(compat_shlex_quote(a))
  3011. return ' '.join(quoted_args)
  3012. def smuggle_url(url, data):
  3013. """ Pass additional data in a URL for internal use. """
  3014. url, idata = unsmuggle_url(url, {})
  3015. data.update(idata)
  3016. sdata = compat_urllib_parse_urlencode(
  3017. {'__youtubedl_smuggle': json.dumps(data)})
  3018. return url + '#' + sdata
  3019. def unsmuggle_url(smug_url, default=None):
  3020. if '#__youtubedl_smuggle' not in smug_url:
  3021. return smug_url, default
  3022. url, _, sdata = smug_url.rpartition('#')
  3023. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  3024. data = json.loads(jsond)
  3025. return url, data
  3026. def format_bytes(bytes):
  3027. if bytes is None:
  3028. return 'N/A'
  3029. if type(bytes) is str:
  3030. bytes = float(bytes)
  3031. if bytes == 0.0:
  3032. exponent = 0
  3033. else:
  3034. exponent = int(math.log(bytes, 1024.0))
  3035. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  3036. converted = float(bytes) / float(1024 ** exponent)
  3037. return '%.2f%s' % (converted, suffix)
  3038. def lookup_unit_table(unit_table, s):
  3039. units_re = '|'.join(re.escape(u) for u in unit_table)
  3040. m = re.match(
  3041. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  3042. if not m:
  3043. return None
  3044. num_str = m.group('num').replace(',', '.')
  3045. mult = unit_table[m.group('unit')]
  3046. return int(float(num_str) * mult)
  3047. def parse_filesize(s):
  3048. if s is None:
  3049. return None
  3050. # The lower-case forms are of course incorrect and unofficial,
  3051. # but we support those too
  3052. _UNIT_TABLE = {
  3053. 'B': 1,
  3054. 'b': 1,
  3055. 'bytes': 1,
  3056. 'KiB': 1024,
  3057. 'KB': 1000,
  3058. 'kB': 1024,
  3059. 'Kb': 1000,
  3060. 'kb': 1000,
  3061. 'kilobytes': 1000,
  3062. 'kibibytes': 1024,
  3063. 'MiB': 1024 ** 2,
  3064. 'MB': 1000 ** 2,
  3065. 'mB': 1024 ** 2,
  3066. 'Mb': 1000 ** 2,
  3067. 'mb': 1000 ** 2,
  3068. 'megabytes': 1000 ** 2,
  3069. 'mebibytes': 1024 ** 2,
  3070. 'GiB': 1024 ** 3,
  3071. 'GB': 1000 ** 3,
  3072. 'gB': 1024 ** 3,
  3073. 'Gb': 1000 ** 3,
  3074. 'gb': 1000 ** 3,
  3075. 'gigabytes': 1000 ** 3,
  3076. 'gibibytes': 1024 ** 3,
  3077. 'TiB': 1024 ** 4,
  3078. 'TB': 1000 ** 4,
  3079. 'tB': 1024 ** 4,
  3080. 'Tb': 1000 ** 4,
  3081. 'tb': 1000 ** 4,
  3082. 'terabytes': 1000 ** 4,
  3083. 'tebibytes': 1024 ** 4,
  3084. 'PiB': 1024 ** 5,
  3085. 'PB': 1000 ** 5,
  3086. 'pB': 1024 ** 5,
  3087. 'Pb': 1000 ** 5,
  3088. 'pb': 1000 ** 5,
  3089. 'petabytes': 1000 ** 5,
  3090. 'pebibytes': 1024 ** 5,
  3091. 'EiB': 1024 ** 6,
  3092. 'EB': 1000 ** 6,
  3093. 'eB': 1024 ** 6,
  3094. 'Eb': 1000 ** 6,
  3095. 'eb': 1000 ** 6,
  3096. 'exabytes': 1000 ** 6,
  3097. 'exbibytes': 1024 ** 6,
  3098. 'ZiB': 1024 ** 7,
  3099. 'ZB': 1000 ** 7,
  3100. 'zB': 1024 ** 7,
  3101. 'Zb': 1000 ** 7,
  3102. 'zb': 1000 ** 7,
  3103. 'zettabytes': 1000 ** 7,
  3104. 'zebibytes': 1024 ** 7,
  3105. 'YiB': 1024 ** 8,
  3106. 'YB': 1000 ** 8,
  3107. 'yB': 1024 ** 8,
  3108. 'Yb': 1000 ** 8,
  3109. 'yb': 1000 ** 8,
  3110. 'yottabytes': 1000 ** 8,
  3111. 'yobibytes': 1024 ** 8,
  3112. }
  3113. return lookup_unit_table(_UNIT_TABLE, s)
  3114. def parse_count(s):
  3115. if s is None:
  3116. return None
  3117. s = s.strip()
  3118. if re.match(r'^[\d,.]+$', s):
  3119. return str_to_int(s)
  3120. _UNIT_TABLE = {
  3121. 'k': 1000,
  3122. 'K': 1000,
  3123. 'm': 1000 ** 2,
  3124. 'M': 1000 ** 2,
  3125. 'kk': 1000 ** 2,
  3126. 'KK': 1000 ** 2,
  3127. }
  3128. return lookup_unit_table(_UNIT_TABLE, s)
  3129. def parse_resolution(s):
  3130. if s is None:
  3131. return {}
  3132. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  3133. if mobj:
  3134. return {
  3135. 'width': int(mobj.group('w')),
  3136. 'height': int(mobj.group('h')),
  3137. }
  3138. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  3139. if mobj:
  3140. return {'height': int(mobj.group(1))}
  3141. mobj = re.search(r'\b([48])[kK]\b', s)
  3142. if mobj:
  3143. return {'height': int(mobj.group(1)) * 540}
  3144. return {}
  3145. def parse_bitrate(s):
  3146. if not isinstance(s, compat_str):
  3147. return
  3148. mobj = re.search(r'\b(\d+)\s*kbps', s)
  3149. if mobj:
  3150. return int(mobj.group(1))
  3151. def month_by_name(name, lang='en'):
  3152. """ Return the number of a month by (locale-independently) English name """
  3153. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  3154. try:
  3155. return month_names.index(name) + 1
  3156. except ValueError:
  3157. return None
  3158. def month_by_abbreviation(abbrev):
  3159. """ Return the number of a month by (locale-independently) English
  3160. abbreviations """
  3161. try:
  3162. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  3163. except ValueError:
  3164. return None
  3165. def fix_xml_ampersands(xml_str):
  3166. """Replace all the '&' by '&amp;' in XML"""
  3167. return re.sub(
  3168. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  3169. '&amp;',
  3170. xml_str)
  3171. def setproctitle(title):
  3172. assert isinstance(title, compat_str)
  3173. # ctypes in Jython is not complete
  3174. # http://bugs.jython.org/issue2148
  3175. if sys.platform.startswith('java'):
  3176. return
  3177. try:
  3178. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  3179. except OSError:
  3180. return
  3181. except TypeError:
  3182. # LoadLibrary in Windows Python 2.7.13 only expects
  3183. # a bytestring, but since unicode_literals turns
  3184. # every string into a unicode string, it fails.
  3185. return
  3186. title_bytes = title.encode('utf-8')
  3187. buf = ctypes.create_string_buffer(len(title_bytes))
  3188. buf.value = title_bytes
  3189. try:
  3190. libc.prctl(15, buf, 0, 0, 0)
  3191. except AttributeError:
  3192. return # Strange libc, just skip this
  3193. def remove_start(s, start):
  3194. return s[len(start):] if s is not None and s.startswith(start) else s
  3195. def remove_end(s, end):
  3196. return s[:-len(end)] if s is not None and s.endswith(end) else s
  3197. def remove_quotes(s):
  3198. if s is None or len(s) < 2:
  3199. return s
  3200. for quote in ('"', "'", ):
  3201. if s[0] == quote and s[-1] == quote:
  3202. return s[1:-1]
  3203. return s
  3204. def url_basename(url):
  3205. path = compat_urlparse.urlparse(url).path
  3206. return path.strip('/').split('/')[-1]
  3207. def base_url(url):
  3208. return re.match(r'https?://[^?#&]+/', url).group()
  3209. def urljoin(base, path):
  3210. if isinstance(path, bytes):
  3211. path = path.decode('utf-8')
  3212. if not isinstance(path, compat_str) or not path:
  3213. return None
  3214. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  3215. return path
  3216. if isinstance(base, bytes):
  3217. base = base.decode('utf-8')
  3218. if not isinstance(base, compat_str) or not re.match(
  3219. r'^(?:https?:)?//', base):
  3220. return None
  3221. return compat_urlparse.urljoin(base, path)
  3222. class HEADRequest(compat_urllib_request.Request):
  3223. def get_method(self):
  3224. return 'HEAD'
  3225. class PUTRequest(compat_urllib_request.Request):
  3226. def get_method(self):
  3227. return 'PUT'
  3228. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  3229. if get_attr:
  3230. if v is not None:
  3231. v = getattr(v, get_attr, None)
  3232. if v == '':
  3233. v = None
  3234. if v is None:
  3235. return default
  3236. try:
  3237. return int(v) * invscale // scale
  3238. except (ValueError, TypeError):
  3239. return default
  3240. def str_or_none(v, default=None):
  3241. return default if v is None else compat_str(v)
  3242. def str_to_int(int_str):
  3243. """ A more relaxed version of int_or_none """
  3244. if isinstance(int_str, compat_integer_types):
  3245. return int_str
  3246. elif isinstance(int_str, compat_str):
  3247. int_str = re.sub(r'[,\.\+]', '', int_str)
  3248. return int_or_none(int_str)
  3249. def float_or_none(v, scale=1, invscale=1, default=None):
  3250. if v is None:
  3251. return default
  3252. try:
  3253. return float(v) * invscale / scale
  3254. except (ValueError, TypeError):
  3255. return default
  3256. def bool_or_none(v, default=None):
  3257. return v if isinstance(v, bool) else default
  3258. def strip_or_none(v, default=None):
  3259. return v.strip() if isinstance(v, compat_str) else default
  3260. def url_or_none(url):
  3261. if not url or not isinstance(url, compat_str):
  3262. return None
  3263. url = url.strip()
  3264. return url if re.match(r'^(?:[a-zA-Z][\da-zA-Z.+-]*:)?//', url) else None
  3265. def parse_duration(s):
  3266. if not isinstance(s, compat_basestring):
  3267. return None
  3268. s = s.strip()
  3269. days, hours, mins, secs, ms = [None] * 5
  3270. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s)
  3271. if m:
  3272. days, hours, mins, secs, ms = m.groups()
  3273. else:
  3274. m = re.match(
  3275. r'''(?ix)(?:P?
  3276. (?:
  3277. [0-9]+\s*y(?:ears?)?\s*
  3278. )?
  3279. (?:
  3280. [0-9]+\s*m(?:onths?)?\s*
  3281. )?
  3282. (?:
  3283. [0-9]+\s*w(?:eeks?)?\s*
  3284. )?
  3285. (?:
  3286. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  3287. )?
  3288. T)?
  3289. (?:
  3290. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  3291. )?
  3292. (?:
  3293. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  3294. )?
  3295. (?:
  3296. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  3297. )?Z?$''', s)
  3298. if m:
  3299. days, hours, mins, secs, ms = m.groups()
  3300. else:
  3301. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  3302. if m:
  3303. hours, mins = m.groups()
  3304. else:
  3305. return None
  3306. duration = 0
  3307. if secs:
  3308. duration += float(secs)
  3309. if mins:
  3310. duration += float(mins) * 60
  3311. if hours:
  3312. duration += float(hours) * 60 * 60
  3313. if days:
  3314. duration += float(days) * 24 * 60 * 60
  3315. if ms:
  3316. duration += float(ms)
  3317. return duration
  3318. def prepend_extension(filename, ext, expected_real_ext=None):
  3319. name, real_ext = os.path.splitext(filename)
  3320. return (
  3321. '{0}.{1}{2}'.format(name, ext, real_ext)
  3322. if not expected_real_ext or real_ext[1:] == expected_real_ext
  3323. else '{0}.{1}'.format(filename, ext))
  3324. def replace_extension(filename, ext, expected_real_ext=None):
  3325. name, real_ext = os.path.splitext(filename)
  3326. return '{0}.{1}'.format(
  3327. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  3328. ext)
  3329. def check_executable(exe, args=[]):
  3330. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  3331. args can be a list of arguments for a short output (like -version) """
  3332. try:
  3333. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  3334. except OSError:
  3335. return False
  3336. return exe
  3337. def get_exe_version(exe, args=['--version'],
  3338. version_re=None, unrecognized='present'):
  3339. """ Returns the version of the specified executable,
  3340. or False if the executable is not present """
  3341. try:
  3342. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  3343. # SIGTTOU if youtube-dl is run in the background.
  3344. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  3345. out, _ = subprocess.Popen(
  3346. [encodeArgument(exe)] + args,
  3347. stdin=subprocess.PIPE,
  3348. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  3349. except OSError:
  3350. return False
  3351. if isinstance(out, bytes): # Python 2.x
  3352. out = out.decode('ascii', 'ignore')
  3353. return detect_exe_version(out, version_re, unrecognized)
  3354. def detect_exe_version(output, version_re=None, unrecognized='present'):
  3355. assert isinstance(output, compat_str)
  3356. if version_re is None:
  3357. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  3358. m = re.search(version_re, output)
  3359. if m:
  3360. return m.group(1)
  3361. else:
  3362. return unrecognized
  3363. class PagedList(object):
  3364. def __len__(self):
  3365. # This is only useful for tests
  3366. return len(self.getslice())
  3367. class OnDemandPagedList(PagedList):
  3368. def __init__(self, pagefunc, pagesize, use_cache=True):
  3369. self._pagefunc = pagefunc
  3370. self._pagesize = pagesize
  3371. self._use_cache = use_cache
  3372. if use_cache:
  3373. self._cache = {}
  3374. def getslice(self, start=0, end=None):
  3375. res = []
  3376. for pagenum in itertools.count(start // self._pagesize):
  3377. firstid = pagenum * self._pagesize
  3378. nextfirstid = pagenum * self._pagesize + self._pagesize
  3379. if start >= nextfirstid:
  3380. continue
  3381. page_results = None
  3382. if self._use_cache:
  3383. page_results = self._cache.get(pagenum)
  3384. if page_results is None:
  3385. page_results = list(self._pagefunc(pagenum))
  3386. if self._use_cache:
  3387. self._cache[pagenum] = page_results
  3388. startv = (
  3389. start % self._pagesize
  3390. if firstid <= start < nextfirstid
  3391. else 0)
  3392. endv = (
  3393. ((end - 1) % self._pagesize) + 1
  3394. if (end is not None and firstid <= end <= nextfirstid)
  3395. else None)
  3396. if startv != 0 or endv is not None:
  3397. page_results = page_results[startv:endv]
  3398. res.extend(page_results)
  3399. # A little optimization - if current page is not "full", ie. does
  3400. # not contain page_size videos then we can assume that this page
  3401. # is the last one - there are no more ids on further pages -
  3402. # i.e. no need to query again.
  3403. if len(page_results) + startv < self._pagesize:
  3404. break
  3405. # If we got the whole page, but the next page is not interesting,
  3406. # break out early as well
  3407. if end == nextfirstid:
  3408. break
  3409. return res
  3410. class InAdvancePagedList(PagedList):
  3411. def __init__(self, pagefunc, pagecount, pagesize):
  3412. self._pagefunc = pagefunc
  3413. self._pagecount = pagecount
  3414. self._pagesize = pagesize
  3415. def getslice(self, start=0, end=None):
  3416. res = []
  3417. start_page = start // self._pagesize
  3418. end_page = (
  3419. self._pagecount if end is None else (end // self._pagesize + 1))
  3420. skip_elems = start - start_page * self._pagesize
  3421. only_more = None if end is None else end - start
  3422. for pagenum in range(start_page, end_page):
  3423. page = list(self._pagefunc(pagenum))
  3424. if skip_elems:
  3425. page = page[skip_elems:]
  3426. skip_elems = None
  3427. if only_more is not None:
  3428. if len(page) < only_more:
  3429. only_more -= len(page)
  3430. else:
  3431. page = page[:only_more]
  3432. res.extend(page)
  3433. break
  3434. res.extend(page)
  3435. return res
  3436. def uppercase_escape(s):
  3437. unicode_escape = codecs.getdecoder('unicode_escape')
  3438. return re.sub(
  3439. r'\\U[0-9a-fA-F]{8}',
  3440. lambda m: unicode_escape(m.group(0))[0],
  3441. s)
  3442. def lowercase_escape(s):
  3443. unicode_escape = codecs.getdecoder('unicode_escape')
  3444. return re.sub(
  3445. r'\\u[0-9a-fA-F]{4}',
  3446. lambda m: unicode_escape(m.group(0))[0],
  3447. s)
  3448. def escape_rfc3986(s):
  3449. """Escape non-ASCII characters as suggested by RFC 3986"""
  3450. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  3451. s = s.encode('utf-8')
  3452. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  3453. def escape_url(url):
  3454. """Escape URL as suggested by RFC 3986"""
  3455. url_parsed = compat_urllib_parse_urlparse(url)
  3456. return url_parsed._replace(
  3457. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  3458. path=escape_rfc3986(url_parsed.path),
  3459. params=escape_rfc3986(url_parsed.params),
  3460. query=escape_rfc3986(url_parsed.query),
  3461. fragment=escape_rfc3986(url_parsed.fragment)
  3462. ).geturl()
  3463. def read_batch_urls(batch_fd):
  3464. def fixup(url):
  3465. if not isinstance(url, compat_str):
  3466. url = url.decode('utf-8', 'replace')
  3467. BOM_UTF8 = '\xef\xbb\xbf'
  3468. if url.startswith(BOM_UTF8):
  3469. url = url[len(BOM_UTF8):]
  3470. url = url.strip()
  3471. if url.startswith(('#', ';', ']')):
  3472. return False
  3473. return url
  3474. with contextlib.closing(batch_fd) as fd:
  3475. return [url for url in map(fixup, fd) if url]
  3476. def urlencode_postdata(*args, **kargs):
  3477. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  3478. def update_url_query(url, query):
  3479. if not query:
  3480. return url
  3481. parsed_url = compat_urlparse.urlparse(url)
  3482. qs = compat_parse_qs(parsed_url.query)
  3483. qs.update(query)
  3484. return compat_urlparse.urlunparse(parsed_url._replace(
  3485. query=compat_urllib_parse_urlencode(qs, True)))
  3486. def update_Request(req, url=None, data=None, headers={}, query={}):
  3487. req_headers = req.headers.copy()
  3488. req_headers.update(headers)
  3489. req_data = data or req.data
  3490. req_url = update_url_query(url or req.get_full_url(), query)
  3491. req_get_method = req.get_method()
  3492. if req_get_method == 'HEAD':
  3493. req_type = HEADRequest
  3494. elif req_get_method == 'PUT':
  3495. req_type = PUTRequest
  3496. else:
  3497. req_type = compat_urllib_request.Request
  3498. new_req = req_type(
  3499. req_url, data=req_data, headers=req_headers,
  3500. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  3501. if hasattr(req, 'timeout'):
  3502. new_req.timeout = req.timeout
  3503. return new_req
  3504. def _multipart_encode_impl(data, boundary):
  3505. content_type = 'multipart/form-data; boundary=%s' % boundary
  3506. out = b''
  3507. for k, v in data.items():
  3508. out += b'--' + boundary.encode('ascii') + b'\r\n'
  3509. if isinstance(k, compat_str):
  3510. k = k.encode('utf-8')
  3511. if isinstance(v, compat_str):
  3512. v = v.encode('utf-8')
  3513. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  3514. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  3515. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  3516. if boundary.encode('ascii') in content:
  3517. raise ValueError('Boundary overlaps with data')
  3518. out += content
  3519. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  3520. return out, content_type
  3521. def multipart_encode(data, boundary=None):
  3522. '''
  3523. Encode a dict to RFC 7578-compliant form-data
  3524. data:
  3525. A dict where keys and values can be either Unicode or bytes-like
  3526. objects.
  3527. boundary:
  3528. If specified a Unicode object, it's used as the boundary. Otherwise
  3529. a random boundary is generated.
  3530. Reference: https://tools.ietf.org/html/rfc7578
  3531. '''
  3532. has_specified_boundary = boundary is not None
  3533. while True:
  3534. if boundary is None:
  3535. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  3536. try:
  3537. out, content_type = _multipart_encode_impl(data, boundary)
  3538. break
  3539. except ValueError:
  3540. if has_specified_boundary:
  3541. raise
  3542. boundary = None
  3543. return out, content_type
  3544. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  3545. if isinstance(key_or_keys, (list, tuple)):
  3546. for key in key_or_keys:
  3547. if key not in d or d[key] is None or skip_false_values and not d[key]:
  3548. continue
  3549. return d[key]
  3550. return default
  3551. return d.get(key_or_keys, default)
  3552. def try_get(src, getter, expected_type=None):
  3553. if not isinstance(getter, (list, tuple)):
  3554. getter = [getter]
  3555. for get in getter:
  3556. try:
  3557. v = get(src)
  3558. except (AttributeError, KeyError, TypeError, IndexError):
  3559. pass
  3560. else:
  3561. if expected_type is None or isinstance(v, expected_type):
  3562. return v
  3563. def merge_dicts(*dicts):
  3564. merged = {}
  3565. for a_dict in dicts:
  3566. for k, v in a_dict.items():
  3567. if v is None:
  3568. continue
  3569. if (k not in merged
  3570. or (isinstance(v, compat_str) and v
  3571. and isinstance(merged[k], compat_str)
  3572. and not merged[k])):
  3573. merged[k] = v
  3574. return merged
  3575. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  3576. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  3577. US_RATINGS = {
  3578. 'G': 0,
  3579. 'PG': 10,
  3580. 'PG-13': 13,
  3581. 'R': 16,
  3582. 'NC': 18,
  3583. }
  3584. TV_PARENTAL_GUIDELINES = {
  3585. 'TV-Y': 0,
  3586. 'TV-Y7': 7,
  3587. 'TV-G': 0,
  3588. 'TV-PG': 0,
  3589. 'TV-14': 14,
  3590. 'TV-MA': 17,
  3591. }
  3592. def parse_age_limit(s):
  3593. if type(s) == int:
  3594. return s if 0 <= s <= 21 else None
  3595. if not isinstance(s, compat_basestring):
  3596. return None
  3597. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  3598. if m:
  3599. return int(m.group('age'))
  3600. if s in US_RATINGS:
  3601. return US_RATINGS[s]
  3602. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  3603. if m:
  3604. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  3605. return None
  3606. def strip_jsonp(code):
  3607. return re.sub(
  3608. r'''(?sx)^
  3609. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  3610. (?:\s*&&\s*(?P=func_name))?
  3611. \s*\(\s*(?P<callback_data>.*)\);?
  3612. \s*?(?://[^\n]*)*$''',
  3613. r'\g<callback_data>', code)
  3614. def js_to_json(code):
  3615. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  3616. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  3617. INTEGER_TABLE = (
  3618. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  3619. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  3620. )
  3621. def fix_kv(m):
  3622. v = m.group(0)
  3623. if v in ('true', 'false', 'null'):
  3624. return v
  3625. elif v.startswith('/*') or v.startswith('//') or v == ',':
  3626. return ""
  3627. if v[0] in ("'", '"'):
  3628. v = re.sub(r'(?s)\\.|"', lambda m: {
  3629. '"': '\\"',
  3630. "\\'": "'",
  3631. '\\\n': '',
  3632. '\\x': '\\u00',
  3633. }.get(m.group(0), m.group(0)), v[1:-1])
  3634. for regex, base in INTEGER_TABLE:
  3635. im = re.match(regex, v)
  3636. if im:
  3637. i = int(im.group(1), base)
  3638. return '"%d":' % i if v.endswith(':') else '%d' % i
  3639. return '"%s"' % v
  3640. return re.sub(r'''(?sx)
  3641. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  3642. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  3643. {comment}|,(?={skip}[\]}}])|
  3644. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  3645. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  3646. [0-9]+(?={skip}:)
  3647. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  3648. def qualities(quality_ids):
  3649. """ Get a numeric quality value out of a list of possible values """
  3650. def q(qid):
  3651. try:
  3652. return quality_ids.index(qid)
  3653. except ValueError:
  3654. return -1
  3655. return q
  3656. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  3657. def limit_length(s, length):
  3658. """ Add ellipses to overly long strings """
  3659. if s is None:
  3660. return None
  3661. ELLIPSES = '...'
  3662. if len(s) > length:
  3663. return s[:length - len(ELLIPSES)] + ELLIPSES
  3664. return s
  3665. def version_tuple(v):
  3666. return tuple(int(e) for e in re.split(r'[-.]', v))
  3667. def is_outdated_version(version, limit, assume_new=True):
  3668. if not version:
  3669. return not assume_new
  3670. try:
  3671. return version_tuple(version) < version_tuple(limit)
  3672. except ValueError:
  3673. return not assume_new
  3674. def ytdl_is_updateable():
  3675. """ Returns if youtube-dl can be updated with -U """
  3676. from zipimport import zipimporter
  3677. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  3678. def args_to_str(args):
  3679. # Get a short string representation for a subprocess command
  3680. return ' '.join(compat_shlex_quote(a) for a in args)
  3681. def error_to_compat_str(err):
  3682. err_str = str(err)
  3683. # On python 2 error byte string must be decoded with proper
  3684. # encoding rather than ascii
  3685. if sys.version_info[0] < 3:
  3686. err_str = err_str.decode(preferredencoding())
  3687. return err_str
  3688. def mimetype2ext(mt):
  3689. if mt is None:
  3690. return None
  3691. ext = {
  3692. 'audio/mp4': 'm4a',
  3693. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  3694. # it's the most popular one
  3695. 'audio/mpeg': 'mp3',
  3696. }.get(mt)
  3697. if ext is not None:
  3698. return ext
  3699. _, _, res = mt.rpartition('/')
  3700. res = res.split(';')[0].strip().lower()
  3701. return {
  3702. '3gpp': '3gp',
  3703. 'smptett+xml': 'tt',
  3704. 'ttaf+xml': 'dfxp',
  3705. 'ttml+xml': 'ttml',
  3706. 'x-flv': 'flv',
  3707. 'x-mp4-fragmented': 'mp4',
  3708. 'x-ms-sami': 'sami',
  3709. 'x-ms-wmv': 'wmv',
  3710. 'mpegurl': 'm3u8',
  3711. 'x-mpegurl': 'm3u8',
  3712. 'vnd.apple.mpegurl': 'm3u8',
  3713. 'dash+xml': 'mpd',
  3714. 'f4m+xml': 'f4m',
  3715. 'hds+xml': 'f4m',
  3716. 'vnd.ms-sstr+xml': 'ism',
  3717. 'quicktime': 'mov',
  3718. 'mp2t': 'ts',
  3719. }.get(res, res)
  3720. def parse_codecs(codecs_str):
  3721. # http://tools.ietf.org/html/rfc6381
  3722. if not codecs_str:
  3723. return {}
  3724. splited_codecs = list(filter(None, map(
  3725. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  3726. vcodec, acodec = None, None
  3727. for full_codec in splited_codecs:
  3728. codec = full_codec.split('.')[0]
  3729. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'):
  3730. if not vcodec:
  3731. vcodec = full_codec
  3732. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  3733. if not acodec:
  3734. acodec = full_codec
  3735. else:
  3736. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  3737. if not vcodec and not acodec:
  3738. if len(splited_codecs) == 2:
  3739. return {
  3740. 'vcodec': splited_codecs[0],
  3741. 'acodec': splited_codecs[1],
  3742. }
  3743. else:
  3744. return {
  3745. 'vcodec': vcodec or 'none',
  3746. 'acodec': acodec or 'none',
  3747. }
  3748. return {}
  3749. def urlhandle_detect_ext(url_handle):
  3750. getheader = url_handle.headers.get
  3751. cd = getheader('Content-Disposition')
  3752. if cd:
  3753. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  3754. if m:
  3755. e = determine_ext(m.group('filename'), default_ext=None)
  3756. if e:
  3757. return e
  3758. return mimetype2ext(getheader('Content-Type'))
  3759. def encode_data_uri(data, mime_type):
  3760. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  3761. def age_restricted(content_limit, age_limit):
  3762. """ Returns True iff the content should be blocked """
  3763. if age_limit is None: # No limit set
  3764. return False
  3765. if content_limit is None:
  3766. return False # Content available for everyone
  3767. return age_limit < content_limit
  3768. def is_html(first_bytes):
  3769. """ Detect whether a file contains HTML by examining its first bytes. """
  3770. BOMS = [
  3771. (b'\xef\xbb\xbf', 'utf-8'),
  3772. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  3773. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  3774. (b'\xff\xfe', 'utf-16-le'),
  3775. (b'\xfe\xff', 'utf-16-be'),
  3776. ]
  3777. for bom, enc in BOMS:
  3778. if first_bytes.startswith(bom):
  3779. s = first_bytes[len(bom):].decode(enc, 'replace')
  3780. break
  3781. else:
  3782. s = first_bytes.decode('utf-8', 'replace')
  3783. return re.match(r'^\s*<', s)
  3784. def determine_protocol(info_dict):
  3785. protocol = info_dict.get('protocol')
  3786. if protocol is not None:
  3787. return protocol
  3788. url = info_dict['url']
  3789. if url.startswith('rtmp'):
  3790. return 'rtmp'
  3791. elif url.startswith('mms'):
  3792. return 'mms'
  3793. elif url.startswith('rtsp'):
  3794. return 'rtsp'
  3795. ext = determine_ext(url)
  3796. if ext == 'm3u8':
  3797. return 'm3u8'
  3798. elif ext == 'f4m':
  3799. return 'f4m'
  3800. return compat_urllib_parse_urlparse(url).scheme
  3801. def render_table(header_row, data):
  3802. """ Render a list of rows, each as a list of values """
  3803. table = [header_row] + data
  3804. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  3805. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  3806. return '\n'.join(format_str % tuple(row) for row in table)
  3807. def _match_one(filter_part, dct):
  3808. COMPARISON_OPERATORS = {
  3809. '<': operator.lt,
  3810. '<=': operator.le,
  3811. '>': operator.gt,
  3812. '>=': operator.ge,
  3813. '=': operator.eq,
  3814. '!=': operator.ne,
  3815. }
  3816. operator_rex = re.compile(r'''(?x)\s*
  3817. (?P<key>[a-z_]+)
  3818. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  3819. (?:
  3820. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  3821. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  3822. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  3823. )
  3824. \s*$
  3825. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  3826. m = operator_rex.search(filter_part)
  3827. if m:
  3828. op = COMPARISON_OPERATORS[m.group('op')]
  3829. actual_value = dct.get(m.group('key'))
  3830. if (m.group('quotedstrval') is not None
  3831. or m.group('strval') is not None
  3832. # If the original field is a string and matching comparisonvalue is
  3833. # a number we should respect the origin of the original field
  3834. # and process comparison value as a string (see
  3835. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  3836. or actual_value is not None and m.group('intval') is not None
  3837. and isinstance(actual_value, compat_str)):
  3838. if m.group('op') not in ('=', '!='):
  3839. raise ValueError(
  3840. 'Operator %s does not support string values!' % m.group('op'))
  3841. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  3842. quote = m.group('quote')
  3843. if quote is not None:
  3844. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  3845. else:
  3846. try:
  3847. comparison_value = int(m.group('intval'))
  3848. except ValueError:
  3849. comparison_value = parse_filesize(m.group('intval'))
  3850. if comparison_value is None:
  3851. comparison_value = parse_filesize(m.group('intval') + 'B')
  3852. if comparison_value is None:
  3853. raise ValueError(
  3854. 'Invalid integer value %r in filter part %r' % (
  3855. m.group('intval'), filter_part))
  3856. if actual_value is None:
  3857. return m.group('none_inclusive')
  3858. return op(actual_value, comparison_value)
  3859. UNARY_OPERATORS = {
  3860. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  3861. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  3862. }
  3863. operator_rex = re.compile(r'''(?x)\s*
  3864. (?P<op>%s)\s*(?P<key>[a-z_]+)
  3865. \s*$
  3866. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  3867. m = operator_rex.search(filter_part)
  3868. if m:
  3869. op = UNARY_OPERATORS[m.group('op')]
  3870. actual_value = dct.get(m.group('key'))
  3871. return op(actual_value)
  3872. raise ValueError('Invalid filter part %r' % filter_part)
  3873. def match_str(filter_str, dct):
  3874. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  3875. return all(
  3876. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  3877. def match_filter_func(filter_str):
  3878. def _match_func(info_dict):
  3879. if match_str(filter_str, info_dict):
  3880. return None
  3881. else:
  3882. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  3883. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  3884. return _match_func
  3885. def parse_dfxp_time_expr(time_expr):
  3886. if not time_expr:
  3887. return
  3888. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  3889. if mobj:
  3890. return float(mobj.group('time_offset'))
  3891. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  3892. if mobj:
  3893. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  3894. def srt_subtitles_timecode(seconds):
  3895. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  3896. def dfxp2srt(dfxp_data):
  3897. '''
  3898. @param dfxp_data A bytes-like object containing DFXP data
  3899. @returns A unicode object containing converted SRT data
  3900. '''
  3901. LEGACY_NAMESPACES = (
  3902. (b'http://www.w3.org/ns/ttml', [
  3903. b'http://www.w3.org/2004/11/ttaf1',
  3904. b'http://www.w3.org/2006/04/ttaf1',
  3905. b'http://www.w3.org/2006/10/ttaf1',
  3906. ]),
  3907. (b'http://www.w3.org/ns/ttml#styling', [
  3908. b'http://www.w3.org/ns/ttml#style',
  3909. ]),
  3910. )
  3911. SUPPORTED_STYLING = [
  3912. 'color',
  3913. 'fontFamily',
  3914. 'fontSize',
  3915. 'fontStyle',
  3916. 'fontWeight',
  3917. 'textDecoration'
  3918. ]
  3919. _x = functools.partial(xpath_with_ns, ns_map={
  3920. 'xml': 'http://www.w3.org/XML/1998/namespace',
  3921. 'ttml': 'http://www.w3.org/ns/ttml',
  3922. 'tts': 'http://www.w3.org/ns/ttml#styling',
  3923. })
  3924. styles = {}
  3925. default_style = {}
  3926. class TTMLPElementParser(object):
  3927. _out = ''
  3928. _unclosed_elements = []
  3929. _applied_styles = []
  3930. def start(self, tag, attrib):
  3931. if tag in (_x('ttml:br'), 'br'):
  3932. self._out += '\n'
  3933. else:
  3934. unclosed_elements = []
  3935. style = {}
  3936. element_style_id = attrib.get('style')
  3937. if default_style:
  3938. style.update(default_style)
  3939. if element_style_id:
  3940. style.update(styles.get(element_style_id, {}))
  3941. for prop in SUPPORTED_STYLING:
  3942. prop_val = attrib.get(_x('tts:' + prop))
  3943. if prop_val:
  3944. style[prop] = prop_val
  3945. if style:
  3946. font = ''
  3947. for k, v in sorted(style.items()):
  3948. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  3949. continue
  3950. if k == 'color':
  3951. font += ' color="%s"' % v
  3952. elif k == 'fontSize':
  3953. font += ' size="%s"' % v
  3954. elif k == 'fontFamily':
  3955. font += ' face="%s"' % v
  3956. elif k == 'fontWeight' and v == 'bold':
  3957. self._out += '<b>'
  3958. unclosed_elements.append('b')
  3959. elif k == 'fontStyle' and v == 'italic':
  3960. self._out += '<i>'
  3961. unclosed_elements.append('i')
  3962. elif k == 'textDecoration' and v == 'underline':
  3963. self._out += '<u>'
  3964. unclosed_elements.append('u')
  3965. if font:
  3966. self._out += '<font' + font + '>'
  3967. unclosed_elements.append('font')
  3968. applied_style = {}
  3969. if self._applied_styles:
  3970. applied_style.update(self._applied_styles[-1])
  3971. applied_style.update(style)
  3972. self._applied_styles.append(applied_style)
  3973. self._unclosed_elements.append(unclosed_elements)
  3974. def end(self, tag):
  3975. if tag not in (_x('ttml:br'), 'br'):
  3976. unclosed_elements = self._unclosed_elements.pop()
  3977. for element in reversed(unclosed_elements):
  3978. self._out += '</%s>' % element
  3979. if unclosed_elements and self._applied_styles:
  3980. self._applied_styles.pop()
  3981. def data(self, data):
  3982. self._out += data
  3983. def close(self):
  3984. return self._out.strip()
  3985. def parse_node(node):
  3986. target = TTMLPElementParser()
  3987. parser = xml.etree.ElementTree.XMLParser(target=target)
  3988. parser.feed(xml.etree.ElementTree.tostring(node))
  3989. return parser.close()
  3990. for k, v in LEGACY_NAMESPACES:
  3991. for ns in v:
  3992. dfxp_data = dfxp_data.replace(ns, k)
  3993. dfxp = compat_etree_fromstring(dfxp_data)
  3994. out = []
  3995. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  3996. if not paras:
  3997. raise ValueError('Invalid dfxp/TTML subtitle')
  3998. repeat = False
  3999. while True:
  4000. for style in dfxp.findall(_x('.//ttml:style')):
  4001. style_id = style.get('id') or style.get(_x('xml:id'))
  4002. if not style_id:
  4003. continue
  4004. parent_style_id = style.get('style')
  4005. if parent_style_id:
  4006. if parent_style_id not in styles:
  4007. repeat = True
  4008. continue
  4009. styles[style_id] = styles[parent_style_id].copy()
  4010. for prop in SUPPORTED_STYLING:
  4011. prop_val = style.get(_x('tts:' + prop))
  4012. if prop_val:
  4013. styles.setdefault(style_id, {})[prop] = prop_val
  4014. if repeat:
  4015. repeat = False
  4016. else:
  4017. break
  4018. for p in ('body', 'div'):
  4019. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  4020. if ele is None:
  4021. continue
  4022. style = styles.get(ele.get('style'))
  4023. if not style:
  4024. continue
  4025. default_style.update(style)
  4026. for para, index in zip(paras, itertools.count(1)):
  4027. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  4028. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  4029. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  4030. if begin_time is None:
  4031. continue
  4032. if not end_time:
  4033. if not dur:
  4034. continue
  4035. end_time = begin_time + dur
  4036. out.append('%d\n%s --> %s\n%s\n\n' % (
  4037. index,
  4038. srt_subtitles_timecode(begin_time),
  4039. srt_subtitles_timecode(end_time),
  4040. parse_node(para)))
  4041. return ''.join(out)
  4042. def cli_option(params, command_option, param):
  4043. param = params.get(param)
  4044. if param:
  4045. param = compat_str(param)
  4046. return [command_option, param] if param is not None else []
  4047. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  4048. param = params.get(param)
  4049. if param is None:
  4050. return []
  4051. assert isinstance(param, bool)
  4052. if separator:
  4053. return [command_option + separator + (true_value if param else false_value)]
  4054. return [command_option, true_value if param else false_value]
  4055. def cli_valueless_option(params, command_option, param, expected_value=True):
  4056. param = params.get(param)
  4057. return [command_option] if param == expected_value else []
  4058. def cli_configuration_args(params, param, default=[]):
  4059. ex_args = params.get(param)
  4060. if ex_args is None:
  4061. return default
  4062. assert isinstance(ex_args, list)
  4063. return ex_args
  4064. class ISO639Utils(object):
  4065. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  4066. _lang_map = {
  4067. 'aa': 'aar',
  4068. 'ab': 'abk',
  4069. 'ae': 'ave',
  4070. 'af': 'afr',
  4071. 'ak': 'aka',
  4072. 'am': 'amh',
  4073. 'an': 'arg',
  4074. 'ar': 'ara',
  4075. 'as': 'asm',
  4076. 'av': 'ava',
  4077. 'ay': 'aym',
  4078. 'az': 'aze',
  4079. 'ba': 'bak',
  4080. 'be': 'bel',
  4081. 'bg': 'bul',
  4082. 'bh': 'bih',
  4083. 'bi': 'bis',
  4084. 'bm': 'bam',
  4085. 'bn': 'ben',
  4086. 'bo': 'bod',
  4087. 'br': 'bre',
  4088. 'bs': 'bos',
  4089. 'ca': 'cat',
  4090. 'ce': 'che',
  4091. 'ch': 'cha',
  4092. 'co': 'cos',
  4093. 'cr': 'cre',
  4094. 'cs': 'ces',
  4095. 'cu': 'chu',
  4096. 'cv': 'chv',
  4097. 'cy': 'cym',
  4098. 'da': 'dan',
  4099. 'de': 'deu',
  4100. 'dv': 'div',
  4101. 'dz': 'dzo',
  4102. 'ee': 'ewe',
  4103. 'el': 'ell',
  4104. 'en': 'eng',
  4105. 'eo': 'epo',
  4106. 'es': 'spa',
  4107. 'et': 'est',
  4108. 'eu': 'eus',
  4109. 'fa': 'fas',
  4110. 'ff': 'ful',
  4111. 'fi': 'fin',
  4112. 'fj': 'fij',
  4113. 'fo': 'fao',
  4114. 'fr': 'fra',
  4115. 'fy': 'fry',
  4116. 'ga': 'gle',
  4117. 'gd': 'gla',
  4118. 'gl': 'glg',
  4119. 'gn': 'grn',
  4120. 'gu': 'guj',
  4121. 'gv': 'glv',
  4122. 'ha': 'hau',
  4123. 'he': 'heb',
  4124. 'iw': 'heb', # Replaced by he in 1989 revision
  4125. 'hi': 'hin',
  4126. 'ho': 'hmo',
  4127. 'hr': 'hrv',
  4128. 'ht': 'hat',
  4129. 'hu': 'hun',
  4130. 'hy': 'hye',
  4131. 'hz': 'her',
  4132. 'ia': 'ina',
  4133. 'id': 'ind',
  4134. 'in': 'ind', # Replaced by id in 1989 revision
  4135. 'ie': 'ile',
  4136. 'ig': 'ibo',
  4137. 'ii': 'iii',
  4138. 'ik': 'ipk',
  4139. 'io': 'ido',
  4140. 'is': 'isl',
  4141. 'it': 'ita',
  4142. 'iu': 'iku',
  4143. 'ja': 'jpn',
  4144. 'jv': 'jav',
  4145. 'ka': 'kat',
  4146. 'kg': 'kon',
  4147. 'ki': 'kik',
  4148. 'kj': 'kua',
  4149. 'kk': 'kaz',
  4150. 'kl': 'kal',
  4151. 'km': 'khm',
  4152. 'kn': 'kan',
  4153. 'ko': 'kor',
  4154. 'kr': 'kau',
  4155. 'ks': 'kas',
  4156. 'ku': 'kur',
  4157. 'kv': 'kom',
  4158. 'kw': 'cor',
  4159. 'ky': 'kir',
  4160. 'la': 'lat',
  4161. 'lb': 'ltz',
  4162. 'lg': 'lug',
  4163. 'li': 'lim',
  4164. 'ln': 'lin',
  4165. 'lo': 'lao',
  4166. 'lt': 'lit',
  4167. 'lu': 'lub',
  4168. 'lv': 'lav',
  4169. 'mg': 'mlg',
  4170. 'mh': 'mah',
  4171. 'mi': 'mri',
  4172. 'mk': 'mkd',
  4173. 'ml': 'mal',
  4174. 'mn': 'mon',
  4175. 'mr': 'mar',
  4176. 'ms': 'msa',
  4177. 'mt': 'mlt',
  4178. 'my': 'mya',
  4179. 'na': 'nau',
  4180. 'nb': 'nob',
  4181. 'nd': 'nde',
  4182. 'ne': 'nep',
  4183. 'ng': 'ndo',
  4184. 'nl': 'nld',
  4185. 'nn': 'nno',
  4186. 'no': 'nor',
  4187. 'nr': 'nbl',
  4188. 'nv': 'nav',
  4189. 'ny': 'nya',
  4190. 'oc': 'oci',
  4191. 'oj': 'oji',
  4192. 'om': 'orm',
  4193. 'or': 'ori',
  4194. 'os': 'oss',
  4195. 'pa': 'pan',
  4196. 'pi': 'pli',
  4197. 'pl': 'pol',
  4198. 'ps': 'pus',
  4199. 'pt': 'por',
  4200. 'qu': 'que',
  4201. 'rm': 'roh',
  4202. 'rn': 'run',
  4203. 'ro': 'ron',
  4204. 'ru': 'rus',
  4205. 'rw': 'kin',
  4206. 'sa': 'san',
  4207. 'sc': 'srd',
  4208. 'sd': 'snd',
  4209. 'se': 'sme',
  4210. 'sg': 'sag',
  4211. 'si': 'sin',
  4212. 'sk': 'slk',
  4213. 'sl': 'slv',
  4214. 'sm': 'smo',
  4215. 'sn': 'sna',
  4216. 'so': 'som',
  4217. 'sq': 'sqi',
  4218. 'sr': 'srp',
  4219. 'ss': 'ssw',
  4220. 'st': 'sot',
  4221. 'su': 'sun',
  4222. 'sv': 'swe',
  4223. 'sw': 'swa',
  4224. 'ta': 'tam',
  4225. 'te': 'tel',
  4226. 'tg': 'tgk',
  4227. 'th': 'tha',
  4228. 'ti': 'tir',
  4229. 'tk': 'tuk',
  4230. 'tl': 'tgl',
  4231. 'tn': 'tsn',
  4232. 'to': 'ton',
  4233. 'tr': 'tur',
  4234. 'ts': 'tso',
  4235. 'tt': 'tat',
  4236. 'tw': 'twi',
  4237. 'ty': 'tah',
  4238. 'ug': 'uig',
  4239. 'uk': 'ukr',
  4240. 'ur': 'urd',
  4241. 'uz': 'uzb',
  4242. 've': 'ven',
  4243. 'vi': 'vie',
  4244. 'vo': 'vol',
  4245. 'wa': 'wln',
  4246. 'wo': 'wol',
  4247. 'xh': 'xho',
  4248. 'yi': 'yid',
  4249. 'ji': 'yid', # Replaced by yi in 1989 revision
  4250. 'yo': 'yor',
  4251. 'za': 'zha',
  4252. 'zh': 'zho',
  4253. 'zu': 'zul',
  4254. }
  4255. @classmethod
  4256. def short2long(cls, code):
  4257. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  4258. return cls._lang_map.get(code[:2])
  4259. @classmethod
  4260. def long2short(cls, code):
  4261. """Convert language code from ISO 639-2/T to ISO 639-1"""
  4262. for short_name, long_name in cls._lang_map.items():
  4263. if long_name == code:
  4264. return short_name
  4265. class ISO3166Utils(object):
  4266. # From http://data.okfn.org/data/core/country-list
  4267. _country_map = {
  4268. 'AF': 'Afghanistan',
  4269. 'AX': 'Åland Islands',
  4270. 'AL': 'Albania',
  4271. 'DZ': 'Algeria',
  4272. 'AS': 'American Samoa',
  4273. 'AD': 'Andorra',
  4274. 'AO': 'Angola',
  4275. 'AI': 'Anguilla',
  4276. 'AQ': 'Antarctica',
  4277. 'AG': 'Antigua and Barbuda',
  4278. 'AR': 'Argentina',
  4279. 'AM': 'Armenia',
  4280. 'AW': 'Aruba',
  4281. 'AU': 'Australia',
  4282. 'AT': 'Austria',
  4283. 'AZ': 'Azerbaijan',
  4284. 'BS': 'Bahamas',
  4285. 'BH': 'Bahrain',
  4286. 'BD': 'Bangladesh',
  4287. 'BB': 'Barbados',
  4288. 'BY': 'Belarus',
  4289. 'BE': 'Belgium',
  4290. 'BZ': 'Belize',
  4291. 'BJ': 'Benin',
  4292. 'BM': 'Bermuda',
  4293. 'BT': 'Bhutan',
  4294. 'BO': 'Bolivia, Plurinational State of',
  4295. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  4296. 'BA': 'Bosnia and Herzegovina',
  4297. 'BW': 'Botswana',
  4298. 'BV': 'Bouvet Island',
  4299. 'BR': 'Brazil',
  4300. 'IO': 'British Indian Ocean Territory',
  4301. 'BN': 'Brunei Darussalam',
  4302. 'BG': 'Bulgaria',
  4303. 'BF': 'Burkina Faso',
  4304. 'BI': 'Burundi',
  4305. 'KH': 'Cambodia',
  4306. 'CM': 'Cameroon',
  4307. 'CA': 'Canada',
  4308. 'CV': 'Cape Verde',
  4309. 'KY': 'Cayman Islands',
  4310. 'CF': 'Central African Republic',
  4311. 'TD': 'Chad',
  4312. 'CL': 'Chile',
  4313. 'CN': 'China',
  4314. 'CX': 'Christmas Island',
  4315. 'CC': 'Cocos (Keeling) Islands',
  4316. 'CO': 'Colombia',
  4317. 'KM': 'Comoros',
  4318. 'CG': 'Congo',
  4319. 'CD': 'Congo, the Democratic Republic of the',
  4320. 'CK': 'Cook Islands',
  4321. 'CR': 'Costa Rica',
  4322. 'CI': 'Côte d\'Ivoire',
  4323. 'HR': 'Croatia',
  4324. 'CU': 'Cuba',
  4325. 'CW': 'Curaçao',
  4326. 'CY': 'Cyprus',
  4327. 'CZ': 'Czech Republic',
  4328. 'DK': 'Denmark',
  4329. 'DJ': 'Djibouti',
  4330. 'DM': 'Dominica',
  4331. 'DO': 'Dominican Republic',
  4332. 'EC': 'Ecuador',
  4333. 'EG': 'Egypt',
  4334. 'SV': 'El Salvador',
  4335. 'GQ': 'Equatorial Guinea',
  4336. 'ER': 'Eritrea',
  4337. 'EE': 'Estonia',
  4338. 'ET': 'Ethiopia',
  4339. 'FK': 'Falkland Islands (Malvinas)',
  4340. 'FO': 'Faroe Islands',
  4341. 'FJ': 'Fiji',
  4342. 'FI': 'Finland',
  4343. 'FR': 'France',
  4344. 'GF': 'French Guiana',
  4345. 'PF': 'French Polynesia',
  4346. 'TF': 'French Southern Territories',
  4347. 'GA': 'Gabon',
  4348. 'GM': 'Gambia',
  4349. 'GE': 'Georgia',
  4350. 'DE': 'Germany',
  4351. 'GH': 'Ghana',
  4352. 'GI': 'Gibraltar',
  4353. 'GR': 'Greece',
  4354. 'GL': 'Greenland',
  4355. 'GD': 'Grenada',
  4356. 'GP': 'Guadeloupe',
  4357. 'GU': 'Guam',
  4358. 'GT': 'Guatemala',
  4359. 'GG': 'Guernsey',
  4360. 'GN': 'Guinea',
  4361. 'GW': 'Guinea-Bissau',
  4362. 'GY': 'Guyana',
  4363. 'HT': 'Haiti',
  4364. 'HM': 'Heard Island and McDonald Islands',
  4365. 'VA': 'Holy See (Vatican City State)',
  4366. 'HN': 'Honduras',
  4367. 'HK': 'Hong Kong',
  4368. 'HU': 'Hungary',
  4369. 'IS': 'Iceland',
  4370. 'IN': 'India',
  4371. 'ID': 'Indonesia',
  4372. 'IR': 'Iran, Islamic Republic of',
  4373. 'IQ': 'Iraq',
  4374. 'IE': 'Ireland',
  4375. 'IM': 'Isle of Man',
  4376. 'IL': 'Israel',
  4377. 'IT': 'Italy',
  4378. 'JM': 'Jamaica',
  4379. 'JP': 'Japan',
  4380. 'JE': 'Jersey',
  4381. 'JO': 'Jordan',
  4382. 'KZ': 'Kazakhstan',
  4383. 'KE': 'Kenya',
  4384. 'KI': 'Kiribati',
  4385. 'KP': 'Korea, Democratic People\'s Republic of',
  4386. 'KR': 'Korea, Republic of',
  4387. 'KW': 'Kuwait',
  4388. 'KG': 'Kyrgyzstan',
  4389. 'LA': 'Lao People\'s Democratic Republic',
  4390. 'LV': 'Latvia',
  4391. 'LB': 'Lebanon',
  4392. 'LS': 'Lesotho',
  4393. 'LR': 'Liberia',
  4394. 'LY': 'Libya',
  4395. 'LI': 'Liechtenstein',
  4396. 'LT': 'Lithuania',
  4397. 'LU': 'Luxembourg',
  4398. 'MO': 'Macao',
  4399. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  4400. 'MG': 'Madagascar',
  4401. 'MW': 'Malawi',
  4402. 'MY': 'Malaysia',
  4403. 'MV': 'Maldives',
  4404. 'ML': 'Mali',
  4405. 'MT': 'Malta',
  4406. 'MH': 'Marshall Islands',
  4407. 'MQ': 'Martinique',
  4408. 'MR': 'Mauritania',
  4409. 'MU': 'Mauritius',
  4410. 'YT': 'Mayotte',
  4411. 'MX': 'Mexico',
  4412. 'FM': 'Micronesia, Federated States of',
  4413. 'MD': 'Moldova, Republic of',
  4414. 'MC': 'Monaco',
  4415. 'MN': 'Mongolia',
  4416. 'ME': 'Montenegro',
  4417. 'MS': 'Montserrat',
  4418. 'MA': 'Morocco',
  4419. 'MZ': 'Mozambique',
  4420. 'MM': 'Myanmar',
  4421. 'NA': 'Namibia',
  4422. 'NR': 'Nauru',
  4423. 'NP': 'Nepal',
  4424. 'NL': 'Netherlands',
  4425. 'NC': 'New Caledonia',
  4426. 'NZ': 'New Zealand',
  4427. 'NI': 'Nicaragua',
  4428. 'NE': 'Niger',
  4429. 'NG': 'Nigeria',
  4430. 'NU': 'Niue',
  4431. 'NF': 'Norfolk Island',
  4432. 'MP': 'Northern Mariana Islands',
  4433. 'NO': 'Norway',
  4434. 'OM': 'Oman',
  4435. 'PK': 'Pakistan',
  4436. 'PW': 'Palau',
  4437. 'PS': 'Palestine, State of',
  4438. 'PA': 'Panama',
  4439. 'PG': 'Papua New Guinea',
  4440. 'PY': 'Paraguay',
  4441. 'PE': 'Peru',
  4442. 'PH': 'Philippines',
  4443. 'PN': 'Pitcairn',
  4444. 'PL': 'Poland',
  4445. 'PT': 'Portugal',
  4446. 'PR': 'Puerto Rico',
  4447. 'QA': 'Qatar',
  4448. 'RE': 'Réunion',
  4449. 'RO': 'Romania',
  4450. 'RU': 'Russian Federation',
  4451. 'RW': 'Rwanda',
  4452. 'BL': 'Saint Barthélemy',
  4453. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  4454. 'KN': 'Saint Kitts and Nevis',
  4455. 'LC': 'Saint Lucia',
  4456. 'MF': 'Saint Martin (French part)',
  4457. 'PM': 'Saint Pierre and Miquelon',
  4458. 'VC': 'Saint Vincent and the Grenadines',
  4459. 'WS': 'Samoa',
  4460. 'SM': 'San Marino',
  4461. 'ST': 'Sao Tome and Principe',
  4462. 'SA': 'Saudi Arabia',
  4463. 'SN': 'Senegal',
  4464. 'RS': 'Serbia',
  4465. 'SC': 'Seychelles',
  4466. 'SL': 'Sierra Leone',
  4467. 'SG': 'Singapore',
  4468. 'SX': 'Sint Maarten (Dutch part)',
  4469. 'SK': 'Slovakia',
  4470. 'SI': 'Slovenia',
  4471. 'SB': 'Solomon Islands',
  4472. 'SO': 'Somalia',
  4473. 'ZA': 'South Africa',
  4474. 'GS': 'South Georgia and the South Sandwich Islands',
  4475. 'SS': 'South Sudan',
  4476. 'ES': 'Spain',
  4477. 'LK': 'Sri Lanka',
  4478. 'SD': 'Sudan',
  4479. 'SR': 'Suriname',
  4480. 'SJ': 'Svalbard and Jan Mayen',
  4481. 'SZ': 'Swaziland',
  4482. 'SE': 'Sweden',
  4483. 'CH': 'Switzerland',
  4484. 'SY': 'Syrian Arab Republic',
  4485. 'TW': 'Taiwan, Province of China',
  4486. 'TJ': 'Tajikistan',
  4487. 'TZ': 'Tanzania, United Republic of',
  4488. 'TH': 'Thailand',
  4489. 'TL': 'Timor-Leste',
  4490. 'TG': 'Togo',
  4491. 'TK': 'Tokelau',
  4492. 'TO': 'Tonga',
  4493. 'TT': 'Trinidad and Tobago',
  4494. 'TN': 'Tunisia',
  4495. 'TR': 'Turkey',
  4496. 'TM': 'Turkmenistan',
  4497. 'TC': 'Turks and Caicos Islands',
  4498. 'TV': 'Tuvalu',
  4499. 'UG': 'Uganda',
  4500. 'UA': 'Ukraine',
  4501. 'AE': 'United Arab Emirates',
  4502. 'GB': 'United Kingdom',
  4503. 'US': 'United States',
  4504. 'UM': 'United States Minor Outlying Islands',
  4505. 'UY': 'Uruguay',
  4506. 'UZ': 'Uzbekistan',
  4507. 'VU': 'Vanuatu',
  4508. 'VE': 'Venezuela, Bolivarian Republic of',
  4509. 'VN': 'Viet Nam',
  4510. 'VG': 'Virgin Islands, British',
  4511. 'VI': 'Virgin Islands, U.S.',
  4512. 'WF': 'Wallis and Futuna',
  4513. 'EH': 'Western Sahara',
  4514. 'YE': 'Yemen',
  4515. 'ZM': 'Zambia',
  4516. 'ZW': 'Zimbabwe',
  4517. }
  4518. @classmethod
  4519. def short2full(cls, code):
  4520. """Convert an ISO 3166-2 country code to the corresponding full name"""
  4521. return cls._country_map.get(code.upper())
  4522. class GeoUtils(object):
  4523. # Major IPv4 address blocks per country
  4524. _country_ip_map = {
  4525. 'AD': '46.172.224.0/19',
  4526. 'AE': '94.200.0.0/13',
  4527. 'AF': '149.54.0.0/17',
  4528. 'AG': '209.59.64.0/18',
  4529. 'AI': '204.14.248.0/21',
  4530. 'AL': '46.99.0.0/16',
  4531. 'AM': '46.70.0.0/15',
  4532. 'AO': '105.168.0.0/13',
  4533. 'AP': '182.50.184.0/21',
  4534. 'AQ': '23.154.160.0/24',
  4535. 'AR': '181.0.0.0/12',
  4536. 'AS': '202.70.112.0/20',
  4537. 'AT': '77.116.0.0/14',
  4538. 'AU': '1.128.0.0/11',
  4539. 'AW': '181.41.0.0/18',
  4540. 'AX': '185.217.4.0/22',
  4541. 'AZ': '5.197.0.0/16',
  4542. 'BA': '31.176.128.0/17',
  4543. 'BB': '65.48.128.0/17',
  4544. 'BD': '114.130.0.0/16',
  4545. 'BE': '57.0.0.0/8',
  4546. 'BF': '102.178.0.0/15',
  4547. 'BG': '95.42.0.0/15',
  4548. 'BH': '37.131.0.0/17',
  4549. 'BI': '154.117.192.0/18',
  4550. 'BJ': '137.255.0.0/16',
  4551. 'BL': '185.212.72.0/23',
  4552. 'BM': '196.12.64.0/18',
  4553. 'BN': '156.31.0.0/16',
  4554. 'BO': '161.56.0.0/16',
  4555. 'BQ': '161.0.80.0/20',
  4556. 'BR': '191.128.0.0/12',
  4557. 'BS': '24.51.64.0/18',
  4558. 'BT': '119.2.96.0/19',
  4559. 'BW': '168.167.0.0/16',
  4560. 'BY': '178.120.0.0/13',
  4561. 'BZ': '179.42.192.0/18',
  4562. 'CA': '99.224.0.0/11',
  4563. 'CD': '41.243.0.0/16',
  4564. 'CF': '197.242.176.0/21',
  4565. 'CG': '160.113.0.0/16',
  4566. 'CH': '85.0.0.0/13',
  4567. 'CI': '102.136.0.0/14',
  4568. 'CK': '202.65.32.0/19',
  4569. 'CL': '152.172.0.0/14',
  4570. 'CM': '102.244.0.0/14',
  4571. 'CN': '36.128.0.0/10',
  4572. 'CO': '181.240.0.0/12',
  4573. 'CR': '201.192.0.0/12',
  4574. 'CU': '152.206.0.0/15',
  4575. 'CV': '165.90.96.0/19',
  4576. 'CW': '190.88.128.0/17',
  4577. 'CY': '31.153.0.0/16',
  4578. 'CZ': '88.100.0.0/14',
  4579. 'DE': '53.0.0.0/8',
  4580. 'DJ': '197.241.0.0/17',
  4581. 'DK': '87.48.0.0/12',
  4582. 'DM': '192.243.48.0/20',
  4583. 'DO': '152.166.0.0/15',
  4584. 'DZ': '41.96.0.0/12',
  4585. 'EC': '186.68.0.0/15',
  4586. 'EE': '90.190.0.0/15',
  4587. 'EG': '156.160.0.0/11',
  4588. 'ER': '196.200.96.0/20',
  4589. 'ES': '88.0.0.0/11',
  4590. 'ET': '196.188.0.0/14',
  4591. 'EU': '2.16.0.0/13',
  4592. 'FI': '91.152.0.0/13',
  4593. 'FJ': '144.120.0.0/16',
  4594. 'FK': '80.73.208.0/21',
  4595. 'FM': '119.252.112.0/20',
  4596. 'FO': '88.85.32.0/19',
  4597. 'FR': '90.0.0.0/9',
  4598. 'GA': '41.158.0.0/15',
  4599. 'GB': '25.0.0.0/8',
  4600. 'GD': '74.122.88.0/21',
  4601. 'GE': '31.146.0.0/16',
  4602. 'GF': '161.22.64.0/18',
  4603. 'GG': '62.68.160.0/19',
  4604. 'GH': '154.160.0.0/12',
  4605. 'GI': '95.164.0.0/16',
  4606. 'GL': '88.83.0.0/19',
  4607. 'GM': '160.182.0.0/15',
  4608. 'GN': '197.149.192.0/18',
  4609. 'GP': '104.250.0.0/19',
  4610. 'GQ': '105.235.224.0/20',
  4611. 'GR': '94.64.0.0/13',
  4612. 'GT': '168.234.0.0/16',
  4613. 'GU': '168.123.0.0/16',
  4614. 'GW': '197.214.80.0/20',
  4615. 'GY': '181.41.64.0/18',
  4616. 'HK': '113.252.0.0/14',
  4617. 'HN': '181.210.0.0/16',
  4618. 'HR': '93.136.0.0/13',
  4619. 'HT': '148.102.128.0/17',
  4620. 'HU': '84.0.0.0/14',
  4621. 'ID': '39.192.0.0/10',
  4622. 'IE': '87.32.0.0/12',
  4623. 'IL': '79.176.0.0/13',
  4624. 'IM': '5.62.80.0/20',
  4625. 'IN': '117.192.0.0/10',
  4626. 'IO': '203.83.48.0/21',
  4627. 'IQ': '37.236.0.0/14',
  4628. 'IR': '2.176.0.0/12',
  4629. 'IS': '82.221.0.0/16',
  4630. 'IT': '79.0.0.0/10',
  4631. 'JE': '87.244.64.0/18',
  4632. 'JM': '72.27.0.0/17',
  4633. 'JO': '176.29.0.0/16',
  4634. 'JP': '133.0.0.0/8',
  4635. 'KE': '105.48.0.0/12',
  4636. 'KG': '158.181.128.0/17',
  4637. 'KH': '36.37.128.0/17',
  4638. 'KI': '103.25.140.0/22',
  4639. 'KM': '197.255.224.0/20',
  4640. 'KN': '198.167.192.0/19',
  4641. 'KP': '175.45.176.0/22',
  4642. 'KR': '175.192.0.0/10',
  4643. 'KW': '37.36.0.0/14',
  4644. 'KY': '64.96.0.0/15',
  4645. 'KZ': '2.72.0.0/13',
  4646. 'LA': '115.84.64.0/18',
  4647. 'LB': '178.135.0.0/16',
  4648. 'LC': '24.92.144.0/20',
  4649. 'LI': '82.117.0.0/19',
  4650. 'LK': '112.134.0.0/15',
  4651. 'LR': '102.183.0.0/16',
  4652. 'LS': '129.232.0.0/17',
  4653. 'LT': '78.56.0.0/13',
  4654. 'LU': '188.42.0.0/16',
  4655. 'LV': '46.109.0.0/16',
  4656. 'LY': '41.252.0.0/14',
  4657. 'MA': '105.128.0.0/11',
  4658. 'MC': '88.209.64.0/18',
  4659. 'MD': '37.246.0.0/16',
  4660. 'ME': '178.175.0.0/17',
  4661. 'MF': '74.112.232.0/21',
  4662. 'MG': '154.126.0.0/17',
  4663. 'MH': '117.103.88.0/21',
  4664. 'MK': '77.28.0.0/15',
  4665. 'ML': '154.118.128.0/18',
  4666. 'MM': '37.111.0.0/17',
  4667. 'MN': '49.0.128.0/17',
  4668. 'MO': '60.246.0.0/16',
  4669. 'MP': '202.88.64.0/20',
  4670. 'MQ': '109.203.224.0/19',
  4671. 'MR': '41.188.64.0/18',
  4672. 'MS': '208.90.112.0/22',
  4673. 'MT': '46.11.0.0/16',
  4674. 'MU': '105.16.0.0/12',
  4675. 'MV': '27.114.128.0/18',
  4676. 'MW': '102.70.0.0/15',
  4677. 'MX': '187.192.0.0/11',
  4678. 'MY': '175.136.0.0/13',
  4679. 'MZ': '197.218.0.0/15',
  4680. 'NA': '41.182.0.0/16',
  4681. 'NC': '101.101.0.0/18',
  4682. 'NE': '197.214.0.0/18',
  4683. 'NF': '203.17.240.0/22',
  4684. 'NG': '105.112.0.0/12',
  4685. 'NI': '186.76.0.0/15',
  4686. 'NL': '145.96.0.0/11',
  4687. 'NO': '84.208.0.0/13',
  4688. 'NP': '36.252.0.0/15',
  4689. 'NR': '203.98.224.0/19',
  4690. 'NU': '49.156.48.0/22',
  4691. 'NZ': '49.224.0.0/14',
  4692. 'OM': '5.36.0.0/15',
  4693. 'PA': '186.72.0.0/15',
  4694. 'PE': '186.160.0.0/14',
  4695. 'PF': '123.50.64.0/18',
  4696. 'PG': '124.240.192.0/19',
  4697. 'PH': '49.144.0.0/13',
  4698. 'PK': '39.32.0.0/11',
  4699. 'PL': '83.0.0.0/11',
  4700. 'PM': '70.36.0.0/20',
  4701. 'PR': '66.50.0.0/16',
  4702. 'PS': '188.161.0.0/16',
  4703. 'PT': '85.240.0.0/13',
  4704. 'PW': '202.124.224.0/20',
  4705. 'PY': '181.120.0.0/14',
  4706. 'QA': '37.210.0.0/15',
  4707. 'RE': '102.35.0.0/16',
  4708. 'RO': '79.112.0.0/13',
  4709. 'RS': '93.86.0.0/15',
  4710. 'RU': '5.136.0.0/13',
  4711. 'RW': '41.186.0.0/16',
  4712. 'SA': '188.48.0.0/13',
  4713. 'SB': '202.1.160.0/19',
  4714. 'SC': '154.192.0.0/11',
  4715. 'SD': '102.120.0.0/13',
  4716. 'SE': '78.64.0.0/12',
  4717. 'SG': '8.128.0.0/10',
  4718. 'SI': '188.196.0.0/14',
  4719. 'SK': '78.98.0.0/15',
  4720. 'SL': '102.143.0.0/17',
  4721. 'SM': '89.186.32.0/19',
  4722. 'SN': '41.82.0.0/15',
  4723. 'SO': '154.115.192.0/18',
  4724. 'SR': '186.179.128.0/17',
  4725. 'SS': '105.235.208.0/21',
  4726. 'ST': '197.159.160.0/19',
  4727. 'SV': '168.243.0.0/16',
  4728. 'SX': '190.102.0.0/20',
  4729. 'SY': '5.0.0.0/16',
  4730. 'SZ': '41.84.224.0/19',
  4731. 'TC': '65.255.48.0/20',
  4732. 'TD': '154.68.128.0/19',
  4733. 'TG': '196.168.0.0/14',
  4734. 'TH': '171.96.0.0/13',
  4735. 'TJ': '85.9.128.0/18',
  4736. 'TK': '27.96.24.0/21',
  4737. 'TL': '180.189.160.0/20',
  4738. 'TM': '95.85.96.0/19',
  4739. 'TN': '197.0.0.0/11',
  4740. 'TO': '175.176.144.0/21',
  4741. 'TR': '78.160.0.0/11',
  4742. 'TT': '186.44.0.0/15',
  4743. 'TV': '202.2.96.0/19',
  4744. 'TW': '120.96.0.0/11',
  4745. 'TZ': '156.156.0.0/14',
  4746. 'UA': '37.52.0.0/14',
  4747. 'UG': '102.80.0.0/13',
  4748. 'US': '6.0.0.0/8',
  4749. 'UY': '167.56.0.0/13',
  4750. 'UZ': '84.54.64.0/18',
  4751. 'VA': '212.77.0.0/19',
  4752. 'VC': '207.191.240.0/21',
  4753. 'VE': '186.88.0.0/13',
  4754. 'VG': '66.81.192.0/20',
  4755. 'VI': '146.226.0.0/16',
  4756. 'VN': '14.160.0.0/11',
  4757. 'VU': '202.80.32.0/20',
  4758. 'WF': '117.20.32.0/21',
  4759. 'WS': '202.4.32.0/19',
  4760. 'YE': '134.35.0.0/16',
  4761. 'YT': '41.242.116.0/22',
  4762. 'ZA': '41.0.0.0/11',
  4763. 'ZM': '102.144.0.0/13',
  4764. 'ZW': '102.177.192.0/18',
  4765. }
  4766. @classmethod
  4767. def random_ipv4(cls, code_or_block):
  4768. if len(code_or_block) == 2:
  4769. block = cls._country_ip_map.get(code_or_block.upper())
  4770. if not block:
  4771. return None
  4772. else:
  4773. block = code_or_block
  4774. addr, preflen = block.split('/')
  4775. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  4776. addr_max = addr_min | (0xffffffff >> int(preflen))
  4777. return compat_str(socket.inet_ntoa(
  4778. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  4779. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  4780. def __init__(self, proxies=None):
  4781. # Set default handlers
  4782. for type in ('http', 'https'):
  4783. setattr(self, '%s_open' % type,
  4784. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  4785. meth(r, proxy, type))
  4786. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  4787. def proxy_open(self, req, proxy, type):
  4788. req_proxy = req.headers.get('Ytdl-request-proxy')
  4789. if req_proxy is not None:
  4790. proxy = req_proxy
  4791. del req.headers['Ytdl-request-proxy']
  4792. if proxy == '__noproxy__':
  4793. return None # No Proxy
  4794. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  4795. req.add_header('Ytdl-socks-proxy', proxy)
  4796. # youtube-dl's http/https handlers do wrapping the socket with socks
  4797. return None
  4798. return compat_urllib_request.ProxyHandler.proxy_open(
  4799. self, req, proxy, type)
  4800. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  4801. # released into Public Domain
  4802. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  4803. def long_to_bytes(n, blocksize=0):
  4804. """long_to_bytes(n:long, blocksize:int) : string
  4805. Convert a long integer to a byte string.
  4806. If optional blocksize is given and greater than zero, pad the front of the
  4807. byte string with binary zeros so that the length is a multiple of
  4808. blocksize.
  4809. """
  4810. # after much testing, this algorithm was deemed to be the fastest
  4811. s = b''
  4812. n = int(n)
  4813. while n > 0:
  4814. s = compat_struct_pack('>I', n & 0xffffffff) + s
  4815. n = n >> 32
  4816. # strip off leading zeros
  4817. for i in range(len(s)):
  4818. if s[i] != b'\000'[0]:
  4819. break
  4820. else:
  4821. # only happens when n == 0
  4822. s = b'\000'
  4823. i = 0
  4824. s = s[i:]
  4825. # add back some pad bytes. this could be done more efficiently w.r.t. the
  4826. # de-padding being done above, but sigh...
  4827. if blocksize > 0 and len(s) % blocksize:
  4828. s = (blocksize - len(s) % blocksize) * b'\000' + s
  4829. return s
  4830. def bytes_to_long(s):
  4831. """bytes_to_long(string) : long
  4832. Convert a byte string to a long integer.
  4833. This is (essentially) the inverse of long_to_bytes().
  4834. """
  4835. acc = 0
  4836. length = len(s)
  4837. if length % 4:
  4838. extra = (4 - length % 4)
  4839. s = b'\000' * extra + s
  4840. length = length + extra
  4841. for i in range(0, length, 4):
  4842. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  4843. return acc
  4844. def ohdave_rsa_encrypt(data, exponent, modulus):
  4845. '''
  4846. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  4847. Input:
  4848. data: data to encrypt, bytes-like object
  4849. exponent, modulus: parameter e and N of RSA algorithm, both integer
  4850. Output: hex string of encrypted data
  4851. Limitation: supports one block encryption only
  4852. '''
  4853. payload = int(binascii.hexlify(data[::-1]), 16)
  4854. encrypted = pow(payload, exponent, modulus)
  4855. return '%x' % encrypted
  4856. def pkcs1pad(data, length):
  4857. """
  4858. Padding input data with PKCS#1 scheme
  4859. @param {int[]} data input data
  4860. @param {int} length target length
  4861. @returns {int[]} padded data
  4862. """
  4863. if len(data) > length - 11:
  4864. raise ValueError('Input data too long for PKCS#1 padding')
  4865. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  4866. return [0, 2] + pseudo_random + [0] + data
  4867. def encode_base_n(num, n, table=None):
  4868. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4869. if not table:
  4870. table = FULL_TABLE[:n]
  4871. if n > len(table):
  4872. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  4873. if num == 0:
  4874. return table[0]
  4875. ret = ''
  4876. while num:
  4877. ret = table[num % n] + ret
  4878. num = num // n
  4879. return ret
  4880. def decode_packed_codes(code):
  4881. mobj = re.search(PACKED_CODES_RE, code)
  4882. obfucasted_code, base, count, symbols = mobj.groups()
  4883. base = int(base)
  4884. count = int(count)
  4885. symbols = symbols.split('|')
  4886. symbol_table = {}
  4887. while count:
  4888. count -= 1
  4889. base_n_count = encode_base_n(count, base)
  4890. symbol_table[base_n_count] = symbols[count] or base_n_count
  4891. return re.sub(
  4892. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  4893. obfucasted_code)
  4894. def caesar(s, alphabet, shift):
  4895. if shift == 0:
  4896. return s
  4897. l = len(alphabet)
  4898. return ''.join(
  4899. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  4900. for c in s)
  4901. def rot47(s):
  4902. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  4903. def parse_m3u8_attributes(attrib):
  4904. info = {}
  4905. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  4906. if val.startswith('"'):
  4907. val = val[1:-1]
  4908. info[key] = val
  4909. return info
  4910. def urshift(val, n):
  4911. return val >> n if val >= 0 else (val + 0x100000000) >> n
  4912. # Based on png2str() written by @gdkchan and improved by @yokrysty
  4913. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  4914. def decode_png(png_data):
  4915. # Reference: https://www.w3.org/TR/PNG/
  4916. header = png_data[8:]
  4917. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  4918. raise IOError('Not a valid PNG file.')
  4919. int_map = {1: '>B', 2: '>H', 4: '>I'}
  4920. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  4921. chunks = []
  4922. while header:
  4923. length = unpack_integer(header[:4])
  4924. header = header[4:]
  4925. chunk_type = header[:4]
  4926. header = header[4:]
  4927. chunk_data = header[:length]
  4928. header = header[length:]
  4929. header = header[4:] # Skip CRC
  4930. chunks.append({
  4931. 'type': chunk_type,
  4932. 'length': length,
  4933. 'data': chunk_data
  4934. })
  4935. ihdr = chunks[0]['data']
  4936. width = unpack_integer(ihdr[:4])
  4937. height = unpack_integer(ihdr[4:8])
  4938. idat = b''
  4939. for chunk in chunks:
  4940. if chunk['type'] == b'IDAT':
  4941. idat += chunk['data']
  4942. if not idat:
  4943. raise IOError('Unable to read PNG data.')
  4944. decompressed_data = bytearray(zlib.decompress(idat))
  4945. stride = width * 3
  4946. pixels = []
  4947. def _get_pixel(idx):
  4948. x = idx % stride
  4949. y = idx // stride
  4950. return pixels[y][x]
  4951. for y in range(height):
  4952. basePos = y * (1 + stride)
  4953. filter_type = decompressed_data[basePos]
  4954. current_row = []
  4955. pixels.append(current_row)
  4956. for x in range(stride):
  4957. color = decompressed_data[1 + basePos + x]
  4958. basex = y * stride + x
  4959. left = 0
  4960. up = 0
  4961. if x > 2:
  4962. left = _get_pixel(basex - 3)
  4963. if y > 0:
  4964. up = _get_pixel(basex - stride)
  4965. if filter_type == 1: # Sub
  4966. color = (color + left) & 0xff
  4967. elif filter_type == 2: # Up
  4968. color = (color + up) & 0xff
  4969. elif filter_type == 3: # Average
  4970. color = (color + ((left + up) >> 1)) & 0xff
  4971. elif filter_type == 4: # Paeth
  4972. a = left
  4973. b = up
  4974. c = 0
  4975. if x > 2 and y > 0:
  4976. c = _get_pixel(basex - stride - 3)
  4977. p = a + b - c
  4978. pa = abs(p - a)
  4979. pb = abs(p - b)
  4980. pc = abs(p - c)
  4981. if pa <= pb and pa <= pc:
  4982. color = (color + a) & 0xff
  4983. elif pb <= pc:
  4984. color = (color + b) & 0xff
  4985. else:
  4986. color = (color + c) & 0xff
  4987. current_row.append(color)
  4988. return width, height, pixels
  4989. def write_xattr(path, key, value):
  4990. # This mess below finds the best xattr tool for the job
  4991. try:
  4992. # try the pyxattr module...
  4993. import xattr
  4994. if hasattr(xattr, 'set'): # pyxattr
  4995. # Unicode arguments are not supported in python-pyxattr until
  4996. # version 0.5.0
  4997. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  4998. pyxattr_required_version = '0.5.0'
  4999. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  5000. # TODO: fallback to CLI tools
  5001. raise XAttrUnavailableError(
  5002. 'python-pyxattr is detected but is too old. '
  5003. 'youtube-dl requires %s or above while your version is %s. '
  5004. 'Falling back to other xattr implementations' % (
  5005. pyxattr_required_version, xattr.__version__))
  5006. setxattr = xattr.set
  5007. else: # xattr
  5008. setxattr = xattr.setxattr
  5009. try:
  5010. setxattr(path, key, value)
  5011. except EnvironmentError as e:
  5012. raise XAttrMetadataError(e.errno, e.strerror)
  5013. except ImportError:
  5014. if compat_os_name == 'nt':
  5015. # Write xattrs to NTFS Alternate Data Streams:
  5016. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  5017. assert ':' not in key
  5018. assert os.path.exists(path)
  5019. ads_fn = path + ':' + key
  5020. try:
  5021. with open(ads_fn, 'wb') as f:
  5022. f.write(value)
  5023. except EnvironmentError as e:
  5024. raise XAttrMetadataError(e.errno, e.strerror)
  5025. else:
  5026. user_has_setfattr = check_executable('setfattr', ['--version'])
  5027. user_has_xattr = check_executable('xattr', ['-h'])
  5028. if user_has_setfattr or user_has_xattr:
  5029. value = value.decode('utf-8')
  5030. if user_has_setfattr:
  5031. executable = 'setfattr'
  5032. opts = ['-n', key, '-v', value]
  5033. elif user_has_xattr:
  5034. executable = 'xattr'
  5035. opts = ['-w', key, value]
  5036. cmd = ([encodeFilename(executable, True)]
  5037. + [encodeArgument(o) for o in opts]
  5038. + [encodeFilename(path, True)])
  5039. try:
  5040. p = subprocess.Popen(
  5041. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5042. except EnvironmentError as e:
  5043. raise XAttrMetadataError(e.errno, e.strerror)
  5044. stdout, stderr = p.communicate()
  5045. stderr = stderr.decode('utf-8', 'replace')
  5046. if p.returncode != 0:
  5047. raise XAttrMetadataError(p.returncode, stderr)
  5048. else:
  5049. # On Unix, and can't find pyxattr, setfattr, or xattr.
  5050. if sys.platform.startswith('linux'):
  5051. raise XAttrUnavailableError(
  5052. "Couldn't find a tool to set the xattrs. "
  5053. "Install either the python 'pyxattr' or 'xattr' "
  5054. "modules, or the GNU 'attr' package "
  5055. "(which contains the 'setfattr' tool).")
  5056. else:
  5057. raise XAttrUnavailableError(
  5058. "Couldn't find a tool to set the xattrs. "
  5059. "Install either the python 'xattr' module, "
  5060. "or the 'xattr' binary.")
  5061. def random_birthday(year_field, month_field, day_field):
  5062. start_date = datetime.date(1950, 1, 1)
  5063. end_date = datetime.date(1995, 12, 31)
  5064. offset = random.randint(0, (end_date - start_date).days)
  5065. random_date = start_date + datetime.timedelta(offset)
  5066. return {
  5067. year_field: str(random_date.year),
  5068. month_field: str(random_date.month),
  5069. day_field: str(random_date.day),
  5070. }