Debian Codegraph @

cloudscraper/user_agent/__init__.py

raw
1 import json
2 import os
3 import random
4 import re
5 import sys
6 import ssl
7
8 from collections import OrderedDict
9
10 # ------------------------------------------------------------------------------- #
11
12
13 class User_Agent():
14
15 # ------------------------------------------------------------------------------- #
16
17 def __init__(self, *args, **kwargs):
18 self.headers = None
19 self.cipherSuite = []
20 self.loadUserAgent(*args, **kwargs)
21
22 # ------------------------------------------------------------------------------- #
23
24 def filterAgents(self, user_agents):
25 filtered = {}
26
27 if self.mobile:
28 if self.platform in user_agents['mobile'] and user_agents['mobile'][self.platform]:
29 filtered.update(user_agents['mobile'][self.platform])
30
31 if self.desktop:
32 if self.platform in user_agents['desktop'] and user_agents['desktop'][self.platform]:
33 filtered.update(user_agents['desktop'][self.platform])
34
35 return filtered
36
37 # ------------------------------------------------------------------------------- #
38
39 def tryMatchCustom(self, user_agents):
40 for device_type in user_agents['user_agents']:
41 for platform in user_agents['user_agents'][device_type]:
42 for browser in user_agents['user_agents'][device_type][platform]:
43 if re.search(re.escape(self.custom), ' '.join(user_agents['user_agents'][device_type][platform][browser])):
44 self.headers = user_agents['headers'][browser]
45 self.headers['User-Agent'] = self.custom
46 self.cipherSuite = user_agents['cipherSuite'][browser]
47 return True
48 return False
49
50 # ------------------------------------------------------------------------------- #
51
52 def loadUserAgent(self, *args, **kwargs):
53 self.browser = kwargs.pop('browser', None)
54
55 self.platforms = ['linux', 'windows', 'darwin', 'android', 'ios']
56 self.browsers = ['chrome', 'firefox']
57
58 if isinstance(self.browser, dict):
59 self.custom = self.browser.get('custom', None)
60 self.platform = self.browser.get('platform', None)
61 self.desktop = self.browser.get('desktop', True)
62 self.mobile = self.browser.get('mobile', True)
63 self.browser = self.browser.get('browser', None)
64 else:
65 self.custom = kwargs.pop('custom', None)
66 self.platform = kwargs.pop('platform', None)
67 self.desktop = kwargs.pop('desktop', True)
68 self.mobile = kwargs.pop('mobile', True)
69
70 if not self.desktop and not self.mobile:
71 sys.tracebacklimit = 0
72 raise RuntimeError("Sorry you can't have mobile and desktop disabled at the same time.")
73
74 with open(os.path.join(os.path.dirname(__file__), 'browsers.json'), 'r') as fp:
75 user_agents = json.load(
76 fp,
77 object_pairs_hook=OrderedDict
78 )
79
80 if self.custom:
81 if not self.tryMatchCustom(user_agents):
82 self.cipherSuite = [
83 ssl._DEFAULT_CIPHERS,
84 '!AES128-SHA',
85 '!ECDHE-RSA-AES256-SHA',
86 ]
87 self.headers = OrderedDict([
88 ('User-Agent', self.custom),
89 ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'),
90 ('Accept-Language', 'en-US,en;q=0.9'),
91 ('Accept-Encoding', 'gzip, deflate, br')
92 ])
93 else:
94 if self.browser and self.browser not in self.browsers:
95 sys.tracebacklimit = 0
96 raise RuntimeError(f'Sorry "{self.browser}" browser is not valid, valid browsers are [{", ".join(self.browsers)}].')
97
98 if not self.platform:
99 self.platform = random.SystemRandom().choice(self.platforms)
100
101 if self.platform not in self.platforms:
102 sys.tracebacklimit = 0
103 raise RuntimeError(f'Sorry the platform "{self.platform}" is not valid, valid platforms are [{", ".join(self.platforms)}]')
104
105 filteredAgents = self.filterAgents(user_agents['user_agents'])
106
107 if not self.browser:
108 # has to be at least one in there...
109 while not filteredAgents.get(self.browser):
110 self.browser = random.SystemRandom().choice(list(filteredAgents.keys()))
111
112 if not filteredAgents[self.browser]:
113 sys.tracebacklimit = 0
114 raise RuntimeError(f'Sorry "{self.browser}" browser was not found with a platform of "{self.platform}".')
115
116 self.cipherSuite = user_agents['cipherSuite'][self.browser]
117 self.headers = user_agents['headers'][self.browser]
118
119 self.headers['User-Agent'] = random.SystemRandom().choice(filteredAgents[self.browser])
120
121 if not kwargs.get('allow_brotli', False) and 'br' in self.headers['Accept-Encoding']:
122 self.headers['Accept-Encoding'] = ','.join([
123 encoding for encoding in self.headers['Accept-Encoding'].split(',') if encoding.strip() != 'br'
124 ]).strip()