-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcodetools.py
More file actions
2302 lines (2003 loc) · 84.5 KB
/
Copy pathleetcodetools.py
File metadata and controls
2302 lines (2003 loc) · 84.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sublime
import sublime_plugin
import os
import json
import re
import ast
import time
import threading
import subprocess
import sys
import io
import contextlib
import traceback
import urllib.request
import urllib.error
import webbrowser
# ==================== 配置 ====================
def _settings():
return sublime.load_settings('LeetCodeTools.sublime-settings')
def _site():
return _settings().get('site', 'cn')
def _base_url():
return 'https://leetcode.cn' if _site() == 'cn' else 'https://leetcode.com'
def _working_dir():
return os.path.expanduser(_settings().get('working_dir', '~/leetcode'))
def _default_lang():
return _settings().get('default_lang', 'python3')
def _lang():
return _settings().get('language', 'zh')
def _run_timeout():
return _settings().get('run_timeout', 1)
def _cache_dir():
return os.path.join(_working_dir(), '.cache')
def _last_update_path():
return os.path.join(_cache_dir(), 'last_update.json')
def _maybe_auto_update():
"""如果缓存过期则自动更新。"""
age_days = _settings().get('cache_age_days', 7)
if not os.path.exists(_problem_list_cache_path()):
return
if os.path.exists(_last_update_path()):
with open(_last_update_path()) as f:
ts = json.load(f).get('timestamp', 0)
if time.time() - ts < age_days * 86400:
return
# 过期了,删缓存触发重建
os.remove(_problem_list_cache_path())
sublime.status_message('LeetCode Tools: Cache expired, auto-updating...')
def _cookie_cache_path():
return os.path.join(_cache_dir(), 'cookie.json')
def _problem_list_cache_path():
return os.path.join(_cache_dir(), 'problem_list.json')
def _study_plans_cache_path():
return os.path.join(_cache_dir(), 'study_plans.json')
def _study_plan_problems_cache_path():
return os.path.join(_cache_dir(), 'study_plan_problems.json')
def _problem_cache_dir():
return os.path.join(_cache_dir(), 'problems')
def _problem_json_path(slug):
return os.path.join(_problem_cache_dir(), slug + '.json')
def _problem_in_path(slug):
return os.path.join(_problem_cache_dir(), slug + '_in.json')
def _problem_out_path(slug):
return os.path.join(_problem_cache_dir(), slug + '_out.json')
def _problem_images_dir(slug):
return os.path.join(_cache_dir(), 'images', slug)
def _explanation_images_dir(slug):
return os.path.join(_cache_dir(), 'images', slug + '_explanation')
def _cache_is_fresh(cache_path):
"""判断缓存文件是否在 cache_age_days 天内。"""
if not os.path.exists(cache_path):
return False
try:
with open(cache_path, 'r', encoding='utf-8') as f:
data = json.load(f)
ts = data.get('timestamp', 0) if isinstance(data, dict) else 0
age_days = _settings().get('cache_age_days', 7)
return time.time() - ts < age_days * 86400
except Exception:
return False
# ── 找到系统 Python,用于跑 offline_runner ──
_SYSTEM_PYTHON = None
def _find_system_python():
"""找到系统较高版本 Python(带缓存,且隐藏控制台窗口)。"""
global _SYSTEM_PYTHON
if _SYSTEM_PYTHON:
return _SYSTEM_PYTHON
import glob
candidates = [
os.path.expandvars(r'%LOCALAPPDATA%\Python\bin\python3.exe'),
os.path.expandvars(r'%LOCALAPPDATA%\Python\bin\python.exe'),
]
for pat in [r'%LOCALAPPDATA%\Python\pythoncore-3.*-64\python.exe']:
candidates.extend(glob.glob(os.path.expandvars(pat)))
candidates.append('python3')
candidates.append('python')
kwargs = {}
if os.name == 'nt':
kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW
for p in candidates:
try:
ver = subprocess.check_output([p, '--version'], stderr=subprocess.STDOUT, timeout=5, **kwargs).decode()
if '3.' in ver:
_SYSTEM_PYTHON = p
return p
except Exception:
continue
raise RuntimeError(
'No system Python 3 found. Please install Python 3 and add it to PATH '
'(required by Login and the offline Run).'
)
LANG_EXT = {
'python3': 'py', 'python': 'py', 'java': 'java',
'cpp': 'cpp', 'c': 'c', 'csharp': 'cs',
'javascript': 'js', 'typescript': 'ts', 'golang': 'go',
'rust': 'rs', 'kotlin': 'kt', 'swift': 'swift',
'scala': 'scala', 'ruby': 'rb', 'php': 'php',
}
EXT_LANG = {v: k for k, v in LANG_EXT.items() if v not in ('py',) or k == 'python3'}
EXT_LANG['py'] = 'python3'
def _detect_slug(fp):
"""从文件路径推断题目 slug(优先读元数据 JSON 的 titleSlug)。"""
ext = os.path.splitext(fp)[1].lstrip('.')
base = fp[:-(len(ext) + 1)] if ext else fp
meta_base = base
for suffix in ('_in', '_out'):
if meta_base.endswith(suffix):
meta_base = meta_base[:-len(suffix)]
break
slug = None
json_path = _problem_json_path(os.path.basename(meta_base))
if os.path.exists(json_path):
try:
with open(json_path, 'r', encoding='utf-8') as f:
slug = json.load(f).get('titleSlug')
except Exception:
slug = None
return slug or os.path.basename(meta_base)
def _guess_image_ext(url, resp):
"""根据 URL 路径或 Content-Type 推断图片扩展名。"""
path = url.split('?')[0]
ext = os.path.splitext(path)[1].lower()
if ext in ('.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp'):
return '.jpg' if ext == '.jpeg' else ext
ctype = ''
try:
ctype = (resp.headers.get('Content-Type', '') or '').split(';')[0].strip().lower()
except Exception:
ctype = ''
mapping = {
'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif',
'image/webp': '.webp', 'image/svg+xml': '.svg', 'image/bmp': '.bmp',
}
return mapping.get(ctype, '.png')
def _download_images(html, img_dir, rel_prefix):
"""下载 HTML 里的 <img> 到本地 img_dir,替换成 。"""
counter = [0]
def _replace(m):
src = m.group(1)
counter[0] += 1
try:
req = urllib.request.Request(src, headers={'User-Agent': 'Mozilla/5.0'})
resp = urllib.request.urlopen(req, timeout=15)
data = resp.read()
ext = _guess_image_ext(src, resp)
fname = str(counter[0]) + ext
os.makedirs(img_dir, exist_ok=True)
with open(os.path.join(img_dir, fname), 'wb') as f:
f.write(data)
return ''
except Exception:
return ''
return re.sub(r'<img[^>]*src="([^"]+)"[^>]*/?>', _replace, html)
_MD_IMAGE_RE = re.compile(r'!\[([^\]]*)\]\(((?:[^)\s]|\\[()])+)\)')
def _download_markdown_images(md, img_dir, rel_prefix):
"""下载 Markdown 里  图片到本地,替换成本地路径。"""
counter = [0]
def _replace(m):
alt = m.group(1)
src = m.group(2).strip()
raw_src = src.replace('\\(', '(').replace('\\)', ')')
if not raw_src.startswith(('http://', 'https://')):
return m.group(0)
counter[0] += 1
try:
req = urllib.request.Request(raw_src, headers={'User-Agent': 'Mozilla/5.0'})
resp = urllib.request.urlopen(req, timeout=15)
data = resp.read()
ext = _guess_image_ext(raw_src, resp)
fname = str(counter[0]) + ext
os.makedirs(img_dir, exist_ok=True)
with open(os.path.join(img_dir, fname), 'wb') as f:
f.write(data)
return ''
except Exception:
return m.group(0)
return _MD_IMAGE_RE.sub(_replace, md)
_VIDEO_PLACEHOLDER_RE = re.compile(
r'!\[([^\]]*)\]\(([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\)'
)
def _clean_solution_markdown(md, videos=None):
"""规整 LeetCode 题解正文(本身已是 Markdown):规整代码块语言标签、统一换行、把视频占位符换成封面链接。"""
content = (md or '').replace('\r\n', '\n').replace('\r', '\n')
def _fix_fence(m):
lang = re.sub(r'\s*\[.*?\]\s*$', '', m.group(1)).strip().lower()
return '```' + lang
content = re.sub(r'```([^\n`]*)', _fix_fence, content)
if videos:
counter = [0]
def _fix_video(m):
alt = m.group(1)
i = counter[0]
counter[0] += 1
cover = ''
if i < len(videos):
cover = (videos[i] or {}).get('coverUrl') or ''
if cover:
return ''
return m.group(0)
content = _VIDEO_PLACEHOLDER_RE.sub(_fix_video, content)
content = re.sub(r'\n{3,}', '\n\n', content)
return content.strip()
# ==================== Cookie & API helpers ====================
def _save_cookie_from_text(text):
"""解析用户粘贴的 Cookie(完整 Cookie 头 / LEETCODE_SESSION=... / 单独的 session 值)。"""
text = (text or '').strip().strip(';').strip()
if not text:
raise ValueError('Cookie is empty.')
# 去掉可能带上的 "Cookie:" 前缀
if text.lower().startswith('cookie:'):
text = text[7:].strip()
# 换行 / 多余空白统一成单个空格(避免换行把值弄坏)
text = ' '.join(text.split())
pairs = {}
lower = text.lower()
if ';' in text or 'sl-session=' in lower or 'csrftoken=' in lower or 'leetcode_session=' in lower:
for part in text.split(';'):
part = part.strip()
if '=' not in part:
continue
k, v = part.split('=', 1)
k = k.strip()
v = v.strip().strip('"').strip()
if k:
pairs[k] = v
session = pairs.get('LEETCODE_SESSION') or pairs.get('sl-session')
if not session:
# 只贴了值(不带 key),当作 LEETCODE_SESSION
session = text.strip('"').strip()
pairs['LEETCODE_SESSION'] = session
if not session:
raise ValueError('No session cookie found. Paste the whole Cookie header.')
data = {
'LEETCODE_SESSION': pairs.get('LEETCODE_SESSION', ''),
'sl-session': pairs.get('sl-session', ''),
'csrftoken': pairs.get('csrftoken', ''),
'all': pairs,
}
os.makedirs(_cache_dir(), exist_ok=True)
with open(_cookie_cache_path(), 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
return data
def _validate_cookie(cookie_dict):
"""用需要登录的查询验证会话:CN 用 todayRecord.userStatus,US 用 globalData.userStatus.isSignedIn。"""
try:
all_cookies = cookie_dict.get('all', {})
raw = '; '.join(k + '=' + v for k, v in all_cookies.items())
if not raw:
session = cookie_dict.get('LEETCODE_SESSION') or cookie_dict.get('sl-session') or ''
raw = 'LEETCODE_SESSION=' + session
if _site() == 'cn':
query = 'query { todayRecord { userStatus } }'
else:
query = 'query { globalData { userStatus { isSignedIn } } }'
req = urllib.request.Request(
_base_url() + '/graphql/',
data=json.dumps({'query': query}).encode(),
headers={'Content-Type': 'application/json', 'Cookie': raw, 'User-Agent': 'Mozilla/5.0'}
)
resp = urllib.request.urlopen(req, timeout=10)
data = json.loads(resp.read()).get('data', {})
if _site() == 'cn':
rec = (data.get('todayRecord') or [{}])[0]
return rec.get('userStatus') is not None
return bool((data.get('userStatus') or {}).get('isSignedIn'))
except Exception:
return False
def get_leetcode_cookie():
cache_path = _cookie_cache_path()
if os.path.exists(cache_path):
with open(cache_path, 'r', encoding='utf-8') as f:
cached = json.load(f)
if _validate_cookie(cached):
return cached
raise RuntimeError('No valid cookie. Run "LeetCode Tools: Login" first — it opens the browser and asks you to paste the LEETCODE_SESSION cookie.')
def _fetch_csrftoken(cookie_raw=''):
"""通过 nojGlobalData 获取 csrftoken(带登录会话,尽量和会话匹配)。"""
try:
base = _base_url()
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0',
'Origin': base,
'Referer': base + '/',
}
if cookie_raw:
headers['Cookie'] = cookie_raw
req = urllib.request.Request(
base + '/graphql/',
data=json.dumps({'query': 'query nojGlobalData { siteRegion }'}).encode(),
headers=headers,
)
resp = urllib.request.urlopen(req, timeout=10)
for h in (resp.headers.get_all('Set-Cookie') or []):
if h.lower().startswith('csrftoken='):
return h.split('=', 1)[1].split(';', 1)[0]
except Exception:
pass
return ''
def _build_client():
cookie_dict = get_leetcode_cookie()
all_cookies = cookie_dict.get('all', {})
parts = []
for k, v in all_cookies.items():
parts.append(k + '=' + v)
raw = '; '.join(parts)
if not raw:
session = cookie_dict.get('LEETCODE_SESSION') or cookie_dict.get('sl-session') or ''
raw = 'LEETCODE_SESSION=' + session
if cookie_dict.get('csrftoken'):
raw += '; csrftoken=' + cookie_dict['csrftoken']
client = LeetCodeToolsClient(raw)
# 只粘了 sl-session、缺 csrftoken 时,自动补一个(带会话去拉)
if not client.csrf_token:
csrf = _fetch_csrftoken(client.cookie_raw)
if csrf:
client.csrf_token = csrf
client.cookie_raw = client.cookie_raw + '; csrftoken=' + csrf
return client
def _build_public_client():
"""无需登录的公开客户端(题解等公开接口用)。"""
return LeetCodeToolsClient('')
# ==================== LeetCode CN API 客户端 ====================
class LeetCodeToolsClient:
def __init__(self, raw_cookie):
self.cookie_raw = raw_cookie
self.csrf_token = self._extract_csrf(raw_cookie)
def _extract_csrf(self, raw_cookie):
for item in raw_cookie.split(';'):
item = item.strip()
if item.startswith('csrftoken='):
return item.split('=')[1]
return ''
def _graphql(self, query, variables=None, operation_name=None):
"""发 GraphQL 请求,返回 data dict。"""
payload = {'query': query}
if variables:
payload['variables'] = variables
if operation_name:
payload['operationName'] = operation_name
body = json.dumps(payload).encode()
base = _base_url()
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Origin': base,
'Referer': base + '/problemset/',
}
if self.cookie_raw:
headers['Cookie'] = self.cookie_raw
if self.csrf_token:
headers['X-CSRFToken'] = self.csrf_token
req = urllib.request.Request(base + '/graphql/', data=body, headers=headers)
resp = urllib.request.urlopen(req, timeout=30)
data = json.loads(resp.read())
if 'errors' in data:
raise Exception('GraphQL error: ' + str(data['errors']))
return data['data']
def get_problem_detail(self, title_slug):
query = '''
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId questionFrontendId title translatedTitle
titleSlug content translatedContent difficulty
exampleTestcases metaData
topicTags { name translatedName slug }
codeSnippets { lang langSlug code }
}
}
'''
data = self._graphql(query, {'titleSlug': title_slug})
return data['question']
def _fetch_problem_list(self):
"""从 GraphQL 一次拉全量题目列表(CN 有 titleCn,US 没有)。"""
all_questions = []
skip = 0
limit = 100
cn = _site() == 'cn'
while True:
if cn:
query = 'query{problemsetQuestionList(skip:' + str(skip) + ' limit:' + str(limit) + '){total questions{frontendQuestionId title titleCn titleSlug difficulty}}}'
data = self._graphql(query)['problemsetQuestionList']
items, total, fid_key = data['questions'], data['total'], 'frontendQuestionId'
else:
query = 'query{questionList(categorySlug:"" skip:' + str(skip) + ' limit:' + str(limit) + ' filters:{}){totalNum data{questionFrontendId title titleSlug difficulty}}}'
data = self._graphql(query)['questionList']
items, total, fid_key = data['data'], data['totalNum'], 'questionFrontendId'
for q in items:
all_questions.append({
'frontendQuestionId': str(q.get(fid_key, '')),
'titleCn': q.get('titleCn', '') if cn else '',
'title': q.get('title', ''),
'titleSlug': q.get('titleSlug', ''),
'difficulty': q.get('difficulty', ''),
})
skip += limit
if skip >= total:
break
os.makedirs(_cache_dir(), exist_ok=True)
with open(_problem_list_cache_path(), 'w', encoding='utf-8') as f:
json.dump(all_questions, f, ensure_ascii=False, indent=2)
with open(_last_update_path(), 'w') as f:
json.dump({'timestamp': time.time()}, f)
return all_questions
def _load_cache(self):
_maybe_auto_update()
cache_path = _problem_list_cache_path()
if os.path.exists(cache_path):
with open(cache_path, 'r', encoding='utf-8') as f:
return json.load(f)
return self._fetch_problem_list()
def search_problems(self, keyword):
problems = self._load_cache()
kw = keyword.strip().lower()
results = []
for p in problems:
fid = str(p.get('frontendQuestionId', ''))
slug = (p.get('titleSlug', '') or '').lower()
cn = (p.get('titleCn', '') or '').lower()
en = (p.get('title', '') or '').lower()
if kw == fid or kw in slug or kw in cn or kw in en:
results.append(p)
return results
def fetch_problem(self, question_id, lang='python3', working_dir=None, force=False, study_plan_slug=None):
if working_dir is None:
working_dir = _working_dir()
problems = self._load_cache()
qid_str = str(question_id)
title_slug = None
fid = None
for p in problems:
if str(p.get('frontendQuestionId', '')) == qid_str:
title_slug = p['titleSlug']
fid = p['frontendQuestionId']
break
if not title_slug:
for p in problems:
if (p.get('titleSlug', '') or '').lower() == qid_str.lower():
title_slug = p['titleSlug']
fid = p['frontendQuestionId']
break
if not title_slug:
raise ValueError('Problem not found: ' + str(question_id))
detail = self.get_problem_detail(title_slug)
os.makedirs(working_dir, exist_ok=True)
# MD
md_path = os.path.join(working_dir, title_slug + '.md')
img_dir = _problem_images_dir(title_slug)
img_ref = os.path.relpath(img_dir, working_dir).replace('\\', '/')
difficulty = detail.get('difficulty') or 'Unknown'
tags = ', '.join((t.get('translatedName') or t.get('name') or '')
for t in detail.get('topicTags', []))
use_zh = (_lang() == 'zh')
content = detail.get('translatedContent' if use_zh else 'content')
content = content or detail.get('content' if use_zh else 'translatedContent') or ''
title = detail.get('translatedTitle' if use_zh else 'title')
title = title or detail.get('title' if use_zh else 'translatedTitle') or ''
content = re.sub(r'<sup>(.*?)</sup>', r'^\1', content)
content = re.sub(r'<sub>(.*?)</sub>', r'_\1', content)
content = re.sub(r'<pre>(.*?)</pre>', r'\n```\n\1\n```\n', content, flags=re.DOTALL)
content = re.sub(r'<code>(.*?)</code>', r'`\1`', content)
content = re.sub(r'<em>(.*?)</em>', r'*\1*', content)
content = re.sub(r'<strong>(.*?)</strong>', r'**\1**', content)
content = _download_images(content, img_dir, img_ref)
content = re.sub(r'<[^>]+>', '', content)
content = re.sub(r' ', ' ', content)
content = re.sub(r'<', '<', content)
content = re.sub(r'>', '>', content)
content = re.sub(r'&', '&', content)
content = re.sub(r'\n{3,}', '\n\n', content)
if force or not os.path.exists(md_path):
with open(md_path, 'w', encoding='utf-8') as f:
f.write('# ' + str(fid) + '. ' + title + '\n\n')
f.write('**Difficulty**: ' + difficulty + '\n\n')
if tags:
f.write('**Tags**: ' + tags + '\n\n')
f.write('---\n\n')
f.write(content)
# Code
ext = LANG_EXT.get(lang, 'txt')
code_path = os.path.join(working_dir, title_slug + '.' + ext)
snippets = detail.get('codeSnippets', [])
code = ''
for s in snippets:
if s.get('langSlug') == lang:
code = s.get('code', '')
break
if not code and snippets:
code = snippets[0].get('code', '')
lang = snippets[0].get('langSlug', lang)
if not code:
code = '# No code template'
if force or not os.path.exists(code_path):
with open(code_path, 'w', encoding='utf-8') as f:
f.write(code)
# JSON
json_path = _problem_json_path(title_slug)
os.makedirs(_problem_cache_dir(), exist_ok=True)
with open(json_path, 'w', encoding='utf-8') as f:
json.dump({
'titleSlug': title_slug,
'frontendQuestionId': fid,
'questionId': detail.get('questionId', ''),
'difficulty': difficulty,
'exampleTestcases': detail.get('exampleTestcases', ''),
'metaData': detail.get('metaData', ''),
'study_plan_slug': study_plan_slug or '',
}, f, ensure_ascii=False, indent=2)
# Interpret: 插 return 桩 → Run Code → 抓预期输出
in_path = _problem_in_path(title_slug)
out_path = _problem_out_path(title_slug)
example = detail.get('exampleTestcases', '')
meta_str = detail.get('metaData', '')
testcases = _parse_testcases(example, meta_str)
question_id = detail.get('questionId', '')
# 检查缓存是否有效
need_interpret = True
if os.path.exists(out_path) and os.path.exists(in_path):
try:
with open(out_path) as f:
cached = json.load(f)
if cached and all(v is not None and v != '' for v in cached):
need_interpret = False
except Exception:
pass
if need_interpret:
stub_code = _insert_return_stubs(code, meta_str)
outputs = []
if _site() != 'cn':
# 美国站 Run Code 被 Cloudflare 拦,跳过,只写空预期输出
outputs = [''] * len(testcases)
else:
try:
sid = self.interpret_solution(title_slug, question_id, lang, stub_code, example)
result_data = self._check_interpret(sid)
expected = result_data.get('expected_code_answer', [])
# 去尾哨兵
while expected and expected[-1] == '':
expected.pop()
for v in expected:
try:
outputs.append(json.loads(v))
except Exception:
outputs.append(v)
except Exception as e:
sublime.error_message('LeetCodeTools: interpret failed\n\n' + str(e))
outputs = [''] * len(testcases)
with open(in_path, 'w', encoding='utf-8') as f:
serializable = []
for tc in testcases:
serializable.append([_to_json(v) for v in tc])
json.dump(serializable, f, ensure_ascii=False, indent=2)
with open(out_path, 'w', encoding='utf-8') as f:
json.dump(outputs, f, ensure_ascii=False, indent=2)
return {
'titleSlug': title_slug, 'fid': fid, 'lang': lang, 'ext': ext,
'md_path': md_path, 'code_path': code_path, 'json_path': json_path,
'in_path': in_path, 'out_path': out_path,
}
def submit_code(self, problem_slug, question_id, lang_slug, typed_code, study_plan_slug=None):
if _site() != 'cn':
raise Exception('美国站 (leetcode.com) 的提交被 Cloudflare 防护,本插件暂不支持 US 提交。请改用网页提交,或把 site 设回 "cn"。')
base_url = _base_url()
url = base_url + '/problems/' + problem_slug + '/submit/'
body = {
'lang': lang_slug,
'question_id': str(question_id),
'typed_code': typed_code,
}
if study_plan_slug:
body['study_plan_slug'] = study_plan_slug
payload = json.dumps(body).encode()
headers = {
'Content-Type': 'application/json',
'Cookie': self.cookie_raw,
'Origin': _base_url(),
'Referer': _base_url() + '/problems/' + problem_slug + '/',
'User-Agent': 'Mozilla/5.0',
}
if self.csrf_token:
headers['X-CSRFToken'] = self.csrf_token
req = urllib.request.Request(url, data=payload, headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as e:
body = ''
try:
body = e.read().decode('utf-8', 'replace')
except Exception:
pass
raise Exception('Submit HTTP %d: %s' % (e.code, body))
res_json = json.loads(resp.read())
if 'submission_id' not in res_json:
raise Exception('Submission failed: ' + str(res_json))
return res_json['submission_id']
def check_submission(self, submission_id):
url = _base_url() + '/submissions/detail/' + str(int(submission_id)) + '/check/'
for _ in range(20):
time.sleep(1)
req = urllib.request.Request(url, headers={
'Cookie': self.cookie_raw,
'User-Agent': 'Mozilla/5.0',
})
resp = urllib.request.urlopen(req, timeout=10)
data = json.loads(resp.read())
state = data.get('state', '')
if state == 'SUCCESS':
return data
raise Exception('Check submission timed out')
def interpret_solution(self, problem_slug, question_id, lang_slug, typed_code, test_input):
"""Run Code(不占提交历史),返回 interpret_id。"""
url = _base_url() + '/problems/' + problem_slug + '/interpret_solution/'
payload = json.dumps({
'lang': lang_slug,
'question_id': str(question_id),
'typed_code': typed_code,
'data_input': test_input,
}).encode()
headers = {
'Content-Type': 'application/json',
'Cookie': self.cookie_raw,
'Origin': _base_url(),
'Referer': _base_url() + '/problems/' + problem_slug + '/',
'User-Agent': 'Mozilla/5.0',
}
if self.csrf_token:
headers['X-CSRFToken'] = self.csrf_token
req = urllib.request.Request(url, data=payload, headers=headers)
resp = urllib.request.urlopen(req, timeout=30)
res = json.loads(resp.read())
if 'interpret_id' not in res:
raise Exception('Interpret failed: ' + str(res))
return res['interpret_id']
def _check_interpret(self, interpret_id):
url = _base_url() + '/submissions/detail/' + str(interpret_id) + '/check/'
for _ in range(20):
time.sleep(1)
req = urllib.request.Request(url, headers={
'Cookie': self.cookie_raw,
'User-Agent': 'Mozilla/5.0',
})
resp = urllib.request.urlopen(req, timeout=10)
data = json.loads(resp.read())
state = data.get('state', '')
if state == 'SUCCESS':
return data
raise Exception('Interpret timed out')
# ── 官方题解 ──
def _find_official_solution(self, title_slug):
query = '''
query questionSolutionArticles($questionSlug: String!, $skip: Int, $first: Int, $orderBy: SolutionArticleOrderBy) {
questionSolutionArticles(questionSlug: $questionSlug, skip: $skip, first: $first, orderBy: $orderBy) {
totalNum
edges {
node {
title
slug
byLeetcode
topic { id }
}
}
}
}
'''
first = 20
skip = 0
while skip < 200:
data = self._graphql(query, {
'questionSlug': title_slug,
'skip': skip,
'first': first,
'orderBy': 'DEFAULT',
})
ps = data.get('questionSolutionArticles') or {}
edges = ps.get('edges') or []
for e in edges:
node = e.get('node') or {}
slug = node.get('slug') or ''
if node.get('byLeetcode') or 'by-leetcode-solution' in slug:
return node
total = ps.get('totalNum') or 0
if skip + first >= total or not edges:
break
skip += first
return None
def _get_solution_detail(self, solution_slug):
query = '''
query solutionArticle($slug: String!) {
solutionArticle(slug: $slug) {
title
content
videosInfo {
videoId
coverUrl
duration
}
}
}
'''
data = self._graphql(query, {'slug': solution_slug})
return data.get('solutionArticle') or {}
def fetch_official_solution(self, title_slug, working_dir=None):
if working_dir is None:
working_dir = _working_dir()
article = self._find_official_solution(title_slug)
if not article:
raise ValueError('No official solution found for: ' + title_slug)
detail = self._get_solution_detail(article.get('slug') or '')
content = _clean_solution_markdown(detail.get('content'), detail.get('videosInfo'))
if not content.strip():
content = '_(题解内容为空)_'
img_dir = _explanation_images_dir(title_slug)
img_ref = os.path.relpath(img_dir, working_dir).replace('\\', '/')
content = _download_markdown_images(content, img_dir, img_ref)
# 原文链接
topic_id = None
topic = article.get('topic')
if isinstance(topic, dict):
topic_id = topic.get('id')
slug = article.get('slug') or ''
url = _base_url() + '/problems/' + title_slug + '/solutions/'
if topic_id:
url += str(topic_id) + '/'
url += slug + '/'
os.makedirs(working_dir, exist_ok=True)
md_path = os.path.join(working_dir, title_slug + '_explanation.md')
with open(md_path, 'w', encoding='utf-8') as f:
f.write('# ' + (article.get('title') or title_slug) + '(官方题解)\n\n')
f.write('> 原文:' + url + '\n\n')
f.write(content)
return md_path
# ── 题集(学习计划)──
def list_study_plans(self):
"""列出全部学习计划(题集),返回 [{slug, name, questionNum, premiumOnly}]。带缓存。"""
cache_path = _study_plans_cache_path()
if _cache_is_fresh(cache_path):
try:
with open(cache_path, 'r', encoding='utf-8') as f:
return json.load(f).get('plans', [])
except Exception:
pass
plans = self._fetch_study_plans()
os.makedirs(_cache_dir(), exist_ok=True)
with open(cache_path, 'w', encoding='utf-8') as f:
json.dump({'timestamp': time.time(), 'plans': plans}, f, ensure_ascii=False)
return plans
def _fetch_study_plans(self):
catalogs_data = self._graphql(
'query { studyPlanV2Catalogs { slug } }')
catalogs = catalogs_data.get('studyPlanV2Catalogs') or []
plans = []
for cat in catalogs:
cat_slug = cat.get('slug') or ''
if not cat_slug:
continue
offset = 0
limit = 100
while True:
data = self._graphql('''
query studyPlansV2ByCatalog($catalogSlug: String!, $offset: Int!, $limit: Int!) {
studyPlansV2ByCatalog(catalogSlug: $catalogSlug, offset: $offset, limit: $limit) {
hasMore
studyPlans {
slug
questionNum
premiumOnly
name
}
}
}
''', {'catalogSlug': cat_slug, 'offset': offset, 'limit': limit})
ps = data.get('studyPlansV2ByCatalog') or {}
for p in (ps.get('studyPlans') or []):
plans.append({
'slug': p.get('slug') or '',
'name': p.get('name') or '',
'questionNum': p.get('questionNum') or 0,
'premiumOnly': bool(p.get('premiumOnly')),
})
if not ps.get('hasMore'):
break
offset += limit
return plans
def get_study_plan_problems(self, plan_slug):
"""列出某个学习计划里的题目,返回 [{frontendQuestionId, title, titleSlug, difficulty}]。带缓存。"""
cache_path = _study_plan_problems_cache_path()
by_slug = {}
if _cache_is_fresh(cache_path):
try:
with open(cache_path, 'r', encoding='utf-8') as f:
by_slug = json.load(f).get('by_slug', {}) or {}
except Exception:
by_slug = {}
if plan_slug in by_slug:
return by_slug[plan_slug]
problems = self._fetch_study_plan_problems(plan_slug)
by_slug[plan_slug] = problems
os.makedirs(_cache_dir(), exist_ok=True)
with open(cache_path, 'w', encoding='utf-8') as f:
json.dump({'timestamp': time.time(), 'by_slug': by_slug}, f, ensure_ascii=False)
return problems
def _fetch_study_plan_problems(self, plan_slug):
query = '''
query studyPlanDetail($slug: String!) {
studyPlanV2Detail(planSlug: $slug) {
name
planSubGroups {
questions {
translatedTitle
titleSlug
title
questionFrontendId
difficulty
}
}
}
}
'''
data = self._graphql(query, {'slug': plan_slug})
detail = data.get('studyPlanV2Detail') or {}
problems = []
for group in (detail.get('planSubGroups') or []):
for q in (group.get('questions') or []):
problems.append({
'frontendQuestionId': str(q.get('questionFrontendId', '')),
'title': q.get('translatedTitle') or q.get('title') or '',
'titleSlug': q.get('titleSlug') or '',
'difficulty': q.get('difficulty') or '',
})
return problems
def refresh_study_plans_cache(self):
"""强制刷新题集列表缓存,并清空题集题目缓存。"""
for p in (_study_plans_cache_path(), _study_plan_problems_cache_path()):
if os.path.exists(p):
os.remove(p)
return self.list_study_plans()
# ── 每日一题 ──
def get_daily_question(self):
"""获取今日的每日一题,返回 {frontendQuestionId, titleSlug, title, difficulty}。"""
query = '''
query questionOfToday {
todayRecord {
date
question {
questionId
questionFrontendId
difficulty
title
translatedTitle
titleSlug
isPaidOnly
}
}
}
'''
data = self._graphql(query)
records = data.get('todayRecord') or []
if not records: