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,139 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Callable, Dict, Sequence
4
+
5
+ import httpx
6
+
7
+ from .auth import normalize_apiurl
8
+
9
+
10
+ def get_group_members(
11
+ *,
12
+ apiurl: str,
13
+ apikey: str,
14
+ group_id: str,
15
+ keyword: str = "",
16
+ page_number: int = 1,
17
+ show_number: int = 100,
18
+ timeout_seconds: float,
19
+ make_http_error: Callable[[int, str], Exception],
20
+ make_sdk_error: Callable[[int, str, str], Exception],
21
+ ) -> Any:
22
+ normalized_apiurl = normalize_apiurl(apiurl)
23
+ normalized_apikey = str(apikey or "").strip()
24
+ normalized_group_id = str(group_id or "").strip()
25
+ normalized_keyword = str(keyword or "").strip()
26
+ normalized_page_number = _normalize_positive_int(page_number, name="page_number")
27
+ normalized_show_number = _normalize_positive_int(show_number, name="show_number")
28
+
29
+ if not normalized_apikey:
30
+ raise ValueError("magiccampus apikey is required")
31
+ if not normalized_group_id:
32
+ raise ValueError("group_id is required")
33
+
34
+ params: Dict[str, Any] = {
35
+ "groupID": normalized_group_id,
36
+ "pageNumber": normalized_page_number,
37
+ "showNumber": normalized_show_number,
38
+ }
39
+ if normalized_keyword:
40
+ params["keyword"] = normalized_keyword
41
+
42
+ response = httpx.get(
43
+ f"{normalized_apiurl}/api/v1/im/group/members",
44
+ params=params,
45
+ headers={"Authorization": f"Bearer {normalized_apikey}"},
46
+ timeout=timeout_seconds,
47
+ )
48
+
49
+ try:
50
+ response.raise_for_status()
51
+ except httpx.HTTPStatusError as exc:
52
+ raise make_http_error(exc.response.status_code, exc.response.text) from exc
53
+
54
+ payload = response.json()
55
+ if not isinstance(payload, dict):
56
+ raise ValueError("magiccampus group members response must be a JSON object")
57
+
58
+ code = int(payload.get("code", 0) or 0)
59
+ if code != 200:
60
+ raise make_sdk_error(code, str(payload.get("msg", "") or ""), str(payload.get("detail", "") or ""))
61
+
62
+ data = payload.get("data")
63
+ return data if data is not None else {}
64
+
65
+
66
+ def invite_group_members(
67
+ *,
68
+ apiurl: str,
69
+ apikey: str,
70
+ group_id: str,
71
+ invited_user_ids: Sequence[str],
72
+ reason: str,
73
+ timeout_seconds: float,
74
+ make_http_error: Callable[[int, str], Exception],
75
+ make_sdk_error: Callable[[int, str, str], Exception],
76
+ ) -> Dict[str, Any]:
77
+ normalized_apiurl = normalize_apiurl(apiurl)
78
+ normalized_apikey = str(apikey or "").strip()
79
+ normalized_group_id = str(group_id or "").strip()
80
+ normalized_reason = str(reason or "").strip()
81
+ normalized_user_ids = _normalize_user_ids(invited_user_ids)
82
+
83
+ if not normalized_apikey:
84
+ raise ValueError("magiccampus apikey is required")
85
+ if not normalized_group_id:
86
+ raise ValueError("group_id is required")
87
+ if not normalized_user_ids:
88
+ raise ValueError("invited_user_ids is required")
89
+
90
+ response = httpx.post(
91
+ f"{normalized_apiurl}/api/v1/im/group/inviteMembers",
92
+ json={
93
+ "groupID": normalized_group_id,
94
+ "invitedUserIDs": normalized_user_ids,
95
+ "reason": normalized_reason or None,
96
+ },
97
+ headers={
98
+ "Authorization": f"Bearer {normalized_apikey}",
99
+ "Content-Type": "application/json",
100
+ },
101
+ timeout=timeout_seconds,
102
+ )
103
+
104
+ try:
105
+ response.raise_for_status()
106
+ except httpx.HTTPStatusError as exc:
107
+ raise make_http_error(exc.response.status_code, exc.response.text) from exc
108
+
109
+ payload = response.json()
110
+ if not isinstance(payload, dict):
111
+ raise ValueError("magiccampus inviteMembers response must be a JSON object")
112
+
113
+ code = int(payload.get("code", 0) or 0)
114
+ if code != 200:
115
+ raise make_sdk_error(code, str(payload.get("msg", "") or ""), str(payload.get("detail", "") or ""))
116
+
117
+ data = payload.get("data")
118
+ return data if isinstance(data, dict) else {}
119
+
120
+
121
+ def _normalize_user_ids(user_ids: Sequence[str]) -> list[str]:
122
+ normalized: list[str] = []
123
+ seen: set[str] = set()
124
+ for user_id in user_ids:
125
+ text = str(user_id or "").strip()
126
+ if text and text not in seen:
127
+ seen.add(text)
128
+ normalized.append(text)
129
+ return normalized
130
+
131
+
132
+ def _normalize_positive_int(value: int, *, name: str) -> int:
133
+ try:
134
+ normalized = int(value)
135
+ except (TypeError, ValueError) as exc:
136
+ raise ValueError(f"{name} must be a positive integer") from exc
137
+ if normalized <= 0:
138
+ raise ValueError(f"{name} must be a positive integer")
139
+ return normalized
@@ -0,0 +1,242 @@
1
+ """HTTP-only group administration and message query operations."""
2
+
3
+ from typing import Any, Dict, Optional, Sequence
4
+ import httpx
5
+ import time
6
+ from .auth import fetch_magiccampus_credentials
7
+ from .platform_http import MagicCampusAPIHTTPError, MagicCampusAPIRemoteError, next_operation_id
8
+ from .http.http_api import post_json_data
9
+ from .http.group_info_api import fetch_group_info, fetch_groups_info
10
+ from .group_api import get_group_members, invite_group_members
11
+
12
+
13
+ class MagicCampusGroupClient:
14
+ def __init__(self, config):
15
+ self._config = config
16
+ self._credentials = None
17
+
18
+ @property
19
+ def credentials(self):
20
+ if self._credentials is None or self._credentials.expire_time <= int(time.time()) + 60:
21
+ self._credentials = fetch_magiccampus_credentials(
22
+ apiurl=self._config.apiurl,
23
+ apikey=self._config.apikey,
24
+ platform=self._config.platform,
25
+ timeout_seconds=self._config.credential_timeout_seconds,
26
+ )
27
+ return self._credentials
28
+
29
+ @property
30
+ def user_id(self):
31
+ return self._credentials.user_id if self._credentials is not None else ""
32
+
33
+ def _assert_login(self):
34
+ self.credentials
35
+
36
+ def _post_api(self, route, payload, *, purpose):
37
+ credentials = self.credentials
38
+ return post_json_data(
39
+ api_addr=credentials.api_addr,
40
+ route=route,
41
+ payload=payload,
42
+ token=credentials.token,
43
+ operation_id=next_operation_id(),
44
+ timeout_seconds=self._config.request_timeout_seconds,
45
+ make_http_error=MagicCampusAPIHTTPError,
46
+ make_sdk_error=MagicCampusAPIRemoteError,
47
+ )
48
+
49
+ def invite_user_to_group(self, *, group_id, invited_user_ids, reason="", send_message=None):
50
+ # The business invitation endpoint controls notification behavior.
51
+ _ = send_message
52
+ return invite_group_members(
53
+ apiurl=self._config.apiurl,
54
+ apikey=self._config.apikey,
55
+ group_id=group_id,
56
+ invited_user_ids=invited_user_ids,
57
+ reason=reason,
58
+ timeout_seconds=self._config.request_timeout_seconds,
59
+ make_http_error=MagicCampusAPIHTTPError,
60
+ make_sdk_error=MagicCampusAPIRemoteError,
61
+ )
62
+
63
+ def get_group_members(self, *, group_id, keyword="", page_number=1, show_number=100):
64
+ return get_group_members(
65
+ apiurl=self._config.apiurl,
66
+ apikey=self._config.apikey,
67
+ group_id=group_id,
68
+ keyword=keyword,
69
+ page_number=page_number,
70
+ show_number=show_number,
71
+ timeout_seconds=self._config.request_timeout_seconds,
72
+ make_http_error=MagicCampusAPIHTTPError,
73
+ make_sdk_error=MagicCampusAPIRemoteError,
74
+ )
75
+
76
+ def _business_post(self, route, payload):
77
+ response = httpx.post(
78
+ self._config.apiurl.rstrip("/") + route,
79
+ headers={"Authorization": f"Bearer {self._config.apikey.strip()}"},
80
+ json=payload,
81
+ timeout=self._config.request_timeout_seconds,
82
+ )
83
+ try:
84
+ response.raise_for_status()
85
+ except httpx.HTTPStatusError as exc:
86
+ raise MagicCampusAPIHTTPError(response.status_code, response.text) from exc
87
+ body = response.json()
88
+ if not isinstance(body, dict):
89
+ raise ValueError("Expected a JSON object")
90
+ if body.get("code") != 200:
91
+ raise MagicCampusAPIRemoteError(body.get("code", 0), body.get("msg", ""), body.get("detail", ""))
92
+ return body.get("data")
93
+
94
+ def kick_members(self, *, group_id, user_ids, reason=""):
95
+ group_id = str(group_id).strip()
96
+ user_ids = self._normalize_string_list(user_ids)
97
+ if not group_id or not user_ids:
98
+ raise ValueError("group_id and user_ids are required")
99
+ return self._business_post(
100
+ "/api/v1/im/group/kickMembers", {"groupID": group_id, "kickedUserIDs": list(user_ids), "reason": reason}
101
+ )
102
+
103
+ def query_messages(self, *, limit=50, include_groups=True):
104
+ if limit <= 0:
105
+ raise ValueError("limit must be positive")
106
+ return self._business_post(
107
+ "/api/v1/im/message/query",
108
+ {
109
+ "userID": self.credentials.user_id,
110
+ "limitPerConversation": limit,
111
+ "includeGroups": include_groups,
112
+ "includeSelf": True,
113
+ "includeNonText": True,
114
+ "includeNotifications": False,
115
+ },
116
+ )
117
+
118
+ def get_groups_info(self, group_ids: Sequence[str]) -> list[Dict[str, Any]]:
119
+ self._assert_login()
120
+ return fetch_groups_info(
121
+ group_ids=group_ids,
122
+ post_api=lambda route, payload: self._post_api(
123
+ route,
124
+ payload,
125
+ purpose="get_groups_info",
126
+ ),
127
+ )
128
+
129
+ def get_group_info(self, group_id: str) -> Dict[str, Any]:
130
+ self._assert_login()
131
+ return fetch_group_info(
132
+ group_id=group_id,
133
+ post_api=lambda route, payload: self._post_api(
134
+ route,
135
+ payload,
136
+ purpose="get_group_info",
137
+ ),
138
+ make_not_found_error=lambda gid: ValueError(f"group info not found, groupID={gid}"),
139
+ )
140
+
141
+ def create_group(
142
+ self,
143
+ *,
144
+ group_name: str,
145
+ member_user_ids: Optional[Sequence[str]] = None,
146
+ admin_user_ids: Optional[Sequence[str]] = None,
147
+ owner_user_id: str = "",
148
+ group_id: str = "",
149
+ notification: str = "",
150
+ introduction: str = "",
151
+ face_url: str = "",
152
+ ex: str = "",
153
+ group_type: Optional[int] = None,
154
+ need_verification: Optional[int] = None,
155
+ look_member_info: Optional[int] = None,
156
+ apply_member_friend: Optional[int] = None,
157
+ send_message: Optional[bool] = None,
158
+ ) -> Dict[str, Any]:
159
+ self._assert_login()
160
+ if not group_name:
161
+ raise ValueError("group_name is required")
162
+ effective_owner_user_id = owner_user_id or self.user_id
163
+
164
+ group_info = self._drop_none(
165
+ {
166
+ "groupID": group_id or None,
167
+ "groupName": group_name,
168
+ "notification": notification or None,
169
+ "introduction": introduction or None,
170
+ "faceURL": face_url or None,
171
+ "ex": ex or None,
172
+ "groupType": int(group_type) if group_type is not None else None,
173
+ "needVerification": int(need_verification) if need_verification is not None else None,
174
+ "lookMemberInfo": int(look_member_info) if look_member_info is not None else None,
175
+ "applyMemberFriend": int(apply_member_friend) if apply_member_friend is not None else None,
176
+ }
177
+ )
178
+ payload = self._drop_none(
179
+ {
180
+ "memberUserIDs": self._normalize_string_list(member_user_ids),
181
+ "adminUserIDs": self._normalize_string_list(admin_user_ids),
182
+ "ownerUserID": effective_owner_user_id,
183
+ "groupInfo": group_info,
184
+ "sendMessage": bool(send_message) if send_message is not None else None,
185
+ }
186
+ )
187
+ return self._post_api("/group/create_group", payload, purpose="create_group")
188
+
189
+ def dismiss_group(
190
+ self,
191
+ *,
192
+ group_id: str,
193
+ delete_member: bool = False,
194
+ send_message: Optional[bool] = None,
195
+ ) -> Dict[str, Any]:
196
+ self._assert_login()
197
+ if not group_id:
198
+ raise ValueError("group_id is required")
199
+ payload = self._drop_none(
200
+ {
201
+ "groupID": group_id,
202
+ "deleteMember": bool(delete_member),
203
+ "sendMessage": bool(send_message) if send_message is not None else None,
204
+ }
205
+ )
206
+ return self._post_api("/group/dismiss_group", payload, purpose="dismiss_group")
207
+
208
+ def transfer_group_owner(
209
+ self,
210
+ *,
211
+ group_id: str,
212
+ new_owner_user_id: str,
213
+ old_owner_user_id: str = "",
214
+ ) -> Dict[str, Any]:
215
+ self._assert_login()
216
+ if not group_id:
217
+ raise ValueError("group_id is required")
218
+ if not new_owner_user_id:
219
+ raise ValueError("new_owner_user_id is required")
220
+ payload = {
221
+ "groupID": group_id,
222
+ "oldOwnerUserID": old_owner_user_id or self.user_id,
223
+ "newOwnerUserID": new_owner_user_id,
224
+ }
225
+ return self._post_api("/group/transfer_group", payload, purpose="transfer_group_owner")
226
+
227
+ @staticmethod
228
+ def _drop_none(values: Dict[str, Any]) -> Dict[str, Any]:
229
+ return {key: value for key, value in values.items() if value is not None}
230
+
231
+ @staticmethod
232
+ def _normalize_string_list(values: Optional[Sequence[str]]) -> list[str]:
233
+ if not values:
234
+ return []
235
+ normalized: list[str] = []
236
+ seen: set[str] = set()
237
+ for value in values:
238
+ text = str(value or "").strip()
239
+ if text and text not in seen:
240
+ seen.add(text)
241
+ normalized.append(text)
242
+ return normalized
@@ -0,0 +1 @@
1
+ """HTTP message operations; no persistent IM connection."""
@@ -0,0 +1,47 @@
1
+ from typing import Any, Callable, Dict, List, Sequence
2
+
3
+
4
+ PostAPI = Callable[[str, Dict[str, Any]], Dict[str, Any]]
5
+
6
+
7
+ def fetch_groups_info(
8
+ *,
9
+ group_ids: Sequence[str],
10
+ post_api: PostAPI,
11
+ ) -> List[Dict[str, Any]]:
12
+ normalized_group_ids = _normalize_group_ids(group_ids)
13
+ if not normalized_group_ids:
14
+ raise ValueError("group_ids is required")
15
+
16
+ data = post_api("/group/get_groups_info", {"groupIDs": normalized_group_ids})
17
+ group_infos = data.get("groupInfos", [])
18
+ if not isinstance(group_infos, list):
19
+ return []
20
+ return [dict(group_info) for group_info in group_infos if isinstance(group_info, dict)]
21
+
22
+
23
+ def fetch_group_info(
24
+ *,
25
+ group_id: str,
26
+ post_api: PostAPI,
27
+ make_not_found_error: Callable[[str], Exception],
28
+ ) -> Dict[str, Any]:
29
+ normalized_group_id = str(group_id or "").strip()
30
+ if not normalized_group_id:
31
+ raise ValueError("group_id is required")
32
+
33
+ for group_info in fetch_groups_info(group_ids=[normalized_group_id], post_api=post_api):
34
+ if str(group_info.get("groupID", "") or "") == normalized_group_id:
35
+ return group_info
36
+ raise make_not_found_error(normalized_group_id)
37
+
38
+
39
+ def _normalize_group_ids(group_ids: Sequence[str]) -> List[str]:
40
+ normalized: List[str] = []
41
+ seen: set[str] = set()
42
+ for group_id in group_ids:
43
+ text = str(group_id or "").strip()
44
+ if text and text not in seen:
45
+ seen.add(text)
46
+ normalized.append(text)
47
+ return normalized
@@ -0,0 +1,58 @@
1
+ import gzip
2
+ import json
3
+ from io import BytesIO
4
+ import urllib.error
5
+ import urllib.request
6
+ from typing import Any, Callable, Dict
7
+
8
+
9
+ def post_json_data(
10
+ *,
11
+ api_addr: str,
12
+ route: str,
13
+ payload: Dict[str, Any],
14
+ token: str,
15
+ operation_id: str,
16
+ timeout_seconds: float,
17
+ make_http_error: Callable[[int, str], Exception],
18
+ make_sdk_error: Callable[[int, str, str], Exception],
19
+ ) -> Dict[str, Any]:
20
+ if not route.startswith("/"):
21
+ route = "/" + route
22
+ url = api_addr.rstrip("/") + route
23
+ body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
24
+ req = urllib.request.Request(url=url, method="POST", data=body)
25
+ req.add_header("Content-Type", "application/json")
26
+ req.add_header("operationID", operation_id)
27
+ req.add_header("token", token)
28
+ req.add_header("Accept-Encoding", "gzip")
29
+
30
+ try:
31
+ with urllib.request.urlopen(req, timeout=timeout_seconds) as resp:
32
+ raw = resp.read()
33
+ if resp.headers.get("Content-Encoding", "") == "gzip":
34
+ raw = gzip.decompress(raw)
35
+ decoded = raw.decode("utf-8")
36
+ except urllib.error.HTTPError as exc:
37
+ raw = exc.read()
38
+ if exc.headers.get("Content-Encoding", "") == "gzip" or raw[:2] == b"\x1f\x8b":
39
+ try:
40
+ raw = gzip.decompress(raw)
41
+ except Exception:
42
+ try:
43
+ raw = gzip.GzipFile(fileobj=BytesIO(raw)).read()
44
+ except Exception:
45
+ pass
46
+ body_text = raw.decode("utf-8", errors="ignore")
47
+ raise make_http_error(exc.code, body_text) from exc
48
+ except urllib.error.URLError as exc:
49
+ raise ConnectionError(str(exc.reason)) from exc
50
+
51
+ result = json.loads(decoded)
52
+ err_code = int(result.get("errCode", 0) or 0)
53
+ if err_code != 0:
54
+ err_msg = str(result.get("errMsg", "") or "")
55
+ err_dlt = str(result.get("errDlt", "") or "")
56
+ raise make_sdk_error(err_code, err_msg, err_dlt)
57
+ data = result.get("data", {})
58
+ return data if isinstance(data, dict) else {}