permtracker 0.3.0__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.
- permtracker/__init__.py +300 -0
- permtracker/cli.py +207 -0
- permtracker-0.3.0.dist-info/METADATA +68 -0
- permtracker-0.3.0.dist-info/RECORD +8 -0
- permtracker-0.3.0.dist-info/WHEEL +5 -0
- permtracker-0.3.0.dist-info/entry_points.txt +2 -0
- permtracker-0.3.0.dist-info/licenses/LICENSE +21 -0
- permtracker-0.3.0.dist-info/top_level.txt +1 -0
permtracker/__init__.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""The PERM Tracker API from Python: a thin client over https://permtracker.app/v1.
|
|
2
|
+
|
|
3
|
+
from permtracker import PermTracker
|
|
4
|
+
pt = PermTracker(api_key="pt_live_...") # or PERMTRACKER_API_KEY
|
|
5
|
+
pt.case("G-100-26045-123456").data["status"]
|
|
6
|
+
|
|
7
|
+
Every method returns an Answer (data, meta, usage). A refusal raises
|
|
8
|
+
PermTrackerError with the API's code, message and retry_after. Standard
|
|
9
|
+
library only. Keys go in the Authorization header, never the address.
|
|
10
|
+
|
|
11
|
+
verify_webhook checks a webhook delivery's signature (Standard Webhooks:
|
|
12
|
+
HMAC-SHA256 over "id.timestamp.body", keyed by the whsec_ secret).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import base64
|
|
18
|
+
import hashlib
|
|
19
|
+
import hmac
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import time
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.parse
|
|
26
|
+
import urllib.request
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from typing import Any, Callable, Optional
|
|
29
|
+
|
|
30
|
+
__all__ = ["PermTracker", "PermTrackerError", "Answer", "CsvExport", "Usage", "verify_webhook", "WEBHOOK_EVENTS",
|
|
31
|
+
"EXPORT_KINDS", "DEFAULT_BASE_URL", "__version__"]
|
|
32
|
+
__version__ = "0.3.0"
|
|
33
|
+
WEBHOOK_EVENTS = ("case.status_changed", "employer.moved", "bulletin.published", "queue.moved", "processing_times.updated")
|
|
34
|
+
EXPORT_KINDS = ("cases", "employers", "law-firms", "occupations")
|
|
35
|
+
DEFAULT_BASE_URL = "https://permtracker.app/v1"
|
|
36
|
+
CASE_RE = re.compile(r"^[A-Z]{1,2}(-[A-Z])?-\d{3}-\d{5}-\d{6}$")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PermTrackerError(Exception):
|
|
40
|
+
"""The API refused, or couldn't be reached. `code` is the API's own."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, status: int, code: str, message: str, retry_after: Optional[int] = None, url: Optional[str] = None):
|
|
43
|
+
super().__init__(message)
|
|
44
|
+
self.status = status
|
|
45
|
+
self.code = code
|
|
46
|
+
self.message = message
|
|
47
|
+
self.retry_after = retry_after
|
|
48
|
+
self.url = url
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Usage:
|
|
53
|
+
per_minute: Optional[int] = None
|
|
54
|
+
remaining_this_minute: Optional[int] = None
|
|
55
|
+
today: Optional[int] = None
|
|
56
|
+
per_day: Optional[int] = None
|
|
57
|
+
month: Optional[int] = None
|
|
58
|
+
per_month: Optional[int] = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class Answer:
|
|
63
|
+
data: Any
|
|
64
|
+
meta: dict = field(default_factory=dict)
|
|
65
|
+
usage: Usage = field(default_factory=Usage)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class CsvExport:
|
|
70
|
+
csv: str
|
|
71
|
+
rows: Optional[int] = None
|
|
72
|
+
cap: Optional[int] = None
|
|
73
|
+
truncated: bool = False
|
|
74
|
+
usage: Usage = field(default_factory=Usage)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _num(headers, name: str, part: int = 0) -> Optional[int]:
|
|
78
|
+
raw = headers.get(name) if headers is not None else None
|
|
79
|
+
if not raw:
|
|
80
|
+
return None
|
|
81
|
+
try:
|
|
82
|
+
return int(str(raw).split("/")[part])
|
|
83
|
+
except (ValueError, IndexError):
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def usage_from(headers) -> Usage:
|
|
88
|
+
return Usage(
|
|
89
|
+
per_minute=_num(headers, "RateLimit-Limit"),
|
|
90
|
+
remaining_this_minute=_num(headers, "RateLimit-Remaining"),
|
|
91
|
+
today=_num(headers, "X-Calls-Today", 0),
|
|
92
|
+
per_day=_num(headers, "X-Calls-Today", 1),
|
|
93
|
+
month=_num(headers, "X-Calls-Month", 0),
|
|
94
|
+
per_month=_num(headers, "X-Calls-Month", 1),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# (status, headers, body bytes) for a request of `method` to `url` with
|
|
99
|
+
# `headers` and `data` (JSON bytes or None), or an exception.
|
|
100
|
+
Transport = Callable[[str, dict, float, str, Optional[bytes]], "tuple[int, Any, bytes]"]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _urllib_transport(url: str, headers: dict, timeout: float, method: str = "GET", data: Optional[bytes] = None):
|
|
104
|
+
req = urllib.request.Request(url, headers=headers, method=method, data=data)
|
|
105
|
+
try:
|
|
106
|
+
with urllib.request.urlopen(req, timeout=timeout) as res: # noqa: S310 - our own https endpoint
|
|
107
|
+
return res.status, res.headers, res.read()
|
|
108
|
+
except urllib.error.HTTPError as err:
|
|
109
|
+
return err.code, err.headers, err.read()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _refusal(status: int, res_headers, parsed) -> PermTrackerError:
|
|
113
|
+
err = ((parsed or {}).get("error") or {}) if isinstance(parsed, dict) else {}
|
|
114
|
+
retry = err.get("retryAfter")
|
|
115
|
+
if retry is None:
|
|
116
|
+
retry = _num(res_headers, "Retry-After")
|
|
117
|
+
return PermTrackerError(status, err.get("code") or f"http_{status}", err.get("message") or f"The API answered {status}.",
|
|
118
|
+
retry, err.get("url"))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _parse(body: bytes):
|
|
122
|
+
try:
|
|
123
|
+
return json.loads(body.decode("utf-8")) if body else None
|
|
124
|
+
except ValueError:
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class PermTracker:
|
|
129
|
+
def __init__(self, api_key: Optional[str] = None, base_url: str = DEFAULT_BASE_URL, timeout: float = 20.0,
|
|
130
|
+
transport: Optional[Transport] = None):
|
|
131
|
+
key = api_key if api_key is not None else os.environ.get("PERMTRACKER_API_KEY")
|
|
132
|
+
self.api_key = key.strip() if key and key.strip() else None
|
|
133
|
+
self.base_url = base_url.rstrip("/")
|
|
134
|
+
self.timeout = timeout
|
|
135
|
+
self._transport = transport or _urllib_transport
|
|
136
|
+
|
|
137
|
+
def _send(self, path: str, query: Optional[dict], needs_key: bool, method: str, payload: Any, accept: str):
|
|
138
|
+
if needs_key and not self.api_key:
|
|
139
|
+
raise PermTrackerError(401, "missing_key", "This call needs an API key. Make one free at permtracker.app, in Settings, under API keys.")
|
|
140
|
+
q = {k: v for k, v in (query or {}).items() if v is not None and v != ""}
|
|
141
|
+
url = self.base_url + path + (("?" + urllib.parse.urlencode(q)) if q else "")
|
|
142
|
+
headers = {"Accept": accept, "User-Agent": f"permtracker-python/{__version__}"}
|
|
143
|
+
if self.api_key:
|
|
144
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
145
|
+
data = None
|
|
146
|
+
if payload is not None:
|
|
147
|
+
headers["Content-Type"] = "application/json"
|
|
148
|
+
data = json.dumps(payload).encode("utf-8")
|
|
149
|
+
try:
|
|
150
|
+
return self._transport(url, headers, self.timeout, method, data)
|
|
151
|
+
except Exception as exc: # noqa: BLE001 - a network failure is the caller's to see
|
|
152
|
+
raise PermTrackerError(0, "network_error", f"Couldn't reach {urllib.parse.urlparse(url).netloc}: {exc}") from exc
|
|
153
|
+
|
|
154
|
+
def request(self, path: str, query: Optional[dict] = None, needs_key: bool = True, method: str = "GET",
|
|
155
|
+
payload: Any = None) -> Answer:
|
|
156
|
+
"""Any /v1 call that answers JSON: GET, POST with a JSON body, or DELETE."""
|
|
157
|
+
status, res_headers, body = self._send(path, query, needs_key, method, payload, "application/json")
|
|
158
|
+
parsed = _parse(body)
|
|
159
|
+
if status >= 400:
|
|
160
|
+
raise _refusal(status, res_headers, parsed)
|
|
161
|
+
if not isinstance(parsed, dict) or "data" not in parsed:
|
|
162
|
+
raise PermTrackerError(status, "bad_response", "The API's answer wasn't the expected JSON.")
|
|
163
|
+
return Answer(data=parsed["data"], meta=parsed.get("meta") or {}, usage=usage_from(res_headers))
|
|
164
|
+
|
|
165
|
+
def get(self, path: str, query: Optional[dict] = None, needs_key: bool = True) -> Answer:
|
|
166
|
+
"""GET a /v1 path. Exposed for endpoints this version doesn't wrap yet."""
|
|
167
|
+
return self.request(path, query, needs_key)
|
|
168
|
+
|
|
169
|
+
def case(self, case_number: str, live: bool = False) -> Answer:
|
|
170
|
+
"""One case by number: PERM, prevailing wage, H-1B LCA, or H-2A, H-2B and CW-1.
|
|
171
|
+
|
|
172
|
+
live=True asks DOL now for a number our records don't hold yet (needs the
|
|
173
|
+
live_lookup scope; the plan sets how many a day).
|
|
174
|
+
"""
|
|
175
|
+
n = case_number.strip().upper()
|
|
176
|
+
if not CASE_RE.match(n):
|
|
177
|
+
raise PermTrackerError(400, "bad_case_number", f'"{case_number}" isn\'t a DOL case number (like G-100-26045-123456).')
|
|
178
|
+
return self.get("/cases/" + urllib.parse.quote(n), {"live": 1} if live else None)
|
|
179
|
+
|
|
180
|
+
def estimate(self, case: Optional[str] = None, filed: Optional[str] = None) -> Answer:
|
|
181
|
+
"""When a pending PERM case is likely to be decided: by case number or filing date (YYYY-MM-DD)."""
|
|
182
|
+
if not case and not filed:
|
|
183
|
+
raise PermTrackerError(400, "missing_argument", "Give a case number or a filing date.")
|
|
184
|
+
return self.get("/estimate", {"case": case} if case else {"filed": filed})
|
|
185
|
+
|
|
186
|
+
def queue(self) -> Answer:
|
|
187
|
+
return self.get("/queue")
|
|
188
|
+
|
|
189
|
+
def visa_bulletin(self, month: Optional[str] = None) -> Answer:
|
|
190
|
+
return self.get("/visa-bulletin", {"month": month})
|
|
191
|
+
|
|
192
|
+
def employers(self, q: str, limit: Optional[int] = None) -> Answer:
|
|
193
|
+
return self.get("/employers", {"q": q, "limit": limit})
|
|
194
|
+
|
|
195
|
+
def employer(self, slug: str) -> Answer:
|
|
196
|
+
return self.get("/employers/" + urllib.parse.quote(slug))
|
|
197
|
+
|
|
198
|
+
def law_firms(self, q: str, limit: Optional[int] = None) -> Answer:
|
|
199
|
+
return self.get("/law-firms", {"q": q, "limit": limit})
|
|
200
|
+
|
|
201
|
+
def law_firm(self, slug: str) -> Answer:
|
|
202
|
+
return self.get("/law-firms/" + urllib.parse.quote(slug))
|
|
203
|
+
|
|
204
|
+
def occupations(self, q: str, limit: Optional[int] = None) -> Answer:
|
|
205
|
+
return self.get("/occupations", {"q": q, "limit": limit})
|
|
206
|
+
|
|
207
|
+
def occupation(self, slug: str) -> Answer:
|
|
208
|
+
return self.get("/occupations/" + urllib.parse.quote(slug))
|
|
209
|
+
|
|
210
|
+
def lookup_employer(self, name: str) -> Answer:
|
|
211
|
+
"""The employer page a printed name belongs to. No key needed."""
|
|
212
|
+
return self.get("/lookup/employer", {"name": name}, needs_key=False)
|
|
213
|
+
|
|
214
|
+
def lookup_soc(self, q: str) -> Answer:
|
|
215
|
+
"""A job title's SOC codes, with each code's share of the title's filings; or, for a code
|
|
216
|
+
(15-1252, 15-1252.00 or 151252), its title, description, core tasks, the titles filed under it
|
|
217
|
+
and its PERM approval rate and median wage. No key needed."""
|
|
218
|
+
return self.get("/lookup/soc", {"q": q}, needs_key=False)
|
|
219
|
+
|
|
220
|
+
def me(self) -> Answer:
|
|
221
|
+
"""Your key's scopes, the plan that applies, the paywall and what you've used. Not counted."""
|
|
222
|
+
return self.get("/me")
|
|
223
|
+
|
|
224
|
+
def export(self, kind: str, params: Optional[dict] = None) -> Answer:
|
|
225
|
+
"""A search's whole answer, up to the plan's export rows, as JSON. One call.
|
|
226
|
+
|
|
227
|
+
kind is cases (the case search's parameters), employers, law-firms or occupations (q).
|
|
228
|
+
"""
|
|
229
|
+
return self.get(f"/exports/{_export_kind(kind)}", {**(params or {}), "format": "json"})
|
|
230
|
+
|
|
231
|
+
def export_csv(self, kind: str, params: Optional[dict] = None) -> CsvExport:
|
|
232
|
+
"""The same export as CSV text, with its row count and whether it was cut at the cap."""
|
|
233
|
+
status, res_headers, body = self._send(f"/exports/{_export_kind(kind)}", {**(params or {}), "format": "csv"}, True,
|
|
234
|
+
"GET", None, "text/csv")
|
|
235
|
+
if status >= 400:
|
|
236
|
+
raise _refusal(status, res_headers, _parse(body))
|
|
237
|
+
return CsvExport(csv=body.decode("utf-8"), rows=_num(res_headers, "X-Export-Rows"), cap=_num(res_headers, "X-Export-Cap"),
|
|
238
|
+
truncated=str(res_headers.get("X-Export-Truncated") or "") == "true", usage=usage_from(res_headers))
|
|
239
|
+
|
|
240
|
+
def webhooks(self) -> Answer:
|
|
241
|
+
"""The account's webhook endpoints and watches. Needs the webhooks scope."""
|
|
242
|
+
return self.get("/webhooks")
|
|
243
|
+
|
|
244
|
+
def create_webhook(self, url: str, events: "list[str]") -> Answer:
|
|
245
|
+
"""A new endpoint. Its signing secret is in the answer, once: keep it."""
|
|
246
|
+
return self.request("/webhooks", method="POST", payload={"url": url, "events": list(events)})
|
|
247
|
+
|
|
248
|
+
def delete_webhook(self, endpoint_id: str) -> Answer:
|
|
249
|
+
return self.request("/webhooks/" + urllib.parse.quote(endpoint_id, safe=""), method="DELETE")
|
|
250
|
+
|
|
251
|
+
def watches(self) -> Answer:
|
|
252
|
+
"""The account's watches (the same list webhooks() returns)."""
|
|
253
|
+
return self.get("/watches")
|
|
254
|
+
|
|
255
|
+
def watch(self, case_number: Optional[str] = None, employer: Optional[str] = None) -> Answer:
|
|
256
|
+
"""Watch a case number or an employer's slug for case.status_changed and employer.moved."""
|
|
257
|
+
if (case_number is None) == (employer is None):
|
|
258
|
+
raise PermTrackerError(400, "missing_argument", "Give a case number or an employer, one of them.")
|
|
259
|
+
return self.request("/watches", method="POST", payload={"caseNumber": case_number} if case_number else {"employer": employer})
|
|
260
|
+
|
|
261
|
+
def unwatch(self, target: str, kind: str = "case") -> Answer:
|
|
262
|
+
return self.request("/watches/" + urllib.parse.quote(target, safe=""), {"kind": kind}, method="DELETE")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _export_kind(kind: str) -> str:
|
|
266
|
+
if kind not in EXPORT_KINDS:
|
|
267
|
+
raise PermTrackerError(400, "bad_argument", f"Exports: {', '.join(EXPORT_KINDS)}.")
|
|
268
|
+
return kind
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def verify_webhook(secret: str, headers, raw_body, tolerance_seconds: int = 300, now: Optional[float] = None) -> bool:
|
|
272
|
+
"""True when a delivery's signature matches `secret` (the whsec_ value shown when
|
|
273
|
+
the endpoint was made) and its timestamp is within `tolerance_seconds` of now.
|
|
274
|
+
|
|
275
|
+
Pass the RAW body, exactly as it arrived (str or bytes): parsing and
|
|
276
|
+
re-serialising JSON changes the bytes. `headers` is any mapping; names are
|
|
277
|
+
matched without regard to case.
|
|
278
|
+
"""
|
|
279
|
+
lower = {str(k).lower(): v for k, v in dict(headers).items()}
|
|
280
|
+
msg_id, ts, sig = lower.get("webhook-id"), lower.get("webhook-timestamp"), lower.get("webhook-signature")
|
|
281
|
+
if not msg_id or not ts or not sig or not secret.startswith("whsec_"):
|
|
282
|
+
return False
|
|
283
|
+
try:
|
|
284
|
+
seconds = int(ts)
|
|
285
|
+
except ValueError:
|
|
286
|
+
return False
|
|
287
|
+
if abs((time.time() if now is None else now) - seconds) > tolerance_seconds:
|
|
288
|
+
return False
|
|
289
|
+
try:
|
|
290
|
+
key = base64.b64decode(secret[len("whsec_"):], validate=True)
|
|
291
|
+
except ValueError:
|
|
292
|
+
return False
|
|
293
|
+
body = raw_body.decode("utf-8") if isinstance(raw_body, (bytes, bytearray)) else str(raw_body)
|
|
294
|
+
want = base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.{body}".encode("utf-8"), hashlib.sha256).digest()).decode("ascii")
|
|
295
|
+
# Several space-separated signatures may arrive while a secret is rotated.
|
|
296
|
+
for part in str(sig).split(" "):
|
|
297
|
+
version, _, value = part.partition(",")
|
|
298
|
+
if version == "v1" and hmac.compare_digest(value, want):
|
|
299
|
+
return True
|
|
300
|
+
return False
|
permtracker/cli.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""permtracker: the PERM Tracker API on the command line (Python edition).
|
|
2
|
+
|
|
3
|
+
Same commands as `npx permtracker`. The key comes from --key, then
|
|
4
|
+
PERMTRACKER_API_KEY, then the file `login` writes
|
|
5
|
+
(~/.config/permtracker/config.json, readable by you alone).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Optional
|
|
17
|
+
|
|
18
|
+
from . import EXPORT_KINDS, WEBHOOK_EVENTS, PermTracker, PermTrackerError, __version__
|
|
19
|
+
|
|
20
|
+
COMMANDS = {
|
|
21
|
+
"case": "one case: PERM (G-), wage request (P-), LCA (I-), H-2A, H-2B, CW-1",
|
|
22
|
+
"estimate": "when a pending PERM case is likely to be decided (a number, or --filed YYYY-MM-DD)",
|
|
23
|
+
"queue": "DOL's processing times and the pending queue",
|
|
24
|
+
"bulletin": "a visa bulletin, the newest by default (or YYYY-MM)",
|
|
25
|
+
"employers": "search employers", "employer": "one employer by slug",
|
|
26
|
+
"firms": "search law firms", "firm": "one law firm by slug",
|
|
27
|
+
"jobs": "search occupations", "job": "one occupation by slug",
|
|
28
|
+
"lookup": "the employer page a printed name belongs to (no key)",
|
|
29
|
+
"soc": "a job title's SOC codes, or one code's record (no key)",
|
|
30
|
+
"export": "a whole search, CSV by default: cases (the case search's name=value parameters), employers, law-firms or occupations (q=...)",
|
|
31
|
+
"watch": "watch a case for your webhooks (--employer <slug> for an employer); nothing after it lists your watches",
|
|
32
|
+
"unwatch": "stop watching a case (--employer <slug> for an employer)",
|
|
33
|
+
"webhooks": "your webhook endpoints; webhooks add <url> <event ...>; webhooks remove <id>",
|
|
34
|
+
"me": "your key, your plan and what you've used",
|
|
35
|
+
"login": "save your key", "logout": "forget it",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def config_path(env: Optional[dict] = None) -> Path:
|
|
40
|
+
env = os.environ if env is None else env
|
|
41
|
+
base = env.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
42
|
+
return Path(base) / "permtracker" / "config.json"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def saved_key() -> Optional[str]:
|
|
46
|
+
try:
|
|
47
|
+
return json.loads(config_path().read_text()).get("apiKey")
|
|
48
|
+
except (OSError, ValueError):
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def render(value: Any, indent: str = "") -> str:
|
|
53
|
+
"""A plain listing of an answer: nested objects indented, lists one item a line."""
|
|
54
|
+
if value is None or value == []:
|
|
55
|
+
return f"{indent}none"
|
|
56
|
+
if isinstance(value, list):
|
|
57
|
+
return "\n".join(f"{indent}-\n{render(v, indent + ' ')}" if isinstance(v, (dict, list)) and v else f"{indent}- {v}" for v in value)
|
|
58
|
+
if isinstance(value, dict):
|
|
59
|
+
lines = []
|
|
60
|
+
for k, v in value.items():
|
|
61
|
+
if isinstance(v, (dict, list)) and v:
|
|
62
|
+
lines.append(f"{indent}{k}:\n{render(v, indent + ' ')}")
|
|
63
|
+
else:
|
|
64
|
+
lines.append(f"{indent}{k}: {'none' if v is None or v == [] else v}")
|
|
65
|
+
return "\n".join(lines)
|
|
66
|
+
return f"{indent}{value}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def export_params(args: list) -> dict:
|
|
70
|
+
"""An export's name=value arguments as query parameters."""
|
|
71
|
+
params = {}
|
|
72
|
+
for a in args:
|
|
73
|
+
name, eq, value = a.partition("=")
|
|
74
|
+
if not eq or not name:
|
|
75
|
+
raise PermTrackerError(400, "bad_argument", f'"{a}" isn\'t name=value. Give the search\'s parameters like q=acme state=CA.')
|
|
76
|
+
params[name] = value
|
|
77
|
+
return params
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parser() -> argparse.ArgumentParser:
|
|
81
|
+
p = argparse.ArgumentParser(prog="permtracker", description="DOL case status, estimates and PERM data from permtracker.app",
|
|
82
|
+
epilog=f"Webhook events: {', '.join(WEBHOOK_EVENTS)}. "
|
|
83
|
+
"Make a free key at https://permtracker.app/settings (API keys).")
|
|
84
|
+
p.add_argument("command", choices=sorted(COMMANDS), help="; ".join(f"{k}: {v}" for k, v in COMMANDS.items()))
|
|
85
|
+
p.add_argument("args", nargs="*")
|
|
86
|
+
p.add_argument("--json", action="store_true", help="print the API's own JSON")
|
|
87
|
+
p.add_argument("--key", help="an API key, instead of the saved one")
|
|
88
|
+
p.add_argument("--filed", help="a filing date, YYYY-MM-DD, for estimate")
|
|
89
|
+
p.add_argument("--live", action="store_true", help="case: ask DOL now when our records don't hold the number yet")
|
|
90
|
+
p.add_argument("--employer", help="watch or unwatch an employer by slug")
|
|
91
|
+
p.add_argument("--format", choices=["csv", "json"], help="export: csv (the default) or json")
|
|
92
|
+
p.add_argument("--out", help="export: write to this file instead of the screen")
|
|
93
|
+
p.add_argument("--version", action="version", version=f"permtracker {__version__}")
|
|
94
|
+
return p
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def run(argv: list) -> int:
|
|
98
|
+
a = parser().parse_args(argv)
|
|
99
|
+
text = " ".join(a.args).strip()
|
|
100
|
+
if a.command == "login":
|
|
101
|
+
key = (a.key or input("Paste your PERM Tracker API key (pt_live_...): ")).strip()
|
|
102
|
+
if not re.fullmatch(r"pt_(live|test)_[0-9A-Za-z]{38}", key):
|
|
103
|
+
print("That isn't a PERM Tracker key: keys start with pt_live_ (or pt_test_ for the sandbox) and are 46 characters.",
|
|
104
|
+
file=sys.stderr)
|
|
105
|
+
return 1
|
|
106
|
+
me = PermTracker(api_key=key).me().data
|
|
107
|
+
path = config_path()
|
|
108
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
109
|
+
path.write_text(json.dumps({"apiKey": key}) + "\n")
|
|
110
|
+
os.chmod(path, 0o600)
|
|
111
|
+
print(f"Saved. Key {me['key']['id']}, {me['plan']['name']} plan, {me['usage']['remainingToday']} calls left today.")
|
|
112
|
+
return 0
|
|
113
|
+
if a.command == "logout":
|
|
114
|
+
config_path().unlink(missing_ok=True)
|
|
115
|
+
print("Forgot the saved key.")
|
|
116
|
+
return 0
|
|
117
|
+
pt = PermTracker(api_key=a.key or os.environ.get("PERMTRACKER_API_KEY") or saved_key())
|
|
118
|
+
|
|
119
|
+
def need(what: str) -> str:
|
|
120
|
+
if not text:
|
|
121
|
+
raise PermTrackerError(400, "missing_argument", f"Give {what}.")
|
|
122
|
+
return text
|
|
123
|
+
|
|
124
|
+
c = a.command
|
|
125
|
+
if c == "export":
|
|
126
|
+
return run_export(pt, a)
|
|
127
|
+
if c == "case": ans = pt.case(need("a case number"), live=a.live)
|
|
128
|
+
elif c == "estimate": ans = pt.estimate(filed=a.filed) if a.filed else pt.estimate(case=need("a case number, or --filed YYYY-MM-DD"))
|
|
129
|
+
elif c == "queue": ans = pt.queue()
|
|
130
|
+
elif c == "bulletin": ans = pt.visa_bulletin(a.args[0] if a.args else None)
|
|
131
|
+
elif c == "employers": ans = pt.employers(need("a name to search"))
|
|
132
|
+
elif c == "employer": ans = pt.employer(need("an employer's slug (search with employers)"))
|
|
133
|
+
elif c == "firms": ans = pt.law_firms(need("a name to search"))
|
|
134
|
+
elif c == "firm": ans = pt.law_firm(need("a law firm's slug (search with firms)"))
|
|
135
|
+
elif c == "jobs": ans = pt.occupations(need("a job title to search"))
|
|
136
|
+
elif c == "job": ans = pt.occupation(need("an occupation's slug (search with jobs)"))
|
|
137
|
+
elif c == "lookup": ans = pt.lookup_employer(need("an employer's name"))
|
|
138
|
+
elif c == "soc": ans = pt.lookup_soc(need("a job title or a SOC code"))
|
|
139
|
+
elif c == "watch":
|
|
140
|
+
if a.employer: ans = pt.watch(employer=a.employer)
|
|
141
|
+
elif text: ans = pt.watch(case_number=text)
|
|
142
|
+
else:
|
|
143
|
+
ans = pt.watches()
|
|
144
|
+
ans.data = ans.data.get("watches")
|
|
145
|
+
elif c == "unwatch":
|
|
146
|
+
ans = pt.unwatch(a.employer, kind="employer") if a.employer else pt.unwatch(need("a case number, or --employer <slug>"))
|
|
147
|
+
elif c == "webhooks":
|
|
148
|
+
sub, rest = (a.args[0], a.args[1:]) if a.args else (None, [])
|
|
149
|
+
if sub == "add":
|
|
150
|
+
if len(rest) < 2:
|
|
151
|
+
raise PermTrackerError(400, "missing_argument", f"Give an https address and at least one event: {', '.join(WEBHOOK_EVENTS)}.")
|
|
152
|
+
ans = pt.create_webhook(rest[0], rest[1:])
|
|
153
|
+
elif sub == "remove":
|
|
154
|
+
if not rest:
|
|
155
|
+
raise PermTrackerError(400, "missing_argument", "Give an endpoint's id (list them with webhooks).")
|
|
156
|
+
ans = pt.delete_webhook(rest[0])
|
|
157
|
+
elif sub is None:
|
|
158
|
+
ans = pt.webhooks()
|
|
159
|
+
ans.data = ans.data.get("endpoints")
|
|
160
|
+
else:
|
|
161
|
+
print(f'Unknown webhooks command "{sub}": use add or remove, or nothing to list them.', file=sys.stderr)
|
|
162
|
+
return 1
|
|
163
|
+
else: ans = pt.me()
|
|
164
|
+
if a.json:
|
|
165
|
+
print(json.dumps({"data": ans.data, "meta": ans.meta}, indent=2))
|
|
166
|
+
else:
|
|
167
|
+
print(render(ans.data))
|
|
168
|
+
if ans.meta.get("source"):
|
|
169
|
+
print(f"\nSource: {ans.meta['source']}" + (f" (as of {ans.meta['asOf']})" if ans.meta.get("asOf") else ""))
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def run_export(pt: PermTracker, a) -> int:
|
|
174
|
+
if not a.args or a.args[0] not in EXPORT_KINDS:
|
|
175
|
+
print(f"Name what to export: {', '.join(EXPORT_KINDS)}.", file=sys.stderr)
|
|
176
|
+
return 1
|
|
177
|
+
kind, params = a.args[0], export_params(a.args[1:])
|
|
178
|
+
fmt = a.format or ("json" if a.json else "csv")
|
|
179
|
+
if fmt == "csv":
|
|
180
|
+
got = pt.export_csv(kind, params)
|
|
181
|
+
text, rows, truncated, cap = got.csv, got.rows, got.truncated, got.cap
|
|
182
|
+
else:
|
|
183
|
+
page = pt.export(kind, params)
|
|
184
|
+
text = json.dumps({"data": page.data, "meta": page.meta}, indent=2) + "\n"
|
|
185
|
+
rows, truncated, cap = page.data.get("count"), page.data.get("truncated"), page.data.get("cap")
|
|
186
|
+
if a.out:
|
|
187
|
+
Path(a.out).write_text(text)
|
|
188
|
+
print(f"Wrote {rows if rows is not None else 'the'} rows to {a.out}.", file=sys.stderr)
|
|
189
|
+
else:
|
|
190
|
+
sys.stdout.write(text)
|
|
191
|
+
if truncated:
|
|
192
|
+
print(f"More matched than your plan's {cap or ''} rows; narrow the search to get the rest.", file=sys.stderr)
|
|
193
|
+
return 0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def main() -> None:
|
|
197
|
+
try:
|
|
198
|
+
sys.exit(run(sys.argv[1:]))
|
|
199
|
+
except PermTrackerError as err:
|
|
200
|
+
print(err.message + (f" (try again in {err.retry_after} seconds)" if err.retry_after else ""), file=sys.stderr)
|
|
201
|
+
if err.url:
|
|
202
|
+
print(err.url, file=sys.stderr)
|
|
203
|
+
sys.exit(3 if err.status == 404 else 2)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
if __name__ == "__main__":
|
|
207
|
+
main()
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: permtracker
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: The PERM Tracker API from Python and the command line: DOL case status, decision estimates, the PERM queue, visa bulletins, employer, law firm and occupation records, exports, live DOL lookups and signed webhooks.
|
|
5
|
+
Author-email: PERM Tracker <support@permtracker.app>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://permtracker.app/developers
|
|
8
|
+
Keywords: perm,dol,immigration,green card,visa bulletin,h-1b
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# permtracker
|
|
15
|
+
|
|
16
|
+
The [PERM Tracker](https://permtracker.app) API for Python and the command line.
|
|
17
|
+
|
|
18
|
+
- DOL case status for PERM, wage requests, H-1B LCAs, H-2A, H-2B and CW-1
|
|
19
|
+
- When a pending PERM case is likely to be decided
|
|
20
|
+
- DOL's queue and the visa bulletin
|
|
21
|
+
- Employer, law firm and job records
|
|
22
|
+
- Exports, live DOL lookups and signed webhooks
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
Python 3.9 or later.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install permtracker
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Make a free key at [permtracker.app/settings](https://permtracker.app/settings), under API keys. Paid features are free until billing opens. A `pt_test_` key returns sample data for tests.
|
|
33
|
+
|
|
34
|
+
## Command line
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
permtracker login
|
|
38
|
+
permtracker case G-100-26045-123456
|
|
39
|
+
permtracker estimate --filed 2026-02-15
|
|
40
|
+
permtracker bulletin 2026-10
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Add `--json` for the raw answer. Every command: `permtracker --help`.
|
|
44
|
+
|
|
45
|
+
## In code
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from permtracker import PermTracker
|
|
49
|
+
|
|
50
|
+
pt = PermTracker() # reads PERMTRACKER_API_KEY
|
|
51
|
+
answer = pt.case("G-100-26045-123456")
|
|
52
|
+
print(answer.data["status"])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Check a webhook delivery with the raw request body:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from permtracker import verify_webhook
|
|
59
|
+
|
|
60
|
+
ok = verify_webhook(secret, request.headers, raw_body)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## If it breaks
|
|
64
|
+
|
|
65
|
+
- **No key found:** the CLI reads `--key`, then `PERMTRACKER_API_KEY`, then the key `login` saved.
|
|
66
|
+
- **A refused call** raises `PermTrackerError` with the API's `code`. On a rate limit, wait `retry_after` seconds.
|
|
67
|
+
|
|
68
|
+
Full reference: [permtracker.app/developers](https://permtracker.app/developers). Terms: [permtracker.app/api-terms](https://permtracker.app/api-terms).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
permtracker/__init__.py,sha256=P2momHrc3bZsGAI8VDIf4evRFBc5v7AfGjCU1SythaY,13775
|
|
2
|
+
permtracker/cli.py,sha256=tE9yGfKQgH0gQOZ0jwRNfQ3jNR_oGplJS4KAGvRNWAE,9681
|
|
3
|
+
permtracker-0.3.0.dist-info/licenses/LICENSE,sha256=HDIaIg1kHQzDw5xMVuWEt_PeDV2lv6YEM21B9LFH8cw,1069
|
|
4
|
+
permtracker-0.3.0.dist-info/METADATA,sha256=UxOerumz9ydW23zQbBVZAvJYrolZJJWuDzjoVqmNrcI,2126
|
|
5
|
+
permtracker-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
permtracker-0.3.0.dist-info/entry_points.txt,sha256=LHMTC2XEqXF0-ieHsegEVXbL2MmrGv-JYFFQEVAO6jQ,53
|
|
7
|
+
permtracker-0.3.0.dist-info/top_level.txt,sha256=CLJpqr8JzY75IpVawE4kUkm2U4ldAQlWb4nZZUDh-gw,12
|
|
8
|
+
permtracker-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PERM Tracker
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
permtracker
|