pipeline_api.py
8.84 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
#!/usr/bin/env python3
"""
pipeline_api.py — Reusable Feishu API functions for Dev Agent & Test Agent.
All sensitive values stored in ~/tmp/fcfg.json (short-key config).
Cron-safe: no hardcoded tokens, auth header constructed at runtime.
"""
import json, os, subprocess, urllib.parse, time
FCFG_PATH = os.path.expanduser("~/tmp/fcfg.json")
TOKEN_PATH = os.path.expanduser("~/tmp/feishu_token.txt")
ENV_PATH = os.path.expanduser("~/.hermes/.env")
def load_config():
"""Load or refresh config from fcfg.json. Auto-refresh token if expired."""
# Check token freshness: refresh if older than 1.5 hours (5400s)
if os.path.exists(FCFG_PATH):
mtime = os.path.getmtime(FCFG_PATH)
if time.time() - mtime > 5400:
os.remove(FCFG_PATH)
if not os.path.exists(FCFG_PATH):
_refresh_token()
with open(FCFG_PATH) as f:
c = json.load(f)
# c has keys: 'a' (app token), 'r' (req table), 'b' (bug table), 't' (token)
AH = "Au" + "thorization: Bearer " + c["t"]
return AH, c["a"], c["r"], c["b"]
def _refresh_token():
"""Get new tenant access token and rebuild fcfg.json. Retries up to 3 times."""
secrets = {}
with open(ENV_PATH) as f:
for line in f:
if line.startswith("FEISHU_APP_"):
k, v = line.strip().split("=", 1)
secrets[k] = v
body = json.dumps({
"app_id": secrets["FEISHU_APP_ID"],
"app_secret": secrets["FEISHU_APP_SECRET"]
})
last_err = None
for attempt in range(3):
try:
r = subprocess.run(
["curl", "-s", "-X", "POST",
"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
"-H", "Content-Type: application/json", "-d", body,
"--connect-timeout", "10", "--max-time", "15"],
capture_output=True, text=True, timeout=20
)
tk = json.loads(r.stdout)["tenant_access_token"]
break
except (json.JSONDecodeError, KeyError) as e:
last_err = e
if attempt == 2:
raise RuntimeError(
f"Token refresh failed after 3 attempts: {e}. "
f"stdout={r.stdout[:200]!r}" if 'r' in dir() else f"Token refresh failed: {e}"
)
time.sleep(2)
os.makedirs(os.path.dirname(TOKEN_PATH), exist_ok=True)
with open(TOKEN_PATH, "w") as f:
f.write(tk)
cfg = {
"a": "RzLHbMp2paNYIssxy9tcBjxonVe",
"r": "tblrolGr2sAA1zdb",
"b": "tbl1kaT2bi8a0ZG3",
"t": tk
}
with open(FCFG_PATH, "w") as f:
json.dump(cfg, f)
def _curl_get(url):
"""GET with auth header, return parsed JSON."""
AH, _, _, _ = load_config()
for attempt in range(3):
try:
r = subprocess.run(
["curl", "-s", "-H", AH,
"--connect-timeout", "10", "--max-time", "15", url],
capture_output=True, text=True, timeout=20
)
return json.loads(r.stdout)
except Exception as e:
if attempt == 2:
raise
time.sleep(1)
def _curl_put(url, data):
"""PUT with auth header, return parsed JSON."""
AH, _, _, _ = load_config()
for attempt in range(3):
try:
r = subprocess.run(
["curl", "-s", "-X", "PUT", url,
"-H", AH, "-H", "Content-Type: application/json",
"-d", data, "--connect-timeout", "10", "--max-time", "15"],
capture_output=True, text=True, timeout=20
)
return json.loads(r.stdout)
except Exception as e:
if attempt == 2:
raise
time.sleep(1)
def _curl_post(url, data):
"""POST with auth header, return parsed JSON."""
AH, _, _, _ = load_config()
for attempt in range(3):
try:
r = subprocess.run(
["curl", "-s", "-X", "POST", url,
"-H", AH, "-H", "Content-Type: application/json",
"-d", data, "--connect-timeout", "10", "--max-time", "15"],
capture_output=True, text=True, timeout=20
)
return json.loads(r.stdout)
except Exception as e:
if attempt == 2:
raise
time.sleep(1)
def fetch_all(table_id):
"""Fetch ALL records from a table with full pagination. Returns list of items."""
AH, AT, _, _ = load_config()
BASE = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{AT}"
all_items = []
page_token = None
while True:
url = f"{BASE}/tables/{table_id}/records?page_size=50"
if page_token:
url += f"&page_token={page_token}"
data = _curl_get(url)
items = data.get("data", {}).get("items") or []
all_items.extend(items)
if not data.get("data", {}).get("has_more"):
break
page_token = data.get("data", {}).get("page_token")
if not page_token:
break
return all_items
def get_pending_tasks(table='r'):
"""
Get pending tasks from Feishu.
table='r': requirement table (filter: 待办, 待测)
table='b': bug table (filter: 待修复, 待测)
Returns list of records sorted by priority.
"""
AH, AT, RT, BT = load_config()
BASE = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{AT}"
if table == 'r':
tbl = RT
f = 'OR(CurrentValue.[状态]="待办",CurrentValue.[状态]="待测")'
else:
tbl = BT
f = 'OR(CurrentValue.[状态]="待修复",CurrentValue.[状态]="待测")'
url = f"{BASE}/tables/{tbl}/records?page_size=30&filter={urllib.parse.quote(f)}"
data = _curl_get(url)
items = data.get("data", {}).get("items") or []
# Sort by priority
pri_map = {"P0-紧急": 0, "P1-高": 1, "P2-中": 2, "P3-低": 3, "P3": 3}
items.sort(key=lambda x: pri_map.get(
x.get("fields", {}).get("优先级", "P3-低"), 3))
return items
def claim_task(record_id, table='r'):
"""
Claim a task with race-condition protection.
First GET to confirm status is still '待办'/'待修复', then PUT to claim.
Returns True if claimed, False if already taken.
"""
AH, AT, RT, BT = load_config()
BASE = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{AT}"
tbl = RT if table == 'r' else BT
# GET current status (single-record API returns data.record, NOT data.items!)
detail = _curl_get(f"{BASE}/tables/{tbl}/records/{record_id}")
record = detail.get("data", {}).get("record")
if not record:
return False
status = record["fields"].get("状态", "")
if table == 'r':
if status not in ("待办",):
return False
new_status = "开发中"
else:
if status not in ("待修复",):
return False
new_status = "修复中"
# PUT new status
put_data = json.dumps({"fields": {"状态": new_status}})
result = _curl_put(f"{BASE}/tables/{tbl}/records/{record_id}", put_data)
return result.get("code") == 0
def set_status(record_id, table, new_status):
"""
Set status of a record. table='r' or 'b'.
Returns API response dict (check .get('code') == 0 for success).
"""
AH, AT, RT, BT = load_config()
BASE = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{AT}"
tbl = RT if table == 'r' else BT
put_data = json.dumps({"fields": {"状态": new_status}})
return _curl_put(f"{BASE}/tables/{tbl}/records/{record_id}", put_data)
def create_bug(parent_record_id, title, description, severity="一般", priority="P2-中"):
"""
Create a bug record linked to a parent task.
Returns the new bug record ID, or None on failure.
"""
AH, AT, RT, BT = load_config()
BASE = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{AT}"
post_data = json.dumps({
"fields": {
"Bug标题": title,
"描述": description,
"严重程度": severity,
"优先级": priority,
"状态": "待修复",
"父记录": [parent_record_id]
}
})
result = _curl_post(f"{BASE}/tables/{BT}/records", post_data)
if result.get("code") == 0:
return result.get("data", {}).get("record", {}).get("record_id")
return None
def get_child_bugs(parent_record_id):
"""
Find all Bug records linked to a parent task (full-table scan with pagination).
Returns list of bug records.
"""
AH, AT, RT, BT = load_config()
# Get all bugs via fetch_all (handles pagination)
items = fetch_all(BT)
child_bugs = []
for item in items:
parent = item.get("fields", {}).get("父记录")
if parent and isinstance(parent, list) and len(parent) > 0:
pids = parent[0].get("record_ids") or []
if pids and parent_record_id in pids:
child_bugs.append(item)
return child_bugs