@auscera/socialscrape 0.0.0-stage โ 2.0.1
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.
- package/README.md +111 -2
- package/bin/socialscrape.mjs +115 -0
- package/engine/README.md +243 -0
- package/engine/SKILL.md +194 -0
- package/engine/agent.py +665 -0
- package/engine/batch_manager.py +622 -0
- package/engine/cli.py +23 -0
- package/engine/handlers.py +1109 -0
- package/engine/plugins/__init__.py +77 -0
- package/engine/plugins/instagram-scrape/README.md +164 -0
- package/engine/plugins/instagram-scrape/SKILL.md +53 -0
- package/engine/plugins/instagram-scrape/cli.py +176 -0
- package/engine/plugins/instagram-scrape/core.py +408 -0
- package/engine/plugins/instagram-scrape/plugin.json +42 -0
- package/engine/plugins/linkedin-scrape/README.md +143 -0
- package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
- package/engine/plugins/linkedin-scrape/cli.py +126 -0
- package/engine/plugins/linkedin-scrape/core.py +188 -0
- package/engine/plugins/linkedin-scrape/plugin.json +36 -0
- package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
- package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
- package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
- package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
- package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
- package/engine/plugins/pinterest-scraper/README.md +150 -0
- package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
- package/engine/plugins/pinterest-scraper/cli.py +193 -0
- package/engine/plugins/pinterest-scraper/core.py +420 -0
- package/engine/plugins/pinterest-scraper/plugin.json +40 -0
- package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
- package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
- package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
- package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
- package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
- package/engine/plugins/shared/__init__.py +15 -0
- package/engine/plugins/shared/paths.py +90 -0
- package/engine/plugins/shared/process_runner.py +169 -0
- package/engine/plugins/shared/session_manager.py +287 -0
- package/engine/plugins/threads-scraper/README.md +139 -0
- package/engine/plugins/threads-scraper/SKILL.md +43 -0
- package/engine/plugins/threads-scraper/cli.py +178 -0
- package/engine/plugins/threads-scraper/core.py +460 -0
- package/engine/plugins/threads-scraper/plugin.json +40 -0
- package/engine/plugins/tiktok-scrape/README.md +158 -0
- package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
- package/engine/plugins/tiktok-scrape/cli.py +163 -0
- package/engine/plugins/tiktok-scrape/core.py +313 -0
- package/engine/plugins/tiktok-scrape/plugin.json +40 -0
- package/engine/plugins/twitter-scrape/README.md +158 -0
- package/engine/plugins/twitter-scrape/SKILL.md +50 -0
- package/engine/plugins/twitter-scrape/cli.py +153 -0
- package/engine/plugins/twitter-scrape/core.py +254 -0
- package/engine/plugins/twitter-scrape/plugin.json +40 -0
- package/engine/plugins/youtube-scrape/README.md +199 -0
- package/engine/plugins/youtube-scrape/SKILL.md +115 -0
- package/engine/plugins/youtube-scrape/cli.py +340 -0
- package/engine/plugins/youtube-scrape/core.py +829 -0
- package/engine/plugins/youtube-scrape/plugin.json +48 -0
- package/engine/requirements.txt +8 -0
- package/engine/socialscrape_cli.py +500 -0
- package/engine/storage.py +570 -0
- package/engine/ui.py +690 -0
- package/package.json +27 -3
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared Path Resolution & Boundary Validation Helpers (`plugins/shared/paths.py`).
|
|
3
|
+
Provides a single source of truth for plugin output directories, shared state
|
|
4
|
+
locations (`.sessions.json`, `.rate_limits.json`), and safe output boundary checks
|
|
5
|
+
across both Global User Mode and Local Developer Mode.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import List, Optional
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from platformdirs import user_data_dir
|
|
14
|
+
HAS_PLATFORMDIRS = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
HAS_PLATFORMDIRS = False
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _is_relative_to(path: Path, base: Path) -> bool:
|
|
20
|
+
"""Python 3.9+ compatible relative-path containment check."""
|
|
21
|
+
try:
|
|
22
|
+
return path.resolve().is_relative_to(base.resolve())
|
|
23
|
+
except AttributeError:
|
|
24
|
+
try:
|
|
25
|
+
path.resolve().relative_to(base.resolve())
|
|
26
|
+
return True
|
|
27
|
+
except ValueError:
|
|
28
|
+
return False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _default_user_data_dir() -> Path:
|
|
32
|
+
"""Returns the OS-native user data directory without importing root storage.py."""
|
|
33
|
+
if HAS_PLATFORMDIRS:
|
|
34
|
+
return Path(user_data_dir("socialscrape", "socialscrape")).resolve()
|
|
35
|
+
return (Path.home() / ".socialscrape").resolve()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_plugin_outputs_dir(plugin_dir: Path) -> Path:
|
|
39
|
+
"""
|
|
40
|
+
Resolves the base Outputs directory for a plugin.
|
|
41
|
+
Uses `SOCIALSCRAPE_OUTPUT_DIR` when invoked by the Hub/Batch Engine in Global Mode,
|
|
42
|
+
falling back to `<plugin_dir>/Outputs` for standalone or local dev execution.
|
|
43
|
+
"""
|
|
44
|
+
env_out = os.environ.get("SOCIALSCRAPE_OUTPUT_DIR", "").strip()
|
|
45
|
+
if env_out:
|
|
46
|
+
return Path(env_out).expanduser().resolve()
|
|
47
|
+
return (Path(plugin_dir).resolve() / "Outputs").resolve()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_shared_state_dir(shared_dir: Path) -> Path:
|
|
51
|
+
"""
|
|
52
|
+
Resolves the writable directory for `.sessions.json` and `.rate_limits.json`.
|
|
53
|
+
Uses `SOCIALSCRAPE_STATE_DIR` when forwarded by the Hub, or falls back to
|
|
54
|
+
user data storage if `shared_dir` resides in site-packages or is not writable.
|
|
55
|
+
"""
|
|
56
|
+
env_state = os.environ.get("SOCIALSCRAPE_STATE_DIR", "").strip()
|
|
57
|
+
if env_state:
|
|
58
|
+
return Path(env_state).expanduser().resolve()
|
|
59
|
+
|
|
60
|
+
resolved = Path(shared_dir).resolve()
|
|
61
|
+
parts_lower = {part.lower() for part in resolved.parts}
|
|
62
|
+
in_site_packages = "site-packages" in parts_lower or "dist-packages" in parts_lower
|
|
63
|
+
if in_site_packages or not os.access(resolved, os.W_OK):
|
|
64
|
+
return (_default_user_data_dir() / "state").resolve()
|
|
65
|
+
return resolved
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_allowed_output_dir(
|
|
69
|
+
target: Path,
|
|
70
|
+
plugin_dir: Path,
|
|
71
|
+
project_root: Path,
|
|
72
|
+
extra_roots: Optional[List[Path]] = None,
|
|
73
|
+
) -> bool:
|
|
74
|
+
"""
|
|
75
|
+
Validates that `target` stays within permitted plugin, project, or SocialScrape
|
|
76
|
+
global user data directory boundaries to prevent path traversal escapes.
|
|
77
|
+
"""
|
|
78
|
+
allowed_roots: List[Path] = [
|
|
79
|
+
Path(project_root),
|
|
80
|
+
Path(plugin_dir),
|
|
81
|
+
_default_user_data_dir(),
|
|
82
|
+
]
|
|
83
|
+
env_out = os.environ.get("SOCIALSCRAPE_OUTPUT_DIR", "").strip()
|
|
84
|
+
if env_out:
|
|
85
|
+
allowed_roots.append(Path(env_out).expanduser())
|
|
86
|
+
if extra_roots:
|
|
87
|
+
allowed_roots.extend(extra_roots)
|
|
88
|
+
|
|
89
|
+
resolved_target = Path(target).resolve()
|
|
90
|
+
return any(_is_relative_to(resolved_target, root) for root in allowed_roots)
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SocialScrape Subprocess Resilience & Fault-Tolerant Runner (`process_runner.py`).
|
|
3
|
+
Provides centralized execution, timeout management, exponential backoff, and graceful recovery
|
|
4
|
+
for all plugin subprocess invocations.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import List, Dict, Any, Optional, Union
|
|
12
|
+
|
|
13
|
+
# Ensure UTF-8 output on Windows
|
|
14
|
+
if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
|
|
15
|
+
try:
|
|
16
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
17
|
+
except Exception as e:
|
|
18
|
+
sys.stderr.write(f"[SocialScrape Notice] UTF-8 stdout reconfiguration skipped: {e}\n")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from rich.console import Console
|
|
23
|
+
console = Console(highlight=False)
|
|
24
|
+
except ImportError:
|
|
25
|
+
console = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _log_warning(message: str) -> None:
|
|
29
|
+
if console:
|
|
30
|
+
try:
|
|
31
|
+
console.print(f"[bold yellow][!] Warning: {message}[/bold yellow]")
|
|
32
|
+
return
|
|
33
|
+
except Exception:
|
|
34
|
+
pass
|
|
35
|
+
print(f"[WARNING] {message}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _log_error(message: str) -> None:
|
|
39
|
+
if console:
|
|
40
|
+
try:
|
|
41
|
+
console.print(f"[bold red][!] Error: {message}[/bold red]")
|
|
42
|
+
return
|
|
43
|
+
except Exception:
|
|
44
|
+
pass
|
|
45
|
+
print(f"[ERROR] {message}")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def run_plugin_subprocess(
|
|
49
|
+
cmd_args: List[Union[str, Path]],
|
|
50
|
+
retries: int = 3,
|
|
51
|
+
timeout_sec: Optional[int] = 120,
|
|
52
|
+
cwd: Optional[Union[str, Path]] = None,
|
|
53
|
+
capture_output: bool = False,
|
|
54
|
+
env: Optional[Dict[str, str]] = None,
|
|
55
|
+
) -> Dict[str, Any]:
|
|
56
|
+
"""
|
|
57
|
+
Executes a plugin CLI command via subprocess with built-in retry resilience,
|
|
58
|
+
exponential backoff, timeout enforcement, and clean error recovery.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
cmd_args: List of command arguments (e.g. [sys.executable, 'plugins/youtube-scrape/cli.py', '-i'])
|
|
62
|
+
retries: Maximum number of execution attempts for network/timeout failures (default: 3)
|
|
63
|
+
timeout_sec: Maximum seconds to wait per attempt before timing out (None for unlimited)
|
|
64
|
+
cwd: Working directory for subprocess execution
|
|
65
|
+
capture_output: If True, captures stdout/stderr; if False, connects directly to terminal
|
|
66
|
+
env: Optional environment variables dictionary
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Dict[str, Any] with keys:
|
|
70
|
+
- success: bool
|
|
71
|
+
- returncode: int
|
|
72
|
+
- error: Optional[str]
|
|
73
|
+
- stdout: Optional[str]
|
|
74
|
+
- stderr: Optional[str]
|
|
75
|
+
"""
|
|
76
|
+
str_cmd = [str(arg) for arg in cmd_args]
|
|
77
|
+
is_interactive = "-i" in str_cmd or "--interactive" in str_cmd
|
|
78
|
+
effective_retries = 1 if is_interactive else max(1, retries)
|
|
79
|
+
|
|
80
|
+
for attempt in range(1, effective_retries + 1):
|
|
81
|
+
try:
|
|
82
|
+
res = subprocess.run(
|
|
83
|
+
str_cmd,
|
|
84
|
+
cwd=str(cwd) if cwd else None,
|
|
85
|
+
timeout=timeout_sec,
|
|
86
|
+
capture_output=capture_output,
|
|
87
|
+
text=True if capture_output else False,
|
|
88
|
+
env=env,
|
|
89
|
+
check=False,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
if res.returncode == 0:
|
|
93
|
+
return {
|
|
94
|
+
"success": True,
|
|
95
|
+
"returncode": 0,
|
|
96
|
+
"stdout": res.stdout if capture_output else None,
|
|
97
|
+
"stderr": res.stderr if capture_output else None,
|
|
98
|
+
"error": None,
|
|
99
|
+
}
|
|
100
|
+
else:
|
|
101
|
+
# Fatal application/input exit codes should NOT be retried (e.g. 1=general fatal error/invalid input, 2=CLI misuse, 127=not found)
|
|
102
|
+
non_retryable_exit_codes = {1, 2, 126, 127}
|
|
103
|
+
if res.returncode in non_retryable_exit_codes or attempt >= effective_retries:
|
|
104
|
+
return {
|
|
105
|
+
"success": False,
|
|
106
|
+
"returncode": res.returncode,
|
|
107
|
+
"stdout": res.stdout if capture_output else None,
|
|
108
|
+
"stderr": res.stderr if capture_output else None,
|
|
109
|
+
"error": f"Process exited with non-zero status code: {res.returncode}",
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
# Transient failure backoff
|
|
113
|
+
backoff = min(2 ** attempt, 8)
|
|
114
|
+
_log_warning(
|
|
115
|
+
f"Plugin command exited with status {res.returncode}. Retrying ({attempt}/{effective_retries}) in {backoff}s..."
|
|
116
|
+
)
|
|
117
|
+
time.sleep(backoff)
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
except subprocess.TimeoutExpired:
|
|
122
|
+
if attempt < effective_retries:
|
|
123
|
+
backoff = min(2 ** attempt, 8)
|
|
124
|
+
_log_warning(
|
|
125
|
+
f"Plugin timed out after {timeout_sec}s. Retrying ({attempt}/{effective_retries}) in {backoff}s..."
|
|
126
|
+
)
|
|
127
|
+
time.sleep(backoff)
|
|
128
|
+
else:
|
|
129
|
+
_log_error(f"Plugin execution timed out after {timeout_sec}s ({effective_retries} attempts exhausted).")
|
|
130
|
+
return {
|
|
131
|
+
"success": False,
|
|
132
|
+
"returncode": -1,
|
|
133
|
+
"stdout": None,
|
|
134
|
+
"stderr": None,
|
|
135
|
+
"error": f"TimeoutExpired: Process exceeded {timeout_sec}s limit.",
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
except KeyboardInterrupt:
|
|
139
|
+
# Immediate user cancellation: do NOT retry
|
|
140
|
+
return {
|
|
141
|
+
"success": False,
|
|
142
|
+
"returncode": 130,
|
|
143
|
+
"stdout": None,
|
|
144
|
+
"stderr": None,
|
|
145
|
+
"error": "Execution interrupted by user (Ctrl+C).",
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
except Exception as e:
|
|
149
|
+
if attempt < effective_retries:
|
|
150
|
+
backoff = min(2 ** attempt, 8)
|
|
151
|
+
_log_warning(f"Unexpected error: {e}. Retrying ({attempt}/{effective_retries}) in {backoff}s...")
|
|
152
|
+
time.sleep(backoff)
|
|
153
|
+
else:
|
|
154
|
+
_log_error(f"Plugin execution failed: {e}")
|
|
155
|
+
return {
|
|
156
|
+
"success": False,
|
|
157
|
+
"returncode": -1,
|
|
158
|
+
"stdout": None,
|
|
159
|
+
"stderr": None,
|
|
160
|
+
"error": str(e),
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
"success": False,
|
|
165
|
+
"returncode": -1,
|
|
166
|
+
"stdout": None,
|
|
167
|
+
"stderr": None,
|
|
168
|
+
"error": "Unknown execution failure.",
|
|
169
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Session & Stealth Management Core (`session_manager.py`)
|
|
3
|
+
Secure local storage, token rotation, and rate-limiting rails for burner accounts.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import random
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Dict, List, Any, Optional
|
|
12
|
+
|
|
13
|
+
from .paths import get_shared_state_dir
|
|
14
|
+
|
|
15
|
+
SHARED_DIR = Path(__file__).parent.resolve()
|
|
16
|
+
SESSIONS_FILE = get_shared_state_dir(SHARED_DIR) / ".sessions.json"
|
|
17
|
+
|
|
18
|
+
# Platform safety rails and rate-limiting limits
|
|
19
|
+
DEFAULT_PLATFORM_LIMITS = {
|
|
20
|
+
"linkedin": {
|
|
21
|
+
"max_requests_per_day": 50,
|
|
22
|
+
"min_delay_seconds": 4.0,
|
|
23
|
+
"max_delay_seconds": 8.0,
|
|
24
|
+
},
|
|
25
|
+
"instagram": {
|
|
26
|
+
"max_requests_per_hour": 100,
|
|
27
|
+
"min_delay_seconds": 2.0,
|
|
28
|
+
"max_delay_seconds": 5.0,
|
|
29
|
+
},
|
|
30
|
+
"twitter": {
|
|
31
|
+
"max_requests_per_hour": 250,
|
|
32
|
+
"min_delay_seconds": 1.0,
|
|
33
|
+
"max_delay_seconds": 3.0,
|
|
34
|
+
},
|
|
35
|
+
"tiktok": {
|
|
36
|
+
"max_requests_per_hour": 150,
|
|
37
|
+
"min_delay_seconds": 1.5,
|
|
38
|
+
"max_delay_seconds": 4.0,
|
|
39
|
+
},
|
|
40
|
+
"reddit": {
|
|
41
|
+
"max_requests_per_hour": 100,
|
|
42
|
+
"min_delay_seconds": 1.0,
|
|
43
|
+
"max_delay_seconds": 3.0,
|
|
44
|
+
},
|
|
45
|
+
"threads": {
|
|
46
|
+
"max_requests_per_hour": 100,
|
|
47
|
+
"min_delay_seconds": 2.0,
|
|
48
|
+
"max_delay_seconds": 4.0,
|
|
49
|
+
},
|
|
50
|
+
"pinterest": {
|
|
51
|
+
"max_requests_per_hour": 120,
|
|
52
|
+
"min_delay_seconds": 1.5,
|
|
53
|
+
"max_delay_seconds": 3.5,
|
|
54
|
+
},
|
|
55
|
+
"meta_ads": {
|
|
56
|
+
"max_requests_per_hour": 60,
|
|
57
|
+
"min_delay_seconds": 3.0,
|
|
58
|
+
"max_delay_seconds": 6.0,
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class RateLimiter:
|
|
64
|
+
"""Tracks and enforces pacing and hard ceilings to protect burner accounts."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, state_file: Optional[Path] = None):
|
|
67
|
+
self.state_file = state_file or (get_shared_state_dir(SHARED_DIR) / ".rate_limits.json")
|
|
68
|
+
self._load_state()
|
|
69
|
+
|
|
70
|
+
def _load_state(self):
|
|
71
|
+
if self.state_file.exists():
|
|
72
|
+
try:
|
|
73
|
+
with open(self.state_file, "r", encoding="utf-8") as f:
|
|
74
|
+
self.state = json.load(f)
|
|
75
|
+
except Exception:
|
|
76
|
+
self.state = {}
|
|
77
|
+
else:
|
|
78
|
+
self.state = {}
|
|
79
|
+
|
|
80
|
+
def _save_state(self):
|
|
81
|
+
try:
|
|
82
|
+
self.state_file.parent.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
with open(self.state_file, "w", encoding="utf-8") as f:
|
|
84
|
+
json.dump(self.state, f, indent=2)
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
def check_and_pace(self, platform: str, account_alias: str = "default") -> bool:
|
|
89
|
+
"""
|
|
90
|
+
Checks rate limit ceilings and introduces randomized human-like delays.
|
|
91
|
+
Returns True if request is allowed, False if limit exceeded.
|
|
92
|
+
"""
|
|
93
|
+
platform = platform.lower()
|
|
94
|
+
limits = DEFAULT_PLATFORM_LIMITS.get(platform, {})
|
|
95
|
+
now = time.time()
|
|
96
|
+
key = f"{platform}:{account_alias}"
|
|
97
|
+
|
|
98
|
+
if key not in self.state:
|
|
99
|
+
self.state[key] = {
|
|
100
|
+
"daily_requests": 0,
|
|
101
|
+
"hourly_requests": 0,
|
|
102
|
+
"last_request_time": 0.0,
|
|
103
|
+
"day_reset_timestamp": now + 86400,
|
|
104
|
+
"hour_reset_timestamp": now + 3600,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
rec = self.state[key]
|
|
108
|
+
|
|
109
|
+
# Reset daily counters if 24 hours elapsed
|
|
110
|
+
if now >= rec.get("day_reset_timestamp", 0):
|
|
111
|
+
rec["daily_requests"] = 0
|
|
112
|
+
rec["day_reset_timestamp"] = now + 86400
|
|
113
|
+
|
|
114
|
+
# Reset hourly counters if 1 hour elapsed
|
|
115
|
+
if now >= rec.get("hour_reset_timestamp", 0):
|
|
116
|
+
rec["hourly_requests"] = 0
|
|
117
|
+
rec["hour_reset_timestamp"] = now + 3600
|
|
118
|
+
|
|
119
|
+
# Check hard ceilings
|
|
120
|
+
max_day = limits.get("max_requests_per_day")
|
|
121
|
+
if max_day and rec["daily_requests"] >= max_day:
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
max_hour = limits.get("max_requests_per_hour")
|
|
125
|
+
if max_hour and rec["hourly_requests"] >= max_hour:
|
|
126
|
+
return False
|
|
127
|
+
|
|
128
|
+
# Apply humanized randomized pacing delay
|
|
129
|
+
min_delay = limits.get("min_delay_seconds", 1.0)
|
|
130
|
+
max_delay = limits.get("max_delay_seconds", 3.0)
|
|
131
|
+
last_time = rec.get("last_request_time", 0.0)
|
|
132
|
+
elapsed = now - last_time
|
|
133
|
+
target_delay = random.uniform(min_delay, max_delay)
|
|
134
|
+
|
|
135
|
+
if elapsed < target_delay:
|
|
136
|
+
time.sleep(target_delay - elapsed)
|
|
137
|
+
|
|
138
|
+
# Record this request
|
|
139
|
+
rec["daily_requests"] += 1
|
|
140
|
+
rec["hourly_requests"] += 1
|
|
141
|
+
rec["last_request_time"] = time.time()
|
|
142
|
+
self._save_state()
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class SessionManager:
|
|
147
|
+
"""Securely stores and rotates burner sessions across SocialScrape plugins."""
|
|
148
|
+
|
|
149
|
+
def __init__(self, storage_file: Optional[Path] = None):
|
|
150
|
+
self.storage_file = storage_file or (get_shared_state_dir(SHARED_DIR) / ".sessions.json")
|
|
151
|
+
self.rate_limiter = RateLimiter()
|
|
152
|
+
self._load()
|
|
153
|
+
|
|
154
|
+
def _load(self):
|
|
155
|
+
if self.storage_file.exists():
|
|
156
|
+
try:
|
|
157
|
+
with open(self.storage_file, "r", encoding="utf-8") as f:
|
|
158
|
+
self.data = json.load(f)
|
|
159
|
+
except Exception:
|
|
160
|
+
self.data = {}
|
|
161
|
+
else:
|
|
162
|
+
self.data = {}
|
|
163
|
+
|
|
164
|
+
def _save(self):
|
|
165
|
+
try:
|
|
166
|
+
self.storage_file.parent.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
with open(self.storage_file, "w", encoding="utf-8") as f:
|
|
168
|
+
json.dump(self.data, f, indent=2)
|
|
169
|
+
except Exception:
|
|
170
|
+
pass
|
|
171
|
+
|
|
172
|
+
def save_session(
|
|
173
|
+
self,
|
|
174
|
+
platform: str,
|
|
175
|
+
alias: str,
|
|
176
|
+
cookies_or_tokens: Dict[str, str],
|
|
177
|
+
notes: str = ""
|
|
178
|
+
) -> Dict[str, Any]:
|
|
179
|
+
"""Saves or updates burner session credentials."""
|
|
180
|
+
platform = platform.lower()
|
|
181
|
+
if platform not in self.data:
|
|
182
|
+
self.data[platform] = {}
|
|
183
|
+
|
|
184
|
+
self.data[platform][alias] = {
|
|
185
|
+
"alias": alias,
|
|
186
|
+
"platform": platform,
|
|
187
|
+
"tokens": cookies_or_tokens,
|
|
188
|
+
"notes": notes,
|
|
189
|
+
"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
190
|
+
"status": "active",
|
|
191
|
+
}
|
|
192
|
+
self._save()
|
|
193
|
+
return {"status": "success", "platform": platform, "alias": alias}
|
|
194
|
+
|
|
195
|
+
def get_session(self, platform: str, alias: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
|
196
|
+
"""Retrieves active burner session for a platform."""
|
|
197
|
+
platform = platform.lower()
|
|
198
|
+
platform_sessions = self.data.get(platform, {})
|
|
199
|
+
if not platform_sessions:
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
if alias:
|
|
203
|
+
return platform_sessions.get(alias)
|
|
204
|
+
|
|
205
|
+
# Return first active session
|
|
206
|
+
for sess in platform_sessions.values():
|
|
207
|
+
if sess.get("status") == "active":
|
|
208
|
+
return sess
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
def rotate_session(self, platform: str) -> Optional[Dict[str, Any]]:
|
|
212
|
+
"""Rotates to the next active session for a platform."""
|
|
213
|
+
platform = platform.lower()
|
|
214
|
+
platform_sessions = self.data.get(platform, {})
|
|
215
|
+
active = [s for s in platform_sessions.values() if s.get("status") == "active"]
|
|
216
|
+
if not active:
|
|
217
|
+
return None
|
|
218
|
+
return random.choice(active)
|
|
219
|
+
|
|
220
|
+
def list_sessions(self, platform: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
221
|
+
"""Lists sessions with masked tokens for UI display."""
|
|
222
|
+
results = []
|
|
223
|
+
platforms = [platform.lower()] if platform else self.data.keys()
|
|
224
|
+
|
|
225
|
+
for plat in platforms:
|
|
226
|
+
for alias, sess in self.data.get(plat, {}).items():
|
|
227
|
+
masked_tokens = {}
|
|
228
|
+
for k, v in sess.get("tokens", {}).items():
|
|
229
|
+
if len(v) > 8:
|
|
230
|
+
masked_tokens[k] = f"{v[:4]}...{v[-4:]}"
|
|
231
|
+
else:
|
|
232
|
+
masked_tokens[k] = "***"
|
|
233
|
+
|
|
234
|
+
results.append({
|
|
235
|
+
"platform": plat,
|
|
236
|
+
"alias": alias,
|
|
237
|
+
"status": sess.get("status", "active"),
|
|
238
|
+
"updated_at": sess.get("updated_at", ""),
|
|
239
|
+
"masked_tokens": masked_tokens,
|
|
240
|
+
"notes": sess.get("notes", ""),
|
|
241
|
+
})
|
|
242
|
+
return results
|
|
243
|
+
|
|
244
|
+
def delete_session(self, platform: str, alias: str) -> bool:
|
|
245
|
+
"""Deletes a burner session."""
|
|
246
|
+
platform = platform.lower()
|
|
247
|
+
if platform in self.data and alias in self.data[platform]:
|
|
248
|
+
del self.data[platform][alias]
|
|
249
|
+
self._save()
|
|
250
|
+
return True
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
def get_auth_headers(self, platform: str, alias: Optional[str] = None) -> Dict[str, str]:
|
|
254
|
+
"""Generates ready-to-use HTTP headers for requests based on stored tokens."""
|
|
255
|
+
session = self.get_session(platform, alias)
|
|
256
|
+
if not session:
|
|
257
|
+
return {}
|
|
258
|
+
|
|
259
|
+
tokens = session.get("tokens", {})
|
|
260
|
+
headers = {}
|
|
261
|
+
platform = platform.lower()
|
|
262
|
+
|
|
263
|
+
if platform == "instagram":
|
|
264
|
+
sessionid = tokens.get("sessionid", "")
|
|
265
|
+
if sessionid:
|
|
266
|
+
headers["Cookie"] = f"sessionid={sessionid};"
|
|
267
|
+
headers["X-IG-App-ID"] = "936619743392459"
|
|
268
|
+
elif platform == "linkedin":
|
|
269
|
+
li_at = tokens.get("li_at", "")
|
|
270
|
+
if li_at:
|
|
271
|
+
headers["Cookie"] = f"li_at={li_at};"
|
|
272
|
+
headers["Csrf-Token"] = tokens.get("csrf_token", "ajax:0000000000000000000")
|
|
273
|
+
headers["X-RestLi-Protocol-Version"] = "2.0.0"
|
|
274
|
+
elif platform == "twitter":
|
|
275
|
+
auth_token = tokens.get("auth_token", "")
|
|
276
|
+
ct0 = tokens.get("ct0", "")
|
|
277
|
+
cookie_parts = []
|
|
278
|
+
if auth_token:
|
|
279
|
+
cookie_parts.append(f"auth_token={auth_token}")
|
|
280
|
+
if ct0:
|
|
281
|
+
cookie_parts.append(f"ct0={ct0}")
|
|
282
|
+
headers["X-Csrf-Token"] = ct0
|
|
283
|
+
if cookie_parts:
|
|
284
|
+
headers["Cookie"] = "; ".join(cookie_parts)
|
|
285
|
+
headers["Authorization"] = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
|
|
286
|
+
|
|
287
|
+
return headers
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Meta Threads Universal Scraper & Downloader Plugin ๐งต
|
|
2
|
+
|
|
3
|
+
> **A self-contained, high-speed, zero-cost Python SDK and CLI engine for Meta Threads profiles, creator thread feeds, single thread discussions, and media downloads.**
|
|
4
|
+
|
|
5
|
+
This plugin extracts structured thread conversations, engagement metrics, and media from **user profiles**, **creator timelines**, and **single thread posts** via dynamic LSD token extraction and public web endpoint parsing.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## ๐ Comprehensive Feature Breakdown & Capabilities
|
|
10
|
+
|
|
11
|
+
### 1. ๐ค User Profile Intelligence & Bio Extraction
|
|
12
|
+
- **How it works**: Makes a stealth request to `https://www.threads.net/@{username}` with dynamic `LSD` CSRF tokens and extracts inline profile state and OpenGraph tags.
|
|
13
|
+
- **Capabilities**:
|
|
14
|
+
- Extracts full `username`, `full_name`, `bio` (biography), `is_verified`, `profile_pic_url`, and internal account `pk` ID.
|
|
15
|
+
- Automatically exports profile metadata to `Outputs/text_posts/user_{username}/profile.json`.
|
|
16
|
+
|
|
17
|
+
### 2. ๐ Creator Threads Timeline & Feed Scraping
|
|
18
|
+
- **How it works**: Queries user profile feeds and extracts chronological thread posts, captions, like counts, and reply counts.
|
|
19
|
+
- **Data Extracted**:
|
|
20
|
+
- `id`: Thread post identifier
|
|
21
|
+
- `text`: Complete post text / caption (decoded from Unicode escape sequences)
|
|
22
|
+
- `likes`: Total like count
|
|
23
|
+
- `author`: Creator handle
|
|
24
|
+
- Saved into `Outputs/text_posts/user_{username}/feed.json`.
|
|
25
|
+
|
|
26
|
+
### 3. ๐ฌ Single Thread Discussions & Reply Extraction
|
|
27
|
+
- **How it works**: Extracts root post caption, original poster handle, and replies from any public Thread post URL or shortcode.
|
|
28
|
+
- **Data Extracted**:
|
|
29
|
+
- `id`: Shortcode / post ID
|
|
30
|
+
- `url`: Direct thread URL
|
|
31
|
+
- `text`: Root discussion text
|
|
32
|
+
- `author`: Post creator
|
|
33
|
+
- `likes`: Post like count
|
|
34
|
+
- Saved into `Outputs/comments/thread_{post_id}/discussion.json`.
|
|
35
|
+
|
|
36
|
+
### 4. ๐ฌ Media & Video Downloader
|
|
37
|
+
- **How it works**: Direct stream extraction via `yt-dlp` to download Threads video clips (MP4) and high-resolution attached photos into `Outputs/`.
|
|
38
|
+
- **Download Modes**:
|
|
39
|
+
- **Video (`--download-video`)**: Downloads high-definition `.mp4` video clips into `Outputs/videos/thread_{post_id}/`.
|
|
40
|
+
- **Thumbnails & Photos (`--download-thumb`)**: Downloads attached images into `Outputs/thumbnails/thread_{post_id}/`.
|
|
41
|
+
- **Quality Selector (`-q / --quality`)**: Select from `best`, `1080p`, `720p`, or `480p`.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## ๐ Standardized `Outputs/` Hierarchy
|
|
46
|
+
|
|
47
|
+
Every extracted thread, profile, and media asset is organized into dedicated folders:
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
plugins/threads-scraper/
|
|
51
|
+
โโโ core.py # โก Pure Python SDK (Zero prints, returns dicts)
|
|
52
|
+
โโโ cli.py # ๐ง Interactive CLI & Terminal Runner
|
|
53
|
+
โโโ plugin.json # ๐ Universal plugin manifest
|
|
54
|
+
โโโ SKILL.md # ๐ง AI Agent parameter discovery protocol
|
|
55
|
+
โโโ README.md # ๐ Master documentation (This file)
|
|
56
|
+
โโโ Outputs/ # ๐พ Standardized Categorized Storage
|
|
57
|
+
โโโ videos/thread_<post_id>/
|
|
58
|
+
โ โโโ video.mp4 # Downloaded Thread video
|
|
59
|
+
โโโ thumbnails/thread_<post_id>/
|
|
60
|
+
โ โโโ thumbnail.jpg # Attached photo or preview image
|
|
61
|
+
โโโ comments/thread_<post_id>/
|
|
62
|
+
โ โโโ discussion.json # Thread post discussion & replies
|
|
63
|
+
โโโ text_posts/user_<username>/
|
|
64
|
+
โโโ profile.json # Structured user profile metadata
|
|
65
|
+
โโโ feed.json # Creator timeline threads
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## ๐ก AI Agent Usage: In-Memory / Zero-Disk Execution
|
|
71
|
+
|
|
72
|
+
When an AI agent (Claude Code, Cursor, Codex, Antigravity) executes this plugin, **it does NOT need to write heavy media artifacts to disk**.
|
|
73
|
+
|
|
74
|
+
### Zero-Disk Execution Modes for AI Agents:
|
|
75
|
+
|
|
76
|
+
1. **In-Memory CLI Pipe (`--stdout`)**:
|
|
77
|
+
```bash
|
|
78
|
+
python plugins/threads-scraper/cli.py @zuck --feed --limit 5 --stdout
|
|
79
|
+
```
|
|
80
|
+
*The structured JSON streams directly into the AI's standard input in RAM.*
|
|
81
|
+
|
|
82
|
+
2. **Direct Python SDK Import**:
|
|
83
|
+
```python
|
|
84
|
+
import sys
|
|
85
|
+
from pathlib import Path
|
|
86
|
+
sys.path.insert(0, str(Path("plugins/threads-scraper").resolve()))
|
|
87
|
+
import core
|
|
88
|
+
|
|
89
|
+
# Returns pure Python dictionary in RAM with zero disk writes!
|
|
90
|
+
profile = core.get_threads_user_profile("zuck")
|
|
91
|
+
feed = core.get_threads_user_posts("zuck", limit=10)
|
|
92
|
+
thread = core.get_thread_post_and_replies("https://www.threads.net/@zuck/post/C8abc123")
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## ๐ CLI Commands & Usage Examples
|
|
98
|
+
|
|
99
|
+
### 1. Interactive Wizard (Easiest for Humans)
|
|
100
|
+
```bash
|
|
101
|
+
python plugins/threads-scraper/cli.py -i
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 2. User Profile Extraction
|
|
105
|
+
```bash
|
|
106
|
+
# Scrape profile metadata by @handle
|
|
107
|
+
python plugins/threads-scraper/cli.py @zuck --profile
|
|
108
|
+
|
|
109
|
+
# Scrape profile by full URL
|
|
110
|
+
python plugins/threads-scraper/cli.py "https://www.threads.net/@mosseri" --profile
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### 3. Creator Threads Feed
|
|
114
|
+
```bash
|
|
115
|
+
# Scrape latest 15 threads from a creator
|
|
116
|
+
python plugins/threads-scraper/cli.py @zuck --feed --limit 15
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### 4. Single Thread Discussion
|
|
120
|
+
```bash
|
|
121
|
+
# Scrape thread post discussion
|
|
122
|
+
python plugins/threads-scraper/cli.py "https://www.threads.net/@zuck/post/C8abc123"
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 5. Media & Video Downloads
|
|
126
|
+
```bash
|
|
127
|
+
# Download video attached to a thread
|
|
128
|
+
python plugins/threads-scraper/cli.py "https://www.threads.net/@zuck/post/C8abc123" --download-video
|
|
129
|
+
|
|
130
|
+
# Download video with thumbnail in 720p HD
|
|
131
|
+
python plugins/threads-scraper/cli.py "https://www.threads.net/@user/post/xyz" --download-video --download-thumb -q 720p
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## ๐ Rate Limiting & Safety Rails
|
|
137
|
+
|
|
138
|
+
- **Dynamic Token Extraction**: Automatically scrapes the dynamic `LSD` token from public HTML on demand with local regex fallbacks.
|
|
139
|
+
- **RateLimiter**: Integrated with `plugins/shared/session_manager.py` enforcing a default pacing of 2.0โ4.0 seconds between requests and a 100 requests/hour ceiling.
|