-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaims_to_atproto.py
More file actions
227 lines (187 loc) · 7.41 KB
/
Copy pathclaims_to_atproto.py
File metadata and controls
227 lines (187 loc) · 7.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""Publish unpublished claims to ATProto PDS.
Reads ATPROTO_HANDLE, ATPROTO_APP_PASSWORD, and ATPROTO_PDS_URL
from .env. Queries the DB for claims with no claimAddress, builds
com.linkedclaims.claim records, publishes them via the PDS createRecord
endpoint, and updates claimAddress with the returned at:// URI.
Usage:
cd /opt/shared/repos/trust-claim-data-pipeline
python -m claims_to_atproto.publish_unpublished
"""
import datetime
import os
import sys
import time
import requests
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, PROJECT_ROOT)
from dotenv import load_dotenv
load_dotenv(os.path.join(PROJECT_ROOT, ".env"))
from lib.db import get_db_cursor, update_claim_address
ATPROTO_PDS_URL = os.getenv("ATPROTO_PDS_URL", "https://bsky.social")
ATPROTO_HANDLE = os.getenv("ATPROTO_HANDLE")
ATPROTO_APP_PASSWORD = os.getenv("ATPROTO_APP_PASSWORD")
BASE_URL = os.getenv("BASE_URL", "https://live.linkedtrust.us")
COLLECTION = "com.linkedclaims.claim"
PUBLISH_DELAY_SECONDS = 1.0
def unpublished_claims_generator():
"""Yield unpublished claims that come from known spider sources.
Currently scoped to OpenFoodFacts claims. Add more sourceURI prefixes
as additional spiders are integrated.
"""
known_sources = [
"https://world.openfoodfacts.org/",
]
source_filter = " OR ".join(['"sourceURI" LIKE \'%s%%\'' % s for s in known_sources])
query = f'''
SELECT id, subject, claim, object, statement, "effectiveDate",
"sourceURI", "howKnown", "dateObserved", "digestMultibase",
author, curator, aspect, score, stars, amt, unit,
"howMeasured", "intendedAudience", "respondAt",
confidence, "issuerId", "issuerIdType", "claimAddress", proof
FROM "Claim"
WHERE ("claimAddress" IS NULL OR "claimAddress" = '')
AND ({source_filter})
'''
with get_db_cursor() as cur:
cur.execute(query)
columns = [desc[0] for desc in cur.description]
while True:
rows = cur.fetchmany(1000)
if not rows:
break
for row in rows:
yield dict(zip(columns, row))
def create_session():
"""Authenticate with the PDS and return (did, access_jwt)."""
if not ATPROTO_HANDLE or not ATPROTO_APP_PASSWORD:
print("Error: ATPROTO_HANDLE and ATPROTO_APP_PASSWORD must be set in .env")
sys.exit(1)
resp = requests.post(
f"{ATPROTO_PDS_URL}/xrpc/com.atproto.server.createSession",
json={"identifier": ATPROTO_HANDLE, "password": ATPROTO_APP_PASSWORD},
timeout=30,
)
resp.raise_for_status()
data = resp.json()
return data["did"], data["accessJwt"]
def map_claim_to_record(claim):
"""Map a DB claim dict to an ATProto com.linkedclaims.claim record.
Matches the field structure used by trust_claim_backend/src/services/atprotoPublisher.ts.
"""
claim_id = claim.get("id")
record = {
"$type": COLLECTION,
"claimUri": claim.get("claimAddress") or (f"{BASE_URL}/api/claim/{claim_id}" if claim_id else None),
"subject": claim["subject"],
"claimType": claim["claim"],
"createdAt": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}
if claim.get("statement"):
record["statement"] = claim["statement"]
if claim.get("object"):
record["object"] = claim["object"]
effective = claim.get("effectiveDate")
if effective:
if isinstance(effective, (datetime.date, datetime.datetime)):
record["effectiveDate"] = effective.isoformat()
else:
record["effectiveDate"] = str(effective)
if claim.get("confidence") is not None:
record["confidence"] = str(claim["confidence"])
# Full source object — matches backend atprotoPublisher.ts
source = {}
if claim.get("sourceURI"):
source["uri"] = claim["sourceURI"]
if claim.get("howKnown"):
source["howKnown"] = claim["howKnown"]
if claim.get("author"):
source["author"] = claim["author"]
if claim.get("curator"):
source["curator"] = claim["curator"]
if claim.get("dateObserved"):
source["dateObserved"] = str(claim["dateObserved"])
if claim.get("digestMultibase"):
source["digestMultibase"] = claim["digestMultibase"]
if source:
record["source"] = source
if claim.get("stars") is not None:
record["stars"] = int(claim["stars"])
if claim.get("aspect"):
record["aspect"] = claim["aspect"]
if claim_id:
record["respondAt"] = f"{BASE_URL}/api/claim/{claim_id}/validate"
return record
def publish_record(did, access_jwt, record):
"""Publish a single record to ATProto PDS. Returns the at:// URI."""
resp = requests.post(
f"{ATPROTO_PDS_URL}/xrpc/com.atproto.repo.createRecord",
headers={"Authorization": f"Bearer {access_jwt}"},
json={
"repo": did,
"collection": COLLECTION,
"record": record,
},
timeout=30,
)
if not resp.ok:
print(f" PDS response: {resp.status_code} {resp.text[:500]}")
print(f" Record keys: {list(record.keys())}")
resp.raise_for_status()
data = resp.json()
return data["uri"]
def is_useful(claim):
"""Return True if the claim has enough fields to publish."""
return bool(
claim.get("claim")
and claim.get("subject")
and (claim.get("statement") or claim.get("object"))
and claim.get("effectiveDate")
)
def publish_unpublished():
"""Publish all unpublished claims to ATProto PDS."""
did, access_jwt = create_session()
print(f"Authenticated as {did}")
total = 0
published = 0
skipped = 0
errors = 0
for claim in unpublished_claims_generator():
if not is_useful(claim):
skipped += 1
print(f" Skipping claim {claim['id']} ({claim.get('subject', '?')[:40]}) - missing fields")
continue
total += 1
try:
record = map_claim_to_record(claim)
at_uri = publish_record(did, access_jwt, record)
update_claim_address(claim["id"], at_uri)
published += 1
print(f" Published claim {claim['id']}: {at_uri}")
except requests.HTTPError as e:
errors += 1
print(f" Error publishing claim {claim['id']}: {e}")
if e.response is not None:
print(f" PDS error: {e.response.status_code} - {e.response.text[:300]}")
if e.response is not None and e.response.status_code == 401:
print(" Session expired, re-authenticating...")
try:
did, access_jwt = create_session()
except Exception:
print(" Re-auth failed, stopping.")
break
if e.response is not None and e.response.status_code == 429:
print(" Rate limited, backing off for 30s...")
time.sleep(30)
continue
except Exception as e:
errors += 1
print(f" Error publishing claim {claim['id']}: {e}")
time.sleep(PUBLISH_DELAY_SECONDS)
print(f"\n=== Summary ===")
print(f"Total in batch: {total}")
print(f"Published: {published}")
print(f"Skipped (missing fields): {skipped}")
if errors:
print(f"Errors: {errors}")
if __name__ == "__main__":
publish_unpublished()