django-dev-tickets 0.2.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 (39) hide show
  1. dev_tickets/__init__.py +3 -0
  2. dev_tickets/actor.py +67 -0
  3. dev_tickets/apps.py +23 -0
  4. dev_tickets/client.py +294 -0
  5. dev_tickets/conf.py +168 -0
  6. dev_tickets/defaults.py +24 -0
  7. dev_tickets/digest.py +125 -0
  8. dev_tickets/endpoints.py +33 -0
  9. dev_tickets/hub.py +136 -0
  10. dev_tickets/lanes.py +128 -0
  11. dev_tickets/management/__init__.py +0 -0
  12. dev_tickets/management/commands/__init__.py +0 -0
  13. dev_tickets/management/commands/devtickets_client.py +86 -0
  14. dev_tickets/management/commands/devtickets_notify.py +17 -0
  15. dev_tickets/mcp.py +410 -0
  16. dev_tickets/migrations/0001_initial.py +195 -0
  17. dev_tickets/migrations/0002_seed_labels.py +16 -0
  18. dev_tickets/migrations/0003_lanes_and_settings.py +81 -0
  19. dev_tickets/migrations/__init__.py +0 -0
  20. dev_tickets/models.py +366 -0
  21. dev_tickets/mutations.py +233 -0
  22. dev_tickets/notify.py +153 -0
  23. dev_tickets/people.py +170 -0
  24. dev_tickets/permissions.py +37 -0
  25. dev_tickets/queries.py +148 -0
  26. dev_tickets/schema.py +14 -0
  27. dev_tickets/service.py +436 -0
  28. dev_tickets/settings_views.py +207 -0
  29. dev_tickets/states.py +157 -0
  30. dev_tickets/templates/dev_tickets/email/digest.html +88 -0
  31. dev_tickets/templates/dev_tickets/email/digest.txt +20 -0
  32. dev_tickets/titles.py +43 -0
  33. dev_tickets/types.py +360 -0
  34. dev_tickets/urls.py +35 -0
  35. dev_tickets/views.py +65 -0
  36. django_dev_tickets-0.2.0.dist-info/METADATA +644 -0
  37. django_dev_tickets-0.2.0.dist-info/RECORD +39 -0
  38. django_dev_tickets-0.2.0.dist-info/WHEEL +4 -0
  39. django_dev_tickets-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3 @@
