izuemon commited on
Commit
af459a7
·
verified ·
1 Parent(s): 9811cec

Create channel_auth.py

Browse files
Files changed (1) hide show
  1. channel_auth.py +373 -0
channel_auth.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ChannelWorks クライアントライブラリ
3
+
4
+ 使い方:
5
+ from channel_works import ChannelWorksClient
6
+
7
+ client = ChannelWorksClient(
8
+ email="you@example.com",
9
+ password="your-password",
10
+ log_level=ChannelWorksClient.LOG_DEBUG,
11
+ )
12
+ client.login() # sign_in + boot
13
+ client.start_auto_touch() # 10分ごとに自動で touch を叩いてトークン更新
14
+ tokens = client.get_tokens() # 最新トークンを取得
15
+ ...
16
+ client.stop_auto_touch()
17
+
18
+ log_level:
19
+ 0 = 何も出力しない
20
+ 1 = エラー・警告のみ (デフォルト)
21
+ 2 = デバッグログも出力
22
+ """
23
+
24
+ import json
25
+ import threading
26
+ from collections import OrderedDict
27
+ from urllib.parse import urlencode
28
+
29
+ import requests
30
+
31
+
32
+ SIGN_IN_URI = "https://api.channel.works/desk/account/sign-in"
33
+ BOOT_URI = "https://api.channel.io/front/v8/elastic/plugins/b823a684-f97e-4e4e-bf12-48b70c1939ae/boot"
34
+ TOUCH_URI = "https://api.channel.works/desk/account/touch"
35
+
36
+ BOOT_URL_TEMPLATE = "https://channel.works/{room_id}/user-chats"
37
+ BOOT_AVATAR_URL = "https://cf.channel.io/avatar/emoji/bee.f7dc8e.png"
38
+
39
+ DEFAULT_TOUCH_INTERVAL = 600 # 10 分
40
+
41
+ # Set-Cookie から抜き出す対象トークン
42
+ _TOKEN_NAMES = ("x-account", "x-account-refresh", "ch-session-1", "ch-veil-id")
43
+
44
+
45
+ class ChannelWorksClient:
46
+ # ログレベル
47
+ LOG_NONE = 0
48
+ LOG_ERROR = 1
49
+ LOG_DEBUG = 2
50
+
51
+ def __init__(
52
+ self,
53
+ room_id,
54
+ email=None,
55
+ password=None,
56
+ log_level=LOG_ERROR,
57
+ touch_interval=DEFAULT_TOUCH_INTERVAL,
58
+ timeout=30,
59
+ ):
60
+ if not room_id:
61
+ raise ValueError("room_id は必須です。")
62
+
63
+ self.room_id = room_id
64
+ self.email = email
65
+ self.password = password
66
+ self.log_level = log_level
67
+ self.touch_interval = touch_interval
68
+ self.timeout = timeout
69
+
70
+ self._lock = threading.RLock()
71
+
72
+ # 最新トークン(この値は常に上書きされる。固定値にはならない)
73
+ self._x_account = None
74
+ self._x_account_refresh = None
75
+ self._ch_session_1 = None
76
+ self._ch_veil_id = None
77
+
78
+ # boot に必要なアカウント情報
79
+ self._account_name = None
80
+ self._account_email = None
81
+ self._account_id = None
82
+ self._member_hash = None
83
+
84
+ # 自動 touch 用スレッド
85
+ self._touch_thread = None
86
+ self._touch_stop = threading.Event()
87
+
88
+ # ------------------------------------------------------------------
89
+ # ログ
90
+ # ------------------------------------------------------------------
91
+ def _log_debug(self, msg):
92
+ if self.log_level >= self.LOG_DEBUG:
93
+ print(f"[DEBUG] {msg}")
94
+
95
+ def _log_error(self, msg):
96
+ if self.log_level >= self.LOG_ERROR:
97
+ print(f"[ERROR] {msg}")
98
+
99
+ def set_log_level(self, level):
100
+ self.log_level = level
101
+
102
+ # ------------------------------------------------------------------
103
+ # 内部ユーティリティ
104
+ # ------------------------------------------------------------------
105
+ @staticmethod
106
+ def _common_headers():
107
+ return {
108
+ "accept": "application/json",
109
+ "accept-language": "ja",
110
+ "content-type": "application/json",
111
+ "priority": "u=1, i",
112
+ "sec-ch-ua": "\"Chromium\";v=\"152\", \"Not?A_Brand\";v=\"24\", \"Google Chrome\";v=\"152\"",
113
+ "sec-ch-ua-mobile": "?0",
114
+ "sec-ch-ua-platform": "\"Windows\"",
115
+ "sec-fetch-dest": "empty",
116
+ "sec-fetch-mode": "cors",
117
+ "sec-fetch-site": "same-site",
118
+ "Referer": "https://channel.works/",
119
+ }
120
+
121
+ @staticmethod
122
+ def _get_set_cookie_headers(resp):
123
+ try:
124
+ headers = resp.raw.headers.getlist("Set-Cookie")
125
+ if headers:
126
+ return headers
127
+ except Exception:
128
+ pass
129
+ raw = resp.headers.get("Set-Cookie")
130
+ return [raw] if raw else []
131
+
132
+ @staticmethod
133
+ def _extract_new_tokens(set_cookie_headers):
134
+ new_tokens = {}
135
+ for set_cookie in set_cookie_headers:
136
+ first_part = set_cookie.split(";", 1)[0].strip()
137
+ if "=" not in first_part:
138
+ continue
139
+ name, value = first_part.split("=", 1)
140
+ name = name.strip()
141
+ if name in _TOKEN_NAMES and value:
142
+ new_tokens[name] = value
143
+ return new_tokens
144
+
145
+ def _build_cookie_header(self):
146
+ cookies = OrderedDict()
147
+ if self._ch_session_1:
148
+ cookies["ch-session-1"] = self._ch_session_1
149
+ if self._ch_veil_id:
150
+ cookies["ch-veil-id"] = self._ch_veil_id
151
+ if self._x_account:
152
+ cookies["x-account"] = self._x_account
153
+ if self._x_account_refresh:
154
+ cookies["x-account-refresh"] = self._x_account_refresh
155
+ cookies["x-account-refresh-bound"] = "false"
156
+ return "; ".join(f"{k}={v}" for k, v in cookies.items())
157
+
158
+ def _apply_new_tokens(self, new_tokens):
159
+ """Set-Cookie から取得した新トークンを保持値に反映する。"""
160
+ with self._lock:
161
+ if "x-account" in new_tokens:
162
+ self._x_account = new_tokens["x-account"]
163
+ if "x-account-refresh" in new_tokens:
164
+ self._x_account_refresh = new_tokens["x-account-refresh"]
165
+ if "ch-session-1" in new_tokens:
166
+ self._ch_session_1 = new_tokens["ch-session-1"]
167
+ if "ch-veil-id" in new_tokens:
168
+ self._ch_veil_id = new_tokens["ch-veil-id"]
169
+
170
+ # ------------------------------------------------------------------
171
+ # 認証
172
+ # ------------------------------------------------------------------
173
+ def sign_in(self):
174
+ if not self.email or not self.password:
175
+ raise ValueError("email と password を指定してください。")
176
+
177
+ headers = self._common_headers()
178
+ headers["x-supports-refresh"] = "true"
179
+ body = json.dumps({"email": self.email, "password": self.password}).encode("utf-8")
180
+
181
+ self._log_debug(f"sign_in POST {SIGN_IN_URI}")
182
+ resp = requests.post(SIGN_IN_URI, headers=headers, data=body, timeout=self.timeout)
183
+
184
+ if not (200 <= resp.status_code < 300):
185
+ self._log_error(f"sign_in 失敗 status={resp.status_code} body={resp.text}")
186
+ return resp
187
+
188
+ set_cookies = self._get_set_cookie_headers(resp)
189
+ new_tokens = self._extract_new_tokens(set_cookies)
190
+ self._apply_new_tokens(new_tokens)
191
+ self._log_debug(f"sign_in 取得トークン: {sorted(new_tokens.keys())}")
192
+
193
+ if not self._x_account or not self._x_account_refresh:
194
+ self._log_error("sign_in 応答から x-account / x-account-refresh を取得できませんでした。")
195
+
196
+ try:
197
+ data = resp.json()
198
+ except ValueError:
199
+ self._log_error("sign_in 応答の JSON パースに失敗しました。")
200
+ return resp
201
+
202
+ account_info = data["account"]
203
+ with self._lock:
204
+ self._account_name = account_info["name"]
205
+ self._account_email = account_info["email"]
206
+ self._account_id = account_info["id"]
207
+ self._member_hash = data["memberHash"]
208
+
209
+ self._log_debug("sign_in 成功")
210
+ return resp
211
+
212
+ def boot(self):
213
+ if not self._account_id or not self._member_hash:
214
+ self._log_error("boot 前に sign_in を実行してください。")
215
+ return None
216
+
217
+ profile = json.dumps(
218
+ {
219
+ "name": self._account_name,
220
+ "email": self._account_email,
221
+ "avatarUrl": BOOT_AVATAR_URL,
222
+ },
223
+ ensure_ascii=False,
224
+ separators=(",", ":"),
225
+ )
226
+
227
+ boot_url_value = BOOT_URL_TEMPLATE.format(room_id=self.room_id)
228
+
229
+ body = urlencode({
230
+ "url": boot_url_value, # ← 変更
231
+ "profile": profile,
232
+ "memberId": self._account_id,
233
+ "memberHash": self._member_hash,
234
+ }).encode("utf-8")
235
+
236
+ headers = {
237
+ "accept": "application/json",
238
+ "accept-language": "ja",
239
+ "content-type": "application/x-www-form-urlencoded",
240
+ "priority": "u=1, i",
241
+ "sec-ch-ua": "\"Chromium\";v=\"152\", \"Not?A_Brand\";v=\"24\", \"Google Chrome\";v=\"152\"",
242
+ "sec-ch-ua-mobile": "?0",
243
+ "sec-ch-ua-platform": "\"Windows\"",
244
+ "sec-fetch-dest": "empty",
245
+ "sec-fetch-mode": "cors",
246
+ "sec-fetch-site": "cross-site",
247
+ "sec-fetch-storage-access": "none",
248
+ "Referer": "https://channel.works/",
249
+ "User-Agent": (
250
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " # User-Agentは必須
251
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
252
+ "Chrome/152.0.0.0 Safari/537.36"
253
+ ),
254
+ }
255
+
256
+ self._log_debug(f"boot POST {BOOT_URI} memberId={self._account_id}")
257
+ resp = requests.post(BOOT_URI, headers=headers, data=body, timeout=self.timeout)
258
+
259
+ if not (200 <= resp.status_code < 300):
260
+ self._log_error(f"boot 失敗 status={resp.status_code} body={resp.text}")
261
+ return resp
262
+
263
+ # boot 応答で ch-session-1 / ch-veil-id が降ってくる場合に備えて反映
264
+ self._apply_new_tokens(self._extract_new_tokens(self._get_set_cookie_headers(resp)))
265
+
266
+ try:
267
+ data = resp.json()
268
+ except ValueError:
269
+ self._log_error("boot 応答の JSON パースに失敗しました。")
270
+ return resp
271
+
272
+ with self._lock:
273
+ self._ch_session_1 = data.get("sessionJWT", self._ch_session_1)
274
+ self._ch_veil_id = data.get("veilId", self._ch_veil_id)
275
+
276
+ self._log_debug("boot 成功")
277
+ return resp
278
+
279
+ def login(self):
280
+ """sign_in → boot をまとめて実行する。"""
281
+ self.sign_in()
282
+ self.boot()
283
+
284
+ # ------------------------------------------------------------------
285
+ # touch
286
+ # ------------------------------------------------------------------
287
+ def touch(self):
288
+ """最新トークンを使って touch を 1 回叩き、返ってきた新トークンで保持値を更新する。"""
289
+ with self._lock:
290
+ if not self._x_account:
291
+ self._log_error("touch 実行不可: x-account 未取得")
292
+ return None
293
+ account = self._x_account
294
+ cookie_header = self._build_cookie_header()
295
+
296
+ headers = self._common_headers()
297
+ headers["x-account"] = account
298
+ headers["Cookie"] = cookie_header
299
+
300
+ body = b'{"refreshOnly":true,"skipSessionExtension":false}'
301
+
302
+ self._log_debug(f"touch POST {TOUCH_URI}")
303
+ try:
304
+ resp = requests.post(TOUCH_URI, headers=headers, data=body, timeout=self.timeout)
305
+ except Exception as e:
306
+ self._log_error(f"touch 通信例外: {e!r}")
307
+ return None
308
+
309
+ if not (200 <= resp.status_code < 300):
310
+ self._log_error(f"touch 失敗 status={resp.status_code} body={resp.text}")
311
+ return resp
312
+
313
+ new_tokens = self._extract_new_tokens(self._get_set_cookie_headers(resp))
314
+ self._apply_new_tokens(new_tokens)
315
+ self._log_debug(f"touch 成功 更新トークン: {sorted(new_tokens.keys()) or '(更新なし)'}")
316
+ return resp
317
+
318
+ # ------------------------------------------------------------------
319
+ # トークン取得
320
+ # ------------------------------------------------------------------
321
+ def get_tokens(self):
322
+ """常に最新のトークンを辞書で返す。"""
323
+ with self._lock:
324
+ return {
325
+ "x-account": self._x_account,
326
+ "x-account-refresh": self._x_account_refresh,
327
+ "ch-session-1": self._ch_session_1,
328
+ "ch-veil-id": self._ch_veil_id,
329
+ }
330
+
331
+ # ------------------------------------------------------------------
332
+ # 自動 touch
333
+ # ------------------------------------------------------------------
334
+ def start_auto_touch(self):
335
+ """バックグラウンドで touch_interval 秒ごとに touch を実行する。"""
336
+ with self._lock:
337
+ if self._touch_thread and self._touch_thread.is_alive():
338
+ self._log_debug("auto-touch は既に起動中")
339
+ return
340
+ self._touch_stop.clear()
341
+ self._touch_thread = threading.Thread(
342
+ target=self._touch_loop, name="ChannelWorksAutoTouch", daemon=True
343
+ )
344
+ self._touch_thread.start()
345
+ self._log_debug(f"auto-touch 開始 (interval={self.touch_interval}s)")
346
+
347
+ def stop_auto_touch(self):
348
+ """自動 touch を停止する。"""
349
+ self._touch_stop.set()
350
+ thread = self._touch_thread
351
+ if thread and thread.is_alive():
352
+ thread.join(timeout=5)
353
+ self._touch_thread = None
354
+ self._log_debug("auto-touch 停止")
355
+
356
+ def _touch_loop(self):
357
+ while not self._touch_stop.wait(self.touch_interval):
358
+ try:
359
+ self.touch()
360
+ except Exception as e:
361
+ self._log_error(f"auto-touch 例外: {e!r}")
362
+
363
+ # ------------------------------------------------------------------
364
+ # コンテキストマネージャ
365
+ # ------------------------------------------------------------------
366
+ def close(self):
367
+ self.stop_auto_touch()
368
+
369
+ def __enter__(self):
370
+ return self
371
+
372
+ def __exit__(self, exc_type, exc, tb):
373
+ self.close()