UAForge 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ import random
2
+ from typing import List, Optional
3
+ from .database import Database
4
+
5
+ class UserAgentGenerator:
6
+ """
7
+ UserAgentGenerator
8
+ A class for generating realistic user agent strings for different web browsers across various platforms.
9
+ This class retrieves browser version information and device platform data from a database and uses them
10
+ to create authentic-looking user agent strings that can be used for web scraping, testing, or other purposes.
11
+ The generator supports three major browser types:
12
+ - Chrome (including iOS variant CriOS)
13
+ - Firefox (including iOS variant FxiOS)
14
+ - Opera
15
+ Attributes:
16
+ db (Database): Database instance for retrieving browser versions and platform information.
17
+ platform_list (dict): Dictionary mapping platform keys to available systems/versions.
18
+ CHROME_VERS (list): List of available Chrome browser versions.
19
+ OPERA_VERS (list): List of available Opera browser versions.
20
+ FIREFOX_VERS (list): List of available Firefox browser versions.
21
+ Example:
22
+ >>> generator = UserAgentGenerator()
23
+ >>> chrome_agent = generator.create_useragent("Chrome")
24
+ >>> firefox_agent = generator.create_useragent("Firefox")
25
+ >>> agents_list = generator.get_list(10)
26
+ """
27
+ def __init__(self, db_path: str = None):
28
+ self.db = Database(db_path)
29
+ self._initialize_data()
30
+
31
+ def _initialize_data(self):
32
+ """
33
+ Initializes user agent data by retrieving platform and browser version information from the database.
34
+
35
+ This method sets the following instance attributes:
36
+ - platform_list: List of device platforms and versions.
37
+ - CHROME_VERS: Latest Chrome browser version.
38
+ - OPERA_VERS: Latest Opera browser version.
39
+ - FIREFOX_VERS: Latest Firefox browser version.
40
+ """
41
+ self.platform_list = self.db.get_device_version()
42
+ self.CHROME_VERS = self.db.get_chrome_vers()[0]
43
+ self.OPERA_VERS = self.db.get_opera_vers()[0]
44
+ self.FIREFOX_VERS = self.db.get_firefox_vers()[0]
45
+
46
+ def _select_random_platform(self) -> tuple:
47
+ """
48
+ Selects a random platform, system, and version type.
49
+ This method randomly chooses a platform key from the available platforms,
50
+ then selects a random system associated with that platform. It also retrieves
51
+ the available version types from the database and selects a random version type
52
+ corresponding to the chosen platform.
53
+ Returns:
54
+ tuple: A tuple containing:
55
+ - select_key (str): The randomly selected platform key.
56
+ - system_select (str): The randomly selected system for the platform.
57
+ - type_select (str): The randomly selected version type for the platform.
58
+ """
59
+ select_key = random.choice(list(self.platform_list.keys()))
60
+ system_select = random.choice(self.platform_list[select_key])
61
+
62
+ version_types = self.db.get_version_type_connect()
63
+ type_select = random.choice(version_types.get(select_key, [""]))
64
+
65
+ return select_key, system_select, type_select
66
+
67
+ def create_useragent(self, browser_type: str = "Chrome") -> str:
68
+ """
69
+ Generates a user agent string for the specified browser type.
70
+ Args:
71
+ browser_type (str, optional): The type of browser for which to generate the user agent.
72
+ Supported values are "Chrome", "Firefox", and "Opera". Defaults to "Chrome".
73
+ Returns:
74
+ str: A user agent string corresponding to the specified browser type and a randomly selected platform.
75
+ Raises:
76
+ ValueError: If an unsupported browser type is provided.
77
+ """
78
+ select_key, system_select, type_select = self._select_random_platform()
79
+
80
+ if browser_type == "Chrome":
81
+ return self._create_chrome_agent(select_key, system_select, type_select)
82
+ elif browser_type == "Firefox":
83
+ return self._create_firefox_agent(select_key, system_select, type_select)
84
+ elif browser_type == "Opera":
85
+ return self._create_opera_agent(select_key, system_select, type_select)
86
+ else:
87
+ raise ValueError(f"Desteklenmeyen tarayıcı tipi: {browser_type}")
88
+
89
+ def _create_chrome_agent(self, system_select: str, type_select: str) -> str:
90
+ """
91
+ Generates a Chrome-based User-Agent string based on the provided system and type selections.
92
+ Args:
93
+ system_select (str): The system information string (e.g., OS and device type).
94
+ type_select (str): The type information string (e.g., locale or device type).
95
+ Returns:
96
+ str: A formatted User-Agent string for Chrome or Chrome on iOS devices.
97
+ Notes:
98
+ - If the system is identified as an iPhone or iPad, the User-Agent is formatted to mimic Chrome on iOS (CriOS).
99
+ - Otherwise, a standard Chrome User-Agent string is generated.
100
+ """
101
+ Moz = "Mozilla"
102
+ Mozilla_vers = "5.0"
103
+
104
+ if "iPhone" in system_select or "iPad" in system_select:
105
+ if "iPad" in system_select:
106
+ system_select = system_select.strip(";").replace("Intel Mac OS X", "CPU OS") + " like Mac OS X"
107
+ else:
108
+ system_select = system_select.strip(";").replace("Intel Mac OS X", "CPU iPhone OS") + " like Mac OS X"
109
+
110
+ CHROME_VERS_SELECT = str(random.choice(self.CHROME_VERS)).replace("Chrome", "CriOS")
111
+ return f"{Moz}/{Mozilla_vers} ({system_select}; {type_select}) AppleWebKit/605.1.15 (KHTML, like Gecko) {CHROME_VERS_SELECT} Mobile/15E148 Safari/604.1"
112
+ else:
113
+ CHROME_VERS_SELECT = random.choice(self.CHROME_VERS)
114
+ return f"{Moz}/{Mozilla_vers} ({system_select}; {type_select}) AppleWebKit/537.36 (KHTML, like Gecko) {CHROME_VERS_SELECT} Safari/537.36"
115
+
116
+ def _create_firefox_agent(self, system_select: str, type_select: str) -> str:
117
+ """
118
+ Generates a Firefox user agent string based on the provided system and type selections.
119
+ Args:
120
+ system_select (str): The system information to include in the user agent (e.g., "Windows NT 10.0", "iPhone", "iPad").
121
+ type_select (str): The type or locale information to include in the user agent (e.g., "en-US").
122
+ Returns:
123
+ str: A formatted Firefox user agent string tailored to the specified system and type.
124
+ Notes:
125
+ - For iPhone and iPad systems, the user agent is formatted to mimic Firefox on iOS (FxiOS).
126
+ - For other systems, a standard Firefox user agent string is generated.
127
+ - The Firefox version is randomly selected from the self.FIREFOX_VERS list.
128
+ """
129
+ Moz = "Mozilla"
130
+ Mozilla_vers = "5.0"
131
+
132
+ if "iPhone" in system_select or "iPad" in system_select:
133
+ if "iPad" in system_select:
134
+ system_select = system_select.strip(";").replace("Intel Mac OS X", "CPU OS") + " like Mac OS X"
135
+ else:
136
+ system_select = system_select.strip(";").replace("Intel Mac OS X", "CPU iPhone OS") + " like Mac OS X"
137
+
138
+ FIREFOX_VERS_SELECT = str(random.choice(self.FIREFOX_VERS)).replace("Firefox", "FxiOS")
139
+ return f"{Moz}/{Mozilla_vers} ({system_select}; {type_select}) Gecko/20100101 {FIREFOX_VERS_SELECT} Mobile/15E148"
140
+ else:
141
+ FIREFOX_VERS_SELECT = random.choice(self.FIREFOX_VERS)
142
+ return f"{Moz}/{Mozilla_vers} ({system_select}; {type_select}; rv:109.0) Gecko/20100101 {FIREFOX_VERS_SELECT}"
143
+
144
+ def _create_opera_agent(self, system_select: str, type_select: str) -> str:
145
+ """
146
+ Generates an Opera browser User-Agent string based on the provided system and type selections.
147
+ Args:
148
+ system_select (str): The system information string (e.g., "iPhone", "iPad", or other OS descriptors).
149
+ type_select (str): The type information string (e.g., device type or architecture).
150
+ Returns:
151
+ str: A formatted Opera User-Agent string appropriate for the specified system and type.
152
+ Notes:
153
+ - If the system is an iPhone or iPad, the User-Agent string is tailored for iOS devices.
154
+ - Otherwise, a standard Opera User-Agent string is generated.
155
+ - Random Opera and Chrome version numbers are selected from predefined lists.
156
+ """
157
+ Moz = "Mozilla"
158
+ Mozilla_vers = "5.0"
159
+
160
+ if "iPhone" in system_select or "iPad" in system_select:
161
+ if "iPad" in system_select:
162
+ system_select = system_select.strip(";").replace("Intel Mac OS X", "CPU OS") + " like Mac OS X"
163
+ else:
164
+ system_select = system_select.strip(";").replace("Intel Mac OS X", "CPU iPhone OS") + " like Mac OS X"
165
+
166
+ OPERA_VERS_SELECT = random.choice(self.OPERA_VERS)
167
+ CHROME_VERS_SELECT = random.choice(self.CHROME_VERS)
168
+ return f"{Moz}/{Mozilla_vers} ({system_select}; {type_select}) AppleWebKit/537.36 (KHTML, like Gecko) {CHROME_VERS_SELECT} Mobile Safari/537.36 OPR/{OPERA_VERS_SELECT.split('/')[0]}"
169
+ else:
170
+ OPERA_VERS_SELECT = random.choice(self.OPERA_VERS)
171
+ CHROME_VERS_SELECT = random.choice(self.CHROME_VERS)
172
+ return f"{Moz}/{Mozilla_vers} ({system_select}; {type_select}) AppleWebKit/537.36 (KHTML, like Gecko) {CHROME_VERS_SELECT} Safari/537.36 OPR/{OPERA_VERS_SELECT.split('/')[0]}"
173
+
174
+ def get_list(self, count: int) -> List[str]:
175
+ """
176
+ Generate a list of unique user agent strings.
177
+ Args:
178
+ count (int): The number of user agent strings to generate.
179
+ Returns:
180
+ List[str]: A list of unique user agent strings for randomly selected browsers
181
+ (Chrome, Firefox, or Opera).
182
+ Note:
183
+ The method attempts to generate `count` user agents, but the returned list
184
+ may contain fewer items if duplicate user agents are generated, as only
185
+ unique agents are included in the result.
186
+ """
187
+
188
+ user_agent_list = []
189
+ browsers = ["Chrome", "Firefox", "Opera"]
190
+
191
+ for i in range(count):
192
+ try :
193
+ browser_select = random.choice(browsers)
194
+ user_agent = self.create_useragent(browser_select)
195
+
196
+ if user_agent not in user_agent_list:
197
+ user_agent_list.append(user_agent)
198
+ except Exception as e:
199
+ print(f"Error generating user agent: {e}")
200
+
201
+ return user_agent_list
@@ -0,0 +1,152 @@
1
+ from bs4 import BeautifulSoup
2
+ import datetime,random, requests
3
+ from typing import Dict, List, Any
4
+
5
+ class VersionFetcher:
6
+
7
+ def __init__(self):
8
+ self.session = requests.Session()
9
+ self.session.headers.update({
10
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
11
+ })
12
+
13
+ def fetch_chrome_versions(self) -> Dict[str, Any]:
14
+ url = "https://chromedriver.storage.googleapis.com"
15
+ req = self.session.get(url)
16
+ soup = BeautifulSoup(req.content, "xml")
17
+
18
+ key_list = soup.find_all("Key")
19
+ date_list = soup.find_all("LastModified")
20
+
21
+ version_list = []
22
+ version_dicts = {}
23
+
24
+ for ky in range(len(key_list)):
25
+ version = str(key_list[ky].text).split("/")[0]
26
+ date = str(date_list[ky].text).strip()
27
+
28
+ if (version and "RELEASE" not in version and "icons" not in version
29
+ and "index" not in version and version[0].isdigit()):
30
+ try:
31
+ if int(version.split(".")[0]) > 79:
32
+ version_list.append(f"Chrome/{version.strip()}")
33
+ version_dicts[version] = date
34
+ except (ValueError, IndexError):
35
+ continue
36
+
37
+ return {"Version_list": version_list, "Version_dict": version_dicts}
38
+
39
+ def fetch_firefox_versions(self) -> Dict[str, Any]:
40
+ url = "https://www.mozilla.org/en-US/firefox/releases/"
41
+ req = self.session.get(url)
42
+ soup = BeautifulSoup(req.content, "html.parser")
43
+
44
+ version_list = []
45
+ version_dicts = {}
46
+
47
+ release = soup.find("ol", {"class": "c-release-list"})
48
+ if release:
49
+ li_list = release.find_all("li")
50
+
51
+ for li in li_list:
52
+ try:
53
+ strong = li.find("a").text
54
+ if float(strong) > 70.0:
55
+ version_list.append(f"Firefox/{strong}")
56
+ version_dicts[f"Firefox/{strong}"] = datetime.datetime.now()
57
+
58
+ for ol_li in li.find_all("li"):
59
+ version_list.append(f"Firefox/{ol_li.text}")
60
+ version_dicts[f"Firefox/{ol_li.text}"] = datetime.datetime.now()
61
+ except (ValueError, AttributeError):
62
+ continue
63
+
64
+ return {"Version_list": version_list, "Version_dict": version_dicts}
65
+
66
+ def fetch_opera_versions(self) -> Dict[str, Any]:
67
+ url = "https://blogs.opera.com/desktop/changelog-for-"
68
+ session = requests.Session()
69
+ session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304 Safari/537.36'})
70
+ version_list = []
71
+ version_dicts = {}
72
+ for ver_count in [x for x in range(60,99)]:
73
+ req = session.get(url+str(ver_count)+"/")
74
+ soup = BeautifulSoup(req.content,"html.parser")
75
+ content = soup.find("div",{"class":"content"})
76
+ for strong in content.find_all("h4") :
77
+ splt = str(strong.text).split("– 20")
78
+ if len(splt) > 1 :
79
+ version_list.append("OPR/%s"%splt[0].strip())
80
+ version_dicts.update({splt[0].strip():splt[1].strip().split(" ")[0]})
81
+
82
+ return {"Version_list":version_list,"Version_dict":version_dicts}
83
+
84
+ def fetch_android_versions(self) -> Dict[str, Any]:
85
+ url = "https://tr.wikipedia.org/wiki/Android"
86
+ req = self.session.get(url)
87
+ soup = BeautifulSoup(req.content, "html.parser")
88
+
89
+ version_list = []
90
+ version_dicts = {}
91
+ skipped_version = ['1.0', '1.1', '1.5', '1.6', '2.0', '2.1', '2.2', '2.2.3',
92
+ '2.3', '2.3.7', '3.0', '3.2.6', '4.0', '4.0.4', '4.1', '4.3.1']
93
+
94
+ table = soup.find("table", {"class": "wikitable"})
95
+ if table:
96
+ tr_list = table.find("tbody").find_all("tr")
97
+
98
+ for tr in tr_list:
99
+ try:
100
+ tds = tr.find_all("td")
101
+ if tds:
102
+ versions = str(tds[0].text).strip().split("-")
103
+ for version in versions:
104
+ version_clean = version.strip()
105
+ if version_clean and version_clean not in skipped_version:
106
+ android_str = f"Linux;Android {version_clean}"
107
+ version_list.append(android_str)
108
+ version_dicts[android_str] = datetime.datetime.now()
109
+ except (IndexError, AttributeError):
110
+ continue
111
+
112
+ return {"Version_list": version_list, "Version_dict": version_dicts}
113
+
114
+ def fetch_macos_versions(self) -> Dict[str, Any]:
115
+ urls = ["https://en.wikipedia.org/wiki/OS_X_Mountain_Lion","https://en.wikipedia.org/wiki/OS_X_Mavericks","https://en.wikipedia.org/wiki/OS_X_Yosemite",
116
+ "https://en.wikipedia.org/wiki/OS_X_El_Capitan","https://en.wikipedia.org/wiki/MacOS_Sierra","https://en.wikipedia.org/wiki/MacOS_High_Sierra",
117
+ "https://en.wikipedia.org/wiki/MacOS_Mojave","https://en.wikipedia.org/wiki/MacOS_Catalina"]
118
+ urls2 = ["https://en.wikipedia.org/wiki/MacOS_Big_Sur","https://en.wikipedia.org/wiki/MacOS_Monterey","https://en.wikipedia.org/wiki/MacOS_Ventura"]
119
+ session = requests.Session()
120
+ session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304 Safari/537.36'})
121
+ version_list = []
122
+ version_dicts = {}
123
+ devices = ["iPhone","iPad","Macintosh"]
124
+ for url in urls :
125
+ req = session.get(url)
126
+ soup = BeautifulSoup(req.content,"html.parser")
127
+ tr_list = soup.find_all("table",{"class":"wikitable"})[0].find("tbody").find_all("tr")
128
+ for tr in tr_list :
129
+ try :
130
+ if "." in tr.find_all("td")[0].text :
131
+ rdm_chc = random.choice(devices)
132
+ version_list.append("%s; Intel Mac OS X %s"%(rdm_chc,str(tr.find_all("td")[0].text).strip()))
133
+ version_dicts.update({"%s; Intel Mac OS X %s"%(rdm_chc,str(tr.find_all("td")[0].text).strip()):datetime.datetime.now()})
134
+
135
+ except:
136
+ pass
137
+ for url in urls2 :
138
+ req = session.get(url)
139
+ soup = BeautifulSoup(req.content,"html.parser")
140
+ tr_list = soup.find_all("table",{"class":"wikitable"})[1].find("tbody").find_all("tr")
141
+ for tr in tr_list :
142
+ try :
143
+ if "." in str(tr.find("th").text).strip() :
144
+ rdm_chc = random.choice(devices)
145
+ version_list.append("%s; Intel Mac OS X %s"%(rdm_chc,str(tr.find("th").text).strip().split("[")[0]))
146
+ version_dicts.update({"%s; Intel Mac OS X %s"%(rdm_chc,str(tr.find("th").text).strip().split("[")[0]):datetime.datetime.now()})
147
+ except:
148
+ pass
149
+ pop_index = version_list[-1]
150
+ version_list.pop(-1)
151
+ version_dicts.pop(pop_index)
152
+ return {"Version_list":version_list,"Version_dict":version_dicts}