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.
Files changed (53) hide show
  1. magic_campus_cli-0.1.0.dist-info/METADATA +51 -0
  2. magic_campus_cli-0.1.0.dist-info/RECORD +53 -0
  3. magic_campus_cli-0.1.0.dist-info/WHEEL +5 -0
  4. magic_campus_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. magic_campus_cli-0.1.0.dist-info/top_level.txt +2 -0
  6. magiccampus_cli/__init__.py +1 -0
  7. magiccampus_cli/__main__.py +9 -0
  8. magiccampus_cli/accounts.py +144 -0
  9. magiccampus_cli/cli.py +176 -0
  10. magiccampus_cli/client.py +54 -0
  11. magiccampus_cli/commands/auth.py +32 -0
  12. magiccampus_cli/commands/comment.py +38 -0
  13. magiccampus_cli/commands/config.py +95 -0
  14. magiccampus_cli/commands/feed.py +26 -0
  15. magiccampus_cli/commands/group.py +346 -0
  16. magiccampus_cli/commands/im.py +47 -0
  17. magiccampus_cli/commands/notify.py +81 -0
  18. magiccampus_cli/commands/playgroup.py +49 -0
  19. magiccampus_cli/commands/reaction.py +50 -0
  20. magiccampus_cli/commands/space.py +134 -0
  21. magiccampus_cli/commands/user.py +311 -0
  22. magiccampus_cli/config_store.py +61 -0
  23. magiccampus_cli/notify.py +493 -0
  24. magiccampus_cli/output.py +104 -0
  25. magiccampus_cli/prompts.py +58 -0
  26. magiccampus_cli/targets.py +26 -0
  27. magiccampus_cli/update.py +149 -0
  28. magiccampus_cli/utils.py +67 -0
  29. magiccampus_sdk/__init__.py +43 -0
  30. magiccampus_sdk/auth.py +111 -0
  31. magiccampus_sdk/comment_client.py +107 -0
  32. magiccampus_sdk/feed_api.py +61 -0
  33. magiccampus_sdk/feed_client.py +30 -0
  34. magiccampus_sdk/group_api.py +139 -0
  35. magiccampus_sdk/group_client.py +242 -0
  36. magiccampus_sdk/http/__init__.py +1 -0
  37. magiccampus_sdk/http/group_info_api.py +47 -0
  38. magiccampus_sdk/http/http_api.py +58 -0
  39. magiccampus_sdk/http/http_send.py +758 -0
  40. magiccampus_sdk/http/media.py +839 -0
  41. magiccampus_sdk/http/models.py +645 -0
  42. magiccampus_sdk/http/self_user_info_api.py +182 -0
  43. magiccampus_sdk/http/text.py +75 -0
  44. magiccampus_sdk/models.py +279 -0
  45. magiccampus_sdk/platform_client.py +137 -0
  46. magiccampus_sdk/platform_http.py +71 -0
  47. magiccampus_sdk/playgroup_api.py +104 -0
  48. magiccampus_sdk/playgroup_client.py +45 -0
  49. magiccampus_sdk/reaction_api.py +110 -0
  50. magiccampus_sdk/space_api.py +170 -0
  51. magiccampus_sdk/space_client.py +93 -0
  52. magiccampus_sdk/user_client.py +211 -0
  53. magiccampus_sdk/user_info_api.py +593 -0
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: magic-campus-cli
3
+ Version: 0.1.0
4
+ Summary: Magic Campus business HTTP SDK and CLI
5
+ License-Expression: AGPL-3.0-or-later
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: httpx<1,>=0.27
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest>=8; extra == "dev"
11
+ Requires-Dist: build>=1; extra == "dev"
12
+ Requires-Dist: twine>=6; extra == "dev"
13
+
14
+ # magic-campus-cli
15
+
16
+ Business Python SDK and HTTP-only `magic-campus` command. Install this distribution
17
+ in a dedicated tool environment. It provides `magiccampus_sdk` and
18
+ `magiccampus_cli`; do not co-install it with the frozen `magic-campus-sdk`.
19
+
20
+ ```python
21
+ from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
22
+
23
+ client = MagicCampusClient(MagicCampusClientConfig(apiurl="https://campus.example", apikey="..."))
24
+ # client.user, client.feed, client.space, client.playgroup, client.comment
25
+ # client.group: HTTP group management, members, and message queries
26
+ # client.im.http(): HTTP message sender; client.im also supplies reactions
27
+ ```
28
+
29
+ All commands use HTTP. Existing OpenIM HTTP group operations retain their request
30
+ semantics; no command initializes a websocket. `im group kick --group ID --users
31
+ ID1,ID2` uses the business kick endpoint. Group invitations and member queries use
32
+ the business API. `auth status` verifies HTTP credentials and reports
33
+ `transport=http_api`, without claiming a websocket is connected.
34
+
35
+ `im notify history --to user:ID|group:ID --limit N` queries
36
+ `POST /api/v1/im/message/query`, then selects the requested conversation. The
37
+ server currently accepts a per-conversation limit rather than a target-conversation
38
+ filter, so the HTTP response can include other conversations; only the requested
39
+ one is returned by the CLI. It does not synchronize or read an IM local database.
40
+ Results use the server's message field names. Pagination/search are not invented.
41
+
42
+ The updater checks only `magic-campus-cli`, uses `cli-update-check.json` and its
43
+ own re-execution marker. `MAGIC_CAMPUS_CLI_SOURCE` selects a local source project
44
+ for development; it must point to a project named `magic-campus-cli`. The updater
45
+ refuses to run in an environment where the frozen `magic-campus-sdk` distribution
46
+ is installed. This is an update guard, not a pip installation conflict mechanism:
47
+ manual co-installation can still overwrite shared files and is unsupported.
48
+ The legacy updater continues to target the frozen package name.
49
+
50
+ See [package split verification](../README.md) and the iAgent integration document
51
+ for controlled migration. This source does not perform an online upgrade.
@@ -0,0 +1,53 @@
1
+ magiccampus_cli/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ magiccampus_cli/__main__.py,sha256=8M3vaTgigNUzQIxx-_rJFzfrAea2Oh_bU176_Fg1ywI,134
3
+ magiccampus_cli/accounts.py,sha256=zU45WtZi3XXEIwv7KXKbN7YOR2JeOCq9N3-ql3o2NxM,5417
4
+ magiccampus_cli/cli.py,sha256=E1bjivgwVsND_LZjq5kMIj6Q4l2tFVUErBBADlPIIek,10277
5
+ magiccampus_cli/client.py,sha256=vSPnhb9u7fCotTLxpt1aR9icKwNTxr7bpYrUTIhhA5Y,1885
6
+ magiccampus_cli/config_store.py,sha256=IITX-FykLEHraR_O_Oxck3aHV_FOvNvDhVMvITmqIEM,1792
7
+ magiccampus_cli/notify.py,sha256=KFDyHbrSeyyw-K6wCQEBQaHV3AIWDgsQjDL_uHpcLD0,18638
8
+ magiccampus_cli/output.py,sha256=kGAZTEWEt_VHZYmagokX1Z06UhmVy1D3SFKby4n9hYk,3313
9
+ magiccampus_cli/prompts.py,sha256=gTNnSSWlXiFNEeAQjHtp2vhCUt88yp3QcX7gQD3ZX2Y,1648
10
+ magiccampus_cli/targets.py,sha256=1Vi8hEXDuAuXDCHi6SNOY2A2hNW9NIbjNukAKatk6s4,885
11
+ magiccampus_cli/update.py,sha256=9c8RYK_BjvJ1r7pg-hC2JJI8AoAnqVYek1w7N0UN868,6116
12
+ magiccampus_cli/utils.py,sha256=poyTOYbAD1h-4wmJPCCA_BzLp4Xh79kQXEGwh65_HDk,1683
13
+ magiccampus_cli/commands/auth.py,sha256=SvEBawEuwIFWJ604uyGFzZTCIzU3VX60Xlehc1Tahrk,1489
14
+ magiccampus_cli/commands/comment.py,sha256=-FDElTkWAYAtiChDOhYnFXlJeYPBUBo7OCaF2Xi_q_Q,1923
15
+ magiccampus_cli/commands/config.py,sha256=NebZ48BwFkiFTR30Ln4DzBpbTCSL_a6xosLAi0Sbib0,3964
16
+ magiccampus_cli/commands/feed.py,sha256=NO_5b2M46oYbyDNdtE7bKIdlNrn_W_40j-7h2nvuB2Y,985
17
+ magiccampus_cli/commands/group.py,sha256=ONOp4vZCXgI6r3Y-wxUox9qriw39UpxsiRTcKgmh0mQ,13812
18
+ magiccampus_cli/commands/im.py,sha256=Rnze2_zsVOYbiz4nXaxOxBwWwrXlGvEp2D-puMsjIeE,1676
19
+ magiccampus_cli/commands/notify.py,sha256=IOL36xeVae9yvqWTwKfvqnW0aueT4fCI7oYEhWFpcdY,4020
20
+ magiccampus_cli/commands/playgroup.py,sha256=oTgSMdkZsEIfJecZaBca4E5CSbOws0ISdoRaneIU4rk,2437
21
+ magiccampus_cli/commands/reaction.py,sha256=aKpoeXED8r4NGyUBPDk-Ur_r8pcMKI7btih7iPMAXpA,1682
22
+ magiccampus_cli/commands/space.py,sha256=VtOj9wT-WI8f5ytnCOoUMr2MShi6NXm8LDm0edcRBxY,4902
23
+ magiccampus_cli/commands/user.py,sha256=N3eos1QnZ39faYElZdW-6MZf_JearCm4NelqOt3CeA0,12714
24
+ magiccampus_sdk/__init__.py,sha256=n8YRRWEygWb6cRFaxvLdqnoTudCAsiUpw8FMhdL0mVU,2713
25
+ magiccampus_sdk/auth.py,sha256=CPJIgOrc6pdXNU3rZFFeSsadbOoCU8FfwDqnxmD7wPw,3423
26
+ magiccampus_sdk/comment_client.py,sha256=RTn6WCfA121Hur9L1gkAVUmKaInBMVlkwwLwi9_I4PE,4307
27
+ magiccampus_sdk/feed_api.py,sha256=1s7cayoEO1w25l8CeVlrQmpVh7vozLLVXwkj5W5Xh3A,2497
28
+ magiccampus_sdk/feed_client.py,sha256=NruheyHZyXsXLNP7Z-HyK5JxveqdPiPzRqZTm_sVZ3Q,896
29
+ magiccampus_sdk/group_api.py,sha256=MEI2LF0ewnyAQlylQgtZZUM4iE9PaC48AAG6Ve2tyw4,4516
30
+ magiccampus_sdk/group_client.py,sha256=37j_037slU6tCSTeU-QGdlFPJ5eeS1hpGh7mI7oAitI,9268
31
+ magiccampus_sdk/models.py,sha256=mPCPCDnx1Ag6Q04JA2z4cYydEqrzxn5G5ZMxEzIi1Lc,9831
32
+ magiccampus_sdk/platform_client.py,sha256=gr9fy6qF5bS2oGxv7HikpgcZRi3Oq4FHZgIDLP4VtRE,5124
33
+ magiccampus_sdk/platform_http.py,sha256=NxFPXcLs9wY2QwNh0rj_9NkIEZJZKhmSnd4bah5ZO9E,1995
34
+ magiccampus_sdk/playgroup_api.py,sha256=S80t-hQ6Pmrena5-dWxzXMts3n2iG0klHi9QwlXpTrc,5005
35
+ magiccampus_sdk/playgroup_client.py,sha256=UPeBYgSwCbO0nL4T3uFR-_O58MKqBEX35urVNtU6YFI,2020
36
+ magiccampus_sdk/reaction_api.py,sha256=T4N4FM-Qc9r_mUieBAE2g_MEPvU-PrK3Kcubgd8Jmx8,3308
37
+ magiccampus_sdk/space_api.py,sha256=ox8S3wmPHmhjGr0OIGNTJS-GZNA4rGmTz1aiBUwx3GY,5521
38
+ magiccampus_sdk/space_client.py,sha256=zdfElM6wocEUykU2kSIkNBerj9XFoSZiHl06vPdvvQc,3509
39
+ magiccampus_sdk/user_client.py,sha256=uuctWBWBaPvzDYC-X0vESenkG-oQgASxrWlwrGvy2Xo,8776
40
+ magiccampus_sdk/user_info_api.py,sha256=52jbZkgiT9YROtd0XJdloS5NLy9NFDWi6C5QKlotOGA,21538
41
+ magiccampus_sdk/http/__init__.py,sha256=4JMnIY024eB-mdw6Sr1ozXnO4dLr1_V8Cx2f03MaYes,60
42
+ magiccampus_sdk/http/group_info_api.py,sha256=req2swn-49Z_2XOIgVbAyKWwd9WFmt-FtWaR8Tc88ME,1506
43
+ magiccampus_sdk/http/http_api.py,sha256=qgtgs1LxlA9vRvHj0rJ0vEFC6L2azv5E4EiJMoDIVTw,2094
44
+ magiccampus_sdk/http/http_send.py,sha256=BOaPkEfwpsCnb-eVI8e90NFNC9-LCn4DI4gkZHegRjs,26925
45
+ magiccampus_sdk/http/media.py,sha256=St2-FdABvFbrbRJSn0EW7q2wWuY5584kP9DoGJ8ubs4,27982
46
+ magiccampus_sdk/http/models.py,sha256=u0s3CoBxngAq-aODh0dBFNJ0kD9i2j-A2f_PAn5yZqc,21698
47
+ magiccampus_sdk/http/self_user_info_api.py,sha256=uSb0gdwyOFYYxoET1Om2FAF97fSFpClevLOyBFFNtxc,6140
48
+ magiccampus_sdk/http/text.py,sha256=xookP5NaY8iCkU_CKMzVeD-uxT76teSXaD4V40N1PBU,2771
49
+ magic_campus_cli-0.1.0.dist-info/METADATA,sha256=zie53coXChf_RhR6s3bkx3px3PHs5EkDz3fV19_GIok,2591
50
+ magic_campus_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
51
+ magic_campus_cli-0.1.0.dist-info/entry_points.txt,sha256=UBHHJkoSwWB6A3of7m1A4m40pK-qJMGVKodCcfOLywA,63
52
+ magic_campus_cli-0.1.0.dist-info/top_level.txt,sha256=N-wijR5BdV8-iLhE9AuPoZ5PUhKrl1I5yTszUw7TQAs,32
53
+ magic_campus_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ magic-campus = magiccampus_cli.__main__:main
@@ -0,0 +1,2 @@
1
+ magiccampus_cli
2
+ magiccampus_sdk
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,9 @@
1
+ from .cli import main as cli_main
2
+
3
+
4
+ def main() -> int:
5
+ return cli_main()
6
+
7
+
8
+ if __name__ == "__main__":
9
+ raise SystemExit(main())
@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, replace
4
+ import os
5
+ from urllib.parse import urlsplit
6
+
7
+ from magiccampus_sdk.auth import normalize_apiurl, normalize_platform
8
+
9
+ from .utils import env_string, mask_secret, trim_string
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AccountConfig:
14
+ account_id: str
15
+ enabled: bool
16
+ apiurl: str
17
+ apikey: str
18
+ platform: str
19
+
20
+
21
+ def account_config_to_raw(account: AccountConfig) -> dict[str, object]:
22
+ return {
23
+ "enabled": account.enabled,
24
+ "apiUrl": account.apiurl,
25
+ "apiKey": account.apikey,
26
+ "platform": account.platform,
27
+ }
28
+
29
+
30
+ def normalize_stored_account(raw: object) -> dict[str, object]:
31
+ source = raw if isinstance(raw, dict) else {}
32
+ apiurl = trim_string(source.get("apiUrl") or source.get("apiurl"))
33
+ platform = trim_string(source.get("platform")) or "IOS"
34
+ normalized: dict[str, object] = {
35
+ "enabled": source.get("enabled") is not False,
36
+ "apiUrl": normalize_apiurl(apiurl) if apiurl else "",
37
+ "apiKey": trim_string(source.get("apiKey") or source.get("apikey")),
38
+ "platform": normalize_platform(platform),
39
+ }
40
+ return normalized
41
+
42
+
43
+ def env_default_account() -> dict[str, object] | None:
44
+ apiurl = env_string("MAGIC_CAMPUS_BASE_URL")
45
+ apikey = env_string("MAGIC_CAMPUS_API_KEY")
46
+ if not apiurl or not apikey:
47
+ return None
48
+
49
+ parts = urlsplit(apiurl)
50
+ if (parts.scheme not in {"http", "https"} or not parts.hostname
51
+ or parts.username is not None or parts.password is not None
52
+ or parts.path not in {"", "/"} or parts.query or parts.fragment):
53
+ raise ValueError("MAGIC_CAMPUS_BASE_URL must be an HTTP(S) origin without a path, credentials, query or fragment.")
54
+ parts.port # Validate the port before constructing an HTTP client.
55
+ if any(c in os.environ.get("MAGIC_CAMPUS_API_KEY", "") for c in "\r\n") or not apikey.isascii():
56
+ raise ValueError("MAGIC_CAMPUS_API_KEY must be ASCII without newlines.")
57
+
58
+ return {
59
+ "enabled": True,
60
+ "apiUrl": apiurl,
61
+ "apiKey": apikey,
62
+ "platform": "IOS",
63
+ }
64
+
65
+
66
+ def normalize_account(account_id: str, raw: object) -> AccountConfig | None:
67
+ stored = normalize_stored_account(raw)
68
+ if not stored["apiUrl"] or not stored["apiKey"]:
69
+ return None
70
+
71
+ return AccountConfig(
72
+ account_id=account_id,
73
+ enabled=stored.get("enabled") is not False,
74
+ apiurl=str(stored["apiUrl"]),
75
+ apikey=str(stored["apiKey"]),
76
+ platform=str(stored["platform"]),
77
+ )
78
+
79
+
80
+ def list_account_ids(root: dict[str, object]) -> list[str]:
81
+ accounts = root.get("accounts")
82
+ ids = list(accounts.keys()) if isinstance(accounts, dict) else []
83
+ if env_default_account() and "default" not in ids:
84
+ ids.insert(0, "default")
85
+ return ids
86
+
87
+
88
+ def get_account_config(root: dict[str, object], account_id: str | None) -> AccountConfig | None:
89
+ resolved_id = account_id or str(root.get("defaultAccountId") or "default")
90
+ if resolved_id == "default":
91
+ env_account = env_default_account()
92
+ if env_account is not None:
93
+ return normalize_account("default", env_account)
94
+
95
+ accounts = root.get("accounts")
96
+ configured = accounts.get(resolved_id) if isinstance(accounts, dict) else None
97
+ if configured is not None:
98
+ return normalize_account(resolved_id, configured)
99
+ return None
100
+
101
+
102
+ def with_overridden_platform(account: AccountConfig, platform: str | None) -> AccountConfig:
103
+ normalized = trim_string(platform)
104
+ if not normalized:
105
+ return account
106
+ return replace(account, platform=normalize_platform(normalized))
107
+
108
+
109
+ def list_account_summaries(root: dict[str, object]) -> list[dict[str, object]]:
110
+ summaries: list[dict[str, object]] = []
111
+ default_account_id = str(root.get("defaultAccountId") or "default")
112
+ for account_id in list_account_ids(root):
113
+ account = get_account_config(root, account_id)
114
+ if account is None:
115
+ continue
116
+ summaries.append(
117
+ {
118
+ "accountId": account.account_id,
119
+ "default": account.account_id == default_account_id,
120
+ "enabled": account.enabled,
121
+ "apiUrl": account.apiurl,
122
+ "platform": account.platform,
123
+ }
124
+ )
125
+ return summaries
126
+
127
+
128
+ def upsert_stored_account(root: dict[str, object], account_id: str, raw_account: dict[str, object], make_default: bool = False) -> dict[str, object]:
129
+ accounts = root.get("accounts")
130
+ next_accounts = dict(accounts) if isinstance(accounts, dict) else {}
131
+ next_accounts[account_id] = normalize_stored_account(raw_account)
132
+ default_account_id = account_id if make_default else str(root.get("defaultAccountId") or account_id)
133
+ return {"defaultAccountId": default_account_id, "accounts": next_accounts}
134
+
135
+
136
+ def remove_stored_account(root: dict[str, object], account_id: str) -> dict[str, object]:
137
+ accounts = root.get("accounts")
138
+ next_accounts = dict(accounts) if isinstance(accounts, dict) else {}
139
+ next_accounts.pop(account_id, None)
140
+ remaining_ids = list(next_accounts.keys())
141
+ default_account_id = str(root.get("defaultAccountId") or "default")
142
+ if default_account_id == account_id:
143
+ default_account_id = remaining_ids[0] if remaining_ids else "default"
144
+ return {"defaultAccountId": default_account_id, "accounts": next_accounts}
magiccampus_cli/cli.py ADDED
@@ -0,0 +1,176 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+
6
+ from . import __version__
7
+ from .commands.auth import run_auth_command
8
+ from .commands.config import run_config_command
9
+ from .commands.comment import run_comment_command
10
+ from .commands.feed import run_feed_command
11
+ from .commands.im import run_im_command
12
+ from .commands.notify import run_notify_command
13
+ from .commands.space import run_space_command
14
+ from .commands.playgroup import run_playgroup_command
15
+ from .commands.user import run_user_command
16
+ from .output import print_output
17
+ from .update import ensure_latest
18
+
19
+
20
+ def _has_explicit_output_format(argv: list[str]) -> bool:
21
+ return "--format" in argv
22
+
23
+
24
+ def parse_argv(argv: list[str]) -> tuple[str, list[str]]:
25
+ args = list(argv)
26
+ output_format = "json"
27
+ index = 0
28
+ while index < len(args):
29
+ if args[index] == "--format":
30
+ if index + 1 >= len(args):
31
+ raise RuntimeError("--format requires a value.")
32
+ output_format = args[index + 1]
33
+ del args[index:index + 2]
34
+ continue
35
+ index += 1
36
+ return output_format, args
37
+
38
+
39
+ def parse_options(argv: list[str]) -> tuple[dict[str, object], list[str]]:
40
+ options: dict[str, object] = {}
41
+ positionals: list[str] = []
42
+ index = 0
43
+ while index < len(argv):
44
+ value = argv[index]
45
+ if value.startswith("--"):
46
+ key = value[2:]
47
+ next_value = argv[index + 1] if index + 1 < len(argv) else None
48
+ if next_value is not None and not next_value.startswith("--"):
49
+ options[key] = next_value
50
+ index += 2
51
+ continue
52
+ options[key] = True
53
+ index += 1
54
+ continue
55
+ positionals.append(value)
56
+ index += 1
57
+ return options, positionals
58
+
59
+
60
+ def usage() -> str:
61
+ return "\n".join(
62
+ [
63
+ f"magic-campus {__version__}",
64
+ "",
65
+ "Commands:",
66
+ " update (check PyPI now and upgrade if needed)",
67
+ " config init [--account <id>] --apiurl <url> --apikey <token> [--platform <name> --enabled <bool> --default <bool>]",
68
+ " config list",
69
+ " config use <accountId>",
70
+ " config remove <accountId>",
71
+ " auth status [--account default] [--platform <name>]",
72
+ " im notify send --to <user:ID|group:ID> (--text <text> | --markdown <text> | --custom <json> | --image <path|url> | --file <path|url> | --video <path|url>) [--cover-image <path|url> (with --custom)] [--name <filename>] [--account default] [--platform <name>] [--dry-run]",
73
+ " im notify send-link-card --to <user:ID|group:ID> --title <text> --sub-title <text> --schema <url> --cover-image <path|url> [--account default] [--platform <name>] [--dry-run] [--debug]",
74
+ " im notify history --to <user:ID|group:ID> [--limit <count>] [--account default] [--platform <name>]",
75
+ " im group kick --group <id> --users <id1,id2> [--reason <text>]",
76
+ " im reaction add --conversation-id <id> --server-msg-id <id> --msg-sender-id <userId> --reaction-code <code> [--account default]",
77
+ " im reaction delete --conversation-id <id> --server-msg-id <id> --msg-sender-id <userId> --reaction-id <id> [--account default]",
78
+ " im group get --group <groupId> [--account default] [--platform <name>]",
79
+ " im group get-batch --groups <id1,id2> [--account default] [--platform <name>]",
80
+ " im group create --name <groupName> [--members <id1,id2>] [--admins <id1,id2>] [--owner <userId>] [--group-id <id>] [--notification <text>] [--introduction <text>] [--face-url <url>] [--ex <json>] [--send-message <bool>] [--account default] [--platform <name>]",
81
+ " im group invite --group <groupId> --users <id1,id2> [--reason <text>] [--send-message <bool>] [--account default] [--platform <name>]",
82
+ " im group dismiss --group <groupId> [--delete-member <bool>] [--send-message <bool>] [--account default] [--platform <name>]",
83
+ " im group transfer-owner --group <groupId> --new-owner <userId> [--old-owner <userId>] [--account default] [--platform <name>]",
84
+ " im chat.members get --group <groupId> [--keyword <text>] [--page-number <number>] [--show-number <number>] [--account default] [--platform <name>]",
85
+ " playgroup list [--account default]",
86
+ " playgroup get --id <spaceId> [--account default]",
87
+ " playgroup join --id <spaceId> [--account default] (submit an application)",
88
+ " playgroup invite-members --id <spaceId> --users <id1,id2|JSON-array> [--reason <text>] [--account default]",
89
+ " space list-notice --space <spaceId> [--account default]",
90
+ " space create-notice --space <spaceId> --title <title> --text <text> --expiretime <timestamp> [--account default]",
91
+ " space group update-name --group <groupId> --name <name> [--account default]",
92
+ " user get --id <userId> [--account default]",
93
+ " user list (--all | --random) [--fields <field1,field2>] [--academy-code <code>] [--account default]",
94
+ " user update-info [--nickname <name>] [--avatar-url <url>] [--introduction <text>] [--birth <yyyy-MM-dd>] [--gender <MALE|FEMALE|OTHER|UNKNOWN>] [--tags <json-array>] [--account default] (authenticated user; no --id)",
95
+ " user update-info (--json <object> | --body <path|->) [--account default]",
96
+ " user update-profile --id <userId> [--nickname <name>] [--avatar-url <url>] [--account default] (deprecated explicit-target compatibility)",
97
+ " user update-ext (--json <object> | --body <path|->) [--account default] (authenticated user; no --id)",
98
+ " user get-growth-profile --id <userId> [--account default]",
99
+ " user init-growth-profile --id <userId> [--reset <true|false>] [--account default]",
100
+ " user set-academy --id <userId> --academy-code <Material|Digital|Sound|Movement|Nature|Healing> [--account default]",
101
+ " user adjust-elements --id <userId> [--metal-delta <int>] [--wood-delta <int>] [--water-delta <int>] [--fire-delta <int>] [--earth-delta <int>] [--account default]",
102
+ " feed list [--limit <1-100>] [--cursor <value>] [--account default] (published user stories, newest first)",
103
+ " comment list --feed-id <feedId> [--page <number>] [--focus-comment-id <commentId>] [--account default]",
104
+ " comment get --id <commentId> [--account default]",
105
+ " comment create --feed-id <feedId> --content <text> [--account default]",
106
+ " comment like|unlike|delete --id <commentId> [--account default]",
107
+ " notify +send --to <user:ID|group:ID> (--text <text> | --markdown <text> | --custom <json> | --image <path|url> | --file <path|url> | --video <path|url>) [--cover-image <path|url> (with --custom)] [--name <filename>] [--account default] [--platform <name>] [--dry-run] (compat)",
108
+ " notify +history --to <user:ID|group:ID> [--limit <count>] [--account default] [--platform <name>] (compat)",
109
+ "",
110
+ "Business authentication: MAGIC_CAMPUS_BASE_URL + MAGIC_CAMPUS_API_KEY (required).",
111
+ "Stored config accounts do not select business credentials; platform defaults to IOS.",
112
+ "",
113
+ "Global flags:",
114
+ " --format json|pretty|table|ndjson",
115
+ ]
116
+ )
117
+
118
+
119
+ def main(raw_argv: list[str] | None = None) -> int:
120
+ argv = list(sys.argv[1:] if raw_argv is None else raw_argv)
121
+ output_format = "json"
122
+ try:
123
+ has_explicit_output_format = _has_explicit_output_format(argv)
124
+ output_format, args = parse_argv(argv)
125
+ if not args or "--help" in args or "-h" in args:
126
+ if not has_explicit_output_format:
127
+ sys.stdout.write(f"{usage()}\n")
128
+ return 0
129
+ print_output({"ok": True, "usage": usage()}, output_format)
130
+ return 0
131
+
132
+ if args[0] == "--version":
133
+ print_output({"ok": True, "version": __version__, "runtime": "python"}, output_format)
134
+ return 0
135
+
136
+ if args[0] == "update" and len(args) != 1:
137
+ raise RuntimeError("update does not accept arguments.")
138
+ if args[0] in {"update", "auth", "im", "user", "space", "playgroup", "feed", "comment", "notify"}:
139
+ exit_code = ensure_latest(argv, refresh=args[0] == "update")
140
+ if exit_code is not None:
141
+ return exit_code
142
+
143
+ if args[0] == "update":
144
+ result = {"ok": True, "version": __version__}
145
+ elif args[0] == "config":
146
+ result = run_config_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
147
+ elif args[0] == "auth":
148
+ result = run_auth_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
149
+ elif args[0] == "im":
150
+ result = run_im_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
151
+ elif args[0] == "user":
152
+ result = run_user_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
153
+ elif args[0] == "playgroup":
154
+ result = run_playgroup_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
155
+ elif args[0] == "space":
156
+ result = run_space_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
157
+ elif args[0] == "feed":
158
+ result = run_feed_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
159
+ elif args[0] == "comment":
160
+ result = run_comment_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
161
+ elif args[0] == "notify":
162
+ result = run_notify_command(args[1] if len(args) > 1 else None, args[2:], parse_options)
163
+ else:
164
+ raise RuntimeError(f"Unknown command: {args[0]}")
165
+
166
+ print_output(result, output_format)
167
+ return 0
168
+ except Exception as error:
169
+ secret = os.environ.get("MAGIC_CAMPUS_API_KEY", "").strip()
170
+ message = str(error).replace(secret, "[REDACTED]") if secret else str(error)
171
+ print_output({"ok": False, "error": message}, output_format)
172
+ return 1
173
+
174
+
175
+ if __name__ == "__main__":
176
+ raise SystemExit(main())
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+ from typing import Callable, TypeVar
3
+ from magiccampus_sdk import MagicCampusClientConfig
4
+ from magiccampus_sdk.group_client import MagicCampusGroupClient
5
+ from magiccampus_sdk.http.http_send import MagicCampusHTTPSendClient, MagicCampusHTTPSendConfig
6
+ from .accounts import AccountConfig
7
+ from .utils import mask_secret
8
+
9
+ T = TypeVar("T")
10
+
11
+
12
+ def build_group_client(account: AccountConfig) -> MagicCampusGroupClient:
13
+ return MagicCampusGroupClient(
14
+ MagicCampusClientConfig(apiurl=account.apiurl, apikey=account.apikey, platform=account.platform)
15
+ )
16
+
17
+
18
+ def with_group_client(account: AccountConfig, action: Callable[..., T]) -> T:
19
+ return action(build_group_client(account))
20
+
21
+
22
+ def with_http_send_client(account: AccountConfig, action: Callable[..., T]) -> T:
23
+ client = MagicCampusHTTPSendClient(
24
+ MagicCampusHTTPSendConfig(apiurl=account.apiurl, apikey=account.apikey, platform=account.platform)
25
+ )
26
+ client.login()
27
+ try:
28
+ return action(client)
29
+ finally:
30
+ client.logout()
31
+
32
+
33
+ def get_auth_status(account: AccountConfig) -> dict[str, object]:
34
+ import time
35
+ from magiccampus_sdk.auth import resolve_platform_id
36
+
37
+ credentials = build_group_client(account).credentials
38
+ return {
39
+ "ok": True,
40
+ "accountId": account.account_id,
41
+ "userID": credentials.user_id,
42
+ "platformID": resolve_platform_id(account.platform),
43
+ "provider": "magiccampus",
44
+ "transport": "http_api",
45
+ "loginStatus": "authenticated",
46
+ "magiccampus": {
47
+ "enabled": account.enabled,
48
+ "platform": account.platform,
49
+ "apiUrl": account.apiurl,
50
+ "apiKeyPreview": mask_secret(account.apikey),
51
+ "expireAt": credentials.expire_time,
52
+ "expiresInSeconds": max(0, credentials.expire_time - int(time.time())),
53
+ },
54
+ }
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ from ..accounts import env_default_account, normalize_account, with_overridden_platform
4
+ from ..config_store import read_config_root
5
+ from ..utils import env_string
6
+
7
+
8
+ def resolve_account_or_throw(root: dict[str, object], account_id: str | None):
9
+ # Stored accounts are intentionally excluded from all business commands.
10
+ if account_id is not None and account_id != "default":
11
+ raise RuntimeError(
12
+ "Business commands use one environment credential; --account only accepts default. "
13
+ "Set MAGIC_CAMPUS_BASE_URL and MAGIC_CAMPUS_API_KEY to select the connection."
14
+ )
15
+ configured = env_default_account()
16
+ if configured is None:
17
+ missing = [name for name in ("MAGIC_CAMPUS_BASE_URL", "MAGIC_CAMPUS_API_KEY") if not env_string(name)]
18
+ raise RuntimeError("Missing " + ", ".join(missing) + ". Set both MAGIC_CAMPUS_BASE_URL and MAGIC_CAMPUS_API_KEY in the runtime environment.")
19
+ return normalize_account("default", configured)
20
+
21
+
22
+ def run_auth_command(subcommand: str | None, argv: list[str], parse_options):
23
+ if subcommand != "status":
24
+ raise RuntimeError(f"Unknown auth subcommand: {subcommand}")
25
+
26
+ options, _ = parse_options(argv)
27
+ root = read_config_root()
28
+ account = resolve_account_or_throw(root, options.get("account"))
29
+ account = with_overridden_platform(account, options.get("platform"))
30
+ from ..client import get_auth_status
31
+
32
+ return get_auth_status(account)
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
4
+
5
+ from ..config_store import read_config_root
6
+ from .auth import resolve_account_or_throw
7
+
8
+
9
+ def run_comment_command(subcommand: str | None, argv: list[str], parse_options):
10
+ fields = {
11
+ "create": {"feed-id", "content"},
12
+ "list": {"feed-id", "page", "focus-comment-id"},
13
+ "get": {"id"}, "like": {"id"}, "unlike": {"id"}, "delete": {"id"},
14
+ }
15
+ if subcommand not in fields:
16
+ raise RuntimeError(f"Unknown comment subcommand: {subcommand}")
17
+ options, positionals = parse_options(argv)
18
+ if positionals or set(options) - fields[subcommand] - {"account"}:
19
+ raise RuntimeError(f"Unsupported arguments for comment {subcommand}.")
20
+ for name in fields[subcommand]:
21
+ value = options.get(name)
22
+ if name in {"page", "focus-comment-id"} and value is None:
23
+ continue
24
+ if not isinstance(value, str) or not value.strip():
25
+ raise RuntimeError(f"comment {subcommand} requires --{name} <value>.")
26
+ page = options.get("page", "1")
27
+ if subcommand == "list" and (not page.isascii() or not page.isdecimal() or int(page) < 1):
28
+ raise RuntimeError("--page must be a positive integer.")
29
+ account = resolve_account_or_throw(read_config_root(), options.get("account"))
30
+ client = MagicCampusClient(MagicCampusClientConfig(apiurl=account.apiurl, apikey=account.apikey))
31
+ if subcommand == "create":
32
+ result = client.comment.create(options["feed-id"], options["content"])
33
+ elif subcommand == "list":
34
+ result = client.comment.list(options["feed-id"], page=int(page),
35
+ focus_comment_id=options.get("focus-comment-id"))
36
+ else:
37
+ result = getattr(client.comment, subcommand)(options["id"])
38
+ return {"ok": True, "resource": "comment", "action": subcommand, "result": result}