Spaces:
Running
Running
Update get_msg.py
Browse files- get_msg.py +188 -63
get_msg.py
CHANGED
|
@@ -28,6 +28,80 @@ REQUEST_TIMEOUT = 30.0
|
|
| 28 |
JST = timezone(timedelta(hours=9))
|
| 29 |
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
def require_env(name: str) -> str:
|
| 32 |
value = os.getenv(name)
|
| 33 |
if not value:
|
|
@@ -35,7 +109,11 @@ def require_env(name: str) -> str:
|
|
| 35 |
return value
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
| 38 |
def get_json(session: requests.Session, url: str, tokens) -> Any:
|
|
|
|
| 39 |
response = session.get(
|
| 40 |
url,
|
| 41 |
headers={
|
|
@@ -50,10 +128,11 @@ def get_json(session: requests.Session, url: str, tokens) -> Any:
|
|
| 50 |
},
|
| 51 |
timeout=REQUEST_TIMEOUT,
|
| 52 |
)
|
|
|
|
| 53 |
response.raise_for_status()
|
| 54 |
|
| 55 |
try:
|
| 56 |
-
|
| 57 |
except ValueError as exc:
|
| 58 |
raise RuntimeError(
|
| 59 |
f"JSONを取得できませんでした: {url}\n"
|
|
@@ -61,6 +140,13 @@ def get_json(session: requests.Session, url: str, tokens) -> Any:
|
|
| 61 |
f"body={response.text[:500]}"
|
| 62 |
) from exc
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
def get_nested(data: Any, *path: str) -> Any:
|
| 66 |
current = data
|
|
@@ -89,9 +175,9 @@ def find_first_key(data: Any, key: str) -> Any:
|
|
| 89 |
|
| 90 |
|
| 91 |
def fetch_ids(tokens: dict[str, str]) -> tuple[str, str]:
|
|
|
|
| 92 |
session = requests.Session()
|
| 93 |
|
| 94 |
-
# ユーザー指定の4トークンを Cookie として付与する。
|
| 95 |
session.cookies.update(
|
| 96 |
{
|
| 97 |
"ch-session-1": tokens["ch-session-1"],
|
|
@@ -122,14 +208,18 @@ def fetch_ids(tokens: dict[str, str]) -> tuple[str, str]:
|
|
| 122 |
f"{CHANNEL_LOOKUP_URL} のJSONから channel.id を取得できませんでした。"
|
| 123 |
)
|
| 124 |
|
|
|
|
|
|
|
| 125 |
return str(manager_id), str(channel_id)
|
| 126 |
|
| 127 |
|
|
|
|
|
|
|
|
|
|
| 128 |
def timestamp_to_text(value: Any) -> str:
|
| 129 |
if not isinstance(value, (int, float)):
|
| 130 |
return str(value)
|
| 131 |
|
| 132 |
-
# UNIX epoch milliseconds を想定。
|
| 133 |
if value < 100_000_000_000:
|
| 134 |
return str(value)
|
| 135 |
|
|
@@ -163,82 +253,93 @@ def format_json_with_timestamps(value: Any, key: str | None = None) -> Any:
|
|
| 163 |
|
| 164 |
def print_create_message(payload: list[Any]) -> None:
|
| 165 |
if len(payload) < 2:
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
return
|
| 169 |
|
| 170 |
event_name = payload[0]
|
| 171 |
entity_wrapper = payload[1]
|
| 172 |
|
| 173 |
-
|
| 174 |
-
print(f"受信イベント: {event_name}")
|
| 175 |
|
| 176 |
if not isinstance(entity_wrapper, dict):
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
| 183 |
return
|
| 184 |
|
| 185 |
entity = entity_wrapper.get("entity", {})
|
| 186 |
refers = entity_wrapper.get("refers", {})
|
| 187 |
|
| 188 |
if isinstance(entity, dict):
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
|
| 202 |
for key in ("createdAt", "updatedAt"):
|
| 203 |
if key in entity:
|
| 204 |
-
|
| 205 |
|
| 206 |
blocks = entity.get("blocks")
|
| 207 |
if blocks:
|
| 208 |
-
|
| 209 |
for index, block in enumerate(blocks, 1):
|
| 210 |
if isinstance(block, dict):
|
| 211 |
-
|
|
|
|
| 212 |
f" [{index}] type={block.get('type')} "
|
| 213 |
-
f"value={block.get('value')!r}"
|
| 214 |
)
|
| 215 |
else:
|
| 216 |
-
|
| 217 |
|
| 218 |
-
|
| 219 |
-
|
|
|
|
| 220 |
json.dumps(
|
| 221 |
format_json_with_timestamps(payload),
|
| 222 |
ensure_ascii=False,
|
| 223 |
indent=2,
|
| 224 |
-
)
|
| 225 |
)
|
| 226 |
-
print("=" * 80)
|
| 227 |
|
| 228 |
|
|
|
|
|
|
|
|
|
|
| 229 |
def parse_socketio_event(packet: str) -> tuple[str | None, list[Any] | None]:
|
| 230 |
"""Socket.IO の 42... パケットを namespace と JSON payload に分解する。"""
|
|
|
|
| 231 |
if not packet.startswith("42"):
|
|
|
|
| 232 |
return None, None
|
| 233 |
|
| 234 |
payload_text = packet[2:]
|
| 235 |
|
| 236 |
-
# namespace 付き:
|
| 237 |
-
# /desk/channel,["create", {...}]
|
| 238 |
if payload_text.startswith("/"):
|
| 239 |
try:
|
| 240 |
namespace, payload_text = payload_text.split(",", 1)
|
| 241 |
except ValueError:
|
|
|
|
| 242 |
return None, None
|
| 243 |
else:
|
| 244 |
namespace = "/"
|
|
@@ -246,17 +347,19 @@ def parse_socketio_event(packet: str) -> tuple[str | None, list[Any] | None]:
|
|
| 246 |
try:
|
| 247 |
payload = json.loads(payload_text)
|
| 248 |
except json.JSONDecodeError:
|
| 249 |
-
|
| 250 |
return namespace, None
|
| 251 |
|
| 252 |
if not isinstance(payload, list):
|
|
|
|
| 253 |
return namespace, None
|
| 254 |
|
|
|
|
| 255 |
return namespace, payload
|
| 256 |
|
| 257 |
|
| 258 |
def send_channel_connect(
|
| 259 |
-
ws:
|
| 260 |
session_token: str,
|
| 261 |
channel_id: str,
|
| 262 |
) -> None:
|
|
@@ -271,11 +374,12 @@ def send_channel_connect(
|
|
| 271 |
separators=(",", ":"),
|
| 272 |
)
|
| 273 |
)
|
|
|
|
| 274 |
ws.send(message)
|
| 275 |
|
| 276 |
|
| 277 |
def send_refresh(
|
| 278 |
-
ws:
|
| 279 |
session_token: str,
|
| 280 |
) -> None:
|
| 281 |
message = (
|
|
@@ -286,11 +390,11 @@ def send_refresh(
|
|
| 286 |
separators=(",", ":"),
|
| 287 |
)
|
| 288 |
)
|
|
|
|
| 289 |
ws.send(message)
|
| 290 |
-
print("[socket] ch-session-1 の変更を検出したため refresh を送信しました。")
|
| 291 |
|
| 292 |
|
| 293 |
-
def send_heartbeat(ws:
|
| 294 |
message = (
|
| 295 |
'42/desk/channel,'
|
| 296 |
+ json.dumps(
|
|
@@ -299,48 +403,63 @@ def send_heartbeat(ws: websocket.WebSocket, manager_id: str) -> None:
|
|
| 299 |
separators=(",", ":"),
|
| 300 |
)
|
| 301 |
)
|
|
|
|
| 302 |
ws.send(message)
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
|
| 306 |
def wait_engineio_open(
|
| 307 |
-
ws:
|
| 308 |
session_token: str,
|
| 309 |
channel_id: str,
|
| 310 |
) -> None:
|
|
|
|
| 311 |
deadline = time.monotonic() + REQUEST_TIMEOUT
|
| 312 |
|
| 313 |
while time.monotonic() < deadline:
|
| 314 |
try:
|
| 315 |
packet = ws.recv()
|
| 316 |
except websocket.WebSocketTimeoutException:
|
|
|
|
| 317 |
continue
|
| 318 |
|
| 319 |
if packet is None:
|
| 320 |
raise RuntimeError("WebSocketが切断されました。")
|
| 321 |
|
| 322 |
-
if isinstance(packet, bytes):
|
| 323 |
-
packet = packet.decode("utf-8", errors="replace")
|
| 324 |
-
|
| 325 |
if packet.startswith("0"):
|
|
|
|
| 326 |
send_channel_connect(ws, session_token, channel_id)
|
| 327 |
-
|
| 328 |
return
|
| 329 |
|
| 330 |
if packet == "2":
|
| 331 |
-
|
| 332 |
continue
|
| 333 |
|
| 334 |
-
|
| 335 |
|
| 336 |
raise TimeoutError("Engine.IO open パケットを受信できませんでした。")
|
| 337 |
|
| 338 |
|
|
|
|
|
|
|
|
|
|
| 339 |
def run() -> None:
|
|
|
|
| 340 |
room_id = require_env("CW_ROOM_ID") if os.getenv("CW_ROOM_ID") else ROOM_ID
|
| 341 |
email = require_env("CW_EMAIL")
|
| 342 |
password = require_env("CW_PASSWORD")
|
| 343 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
client = ChannelWorksClient(
|
| 345 |
room_id=room_id,
|
| 346 |
email=email,
|
|
@@ -351,9 +470,11 @@ def run() -> None:
|
|
| 351 |
)
|
| 352 |
|
| 353 |
try:
|
| 354 |
-
|
| 355 |
client.login()
|
|
|
|
| 356 |
client.start_auto_touch()
|
|
|
|
| 357 |
|
| 358 |
tokens = client.get_tokens()
|
| 359 |
if not tokens:
|
|
@@ -371,21 +492,23 @@ def run() -> None:
|
|
| 371 |
"必要なトークンが取得できませんでした: "
|
| 372 |
+ ", ".join(missing)
|
| 373 |
)
|
|
|
|
| 374 |
|
| 375 |
manager_id, channel_id = fetch_ids(tokens)
|
| 376 |
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
print(f"[http] manager.id = {manager_id}")
|
| 380 |
-
print(f"[http] channel.id = {channel_id}")
|
| 381 |
|
| 382 |
last_session_token = tokens["ch-session-1"]
|
| 383 |
-
|
|
|
|
| 384 |
WS_URL,
|
| 385 |
timeout=1.0,
|
| 386 |
origin="https://desk.channel.io",
|
| 387 |
host="desk-ws.channel.io",
|
| 388 |
)
|
|
|
|
|
|
|
| 389 |
|
| 390 |
try:
|
| 391 |
wait_engineio_open(
|
|
@@ -397,17 +520,15 @@ def run() -> None:
|
|
| 397 |
last_heartbeat = time.monotonic()
|
| 398 |
last_token_check = time.monotonic()
|
| 399 |
|
| 400 |
-
|
| 401 |
|
| 402 |
while True:
|
| 403 |
now = time.monotonic()
|
| 404 |
|
| 405 |
-
# 30秒ごとの heartbeat
|
| 406 |
if now - last_heartbeat >= HEARTBEAT_INTERVAL:
|
| 407 |
send_heartbeat(ws, manager_id)
|
| 408 |
last_heartbeat = now
|
| 409 |
|
| 410 |
-
# touch により ch-session-1 が更新されたか確認
|
| 411 |
if now - last_token_check >= TOKEN_CHECK_INTERVAL:
|
| 412 |
current_tokens = client.get_tokens()
|
| 413 |
current_session_token = current_tokens.get("ch-session-1")
|
|
@@ -416,6 +537,10 @@ def run() -> None:
|
|
| 416 |
current_session_token
|
| 417 |
and current_session_token != last_session_token
|
| 418 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
send_refresh(ws, current_session_token)
|
| 420 |
last_session_token = current_session_token
|
| 421 |
|
|
@@ -429,16 +554,14 @@ def run() -> None:
|
|
| 429 |
if packet is None:
|
| 430 |
raise RuntimeError("WebSocketが切断されました。")
|
| 431 |
|
| 432 |
-
if isinstance(packet, bytes):
|
| 433 |
-
packet = packet.decode("utf-8", errors="replace")
|
| 434 |
-
|
| 435 |
# Engine.IO ping -> pong
|
| 436 |
if packet == "2":
|
| 437 |
-
|
| 438 |
continue
|
| 439 |
|
| 440 |
# Engine.IO pong
|
| 441 |
if packet == "3":
|
|
|
|
| 442 |
continue
|
| 443 |
|
| 444 |
namespace, payload = parse_socketio_event(packet)
|
|
@@ -447,6 +570,7 @@ def run() -> None:
|
|
| 447 |
|
| 448 |
if namespace == "/desk/channel" and payload:
|
| 449 |
event_name = payload[0]
|
|
|
|
| 450 |
|
| 451 |
if event_name == "create":
|
| 452 |
print_create_message(payload)
|
|
@@ -456,7 +580,8 @@ def run() -> None:
|
|
| 456 |
|
| 457 |
finally:
|
| 458 |
client.stop_auto_touch()
|
|
|
|
| 459 |
|
| 460 |
|
| 461 |
if __name__ == "__main__":
|
| 462 |
-
run()
|
|
|
|
| 28 |
JST = timezone(timedelta(hours=9))
|
| 29 |
|
| 30 |
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
# ログ用ヘルパ
|
| 33 |
+
# ---------------------------------------------------------------------------
|
| 34 |
+
def log(tag: str, message: str) -> None:
|
| 35 |
+
now = datetime.now(JST).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
| 36 |
+
print(f"[{now}] [{tag}] {message}", flush=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def log_block(tag: str, title: str, body: str) -> None:
|
| 40 |
+
now = datetime.now(JST).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
| 41 |
+
print(f"\n[{now}] [{tag}] ===== {title} =====", flush=True)
|
| 42 |
+
print(body, flush=True)
|
| 43 |
+
print(f"[{now}] [{tag}] ===== /{title} =====", flush=True)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
# WebSocket ラッパ(送受信ログ付き)
|
| 48 |
+
# ---------------------------------------------------------------------------
|
| 49 |
+
class LoggingWS:
|
| 50 |
+
"""websocket.WebSocket をラップして送受信を必ずログ出力する。"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, ws: websocket.WebSocket) -> None:
|
| 53 |
+
self._ws = ws
|
| 54 |
+
self._send_count = 0
|
| 55 |
+
self._recv_count = 0
|
| 56 |
+
|
| 57 |
+
# --- 送信 ---
|
| 58 |
+
def send(self, payload: str | bytes) -> None:
|
| 59 |
+
self._send_count += 1
|
| 60 |
+
text = (
|
| 61 |
+
payload.decode("utf-8", errors="replace")
|
| 62 |
+
if isinstance(payload, (bytes, bytearray))
|
| 63 |
+
else payload
|
| 64 |
+
)
|
| 65 |
+
log_block(
|
| 66 |
+
"WS-SEND",
|
| 67 |
+
f"#{self._send_count} ({len(text)} bytes)",
|
| 68 |
+
text,
|
| 69 |
+
)
|
| 70 |
+
self._ws.send(payload)
|
| 71 |
+
|
| 72 |
+
# --- 受信 ---
|
| 73 |
+
def recv(self) -> str | bytes | None:
|
| 74 |
+
packet = self._ws.recv()
|
| 75 |
+
self._recv_count += 1
|
| 76 |
+
if packet is None:
|
| 77 |
+
log("WS-RECV", f"#{self._recv_count} (None / 切断)")
|
| 78 |
+
return None
|
| 79 |
+
text = (
|
| 80 |
+
packet.decode("utf-8", errors="replace")
|
| 81 |
+
if isinstance(packet, (bytes, bytearray))
|
| 82 |
+
else packet
|
| 83 |
+
)
|
| 84 |
+
log_block(
|
| 85 |
+
"WS-RECV",
|
| 86 |
+
f"#{self._recv_count} ({len(text)} chars)",
|
| 87 |
+
text,
|
| 88 |
+
)
|
| 89 |
+
return text
|
| 90 |
+
|
| 91 |
+
def close(self) -> None:
|
| 92 |
+
try:
|
| 93 |
+
self._ws.close()
|
| 94 |
+
finally:
|
| 95 |
+
log("WS", "WebSocket をクローズしました。")
|
| 96 |
+
|
| 97 |
+
def __getattr__(self, name: str) -> Any:
|
| 98 |
+
# 未定義の属性は元の WebSocket に委譲
|
| 99 |
+
return getattr(self._ws, name)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ---------------------------------------------------------------------------
|
| 103 |
+
# 環境変数
|
| 104 |
+
# ---------------------------------------------------------------------------
|
| 105 |
def require_env(name: str) -> str:
|
| 106 |
value = os.getenv(name)
|
| 107 |
if not value:
|
|
|
|
| 109 |
return value
|
| 110 |
|
| 111 |
|
| 112 |
+
# ---------------------------------------------------------------------------
|
| 113 |
+
# HTTP
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
def get_json(session: requests.Session, url: str, tokens) -> Any:
|
| 116 |
+
log("HTTP", f"GET {url}")
|
| 117 |
response = session.get(
|
| 118 |
url,
|
| 119 |
headers={
|
|
|
|
| 128 |
},
|
| 129 |
timeout=REQUEST_TIMEOUT,
|
| 130 |
)
|
| 131 |
+
log("HTTP", f"-> status={response.status_code} ({url})")
|
| 132 |
response.raise_for_status()
|
| 133 |
|
| 134 |
try:
|
| 135 |
+
data = response.json()
|
| 136 |
except ValueError as exc:
|
| 137 |
raise RuntimeError(
|
| 138 |
f"JSONを取得できませんでした: {url}\n"
|
|
|
|
| 140 |
f"body={response.text[:500]}"
|
| 141 |
) from exc
|
| 142 |
|
| 143 |
+
log_block(
|
| 144 |
+
"HTTP-BODY",
|
| 145 |
+
url,
|
| 146 |
+
json.dumps(data, ensure_ascii=False, indent=2),
|
| 147 |
+
)
|
| 148 |
+
return data
|
| 149 |
+
|
| 150 |
|
| 151 |
def get_nested(data: Any, *path: str) -> Any:
|
| 152 |
current = data
|
|
|
|
| 175 |
|
| 176 |
|
| 177 |
def fetch_ids(tokens: dict[str, str]) -> tuple[str, str]:
|
| 178 |
+
log("HTTP", "fetch_ids 開始")
|
| 179 |
session = requests.Session()
|
| 180 |
|
|
|
|
| 181 |
session.cookies.update(
|
| 182 |
{
|
| 183 |
"ch-session-1": tokens["ch-session-1"],
|
|
|
|
| 208 |
f"{CHANNEL_LOOKUP_URL} のJSONから channel.id を取得できませんでした。"
|
| 209 |
)
|
| 210 |
|
| 211 |
+
log("HTTP", f"manager.id = {manager_id}")
|
| 212 |
+
log("HTTP", f"channel.id = {channel_id}")
|
| 213 |
return str(manager_id), str(channel_id)
|
| 214 |
|
| 215 |
|
| 216 |
+
# ---------------------------------------------------------------------------
|
| 217 |
+
# 表示整形
|
| 218 |
+
# ---------------------------------------------------------------------------
|
| 219 |
def timestamp_to_text(value: Any) -> str:
|
| 220 |
if not isinstance(value, (int, float)):
|
| 221 |
return str(value)
|
| 222 |
|
|
|
|
| 223 |
if value < 100_000_000_000:
|
| 224 |
return str(value)
|
| 225 |
|
|
|
|
| 253 |
|
| 254 |
def print_create_message(payload: list[Any]) -> None:
|
| 255 |
if len(payload) < 2:
|
| 256 |
+
log("CREATE", "payloadが不正です:")
|
| 257 |
+
log_block(
|
| 258 |
+
"CREATE",
|
| 259 |
+
"payload",
|
| 260 |
+
json.dumps(payload, ensure_ascii=False, indent=2),
|
| 261 |
+
)
|
| 262 |
return
|
| 263 |
|
| 264 |
event_name = payload[0]
|
| 265 |
entity_wrapper = payload[1]
|
| 266 |
|
| 267 |
+
log("CREATE", f"受信イベント: {event_name}")
|
|
|
|
| 268 |
|
| 269 |
if not isinstance(entity_wrapper, dict):
|
| 270 |
+
log_block(
|
| 271 |
+
"CREATE",
|
| 272 |
+
"entity_wrapper",
|
| 273 |
+
json.dumps(
|
| 274 |
+
format_json_with_timestamps(entity_wrapper),
|
| 275 |
+
ensure_ascii=False,
|
| 276 |
+
indent=2,
|
| 277 |
+
),
|
| 278 |
+
)
|
| 279 |
return
|
| 280 |
|
| 281 |
entity = entity_wrapper.get("entity", {})
|
| 282 |
refers = entity_wrapper.get("refers", {})
|
| 283 |
|
| 284 |
if isinstance(entity, dict):
|
| 285 |
+
log("CREATE", f"chatKey : {entity.get('chatKey')}")
|
| 286 |
+
log("CREATE", f"id : {entity.get('id')}")
|
| 287 |
+
log("CREATE", f"mainKey : {entity.get('mainKey')}")
|
| 288 |
+
log("CREATE", f"channelId : {entity.get('channelId')}")
|
| 289 |
+
log("CREATE", f"chatType : {entity.get('chatType')}")
|
| 290 |
+
log("CREATE", f"chatId : {entity.get('chatId')}")
|
| 291 |
+
log("CREATE", f"hubId : {entity.get('hubId')}")
|
| 292 |
+
log("CREATE", f"personType : {entity.get('personType')}")
|
| 293 |
+
log("CREATE", f"personId : {entity.get('personId')}")
|
| 294 |
+
log("CREATE", f"language : {entity.get('language')}")
|
| 295 |
+
log("CREATE", f"plainText : {entity.get('plainText')}")
|
| 296 |
+
log("CREATE", f"writingType: {entity.get('writingType')}")
|
| 297 |
|
| 298 |
for key in ("createdAt", "updatedAt"):
|
| 299 |
if key in entity:
|
| 300 |
+
log("CREATE", f"{key:<11}: {timestamp_to_text(entity[key])}")
|
| 301 |
|
| 302 |
blocks = entity.get("blocks")
|
| 303 |
if blocks:
|
| 304 |
+
log("CREATE", "blocks:")
|
| 305 |
for index, block in enumerate(blocks, 1):
|
| 306 |
if isinstance(block, dict):
|
| 307 |
+
log(
|
| 308 |
+
"CREATE",
|
| 309 |
f" [{index}] type={block.get('type')} "
|
| 310 |
+
f"value={block.get('value')!r}",
|
| 311 |
)
|
| 312 |
else:
|
| 313 |
+
log("CREATE", f" [{index}] {block!r}")
|
| 314 |
|
| 315 |
+
log_block(
|
| 316 |
+
"CREATE",
|
| 317 |
+
"詳細JSON",
|
| 318 |
json.dumps(
|
| 319 |
format_json_with_timestamps(payload),
|
| 320 |
ensure_ascii=False,
|
| 321 |
indent=2,
|
| 322 |
+
),
|
| 323 |
)
|
|
|
|
| 324 |
|
| 325 |
|
| 326 |
+
# ---------------------------------------------------------------------------
|
| 327 |
+
# Socket.IO / Engine.IO
|
| 328 |
+
# ---------------------------------------------------------------------------
|
| 329 |
def parse_socketio_event(packet: str) -> tuple[str | None, list[Any] | None]:
|
| 330 |
"""Socket.IO の 42... パケットを namespace と JSON payload に分解する。"""
|
| 331 |
+
log("PARSE", f"packet={packet!r}")
|
| 332 |
if not packet.startswith("42"):
|
| 333 |
+
log("PARSE", "-> Socket.IO イベント(42)ではありません。")
|
| 334 |
return None, None
|
| 335 |
|
| 336 |
payload_text = packet[2:]
|
| 337 |
|
|
|
|
|
|
|
| 338 |
if payload_text.startswith("/"):
|
| 339 |
try:
|
| 340 |
namespace, payload_text = payload_text.split(",", 1)
|
| 341 |
except ValueError:
|
| 342 |
+
log("PARSE", "-> namespace と payload の分離に失敗しました。")
|
| 343 |
return None, None
|
| 344 |
else:
|
| 345 |
namespace = "/"
|
|
|
|
| 347 |
try:
|
| 348 |
payload = json.loads(payload_text)
|
| 349 |
except json.JSONDecodeError:
|
| 350 |
+
log("PARSE", f"-> JSON解析失敗: {payload_text!r}")
|
| 351 |
return namespace, None
|
| 352 |
|
| 353 |
if not isinstance(payload, list):
|
| 354 |
+
log("PARSE", "-> payload がリストではありません。")
|
| 355 |
return namespace, None
|
| 356 |
|
| 357 |
+
log("PARSE", f"-> namespace={namespace}, payload={payload!r}")
|
| 358 |
return namespace, payload
|
| 359 |
|
| 360 |
|
| 361 |
def send_channel_connect(
|
| 362 |
+
ws: LoggingWS,
|
| 363 |
session_token: str,
|
| 364 |
channel_id: str,
|
| 365 |
) -> None:
|
|
|
|
| 374 |
separators=(",", ":"),
|
| 375 |
)
|
| 376 |
)
|
| 377 |
+
log("SOCKET", f"channel connect 送信: channelId={channel_id}")
|
| 378 |
ws.send(message)
|
| 379 |
|
| 380 |
|
| 381 |
def send_refresh(
|
| 382 |
+
ws: LoggingWS,
|
| 383 |
session_token: str,
|
| 384 |
) -> None:
|
| 385 |
message = (
|
|
|
|
| 390 |
separators=(",", ":"),
|
| 391 |
)
|
| 392 |
)
|
| 393 |
+
log("SOCKET", "refresh を送信します。")
|
| 394 |
ws.send(message)
|
|
|
|
| 395 |
|
| 396 |
|
| 397 |
+
def send_heartbeat(ws: LoggingWS, manager_id: str) -> None:
|
| 398 |
message = (
|
| 399 |
'42/desk/channel,'
|
| 400 |
+ json.dumps(
|
|
|
|
| 403 |
separators=(",", ":"),
|
| 404 |
)
|
| 405 |
)
|
| 406 |
+
log("SOCKET", f"heartbeat 送信: manager_id={manager_id}")
|
| 407 |
ws.send(message)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def send_pong(ws: LoggingWS) -> None:
|
| 411 |
+
"""Engine.IO ping(2) に対する pong(3)。"""
|
| 412 |
+
log("SOCKET", "Engine.IO ping(2) を受信 -> pong(3) を返します。")
|
| 413 |
+
ws.send("3")
|
| 414 |
|
| 415 |
|
| 416 |
def wait_engineio_open(
|
| 417 |
+
ws: LoggingWS,
|
| 418 |
session_token: str,
|
| 419 |
channel_id: str,
|
| 420 |
) -> None:
|
| 421 |
+
log("SOCKET", "Engine.IO open 待機開始")
|
| 422 |
deadline = time.monotonic() + REQUEST_TIMEOUT
|
| 423 |
|
| 424 |
while time.monotonic() < deadline:
|
| 425 |
try:
|
| 426 |
packet = ws.recv()
|
| 427 |
except websocket.WebSocketTimeoutException:
|
| 428 |
+
log("SOCKET", "recv タイムアウト(待機継続)")
|
| 429 |
continue
|
| 430 |
|
| 431 |
if packet is None:
|
| 432 |
raise RuntimeError("WebSocketが切断されました。")
|
| 433 |
|
|
|
|
|
|
|
|
|
|
| 434 |
if packet.startswith("0"):
|
| 435 |
+
log("SOCKET", "Engine.IO open パケットを受信しました。")
|
| 436 |
send_channel_connect(ws, session_token, channel_id)
|
| 437 |
+
log("SOCKET", "desk/channel に接続しました。")
|
| 438 |
return
|
| 439 |
|
| 440 |
if packet == "2":
|
| 441 |
+
send_pong(ws)
|
| 442 |
continue
|
| 443 |
|
| 444 |
+
log("SOCKET", f"接続待機中に受信: {packet!r}")
|
| 445 |
|
| 446 |
raise TimeoutError("Engine.IO open パケットを受信できませんでした。")
|
| 447 |
|
| 448 |
|
| 449 |
+
# ---------------------------------------------------------------------------
|
| 450 |
+
# メイン
|
| 451 |
+
# ---------------------------------------------------------------------------
|
| 452 |
def run() -> None:
|
| 453 |
+
log("MAIN", "起動")
|
| 454 |
room_id = require_env("CW_ROOM_ID") if os.getenv("CW_ROOM_ID") else ROOM_ID
|
| 455 |
email = require_env("CW_EMAIL")
|
| 456 |
password = require_env("CW_PASSWORD")
|
| 457 |
|
| 458 |
+
log("MAIN", f"room_id={room_id}")
|
| 459 |
+
log("MAIN", f"CHANNEL_API_URL={CHANNEL_API_URL}")
|
| 460 |
+
log("MAIN", f"CHANNEL_LOOKUP_URL={CHANNEL_LOOKUP_URL}")
|
| 461 |
+
log("MAIN", f"WS_URL={WS_URL}")
|
| 462 |
+
|
| 463 |
client = ChannelWorksClient(
|
| 464 |
room_id=room_id,
|
| 465 |
email=email,
|
|
|
|
| 470 |
)
|
| 471 |
|
| 472 |
try:
|
| 473 |
+
log("AUTH", "login...")
|
| 474 |
client.login()
|
| 475 |
+
log("AUTH", "login 完了")
|
| 476 |
client.start_auto_touch()
|
| 477 |
+
log("AUTH", "auto_touch 開始")
|
| 478 |
|
| 479 |
tokens = client.get_tokens()
|
| 480 |
if not tokens:
|
|
|
|
| 492 |
"必要なトークンが取得できませんでした: "
|
| 493 |
+ ", ".join(missing)
|
| 494 |
)
|
| 495 |
+
log("AUTH", f"トークン取得 OK({len(tokens)} 件)")
|
| 496 |
|
| 497 |
manager_id, channel_id = fetch_ids(tokens)
|
| 498 |
|
| 499 |
+
log("HTTP", f"manager.id = {manager_id}")
|
| 500 |
+
log("HTTP", f"channel.id = {channel_id}")
|
|
|
|
|
|
|
| 501 |
|
| 502 |
last_session_token = tokens["ch-session-1"]
|
| 503 |
+
|
| 504 |
+
raw_ws = websocket.create_connection(
|
| 505 |
WS_URL,
|
| 506 |
timeout=1.0,
|
| 507 |
origin="https://desk.channel.io",
|
| 508 |
host="desk-ws.channel.io",
|
| 509 |
)
|
| 510 |
+
log("WS", "WebSocket 接続完了")
|
| 511 |
+
ws = LoggingWS(raw_ws)
|
| 512 |
|
| 513 |
try:
|
| 514 |
wait_engineio_open(
|
|
|
|
| 520 |
last_heartbeat = time.monotonic()
|
| 521 |
last_token_check = time.monotonic()
|
| 522 |
|
| 523 |
+
log("SOCKET", "待機中...")
|
| 524 |
|
| 525 |
while True:
|
| 526 |
now = time.monotonic()
|
| 527 |
|
|
|
|
| 528 |
if now - last_heartbeat >= HEARTBEAT_INTERVAL:
|
| 529 |
send_heartbeat(ws, manager_id)
|
| 530 |
last_heartbeat = now
|
| 531 |
|
|
|
|
| 532 |
if now - last_token_check >= TOKEN_CHECK_INTERVAL:
|
| 533 |
current_tokens = client.get_tokens()
|
| 534 |
current_session_token = current_tokens.get("ch-session-1")
|
|
|
|
| 537 |
current_session_token
|
| 538 |
and current_session_token != last_session_token
|
| 539 |
):
|
| 540 |
+
log(
|
| 541 |
+
"AUTH",
|
| 542 |
+
"ch-session-1 の変更を検出しました。",
|
| 543 |
+
)
|
| 544 |
send_refresh(ws, current_session_token)
|
| 545 |
last_session_token = current_session_token
|
| 546 |
|
|
|
|
| 554 |
if packet is None:
|
| 555 |
raise RuntimeError("WebSocketが切断されました。")
|
| 556 |
|
|
|
|
|
|
|
|
|
|
| 557 |
# Engine.IO ping -> pong
|
| 558 |
if packet == "2":
|
| 559 |
+
send_pong(ws)
|
| 560 |
continue
|
| 561 |
|
| 562 |
# Engine.IO pong
|
| 563 |
if packet == "3":
|
| 564 |
+
log("SOCKET", "Engine.IO pong(3) を受信(無視)")
|
| 565 |
continue
|
| 566 |
|
| 567 |
namespace, payload = parse_socketio_event(packet)
|
|
|
|
| 570 |
|
| 571 |
if namespace == "/desk/channel" and payload:
|
| 572 |
event_name = payload[0]
|
| 573 |
+
log("SOCKET", f"event={event_name}")
|
| 574 |
|
| 575 |
if event_name == "create":
|
| 576 |
print_create_message(payload)
|
|
|
|
| 580 |
|
| 581 |
finally:
|
| 582 |
client.stop_auto_touch()
|
| 583 |
+
log("AUTH", "auto_touch 停止")
|
| 584 |
|
| 585 |
|
| 586 |
if __name__ == "__main__":
|
| 587 |
+
run()
|