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3
+ import threading
4
+ import time
5
+ from datetime import datetime, timezone, timedelta
6
+ from typing import Any
7
+
8
+ import requests
9
+ import websocket
10
+
11
+ from channel_auth import ChannelWorksClient
12
+
13
+
14
+ ROOM_ID = os.getenv("CW_ROOM_ID")
15
+ CHANNEL_SLUG = os.getenv("CW_CHANNEL_SLUG")
16
+
17
+ CHANNEL_API_URL = f"https://api.channel.works/desk/channels/{ROOM_ID}"
18
+ CHANNEL_LOOKUP_URL = f"https://api.channel.works/desk/channels/{CHANNEL_SLUG}"
19
+ WS_URL = (
20
+ "wss://desk-ws.channel.io/socket.io/"
21
+ "?platform=web&EIO=4&transport=websocket"
22
+ )
23
+
24
+ HEARTBEAT_INTERVAL = 30.0
25
+ TOKEN_CHECK_INTERVAL = 1.0
26
+ REQUEST_TIMEOUT = 30.0
27
+
28
+ JST = timezone(timedelta(hours=9))
29
+
30
+
31
+ def require_env(name: str) -> str:
32
+ value = os.getenv(name)
33
+ if not value:
34
+ raise RuntimeError(f"環境変数 {name} が設定されていません。")
35
+ return value
36
+
37
+
38
+ def get_json(session: requests.Session, url: str) -> Any:
39
+ response = session.get(
40
+ url,
41
+ headers={
42
+ "Accept": "application/json",
43
+ "User-Agent": "Mozilla/5.0",
44
+ },
45
+ timeout=REQUEST_TIMEOUT,
46
+ )
47
+ response.raise_for_status()
48
+
49
+ try:
50
+ return response.json()
51
+ except ValueError as exc:
52
+ raise RuntimeError(
53
+ f"JSONを取得できませんでした: {url}\n"
54
+ f"status={response.status_code}\n"
55
+ f"body={response.text[:500]}"
56
+ ) from exc
57
+
58
+
59
+ def get_nested(data: Any, *path: str) -> Any:
60
+ current = data
61
+ for key in path:
62
+ if not isinstance(current, dict) or key not in current:
63
+ return None
64
+ current = current[key]
65
+ return current
66
+
67
+
68
+ def find_first_key(data: Any, key: str) -> Any:
69
+ """レスポンス形式が多少変わっても id を拾えるように再帰検索する。"""
70
+ if isinstance(data, dict):
71
+ if key in data:
72
+ return data[key]
73
+ for value in data.values():
74
+ result = find_first_key(value, key)
75
+ if result is not None:
76
+ return result
77
+ elif isinstance(data, list):
78
+ for value in data:
79
+ result = find_first_key(value, key)
80
+ if result is not None:
81
+ return result
82
+ return None
83
+
84
+
85
+ def fetch_ids(tokens: dict[str, str]) -> tuple[str, str]:
86
+ session = requests.Session()
87
+
88
+ # ユーザー指定の4トークンを Cookie として付与する。
89
+ session.cookies.update(
90
+ {
91
+ "ch-session-1": tokens["ch-session-1"],
92
+ "ch-veil-id": tokens["ch-veil-id"],
93
+ "x-account": tokens["x-account"],
94
+ "x-account-refresh": tokens["x-account-refresh"],
95
+ }
96
+ )
97
+
98
+ room_json = get_json(session, CHANNEL_API_URL)
99
+ manager_id = get_nested(room_json, "manager", "id")
100
+ if manager_id is None:
101
+ manager_id = find_first_key(room_json, "manager")
102
+ if isinstance(manager_id, dict):
103
+ manager_id = manager_id.get("id")
104
+
105
+ channel_json = get_json(session, CHANNEL_LOOKUP_URL)
106
+ channel_id = get_nested(channel_json, "channel", "id")
107
+ if channel_id is None:
108
+ channel_id = find_first_key(channel_json, "id")
109
+
110
+ if manager_id is None:
111
+ raise RuntimeError(
112
+ f"{CHANNEL_API_URL} のJSONから manager.id を取得できませんでした。"
113
+ )
114
+ if channel_id is None:
115
+ raise RuntimeError(
116
+ f"{CHANNEL_LOOKUP_URL} のJSONから channel.id を取得できませんでした。"
117
+ )
118
+
119
+ return str(manager_id), str(channel_id)
120
+
121
+
122
+ def timestamp_to_text(value: Any) -> str:
123
+ if not isinstance(value, (int, float)):
124
+ return str(value)
125
+
126
+ # UNIX epoch milliseconds を想定。
127
+ if value < 100_000_000_000:
128
+ return str(value)
129
+
130
+ dt_utc = datetime.fromtimestamp(value / 1000, tz=timezone.utc)
131
+ dt_jst = dt_utc.astimezone(JST)
132
+ return (
133
+ f"{dt_jst:%Y-%m-%d %H:%M:%S.%f} JST "
134
+ f"(UTC {dt_utc:%Y-%m-%d %H:%M:%S.%f})"
135
+ )
136
+
137
+
138
+ def format_json_with_timestamps(value: Any, key: str | None = None) -> Any:
139
+ if isinstance(value, dict):
140
+ return {
141
+ k: format_json_with_timestamps(v, k)
142
+ for k, v in value.items()
143
+ }
144
+ if isinstance(value, list):
145
+ return [format_json_with_timestamps(v) for v in value]
146
+ if (
147
+ key
148
+ and key.lower().endswith("at")
149
+ and isinstance(value, (int, float))
150
+ ):
151
+ return {
152
+ "epoch_ms": value,
153
+ "formatted": timestamp_to_text(value),
154
+ }
155
+ return value
156
+
157
+
158
+ def print_create_message(payload: list[Any]) -> None:
159
+ if len(payload) < 2:
160
+ print("[create] payloadが不正です:")
161
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
162
+ return
163
+
164
+ event_name = payload[0]
165
+ entity_wrapper = payload[1]
166
+
167
+ print("\n" + "=" * 80)
168
+ print(f"受信イベント: {event_name}")
169
+
170
+ if not isinstance(entity_wrapper, dict):
171
+ print(json.dumps(
172
+ format_json_with_timestamps(entity_wrapper),
173
+ ensure_ascii=False,
174
+ indent=2,
175
+ ))
176
+ print("=" * 80)
177
+ return
178
+
179
+ entity = entity_wrapper.get("entity", {})
180
+ refers = entity_wrapper.get("refers", {})
181
+
182
+ if isinstance(entity, dict):
183
+ print(f"chatKey : {entity.get('chatKey')}")
184
+ print(f"id : {entity.get('id')}")
185
+ print(f"mainKey : {entity.get('mainKey')}")
186
+ print(f"channelId : {entity.get('channelId')}")
187
+ print(f"chatType : {entity.get('chatType')}")
188
+ print(f"chatId : {entity.get('chatId')}")
189
+ print(f"hubId : {entity.get('hubId')}")
190
+ print(f"personType : {entity.get('personType')}")
191
+ print(f"personId : {entity.get('personId')}")
192
+ print(f"language : {entity.get('language')}")
193
+ print(f"plainText : {entity.get('plainText')}")
194
+ print(f"writingType: {entity.get('writingType')}")
195
+
196
+ for key in ("createdAt", "updatedAt"):
197
+ if key in entity:
198
+ print(f"{key:<11}: {timestamp_to_text(entity[key])}")
199
+
200
+ blocks = entity.get("blocks")
201
+ if blocks:
202
+ print("blocks:")
203
+ for index, block in enumerate(blocks, 1):
204
+ if isinstance(block, dict):
205
+ print(
206
+ f" [{index}] type={block.get('type')} "
207
+ f"value={block.get('value')!r}"
208
+ )
209
+ else:
210
+ print(f" [{index}] {block!r}")
211
+
212
+ print("\n詳細JSON:")
213
+ print(
214
+ json.dumps(
215
+ format_json_with_timestamps(payload),
216
+ ensure_ascii=False,
217
+ indent=2,
218
+ )
219
+ )
220
+ print("=" * 80)
221
+
222
+
223
+ def parse_socketio_event(packet: str) -> tuple[str | None, list[Any] | None]:
224
+ """Socket.IO の 42... パケットを namespace と JSON payload に分解する。"""
225
+ if not packet.startswith("42"):
226
+ return None, None
227
+
228
+ payload_text = packet[2:]
229
+
230
+ # namespace 付き:
231
+ # /desk/channel,["create", {...}]
232
+ if payload_text.startswith("/"):
233
+ try:
234
+ namespace, payload_text = payload_text.split(",", 1)
235
+ except ValueError:
236
+ return None, None
237
+ else:
238
+ namespace = "/"
239
+
240
+ try:
241
+ payload = json.loads(payload_text)
242
+ except json.JSONDecodeError:
243
+ print(f"JSON解析失敗: {packet}")
244
+ return namespace, None
245
+
246
+ if not isinstance(payload, list):
247
+ return namespace, None
248
+
249
+ return namespace, payload
250
+
251
+
252
+ def send_channel_connect(
253
+ ws: websocket.WebSocket,
254
+ session_token: str,
255
+ channel_id: str,
256
+ ) -> None:
257
+ message = (
258
+ '40/desk/channel,'
259
+ + json.dumps(
260
+ {
261
+ "jwt": session_token,
262
+ "channelId": channel_id,
263
+ },
264
+ ensure_ascii=False,
265
+ separators=(",", ":"),
266
+ )
267
+ )
268
+ ws.send(message)
269
+
270
+
271
+ def send_refresh(
272
+ ws: websocket.WebSocket,
273
+ session_token: str,
274
+ ) -> None:
275
+ message = (
276
+ '42/desk/account,0'
277
+ + json.dumps(
278
+ ["refresh", {"jwt": session_token}],
279
+ ensure_ascii=False,
280
+ separators=(",", ":"),
281
+ )
282
+ )
283
+ ws.send(message)
284
+ print("[socket] ch-session-1 の変更を検出したため refresh を送信しました。")
285
+
286
+
287
+ def send_heartbeat(ws: websocket.WebSocket, manager_id: str) -> None:
288
+ message = (
289
+ '42/desk/channel,'
290
+ + json.dumps(
291
+ ["heartbeat", manager_id],
292
+ ensure_ascii=False,
293
+ separators=(",", ":"),
294
+ )
295
+ )
296
+ ws.send(message)
297
+ print("[socket] heartbeat を送信しました。")
298
+
299
+
300
+ def wait_engineio_open(
301
+ ws: websocket.WebSocket,
302
+ session_token: str,
303
+ channel_id: str,
304
+ ) -> None:
305
+ deadline = time.monotonic() + REQUEST_TIMEOUT
306
+
307
+ while time.monotonic() < deadline:
308
+ try:
309
+ packet = ws.recv()
310
+ except websocket.WebSocketTimeoutException:
311
+ continue
312
+
313
+ if packet is None:
314
+ raise RuntimeError("WebSocketが切断されました。")
315
+
316
+ if isinstance(packet, bytes):
317
+ packet = packet.decode("utf-8", errors="replace")
318
+
319
+ if packet.startswith("0"):
320
+ send_channel_connect(ws, session_token, channel_id)
321
+ print("[socket] Engine.IO open を受信し、desk/channel に接続しました。")
322
+ return
323
+
324
+ if packet == "2":
325
+ ws.send("3")
326
+ continue
327
+
328
+ print(f"[socket] 接続待機中に受信: {packet}")
329
+
330
+ raise TimeoutError("Engine.IO open パケットを受信できませんでした。")
331
+
332
+
333
+ def run() -> None:
334
+ room_id = require_env("CW_ROOM_ID") if os.getenv("CW_ROOM_ID") else ROOM_ID
335
+ email = require_env("CW_EMAIL")
336
+ password = require_env("CW_PASSWORD")
337
+
338
+ client = ChannelWorksClient(
339
+ room_id=room_id,
340
+ email=email,
341
+ password=password,
342
+ log_level=ChannelWorksClient.LOG_ERROR,
343
+ touch_interval=600,
344
+ timeout=REQUEST_TIMEOUT,
345
+ )
346
+
347
+ try:
348
+ print("[auth] login...")
349
+ client.login()
350
+ client.start_auto_touch()
351
+
352
+ tokens = client.get_tokens()
353
+ if not tokens:
354
+ raise RuntimeError("get_tokens() が空でした。")
355
+
356
+ required = (
357
+ "ch-session-1",
358
+ "ch-veil-id",
359
+ "x-account",
360
+ "x-account-refresh",
361
+ )
362
+ missing = [key for key in required if not tokens.get(key)]
363
+ if missing:
364
+ raise RuntimeError(
365
+ "必要なトークンが取得できませんでした: "
366
+ + ", ".join(missing)
367
+ )
368
+
369
+ manager_id, channel_id = fetch_ids(tokens)
370
+
371
+ # 実行中に room_id を環境変数で差し替える必要はないため、
372
+ # ログでは取得結果だけ表示し、トークン自体は表示しない。
373
+ print(f"[http] manager.id = {manager_id}")
374
+ print(f"[http] channel.id = {channel_id}")
375
+
376
+ last_session_token = tokens["ch-session-1"]
377
+ ws = websocket.create_connection(
378
+ WS_URL,
379
+ timeout=1.0,
380
+ origin="https://desk.channel.io",
381
+ host="desk-ws.channel.io",
382
+ )
383
+
384
+ try:
385
+ wait_engineio_open(
386
+ ws,
387
+ last_session_token,
388
+ channel_id,
389
+ )
390
+
391
+ last_heartbeat = time.monotonic()
392
+ last_token_check = time.monotonic()
393
+
394
+ print("[socket] 待機中...")
395
+
396
+ while True:
397
+ now = time.monotonic()
398
+
399
+ # 30秒ごとの heartbeat
400
+ if now - last_heartbeat >= HEARTBEAT_INTERVAL:
401
+ send_heartbeat(ws, manager_id)
402
+ last_heartbeat = now
403
+
404
+ # touch により ch-session-1 が更新されたか確認
405
+ if now - last_token_check >= TOKEN_CHECK_INTERVAL:
406
+ current_tokens = client.get_tokens()
407
+ current_session_token = current_tokens.get("ch-session-1")
408
+
409
+ if (
410
+ current_session_token
411
+ and current_session_token != last_session_token
412
+ ):
413
+ send_refresh(ws, current_session_token)
414
+ last_session_token = current_session_token
415
+
416
+ last_token_check = now
417
+
418
+ try:
419
+ packet = ws.recv()
420
+ except websocket.WebSocketTimeoutException:
421
+ continue
422
+
423
+ if packet is None:
424
+ raise RuntimeError("WebSocketが切断されました。")
425
+
426
+ if isinstance(packet, bytes):
427
+ packet = packet.decode("utf-8", errors="replace")
428
+
429
+ # Engine.IO ping -> pong
430
+ if packet == "2":
431
+ ws.send("3")
432
+ continue
433
+
434
+ # Engine.IO pong
435
+ if packet == "3":
436
+ continue
437
+
438
+ namespace, payload = parse_socketio_event(packet)
439
+ if namespace is None or payload is None:
440
+ continue
441
+
442
+ if namespace == "/desk/channel" and payload:
443
+ event_name = payload[0]
444
+
445
+ if event_name == "create":
446
+ print_create_message(payload)
447
+
448
+ finally:
449
+ ws.close()
450
+
451
+ finally:
452
+ client.stop_auto_touch()
453
+
454
+
455
+ if __name__ == "__main__":
456
+ run()