1
+ """Dev Tickets: an issue tracker that lives inside your Django app."""
2
+
3
+ __version__ = "0.2.0"
dev_tickets/actor.py ADDED
@@ -0,0 +1,67 @@
1
+ """Who is acting on this request, decided once and kept on the request.
2
+
3
+ Every resolver and file view asks `actor_for(request)` and never looks at
4
+ `request.user` itself, so the same code serves a person signed in to this install
5
+ and a person a hub client vouches for (`hub.py` sets the actor before the schema
6
+ runs). An actor without a `person` was refused, and `refusal` says why in the words
7
+ the package has always used.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from django.core.exceptions import PermissionDenied
16
+
17
+ ATTRIBUTE = "_dev_tickets_actor"
18
+
19
+ SIGNED_OUT = "Authentication required."
20
+ NO_ACCESS = "You do not have access to dev tickets."
21
+ READ_ONLY = "This hub client's key is read-only."
22
+
23
+
24
+ @dataclass
25
+ class Actor:
26
+ person: Any = None # a models.Person, or None when refused
27
+ refusal: str = ""
28
+ context_label: str = ""
29
+ # The hub client this came through; blank for this install's own users.
30
+ source: str = ""
31
+ read_only: bool = False
32
+ # The local user, when there is one (never for a remote actor).
33
+ user: Any = None
34
+
35
+
36
+ def actor_for(request) -> Actor:
37
+ cached = getattr(request, ATTRIBUTE, None)
38
+ if cached is not None:
39
+ return cached
40
+ from . import people
41
+ from .permissions import can_access, context_label
42
+
43
+ user = getattr(request, "user", None)
44
+ if user is None or not getattr(user, "is_authenticated", False):
45
+ actor = Actor(refusal=SIGNED_OUT)
46
+ elif not can_access(user):
47
+ actor = Actor(refusal=NO_ACCESS, user=user)
48
+ else:
49
+ actor = Actor(
50
+ person=people.for_user(user), context_label=context_label(request), user=user
51
+ )
52
+ setattr(request, ATTRIBUTE, actor)
53
+ return actor
54
+
55
+
56
+ def set_actor(request, actor: Actor) -> None:
57
+ setattr(request, ATTRIBUTE, actor)
58
+
59
+
60
+ def require(request, *, write: bool = False) -> Actor:
61
+ """The actor, or PermissionDenied for anyone refused (or a read-only key writing)."""
62
+ actor = actor_for(request)
63
+ if actor.person is None:
64
+ raise PermissionDenied(actor.refusal or NO_ACCESS)
65
+ if write and actor.read_only:
66
+ raise PermissionDenied(READ_ONLY)
67
+ return actor
dev_tickets/apps.py ADDED
@@ -0,0 +1,23 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DevTicketsConfig(AppConfig):
5
+ name = "dev_tickets"
6
+ label = "dev_tickets"
7
+ verbose_name = "Dev tickets"
8
+ default_auto_field = "django.db.models.BigAutoField"
9
+
10
+ def ready(self):
11
+ from django.core.signals import request_started
12
+ from django.db.models.signals import post_delete, post_save
13
+
14
+ from . import conf, states
15
+ from .models import TicketState, TrackerSettings
16
+
17
+ conf.check()
18
+ # Lanes and stored settings are cached for a request; any change clears them.
19
+ request_started.connect(states.clear_cache, dispatch_uid="dev_tickets_states")
20
+ request_started.connect(conf.clear_cache, dispatch_uid="dev_tickets_conf")
21
+ for signal in (post_save, post_delete):
22
+ signal.connect(states.clear_cache, sender=TicketState, dispatch_uid=f"dt_s_{signal}")
23
+ signal.connect(conf.clear_cache, sender=TrackerSettings, dispatch_uid=f"dt_c_{signal}")
dev_tickets/client.py ADDED
@@ -0,0 +1,294 @@
1
+ """Client mode: this install keeps no tickets and forwards its users to the hub.
2
+
3
+ The browser only ever talks to its own backend, at the same URLs as standalone, and
4
+ never sees the hub's address or key. For each request this module:
5
+
6
+ 1. Decides locally whether the user may use dev tickets at all (`CAN_ACCESS`). Someone
7
+ refused, signed out, or without an email address never reaches the hub: the
8
+ package's own schema answers them (`devSupportConfig` says `enabled: false`,
9
+ everything else is refused with the usual message).
10
+ 2. Otherwise forwards the request with the key, an actor header (email, name, avatar,
11
+ whether they are on the team) and the context label, and returns the hub's answer
12
+ as it came.
13
+
14
+ If the hub cannot be reached, answers 5xx or takes longer than `HUB_TIMEOUT`, the
15
+ user gets "The ticket hub is unreachable" (HTTP 502) and the detail goes to the log.
16
+
17
+ Everything goes through `transport`, one function over the standard library's
18
+ urllib, so tests can route it into a hub in the same process.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import logging
25
+ import secrets
26
+ import urllib.error
27
+ import urllib.request
28
+ from collections.abc import Iterator, Mapping
29
+ from dataclasses import dataclass, field
30
+ from typing import IO
31
+ from urllib.parse import quote
32
+
33
+ from django.core.exceptions import PermissionDenied
34
+ from django.http import (
35
+ HttpRequest,
36
+ HttpResponse,
37
+ JsonResponse,
38
+ StreamingHttpResponse,
39
+ )
40
+ from strawberry.django.views import GraphQLView
41
+
42
+ from . import conf, people, service
43
+ from .actor import NO_ACCESS, SIGNED_OUT, Actor, set_actor
44
+ from .hub import ACTOR_HEADER, CONTEXT_HEADER
45
+ from .permissions import can_access, context_label
46
+ from .schema import schema
47
+
48
+ log = logging.getLogger(__name__)
49
+
50
+ UNREACHABLE = "The ticket hub is unreachable. Try again in a moment."
51
+ NO_EMAIL = "Your account needs an email address to use dev tickets."
52
+ API = "/devtickets/api/v1/"
53
+ CHUNK = 64 * 1024
54
+ # Response headers worth passing from the hub to the browser for a file.
55
+ FILE_HEADERS = ("Content-Type", "Content-Disposition", "Content-Length", "Cache-Control",
56
+ "X-Content-Type-Options") # fmt: skip
57
+
58
+ _local_graphql = GraphQLView.as_view(schema=schema)
59
+
60
+
61
+ class HubUnreachable(Exception):
62
+ """The hub did not answer: refused, DNS, TLS, timeout."""
63
+
64
+
65
+ @dataclass
66
+ class HubResponse:
67
+ status: int
68
+ headers: Mapping[str, str] = field(default_factory=dict)
69
+ body: IO[bytes] | None = None
70
+
71
+ def read(self) -> bytes:
72
+ return self.body.read() if self.body is not None else b""
73
+
74
+ def chunks(self) -> Iterator[bytes]:
75
+ if self.body is None:
76
+ return
77
+ try:
78
+ while chunk := self.body.read(CHUNK):
79
+ yield chunk
80
+ finally:
81
+ self.body.close()
82
+
83
+ def close(self) -> None:
84
+ if self.body is not None:
85
+ self.body.close()
86
+
87
+
88
+ def transport(
89
+ method: str, url: str, *, headers: dict[str, str], body: bytes | None = None,
90
+ timeout: float = 10,
91
+ ) -> HubResponse: # fmt: skip
92
+ """One HTTP request to the hub. An HTTP error status is returned, not raised;
93
+ only a hub that does not answer raises `HubUnreachable`."""
94
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
95
+ try:
96
+ response = urllib.request.urlopen(request, timeout=timeout) # noqa: S310 -- configured URL
97
+ except urllib.error.HTTPError as exc:
98
+ return HubResponse(exc.code, dict(exc.headers.items()), exc)
99
+ except (urllib.error.URLError, OSError, ValueError) as exc:
100
+ raise HubUnreachable(str(getattr(exc, "reason", exc))) from exc
101
+ return HubResponse(response.status, dict(response.headers.items()), response)
102
+
103
+
104
+ # --- who ----------------------------------------------------------------------
105
+
106
+
107
+ def _refusal(user) -> str:
108
+ """Why this user is handled here and not forwarded; "" when they may go on."""
109
+ if user is None or not getattr(user, "is_authenticated", False):
110
+ return SIGNED_OUT
111
+ if not can_access(user):
112
+ return NO_ACCESS
113
+ if not people.normalise_email(getattr(user, "email", "")):
114
+ return NO_EMAIL
115
+ return ""
116
+
117
+
118
+ def _actor_header(user) -> str:
119
+ avatar_hook = conf.hook("AVATAR")
120
+ team = conf.hook("TEAM")().filter(is_active=True, pk=user.pk).exists()
121
+ return json.dumps({
122
+ "email": people.normalise_email(user.email),
123
+ "name": people.user_name(user),
124
+ "avatar": str(avatar_hook(user) or "") if avatar_hook else "",
125
+ "team": team,
126
+ }) # fmt: skip
127
+
128
+
129
+ def _headers(request: HttpRequest, key: str | None = None, **extra: str) -> dict[str, str]:
130
+ return {
131
+ "Authorization": f"Bearer {key or conf.get('HUB_API_KEY')}",
132
+ ACTOR_HEADER: _actor_header(request.user),
133
+ CONTEXT_HEADER: quote(context_label(request), safe=""),
134
+ "Accept": "application/json",
135
+ **extra,
136
+ }
137
+
138
+
139
+ def _call(request: HttpRequest, method: str, path: str, **kwargs) -> HubResponse:
140
+ url = str(conf.get("HUB_URL")).rstrip("/") + API + path
141
+ response = transport(
142
+ method, url, headers=_headers(request, **kwargs.pop("headers", {})),
143
+ timeout=float(conf.get("HUB_TIMEOUT")), **kwargs,
144
+ ) # fmt: skip
145
+ if response.status >= 500:
146
+ detail = response.read()[:500]
147
+ response.close()
148
+ raise HubUnreachable(f"HTTP {response.status} from the hub: {detail!r}")
149
+ return response
150
+
151
+
152
+ PROBE = '{"query": "{ devSupportConfig { enabled teamName prefix } }"}'
153
+
154
+
155
+ def probe(request: HttpRequest, url: str, key: str) -> dict:
156
+ """Try a hub with this URL and key, as the signed-in user, before it is saved.
157
+ `{"ok": True, "team": ..., "prefix": ...}` or `{"ok": False, "message": ...}`."""
158
+ if not people.normalise_email(getattr(request.user, "email", "")):
159
+ return {"ok": False, "message": NO_EMAIL}
160
+ try:
161
+ response = transport(
162
+ "POST", url.rstrip("/") + API + "graphql/", body=PROBE.encode(),
163
+ headers=_headers(request, key=key, **{"Content-Type": "application/json"}),
164
+ timeout=float(conf.get("HUB_TIMEOUT")),
165
+ ) # fmt: skip
166
+ except HubUnreachable as exc:
167
+ return {"ok": False, "message": f"No answer from {url}: {exc}"}
168
+ raw = response.read()[:20000]
169
+ response.close()
170
+ if response.status == 404:
171
+ return {"ok": False, "message": "That server is not a dev-tickets hub (no hub API)."}
172
+ try:
173
+ body = json.loads(raw)
174
+ except ValueError:
175
+ return {"ok": False, "message": f"The hub answered HTTP {response.status}, not JSON."}
176
+ errors = body.get("errors") if isinstance(body, dict) else None
177
+ if errors:
178
+ return {"ok": False, "message": "; ".join(str(e.get("message")) for e in errors)}
179
+ config = (body.get("data") or {}).get("devSupportConfig") or {}
180
+ return {"ok": True, "team": config.get("teamName", ""), "prefix": config.get("prefix", "")}
181
+
182
+
183
+ # --- views --------------------------------------------------------------------
184
+
185
+
186
+ def graphql(request: HttpRequest) -> HttpResponse:
187
+ """`devtickets/graphql/` in client mode."""
188
+ refusal = _refusal(request.user)
189
+ if refusal or request.method != "POST":
190
+ # Answered here, by the package's own resolvers, with the reason as refusal.
191
+ set_actor(request, Actor(refusal=refusal or NO_ACCESS))
192
+ return _local_graphql(request)
193
+ try:
194
+ response = _call(
195
+ request, "POST", "graphql/", body=request.body,
196
+ headers={"Content-Type": "application/json"},
197
+ ) # fmt: skip
198
+ except HubUnreachable as exc:
199
+ log.warning("Dev tickets: hub request failed: %s", exc)
200
+ return JsonResponse({"data": None, "errors": [{"message": UNREACHABLE}]}, status=502)
201
+ body = response.read()
202
+ response.close()
203
+ return HttpResponse(
204
+ body, status=response.status,
205
+ content_type=response.headers.get("Content-Type", "application/json"),
206
+ ) # fmt: skip
207
+
208
+
209
+ def _problem(message: str, status: int) -> JsonResponse:
210
+ return JsonResponse({"problems": [message]}, status=status)
211
+
212
+
213
+ def upload(request: HttpRequest, ref: str) -> HttpResponse:
214
+ """`devtickets-files/<ref>/` in client mode: checked here, then sent on."""
215
+ if request.method != "POST":
216
+ return HttpResponse(status=405)
217
+ refusal = _refusal(request.user)
218
+ if refusal:
219
+ return _problem(refusal, 403)
220
+ files = request.FILES.getlist("file")
221
+ if not files:
222
+ return _problem("Choose a file to upload.", 400)
223
+ try:
224
+ for f in files:
225
+ service.check_upload_size(f)
226
+ except PermissionDenied as exc:
227
+ return _problem(str(exc), 400)
228
+ body, content_type = _multipart(files)
229
+ try:
230
+ response = _call(
231
+ request, "POST", f"files/{quote(ref, safe='')}/", body=body,
232
+ headers={"Content-Type": content_type},
233
+ ) # fmt: skip
234
+ except HubUnreachable as exc:
235
+ log.warning("Dev tickets: hub upload failed: %s", exc)
236
+ return _problem(UNREACHABLE, 502)
237
+ answer = response.read()
238
+ response.close()
239
+ return HttpResponse(
240
+ answer, status=response.status,
241
+ content_type=response.headers.get("Content-Type", "application/json"),
242
+ ) # fmt: skip
243
+
244
+
245
+ def attachment_file(request: HttpRequest, attachment_id: int) -> HttpResponse:
246
+ """`devtickets-files/attachment/<id>/` in client mode: streamed from the hub."""
247
+ if request.method != "GET":
248
+ return HttpResponse(status=405)
249
+ if _refusal(request.user):
250
+ raise PermissionDenied
251
+ query = "?download=1" if request.GET.get("download") == "1" else ""
252
+ try:
253
+ response = _call(request, "GET", f"files/attachment/{int(attachment_id)}/{query}")
254
+ except HubUnreachable as exc:
255
+ log.warning("Dev tickets: hub download failed: %s", exc)
256
+ return HttpResponse(UNREACHABLE, status=502, content_type="text/plain")
257
+ if response.status != 200:
258
+ body = response.read()
259
+ response.close()
260
+ return HttpResponse(
261
+ body, status=response.status,
262
+ content_type=response.headers.get("Content-Type", "text/plain"),
263
+ ) # fmt: skip
264
+ streamed = StreamingHttpResponse(response.chunks(), status=200)
265
+ for name in FILE_HEADERS:
266
+ value = _header(response.headers, name)
267
+ if value:
268
+ streamed[name] = value
269
+ return streamed
270
+
271
+
272
+ def _header(headers: Mapping[str, str], name: str) -> str:
273
+ for key, value in headers.items():
274
+ if key.lower() == name.lower():
275
+ return value
276
+ return ""
277
+
278
+
279
+ def _multipart(files) -> tuple[bytes, str]:
280
+ """`files` as a multipart/form-data body, each under the field name `file`."""
281
+ boundary = "devtickets-" + secrets.token_hex(16)
282
+ parts: list[bytes] = []
283
+ for f in files:
284
+ name = (f.name or "file").replace('"', "").replace("\r", "").replace("\n", "")
285
+ kind = f.content_type or "application/octet-stream"
286
+ parts.append(
287
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; "
288
+ f"filename=\"{name}\"\r\nContent-Type: {kind}\r\n\r\n".encode()
289
+ )
290
+ f.seek(0)
291
+ parts.append(f.read())
292
+ parts.append(b"\r\n")
293
+ parts.append(f"--{boundary}--\r\n".encode())
294
+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"
dev_tickets/conf.py ADDED
@@ -0,0 +1,168 @@
1
+ """Settings, read from one `DEV_TICKETS` dict in the host's settings.
2
+
3
+ Every value is read when it is used, not at import, so `override_settings` and
4
+ pytest-django's `settings` fixture work without reloading anything.
5
+
6
+ `STORED` settings (the mode and how a client reaches its hub) can also be set from
7
+ the board's Settings dialog, kept in `TrackerSettings`. The host's value wins when
8
+ it sets one, and the dialog shows that field as locked (`locked`). The hooks
9
+ (`CAN_ACCESS`, `TEAM`, ...) take a callable or a dotted path to one; a dotted path
10
+ is imported on first use, so a host module that imports these models can be named.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ from django.conf import settings
20
+ from django.core.exceptions import ImproperlyConfigured
21
+ from django.utils.module_loading import import_string
22
+
23
+ DEFAULTS: dict[str, Any] = {
24
+ # standalone: tickets in this database, for this install's users.
25
+ # hub: the same, and other installs reach the board through the API (`hub.py`).
26
+ # client: no tickets here; every request is forwarded to the hub (`client.py`).
27
+ "MODE": "standalone",
28
+ # Identifier prefix: DEV-12.
29
+ "PREFIX": "DEV",
30
+ # What the board calls the team ("<team> tickets").
31
+ "TEAM_NAME": "Dev",
32
+ # Absolute URL of the board; email links are BOARD_URL + "/" + identifier.
33
+ "BOARD_URL": "",
34
+ # (user) -> bool. Who may see the board, file tickets and hold one.
35
+ "CAN_ACCESS": "dev_tickets.defaults.can_access",
36
+ # (user) -> bool. Who may change the mode and hub connection in Settings.
37
+ # None: whoever passes CAN_ACCESS.
38
+ "CAN_CONFIGURE": None,
39
+ # () -> QuerySet of users who can be assigned a ticket.
40
+ "TEAM": "dev_tickets.defaults.team",
41
+ # (request) -> str. The company / workspace a ticket was filed from.
42
+ "CONTEXT_LABEL": None,
43
+ # (description, request) -> str. None: the description's first line.
44
+ "TITLE_GENERATOR": None,
45
+ # (subject, text, html, to) -> None. Default: Django's EmailMultiAlternatives.
46
+ "SEND_MAIL": "dev_tickets.defaults.send_mail",
47
+ # Seconds a notification stays unread before it is emailed.
48
+ "EMAIL_AFTER": 120,
49
+ # Name of the STORAGES entry attachments are kept in.
50
+ "STORAGE": "default",
51
+ "MAX_ATTACHMENT_MB": 15,
52
+ # Username or email new tickets are assigned to when the reporter names nobody.
53
+ "DEFAULT_ASSIGNEE": None,
54
+ # client mode: the hub's base URL, this environment's key (`devtickets_client add`
55
+ # on the hub prints it) and its name, shown on the hub as "from <SOURCE>".
56
+ "HUB_URL": None,
57
+ "HUB_API_KEY": None,
58
+ "SOURCE": None,
59
+ # client mode: seconds to wait for the hub before giving up.
60
+ "HUB_TIMEOUT": 10,
61
+ # (user) -> str | None. A picture of the user, sent to the hub with each request.
62
+ "AVATAR": None,
63
+ }
64
+
65
+ # Settings a client cannot run without.
66
+ CLIENT_REQUIRED = ("HUB_URL", "HUB_API_KEY", "SOURCE")
67
+
68
+ MODES = ("standalone", "hub", "client")
69
+
70
+ # Settings the Settings dialog may set, and the `TrackerSettings` field each lives in.
71
+ STORED = {"MODE": "mode", "HUB_URL": "hub_url", "HUB_API_KEY": "hub_api_key", "SOURCE": "source"}
72
+
73
+ _TTL = 1.0
74
+ _stored: tuple[float, dict[str, str]] | None = None
75
+
76
+
77
+ def _host() -> dict:
78
+ return getattr(settings, "DEV_TICKETS", {})
79
+
80
+
81
+ def clear_cache(*_args, **_kwargs) -> None:
82
+ global _stored
83
+ _stored = None
84
+
85
+
86
+ def _stored_values() -> dict[str, str]:
87
+ """The Settings dialog's values, cached for a request (cleared on request start
88
+ and on save). Empty before the table exists, e.g. during the first migrate."""
89
+ global _stored
90
+ now = time.monotonic()
91
+ if _stored is not None and now - _stored[0] < _TTL:
92
+ return _stored[1]
93
+ from django.db import DatabaseError
94
+
95
+ try:
96
+ from .models import TrackerSettings
97
+
98
+ row = TrackerSettings.objects.order_by("pk").first()
99
+ except DatabaseError:
100
+ row = None
101
+ values = (
102
+ {name: (getattr(row, field) or "").strip() for name, field in STORED.items()}
103
+ if row else {}
104
+ ) # fmt: skip
105
+ _stored = (now, values)
106
+ return values
107
+
108
+
109
+ def locked(name: str) -> bool:
110
+ """True when the host's settings fix this value, so the dialog cannot change it."""
111
+ return name in _host()
112
+
113
+
114
+ def get(name: str) -> Any:
115
+ if name not in DEFAULTS:
116
+ raise KeyError(f"Unknown DEV_TICKETS setting {name!r}.")
117
+ host = _host()
118
+ if name in host:
119
+ return host[name]
120
+ if name in STORED:
121
+ value = _stored_values().get(name)
122
+ if value:
123
+ return value
124
+ return DEFAULTS[name]
125
+
126
+
127
+ def hook(name: str) -> Callable | None:
128
+ """A hook setting as a callable, or None when it is unset."""
129
+ value = get(name)
130
+ if value is None or value == "":
131
+ return None
132
+ if callable(value):
133
+ return value
134
+ try:
135
+ return import_string(value)
136
+ except ImportError as exc:
137
+ raise ImproperlyConfigured(f"DEV_TICKETS[{name!r}] = {value!r}: {exc}") from exc
138
+
139
+
140
+ def check() -> None:
141
+ """The host's own settings, at startup. Values from the Settings dialog are
142
+ checked when they are saved instead (this runs before the database is ready)."""
143
+ host = _host()
144
+ unknown = set(host) - set(DEFAULTS)
145
+ if unknown:
146
+ raise ImproperlyConfigured(f"Unknown DEV_TICKETS settings: {', '.join(sorted(unknown))}.")
147
+ if "MODE" not in host:
148
+ return
149
+ mode = host["MODE"]
150
+ if mode not in MODES:
151
+ raise ImproperlyConfigured(f"DEV_TICKETS['MODE'] must be one of {', '.join(MODES)}.")
152
+ if mode == "client":
153
+ missing = [name for name in CLIENT_REQUIRED if not str(host.get(name) or "").strip()]
154
+ if missing:
155
+ raise ImproperlyConfigured(
156
+ "DEV_TICKETS['MODE'] = 'client' needs "
157
+ + ", ".join(f"DEV_TICKETS[{name!r}]" for name in missing)
158
+ + "."
159
+ )
160
+ url = str(host.get("HUB_URL"))
161
+ if not url.startswith(("http://", "https://")):
162
+ raise ImproperlyConfigured(
163
+ f"DEV_TICKETS['HUB_URL'] = {url!r} must start with http:// or https://."
164
+ )
165
+
166
+
167
+ def mode() -> str:
168
+ return str(get("MODE"))
@@ -0,0 +1,24 @@
1
+ """The hooks' default implementations, named by dotted path in `conf.DEFAULTS`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django.conf import settings
6
+ from django.contrib.auth import get_user_model
7
+ from django.core.mail import EmailMultiAlternatives
8
+
9
+
10
+ def can_access(user) -> bool:
11
+ """Active superusers only: tickets carry screenshots of whatever a user had open."""
12
+ return bool(getattr(user, "is_authenticated", False) and user.is_active and user.is_superuser)
13
+
14
+
15
+ def team():
16
+ return get_user_model().objects.filter(is_active=True, is_superuser=True)
17
+
18
+
19
+ def send_mail(subject: str, text: str, html: str, to: list[str]) -> None:
20
+ """One multipart message: the text half is what spam filters and plain-text
21
+ clients read, so an HTML-only digest is never sent."""
22
+ message = EmailMultiAlternatives(subject, text, settings.DEFAULT_FROM_EMAIL, to)
23
+ message.attach_alternative(html, "text/html")
24
+ message.send()