| 1 | """LinkedIn post search via ScrapeCreators API. |
| 2 | |
| 3 | Searches public LinkedIn posts by keyword using the ScrapeCreators |
| 4 | /v1/linkedin/search/posts endpoint, which uses Google-indexed LinkedIn |
| 5 | content to bypass auth requirements. |
| 6 | |
| 7 | Requires SCRAPECREATORS_API_KEY environment variable. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import datetime |
| 13 | import hashlib |
| 14 | import json |
| 15 | import re |
| 16 | import time |
| 17 | from typing import Any, Dict, List |
| 18 | from urllib.parse import unquote, urlsplit |
| 19 | |
| 20 | from . import auth_safety, http, log |
| 21 | |
| 22 | SC_BASE = "https://api.scrapecreators.com/v1/linkedin" |
| 23 | |
| 24 | |
| 25 | def _sc_base() -> str: |
| 26 | if SC_BASE != "https://api.scrapecreators.com/v1/linkedin": |
| 27 | return SC_BASE |
| 28 | from . import env |
| 29 | return f"{env.get_scrapecreators_base_url()}/v1/linkedin" |
| 30 | |
| 31 | DEPTH_CONFIG: dict[str, dict[str, Any]] = { |
| 32 | "quick": {"date_posted": "last-week", "max_results": 10}, |
| 33 | "default": {"date_posted": "last-month", "max_results": 20}, |
| 34 | "deep": {"date_posted": "last-month", "max_results": 30}, |
| 35 | } |
| 36 | |
| 37 | # The upstream endpoint only accepts these coarse buckets. Anything else is a |
| 38 | # hard 400, so an arbitrary day count has to be widened to the smallest bucket |
| 39 | # that still covers it; the caller's real from_date/to_date window is then |
| 40 | # enforced downstream by normalize.filter_by_date_range(). |
| 41 | DATE_POSTED_BUCKETS: tuple[tuple[int, str], ...] = ( |
| 42 | (1, "last-day"), |
| 43 | (7, "last-week"), |
| 44 | (31, "last-month"), |
| 45 | (366, "last-year"), |
| 46 | ) |
| 47 | |
| 48 | # This endpoint returns HTTP 404 with {"message": "No posts found"} for a query |
| 49 | # that simply matched nothing. That is an empty result, not a failure: treating |
| 50 | # it as an error marks a whole run partial and hides a legitimate null behind |
| 51 | # what looks like an outage. |
| 52 | EMPTY_RESULT_STATUS = 404 |
| 53 | |
| 54 | |
| 55 | def _is_no_posts_found_404(exc: http.HTTPError) -> bool: |
| 56 | """Recognize ScrapeCreators' documented empty-search 404, not arbitrary 404s.""" |
| 57 | if exc.status_code != EMPTY_RESULT_STATUS or not isinstance(exc.body, str): |
| 58 | return False |
| 59 | body = exc.body.strip() |
| 60 | if not body: |
| 61 | return False |
| 62 | try: |
| 63 | payload = json.loads(body) |
| 64 | except ValueError: |
| 65 | return False |
| 66 | if not isinstance(payload, dict): |
| 67 | return False |
| 68 | for key in ("message", "error", "detail"): |
| 69 | val = payload.get(key) |
| 70 | if isinstance(val, str) and "no posts found" in val.lower(): |
| 71 | return True |
| 72 | return False |
| 73 | |
| 74 | # Each cursor page returns ~10 posts; this bounds a runaway pagination loop. |
| 75 | MAX_PAGES = 10 |
| 76 | |
| 77 | # Consecutive all-duplicate pages tolerated before a bucket is abandoned. The |
| 78 | # covering bucket's first page routinely repeats the narrow bucket's top hits, |
| 79 | # so breaking on the first zero-add page would skip the older tail the second |
| 80 | # bucket exists to fetch. |
| 81 | MAX_EMPTY_ADD_PAGES = 3 |
| 82 | |
| 83 | # Whole-call wall-clock budget. Pagination bounds the request COUNT, not time: |
| 84 | # 2 buckets x MAX_PAGES pages x (30s timeout + retry) is ~10 minutes against a |
| 85 | # slow-but-alive endpoint, with no error to attribute the stall to. Each request |
| 86 | # is additionally clamped to the remaining budget so the bound actually holds. |
| 87 | SEARCH_BUDGET_SECONDS = 120.0 |
| 88 | PAGE_TIMEOUT = 30.0 |
| 89 | MIN_PAGE_TIMEOUT = 5.0 |
| 90 | |
| 91 | # Endpoint-scoped failures. These are properties of the credential or the |
| 92 | # account, not of one bucket, so retrying the next bucket only wastes a call |
| 93 | # and — for 429 — deepens the rate limit already being hit. |
| 94 | FATAL_STATUS_CODES = frozenset({401, 403, 429}) |
| 95 | |
| 96 | |
| 97 | def _log(msg: str) -> None: |
| 98 | log.source_log("LinkedIn", msg, tty_only=False) |
| 99 | |
| 100 | |
| 101 | def _coerce_date(raw: Any) -> datetime.date | None: |
| 102 | """Parse a YYYY-MM-DD date, tolerating a full ISO timestamp.""" |
| 103 | try: |
| 104 | return datetime.date.fromisoformat(str(raw)[:10]) |
| 105 | except (TypeError, ValueError): |
| 106 | return None |
| 107 | |
| 108 | |
| 109 | def _buckets_for_window( |
| 110 | from_date: str, |
| 111 | to_date: str, |
| 112 | fallback: str, |
| 113 | today: datetime.date | None = None, |
| 114 | ) -> List[str]: |
| 115 | """Buckets to query for a window, narrowest first. |
| 116 | |
| 117 | Two properties of the upstream endpoint drive this: |
| 118 | |
| 119 | 1. Buckets are relative to NOW, not to the requested window. So the bucket |
| 120 | has to be sized by how OLD the requested window is (today - from_date), |
| 121 | never by its span. Sizing by span would send a 31-day window from two |
| 122 | years ago to 'last-month', which cannot contain a single matching post. |
| 123 | 2. Results inside a bucket are relevance-ranked, not recency-ranked, so a |
| 124 | widened bucket does NOT contain the narrower one's yield: 'last-year' |
| 125 | for a 90-day window returned 30 posts spread across a full year, only 4 |
| 126 | inside the window. So query the narrow bucket for dense recent coverage |
| 127 | AND the covering bucket for the older tail, then union them. |
| 128 | |
| 129 | The caller's exact window is still enforced downstream by |
| 130 | filter_by_date_range(); these buckets only have to COVER it. |
| 131 | """ |
| 132 | start = _coerce_date(from_date) |
| 133 | end = _coerce_date(to_date) |
| 134 | if start is None or end is None: |
| 135 | _log(f"Unparseable window ({from_date!r}..{to_date!r}), using {fallback}") |
| 136 | return [fallback] |
| 137 | if end < start: |
| 138 | _log(f"Inverted window ({from_date}..{to_date}), using {fallback}") |
| 139 | return [fallback] |
| 140 | |
| 141 | today = today or datetime.date.today() |
| 142 | # Age of the OLDEST requested post, which is what the bucket must reach |
| 143 | # back to. +1 because the window is inclusive of from_date. |
| 144 | age_days = (today - start).days + 1 |
| 145 | if age_days < 0: |
| 146 | _log(f"Window starts in the future ({from_date}), using {fallback}") |
| 147 | return [fallback] |
| 148 | |
| 149 | widest_limit, widest_bucket = DATE_POSTED_BUCKETS[-1] |
| 150 | covering = widest_bucket |
| 151 | for limit, bucket in DATE_POSTED_BUCKETS: |
| 152 | if age_days <= limit: |
| 153 | covering = bucket |
| 154 | break |
| 155 | else: |
| 156 | _log( |
| 157 | f"Window reaches back {age_days}d but the widest bucket is " |
| 158 | f"{widest_bucket} ({widest_limit}d) — older results are unreachable" |
| 159 | ) |
| 160 | |
| 161 | buckets = [covering] |
| 162 | # Backfill the dense recent block that the wider bucket skips over. |
| 163 | for _, bucket in DATE_POSTED_BUCKETS: |
| 164 | if bucket == covering: |
| 165 | break |
| 166 | if bucket not in buckets: |
| 167 | buckets.insert(-1, bucket) |
| 168 | # Only the immediately-narrower bucket is worth the extra calls. |
| 169 | return buckets[-2:] |
| 170 | |
| 171 | |
| 172 | def _dedupe_key(post: Dict[str, Any]) -> str: |
| 173 | """Stable identity for a post. |
| 174 | |
| 175 | Falls back to a content fingerprint when no identifier is present. Without |
| 176 | it, keyless posts are never deduped, so the union returns them once per |
| 177 | bucket AND a repeating cursor never trips the all-duplicates guard. |
| 178 | """ |
| 179 | for field in ("url", "postUrl", "post_url", "urn", "id", "postId"): |
| 180 | val = post.get(field) |
| 181 | if val: |
| 182 | return str(val) |
| 183 | body = str(post.get("description") or post.get("text") or "") |
| 184 | author = str(post.get("author") or "") |
| 185 | if not body and not author: |
| 186 | return "" |
| 187 | return "sha1:" + hashlib.sha1(f"{author}\x00{body}".encode()).hexdigest() |
| 188 | |
| 189 | |
| 190 | def search_linkedin( |
| 191 | topic: str, |
| 192 | from_date: str, |
| 193 | to_date: str, |
| 194 | depth: str = "default", |
| 195 | token: str = "", |
| 196 | ) -> Dict[str, Any]: |
| 197 | """Search LinkedIn posts via ScrapeCreators API. |
| 198 | |
| 199 | Args: |
| 200 | topic: Search query / topic string. |
| 201 | from_date: Window start date (YYYY-MM-DD) — sets the date_posted bucket. |
| 202 | to_date: Window end date (YYYY-MM-DD). |
| 203 | depth: Retrieval profile — 'quick', 'default', or 'deep'. |
| 204 | token: ScrapeCreators API key. |
| 205 | |
| 206 | Returns: |
| 207 | Dict with a 'posts' list of raw post dicts. |
| 208 | """ |
| 209 | raw_token = token |
| 210 | clean_token, token_err = auth_safety.normalize_header_token(raw_token) |
| 211 | if token_err: |
| 212 | _log(f"Search failed: {token_err}") |
| 213 | return {"posts": [], "error": token_err} |
| 214 | if not clean_token: |
| 215 | _log("No SCRAPECREATORS_API_KEY — skipping") |
| 216 | return {"posts": []} |
| 217 | |
| 218 | cfg = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 219 | buckets = _buckets_for_window(from_date, to_date, cfg["date_posted"]) |
| 220 | max_results = cfg["max_results"] |
| 221 | query = topic.strip() |
| 222 | if not query: |
| 223 | _log("Empty query — skipping") |
| 224 | return {"posts": []} |
| 225 | |
| 226 | # max_results bounds the RETURNED collection, not each retrieval lane, so |
| 227 | # split it across buckets rather than granting each the full budget. |
| 228 | quota = max(1, -(-max_results // len(buckets))) |
| 229 | deadline = time.monotonic() + SEARCH_BUDGET_SECONDS |
| 230 | |
| 231 | _log( |
| 232 | f"Searching for '{query}' (date_posted={','.join(buckets)}, " |
| 233 | f"max_results={max_results}, quota/window={quota})" |
| 234 | ) |
| 235 | |
| 236 | posts: List[Dict[str, Any]] = [] |
| 237 | seen: set[str] = set() |
| 238 | errors: List[str] = [] |
| 239 | fatal = False |
| 240 | |
| 241 | for date_posted in buckets: |
| 242 | if fatal or len(posts) >= max_results: |
| 243 | break |
| 244 | |
| 245 | bucket_count = 0 |
| 246 | pages = 0 |
| 247 | empty_adds = 0 |
| 248 | cursor: Any = None |
| 249 | prev_cursor: Any = None |
| 250 | stop = "pages exhausted" |
| 251 | |
| 252 | for _ in range(MAX_PAGES): |
| 253 | remaining = deadline - time.monotonic() |
| 254 | if remaining <= 0: |
| 255 | stop = "wall-clock budget exceeded" |
| 256 | errors.append(f"{date_posted}: search budget of {SEARCH_BUDGET_SECONDS}s exceeded") |
| 257 | break |
| 258 | |
| 259 | # Clamp the request to what is left of the budget, and drop the |
| 260 | # retry when there is not room for one. Checking the deadline only |
| 261 | # BETWEEN requests does not bound the call: a request starting a |
| 262 | # second before the deadline could still run its full |
| 263 | # timeout-times-retries budget past it. |
| 264 | page_timeout = max(MIN_PAGE_TIMEOUT, min(PAGE_TIMEOUT, remaining)) |
| 265 | page_retries = 2 if remaining > (page_timeout * 2 + 2) else 1 |
| 266 | |
| 267 | params: Dict[str, Any] = {"query": query, "date_posted": date_posted} |
| 268 | if cursor: |
| 269 | params["cursor"] = cursor |
| 270 | local_failures: List[http.HTTPError] = [] |
| 271 | try: |
| 272 | with http.capture_failures() as local_failures: |
| 273 | response = http.get( |
| 274 | f"{_sc_base()}/search/posts", |
| 275 | params=params, |
| 276 | headers=http.scrapecreators_headers(clean_token), |
| 277 | timeout=page_timeout, |
| 278 | retries=page_retries, |
| 279 | ) |
| 280 | except http.HTTPError as exc: |
| 281 | if _is_no_posts_found_404(exc): |
| 282 | # "No posts found" — a legitimate empty result, not a |
| 283 | # failure. Keep it out of the outer failure sink so an |
| 284 | # empty search does not brand LinkedIn as ERROR. |
| 285 | stop = "no posts found" |
| 286 | break |
| 287 | for failure in (local_failures or [exc]): |
| 288 | http._record_failure(failure) |
| 289 | safe_err = auth_safety.scrub_secrets(str(exc), (raw_token, clean_token)) |
| 290 | _log(f"Search failed (HTTP {exc.status_code}, {date_posted}): {safe_err}") |
| 291 | errors.append(f"{date_posted}: {safe_err}") |
| 292 | stop = f"HTTP {exc.status_code}" |
| 293 | if exc.status_code in FATAL_STATUS_CODES: |
| 294 | # Credential- or account-scoped: the next bucket would fail |
| 295 | # identically, and retrying a 429 deepens the rate limit. |
| 296 | fatal = True |
| 297 | break |
| 298 | except Exception as exc: |
| 299 | for failure in local_failures: |
| 300 | http._record_failure(failure) |
| 301 | safe_err = auth_safety.scrub_secrets(str(exc), (raw_token, clean_token)) |
| 302 | _log(f"Search failed ({date_posted}): {type(exc).__name__}: {safe_err}") |
| 303 | errors.append(f"{date_posted}: {type(exc).__name__}: {safe_err}") |
| 304 | stop = type(exc).__name__ |
| 305 | fatal = True |
| 306 | break |
| 307 | |
| 308 | pages += 1 |
| 309 | page = _extract_posts(response) |
| 310 | if not page: |
| 311 | stop = "empty page" |
| 312 | break |
| 313 | |
| 314 | added = 0 |
| 315 | for post in page: |
| 316 | if len(posts) >= max_results: |
| 317 | break |
| 318 | key = _dedupe_key(post) |
| 319 | if key and key in seen: |
| 320 | continue |
| 321 | if key: |
| 322 | seen.add(key) |
| 323 | posts.append(post) |
| 324 | added += 1 |
| 325 | bucket_count += 1 |
| 326 | |
| 327 | if len(posts) >= max_results: |
| 328 | stop = "max_results reached" |
| 329 | break |
| 330 | if bucket_count >= quota: |
| 331 | stop = "window quota reached" |
| 332 | break |
| 333 | |
| 334 | # An all-duplicate page is expected where buckets overlap; only a |
| 335 | # run of them means the cursor has stopped yielding anything new. |
| 336 | empty_adds = empty_adds + 1 if added == 0 else 0 |
| 337 | if empty_adds >= MAX_EMPTY_ADD_PAGES: |
| 338 | stop = f"{empty_adds} consecutive all-duplicate pages" |
| 339 | break |
| 340 | |
| 341 | raw_cursor = response.get("cursor") if isinstance(response, dict) else None |
| 342 | cursor = raw_cursor if isinstance(raw_cursor, (str, int)) else None |
| 343 | if not cursor: |
| 344 | stop = "no cursor" |
| 345 | break |
| 346 | if cursor == prev_cursor: |
| 347 | stop = "cursor stopped advancing" |
| 348 | break |
| 349 | prev_cursor = cursor |
| 350 | |
| 351 | _log(f" {date_posted}: {bucket_count} posts over {pages} page(s), stopped: {stop}") |
| 352 | |
| 353 | if not posts and errors: |
| 354 | return {"posts": [], "error": errors[0]} |
| 355 | |
| 356 | result: Dict[str, Any] = {"posts": posts} |
| 357 | if errors: |
| 358 | # A window that failed after another succeeded must not read as a |
| 359 | # complete result — downstream would treat thin coverage as a finding |
| 360 | # about LinkedIn rather than about the request that never landed. |
| 361 | result["partial"] = True |
| 362 | result["error"] = errors[0] |
| 363 | _log(f"PARTIAL — {len(errors)} window/page failure(s); first: {errors[0]}") |
| 364 | |
| 365 | _log(f"Found {len(posts)} posts across {len(buckets)} window(s)") |
| 366 | return result |
| 367 | |
| 368 | |
| 369 | def _extract_posts(response: Any) -> List[Dict[str, Any]]: |
| 370 | """Extract the posts list from various possible response shapes.""" |
| 371 | if not isinstance(response, dict): |
| 372 | return [] |
| 373 | for key in ("posts", "items", "data", "results"): |
| 374 | val = response.get(key) |
| 375 | if isinstance(val, list): |
| 376 | return val |
| 377 | return [] |
| 378 | |
| 379 | |
| 380 | def _parse_date(raw: Any) -> str | None: |
| 381 | """Extract a YYYY-MM-DD string from various date formats.""" |
| 382 | if not raw: |
| 383 | return None |
| 384 | s = str(raw).strip() |
| 385 | m = re.search(r"(\d{4}-\d{2}-\d{2})", s) |
| 386 | if m: |
| 387 | return m.group(1) |
| 388 | return None |
| 389 | |
| 390 | |
| 391 | def _int_field(post: dict[str, Any], *keys: str) -> int: |
| 392 | """Return the first present integer field from a post dict.""" |
| 393 | for key in keys: |
| 394 | val = post.get(key) |
| 395 | if val is not None: |
| 396 | try: |
| 397 | return int(val) |
| 398 | except (TypeError, ValueError): |
| 399 | pass |
| 400 | return 0 |
| 401 | |
| 402 | |
| 403 | def _is_article(url: str) -> bool: |
| 404 | """A LinkedIn long-form article (Pulse) lives under a /pulse/ URL. |
| 405 | |
| 406 | Articles are higher-signal than ordinary posts — someone who wrote a |
| 407 | full article on a topic is a stronger source than someone who dashed off |
| 408 | a status update. |
| 409 | """ |
| 410 | return "/pulse/" in (url or "").lower() |
| 411 | |
| 412 | |
| 413 | # Relevance hints: articles outrank ordinary posts at rerank time. |
| 414 | _ARTICLE_RELEVANCE = 0.9 |
| 415 | _POST_RELEVANCE = 0.5 |
| 416 | |
| 417 | |
| 418 | def parse_linkedin_response( |
| 419 | result: Dict[str, Any], |
| 420 | from_date: str | None = None, |
| 421 | to_date: str | None = None, |
| 422 | ) -> List[Dict[str, Any]]: |
| 423 | """Parse ScrapeCreators LinkedIn response into engine-compatible item dicts. |
| 424 | |
| 425 | Each returned dict must be normalizable by normalize._normalize_linkedin. |
| 426 | |
| 427 | If from_date/to_date are given, applies the same hard date-range filter |
| 428 | used by instagram.search_and_enrich: drop items outside the window, but |
| 429 | fall back to keeping everything if the filter would otherwise empty the |
| 430 | result (SC doesn't always return a usable date per post). |
| 431 | """ |
| 432 | posts = result.get("posts") or [] |
| 433 | items: List[Dict[str, Any]] = [] |
| 434 | |
| 435 | for i, post in enumerate(posts): |
| 436 | if not isinstance(post, dict): |
| 437 | continue |
| 438 | |
| 439 | # The live ScrapeCreators post object carries the body in `description` |
| 440 | # and the timestamp in `datePublished`. The other keys are tolerated |
| 441 | # fallbacks for shape drift / alternate endpoints. |
| 442 | text = str( |
| 443 | post.get("description") |
| 444 | or post.get("text") |
| 445 | or post.get("content") |
| 446 | or post.get("body") |
| 447 | or "" |
| 448 | ).strip() |
| 449 | if not text: |
| 450 | continue |
| 451 | |
| 452 | author_raw = ( |
| 453 | post.get("author") |
| 454 | or post.get("authorName") |
| 455 | or post.get("author_name") |
| 456 | or "" |
| 457 | ) |
| 458 | author_url = "" |
| 459 | if isinstance(author_raw, dict): |
| 460 | author = str( |
| 461 | author_raw.get("name") or author_raw.get("full_name") or "" |
| 462 | ).strip() |
| 463 | candidate_author_url = str(author_raw.get("url") or author_raw.get("link") or "").strip() |
| 464 | if _is_valid_linkedin_profile_url(candidate_author_url): |
| 465 | author_url = candidate_author_url |
| 466 | else: |
| 467 | author = str(author_raw).strip() |
| 468 | |
| 469 | url = str( |
| 470 | post.get("url") or post.get("postUrl") or post.get("post_url") or "" |
| 471 | ).strip() |
| 472 | |
| 473 | post_id = str( |
| 474 | post.get("urn") or post.get("id") or post.get("postId") or f"LI{i + 1}" |
| 475 | ) |
| 476 | |
| 477 | date_raw = ( |
| 478 | post.get("datePublished") |
| 479 | or post.get("date") |
| 480 | or post.get("postedAt") |
| 481 | or post.get("posted_at") |
| 482 | or post.get("createdAt") |
| 483 | or post.get("created_at") |
| 484 | ) |
| 485 | date = _parse_date(date_raw) |
| 486 | |
| 487 | likes = _int_field(post, "likes", "likesCount", "likes_count", "numLikes", "likeCount") |
| 488 | comments = _int_field(post, "comments", "commentsCount", "comments_count", "numComments", "commentCount") |
| 489 | reposts = _int_field(post, "reposts", "repostsCount", "shares", "shareCount", "reshares") |
| 490 | |
| 491 | is_article = _is_article(url) |
| 492 | items.append({ |
| 493 | "id": post_id, |
| 494 | "text": text, |
| 495 | "url": url, |
| 496 | "author": author, |
| 497 | "author_url": author_url, |
| 498 | "date": date, |
| 499 | "engagement": { |
| 500 | "likes": likes, |
| 501 | "comments": comments, |
| 502 | "reposts": reposts, |
| 503 | }, |
| 504 | "relevance": _ARTICLE_RELEVANCE if is_article else _POST_RELEVANCE, |
| 505 | "is_article": is_article, |
| 506 | }) |
| 507 | |
| 508 | if from_date and to_date: |
| 509 | in_range = [i for i in items if i["date"] and from_date <= i["date"] <= to_date] |
| 510 | out_of_range = len(items) - len(in_range) |
| 511 | if in_range: |
| 512 | items = in_range |
| 513 | if out_of_range: |
| 514 | _log(f"Filtered {out_of_range} posts outside date range") |
| 515 | elif items: |
| 516 | _log(f"No posts within date range, keeping all {len(items)}") |
| 517 | |
| 518 | return items |
| 519 | |
| 520 | |
| 521 | # --- Article enrichment --------------------------------------------------- |
| 522 | # |
| 523 | # LinkedIn articles (Pulse long-form) never appear in /search/posts results — |
| 524 | # every search hit is a /posts/ status update. Articles live only on the |
| 525 | # author's profile, under `articles[]`. To honor "an article is high signal" |
| 526 | # we run a bounded enrichment lane: when a returned post's author name matches |
| 527 | # the topic (i.e. this is a person topic and we already hold their profile |
| 528 | # URL), make ONE profile call and surface their articles as high-signal items. |
| 529 | |
| 530 | |
| 531 | def _normalize_name(s: str) -> str: |
| 532 | """Lowercase, strip punctuation, collapse whitespace — for name matching.""" |
| 533 | return re.sub(r"[^a-z0-9]+", " ", (s or "").lower()).strip() |
| 534 | |
| 535 | |
| 536 | def _token_run(needle: List[str], haystack: List[str]) -> bool: |
| 537 | """True if `needle` appears as a contiguous run of whole tokens in `haystack`. |
| 538 | |
| 539 | Token-level (not substring) so "ai" never matches inside "daisuke" — matching |
| 540 | is on word boundaries. Equality is the n == len(haystack) case. |
| 541 | """ |
| 542 | n = len(needle) |
| 543 | if n == 0 or n > len(haystack): |
| 544 | return False |
| 545 | return any(haystack[i : i + n] == needle for i in range(len(haystack) - n + 1)) |
| 546 | |
| 547 | |
| 548 | def _is_valid_linkedin_profile_url(url: Any) -> bool: |
| 549 | """Return True only for https://[*.]linkedin.com/in/<slug> URLs without credentials.""" |
| 550 | if not isinstance(url, str): |
| 551 | return False |
| 552 | text = url.strip() |
| 553 | if not text or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text): |
| 554 | return False |
| 555 | try: |
| 556 | parts = urlsplit(text) |
| 557 | port = parts.port |
| 558 | except ValueError: |
| 559 | return False |
| 560 | if parts.scheme.lower() != "https": |
| 561 | return False |
| 562 | if parts.username is not None or parts.password is not None: |
| 563 | return False |
| 564 | if "\\" in parts.netloc or port not in (None, 443): |
| 565 | return False |
| 566 | host = (parts.hostname or "").removesuffix(".").lower() |
| 567 | if not (host == "linkedin.com" or host.endswith(".linkedin.com")): |
| 568 | return False |
| 569 | if host.startswith(".") or ".." in host: |
| 570 | return False |
| 571 | path = parts.path or "" |
| 572 | if not path.lower().startswith("/in/"): |
| 573 | return False |
| 574 | raw_slug = path[4:].removesuffix("/") |
| 575 | slug = unquote(raw_slug) |
| 576 | if ( |
| 577 | not raw_slug |
| 578 | or not slug |
| 579 | or slug in (".", "..") |
| 580 | or "/" in raw_slug |
| 581 | or "/" in slug |
| 582 | or "\\" in slug |
| 583 | or any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in slug) |
| 584 | ): |
| 585 | return False |
| 586 | return True |
| 587 | |
| 588 | |
| 589 | def _best_author_match(items: List[Dict[str, Any]], topic: str) -> str: |
| 590 | """Return the profile URL of the post author whose name matches the topic. |
| 591 | |
| 592 | Person-topic detection without a global predicate: when a returned post's |
| 593 | author has a multi-word name that the topic clearly refers to, treat the |
| 594 | topic as being about that person and return their profile URL. Matching is |
| 595 | on whole-token runs (the author's full name appears in the topic, or vice |
| 596 | versa), and the topic itself must be at least two tokens — so single-word |
| 597 | keyword topics ("AI", "Tesla") and short phrases never enrich, and a topic |
| 598 | token can't accidentally match inside an unrelated author's name. |
| 599 | """ |
| 600 | topic_tokens = _normalize_name(topic).split() |
| 601 | if len(topic_tokens) < 2: |
| 602 | return "" |
| 603 | for item in items: |
| 604 | name_tokens = _normalize_name(item.get("author", "")).split() |
| 605 | url = (item.get("author_url") or "").strip() |
| 606 | if not url or not _is_valid_linkedin_profile_url(url) or len(name_tokens) < 2: |
| 607 | continue |
| 608 | if _token_run(name_tokens, topic_tokens) or _token_run(topic_tokens, name_tokens): |
| 609 | return url |
| 610 | return "" |
| 611 | |
| 612 | |
| 613 | def search_profile(profile_url: str, token: str) -> Dict[str, Any]: |
| 614 | """Fetch a LinkedIn profile (incl. `articles[]`) via ScrapeCreators.""" |
| 615 | raw_token = token |
| 616 | clean_token, token_err = auth_safety.normalize_header_token(raw_token) |
| 617 | if token_err: |
| 618 | _log(f"Profile fetch failed: {token_err}") |
| 619 | return {} |
| 620 | if not clean_token or not _is_valid_linkedin_profile_url(profile_url): |
| 621 | if profile_url and clean_token: |
| 622 | _log("Profile fetch refused: invalid LinkedIn profile URL") |
| 623 | return {} |
| 624 | clean_url = profile_url.strip() |
| 625 | try: |
| 626 | with http.capture_failures(): |
| 627 | response = http.get( |
| 628 | f"{_sc_base()}/profile", |
| 629 | params={"url": clean_url}, |
| 630 | headers=http.scrapecreators_headers(clean_token), |
| 631 | timeout=30, |
| 632 | retries=2, |
| 633 | ) |
| 634 | except http.HTTPError as exc: |
| 635 | safe_err = auth_safety.scrub_secrets(str(exc), (raw_token, clean_token)) |
| 636 | _log(f"Profile fetch failed (HTTP {exc.status_code}): {safe_err}") |
| 637 | return {} |
| 638 | except Exception as exc: |
| 639 | safe_err = auth_safety.scrub_secrets(str(exc), (raw_token, clean_token)) |
| 640 | _log(f"Profile fetch failed: {type(exc).__name__}: {safe_err}") |
| 641 | return {} |
| 642 | return response if isinstance(response, dict) else {} |
| 643 | |
| 644 | |
| 645 | def parse_profile_articles( |
| 646 | profile: Dict[str, Any], |
| 647 | from_date: str | None = None, |
| 648 | to_date: str | None = None, |
| 649 | ) -> List[Dict[str, Any]]: |
| 650 | """Map a profile's `articles[]` into high-signal engine item dicts.""" |
| 651 | articles = profile.get("articles") or [] |
| 652 | author = str(profile.get("name") or "").strip() |
| 653 | items: List[Dict[str, Any]] = [] |
| 654 | |
| 655 | for i, art in enumerate(articles): |
| 656 | if not isinstance(art, dict): |
| 657 | continue |
| 658 | headline = str(art.get("headline") or art.get("title") or "").strip() |
| 659 | if not headline: |
| 660 | continue |
| 661 | url = str(art.get("url") or art.get("link") or "").strip() |
| 662 | date = _parse_date(art.get("datePublished") or art.get("date")) |
| 663 | items.append({ |
| 664 | "id": str(art.get("id") or f"LIA{i + 1}"), |
| 665 | "text": headline, |
| 666 | "url": url, |
| 667 | "author": author, |
| 668 | "date": date, |
| 669 | "engagement": {}, |
| 670 | "relevance": _ARTICLE_RELEVANCE, |
| 671 | "is_article": True, |
| 672 | }) |
| 673 | |
| 674 | if from_date and to_date: |
| 675 | in_range = [i for i in items if i["date"] and from_date <= i["date"] <= to_date] |
| 676 | if in_range: |
| 677 | items = in_range |
| 678 | return items |
| 679 | |
| 680 | |
| 681 | def enrich_articles( |
| 682 | items: List[Dict[str, Any]], |
| 683 | topic: str, |
| 684 | token: str, |
| 685 | from_date: str | None = None, |
| 686 | to_date: str | None = None, |
| 687 | ) -> List[Dict[str, Any]]: |
| 688 | """Surface a person's LinkedIn articles as high-signal items. |
| 689 | |
| 690 | Bounded: fires only on person topics (a returned post author matches the |
| 691 | topic) and makes at most ONE profile API call. No-ops gracefully when |
| 692 | there's no match, no token, no profile, or no articles. |
| 693 | """ |
| 694 | clean_token, token_err = auth_safety.normalize_header_token(token) |
| 695 | if token_err or not clean_token: |
| 696 | return [] |
| 697 | profile_url = _best_author_match(items, topic) |
| 698 | if not profile_url: |
| 699 | return [] |
| 700 | _log(f"Person topic — enriching articles from {profile_url}") |
| 701 | profile = search_profile(profile_url, clean_token) |
| 702 | if not profile: |
| 703 | return [] |
| 704 | articles = parse_profile_articles(profile, from_date=from_date, to_date=to_date) |
| 705 | if articles: |
| 706 | _log(f"Found {len(articles)} article(s)") |
| 707 | return articles |
| 708 | |
| 709 | |
| 710 | # --- Person-run profile read ---------------------------------------------- |
| 711 | # |
| 712 | # A person run without a Deepline key can read the person's profile here, |
| 713 | # under the LinkedIn consent rule (the caller checks it). This endpoint masks |
| 714 | # job titles, so the parse keeps the person's own posts and listed links and |
| 715 | # never reports a role: a masked title must not read as a current position. |
| 716 | |
| 717 | PROFILE_TIMEOUT = 30.0 |
| 718 | # Recent-post entries whose activity says someone else posted them. |
| 719 | _OTHERS_ACTIVITY = ("liked by", "commented on", "reacted") |
| 720 | |
| 721 | |
| 722 | def read_profile( |
| 723 | profile_url: str, token: str, *, deadline_monotonic: float | None = None, |
| 724 | ) -> Dict[str, Any]: |
| 725 | """Read one profile for a person run. |
| 726 | |
| 727 | Returns ``{"status", "data", "detail"}``: status "ok" with |
| 728 | ``parse_person_profile`` output, else "failed" (never raises). |
| 729 | """ |
| 730 | clean_token, token_err = auth_safety.normalize_header_token(token) |
| 731 | if token_err or not clean_token: |
| 732 | return {"status": "failed", "data": None, "detail": token_err or "missing API key"} |
| 733 | if not _is_valid_linkedin_profile_url(profile_url): |
| 734 | _log("Person profile read refused: invalid LinkedIn profile URL") |
| 735 | return {"status": "failed", "data": None, "detail": "invalid LinkedIn profile URL"} |
| 736 | clean_url = profile_url.strip() |
| 737 | timeout = PROFILE_TIMEOUT |
| 738 | if deadline_monotonic is not None: |
| 739 | timeout = min(timeout, deadline_monotonic - time.monotonic()) |
| 740 | if timeout < MIN_PAGE_TIMEOUT: |
| 741 | return {"status": "failed", "data": None, "detail": "not enough time left to start"} |
| 742 | try: |
| 743 | response = http.get( |
| 744 | f"{_sc_base()}/profile", |
| 745 | params={"url": clean_url}, |
| 746 | headers=http.scrapecreators_headers(clean_token), |
| 747 | timeout=timeout, |
| 748 | retries=1, |
| 749 | deadline_monotonic=deadline_monotonic, |
| 750 | ) |
| 751 | except http.HTTPError as exc: |
| 752 | _log(f"Person profile read failed (HTTP {exc.status_code})") |
| 753 | return {"status": "failed", "data": None, "detail": f"HTTP {exc.status_code}"} |
| 754 | except Exception as exc: # noqa: BLE001 - a read failure is a status, not a crash |
| 755 | _log(f"Person profile read failed: {type(exc).__name__}") |
| 756 | return {"status": "failed", "data": None, "detail": type(exc).__name__} |
| 757 | if not isinstance(response, dict) or not response or response.get("success") is False: |
| 758 | return {"status": "failed", "data": None, "detail": "unexpected response shape"} |
| 759 | return {"status": "ok", "data": parse_person_profile(response), "detail": ""} |
| 760 | |
| 761 | |
| 762 | def _profile_links(profile: Dict[str, Any]) -> List[str]: |
| 763 | links: List[str] = [] |
| 764 | for key in ("website", "websites", "links"): |
| 765 | raw = profile.get(key) |
| 766 | for entry in raw if isinstance(raw, list) else [raw]: |
| 767 | url = entry.get("url") if isinstance(entry, dict) else entry |
| 768 | url = str(url or "").strip() |
| 769 | if url.startswith(("http://", "https://")) and url not in links: |
| 770 | links.append(url) |
| 771 | return links |
| 772 | |
| 773 | |
| 774 | def parse_person_profile(profile: Dict[str, Any]) -> Dict[str, Any]: |
| 775 | """Posts and links from a ScrapeCreators profile, with no roles. |
| 776 | |
| 777 | ``current_roles`` and ``history`` are always empty: this endpoint masks |
| 778 | titles, so nothing it returns is presented as a position. |
| 779 | """ |
| 780 | posts: List[Dict[str, Any]] = [] |
| 781 | for entry in profile.get("recentPosts") or profile.get("posts") or []: |
| 782 | if not isinstance(entry, dict): |
| 783 | continue |
| 784 | activity = str(entry.get("activityType") or "").strip().lower() |
| 785 | if any(word in activity for word in _OTHERS_ACTIVITY): |
| 786 | continue |
| 787 | url = str(entry.get("link") or entry.get("url") or "").strip() |
| 788 | text = str(entry.get("title") or entry.get("text") or "").strip() |
| 789 | if not url and not text: |
| 790 | continue |
| 791 | posts.append({ |
| 792 | "url": url or None, |
| 793 | "text": text, |
| 794 | "date": _parse_date(entry.get("datePublished") or entry.get("date")), |
| 795 | "is_reshare": "repost" in activity, |
| 796 | }) |
| 797 | location = profile.get("location") |
| 798 | return { |
| 799 | "name": str(profile.get("name") or "").strip(), |
| 800 | "headline": "", |
| 801 | "location": location.strip() if isinstance(location, str) else "", |
| 802 | "about": str(profile.get("about") or "").strip(), |
| 803 | "current_roles": [], |
| 804 | "history": [], |
| 805 | "websites": _profile_links(profile), |
| 806 | "posts": posts, |
| 807 | } |
| 808 |