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.

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