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