magic-campus-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- magic_campus_cli-0.1.0.dist-info/METADATA +51 -0
- magic_campus_cli-0.1.0.dist-info/RECORD +53 -0
- magic_campus_cli-0.1.0.dist-info/WHEEL +5 -0
- magic_campus_cli-0.1.0.dist-info/entry_points.txt +2 -0
- magic_campus_cli-0.1.0.dist-info/top_level.txt +2 -0
- magiccampus_cli/__init__.py +1 -0
- magiccampus_cli/__main__.py +9 -0
- magiccampus_cli/accounts.py +144 -0
- magiccampus_cli/cli.py +176 -0
- magiccampus_cli/client.py +54 -0
- magiccampus_cli/commands/auth.py +32 -0
- magiccampus_cli/commands/comment.py +38 -0
- magiccampus_cli/commands/config.py +95 -0
- magiccampus_cli/commands/feed.py +26 -0
- magiccampus_cli/commands/group.py +346 -0
- magiccampus_cli/commands/im.py +47 -0
- magiccampus_cli/commands/notify.py +81 -0
- magiccampus_cli/commands/playgroup.py +49 -0
- magiccampus_cli/commands/reaction.py +50 -0
- magiccampus_cli/commands/space.py +134 -0
- magiccampus_cli/commands/user.py +311 -0
- magiccampus_cli/config_store.py +61 -0
- magiccampus_cli/notify.py +493 -0
- magiccampus_cli/output.py +104 -0
- magiccampus_cli/prompts.py +58 -0
- magiccampus_cli/targets.py +26 -0
- magiccampus_cli/update.py +149 -0
- magiccampus_cli/utils.py +67 -0
- magiccampus_sdk/__init__.py +43 -0
- magiccampus_sdk/auth.py +111 -0
- magiccampus_sdk/comment_client.py +107 -0
- magiccampus_sdk/feed_api.py +61 -0
- magiccampus_sdk/feed_client.py +30 -0
- magiccampus_sdk/group_api.py +139 -0
- magiccampus_sdk/group_client.py +242 -0
- magiccampus_sdk/http/__init__.py +1 -0
- magiccampus_sdk/http/group_info_api.py +47 -0
- magiccampus_sdk/http/http_api.py +58 -0
- magiccampus_sdk/http/http_send.py +758 -0
- magiccampus_sdk/http/media.py +839 -0
- magiccampus_sdk/http/models.py +645 -0
- magiccampus_sdk/http/self_user_info_api.py +182 -0
- magiccampus_sdk/http/text.py +75 -0
- magiccampus_sdk/models.py +279 -0
- magiccampus_sdk/platform_client.py +137 -0
- magiccampus_sdk/platform_http.py +71 -0
- magiccampus_sdk/playgroup_api.py +104 -0
- magiccampus_sdk/playgroup_client.py +45 -0
- magiccampus_sdk/reaction_api.py +110 -0
- magiccampus_sdk/space_api.py +170 -0
- magiccampus_sdk/space_client.py +93 -0
- magiccampus_sdk/user_client.py +211 -0
- magiccampus_sdk/user_info_api.py +593 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
import urllib.request
|
|
7
|
+
import uuid
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from magiccampus_sdk.http.media import build_markdown_ex
|
|
12
|
+
from magiccampus_sdk.http.text import parse_at_text_markup
|
|
13
|
+
|
|
14
|
+
from .accounts import AccountConfig
|
|
15
|
+
from .targets import format_target, parse_target, recv_and_group_ids
|
|
16
|
+
from .utils import infer_name_from_url, is_http_url, to_local_path, trim_string
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class SendInput:
|
|
21
|
+
target: dict[str, str]
|
|
22
|
+
target_text: str
|
|
23
|
+
mode: str
|
|
24
|
+
value: str
|
|
25
|
+
name: str | None
|
|
26
|
+
dry_run: bool
|
|
27
|
+
cover_image: str | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class HistoryInput:
|
|
32
|
+
target: dict[str, str]
|
|
33
|
+
target_text: str
|
|
34
|
+
limit: int
|
|
35
|
+
|
|
36
|
+
def _group_session_candidates(sdk: object, target: dict[str, str]) -> list[int | None]:
|
|
37
|
+
if target["kind"] != "group":
|
|
38
|
+
return [None]
|
|
39
|
+
if getattr(sdk, "transport_kind", "") == "http_api":
|
|
40
|
+
return [3]
|
|
41
|
+
return [2, 3]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _should_retry_group_session(error: Exception, session_type: int | None, target: dict[str, str]) -> bool:
|
|
45
|
+
if target["kind"] != "group" or session_type != 2:
|
|
46
|
+
return False
|
|
47
|
+
err_code = getattr(error, "err_code", None)
|
|
48
|
+
err_msg = str(getattr(error, "err_msg", "") or "")
|
|
49
|
+
return err_code == 1001 and "unknown sessionType" in err_msg
|
|
50
|
+
|
|
51
|
+
def _send_with_group_compat(sdk: object, target: dict[str, str], sender_factory) -> dict[str, object]:
|
|
52
|
+
last_error: Exception | None = None
|
|
53
|
+
for session_type in _group_session_candidates(sdk, target):
|
|
54
|
+
try:
|
|
55
|
+
return sender_factory(session_type)
|
|
56
|
+
except Exception as error:
|
|
57
|
+
if _should_retry_group_session(error, session_type, target):
|
|
58
|
+
last_error = error
|
|
59
|
+
continue
|
|
60
|
+
raise
|
|
61
|
+
if last_error is not None:
|
|
62
|
+
raise last_error
|
|
63
|
+
raise RuntimeError("send failed without a usable session type")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _has_value(value: object) -> bool:
|
|
67
|
+
if isinstance(value, str):
|
|
68
|
+
return bool(value.strip())
|
|
69
|
+
return bool(value)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _source_kind(send_input: SendInput) -> str:
|
|
73
|
+
if send_input.mode in {"text", "markdown", "custom"}:
|
|
74
|
+
return "inline_text"
|
|
75
|
+
if send_input.mode == "link_card":
|
|
76
|
+
return "remote_url" if is_http_url(send_input.cover_image or "") else "local_path"
|
|
77
|
+
if is_http_url(send_input.value):
|
|
78
|
+
return "remote_url"
|
|
79
|
+
return "local_path"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _normalize_markdown_value(value: str) -> str:
|
|
83
|
+
if "\\" not in value:
|
|
84
|
+
return value
|
|
85
|
+
normalized = value.replace("\\r\\n", "\n")
|
|
86
|
+
normalized = normalized.replace("\\n", "\n")
|
|
87
|
+
normalized = normalized.replace("\\t", "\t")
|
|
88
|
+
return normalized
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def resolve_send_input(options: dict[str, object]) -> SendInput:
|
|
92
|
+
target = parse_target(options.get("to"))
|
|
93
|
+
if target is None:
|
|
94
|
+
raise ValueError("Invalid target format. Expected user:<id> or group:<id>.")
|
|
95
|
+
|
|
96
|
+
candidates = [
|
|
97
|
+
("text", "text"),
|
|
98
|
+
("markdown", "markdown"),
|
|
99
|
+
("custom", "custom"),
|
|
100
|
+
("image", "image"),
|
|
101
|
+
("file", "file"),
|
|
102
|
+
("video", "video"),
|
|
103
|
+
]
|
|
104
|
+
selected = [(mode, key) for mode, key in candidates if _has_value(options.get(key))]
|
|
105
|
+
if len(selected) != 1:
|
|
106
|
+
raise ValueError("notify +send requires exactly one of --text, --markdown, --custom, --image, --file, or --video.")
|
|
107
|
+
|
|
108
|
+
mode, key = selected[0]
|
|
109
|
+
if _has_value(options.get("name")) and mode not in {"file", "video"}:
|
|
110
|
+
raise ValueError("--name is only supported with --file or --video.")
|
|
111
|
+
|
|
112
|
+
cover_image = trim_string(options.get("cover-image")) or None
|
|
113
|
+
if cover_image:
|
|
114
|
+
if mode != "custom":
|
|
115
|
+
raise ValueError("--cover-image is only supported with --custom.")
|
|
116
|
+
|
|
117
|
+
value = trim_string(options.get(key))
|
|
118
|
+
if mode == "markdown":
|
|
119
|
+
value = _normalize_markdown_value(value)
|
|
120
|
+
if cover_image:
|
|
121
|
+
_prepare_custom_cover(_parse_custom_value(value))
|
|
122
|
+
|
|
123
|
+
return SendInput(
|
|
124
|
+
target=target,
|
|
125
|
+
target_text=format_target(target),
|
|
126
|
+
mode=mode,
|
|
127
|
+
value=value,
|
|
128
|
+
name=trim_string(options.get("name")) or None,
|
|
129
|
+
dry_run=options.get("dry-run") is True,
|
|
130
|
+
cover_image=cover_image,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def resolve_link_card_input(options: dict[str, object]) -> SendInput:
|
|
135
|
+
required = ("title", "sub-title", "schema", "cover-image")
|
|
136
|
+
missing = [f"--{key}" for key in required if not _has_value(options.get(key))]
|
|
137
|
+
if missing:
|
|
138
|
+
raise ValueError("send-link-card requires " + ", ".join(missing) + ".")
|
|
139
|
+
if any(_has_value(options.get(key)) for key in ("text", "markdown", "custom", "image", "file", "video")):
|
|
140
|
+
raise ValueError("send-link-card does not accept other message content options.")
|
|
141
|
+
|
|
142
|
+
payload = {
|
|
143
|
+
"customType": 503,
|
|
144
|
+
"data": {
|
|
145
|
+
"title": trim_string(options["title"]),
|
|
146
|
+
"subTitle": trim_string(options["sub-title"]),
|
|
147
|
+
"schema": trim_string(options["schema"]),
|
|
148
|
+
},
|
|
149
|
+
}
|
|
150
|
+
send_input = resolve_send_input({**options, "custom": json.dumps(payload, ensure_ascii=False)})
|
|
151
|
+
return replace(send_input, mode="link_card")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def build_send_result(
|
|
155
|
+
account: AccountConfig,
|
|
156
|
+
send_input: SendInput,
|
|
157
|
+
extra: dict[str, object] | None = None,
|
|
158
|
+
*,
|
|
159
|
+
transport: str = "http_api",
|
|
160
|
+
) -> dict[str, object]:
|
|
161
|
+
result: dict[str, object] = {
|
|
162
|
+
"ok": True,
|
|
163
|
+
"accountId": account.account_id,
|
|
164
|
+
"target": send_input.target_text,
|
|
165
|
+
"mode": send_input.mode,
|
|
166
|
+
"provider": "magiccampus",
|
|
167
|
+
"transport": transport,
|
|
168
|
+
"dryRun": send_input.dry_run,
|
|
169
|
+
"magiccampus": {
|
|
170
|
+
"apiUrl": account.apiurl,
|
|
171
|
+
"platform": account.platform,
|
|
172
|
+
"targetKind": send_input.target["kind"],
|
|
173
|
+
"sourceKind": _source_kind(send_input),
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
if extra:
|
|
177
|
+
result.update(extra)
|
|
178
|
+
return result
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _parse_positive_int(value: object, *, option_name: str, default: int) -> int:
|
|
182
|
+
if value is None or value is False:
|
|
183
|
+
return default
|
|
184
|
+
try:
|
|
185
|
+
parsed = int(str(value).strip())
|
|
186
|
+
except (TypeError, ValueError) as exc:
|
|
187
|
+
raise ValueError(f"{option_name} must be a positive integer.") from exc
|
|
188
|
+
if parsed <= 0:
|
|
189
|
+
raise ValueError(f"{option_name} must be a positive integer.")
|
|
190
|
+
return parsed
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def resolve_history_input(options: dict[str, object]) -> HistoryInput:
|
|
194
|
+
target = parse_target(options.get("to"))
|
|
195
|
+
if target is None:
|
|
196
|
+
raise ValueError("Invalid target format. Expected user:<id> or group:<id>.")
|
|
197
|
+
|
|
198
|
+
return HistoryInput(
|
|
199
|
+
target=target,
|
|
200
|
+
target_text=format_target(target),
|
|
201
|
+
limit=_parse_positive_int(options.get("limit"), option_name="--limit", default=50),
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _history_conversation_ids(target: dict[str, str], login_user_id: str) -> list[str]:
|
|
206
|
+
if target["kind"] == "group":
|
|
207
|
+
return [f"g_{target['id']}", f"sg_{target['id']}"]
|
|
208
|
+
pair = sorted([login_user_id, target["id"]])
|
|
209
|
+
return [f"si_{pair[0]}_{pair[1]}"]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def select_history(data: dict, *, login_user_id: str, history_input: HistoryInput) -> list[dict[str, object]]:
|
|
213
|
+
conversation_ids = set(_history_conversation_ids(history_input.target, login_user_id))
|
|
214
|
+
messages = []
|
|
215
|
+
for conversation in data.get("conversations") or []:
|
|
216
|
+
if conversation.get("conversationID") in conversation_ids:
|
|
217
|
+
messages.extend(conversation.get("messages") or [])
|
|
218
|
+
messages.sort(key=lambda msg: int(msg.get("sendTime") or 0), reverse=True)
|
|
219
|
+
return messages[:history_input.limit]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def build_history_result(account: AccountConfig, history_input: HistoryInput,
|
|
223
|
+
messages: list[dict[str, object]]) -> dict[str, object]:
|
|
224
|
+
return {
|
|
225
|
+
"ok": True, "accountId": account.account_id, "target": history_input.target_text,
|
|
226
|
+
"provider": "magiccampus", "transport": "http_api", "limit": history_input.limit,
|
|
227
|
+
"count": len(messages), "messages": messages,
|
|
228
|
+
"magiccampus": {"apiUrl": account.apiurl, "platform": account.platform,
|
|
229
|
+
"targetKind": history_input.target["kind"]},
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def validate_send_account(account: AccountConfig, send_input: SendInput) -> None:
|
|
234
|
+
del account, send_input
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _download_to_temp(url: str, fallback_name: str) -> Path:
|
|
239
|
+
inferred_name = infer_name_from_url(url, fallback_name)
|
|
240
|
+
suffix = Path(inferred_name).suffix
|
|
241
|
+
fd, temp_path = tempfile.mkstemp(prefix="magic-campus-", suffix=suffix)
|
|
242
|
+
os.close(fd)
|
|
243
|
+
urllib.request.urlretrieve(url, temp_path)
|
|
244
|
+
return Path(temp_path)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _send_text(sdk: object, target: dict[str, str], text: str, *, ex: str = "") -> dict[str, object]:
|
|
248
|
+
recv_id, group_id = recv_and_group_ids(target)
|
|
249
|
+
user_info_resolver = getattr(sdk, "get_user_info", None)
|
|
250
|
+
parsed_at_text = parse_at_text_markup(
|
|
251
|
+
text,
|
|
252
|
+
user_info_resolver=user_info_resolver if callable(user_info_resolver) else None,
|
|
253
|
+
)
|
|
254
|
+
if parsed_at_text is not None and parsed_at_text[1]:
|
|
255
|
+
parsed_text, at_user_list, at_users_info = parsed_at_text
|
|
256
|
+
def _send_at(session_type):
|
|
257
|
+
kwargs = {
|
|
258
|
+
"at_user_list": at_user_list,
|
|
259
|
+
"at_users_info": at_users_info,
|
|
260
|
+
"recv_id": recv_id,
|
|
261
|
+
"group_id": group_id,
|
|
262
|
+
"session_type": session_type,
|
|
263
|
+
}
|
|
264
|
+
if ex:
|
|
265
|
+
kwargs["ex"] = ex
|
|
266
|
+
return sdk.send_at_text(parsed_text, **kwargs)
|
|
267
|
+
|
|
268
|
+
return _send_with_group_compat(
|
|
269
|
+
sdk,
|
|
270
|
+
target,
|
|
271
|
+
_send_at,
|
|
272
|
+
)
|
|
273
|
+
plain_text = parsed_at_text[0] if parsed_at_text is not None else text
|
|
274
|
+
|
|
275
|
+
def _send_plain(session_type):
|
|
276
|
+
kwargs = {
|
|
277
|
+
"recv_id": recv_id,
|
|
278
|
+
"group_id": group_id,
|
|
279
|
+
"session_type": session_type,
|
|
280
|
+
}
|
|
281
|
+
if ex:
|
|
282
|
+
kwargs["ex"] = ex
|
|
283
|
+
return sdk.send_text(plain_text, **kwargs)
|
|
284
|
+
|
|
285
|
+
return _send_with_group_compat(
|
|
286
|
+
sdk,
|
|
287
|
+
target,
|
|
288
|
+
_send_plain,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _send_image(sdk: object, target: dict[str, str], image: str) -> dict[str, object]:
|
|
293
|
+
recv_id, group_id = recv_and_group_ids(target)
|
|
294
|
+
if is_http_url(image):
|
|
295
|
+
from magiccampus_sdk.http.media import read_image_metadata
|
|
296
|
+
|
|
297
|
+
staged = _download_to_temp(image, "image.jpg")
|
|
298
|
+
try:
|
|
299
|
+
meta = read_image_metadata(str(staged))
|
|
300
|
+
return _send_with_group_compat(
|
|
301
|
+
sdk,
|
|
302
|
+
target,
|
|
303
|
+
lambda session_type: sdk.send_image_by_url(
|
|
304
|
+
source_url=image,
|
|
305
|
+
width=meta.width,
|
|
306
|
+
height=meta.height,
|
|
307
|
+
size=meta.size,
|
|
308
|
+
source_path=infer_name_from_url(image, staged.name),
|
|
309
|
+
recv_id=recv_id,
|
|
310
|
+
group_id=group_id,
|
|
311
|
+
session_type=session_type,
|
|
312
|
+
),
|
|
313
|
+
)
|
|
314
|
+
finally:
|
|
315
|
+
staged.unlink(missing_ok=True)
|
|
316
|
+
|
|
317
|
+
return _send_with_group_compat(
|
|
318
|
+
sdk,
|
|
319
|
+
target,
|
|
320
|
+
lambda session_type: sdk.send_image(to_local_path(image), recv_id=recv_id, group_id=group_id, session_type=session_type),
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _send_markdown(sdk: object, target: dict[str, str], markdown: str) -> dict[str, object]:
|
|
325
|
+
return _send_text(sdk, target, markdown, ex=build_markdown_ex())
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _parse_custom_value(value: str) -> dict[str, object]:
|
|
329
|
+
try:
|
|
330
|
+
parsed = json.loads(value)
|
|
331
|
+
except json.JSONDecodeError as exc:
|
|
332
|
+
raise ValueError("--custom must be a JSON object with data, extension, and description fields.") from exc
|
|
333
|
+
if not isinstance(parsed, dict):
|
|
334
|
+
raise ValueError("--custom must be a JSON object with data, extension, and description fields.")
|
|
335
|
+
return parsed
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _prepare_custom_cover(custom_content: dict[str, object]) -> tuple[dict[str, object], dict[str, object]]:
|
|
339
|
+
if "customType" in custom_content:
|
|
340
|
+
payload = custom_content
|
|
341
|
+
custom_content = {"data": payload}
|
|
342
|
+
else:
|
|
343
|
+
raw_payload = custom_content.get("data")
|
|
344
|
+
if isinstance(raw_payload, str):
|
|
345
|
+
try:
|
|
346
|
+
payload = json.loads(raw_payload)
|
|
347
|
+
except json.JSONDecodeError as exc:
|
|
348
|
+
raise ValueError("--custom data must contain a JSON object when --cover-image is used.") from exc
|
|
349
|
+
else:
|
|
350
|
+
payload = raw_payload
|
|
351
|
+
if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
|
|
352
|
+
raise ValueError("--custom must contain an object with a data object when --cover-image is used.")
|
|
353
|
+
return custom_content, payload
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _send_custom(sdk: object, target: dict[str, str], custom: str, cover_image: str | None = None) -> dict[str, object]:
|
|
357
|
+
recv_id, group_id = recv_and_group_ids(target)
|
|
358
|
+
custom_content = _parse_custom_value(custom)
|
|
359
|
+
if cover_image:
|
|
360
|
+
custom_content, payload = _prepare_custom_cover(custom_content)
|
|
361
|
+
if is_http_url(cover_image):
|
|
362
|
+
from magiccampus_sdk.http.media import read_image_metadata
|
|
363
|
+
|
|
364
|
+
staged = _download_to_temp(cover_image, "cover.jpg")
|
|
365
|
+
try:
|
|
366
|
+
metadata = read_image_metadata(str(staged))
|
|
367
|
+
finally:
|
|
368
|
+
staged.unlink(missing_ok=True)
|
|
369
|
+
cover = {"url": cover_image, "width": metadata.width, "height": metadata.height}
|
|
370
|
+
else:
|
|
371
|
+
cover = sdk.upload_image(to_local_path(cover_image))
|
|
372
|
+
payload["data"]["cover"] = {
|
|
373
|
+
"url": cover["url"],
|
|
374
|
+
"width": cover["width"],
|
|
375
|
+
"height": cover["height"],
|
|
376
|
+
}
|
|
377
|
+
custom_content["data"] = payload
|
|
378
|
+
return _send_with_group_compat(
|
|
379
|
+
sdk,
|
|
380
|
+
target,
|
|
381
|
+
lambda session_type: sdk.send_custom(
|
|
382
|
+
custom_content,
|
|
383
|
+
recv_id=recv_id,
|
|
384
|
+
group_id=group_id,
|
|
385
|
+
session_type=session_type,
|
|
386
|
+
),
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _send_file_like(sdk: object, target: dict[str, str], value: str, name: str | None) -> dict[str, object]:
|
|
391
|
+
recv_id, group_id = recv_and_group_ids(target)
|
|
392
|
+
if is_http_url(value):
|
|
393
|
+
file_name = name or infer_name_from_url(value, "file.bin")
|
|
394
|
+
return _send_with_group_compat(
|
|
395
|
+
sdk,
|
|
396
|
+
target,
|
|
397
|
+
lambda session_type: sdk.send_file_by_url(
|
|
398
|
+
source_url=value,
|
|
399
|
+
file_name=file_name,
|
|
400
|
+
recv_id=recv_id,
|
|
401
|
+
group_id=group_id,
|
|
402
|
+
session_type=session_type,
|
|
403
|
+
),
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
local_path = to_local_path(value)
|
|
407
|
+
file_name = name or Path(local_path).name
|
|
408
|
+
return _send_with_group_compat(
|
|
409
|
+
sdk,
|
|
410
|
+
target,
|
|
411
|
+
lambda session_type: sdk.send_file(local_path, recv_id=recv_id, group_id=group_id, file_name=file_name, session_type=session_type),
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _upload_snapshot_for_video_url(sdk: object, snapshot_path: str) -> str:
|
|
416
|
+
api_addr = getattr(sdk, "_api_addr", "")
|
|
417
|
+
if not api_addr or not snapshot_path:
|
|
418
|
+
return ""
|
|
419
|
+
remote_name_builder = getattr(sdk, "_build_remote_name", None)
|
|
420
|
+
upload_media_file = getattr(sdk, "_upload_media_file", None)
|
|
421
|
+
if remote_name_builder is None or upload_media_file is None:
|
|
422
|
+
return ""
|
|
423
|
+
remote_name = remote_name_builder("videoSnapshot", uuid.uuid4().hex, snapshot_path)
|
|
424
|
+
return upload_media_file(file_path=snapshot_path, name=remote_name, cause="msg-video-snapshot")
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _send_video(sdk: object, target: dict[str, str], value: str, name: str | None) -> dict[str, object]:
|
|
428
|
+
from magiccampus_sdk.http.media import auto_video_snapshot, detect_content_type, probe_video_duration_ms, read_image_metadata
|
|
429
|
+
|
|
430
|
+
recv_id, group_id = recv_and_group_ids(target)
|
|
431
|
+
if is_http_url(value):
|
|
432
|
+
staged = _download_to_temp(value, name or "video.mp4")
|
|
433
|
+
try:
|
|
434
|
+
video_name = name or infer_name_from_url(value, staged.name)
|
|
435
|
+
duration = probe_video_duration_ms(str(staged))
|
|
436
|
+
video_size = staged.stat().st_size
|
|
437
|
+
video_type = detect_content_type(video_name or value, default="application/octet-stream")
|
|
438
|
+
with auto_video_snapshot(str(staged)) as snapshot_path:
|
|
439
|
+
snapshot_url = _upload_snapshot_for_video_url(sdk, snapshot_path)
|
|
440
|
+
snapshot_size = 0
|
|
441
|
+
snapshot_width = 0
|
|
442
|
+
snapshot_height = 0
|
|
443
|
+
snapshot_type = ""
|
|
444
|
+
if snapshot_path and snapshot_url:
|
|
445
|
+
snapshot_meta = read_image_metadata(snapshot_path)
|
|
446
|
+
snapshot_size = snapshot_meta.size
|
|
447
|
+
snapshot_width = snapshot_meta.width
|
|
448
|
+
snapshot_height = snapshot_meta.height
|
|
449
|
+
snapshot_type = snapshot_meta.content_type
|
|
450
|
+
return _send_with_group_compat(
|
|
451
|
+
sdk,
|
|
452
|
+
target,
|
|
453
|
+
lambda session_type: sdk.send_video_by_url(
|
|
454
|
+
video_url=value,
|
|
455
|
+
duration=duration,
|
|
456
|
+
recv_id=recv_id,
|
|
457
|
+
group_id=group_id,
|
|
458
|
+
video_size=video_size,
|
|
459
|
+
video_path=video_name,
|
|
460
|
+
video_type=video_type,
|
|
461
|
+
snapshot_url=snapshot_url,
|
|
462
|
+
snapshot_path=os.path.basename(snapshot_path) if snapshot_path and snapshot_url else "",
|
|
463
|
+
snapshot_size=snapshot_size,
|
|
464
|
+
snapshot_width=snapshot_width,
|
|
465
|
+
snapshot_height=snapshot_height,
|
|
466
|
+
snapshot_type=snapshot_type,
|
|
467
|
+
session_type=session_type,
|
|
468
|
+
),
|
|
469
|
+
)
|
|
470
|
+
finally:
|
|
471
|
+
staged.unlink(missing_ok=True)
|
|
472
|
+
|
|
473
|
+
local_path = to_local_path(value)
|
|
474
|
+
duration = probe_video_duration_ms(local_path)
|
|
475
|
+
return _send_with_group_compat(
|
|
476
|
+
sdk,
|
|
477
|
+
target,
|
|
478
|
+
lambda session_type: sdk.send_video(local_path, duration=duration, recv_id=recv_id, group_id=group_id, session_type=session_type),
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def execute_send(sdk: object, send_input: SendInput) -> dict[str, object]:
|
|
483
|
+
if send_input.mode == "text":
|
|
484
|
+
return _send_text(sdk, send_input.target, send_input.value)
|
|
485
|
+
if send_input.mode == "markdown":
|
|
486
|
+
return _send_markdown(sdk, send_input.target, send_input.value)
|
|
487
|
+
if send_input.mode in {"custom", "link_card"}:
|
|
488
|
+
return _send_custom(sdk, send_input.target, send_input.value, send_input.cover_image)
|
|
489
|
+
if send_input.mode == "image":
|
|
490
|
+
return _send_image(sdk, send_input.target, send_input.value)
|
|
491
|
+
if send_input.mode == "video":
|
|
492
|
+
return _send_video(sdk, send_input.target, send_input.value, send_input.name)
|
|
493
|
+
return _send_file_like(sdk, send_input.target, send_input.value, send_input.name)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import __version__
|
|
7
|
+
from .utils import format_value
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _expand_magiccampus_visual_fields(row: dict[str, object]) -> dict[str, object]:
|
|
11
|
+
details = row.get("magiccampus")
|
|
12
|
+
if not isinstance(details, dict):
|
|
13
|
+
return row
|
|
14
|
+
|
|
15
|
+
expanded = dict(row)
|
|
16
|
+
expanded.pop("magiccampus", None)
|
|
17
|
+
preferred_order = [
|
|
18
|
+
"enabled",
|
|
19
|
+
"platform",
|
|
20
|
+
"apiUrl",
|
|
21
|
+
"apiKeyPreview",
|
|
22
|
+
"targetKind",
|
|
23
|
+
"sourceKind",
|
|
24
|
+
"loginUserID",
|
|
25
|
+
"wsAddr",
|
|
26
|
+
"apiAddr",
|
|
27
|
+
"dbPath",
|
|
28
|
+
"expireAt",
|
|
29
|
+
"expiresInSeconds",
|
|
30
|
+
"dataDir",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
for key in preferred_order:
|
|
34
|
+
if key in details and key not in expanded:
|
|
35
|
+
expanded[key] = details[key]
|
|
36
|
+
|
|
37
|
+
for key, value in details.items():
|
|
38
|
+
if key not in expanded:
|
|
39
|
+
expanded[key] = value
|
|
40
|
+
return expanded
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def render_rows_as_table(rows: list[dict[str, object]]) -> str:
|
|
44
|
+
if not rows:
|
|
45
|
+
return "(no rows)"
|
|
46
|
+
|
|
47
|
+
visual_rows = [_expand_magiccampus_visual_fields(row) for row in rows]
|
|
48
|
+
|
|
49
|
+
columns: list[str] = []
|
|
50
|
+
seen: set[str] = set()
|
|
51
|
+
for row in visual_rows:
|
|
52
|
+
for key in row.keys():
|
|
53
|
+
if key not in seen:
|
|
54
|
+
columns.append(key)
|
|
55
|
+
seen.add(key)
|
|
56
|
+
|
|
57
|
+
widths = [
|
|
58
|
+
max(len(column), *(len(format_value(row.get(column))) for row in visual_rows))
|
|
59
|
+
for column in columns
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
def render_row(row: dict[str, object]) -> str:
|
|
63
|
+
return " | ".join(
|
|
64
|
+
format_value(row.get(column)).ljust(widths[index])
|
|
65
|
+
for index, column in enumerate(columns)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
header = " | ".join(column.ljust(widths[index]) for index, column in enumerate(columns))
|
|
69
|
+
divider = "-|-".join("-" * width for width in widths)
|
|
70
|
+
body = [render_row(row) for row in visual_rows]
|
|
71
|
+
return "\n".join([header, divider, *body])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def render_object_pretty(value: dict[str, object]) -> str:
|
|
75
|
+
visual_value = _expand_magiccampus_visual_fields(value)
|
|
76
|
+
return "\n".join(f"{key}: {format_value(entry)}" for key, entry in visual_value.items())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _with_meta(value: object) -> dict[str, object]:
|
|
80
|
+
if isinstance(value, dict):
|
|
81
|
+
return {**value, "_meta": {"cliVersion": __version__}}
|
|
82
|
+
return {"data": value, "_meta": {"cliVersion": __version__}}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def print_output(value: object, output_format: str = "json") -> None:
|
|
86
|
+
if output_format == "ndjson":
|
|
87
|
+
sys.stdout.write(json.dumps({"_meta": {"cliVersion": __version__}}, ensure_ascii=False) + "\n")
|
|
88
|
+
if isinstance(value, list):
|
|
89
|
+
for item in value:
|
|
90
|
+
sys.stdout.write(json.dumps(item, ensure_ascii=False, default=str) + "\n")
|
|
91
|
+
return
|
|
92
|
+
sys.stdout.write(json.dumps(value, ensure_ascii=False, default=str) + "\n")
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
if output_format in {"table", "pretty"}:
|
|
96
|
+
sys.stdout.write(f"magic-campus {__version__}\n")
|
|
97
|
+
if output_format == "pretty" and isinstance(value, dict):
|
|
98
|
+
sys.stdout.write(f"{render_object_pretty(value)}\n")
|
|
99
|
+
return
|
|
100
|
+
rows = value if isinstance(value, list) else [value]
|
|
101
|
+
sys.stdout.write(f"{render_rows_as_table(rows)}\n")
|
|
102
|
+
return
|
|
103
|
+
|
|
104
|
+
sys.stdout.write(f"{json.dumps(_with_meta(value), ensure_ascii=False, indent=2, default=str)}\n")
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import getpass
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from .utils import parse_optional_bool, trim_string
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _prompt_value(label: str, default: str = "", *, secret: bool = False) -> str:
|
|
10
|
+
suffix = f" [{default}]" if default else ""
|
|
11
|
+
prompt = f"{label}{suffix}: "
|
|
12
|
+
entered = getpass.getpass(prompt) if secret else input(prompt)
|
|
13
|
+
return trim_string(entered) or default
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _prompt_bool(label: str, default: bool) -> bool:
|
|
17
|
+
suffix = "Y/n" if default else "y/N"
|
|
18
|
+
entered = trim_string(input(f"{label} [{suffix}]: "))
|
|
19
|
+
parsed = parse_optional_bool(entered or None, default)
|
|
20
|
+
return bool(parsed)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def prompt_for_account(existing: dict[str, object], account_id: str) -> dict[str, object]:
|
|
24
|
+
if not sys.stdin.isatty():
|
|
25
|
+
raise RuntimeError(
|
|
26
|
+
"config init without auth flags requires a TTY. "
|
|
27
|
+
"Re-run with --apiurl and --apikey."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
apiurl = _prompt_value(
|
|
31
|
+
"MagicCampus apiurl",
|
|
32
|
+
trim_string(existing.get("apiUrl")),
|
|
33
|
+
)
|
|
34
|
+
apikey = _prompt_value(
|
|
35
|
+
"MagicCampus apikey",
|
|
36
|
+
trim_string(existing.get("apiKey")),
|
|
37
|
+
secret=True,
|
|
38
|
+
)
|
|
39
|
+
platform = _prompt_value(
|
|
40
|
+
"MagicCampus platform",
|
|
41
|
+
trim_string(existing.get("platform")) or "IOS",
|
|
42
|
+
)
|
|
43
|
+
enabled = _prompt_bool(
|
|
44
|
+
"Enable this account",
|
|
45
|
+
existing.get("enabled") is not False,
|
|
46
|
+
)
|
|
47
|
+
make_default = _prompt_bool(
|
|
48
|
+
"Set as default account",
|
|
49
|
+
account_id == "default",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
"apiUrl": apiurl,
|
|
54
|
+
"apiKey": apikey,
|
|
55
|
+
"platform": platform,
|
|
56
|
+
"enabled": enabled,
|
|
57
|
+
"makeDefault": make_default,
|
|
58
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def parse_target(value: object) -> dict[str, str] | None:
|
|
5
|
+
raw = str(value or "").strip()
|
|
6
|
+
if not raw:
|
|
7
|
+
return None
|
|
8
|
+
|
|
9
|
+
normalized = raw[13:] if raw.lower().startswith("magiccampus:") else raw
|
|
10
|
+
if normalized.startswith("user:"):
|
|
11
|
+
target_id = normalized[len("user:") :].strip()
|
|
12
|
+
return {"kind": "user", "id": target_id} if target_id else None
|
|
13
|
+
if normalized.startswith("group:"):
|
|
14
|
+
target_id = normalized[len("group:") :].strip()
|
|
15
|
+
return {"kind": "group", "id": target_id} if target_id else None
|
|
16
|
+
return {"kind": "user", "id": normalized}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def format_target(target: dict[str, str]) -> str:
|
|
20
|
+
return f"{target['kind']}:{target['id']}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def recv_and_group_ids(target: dict[str, str]) -> tuple[str, str]:
|
|
24
|
+
if target["kind"] == "group":
|
|
25
|
+
return "", target["id"]
|
|
26
|
+
return target["id"], ""
|