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,149 @@
1
+ """Check the CLI release before dispatching a business command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from importlib import metadata
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ import urllib.request
15
+
16
+ from . import __version__
17
+
18
+ PYPI_PACKAGE = "magic-campus-cli"
19
+ PYPI_METADATA_URL = f"https://pypi.org/pypi/{PYPI_PACKAGE}/json"
20
+ _UPDATE_TARGET = "_MAGIC_CAMPUS_BUSINESS_CLI_UPDATE_TARGET"
21
+ _CACHE_TTL_SECONDS = 12 * 60 * 60
22
+ _CACHE_PATH = Path.home() / ".magic-campus" / "cache" / "cli-update-check.json"
23
+
24
+
25
+ def version_key(version: str) -> tuple:
26
+ """Compare a public release version against a stable PyPI target."""
27
+ match = re.fullmatch(
28
+ r"v?(?:(?P<epoch>\d+)!)?(?P<release>\d+(?:\.\d+)*)"
29
+ r"(?:(?P<pre>a|b|rc)\d+)?(?:\.post(?P<post>\d+))?"
30
+ r"(?:\.dev(?P<dev>\d+))?(?:\+[a-z0-9]+(?:[._-][a-z0-9]+)*)?",
31
+ version.strip().lower(),
32
+ )
33
+ if match is None:
34
+ raise ValueError(f"Unsupported SDK version: {version}")
35
+ release = [int(part) for part in match["release"].split(".")]
36
+ while len(release) > 1 and release[-1] == 0:
37
+ release.pop()
38
+ before_release = match["pre"] is not None or (match["dev"] is not None and match["post"] is None)
39
+ return (
40
+ int(match["epoch"] or 0),
41
+ tuple(release),
42
+ not before_release,
43
+ int(match["post"] or -1),
44
+ match["dev"] is None,
45
+ )
46
+
47
+
48
+ def latest_pypi_version(*, refresh: bool = False) -> str:
49
+ cache_path = _CACHE_PATH
50
+ try:
51
+ cached = json.loads(cache_path.read_text(encoding="utf-8"))
52
+ checked_at = cached["checkedAt"]
53
+ version = cached["version"]
54
+ if isinstance(version, str) and type(checked_at) in (int, float):
55
+ key = version_key(version)
56
+ if not refresh and key[2] and key[-1] and 0 <= time.time() - checked_at < _CACHE_TTL_SECONDS:
57
+ return version
58
+ except (OSError, ValueError, KeyError, TypeError):
59
+ pass
60
+
61
+ try:
62
+ with urllib.request.urlopen(PYPI_METADATA_URL, timeout=15) as response:
63
+ payload = json.load(response)
64
+ version = payload["info"]["version"]
65
+ if not isinstance(version, str):
66
+ raise ValueError("Expected a stable release version")
67
+ key = version_key(version)
68
+ if not key[2] or not key[-1]:
69
+ raise ValueError("Expected a stable release version")
70
+ try:
71
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
72
+ with tempfile.TemporaryDirectory(dir=cache_path.parent) as directory:
73
+ temporary = Path(directory) / cache_path.name
74
+ temporary.write_text(
75
+ json.dumps({"version": version, "checkedAt": time.time()}),
76
+ encoding="utf-8",
77
+ )
78
+ temporary.replace(cache_path)
79
+ except OSError:
80
+ pass # An unwritable cache must not discard a successful version check.
81
+ return version
82
+ except (OSError, ValueError, KeyError, TypeError) as exc:
83
+ raise RuntimeError(
84
+ f"Unable to check the latest {PYPI_PACKAGE} version on PyPI: {exc}. No upgrade attempted."
85
+ ) from exc
86
+
87
+
88
+ def ensure_latest(argv: list[str], *, refresh: bool = False) -> int | None:
89
+ # These distributions own the same module/command paths. Never let an update
90
+ # mutate an environment still owned by the frozen runtime dependency.
91
+ try:
92
+ metadata.version("magic-campus-sdk")
93
+ except metadata.PackageNotFoundError:
94
+ pass
95
+ else:
96
+ raise RuntimeError(
97
+ "magic-campus-cli must run in a separate environment from frozen magic-campus-sdk. No upgrade attempted."
98
+ )
99
+ target = os.environ.pop(_UPDATE_TARGET, "").strip()
100
+ if target:
101
+ if version_key(__version__) < version_key(target):
102
+ raise RuntimeError(
103
+ f"SDK upgrade still loads {__version__}; expected at least {target}. Check the Python environment and source path. No repeated upgrade attempted."
104
+ )
105
+ return None
106
+
107
+ latest = latest_pypi_version(refresh=True) if refresh else latest_pypi_version()
108
+ if version_key(__version__) >= version_key(latest):
109
+ return None
110
+
111
+ flags = ["--upgrade"] if sys.prefix != sys.base_prefix else ["--user", "--upgrade"]
112
+ source = os.getenv("MAGIC_CAMPUS_CLI_SOURCE", "").strip()
113
+ if source:
114
+ project = Path(source).expanduser()
115
+ if not (project / "pyproject.toml").is_file():
116
+ raise ValueError("MAGIC_CAMPUS_CLI_SOURCE must point to an SDK project containing pyproject.toml.")
117
+ document = (project / "pyproject.toml").read_text(encoding="utf-8")
118
+ section = re.search(r"(?ms)^\[project\][ \t]*\n(.*?)(?=^\[|\Z)", document)
119
+ project_name = re.search(r"(?m)^name\s*=\s*[\"']([^\"']+)[\"']\s*(?:#.*)?$", section[1]) if section else None
120
+ if project_name is None or project_name[1] != PYPI_PACKAGE:
121
+ raise ValueError("MAGIC_CAMPUS_CLI_SOURCE must select the magic-campus-cli project. No upgrade attempted.")
122
+ flags.append("--no-build-isolation")
123
+ package = str(project)
124
+ else:
125
+ package = f"{PYPI_PACKAGE}=={latest}"
126
+ # Keep stderr empty on success: some runtimes spill any stderr to a file,
127
+ # costing the caller another round just to read it.
128
+ installed = subprocess.run(
129
+ [sys.executable, "-m", "pip", "install", *flags, package],
130
+ capture_output=True,
131
+ text=True,
132
+ check=False,
133
+ timeout=300,
134
+ )
135
+ if installed.returncode != 0:
136
+ detail = (installed.stderr or installed.stdout or "").strip()[-2000:]
137
+ raise RuntimeError(
138
+ "Automatic SDK upgrade failed; no business request, retry or privilege escalation. "
139
+ f"pip output: {detail or 'none'}"
140
+ )
141
+
142
+ # A fresh process both loads the upgraded code and verifies it before dispatch.
143
+ env = os.environ.copy()
144
+ env[_UPDATE_TARGET] = latest
145
+ return subprocess.run(
146
+ [sys.executable, "-m", "magiccampus_cli", *argv],
147
+ env=env,
148
+ check=False,
149
+ ).returncode
@@ -0,0 +1,67 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from urllib.parse import unquote, urlparse
7
+
8
+
9
+ def safe_json_dumps(value: object) -> str:
10
+ return json.dumps(value, ensure_ascii=False, default=str)
11
+
12
+
13
+ def trim_string(value: object) -> str:
14
+ return str(value or "").strip()
15
+
16
+
17
+ def format_value(value: object) -> str:
18
+ if value is None:
19
+ return ""
20
+ if isinstance(value, (dict, list, tuple)):
21
+ return safe_json_dumps(value)
22
+ return str(value)
23
+
24
+
25
+ def parse_optional_bool(value: object, fallback: bool | None = None) -> bool | None:
26
+ if value is None:
27
+ return fallback
28
+ if value is True:
29
+ return True
30
+ normalized = trim_string(value).lower()
31
+ if normalized in {"1", "true", "yes", "y", "on"}:
32
+ return True
33
+ if normalized in {"0", "false", "no", "n", "off"}:
34
+ return False
35
+ raise ValueError(f"Invalid boolean value: {value}")
36
+
37
+
38
+ def is_http_url(value: str) -> bool:
39
+ lowered = trim_string(value).lower()
40
+ return lowered.startswith("http://") or lowered.startswith("https://")
41
+
42
+
43
+ def to_local_path(value: str) -> str:
44
+ raw = trim_string(value)
45
+ if raw.lower().startswith("file://"):
46
+ return unquote(urlparse(raw).path)
47
+ return raw
48
+
49
+
50
+ def infer_name_from_url(url: str, fallback: str) -> str:
51
+ try:
52
+ parsed = urlparse(url)
53
+ name = Path(parsed.path).name
54
+ return name or fallback
55
+ except Exception:
56
+ return fallback
57
+
58
+
59
+ def env_string(name: str) -> str:
60
+ return trim_string(os.getenv(name))
61
+
62
+
63
+ def mask_secret(value: str) -> str:
64
+ raw = trim_string(value)
65
+ if len(raw) <= 8:
66
+ return raw
67
+ return f"{raw[:4]}...{raw[-4:]}"
@@ -0,0 +1,43 @@
1
+ from importlib import import_module
2
+
3
+ __version__ = "0.1.0"
4
+ _EXPORTS = {
5
+ "MagicCampusCommentClient": ("magiccampus_sdk.comment_client", "MagicCampusCommentClient"),
6
+ "MagicCampusCommentClientConfig": ("magiccampus_sdk.comment_client", "MagicCampusCommentClientConfig"),
7
+ "MagicCampusAPIHTTPError": ("magiccampus_sdk.platform_http", "MagicCampusAPIHTTPError"),
8
+ "MagicCampusAPINotFoundError": ("magiccampus_sdk.platform_http", "MagicCampusAPINotFoundError"),
9
+ "MagicCampusAPIRemoteError": ("magiccampus_sdk.platform_http", "MagicCampusAPIRemoteError"),
10
+ "MagicCampusClientConfig": ("magiccampus_sdk.platform_client", "MagicCampusClientConfig"),
11
+ "MagicCampusClient": ("magiccampus_sdk.platform_client", "MagicCampusClient"),
12
+ "MagicCampusCredentials": ("magiccampus_sdk.auth", "MagicCampusCredentials"),
13
+ "fetch_magiccampus_credentials": ("magiccampus_sdk.auth", "fetch_magiccampus_credentials"),
14
+ "MagicCampusIMClient": ("magiccampus_sdk.platform_client", "MagicCampusIMClient"),
15
+ "MagicCampusHTTPSendAPIError": ("magiccampus_sdk.http.http_send", "MagicCampusHTTPSendAPIError"),
16
+ "MagicCampusHTTPSendClient": ("magiccampus_sdk.http.http_send", "MagicCampusHTTPSendClient"),
17
+ "MagicCampusHTTPSendConfig": ("magiccampus_sdk.http.http_send", "MagicCampusHTTPSendConfig"),
18
+ "MagicCampusHTTPSendHTTPError": ("magiccampus_sdk.http.http_send", "MagicCampusHTTPSendHTTPError"),
19
+ "MagicCampusPlaygroupClient": ("magiccampus_sdk.playgroup_client", "MagicCampusPlaygroupClient"),
20
+ "MagicCampusSpaceClient": ("magiccampus_sdk.space_client", "MagicCampusSpaceClient"),
21
+ "MagicCampusUserClient": ("magiccampus_sdk.user_client", "MagicCampusUserClient"),
22
+ "MagicCampusUserInfo": ("magiccampus_sdk.models", "MagicCampusUserInfo"),
23
+ "MagicCampusPageInfo": ("magiccampus_sdk.models", "MagicCampusPageInfo"),
24
+ "MagicCampusUserPage": ("magiccampus_sdk.models", "MagicCampusUserPage"),
25
+ "MagicCampusFeedClient": ("magiccampus_sdk.feed_client", "MagicCampusFeedClient"),
26
+ "AgentData": ("magiccampus_sdk.models", "AgentData"),
27
+ "BaseSpace": ("magiccampus_sdk.models", "BaseSpace"),
28
+ "Notice": ("magiccampus_sdk.models", "Notice"),
29
+ "Space": ("magiccampus_sdk.models", "Space"),
30
+ "GrowthProfile": ("magiccampus_sdk.models", "GrowthProfile"),
31
+ "GrowthProfileView": ("magiccampus_sdk.models", "GrowthProfileView"),
32
+ "parse_at_text_markup": ("magiccampus_sdk.http.text", "parse_at_text_markup"),
33
+ }
34
+ __all__ = ["__version__", *_EXPORTS]
35
+
36
+
37
+ def __getattr__(name):
38
+ if name not in _EXPORTS:
39
+ raise AttributeError(name)
40
+ module, symbol = _EXPORTS[name]
41
+ value = getattr(import_module(module), symbol)
42
+ globals()[name] = value
43
+ return value
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ PLATFORM_IDS = {
10
+ "IOS": 1,
11
+ "ANDROID": 2,
12
+ "WEB": 5,
13
+ "MAC": 6,
14
+ }
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class MagicCampusCredentials:
19
+ apiurl: str
20
+ platform: str
21
+ user_id: str
22
+ token: str
23
+ ws_addr: str
24
+ api_addr: str
25
+ expire_time: int
26
+
27
+
28
+ def normalize_apiurl(apiurl: str) -> str:
29
+ normalized = str(apiurl or "").strip().rstrip("/")
30
+ if not normalized:
31
+ raise ValueError("magiccampus apiurl is required")
32
+ return normalized
33
+
34
+
35
+ def normalize_platform(platform: str | None) -> str:
36
+ normalized = str(platform or "IOS").strip().upper() or "IOS"
37
+ if normalized not in PLATFORM_IDS:
38
+ supported = ", ".join(sorted(PLATFORM_IDS))
39
+ raise ValueError(f"unsupported magiccampus platform: {normalized}; expected one of: {supported}")
40
+ return normalized
41
+
42
+
43
+ def resolve_platform_id(platform: str | None) -> int:
44
+ return PLATFORM_IDS[normalize_platform(platform)]
45
+
46
+
47
+ def safe_int(value: Any, default: int = 0) -> int:
48
+ try:
49
+ return int(value)
50
+ except Exception:
51
+ return default
52
+
53
+
54
+ def normalize_expire_time(value: Any) -> int:
55
+ expire_time = safe_int(value)
56
+ if expire_time <= 0:
57
+ return 0
58
+ if expire_time > 10_000_000_000:
59
+ return expire_time // 1000
60
+ if expire_time < 100_000_000:
61
+ return int(time.time()) + expire_time
62
+ return expire_time
63
+
64
+
65
+ def fetch_magiccampus_credentials(
66
+ *,
67
+ apiurl: str,
68
+ apikey: str,
69
+ platform: str | None = None,
70
+ timeout_seconds: float = 15.0,
71
+ ) -> MagicCampusCredentials:
72
+ normalized_apiurl = normalize_apiurl(apiurl)
73
+ normalized_platform = normalize_platform(platform)
74
+ normalized_apikey = str(apikey or "").strip()
75
+ if not normalized_apikey:
76
+ raise ValueError("magiccampus apikey is required")
77
+
78
+ response = httpx.get(
79
+ f"{normalized_apiurl}/api/v1/accounts/imToken",
80
+ params={"platform": normalized_platform},
81
+ headers={"Authorization": f"Bearer {normalized_apikey}"},
82
+ timeout=timeout_seconds,
83
+ )
84
+ response.raise_for_status()
85
+ payload = response.json()
86
+ if not isinstance(payload, dict):
87
+ raise ValueError("magiccampus imToken response must be a JSON object")
88
+
89
+ code = safe_int(payload.get("code"), default=200)
90
+ if code != 200:
91
+ raise ValueError(f"magiccampus imToken request failed: code={code} msg={payload.get('msg')}")
92
+
93
+ data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
94
+ user_id = str(data.get("userId") or data.get("user_id") or "").strip()
95
+ token = str(data.get("imToken") or data.get("token") or "").strip()
96
+ ws_addr = str(data.get("wsApi") or data.get("ws_addr") or data.get("wsAddr") or "").strip()
97
+ api_addr = str(data.get("httpApi") or data.get("api_addr") or data.get("apiAddr") or "").strip()
98
+ expire_time = normalize_expire_time(data.get("expireTime") or data.get("expire_time"))
99
+
100
+ if not user_id or not token or not ws_addr or not api_addr or expire_time <= 0:
101
+ raise ValueError("magiccampus imToken response missing userId/imToken/expireTime/wsApi/httpApi")
102
+
103
+ return MagicCampusCredentials(
104
+ apiurl=normalized_apiurl,
105
+ platform=normalized_platform,
106
+ user_id=user_id,
107
+ token=token,
108
+ ws_addr=ws_addr,
109
+ api_addr=api_addr,
110
+ expire_time=expire_time,
111
+ )
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+ from .auth import normalize_apiurl
9
+ from .platform_http import MagicCampusAPIHTTPError, MagicCampusAPIRemoteError
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class MagicCampusCommentClientConfig:
14
+ apiurl: str
15
+ apikey: str
16
+ request_timeout_seconds: float = 15.0
17
+
18
+
19
+ def _required_text(value: str, name: str) -> str:
20
+ if not isinstance(value, str) or not value.strip():
21
+ raise ValueError(f"{name} must be a non-empty string")
22
+ return value.strip()
23
+
24
+
25
+ class MagicCampusCommentClient:
26
+ """Story comments using the API Key's user/owner identity; no IM login needed."""
27
+
28
+ def __init__(self, config: MagicCampusCommentClientConfig) -> None:
29
+ self._config = config
30
+
31
+ def create(self, feed_id: str, content: str) -> dict[str, Any]:
32
+ body = {"feedId": _required_text(feed_id, "feed_id"),
33
+ "content": _required_text(content, "content")}
34
+ return self._object(self._request("POST", "create", body=body))
35
+
36
+ def list(
37
+ self, feed_id: str, *, page: int = 1, focus_comment_id: str | None = None,
38
+ ) -> dict[str, Any]:
39
+ params: dict[str, Any] = {"feedId": _required_text(feed_id, "feed_id")}
40
+ if type(page) is not int or page < 1:
41
+ raise ValueError("page must be a positive integer")
42
+ params["page"] = page
43
+ if focus_comment_id is not None:
44
+ params["focusCommentId"] = _required_text(focus_comment_id, "focus_comment_id")
45
+ data = self._object(self._request("GET", "list", params=params))
46
+ result = data.get("result")
47
+ if (not isinstance(result, dict) or not isinstance(result.get("content"), list)
48
+ or any(not isinstance(item, dict) for item in result["content"])):
49
+ raise ValueError("comment list response must contain result.content objects")
50
+ return data
51
+
52
+ def get(self, comment_id: str) -> dict[str, Any]:
53
+ return self._object(self._request(
54
+ "GET", "detail", params={"commentId": _required_text(comment_id, "comment_id")},
55
+ ))
56
+
57
+ def like(self, comment_id: str) -> None:
58
+ self._like(comment_id, "LIKE")
59
+
60
+ def unlike(self, comment_id: str) -> None:
61
+ self._like(comment_id, "UNLIKE")
62
+
63
+ def _like(self, comment_id: str, action: str) -> None:
64
+ data = self._request("POST", "like", body={
65
+ "commentId": _required_text(comment_id, "comment_id"), "action": action,
66
+ })
67
+ if data is not None:
68
+ raise ValueError("comment like response data must be null")
69
+
70
+ def delete(self, comment_id: str) -> bool:
71
+ data = self._request("POST", "delete", body={
72
+ "commentId": _required_text(comment_id, "comment_id"),
73
+ })
74
+ if type(data) is not bool:
75
+ raise ValueError("comment delete response data must be a boolean")
76
+ return data
77
+
78
+ @staticmethod
79
+ def _object(data: Any) -> dict[str, Any]:
80
+ if not isinstance(data, dict):
81
+ raise ValueError("comment response data must be a JSON object")
82
+ return data
83
+
84
+ def _request(self, method: str, action: str, *, params=None, body=None) -> Any:
85
+ base = normalize_apiurl(self._config.apiurl)
86
+ token = _required_text(self._config.apikey, "apikey")
87
+ kwargs: dict[str, Any] = {
88
+ "headers": {"Authorization": f"Bearer {token}"},
89
+ "timeout": self._config.request_timeout_seconds,
90
+ }
91
+ if params is not None:
92
+ kwargs["params"] = params
93
+ if body is not None:
94
+ kwargs["json"] = body
95
+ response = httpx.request(method, f"{base}/api/v1/comments/{action}", **kwargs)
96
+ try:
97
+ response.raise_for_status()
98
+ except httpx.HTTPStatusError as exc:
99
+ raise MagicCampusAPIHTTPError(exc.response.status_code, exc.response.text) from exc
100
+ payload = response.json()
101
+ if not isinstance(payload, dict) or type(payload.get("code")) is not int:
102
+ raise ValueError("comment response must have an integer code")
103
+ if payload["code"] != 200:
104
+ raise MagicCampusAPIRemoteError(
105
+ payload["code"], str(payload.get("msg") or ""), str(payload.get("detail") or ""),
106
+ )
107
+ return payload.get("data")
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ from .auth import normalize_apiurl
8
+ from .platform_http import MagicCampusAPIHTTPError, MagicCampusAPIRemoteError
9
+
10
+
11
+ def fetch_user_story_page(
12
+ *,
13
+ apiurl: str,
14
+ apikey: str,
15
+ limit: int = 20,
16
+ cursor: str | None = None,
17
+ timeout_seconds: float = 15.0,
18
+ ) -> dict[str, Any]:
19
+ """Fetch one chronological page of published human-authored APP stories."""
20
+ base = normalize_apiurl(apiurl)
21
+ token = str(apikey or "").strip()
22
+ if not token:
23
+ raise ValueError("magiccampus apikey is required")
24
+ if isinstance(limit, bool) or not isinstance(limit, (int, str)):
25
+ raise ValueError("limit must be an integer between 1 and 100")
26
+ try:
27
+ page_limit = int(limit)
28
+ except ValueError as exc:
29
+ raise ValueError("limit must be an integer between 1 and 100") from exc
30
+ if not 1 <= page_limit <= 100:
31
+ raise ValueError("limit must be an integer between 1 and 100")
32
+ if cursor is not None and not isinstance(cursor, str):
33
+ raise ValueError("cursor must be a string or None")
34
+ params: dict[str, Any] = {"limit": page_limit}
35
+ if cursor is not None and cursor.strip():
36
+ params["cursor"] = cursor
37
+ response = httpx.get(
38
+ f"{base}/api/v1/feeds/list",
39
+ params=params,
40
+ headers={"Authorization": f"Bearer {token}"},
41
+ timeout=timeout_seconds,
42
+ )
43
+ try:
44
+ response.raise_for_status()
45
+ except httpx.HTTPStatusError as exc:
46
+ raise MagicCampusAPIHTTPError(exc.response.status_code, exc.response.text) from exc
47
+ payload = response.json()
48
+ if not isinstance(payload, dict) or type(payload.get("code")) is not int:
49
+ raise ValueError("magiccampus feed list response must have an integer code")
50
+ if payload["code"] != 200:
51
+ raise MagicCampusAPIRemoteError(
52
+ payload["code"], str(payload.get("msg") or ""), str(payload.get("detail") or ""),
53
+ )
54
+ data = payload.get("data")
55
+ if not isinstance(data, dict) or not isinstance(data.get("feeds"), list):
56
+ raise ValueError("magiccampus feed list data must contain a feeds array")
57
+ if any(not isinstance(feed, dict) for feed in data["feeds"]):
58
+ raise ValueError("magiccampus feed list feeds must contain JSON objects")
59
+ if data.get("nextCursor") is not None and not isinstance(data["nextCursor"], str):
60
+ raise ValueError("magiccampus feed list nextCursor must be a string or null")
61
+ return data
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from .feed_api import fetch_user_story_page
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class MagicCampusFeedClientConfig:
11
+ apiurl: str
12
+ apikey: str
13
+ platform: str = "IOS"
14
+ credential_timeout_seconds: float = 15.0
15
+ request_timeout_seconds: float = 15.0
16
+
17
+
18
+ class MagicCampusFeedClient:
19
+ def __init__(self, config: MagicCampusFeedClientConfig) -> None:
20
+ self._config = config
21
+
22
+ def list(self, *, limit: int = 20, cursor: str | None = None) -> dict[str, Any]:
23
+ """Published USER/APP stories, newest first; preserve the server's nextCursor."""
24
+ return fetch_user_story_page(
25
+ apiurl=self._config.apiurl,
26
+ apikey=self._config.apikey,
27
+ limit=limit,
28
+ cursor=cursor,
29
+ timeout_seconds=self._config.request_timeout_seconds,
30
+ )