返回 last30days-skill
phenom.py
1 """Phenom: the careers site's ``/widgets`` search, as its own page calls it.
2
3 The search page embeds ``phApp.ddo`` with ten roles; the same ``refineSearch``
4 query sent to ``/widgets`` answers up to 500 a call, with the board's total
5 in ``totalHits``. The search cannot be sorted by date, so the board is read
6 whole (to the row ceiling) rather than newest first. A role's page embeds its
7 full text under ``jobDetail``.
8 """
9
10 from __future__ import annotations
11
12 import json
13 import re
14 from typing import Any, Callable
15 from urllib.parse import quote, urlparse
16
17 from .. import http, jobs
18 from . import detect
19 from .detect import PROVIDER_PHENOM
20
21 PAGE_SIZE = 500
22 _DDO = re.compile(r"phApp\.ddo\s*=\s*")
23
24
25 def widgets_url(entry: dict[str, Any]) -> str:
26 return f"https://{entry['board']}/widgets"
27
28
29 def search_body(entry: dict[str, Any], offset: int) -> dict[str, Any]:
30 country = entry.get("country") or "global"
31 return {
32 "lang": f"{entry.get('lang') or 'en'}_{country}",
33 "deviceType": "desktop",
34 "country": country,
35 "pageName": "search-results",
36 "ddoKey": "refineSearch",
37 "sortBy": "",
38 "subsearch": "",
39 "from": offset,
40 "jobs": True,
41 "counts": False,
42 "all_fields": [],
43 "size": PAGE_SIZE,
44 "clearAll": False,
45 "jdsource": "facets",
46 "isSliderEnable": False,
47 "pageId": "page20",
48 "siteType": "external",
49 "keywords": "",
50 "global": True,
51 "selected_fields": {},
52 "locationData": {},
53 }
54
55
56 def _safe_base_url(entry: dict[str, Any]) -> str:
57 board = str(entry["board"]).strip().rstrip(".").lower()
58 raw = str(entry.get("base_url") or "").strip()
59 if raw and detect.is_safe_public_url(raw):
60 parsed = urlparse(raw)
61 if (
62 parsed.scheme.lower() == "https"
63 and parsed.port in (None, 443)
64 and detect.page_host(raw) == board
65 and not parsed.query
66 and not parsed.fragment
67 ):
68 path = parsed.path or "/"
69 if not path.startswith("/"):
70 path = "/" + path
71 if not path.endswith("/"):
72 path += "/"
73 return f"https://{board}{path}"
74 return f"https://{board}/"
75
76
77 def parse_listing(payload: Any, entry: dict[str, Any]) -> tuple[list[dict[str, Any]], int]:
78 search = payload.get("refineSearch") if isinstance(payload, dict) else None
79 data = search.get("data") if isinstance(search, dict) else None
80 rows = data.get("jobs") if isinstance(data, dict) else None
81 if not isinstance(rows, list):
82 raise jobs.BoardShapeError("no refineSearch jobs")
83 base = _safe_base_url(entry)
84 items: list[dict[str, Any]] = []
85 for row in rows:
86 if not isinstance(row, dict) or not row.get("title") or not row.get("jobId"):
87 continue
88 ident = str(row["jobId"]).strip()
89 if not ident:
90 continue
91 posted = jobs._date_part(row.get("postedDate"))
92 places = [str(place).strip() for place in row.get("multi_location") or [] if place]
93 teaser = str(row.get("descriptionTeaser") or "").strip()
94 item = jobs._ats_item(
95 provider=PROVIDER_PHENOM,
96 slug=entry["board"],
97 ident=ident,
98 title=str(row["title"]).strip(),
99 url=f"{base}job/{quote(ident, safe='')}",
100 description=teaser,
101 description_blocks=teaser,
102 date=posted,
103 posted_date_true=bool(posted),
104 department=str(row.get("category") or "").strip(),
105 location=str(row.get("location") or row.get("cityStateCountry") or "").strip(),
106 company_name=str(row.get("companyName") or entry.get("name") or "").strip(),
107 whole_posting=True,
108 )
109 if places:
110 item["locations"] = places
111 items.append(item)
112 return items, jobs._reported_total(search, "totalHits")
113
114
115 def read_board(
116 entry: dict[str, Any], *, deadline: float, date_range: tuple[str, str],
117 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
118 """The whole board up to the row ceiling, with the total it reports."""
119
120 def page(offset: int) -> Callable[[float], Any]:
121 body = search_body(entry, offset)
122 url = widgets_url(entry)
123
124 def fetch(http_deadline: float) -> Any:
125 if not detect.is_safe_public_url(url):
126 raise http.HTTPError("Refused non-public URL")
127 return http.post(
128 url, body, headers={"Accept": "application/json"},
129 timeout=jobs.API_TIMEOUT_SECONDS, retries=2, deadline_monotonic=http_deadline,
130 public_only=True, redirect_guard=detect.same_site_redirect_guard(url),
131 )
132
133 return fetch
134
135 return jobs._read_newest_first(
136 page, lambda payload: parse_listing(payload, entry), page_size=PAGE_SIZE,
137 row_ceiling=jobs.COMPANY_BOARD_ROW_CEILING, window_start=date_range[0],
138 deadline=deadline, newest_first=False,
139 )
140
141
142 def page_object(html: str) -> dict[str, Any] | None:
143 """The ``phApp.ddo`` object a Phenom page embeds, or None."""
144 bounded = (html or "")[:detect.MAX_HTML_CHARS]
145 match = _DDO.search(bounded)
146 if not match:
147 return None
148 start = bounded.find("{", match.end())
149 if start < 0:
150 return None
151 try:
152 found, _end = json.JSONDecoder().raw_decode(bounded, start)
153 except (ValueError, RecursionError):
154 return None
155 return found if isinstance(found, dict) else None
156
157
158 def fetch_details(items: list[dict[str, Any]], *, deadline: float) -> tuple[int, int]:
159 """Fill the full text of the given roles from their own pages."""
160
161 def call(item: dict[str, Any]) -> Callable[[float], Any]:
162 url = str(item.get("url") or "")
163 if not detect.is_safe_public_url(url):
164 return lambda _http_deadline: None
165 return lambda http_deadline: jobs.role_page_text(
166 url, timeout=jobs.API_TIMEOUT_SECONDS, deadline_monotonic=http_deadline,
167 redirect_guard=detect.same_site_redirect_guard(url),
168 )
169
170 def text_of(payload: Any) -> tuple[str, str] | None:
171 found = page_object(payload) if isinstance(payload, str) else None
172 detail = (found or {}).get("jobDetail")
173 role = ((detail or {}).get("data") or {}).get("job") if isinstance(detail, dict) else None
174 html = str((role or {}).get("description") or "") if isinstance(role, dict) else ""
175 return (jobs._block_text(html), jobs._clean_html(html)) if html.strip() else None
176
177 return jobs._fill_role_text(items, call, text_of, deadline=deadline)
178
178 lines PYTHON