]> jfr.im git - yt-dlp.git/blob - yt_dlp/utils/_legacy.py
[core] Improve HTTP redirect handling (#7094)
[yt-dlp.git] / yt_dlp / utils / _legacy.py
1 """No longer used and new code should not use. Exists only for API compat."""
2
3 import platform
4 import struct
5 import sys
6 import urllib.parse
7 import zlib
8
9 from ._utils import decode_base_n, preferredencoding
10 from .traversal import traverse_obj
11 from ..dependencies import certifi, websockets
12
13 has_certifi = bool(certifi)
14 has_websockets = bool(websockets)
15
16
17 def load_plugins(name, suffix, namespace):
18 from ..plugins import load_plugins
19 ret = load_plugins(name, suffix)
20 namespace.update(ret)
21 return ret
22
23
24 def traverse_dict(dictn, keys, casesense=True):
25 return traverse_obj(dictn, keys, casesense=casesense, is_user_input=True, traverse_string=True)
26
27
28 def decode_base(value, digits):
29 return decode_base_n(value, table=digits)
30
31
32 def platform_name():
33 """ Returns the platform name as a str """
34 return platform.platform()
35
36
37 def get_subprocess_encoding():
38 if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
39 # For subprocess calls, encode with locale encoding
40 # Refer to http://stackoverflow.com/a/9951851/35070
41 encoding = preferredencoding()
42 else:
43 encoding = sys.getfilesystemencoding()
44 if encoding is None:
45 encoding = 'utf-8'
46 return encoding
47
48
49 # UNUSED
50 # Based on png2str() written by @gdkchan and improved by @yokrysty
51 # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
52 def decode_png(png_data):
53 # Reference: https://www.w3.org/TR/PNG/
54 header = png_data[8:]
55
56 if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
57 raise OSError('Not a valid PNG file.')
58
59 int_map = {1: '>B', 2: '>H', 4: '>I'}
60 unpack_integer = lambda x: struct.unpack(int_map[len(x)], x)[0]
61
62 chunks = []
63
64 while header:
65 length = unpack_integer(header[:4])
66 header = header[4:]
67
68 chunk_type = header[:4]
69 header = header[4:]
70
71 chunk_data = header[:length]
72 header = header[length:]
73
74 header = header[4:] # Skip CRC
75
76 chunks.append({
77 'type': chunk_type,
78 'length': length,
79 'data': chunk_data
80 })
81
82 ihdr = chunks[0]['data']
83
84 width = unpack_integer(ihdr[:4])
85 height = unpack_integer(ihdr[4:8])
86
87 idat = b''
88
89 for chunk in chunks:
90 if chunk['type'] == b'IDAT':
91 idat += chunk['data']
92
93 if not idat:
94 raise OSError('Unable to read PNG data.')
95
96 decompressed_data = bytearray(zlib.decompress(idat))
97
98 stride = width * 3
99 pixels = []
100
101 def _get_pixel(idx):
102 x = idx % stride
103 y = idx // stride
104 return pixels[y][x]
105
106 for y in range(height):
107 basePos = y * (1 + stride)
108 filter_type = decompressed_data[basePos]
109
110 current_row = []
111
112 pixels.append(current_row)
113
114 for x in range(stride):
115 color = decompressed_data[1 + basePos + x]
116 basex = y * stride + x
117 left = 0
118 up = 0
119
120 if x > 2:
121 left = _get_pixel(basex - 3)
122 if y > 0:
123 up = _get_pixel(basex - stride)
124
125 if filter_type == 1: # Sub
126 color = (color + left) & 0xff
127 elif filter_type == 2: # Up
128 color = (color + up) & 0xff
129 elif filter_type == 3: # Average
130 color = (color + ((left + up) >> 1)) & 0xff
131 elif filter_type == 4: # Paeth
132 a = left
133 b = up
134 c = 0
135
136 if x > 2 and y > 0:
137 c = _get_pixel(basex - stride - 3)
138
139 p = a + b - c
140
141 pa = abs(p - a)
142 pb = abs(p - b)
143 pc = abs(p - c)
144
145 if pa <= pb and pa <= pc:
146 color = (color + a) & 0xff
147 elif pb <= pc:
148 color = (color + b) & 0xff
149 else:
150 color = (color + c) & 0xff
151
152 current_row.append(color)
153
154 return width, height, pixels
155
156
157 def register_socks_protocols():
158 # "Register" SOCKS protocols
159 # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
160 # URLs with protocols not in urlparse.uses_netloc are not handled correctly
161 for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
162 if scheme not in urllib.parse.uses_netloc:
163 urllib.parse.uses_netloc.append(scheme)
164
165
166 def handle_youtubedl_headers(headers):
167 filtered_headers = headers
168
169 if 'Youtubedl-no-compression' in filtered_headers:
170 filtered_headers = {k: v for k, v in filtered_headers.items() if k.lower() != 'accept-encoding'}
171 del filtered_headers['Youtubedl-no-compression']
172
173 return filtered_headers