-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgdocs_sync.py
More file actions
542 lines (475 loc) · 21.5 KB
/
gdocs_sync.py
File metadata and controls
542 lines (475 loc) · 21.5 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#!/usr/bin/env python3
"""
Research Tracker - Google Docs Sync
Uses Google Docs API to sync all topics and papers to a structured Google Doc.
OAuth2 flow via browser redirect to localhost.
"""
import json
import os
import sys
import ssl
import time
import socket
import webbrowser
import urllib.request
import urllib.parse
import urllib.error
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
# ─── Paths ────────────────────────────────────────────────────────────────────
HOME = os.path.expanduser("~")
CONFIG_DIR = os.path.join(HOME, ".research_tracker")
DATA_FILE = os.path.join(CONFIG_DIR, "data.json")
CONFIG_FILE = os.path.join(CONFIG_DIR, "gdocs_config.json")
TOKEN_FILE = os.path.join(CONFIG_DIR, "gdocs_token.json")
os.makedirs(CONFIG_DIR, exist_ok=True)
# ─── Config ───────────────────────────────────────────────────────────────────
def load_config():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE) as f:
return json.load(f)
return {}
def save_config(cfg):
with open(CONFIG_FILE, 'w') as f:
json.dump(cfg, f, indent=2)
def load_token():
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE) as f:
return json.load(f)
return {}
def save_token(tok):
with open(TOKEN_FILE, 'w') as f:
json.dump(tok, f, indent=2)
# ─── OAuth2 ───────────────────────────────────────────────────────────────────
OAUTH_CODE = None
OAUTH_DONE = threading.Event()
class OAuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
global OAUTH_CODE
params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
if 'code' in params:
OAUTH_CODE = params['code'][0]
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(b"""
<html><body style="font-family:sans-serif;background:#1a1a2e;color:#eee;display:flex;
align-items:center;justify-content:center;height:100vh;margin:0">
<div style="text-align:center;padding:40px;background:#16213e;border-radius:16px">
<h2 style="color:#9342f2">✓ Authorized!</h2>
<p>Research Tracker is now connected to Google Docs.</p>
<p style="color:#888">You can close this tab.</p>
</div></body></html>""")
OAUTH_DONE.set()
else:
self.send_response(400)
self.end_headers()
self.wfile.write(b"Authorization failed.")
def log_message(self, fmt, *args): pass
def do_oauth(client_id, client_secret):
"""Run OAuth2 flow, returns access_token, refresh_token"""
redirect_uri = "http://localhost:8765"
scope = "https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/drive"
auth_url = (
"https://accounts.google.com/o/oauth2/v2/auth?"
+ urllib.parse.urlencode({
"client_id": client_id,
"redirect_uri": redirect_uri,
"response_type": "code",
"scope": scope,
"access_type": "offline",
"prompt": "consent"
})
)
print(f"\nOpening browser for Google authorization...")
print(f"If browser doesn't open, visit:\n{auth_url}\n")
# Start local server
server = HTTPServer(("localhost", 8765), OAuthHandler)
t = threading.Thread(target=server.handle_request)
t.start()
webbrowser.open(auth_url)
OAUTH_DONE.wait(timeout=120)
server.server_close()
if not OAUTH_CODE:
print("ERROR: Authorization timed out")
sys.exit(1)
# Exchange code for tokens
token_data = urllib.parse.urlencode({
"code": OAUTH_CODE,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code"
}).encode()
ctx = ssl.create_default_context()
req = urllib.request.Request(
"https://oauth2.googleapis.com/token",
data=token_data,
method="POST"
)
req.add_header("Content-Type", "application/x-www-form-urlencoded")
with urllib.request.urlopen(req, context=ctx) as resp:
tokens = json.loads(resp.read())
return tokens["access_token"], tokens.get("refresh_token", ""), tokens.get("expires_in", 3600)
def refresh_access_token(client_id, client_secret, refresh_token):
token_data = urllib.parse.urlencode({
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
"grant_type": "refresh_token"
}).encode()
ctx = ssl.create_default_context()
req = urllib.request.Request(
"https://oauth2.googleapis.com/token",
data=token_data,
method="POST"
)
req.add_header("Content-Type", "application/x-www-form-urlencoded")
with urllib.request.urlopen(req, context=ctx) as resp:
tokens = json.loads(resp.read())
return tokens["access_token"], tokens.get("expires_in", 3600)
def get_valid_token():
cfg = load_config()
tok = load_token()
if not cfg.get("client_id") or not cfg.get("client_secret"):
print("ERROR: No OAuth credentials. Run: research_tracker_sync --setup")
sys.exit(1)
if not tok.get("refresh_token"):
access, refresh, expires = do_oauth(cfg["client_id"], cfg["client_secret"])
tok = {"access_token": access, "refresh_token": refresh,
"expires_at": time.time() + expires - 60}
save_token(tok)
return access
if time.time() > tok.get("expires_at", 0):
access, expires = refresh_access_token(cfg["client_id"], cfg["client_secret"], tok["refresh_token"])
tok["access_token"] = access
tok["expires_at"] = time.time() + expires - 60
save_token(tok)
return tok["access_token"]
# ─── Google Docs API helpers ───────────────────────────────────────────────────
def api_request(method, url, token, data=None):
ctx = ssl.create_default_context()
body = json.dumps(data).encode() if data else None
req = urllib.request.Request(url, data=body, method=method)
req.add_header("Authorization", f"Bearer {token}")
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, context=ctx) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as e:
print(f"API error {e.code}: {e.read().decode()}")
raise
def create_document(token, title):
doc = api_request("POST", "https://docs.googleapis.com/v1/documents",
token, {"title": title})
return doc["documentId"]
def get_document(token, doc_id):
return api_request("GET", f"https://docs.googleapis.com/v1/documents/{doc_id}", token)
def batch_update(token, doc_id, requests_list):
if not requests_list:
return
return api_request("POST",
f"https://docs.googleapis.com/v1/documents/{doc_id}:batchUpdate",
token, {"requests": requests_list})
# ─── Rich text → Docs API requests ────────────────────────────────────────────
def strip_markup(text):
"""Remove our markup tags to get plain text"""
import re
text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
text = re.sub(r'__(.*?)__', r'\1', text)
text = re.sub(r'_(.*?)_', r'\1', text)
text = re.sub(r'~~(.*?)~~', r'\1', text)
text = re.sub(r'\[c=#[0-9a-fA-F]{6}\](.*?)\[/c\]', r'\1', text)
text = re.sub(r'\[s=\d+\](.*?)\[/s\]', r'\1', text)
return text
def parse_spans(text):
"""Parse markup into list of (text, bold, italic, underline, color) tuples"""
spans = []
i = 0
bold = False
italic = False
underline = False
color = None
buf = ""
def flush():
nonlocal buf
if buf:
spans.append({"text": buf, "bold": bold, "italic": italic,
"underline": underline, "color": color})
buf = ""
while i < len(text):
if text[i:i+2] == '**':
flush(); bold = not bold; i += 2
elif text[i:i+2] == '__':
flush(); underline = not underline; i += 2
elif text[i] == '_':
flush(); italic = not italic; i += 1
elif text[i:i+2] == '~~':
flush(); i += 2 # skip strikethrough for Docs
elif text[i:i+3] == '[c=':
end = text.find(']', i)
if end != -1:
flush(); color = text[i+3:end]; i = end+1
else:
buf += text[i]; i += 1
elif text[i:i+4] == '[/c]':
flush(); color = None; i += 4
elif text[i:i+3] == '[s=':
end = text.find(']', i)
if end != -1: i = end+1
else: buf += text[i]; i += 1
elif text[i:i+4] == '[/s]':
i += 4
else:
buf += text[i]; i += 1
flush()
return spans
# ─── Build document content ────────────────────────────────────────────────────
def build_doc_requests(data, start_index=1):
"""Build batchUpdate requests to populate the document"""
requests = []
idx = start_index # current insert position
def ins_text(text, idx):
return {"insertText": {"location": {"index": idx}, "text": text}}
def style_text(start, end, bold=False, italic=False, underline=False,
color=None, font_size=None, heading=None):
req = {}
fields = []
ts = {}
if bold: ts["bold"] = True; fields.append("bold")
if italic: ts["italic"] = True; fields.append("italic")
if underline: ts["underline"] = True; fields.append("underline")
if color:
# color is like "#ff0000"
r = int(color[1:3],16)/255.0
g = int(color[3:5],16)/255.0
b = int(color[5:7],16)/255.0
ts["foregroundColor"] = {"color": {"rgbColor": {"red":r,"green":g,"blue":b}}}
fields.append("foregroundColor")
if font_size:
ts["fontSize"] = {"magnitude": font_size, "unit": "PT"}
fields.append("fontSize")
if ts and fields:
req = {"updateTextStyle": {
"range": {"startIndex": start, "endIndex": end},
"textStyle": ts,
"fields": ",".join(fields)
}}
return req
def para_style(start, end, heading_id=None, indent=False):
ps = {}
fields = []
if heading_id:
ps["namedStyleType"] = heading_id
fields.append("namedStyleType")
if indent:
ps["indentFirstLine"] = {"magnitude": 18, "unit": "PT"}
ps["indentStart"] = {"magnitude": 18, "unit": "PT"}
fields.append("indentFirstLine")
fields.append("indentStart")
if ps and fields:
return {"updateParagraphStyle": {
"range": {"startIndex": start, "endIndex": end},
"paragraphStyle": ps,
"fields": ",".join(fields)
}}
return None
def append(text, bold=False, italic=False, underline=False,
color=None, font_size=None, heading=None, bullet_indent=False):
nonlocal idx, requests
requests.append(ins_text(text, idx))
end = idx + len(text)
sty = style_text(idx, end, bold, italic, underline, color, font_size)
if sty: requests.append(sty)
ps = para_style(idx, end, heading, bullet_indent)
if ps: requests.append(ps)
idx = end
def section_label(label, value, label_color="#7cb9e8"):
"""Append a label: value line"""
if not value or not strip_markup(value).strip():
return
append(f"{label}: ", bold=True, color=label_color)
# Parse rich text spans
spans = parse_spans(value)
for sp in spans:
append(sp["text"], bold=sp["bold"], italic=sp["italic"],
underline=sp["underline"], color=sp["color"])
append("\n")
def rich_section(label, value, label_color="#a0d4a0"):
"""Append a labelled multi-line rich text block"""
plain = strip_markup(value).strip()
if not plain:
return
append(f"\n{label}\n", bold=True, font_size=13, color=label_color)
spans = parse_spans(value)
for sp in spans:
if sp["text"] == "\n":
append("\n")
else:
# Check for bullet lines
lines = sp["text"].split("\n")
for j, line in enumerate(lines):
is_bullet = line.startswith("• ") or line.startswith("- ")
if is_bullet:
line = line[2:]
append("• " + line, bold=sp["bold"], italic=sp["italic"],
underline=sp["underline"], color=sp["color"],
bullet_indent=True)
else:
append(line, bold=sp["bold"], italic=sp["italic"],
underline=sp["underline"], color=sp["color"])
if j < len(lines)-1:
append("\n")
append("\n")
# ── Document Title ──────────────────────────────────────────────────────
append("Research Tracker — Synced Notes\n", bold=True, font_size=20, heading="HEADING_1")
append(f"Last synced: {time.strftime('%Y-%m-%d %H:%M')}\n\n", italic=True, color="#888888")
status_map = {"unread": "Unread", "reading": "Reading", "read": "✓ Read"}
for topic in data.get("topics", []):
# ── Topic Heading ───────────────────────────────────────────────────
append(f"\n{'═'*60}\n", color="#444466")
append(f"📚 {topic['name']}\n", bold=True, font_size=18, heading="HEADING_1")
if topic.get("description"):
append(strip_markup(topic["description"]) + "\n", italic=True, color="#aaaacc")
append("\n")
papers = topic.get("papers", [])
# Sort by priority desc
papers = sorted(papers, key=lambda p: -p.get("priority", 3))
for i, paper in enumerate(papers):
# ── Paper Heading ───────────────────────────────────────────────
append(f"\n{'─'*50}\n", color="#333355")
stars = "★" * paper.get("priority", 3) + "☆" * (5 - paper.get("priority", 3))
status = status_map.get(paper.get("status","unread"), "Unread")
append(f" {stars} [{status}]\n", font_size=11, color="#888888")
append(f"{i+1}. {paper['title']}\n", bold=True, font_size=15, heading="HEADING_2")
# Meta
if paper.get("authors"):
append(f"Authors: ", bold=True, color="#9898cc")
append(paper["authors"] + "\n", color="#ccccee")
if paper.get("year"):
append(f"Year: ", bold=True, color="#9898cc")
append(paper["year"] + "\n")
if paper.get("doi_url"):
append(f"DOI/URL: ", bold=True, color="#9898cc")
append(paper["doi_url"] + "\n", color="#6699ff", underline=True)
if paper.get("date_added"):
append(f"Added: {paper['date_added']}\n", color="#666688", font_size=11)
append("\n")
# Sections
rich_section("📝 Abstract / Description", paper.get("brief_description",""), "#88aadd")
rich_section("✅ Strengths", paper.get("strengths",""), "#66bb88")
rich_section("❌ Weaknesses", paper.get("weaknesses",""), "#dd7766")
rich_section("💡 Follow-up Ideas", paper.get("followup_ideas",""), "#ddcc55")
rich_section("🗒️ Personal Notes", paper.get("notes",""), "#9988cc")
if not papers:
append(" (No papers added yet)\n", italic=True, color="#666688")
append("\n")
return requests
# ─── Main sync logic ───────────────────────────────────────────────────────────
def do_setup():
print("\n╔══════════════════════════════════════════════════════╗")
print("║ Research Tracker — Google Docs Sync Setup ║")
print("╠══════════════════════════════════════════════════════╣")
print("║ You need a Google Cloud project with Docs API. ║")
print("║ ║")
print("║ Steps: ║")
print("║ 1. Go to: https://console.cloud.google.com ║")
print("║ 2. Create project → Enable 'Google Docs API' ║")
print("║ 3. Create OAuth2 credentials (Desktop app) ║")
print("║ 4. Copy Client ID and Client Secret below ║")
print("╚══════════════════════════════════════════════════════╝\n")
cfg = load_config()
client_id = input(f"Client ID [{cfg.get('client_id','not set')}]: ").strip()
client_secret = input(f"Client Secret [{cfg.get('client_secret','not set')}]: ").strip()
if client_id: cfg["client_id"] = client_id
if client_secret: cfg["client_secret"] = client_secret
save_config(cfg)
print("\n✓ Config saved.")
# Clear token so re-auth happens
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
print("✓ Previous tokens cleared (will re-authorize on next sync).")
print("\nRun 'research_tracker_sync' to perform first sync.\n")
def do_sync():
print("\n→ Loading data...")
if not os.path.exists(DATA_FILE):
print("No data file found. Open Research Tracker first.")
sys.exit(1)
with open(DATA_FILE) as f:
data = json.load(f)
topics_count = len(data.get("topics", []))
papers_count = sum(len(t.get("papers",[])) for t in data.get("topics",[]))
print(f" Found {topics_count} topics, {papers_count} papers")
print("→ Authenticating with Google...")
token = get_valid_token()
cfg = load_config()
doc_id = cfg.get("doc_id")
if doc_id:
# Verify doc still exists
try:
doc = get_document(token, doc_id)
print(f" Using existing doc: {doc.get('title')}")
print(f" URL: https://docs.google.com/document/d/{doc_id}/edit")
except Exception:
print(" Existing doc not found, creating new one...")
doc_id = None
if not doc_id:
print("→ Creating new Google Doc...")
doc_id = create_document(token, "Research Tracker Notes")
cfg["doc_id"] = doc_id
save_config(cfg)
print(f" Created: https://docs.google.com/document/d/{doc_id}/edit")
print("→ Clearing existing content...")
# Get current doc to find end index
doc = get_document(token, doc_id)
body = doc.get("body", {})
content = body.get("content", [])
end_idx = 1
for el in content:
if "endIndex" in el:
end_idx = max(end_idx, el["endIndex"])
clear_reqs = []
if end_idx > 2:
clear_reqs = [{"deleteContentRange": {
"range": {"startIndex": 1, "endIndex": end_idx - 1}
}}]
batch_update(token, doc_id, clear_reqs)
print("→ Writing content...")
reqs = build_doc_requests(data)
# Batch in chunks of 50 to avoid API limits
chunk_size = 50
total = len(reqs)
for i in range(0, total, chunk_size):
chunk = reqs[i:i+chunk_size]
batch_update(token, doc_id, chunk)
print(f" Progress: {min(i+chunk_size,total)}/{total} requests")
doc_url = f"https://docs.google.com/document/d/{doc_id}/edit"
print(f"\n✓ Sync complete!")
print(f" Doc URL: {doc_url}\n")
# Save URL to config for the app to read
cfg["doc_url"] = doc_url
save_config(cfg)
# Try to open in browser
try:
webbrowser.open(doc_url)
except Exception:
pass
# ─── Entry point ──────────────────────────────────────────────────────────────
if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else "sync"
if cmd == "--setup" or cmd == "setup":
do_setup()
elif cmd == "--sync" or cmd == "sync":
do_sync()
elif cmd == "--doc-url":
cfg = load_config()
print(cfg.get("doc_url", ""))
elif cmd == "--has-config":
cfg = load_config()
if cfg.get("client_id") and cfg.get("client_secret"):
sys.exit(0)
else:
sys.exit(1)
else:
print(f"Usage: {sys.argv[0]} [setup|sync|--doc-url|--has-config]")
sys.exit(1)