|
7 | 7 | from __future__ import annotations |
8 | 8 |
|
9 | 9 | import re |
| 10 | +import time |
10 | 11 | from dataclasses import dataclass, field |
11 | 12 | from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence |
12 | 13 |
|
| 14 | +import requests |
| 15 | + |
| 16 | +from .config import ORCID_API_BASE_DEFAULT |
| 17 | + |
13 | 18 | # An ORCID iD is 16 digits in groups of four; the last character may be an X. |
14 | 19 | ORCID_RE = re.compile(r"^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$") |
15 | 20 |
|
@@ -106,3 +111,145 @@ def partition_by_orcid(users: Iterable[MwUser]) -> Dict[str, List[MwUser]]: |
106 | 111 | for user in users: |
107 | 112 | (orcid if user.is_orcid else other).append(user) |
108 | 113 | return {"orcid": orcid, "other": other} |
| 114 | + |
| 115 | + |
| 116 | +class OrcidRateLimitError(RuntimeError): |
| 117 | + """Raised when the ORCID public API keeps returning HTTP 429.""" |
| 118 | + |
| 119 | + |
| 120 | +@dataclass |
| 121 | +class OrcidAffiliation: |
| 122 | + """An employment entry from an ORCID record.""" |
| 123 | + |
| 124 | + organization: str |
| 125 | + ror_id: Optional[str] = None |
| 126 | + department: Optional[str] = None |
| 127 | + role: Optional[str] = None |
| 128 | + |
| 129 | + |
| 130 | +@dataclass |
| 131 | +class OrcidProfile: |
| 132 | + """The subset of a public ORCID record that maps to an OSW User item.""" |
| 133 | + |
| 134 | + orcid_id: str |
| 135 | + given_names: Optional[str] = None |
| 136 | + family_name: Optional[str] = None |
| 137 | + credit_name: Optional[str] = None |
| 138 | + other_names: List[str] = field(default_factory=list) |
| 139 | + emails: List[str] = field(default_factory=list) |
| 140 | + urls: List[str] = field(default_factory=list) |
| 141 | + affiliations: List[OrcidAffiliation] = field(default_factory=list) |
| 142 | + |
| 143 | + @property |
| 144 | + def orcid_uri(self) -> str: |
| 145 | + return f"https://orcid.org/{self.orcid_id}" |
| 146 | + |
| 147 | + @property |
| 148 | + def display_name(self) -> Optional[str]: |
| 149 | + """Best full name: credit name, else given + family, else None.""" |
| 150 | + if self.credit_name: |
| 151 | + return self.credit_name |
| 152 | + parts = [p for p in (self.given_names, self.family_name) if p] |
| 153 | + return " ".join(parts) or None |
| 154 | + |
| 155 | + |
| 156 | +def _value(node: Any, *keys: str) -> Optional[Any]: |
| 157 | + """Safely walk nested dicts, returning None on any missing key.""" |
| 158 | + cur = node |
| 159 | + for key in keys: |
| 160 | + if not isinstance(cur, dict): |
| 161 | + return None |
| 162 | + cur = cur.get(key) |
| 163 | + return cur |
| 164 | + |
| 165 | + |
| 166 | +def _parse_affiliations(activities: Any) -> List[OrcidAffiliation]: |
| 167 | + affiliations: List[OrcidAffiliation] = [] |
| 168 | + groups = _value(activities, "employments", "affiliation-group") or [] |
| 169 | + for group in groups: |
| 170 | + for summary in group.get("summaries") or []: |
| 171 | + emp = summary.get("employment-summary") or {} |
| 172 | + org = emp.get("organization") or {} |
| 173 | + name = org.get("name") |
| 174 | + if not name: |
| 175 | + continue |
| 176 | + ror = None |
| 177 | + disamb = org.get("disambiguated-organization") or {} |
| 178 | + if (disamb.get("disambiguation-source") or "").upper() == "ROR": |
| 179 | + ror = disamb.get("disambiguated-organization-identifier") |
| 180 | + affiliations.append( |
| 181 | + OrcidAffiliation( |
| 182 | + organization=name, |
| 183 | + ror_id=ror, |
| 184 | + department=emp.get("department-name"), |
| 185 | + role=emp.get("role-title"), |
| 186 | + ) |
| 187 | + ) |
| 188 | + return affiliations |
| 189 | + |
| 190 | + |
| 191 | +def parse_orcid_record(data: Dict[str, Any], orcid_id: str) -> OrcidProfile: |
| 192 | + """Parse an ORCID ``/record`` JSON payload into an OrcidProfile (pure).""" |
| 193 | + person = data.get("person") or {} |
| 194 | + other_names = [ |
| 195 | + n.get("content") |
| 196 | + for n in _value(person, "other-names", "other-name") or [] |
| 197 | + if n.get("content") |
| 198 | + ] |
| 199 | + emails = [ |
| 200 | + e.get("email") |
| 201 | + for e in _value(person, "emails", "email") or [] |
| 202 | + if e.get("email") |
| 203 | + ] |
| 204 | + urls = [ |
| 205 | + _value(u, "url", "value") |
| 206 | + for u in _value(person, "researcher-urls", "researcher-url") or [] |
| 207 | + if _value(u, "url", "value") |
| 208 | + ] |
| 209 | + return OrcidProfile( |
| 210 | + orcid_id=orcid_id, |
| 211 | + given_names=_value(person, "name", "given-names", "value"), |
| 212 | + family_name=_value(person, "name", "family-name", "value"), |
| 213 | + credit_name=_value(person, "name", "credit-name", "value"), |
| 214 | + other_names=other_names, |
| 215 | + emails=emails, |
| 216 | + urls=urls, |
| 217 | + affiliations=_parse_affiliations(data.get("activities-summary") or {}), |
| 218 | + ) |
| 219 | + |
| 220 | + |
| 221 | +def fetch_orcid_record( |
| 222 | + orcid_id: str, |
| 223 | + session: Optional[requests.Session] = None, |
| 224 | + base: str = ORCID_API_BASE_DEFAULT, |
| 225 | + timeout: float = 30.0, |
| 226 | + max_retries: int = 2, |
| 227 | + cache: Optional[Dict[str, Optional[OrcidProfile]]] = None, |
| 228 | +) -> Optional[OrcidProfile]: |
| 229 | + """Fetch and parse a public ORCID record. |
| 230 | +
|
| 231 | + Returns None when the record does not exist (HTTP 404). Retries on HTTP 429 |
| 232 | + honoring ``Retry-After`` and raises OrcidRateLimitError if still limited. |
| 233 | + """ |
| 234 | + if cache is not None and orcid_id in cache: |
| 235 | + return cache[orcid_id] |
| 236 | + sess = session or requests.Session() |
| 237 | + url = f"{base}/{orcid_id}/record" |
| 238 | + headers = {"Accept": "application/json"} |
| 239 | + result: Optional[OrcidProfile] = None |
| 240 | + for attempt in range(max_retries + 1): |
| 241 | + resp = sess.get(url, headers=headers, timeout=timeout) |
| 242 | + if resp.status_code == 404: |
| 243 | + result = None |
| 244 | + break |
| 245 | + if resp.status_code == 429: |
| 246 | + if attempt >= max_retries: |
| 247 | + raise OrcidRateLimitError(f"ORCID rate limit for {orcid_id}") |
| 248 | + time.sleep(float(resp.headers.get("Retry-After", 1))) |
| 249 | + continue |
| 250 | + resp.raise_for_status() |
| 251 | + result = parse_orcid_record(resp.json(), orcid_id) |
| 252 | + break |
| 253 | + if cache is not None: |
| 254 | + cache[orcid_id] = result |
| 255 | + return result |
0 commit comments