pyinproxy 0.1.1__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.

Potentially problematic release.


This version of pyinproxy might be problematic. Click here for more details.

inproxy/main.py ADDED
@@ -0,0 +1,1406 @@
1
+ import ast
2
+ import base64
3
+ import json
4
+ import operator
5
+ import re
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ from copy import deepcopy
8
+ from dataclasses import asdict, dataclass
9
+ from io import StringIO
10
+ from threading import Event, Lock
11
+ from urllib.parse import urlsplit
12
+
13
+ import pandas as pd
14
+ from curl_cffi import requests
15
+ from fake_useragent import UserAgent
16
+ from lxml import html
17
+
18
+ try:
19
+ from config import PROXY_CONFIG
20
+ from exceptions import InvalidDataTypeException, NoProxyFoundException
21
+ except ImportError:
22
+ from .config import PROXY_CONFIG
23
+ from .exceptions import InvalidDataTypeException
24
+
25
+ ua = UserAgent()
26
+
27
+
28
+ @dataclass
29
+ class Proxy:
30
+ ip: str
31
+ port: int | None = None
32
+ protocol: str = "http"
33
+ country: str | None = None
34
+ country_code: str | None = None
35
+ state: str | None = None
36
+ state_code: str | None = None
37
+ city: str | None = None
38
+ region: str | None = None
39
+ continent: str | None = None
40
+ timezone: str | None = None
41
+ isp: str | None = None
42
+ organization: str | None = None
43
+ asn: int | None = None
44
+ anonymity: str | None = None
45
+ latency: float | None = None
46
+ source: str | None = None
47
+ continent_code: str | None = None
48
+ pincode: str | None = None
49
+ google: bool | None = None
50
+
51
+ @property
52
+ def proxy(self):
53
+ protocol = (self.protocol or "http").lower()
54
+ ip = str(self.ip).strip()
55
+
56
+ if ":" in ip and not ip.startswith("["):
57
+ ip = f"[{ip}]"
58
+
59
+ if self.port is None:
60
+ return f"{protocol}://{ip}"
61
+
62
+ return f"{protocol}://{ip}:{self.port}"
63
+
64
+ def __str__(self):
65
+ return self.proxy
66
+
67
+ def __repr__(self):
68
+ return self.proxy
69
+
70
+ def to_dict(self):
71
+ data = asdict(self)
72
+ data["proxy"] = self.proxy
73
+ return data
74
+
75
+
76
+ class InProxy:
77
+ _OPERATORS = {
78
+ ast.Add: operator.add,
79
+ ast.Sub: operator.sub,
80
+ ast.Mult: operator.mul,
81
+ ast.Div: operator.truediv,
82
+ ast.FloorDiv: operator.floordiv,
83
+ ast.Mod: operator.mod,
84
+ ast.Pow: operator.pow,
85
+ ast.BitXor: operator.xor,
86
+ ast.LShift: operator.lshift,
87
+ ast.RShift: operator.rshift,
88
+ ast.BitOr: operator.or_,
89
+ ast.BitAnd: operator.and_,
90
+ }
91
+
92
+ _UNARY_OPERATORS = {
93
+ ast.UAdd: operator.pos,
94
+ ast.USub: operator.neg,
95
+ ast.Invert: operator.invert,
96
+ }
97
+
98
+ def __init__(self, source_workers=20, source_timeout=3):
99
+ self._proxy_config = deepcopy(PROXY_CONFIG)
100
+ self._source_workers = source_workers
101
+ self.source_timeout = source_timeout
102
+ self.output = {}
103
+ self.output_count = 0
104
+ self.set_lock = Lock()
105
+ self.count_lock = Lock()
106
+ self.stop_event = Event()
107
+ self.count = 0
108
+ self.filters = {}
109
+
110
+ def _normalize_sites(self, sites):
111
+ if isinstance(sites, str):
112
+ return [site.lower().strip() for site in sites.split(",") if site.strip()]
113
+
114
+ if isinstance(sites, list):
115
+ return [site.lower().strip() for site in sites]
116
+
117
+ return list(self._proxy_config.keys())
118
+
119
+ def _validate_sites(self, sites):
120
+ unknown = [site for site in sites if site not in self._proxy_config]
121
+
122
+ if unknown:
123
+ raise InvalidDataTypeException(
124
+ f"Unknown sources: {unknown}\n"
125
+ f"Available sources: {list(self._proxy_config.keys())}"
126
+ )
127
+
128
+ def make_request(
129
+ self,
130
+ session,
131
+ method,
132
+ url,
133
+ headers=None,
134
+ params=None,
135
+ payload=None,
136
+ proxies=None,
137
+ timeout=None,
138
+ ):
139
+ try:
140
+ kwargs = {
141
+ "method": method,
142
+ "url": url,
143
+ "headers": headers or {},
144
+ "params": params or {},
145
+ "timeout": timeout,
146
+ "impersonate": "chrome",
147
+ }
148
+
149
+ if proxies:
150
+ kwargs["proxies"] = proxies
151
+
152
+ if payload is not None:
153
+ kwargs["json"] = payload
154
+
155
+ return session.request(**kwargs)
156
+
157
+ except KeyboardInterrupt:
158
+ raise
159
+
160
+ except requests.RequestsError:
161
+ return None
162
+
163
+ def fetch_data(self, session, url, site_config):
164
+ method = site_config.get("METHOD", "GET").upper()
165
+ headers = deepcopy(site_config.get("HEADERS", {}))
166
+ params = deepcopy(site_config.get("PARAMS", {}))
167
+ payload = deepcopy(site_config.get("PAYLOAD"))
168
+ timeout = deepcopy(site_config.get("TIMEOUT", self.source_timeout))
169
+
170
+ if not any(key.lower() == "user-agent" for key in headers):
171
+ headers["User-Agent"] = ua.chrome
172
+
173
+ response = self.make_request(
174
+ session=session,
175
+ method=method,
176
+ url=url,
177
+ headers=headers,
178
+ params=params,
179
+ payload=payload,
180
+ timeout=timeout,
181
+ )
182
+
183
+ if response is None or not response.ok:
184
+ return None
185
+
186
+ encoding = site_config.get("ENCODING")
187
+
188
+ if encoding:
189
+ try:
190
+ return response.content.decode(encoding, errors="replace")
191
+ except (LookupError, UnicodeDecodeError):
192
+ pass
193
+
194
+ return response.text
195
+
196
+ def extract_path(self, data, path):
197
+ if path is None or path == "":
198
+ return data
199
+
200
+ if isinstance(path, dict):
201
+ return self.extract_field(data, path)
202
+
203
+ if isinstance(path, (list, tuple)):
204
+ path = ",".join(map(str, path))
205
+
206
+ if not isinstance(path, str):
207
+ return None
208
+
209
+ for key in path.split(","):
210
+ key = key.strip()
211
+
212
+ try:
213
+ if isinstance(data, dict):
214
+ if key in data:
215
+ data = data[key]
216
+ elif key.isdigit() and int(key) in data:
217
+ data = data[int(key)]
218
+ else:
219
+ return None
220
+
221
+ elif isinstance(data, (list, tuple)):
222
+ if not key.isdigit():
223
+ return None
224
+
225
+ data = data[int(key)]
226
+
227
+ else:
228
+ return None
229
+
230
+ except (KeyError, IndexError, ValueError, TypeError):
231
+ return None
232
+
233
+ return data
234
+
235
+ def _xpath_value(self, node, xpath, index=0, text=False):
236
+ if not xpath:
237
+ return None
238
+
239
+ try:
240
+ values = node.xpath(xpath)
241
+
242
+ if not isinstance(values, list):
243
+ values = [values]
244
+
245
+ if not 0 <= index < len(values):
246
+ return None
247
+
248
+ value = values[index]
249
+
250
+ if isinstance(value, bytes):
251
+ return value.decode(errors="replace").strip()
252
+
253
+ if isinstance(value, str):
254
+ return value.strip()
255
+
256
+ if hasattr(value, "text_content"):
257
+ return value.text_content().strip()
258
+
259
+ if text:
260
+ return str(value).strip()
261
+
262
+ return value
263
+
264
+ except (ValueError, TypeError, IndexError):
265
+ return None
266
+
267
+ def _decode_value(self, value, encoding):
268
+ if value is None:
269
+ return None
270
+
271
+ if not isinstance(value, str):
272
+ return value
273
+
274
+ encoding = str(encoding).upper()
275
+
276
+ if encoding == "BASE64":
277
+ try:
278
+ padded = value.strip()
279
+ padded += "=" * (-len(padded) % 4)
280
+ decoded = base64.b64decode(padded).decode("utf-8", errors="replace")
281
+ return decoded.strip()
282
+ except Exception:
283
+ return value
284
+
285
+ return value
286
+
287
+ def _safe_eval(self, expression, variables=None):
288
+ variables = variables or {}
289
+
290
+ if isinstance(expression, (int, float)):
291
+ return expression
292
+
293
+ if not isinstance(expression, str):
294
+ raise InvalidDataTypeException("Invalid expression")
295
+
296
+ tree = ast.parse(expression.strip(), mode="eval")
297
+
298
+ def evaluate(node):
299
+ if isinstance(node, ast.Expression):
300
+ return evaluate(node.body)
301
+
302
+ if isinstance(node, ast.Constant):
303
+ if isinstance(node.value, (int, float)):
304
+ return node.value
305
+ raise InvalidDataTypeException("Invalid expression value")
306
+
307
+ if isinstance(node, ast.Name):
308
+ if node.id in variables and isinstance(
309
+ variables[node.id], (int, float)
310
+ ):
311
+ return variables[node.id]
312
+
313
+ raise InvalidDataTypeException(
314
+ f"Unknown expression variable: {node.id}"
315
+ )
316
+
317
+ if isinstance(node, ast.BinOp):
318
+ operation = self._OPERATORS.get(type(node.op))
319
+
320
+ if operation is None:
321
+ raise InvalidDataTypeException("Unsupported operator")
322
+
323
+ left = evaluate(node.left)
324
+ right = evaluate(node.right)
325
+
326
+ if isinstance(node.op, ast.Pow) and abs(right) > 10:
327
+ raise InvalidDataTypeException("Exponent too large")
328
+
329
+ return operation(left, right)
330
+
331
+ if isinstance(node, ast.UnaryOp):
332
+ operation = self._UNARY_OPERATORS.get(type(node.op))
333
+
334
+ if operation is None:
335
+ raise InvalidDataTypeException("Unsupported unary operator")
336
+
337
+ return operation(evaluate(node.operand))
338
+
339
+ raise InvalidDataTypeException("Unsupported expression")
340
+
341
+ result = evaluate(tree)
342
+
343
+ if not isinstance(result, (int, float)):
344
+ raise InvalidDataTypeException("Invalid expression result")
345
+
346
+ return result
347
+
348
+ def _extract_regex(self, value, config):
349
+ if value is None:
350
+ return None
351
+
352
+ if not isinstance(value, str):
353
+ value = str(value)
354
+
355
+ pattern = config.get("PATTERN")
356
+
357
+ if not pattern:
358
+ return None
359
+
360
+ match = re.search(pattern, value, re.DOTALL)
361
+
362
+ if not match:
363
+ return None
364
+
365
+ group = config.get("GROUP", 1)
366
+
367
+ try:
368
+ return match.group(group)
369
+ except (IndexError, KeyError):
370
+ return None
371
+
372
+ def _get_source_value(self, data, config):
373
+ if not isinstance(config, dict):
374
+ return self.extract_path(data, config)
375
+
376
+ source = config.get("SOURCE")
377
+
378
+ if source is None:
379
+ if "XPATH" in config:
380
+ return self._xpath_value(
381
+ data,
382
+ config.get("XPATH"),
383
+ config.get("INDEX", 0),
384
+ config.get("TEXT") == "YES",
385
+ )
386
+
387
+ return self.extract_path(data, config)
388
+
389
+ source_type = str(source.get("TYPE", "")).upper()
390
+
391
+ if source_type == "KEY":
392
+ value = self.extract_path(data, source.get("KEY"))
393
+
394
+ elif source_type == "COLUMN":
395
+ index = source.get("INDEX", 0)
396
+
397
+ try:
398
+ if hasattr(data, "iloc"):
399
+ value = data.iloc[index]
400
+ elif isinstance(data, dict):
401
+ value = list(data.values())[index]
402
+ else:
403
+ value = data[index]
404
+ except (IndexError, KeyError, TypeError):
405
+ value = None
406
+
407
+ elif source_type == "XPATH":
408
+ value = self._xpath_value(
409
+ data, source.get("XPATH"), source.get("INDEX", 0), True
410
+ )
411
+
412
+ else:
413
+ value = None
414
+
415
+ if source.get("RAW") != "YES" and isinstance(value, str):
416
+ value = value.strip()
417
+
418
+ return value
419
+
420
+ def _transform_value(self, value, field_config, site_config=None):
421
+ if value is None:
422
+ return None
423
+
424
+ decode = field_config.get("DECODE")
425
+
426
+ if decode:
427
+ value = self._decode_value(value, decode)
428
+
429
+ extract = field_config.get("EXTRACT")
430
+
431
+ if extract:
432
+ extract_type = str(extract.get("TYPE", "")).upper()
433
+
434
+ if extract_type == "REGEX":
435
+ value = self._extract_regex(value, extract)
436
+
437
+ transform = field_config.get("TRANSFORM")
438
+
439
+ if transform and value is not None:
440
+ transform_type = str(transform.get("TYPE", "")).upper()
441
+
442
+ if transform_type == "EVAL_EXPRESSION":
443
+ separator = transform.get("SEP")
444
+ variables = (site_config or {}).get("SCRIPT_VARS", {})
445
+
446
+ if isinstance(value, str):
447
+ value = value.strip()
448
+
449
+ if separator and separator in value:
450
+ value = value.split(separator)[-1].strip()
451
+
452
+ expressions = re.findall(r"\(([^()]*)\)", value)
453
+
454
+ if expressions:
455
+ value = "".join(
456
+ str(self._safe_eval(expression, variables))
457
+ for expression in expressions
458
+ )
459
+ else:
460
+ value = self._safe_eval(value, variables)
461
+ else:
462
+ value = self._safe_eval(value, variables)
463
+
464
+ return value
465
+
466
+ def extract_field(self, data, field_config, site_config=None):
467
+ if not isinstance(field_config, dict):
468
+ return self.extract_path(data, field_config)
469
+
470
+ value = self._get_source_value(data, field_config)
471
+
472
+ if value is None:
473
+ return None
474
+
475
+ return self._transform_value(value, field_config, site_config)
476
+
477
+ def _parse_script(self, data, script_config, site_config=None):
478
+ if not isinstance(data, str):
479
+ return None
480
+
481
+ pattern = script_config.get("REGEX")
482
+ value = data
483
+
484
+ if pattern:
485
+ match = re.search(pattern, data, re.DOTALL)
486
+
487
+ if match:
488
+ group = script_config.get("GROUP", 1)
489
+
490
+ try:
491
+ value = match.group(group)
492
+ except (IndexError, KeyError):
493
+ value = match.group(0)
494
+
495
+ script_type = str(script_config.get("TYPE", "")).upper()
496
+
497
+ if script_type == "JSON":
498
+ candidates = [value, value.strip().rstrip(";")]
499
+
500
+ for candidate in candidates:
501
+ try:
502
+ return json.loads(candidate)
503
+ except (json.JSONDecodeError, TypeError):
504
+ continue
505
+
506
+ return None
507
+
508
+ variables = {}
509
+
510
+ assignment_pattern = re.compile(
511
+ r"(?:\b(?:var|let|const)\s+)?([A-Za-z_$][\w$]*)\s*=\s*([^;]+);"
512
+ )
513
+
514
+ assignments = assignment_pattern.findall(data)
515
+ pending = list(assignments)
516
+
517
+ for _ in range(len(pending) + 1):
518
+ unresolved = []
519
+ changed = False
520
+
521
+ for name, expression in pending:
522
+ expression = expression.strip()
523
+ expression = re.sub(
524
+ r"\bparseInt\s*\(\s*([^()]+)\s*\)", r"(\1)", expression
525
+ )
526
+
527
+ try:
528
+ variables[name] = self._safe_eval(expression, variables)
529
+ changed = True
530
+
531
+ except (
532
+ SyntaxError,
533
+ ValueError,
534
+ TypeError,
535
+ InvalidDataTypeException,
536
+ ZeroDivisionError,
537
+ ):
538
+ unresolved.append((name, expression))
539
+
540
+ pending = unresolved
541
+
542
+ if not pending or not changed:
543
+ break
544
+
545
+ if site_config is not None:
546
+ site_config["SCRIPT_VARS"] = variables
547
+
548
+ return value
549
+
550
+ def _decode_indexed_json(self, data):
551
+ if not isinstance(data, list) or len(data) < 3:
552
+ return data
553
+
554
+ records = []
555
+
556
+ for item in data:
557
+ if not isinstance(item, dict):
558
+ continue
559
+
560
+ record = {}
561
+
562
+ for key, index in item.items():
563
+ if (
564
+ isinstance(index, int)
565
+ and not isinstance(index, bool)
566
+ and 0 <= index < len(data)
567
+ ):
568
+ record[key] = data[index]
569
+
570
+ if "ip" in record and "port" in record:
571
+ records.append(record)
572
+
573
+ return records
574
+
575
+ def _parse_json(self, site_config):
576
+ data = site_config.get("DATA", "")
577
+
578
+ try:
579
+ formatted = json.loads(data)
580
+ except (json.JSONDecodeError, TypeError):
581
+ formatted = {}
582
+
583
+ rule = site_config.get("RULE_JSON", {})
584
+
585
+ if rule.get("INDEXED") == "YES":
586
+ formatted = self._decode_indexed_json(formatted)
587
+
588
+ site_config["FORMATTED_DATA"] = formatted
589
+
590
+ nested_html = rule.get("RULE_HTML")
591
+
592
+ if nested_html:
593
+ html_data = self.extract_path(formatted, rule.get("PARENT"))
594
+
595
+ if isinstance(html_data, str):
596
+ nested_config = {
597
+ "DATA": html_data,
598
+ "RULE_HTML": nested_html,
599
+ "SOURCE": site_config.get("SOURCE"),
600
+ }
601
+
602
+ self._parse_html(nested_config)
603
+
604
+ site_config["FORMATTED_DATA"] = nested_config.get("FORMATTED_DATA", [])
605
+
606
+ def _parse_html(self, site_config):
607
+ data = site_config.get("DATA", "")
608
+ rule = site_config.get("RULE_HTML", {})
609
+
610
+ if not isinstance(data, str) or not data.strip():
611
+ site_config["FORMATTED_DATA"] = []
612
+ return
613
+
614
+ script_config = rule.get("SCRIPT")
615
+
616
+ if script_config:
617
+ script_data = self._parse_script(data, script_config, site_config)
618
+
619
+ if str(script_config.get("TYPE", "")).upper() == "JSON":
620
+ site_config["FORMATTED_DATA"] = (
621
+ script_data if isinstance(script_data, list) else []
622
+ )
623
+ return
624
+
625
+ if rule.get("REGEX"):
626
+ try:
627
+ rows = re.findall(rule["REGEX"], data, re.DOTALL)
628
+ result = []
629
+
630
+ for row in rows:
631
+ if isinstance(row, tuple):
632
+ row = "".join(str(value) for value in row)
633
+
634
+ item = {}
635
+
636
+ for key, field_config in rule.get("FIELD_KEYS", {}).items():
637
+ if isinstance(field_config, dict):
638
+ item[key] = self._transform_value(
639
+ row,
640
+ field_config,
641
+ site_config,
642
+ )
643
+ else:
644
+ item[key] = self._extract_regex(
645
+ row,
646
+ {"PATTERN": field_config},
647
+ )
648
+
649
+ result.append(item)
650
+
651
+ site_config["FORMATTED_DATA"] = result
652
+
653
+ except (re.error, TypeError, AttributeError):
654
+ site_config["FORMATTED_DATA"] = []
655
+
656
+ return
657
+
658
+ if rule.get("PANDAS") == "YES":
659
+ self._parse_html_pandas(site_config)
660
+ return
661
+
662
+ xpath = rule.get("XPATH")
663
+
664
+ if not xpath:
665
+ site_config["FORMATTED_DATA"] = []
666
+ return
667
+
668
+ try:
669
+ tree = html.fromstring(data)
670
+ rows = tree.xpath(xpath)
671
+ result = []
672
+
673
+ for row in rows:
674
+ item = {}
675
+
676
+ for key, field_config in rule.get("FIELD_KEYS", {}).items():
677
+ item[key] = self.extract_field(
678
+ row,
679
+ field_config,
680
+ site_config,
681
+ )
682
+
683
+ result.append(item)
684
+
685
+ site_config["FORMATTED_DATA"] = result
686
+
687
+ except (ValueError, TypeError, KeyError) as e:
688
+ site_config["FORMATTED_DATA"] = []
689
+ print(f"HTML parsing failed: {e}")
690
+
691
+ def _parse_html_pandas(self, site_config):
692
+ data = site_config.get("DATA", "")
693
+ rule = site_config.get("RULE_HTML", {})
694
+ table_index = rule.get("INDEX", 0)
695
+
696
+ try:
697
+ tables = pd.read_html(StringIO(data))
698
+
699
+ if not 0 <= table_index < len(tables):
700
+ site_config["FORMATTED_DATA"] = []
701
+ return
702
+
703
+ table = tables[table_index]
704
+ table.columns = [str(column).strip() for column in table.columns]
705
+
706
+ records = table.to_dict(orient="records")
707
+ data_start = int(rule.get("DATA_START", 0) or 0)
708
+ records = records[max(data_start, 0) :]
709
+
710
+ site_config["FORMATTED_DATA"] = records
711
+
712
+ except (ValueError, TypeError, ImportError, IndexError):
713
+ site_config["FORMATTED_DATA"] = []
714
+
715
+ def _parse_txt(self, site_config):
716
+ data = site_config.get("DATA", "")
717
+ rule = site_config.get("RULE_TXT", {})
718
+
719
+ if not isinstance(data, str):
720
+ site_config["FORMATTED_DATA"] = []
721
+ return
722
+
723
+ separator = rule.get("SEP", rule.get("SEPARATOR", "\n"))
724
+
725
+ if not separator:
726
+ separator = "\n"
727
+
728
+ site_config["FORMATTED_DATA"] = [
729
+ item.strip() for item in data.split(separator) if item.strip()
730
+ ]
731
+
732
+ def process_rules(self, site_config):
733
+ for key in list(site_config):
734
+ if not key.startswith("RULE_"):
735
+ continue
736
+
737
+ rule_type = key[5:]
738
+
739
+ if rule_type == "JSON":
740
+ self._parse_json(site_config)
741
+
742
+ elif rule_type == "HTML":
743
+ self._parse_html(site_config)
744
+
745
+ elif rule_type == "TXT":
746
+ self._parse_txt(site_config)
747
+
748
+ return site_config
749
+
750
+ def _normalize_proxy_url(self, value):
751
+ if not isinstance(value, str):
752
+ return None
753
+
754
+ value = value.strip()
755
+
756
+ if not value or "://" not in value:
757
+ return None
758
+
759
+ try:
760
+ parsed = urlsplit(value)
761
+
762
+ if not parsed.hostname:
763
+ return None
764
+
765
+ protocol = parsed.scheme.lower()
766
+
767
+ if protocol not in (
768
+ "http",
769
+ "https",
770
+ "socks4",
771
+ "socks5",
772
+ "socks4a",
773
+ "socks5h",
774
+ ):
775
+ return None
776
+
777
+ return {
778
+ "ip": parsed.hostname,
779
+ "port": parsed.port,
780
+ "protocol": protocol,
781
+ }
782
+
783
+ except ValueError:
784
+ return None
785
+
786
+ def _normalize_proxy_address(self, value):
787
+ if not isinstance(value, str):
788
+ return None
789
+
790
+ value = value.strip()
791
+
792
+ if not value:
793
+ return None
794
+
795
+ full_url = self._normalize_proxy_url(value)
796
+
797
+ if full_url:
798
+ return full_url
799
+
800
+ match = re.match(
801
+ r"^(?P<ip>\[[^\]]+\]|[^:\s]+):(?P<port>\d+)$",
802
+ value,
803
+ )
804
+
805
+ if not match:
806
+ return None
807
+
808
+ ip = match.group("ip").strip("[]")
809
+ port = int(match.group("port"))
810
+
811
+ if not 1 <= port <= 65535:
812
+ return None
813
+
814
+ return {"ip": ip, "port": port}
815
+
816
+ def create_ip_object(self, ip_data, extraction_keys, site_config=None):
817
+ if not isinstance(ip_data, dict):
818
+ raise InvalidDataTypeException("Invalid proxy data")
819
+
820
+ field_keys = extraction_keys.get("FIELD_KEYS", extraction_keys)
821
+ field_keys = {
822
+ field: config
823
+ for field, config in field_keys.items()
824
+ if field in Proxy.__dataclass_fields__
825
+ }
826
+
827
+ list_path = None
828
+
829
+ for field_config in field_keys.values():
830
+ if not isinstance(field_config, str):
831
+ continue
832
+
833
+ keys = [key.strip() for key in field_config.split(",") if key.strip()]
834
+ current = ip_data
835
+
836
+ for index, key in enumerate(keys[:-1]):
837
+ if isinstance(current, dict):
838
+ current = current.get(key)
839
+ elif isinstance(current, (list, tuple)):
840
+ break
841
+ else:
842
+ break
843
+
844
+ if isinstance(current, (list, tuple)):
845
+ list_path = ",".join(keys[:index + 1])
846
+ break
847
+
848
+ if list_path:
849
+ break
850
+
851
+ records = self.extract_path(ip_data, list_path) if list_path else [ip_data]
852
+
853
+ if isinstance(records, dict):
854
+ records = [records]
855
+
856
+ if not isinstance(records, (list, tuple)):
857
+ records = [ip_data]
858
+
859
+ proxies = []
860
+
861
+ for record in records:
862
+ if not isinstance(record, dict):
863
+ continue
864
+
865
+ proxy_data = {}
866
+
867
+ for field, field_config in field_keys.items():
868
+ if isinstance(field_config, str) and list_path:
869
+ prefix = list_path + ","
870
+
871
+ if field_config.startswith(prefix):
872
+ field_config = field_config[len(prefix):]
873
+ source_data = record
874
+ else:
875
+ source_data = ip_data
876
+ else:
877
+ source_data = record if not list_path else ip_data
878
+
879
+ value = self.extract_field(source_data, field_config, site_config)
880
+
881
+ if value is not None and value != "":
882
+ proxy_data[field] = value
883
+
884
+ if not proxy_data.get("ip"):
885
+ continue
886
+
887
+ proxy_value = str(proxy_data["ip"]).strip()
888
+ normalized = self._normalize_proxy_address(proxy_value)
889
+
890
+ if normalized:
891
+ proxy_data["ip"] = normalized["ip"]
892
+
893
+ if normalized.get("port") is not None:
894
+ proxy_data["port"] = normalized["port"]
895
+
896
+ if normalized.get("protocol"):
897
+ proxy_data["protocol"] = normalized["protocol"]
898
+ else:
899
+ proxy_data["ip"] = proxy_value.strip("[]")
900
+
901
+ if proxy_data.get("port") is not None:
902
+ proxy_data["port"] = int(proxy_data["port"])
903
+
904
+ if not 1 <= proxy_data["port"] <= 65535:
905
+ continue
906
+
907
+ if proxy_data.get("asn") is not None:
908
+ proxy_data["asn"] = int(
909
+ re.sub(
910
+ r"^AS",
911
+ "",
912
+ str(proxy_data["asn"]).strip(),
913
+ flags=re.IGNORECASE,
914
+ )
915
+ )
916
+
917
+ if proxy_data.get("latency") is not None:
918
+ proxy_data["latency"] = float(proxy_data["latency"])
919
+
920
+ if "protocol" in proxy_data:
921
+ protocol = proxy_data["protocol"]
922
+
923
+ if isinstance(protocol, (list, tuple)):
924
+ protocol = protocol[0] if protocol else None
925
+
926
+ protocol = str(protocol).strip().lower() if protocol is not None else None
927
+
928
+ if protocol not in {
929
+ "http",
930
+ "https",
931
+ "socks4",
932
+ "socks5",
933
+ "socks4a",
934
+ "socks5h",
935
+ }:
936
+ proxy_data.pop("protocol", None)
937
+ else:
938
+ proxy_data["protocol"] = protocol
939
+
940
+ try:
941
+ proxies.append(Proxy(**proxy_data))
942
+ except (TypeError, ValueError):
943
+ continue
944
+
945
+ if not proxies:
946
+ raise InvalidDataTypeException(f"Proxy IP is missing. Input: {ip_data}")
947
+
948
+ for proxy in proxies[1:]:
949
+ self._collect_proxy(proxy)
950
+
951
+ return proxies[0]
952
+
953
+ def _collect_proxy(self, proxy):
954
+ if self.stop_event.is_set():
955
+ return False
956
+
957
+ if not self._matches_filters(proxy):
958
+ return False
959
+
960
+ with self.set_lock:
961
+ if self.stop_event.is_set():
962
+ return False
963
+
964
+ if proxy.proxy in self.output:
965
+ return False
966
+
967
+ if self.output_count >= self.count:
968
+ self.stop_event.set()
969
+ return False
970
+
971
+ self.output[proxy.proxy] = proxy
972
+ self.output_count += 1
973
+
974
+ if self.output_count >= self.count:
975
+ self.stop_event.set()
976
+
977
+ return True
978
+
979
+ def _extract_proxies(self, data, extraction_keys, site_config=None):
980
+ if data is None:
981
+ return
982
+
983
+ parent = extraction_keys.get("PARENT")
984
+
985
+ if parent:
986
+ data = self.extract_path(data, parent)
987
+
988
+ if isinstance(data, dict):
989
+ data = [data]
990
+
991
+ if not isinstance(data, (list, tuple)):
992
+ return
993
+
994
+ for item in data:
995
+ if self.stop_event.is_set():
996
+ break
997
+
998
+ if not isinstance(item, dict):
999
+ continue
1000
+
1001
+ try:
1002
+ proxy = self.create_ip_object(item, extraction_keys, site_config)
1003
+ self._collect_proxy(proxy)
1004
+ except (TypeError, ValueError, InvalidDataTypeException):
1005
+ continue
1006
+
1007
+ def _extract_txt_proxies(self, data, extraction_keys):
1008
+ if not isinstance(data, list):
1009
+ return
1010
+
1011
+ pattern = extraction_keys.get(
1012
+ "REGEX",
1013
+ extraction_keys.get(
1014
+ "PATTERN",
1015
+ r"(?P<ip>\d{1,3}(?:\.\d{1,3}){3})\s*:\s*(?P<port>\d+)",
1016
+ ),
1017
+ )
1018
+
1019
+ source_url = str(extraction_keys.get("SOURCE_URL", "")).lower()
1020
+ protocol = extraction_keys.get("PROTOCOL")
1021
+
1022
+ if not protocol:
1023
+ if "socks5" in source_url:
1024
+ protocol = "socks5"
1025
+ elif "socks4" in source_url:
1026
+ protocol = "socks4"
1027
+ elif "http" in source_url:
1028
+ protocol = "http"
1029
+ else:
1030
+ protocol = "http"
1031
+
1032
+ field_keys = {
1033
+ "ip": "ip",
1034
+ "port": "port",
1035
+ "protocol": "protocol",
1036
+ }
1037
+
1038
+ field_keys.update(extraction_keys.get("FIELD_KEYS", {}))
1039
+ object_config = {"FIELD_KEYS": field_keys}
1040
+
1041
+ for item in data:
1042
+ if self.stop_event.is_set():
1043
+ break
1044
+
1045
+ if not isinstance(item, str):
1046
+ continue
1047
+
1048
+ item = item.strip()
1049
+
1050
+ if not item:
1051
+ continue
1052
+
1053
+ match = re.search(pattern, item)
1054
+
1055
+ if match:
1056
+ proxy_data = {
1057
+ key: value
1058
+ for key, value in match.groupdict().items()
1059
+ if value is not None
1060
+ }
1061
+
1062
+ if not proxy_data.get("ip") or not proxy_data.get("port"):
1063
+ if match.lastindex and match.lastindex >= 2:
1064
+ proxy_data = {
1065
+ "ip": match.group(1),
1066
+ "port": match.group(2),
1067
+ }
1068
+ else:
1069
+ proxy_data = self._normalize_proxy_address(
1070
+ match.group(0).strip()
1071
+ )
1072
+
1073
+ else:
1074
+ proxy_data = self._normalize_proxy_address(item)
1075
+
1076
+ if not isinstance(proxy_data, dict):
1077
+ continue
1078
+
1079
+ proxy_data.setdefault("protocol", protocol)
1080
+
1081
+ try:
1082
+ proxy = self.create_ip_object(
1083
+ proxy_data,
1084
+ object_config,
1085
+ )
1086
+
1087
+ self._collect_proxy(proxy)
1088
+
1089
+ except (TypeError, ValueError, InvalidDataTypeException):
1090
+ continue
1091
+
1092
+ def extract_keys(self, site_config):
1093
+ source = site_config.get("SOURCE")
1094
+ formatted_data = site_config.get("FORMATTED_DATA")
1095
+
1096
+ if source not in self._proxy_config:
1097
+ return
1098
+
1099
+ if not isinstance(formatted_data, (list, tuple, dict)):
1100
+ return
1101
+
1102
+ rule_type = next(
1103
+ (key for key in site_config if key.startswith("RULE_")),
1104
+ None,
1105
+ )
1106
+
1107
+ if not rule_type:
1108
+ return
1109
+
1110
+ extraction_keys = site_config.get(rule_type, {})
1111
+
1112
+ if rule_type == "RULE_TXT":
1113
+ self._extract_txt_proxies(
1114
+ formatted_data,
1115
+ extraction_keys,
1116
+ )
1117
+
1118
+ elif rule_type == "RULE_HTML" and extraction_keys.get("REGEX"):
1119
+ normalized_keys = {
1120
+ "FIELD_KEYS": {
1121
+ key: key for key in extraction_keys.get("FIELD_KEYS", {})
1122
+ }
1123
+ }
1124
+
1125
+ self._extract_proxies(
1126
+ formatted_data,
1127
+ normalized_keys,
1128
+ site_config,
1129
+ )
1130
+
1131
+ elif (
1132
+ rule_type == "RULE_HTML"
1133
+ and extraction_keys.get("XPATH")
1134
+ and extraction_keys.get("PANDAS") != "YES"
1135
+ and not extraction_keys.get("SCRIPT")
1136
+ ):
1137
+ normalized_keys = {
1138
+ "FIELD_KEYS": {
1139
+ key: key for key in extraction_keys.get("FIELD_KEYS", {})
1140
+ }
1141
+ }
1142
+
1143
+ self._extract_proxies(
1144
+ formatted_data,
1145
+ normalized_keys,
1146
+ site_config,
1147
+ )
1148
+
1149
+ elif rule_type == "RULE_JSON" and extraction_keys.get("RULE_HTML"):
1150
+ nested_keys = extraction_keys["RULE_HTML"].get(
1151
+ "FIELD_KEYS",
1152
+ {},
1153
+ )
1154
+
1155
+ normalized_keys = {"FIELD_KEYS": {key: key for key in nested_keys}}
1156
+
1157
+ self._extract_proxies(
1158
+ formatted_data,
1159
+ normalized_keys,
1160
+ site_config,
1161
+ )
1162
+
1163
+ else:
1164
+ self._extract_proxies(
1165
+ formatted_data,
1166
+ extraction_keys,
1167
+ site_config,
1168
+ )
1169
+
1170
+ def _matches_filters(self, proxy):
1171
+ for field in (
1172
+ "country",
1173
+ "country_code",
1174
+ "state",
1175
+ "state_code",
1176
+ "city",
1177
+ "region",
1178
+ "continent",
1179
+ "timezone",
1180
+ "isp",
1181
+ "organization",
1182
+ "anonymity",
1183
+ ):
1184
+ expected = self.filters.get(field)
1185
+
1186
+ if expected is None:
1187
+ continue
1188
+
1189
+ actual = getattr(proxy, field)
1190
+
1191
+ if actual is None:
1192
+ return False
1193
+
1194
+ if isinstance(expected, str):
1195
+ if expected.lower() not in str(actual).lower():
1196
+ return False
1197
+
1198
+ elif isinstance(expected, (list, tuple, set)):
1199
+ if not any(
1200
+ str(value).lower() == str(actual).lower() for value in expected
1201
+ ):
1202
+ return False
1203
+
1204
+ asn = self.filters.get("asn")
1205
+
1206
+ if asn is not None and proxy.asn != asn:
1207
+ return False
1208
+
1209
+ min_latency = self.filters.get("min_latency")
1210
+
1211
+ if min_latency is not None:
1212
+ if proxy.latency is None or proxy.latency < min_latency:
1213
+ return False
1214
+
1215
+ max_latency = self.filters.get("max_latency")
1216
+
1217
+ if max_latency is not None:
1218
+ if proxy.latency is None or proxy.latency > max_latency:
1219
+ return False
1220
+
1221
+ return True
1222
+
1223
+ def format_data(self, site_config):
1224
+ self.process_rules(site_config)
1225
+ self.extract_keys(site_config)
1226
+
1227
+ def process_site(self, site, url, site_config):
1228
+ if self.stop_event.is_set():
1229
+ return
1230
+
1231
+ session = requests.Session(impersonate="chrome")
1232
+
1233
+ try:
1234
+ site_config["SOURCE"] = site
1235
+
1236
+ if isinstance(site_config.get("RULE_TXT"), dict):
1237
+ site_config["RULE_TXT"]["SOURCE_URL"] = url
1238
+
1239
+ data = self.fetch_data(session, url, site_config)
1240
+
1241
+ if not data or self.stop_event.is_set():
1242
+ return
1243
+
1244
+ site_config["DATA"] = data
1245
+ self.format_data(site_config)
1246
+
1247
+ finally:
1248
+ session.close()
1249
+
1250
+ def _start_source(self, job):
1251
+ import traceback
1252
+
1253
+ site, url, site_config = job
1254
+
1255
+ try:
1256
+ self.process_site(site, url, site_config)
1257
+
1258
+ except KeyboardInterrupt:
1259
+ raise
1260
+
1261
+ except Exception as e:
1262
+ print(
1263
+ f"Worker error | source={site} | "
1264
+ f"url={url} | error={type(e).__name__}: {e}"
1265
+ )
1266
+
1267
+ traceback.print_exc()
1268
+
1269
+ def format_config(self, site_config):
1270
+ site_config = deepcopy(site_config)
1271
+
1272
+ for key, value in site_config.items():
1273
+ if key.startswith("RULE_") and isinstance(value, dict):
1274
+ parent_config = {k: v for k, v in value.items() if k != "FIELD_KEYS"}
1275
+
1276
+ for config_key, config_value in site_config.items():
1277
+ if config_key != key:
1278
+ parent_config.setdefault(
1279
+ config_key,
1280
+ config_value,
1281
+ )
1282
+
1283
+ for field_config in value.get("FIELD_KEYS", {}).values():
1284
+ if isinstance(field_config, dict):
1285
+ field_config.update(
1286
+ {
1287
+ k: v
1288
+ for k, v in parent_config.items()
1289
+ if k not in field_config
1290
+ }
1291
+ )
1292
+
1293
+ return site_config
1294
+
1295
+ def _start_source_worker(self, sites):
1296
+ jobs = []
1297
+
1298
+ for site in sites:
1299
+ site_config = self._proxy_config.get(site, {})
1300
+ urls = site_config.get("URL", [])
1301
+
1302
+ if isinstance(urls, str):
1303
+ urls = [urls]
1304
+
1305
+ for url in urls:
1306
+ jobs.append((site, url, self.format_config(site_config)))
1307
+
1308
+ if not jobs:
1309
+ return
1310
+
1311
+ executor = ThreadPoolExecutor(max_workers=self._source_workers)
1312
+
1313
+ futures = [executor.submit(self._start_source, job) for job in jobs]
1314
+
1315
+ try:
1316
+ for future in as_completed(futures):
1317
+ try:
1318
+ future.result()
1319
+
1320
+ except Exception as e:
1321
+ print(f"Worker error: {type(e).__name__}: {e}")
1322
+
1323
+ if self.stop_event.is_set():
1324
+ for pending in futures:
1325
+ pending.cancel()
1326
+
1327
+ break
1328
+
1329
+ except KeyboardInterrupt:
1330
+ self.stop_event.set()
1331
+
1332
+ for pending in futures:
1333
+ pending.cancel()
1334
+
1335
+ executor.shutdown(
1336
+ wait=False,
1337
+ cancel_futures=True,
1338
+ )
1339
+
1340
+ raise
1341
+
1342
+ else:
1343
+ executor.shutdown(
1344
+ wait=True,
1345
+ cancel_futures=True,
1346
+ )
1347
+
1348
+ def fetch(
1349
+ self,
1350
+ count: int = 1,
1351
+ sites: str | list | None = None,
1352
+ country: str | None = None,
1353
+ country_code: str | None = None,
1354
+ state: str | None = None,
1355
+ state_code: str | None = None,
1356
+ city: str | None = None,
1357
+ region: str | None = None,
1358
+ continent: str | None = None,
1359
+ timezone: str | None = None,
1360
+ isp: str | None = None,
1361
+ organization: str | None = None,
1362
+ asn: int | None = None,
1363
+ anonymity: str | None = None,
1364
+ min_latency: float | None = None,
1365
+ max_latency: float | None = None,
1366
+ google: bool | None = None,
1367
+ ):
1368
+ if not isinstance(count, int) or isinstance(count, bool):
1369
+ raise InvalidDataTypeException("Count must be an integer")
1370
+
1371
+ if count < 1:
1372
+ raise InvalidDataTypeException("Count must be greater than 0")
1373
+
1374
+ if min_latency is not None and max_latency is not None:
1375
+ if min_latency > max_latency:
1376
+ raise InvalidDataTypeException("min_latency cannot exceed max_latency")
1377
+
1378
+ self.count = count
1379
+ self.output = {}
1380
+ self.output_count = 0
1381
+ self.stop_event.clear()
1382
+
1383
+ self.filters = {
1384
+ "country": country,
1385
+ "country_code": country_code,
1386
+ "state": state,
1387
+ "state_code": state_code,
1388
+ "city": city,
1389
+ "region": region,
1390
+ "continent": continent,
1391
+ "timezone": timezone,
1392
+ "isp": isp,
1393
+ "organization": organization,
1394
+ "asn": asn,
1395
+ "anonymity": anonymity,
1396
+ "min_latency": min_latency,
1397
+ "max_latency": max_latency,
1398
+ "google": google,
1399
+ }
1400
+
1401
+ sites = self._normalize_sites(sites)
1402
+ self._validate_sites(sites)
1403
+
1404
+ self._start_source_worker(sites)
1405
+
1406
+ return list(self.output.values())