Compare commits

...

128 Commits

Author SHA1 Message Date
Jakub Zych
885cd2bcd7 build: rebuild the student app (open answer autosave, material IDs) 2026-11-10 01:10:45 +01:00
Jakub Zych
5c0e5f1fa8 build: rebuild the student app (open questions) 2026-11-09 20:37:52 +01:00
Jakub Zych
d902815f29 build: rebuild the student app (resizable chat) 2026-11-09 15:54:28 +01:00
Jakub Zych
f0d1c18df2 build: rebuild the student app (safe test finish) 2026-11-09 15:32:37 +01:00
Jakub Zych
62ee3b7b1b build: rebuild the student app (quiz choice questions and tests) 2026-11-09 14:48:48 +01:00
Jakub Zych
9a5a28ab2f fix: state material privacy on the pin tools
bm_pin_material and bm_unpin_material bind /materials paths, so their
descriptions carry MCPMaterialPrivacy like the other material tools.
2026-11-09 14:48:14 +01:00
Jakub Zych
a4b564b2f8 build: rebuild the student app (pins, save stays, page titles) 2026-11-09 13:25:33 +01:00
Jakub Zych
bff92cca78 test: cover material pins against postgres 2026-11-09 13:15:44 +01:00
Jakub Zych
341f6cd95a feat: add the material pin MCP tools
bm_pin_material and bm_unpin_material on the token twins (scope write), with the pin routes documented in the README.
2026-11-09 13:14:37 +01:00
Jakub Zych
9436fb62d6 feat: personal pins on materials
A per-user jz_bm_material_pins table and PUT/DELETE /materials/{id}/pin
on the student API and its token twins: 204 for a material the caller
may see, idempotent, 404 otherwise. List rows, course rows and the
detail carry pinned. The plain list lists the caller's pins first
(newest pin first); with q the relevance order stays. A pin writes only
the pins table and never changes the material's revision.
2026-11-09 13:13:54 +01:00
Jakub Zych
b8b46be398 build: rebuild the student app (tag type-ahead in the editor) 2026-11-09 12:40:54 +01:00
Jakub Zych
7c49f9283c build: rebuild the student app (note editor, tables and images, conflicts) 2026-11-09 02:04:29 +01:00
Jakub Zych
8bef2d7acf feat: material managers get a realtime token
- jz.bm.realtime-access admits holders of jz.bm.access_materials
  (Assumption A5), so every editor can follow materials:{id}
- README documents the materials channel, event and authorizer
2026-11-09 01:14:56 +01:00
Jakub Zych
2a47186a7a feat: announce material revisions on materials:{id}
- every revision bump (API writes and /bmadmin saves) enqueues
  updated.jz.bm.material with {material_id, revision} in a savepoint
- the materials namespace authorizer allows a subscribe only to a
  visible material the user may manage
- api.ManagesMaterials and api.CanWatchMaterial
2026-11-09 01:12:49 +01:00
Jakub Zych
40e4a2438b feat: tags, unpublish and image upload for the author
- GET /_bm/api/v1/tags: the jz_bm_tags dictionary, to material managers
- POST /materials/{id}/unpublish: back to drafts, no revision bump, the
  search document resynced
- POST /materials/{id}/images: one JPEG/PNG/GIF/WebP per request through
  storeMaterialUpload, refusals with reason type, size or count
- storeMaterialUpload/fileRefusalFor: attach.ErrNotImage is a type
  refusal, not a 500; storeMaterialFile keeps its texts
- the author's routes get their own per-user buckets (the inline
  throttle form shares one counter per user)
- README: the author routes and revision on the student detail
2026-11-09 01:05:54 +01:00
Jakub Zych
7bf18de987 feat: the author edits a material in the app
- PUT /_bm/api/v1/materials/{id} (jwt.auth only, no token twin): every
  key of the edit body required, revision checked on the row locked FOR
  UPDATE, 409 with the student detail of the server version
- editableMaterialForCaller: 404 for what the caller cannot see, 403 for
  what they see but may not manage
- tags from the dictionary only (at most 4), http(s) urls, the body
  normalised as bm-notatka push does; course, author and publication kept
- loadMaterialDetail shared by GET /materials/{id} and the edit answers
2026-11-09 01:01:25 +01:00
Jakub Zych
263c9c3926 feat: revision-check the upsert, MCP and admin writes
- POST /materials locks the matched row and answers 409 to a stale
  revision when it updates; a create ignores revision
- bm_manage_save_material and bm_manage_update_material take revision
- /bmadmin saves bump the revision on content changes (not checked)
- document revisions and the 409 in the README
2026-11-08 23:36:17 +01:00
Jakub Zych
237069c827 feat: revision-check material writes
- add jz_bm_materials.revision (default 1), read-only for GORM
- bump it only on content changes (models.ReviseMaterial)
- PUT /materials/{id} locks the row and answers 409 to a stale revision
- management answers carry revision and updated_at, the student detail
  carries revision
2026-11-08 23:33:34 +01:00
Jakub Zych
94ca257c6f build: rebuild the student app (materials search, zjazd filter, share input, print) 2026-11-08 20:34:17 +01:00
Jakub Zych
54300de94c docs: tags hold topics, the zjazd is meeting_id
The backend materials list shows the zjazd (meeting, by number). The
MCP save and update material tools, the README material example and the
management token test stop modelling a zjazd as a tag, and the README
describes the one-way zjazd tag migration.
2026-11-08 20:30:29 +01:00
Jakub Zych
7cea8ab318 feat: move zjazd tags to the material's meeting
The one-way migration 20261108140000_move_zjazd_tags_to_meetings gives
every material tagged zjazd-N without a meeting meeting N (the lowest
when it has several), never overwrites a meeting_id, logs tags naming a
missing meeting or disagreeing with meeting_id at Warn, and deletes the
exact zjazd-N tags; their links go through ON DELETE CASCADE. Rollback
is a no-op: the backup is the pg_dump taken before migrate.
2026-11-08 20:29:31 +01:00
Jakub Zych
f841e8ed71 feat: extract file text on every attach path and backfill on reindex
- inline and signed uploads queue the text job in their transaction
- the admin form queues it in the save transaction
- detach resyncs the material (its text row goes by cascade)
- bm:materials-reindex backfills missing PDF texts before each sync
2026-11-08 20:16:14 +01:00
Jakub Zych
412821ec56 feat: index the text of attached PDFs
- jz_bm_material_file_texts caches the pdftotext output per file
- the River job jz.bm.extract_material_text extracts and resyncs
- the management multipart attach queues it inside its transaction
- file_texts in the document and a file snippet with its name
2026-11-08 20:11:19 +01:00
Jakub Zych
dd13795e6f feat: search the management list and the MCP material tools
- GET /api/v1/bm/materials takes q: candidates over every material, in
  rank order, with the snippet of the student list; 503 when the engine
  cannot answer
- bm_materials and bm_manage_list_materials take q; under MCP the snippet
  is plain text with ellipses where text was cut
- MCPMaterialPrivacy no longer claims no file text is ever returned
- README documents q, the snippet, the 503, the Search section and
  bm:materials-reindex
2026-11-08 19:53:26 +01:00
Jakub Zych
ffd19342b2 feat: keep the materials index in sync and add bm:materials-reindex
- the materials admin syncs after create and update and removes after
  delete, once the save transaction commits (UseMaterialIndex, set at Boot)
- POST and PUT /api/v1/bm/materials sync after the transaction, DELETE
  removes the document (its statement has no primary key, so no callback)
- bm:materials-reindex [--fresh] [--if-configured] ensures the index and
  syncs every material; it refuses without an engine and runs nightly
  at 04:15 with --if-configured
- TestMaterialSearchAgainstDatabase (Postgres) is written for the final
  verification phase
2026-11-08 19:50:50 +01:00
Jakub Zych
4ffce6e6ac feat: search materials through beachcomber
- Material is a beachcomber Searchable (index jz_bm_materials) in the
  hand-written models/material_search.go; jz.bm requires summercms v0.6.4
- classes.MaterialIndexer asks Typesense for up to 250 candidates with
  body highlights; the app-wide Gate is on only for jz.bm-marked contexts
- GET /_bm/api/v1/materials takes q: candidates are re-gated, counted and
  paged in SQL in rank order, each row with at most one plain snippet
- search failure answers 503 Search is unavailable.; without q the list
  is unchanged
2026-11-08 19:45:46 +01:00
Jakub Zych
f7c400756f build: rebuild the student app (private materials) 2026-11-08 11:58:11 +01:00
Jakub Zych
3346cb6ff6 feat: manage material visibility and shares
The management save/update body takes is_private, author_user_id and
share_user_ids (absent keeps each; a new material gets the caller as
author), and the managed material shows them. New routes PATCH
/materials/{id}/visibility, PUT /materials/{id}/shares and GET /users,
with the MCP tools bm_manage_set_material_visibility,
bm_manage_set_material_shares and bm_manage_list_users. The /bmadmin
form gets the private switch, the author picker and shared_with.
2026-11-08 11:56:14 +01:00
Jakub Zych
418f8240a4 feat: private materials with per-user shares
A material may be private: only its author and the users it is shared
with see it. Every student read (list, detail, course detail and
counters, the checklist linked material, the token twins) goes through
one visibility fragment. Existing materials stay public with no author.

GET/PUT /_bm/api/v1/materials/{id}/access let the author, a material
manager, toggle the flag and pick the users; the first change of an
author-less material makes the caller its author.
2026-11-08 11:52:47 +01:00
Jakub Zych
5ed02ed9f7 build: rebuild the student app (theme switch, print styles) 2026-11-07 20:48:40 +01:00
Jakub Zych
dbd64aca33 build: rebuild the student app (delete a deck, Pilot first) 2026-11-07 19:18:22 +01:00
Jakub Zych
cdc116c145 build: rebuild the student app (mobile tab bar order) 2026-11-07 15:57:44 +01:00
Jakub Zych
89772fa020 build: rebuild the student app (cast status to the casting phone only) 2026-11-07 14:37:26 +01:00
Jakub Zych
ef5155b0ab build: rebuild the student app (cast player mounted before start) 2026-11-07 13:39:01 +01:00
Jakub Zych
2691dca004 build: rebuild the student app (cast keep-awake as in HA) 2026-11-07 13:20:59 +01:00
Jakub Zych
aed08bbe09 build: rebuild the student app (cast keep-awake) 2026-11-07 12:43:13 +01:00
Jakub Zych
7c0f8de31b build: rebuild the student app (cast cover stays down) 2026-11-07 12:34:42 +01:00
Jakub Zych
018cd5537e build: rebuild the student app (cast receiver diagnostics) 2026-11-07 11:57:00 +01:00
Jakub Zych
d6dbcb48bf build: rebuild the student app (cast receiver and cast mode) 2026-11-07 08:35:13 +01:00
Jakub Zych
de1e4624bc build: deck export to PPTX 2026-11-06 15:05:55 +01:00
Jakub Zych
a27a16243d build: robots meta and robots.txt (noindex, Disallow) 2026-11-05 01:59:53 +01:00
Jakub Zych
0dd01855fa build: deck print to PDF, section-slide speaker panels fix 2026-11-03 21:07:15 +01:00
Jakub Zych
a075963c4c Checklisty: procent postępu liczony wg szacowanego czasu 2026-10-30 18:07:36 +01:00
Jakub Zych
9677e58288 fix: answer an empty checklist with an empty items list 2026-10-30 13:36:09 +01:00
Jakub Zych
d894515da1 chore: rebuild the frontend with checklists 2026-10-30 12:41:04 +01:00
Jakub Zych
d7cd5baedf feat: private checklists for zjazd preparation
Per-user checklists with items that may link a course, reading, deadline,
material or own presentation deck. An item with a reading shares the
reading's read mark. Student API routes with token twins, MCP tools,
migrations, tests and README.
2026-10-30 12:41:04 +01:00
Jakub Zych
643f8cbf7c chore: rebuild the frontend with the sztab deck theme 2026-10-30 00:04:25 +01:00
924e6aa0dc feat: signed one-time uploads for material files
- classes/uploads.go: tickets signed with HMAC-SHA256 under the
  jz.bm.upload.v1: label (app.key), 10-minute expiry, the nonce pulled
  from the cache once (duplicated from golem15.presentations on purpose)
- POST /api/v1/bm/materials/{id}/files/upload-url issues the URL with a
  curl example; POST /_bm/api/v1/uploads/{ticket} takes one file part,
  no bearer, throttled per IP and per ticket, user and permission
  re-checked, stored through storeMaterialFile
- bm_manage_create_material_upload; README documents the file routes
2026-10-28 15:10:32 +01:00
ce6ac0a78e test: expect signed one-time material uploads
- TestUploadTicket: HMAC under the jz.bm.upload.v1: label, expiry,
  malformed and foreign tickets, single use through the cache
- TestSignedMaterialUploadRefusesBadTickets, TestCreateMaterialUploadNeedsCaller
- TestRoutes, TestBMMCP and TestManageBucketKey expect the upload-url
  route, the uploads route with its two buckets and the upload tool
- compile-only stubs
2026-10-28 15:07:30 +01:00
93066c63ea feat: attach material files over MCP as base64
- storeMaterialFile: the one attach.Store call of the management API,
  shared by the multipart route and the new inline route
- POST /api/v1/bm/materials/{id}/files/inline: JSON {name, mime?,
  content_base64}, at most 3000000 bytes decoded, body.limit 4300000
- bm_manage_attach_material_file and bm_manage_detach_material_file,
  both warning that material files are public to anyone with the link
2026-10-28 15:03:43 +01:00
a0aaeba0b7 feat: add the BM management MCP tools
- 28 typed tools over /api/v1/bm: list, show, create and update for
  courses and meetings, plus delete for class sessions, readings,
  deadlines and materials (save upserts on title and course)
- inputs mirror Fillable and Rules; enums, lengths and date formats in
  the field descriptions; no seed, me or dry_run tool
- materials accept meeting_id (absent keeps, null clears, must exist)
  and the managed material JSON shows it
- README: MCP tools section
2026-10-28 14:41:30 +01:00
b08d40cba2 test: expect the BM management MCP tools
- 28 typed management tools pinned in TestBMMCP
- body keys are Fillable columns, create inputs require the required
  columns, material save/update require body, source and url
- no seed or me tool, deletes only where the route deletes
- every description names its scope and permission
2026-10-28 14:39:07 +01:00
df42e30034 feat: MCP view of BM answers (absolute links, no material body by default)
- jz.bm.mcp-links on the token twins and the management API: under MCP,
  url and *_url strings starting with a single / get the app base
- material answers under MCP leave the body out unless include_body,
  marking it with body_omitted; write answers never echo it
- jz.bm.manage keys a dispatched call by user
- bm_materials and bm_material student tools
Plain HTTP answers are unchanged.
2026-10-28 14:37:10 +01:00
464c74b80f test: expect the MCP view of BM answers
- viaMCP, includeBody and the material views (no body unless asked)
- jz.bm.mcp-links: absolute url / *_url under MCP only
- jz.bm.manage keyed per user for dispatched calls
- bm_material and bm_materials in the pinned tool list
Compile-only stubs; the tests fail on their assertions.
2026-10-28 14:34:58 +01:00
e106b36a9a feat: add the BM student MCP tools
- token twins of the student API under /_bm/api/v1/token (user.api_token,
  per-user jz.bm.token bucket, a scope on each), from one mountStudent
- pact.HasMCP with the eleven student tools over the twins
- TestBMMCP and TestTokenMirrorRoutes
2026-10-28 14:32:03 +01:00
65a9a683af build: rebuild the student app (connect page) 2026-10-28 14:09:42 +01:00
72043ac85e feat: reserve the MCP paths
/mcp (the MCP endpoint) and /.well-known (the OAuth metadata documents)
join reservedPrefixes, so they answer a plain 404 here instead of the
student app; /connect stays a client route.
2026-10-28 14:09:22 +01:00
0ac83de8b2 test: expect the MCP paths reserved 2026-10-28 14:08:16 +01:00
e22b36e03f chore: require golem15.chat v0.1.3 2026-10-27 11:40:14 +01:00
Jakub Zych
67bc3eb944 build: rebuild the student app (pulpit reading links) 2026-10-27 01:46:33 +01:00
Jakub Zych
ff2f97eb2b feat: materials by zjazd in the student API and admin
The material admin form gets the "Na zjazd" picker, every student
material JSON carries meeting_id, and GET /materials accepts meeting=
inside the published-only scope, so the Pulpit hero can list the
zjazd's materials next to its readings.
2026-10-27 01:44:38 +01:00
Jakub Zych
3241cc9894 feat: zjazd (meeting) on readings and materials
The Pulpit hero lists what to read for the current or next zjazd, so
readings and materials get a nullable meeting_id (FK to jz_bm_meetings,
ON DELETE SET NULL, indexed). The reading admin form gets a "Na zjazd"
picker, the student reading JSON carries meeting_id, and the management
/readings records filter and validate it.
2026-10-27 01:41:48 +01:00
8843e73f98 chore: require golem15.chat v0.1.2 2026-10-26 20:31:54 +01:00
3a7bc46f08 build: rebuild the student app (full-width pages) 2026-10-26 20:08:59 +01:00
35ef575b08 build: rebuild the student app (chat review fixes)
Per-message attachment total, deleted-while-offline messages, nested
code spans in links and /\host site paths.
2026-10-26 19:40:22 +01:00
be3769d75f chore: require golem15.chat v0.1.1 2026-10-26 19:39:54 +01:00
0ff943b6af fix: keep DM participant rows when a user leaves the chat group
The participant sync and the non-member prune now remove only ogólny's
rows. A user taken out of studenci, even briefly, keeps their DMs (the
live membership check denies access while they are out) and gets them
back when re-added, instead of losing them for good.
2026-10-26 19:34:53 +01:00
8b81295458 fix: revoke chat access as soon as a user leaves the chat group
The BM chat context implements golem15.chat's LiveMembership, so every
participant check also requires chat-group membership: a removed user
loses # ogólny, their DMs, uploads, subscriptions and chat:message
delivery at once instead of after the next participant sync.
2026-10-26 19:33:52 +01:00
a840d0ad02 fix: enforce the chat's per-message upload total
jz.bm.chat.max_upload_bytes is now handed to golem15.chat as the total
size of one message's attachments, so the server enforces the limit the
bootstrap advertises.
2026-10-26 19:32:07 +01:00
cf32fa18b9 build: rebuild the student app (chat) 2026-10-26 17:17:54 +01:00
2681d304e2 feat: delete-only chat moderation and embed search and resolve
- ChatContext implements golem15.chat's MessageModerator: moderator
  group members who are chat members delete in group conversations
  only, never in DMs
- GET /chat/embeds?type=deadline|class|reading&q= (members only,
  at most 20 rows, escaped ILIKE, q at most 100 characters)
- POST /chat/embeds/resolve {refs} (members only, at most 50 distinct
  refs, 8 KiB body): current data or null per ref
2026-10-26 16:07:26 +01:00
ac4c2e6f73 test: cover chat moderation and the embed endpoints
- CanModerateMessage: group conversations only, chat members only
- parseEmbedRefs, embedKey, escapeLike
- /chat/embeds and /chat/embeds/resolve: 401, 422 before the
  database, 503 without one
2026-10-26 16:05:33 +01:00
eea171cee6 feat: open realtime tokens to chat members
The connection-token route is guarded by jz.bm.realtime-access instead
of presentations.realtime-owner: chat-group members get a token, and
when golem15.presentations is active so does everyone its owner guard
lets through (looked up by name among the activated plugins, no import).
Everyone else gets 401, 403 or 503 in the guard's error shape. The
realtime routes mount when golem15.chat or golem15.presentations is
active. /_chat, /_chatchannels and /_chatbots are reserved prefixes of
the student app.
2026-10-26 15:49:29 +01:00
cb7ba7ec8a test: cover the realtime access guard and chat prefixes
jz.bm.realtime-access admits chat-group members and, through
golem15.presentations' owner guard, presentation owners; everyone else
gets 401, 403 or 503 with Cache-Control no-cache, private. /_chat,
/_chatchannels and /_chatbots are reserved for the APIs.
2026-10-26 15:48:07 +01:00
0642fb1d08 feat: chat bootstrap, members and group sync
GET /_bm/api/v1/chat gives a chat-group member ogólny (the bm/1 group
conversation, adopted once as the system default channel under an
advisory lock), its unread and mention counts, the member's DMs newest
message first, the moderator flag and the composer limits. Every member
bootstrap syncs participants with the group: missing members join
ogólny, users no longer in the group lose their rows in every bm/1
conversation. A non-member gets only member:false and is pruned.

GET /_bm/api/v1/chat/members lists members (id, name, surname, handle,
is_bot from golem15.chatbots when active) and assigns missing handles;
non-members get 404.

The chatchannels access policy (ChatAccess) is installed from a
database hook: bm/1 for members only, nobody manages channels.
bm:chat-sync creates the groups when missing, syncs and assigns
handles. Migration 20261026130000_seed_jz_bm_chat_groups creates
studenci and moderatorzy without members; its rollback keeps them.
2026-10-26 15:46:13 +01:00
07d67be1e7 test: cover the chat access policy and bootstrap guards
ChatAccess admits only chat-group members to context bm/1 and manages
nothing; the chat context oversees nothing and its loader knows only
id 1; /chat and /chat/members need a caller and a database. The
migration count rises to 15 for the chat group seed.
2026-10-26 15:42:53 +01:00
64601f6817 feat: host the BM chat context
When golem15.chat is active, Boot registers the context alias bm (id 1)
on its registry. Membership is the user group jz.bm.chat.group (default
studenci); CanOverseeChats is always false, so nobody reads other
people's DMs or edits their messages; the broadcast channel is
chat:context:1, never empty.

GET /_bm/api/v1/chat answers the caller's membership behind jwt.auth and
the per-user bucket jz.bm.chat (240 a minute). The chat config block
(group, moderator_group, max_upload_bytes, max_embeds) is added. jz.bm
still Requires only golem15.user; all chat wiring is gated by HasPlugin.
2026-10-26 15:40:44 +01:00
67806f49a7 build: frontend with the owned-only readings filter 2026-10-26 11:19:22 +01:00
b4abf2630a build: frontend with the owned checkbox on readings 2026-10-26 11:12:08 +01:00
cf84f1d0e8 feat: per-student owned flag on readings
- new table jz_bm_reading_ownership and its migration
  20261026120000_create_jz_bm_reading_ownership
- PUT and DELETE /_bm/api/v1/readings/{id}/owned, idempotent
- owned_at on every reading in /readings and /courses/{id}
- read semantics, progress routes and counts unchanged
2026-10-26 11:11:22 +01:00
Jakub Zych
85cae45cb9 build: frontend with Microsoft 365 sign-in
The student app's login page offers Microsoft 365 when the provider is
configured, /auth/oauth/callback redeems the one-time code, a consent
screen finishes a first sign-in, the profile attaches Microsoft through
a link ticket, and the service worker leaves /oauth alone. The build
also carries the summer presentation theme already committed in the
frontend sources.
2026-10-21 00:23:38 +02:00
Jakub Zych
438c0b9761 fix: reserve /oauth for social sign-in
The SPA fallback no longer answers /oauth and the paths below it with
index.html, so golem15.sociallogin's start and provider callback routes
reach the backend; /oauthy is still a client route.
2026-10-21 00:15:31 +02:00
Jakub Zych
2536bcb959 Management API: record routes for courses, meetings, class sessions, readings and deadlines (Fillable + Rules + TemporalErrors, PATCH, filters) 2026-10-17 18:05:39 +02:00
Jakub Zych
996b4d1542 Management API: POST/DELETE /materials/{id}/files (attach.Store, 50 MB, 20 files), DELETE /materials/{id} removes files; download keeps the file name 2026-10-17 17:53:22 +02:00
Jakub Zych
584d15257c Sylabusy: PDF-y w public/sylabusy, typ application/pdf w serwerze statycznym 2026-10-17 12:06:24 +02:00
Jakub Zych
76f559b6d9 build: rebuild the student app (multi-line course descriptions) 2026-10-17 12:01:15 +02:00
Jakub Zych
ebd9117f8c feat: lecturer on class sessions and in the session course ref
The schedule showed a lecturer only where the session notes named one
(Globalizacja), so the student plan had nobody under the other courses.
The session JSON now carries the course lecturer in its course ref and an
optional per-session lecturer (new nullable column, admin field, seed key)
for courses shared between two people. The student app shows the
session's own lecturer or, failing that, the course's.
2026-10-17 11:20:11 +02:00
Jakub Zych
d2096e2128 feat(manage): GET and PUT /api/v1/bm/materials/{id}
The management API could only upsert a material on its title and course,
so a renamed note became a second material. PUT /materials/{id} applies the
same body to one material (422 when the new title and course belong to
another one), GET /materials/{id} shows a draft or published material with
its public files, and the upsert, update and validation share one path.
The README documents the management API.
2026-10-16 20:40:47 +02:00
Jakub Zych
2a8cdac282 public: slide counter in the public deck toolbar 2026-10-16 00:44:06 +02:00
Jakub Zych
b32668029c build: rebuild the student app (deadline card padding) 2026-10-15 23:23:16 +02:00
Jakub Zych
67e04b3101 build: rebuild the student app (deck themes, scheme switch) 2026-10-13 10:18:10 +02:00
Jakub Zych
b86cbbcd2d build: rebuild the student app (pwa) 2026-10-09 02:47:29 +02:00
Jakub Zych
a406a514d3 build: rebuild the student app (title-slide notes, pilot key order) 2026-10-09 02:31:53 +02:00
Jakub Zych
9aa620f975 build: rebuild the student app (phone remote review fixes) 2026-10-08 18:53:25 +02:00
Jakub Zych
5563e080cf fix: stop throttling the realtime subscribe proxy
Centrifugo calls the proxy from 127.0.0.1 for every client, so the
per-IP fallback put every subscribe into one bucket that any token
holder could exhaust. Throttle only the token route, per user.
2026-10-08 18:47:20 +02:00
Jakub Zych
2365bf6df9 build: rebuild the student app (phone remote layout) 2026-10-08 18:26:12 +02:00
Jakub Zych
e0a60e0f35 build: rebuild the student app (phone remote) 2026-10-08 18:14:15 +02:00
Jakub Zych
a740373b0e feat: wire the lighthouse realtime service
- Boot builds the realtime service and installs the user lookup
- the Centrifugo driver ships with the app; config keeps the null driver
- token and subscribe-proxy routes mount only with golem15.presentations,
  the token route behind presentations.realtime-owner
- jz.bm.realtime per-user throttle bucket and websockets:health
2026-10-08 17:53:54 +02:00
Jakub Zych
4b36eb940d build: rebuild the student app (speaker clock fix) 2026-10-08 14:01:00 +02:00
Jakub Zych
977b380f70 fix: stop prev-slide focus outline from slicing the deck 2026-10-06 23:45:21 +02:00
Jakub Zych
904c7b07d5 fix: pin dark lecture tokens in the deck viewer 2026-10-06 23:37:15 +02:00
Jakub Zych
8aefdab027 fix: follow system dark scheme in the deck viewer 2026-10-06 23:29:46 +02:00
Jakub Zych
30c424c814 build: rebuild presentation viewer 2026-10-06 22:42:04 +02:00
Jakub Zych
3f4829a6f2 feat(02-03): bundle the speaker clock and images
- Private toolbar and clock stay in the speaker chunk
- Speaker image fetches are not part of the public view
2026-10-06 19:36:03 +02:00
Jakub Zych
febf74c6c9 feat(02-03): bundle the owner list and speaker route
- The shell includes Moje prezentacje and the bare speaker tab
- Speaker copy stays in its own chunk, off the public deck
2026-10-06 19:20:10 +02:00
Jakub Zych
2eb9dfccd2 feat(02-02): bundle the public toolbar and reading layout
- rebuild the visitor assets with local fonts
- drop the previous hashed bundles replaced by this build
2026-10-06 18:46:46 +02:00
Jakub Zych
913fddb36b feat(02-02): bundle the public deck without external fonts
- Rebuild the embedded student app with self-hosted font files
- Drop the previous hashed assets replaced by this build
2026-10-06 18:35:49 +02:00
Jakub Zych
30df20c48d feat(02-01): gate the public presentation path
- 404 /_presentations before the SPA shell
- serve /prezentacje/{slugHash} only when presentations is active
- rebuild the embedded student app
2026-10-06 18:14:24 +02:00
Jakub Zych
9986df32a4 test(02-01): add failing test for the presentations prefix
- /_presentations must be a plain 404, not the SPA shell
- A router without the presentations plugin has no public document route
2026-10-06 18:05:09 +02:00
Jakub Zych
840935d22d refactor: drop the quiz import and the golem15.quizzes dependency
golem15.quizzes now serves its own import at /api/v1/quizzes/import behind
the same shared API token.
2026-10-04 23:15:01 +02:00
Jakub Zych
97000dcd1e feat: add the management API behind the shared golem15.user API token
Serve /api/v1/bm (seed, quiz import, materials, courses, me) behind
user.api_token, user.scope and user.permission. jz.bm now requires
golem15.quizzes for the quiz import.
2026-10-04 23:11:21 +02:00
Jakub Zych
71b848a376 Adopt SummerCMS v0.1.1 admin features
Datepickers on native time.Time / lagoon.Date fields, file uploads on
materials, readings and class sessions managed from the course form
(course_id made nullable).
2026-10-03 06:03:34 +02:00
Jakub Zych
ac2e2ddd7b build: add the calendar feed section to the profile 2026-10-02 17:42:16 +02:00
Jakub Zych
57e4ff7cea docs: document the calendar feed routes and jz.bm.public_url 2026-10-02 17:38:48 +02:00
Jakub Zych
b39f627fe3 test: cover the ICS writer and the calendar feed routes 2026-10-02 17:38:48 +02:00
Jakub Zych
90247a460d feat: serve a subscribable ICS calendar feed 2026-10-02 17:38:48 +02:00
Jakub Zych
bccb747171 feat: add the calendar feed model and migration 2026-10-02 17:38:48 +02:00
Jakub Zych
28f68d002f feat: add --prune and a rolled-back --dry-run to bm:seed 2026-10-02 17:28:07 +02:00
Jakub Zych
e8411adac3 build: redirect the old /quiz address to the review quiz 2026-10-02 15:30:00 +02:00
Jakub Zych
7110b1ab12 build: reveal quiz answers locally 2026-10-02 14:45:16 +02:00
Jakub Zych
860120d9cf build: add the student app build output 2026-10-02 14:43:02 +02:00
Jakub Zych
21107e9804 feat: serve the student app from the plugin 2026-10-02 14:43:02 +02:00
Jakub Zych
5106239c97 docs: add the plugin README
Overview, features, the API reference with every route and response
shape, admin screens, configuration, the bm:seed file format,
dependencies and testing.
2026-10-02 14:27:01 +02:00
Jakub Zych
7889621b69 test: add Postgres integration tests
Testcontainers Postgres, a fresh database per test, skipped under
-short: migrations up and down, schema constraints, bm:seed idempotency
and rollback, every API route through the real jwt.auth guard, and admin
saves through the admin API.
2026-10-02 14:27:01 +02:00
Jakub Zych
ce901d5f26 feat: add the bm:seed command
Validates a whole JSON file (course keys, meeting numbers, values, dates)
and upserts meetings, courses, class sessions, deadlines and readings in
one transaction, matched on their natural identity. Prints a created,
updated and unchanged summary; --dry-run only validates. Ships a small
example fixture with made-up data.
2026-10-02 14:26:43 +02:00
Jakub Zych
98cabfd51d feat: add the student API under /_bm/api/v1
Dashboard, courses with counters, schedule, meetings, deadlines,
readings with per-user progress (mark and unmark) and paginated
published materials with tags and files, behind golem15.user's
jwt.auth. Responses are built field by field with Warsaw RFC 3339
timestamps; bad query parameters answer 422 in Laravel's shape.
2026-10-02 14:26:34 +02:00
Jakub Zych
577fa14d3d feat: add admin screens, permissions and navigation
Seven admin controllers in a "Studia BM" navigation group, guarded by
jz.bm.access_courses, jz.bm.access_schedule and jz.bm.access_materials,
with Polish and English labels. Date and time fields are checked by the
models before a save and answered as 422 on the field.
2026-10-02 14:26:26 +02:00
Jakub Zych
1046237771 feat: add the study data models and schema migrations
Courses, meetings, class sessions, deadlines, readings with per-user
progress, materials with tags and file attachments. Timestamps are
stored in UTC and held as Europe/Warsaw text so the admin text inputs
can write them.
2026-10-02 14:26:08 +02:00
410 changed files with 25031 additions and 20 deletions

527
README.md Normal file
View File

@@ -0,0 +1,527 @@
# jz.bm
The study dashboard backend of the part-time master's programme "Bezpieczeństwo międzynarodowe" (UWr): courses, meetings, timetable, deadlines, reading lists with per-student progress, and study materials.
```go
import _ "git.golem15.com/jakub/sm-bm-plugin"
```
## Overview
`jz.bm` is a SummerCMS plugin. It keeps the programme's data in `jz_bm_*` tables, serves it to signed-in students as a read-only JSON API under `/_bm/api/v1`, and gives administrators admin screens to edit it. Students write two things only: which readings they have read, and the settings of their calendar feed, a private ICS URL they subscribe to in Google Calendar or on a phone.
Students are the users of `golem15.user`: the API sits behind its `jwt.auth` guard, and reading progress points at its `users` table. Course data is loaded from a JSON file with `bm:seed` and maintained in the admin afterwards.
Timestamps are stored in UTC (`TIMESTAMPTZ`) and written in RFC 3339 in Europe/Warsaw (`2026-10-03T08:00:00+02:00`). Dates are `YYYY-MM-DD`. A date or time without an offset in a seed file is read as Polish time.
## Features
- Models: `Course` (przedmiot, one row per course and form), `Meeting` (zjazd), `ClassSession` (zajęcia), `Deadline` (terminarz), `Reading` (lektura), `ReadingProgress`, `Material` with file attachments (`system_files`, field `files`) and `Tag`, many-to-many through `jz_bm_material_tag`, `CalendarFeed` (one per user), and `Checklist` with `ChecklistItem` (each user's own checklists, e.g. the preparation for a zjazd).
- A subscribable calendar feed (`/_bm/calendar/<token>.ics`) of the class sessions, meetings and deadlines, see [Calendar feed](#calendar-feed).
- Courses that share an `elective_group` are alternatives ("do wyboru"), such as the specialisation courses.
- A material without `published_at` is a draft; a material whose `published_at` lies in the future is not shown yet.
- A material may be private (`is_private`): only its author (`author_user_id`) and the users it is shared with (`jz_bm_material_shares`) see it, see [Private materials](#private-materials). Existing materials are public and have no author.
- Cascades: deleting a course deletes its class sessions and readings and unlinks its deadlines and materials; deleting a meeting unlinks its sessions; deleting a reading or a user deletes the progress and ownership rows; deleting a user deletes the user's calendar feed and checklists; deleting a checklist deletes its items; deleting a meeting, course, reading, deadline or material unlinks the checklists and items that point at it; deleting a material or a user deletes their `jz_bm_material_shares` rows, and deleting a material's author clears `author_user_id`.
- Admin screens for every model in a "Studia BM" navigation group, guarded by three permissions.
- `bm:seed`: an idempotent upsert of meetings, courses, class sessions, deadlines and readings from a JSON file, all or nothing, with `--prune` to delete what the file no longer lists and `--dry-run` to preview.
## API reference
Every route except the calendar feed itself needs `Authorization: Bearer <golem15.user JWT>` (or the user plugin's token cookie) and answers 401 `{"error": true, "message": "..."}` without one. Responses are wrapped in `{"data": ...}`; `/materials` adds the `meta` block of `lagoon.Paginate`. A missing record, an unpublished material or a non-numeric `{id}` is a 404. Invalid query parameters are a 422 in Laravel's shape, with messages in the request locale:
```json
{"message": "The to must be a date after or equal to from.", "errors": {"to": ["The to must be a date after or equal to from."]}}
```
| Method | Path | Query | Answers |
|--------|------|-------|---------|
| GET | `/_bm/api/v1/dashboard` | | Next sessions, upcoming deadlines, current and next meeting, reading progress |
| GET | `/_bm/api/v1/courses` | `semester` (1–4) | Every course with counters |
| GET | `/_bm/api/v1/courses/{id}` | | One course with its sessions, readings and published materials |
| GET | `/_bm/api/v1/schedule` | `from`, `to` (`YYYY-MM-DD`) | Class sessions starting in the range |
| GET | `/_bm/api/v1/meetings` | | Every meeting |
| GET | `/_bm/api/v1/deadlines` | `from`, `to` (`YYYY-MM-DD`) | Deadlines in the range |
| GET | `/_bm/api/v1/readings` | `course` (ID) | Readings with the caller's `read_at` |
| PUT | `/_bm/api/v1/readings/{id}/progress` | | Marks the reading read (idempotent) |
| DELETE | `/_bm/api/v1/readings/{id}/progress` | | Clears the mark (idempotent) |
| PUT | `/_bm/api/v1/readings/{id}/owned` | | Marks the reading owned (idempotent) |
| DELETE | `/_bm/api/v1/readings/{id}/owned` | | Clears the owned mark (idempotent) |
| GET | `/_bm/api/v1/materials` | `q` (search, 2–100 characters), `course`, `meeting`, `tag` (slug), `type`, `page`, `per_page` (1–100) | One page of the published materials the caller may see: without `q` the caller's pins first, by relevance with `q`, see [Search](#search) |
| GET | `/_bm/api/v1/materials/{id}` | | One published material the caller may see, with body, tags, files and `can_manage` |
| PUT | `/_bm/api/v1/materials/{id}/pin` | | Pins the material for the caller only (idempotent); 204 |
| DELETE | `/_bm/api/v1/materials/{id}/pin` | | Removes the caller's pin (idempotent); 204 |
| GET | `/_bm/api/v1/checklists` | `meeting` (ID) | The caller's checklists with progress, without items |
| POST | `/_bm/api/v1/checklists` | | Creates a checklist for the caller; 201 |
| GET | `/_bm/api/v1/checklists/{id}` | | One of the caller's checklists with progress and items |
| PATCH | `/_bm/api/v1/checklists/{id}` | | Changes the sent fields |
| DELETE | `/_bm/api/v1/checklists/{id}` | | Deletes it with its items; 204 |
| POST | `/_bm/api/v1/checklists/{id}/items` | | Adds an item, last unless `sort_order` is sent; 201 |
| PATCH | `/_bm/api/v1/checklist-items/{id}` | | Changes the sent fields of an item |
| DELETE | `/_bm/api/v1/checklist-items/{id}` | | Deletes an item; 204 |
| PUT | `/_bm/api/v1/checklist-items/{id}/done` | | Marks the item done (idempotent) |
| DELETE | `/_bm/api/v1/checklist-items/{id}/done` | | Clears the done mark (idempotent) |
| GET | `/_bm/api/v1/calendar-feed` | | The caller's calendar feed, or `null` |
| PUT | `/_bm/api/v1/calendar-feed` | | Creates the feed when missing, applies the settings in the body |
| POST | `/_bm/api/v1/calendar-feed/rotate` | | A new token (the old URL stops working); 404 without a feed; `throttle:10,1` |
| DELETE | `/_bm/api/v1/calendar-feed` | | Deletes the feed; 204, also when there was none |
| GET | `/_bm/api/v1/materials/{id}/access` | | The material's visibility, shares and the users to pick from; the author only, see [Private materials](#private-materials) |
| PUT | `/_bm/api/v1/materials/{id}/access` | | Sets the visibility and the shares; the author only |
| PUT | `/_bm/api/v1/materials/{id}` | | Saves the author's edit, revision-checked; see [the author's routes](#author-routes-no-token-twin) |
| GET | `/_bm/api/v1/tags` | | The tag dictionary, to material managers |
| POST | `/_bm/api/v1/materials/{id}/unpublish` | | Moves the material to drafts; 204 |
| POST | `/_bm/api/v1/materials/{id}/images` | | Stores one editor image; 201 |
### Shared shapes
A course reference, embedded in other records:
```json
{"id": 1, "code": null, "name": "…", "form": "wyklad", "semester": 1}
```
`form` is one of `wyklad`, `cwiczenia`, `konwersatorium`, `seminarium`, `inne`.
A class session:
```json
{"id": 1, "course_id": 1, "meeting_id": 1, "meeting_number": 1,
"starts_at": "2026-10-03T08:00:00+02:00", "ends_at": "2026-10-03T09:30:00+02:00",
"room": "237", "kind": null, "notes": null, "is_online": false,
"course": {"id": 1, "code": null, "name": "…", "form": "wyklad", "semester": 1}}
```
A meeting:
```json
{"id": 1, "number": 1, "starts_on": "2026-10-03", "ends_on": "2026-10-04", "notes": null, "sessions_count": 12}
```
A deadline (`kind` is one of `zaliczenie`, `egzamin`, `praca`, `organizacyjne`, `inne`; `course` is null when the deadline belongs to no course):
```json
{"id": 1, "title": "…", "due_at": "2026-10-05T23:59:00+02:00", "kind": "organizacyjne", "description": null, "course_id": null, "course": null}
```
A reading (`read_at` is the caller's, or null; `meeting_id` is the zjazd the reading is meant for, null when none):
```json
{"id": 1, "course_id": 1, "course": {…}, "meeting_id": 4, "title": "…", "author": null, "source": null, "url": null,
"is_required": true, "sort_order": 1, "read_at": "2026-10-02T21:15:04+02:00"}
```
A material in a list (`type` is one of `pdf`, `notatka`, `link`, `inne`; `files_count` counts public files; `meeting_id` is the zjazd the material is meant for, null when none; `is_private` is true for a private material, which only its author and the users it is shared with get):
```json
{"id": 1, "course_id": 1, "course": {…}, "meeting_id": null, "title": "…", "type": "notatka", "source": null, "url": null,
"published_at": "2026-10-01T12:00:00+02:00", "tags": [{"id": 1, "name": "Geopolityka", "slug": "geopolityka"}], "files_count": 1, "is_private": false}
```
A course with counters (`readings_read` is the caller's; `materials` counts the published materials the caller may see):
```json
{"id": 1, "code": null, "name": "…", "form": "wyklad", "lecturer": "…", "semester": 1, "ects": 8,
"assessment": "egzamin", "elective_group": null, "description": null, "syllabus_url": null, "sort_order": 1,
"counts": {"sessions": 6, "readings": 4, "readings_read": 1, "materials": 2}}
```
### GET /dashboard
```json
{"data": {
"next_sessions": [<session>, …],
"upcoming_deadlines": [<deadline>, …],
"current_meeting": <meeting> | null,
"next_meeting": <meeting> | null,
"readings": {"total": 40, "read": 3, "required_total": 25, "required_read": 2}
}}
```
`next_sessions` are the first sessions that have not ended yet, by start time; `upcoming_deadlines` the first deadlines not yet due. Both hold `jz.bm.dashboard_limit` items (5). `current_meeting` is the meeting whose dates include today in Warsaw; `next_meeting` the first one that starts after today.
### GET /courses, GET /courses/{id}
`/courses` answers `{"data": [<course with counters>, …]}` in programme order (semester, `sort_order`, name). `/courses/{id}` answers one course with counters plus:
```json
{"data": {…course with counters…,
"sessions": [<session>, …],
"readings": [<reading>, …],
"materials": [<material>, …]}}
```
### GET /schedule, GET /meetings, GET /deadlines
`/schedule` answers `{"data": [<session>, …]}` by start time: the sessions that start from midnight of `from` (default today) until the end of `to` (default no limit), in Warsaw. `/meetings` answers `{"data": [<meeting>, …]}` by number. `/deadlines` answers `{"data": [<deadline>, …]}` by due time; without `from` it starts now, so it lists the deadlines not yet due.
### GET /readings, PUT and DELETE /readings/{id}/progress and /owned
`/readings` answers `{"data": [<reading>, …]}` in course and `sort_order` order; an unknown `course` gives an empty list. Each reading carries the caller's `read_at` and `owned_at`, `null` when unset; a course's readings in `/courses/{id}` carry the same pair. The progress routes answer:
```json
{"data": {"reading_id": 7, "read_at": "2026-10-02T21:15:04+02:00"}}
```
Marking a read reading again keeps the first `read_at`. Clearing answers `read_at: null`, also when the reading was not marked.
The owned routes record that the caller owns a copy of the reading, apart from whether it is read, and answer `{"data": {"reading_id": 7, "owned_at": "2026-10-26T12:00:00+01:00"}}` with the same rules: marking an owned reading again keeps the first `owned_at`, and clearing answers `owned_at: null`, also when the reading was not owned.
### Checklists
Checklists are private: every route reaches only the caller's own checklists and items, and another user's id answers 404 like a missing one. A checklist has `meeting_id` (optional zjazd), `title`, `description` and `sort_order`; it is answered with `meeting` (`id`, `number`, `starts_on`, `ends_on`) and `progress`:
```json
{"total": 4, "done": 1, "percent": 21, "minutes_total": 185, "minutes_done": 40, "minutes_left": 145}
```
`percent` is weighed by time: `minutes_done * 100 / minutes_total`, rounded down, so a long item counts more than a short one and an item without `estimate_minutes` counts nothing. A checklist with no estimates at all falls back to `done * 100 / total`.
An item has `kind` (`lektura`, `artykul`, `ksiazka`, `prezentacja`, `zadanie`, `inne`; default `zadanie`), `title`, `notes`, `url`, `due_at`, `estimate_minutes` (0–10000), `sort_order`, optional links `course_id`, `reading_id`, `deadline_id`, `material_id` (each must exist) and `presentation_slug` (must name one of the caller's decks in `golem15.presentations`, read by table name; the plugin is not required). `checklist_id` moves an item to another of the caller's checklists. It is answered with `done`, `done_at` and the linked rows (`course`, `reading`, `deadline`, `material` (published only), `presentation`), `null` when unset or gone.
**Readings share the mark.** An item with a `reading_id` has no done mark of its own: it is done exactly when the caller has read that reading. Marking it done inserts the `jz_bm_reading_progress` row and clearing it deletes the row, so `/readings` and every checklist with that reading agree. Deleting an item or a checklist leaves reading marks alone.
Bodies are JSON objects of columns checked like the management API: keys outside the writable columns, rule failures and unknown foreign keys answer 422 with errors per field.
### GET /materials, GET /materials/{id}
```json
{"data": [<material>, …], "meta": {"current_page": 1, "last_page": 1, "per_page": 20, "total": 2}}
```
Without `q` the caller's pinned materials come first (newest pin first), then the newest publication first, with the id as the last tie-breaker, so pages are stable. The filters apply to pinned rows too, and `meta.total` counts as before. Every row, the detail and the materials of `/courses/{id}` (which keep newest first) carry `pinned`, the caller's own pin; nobody else's pins show or change the order. With `q` the order stays relevance and pinned rows are only marked. `meeting` keeps the materials assigned to that zjazd (meeting id); like every filter it applies to published materials only. The detail adds the Markdown body and the public files; `url` starts with `storage.uploads.public_path_prefix`. `can_manage` is true when the caller may change the material's access (see below):
```json
{"data": {…material…, "body": "# …",
"files": [{"id": 3, "url": "/storage/uploads/5f1/d0c/2e9/5f1d0c2e9a7b4c3d8e6f.pdf", "name": "wyklad.pdf", "size": 123456, "mime": "application/pdf"}],
"pinned": false, "can_manage": false, "revision": 3}}
```
`revision` is the content revision (see [Revisions](#revisions)); the author's edit sends it back.
`q` searches (see [Search](#search)): a trimmed `q` of fewer than 2 characters is ignored, one over 100 is a 422. With `q` the page is in relevance order, combined with the other filters (AND); `meta.total` is counted in SQL over the materials the caller may see, never taken from the engine. A row whose match is in the body carries one `snippet`:
```json
{"snippet": {"source": "body", "file_name": null, "lead": true, "trail": true,
"segments": [{"text": "proces ", "hit": false}, {"text": "globalizacji", "hit": true}, {"text": " zmienia państwa", "hit": false}]}}
```
A row whose match is only in an attached PDF carries a file snippet instead: `"source": "file"`, `file_name` the name of that file (null when the engine's array index does not resolve to a current file) and `lead` and `trail` both true. A body snippet is preferred when both exist.
`segments` are the engine's plain text, verbatim, never markup: render each `text` as text and mark the `hit` ones. `lead` and `trail` say that text was cut before or after the excerpt. The key is absent when there is no snippet, and always without `q`. When the search engine is not configured or does not answer, a request with `q` is a 503 `{"error": true, "message": "Search is unavailable."}`; the list without `q` keeps working and never calls the engine.
### PUT and DELETE /materials/{id}/pin
Pins are personal: they live in `jz_bm_material_pins` (migration `20261109130000_create_jz_bm_material_pins`), one row per material and user, gone with the material or the user. Nobody but the caller sees a pin. Both routes need a material the caller may see (published and the privacy rule, as the detail), else a 404. `PUT` keeps the first `pinned_at` when the material is pinned again; `DELETE` of a material that is not pinned is fine. Both answer 204 with no body.
A pin is not content: it does not change `revision` or `updated_at`, does not resync the search document and publishes nothing on `materials:{id}`. The token twins under `/_bm/api/v1/token` need `user.scope:write`.
### Private materials
A private material (`is_private`) is visible only to its author (`author_user_id`) and to the users it is shared with (`jz_bm_material_shares`); a public one to every student. The rule is one SQL fragment (`visibleMaterialSQL` in `controllers/api/material_access.go`) applied to every student read: `/materials`, `/materials/{id}`, the materials of `/courses/{id}`, the `materials` counters of `/courses` and `/courses/{id}`, the material linked from a checklist item, and through the token twins the student MCP tools. For anyone else a private material is a 404 and is not counted.
`can_manage` is true when the caller holds `jz.bm.access_materials` and is the material's author, or the material has no author yet. Such a caller uses the access routes (jwt only, no token twin; tokens and MCP use the management API):
```json
GET /_bm/api/v1/materials/{id}/access
{"data": {"material_id": 4, "is_private": true, "author_user_id": 1,
"shares": [{"id": 2, "name": "Anna Nowak", "email": "anna@example.test"}],
"users": [{"id": 2, "name": "Anna Nowak", "email": "anna@example.test"}, …]}}
```
`users` is every user but the caller, by name; `name` is "name surname", else the email. `PUT` takes `{"is_private": true, "user_ids": [2, 5]}`: an absent key keeps the stored value, and `user_ids` (null meaning none) replaces the shares. Every id must be an existing user, at most 200 (else a 422 on `user_ids`); an unknown key such as `author_user_id` is a 422; the body is capped at 16 KB. Anyone else, including another manager when the material has an author, gets a 404, never a 403. **The claim rule:** the first access change of a material with no author makes the caller its author, so a private material is never invisible to everyone. `/bmadmin` can reassign the author.
The files of a private material are still public storage URLs: the API never shows them to a user who cannot see the material, but a leaked or guessed URL still downloads.
### Author routes (no token twin)
The student app edits, unpublishes and adds editor images to a material through four routes. They are jwt only, like the access panel; tokens and MCP write materials through the management API. The `{id}` routes are for a caller with `jz.bm.access_materials` who is the material's author, or any such caller while the material has no author (the `can_manage` rule). Unlike the access panel they tell the two refusals apart: a material the caller cannot see (private and not theirs, a draft, not published yet, unknown) is a 404, and one they see but may not manage is a 403 `{"error": true, "message": "Forbidden."}`. Each route checks again on the row locked `FOR UPDATE`. No route changes the author, `is_private` or the shares, and only unpublish changes `published_at`. Each route has its own per-user throttle: 30 a minute for the edit and for images, 10 for unpublish.
**`PUT /materials/{id}`** takes exactly these keys, all required:
```json
{"revision": 3, "title": "Notatka", "type": "notatka", "body": "# …", "source": null, "url": null, "meeting_id": 2, "tags": ["lektura", "cyber"]}
```
- An unknown key is a 422, `course_id` and `published_at` included. The course stays the stored one.
- A missing key is a 422 on that key, and so is a null `revision`, `title`, `type` or `tags`.
- The rules of the management `PUT` apply: title 1–255, `type` one of `pdf`, `notatka`, `link`, `inne`, source ≤ 500, url ≤ 2048, `meeting_id` an existing meeting or null. A title and course another material has is a 422 on `title`.
- Student-only rules: `url`, when not empty, starts with `http://` or `https://`. There are at most 4 tags, and each must be in the dictionary (`GET /tags`), else a 422 on `tags`. The app never creates a tag.
- The body is normalised as `bm-notatka push` does it: LF line ends, trimmed, one trailing newline, and empty means null. So a web save, a pull and a push of the same text never bump the revision.
- A stale `revision` is a 409, and nothing is written. `data` is the student detail of the current version, body included:
```json
{"error": true, "message": "The material was changed since the revision you sent.", "revision": 4, "updated_at": "2026-11-09T10:00:00+01:00", "data": {…detail…}}
```
The answer is the student detail (200), with the revision bumped when the content changed. The search document is resynced.
**`GET /tags`** answers `{"data": [{"id": 1, "name": "Cyber", "slug": "cyber"}, …]}`: every row of `jz_bm_tags`, by name. A caller without `jz.bm.access_materials` gets a 403.
**`POST /materials/{id}/unpublish`** ("Usuń" in the app) sets `published_at` to null, which makes the material a draft. The student API no longer serves it, so even the author gets a 404 afterwards. Nothing is deleted: a `bm-notatka push` without `--draft`, or `/bmadmin`, publishes it again. The revision stays. The search document is resynced (the management search keeps drafts). It answers 204.
**`POST /materials/{id}/images`** takes `multipart/form-data` with one part named `file`. The file is stored as a public file of the material through the same path as `POST /api/v1/bm/materials/{id}/files`, and the file text job is queued with it. Only JPEG, PNG, GIF and WebP pass, judged by the bytes; SVG and every other type are refused. The limits are 50 MB per file and 20 files per material, and the body is capped like the management upload. The revision does not change; the edit that links the image bumps it on save. The answer is 201:
```json
{"data": {"id": 12, "url": "/storage/app/uploads/public/5f1/d0c/2e9/5f1d0c2e9a7b4c3d8e6f.png", "name": "wklejony.png", "size": 48213, "mime": "image/png"}}
```
A refused file is a 422 `{"message": "…", "errors": {"file": ["…"]}, "reason": "type"}`, where `reason` is `type`, `size` or `count`. A second `file` part and a request with no file are both `type` refusals. A body over the limit is a 413 with `"reason": "size"`. Editor images are public storage URLs, like every material file.
### Calendar feed
The calendar-feed routes answer the caller's feed:
```json
{"data": {"url": "https://bm.jakubzych.com/_bm/calendar/<64 hex digits>.ics",
"excluded_course_ids": [9, 10], "include_meetings": true, "include_deadlines": true,
"last_fetched_at": "2026-10-02T21:15:04+02:00"}}
```
`GET` answers `{"data": null}` while the caller has no feed. `PUT` takes a JSON object whose keys are all optional and creates the feed with a new token and the defaults (`[]`, `true`, `true`) when there is none:
```json
{"excluded_course_ids": [9, 10], "include_meetings": true, "include_deadlines": false}
```
`excluded_course_ids` replaces the whole list (duplicates are dropped); every ID must be an existing course, otherwise the answer is a 422 on `excluded_course_ids.<index>`. The booleans take `true`/`false` (or `1`/`0`). A body that is not a JSON object is a 400. `last_fetched_at` is the last time a calendar fetched the feed (written at most once a minute), or null.
`url` starts with `jz.bm.public_url`, or with the scheme and Host of the request when that key is empty.
The feed itself, `GET /_bm/calendar/{token}.ics` (also without `.ics`), needs no authentication: calendar clients fetch it without credentials, so the 32 random bytes of the token are the credential. Rotate the token when the URL leaks. An unknown or malformed token is a 404. The route is throttled per client IP (`throttle:jz.bm.calendar-ip`, 60 a minute) and per token (`throttle:jz.bm.calendar-token`, 20 a minute). The answer is `text/calendar; charset=utf-8` with `Content-Disposition: inline; filename="bm.ics"`, `Cache-Control: private, max-age=900` and an ETag (304 on revalidation).
The calendar is RFC 5545 (CRLF lines folded at 75 octets, escaped TEXT) with times in UTC, so it needs no VTIMEZONE; `X-WR-TIMEZONE` is `Europe/Warsaw` and `REFRESH-INTERVAL`/`X-PUBLISHED-TTL` ask for a refresh every 6 hours (Google refreshes subscribed calendars on its own schedule, usually every few hours). It lists:
- every class session of the courses not excluded: UID `session-<id>@bm.jakubzych.com`, summary `<course> – <form>` (`wykład`, `ćwiczenia`, `konwersatorium`, `seminarium`; nothing for `inne`) plus ` (online)`, location `Koszarowa 3, s. <room> (bud. 21 ISMiB)` or `online`, and a description with the lecturer, the meeting number, the notes, "Przedmiot do wyboru" for an elective and a link to `/przedmioty/<course id>`;
- with `include_meetings`, every meeting as an all-day event (`meeting-<id>@…`, `3. zjazd (stacjonarny)` or `(online)` read from the notes, `TRANSP:TRANSPARENT`);
- with `include_deadlines`, every deadline not tied to an excluded course, as a 30-minute event ending at the due time (`deadline-<id>@…`, `Termin: <title>`) with a display alarm a day before.
`DTSTAMP` and `LAST-MODIFIED` are the row's `updated_at`, so an unchanged timetable gives the same bytes.
## Management API
`/api/v1/bm` is what `bm:seed` and the materials screen do, over HTTP, for scripts: it sits behind the application-wide API token of `golem15.user` (`Authorization: Bearer <token>`, middleware `user.api_token`), not the students' `jwt.auth`. Every route needs a token scope (`user.scope:read` or `user.scope:write`) and, except `/me`, a permission of the token owner's groups (`jz.bm.access_courses`, `jz.bm.access_schedule`, `jz.bm.access_materials`, the codes of the admin screens); a missing one is a 403. The group is throttled per token (`throttle:jz.bm.manage`, 120 a minute); an MCP tool call is throttled per user instead (see [MCP tools](#mcp-tools)). Responses are `{"data": …}`; validation errors are a 422 in Laravel's shape (`{"message", "errors": {field: [...]}}`), a bad or oversized body a 400 or 413.
| Method | Route | Scope, permission | Answer |
|--------|-------|-------------------|--------|
| GET | `/api/v1/bm/me` | read | The token owner's `user_id` and the token (`id`, `name`, `scopes`, `expires_at`). |
| GET | `/api/v1/bm/materials` | read, materials | Every material, drafts and private ones included, newest first. `q` (2–100 characters) searches all of them, in relevance order, with the `snippet` of the student list; a 503 `Search is unavailable.` when the engine cannot answer. |
| GET | `/api/v1/bm/materials/{id}` | read, materials | One material, draft or not, with its public `files`. 404 when unknown. |
| POST | `/api/v1/bm/materials` | write, materials | Upsert on `title` + `course_id`: 201 `{"data", "created": true}` for a new material, 200 `{"data", "created": false}` for an updated one; 409 when an update sends a stale `revision` (see [Revisions](#revisions)). |
| PUT | `/api/v1/bm/materials/{id}` | write, materials | The same body applied to that material, so the title or course can change. 404 when unknown; 422 on `title` when another material already has the new title and course; 409 on a stale `revision`. |
| DELETE | `/api/v1/bm/materials/{id}` | write, materials | 204, with the material's files (rows, then blobs); 404 when unknown. |
| POST | `/api/v1/bm/materials/{id}/files` | write, materials | Multipart body, parts named `file`: each is stored as a public file of the material, after the ones it has. 201 with the material as GET shows it; 404 when unknown; 422 on `file` when there is no file part, a type is not allowed, a file is over 50 MB or the material would hold more than 20 files (nothing is stored then); 413 over the body cap (`body.limit`, 51 MB, so one large file per request). |
| POST | `/api/v1/bm/materials/{id}/files/inline` | write, materials | JSON `{"name": "notatki.pdf", "mime": "application/pdf", "content_base64": "…"}` (`mime` optional; unknown keys are a 422): one file of at most 3000000 bytes decoded (`MaterialInlineMaxBytes`, so it fits under the MCP endpoint's 4 MiB request cap), stored like a multipart file; a sent `mime` must match the stored content type. Larger content is a 422 on `content_base64` that points at the upload URL. 201 with the material as GET shows it plus a top-level `warning`; 413 over the body cap (`body.limit`, 4300000). |
| POST | `/api/v1/bm/materials/{id}/files/upload-url` | write, materials | 201 `{"data": {"upload_url", "expires_at", "max_bytes", "accept", "curl_example", "warning"}}`: a signed, single-use URL for one file of this material by the caller, valid 10 minutes, at most 50 MiB (`max_bytes` 52428800). 503 when `app.key` or the cache is missing. See [Signed uploads](#signed-uploads). |
| DELETE | `/api/v1/bm/materials/{id}/files/{file}` | write, materials | 204: the file row, then its blob and thumbnails; 404 when the material or a file of it is unknown. |
| PATCH | `/api/v1/bm/materials/{id}/visibility` | write, materials | `{"is_private": true}` (required): 200 with the material; a material with no author gets the caller as author; 404 when unknown. |
| PUT | `/api/v1/bm/materials/{id}/shares` | write, materials | `{"user_ids": [2, 5]}` (the key is required, `null` or `[]` removes every share): the list replaces the shares; 422 on `user_ids` for an unknown user or more than 200; the claim rule as above; body capped at 16 KB. |
| GET | `/api/v1/bm/users` | read, materials | `[{"id", "name", "email"}, …]` of every user, to pick an author or shares. |
| GET | `/api/v1/bm/{records}` | read, see below | Every row of the table, filtered by `?column=value` on the columns listed below (`null` matches NULL). |
| GET | `/api/v1/bm/{records}/{id}` | read | One row; 404 when unknown. |
| POST | `/api/v1/bm/{records}` | write | 201 with the new row. |
| PATCH | `/api/v1/bm/{records}/{id}` | write | Only the sent columns change; 200 with the row. |
| DELETE | `/api/v1/bm/{records}/{id}` | write | 204 (class sessions, readings, deadlines only; courses and meetings are deleted in the admin, because rows hang on them). |
| POST | `/api/v1/bm/seed?dry_run=&prune=` | write, courses + schedule + materials | `bm:seed` over HTTP: the body is the seed document, the answer the summary table. |
The record tables (`controllers/api/manage_records.go`, mounted by `mountRecords` in `routes.go`):
| `{records}` | Model | Permission | List filters | Order |
|-------------|-------|------------|--------------|-------|
| `courses` | `Course` | courses | `semester`, `form`, `code` | semester, sort_order |
| `meetings` | `Meeting` | schedule | | number |
| `class-sessions` | `ClassSession` | schedule | `course_id`, `meeting_id` | starts_at |
| `readings` | `Reading` | courses | `course_id`, `meeting_id`, `is_required` | course_id, sort_order |
| `deadlines` | `Deadline` | schedule | `course_id`, `kind` | due_at |
A row is answered as an object of its columns (`id`, `created_at` and `updated_at` included); times are RFC 3339 in Europe/Warsaw, dates `YYYY-MM-DD`. A POST or PATCH body is an object of columns: only the model's `Fillable()` ones (another key is a 422 that lists them), with times as RFC 3339 or `2006-01-02 15:04` in Europe/Warsaw, dates as `YYYY-MM-DD`, `""` or `null` clearing an optional column, and a number accepted for a text column. The model's `Rules()` (the admin's) run on the row as it would be saved, so a PATCH of one column still meets the required ones, and `unique` skips the row itself; `TemporalErrors()` checks the order of times; `course_id` and `meeting_id` must exist. A seed run (`bm:seed`, `POST /seed`) overwrites the columns it carries on the rows it matches, so changes made here are lost when the same rows are seeded again.
The material body (POST and PUT), unknown keys are a 422:
```json
{"course_id": 7, "meeting_id": 2, "title": "Definicje globalizacji", "type": "notatka",
"body": "# Robertson\n\n> …", "source": null, "url": null,
"published_at": "2026-10-16T20:00:00+02:00", "tags": ["Globalizacja"]}
```
- `type`: `pdf`, `notatka`, `link`, `inne`. `body` is Markdown, rendered by the student app (headings start at h2 there; the title is the page's h1).
- `course_id`: null or an existing course. `body`, `source` and `url` are replaced as sent (absent means null).
- `meeting_id`: absent keeps the stored meeting (so scripts that never send it keep working), `null` clears it, otherwise an existing meeting (else a 422 on `meeting_id`). The managed material JSON shows `meeting_id`, and the material then lists under that zjazd in `GET /_bm/api/v1/materials?meeting=`.
- `published_at`: absent publishes a new material now and keeps an existing one as it is; `null` makes it a draft; otherwise a time as in the seed file.
- `tags`: absent keeps the tags; otherwise the list of names replaces them, and unknown tags are created (slug from the name, Polish letters folded). Tags hold topics only: the zjazd is `meeting_id`, never a tag (the student app's Zjazd filter and badge read `meeting_id`).
The one-way migration `20261108140000_move_zjazd_tags_to_meetings` moved the old zjazd tags onto `meeting_id`: a material tagged `zjazd-N` (slug matching `^zjazd-[0-9]{1,6}$`) with no meeting got meeting number N (the lowest when it had several), an existing `meeting_id` was kept, and every such tag was deleted with its links; a slug such as `zjazd-3-24-10` is a topic and stays. A tag naming a missing meeting, a tag disagreeing with `meeting_id` and a material with several zjazd tags are logged at Warn under `jz.bm`. Its Rollback does nothing: the only way back is the `pg_dump --data-only -t jz_bm_tags -t jz_bm_material_tag` taken before `migrate`.
- `is_private`: absent keeps it (a new material is public). `author_user_id`: absent keeps it (a new material gets the token user as author), `null` clears it, otherwise an existing user (else a 422 on `author_user_id`). `share_user_ids`: absent keeps the shares; otherwise the list of user ids replaces them (else a 422 on `share_user_ids`, as for the access routes). The managed material JSON shows `is_private`, `author_user_id`, `author` (`{"id", "name", "email"}` or null) and `shares` (a list, never null).
- `revision`: optional, the revision the caller last read; see [Revisions](#revisions).
- Files go through `POST /materials/{id}/files`, `/files/inline` or a signed upload. All three use one helper, `storeMaterialFile`, which applies the 20-file cap, stores through `attach.Store` (the default document and image extensions, content type sniffed from the bytes, a random disk name; `file_name` keeps the client's name) and binds the file to the material; a refused or failed store deletes the blobs it wrote. The file `url` is under `storage.uploads.public_path_prefix`, served by the application when `storage.uploads.serve` is true (the app's `config/storage.yaml` sets it): GET only, `is_public` rows only, anything but a raster image as `Content-Disposition: attachment`.
### Revisions
Every material answer of the management API (`GET /materials`, `GET /materials/{id}` and every POST and PUT) carries `revision`, starting at 1, and `updated_at`; the student detail `GET /_bm/api/v1/materials/{id}` (and its token twin) carries `revision` too. The revision goes up by one only when the material's content changes: its `title`, `type`, `body`, `source`, `url`, course, zjazd (`meeting_id`) or tags. A write that changes only `published_at`, `is_private`, the author or the shares, a file attach or detach, a student's pin, or a write that sends identical content, keeps it (migration `20261109120000_add_revision_to_jz_bm_materials`; `models.ReviseMaterial` is the only writer of the column).
POST and PUT accept an optional `revision`. When it is sent and is not the stored one, the answer is a 409 and nothing is written:
```json
{"error": true, "message": "The material was changed since the revision you sent.",
"revision": 4, "updated_at": "2026-11-09T12:00:00+01:00", "data": <material>}
```
`data` is the material as GET shows it, so the caller can diff or pull; over plain HTTP it carries the `body`, under MCP the body is left out as in every other MCP answer. Without `revision` the write overwrites as before, so callers that never send it keep working. The compare and the write run on the row locked `FOR UPDATE`, so two writers holding the same revision cannot both succeed. A POST that creates a material ignores `revision` (the new material starts at 1). Saves in `/bmadmin` are not checked (the form has no revision), but they bump the revision when they change the content, so a later write with an older revision gets the 409 instead of silently overwriting the admin edit.
### Signed uploads
`POST /_bm/api/v1/uploads/{ticket}` takes the file of a signed upload URL, for example `curl -fsS -F 'file=@wyklad.pdf' '<upload_url>'`. It has no bearer: the ticket in the path is the credential. The ticket is `base64url(payload).base64url(HMAC-SHA256(app.key, "jz.bm.upload.v1:" + payload))` with the payload `material|<material id>|<user id>|<expiry unix>|<nonce>` (16 random bytes in hex). Issuing stores the payload under the nonce in the application cache (`cooler`) for 10 minutes; the upload takes it out again with an atomic pull, so a URL works once, and a restart of the memory cache voids every issued URL. The URL carries no bearer token and no key.
The route is throttled per client IP (`throttle:jz.bm.upload-ip`, 10 a minute) and per ticket (`throttle:jz.bm.upload-ticket`, 3 a minute, keyed by a SHA-256 digest of the ticket) and capped at `body.limit` 51 MB. A malformed, forged, expired or used ticket is a 403 `{"error": true, "message": "Invalid or expired upload URL."}` before the database is touched; so is a ticket whose user no longer exists or no longer holds `jz.bm.access_materials`. A deleted material is a 404. The body must be multipart with exactly one part, named `file` (else a 422 on `file`); the file goes through `attach.Store` with the material file limits (50 MiB, the default extensions, the 20-file cap). The answer is 201 `{"data": {"material_id", "file": {"id", "name", "size", "mime", "url"}}, "warning"}` with an absolute `url` (`app.url`, else `jz.bm.public_url`, else the request). A refused upload still uses up its URL: ask for a new one.
**Material files are public to anyone with the link.** The inline and signed answers and every file tool say so.
## MCP tools
`jz.bm` implements `pact.HasMCP`. With the framework's MCP endpoint (`pier`, the `summercms_mcp` build tag) its tools are offered at `/mcp` as `bm_<name>`, to OAuth sessions and personal tokens of `golem15.user` (guard `user`). Every tool binds a token-guarded route, every description is static text naming the scope it needs (and, for management tools, the permission code), and no tool has a `dry_run`. `jz.bm` still requires only `golem15.user`.
**Token twins of the student API.** `/_bm/api/v1/token/*` (`TokenPrefix`) mounts the student routes a second time, from the same `mountStudent` helper as the `jwt.auth` group, behind `user.api_token`, the per-user bucket `throttle:jz.bm.token` (240 a minute) and `locale.from-principal`, with `user.scope:read` on the reads and `user.scope:write` on the reading marks, the material pins and the checklist writes. The handlers read `bouncer.User`, so a personal token or an MCP session reaches only its own user's data. The calendar feed and the chat have no twin. `TestTokenMirrorRoutes` fails when a student route is added to one surface only.
| Tool | Route | Scope |
|------|-------|-------|
| `bm_dashboard`, `bm_courses`, `bm_course`, `bm_schedule`, `bm_meetings`, `bm_deadlines`, `bm_readings`, `bm_materials`, `bm_material` | `GET /_bm/api/v1/token/…` | read |
| `bm_mark_reading_read`, `bm_unmark_reading_read`, `bm_mark_reading_owned`, `bm_unmark_reading_owned` | `PUT` / `DELETE /_bm/api/v1/token/readings/{id}/progress` and `/owned` | write |
| `bm_pin_material`, `bm_unpin_material` | `PUT` / `DELETE /_bm/api/v1/token/materials/{id}/pin` | write |
| `bm_checklists`, `bm_checklist` | `GET /_bm/api/v1/token/checklists[/{id}]` | read |
| `bm_create_checklist`, `bm_update_checklist`, `bm_delete_checklist`, `bm_add_checklist_item`, `bm_update_checklist_item`, `bm_delete_checklist_item`, `bm_mark_checklist_item_done`, `bm_unmark_checklist_item_done` | `POST` / `PATCH` / `PUT` / `DELETE /_bm/api/v1/token/checklists…` and `/checklist-items…` | write |
**Management tools** bind the existing `/api/v1/bm` routes, whose `user.scope:*` and `user.permission:jz.bm.access_*` middleware filter the listing: a user whose groups lack the codes never sees them, and write tools need the write grant. Each input mirrors the model's `Fillable()` columns and `Rules()` (required columns are required on create, every update field is optional and nullable); enum values, lengths and date and time formats are in the field descriptions, and the routes still answer 422.
| Table | Tools | Permission |
|-------|-------|------------|
| courses | `bm_manage_list_courses`, `_show_course`, `_create_course`, `_update_course` | `jz.bm.access_courses` |
| meetings | `bm_manage_list_meetings`, `_show_meeting`, `_create_meeting`, `_update_meeting` | `jz.bm.access_schedule` |
| class sessions | `bm_manage_list_class_sessions`, `_show_class_session`, `_create_class_session`, `_update_class_session`, `_delete_class_session` | `jz.bm.access_schedule` |
| readings | `bm_manage_list_readings`, `_show_reading`, `_create_reading`, `_update_reading`, `_delete_reading` | `jz.bm.access_courses` |
| deadlines | `bm_manage_list_deadlines`, `_show_deadline`, `_create_deadline`, `_update_deadline`, `_delete_deadline` | `jz.bm.access_schedule` |
| materials | `bm_manage_list_materials`, `_show_material`, `_save_material` (upsert on title and course), `_update_material`, `_delete_material`, `_set_material_visibility`, `_set_material_shares`, `_list_users` | `jz.bm.access_materials` |
| material files | `bm_manage_attach_material_file` (base64, at most 3000000 bytes), `_create_material_upload` (signed one-time URL, then curl), `_detach_material_file` (destructive) | `jz.bm.access_materials` |
The file tools return metadata and links, never file contents, and their descriptions carry the public-file warning. `POST /seed` and `GET /me` are not tools. Courses and meetings have no delete tool, because the route has none. The material save and update tools require `body`, `source` and `url` (each may be `null`), because the route replaces them as sent; their descriptions tell the agent to read the material with `include_body` first to keep its body. They also take `is_private`, `author_user_id` and `share_user_ids` (absent keeps each), and an optional `revision`: the revision last read with `bm_manage_show_material`; a material changed since then is refused with 409 and its current revision, and without it the write overwrites (see [Revisions](#revisions)). `bm_manage_set_material_visibility` and `bm_manage_set_material_shares` change only the visibility or the shares (ids from `bm_manage_list_users`), with the claim rule of the access routes. The student tools `bm_materials`, `bm_material` and `bm_course` show only the materials the token's user may see.
**The MCP view.** Only an answer to an MCP tool call (a request `pier` dispatched in-process, carrying the `api_token` dispatch marker, which an HTTP request can never carry) is changed; plain HTTP answers are byte for byte as before.
- Links: the middleware `jz.bm.mcp-links` (on the token twins and the management API) prefixes every JSON string under a key named `url` or ending in `_url` that starts with a single `/` with `app.url`, else `jz.bm.public_url`, else the request's scheme and Host, so file and syllabus links are ready to follow.
- Material bodies (possible transcript text): `bm_material`, `bm_manage_list_materials` and `bm_manage_show_material` leave `body` out unless `include_body=true`, and mark an omitted non-empty body with `body_omitted: true`; the material write answers never echo it. Material tools return metadata and links, never whole file contents.
- Search: `bm_materials` and `bm_manage_list_materials` take `q` as the HTTP lists do. With `q` the results come by relevance and a material may carry `snippet` as a plain string, the matched passage with `…` where text was cut; it can come from the body or from an attached PDF.
- Throttling: `jz.bm.manage` keys an MCP call by its user (`jz.bm.manage.user|<id>`) before the bearer and IP keys.
## Student app
The built single-page app (Vue, source in the application repository's `frontend/`) is embedded from `public/` and served at `/`. Existing files are served as they are: `assets/*` (content-hashed) with `Cache-Control: public, max-age=31536000, immutable`, everything else with `no-cache` and an ETag (304 on revalidation). A GET for any other extension-less path answers `index.html` (client routes); a missing path with an extension is a 404. `/_user`, `/_bm`, `/_quizzes`, `/storage` and the admin path (`backend.uri`, default `/bmadmin`) are never answered by the app. Routes fails when `public/index.html` is missing. The output of `npm run build` in `frontend/` is committed in `public/`.
## Admin
Controllers (admin API path `<backend.uri>/api/v1/jz/bm/<name>`), all in the "Studia BM" navigation group:
| Controller | Permission |
|------------|------------|
| `jz.bm.courses`, `jz.bm.readings` | `jz.bm.access_courses` |
| `jz.bm.meetings`, `jz.bm.class_sessions`, `jz.bm.deadlines` | `jz.bm.access_schedule` |
| `jz.bm.materials`, `jz.bm.tags` | `jz.bm.access_materials` |
Courses, meetings, sessions and deadlines are picked through relation fields; a material's tags through a belongsToMany relation field. The material form has the `is_private` switch, the author picker (`author`, a belongsTo of `users` on `author_user_id`, by email) and `shared_with` (a belongsToMany of `users` through `jz_bm_material_shares`, by email); the list shows `is_private` and the zjazd (`meeting`, by number). Dates and times are edited with date pickers (`type: datepicker`); the admin shows times in the browser's time zone and stores them in UTC. Labels are in Polish (`lang/pl`) and English (`lang/en`).
A material's files are uploaded in its form (`type: fileupload` on the attachMany `files`, public, up to 20 files of 50 MB). The course form embeds relation managers for its readings and class sessions, which create, edit and delete them, also before the course is first saved: `course_id` on both tables is nullable for that, the pending rows are bound to the form session and get the course on its first save, and `deferred:purge` deletes abandoned ones. The student API leaves out sessions and readings without a course. A class session added from the course form has no meeting; set it on the class sessions screen.
## Configuration
Defaults in `config/config.yaml`, read as `jz.bm.<key>`:
| Key | Default | Sets |
|-----|---------|------|
| `jz.bm.materials_per_page` | `20` | Default page size of `/materials` (clamped to 1–100). |
| `jz.bm.dashboard_limit` | `5` | Sessions and deadlines on `/dashboard`. |
| `jz.bm.public_url` | `""` | Absolute base URL of the application (`https://bm.jakubzych.com`), used in the calendar feed URL and the course links inside the feed. Empty means the scheme and Host of the request; set it behind a TLS-terminating proxy. The application overrides it in `config/jz.bm.yaml`. |
## Search
Materials are searched through the framework's `beachcomber` module with the Typesense engine (`search.driver: typesense`; the blank import of `beachcomber/typesense` is in `search.go`). `models.Material` is a `beachcomber.Searchable` (`models/material_search.go`) kept in the index `jz_bm_materials` (after `search.prefix`). A document holds `id`, `title`, `source`, `url`, `tags` and `tag_slugs`, `course` (name and code), `course_id`, `meeting_id`, `meeting_number`, `type`, `published_at` (Unix seconds, 0 for a draft), the body with its Markdown syntax removed and `file_texts` (the text of attached files). No field sets a locale, so the default one folds diacritics and `lodz` finds `Łódź`.
The index holds every material, drafts and private ones included, and no visibility: the engine's ids are candidates only. A search asks for at most 250 of them (title weighted over tags, source and course, then body, link and file text), and SQL re-gates them with the same visibility rule and filters as the list, counts them and pages over them in the engine's order. A snippet is read only for a row SQL returned, so a material the caller may not see never reaches an answer, its count or a snippet.
The beachcomber service is app-wide, and so is its Gate: jz.bm installs one that is on only for contexts it marks (`classes.MarkMaterialSearch`), so `golem15.chatchannels` messages and DMs are never indexed. Every material write syncs explicitly after it commits: the admin form (create, update, delete), `POST`, `PUT` and `DELETE /api/v1/bm/materials`. A failed sync is logged with the material id and never fails the write.
Attached PDFs are searchable too. After any attach (the admin form, `POST /api/v1/bm/materials/{id}/files`, `/files/inline` and the signed upload, so also the MCP attach and upload tools) the background job `jz.bm.extract_material_text` (River, through `conga`; enqueued inside the attach transaction, three attempts of at most two minutes) runs `pdftotext` from poppler-utils on each new public PDF of the material and caches the text in `jz_bm_material_file_texts`, then resyncs the material, whose document carries the texts as `file_texts`, in file order. `pdftotext` is an optional runtime tool on the server: it runs without a shell on a 0600 temp file under `storage/app/tmp`, with a 60 s timeout and at most 1 MiB of text per file (the row's `truncated` is set beyond that). A scan or a broken PDF stores an empty text and adds nothing (there is no OCR); a missing `pdftotext` is logged once and stores nothing, so a later run retries. Detaching a file drops its text row (foreign-key cascade) and resyncs the material. `bm:materials-reindex` extracts the text of any PDF that has none before syncing each material, which backfills PDFs attached before file search existed.
Configuration, in the app's `config/search.yaml`: `search.driver`, `search.prefix`, `search.typesense.host`, `port`, `protocol` and `connection_timeout_seconds`. The API key goes only in the environment, `SUMMER_SEARCH__TYPESENSE__API_KEY`; with no key the engine is not configured, nothing is sent and every search answers 503.
## Realtime
An open editor learns of a newer revision before its own save (D-20); the save-time 409 stays the guarantee. After every write that bumps a material's revision (the author's `PUT /_bm/api/v1/materials/{id}`, the management `PUT` and `POST` upsert, so also `bm-notatka push` and the MCP tools, and a `/bmadmin` save) the server enqueues, on the write's own transaction, one broadcast on channel `materials:{id}` with event `updated.jz.bm.material` and payload `{"material_id": 5, "revision": 4}`. It is published only if the write commits, and only ids and the revision number travel, never content. The enqueue runs in a savepoint: a failure is logged and never fails or loses the save. A write that does not bump (visibility, shares, unpublish, files, a student's pin, identical content) publishes nothing (`classes.MaterialRevisionNotifier`).
jz.bm owns the realtime namespace `materials`. Its authorizer accepts only channels of the form `materials:{id}` (`^materials:[1-9][0-9]{0,18}$`; a `presence:` prefix, a leading zero or trailing characters are denied) and allows a subscribe only when the material is visible to the user and they may manage it: `jz.bm.access_materials` and its author, or any such user while it has no author (`api.CanWatchMaterial`), checked on current state at every subscribe. The connection-token guard `jz.bm.realtime-access` admits material managers besides chat-group members and presentation owners, so every possible editor can get a token; the token and subscribe-proxy routes are mounted only while `golem15.chat` or `golem15.presentations` is active. The Centrifugo instance needs the `materials` namespace (see the app's `DEPLOY.md`).
## CLI commands
### bm:materials-reindex
```sh
./bin/bm bm:materials-reindex
./bin/bm bm:materials-reindex --fresh
```
Ensures the `jz_bm_materials` collection and syncs every material through the same path as the sync after a save, first extracting the text of its PDFs that have none yet (a missing `pdftotext` is one warning, and the run goes on without file text), ending with `Reindexed: N synced, M failed`; it exits non-zero when any material failed. `--fresh` first drops the collection and recreates it from `models.Material.SearchIndexSchema`: use it on the first deploy and after a schema change. Without an engine the command refuses with an error naming `search.driver` and `search.typesense.api_key`; `--if-configured` makes that a notice and a zero exit. The plugin schedules `bm:materials-reindex --if-configured` every night at 04:15 (`Schedule`, run by `serve`'s scheduler), because course renames, meeting renumbering, failed syncs and Typesense restarts can leave the index stale. Run it by hand after a Typesense restart.
### bm:seed
```sh
./bin/bm bm:seed data/bm-2026-27.json
./bin/bm bm:seed data/bm-2026-27.json --dry-run --prune
./bin/bm bm:seed data/bm-2026-27.json --prune
```
Reads a JSON file, validates all of it, and upserts it in one transaction. Each kind is matched on its identity, updated in place when a field changed, and created otherwise; rows that are not in the file are left alone, so running the same file again changes nothing. Any error (an unknown key in the document, a bad value, a course key or meeting number that does not exist in the file) names the record and writes nothing. The command prints a table of created, updated, unchanged and deleted rows per kind.
`--prune` makes the file authoritative for what it covers: it deletes the courses of the file's semesters that the file does not list (their sessions and readings go with them, their deadlines and materials are unlinked), then the class sessions and readings of the listed courses that the file does not list. Reading progress of a deleted reading is deleted with it. Meetings and deadlines are never pruned. Each deleted row is printed. Use it when a timetable changes: a moved session is a new start time, so without `--prune` the old one would stay.
`--dry-run` applies the seed (and the prune) in a transaction that is rolled back, so the table and the deleted rows show what a real run would do.
| Kind | Identity |
|------|----------|
| meetings | `number` |
| courses | `name` + `form` + `semester` |
| class_sessions | course + `starts_at` |
| deadlines | `title` + `due_at` |
| readings | course + `title` |
The file format (every top-level array is optional, and nullable fields may be left out):
```json
{
"meetings": [{"number": 1, "starts_on": "2026-10-03", "ends_on": "2026-10-04", "notes": "stacjonarny"}],
"courses": [{"key": "glob-w", "code": null, "name": "…", "form": "wyklad", "lecturer": "…", "semester": 1,
"ects": 8, "assessment": "egzamin", "elective_group": null, "description": null, "syllabus_url": null, "sort_order": 1}],
"class_sessions": [{"course": "glob-w", "meeting": 1, "starts_at": "2026-10-03T08:00:00+02:00", "ends_at": "2026-10-03T09:30:00+02:00",
"room": "237", "kind": null, "is_online": false, "notes": null}],
"deadlines": [{"title": "…", "due_at": "2026-10-05T23:59:00+02:00", "course": null, "kind": "organizacyjne", "description": null}],
"readings": [{"course": "glob-w", "title": "…", "author": null, "source": null, "url": null, "is_required": true, "sort_order": 1}]
}
```
- `key` is a reference inside the file only; `course` in sessions, deadlines and readings names a course `key`, `meeting` in sessions a meeting `number`.
- `form`: `wyklad`, `cwiczenia`, `konwersatorium`, `seminarium`, `inne`. `semester`: 1–4. `kind` of a deadline: `zaliczenie`, `egzamin`, `praca`, `organizacyjne`, `inne`.
- Dates are `YYYY-MM-DD`; times RFC 3339 with an offset, or `YYYY-MM-DD HH:MM` in Polish time.
- A blank optional text is stored as null.
`testdata/seed.example.json` is a small example with made-up data.
## Dependencies
- SummerCMS framework modules (v0.6.4): `pact`, `party`, `backpack`, `surf`, `wire`, `bouncer`, `lagoon` (with `lagoon/attach`), `cabana`, `bonfire`, `phrasebook`, `beachcomber` (with `beachcomber/typesense`).
- The `golem15.user` plugin (`git.golem15.com/golem15/sm-user-plugin`): the `users` table and the `jwt.auth` middleware. `jz.bm` declares it in `Requires`, so its migrations run first.
- GORM and gormigrate. Tests also use testcontainers-go and pgx.
## Testing
```sh
go vet ./...
go test ./... # unit tests and Postgres integration tests (Docker)
go test -short ./... # unit tests only
```
The integration tests start a `postgres:16-alpine` container through testcontainers and create a fresh database per test; they never touch a development database. They cover the migrations up and down, the schema constraints, `bm:seed` (idempotency, in-place updates, all-or-nothing, prune and dry run), every API route through the real `jwt.auth` guard, the calendar feed (per-user isolation, exclusions, rotation, headers), and admin saves through the admin API.

246
admin_test.go Normal file
View File

@@ -0,0 +1,246 @@
package bm_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
const adminAPI = "/backend/api/v1"
// adminToken creates an administrator whose role grants perms and signs in
// through the admin API.
func adminToken(t *testing.T, gdb *gorm.DB, h http.Handler, perms string) string {
t.Helper()
hash, err := bouncer.HashPassword(10, "admin-secret-password")
if err != nil {
t.Fatal(err)
}
var roleID uint
if err := gdb.Raw(`INSERT INTO backend_user_roles (name, code, permissions, is_system, created_at, updated_at)
VALUES ('BM', 'bm', ?, FALSE, NOW(), NOW()) RETURNING id`, perms).Scan(&roleID).Error; err != nil {
t.Fatal(err)
}
if err := gdb.Exec(`INSERT INTO backend_users (login, email, password, is_activated, is_superuser, role_id, created_at, updated_at)
VALUES ('editor', 'editor@example.test', ?, TRUE, FALSE, ?, NOW(), NOW())`, hash, roleID).Error; err != nil {
t.Fatal(err)
}
rec := adminSend(t, h, http.MethodPost, "/auth/login", "", map[string]string{"login": "editor", "password": "admin-secret-password"})
var body struct {
Data struct {
AccessToken string `json:"access_token"`
} `json:"data"`
}
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil || body.Data.AccessToken == "" {
t.Fatalf("admin login = %d %s", rec.Code, rec.Body.String())
}
return body.Data.AccessToken
}
func adminSend(t *testing.T, h http.Handler, method, path, token string, body any) *httptest.ResponseRecorder {
t.Helper()
var reader io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
reader = bytes.NewReader(raw)
}
req := httptest.NewRequest(method, adminAPI+path, reader)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
req.Header.Set("Accept-Language", "en")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func createdID(t *testing.T, rec *httptest.ResponseRecorder) uint {
t.Helper()
if rec.Code != http.StatusCreated {
t.Fatalf("create = %d %s", rec.Code, rec.Body.String())
}
var body struct {
Data struct {
ID uint `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.ID == 0 {
t.Fatalf("create body %s: %v", rec.Body.String(), err)
}
return body.Data.ID
}
func TestAdminCRUDAgainstDatabase(t *testing.T) {
app, plugins, gdb := migrated(t)
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
token := adminToken(t, gdb, h, `{"jz.bm.access_courses":1,"jz.bm.access_schedule":1,"jz.bm.access_materials":1}`)
courseID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/courses", token, map[string]any{
"name": "Przedmiot testowy", "form": "seminarium", "semester": 2, "ects": 5, "elective_group": "", "lecturer": "dr X",
}))
var course models.Course
gdb.Take(&course, courseID)
if course.ElectiveGroup != nil || course.Lecturer == nil || course.ECTS == nil || *course.ECTS != 5 {
t.Errorf("course = %+v", course)
}
if rec := adminSend(t, h, http.MethodPost, "/jz/bm/courses", token, map[string]any{"name": "X", "form": "lecture", "semester": 1}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("bad form = %d %s", rec.Code, rec.Body.String())
}
meetingID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/meetings", token, map[string]any{
"number": 1, "starts_on": "2030-10-05", "ends_on": "2030-10-06",
}))
if rec := adminSend(t, h, http.MethodPost, "/jz/bm/meetings", token, map[string]any{"number": 2, "starts_on": "5.10.2030", "ends_on": "2030-10-06"}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "starts_on") {
t.Errorf("bad date = %d %s", rec.Code, rec.Body.String())
}
sessionID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/class_sessions", token, map[string]any{
"course": courseID, "meeting": meetingID, "starts_at": "2030-10-05T06:00:00Z", "ends_at": "2030-10-05T07:30:00Z", "room": "", "is_online": true,
}))
var stored time.Time
gdb.Raw(`SELECT starts_at FROM jz_bm_class_sessions WHERE id = ?`, sessionID).Scan(&stored)
if !stored.Equal(time.Date(2030, 10, 5, 6, 0, 0, 0, time.UTC)) {
t.Errorf("stored starts_at = %v, want 06:00 UTC", stored)
}
var session models.ClassSession
gdb.Take(&session, sessionID)
if session.CourseID == nil || *session.CourseID != courseID || session.MeetingID == nil || *session.MeetingID != meetingID || session.Room != nil || !session.IsOnline {
t.Errorf("session = %+v", session)
}
rec := adminSend(t, h, http.MethodPost, "/jz/bm/class_sessions", token, map[string]any{
"course": courseID, "starts_at": "2030-10-05T08:00:00Z", "ends_at": "2030-10-05T07:00:00Z",
})
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "ends_at") {
t.Errorf("bad ends_at = %d %s", rec.Code, rec.Body.String())
}
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/class_sessions", token, nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Przedmiot testowy") {
t.Errorf("session list = %d %s", rec.Code, rec.Body.String())
}
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/class_sessions/"+strconv.Itoa(int(sessionID)), token, nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "2030-10-05T08:00:00+02:00") {
t.Errorf("session show = %d %s", rec.Code, rec.Body.String())
}
tagID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/tags", token, map[string]any{"name": "Geopolityka", "slug": "geopolityka"}))
materialID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/materials", token, map[string]any{
"title": "Notatka", "type": "notatka", "course": courseID, "tags": []uint{tagID}, "published_at": nil, "body": "# Treść",
}))
var material models.Material
gdb.Preload("Tags").Take(&material, materialID)
if material.PublishedAt != nil || len(material.Tags) != 1 || material.CourseID == nil {
t.Errorf("material = %+v", material)
}
rec = adminSend(t, h, http.MethodPut, "/jz/bm/materials/"+strconv.Itoa(int(materialID)), token, map[string]any{
"title": "Notatka", "type": "notatka", "published_at": "2026-01-15T11:00:00Z",
})
if rec.Code != http.StatusOK {
t.Fatalf("publish = %d %s", rec.Code, rec.Body.String())
}
gdb.Take(&material, materialID)
if material.PublishedAt == nil || !material.PublishedAt.Equal(time.Date(2026, 1, 15, 11, 0, 0, 0, time.UTC)) {
t.Errorf("published_at = %v", material.PublishedAt)
}
// Permissions are per screen group.
gdb.Exec(`UPDATE backend_user_roles SET permissions = '{"jz.bm.access_materials":1}'`)
limited := adminToken2(t, gdb, h)
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/courses", limited, nil); rec.Code != http.StatusForbidden {
t.Errorf("courses without access_courses = %d", rec.Code)
}
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/materials", limited, nil); rec.Code != http.StatusOK {
t.Errorf("materials with access_materials = %d %s", rec.Code, rec.Body.String())
}
}
// adminToken2 signs the existing editor in again, after a role change.
func adminToken2(t *testing.T, gdb *gorm.DB, h http.Handler) string {
t.Helper()
rec := adminSend(t, h, http.MethodPost, "/auth/login", "", map[string]string{"login": "editor", "password": "admin-secret-password"})
var body struct {
Data struct {
AccessToken string `json:"access_token"`
} `json:"data"`
}
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil {
t.Fatalf("admin login = %d %s", rec.Code, rec.Body.String())
}
return body.Data.AccessToken
}
// TestCourseRelationManagersOnUnsavedCourse creates a reading and a class
// session from the course form before the course exists: they wait without
// a course, stay out of the student API, and get the course on its first
// save with the same form session key.
func TestCourseRelationManagersOnUnsavedCourse(t *testing.T) {
app, plugins, gdb := migrated(t)
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
token := adminToken(t, gdb, h, `{"jz.bm.access_courses":1}`)
key := strings.Repeat("k", 40)
send := func(method, path string, body any) *httptest.ResponseRecorder {
t.Helper()
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(method, adminAPI+path, bytes.NewReader(raw))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept-Language", "en")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Session-Key", key)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
readingID := createdID(t, send(http.MethodPost, "/jz/bm/courses/0/relations/readings/records", map[string]any{
"title": "Lektura w toku", "is_required": true,
}))
sessionID := createdID(t, send(http.MethodPost, "/jz/bm/courses/0/relations/sessions/records", map[string]any{
"starts_at": "2030-10-05T06:00:00Z", "ends_at": "2030-10-05T07:30:00Z", "room": "237",
}))
if rec := send(http.MethodPost, "/jz/bm/courses/0/relations/sessions/records", map[string]any{
"starts_at": "2030-10-05T08:00:00Z", "ends_at": "2030-10-05T07:00:00Z",
}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "ends_at") {
t.Errorf("session ending before it starts = %d %s", rec.Code, rec.Body.String())
}
var pending models.ClassSession
gdb.Take(&pending, sessionID)
if pending.CourseID != nil {
t.Fatalf("pending session has course %d", *pending.CourseID)
}
courseID := createdID(t, send(http.MethodPost, "/jz/bm/courses", map[string]any{
"name": "Przedmiot z lekturami", "form": "wyklad", "semester": 1,
}))
var reading models.Reading
gdb.Take(&reading, readingID)
var session models.ClassSession
gdb.Take(&session, sessionID)
if reading.CourseID == nil || *reading.CourseID != courseID || session.CourseID == nil || *session.CourseID != courseID {
t.Errorf("after save: reading course %v, session course %v, want %d", reading.CourseID, session.CourseID, courseID)
}
if !session.StartsAt.Equal(time.Date(2030, 10, 5, 6, 0, 0, 0, time.UTC)) {
t.Errorf("session starts_at = %v", session.StartsAt)
}
}

276
calendar_postgres_test.go Normal file
View File

@@ -0,0 +1,276 @@
package bm_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// send is apiClient.do with a JSON body.
func (c apiClient) send(method, path, body string) (int, map[string]any) {
c.t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
rec := httptest.NewRecorder()
c.h.ServeHTTP(rec, req)
var out map[string]any
if rec.Code != http.StatusNoContent {
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
c.t.Fatalf("%s %s = %d, not JSON: %s", method, path, rec.Code, rec.Body.String())
}
}
return rec.Code, out
}
// fetchICS GETs a feed URL (absolute or a path) without credentials.
func fetchICS(t *testing.T, h http.Handler, url string, header ...string) *httptest.ResponseRecorder {
t.Helper()
path := url
if i := strings.Index(url, "/_bm/"); i >= 0 {
path = url[i:]
}
req := httptest.NewRequest(http.MethodGet, path, nil)
req.RemoteAddr = "198.51.100.7:4000"
for i := 0; i+1 < len(header); i += 2 {
req.Header.Set(header[i], header[i+1])
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func feedURL(t *testing.T, body map[string]any) string {
t.Helper()
u, _ := obj(body["data"])["url"].(string)
if u == "" {
t.Fatalf("no feed url in %v", body)
}
return u
}
func TestCalendarFeedAgainstDatabase(t *testing.T) {
app, plugins, gdb := migrated(t)
seedFixture(t, plugins, "testdata/seed.example.json")
if err := app.Config.Set("jz.bm.public_url", "https://bm.example.test/"); err != nil {
t.Fatal(err)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatalf("Assemble: %v", err)
}
aliceID := createUser(t, gdb, "alice@example.test")
alice := apiClient{t: t, h: h, token: tokenFor(t, aliceID)}
bob := apiClient{t: t, h: h, token: tokenFor(t, createUser(t, gdb, "bob@example.test"))}
guest := apiClient{t: t, h: h}
if code, _ := guest.do("GET", "/_bm/api/v1/calendar-feed"); code != http.StatusUnauthorized {
t.Errorf("guest GET /calendar-feed = %d, want 401", code)
}
if body := alice.ok("GET", "/_bm/api/v1/calendar-feed"); body["data"] != nil {
t.Errorf("feed before creation = %v, want null", body)
}
if code, _ := alice.do("POST", "/_bm/api/v1/calendar-feed/rotate"); code != http.StatusNotFound {
t.Errorf("rotate without a feed = %d, want 404", code)
}
var konw models.Course
gdb.Where("form = ?", "konwersatorium").Take(&konw)
// Creating with defaults.
code, body := alice.send("PUT", "/_bm/api/v1/calendar-feed", `{}`)
if code != http.StatusOK {
t.Fatalf("PUT = %d %v", code, body)
}
data := obj(body["data"])
aliceURL := feedURL(t, body)
if !strings.HasPrefix(aliceURL, "https://bm.example.test/_bm/calendar/") || !strings.HasSuffix(aliceURL, ".ics") || len(aliceURL) != len("https://bm.example.test/_bm/calendar/")+64+4 {
t.Errorf("url = %q", aliceURL)
}
if data["include_meetings"] != true || data["include_deadlines"] != true || data["last_fetched_at"] != nil {
t.Errorf("defaults = %v", data)
}
if ids, ok := data["excluded_course_ids"].([]any); !ok || len(ids) != 0 {
t.Errorf("excluded_course_ids = %#v, want []", data["excluded_course_ids"])
}
// Validation: an unknown course, a non-integer, a non-array, a non-boolean.
for _, bad := range []struct{ body, field string }{
{`{"excluded_course_ids": [999999]}`, "excluded_course_ids.0"},
{`{"excluded_course_ids": [1.5]}`, "excluded_course_ids.0"},
{`{"excluded_course_ids": "1"}`, "excluded_course_ids"},
{`{"include_meetings": "tak"}`, "include_meetings"},
} {
code, body := alice.send("PUT", "/_bm/api/v1/calendar-feed", bad.body)
if code != http.StatusUnprocessableEntity || obj(body["errors"])[bad.field] == nil {
t.Errorf("%s = %d %v, want 422 on %s", bad.body, code, body, bad.field)
}
}
// Updating keeps the token; duplicates are dropped.
idStr := id(float64(konw.ID))
code, body = alice.send("PUT", "/_bm/api/v1/calendar-feed", `{"excluded_course_ids": [`+idStr+`, `+idStr+`], "include_deadlines": false}`)
if code != http.StatusOK || feedURL(t, body) != aliceURL {
t.Fatalf("update = %d %v", code, body)
}
data = obj(body["data"])
if ids := data["excluded_course_ids"].([]any); len(ids) != 1 || id(ids[0]) != idStr || data["include_deadlines"] != false || data["include_meetings"] != true {
t.Errorf("after update = %v", data)
}
// The feed itself: public, with the right headers and content.
rec := fetchICS(t, h, aliceURL)
if rec.Code != http.StatusOK {
t.Fatalf("GET feed = %d %s", rec.Code, rec.Body.String())
}
hdr := rec.Header()
if hdr.Get("Content-Type") != "text/calendar; charset=utf-8" || hdr.Get("Content-Disposition") != `inline; filename="bm.ics"` || hdr.Get("Cache-Control") != "private, max-age=900" {
t.Errorf("headers = %v", hdr)
}
ics := rec.Body.String()
unfolded := strings.ReplaceAll(ics, "\r\n ", "")
if !strings.HasPrefix(ics, "BEGIN:VCALENDAR\r\n") || !strings.HasSuffix(ics, "END:VCALENDAR\r\n") {
t.Errorf("not a calendar: %q", ics)
}
var sessA models.ClassSession
gdb.Where("room = ?", "101").Take(&sessA)
for _, want := range []string{
"UID:session-" + id(float64(sessA.ID)) + "@bm.jakubzych.com",
"DTSTART:20301005T060000Z",
"SUMMARY:Przedmiot przykładowy A – wykład\r\n",
"https://bm.example.test/przedmioty/",
"SUMMARY:1. zjazd\r\n",
"DTSTART;VALUE=DATE:20301005", "DTEND;VALUE=DATE:20301007",
} {
if !strings.Contains(unfolded, want) {
t.Errorf("feed lacks %q:\n%s", want, unfolded)
}
}
for _, unwanted := range []string{"Przedmiot przykładowy B", "Termin:"} {
if strings.Contains(unfolded, unwanted) {
t.Errorf("feed has %q although it is excluded:\n%s", unwanted, unfolded)
}
}
// A revalidation with the ETag is a 304.
if rec2 := fetchICS(t, h, aliceURL, "If-None-Match", hdr.Get("ETag")); rec2.Code != http.StatusNotModified {
t.Errorf("If-None-Match = %d, want 304", rec2.Code)
}
// Without .ics the feed answers too.
if rec := fetchICS(t, h, strings.TrimSuffix(aliceURL, ".ics")); rec.Code != http.StatusOK {
t.Errorf("without .ics = %d", rec.Code)
}
// last_fetched_at is set by the fetch and written at most once a minute.
body = alice.ok("GET", "/_bm/api/v1/calendar-feed")
if obj(body["data"])["last_fetched_at"] == nil {
t.Errorf("last_fetched_at not set: %v", body)
}
var stamped time.Time
gdb.Raw(`SELECT last_fetched_at FROM jz_bm_calendar_feeds WHERE user_id = ?`, aliceID).Scan(&stamped)
gdb.Exec(`UPDATE jz_bm_calendar_feeds SET last_fetched_at = last_fetched_at - interval '30 seconds' WHERE user_id = ?`, aliceID)
fetchICS(t, h, aliceURL)
var again time.Time
gdb.Raw(`SELECT last_fetched_at FROM jz_bm_calendar_feeds WHERE user_id = ?`, aliceID).Scan(&again)
if !again.Equal(stamped.Add(-30 * time.Second)) {
t.Errorf("last_fetched_at rewritten within a minute: %v -> %v", stamped, again)
}
// Feeds are per user: Bob's feed lists what Alice excluded, and his
// settings do not touch hers.
code, body = bob.send("PUT", "/_bm/api/v1/calendar-feed", `{"include_meetings": false}`)
if code != http.StatusOK {
t.Fatalf("bob PUT = %d %v", code, body)
}
bobURL := feedURL(t, body)
if bobURL == aliceURL {
t.Fatal("bob got alice's token")
}
bobICS := strings.ReplaceAll(fetchICS(t, h, bobURL).Body.String(), "\r\n ", "")
if !strings.Contains(bobICS, "Przedmiot przykładowy B") || !strings.Contains(bobICS, "Termin: Termin przykładowy") || strings.Contains(bobICS, ". zjazd") {
t.Errorf("bob's feed:\n%s", bobICS)
}
if data := obj(alice.ok("GET", "/_bm/api/v1/calendar-feed")["data"]); data["include_meetings"] != true || len(data["excluded_course_ids"].([]any)) != 1 {
t.Errorf("alice's feed changed by bob: %v", data)
}
// Rotating: the old URL is gone, the new one works.
code, body = alice.send("POST", "/_bm/api/v1/calendar-feed/rotate", "")
if code != http.StatusOK {
t.Fatalf("rotate = %d %v", code, body)
}
rotated := feedURL(t, body)
if rotated == aliceURL {
t.Error("rotate kept the token")
}
if rec := fetchICS(t, h, aliceURL); rec.Code != http.StatusNotFound {
t.Errorf("old URL after rotate = %d, want 404", rec.Code)
}
if rec := fetchICS(t, h, rotated); rec.Code != http.StatusOK {
t.Errorf("new URL = %d", rec.Code)
}
// Unknown and malformed tokens.
for _, path := range []string{"/_bm/calendar/" + strings.Repeat("0", 64) + ".ics", "/_bm/calendar/nope.ics"} {
if rec := fetchICS(t, h, path); rec.Code != http.StatusNotFound {
t.Errorf("%s = %d, want 404", path, rec.Code)
}
}
// Deleting: 204, idempotent, the URL is gone.
if code, _ := alice.send("DELETE", "/_bm/api/v1/calendar-feed", ""); code != http.StatusNoContent {
t.Errorf("DELETE = %d", code)
}
if code, _ := alice.send("DELETE", "/_bm/api/v1/calendar-feed", ""); code != http.StatusNoContent {
t.Errorf("second DELETE = %d", code)
}
if rec := fetchICS(t, h, rotated); rec.Code != http.StatusNotFound {
t.Errorf("URL after delete = %d", rec.Code)
}
if body := alice.ok("GET", "/_bm/api/v1/calendar-feed"); body["data"] != nil {
t.Errorf("feed after delete = %v", body)
}
// The feed goes with its user.
gdb.Exec(`DELETE FROM users WHERE email = ?`, "bob@example.test")
if n := count(t, gdb, "jz_bm_calendar_feeds"); n != 0 {
t.Errorf("feeds after deleting bob = %d", n)
}
}
func TestCalendarFeedSchema(t *testing.T) {
_, _, gdb := migrated(t)
uid := createUser(t, gdb, "carol@example.test")
exec := func(db *gorm.DB, sql string, args ...any) error { return db.Exec(sql, args...).Error }
if err := exec(gdb, `INSERT INTO jz_bm_calendar_feeds (user_id, token) VALUES (?, 'a')`, uid); err != nil {
t.Fatal(err)
}
var feed models.CalendarFeed
if err := gdb.Where("user_id = ?", uid).Take(&feed).Error; err != nil {
t.Fatal(err)
}
if !feed.IncludeMeetings || !feed.IncludeDeadlines || feed.ExcludedCourseIDs == nil || len(feed.ExcludedCourseIDs) != 0 {
t.Errorf("defaults = %+v", feed)
}
other := createUser(t, gdb, "dave@example.test")
for _, bad := range []struct {
sql string
args []any
}{
{`INSERT INTO jz_bm_calendar_feeds (user_id, token) VALUES (?, 'b')`, []any{uid}},
{`INSERT INTO jz_bm_calendar_feeds (user_id, token) VALUES (?, 'a')`, []any{other}},
{`INSERT INTO jz_bm_calendar_feeds (user_id, token) VALUES (999999, 'c')`, nil},
{`INSERT INTO jz_bm_calendar_feeds (user_id, token, excluded_course_ids) VALUES (?, 'd', '{}')`, []any{other}},
} {
if err := exec(gdb, bad.sql, bad.args...); err == nil {
t.Errorf("accepted: %s", bad.sql)
}
}
}

140
chat.go Normal file
View File

@@ -0,0 +1,140 @@
package bm
import (
"context"
"database/sql"
"errors"
chatclasses "git.golem15.com/golem15/sm-chat-plugin/classes"
chatcontracts "git.golem15.com/golem15/sm-chat-plugin/contracts"
chanclasses "git.golem15.com/golem15/sm-chatchannels-plugin/classes"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gorm.io/gorm"
)
// The chat config keys and their fallbacks (config/config.yaml).
const (
configChatGroup = "jz.bm.chat.group"
configChatModeratorGroup = "jz.bm.chat.moderator_group"
configChatMaxUpload = "jz.bm.chat.max_upload_bytes"
configChatMaxEmbeds = "jz.bm.chat.max_embeds"
defaultChatGroup = "studenci"
defaultChatModeratorGroup = "moderatorzy"
defaultChatMaxUpload = 62914560
defaultChatMaxEmbeds = 3
)
// registerChat makes jz.bm the host of the BM chat: it registers the bm
// context alias on golem15.chat's registry and installs the channel access
// policy. Without golem15.chat it does nothing, so jz.bm keeps working (and
// its tests keep activating) without the chat plugins; jz.bm does not
// Require them.
func (p *Plugin) registerChat(app *backpack.App) error {
if app == nil || !app.HasPlugin("golem15.chat") {
return nil
}
reg, ok := app.Lookup[*chatcontracts.Registry]()
if !ok || reg == nil {
return errors.New("jz.bm: golem15.chat must be listed before jz.bm in summer.yaml")
}
if err := reg.Add(p.ID(), chatcontracts.Registration{Alias: classes.ChatContextType, Loader: p.loadChatContext}); err != nil {
return err
}
if err := p.installChatLimits(app); err != nil {
return err
}
return p.installChatAccess(app)
}
// installChatLimits makes golem15.chat enforce jz.bm.chat.max_upload_bytes
// as the total size of one message's attachments, the value the bootstrap
// advertises to the student app. golem15.chat publishes its service from
// its own database hook, which runs before this one.
func (p *Plugin) installChatLimits(app *backpack.App) error {
return lagoon.OnDatabase(app, func(_ *sql.DB, _ *gorm.DB) error {
svc, ok := app.Lookup[*chatclasses.Service]()
if !ok || svc == nil {
return errors.New("jz.bm: golem15.chat must be listed before jz.bm in summer.yaml")
}
svc.SetMaxMessageBytes(int64(p.chatMaxUploadBytes()))
return nil
})
}
// loadChatContext is the loader of the bm alias. The only context is id 1;
// any other id is unknown, which golem15.chat answers with its not-a-member
// error.
func (p *Plugin) loadChatContext(ctx context.Context, db *gorm.DB, id uint) (chatcontracts.Context, error) {
return classes.ChatContextLoader(p.chatGroup, p.chatModeratorGroup)(ctx, db, id)
}
// installChatAccess installs BM's access policy on golem15.chatchannels'
// channel service. The service is published from chatchannels' own
// database hook, which runs before this one because chatchannels boots
// first; under a database-less boot (tests, route:list) neither runs.
func (p *Plugin) installChatAccess(app *backpack.App) error {
if app == nil || !app.HasPlugin("golem15.chatchannels") {
return nil
}
return lagoon.OnDatabase(app, func(_ *sql.DB, _ *gorm.DB) error {
svc, ok := app.Lookup[*chanclasses.ChannelService]()
if !ok || svc == nil {
return errors.New("jz.bm: golem15.chatchannels must be listed before jz.bm in summer.yaml")
}
svc.SetAccessResolver(classes.NewChatAccess(p.database, p.chatGroup(), nil))
return nil
})
}
// database returns the published application database, or nil.
func (p *Plugin) database() *gorm.DB {
if p.app == nil {
return nil
}
db, _ := p.app.Lookup[*gorm.DB]()
return db
}
// chatGroup is the code of the user group whose members are in the chat.
func (p *Plugin) chatGroup() string {
return p.configString(configChatGroup, defaultChatGroup)
}
// chatModeratorGroup is the code of the user group whose members moderate
// the chat's channels.
func (p *Plugin) chatModeratorGroup() string {
return p.configString(configChatModeratorGroup, defaultChatModeratorGroup)
}
// chatMaxUploadBytes is the total attachment size of one message.
func (p *Plugin) chatMaxUploadBytes() int {
return p.configInt(configChatMaxUpload, defaultChatMaxUpload)
}
// chatMaxEmbeds is the number of entity embeds one message may carry.
func (p *Plugin) chatMaxEmbeds() int {
return p.configInt(configChatMaxEmbeds, defaultChatMaxEmbeds)
}
func (p *Plugin) configString(key, fallback string) string {
if p.app == nil || p.app.Config == nil {
return fallback
}
if v := p.app.Config.String(key); v != "" {
return v
}
return fallback
}
func (p *Plugin) configInt(key string, fallback int) int {
if p.app == nil || p.app.Config == nil {
return fallback
}
if v := p.app.Config.Int(key); v > 0 {
return v
}
return fallback
}

129
checklists_postgres_test.go Normal file
View File

@@ -0,0 +1,129 @@
package bm_test
import (
"encoding/json"
"net/http"
"testing"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// want is apiClient.send that fails unless the status is code.
func (c apiClient) want(code int, method, path, body string) map[string]any {
c.t.Helper()
got, out := c.send(method, path, body)
if got != code {
c.t.Fatalf("%s %s = %d %v, want %d", method, path, got, out, code)
}
return out
}
func TestChecklistsAgainstDatabase(t *testing.T) {
app, plugins, gdb := migrated(t)
seedFixture(t, plugins, "testdata/seed.example.json")
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatalf("Assemble: %v", err)
}
aliceID := createUser(t, gdb, "alice@example.test")
alice := apiClient{t: t, h: h, token: tokenFor(t, aliceID)}
bob := apiClient{t: t, h: h, token: tokenFor(t, createUser(t, gdb, "bob@example.test"))}
const base = "/_bm/api/v1"
var meeting models.Meeting
gdb.Order("number").Take(&meeting)
var reading models.Reading
gdb.Where("course_id IS NOT NULL").Order("id").Take(&reading)
// Create, with validation of the zjazd and unknown fields.
alice.want(http.StatusUnprocessableEntity, "POST", base+"/checklists", `{"title":"X","meeting_id":99999}`)
alice.want(http.StatusUnprocessableEntity, "POST", base+"/checklists", `{"title":"X","user_id":1}`)
alice.want(http.StatusUnprocessableEntity, "POST", base+"/checklists", `{}`)
created := obj(alice.want(http.StatusCreated, "POST", base+"/checklists",
`{"title":"Zjazd 1","meeting_id":`+jsonID(meeting.ID)+`}`)["data"])
cid := id(created["id"])
if items, ok := created["items"].([]any); !ok || len(items) != 0 {
t.Errorf("new checklist items = %v, want []", created["items"])
}
if obj(created["meeting"])["number"] != float64(meeting.Number) {
t.Errorf("meeting = %v", created["meeting"])
}
// Items: a task with an estimate and an item with a reading.
alice.want(http.StatusUnprocessableEntity, "POST", base+"/checklists/"+cid+"/items", `{"title":"X","kind":"film"}`)
alice.want(http.StatusUnprocessableEntity, "POST", base+"/checklists/"+cid+"/items", `{"title":"X","presentation_slug":"nie-ma"}`)
alice.want(http.StatusUnprocessableEntity, "POST", base+"/checklists/"+cid+"/items", `{"title":"X","estimate_minutes":-5}`)
task := obj(alice.want(http.StatusCreated, "POST", base+"/checklists/"+cid+"/items",
`{"title":"Slajdy","estimate_minutes":60,"due_at":"2026-11-07 20:00"}`)["data"])
if task["kind"] != "zadanie" || task["done"] != false {
t.Errorf("task = %v", task)
}
lektura := obj(alice.want(http.StatusCreated, "POST", base+"/checklists/"+cid+"/items",
`{"title":"Lektura","kind":"lektura","reading_id":`+jsonID(reading.ID)+`,"estimate_minutes":30}`)["data"])
if lektura["sort_order"].(float64) <= task["sort_order"].(float64) {
t.Errorf("new item not last: %v after %v", lektura["sort_order"], task["sort_order"])
}
if obj(lektura["reading"])["title"] != reading.Title {
t.Errorf("reading = %v", lektura["reading"])
}
// Bob sees none of it and cannot touch it.
if got := list(bob.ok("GET", base+"/checklists")); len(got) != 0 {
t.Errorf("bob sees %v", got)
}
bob.want(http.StatusNotFound, "GET", base+"/checklists/"+cid, "")
bob.want(http.StatusNotFound, "PATCH", base+"/checklists/"+cid, `{"title":"Mine"}`)
bob.want(http.StatusNotFound, "POST", base+"/checklists/"+cid+"/items", `{"title":"X"}`)
bob.want(http.StatusNotFound, "PUT", base+"/checklist-items/"+id(task["id"])+"/done", "")
bob.want(http.StatusNotFound, "DELETE", base+"/checklist-items/"+id(task["id"]), "")
bobList := obj(bob.want(http.StatusCreated, "POST", base+"/checklists", `{"title":"Bob"}`)["data"])
alice.want(http.StatusUnprocessableEntity, "PATCH", base+"/checklist-items/"+id(task["id"]), `{"checklist_id":`+id(bobList["id"])+`}`)
// Done marks: a task gets done_at, an item with a reading marks the
// reading read, and a reading read in the reading list shows done.
done := obj(alice.ok("PUT", base+"/checklist-items/"+id(task["id"])+"/done")["data"])
if done["done"] != true || done["done_at"] == nil {
t.Errorf("task done = %v", done)
}
alice.ok("PUT", base+"/checklist-items/"+id(lektura["id"])+"/done")
var n int64
gdb.Model(&models.ReadingProgress{}).Where("reading_id = ? AND user_id = ?", reading.ID, aliceID).Count(&n)
if n != 1 {
t.Errorf("reading progress rows = %d, want 1", n)
}
detail := obj(alice.ok("GET", base+"/checklists/"+cid)["data"])
progress := obj(detail["progress"])
if progress["total"] != 2.0 || progress["done"] != 2.0 || progress["percent"] != 100.0 || progress["minutes_left"] != 0.0 || progress["minutes_total"] != 90.0 {
t.Errorf("progress = %v", progress)
}
alice.ok("DELETE", "/_bm/api/v1/readings/"+jsonID(reading.ID)+"/progress")
summary := list(alice.ok("GET", base+"/checklists?meeting="+jsonID(meeting.ID)))
if len(summary) != 1 || obj(summary[0]["progress"])["done"] != 1.0 || obj(summary[0]["progress"])["minutes_left"] != 30.0 || obj(summary[0]["progress"])["percent"] != 66.0 {
t.Errorf("after unread: %v", summary)
}
if summary[0]["items"] != nil {
t.Errorf("list carries items: %v", summary[0]["items"])
}
undone := obj(alice.ok("DELETE", base+"/checklist-items/"+id(task["id"])+"/done")["data"])
if undone["done"] != false {
t.Errorf("task undone = %v", undone)
}
// Patch, the token twin, and delete with cascade.
patched := obj(alice.want(http.StatusOK, "PATCH", base+"/checklist-items/"+id(task["id"]), `{"title":"Slajdy v2","notes":""}`)["data"])
if patched["title"] != "Slajdy v2" || patched["estimate_minutes"] != 60.0 {
t.Errorf("patched = %v", patched)
}
alice.want(http.StatusNoContent, "DELETE", base+"/checklist-items/"+id(task["id"]), "")
alice.want(http.StatusNoContent, "DELETE", base+"/checklists/"+cid, "")
if c := count(t, gdb, "jz_bm_checklist_items"); c != 0 {
t.Errorf("items left = %d", c)
}
alice.want(http.StatusNotFound, "GET", base+"/checklists/"+cid, "")
}
func jsonID(id uint) string {
b, _ := json.Marshal(id)
return string(b)
}

236
classes/calendar.go Normal file
View File

@@ -0,0 +1,236 @@
package classes
import (
"strconv"
"strings"
"time"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// CalendarUIDDomain is the right-hand side of every UID in the feed. It
// stays fixed, whatever host serves the feed, so a calendar that has
// subscribed keeps matching its events.
const CalendarUIDDomain = "bm.jakubzych.com"
// CalendarName is the X-WR-CALNAME of the feed.
const CalendarName = "BM UWr – plan zajęć"
// CalendarOptions selects what a feed lists.
type CalendarOptions struct {
// ExcludedCourseIDs are left out, with their sessions and deadlines.
ExcludedCourseIDs []uint
// IncludeMeetings adds the meetings as all-day events.
IncludeMeetings bool
// IncludeDeadlines adds the deadlines.
IncludeDeadlines bool
// SiteURL is the student app's base URL (no trailing slash), used for the
// course links in the descriptions. Empty leaves the links out.
SiteURL string
}
// CalendarData is what a feed is built from. Sessions need their Course and
// Meeting loaded, deadlines their Course.
type CalendarData struct {
Sessions []models.ClassSession
Meetings []models.Meeting
Deadlines []models.Deadline
}
// formLabels are the Polish names of the course forms in a summary. "inne"
// has none: the course name says enough.
var formLabels = map[string]string{
models.FormWyklad: "wykład",
models.FormCwiczenia: "ćwiczenia",
models.FormKonwersatorium: "konwersatorium",
models.FormSeminarium: "seminarium",
}
// deadlineLead is how long before its due time a deadline event starts:
// most calendars show a zero-length event badly.
const deadlineLead = 30 * time.Minute
// BuildCalendar writes the feed: a VCALENDAR with the class sessions of the
// courses not excluded, then the meetings and the deadlines when included.
// Times are written in UTC, so no VTIMEZONE is needed.
func BuildCalendar(data CalendarData, opt CalendarOptions) []byte {
excluded := make(map[uint]bool, len(opt.ExcludedCourseIDs))
for _, id := range opt.ExcludedCourseIDs {
excluded[id] = true
}
var w ICS
w.Begin("VCALENDAR")
w.Prop("PRODID", "-//jakubzych//BM UWr//PL")
w.Prop("VERSION", "2.0")
w.Prop("CALSCALE", "GREGORIAN")
w.Prop("METHOD", "PUBLISH")
w.Text("X-WR-CALNAME", CalendarName)
w.Prop("X-WR-TIMEZONE", "Europe/Warsaw")
w.Prop("REFRESH-INTERVAL;VALUE=DURATION", "PT6H")
w.Prop("X-PUBLISHED-TTL", "PT6H")
for _, s := range data.Sessions {
if s.CourseID == nil || excluded[*s.CourseID] {
continue
}
writeSession(&w, s, opt.SiteURL)
}
if opt.IncludeMeetings {
for _, m := range data.Meetings {
writeMeeting(&w, m)
}
}
if opt.IncludeDeadlines {
for _, d := range data.Deadlines {
if d.CourseID != nil && excluded[*d.CourseID] {
continue
}
writeDeadline(&w, d)
}
}
w.End("VCALENDAR")
return w.Bytes()
}
func uid(kind string, id uint) string {
return kind + "-" + strconv.FormatUint(uint64(id), 10) + "@" + CalendarUIDDomain
}
// stamp writes DTSTAMP and LAST-MODIFIED from the row's update time, so an
// unchanged row gives the same bytes on every fetch.
func stamp(w *ICS, updated time.Time) {
if updated.IsZero() {
updated = time.Unix(0, 0)
}
w.UTC("DTSTAMP", updated)
w.UTC("LAST-MODIFIED", updated)
}
// SessionSummary is the title of a class session: the course name, the form
// in Polish (none for "inne") and " (online)" for an online session.
func SessionSummary(s models.ClassSession) string {
var b strings.Builder
if s.Course != nil {
b.WriteString(s.Course.Name)
if label := formLabels[s.Course.Form]; label != "" {
b.WriteString(" – ")
b.WriteString(label)
}
} else {
b.WriteString("Zajęcia")
}
if s.IsOnline {
b.WriteString(" (online)")
}
return b.String()
}
func writeSession(w *ICS, s models.ClassSession, siteURL string) {
w.Begin("VEVENT")
w.Prop("UID", uid("session", s.ID))
stamp(w, s.UpdatedAt)
w.Prop("SEQUENCE", "0")
w.UTC("DTSTART", s.StartsAt)
w.UTC("DTEND", s.EndsAt)
w.Text("SUMMARY", SessionSummary(s))
switch {
case s.IsOnline:
w.Text("LOCATION", "online")
case s.Room != nil && strings.TrimSpace(*s.Room) != "":
w.Text("LOCATION", "Koszarowa 3, s. "+strings.TrimSpace(*s.Room)+" (bud. 21 ISMiB)")
}
var lines []string
if s.Course != nil && s.Course.Lecturer != nil && *s.Course.Lecturer != "" {
lines = append(lines, "Prowadzący: "+*s.Course.Lecturer)
}
if s.Meeting != nil {
lines = append(lines, "Zjazd "+strconv.Itoa(s.Meeting.Number))
}
if s.Notes != nil && strings.TrimSpace(*s.Notes) != "" {
lines = append(lines, strings.TrimSpace(*s.Notes))
}
if s.Course != nil && s.Course.ElectiveGroup != nil {
lines = append(lines, "Przedmiot do wyboru")
}
if siteURL != "" {
link := siteURL + "/przedmioty/" + strconv.FormatUint(uint64(*s.CourseID), 10)
lines = append(lines, link)
w.Prop("URL", link)
}
if len(lines) > 0 {
w.Text("DESCRIPTION", strings.Join(lines, "\n"))
}
w.Prop("STATUS", "CONFIRMED")
w.End("VEVENT")
}
// MeetingSummary is the title of a meeting: "3. zjazd (stacjonarny)", with
// the mode read from the start of the notes.
func MeetingSummary(m models.Meeting) string {
out := strconv.Itoa(m.Number) + ". zjazd"
if m.Notes != nil {
notes := strings.ToLower(strings.TrimSpace(*m.Notes))
switch {
case strings.HasPrefix(notes, "online"):
out += " (online)"
case strings.HasPrefix(notes, "stacjonarn"):
out += " (stacjonarny)"
}
}
return out
}
func writeMeeting(w *ICS, m models.Meeting) {
if m.StartsOn.IsZero() {
return
}
// Midnight UTC keeps the calendar date for w.Date.
start := m.StartsOn.Time(nil)
end := m.EndsOn.Time(nil)
if m.EndsOn.IsZero() || end.Before(start) {
end = start
}
w.Begin("VEVENT")
w.Prop("UID", uid("meeting", m.ID))
stamp(w, m.UpdatedAt)
w.Prop("SEQUENCE", "0")
w.Date("DTSTART", start)
// DTEND of an all-day event is exclusive: the day after the last day.
w.Date("DTEND", end.AddDate(0, 0, 1))
w.Text("SUMMARY", MeetingSummary(m))
if m.Notes != nil && strings.TrimSpace(*m.Notes) != "" {
w.Text("DESCRIPTION", strings.TrimSpace(*m.Notes))
}
w.Prop("TRANSP", "TRANSPARENT")
w.End("VEVENT")
}
func writeDeadline(w *ICS, d models.Deadline) {
due := d.DueAt
if due.IsZero() {
return
}
summary := "Termin: " + d.Title
w.Begin("VEVENT")
w.Prop("UID", uid("deadline", d.ID))
stamp(w, d.UpdatedAt)
w.Prop("SEQUENCE", "0")
w.UTC("DTSTART", due.Add(-deadlineLead))
w.UTC("DTEND", due)
w.Text("SUMMARY", summary)
var lines []string
if d.Course != nil {
lines = append(lines, "Przedmiot: "+d.Course.Name)
}
if d.Description != nil && strings.TrimSpace(*d.Description) != "" {
lines = append(lines, strings.TrimSpace(*d.Description))
}
if len(lines) > 0 {
w.Text("DESCRIPTION", strings.Join(lines, "\n"))
}
w.Begin("VALARM")
w.Prop("ACTION", "DISPLAY")
w.Text("DESCRIPTION", summary)
w.Prop("TRIGGER", "-P1D")
w.End("VALARM")
w.End("VEVENT")
}

230
classes/calendar_test.go Normal file
View File

@@ -0,0 +1,230 @@
package classes_test
import (
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
func sp(s string) *string { return &s }
func up(n uint) *uint { return &n }
func calendarFixture() classes.CalendarData {
updated := time.Date(2026, 10, 2, 12, 30, 0, 0, time.UTC)
glob := &models.Course{ID: 1, Name: "Globalizacja i regionalizacja", Form: models.FormWyklad, Lecturer: sp("prof. dr hab. Piotr Mikiewicz")}
hist := &models.Course{ID: 8, Name: "Historia wojen i konfliktów do 1945 roku", Form: models.FormInne, ElectiveGroup: sp("historia-koncepcje")}
konc := &models.Course{ID: 9, Name: "Koncepcje wojny i pokoju – historia i współczesność", Form: models.FormInne, ElectiveGroup: sp("historia-koncepcje")}
m3 := &models.Meeting{ID: 3, Number: 3, StartsOn: day("2026-10-24"), EndsOn: day("2026-10-25"), Notes: sp("stacjonarny (Koszarowa 3, bud. 21)"), UpdatedAt: updated}
m2 := &models.Meeting{ID: 2, Number: 2, StartsOn: day("2026-10-17"), EndsOn: day("2026-10-18"), Notes: sp("online"), UpdatedAt: updated}
return classes.CalendarData{
Sessions: []models.ClassSession{
{ID: 11, CourseID: up(1), Course: glob, MeetingID: up(3), Meeting: m3, StartsAt: ts("2026-10-24T08:00:00+02:00"), EndsAt: ts("2026-10-24T09:30:00+02:00"), Room: sp("237"), Notes: sp("prof. P. Mikiewicz"), UpdatedAt: updated},
{ID: 12, CourseID: up(8), Course: hist, MeetingID: up(3), Meeting: m3, StartsAt: ts("2026-10-25T08:00:00+01:00"), EndsAt: ts("2026-10-25T09:30:00+01:00"), Room: sp("110"), UpdatedAt: updated},
{ID: 13, CourseID: up(9), Course: konc, MeetingID: up(2), Meeting: m2, StartsAt: ts("2026-10-17T10:00:00+02:00"), EndsAt: ts("2026-10-17T11:30:00+02:00"), IsOnline: true, Room: sp("237"), UpdatedAt: updated},
},
Meetings: []models.Meeting{*m2, *m3},
Deadlines: []models.Deadline{
{ID: 21, Title: "Esej; wersja 1, szkic", DueAt: ts("2026-11-30T23:59:00+01:00"), CourseID: up(1), Course: glob, Description: sp("Wysłać\nmailem"), UpdatedAt: updated},
{ID: 22, Title: "Esej z koncepcji", DueAt: ts("2026-12-01T12:00:00+01:00"), CourseID: up(9), Course: konc, UpdatedAt: updated},
{ID: 23, Title: "Ślubowanie", DueAt: ts("2026-10-05T23:59:00+02:00"), UpdatedAt: updated},
},
}
}
// unfold returns the content lines of an ICS stream.
func unfold(t *testing.T, ics []byte) []string {
t.Helper()
s := string(ics)
if !strings.HasSuffix(s, "\r\n") {
t.Fatalf("stream does not end with CRLF")
}
for _, line := range strings.Split(strings.TrimSuffix(s, "\r\n"), "\r\n") {
if len(line) > 75 {
t.Errorf("line of %d octets: %q", len(line), line)
}
}
return strings.Split(strings.TrimSuffix(strings.ReplaceAll(s, "\r\n ", ""), "\r\n"), "\r\n")
}
// events splits the content lines into VEVENTs keyed by UID.
func events(lines []string) map[string][]string {
out := map[string][]string{}
var cur []string
for _, l := range lines {
switch {
case l == "BEGIN:VEVENT":
cur = []string{}
case l == "END:VEVENT":
for _, c := range cur {
if uid, ok := strings.CutPrefix(c, "UID:"); ok {
out[uid] = cur
}
}
cur = nil
case cur != nil:
cur = append(cur, l)
}
}
return out
}
func has(lines []string, want string) bool {
for _, l := range lines {
if l == want {
return true
}
}
return false
}
func TestBuildCalendarHeaderAndBalance(t *testing.T) {
lines := unfold(t, classes.BuildCalendar(calendarFixture(), classes.CalendarOptions{IncludeMeetings: true, IncludeDeadlines: true, SiteURL: "https://bm.jakubzych.com"}))
if lines[0] != "BEGIN:VCALENDAR" || lines[len(lines)-1] != "END:VCALENDAR" {
t.Errorf("first/last lines %q %q", lines[0], lines[len(lines)-1])
}
for _, want := range []string{
"PRODID:-//jakubzych//BM UWr//PL", "VERSION:2.0", "CALSCALE:GREGORIAN", "METHOD:PUBLISH",
"X-WR-CALNAME:BM UWr – plan zajęć", "X-WR-TIMEZONE:Europe/Warsaw",
"REFRESH-INTERVAL;VALUE=DURATION:PT6H", "X-PUBLISHED-TTL:PT6H",
} {
if !has(lines, want) {
t.Errorf("missing %q", want)
}
}
depth := map[string]int{}
for _, l := range lines {
if c, ok := strings.CutPrefix(l, "BEGIN:"); ok {
depth[c]++
}
if c, ok := strings.CutPrefix(l, "END:"); ok {
depth[c]--
}
}
for c, d := range depth {
if d != 0 {
t.Errorf("BEGIN/END of %s off by %d", c, d)
}
}
if n := len(events(lines)); n != 3+2+3 {
t.Errorf("%d events, want 8", n)
}
}
func TestBuildCalendarSessions(t *testing.T) {
ev := events(unfold(t, classes.BuildCalendar(calendarFixture(), classes.CalendarOptions{SiteURL: "https://bm.jakubzych.com"})))
glob := ev["session-11@bm.jakubzych.com"]
for _, want := range []string{
"DTSTART:20261024T060000Z", "DTEND:20261024T073000Z",
"DTSTAMP:20261002T123000Z", "LAST-MODIFIED:20261002T123000Z", "SEQUENCE:0",
"SUMMARY:Globalizacja i regionalizacja – wykład",
`LOCATION:Koszarowa 3\, s. 237 (bud. 21 ISMiB)`,
`DESCRIPTION:Prowadzący: prof. dr hab. Piotr Mikiewicz\nZjazd 3\nprof. P. Mikiewicz\nhttps://bm.jakubzych.com/przedmioty/1`,
} {
if !has(glob, want) {
t.Errorf("session 11 lacks %q:\n%s", want, strings.Join(glob, "\n"))
}
}
// After the DST change Warsaw is UTC+1.
hist := ev["session-12@bm.jakubzych.com"]
if !has(hist, "DTSTART:20261025T070000Z") || !has(hist, "SUMMARY:Historia wojen i konfliktów do 1945 roku") {
t.Errorf("session 12:\n%s", strings.Join(hist, "\n"))
}
if !has(hist, `DESCRIPTION:Zjazd 3\nPrzedmiot do wyboru\nhttps://bm.jakubzych.com/przedmioty/8`) {
t.Errorf("session 12 description:\n%s", strings.Join(hist, "\n"))
}
online := ev["session-13@bm.jakubzych.com"]
if !has(online, "SUMMARY:Koncepcje wojny i pokoju – historia i współczesność (online)") || !has(online, "LOCATION:online") {
t.Errorf("online session:\n%s", strings.Join(online, "\n"))
}
if len(ev) != 3 {
t.Errorf("meetings or deadlines without being asked: %v", ev)
}
}
func TestBuildCalendarExclusions(t *testing.T) {
ev := events(unfold(t, classes.BuildCalendar(calendarFixture(), classes.CalendarOptions{ExcludedCourseIDs: []uint{9}, IncludeDeadlines: true})))
if _, ok := ev["session-13@bm.jakubzych.com"]; ok {
t.Error("a session of an excluded course is listed")
}
if _, ok := ev["deadline-22@bm.jakubzych.com"]; ok {
t.Error("a deadline of an excluded course is listed")
}
for _, uid := range []string{"session-11@bm.jakubzych.com", "session-12@bm.jakubzych.com", "deadline-21@bm.jakubzych.com", "deadline-23@bm.jakubzych.com"} {
if _, ok := ev[uid]; !ok {
t.Errorf("%s is missing", uid)
}
}
// Without a site URL there is no link.
if has(ev["session-11@bm.jakubzych.com"], "URL:https://bm.jakubzych.com/przedmioty/1") {
t.Error("link without a site URL")
}
}
func TestBuildCalendarMeetingsAreAllDay(t *testing.T) {
ev := events(unfold(t, classes.BuildCalendar(calendarFixture(), classes.CalendarOptions{IncludeMeetings: true})))
m3 := ev["meeting-3@bm.jakubzych.com"]
for _, want := range []string{
"DTSTART;VALUE=DATE:20261024", "DTEND;VALUE=DATE:20261026",
"SUMMARY:3. zjazd (stacjonarny)", "TRANSP:TRANSPARENT",
`DESCRIPTION:stacjonarny (Koszarowa 3\, bud. 21)`,
} {
if !has(m3, want) {
t.Errorf("meeting 3 lacks %q:\n%s", want, strings.Join(m3, "\n"))
}
}
if !has(ev["meeting-2@bm.jakubzych.com"], "SUMMARY:2. zjazd (online)") {
t.Errorf("meeting 2: %v", ev["meeting-2@bm.jakubzych.com"])
}
}
func TestBuildCalendarDeadlines(t *testing.T) {
lines := unfold(t, classes.BuildCalendar(calendarFixture(), classes.CalendarOptions{IncludeDeadlines: true}))
d := events(lines)["deadline-21@bm.jakubzych.com"]
for _, want := range []string{
"DTSTART:20261130T222900Z", "DTEND:20261130T225900Z",
`SUMMARY:Termin: Esej\; wersja 1\, szkic`,
`DESCRIPTION:Przedmiot: Globalizacja i regionalizacja\nWysłać\nmailem`,
"BEGIN:VALARM", "ACTION:DISPLAY", "TRIGGER:-P1D", "END:VALARM",
} {
if !has(d, want) {
t.Errorf("deadline lacks %q:\n%s", want, strings.Join(d, "\n"))
}
}
if strings.Contains(strings.Join(lines, "\n"), "VALARM") && has(events(lines)["session-11@bm.jakubzych.com"], "BEGIN:VALARM") {
t.Error("a session has an alarm")
}
}
func TestSummaries(t *testing.T) {
for form, want := range map[string]string{
models.FormWyklad: "X – wykład", models.FormCwiczenia: "X – ćwiczenia", models.FormKonwersatorium: "X – konwersatorium",
models.FormSeminarium: "X – seminarium", models.FormInne: "X",
} {
if got := classes.SessionSummary(models.ClassSession{Course: &models.Course{Name: "X", Form: form}}); got != want {
t.Errorf("%s: %q, want %q", form, got, want)
}
}
if got := classes.MeetingSummary(models.Meeting{Number: 7}); got != "7. zjazd" {
t.Errorf("meeting without notes = %q", got)
}
}
func day(s string) lagoon.Date {
d, err := lagoon.ParseDate(s)
if err != nil {
panic(err)
}
return d
}
func ts(s string) time.Time {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
panic(err)
}
return t
}

208
classes/chat_context.go Normal file
View File

@@ -0,0 +1,208 @@
package classes
import (
"context"
chatcontracts "git.golem15.com/golem15/sm-chat-plugin/contracts"
chancontracts "git.golem15.com/golem15/sm-chatchannels-plugin/contracts"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"gorm.io/gorm"
)
var (
_ chatcontracts.Context = (*ChatContext)(nil)
_ chatcontracts.MessageModerator = (*ChatContext)(nil)
_ chatcontracts.LiveMembership = (*ChatContext)(nil)
_ chancontracts.AccessResolver = (*ChatAccess)(nil)
)
// The BM chat context: one context of type bm with id 1, whose members are
// the members of one user group.
const (
// ChatContextType is the context alias (context_type) jz.bm registers on
// golem15.chat.
ChatContextType = "bm"
// ChatContextID is the id of the one BM chat context.
ChatContextID uint = 1
// ChatGeneralName is the name of the group conversation and its channel.
ChatGeneralName = "ogólny"
// ChatGeneralSlug is the slug of the adopted channel.
ChatGeneralSlug = "ogolny"
// ChatBroadcastChannel is the host channel golem15.chat publishes created
// events to. It must never be empty: an empty host channel silences the
// conversation channels too. No client can subscribe to it, because the
// chat authorizer only admits chat:conversation:{id}.
ChatBroadcastChannel = "chat:context:1"
)
// MemberFunc reports whether userID belongs to the user group with code
// group. IsChatMember is the production check; tests inject their own.
type MemberFunc func(ctx context.Context, db *gorm.DB, userID uint, group string) (bool, error)
// IsChatMember reports whether userID is in the chat group group. No user,
// no group code or no database is never a member.
func IsChatMember(ctx context.Context, db *gorm.DB, userID uint, group string) (bool, error) {
if userID == 0 || group == "" || db == nil {
return false, nil
}
return userclasses.HasGroupCode(ctx, db, userID, group)
}
// IsChatModerator reports whether userID is in the moderator group
// moderatorGroup.
func IsChatModerator(ctx context.Context, db *gorm.DB, userID uint, moderatorGroup string) (bool, error) {
return IsChatMember(ctx, db, userID, moderatorGroup)
}
// ChatMemberIDs lists the ids of the users in group that are not deleted,
// ordered by id. A group code with no group row has no member.
func ChatMemberIDs(ctx context.Context, db *gorm.DB, group string) ([]uint, error) {
ids := []uint{}
if group == "" || db == nil {
return ids, nil
}
err := db.WithContext(ctx).
Table("users_groups").
Joins("JOIN user_groups ON user_groups.id = users_groups.user_group_id").
Joins("JOIN users ON users.id = users_groups.user_id").
Where("user_groups.code = ? AND users.deleted_at IS NULL", group).
Distinct().
Order("users_groups.user_id").
Pluck("users_groups.user_id", &ids).Error
if err != nil {
return nil, err
}
return ids, nil
}
// ChatContext is the golem15.chat context of the BM chat. Membership is the
// user group named by group; nobody oversees other people's chats, so a
// moderator reads no DM and edits no foreign message. Moderators delete
// through CanModerateMessage, in group conversations only.
type ChatContext struct {
db *gorm.DB
group string
moderatorGroup string
isMember MemberFunc
}
// NewChatContext returns the BM chat context over db for the chat group
// code group and the moderator group code moderatorGroup.
func NewChatContext(db *gorm.DB, group, moderatorGroup string) *ChatContext {
return &ChatContext{db: db, group: group, moderatorGroup: moderatorGroup}
}
// WithMembership replaces the group check (IsChatMember) and returns c.
func (c *ChatContext) WithMembership(fn MemberFunc) *ChatContext {
c.isMember = fn
return c
}
func (c *ChatContext) ID() uint { return ChatContextID }
func (c *ChatContext) Type() string { return ChatContextType }
func (c *ChatContext) ChatEnabled() bool { return true }
func (c *ChatContext) GroupName() string { return ChatGeneralName }
func (c *ChatContext) BroadcastChannel() string { return ChatBroadcastChannel }
// CanActFor is the default: a user acts only for themself.
func (c *ChatContext) CanActFor(ctx context.Context, actorID, memberID uint) bool {
return chatcontracts.DefaultCanActFor(ctx, actorID, memberID)
}
// CanOverseeChats is always false. golem15.chat grants an overseer read
// access to every conversation and edits of other people's messages, which
// no BM user gets; moderators delete through a narrower hook.
func (c *ChatContext) CanOverseeChats(context.Context, uint) (bool, error) {
return false, nil
}
// CanModerateMessage is golem15.chat's delete-only moderation hook (D-10):
// a member of the moderator group who is also a chat-group member may
// delete other people's messages in group conversations (# ogólny). In a
// DM the answer is always false, so moderators never act on private
// conversations (D-24). It grants no viewing or editing.
func (c *ChatContext) CanModerateMessage(ctx context.Context, userID uint, conversationType string) (bool, error) {
if conversationType != "group" || userID == 0 || c.moderatorGroup == "" {
return false, nil
}
member, err := c.HasMember(ctx, userID)
if err != nil || !member {
return false, err
}
if c.isMember != nil {
return c.isMember(ctx, c.db, userID, c.moderatorGroup)
}
return IsChatModerator(ctx, c.db, userID, c.moderatorGroup)
}
// RequireLiveMembership is always true: golem15.chat checks HasMember on
// every participant check of the BM chat, so someone taken out of the
// chat group loses # ogólny and their DMs at once, not when their
// participant rows are pruned.
func (c *ChatContext) RequireLiveMembership() bool { return true }
// HasMember reports whether userID is in the chat group.
func (c *ChatContext) HasMember(ctx context.Context, userID uint) (bool, error) {
if userID == 0 || c.group == "" {
return false, nil
}
if c.isMember != nil {
return c.isMember(ctx, c.db, userID, c.group)
}
return IsChatMember(ctx, c.db, userID, c.group)
}
// Members lists the ids of the chat group's users that are not deleted.
func (c *ChatContext) Members(ctx context.Context) ([]uint, error) {
return ChatMemberIDs(ctx, c.db, c.group)
}
// ChatContextLoader is the golem15.chat loader of the bm alias. The only
// context is id 1; any other id is unknown (nil, nil), which golem15.chat
// answers with its not-a-member error. The group codes are read per load,
// so a config change needs no re-registration.
func ChatContextLoader(group, moderatorGroup func() string) chatcontracts.Loader {
return func(_ context.Context, db *gorm.DB, id uint) (chatcontracts.Context, error) {
if id != ChatContextID {
return nil, nil
}
return NewChatContext(db, group(), moderatorGroup()), nil
}
}
// ChatAccess is golem15.chatchannels' access policy for BM: chat-group
// members may access context bm/1 and nothing else, and nobody manages it,
// so no channel is ever created through the channel service.
type ChatAccess struct {
db func() *gorm.DB
group string
isMember MemberFunc
}
// NewChatAccess returns the access policy for the chat group group. db is
// resolved per check; isMember nil means IsChatMember.
func NewChatAccess(db func() *gorm.DB, group string, isMember MemberFunc) *ChatAccess {
if isMember == nil {
isMember = IsChatMember
}
return &ChatAccess{db: db, group: group, isMember: isMember}
}
// CanAccessContext is true only for a chat-group member and context bm/1.
// Any error, or no database, denies.
func (a *ChatAccess) CanAccessContext(ctx context.Context, userID uint, contextType string, contextID uint) bool {
if contextType != ChatContextType || contextID != ChatContextID || userID == 0 || a.group == "" || a.db == nil {
return false
}
db := a.db()
if db == nil {
return false
}
ok, err := a.isMember(ctx, db, userID, a.group)
return err == nil && ok
}
// CanManageContext is always false: nobody creates or edits channels.
func (a *ChatAccess) CanManageContext(context.Context, uint, string, uint) bool {
return false
}

View File

@@ -0,0 +1,139 @@
package classes_test
import (
"context"
"errors"
"testing"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gorm.io/gorm"
)
// members is an injected group check: user 7 is in studenci, user 9 is in
// moderatorzy only, user 13 makes the check fail.
func members(_ context.Context, _ *gorm.DB, userID uint, group string) (bool, error) {
switch {
case userID == 13:
return false, errors.New("database down")
case group == "studenci":
return userID == 7, nil
case group == "moderatorzy":
return userID == 9 || userID == 7, nil
}
return false, nil
}
func TestChatAccess(t *testing.T) {
db := func() *gorm.DB { return &gorm.DB{} }
access := classes.NewChatAccess(db, "studenci", members)
ctx := t.Context()
for _, c := range []struct {
name string
userID uint
contextType string
contextID uint
want bool
}{
{"member of bm/1", 7, "bm", 1, true},
{"other context type", 7, "channel", 1, false},
{"other context id", 7, "bm", 2, false},
{"non-member", 8, "bm", 1, false},
{"moderator only", 9, "bm", 1, false},
{"check fails", 13, "bm", 1, false},
{"no user", 0, "bm", 1, false},
} {
if got := access.CanAccessContext(ctx, c.userID, c.contextType, c.contextID); got != c.want {
t.Errorf("%s: CanAccessContext = %v, want %v", c.name, got, c.want)
}
if access.CanManageContext(ctx, c.userID, c.contextType, c.contextID) {
t.Errorf("%s: CanManageContext = true; nobody creates channels", c.name)
}
}
noDB := classes.NewChatAccess(func() *gorm.DB { return nil }, "studenci", members)
if noDB.CanAccessContext(ctx, 7, "bm", 1) {
t.Error("CanAccessContext without a database = true, want false")
}
nilFunc := classes.NewChatAccess(nil, "studenci", members)
if nilFunc.CanAccessContext(ctx, 7, "bm", 1) {
t.Error("CanAccessContext without a database func = true, want false")
}
noGroup := classes.NewChatAccess(db, "", members)
if noGroup.CanAccessContext(ctx, 7, "bm", 1) {
t.Error("CanAccessContext without a chat group = true, want false")
}
}
func TestChatContext(t *testing.T) {
ctx := t.Context()
c := classes.NewChatContext(&gorm.DB{}, "studenci", "moderatorzy").WithMembership(members)
if c.ID() != classes.ChatContextID || c.ID() != 1 || c.Type() != "bm" {
t.Errorf("context = %s/%d, want bm/1", c.Type(), c.ID())
}
if !c.ChatEnabled() || c.GroupName() != "ogólny" {
t.Errorf("ChatEnabled %v GroupName %q", c.ChatEnabled(), c.GroupName())
}
if c.BroadcastChannel() != "chat:context:1" {
t.Errorf("BroadcastChannel = %q, want chat:context:1", c.BroadcastChannel())
}
for _, id := range []uint{7, 9, 8} {
if ok, err := c.CanOverseeChats(ctx, id); ok || err != nil {
t.Errorf("CanOverseeChats(%d) = %v, %v; nobody oversees", id, ok, err)
}
}
if ok, err := c.HasMember(ctx, 7); !ok || err != nil {
t.Errorf("HasMember(7) = %v, %v, want true", ok, err)
}
if ok, err := c.HasMember(ctx, 9); ok || err != nil {
t.Errorf("HasMember(9) = %v, %v, want false (moderator group only)", ok, err)
}
if ok, _ := c.HasMember(ctx, 0); ok {
t.Error("HasMember(0) = true")
}
if _, err := c.HasMember(ctx, 13); err == nil {
t.Error("HasMember with a failing check returned no error")
}
if !c.RequireLiveMembership() {
t.Error("RequireLiveMembership = false, want true: removal from the chat group must revoke access at once")
}
if !c.CanActFor(ctx, 7, 7) || c.CanActFor(ctx, 7, 8) {
t.Error("CanActFor is not self-only")
}
// Moderators delete other people's messages in group conversations
// (# ogólny) only, and only while they are chat-group members too
// (D-10, D-24).
for _, mc := range []struct {
name string
userID uint
convType string
want bool
}{
{"moderator in group", 7, "group", true},
{"moderator in dm", 7, "dm", false},
{"moderator, unknown type", 7, "", false},
{"non-moderator in group", 8, "group", false},
{"moderator outside the chat group", 9, "group", false},
{"no user", 0, "group", false},
} {
got, err := c.CanModerateMessage(ctx, mc.userID, mc.convType)
if err != nil || got != mc.want {
t.Errorf("%s: CanModerateMessage = %v, %v, want %v", mc.name, got, err, mc.want)
}
}
if _, err := c.CanModerateMessage(ctx, 13, "group"); err == nil {
t.Error("CanModerateMessage with a failing check returned no error")
}
noMods := classes.NewChatContext(&gorm.DB{}, "studenci", "").WithMembership(members)
if ok, err := noMods.CanModerateMessage(ctx, 7, "group"); ok || err != nil {
t.Errorf("CanModerateMessage without a moderator group = %v, %v, want false", ok, err)
}
load := classes.ChatContextLoader(func() string { return "studenci" }, func() string { return "moderatorzy" })
if got, err := load(ctx, &gorm.DB{}, 2); got != nil || err != nil {
t.Errorf("loader(2) = %v, %v, want nil, nil", got, err)
}
got, err := load(ctx, &gorm.DB{}, 1)
if err != nil || got == nil || got.ID() != 1 || got.Type() != "bm" {
t.Errorf("loader(1) = %v, %v, want the bm/1 context", got, err)
}
}

201
classes/chat_sync.go Normal file
View File

@@ -0,0 +1,201 @@
package classes
import (
"context"
"errors"
chatclasses "git.golem15.com/golem15/sm-chat-plugin/classes"
chatmodels "git.golem15.com/golem15/sm-chat-plugin/models"
chanclasses "git.golem15.com/golem15/sm-chatchannels-plugin/classes"
chanmodels "git.golem15.com/golem15/sm-chatchannels-plugin/models"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/lagoon"
"gorm.io/gorm"
)
// chatGeneralLock is the transaction advisory lock that serialises finding
// or creating ogólny, so members bootstrapping at the same moment end with
// one group conversation and one channel.
const chatGeneralLock int64 = 0x6a7a626d63686174
// chatGroupNames are the display names of the default group codes; any
// other code is named after itself.
var chatGroupNames = map[string]string{
"studenci": "Studenci",
"moderatorzy": "Moderatorzy czatu",
}
// chatMembersSQL selects the ids of the users in the group with code ?
// that are not deleted.
const chatMembersSQL = `SELECT DISTINCT users_groups.user_id
FROM users_groups
JOIN user_groups ON user_groups.id = users_groups.user_group_id
JOIN users ON users.id = users_groups.user_id
WHERE user_groups.code = ? AND users.deleted_at IS NULL`
// chatGroupConversationsSQL selects the ids of the group conversations of
// context bm/1 (ogólny). DMs are never listed: their participant rows are
// kept when someone leaves the chat group, so the history comes back when
// they are re-added. Access while they are out is denied by golem15.chat's
// live membership check (ChatContext.RequireLiveMembership).
const chatGroupConversationsSQL = `SELECT id FROM golem15_chat_conversations WHERE context_type = ? AND context_id = ? AND type = ?`
// EnsureChatGroups creates a user group for each code that has none and
// returns how many it created. It never assigns a user to a group: members
// are added by hand in the backend.
func EnsureChatGroups(ctx context.Context, db *gorm.DB, codes ...string) (int64, error) {
if db == nil {
return 0, errors.New("jz.bm: chat groups need a database")
}
var created int64
seen := map[string]bool{}
for _, code := range codes {
if code == "" || seen[code] {
continue
}
seen[code] = true
name := chatGroupNames[code]
if name == "" {
name = code
}
res := db.WithContext(ctx).Exec(`INSERT INTO user_groups (name, code, description, created_at, updated_at)
SELECT ?, ?, ?, NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM user_groups WHERE code = ?)`, name, code, "Czat BM (jz.bm)", code)
if res.Error != nil {
return created, res.Error
}
created += res.RowsAffected
}
return created, nil
}
// EnsureGeneral finds or creates the group conversation of context bm/1
// (golem15.chat GetGroupChat, which also joins actorID) and adopts it as
// the system default channel ogólny, so mentions accrue on it. Adoption is
// idempotent. actorID must be a chat-group member.
func EnsureGeneral(ctx context.Context, db *gorm.DB, chat *chatclasses.Service, channels *chanclasses.ChannelService, actorID uint) (*chatmodels.Conversation, *chanmodels.Channel, error) {
if db == nil || chat == nil || channels == nil {
return nil, nil, errors.New("jz.bm: ogólny needs the database and the chat services")
}
var conv *chatmodels.Conversation
var ch *chanmodels.Channel
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
if err := tx.Exec("SELECT pg_advisory_xact_lock(?)", chatGeneralLock).Error; err != nil {
return err
}
c, err := chat.WithDB(tx).GetGroupChat(ctx, actorID, ChatContextType, ChatContextID)
if err != nil {
return err
}
yes := true
adopted, err := channels.WithDB(tx).AdoptConversation(ctx, ChatContextType, ChatContextID, c.ID, chanclasses.AdoptConversationInput{
Name: ChatGeneralName,
Slug: ChatGeneralSlug,
IsSystem: &yes,
IsDefault: &yes,
})
if err != nil {
return err
}
conv, ch = c, adopted
return nil
})
if err != nil {
return nil, nil, err
}
return conv, ch, nil
}
// FindGeneral returns the group conversation of context bm/1, or nil when
// nobody has opened the chat yet.
func FindGeneral(ctx context.Context, db *gorm.DB) (*chatmodels.Conversation, error) {
var conv chatmodels.Conversation
err := db.WithContext(ctx).
Where("type = ? AND context_type = ? AND context_id = ?", chatmodels.TypeGroup, ChatContextType, ChatContextID).
Order("id").Take(&conv).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &conv, nil
}
// SyncChatParticipants makes ogólny's participants follow the chat group,
// in one transaction: every member missing from ogólny (generalID) joins
// it, and users no longer in the group leave it. DM participant rows are
// kept (a re-added user gets their DMs back; until then golem15.chat's
// live membership check denies access). Nothing is pruned while no group
// with that code exists. It returns how many rows it added and removed.
func SyncChatParticipants(ctx context.Context, db *gorm.DB, generalID uint, group string) (int64, int64, error) {
if db == nil {
return 0, 0, errors.New("jz.bm: chat sync needs a database")
}
if group == "" {
return 0, 0, errors.New("jz.bm: chat sync needs a chat group code")
}
var added, removed int64
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
if generalID != 0 {
res := tx.Exec(`INSERT INTO golem15_chat_participants (conversation_id, user_id, joined_at)
SELECT ?, m.user_id, NOW() FROM (`+chatMembersSQL+`) m
ON CONFLICT (conversation_id, user_id) DO NOTHING`, generalID, group)
if res.Error != nil {
return res.Error
}
added = res.RowsAffected
}
res := tx.Exec(`DELETE FROM golem15_chat_participants
WHERE conversation_id IN (`+chatGroupConversationsSQL+`)
AND user_id NOT IN (`+chatMembersSQL+`)
AND EXISTS (SELECT 1 FROM user_groups WHERE code = ?)`, ChatContextType, ChatContextID, chatmodels.TypeGroup, group, group)
if res.Error != nil {
return res.Error
}
removed = res.RowsAffected
return nil
})
return added, removed, err
}
// PruneChatParticipant removes userID from ogólny (the group
// conversations of context bm/1); their DM rows are kept, as in
// SyncChatParticipants. It runs when someone outside the chat group asks
// for the chat.
func PruneChatParticipant(ctx context.Context, db *gorm.DB, userID uint) error {
if db == nil {
return errors.New("jz.bm: chat prune needs a database")
}
return db.WithContext(ctx).Exec(`DELETE FROM golem15_chat_participants
WHERE user_id = ? AND conversation_id IN (`+chatGroupConversationsSQL+`)`, userID, ChatContextType, ChatContextID, chatmodels.TypeGroup).Error
}
// AssignMissingHandles gives every chat-group member without a handle one
// (golem15.user AssignHandle), so they can be @mentioned, and returns how
// many it assigned.
func AssignMissingHandles(ctx context.Context, db *gorm.DB, group string) (int, error) {
if db == nil {
return 0, errors.New("jz.bm: handles need a database")
}
if group == "" {
return 0, nil
}
var users []usermodels.User
err := db.WithContext(ctx).
Where("id IN ("+chatMembersSQL+")", group).
Where("handle IS NULL OR handle = ''").
Order("id").Find(&users).Error
if err != nil {
return 0, err
}
n := 0
for i := range users {
if err := userclasses.AssignHandle(ctx, db, &users[i]); err != nil {
return n, err
}
n++
}
return n, nil
}

105
classes/ics.go Normal file
View File

@@ -0,0 +1,105 @@
package classes
import (
"bytes"
"strings"
"time"
"unicode/utf8"
)
// ICS writes an iCalendar (RFC 5545) stream: CRLF line endings, content
// lines folded at 75 octets without splitting a UTF-8 sequence, and TEXT
// values escaped. The zero value is ready to use.
type ICS struct {
buf bytes.Buffer
}
// icsLineOctets is the longest content line RFC 5545 allows, not counting
// the CRLF.
const icsLineOctets = 75
// Begin writes BEGIN:<component>.
func (w *ICS) Begin(component string) { w.Line("BEGIN:" + component) }
// End writes END:<component>.
func (w *ICS) End(component string) { w.Line("END:" + component) }
// Prop writes name:value with the value as it is (a value of a type that
// needs no escaping, such as a date, a duration or a URI).
func (w *ICS) Prop(name, value string) { w.Line(name + ":" + value) }
// Text writes name:value with the value escaped as TEXT.
func (w *ICS) Text(name, value string) { w.Line(name + ":" + EscapeText(value)) }
// UTC writes name:<t in UTC>, such as DTSTART:20261003T060000Z.
func (w *ICS) UTC(name string, t time.Time) { w.Prop(name, FormatUTC(t)) }
// Date writes name;VALUE=DATE:<YYYYMMDD> for an all-day value.
func (w *ICS) Date(name string, t time.Time) { w.Prop(name+";VALUE=DATE", t.Format("20060102")) }
// Line writes one content line, folded.
func (w *ICS) Line(line string) {
line = strings.NewReplacer("\r", "", "\n", "").Replace(line)
w.buf.WriteString(FoldLine(line))
w.buf.WriteString("\r\n")
}
// Bytes returns the stream written so far.
func (w *ICS) Bytes() []byte { return w.buf.Bytes() }
// FormatUTC formats t as an RFC 5545 UTC date-time (20261003T060000Z).
func FormatUTC(t time.Time) string { return t.UTC().Format("20060102T150405Z") }
// EscapeText escapes a TEXT value: backslash, semicolon, comma and line
// breaks (as \n). A lone CR is dropped.
func EscapeText(s string) string {
var b strings.Builder
b.Grow(len(s))
s = strings.ReplaceAll(s, "\r\n", "\n")
for _, r := range s {
switch r {
case '\\':
b.WriteString(`\\`)
case ';':
b.WriteString(`\;`)
case ',':
b.WriteString(`\,`)
case '\n':
b.WriteString(`\n`)
case '\r':
default:
b.WriteRune(r)
}
}
return b.String()
}
// FoldLine folds a content line (without its CRLF) so that no physical line
// is longer than 75 octets. Continuation lines start with one space, which
// counts towards their 75 octets; a multi-octet UTF-8 character is never
// split.
func FoldLine(line string) string {
if len(line) <= icsLineOctets {
return line
}
var b strings.Builder
n := 0
for i := 0; i < len(line); {
size := runeBytes(line[i:])
if n+size > icsLineOctets {
b.WriteString("\r\n ")
n = 1
}
b.WriteString(line[i : i+size])
n += size
i += size
}
return b.String()
}
// runeBytes is the length in bytes of the first character of s, also for an
// invalid sequence (one byte).
func runeBytes(s string) int {
_, size := utf8.DecodeRuneInString(s)
return size
}

115
classes/ics_test.go Normal file
View File

@@ -0,0 +1,115 @@
package classes_test
import (
"strings"
"testing"
"time"
"unicode/utf8"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
func TestEscapeText(t *testing.T) {
cases := map[string]string{
"zwykły tekst": "zwykły tekst",
`a\b`: `a\\b`,
"a;b,c": `a\;b\,c`,
"pierwsza\ndruga": `pierwsza\ndruga`,
"windows\r\nkoniec\rcr": `windows\nkonieccr`,
`już \n nie jest znakiem`: `już \\n nie jest znakiem`,
}
for in, want := range cases {
if got := classes.EscapeText(in); got != want {
t.Errorf("EscapeText(%q) = %q, want %q", in, got, want)
}
}
}
// checkFolded checks that a folded line has physical lines of at most 75
// octets, each valid UTF-8, continuation lines starting with a space, and
// that unfolding gives the input back.
func checkFolded(t *testing.T, in, folded string) {
t.Helper()
parts := strings.Split(folded, "\r\n")
for i, p := range parts {
if len(p) > 75 {
t.Errorf("physical line %d has %d octets: %q", i, len(p), p)
}
if !utf8.ValidString(p) {
t.Errorf("physical line %d splits a UTF-8 sequence: %q", i, p)
}
if i > 0 && !strings.HasPrefix(p, " ") {
t.Errorf("continuation line %d does not start with a space: %q", i, p)
}
}
if unfolded := strings.ReplaceAll(folded, "\r\n ", ""); unfolded != in {
t.Errorf("unfolded = %q, want %q", unfolded, in)
}
}
func TestFoldLine(t *testing.T) {
short := "SUMMARY:" + strings.Repeat("a", 67) // exactly 75 octets
if got := classes.FoldLine(short); got != short {
t.Errorf("a 75-octet line was folded: %q", got)
}
long := "SUMMARY:" + strings.Repeat("a", 68)
got := classes.FoldLine(long)
if got != "SUMMARY:"+strings.Repeat("a", 67)+"\r\n a" {
t.Errorf("76-octet line folded as %q", got)
}
checkFolded(t, long, got)
// Two-octet Polish letters at every offset, so a boundary falls inside a
// character at some point; and a three-octet en dash.
for pad := 0; pad < 4; pad++ {
in := "DESCRIPTION:" + strings.Repeat("x", pad) + strings.Repeat("zażółć gęślą jaźń – ", 12)
checkFolded(t, in, classes.FoldLine(in))
}
// Four-octet characters.
emoji := "SUMMARY:" + strings.Repeat("😀", 50)
checkFolded(t, emoji, classes.FoldLine(emoji))
}
func TestICSWriterUsesCRLFAndFolds(t *testing.T) {
var w classes.ICS
w.Begin("VCALENDAR")
w.Text("X-WR-CALNAME", "Bezpieczeństwo międzynarodowe; plan, zjazdy\nwiele linii "+strings.Repeat("ąę", 40))
w.UTC("DTSTART", time.Date(2026, 10, 3, 8, 0, 0, 0, models.Location))
w.Date("DTSTART", time.Date(2026, 10, 24, 0, 0, 0, 0, models.Location))
w.End("VCALENDAR")
out := string(w.Bytes())
if !strings.HasSuffix(out, "END:VCALENDAR\r\n") {
t.Errorf("does not end with END:VCALENDAR CRLF: %q", out)
}
if strings.Contains(strings.ReplaceAll(out, "\r\n", ""), "\n") || strings.Contains(strings.ReplaceAll(out, "\r\n", ""), "\r") {
t.Errorf("bare LF or CR in %q", out)
}
for _, line := range strings.Split(strings.TrimSuffix(out, "\r\n"), "\r\n") {
if len(line) > 75 {
t.Errorf("line of %d octets: %q", len(line), line)
}
}
unfolded := strings.ReplaceAll(out, "\r\n ", "")
for _, want := range []string{
`X-WR-CALNAME:Bezpieczeństwo międzynarodowe\; plan\, zjazdy\nwiele linii ąę`,
"DTSTART:20261003T060000Z\r\n",
"DTSTART;VALUE=DATE:20261024\r\n",
} {
if !strings.Contains(unfolded, want) {
t.Errorf("output lacks %q:\n%s", want, unfolded)
}
}
}
func TestFormatUTC(t *testing.T) {
// Saturday before the DST change (+02:00), Sunday after it (+01:00).
sat := time.Date(2026, 10, 24, 8, 0, 0, 0, models.Location)
sun := time.Date(2026, 10, 25, 8, 0, 0, 0, models.Location)
if got := classes.FormatUTC(sat); got != "20261024T060000Z" {
t.Errorf("Saturday = %s", got)
}
if got := classes.FormatUTC(sun); got != "20261025T070000Z" {
t.Errorf("Sunday = %s", got)
}
}

283
classes/material_index.go Normal file
View File

@@ -0,0 +1,283 @@
package classes
import (
"context"
"errors"
"fmt"
"log/slog"
"regexp"
"slices"
"strconv"
"strings"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/beachcomber"
"git.golem15.com/golem15/summercms/modules/beachcomber/typesense"
"git.golem15.com/golem15/summercms/modules/conga"
"git.golem15.com/golem15/summercms/modules/diary"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/jobs"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// materialSearchKey marks a context whose syncs belong to jz.bm.
type materialSearchKey struct{}
// MarkMaterialSearch returns ctx marked as a jz.bm material sync. The
// app-wide beachcomber Gate (MaterialSearchGate) is on only for a marked
// context, so every jz.bm Sync or Remove passes one.
func MarkMaterialSearch(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, materialSearchKey{}, true)
}
// MaterialSearchGate is the app-wide beachcomber Gate jz.bm installs. The
// Gate sees only (ctx, db), not the model, so it is on only for a context
// marked by MarkMaterialSearch: golem15.chatchannels syncs its messages
// with unmarked contexts, and chat messages and DMs never reach the index.
// The automatic callbacks of material writes are off as well; every jz.bm
// write path syncs explicitly.
func MaterialSearchGate() beachcomber.Gate {
return beachcomber.GateFunc(func(ctx context.Context, _ *gorm.DB) bool {
return ctx != nil && ctx.Value(materialSearchKey{}) != nil
})
}
// MaterialSearchWindow is how many engine candidates one search re-gates in
// SQL. The list counts and pages over the gated rows, so a page never
// depends on how the engine paged.
const MaterialSearchWindow = typesense.MaxPerPage
// MaterialQueryBy are the document fields a query is matched against, and
// MaterialQueryWeights their weights in the same order: the title over the
// tags, the source and the course, then the body, the link and file text.
var (
MaterialQueryBy = []string{"title", "tags", "source", "course", "url", "body", "file_texts"}
MaterialQueryWeights = []int{6, 4, 3, 3, 1, 2, 1}
)
// materialHighlightFields are the fields snippets are cut from.
var materialHighlightFields = []string{"body", "file_texts"}
// ErrSearchUnavailable is returned by Search when the engine is not
// configured or the search failed. The API answers it with a 503.
var ErrSearchUnavailable = errors.New("jz.bm: search is unavailable")
// MaterialSearch is one material search: the query text and the validated
// filters of the list.
type MaterialSearch struct {
Q string
CourseID uint
MeetingID uint
Type string
Tag string
}
// MaterialCandidates are the engine's answer: the candidate ids in rank
// order and the Hit of each. Both are candidates only: the caller re-gates
// the ids in SQL and reads the Hit of a row only once SQL returned it.
// Highlights reports whether the engine was asked for snippets.
type MaterialCandidates struct {
IDs []uint
Hits map[uint]beachcomber.Hit
Highlights bool
}
// MaterialIndexer searches the materials index and keeps it current. A nil
// *MaterialIndexer is valid: Search answers ErrSearchUnavailable and the
// syncs do nothing.
type MaterialIndexer struct {
// Service returns the app's beachcomber service, or nil.
Service func() *beachcomber.Service
// Log is where failures are logged; nil means slog.Default.
Log *slog.Logger
// Enqueue inserts a background job, inside tx when tx is in a
// transaction. Nil means jobs are not queued.
Enqueue func(ctx context.Context, tx *gorm.DB, args pact.JobArgs) error
}
// NewMaterialIndexer returns the indexer of app. The service is resolved on
// each call, so it may be built after the indexer.
func NewMaterialIndexer(app *backpack.App) *MaterialIndexer {
return &MaterialIndexer{
Service: func() *beachcomber.Service {
if app == nil {
return nil
}
svc, err := beachcomber.From(app)
if err != nil {
return nil
}
return svc
},
Log: diary.For("jz.bm"),
Enqueue: func(ctx context.Context, tx *gorm.DB, args pact.JobArgs) error {
m, err := conga.From(app)
if err != nil {
return err
}
return m.Enqueue(ctx, tx, args, conga.EnqueueOpts{})
},
}
}
// QueueExtract enqueues the file text job of material id inside tx, so the
// job exists only when the attach commits. The job extracts the text of the
// material's new PDFs and then syncs its document. A failure is logged and
// not returned: an attach never fails because of the job, and
// bm:materials-reindex backfills the text.
func (ix *MaterialIndexer) QueueExtract(ctx context.Context, tx *gorm.DB, id uint) {
if ix == nil || ix.Enqueue == nil || id == 0 {
return
}
if err := ix.Enqueue(ctx, tx, jobs.ExtractMaterialTextArgs{MaterialID: id}); err != nil {
ix.log().Warn("jz.bm: could not queue the file text job", "material_id", id, "err", err)
}
}
func (ix *MaterialIndexer) service() *beachcomber.Service {
if ix == nil || ix.Service == nil {
return nil
}
return ix.Service()
}
func (ix *MaterialIndexer) log() *slog.Logger {
if ix == nil || ix.Log == nil {
return slog.Default()
}
return ix.Log
}
// Search asks the engine for up to MaterialSearchWindow candidates of req.
// It answers ErrSearchUnavailable (wrapping the cause) when the service or
// its engine is missing, the engine is not configured or the call fails.
// The query text is never logged.
func (ix *MaterialIndexer) Search(ctx context.Context, req MaterialSearch) (MaterialCandidates, error) {
svc := ix.service()
if svc == nil {
return MaterialCandidates{}, fmt.Errorf("%w: no search service", ErrSearchUnavailable)
}
engine := svc.Engine()
if engine == nil || !engine.Configured() {
return MaterialCandidates{}, fmt.Errorf("%w: the search engine is not configured", ErrSearchUnavailable)
}
q := beachcomber.Query{
Q: req.Q,
QueryBy: MaterialQueryBy,
QueryByWeights: MaterialQueryWeights,
FilterBy: materialFilterBy(req),
SortBy: "_text_match:desc,published_at:desc",
Page: 1,
PerPage: MaterialSearchWindow,
ExcludeFields: []string{"body", "file_texts"},
}
highlights := beachcomber.SupportsHighlights(engine)
if highlights {
q.Highlight = &beachcomber.Highlight{Fields: materialHighlightFields, AffixTokens: 12, MaxSnippetsPerArray: 1}
}
res, err := beachcomber.SearchPage(ctx, engine, svc.IndexName(&models.Material{}), q)
if err != nil {
ix.log().Warn("jz.bm: material search failed", "err", err)
return MaterialCandidates{}, fmt.Errorf("%w: %w", ErrSearchUnavailable, err)
}
out := MaterialCandidates{IDs: make([]uint, 0, len(res.IDs)), Hits: make(map[uint]beachcomber.Hit, len(res.IDs)), Highlights: highlights}
for i, raw := range res.IDs {
n, err := strconv.ParseUint(raw, 10, 64)
if err != nil || n == 0 {
continue
}
id := uint(n)
if _, seen := out.Hits[id]; seen {
continue
}
out.IDs = append(out.IDs, id)
hit := beachcomber.Hit{ID: raw}
if i < len(res.Hits) {
hit = res.Hits[i]
}
out.Hits[id] = hit
}
return out, nil
}
// materialTagSlug is the shape of a tag slug the engine filter may carry.
var materialTagSlug = regexp.MustCompile(`^[a-z0-9-]{1,100}$`)
// materialFilterBy narrows the engine's candidates to the list filters. It
// is built only from parsed integers, an enumerated type and a tag that is
// a plain slug; any other value is left out and applied by SQL alone, which
// applies every filter anyway.
func materialFilterBy(req MaterialSearch) string {
var parts []string
if req.CourseID != 0 {
parts = append(parts, "course_id:="+strconv.FormatUint(uint64(req.CourseID), 10))
}
if req.MeetingID != 0 {
parts = append(parts, "meeting_id:="+strconv.FormatUint(uint64(req.MeetingID), 10))
}
if slices.Contains(models.MaterialTypes, req.Type) {
parts = append(parts, "type:=`"+req.Type+"`")
}
if materialTagSlug.MatchString(req.Tag) {
parts = append(parts, "tag_slugs:=`"+req.Tag+"`")
}
return strings.Join(parts, " && ")
}
// Sync upserts the document of material id now. A failure is logged with
// the id and never returned: a write never fails because of the index.
func (ix *MaterialIndexer) Sync(ctx context.Context, db *gorm.DB, id uint) {
ix.run(ctx, db, id, false)
}
// Remove deletes the document of material id now, logging a failure like
// Sync.
func (ix *MaterialIndexer) Remove(ctx context.Context, db *gorm.DB, id uint) {
ix.run(ctx, db, id, true)
}
// SyncAfterCommit runs Sync once tx commits; with a nil tx, or outside a
// transaction, it runs at once.
func (ix *MaterialIndexer) SyncAfterCommit(ctx context.Context, tx *gorm.DB, id uint) {
ix.afterCommit(ctx, tx, id, false)
}
// RemoveAfterCommit runs Remove once tx commits, like SyncAfterCommit.
func (ix *MaterialIndexer) RemoveAfterCommit(ctx context.Context, tx *gorm.DB, id uint) {
ix.afterCommit(ctx, tx, id, true)
}
func (ix *MaterialIndexer) afterCommit(ctx context.Context, tx *gorm.DB, id uint, remove bool) {
if ix == nil || id == 0 {
return
}
if tx == nil {
ix.run(ctx, nil, id, remove)
return
}
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, db *gorm.DB) {
ix.run(ctx, db, id, remove)
})
}
func (ix *MaterialIndexer) run(ctx context.Context, db *gorm.DB, id uint, remove bool) {
svc := ix.service()
if svc == nil || id == 0 {
return
}
ctx = MarkMaterialSearch(ctx)
var err error
if remove {
err = svc.Remove(ctx, db, &models.Material{ID: id})
} else {
err = svc.Sync(ctx, db, &models.Material{ID: id})
}
if err != nil {
ix.log().Warn("jz.bm: material index sync failed", "material_id", id, "remove", remove, "err", err)
}
}

View File

@@ -0,0 +1,183 @@
package classes_test
import (
"bytes"
"context"
"errors"
"log/slog"
"net/http"
"slices"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/internal/searchtest"
"git.golem15.com/jakub/sm-bm-plugin/jobs"
"gorm.io/gorm"
)
func TestMaterialSearchGate(t *testing.T) {
gate := classes.MaterialSearchGate()
if !gate.Enabled(classes.MarkMaterialSearch(context.Background()), nil) {
t.Error("a marked context is off")
}
if gate.Enabled(context.Background(), nil) {
t.Error("an unmarked context (a chat message sync) is on")
}
}
func TestMaterialSearchRequest(t *testing.T) {
t.Run("unavailable", materialSearchUnavailable)
stub := &searchtest.Stub{Hits: []searchtest.Hit{
{ID: "12", Field: "body", Snippet: "o " + searchtest.HighlightStart + "globalizacji" + searchtest.HighlightEnd + " dziś"},
{ID: "abc"},
{ID: "0"},
{ID: "5"},
}}
ix := classes.NewMaterialIndexer(searchtest.App(t, searchtest.Start(t, stub)...))
got, err := ix.Search(context.Background(), classes.MaterialSearch{Q: "globalizacja", CourseID: 7, MeetingID: 3, Type: "pdf", Tag: "globalizacja"})
if err != nil {
t.Fatalf("Search: %v", err)
}
searches := stub.Searches()
if len(searches) != 1 {
t.Fatalf("searches = %d, want 1", len(searches))
}
q := searches[0].Query
want := map[string]string{
"q": "globalizacja",
"query_by": "title,tags,source,course,url,body,file_texts",
"query_by_weights": "6,4,3,3,1,2,1",
"filter_by": "course_id:=7 && meeting_id:=3 && type:=`pdf` && tag_slugs:=`globalizacja`",
"sort_by": "_text_match:desc,published_at:desc",
"page": "1",
"per_page": "250",
"exclude_fields": "body,file_texts",
"highlight_fields": "body,file_texts",
}
for k, v := range want {
if q.Get(k) != v {
t.Errorf("%s = %q, want %q", k, q.Get(k), v)
}
}
if !slices.Equal(got.IDs, []uint{12, 5}) {
t.Errorf("ids = %v, want [12 5]", got.IDs)
}
if !got.Highlights {
t.Error("Highlights is false against the typesense engine")
}
if h := got.Hits[12]; len(h.Highlights) != 1 || h.Highlights[0].Field != "body" {
t.Errorf("hit 12 = %+v", h)
} else if segs := h.Highlights[0].Segments; len(segs) != 3 || segs[1].Text != "globalizacji" || !segs[1].Match {
t.Errorf("hit 12 segments = %+v", segs)
}
if _, ok := got.Hits[5]; !ok {
t.Error("hit 5 is missing")
}
if len(got.Hits) != 2 {
t.Errorf("hits = %v, want only 12 and 5", got.Hits)
}
// A tag that is not a plain slug and an unknown type stay out of the
// engine filter; SQL applies them.
if _, err := ix.Search(context.Background(), classes.MaterialSearch{Q: "xx", Tag: "x`y", Type: "exe"}); err != nil {
t.Fatal(err)
}
searches = stub.Searches()
if f := searches[len(searches)-1].Query.Get("filter_by"); f != "" {
t.Errorf("filter_by = %q, want empty", f)
}
if _, err := ix.Search(context.Background(), classes.MaterialSearch{Q: "xx", Tag: "zła-Wielka"}); err != nil {
t.Fatal(err)
}
searches = stub.Searches()
if f := searches[len(searches)-1].Query.Get("filter_by"); strings.Contains(f, "tag_slugs") {
t.Errorf("filter_by = %q carries a tag that is not a slug", f)
}
}
// materialSearchUnavailable runs under TestMaterialSearchRequest.
func materialSearchUnavailable(t *testing.T) {
// No key: the engine is not configured and nothing is sent.
stub := &searchtest.Stub{}
env := searchtest.Start(t, stub)
noKey := slices.DeleteFunc(slices.Clone(env), func(s string) bool { return strings.Contains(s, "API_KEY") })
ix := classes.NewMaterialIndexer(searchtest.App(t, noKey...))
if _, err := ix.Search(context.Background(), classes.MaterialSearch{Q: "xx"}); !errors.Is(err, classes.ErrSearchUnavailable) {
t.Errorf("unconfigured engine: err = %v, want ErrSearchUnavailable", err)
}
if n := len(stub.Requests()); n != 0 {
t.Errorf("unconfigured engine sent %d requests", n)
}
failing := &searchtest.Stub{Status: http.StatusInternalServerError}
ix = classes.NewMaterialIndexer(searchtest.App(t, searchtest.Start(t, failing)...))
if _, err := ix.Search(context.Background(), classes.MaterialSearch{Q: "xx"}); !errors.Is(err, classes.ErrSearchUnavailable) {
t.Errorf("failing engine: err = %v, want ErrSearchUnavailable", err)
}
var none *classes.MaterialIndexer
if _, err := none.Search(context.Background(), classes.MaterialSearch{Q: "xx"}); !errors.Is(err, classes.ErrSearchUnavailable) {
t.Errorf("nil indexer: err = %v, want ErrSearchUnavailable", err)
}
none.Sync(context.Background(), nil, 1)
none.RemoveAfterCommit(context.Background(), nil, 1)
}
func TestMaterialQueueExtract(t *testing.T) {
ctx := context.Background()
// A nil indexer, or one without Enqueue, is a no-op.
var none *classes.MaterialIndexer
none.QueueExtract(ctx, nil, 3)
(&classes.MaterialIndexer{}).QueueExtract(ctx, nil, 3)
var logs bytes.Buffer
var got []pact.JobArgs
var txs []*gorm.DB
ix := &classes.MaterialIndexer{
Log: slog.New(slog.NewTextHandler(&logs, nil)),
Enqueue: func(_ context.Context, tx *gorm.DB, args pact.JobArgs) error {
got = append(got, args)
txs = append(txs, tx)
return nil
},
}
tx := &gorm.DB{}
ix.QueueExtract(ctx, tx, 12)
ix.QueueExtract(ctx, tx, 0)
if len(got) != 1 {
t.Fatalf("enqueued %d jobs, want 1 (id 0 queues nothing)", len(got))
}
args, ok := got[0].(jobs.ExtractMaterialTextArgs)
if !ok || args.MaterialID != 12 || args.Kind() != "jz.bm.extract_material_text" {
t.Errorf("args = %#v, want ExtractMaterialTextArgs{12} of kind jz.bm.extract_material_text", got[0])
}
if txs[0] != tx {
t.Error("the job was not enqueued in the given transaction")
}
if logs.Len() != 0 {
t.Errorf("a successful enqueue logged %q", logs.String())
}
// A failing Enqueue is logged with the material id and not returned.
ix.Enqueue = func(context.Context, *gorm.DB, pact.JobArgs) error { return errors.New("river is down") }
ix.QueueExtract(ctx, tx, 12)
if out := logs.String(); !strings.Contains(out, "could not queue the file text job") || !strings.Contains(out, "material_id=12") || !strings.Contains(out, "river is down") {
t.Errorf("log = %q, want the failure with the material id", out)
}
// The indexer of an app resolves conga at call time; without an app the
// enqueue fails and is only logged.
logs.Reset()
app := classes.NewMaterialIndexer(nil)
if app.Enqueue == nil {
t.Fatal("NewMaterialIndexer left Enqueue nil")
}
app.Log = slog.New(slog.NewTextHandler(&logs, nil))
app.QueueExtract(ctx, nil, 5)
if !strings.Contains(logs.String(), "material_id=5") {
t.Errorf("log = %q, want the failed enqueue logged", logs.String())
}
}

View File

@@ -0,0 +1,92 @@
package classes
import (
"context"
"log/slog"
"regexp"
"strconv"
"git.golem15.com/golem15/summercms/modules/lighthouse"
"gorm.io/gorm"
)
// The live heads-up of a material's revision (D-20): an open editor learns
// that a newer revision was saved before its own save, which still meets
// the 409. Only ids and the revision number travel on the channel, never
// content.
const (
// MaterialsNamespace is the realtime namespace jz.bm owns.
MaterialsNamespace = "materials"
// MaterialRevisedEvent is the event published after a content write.
MaterialRevisedEvent = "updated.jz.bm.material"
)
// materialChannelRE is the only accepted form of a material channel:
// lighthouse.ChannelID reads segments with a PHP-style cast, which would
// take "materials:5abc" for material 5.
var materialChannelRE = regexp.MustCompile(`^materials:[1-9][0-9]{0,18}$`)
// MaterialChannel is the channel of material id.
func MaterialChannel(id uint) string {
return MaterialsNamespace + ":" + strconv.FormatUint(uint64(id), 10)
}
// MaterialChannelID returns the material id of a channel of the form
// materials:{id}, and false for any other channel (a presence: prefix, a
// leading zero, trailing characters, a third segment).
func MaterialChannelID(channel string) (uint, bool) {
if !materialChannelRE.MatchString(channel) {
return 0, false
}
n, err := strconv.ParseUint(channel[len(MaterialsNamespace)+1:], 10, strconv.IntSize)
if err != nil || n == 0 {
return 0, false
}
return uint(n), true
}
// MaterialRevised is the payload of MaterialRevisedEvent. The field order
// is fixed so the payload's key order is stable.
type MaterialRevised struct {
MaterialID uint `json:"material_id"`
Revision uint `json:"revision"`
}
// MaterialRevisionNotifier publishes MaterialRevisedEvent after a write
// that bumped a material's revision. A nil notifier, or one without a
// realtime service, publishes nothing.
type MaterialRevisionNotifier struct {
// Realtime is the app's lighthouse service; nil turns the event off.
Realtime *lighthouse.Service
// Log is where enqueue failures are logged; nil means slog.Default.
Log *slog.Logger
}
// Revised enqueues the event of material id at revision on the write's
// transaction tx, so it is published only when that write commits. The
// enqueue runs in a savepoint: a failure rolls back the savepoint only, is
// logged and never fails or loses the write. Without a transaction it does
// nothing.
func (n *MaterialRevisionNotifier) Revised(ctx context.Context, tx *gorm.DB, id, revision uint) {
if n == nil || n.Realtime == nil || tx == nil {
return
}
b := lighthouse.Broadcast{
Channels: []string{MaterialChannel(id)},
Event: MaterialRevisedEvent,
Payload: MaterialRevised{MaterialID: id, Revision: revision},
}
err := tx.Transaction(func(sp *gorm.DB) error {
return n.Realtime.Emit(ctx, sp, b)
})
if err != nil {
n.log().Warn("jz.bm: material revision event not queued", "material_id", id, "revision", revision, "error", err)
}
}
func (n *MaterialRevisionNotifier) log() *slog.Logger {
if n.Log != nil {
return n.Log
}
return slog.Default()
}

View File

@@ -0,0 +1,48 @@
package classes
import (
"context"
"testing"
"git.golem15.com/golem15/summercms/modules/lighthouse"
"gorm.io/gorm"
)
func TestMaterialChannel(t *testing.T) {
for _, id := range []uint{1, 5, 42, 1234567890} {
ch := MaterialChannel(id)
got, ok := MaterialChannelID(ch)
if !ok || got != id {
t.Errorf("MaterialChannelID(%q) = %d, %v, want %d, true", ch, got, ok, id)
}
}
if got := MaterialChannel(5); got != "materials:5" {
t.Errorf("MaterialChannel(5) = %q", got)
}
for _, ch := range []string{
"materials:5abc",
"materials:05",
"materials:0",
"materials:5:x",
"presence:materials:5",
"materials:",
"materials",
"materials:-5",
"materials: 5",
"materials:99999999999999999999",
"user:5",
"",
} {
if id, ok := MaterialChannelID(ch); ok {
t.Errorf("MaterialChannelID(%q) = %d, true, want a refusal", ch, id)
}
}
}
func TestMaterialRevisionNotifierNil(t *testing.T) {
ctx := context.Background()
var nilNotifier *MaterialRevisionNotifier
nilNotifier.Revised(ctx, &gorm.DB{}, 5, 2)
(&MaterialRevisionNotifier{}).Revised(ctx, &gorm.DB{}, 5, 2)
(&MaterialRevisionNotifier{Realtime: &lighthouse.Service{}}).Revised(ctx, nil, 5, 2)
}

76
classes/material_texts.go Normal file
View File

@@ -0,0 +1,76 @@
package classes
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gocloud.dev/blob"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// EnsureFileTexts extracts the text of every current public PDF of material
// materialID that has no text row yet, and stores one row per file (an
// empty text for a scan or a broken PDF, so it is not retried). It returns
// how many rows it added. ErrPDFToolMissing stops the loop and is returned
// as is, so callers can match it; a blob, extraction or insert error is
// returned wrapped with the file id. It runs only in the extraction job and
// bm:materials-reindex, never in a request.
func EnsureFileTexts(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, pdf PDFText, materialID uint) (int, error) {
if db == nil {
return 0, fmt.Errorf("jz.bm: no database for the file texts of material %d", materialID)
}
if bucket == nil {
return 0, fmt.Errorf("jz.bm: no uploads bucket for the file texts of material %d", materialID)
}
db = db.WithContext(ctx)
// The conditions of the API's materialFiles, which classes cannot import.
var files []attach.File
err := db.Model(&attach.File{}).
Select("system_files.*").
Joins("LEFT JOIN jz_bm_material_file_texts t ON t.file_id = system_files.id").
Where("system_files.attachment_type = ? AND system_files.attachment_id = ? AND system_files.field = ?",
models.Material{}.MorphName(), strconv.FormatUint(uint64(materialID), 10), models.MaterialFilesField).
Where("system_files.is_public").
Where("(system_files.content_type = 'application/pdf' OR lower(system_files.file_name) LIKE '%.pdf')").
Where("t.file_id IS NULL").
Order("system_files.sort_order NULLS LAST, system_files.id").
Find(&files).Error
if err != nil {
return 0, err
}
added := 0
for _, f := range files {
text, truncated, err := extractBlob(ctx, bucket, pdf, f)
if errors.Is(err, ErrPDFToolMissing) {
return added, err
}
if err != nil {
return added, fmt.Errorf("jz.bm: file %d: %w", f.ID, err)
}
row := models.MaterialFileText{FileID: f.ID, MaterialID: materialID, Text: text, Truncated: truncated, ExtractedAt: time.Now().UTC()}
res := db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "file_id"}}, DoNothing: true}).Create(&row)
if res.Error != nil {
return added, fmt.Errorf("jz.bm: file %d: %w", f.ID, res.Error)
}
if res.RowsAffected > 0 {
added++
}
}
return added, nil
}
// extractBlob runs pdf on the blob of f.
func extractBlob(ctx context.Context, bucket *blob.Bucket, pdf PDFText, f attach.File) (string, bool, error) {
rd, err := bucket.NewReader(ctx, attach.BlobKey(f.DiskName), nil)
if err != nil {
return "", false, err
}
defer rd.Close()
return pdf.Extract(ctx, rd)
}

124
classes/pdftext.go Normal file
View File

@@ -0,0 +1,124 @@
package classes
import (
"context"
"errors"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// ErrPDFToolMissing is returned by Extract when the pdftotext binary is not
// installed (poppler-utils). Nothing is stored then, so a later run
// retries.
var ErrPDFToolMissing = errors.New("jz.bm: pdftotext is not installed")
// PDFText runs pdftotext (poppler-utils) on one PDF. The PDF comes from a
// material manager, so it is untrusted input to a native tool: it runs
// without a shell, from a 0600 temp file in a 0700 directory that is
// removed afterwards, for at most Timeout and with at most MaxBytes of text
// read. It runs only in the extraction job and the reindex command, never in
// a request.
type PDFText struct {
// Bin is the pdftotext binary, looked up in PATH.
Bin string
// Timeout bounds one run.
Timeout time.Duration
// MaxBytes is the most text kept per file.
MaxBytes int
// TempDir is where the PDF is copied for the tool.
TempDir string
}
// DefaultPDFText is pdftotext with a 60 s timeout and 1 MiB of text per
// file, with its temp files under storage/app/tmp in the app's working
// directory (beside the uploads bucket, not a tmpfs /tmp).
func DefaultPDFText() PDFText {
return PDFText{
Bin: "pdftotext",
Timeout: 60 * time.Second,
MaxBytes: 1 << 20,
TempDir: filepath.Join("storage", "app", "tmp"),
}
}
// Extract returns the text of the PDF read from r. A PDF with no text layer
// (a scan) or a broken one makes pdftotext fail; that is not an error: the
// text read so far, usually "", comes back with a nil error. truncated is
// set when the text went over MaxBytes or the run timed out. A missing
// binary is ErrPDFToolMissing; a cancelled ctx is its error.
func (p PDFText) Extract(ctx context.Context, r io.Reader) (string, bool, error) {
bin := p.Bin
if bin == "" {
bin = "pdftotext"
}
dir := p.TempDir
if dir == "" {
dir = os.TempDir()
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", false, err
}
tmp, err := os.CreateTemp(dir, "jz-bm-pdftext-*.pdf")
if err != nil {
return "", false, err
}
path := tmp.Name()
defer os.Remove(path)
if _, err := io.Copy(tmp, r); err != nil {
tmp.Close()
return "", false, err
}
if err := tmp.Close(); err != nil {
return "", false, err
}
runCtx := ctx
if p.Timeout > 0 {
var cancel context.CancelFunc
runCtx, cancel = context.WithTimeout(ctx, p.Timeout)
defer cancel()
}
cmd := exec.CommandContext(runCtx, bin, "-q", "-enc", "UTF-8", path, "-")
// No stdin (the PDF is a path) and stderr is discarded.
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", false, err
}
if err := cmd.Start(); err != nil {
if errors.Is(err, exec.ErrNotFound) {
return "", false, ErrPDFToolMissing
}
return "", false, err
}
limit := p.MaxBytes
if limit <= 0 {
limit = 1 << 20
}
out, _ := io.ReadAll(io.LimitReader(stdout, int64(limit)+1))
truncated := len(out) > limit
if truncated {
out = out[:limit]
// The rest is not wanted; stop the tool instead of draining it.
_ = cmd.Process.Kill()
}
_ = cmd.Wait()
if ctx.Err() != nil {
return "", false, ctx.Err()
}
if runCtx.Err() != nil {
truncated = true
}
return CleanExtractedText(string(out)), truncated, nil
}
// CleanExtractedText removes NUL bytes, which a Postgres TEXT column
// refuses, and invalid UTF-8 (such as a sequence cut at the size cap) from
// text a tool extracted.
func CleanExtractedText(s string) string {
s = strings.ReplaceAll(s, "\x00", "")
return strings.ToValidUTF8(s, "")
}

89
classes/pdftext_test.go Normal file
View File

@@ -0,0 +1,89 @@
package classes_test
import (
"bytes"
"context"
"crypto/rand"
"errors"
"os"
"os/exec"
"strings"
"testing"
"time"
"unicode/utf8"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/internal/pdftest"
)
func TestPDFTextExtract(t *testing.T) {
if _, err := exec.LookPath("pdftotext"); err != nil {
t.Skip("pdftotext is not installed (poppler-utils)")
}
ctx := context.Background()
dir := t.TempDir()
pdf := classes.DefaultPDFText()
pdf.TempDir = dir
if pdf.Bin != "pdftotext" || pdf.Timeout != 60*time.Second || pdf.MaxBytes != 1<<20 {
t.Errorf("DefaultPDFText = %+v, want pdftotext, 60 s, 1 MiB", pdf)
}
doc := pdftest.OnePage("Globalizacja i demokracja")
text, truncated, err := pdf.Extract(ctx, bytes.NewReader(doc))
if err != nil {
t.Fatalf("Extract: %v", err)
}
if !strings.Contains(text, "Globalizacja i demokracja") || truncated {
t.Errorf("Extract = %q truncated %v, want the phrase, not truncated", text, truncated)
}
small := pdf
small.MaxBytes = 5
text, truncated, err = small.Extract(ctx, bytes.NewReader(doc))
if err != nil || !truncated || len(text) > 5 {
t.Errorf("MaxBytes 5: %q truncated %v err %v, want at most 5 bytes and truncated", text, truncated, err)
}
junk := make([]byte, 4096)
_, _ = rand.Read(junk)
text, _, err = pdf.Extract(ctx, bytes.NewReader(junk))
if err != nil || text != "" {
t.Errorf("random bytes: %q err %v, want empty text and no error", text, err)
}
missing := pdf
missing.Bin = "jz-bm-no-such-pdftotext"
if _, _, err := missing.Extract(ctx, bytes.NewReader(doc)); !errors.Is(err, classes.ErrPDFToolMissing) {
t.Errorf("missing binary: err %v, want ErrPDFToolMissing", err)
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Errorf("the temp dir holds %d files after extraction, want none", len(entries))
}
// A temp dir Extract creates itself is private to the app user.
sub := pdf
sub.TempDir = dir + "/sub"
if _, _, err := sub.Extract(ctx, bytes.NewReader(doc)); err != nil {
t.Fatal(err)
}
if info, err := os.Stat(sub.TempDir); err != nil || info.Mode().Perm() != 0o700 {
t.Errorf("created temp dir: %v %v, want mode 0700", info, err)
}
for _, c := range []struct{ in, want string }{
{"plain tekst", "plain tekst"},
{"a\x00b\x00", "ab"},
{"zażółć\xff\xfe gęślą", "zażółć gęślą"},
{"cut \xc5", "cut "},
{"", ""},
} {
got := classes.CleanExtractedText(c.in)
if got != c.want || !utf8.ValidString(got) {
t.Errorf("CleanExtractedText(%q) = %q, want %q", c.in, got, c.want)
}
}
}

557
classes/seed.go Normal file
View File

@@ -0,0 +1,557 @@
package classes
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"slices"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// SeedFile is the JSON document bm:seed reads. Every top-level array is
// optional. Courses carry a seed-local key that class sessions, deadlines
// and readings use to point at them; meetings are referenced by number.
type SeedFile struct {
Meetings []SeedMeeting `json:"meetings"`
Courses []SeedCourse `json:"courses"`
ClassSessions []SeedSession `json:"class_sessions"`
Deadlines []SeedDeadline `json:"deadlines"`
Readings []SeedReading `json:"readings"`
}
// SeedMeeting is one meeting; its identity is Number.
type SeedMeeting struct {
Number int `json:"number"`
StartsOn string `json:"starts_on"`
EndsOn string `json:"ends_on"`
Notes *string `json:"notes"`
}
// SeedCourse is one course; its identity is Name, Form and Semester. Key is
// only a reference inside the file.
type SeedCourse struct {
Key string `json:"key"`
Code *string `json:"code"`
Name string `json:"name"`
Form string `json:"form"`
Lecturer *string `json:"lecturer"`
Semester int `json:"semester"`
ECTS *float64 `json:"ects"`
Assessment *string `json:"assessment"`
ElectiveGroup *string `json:"elective_group"`
Description *string `json:"description"`
SyllabusURL *string `json:"syllabus_url"`
SortOrder int `json:"sort_order"`
}
// SeedSession is one class session; its identity is the course and StartsAt.
// Course is a course key, Meeting an optional meeting number.
type SeedSession struct {
Course string `json:"course"`
Meeting *int `json:"meeting"`
StartsAt string `json:"starts_at"`
EndsAt string `json:"ends_at"`
Room *string `json:"room"`
Kind *string `json:"kind"`
Lecturer *string `json:"lecturer"`
IsOnline bool `json:"is_online"`
Notes *string `json:"notes"`
}
// SeedDeadline is one deadline; its identity is Title and DueAt. Course is
// an optional course key.
type SeedDeadline struct {
Title string `json:"title"`
DueAt string `json:"due_at"`
Course *string `json:"course"`
Kind string `json:"kind"`
Description *string `json:"description"`
}
// SeedReading is one reading; its identity is the course and Title.
type SeedReading struct {
Course string `json:"course"`
Title string `json:"title"`
Author *string `json:"author"`
Source *string `json:"source"`
URL *string `json:"url"`
IsRequired bool `json:"is_required"`
SortOrder int `json:"sort_order"`
}
// SeedCounts counts the rows of one kind a seed created, updated, left
// unchanged or (with SeedOptions.Prune) deleted.
type SeedCounts struct {
Created int
Updated int
Unchanged int
Deleted int
}
// SeedOptions changes how a seed is applied.
type SeedOptions struct {
// Prune deletes the courses of the file's semesters, and the class
// sessions and readings of the file's courses, that the file does not
// list. Meetings and deadlines are never pruned.
Prune bool
// DryRun applies the seed in a transaction that is rolled back, so the
// summary shows what would change and nothing is written.
DryRun bool
}
// errDryRun rolls back a dry-run transaction.
var errDryRun = errors.New("bm:seed: dry run")
func (c *SeedCounts) record(created, changed bool) {
switch {
case created:
c.Created++
case changed:
c.Updated++
default:
c.Unchanged++
}
}
// SeedSummary is the outcome of a seed, per kind.
type SeedSummary struct {
Meetings SeedCounts
Courses SeedCounts
ClassSessions SeedCounts
Deadlines SeedCounts
Readings SeedCounts
// Removed describes each row Prune deleted, for the command output.
Removed []string
}
// Rows returns the summary as table rows: kind, created, updated,
// unchanged, deleted.
func (s SeedSummary) Rows() [][]string {
row := func(name string, c SeedCounts) []string {
return []string{name, fmt.Sprint(c.Created), fmt.Sprint(c.Updated), fmt.Sprint(c.Unchanged), fmt.Sprint(c.Deleted)}
}
return [][]string{
row("meetings", s.Meetings),
row("courses", s.Courses),
row("class_sessions", s.ClassSessions),
row("deadlines", s.Deadlines),
row("readings", s.Readings),
}
}
// ParseSeed decodes a seed document. Unknown fields are an error, so a typo
// in a key never drops data silently.
func ParseSeed(r io.Reader) (*SeedFile, error) {
body, err := io.ReadAll(r)
if err != nil {
return nil, err
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
var f SeedFile
if err := dec.Decode(&f); err != nil {
return nil, fmt.Errorf("bm:seed: %w", err)
}
if dec.More() {
return nil, errors.New("bm:seed: trailing data after the JSON document")
}
return &f, nil
}
// Validate checks the whole document before anything is written: required
// fields, allowed values, dates and times, duplicate identities and that
// every course key and meeting number a record points at exists in the
// file. Each error names the record.
func (f *SeedFile) Validate() error {
var errs []error
add := func(format string, args ...any) { errs = append(errs, fmt.Errorf(format, args...)) }
meetings := map[int]bool{}
for i, m := range f.Meetings {
at := fmt.Sprintf("meetings[%d] (number %d)", i, m.Number)
if m.Number < 1 {
add("%s: number must be a positive integer", at)
}
if meetings[m.Number] {
add("%s: duplicate meeting number", at)
}
meetings[m.Number] = true
start, err1 := models.ParseDate(m.StartsOn)
end, err2 := models.ParseDate(m.EndsOn)
if err1 != nil {
add("%s: starts_on: %v", at, err1)
}
if err2 != nil {
add("%s: ends_on: %v", at, err2)
}
if err1 == nil && err2 == nil && end.Time(nil).Before(start.Time(nil)) {
add("%s: ends_on is before starts_on", at)
}
}
keys := map[string]bool{}
identities := map[string]bool{}
for i, c := range f.Courses {
at := fmt.Sprintf("courses[%d] (key %q)", i, c.Key)
if strings.TrimSpace(c.Key) == "" {
add("%s: key is required", at)
} else if keys[c.Key] {
add("%s: duplicate course key", at)
}
keys[c.Key] = true
if strings.TrimSpace(c.Name) == "" {
add("%s: name is required", at)
}
if !slices.Contains(models.CourseForms, c.Form) {
add("%s: form %q is not one of %s", at, c.Form, strings.Join(models.CourseForms, ", "))
}
if c.Semester < 1 || c.Semester > 4 {
add("%s: semester must be between 1 and 4", at)
}
id := fmt.Sprintf("%s\x00%s\x00%d", c.Name, c.Form, c.Semester)
if identities[id] {
add("%s: another course has the same name, form and semester", at)
}
identities[id] = true
}
sessions := map[string]bool{}
for i, s := range f.ClassSessions {
at := fmt.Sprintf("class_sessions[%d] (course %q, starts_at %s)", i, s.Course, s.StartsAt)
if !keys[s.Course] {
add("%s: unknown course key %q", at, s.Course)
}
if s.Meeting != nil && !meetings[*s.Meeting] {
add("%s: unknown meeting number %d", at, *s.Meeting)
}
start, err1 := models.ParseDateTime(s.StartsAt)
end, err2 := models.ParseDateTime(s.EndsAt)
if err1 != nil {
add("%s: starts_at: %v", at, err1)
}
if err2 != nil {
add("%s: ends_at: %v", at, err2)
}
if err1 == nil && err2 == nil {
if !end.After(start) {
add("%s: ends_at is not after starts_at", at)
}
id := s.Course + "\x00" + start.UTC().String()
if sessions[id] {
add("%s: duplicate session of the course at this time", at)
}
sessions[id] = true
}
}
deadlines := map[string]bool{}
for i, d := range f.Deadlines {
at := fmt.Sprintf("deadlines[%d] (%q)", i, d.Title)
if strings.TrimSpace(d.Title) == "" {
add("%s: title is required", at)
}
if d.Course != nil && !keys[*d.Course] {
add("%s: unknown course key %q", at, *d.Course)
}
if !slices.Contains(models.DeadlineKinds, d.Kind) {
add("%s: kind %q is not one of %s", at, d.Kind, strings.Join(models.DeadlineKinds, ", "))
}
due, err := models.ParseDateTime(d.DueAt)
if err != nil {
add("%s: due_at: %v", at, err)
continue
}
id := d.Title + "\x00" + due.UTC().String()
if deadlines[id] {
add("%s: duplicate deadline (same title and due_at)", at)
}
deadlines[id] = true
}
readings := map[string]bool{}
for i, r := range f.Readings {
at := fmt.Sprintf("readings[%d] (course %q, %q)", i, r.Course, r.Title)
if !keys[r.Course] {
add("%s: unknown course key %q", at, r.Course)
}
if strings.TrimSpace(r.Title) == "" {
add("%s: title is required", at)
}
id := r.Course + "\x00" + r.Title
if readings[id] {
add("%s: duplicate reading of the course", at)
}
readings[id] = true
}
return errors.Join(errs...)
}
// Seed validates f and upserts it in one transaction: meetings by number,
// courses by name, form and semester, class sessions by course and start
// time, deadlines by title and due time, readings by course and title. Rows
// absent from the file are left alone. On any error nothing is written.
func Seed(ctx context.Context, db *gorm.DB, f *SeedFile) (SeedSummary, error) {
return SeedWith(ctx, db, f, SeedOptions{})
}
// SeedWith is Seed with options: pruning rows the file no longer lists and
// dry runs.
func SeedWith(ctx context.Context, db *gorm.DB, f *SeedFile, opts SeedOptions) (SeedSummary, error) {
var sum SeedSummary
if err := f.Validate(); err != nil {
return sum, err
}
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
meetingIDs := map[int]uint{}
for _, in := range f.Meetings {
m := models.Meeting{}
created, changed, err := upsert(tx, &m, clause.Eq{Column: "number", Value: in.Number}, func(m *models.Meeting) {
m.Number = in.Number
m.StartsOn, _ = models.ParseDate(in.StartsOn)
m.EndsOn, _ = models.ParseDate(in.EndsOn)
m.Notes = nz(in.Notes)
})
if err != nil {
return fmt.Errorf("meeting %d: %w", in.Number, err)
}
sum.Meetings.record(created, changed)
meetingIDs[in.Number] = m.ID
}
courseIDs := map[string]uint{}
semesters := map[int]bool{}
for _, in := range f.Courses {
semesters[in.Semester] = true
c := models.Course{}
where := clause.And(
clause.Eq{Column: "name", Value: in.Name},
clause.Eq{Column: "form", Value: in.Form},
clause.Eq{Column: "semester", Value: in.Semester},
)
created, changed, err := upsert(tx, &c, where, func(c *models.Course) {
c.Code = nz(in.Code)
c.Name = in.Name
c.Form = in.Form
c.Lecturer = nz(in.Lecturer)
c.Semester = in.Semester
c.ECTS = in.ECTS
c.Assessment = nz(in.Assessment)
c.ElectiveGroup = nz(in.ElectiveGroup)
c.Description = nz(in.Description)
c.SyllabusURL = nz(in.SyllabusURL)
c.SortOrder = in.SortOrder
})
if err != nil {
return fmt.Errorf("course %q: %w", in.Key, err)
}
sum.Courses.record(created, changed)
courseIDs[in.Key] = c.ID
}
keptSessions := []uint{0}
for _, in := range f.ClassSessions {
start, _ := models.ParseDateTime(in.StartsAt)
s := models.ClassSession{}
where := clause.And(
clause.Eq{Column: "course_id", Value: courseIDs[in.Course]},
clause.Eq{Column: "starts_at", Value: start.UTC()},
)
created, changed, err := upsert(tx, &s, where, func(s *models.ClassSession) {
courseID := courseIDs[in.Course]
s.CourseID = &courseID
s.MeetingID = nil
if in.Meeting != nil {
id := meetingIDs[*in.Meeting]
s.MeetingID = &id
}
end, _ := models.ParseDateTime(in.EndsAt)
setInstant(&s.StartsAt, start)
setInstant(&s.EndsAt, end)
s.Room = nz(in.Room)
s.Kind = nz(in.Kind)
s.Lecturer = nz(in.Lecturer)
s.IsOnline = in.IsOnline
s.Notes = nz(in.Notes)
})
if err != nil {
return fmt.Errorf("class session %s %s: %w", in.Course, in.StartsAt, err)
}
sum.ClassSessions.record(created, changed)
keptSessions = append(keptSessions, s.ID)
}
for _, in := range f.Deadlines {
due, _ := models.ParseDateTime(in.DueAt)
d := models.Deadline{}
where := clause.And(
clause.Eq{Column: "title", Value: in.Title},
clause.Eq{Column: "due_at", Value: due.UTC()},
)
created, changed, err := upsert(tx, &d, where, func(d *models.Deadline) {
d.Title = in.Title
setInstant(&d.DueAt, due)
d.CourseID = nil
if in.Course != nil {
id := courseIDs[*in.Course]
d.CourseID = &id
}
d.Kind = in.Kind
d.Description = nz(in.Description)
})
if err != nil {
return fmt.Errorf("deadline %q: %w", in.Title, err)
}
sum.Deadlines.record(created, changed)
}
keptReadings := []uint{0}
for _, in := range f.Readings {
r := models.Reading{}
where := clause.And(
clause.Eq{Column: "course_id", Value: courseIDs[in.Course]},
clause.Eq{Column: "title", Value: in.Title},
)
created, changed, err := upsert(tx, &r, where, func(r *models.Reading) {
courseID := courseIDs[in.Course]
r.CourseID = &courseID
r.Title = in.Title
r.Author = nz(in.Author)
r.Source = nz(in.Source)
r.URL = nz(in.URL)
r.IsRequired = in.IsRequired
r.SortOrder = in.SortOrder
})
if err != nil {
return fmt.Errorf("reading %q of %s: %w", in.Title, in.Course, err)
}
sum.Readings.record(created, changed)
keptReadings = append(keptReadings, r.ID)
}
if opts.Prune {
if err := prune(tx, &sum, semesters, courseIDs, keptSessions, keptReadings); err != nil {
return err
}
}
if opts.DryRun {
return errDryRun
}
return nil
})
if err != nil && !errors.Is(err, errDryRun) {
return SeedSummary{}, err
}
return sum, nil
}
// prune deletes what the file no longer lists: courses of its semesters
// (their sessions and readings go with them through the foreign keys), then
// the sessions and readings of the kept courses that the seed did not touch.
func prune(tx *gorm.DB, sum *SeedSummary, semesters map[int]bool, courseIDs map[string]uint, keptSessions, keptReadings []uint) error {
kept := []uint{0}
for _, id := range courseIDs {
kept = append(kept, id)
}
sems := []int{}
for sem := range semesters {
sems = append(sems, sem)
}
var courses []models.Course
if len(sems) > 0 {
if err := tx.Where("semester IN ? AND id NOT IN ?", sems, kept).Order("id").Find(&courses).Error; err != nil {
return err
}
}
for _, c := range courses {
var sessions, readings int64
tx.Model(&models.ClassSession{}).Where("course_id = ?", c.ID).Count(&sessions)
tx.Model(&models.Reading{}).Where("course_id = ?", c.ID).Count(&readings)
sum.Removed = append(sum.Removed, fmt.Sprintf("course %q (%s, semester %d) with %d sessions and %d readings", c.Name, c.Form, c.Semester, sessions, readings))
if err := tx.Delete(&models.Course{}, c.ID).Error; err != nil {
return fmt.Errorf("prune course %q: %w", c.Name, err)
}
sum.Courses.Deleted++
sum.ClassSessions.Deleted += int(sessions)
sum.Readings.Deleted += int(readings)
}
var sessions []models.ClassSession
if err := tx.Where("course_id IN ? AND id NOT IN ?", kept, keptSessions).Order("starts_at").Find(&sessions).Error; err != nil {
return err
}
for _, s := range sessions {
sum.Removed = append(sum.Removed, fmt.Sprintf("class session of course %d at %s", s.CourseID, models.FormatDateTime(s.StartsAt)))
if err := tx.Delete(&models.ClassSession{}, s.ID).Error; err != nil {
return fmt.Errorf("prune class session %d: %w", s.ID, err)
}
sum.ClassSessions.Deleted++
}
var readings []models.Reading
if err := tx.Where("course_id IN ? AND id NOT IN ?", kept, keptReadings).Order("id").Find(&readings).Error; err != nil {
return err
}
for _, r := range readings {
sum.Removed = append(sum.Removed, fmt.Sprintf("reading %q of course %d", r.Title, r.CourseID))
if err := tx.Delete(&models.Reading{}, r.ID).Error; err != nil {
return fmt.Errorf("prune reading %d: %w", r.ID, err)
}
sum.Readings.Deleted++
}
return nil
}
// nz returns nil for a missing or blank optional text, as the models'
// BeforeSave hooks store it, so an unchanged row compares equal.
func nz(s *string) *string {
if s == nil || strings.TrimSpace(*s) == "" {
return nil
}
return s
}
// upsert loads the row matching where into row, applies set and writes it:
// an insert when there was no row, an update when set changed a column, and
// nothing otherwise. The comparison is on the row's own fields, before and
// after set, as JSON.
// setInstant sets *dst to t unless it already holds the same instant, so a
// time read back from the database in another zone does not count as a
// change in upsert.
func setInstant(dst *time.Time, t time.Time) {
if !dst.Equal(t) {
*dst = t
}
}
func upsert[T any](tx *gorm.DB, row *T, where clause.Expression, set func(*T)) (created, changed bool, err error) {
res := tx.Clauses(where).Limit(1).Find(row)
if res.Error != nil {
return false, false, res.Error
}
if res.RowsAffected == 0 {
set(row)
return true, false, tx.Create(row).Error
}
before, err := json.Marshal(row)
if err != nil {
return false, false, err
}
set(row)
after, err := json.Marshal(row)
if err != nil {
return false, false, err
}
if bytes.Equal(before, after) {
return false, false, nil
}
return false, true, tx.Save(row).Error
}

117
classes/seed_test.go Normal file
View File

@@ -0,0 +1,117 @@
package classes_test
import (
"os"
"strings"
"testing"
"git.golem15.com/jakub/sm-bm-plugin/classes"
)
func parse(t *testing.T, doc string) *classes.SeedFile {
t.Helper()
f, err := classes.ParseSeed(strings.NewReader(doc))
if err != nil {
t.Fatalf("ParseSeed: %v", err)
}
return f
}
func TestExampleFixtureIsValid(t *testing.T) {
fh, err := os.Open("../testdata/seed.example.json")
if err != nil {
t.Fatal(err)
}
defer fh.Close()
f, err := classes.ParseSeed(fh)
if err != nil {
t.Fatal(err)
}
if err := f.Validate(); err != nil {
t.Fatalf("Validate: %v", err)
}
if len(f.Meetings) != 2 || len(f.Courses) != 3 || len(f.ClassSessions) != 3 || len(f.Deadlines) != 2 || len(f.Readings) != 2 {
t.Errorf("fixture counts = %d %d %d %d %d", len(f.Meetings), len(f.Courses), len(f.ClassSessions), len(f.Deadlines), len(f.Readings))
}
if f.Courses[2].ElectiveGroup == nil || *f.Courses[2].ElectiveGroup != "przyklad-do-wyboru" {
t.Errorf("elective_group = %v", f.Courses[2].ElectiveGroup)
}
}
func TestEmptyDocumentIsValid(t *testing.T) {
if err := parse(t, `{}`).Validate(); err != nil {
t.Errorf("{}: %v", err)
}
}
func TestParseRejectsUnknownFieldsAndTrailingData(t *testing.T) {
for _, doc := range []string{
`{"courses": [{"key": "a", "nmae": "typo"}]}`,
`{"lectures": []}`,
`{} {}`,
`[]`,
`{"meetings": [{"number": "one"}]}`,
} {
if _, err := classes.ParseSeed(strings.NewReader(doc)); err == nil {
t.Errorf("ParseSeed(%s) accepted", doc)
}
}
}
func TestValidateNamesTheRecord(t *testing.T) {
cases := []struct {
doc string
want []string
}{
{`{"class_sessions": [{"course": "ghost", "starts_at": "2030-10-05T08:00:00+02:00", "ends_at": "2030-10-05T09:00:00+02:00"}]}`,
[]string{`class_sessions[0]`, `unknown course key "ghost"`}},
{`{"courses": [{"key": "a", "name": "A", "form": "wyklad", "semester": 1}],
"class_sessions": [{"course": "a", "meeting": 9, "starts_at": "2030-10-05T08:00:00+02:00", "ends_at": "2030-10-05T09:00:00+02:00"}]}`,
[]string{`unknown meeting number 9`}},
{`{"deadlines": [{"title": "X", "due_at": "2030-10-05T08:00:00+02:00", "course": "nope", "kind": "inne"}]}`,
[]string{`deadlines[0] ("X")`, `unknown course key "nope"`}},
{`{"readings": [{"course": "nope", "title": "Book"}]}`,
[]string{`readings[0]`, `unknown course key "nope"`}},
{`{"courses": [{"key": "a", "name": "A", "form": "lecture", "semester": 7}]}`,
[]string{`form "lecture"`, `semester must be between 1 and 4`}},
{`{"courses": [{"key": "a", "name": "A", "form": "wyklad", "semester": 1}, {"key": "a", "name": "A", "form": "wyklad", "semester": 1}]}`,
[]string{`duplicate course key`, `same name, form and semester`}},
{`{"meetings": [{"number": 1, "starts_on": "2030-10-06", "ends_on": "2030-10-05"}, {"number": 1, "starts_on": "05.10.2030", "ends_on": "2030-10-05"}]}`,
[]string{`ends_on is before starts_on`, `duplicate meeting number`, `starts_on`}},
{`{"courses": [{"key": "a", "name": "A", "form": "wyklad", "semester": 1}],
"class_sessions": [{"course": "a", "starts_at": "2030-10-05 10:00", "ends_at": "2030-10-05 09:00"}]}`,
[]string{`ends_at is not after starts_at`}},
{`{"deadlines": [{"title": "", "due_at": "soon", "kind": "deadline"}]}`,
[]string{`title is required`, `due_at`, `kind "deadline"`}},
}
for _, tc := range cases {
err := parse(t, tc.doc).Validate()
if err == nil {
t.Errorf("Validate(%s) passed", tc.doc)
continue
}
for _, want := range tc.want {
if !strings.Contains(err.Error(), want) {
t.Errorf("Validate(%s) = %q, want it to mention %q", tc.doc, err, want)
}
}
}
}
func TestSeedValidatesBeforeTouchingTheDatabase(t *testing.T) {
f := parse(t, `{"readings": [{"course": "ghost", "title": "Book"}]}`)
// A nil database would panic if Seed reached it.
if _, err := classes.Seed(t.Context(), nil, f); err == nil || !strings.Contains(err.Error(), "ghost") {
t.Errorf("Seed = %v, want the unknown course error", err)
}
}
func TestSummaryRows(t *testing.T) {
var s classes.SeedSummary
s.Courses.Created = 2
s.Readings.Unchanged = 1
rows := s.Rows()
if len(rows) != 5 || rows[1][0] != "courses" || rows[1][1] != "2" || rows[4][3] != "1" || len(rows[0]) != 5 {
t.Errorf("Rows = %v", rows)
}
}

192
classes/uploads.go Normal file
View File

@@ -0,0 +1,192 @@
package classes
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"regexp"
"strconv"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/cooler"
)
// Signed one-time upload URLs for material files (D-10, D-12). The owner's
// agent asks for an upload URL over MCP and sends the file with curl, so
// the bytes never pass through MCP. Each plugin signs its own tickets with
// its own label: golem15.presentations has the same design, and the code is
// duplicated on purpose so jz.bm imports neither that plugin nor new
// golem15.user code. A ticket is
//
// base64url(payload) + "." + base64url(HMAC-SHA256(key, uploadLabel + payload))
//
// with payload "<kind>|<target>|<user>|<expiry unix>|<nonce>", the nonce 16
// random bytes in hex. It is valid for UploadTTL and redeemable once:
// issuing stores the payload under the nonce in the app cache, redeeming
// pulls it atomically. A restart of a memory cache forgets every issued
// ticket, so they fail closed.
// uploadLabel separates the upload HMAC from any other use of the key.
const uploadLabel = "jz.bm.upload.v1:"
// uploadCachePrefix is the cache key prefix of issued tickets.
const uploadCachePrefix = "jz.bm.upload:"
// UploadTTL is how long an upload URL is valid.
const UploadTTL = 10 * time.Minute
// uploadTicketMaxLen bounds the ticket text read from a URL.
const uploadTicketMaxLen = 512
var (
// ErrUploadTicket is every refused ticket: malformed, forged, signed
// with another key or label, expired, unknown or already used.
ErrUploadTicket = errors.New("bm: invalid or expired upload ticket")
// ErrUploadKeyMissing means no key to sign upload tickets with (app.key
// is empty): no upload URL is issued.
ErrUploadKeyMissing = errors.New("bm: upload key is not configured")
)
var (
uploadKind = regexp.MustCompile(`^[a-z]{1,20}$`)
uploadNonce = regexp.MustCompile(`^[0-9a-f]{32}$`)
)
// UploadTicket is what a signed upload URL grants: one upload of Kind to
// Target (a material id) by User, until Expires.
type UploadTicket struct {
Kind string
Target uint
User uint
Expires time.Time
Nonce string
}
// payload is the signed text of t.
func (t UploadTicket) payload() string {
return t.Kind + "|" + strconv.FormatUint(uint64(t.Target), 10) + "|" + strconv.FormatUint(uint64(t.User), 10) + "|" + strconv.FormatInt(t.Expires.Unix(), 10) + "|" + t.Nonce
}
// UploadKey is the signing key from the app key: trimmed, nil when empty.
func UploadKey(appKey string) []byte {
if k := strings.TrimSpace(appKey); k != "" {
return []byte(k)
}
return nil
}
func uploadMAC(key []byte, payload string) []byte {
mac := hmac.New(sha256.New, key)
mac.Write([]byte(uploadLabel + payload))
return mac.Sum(nil)
}
// SignUpload signs t. It does not register the ticket; IssueUpload does.
func SignUpload(key []byte, t UploadTicket) (string, error) {
if len(key) == 0 {
return "", ErrUploadKeyMissing
}
payload := t.payload()
return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + base64.RawURLEncoding.EncodeToString(uploadMAC(key, payload)), nil
}
// VerifyUpload checks a ticket's signature and expiry at now. An expiry
// further away than UploadTTL (and a minute of clock skew) is refused too.
// Every failure is ErrUploadTicket.
func VerifyUpload(key []byte, ticket string, now time.Time) (UploadTicket, error) {
if len(key) == 0 || ticket == "" || len(ticket) > uploadTicketMaxLen {
return UploadTicket{}, ErrUploadTicket
}
parts := strings.Split(ticket, ".")
if len(parts) != 2 {
return UploadTicket{}, ErrUploadTicket
}
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return UploadTicket{}, ErrUploadTicket
}
mac, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return UploadTicket{}, ErrUploadTicket
}
if !hmac.Equal(mac, uploadMAC(key, string(payload))) {
return UploadTicket{}, ErrUploadTicket
}
t, ok := parseUploadPayload(string(payload))
if !ok || !now.Before(t.Expires) || t.Expires.Sub(now) > UploadTTL+time.Minute {
return UploadTicket{}, ErrUploadTicket
}
return t, nil
}
func parseUploadPayload(payload string) (UploadTicket, bool) {
fields := strings.Split(payload, "|")
if len(fields) != 5 || !uploadKind.MatchString(fields[0]) || !uploadNonce.MatchString(fields[4]) {
return UploadTicket{}, false
}
target, err := strconv.ParseUint(fields[1], 10, 32)
if err != nil || target == 0 {
return UploadTicket{}, false
}
user, err := strconv.ParseUint(fields[2], 10, 32)
if err != nil || user == 0 {
return UploadTicket{}, false
}
expiry, err := strconv.ParseInt(fields[3], 10, 64)
if err != nil {
return UploadTicket{}, false
}
return UploadTicket{Kind: fields[0], Target: uint(target), User: uint(user), Expires: time.Unix(expiry, 0).UTC(), Nonce: fields[4]}, true
}
// IssueUpload signs a ticket for one upload of kind to target by user,
// valid for UploadTTL from now, and stores its payload in cache under the
// nonce for RedeemUpload. It answers the ticket and its expiry.
func IssueUpload(ctx context.Context, cache cooler.Cache, key []byte, kind string, target, user uint, now time.Time) (string, time.Time, error) {
if len(key) == 0 {
return "", time.Time{}, ErrUploadKeyMissing
}
if cache == nil {
return "", time.Time{}, errors.New("bm: upload cache is not available")
}
if !uploadKind.MatchString(kind) || target == 0 || user == 0 {
return "", time.Time{}, errors.New("bm: invalid upload target")
}
var nonce [16]byte
if _, err := rand.Read(nonce[:]); err != nil {
return "", time.Time{}, err
}
t := UploadTicket{Kind: kind, Target: target, User: user, Expires: now.Add(UploadTTL).Truncate(time.Second).UTC(), Nonce: hex.EncodeToString(nonce[:])}
signed, err := SignUpload(key, t)
if err != nil {
return "", time.Time{}, err
}
if err := cache.Set(ctx, uploadCachePrefix+t.Nonce, []byte(t.payload()), UploadTTL); err != nil {
return "", time.Time{}, err
}
return signed, t.Expires, nil
}
// RedeemUpload verifies ticket and takes it out of cache in one atomic Pull,
// so it works once. A ticket whose cache entry is missing (used, expired or
// forgotten by a restart) or differs from its payload is refused. Every
// failure is ErrUploadTicket.
func RedeemUpload(ctx context.Context, cache cooler.Cache, key []byte, ticket string, now time.Time) (UploadTicket, error) {
t, err := VerifyUpload(key, ticket, now)
if err != nil {
return UploadTicket{}, err
}
if cache == nil {
return UploadTicket{}, ErrUploadTicket
}
raw, found, err := cache.Pull(ctx, uploadCachePrefix+t.Nonce)
if err != nil || !found || string(raw) != t.payload() {
return UploadTicket{}, ErrUploadTicket
}
return t, nil
}

164
classes/uploads_test.go Normal file
View File

@@ -0,0 +1,164 @@
package classes_test
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"strconv"
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/jakub/sm-bm-plugin/classes"
)
// signWith builds a ticket for payload with an explicit label, as another
// plugin (or a forger who knows the format) would.
func signWith(key []byte, label, payload string) string {
mac := hmac.New(sha256.New, key)
mac.Write([]byte(label + payload))
return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func memCache(t *testing.T) cooler.Cache {
t.Helper()
c, err := cooler.NewMemoryCache("test:", 100)
if err != nil {
t.Fatal(err)
}
return c
}
// TestUploadTicket (D-10, D-12) covers the signed one-time upload tickets:
// the HMAC under the jz.bm.upload.v1: label, the expiry and the single use.
func TestUploadTicket(t *testing.T) {
key := classes.UploadKey(" app-key ")
now := time.Date(2026, 10, 28, 14, 0, 0, 0, time.UTC)
nonce := strings.Repeat("ab", 16)
tk := classes.UploadTicket{Kind: "material", Target: 12, User: 7, Expires: now.Add(classes.UploadTTL), Nonce: nonce}
payload := "material|12|7|" + strconvInt(now.Add(classes.UploadTTL).Unix()) + "|" + nonce
t.Run("key", func(t *testing.T) {
if string(key) != "app-key" {
t.Errorf("UploadKey trimmed = %q, want app-key", key)
}
if classes.UploadKey(" ") != nil || classes.UploadKey("") != nil {
t.Error("an empty app key is not nil")
}
if classes.UploadTTL != 10*time.Minute {
t.Errorf("UploadTTL = %v, want 10m", classes.UploadTTL)
}
})
t.Run("round trip", func(t *testing.T) {
signed, err := classes.SignUpload(key, tk)
if err != nil {
t.Fatal(err)
}
if signed != signWith(key, "jz.bm.upload.v1:", payload) {
t.Errorf("ticket %q is not base64url(payload).base64url(HMAC(label+payload))", signed)
}
got, err := classes.VerifyUpload(key, signed, now)
if err != nil {
t.Fatalf("VerifyUpload: %v", err)
}
if got.Kind != "material" || got.Target != 12 || got.User != 7 || !got.Expires.Equal(tk.Expires) || got.Nonce != nonce {
t.Errorf("verified %+v, want %+v", got, tk)
}
})
t.Run("refused", func(t *testing.T) {
signed := signWith(key, "jz.bm.upload.v1:", payload)
head, mac, _ := strings.Cut(signed, ".")
raw, _ := base64.RawURLEncoding.DecodeString(head)
raw[len("material|1")] = '3'
macRaw, _ := base64.RawURLEncoding.DecodeString(mac)
macRaw[0] ^= 1
cases := map[string]string{
"empty": "",
"no dot": head,
"two dots": signed + ".x",
"bad base64 payload": "!!!." + mac,
"bad base64 mac": head + ".!!!",
"changed payload": base64.RawURLEncoding.EncodeToString(raw) + "." + mac,
"changed mac": head + "." + base64.RawURLEncoding.EncodeToString(macRaw),
"other key": signWith([]byte("other-key"), "jz.bm.upload.v1:", payload),
"other label": signWith(key, "golem15.presentations.upload.v1:", payload),
"no label": signWith(key, "", payload),
"four fields": signWith(key, "jz.bm.upload.v1:", "material|12|7|"+strconvInt(tk.Expires.Unix())),
"six fields": signWith(key, "jz.bm.upload.v1:", payload+"|x"),
"zero target": signWith(key, "jz.bm.upload.v1:", "material|0|7|"+strconvInt(tk.Expires.Unix())+"|"+nonce),
"short nonce": signWith(key, "jz.bm.upload.v1:", "material|12|7|"+strconvInt(tk.Expires.Unix())+"|abcd"),
"far expiry": signWith(key, "jz.bm.upload.v1:", "material|12|7|"+strconvInt(now.Add(24*time.Hour).Unix())+"|"+nonce),
}
for name, ticket := range cases {
if _, err := classes.VerifyUpload(key, ticket, now); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("%s: err %v, want ErrUploadTicket", name, err)
}
}
if _, err := classes.VerifyUpload(key, signed, tk.Expires); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("expired: err %v, want ErrUploadTicket", err)
}
if _, err := classes.VerifyUpload(nil, signed, now); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("no key: err %v, want ErrUploadTicket", err)
}
})
t.Run("issue and redeem once", func(t *testing.T) {
ctx := context.Background()
cache := memCache(t)
if _, _, err := classes.IssueUpload(ctx, cache, nil, "material", 12, 7, now); !errors.Is(err, classes.ErrUploadKeyMissing) {
t.Errorf("empty key: err %v, want ErrUploadKeyMissing", err)
}
ticket, expires, err := classes.IssueUpload(ctx, cache, key, "material", 12, 7, now)
if err != nil {
t.Fatalf("IssueUpload: %v", err)
}
if !expires.Equal(now.Add(classes.UploadTTL)) {
t.Errorf("expires %v, want %v", expires, now.Add(classes.UploadTTL))
}
if strings.Contains(ticket, string(key)) {
t.Error("the ticket carries the key")
}
got, err := classes.RedeemUpload(ctx, cache, key, ticket, now.Add(time.Minute))
if err != nil {
t.Fatalf("first RedeemUpload: %v", err)
}
if got.Kind != "material" || got.Target != 12 || got.User != 7 || len(got.Nonce) != 32 {
t.Errorf("redeemed %+v", got)
}
if _, err := classes.RedeemUpload(ctx, cache, key, ticket, now.Add(time.Minute)); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("second RedeemUpload: err %v, want ErrUploadTicket", err)
}
other, _, err := classes.IssueUpload(ctx, cache, key, "material", 12, 7, now)
if err != nil {
t.Fatal(err)
}
if other == ticket {
t.Error("two issued tickets are equal (no fresh nonce)")
}
})
t.Run("restart fails closed", func(t *testing.T) {
ctx := context.Background()
ticket, _, err := classes.IssueUpload(ctx, memCache(t), key, "material", 12, 7, now)
if err != nil {
t.Fatal(err)
}
if _, err := classes.RedeemUpload(ctx, memCache(t), key, ticket, now); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("ticket without its cache entry: err %v, want ErrUploadTicket", err)
}
signed, _ := classes.SignUpload(key, tk)
if _, err := classes.RedeemUpload(ctx, memCache(t), key, signed, now); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("signed but never issued: err %v, want ErrUploadTicket", err)
}
if _, err := classes.RedeemUpload(ctx, nil, key, signed, now); !errors.Is(err, classes.ErrUploadTicket) {
t.Errorf("no cache: err %v, want ErrUploadTicket", err)
}
})
}
func strconvInt(n int64) string { return strconv.FormatInt(n, 10) }

View File

@@ -1 +1,28 @@
{} # Defaults for jz.bm, merged under the plugin ID: the application reads them
# as jz.bm.<key> and can override them in its own config.
# Default page size of GET /_bm/api/v1/materials (clamped to 1..100).
materials_per_page: 20
# Number of class sessions and deadlines on GET /_bm/api/v1/dashboard.
dashboard_limit: 5
# Absolute base URL of the application (https://bm.example.org), used for
# the calendar feed URL and the course links inside the feed. Empty means
# the scheme and Host of the request.
public_url: ""
# The student chat (golem15.chat, golem15.chatchannels). Membership is the
# user group whose code is chat.group; nobody is added to it automatically,
# members are assigned in the backend. Members of chat.moderator_group may
# delete other people's messages in channels. Env keys:
# SUMMER_JZ__BM__CHAT__GROUP, SUMMER_JZ__BM__CHAT__MODERATOR_GROUP,
# SUMMER_JZ__BM__CHAT__MAX_UPLOAD_BYTES, SUMMER_JZ__BM__CHAT__MAX_EMBEDS.
chat:
group: studenci
moderator_group: moderatorzy
# Total size of one message's attachments (60 MiB), enforced by
# golem15.chat when the message is sent (Service.SetMaxMessageBytes) and
# checked by the student app before upload. It stays under nginx's
# client_max_body_size 64m so the multipart envelope still fits.
max_upload_bytes: 62914560
# Entity embeds (deadline, class, reading) per message.
max_embeds: 3

59
console/chat_sync.go Normal file
View File

@@ -0,0 +1,59 @@
package console
import (
"context"
"fmt"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gorm.io/gorm"
)
// chatSyncName is the name of the chat sync command.
const chatSyncName = "bm:chat-sync"
// ChatSyncCommand returns the chat sync console command. withDB runs the
// command's work with the application's database; groups returns the chat
// group code and the moderator group code. It never adds anyone to a group:
// members are assigned by hand in the backend.
func ChatSyncCommand(withDB func(ctx context.Context, fn func(*gorm.DB) error) error, groups func() (string, string)) bonfire.Command {
return bonfire.Command{
Name: chatSyncName,
Description: "Create the chat groups if missing, sync ogólny participants with the chat group and give members a handle",
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
group, moderatorGroup := groups()
return withDB(ctx, func(db *gorm.DB) error {
created, err := classes.EnsureChatGroups(ctx, db, group, moderatorGroup)
if err != nil {
return fmt.Errorf("%s: groups: %w", chatSyncName, err)
}
general, err := classes.FindGeneral(ctx, db)
if err != nil {
return fmt.Errorf("%s: ogólny: %w", chatSyncName, err)
}
var generalID uint
if general != nil {
generalID = general.ID
}
added, removed, err := classes.SyncChatParticipants(ctx, db, generalID, group)
if err != nil {
return fmt.Errorf("%s: participants: %w", chatSyncName, err)
}
handles, err := classes.AssignMissingHandles(ctx, db, group)
if err != nil {
return fmt.Errorf("%s: handles: %w", chatSyncName, err)
}
out.Printf("groups created: %d\n", created)
if general == nil {
out.Printf("ogólny does not exist yet; it is created when a member first opens the chat\n")
} else {
out.Printf("ogólny participants added: %d\n", added)
}
out.Printf("ogólny participants removed: %d\n", removed)
out.Printf("handles assigned: %d\n", handles)
out.Success(chatSyncName + ": chat group " + group + " synced")
return nil
})
},
}
}

24
console/export_test.go Normal file
View File

@@ -0,0 +1,24 @@
package console
import (
"context"
"git.golem15.com/golem15/summercms/modules/bonfire"
"gorm.io/gorm"
)
// ReindexRun exposes one reindex walk to the console_test package.
type ReindexRun struct{ r *reindexRun }
// NewReindexRun is a walk with deps' Backfill and the given sync.
func NewReindexRun(deps MaterialsReindexDeps, sync func(id uint) error, out bonfire.Output) ReindexRun {
return ReindexRun{r: &reindexRun{backfill: deps.Backfill, sync: sync, out: out}}
}
// Material runs the per-material step.
func (w ReindexRun) Material(ctx context.Context, db *gorm.DB, id uint) { w.r.material(ctx, db, id) }
// Counts are the run's counters and the tool-missing flag.
func (w ReindexRun) Counts() (synced, failed int, noTool bool) {
return w.r.synced, w.r.failed, w.r.noTool
}

View File

@@ -0,0 +1,183 @@
package console
import (
"context"
"errors"
"fmt"
"git.golem15.com/golem15/summercms/modules/beachcomber"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// MaterialsReindexName is the name of the materials reindex command.
const MaterialsReindexName = "bm:materials-reindex"
// materialsReindexBatch is how many material ids one database read loads.
const materialsReindexBatch = 200
// errSearchNotConfigured is the refusal of a reindex without an engine.
var errSearchNotConfigured = errors.New("jz.bm: the search engine is not configured (set search.driver and search.typesense.api_key)")
// MaterialsReindexDeps are what the reindex command needs. DB returns the
// application database, published on the app (Sync skips silently when no
// database is published), and done, which closes a pool DB opened. Index
// reaches the beachcomber service.
type MaterialsReindexDeps struct {
DB func(ctx context.Context) (*gorm.DB, func(), error)
Index *classes.MaterialIndexer
// Backfill extracts the text of a material's PDFs that have none yet
// (classes.EnsureFileTexts) before the material is synced. Nil skips
// it.
Backfill func(ctx context.Context, db *gorm.DB, materialID uint) error
}
// MaterialsReindexCommand returns bm:materials-reindex: it ensures the
// materials index (dropping it first with --fresh) and syncs every
// material. It refuses with an error when the engine is not configured,
// unless --if-configured, which the nightly schedule passes, makes that a
// notice.
func MaterialsReindexCommand(deps MaterialsReindexDeps) bonfire.Command {
return bonfire.Command{
Name: MaterialsReindexName,
Description: "Sync every material into the search index",
Long: `Upserts the search document of every material, drafts and private ones
included (visibility is enforced in SQL, never by the index), through the same
path as the sync after a save. Before each material is synced, the text of
its attached PDFs that have none yet is extracted with pdftotext, so PDFs
attached before file search existed become searchable; a missing pdftotext
(poppler-utils) is one warning and the run goes on without file text.
--fresh first drops the collection and recreates it from the material schema
(models.Material.SearchIndexSchema). Use it on first deploy and after the
schema changed; search finds nothing while the collection is being refilled.
The command refuses, and sends nothing, when the search engine is not
configured (search.driver null, or no search.typesense.api_key).
--if-configured makes that a notice and a zero exit; the nightly schedule
runs the command with it. It ends with "Reindexed: N synced, M failed" and
exits non-zero when any material failed.`,
Flags: []bonfire.Flag{
{Name: "fresh", Description: "Drop and recreate the collection from the schema before syncing", Bare: true},
{Name: "if-configured", Description: "Exit 0 with a notice when the search engine is not configured", Bare: true},
},
Examples: []bonfire.Example{
{Command: MaterialsReindexName, Description: "Sync every material into the existing collection"},
{Command: MaterialsReindexName + " --fresh", Description: "Recreate the collection from the schema, then sync every material"},
},
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
return reindexMaterials(ctx, deps, flagOn(in, "fresh"), flagOn(in, "if-configured"), out)
},
}
}
func reindexMaterials(ctx context.Context, deps MaterialsReindexDeps, fresh, ifConfigured bool, out bonfire.Output) error {
var svc *beachcomber.Service
if deps.Index != nil && deps.Index.Service != nil {
svc = deps.Index.Service()
}
engine := svc.Engine()
if engine == nil || !engine.Configured() {
if ifConfigured {
out.Info(MaterialsReindexName + ": search is not configured; nothing to do")
return nil
}
return errSearchNotConfigured
}
if deps.DB == nil {
return errors.New("jz.bm: no database")
}
gdb, done, err := deps.DB(ctx)
if err != nil {
return err
}
defer done()
index := svc.IndexName(&models.Material{})
if fresh {
existed, err := beachcomber.DropIndex(ctx, engine, index)
if err != nil {
return fmt.Errorf("jz.bm: drop %s: %w", index, err)
}
if existed {
out.Printf("Dropped %s\n", index)
}
}
if err := beachcomber.EnsureIndex(ctx, engine, index, models.Material{}.SearchIndexSchema()); err != nil {
return fmt.Errorf("jz.bm: create %s: %w", index, err)
}
marked := classes.MarkMaterialSearch(ctx)
run := &reindexRun{
backfill: deps.Backfill,
sync: func(id uint) error {
return svc.Sync(marked, gdb, &models.Material{ID: id})
},
out: out,
}
var batch []models.Material
err = gdb.WithContext(ctx).Model(&models.Material{}).
Select("id").
Order("id").
FindInBatches(&batch, materialsReindexBatch, func(_ *gorm.DB, _ int) error {
for i := range batch {
run.material(ctx, gdb, batch[i].ID)
}
return ctx.Err()
}).Error
if err != nil {
return err
}
msg := fmt.Sprintf("Reindexed: %d synced, %d failed", run.synced, run.failed)
if run.failed > 0 {
out.Error(msg)
return fmt.Errorf("jz.bm: %d materials failed to sync", run.failed)
}
out.Success(msg)
return nil
}
// pdfToolMissingWarning is printed once per run when pdftotext is missing.
const pdfToolMissingWarning = "pdftotext not found: PDFs add no search text; install poppler-utils and rerun"
// reindexRun is the state of one reindex walk: the run's counters and
// whether pdftotext turned out to be missing.
type reindexRun struct {
backfill func(ctx context.Context, db *gorm.DB, materialID uint) error
sync func(id uint) error
out bonfire.Output
synced int
failed int
noTool bool
}
// material backfills the file texts of material id, then syncs it. A
// missing pdftotext warns once and stops the backfill for the rest of the
// run; another backfill error warns for this material, which is still
// synced.
func (r *reindexRun) material(ctx context.Context, db *gorm.DB, id uint) {
if r.backfill != nil && !r.noTool {
err := r.backfill(ctx, db, id)
switch {
case errors.Is(err, classes.ErrPDFToolMissing):
r.noTool = true
r.out.Warning(pdfToolMissingWarning)
case err != nil:
r.out.Warning(fmt.Sprintf("material %d: file text: %v", id, err))
}
}
if err := r.sync(id); err != nil {
r.failed++
r.out.Warning(fmt.Sprintf("material %d: %v", id, err))
return
}
r.synced++
}
// flagOn reports whether a bare flag was given.
func flagOn(in bonfire.Input, name string) bool {
v, _ := in.Flag(name)
return v == "true"
}

View File

@@ -0,0 +1,171 @@
package console_test
import (
"bytes"
"context"
"errors"
"net/http"
"slices"
"strconv"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/console"
"git.golem15.com/jakub/sm-bm-plugin/internal/searchtest"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func TestMaterialsReindexRefuses(t *testing.T) {
asked := false
deps := console.MaterialsReindexDeps{
DB: func(context.Context) (*gorm.DB, func(), error) {
asked = true
return nil, func() {}, nil
},
Index: classes.NewMaterialIndexer(searchtest.App(t)),
}
cmds := []bonfire.Command{console.MaterialsReindexCommand(deps)}
var out bytes.Buffer
err := bonfire.Call(context.Background(), cmds, console.MaterialsReindexName, nil, &out)
if err == nil || !strings.Contains(err.Error(), "search.driver") || !strings.Contains(err.Error(), "search.typesense.api_key") {
t.Errorf("unconfigured engine: err = %v, want the configuration hint", err)
}
out.Reset()
if err := bonfire.Call(context.Background(), cmds, console.MaterialsReindexName, []string{"--if-configured"}, &out); err != nil {
t.Errorf("--if-configured: %v", err)
}
if !strings.Contains(out.String(), "not configured") {
t.Errorf("--if-configured output %q, want the notice", out.String())
}
if asked {
t.Error("the command opened the database without an engine")
}
}
func TestMaterialsReindexFresh(t *testing.T) {
stub := &searchtest.Stub{}
app := searchtest.App(t, searchtest.Start(t, stub)...)
gdb, err := gorm.Open(postgres.New(postgres.Config{DSN: "host=127.0.0.1"}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
if err != nil {
t.Fatal(err)
}
sqlDB, err := gdb.DB()
if err != nil {
t.Fatal(err)
}
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
t.Fatal(err)
}
deps := console.MaterialsReindexDeps{
DB: func(context.Context) (*gorm.DB, func(), error) { return gdb, func() {}, nil },
Index: classes.NewMaterialIndexer(app),
}
cmds := []bonfire.Command{console.MaterialsReindexCommand(deps)}
coll := "/collections/" + searchtest.Index
var out bytes.Buffer
for run := 1; run <= 2; run++ {
before := len(stub.Requests())
out.Reset()
if err := bonfire.Call(context.Background(), cmds, console.MaterialsReindexName, []string{"--fresh"}, &out); err != nil {
t.Fatalf("run %d: %v\n%s", run, err, out.String())
}
var sent []string
for _, r := range stub.Requests()[before:] {
sent = append(sent, r.Method+" "+r.Path)
}
if want := []string{http.MethodDelete + " " + coll, http.MethodGet + " " + coll, http.MethodPost + " /collections"}; !slices.Equal(sent, want) {
t.Errorf("run %d sent %v, want %v", run, sent, want)
}
if !strings.Contains(out.String(), "Reindexed: 0 synced, 0 failed") {
t.Errorf("run %d output %q", run, out.String())
}
}
// The second run dropped the collection the first one created.
if !strings.Contains(out.String(), "Dropped "+searchtest.Index) {
t.Errorf("second run output %q, want Dropped", out.String())
}
}
func TestMaterialsReindexBackfill(t *testing.T) {
ctx := context.Background()
var calls []string
var synced []uint
sync := func(id uint) error {
calls = append(calls, "sync "+strconv.FormatUint(uint64(id), 10))
synced = append(synced, id)
return nil
}
// pdftotext missing on the first material: one warning, no more
// backfill calls, and every material is still synced.
deps := console.MaterialsReindexDeps{Backfill: func(_ context.Context, _ *gorm.DB, id uint) error {
calls = append(calls, "backfill "+strconv.FormatUint(uint64(id), 10))
return classes.ErrPDFToolMissing
}}
var stdout, stderr bytes.Buffer
run := console.NewReindexRun(deps, sync, bonfire.NewOutput(strings.NewReader(""), &stdout, &stderr))
for _, id := range []uint{1, 2, 3} {
run.Material(ctx, nil, id)
}
if want := []string{"backfill 1", "sync 1", "sync 2", "sync 3"}; !slices.Equal(calls, want) {
t.Errorf("calls = %v, want %v", calls, want)
}
if !slices.Equal(synced, []uint{1, 2, 3}) {
t.Errorf("synced = %v, want all three", synced)
}
all := stdout.String() + stderr.String()
if n := strings.Count(all, "pdftotext not found"); n != 1 {
t.Errorf("the tool warning was printed %d times, want once:\n%s", n, all)
}
if !strings.Contains(all, "install poppler-utils") {
t.Errorf("output %q, want the poppler-utils hint", all)
}
if s, f, noTool := run.Counts(); s != 3 || f != 0 || !noTool {
t.Errorf("counts = %d synced %d failed noTool %v, want 3 0 true", s, f, noTool)
}
// Another backfill error warns for that material only; it is still
// synced and the next material is backfilled. A failed sync counts.
calls, synced = nil, nil
stdout.Reset()
stderr.Reset()
deps.Backfill = func(_ context.Context, _ *gorm.DB, id uint) error {
calls = append(calls, "backfill "+strconv.FormatUint(uint64(id), 10))
if id == 1 {
return errors.New("blob gone")
}
return nil
}
failing := func(id uint) error {
if err := sync(id); err != nil || id == 3 {
return errors.New("engine down")
}
return nil
}
run = console.NewReindexRun(deps, failing, bonfire.NewOutput(strings.NewReader(""), &stdout, &stderr))
for _, id := range []uint{1, 2, 3} {
run.Material(ctx, nil, id)
}
if want := []string{"backfill 1", "sync 1", "backfill 2", "sync 2", "backfill 3", "sync 3"}; !slices.Equal(calls, want) {
t.Errorf("calls = %v, want %v", calls, want)
}
all = stdout.String() + stderr.String()
if !strings.Contains(all, "material 1: file text: blob gone") || strings.Contains(all, "pdftotext not found") {
t.Errorf("output %q, want the material 1 file text warning only", all)
}
if s, f, noTool := run.Counts(); s != 2 || f != 1 || noTool {
t.Errorf("counts = %d synced %d failed noTool %v, want 2 1 false", s, f, noTool)
}
// No Backfill: only syncs.
calls = nil
run = console.NewReindexRun(console.MaterialsReindexDeps{}, sync, bonfire.NewOutput(strings.NewReader(""), &stdout, &stderr))
run.Material(ctx, nil, 9)
if !slices.Equal(calls, []string{"sync 9"}) {
t.Errorf("calls without Backfill = %v", calls)
}
}

66
console/seed.go Normal file
View File

@@ -0,0 +1,66 @@
// Code generated by summer make. DO NOT EDIT.
package console
import (
"context"
"fmt"
"os"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gorm.io/gorm"
)
// SeedCommand returns the bm:seed console command. withDB runs the
// command's work with the application's database; the plugin supplies it.
func SeedCommand(withDB func(ctx context.Context, fn func(*gorm.DB) error) error) bonfire.Command {
return bonfire.Command{
Name: "bm:seed",
Description: "Upsert meetings, courses, class sessions, deadlines and readings from a JSON file",
Args: []bonfire.Arg{{Name: "file", Description: "Path of the seed JSON file", Required: true}},
Flags: []bonfire.Flag{
{Name: "dry-run", Description: "Show what the seed would change, then roll it back", Bare: true},
{Name: "prune", Description: "Delete courses of the file's semesters, and sessions and readings of its courses, that the file does not list", Bare: true},
},
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
path, _ := in.Argument("file")
if path == "" {
return fmt.Errorf("bm:seed: a file is required")
}
fh, err := os.Open(path)
if err != nil {
return fmt.Errorf("bm:seed: %w", err)
}
defer fh.Close()
file, err := classes.ParseSeed(fh)
if err != nil {
return err
}
if err := file.Validate(); err != nil {
return fmt.Errorf("bm:seed: %s is not valid, nothing was written:\n%w", path, err)
}
dry, _ := in.Flag("dry-run")
prune, _ := in.Flag("prune")
opts := classes.SeedOptions{DryRun: dry == "true", Prune: prune == "true"}
out.Printf("%s is valid: %d meetings, %d courses, %d class sessions, %d deadlines, %d readings\n", path,
len(file.Meetings), len(file.Courses), len(file.ClassSessions), len(file.Deadlines), len(file.Readings))
return withDB(ctx, func(db *gorm.DB) error {
sum, err := classes.SeedWith(ctx, db, file, opts)
if err != nil {
return fmt.Errorf("bm:seed: nothing was written: %w", err)
}
out.Table([]string{"kind", "created", "updated", "unchanged", "deleted"}, sum.Rows())
for _, r := range sum.Removed {
out.Printf("deleted: %s\n", r)
}
if opts.DryRun {
out.Success("bm:seed: dry run of " + path + ", nothing was written")
return nil
}
out.Success("bm:seed: " + path + " applied")
return nil
})
},
}
}

68
console/seed_test.go Normal file
View File

@@ -0,0 +1,68 @@
package console_test
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/jakub/sm-bm-plugin/console"
"gorm.io/gorm"
)
func TestSeedCommandShape(t *testing.T) {
cmd := console.SeedCommand(nil)
if cmd.Name != "bm:seed" || cmd.Description == "" {
t.Errorf("command = %q %q", cmd.Name, cmd.Description)
}
if len(cmd.Args) != 1 || cmd.Args[0].Name != "file" || !cmd.Args[0].Required {
t.Errorf("Args = %+v, want one required file argument", cmd.Args)
}
}
func TestSeedCommandChecksTheFileBeforeTheDatabase(t *testing.T) {
called := false
withDB := func(ctx context.Context, fn func(*gorm.DB) error) error {
called = true
return errors.New("no database in this test")
}
cmds := []bonfire.Command{console.SeedCommand(withDB)}
dir := t.TempDir()
invalid := filepath.Join(dir, "invalid.json")
if err := os.WriteFile(invalid, []byte(`{"readings": [{"course": "ghost", "title": "X"}]}`), 0o644); err != nil {
t.Fatal(err)
}
broken := filepath.Join(dir, "broken.json")
if err := os.WriteFile(broken, []byte(`{"courses": [`), 0o644); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
for _, args := range [][]string{nil, {filepath.Join(dir, "missing.json")}, {broken}, {invalid}} {
if err := bonfire.Call(context.Background(), cmds, "bm:seed", args, &out); err == nil {
t.Errorf("bm:seed %v succeeded", args)
}
}
err := bonfire.Call(context.Background(), cmds, "bm:seed", []string{invalid}, &out)
if err == nil || !strings.Contains(err.Error(), "nothing was written") || !strings.Contains(err.Error(), "ghost") {
t.Errorf("invalid file error = %v", err)
}
if called {
t.Error("bm:seed reached the database with an invalid file")
}
out.Reset()
err = bonfire.Call(context.Background(), cmds, "bm:seed", []string{"../testdata/seed.example.json", "--dry-run", "--prune"}, &out)
if !called || err == nil || !strings.Contains(out.String(), "3 courses") {
t.Errorf("dry run called=%v err=%v output %q, want the validation line and the withDB error", called, err, out.String())
}
called = false
err = bonfire.Call(context.Background(), cmds, "bm:seed", []string{"../testdata/seed.example.json"}, &out)
if !called || err == nil {
t.Errorf("valid file: called=%v err=%v, want the withDB error", called, err)
}
}

37
controllers/admin_test.go Normal file
View File

@@ -0,0 +1,37 @@
package controllers
import (
"context"
"errors"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
func TestTemporalHooksAnswerOnTheField(t *testing.T) {
var hooks temporalHooks
at := func(h, m int) time.Time { return time.Date(2026, 10, 3, h, m, 0, 0, models.Location) }
bad := &models.ClassSession{StartsAt: at(8, 0), EndsAt: at(7, 0)}
for name, fn := range map[string]func(context.Context, any) error{
"create": hooks.FormBeforeCreate,
"update": hooks.FormBeforeUpdate,
} {
err := fn(context.Background(), bad)
var ve *cabana.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("%s: err = %v, want a cabana.ValidationError", name, err)
}
if _, ok := ve.Details["ends_at"]; !ok {
t.Errorf("%s: details %v name no ends_at", name, ve.Details)
}
}
good := &models.ClassSession{StartsAt: at(8, 0), EndsAt: at(9, 30)}
if err := hooks.FormBeforeCreate(context.Background(), good); err != nil {
t.Errorf("valid session: %v", err)
}
if err := hooks.FormBeforeUpdate(context.Background(), &models.Tag{}); err != nil {
t.Errorf("model without dates: %v", err)
}
}

170
controllers/api/api.go Normal file
View File

@@ -0,0 +1,170 @@
// Package api holds the student-facing JSON handlers of the jz.bm plugin,
// served under /_bm/api/v1 behind the golem15.user jwt.auth guard.
//
// Every response is built field by field and wrapped in {"data": ...}; a
// paginated list adds {"meta": ...}. Timestamps are RFC 3339 in
// Europe/Warsaw, dates are YYYY-MM-DD.
package api
import (
"net/http"
"sort"
"time"
chatclasses "git.golem15.com/golem15/sm-chat-plugin/classes"
chanclasses "git.golem15.com/golem15/sm-chatchannels-plugin/classes"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// Handlers serves the API. The plugin builds it in Routes; tests build it
// with their own database and clock.
type Handlers struct {
// DB returns the application database, or nil while none is published.
// It is resolved per request: the binary boots plugins before serve
// publishes the database.
DB func() *gorm.DB
// Translator returns the application translator for validation
// messages; nil gives English.
Translator func() *phrasebook.Translator
// Now is the clock; nil means time.Now.
Now func() time.Time
// PerPage is the default page size of /materials.
PerPage int
// DashboardLimit is the number of sessions and deadlines on /dashboard.
DashboardLimit int
// Bucket returns the uploads bucket for material files, or nil while
// none is published.
Bucket func() *blob.Bucket
// PublicURL is the absolute base URL of the application
// (jz.bm.public_url), used for the calendar feed URL and the links in
// it. Empty means the scheme and Host of the request.
PublicURL string
// AppURL is the application URL (app.url). The MCP link rewriter
// (jz.bm.mcp-links) prefers it to PublicURL when it makes the links of
// an MCP answer absolute.
AppURL string
// ChatService returns golem15.chat's service, or nil while none is published
// (golem15.chat inactive, or no database yet).
ChatService func() *chatclasses.Service
// Channels returns golem15.chatchannels' channel service, or nil while
// none is published.
Channels func() *chanclasses.ChannelService
// ChatGroup is the code of the user group whose members are in the chat
// (jz.bm.chat.group). Empty means nobody is.
ChatGroup string
// ChatModeratorGroup is the code of the chat's moderator group
// (jz.bm.chat.moderator_group).
ChatModeratorGroup string
// ChatMaxUploadBytes is the total attachment size of one chat message.
ChatMaxUploadBytes int
// ChatMaxEmbeds is the number of entity embeds one chat message may carry.
ChatMaxEmbeds int
// ChatBots is whether golem15.chatbots is active, so its is_bot flags
// can be read.
ChatBots bool
// UploadKey returns the key the signed material upload URLs are signed
// with (app.key), or nil when none is set: then no URL is issued.
UploadKey func() []byte
// Cache returns the application cache that holds the issued upload
// tickets until they are used, or nil while none is available.
Cache func() cooler.Cache
// MaterialIndex searches the materials index and keeps it current. Nil
// means a search (q) answers 503 and the syncs after a write are
// skipped.
MaterialIndex *classes.MaterialIndexer
// Revisions publishes the live heads-up after a write that bumped a
// material's revision (D-20). Nil means no live event.
Revisions *classes.MaterialRevisionNotifier
}
func (h *Handlers) now() time.Time {
if h.Now != nil {
return h.Now()
}
return time.Now()
}
func (h *Handlers) perPage() int {
if h.PerPage > 0 {
return min(h.PerPage, maxPerPage)
}
return defaultPerPage
}
func (h *Handlers) dashboardLimit() int {
if h.DashboardLimit > 0 {
return h.DashboardLimit
}
return 5
}
func (h *Handlers) translator() *phrasebook.Translator {
if h.Translator == nil {
return nil
}
return h.Translator()
}
const (
defaultPerPage = 20
maxPerPage = 100
)
// caller returns the signed-in user's ID. It answers 401 itself and returns
// false when there is none (the jwt.auth guard normally answers first).
func (h *Handlers) caller(w http.ResponseWriter, r *http.Request) (uint, bool) {
user, ok := bouncer.User(r.Context())
if !ok || user == nil || user.ID == 0 {
wire.WriteJSON(w, http.StatusUnauthorized, map[string]any{"error": true, "message": "Unauthenticated."})
return 0, false
}
return user.ID, true
}
// db returns the database bound to the request context. It answers 503
// itself and returns false while no database is published.
func (h *Handlers) db(w http.ResponseWriter, r *http.Request) (*gorm.DB, bool) {
var db *gorm.DB
if h.DB != nil {
db = h.DB()
}
if db == nil {
wire.WriteJSON(w, http.StatusServiceUnavailable, map[string]any{"error": true, "message": "Database unavailable."})
return nil, false
}
return db.WithContext(r.Context()), true
}
func writeData(w http.ResponseWriter, v any) {
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": v})
}
func writeNotFound(w http.ResponseWriter) {
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": true, "message": "Not found."})
}
// writeValidation answers 422 with Laravel's validation body: the first
// message and the errors object from lagoon.ValidateRequest.
func writeValidation(w http.ResponseWriter, errs map[string][]string) {
keys := make([]string, 0, len(errs))
for k := range errs {
keys = append(keys, k)
}
sort.Strings(keys)
message := "The given data was invalid."
if len(keys) > 0 && len(errs[keys[0]]) > 0 {
message = errs[keys[0]][0]
}
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": message, "errors": errs})
}
func writeOpaque500(w http.ResponseWriter) { wire.WriteOpaque500(w) }
// writeJSONPage writes a lagoon.Page as it is: {data, meta}.
func writeJSONPage(w http.ResponseWriter, page any) { wire.WriteJSON(w, http.StatusOK, page) }

372
controllers/api/calendar.go Normal file
View File

@@ -0,0 +1,372 @@
package api
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"slices"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// CalendarPath is the path prefix of the public ICS feed; the feed of a
// token is at CalendarPath/<token>.ics.
const CalendarPath = "/_bm/calendar"
// calendarCacheControl lets a calendar client reuse a fetch for 15 minutes.
const calendarCacheControl = "private, max-age=900"
// fetchStampEvery limits the last_fetched_at writes of a feed.
const fetchStampEvery = time.Minute
// tokenBytes is the size of a feed token before hex encoding.
const tokenBytes = 32
var calendarFeedRules = []lagoon.RequestRule{
{Field: "excluded_course_ids", Rules: lagoon.ParseRules("sometimes|array|max:500")},
{Field: "excluded_course_ids.*", Rules: lagoon.ParseRules("integer|min:1|exists:jz_bm_courses,id")},
{Field: "include_meetings", Rules: lagoon.ParseRules("sometimes|boolean")},
{Field: "include_deadlines", Rules: lagoon.ParseRules("sometimes|boolean")},
}
// calendarFeedJSON is the caller's feed as the API shows it.
type calendarFeedJSON struct {
URL string `json:"url"`
ExcludedCourseIDs []uint `json:"excluded_course_ids"`
IncludeMeetings bool `json:"include_meetings"`
IncludeDeadlines bool `json:"include_deadlines"`
LastFetchedAt *string `json:"last_fetched_at"`
}
// publicBase is the absolute base URL of the application: jz.bm.public_url
// when set, otherwise the scheme and Host of the request.
func (h *Handlers) publicBase(r *http.Request) string {
if base := strings.TrimRight(strings.TrimSpace(h.PublicURL), "/"); base != "" {
return base
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
return scheme + "://" + r.Host
}
func (h *Handlers) newFeedJSON(r *http.Request, f *models.CalendarFeed) calendarFeedJSON {
ids := []uint(f.ExcludedCourseIDs)
if ids == nil {
ids = []uint{}
}
out := calendarFeedJSON{
URL: h.publicBase(r) + CalendarPath + "/" + f.Token + ".ics",
ExcludedCourseIDs: ids,
IncludeMeetings: f.IncludeMeetings,
IncludeDeadlines: f.IncludeDeadlines,
}
if f.LastFetchedAt != nil {
s := models.FormatDateTime(*f.LastFetchedAt)
out.LastFetchedAt = &s
}
return out
}
// newToken returns 32 random bytes in hex.
func newToken() (string, error) {
b := make([]byte, tokenBytes)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
// findFeed loads the caller's feed; nil when there is none.
func findFeed(db *gorm.DB, userID uint) (*models.CalendarFeed, error) {
var feed models.CalendarFeed
res := db.Where("user_id = ?", userID).Limit(1).Find(&feed)
if res.Error != nil {
return nil, res.Error
}
if res.RowsAffected == 0 {
return nil, nil
}
return &feed, nil
}
// CalendarFeed answers GET /calendar-feed: the caller's feed, or null.
func (h *Handlers) CalendarFeed(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
feed, err := findFeed(db, userID)
if err != nil {
writeOpaque500(w)
return
}
if feed == nil {
writeData(w, nil)
return
}
writeData(w, h.newFeedJSON(r, feed))
}
// readJSONObject decodes a JSON object body; an empty body is an empty
// object.
func readJSONObject(r *http.Request) (map[string]any, error) {
var in map[string]any
if err := json.NewDecoder(r.Body).Decode(&in); err != nil && !errors.Is(err, io.EOF) {
return nil, err
}
if in == nil {
in = map[string]any{}
}
// JSON numbers decode as float64; whole ones become int64, so the
// exists rule queries with an integer.
if raw, ok := in["excluded_course_ids"].([]any); ok {
for i, v := range raw {
if f, ok := v.(float64); ok && f == math.Trunc(f) && math.Abs(f) < 1<<53 {
raw[i] = int64(f)
}
}
}
return in, nil
}
// excludedIDs returns the validated excluded_course_ids, sorted and without
// duplicates.
func excludedIDs(v any) models.IDList {
raw, _ := v.([]any)
out := models.IDList{}
for _, item := range raw {
if n, ok := item.(int64); ok && n > 0 {
out = append(out, uint(n))
}
}
slices.Sort(out)
return slices.Compact(out)
}
// UpdateCalendarFeed answers PUT /calendar-feed: it creates the caller's
// feed with a new token when there is none, and applies the settings the
// body gives.
func (h *Handlers) UpdateCalendarFeed(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
in, err := readJSONObject(r)
if err != nil {
wire.WriteJSON(w, http.StatusBadRequest, map[string]any{"error": true, "message": "The request body is not a JSON object."})
return
}
db, ok := h.db(w, r)
if !ok {
return
}
errs, err := lagoon.ValidateRequest(r.Context(), db, in, calendarFeedRules, h.translator())
if err != nil {
writeOpaque500(w)
return
}
if len(errs) > 0 {
writeValidation(w, errs)
return
}
token, err := newToken()
if err != nil {
writeOpaque500(w)
return
}
now := h.now().UTC()
var feed *models.CalendarFeed
err = db.Transaction(func(tx *gorm.DB) error {
if err := tx.Exec(`INSERT INTO jz_bm_calendar_feeds (user_id, token, created_at, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT (user_id) DO NOTHING`, userID, token, now, now).Error; err != nil {
return err
}
set := map[string]any{}
if v, ok := in["excluded_course_ids"]; ok {
set["excluded_course_ids"] = excludedIDs(v)
}
if v, ok := in["include_meetings"]; ok {
set["include_meetings"] = truthy(v)
}
if v, ok := in["include_deadlines"]; ok {
set["include_deadlines"] = truthy(v)
}
if len(set) > 0 {
set["updated_at"] = now
if err := tx.Model(&models.CalendarFeed{}).Where("user_id = ?", userID).UpdateColumns(set).Error; err != nil {
return err
}
}
var err error
feed, err = findFeed(tx, userID)
return err
})
if err != nil || feed == nil {
writeOpaque500(w)
return
}
writeData(w, h.newFeedJSON(r, feed))
}
// truthy reads a value the boolean rule accepted: true, false, 1, 0, "1",
// "0", "true", "false".
func truthy(v any) bool {
switch b := v.(type) {
case bool:
return b
case int64:
return b == 1
case float64:
return b == 1
case string:
return b == "1" || b == "true"
}
return false
}
// RotateCalendarFeed answers POST /calendar-feed/rotate: the caller's feed
// gets a new token, so the old URL stops working. 404 without a feed.
func (h *Handlers) RotateCalendarFeed(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
token, err := newToken()
if err != nil {
writeOpaque500(w)
return
}
res := db.Model(&models.CalendarFeed{}).Where("user_id = ?", userID).
UpdateColumns(map[string]any{"token": token, "updated_at": h.now().UTC()})
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
feed, err := findFeed(db, userID)
if err != nil || feed == nil {
writeOpaque500(w)
return
}
writeData(w, h.newFeedJSON(r, feed))
}
// DeleteCalendarFeed answers DELETE /calendar-feed: it deletes the caller's
// feed (204, also when there was none).
func (h *Handlers) DeleteCalendarFeed(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
if err := db.Where("user_id = ?", userID).Delete(&models.CalendarFeed{}).Error; err != nil {
writeOpaque500(w)
return
}
w.WriteHeader(http.StatusNoContent)
}
// feedToken reads {token} with an optional .ics suffix and reports whether
// it has the shape of a token (64 lower-case hex digits).
func feedToken(r *http.Request) (string, bool) {
token := strings.TrimSuffix(r.PathValue("token"), ".ics")
if len(token) != 2*tokenBytes {
return "", false
}
for _, c := range token {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return "", false
}
}
return token, true
}
// CalendarICS answers GET /_bm/calendar/{token}.ics without authentication:
// the token is the credential. An unknown token is a 404.
func (h *Handlers) CalendarICS(w http.ResponseWriter, r *http.Request) {
token, ok := feedToken(r)
if !ok {
writeNotFound(w)
return
}
db, ok := h.db(w, r)
if !ok {
return
}
var feed models.CalendarFeed
res := db.Where("token = ?", token).Limit(1).Find(&feed)
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
var data classes.CalendarData
if err := preloadSession(db).Order("starts_at, id").Find(&data.Sessions).Error; err != nil {
writeOpaque500(w)
return
}
if feed.IncludeMeetings {
if err := db.Order("number, id").Find(&data.Meetings).Error; err != nil {
writeOpaque500(w)
return
}
}
if feed.IncludeDeadlines {
if err := db.Preload("Course").Order("due_at, id").Find(&data.Deadlines).Error; err != nil {
writeOpaque500(w)
return
}
}
body := classes.BuildCalendar(data, classes.CalendarOptions{
ExcludedCourseIDs: feed.ExcludedCourseIDs,
IncludeMeetings: feed.IncludeMeetings,
IncludeDeadlines: feed.IncludeDeadlines,
SiteURL: h.publicBase(r),
})
// One cheap write per feed and minute at most; a failure does not cost
// the client its calendar.
now := h.now().UTC()
_ = db.Exec(`UPDATE jz_bm_calendar_feeds SET last_fetched_at = ?
WHERE id = ? AND (last_fetched_at IS NULL OR last_fetched_at <= ?)`, now, feed.ID, now.Add(-fetchStampEvery)).Error
sum := sha256.Sum256(body)
hdr := w.Header()
hdr.Set("Content-Type", "text/calendar; charset=utf-8")
hdr.Set("Content-Disposition", `inline; filename="bm.ics"`)
hdr.Set("Cache-Control", calendarCacheControl)
hdr.Set("ETag", `"`+hex.EncodeToString(sum[:])[:32]+`"`)
hdr.Set("X-Content-Type-Options", "nosniff")
hdr.Set("Referrer-Policy", "no-referrer")
http.ServeContent(w, r, "bm.ics", time.Time{}, bytes.NewReader(body))
}

318
controllers/api/chat.go Normal file
View File

@@ -0,0 +1,318 @@
package api
import (
"net/http"
"sort"
chatclasses "git.golem15.com/golem15/sm-chat-plugin/classes"
chatmodels "git.golem15.com/golem15/sm-chat-plugin/models"
chanclasses "git.golem15.com/golem15/sm-chatchannels-plugin/classes"
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// chatNonMemberJSON is the whole answer of /chat for a user outside the
// chat group.
type chatNonMemberJSON struct {
Member bool `json:"member"`
}
// chatBootstrapJSON is the answer of /chat for a chat-group member.
type chatBootstrapJSON struct {
Member bool `json:"member"`
Moderator bool `json:"moderator"`
Context chatContextJSON `json:"context"`
General chatGeneralJSON `json:"general"`
Conversations []chatConversationJSON `json:"conversations"`
Limits chatLimitsJSON `json:"limits"`
}
type chatContextJSON struct {
Type string `json:"type"`
ID uint `json:"id"`
}
// chatGeneralJSON is ogólny: its conversation, unread messages and unread
// mentions of the caller.
type chatGeneralJSON struct {
ConversationID uint `json:"conversation_id"`
Name string `json:"name"`
Unread int64 `json:"unread"`
Mentions int64 `json:"mentions"`
}
// chatConversationJSON is one of the caller's DMs.
type chatConversationJSON struct {
ID uint `json:"id"`
Type string `json:"type"`
OtherUserID uint `json:"other_user_id"`
Unread int64 `json:"unread"`
LastMessage *chatLastMessageJSON `json:"last_message"`
}
type chatLastMessageJSON struct {
ID uint `json:"id"`
SenderID uint `json:"sender_id"`
Content string `json:"content"`
CreatedAt string `json:"created_at"`
}
// chatLimitsJSON are the composer limits: attachments per message, their
// total size and embeds per message.
type chatLimitsJSON struct {
MaxFiles int `json:"max_files"`
MaxBytes int `json:"max_bytes"`
MaxEmbeds int `json:"max_embeds"`
}
// chatMemberJSON is one chat-group member as the mention picker and the DM
// picker show them.
type chatMemberJSON struct {
ID uint `json:"id"`
Name string `json:"name"`
Surname string `json:"surname"`
Handle string `json:"handle"`
IsBot bool `json:"is_bot"`
}
// chatServices returns golem15.chat's and golem15.chatchannels' services,
// or answers an opaque 500 and false while either is missing.
func (h *Handlers) chatServices(w http.ResponseWriter) (*chatclasses.Service, *chanclasses.ChannelService, bool) {
var chat *chatclasses.Service
var channels *chanclasses.ChannelService
if h.ChatService != nil {
chat = h.ChatService()
}
if h.Channels != nil {
channels = h.Channels()
}
if chat == nil || channels == nil {
writeOpaque500(w)
return nil, nil, false
}
return chat, channels, true
}
// Chat answers GET /chat, the chat bootstrap. A user outside the chat group
// gets only member: false and loses any participant rows left in the BM
// chat. A member is joined to ogólny (created and adopted as a channel on
// first use), the participants are synced with the chat group, and the
// answer carries ogólny's unread and mention counts, the caller's DMs
// (newest message first), the moderator flag and the composer limits.
func (h *Handlers) Chat(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
chat, channels, ok := h.chatServices(w)
if !ok {
return
}
ctx := r.Context()
member, err := classes.IsChatMember(ctx, db, userID, h.ChatGroup)
if err != nil {
writeOpaque500(w)
return
}
if !member {
if err := classes.PruneChatParticipant(ctx, db, userID); err != nil {
writeOpaque500(w)
return
}
writeData(w, chatNonMemberJSON{Member: false})
return
}
general, channel, err := classes.EnsureGeneral(ctx, db, chat, channels, userID)
if err != nil {
writeOpaque500(w)
return
}
if _, _, err := classes.SyncChatParticipants(ctx, db, general.ID, h.ChatGroup); err != nil {
writeOpaque500(w)
return
}
views, err := chat.GetConversationsForUser(ctx, userID, classes.ChatContextType, classes.ChatContextID)
if err != nil {
writeOpaque500(w)
return
}
mentions, err := channels.MentionCountFor(ctx, userID, channel)
if err != nil {
writeOpaque500(w)
return
}
moderator, err := classes.IsChatModerator(ctx, db, userID, h.ChatModeratorGroup)
if err != nil {
writeOpaque500(w)
return
}
out := chatBootstrapJSON{
Member: true,
Moderator: moderator,
Context: chatContextJSON{Type: classes.ChatContextType, ID: classes.ChatContextID},
General: chatGeneralJSON{ConversationID: general.ID, Name: classes.ChatGeneralName, Mentions: mentions},
Limits: chatLimitsJSON{
MaxFiles: chatclasses.MaxAttachments,
MaxBytes: h.ChatMaxUploadBytes,
MaxEmbeds: h.ChatMaxEmbeds,
},
}
dms := []chatclasses.ConversationView{}
for _, v := range views {
switch {
case v.Conversation.ID == general.ID:
out.General.Unread = v.UnreadCount
case v.Conversation.Type == chatmodels.TypeDM:
dms = append(dms, v)
}
}
others, err := otherParticipants(db, dms, userID)
if err != nil {
writeOpaque500(w)
return
}
out.Conversations = newChatConversationsJSON(dms, others)
writeData(w, out)
}
// otherParticipants maps each DM to the participant who is not userID.
func otherParticipants(db *gorm.DB, dms []chatclasses.ConversationView, userID uint) (map[uint]uint, error) {
others := map[uint]uint{}
if len(dms) == 0 {
return others, nil
}
ids := make([]uint, len(dms))
for i, v := range dms {
ids[i] = v.Conversation.ID
}
var rows []chatmodels.Participant
err := db.Select("conversation_id", "user_id").
Where("conversation_id IN ? AND user_id <> ?", ids, userID).
Order("id").Find(&rows).Error
if err != nil {
return nil, err
}
for _, p := range rows {
if _, ok := others[p.ConversationID]; !ok {
others[p.ConversationID] = p.UserID
}
}
return others, nil
}
// newChatConversationsJSON lists the DMs newest message first; DMs without
// a message come last, newest conversation first.
func newChatConversationsJSON(dms []chatclasses.ConversationView, others map[uint]uint) []chatConversationJSON {
sort.SliceStable(dms, func(i, j int) bool {
a, b := dms[i].LastMessage, dms[j].LastMessage
switch {
case a == nil && b == nil:
return dms[i].Conversation.ID > dms[j].Conversation.ID
case a == nil || b == nil:
return b == nil
case a.CreatedAt == nil || b.CreatedAt == nil:
return a.ID > b.ID
case !a.CreatedAt.Equal(*b.CreatedAt):
return a.CreatedAt.After(*b.CreatedAt)
}
return a.ID > b.ID
})
out := make([]chatConversationJSON, 0, len(dms))
for _, v := range dms {
row := chatConversationJSON{
ID: v.Conversation.ID,
Type: chatmodels.TypeDM,
OtherUserID: others[v.Conversation.ID],
Unread: v.UnreadCount,
}
if m := v.LastMessage; m != nil {
last := &chatLastMessageJSON{ID: m.ID, SenderID: m.SenderID}
if m.Content != nil {
last.Content = *m.Content
}
if m.CreatedAt != nil {
last.CreatedAt = models.FormatDateTime(*m.CreatedAt)
}
row.LastMessage = last
}
out = append(out, row)
}
return out
}
// ChatMembers answers GET /chat/members: the chat-group members with their
// name, surname, @handle and bot flag, ordered by id. Members without a
// handle get one first. Anyone outside the chat group gets 404.
func (h *Handlers) ChatMembers(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
ctx := r.Context()
member, err := classes.IsChatMember(ctx, db, userID, h.ChatGroup)
if err != nil {
writeOpaque500(w)
return
}
if !member {
writeNotFound(w)
return
}
if _, err := classes.AssignMissingHandles(ctx, db, h.ChatGroup); err != nil {
writeOpaque500(w)
return
}
ids, err := classes.ChatMemberIDs(ctx, db, h.ChatGroup)
if err != nil {
writeOpaque500(w)
return
}
out := make([]chatMemberJSON, 0, len(ids))
if len(ids) == 0 {
writeData(w, out)
return
}
var users []usermodels.User
if err := db.Select("id", "name", "surname", "handle").Where("id IN ?", ids).Order("id").Find(&users).Error; err != nil {
writeOpaque500(w)
return
}
bots := map[uint]bool{}
if h.ChatBots {
var botIDs []uint
if err := db.Table("golem15_chatbots_bot_flags").Where("is_bot AND user_id IN ?", ids).Pluck("user_id", &botIDs).Error; err != nil {
writeOpaque500(w)
return
}
for _, id := range botIDs {
bots[id] = true
}
}
for _, u := range users {
out = append(out, chatMemberJSON{
ID: u.ID,
Name: deref(u.Name),
Surname: deref(u.Surname),
Handle: deref(u.Handle),
IsBot: bots[u.ID],
})
}
writeData(w, out)
}
func deref(s *string) string {
if s == nil {
return ""
}
return *s
}

View File

@@ -0,0 +1,289 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// The entity types a chat message can embed (D-14). Materials and quizzes
// are deferred and are not accepted.
const (
embedTypeDeadline = "deadline"
embedTypeClass = "class"
embedTypeReading = "reading"
)
// embedSearchLimit is the number of rows one picker search answers.
const embedSearchLimit = 20
// embedResolveLimit is the number of distinct refs one resolve call takes.
const embedResolveLimit = 50
var embedTypes = []string{embedTypeDeadline, embedTypeClass, embedTypeReading}
var chatEmbedsRules = []lagoon.RequestRule{
{Field: "type", Rules: append(lagoon.ParseRules("required"), lagoon.In(embedTypes...))},
{Field: "q", Rules: lagoon.ParseRules("nullable|string|max:100")},
}
// embedRef is one entity reference a message stores in its metadata.
type embedRef struct {
Type string `json:"type"`
ID uint `json:"id"`
}
// embedJSON is one embeddable item: its type and id, and the same JSON the
// rest of the API serves for it in the field named after the type.
type embedJSON struct {
Type string `json:"type"`
ID uint `json:"id"`
Deadline *deadlineJSON `json:"deadline,omitempty"`
Session *sessionJSON `json:"session,omitempty"`
Reading *readingCardJSON `json:"reading,omitempty"`
}
// readingCardJSON is a reading as an embed card shows it: no per-user read
// or owned state.
type readingCardJSON struct {
ID uint `json:"id"`
Title string `json:"title"`
Author *string `json:"author"`
IsRequired bool `json:"is_required"`
CourseID uint `json:"course_id"`
Course *courseRef `json:"course"`
}
// resolveEmbedsRequest is the body of POST /chat/embeds/resolve.
type resolveEmbedsRequest struct {
Refs []embedRef `json:"refs"`
}
// embedKey is the key of a ref in the resolve answer, "{type}:{id}".
func embedKey(typ string, id uint) string {
return typ + ":" + strconv.FormatUint(uint64(id), 10)
}
// escapeLike escapes the ILIKE wildcards % and _ and the escape character
// itself, so user input matches literally.
func escapeLike(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}
// parseEmbedRefs checks refs: a supported type, a positive id, at most
// embedResolveLimit distinct refs. Duplicates collapse and the first-seen
// order is kept. Any problem returns validation errors and no refs.
func parseEmbedRefs(refs []embedRef) ([]embedRef, map[string][]string) {
errs := map[string][]string{}
seen := map[embedRef]bool{}
out := make([]embedRef, 0, len(refs))
for i, r := range refs {
if !slices.Contains(embedTypes, r.Type) {
errs[fmt.Sprintf("refs.%d.type", i)] = []string{"The selected type is invalid."}
continue
}
if r.ID == 0 {
errs[fmt.Sprintf("refs.%d.id", i)] = []string{"The id must be at least 1."}
continue
}
if seen[r] {
continue
}
seen[r] = true
out = append(out, r)
}
if len(out) > embedResolveLimit {
errs["refs"] = []string{fmt.Sprintf("The refs may not have more than %d items.", embedResolveLimit)}
}
if len(errs) > 0 {
return nil, errs
}
return out, nil
}
// chatMember answers 404 itself and returns false when userID is not in the
// chat group (500 when the check fails).
func (h *Handlers) chatMember(w http.ResponseWriter, r *http.Request, db *gorm.DB, userID uint) bool {
member, err := classes.IsChatMember(r.Context(), db, userID, h.ChatGroup)
if err != nil {
writeOpaque500(w)
return false
}
if !member {
writeNotFound(w)
return false
}
return true
}
// ChatEmbeds answers GET /chat/embeds?type=deadline|class|reading&q=, the
// embed picker search, to chat-group members (404 otherwise). It lists at
// most embedSearchLimit items: upcoming deadlines soonest first, upcoming
// class sessions soonest first, readings required first then by title. q
// (at most 100 characters) narrows by deadline title, course name or
// reading title and author, case-insensitively.
func (h *Handlers) ChatEmbeds(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
in := query(r, "type", "q")
if !h.validate(w, r, in, chatEmbedsRules) {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
if !h.chatMember(w, r, db, userID) {
return
}
items, err := searchEmbeds(db, str(in, "type"), strings.TrimSpace(str(in, "q")), h.now().UTC())
if err != nil {
writeOpaque500(w)
return
}
writeData(w, items)
}
func searchEmbeds(db *gorm.DB, typ, q string, now time.Time) ([]embedJSON, error) {
pattern := "%" + escapeLike(q) + "%"
out := []embedJSON{}
switch typ {
case embedTypeDeadline:
var rows []models.Deadline
find := db.Preload("Course").Where("jz_bm_deadlines.due_at >= ?", now)
if q != "" {
find = find.Where("jz_bm_deadlines.title ILIKE ?", pattern)
}
if err := find.Order("jz_bm_deadlines.due_at, jz_bm_deadlines.id").Limit(embedSearchLimit).Find(&rows).Error; err != nil {
return nil, err
}
for _, d := range newDeadlinesJSON(rows) {
out = append(out, embedJSON{Type: embedTypeDeadline, ID: d.ID, Deadline: &d})
}
case embedTypeClass:
var rows []models.ClassSession
find := preloadSession(db).Where("jz_bm_class_sessions.ends_at > ?", now)
if q != "" {
find = find.Joins("JOIN jz_bm_courses ON jz_bm_courses.id = jz_bm_class_sessions.course_id").
Where("jz_bm_courses.name ILIKE ?", pattern)
}
if err := find.Order("jz_bm_class_sessions.starts_at, jz_bm_class_sessions.id").Limit(embedSearchLimit).Find(&rows).Error; err != nil {
return nil, err
}
for _, s := range newSessionsJSON(rows) {
out = append(out, embedJSON{Type: embedTypeClass, ID: s.ID, Session: &s})
}
case embedTypeReading:
var rows []models.Reading
find := db.Preload("Course").Where("jz_bm_readings.course_id IS NOT NULL")
if q != "" {
find = find.Where("(jz_bm_readings.title ILIKE ? OR jz_bm_readings.author ILIKE ?)", pattern, pattern)
}
if err := find.Order("jz_bm_readings.is_required DESC, jz_bm_readings.title, jz_bm_readings.id").Limit(embedSearchLimit).Find(&rows).Error; err != nil {
return nil, err
}
for _, rd := range rows {
card := newReadingCardJSON(rd)
out = append(out, embedJSON{Type: embedTypeReading, ID: rd.ID, Reading: &card})
}
}
return out, nil
}
func newReadingCardJSON(r models.Reading) readingCardJSON {
return readingCardJSON{
ID: r.ID,
Title: r.Title,
Author: r.Author,
IsRequired: r.IsRequired,
CourseID: idOf(r.CourseID),
Course: newCourseRef(r.Course),
}
}
// ResolveChatEmbeds answers POST /chat/embeds/resolve {"refs": [{type, id}]}
// for chat-group members (404 otherwise): {"data": {"{type}:{id}": item or
// null}} for every requested ref. Items are read on every call, so a
// renamed or moved deadline shows its current title and date. A missing
// row, or a class session without a course, is null: the neutral
// unavailable card (D-04).
func (h *Handlers) ResolveChatEmbeds(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
var body resolveEmbedsRequest
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&body); err != nil {
writeValidation(w, map[string][]string{"refs": {"The request body must be a JSON object with a refs list."}})
return
}
refs, errs := parseEmbedRefs(body.Refs)
if len(errs) > 0 {
writeValidation(w, errs)
return
}
db, ok := h.db(w, r)
if !ok {
return
}
if !h.chatMember(w, r, db, userID) {
return
}
out, err := resolveEmbeds(db, refs)
if err != nil {
writeOpaque500(w)
return
}
writeData(w, out)
}
func resolveEmbeds(db *gorm.DB, refs []embedRef) (map[string]*embedJSON, error) {
out := make(map[string]*embedJSON, len(refs))
ids := map[string][]uint{}
for _, ref := range refs {
out[embedKey(ref.Type, ref.ID)] = nil
ids[ref.Type] = append(ids[ref.Type], ref.ID)
}
if list := ids[embedTypeDeadline]; len(list) > 0 {
var rows []models.Deadline
if err := db.Preload("Course").Where("jz_bm_deadlines.id IN ?", list).Find(&rows).Error; err != nil {
return nil, err
}
for _, d := range newDeadlinesJSON(rows) {
out[embedKey(embedTypeDeadline, d.ID)] = &embedJSON{Type: embedTypeDeadline, ID: d.ID, Deadline: &d}
}
}
if list := ids[embedTypeClass]; len(list) > 0 {
var rows []models.ClassSession
if err := preloadSession(db).Where("jz_bm_class_sessions.id IN ?", list).Find(&rows).Error; err != nil {
return nil, err
}
for _, s := range newSessionsJSON(rows) {
out[embedKey(embedTypeClass, s.ID)] = &embedJSON{Type: embedTypeClass, ID: s.ID, Session: &s}
}
}
if list := ids[embedTypeReading]; len(list) > 0 {
var rows []models.Reading
if err := db.Preload("Course").Where("jz_bm_readings.id IN ? AND jz_bm_readings.course_id IS NOT NULL", list).Find(&rows).Error; err != nil {
return nil, err
}
for _, rd := range rows {
card := newReadingCardJSON(rd)
out[embedKey(embedTypeReading, rd.ID)] = &embedJSON{Type: embedTypeReading, ID: rd.ID, Reading: &card}
}
}
return out, nil
}

View File

@@ -0,0 +1,161 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/bouncer"
"gorm.io/gorm"
)
func embedHandlers() *Handlers {
return &Handlers{DB: func() *gorm.DB { return nil }, ChatGroup: "studenci", ChatModeratorGroup: "moderatorzy"}
}
func serveEmbed(t *testing.T, fn http.HandlerFunc, method, target, body string, userID uint) (int, map[string]any) {
t.Helper()
req := httptest.NewRequest(method, target, strings.NewReader(body))
if userID != 0 {
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: userID}))
}
rec := httptest.NewRecorder()
fn(rec, req)
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("%s %s: body is not JSON: %v\n%s", method, target, err, rec.Body.String())
}
return rec.Code, out
}
// TestChatEmbedRefs: the resolver accepts deadline, class and reading refs
// with a positive id, collapses duplicates and takes at most 50 distinct
// refs; materials and quizzes are not embed types (D-14).
func TestChatEmbedRefs(t *testing.T) {
ok := []embedRef{{"deadline", 1}, {"class", 2}, {"reading", 3}, {"deadline", 1}}
got, errs := parseEmbedRefs(ok)
if len(errs) != 0 {
t.Fatalf("valid refs refused: %v", errs)
}
if want := []embedRef{{"deadline", 1}, {"class", 2}, {"reading", 3}}; fmt.Sprint(got) != fmt.Sprint(want) {
t.Errorf("refs = %v, want %v (duplicates collapse, order kept)", got, want)
}
for name, refs := range map[string][]embedRef{
"material": {{"material", 1}},
"quiz": {{"quiz", 1}},
"empty": {{"", 1}},
"id 0": {{"deadline", 0}},
"51 refs": manyRefs(51),
} {
if _, errs := parseEmbedRefs(refs); len(errs) == 0 {
t.Errorf("%s: accepted, want a validation error", name)
}
}
if _, errs := parseEmbedRefs(manyRefs(50)); len(errs) != 0 {
t.Errorf("50 refs refused: %v", errs)
}
dup := append(manyRefs(50), manyRefs(50)...)
if got, errs := parseEmbedRefs(dup); len(errs) != 0 || len(got) != 50 {
t.Errorf("50 distinct refs sent twice = %d refs, %v; want 50 and no error", len(got), errs)
}
if embedKey("deadline", 12) != "deadline:12" || embedKey("class", 3) != "class:3" {
t.Errorf("embedKey = %q / %q", embedKey("deadline", 12), embedKey("class", 3))
}
if embedSearchLimit != 20 {
t.Errorf("embedSearchLimit = %d, want 20", embedSearchLimit)
}
}
func manyRefs(n int) []embedRef {
out := make([]embedRef, n)
for i := range out {
out[i] = embedRef{Type: "reading", ID: uint(i + 1)}
}
return out
}
// TestEscapeLike: %, _ and the backslash escape character are matched
// literally in an ILIKE pattern.
func TestEscapeLike(t *testing.T) {
for in, want := range map[string]string{
`50%_a\b`: `50\%\_a\\b`,
"plain": "plain",
"": "",
"Wstęp_100": `Wstęp\_100`,
} {
if got := escapeLike(in); got != want {
t.Errorf("escapeLike(%q) = %q, want %q", in, got, want)
}
}
}
func TestChatEmbedsUnauthenticated(t *testing.T) {
code, body := serveEmbed(t, embedHandlers().ChatEmbeds, http.MethodGet, "/?type=deadline", "", 0)
if code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("GET /chat/embeds without a principal = %d %v, want 401", code, body)
}
}
func TestResolveChatEmbedsUnauthenticated(t *testing.T) {
code, body := serveEmbed(t, embedHandlers().ResolveChatEmbeds, http.MethodPost, "/", `{"refs":[{"type":"deadline","id":1}]}`, 0)
if code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("POST /chat/embeds/resolve without a principal = %d %v, want 401", code, body)
}
}
// TestChatEmbedsInvalid: the search validates type and q before the
// database (422 without one).
func TestChatEmbedsInvalid(t *testing.T) {
h := embedHandlers()
for target, field := range map[string]string{
"/": "type",
"/?type=material": "type",
"/?type=deadline&q=" + strings.Repeat("ą", 101): "q",
} {
code, body := serveEmbed(t, h.ChatEmbeds, http.MethodGet, target, "", 7)
if code != http.StatusUnprocessableEntity {
t.Errorf("%s = %d %v, want 422", target, code, body)
continue
}
if errs, _ := body["errors"].(map[string]any); errs[field] == nil {
t.Errorf("%s: errors %v have no %s", target, body["errors"], field)
}
}
code, _ := serveEmbed(t, h.ChatEmbeds, http.MethodGet, "/?type=reading&q="+strings.Repeat("ą", 100), "", 7)
if code != http.StatusServiceUnavailable {
t.Errorf("100-rune q = %d, want to pass validation (503 without a database)", code)
}
}
// TestResolveChatEmbedsInvalid: an unsupported type, id 0, too many refs,
// an unknown field or a malformed body is 422 before the database.
func TestResolveChatEmbedsInvalid(t *testing.T) {
h := embedHandlers()
many, _ := json.Marshal(map[string]any{"refs": manyRefs(51)})
for name, body := range map[string]string{
"material": `{"refs":[{"type":"material","id":1}]}`,
"id 0": `{"refs":[{"type":"deadline","id":0}]}`,
"51 refs": string(many),
"unknown field": `{"refs":[],"extra":1}`,
"not an object": `[1]`,
"malformed": `{`,
"empty body": ``,
} {
code, out := serveEmbed(t, h.ResolveChatEmbeds, http.MethodPost, "/", body, 7)
if code != http.StatusUnprocessableEntity {
t.Errorf("%s = %d %v, want 422", name, code, out)
}
}
}
// TestResolveChatEmbedsNoDatabase: valid refs pass validation and need the
// database (503 without one).
func TestResolveChatEmbedsNoDatabase(t *testing.T) {
code, body := serveEmbed(t, embedHandlers().ResolveChatEmbeds, http.MethodPost, "/", `{"refs":[{"type":"deadline","id":1},{"type":"class","id":2},{"type":"reading","id":3}]}`, 7)
if code != http.StatusServiceUnavailable {
t.Errorf("valid refs without a database = %d %v, want 503", code, body)
}
}

View File

@@ -0,0 +1,46 @@
package api_test
import (
"net/http"
"testing"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"gorm.io/gorm"
)
// chatNoDB is a chat-enabled Handlers whose database is never published.
func chatNoDB() *api.Handlers {
return &api.Handlers{DB: func() *gorm.DB { return nil }, ChatGroup: "studenci", ChatModeratorGroup: "moderatorzy"}
}
func TestChatBootstrapUnauthenticated(t *testing.T) {
code, body := serve(t, chatNoDB().Chat, http.MethodGet, "/", nil, nil)
if code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("GET /chat without a principal = %d %v, want 401", code, body)
}
}
func TestChatBootstrapNoDatabase(t *testing.T) {
code, body := serve(t, chatNoDB().Chat, http.MethodGet, "/", &bouncer.Principal{ID: 7}, nil)
if code != http.StatusServiceUnavailable || body["message"] != "Database unavailable." {
t.Errorf("GET /chat without a database = %d %v, want 503 Database unavailable.", code, body)
}
if _, ok := body["data"]; ok {
t.Errorf("GET /chat without a database carries data: %v", body)
}
}
func TestChatMembersUnauthenticated(t *testing.T) {
code, body := serve(t, chatNoDB().ChatMembers, http.MethodGet, "/", nil, nil)
if code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("GET /chat/members without a principal = %d %v, want 401", code, body)
}
}
func TestChatMembersNoDatabase(t *testing.T) {
code, body := serve(t, chatNoDB().ChatMembers, http.MethodGet, "/", &bouncer.Principal{ID: 7}, nil)
if code != http.StatusServiceUnavailable {
t.Errorf("GET /chat/members without a database = %d %v, want 503", code, body)
}
}

View File

@@ -0,0 +1,694 @@
package api
import (
"context"
"net/http"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// The checklists of the student API: each user's own lists (usually the
// preparation for one zjazd), never anyone else's; a checklist or item of
// another user answers 404 like a missing one. Bodies are JSON objects of
// columns, checked as on the management API (Fillable, Rules, existing
// foreign keys). An item with a reading shares its done mark with the
// reading list: marking it done marks the reading read, and a reading read
// in the reading list shows its items done.
// presentationsTable is the deck table of golem15.presentations, read by
// name without importing the plugin.
const presentationsTable = "golem15_presentations_presentations"
var checklistsRules = []lagoon.RequestRule{
{Field: "meeting", Rules: lagoon.ParseRules("nullable|integer|min:1")},
}
// checklistProgress counts a checklist's items. Percent weighs them by
// estimate_minutes, so a 3 h item counts more than a 5 min one; without any
// estimate it counts items.
type checklistProgress struct {
Total int `json:"total"`
Done int `json:"done"`
Percent int `json:"percent"`
MinutesTotal int `json:"minutes_total"`
MinutesDone int `json:"minutes_done"`
MinutesLeft int `json:"minutes_left"`
}
func (p *checklistProgress) add(item checklistItemJSON) {
p.Total++
minutes := 0
if item.EstimateMinutes != nil {
minutes = *item.EstimateMinutes
}
p.MinutesTotal += minutes
if item.Done {
p.Done++
p.MinutesDone += minutes
} else {
p.MinutesLeft += minutes
}
if p.MinutesTotal > 0 {
p.Percent = p.MinutesDone * 100 / p.MinutesTotal
} else {
p.Percent = p.Done * 100 / p.Total
}
}
// checklistMeetingRef is the short form of a checklist's zjazd.
type checklistMeetingRef struct {
ID uint `json:"id"`
Number int `json:"number"`
StartsOn string `json:"starts_on"`
EndsOn string `json:"ends_on"`
}
// checklistJSON is a checklist with its progress, and its items on the
// detail route.
type checklistJSON struct {
ID uint `json:"id"`
MeetingID *uint `json:"meeting_id"`
Meeting *checklistMeetingRef `json:"meeting"`
Title string `json:"title"`
Description *string `json:"description"`
SortOrder int `json:"sort_order"`
Progress checklistProgress `json:"progress"`
Items *[]checklistItemJSON `json:"items,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type linkedReading struct {
ID uint `json:"id"`
Title string `json:"title"`
Author *string `json:"author"`
}
type linkedDeadline struct {
ID uint `json:"id"`
Title string `json:"title"`
DueAt string `json:"due_at"`
Kind string `json:"kind"`
}
type linkedMaterial struct {
ID uint `json:"id"`
Title string `json:"title"`
}
type linkedPresentation struct {
Slug string `json:"slug"`
Title string `json:"title"`
}
// checklistItemJSON is one item with its done state and the rows it points
// at (null when unset or gone; presentation is null when the caller owns no
// deck with that slug).
type checklistItemJSON struct {
ID uint `json:"id"`
ChecklistID uint `json:"checklist_id"`
Kind string `json:"kind"`
Title string `json:"title"`
Notes *string `json:"notes"`
URL *string `json:"url"`
CourseID *uint `json:"course_id"`
Course *courseRef `json:"course"`
ReadingID *uint `json:"reading_id"`
Reading *linkedReading `json:"reading"`
DeadlineID *uint `json:"deadline_id"`
Deadline *linkedDeadline `json:"deadline"`
MaterialID *uint `json:"material_id"`
Material *linkedMaterial `json:"material"`
PresentationSlug *string `json:"presentation_slug"`
Presentation *linkedPresentation `json:"presentation"`
DueAt *string `json:"due_at"`
EstimateMinutes *int `json:"estimate_minutes"`
SortOrder int `json:"sort_order"`
Done bool `json:"done"`
DoneAt *string `json:"done_at"`
}
// checklistItemRow is an item with its effective done mark: the reading's
// read_at for an item with a reading, else its own done_at.
type checklistItemRow struct {
models.ChecklistItem `gorm:"embedded"`
DoneMark *time.Time `gorm:"column:done_mark"`
}
func formatTime(t *time.Time) *string {
if t == nil {
return nil
}
s := models.FormatDateTime(*t)
return &s
}
// loadChecklistItems returns the caller's items of the given checklists,
// keyed by checklist, in display order.
func loadChecklistItems(db *gorm.DB, userID uint, checklistIDs []uint) (map[uint][]checklistItemJSON, error) {
out := map[uint][]checklistItemJSON{}
if len(checklistIDs) == 0 {
return out, nil
}
var rows []checklistItemRow
err := db.Table("jz_bm_checklist_items AS i").
Select("i.*, CASE WHEN i.reading_id IS NULL THEN i.done_at ELSE p.read_at END AS done_mark").
Joins("JOIN jz_bm_checklists c ON c.id = i.checklist_id").
Joins("LEFT JOIN jz_bm_reading_progress p ON p.reading_id = i.reading_id AND p.user_id = c.user_id").
Where("c.user_id = ? AND i.checklist_id IN ?", userID, checklistIDs).
Order("i.checklist_id, i.sort_order, i.id").
Scan(&rows).Error
if err != nil {
return nil, err
}
var courseIDs, readingIDs, deadlineIDs, materialIDs []uint
var slugs []string
for _, row := range rows {
if row.CourseID != nil {
courseIDs = append(courseIDs, *row.CourseID)
}
if row.ReadingID != nil {
readingIDs = append(readingIDs, *row.ReadingID)
}
if row.DeadlineID != nil {
deadlineIDs = append(deadlineIDs, *row.DeadlineID)
}
if row.MaterialID != nil {
materialIDs = append(materialIDs, *row.MaterialID)
}
if row.PresentationSlug != nil {
slugs = append(slugs, *row.PresentationSlug)
}
}
courses, err := coursesByID(db, courseIDs)
if err != nil {
return nil, err
}
readings := map[uint]*linkedReading{}
if len(readingIDs) > 0 {
var rs []models.Reading
if err := db.Where("id IN ?", readingIDs).Find(&rs).Error; err != nil {
return nil, err
}
for _, r := range rs {
readings[r.ID] = &linkedReading{ID: r.ID, Title: r.Title, Author: r.Author}
}
}
deadlines := map[uint]*linkedDeadline{}
if len(deadlineIDs) > 0 {
var ds []models.Deadline
if err := db.Where("id IN ?", deadlineIDs).Find(&ds).Error; err != nil {
return nil, err
}
for _, d := range ds {
deadlines[d.ID] = &linkedDeadline{ID: d.ID, Title: d.Title, DueAt: models.FormatDateTime(d.DueAt), Kind: d.Kind}
}
}
materials := map[uint]*linkedMaterial{}
if len(materialIDs) > 0 {
// Only published materials the caller may see, so a private
// material's title never shows.
var ms []models.Material
err := db.Select("id", "title").Where("id IN ? AND published_at IS NOT NULL", materialIDs).
Where(visibleMaterialSQL("jz_bm_materials"), userID, userID).Find(&ms).Error
if err != nil {
return nil, err
}
for _, m := range ms {
materials[m.ID] = &linkedMaterial{ID: m.ID, Title: m.Title}
}
}
decks, err := ownedDecks(db, userID, slugs)
if err != nil {
return nil, err
}
for _, row := range rows {
item := checklistItemJSON{
ID: row.ID,
ChecklistID: row.ChecklistID,
Kind: row.Kind,
Title: row.Title,
Notes: row.Notes,
URL: row.URL,
CourseID: row.CourseID,
ReadingID: row.ReadingID,
DeadlineID: row.DeadlineID,
MaterialID: row.MaterialID,
PresentationSlug: row.PresentationSlug,
DueAt: formatTime(row.DueAt),
EstimateMinutes: row.EstimateMinutes,
SortOrder: row.SortOrder,
Done: row.DoneMark != nil,
DoneAt: formatTime(row.DoneMark),
}
if row.CourseID != nil {
item.Course = newCourseRef(courses[*row.CourseID])
}
if row.ReadingID != nil {
item.Reading = readings[*row.ReadingID]
}
if row.DeadlineID != nil {
item.Deadline = deadlines[*row.DeadlineID]
}
if row.MaterialID != nil {
item.Material = materials[*row.MaterialID]
}
if row.PresentationSlug != nil {
item.Presentation = decks[*row.PresentationSlug]
}
out[row.ChecklistID] = append(out[row.ChecklistID], item)
}
return out, nil
}
// ownedDecks returns the caller's decks among slugs, keyed by slug. Without
// golem15.presentations installed there are none.
func ownedDecks(db *gorm.DB, userID uint, slugs []string) (map[string]*linkedPresentation, error) {
out := map[string]*linkedPresentation{}
if len(slugs) == 0 || !db.Migrator().HasTable(presentationsTable) {
return out, nil
}
var rows []linkedPresentation
err := db.Table(presentationsTable).Select("slug, title").
Where("owner_user_id = ? AND slug IN ?", userID, slugs).Scan(&rows).Error
if err != nil {
return nil, err
}
for i := range rows {
out[rows[i].Slug] = &rows[i]
}
return out, nil
}
// checklistsJSON builds the answer for the given checklists, with items
// when withItems.
func checklistsJSON(db *gorm.DB, userID uint, lists []models.Checklist, withItems bool) ([]checklistJSON, error) {
ids := make([]uint, 0, len(lists))
meetingIDs := []uint{}
for _, c := range lists {
ids = append(ids, c.ID)
if c.MeetingID != nil {
meetingIDs = append(meetingIDs, *c.MeetingID)
}
}
items, err := loadChecklistItems(db, userID, ids)
if err != nil {
return nil, err
}
meetings := map[uint]*checklistMeetingRef{}
if len(meetingIDs) > 0 {
var ms []models.Meeting
if err := db.Where("id IN ?", meetingIDs).Find(&ms).Error; err != nil {
return nil, err
}
for _, m := range ms {
meetings[m.ID] = &checklistMeetingRef{ID: m.ID, Number: m.Number, StartsOn: m.StartsOn.String(), EndsOn: m.EndsOn.String()}
}
}
out := make([]checklistJSON, 0, len(lists))
for _, c := range lists {
item := checklistJSON{
ID: c.ID,
MeetingID: c.MeetingID,
Title: c.Title,
Description: c.Description,
SortOrder: c.SortOrder,
CreatedAt: models.FormatDateTime(c.CreatedAt),
UpdatedAt: models.FormatDateTime(c.UpdatedAt),
}
if c.MeetingID != nil {
item.Meeting = meetings[*c.MeetingID]
}
for _, it := range items[c.ID] {
item.Progress.add(it)
}
if withItems {
list := items[c.ID]
if list == nil {
list = []checklistItemJSON{}
}
item.Items = &list
}
out = append(out, item)
}
return out, nil
}
// Checklists answers GET /checklists?meeting=ID: the caller's checklists
// with their progress, without items.
func (h *Handlers) Checklists(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
in := query(r, "meeting")
if !h.validate(w, r, in, checklistsRules) {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
q := db.Where("user_id = ?", userID)
if id := uintParam(in, "meeting"); id != 0 {
q = q.Where("meeting_id = ?", id)
}
var lists []models.Checklist
if err := q.Order("sort_order, id").Find(&lists).Error; err != nil {
writeOpaque500(w)
return
}
out, err := checklistsJSON(db, userID, lists, false)
if err != nil {
writeOpaque500(w)
return
}
writeData(w, out)
}
// checklistFor resolves {id} to one of the caller's checklists and answers
// 404 itself when there is none.
func checklistFor(w http.ResponseWriter, r *http.Request, db *gorm.DB, userID uint) (*models.Checklist, bool) {
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return nil, false
}
var c models.Checklist
res := db.Where("id = ? AND user_id = ?", id, userID).Limit(1).Find(&c)
if res.Error != nil {
writeOpaque500(w)
return nil, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return nil, false
}
return &c, true
}
// itemFor resolves {id} to an item of one of the caller's checklists and
// answers 404 itself when there is none.
func itemFor(w http.ResponseWriter, r *http.Request, db *gorm.DB, userID uint) (*models.ChecklistItem, bool) {
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return nil, false
}
var item models.ChecklistItem
res := db.Table("jz_bm_checklist_items AS i").Select("i.*").
Joins("JOIN jz_bm_checklists c ON c.id = i.checklist_id").
Where("i.id = ? AND c.user_id = ?", id, userID).Limit(1).Find(&item)
if res.Error != nil {
writeOpaque500(w)
return nil, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return nil, false
}
return &item, true
}
// writeChecklist answers one checklist with its items.
func writeChecklist(w http.ResponseWriter, db *gorm.DB, userID uint, c models.Checklist, status int) {
out, err := checklistsJSON(db, userID, []models.Checklist{c}, true)
if err != nil || len(out) != 1 {
writeOpaque500(w)
return
}
wire.WriteJSON(w, status, map[string]any{"data": out[0]})
}
// writeItem answers one item as the detail route shows it.
func writeItem(w http.ResponseWriter, db *gorm.DB, userID uint, item models.ChecklistItem, status int) {
items, err := loadChecklistItems(db, userID, []uint{item.ChecklistID})
if err != nil {
writeOpaque500(w)
return
}
for _, it := range items[item.ChecklistID] {
if it.ID == item.ID {
wire.WriteJSON(w, status, map[string]any{"data": it})
return
}
}
writeOpaque500(w)
}
// Checklist answers GET /checklists/{id}: one of the caller's checklists
// with its items.
func (h *Handlers) Checklist(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
c, ok := checklistFor(w, r, db, userID)
if !ok {
return
}
writeChecklist(w, db, userID, *c, http.StatusOK)
}
var checklistReferences = map[string]string{"meeting_id": "jz_bm_meetings"}
var itemReferences = map[string]string{
"course_id": "jz_bm_courses",
"reading_id": "jz_bm_readings",
"deadline_id": "jz_bm_deadlines",
"material_id": "jz_bm_materials",
}
// CreateChecklist answers POST /checklists: 201 with the new checklist.
func (h *Handlers) CreateChecklist(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
c := &models.Checklist{UserID: userID}
if _, ok := h.fillRecord(w, r, db, c, c, checklistReferences, nil); !ok {
return
}
if err := db.Create(c).Error; err != nil {
writeOpaque500(w)
return
}
writeChecklist(w, db, userID, *c, http.StatusCreated)
}
// UpdateChecklist answers PATCH /checklists/{id}: the sent columns change.
func (h *Handlers) UpdateChecklist(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
c, ok := checklistFor(w, r, db, userID)
if !ok {
return
}
if _, ok := h.fillRecord(w, r, db, c, c, checklistReferences, nil); !ok {
return
}
if err := db.Save(c).Error; err != nil {
writeOpaque500(w)
return
}
writeChecklist(w, db, userID, *c, http.StatusOK)
}
// DeleteChecklist answers DELETE /checklists/{id}: 204; its items go with
// it. Reading marks stay.
func (h *Handlers) DeleteChecklist(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
c, ok := checklistFor(w, r, db, userID)
if !ok {
return
}
if err := db.Delete(c).Error; err != nil {
writeOpaque500(w)
return
}
w.WriteHeader(http.StatusNoContent)
}
// checkItem adds the item checks the rules cannot make: the target
// checklist is the caller's, and a deck slug names one of the caller's
// decks.
func checkItem(db *gorm.DB, userID uint) func(map[string]any, map[string][]string) error {
return func(check map[string]any, errs map[string][]string) error {
if id, ok := check["checklist_id"].(uint); ok {
var n int64
if err := db.Model(&models.Checklist{}).Where("id = ? AND user_id = ?", id, userID).Count(&n).Error; err != nil {
return err
}
if n == 0 {
errs["checklist_id"] = append(errs["checklist_id"], "The selected checklist_id is invalid.")
}
}
if slug, ok := check["presentation_slug"].(string); ok && slug != "" {
decks, err := ownedDecks(db, userID, []string{slug})
if err != nil {
return err
}
if decks[slug] == nil {
errs["presentation_slug"] = append(errs["presentation_slug"], "The selected presentation_slug is not one of your decks.")
}
}
return nil
}
}
// CreateChecklistItem answers POST /checklists/{id}/items: 201 with the new
// item, at the end of the list unless sort_order is sent. kind defaults to
// zadanie.
func (h *Handlers) CreateChecklistItem(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
c, ok := checklistFor(w, r, db, userID)
if !ok {
return
}
var last struct{ Max *int }
if err := db.Model(&models.ChecklistItem{}).Select("MAX(sort_order) AS max").Where("checklist_id = ?", c.ID).Scan(&last).Error; err != nil {
writeOpaque500(w)
return
}
item := &models.ChecklistItem{ChecklistID: c.ID, Kind: "zadanie"}
if last.Max != nil {
item.SortOrder = *last.Max + 1
}
if _, ok := h.fillRecord(w, r, db, item, item, itemReferences, checkItem(db, userID)); !ok {
return
}
if err := db.Create(item).Error; err != nil {
writeOpaque500(w)
return
}
writeItem(w, db, userID, *item, http.StatusCreated)
}
// UpdateChecklistItem answers PATCH /checklist-items/{id}: the sent columns
// change; checklist_id moves the item to another of the caller's lists.
func (h *Handlers) UpdateChecklistItem(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
item, ok := itemFor(w, r, db, userID)
if !ok {
return
}
if _, ok := h.fillRecord(w, r, db, item, item, itemReferences, checkItem(db, userID)); !ok {
return
}
if err := db.Save(item).Error; err != nil {
writeOpaque500(w)
return
}
writeItem(w, db, userID, *item, http.StatusOK)
}
// DeleteChecklistItem answers DELETE /checklist-items/{id}: 204. A reading
// mark stays.
func (h *Handlers) DeleteChecklistItem(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
item, ok := itemFor(w, r, db, userID)
if !ok {
return
}
if err := db.Delete(item).Error; err != nil {
writeOpaque500(w)
return
}
w.WriteHeader(http.StatusNoContent)
}
// MarkChecklistItemDone answers PUT /checklist-items/{id}/done. An item
// with a reading marks the reading read by the caller (the reading list
// shows it read); any other item gets done_at. Marking it again keeps the
// first mark.
func (h *Handlers) MarkChecklistItemDone(w http.ResponseWriter, r *http.Request) {
h.setItemDone(w, r, true)
}
// UnmarkChecklistItemDone answers DELETE /checklist-items/{id}/done: it
// clears the mark, and for an item with a reading the caller's read mark.
func (h *Handlers) UnmarkChecklistItemDone(w http.ResponseWriter, r *http.Request) {
h.setItemDone(w, r, false)
}
func (h *Handlers) setItemDone(w http.ResponseWriter, r *http.Request, done bool) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
item, ok := itemFor(w, r, db, userID)
if !ok {
return
}
now := h.now().UTC()
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
if item.ReadingID != nil {
if done {
return tx.Exec(`INSERT INTO jz_bm_reading_progress (reading_id, user_id, read_at) VALUES (?, ?, ?)
ON CONFLICT (reading_id, user_id) DO NOTHING`, *item.ReadingID, userID, now).Error
}
return tx.Where("reading_id = ? AND user_id = ?", *item.ReadingID, userID).Delete(&models.ReadingProgress{}).Error
}
q := tx.Model(&models.ChecklistItem{}).Where("id = ?", item.ID)
if done {
return q.Where("done_at IS NULL").Update("done_at", now).Error
}
return q.Update("done_at", nil).Error
})
if err != nil {
writeOpaque500(w)
return
}
writeItem(w, db, userID, *item, http.StatusOK)
}

118
controllers/api/courses.go Normal file
View File

@@ -0,0 +1,118 @@
package api
import (
"net/http"
"time"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// courseRow is a course with its counters, as the counting query returns it.
type courseRow struct {
models.Course `gorm:"embedded"`
SessionsCount int64 `gorm:"column:sessions_count"`
ReadingsCount int64 `gorm:"column:readings_count"`
ReadingsRead int64 `gorm:"column:readings_read"`
MaterialsCount int64 `gorm:"column:materials_count"`
}
func (c courseRow) counts() courseCounts {
return courseCounts{Sessions: c.SessionsCount, Readings: c.ReadingsCount, ReadingsRead: c.ReadingsRead, Materials: c.MaterialsCount}
}
// coursesWithCounts selects courses with their session, reading and
// visible published material counts and the caller's read readings.
func coursesWithCounts(db *gorm.DB, userID uint, now time.Time) *gorm.DB {
return db.Table("jz_bm_courses AS c").Select(`c.*,
(SELECT COUNT(*) FROM jz_bm_class_sessions s WHERE s.course_id = c.id) AS sessions_count,
(SELECT COUNT(*) FROM jz_bm_readings r WHERE r.course_id = c.id) AS readings_count,
(SELECT COUNT(*) FROM jz_bm_reading_progress p JOIN jz_bm_readings r ON r.id = p.reading_id
WHERE r.course_id = c.id AND p.user_id = ?) AS readings_read,
(SELECT COUNT(*) FROM jz_bm_materials m WHERE m.course_id = c.id
AND m.published_at IS NOT NULL AND m.published_at <= ? AND `+visibleMaterialSQL("m")+`) AS materials_count`, userID, now.UTC(), userID, userID)
}
// Courses answers GET /courses?semester=N: every course in programme order
// with its counters.
func (h *Handlers) Courses(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
in := query(r, "semester")
if !h.validate(w, r, in, coursesRules) {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
q := coursesWithCounts(db, userID, h.now())
if semester := intParam(in, "semester", 0); semester != 0 {
q = q.Where("c.semester = ?", semester)
}
var rows []courseRow
if err := q.Order("c.semester, c.sort_order, c.name, c.id").Scan(&rows).Error; err != nil {
writeOpaque500(w)
return
}
out := make([]courseListJSON, 0, len(rows))
for _, row := range rows {
out = append(out, courseListJSON{courseJSON: newCourseJSON(row.Course), Counts: row.counts()})
}
writeData(w, out)
}
// Course answers GET /courses/{id}: the course with its counters, all its
// class sessions, its readings with the caller's read state and its
// published materials.
func (h *Handlers) Course(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return
}
now := h.now()
var rows []courseRow
if err := coursesWithCounts(db, userID, now).Where("c.id = ?", id).Limit(1).Scan(&rows).Error; err != nil {
writeOpaque500(w)
return
}
if len(rows) == 0 {
writeNotFound(w)
return
}
row := rows[0]
var sessions []models.ClassSession
if err := preloadSession(db).Where("course_id = ?", row.ID).Order("starts_at, id").Find(&sessions).Error; err != nil {
writeOpaque500(w)
return
}
readings, err := listReadings(db, userID, row.ID)
if err != nil {
writeOpaque500(w)
return
}
materials, err := publishedMaterialsOfCourse(db, now, userID, row.ID)
if err != nil {
writeOpaque500(w)
return
}
writeData(w, courseDetailJSON{
courseJSON: newCourseJSON(row.Course),
Counts: row.counts(),
Sessions: newSessionsJSON(sessions),
Readings: readings,
Materials: materials,
})
}

View File

@@ -0,0 +1,89 @@
package api
import (
"git.golem15.com/golem15/summercms/modules/lagoon"
"net/http"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// dashboardJSON is the answer of /dashboard.
type dashboardJSON struct {
NextSessions []sessionJSON `json:"next_sessions"`
UpcomingDeadlines []deadlineJSON `json:"upcoming_deadlines"`
CurrentMeeting *meetingJSON `json:"current_meeting"`
NextMeeting *meetingJSON `json:"next_meeting"`
Readings readingsSummary `json:"readings"`
}
// Dashboard answers GET /dashboard: the next class sessions (those not yet
// over), the deadlines not yet due, the meeting under way today and the next
// one, and the caller's reading progress.
func (h *Handlers) Dashboard(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
now := h.now().UTC()
limit := h.dashboardLimit()
out := dashboardJSON{}
var sessions []models.ClassSession
if err := preloadSession(db).Where("ends_at > ?", now).Order("starts_at, id").Limit(limit).Find(&sessions).Error; err != nil {
writeOpaque500(w)
return
}
out.NextSessions = newSessionsJSON(sessions)
var deadlines []models.Deadline
if err := db.Preload("Course").Where("due_at >= ?", now).Order("due_at, id").Limit(limit).Find(&deadlines).Error; err != nil {
writeOpaque500(w)
return
}
out.UpcomingDeadlines = newDeadlinesJSON(deadlines)
day := lagoon.DateOf(today(h.now())).String()
var err error
if out.CurrentMeeting, err = meetingWhere(db, "starts_on <= ? AND ends_on >= ?", day, day); err != nil {
writeOpaque500(w)
return
}
if out.NextMeeting, err = meetingWhere(db, "starts_on > ?", day); err != nil {
writeOpaque500(w)
return
}
err = db.Raw(`SELECT
COUNT(*) AS total,
COUNT(p.id) AS read,
COUNT(*) FILTER (WHERE r.is_required) AS required_total,
COUNT(p.id) FILTER (WHERE r.is_required) AS required_read
FROM jz_bm_readings r
LEFT JOIN jz_bm_reading_progress p ON p.reading_id = r.id AND p.user_id = ?`, userID).Scan(&out.Readings).Error
if err != nil {
writeOpaque500(w)
return
}
writeData(w, out)
}
// meetingWhere returns the first meeting by start date that matches the
// condition, with its session count, or nil.
func meetingWhere(db *gorm.DB, cond string, args ...any) (*meetingJSON, error) {
var m models.Meeting
res := db.Where(cond, args...).Order("starts_on, number").Limit(1).Find(&m)
if res.Error != nil || res.RowsAffected == 0 {
return nil, res.Error
}
var sessions int64
if err := db.Model(&models.ClassSession{}).Where("meeting_id = ?", m.ID).Count(&sessions).Error; err != nil {
return nil, err
}
out := newMeetingJSON(m, sessions)
return &out, nil
}

View File

@@ -0,0 +1,13 @@
package api
// DecodeInline exposes decodeInline to the api_test package.
var DecodeInline = decodeInline
// PickSnippet, FlattenSnippet and RankOrder expose the search helpers to the
// api_test package.
var (
PickSnippet = pickSnippet
FlattenSnippet = flattenSnippet
RankOrder = rankOrder
HasFileSnippet = hasFileSnippet
)

View File

@@ -0,0 +1,237 @@
package api_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"gorm.io/gorm"
)
// noDB is a Handlers whose database is never published, so a request that
// gets past authentication and validation answers 503.
func noDB() *api.Handlers {
return &api.Handlers{DB: func() *gorm.DB { return nil }}
}
func serve(t *testing.T, h http.HandlerFunc, method, target string, user *bouncer.Principal, pathValues map[string]string) (int, map[string]any) {
t.Helper()
req := httptest.NewRequest(method, target, nil)
if user != nil {
req = req.WithContext(bouncer.WithUser(req.Context(), user))
}
for k, v := range pathValues {
req.SetPathValue(k, v)
}
rec := httptest.NewRecorder()
h(rec, req)
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("%s %s: body is not JSON: %v\n%s", method, target, err, rec.Body.String())
}
return rec.Code, body
}
func handlers(h *api.Handlers) map[string]http.HandlerFunc {
return map[string]http.HandlerFunc{
"dashboard": h.Dashboard,
"courses": h.Courses,
"course": h.Course,
"schedule": h.Schedule,
"meetings": h.Meetings,
"deadlines": h.Deadlines,
"readings": h.Readings,
"mark": h.MarkRead,
"unmark": h.UnmarkRead,
"own": h.MarkOwned,
"unown": h.UnmarkOwned,
"materials": h.Materials,
"material": h.Material,
"pin": h.PinMaterial,
"unpin": h.UnpinMaterial,
"mat-access": h.MaterialAccess,
"mat-edit": h.EditMaterial,
"tags": h.Tags,
"unpublish": h.UnpublishMaterial,
"mat-image": h.UploadMaterialImage,
"feed": h.CalendarFeed,
"feed-put": h.UpdateCalendarFeed,
"rotate": h.RotateCalendarFeed,
"feed-del": h.DeleteCalendarFeed,
"chat": h.Chat,
"chat-mem": h.ChatMembers,
}
}
// bodyRequest is a handler that validates its query or body before the
// database, with a request that passes that validation.
type bodyRequest struct {
fn http.HandlerFunc
method string
target string
body string
}
func bodyHandlers(h *api.Handlers) map[string]bodyRequest {
return map[string]bodyRequest{
"chat-embeds": {h.ChatEmbeds, http.MethodGet, "/?type=deadline&q=esej", ""},
"chat-resolve": {h.ResolveChatEmbeds, http.MethodPost, "/", `{"refs":[{"type":"reading","id":1}]}`},
"mat-access-put": {h.UpdateMaterialAccess, http.MethodPut, "/", `{"is_private":true,"user_ids":[]}`},
}
}
func serveBody(t *testing.T, b bodyRequest, user *bouncer.Principal) (int, map[string]any) {
t.Helper()
req := httptest.NewRequest(b.method, b.target, strings.NewReader(b.body))
if user != nil {
req = req.WithContext(bouncer.WithUser(req.Context(), user))
}
rec := httptest.NewRecorder()
b.fn(rec, req)
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("%s %s: body is not JSON: %v\n%s", b.method, b.target, err, rec.Body.String())
}
return rec.Code, body
}
func TestEveryHandlerNeedsACaller(t *testing.T) {
for name, fn := range handlers(noDB()) {
code, body := serve(t, fn, http.MethodGet, "/", nil, map[string]string{"id": "1"})
if code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("%s without a principal = %d %v, want 401", name, code, body)
}
}
for name, b := range bodyHandlers(noDB()) {
code, body := serveBody(t, b, nil)
if code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("%s without a principal = %d %v, want 401", name, code, body)
}
}
}
func TestEveryHandlerNeedsADatabase(t *testing.T) {
user := &bouncer.Principal{ID: 7}
for name, fn := range handlers(noDB()) {
code, body := serve(t, fn, http.MethodGet, "/", user, map[string]string{"id": "1"})
if code != http.StatusServiceUnavailable {
t.Errorf("%s without a database = %d %v, want 503", name, code, body)
}
}
for name, b := range bodyHandlers(noDB()) {
code, body := serveBody(t, b, user)
if code != http.StatusServiceUnavailable {
t.Errorf("%s without a database = %d %v, want 503", name, code, body)
}
}
// A nil DB func is the same as an unpublished database.
code, _ := serve(t, (&api.Handlers{}).Meetings, http.MethodGet, "/", user, nil)
if code != http.StatusServiceUnavailable {
t.Errorf("nil DB func = %d, want 503", code)
}
}
func TestQueryValidation(t *testing.T) {
h := noDB()
user := &bouncer.Principal{ID: 7}
cases := []struct {
name string
fn http.HandlerFunc
target string
field string
}{
{"schedule from not a date", h.Schedule, "/?from=jutro", "from"},
{"schedule from impossible date", h.Schedule, "/?from=2026-02-30", "from"},
{"schedule from not ISO", h.Schedule, "/?from=03.10.2026", "from"},
{"schedule to before from", h.Schedule, "/?from=2026-10-10&to=2026-10-01", "to"},
{"deadlines to not a date", h.Deadlines, "/?to=10/01/2026", "to"},
{"readings course not a number", h.Readings, "/?course=abc", "course"},
{"readings course zero", h.Readings, "/?course=0", "course"},
{"courses semester out of range", h.Courses, "/?semester=9", "semester"},
{"materials type unknown", h.Materials, "/?type=video", "type"},
{"materials page zero", h.Materials, "/?page=0", "page"},
{"materials per_page too large", h.Materials, "/?per_page=1000", "per_page"},
{"materials course negative", h.Materials, "/?course=-1", "course"},
{"materials meeting zero", h.Materials, "/?meeting=0", "meeting"},
{"materials tag too long", h.Materials, "/?tag=" + longTag(), "tag"},
{"materials q too long", h.Materials, "/?q=" + longTag(), "q"},
}
for _, tc := range cases {
code, body := serve(t, tc.fn, http.MethodGet, tc.target, user, nil)
if code != http.StatusUnprocessableEntity {
t.Errorf("%s: status %d %v, want 422", tc.name, code, body)
continue
}
errs, _ := body["errors"].(map[string]any)
if msgs, _ := errs[tc.field].([]any); len(msgs) == 0 {
t.Errorf("%s: errors %v have no %s message", tc.name, errs, tc.field)
}
if msg, _ := body["message"].(string); msg == "" {
t.Errorf("%s: no message in %v", tc.name, body)
}
}
}
func longTag() string {
b := make([]byte, 101)
for i := range b {
b[i] = 'a'
}
return string(b)
}
func TestValidQueriesReachTheDatabase(t *testing.T) {
h := noDB()
user := &bouncer.Principal{ID: 7}
for _, tc := range []struct {
fn http.HandlerFunc
target string
}{
{h.Schedule, "/?from=2026-10-01&to=2026-10-31"},
{h.Schedule, "/?to=2026-10-31"},
{h.Schedule, "/?from=2026-10-01&to=2026-10-01"},
{h.Deadlines, "/"},
{h.Readings, "/?course=3"},
{h.Courses, "/?semester=2"},
{h.Materials, "/?course=1&tag=geopolityka&type=pdf&page=2&per_page=10"},
{h.Materials, "/?meeting=4&per_page=100"},
} {
if code, body := serve(t, tc.fn, http.MethodGet, tc.target, user, nil); code != http.StatusServiceUnavailable {
t.Errorf("%s = %d %v, want to pass validation (503 without a database)", tc.target, code, body)
}
}
}
func TestCalendarICSRejectsMalformedTokens(t *testing.T) {
h := noDB()
good := strings.Repeat("ab", 32)
for _, token := range []string{"", "abc", good[:63], good + "0", strings.ToUpper(good), good[:62] + "zz", good + ".ical", "../" + good} {
code, body := serve(t, h.CalendarICS, http.MethodGet, "/", nil, map[string]string{"token": token})
if code != http.StatusNotFound {
t.Errorf("token %q = %d %v, want 404 without a database lookup", token, code, body)
}
}
// A well-formed token, with or without .ics, is looked up (503 here).
for _, token := range []string{good, good + ".ics"} {
if code, _ := serve(t, h.CalendarICS, http.MethodGet, "/", nil, map[string]string{"token": token}); code != http.StatusServiceUnavailable {
t.Errorf("token %q = %d, want 503 without a database", token, code)
}
}
}
func TestUpdateCalendarFeedRejectsAnInvalidBody(t *testing.T) {
h := noDB()
for _, body := range []string{"[1,2]", "{", `"x"`} {
req := httptest.NewRequest(http.MethodPut, "/", strings.NewReader(body))
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: 7}))
rec := httptest.NewRecorder()
h.UpdateCalendarFeed(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("body %s = %d %s, want 400", body, rec.Code, rec.Body.String())
}
}
}

270
controllers/api/json.go Normal file
View File

@@ -0,0 +1,270 @@
package api
import "git.golem15.com/jakub/sm-bm-plugin/models"
// idOf is the value of an optional id, 0 when it is nil. The API serves only
// sessions and readings that have a course, so their course_id is set.
func idOf(id *uint) uint {
if id == nil {
return 0
}
return *id
}
// courseRef is the short form of a course embedded in other records.
type courseRef struct {
ID uint `json:"id"`
Code *string `json:"code"`
Name string `json:"name"`
Form string `json:"form"`
Lecturer *string `json:"lecturer"`
Semester int `json:"semester"`
}
func newCourseRef(c *models.Course) *courseRef {
if c == nil {
return nil
}
return &courseRef{ID: c.ID, Code: c.Code, Name: c.Name, Form: c.Form, Lecturer: c.Lecturer, Semester: c.Semester}
}
// courseJSON is a course's own fields.
type courseJSON struct {
ID uint `json:"id"`
Code *string `json:"code"`
Name string `json:"name"`
Form string `json:"form"`
Lecturer *string `json:"lecturer"`
Semester int `json:"semester"`
ECTS *float64 `json:"ects"`
Assessment *string `json:"assessment"`
ElectiveGroup *string `json:"elective_group"`
Description *string `json:"description"`
SyllabusURL *string `json:"syllabus_url"`
SortOrder int `json:"sort_order"`
}
func newCourseJSON(c models.Course) courseJSON {
return courseJSON{
ID: c.ID,
Code: c.Code,
Name: c.Name,
Form: c.Form,
Lecturer: c.Lecturer,
Semester: c.Semester,
ECTS: c.ECTS,
Assessment: c.Assessment,
ElectiveGroup: c.ElectiveGroup,
Description: c.Description,
SyllabusURL: c.SyllabusURL,
SortOrder: c.SortOrder,
}
}
// courseCounts are the per-course counters of /courses and /courses/{id}.
type courseCounts struct {
Sessions int64 `json:"sessions"`
Readings int64 `json:"readings"`
ReadingsRead int64 `json:"readings_read"`
Materials int64 `json:"materials"`
}
type courseListJSON struct {
courseJSON
Counts courseCounts `json:"counts"`
}
type courseDetailJSON struct {
courseJSON
Counts courseCounts `json:"counts"`
Sessions []sessionJSON `json:"sessions"`
Readings []readingJSON `json:"readings"`
Materials []materialListJSON `json:"materials"`
}
// meetingJSON is one zjazd.
type meetingJSON struct {
ID uint `json:"id"`
Number int `json:"number"`
StartsOn string `json:"starts_on"`
EndsOn string `json:"ends_on"`
Notes *string `json:"notes"`
SessionsCount int64 `json:"sessions_count"`
}
func newMeetingJSON(m models.Meeting, sessions int64) meetingJSON {
return meetingJSON{ID: m.ID, Number: m.Number, StartsOn: m.StartsOn.String(), EndsOn: m.EndsOn.String(), Notes: m.Notes, SessionsCount: sessions}
}
// sessionJSON is one class session with its course.
type sessionJSON struct {
ID uint `json:"id"`
CourseID uint `json:"course_id"`
MeetingID *uint `json:"meeting_id"`
MeetingNumber *int `json:"meeting_number"`
StartsAt string `json:"starts_at"`
EndsAt string `json:"ends_at"`
Room *string `json:"room"`
Kind *string `json:"kind"`
Lecturer *string `json:"lecturer"`
Notes *string `json:"notes"`
IsOnline bool `json:"is_online"`
Course *courseRef `json:"course"`
}
func newSessionJSON(s models.ClassSession) sessionJSON {
out := sessionJSON{
ID: s.ID,
CourseID: idOf(s.CourseID),
MeetingID: s.MeetingID,
StartsAt: models.FormatDateTime(s.StartsAt),
EndsAt: models.FormatDateTime(s.EndsAt),
Room: s.Room,
Kind: s.Kind,
Lecturer: s.Lecturer,
Notes: s.Notes,
IsOnline: s.IsOnline,
Course: newCourseRef(s.Course),
}
if s.Meeting != nil {
n := s.Meeting.Number
out.MeetingNumber = &n
}
return out
}
func newSessionsJSON(rows []models.ClassSession) []sessionJSON {
out := make([]sessionJSON, 0, len(rows))
for _, s := range rows {
out = append(out, newSessionJSON(s))
}
return out
}
// deadlineJSON is one terminarz entry.
type deadlineJSON struct {
ID uint `json:"id"`
Title string `json:"title"`
DueAt string `json:"due_at"`
Kind string `json:"kind"`
Description *string `json:"description"`
CourseID *uint `json:"course_id"`
Course *courseRef `json:"course"`
}
func newDeadlinesJSON(rows []models.Deadline) []deadlineJSON {
out := make([]deadlineJSON, 0, len(rows))
for _, d := range rows {
out = append(out, deadlineJSON{
ID: d.ID,
Title: d.Title,
DueAt: models.FormatDateTime(d.DueAt),
Kind: d.Kind,
Description: d.Description,
CourseID: d.CourseID,
Course: newCourseRef(d.Course),
})
}
return out
}
// readingJSON is one reading with the caller's read and owned state.
type readingJSON struct {
ID uint `json:"id"`
CourseID uint `json:"course_id"`
Course *courseRef `json:"course"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"`
Author *string `json:"author"`
Source *string `json:"source"`
URL *string `json:"url"`
IsRequired bool `json:"is_required"`
SortOrder int `json:"sort_order"`
ReadAt *string `json:"read_at"`
OwnedAt *string `json:"owned_at"`
}
// tagJSON is one material tag.
type tagJSON struct {
ID uint `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
}
func newTagsJSON(tags []models.Tag) []tagJSON {
out := make([]tagJSON, 0, len(tags))
for _, t := range tags {
out = append(out, tagJSON{ID: t.ID, Name: t.Name, Slug: t.Slug})
}
return out
}
// materialListJSON is a published material the caller may see, in a list.
type materialListJSON struct {
ID uint `json:"id"`
CourseID *uint `json:"course_id"`
Course *courseRef `json:"course"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"`
Type string `json:"type"`
Source *string `json:"source"`
URL *string `json:"url"`
PublishedAt string `json:"published_at"`
Tags []tagJSON `json:"tags"`
FilesCount int64 `json:"files_count"`
IsPrivate bool `json:"is_private"`
// Pinned is the caller's own pin; nobody else sees it.
Pinned bool `json:"pinned"`
// Snippet is the matched passage of a search result (*snippetJSON, or
// a plain string through MCP). It is nil, and the key absent, without
// q or without a highlight.
Snippet any `json:"snippet,omitempty"`
}
func newMaterialListJSON(m models.Material, files int64) materialListJSON {
out := materialListJSON{
ID: m.ID,
CourseID: m.CourseID,
Course: newCourseRef(m.Course),
MeetingID: m.MeetingID,
Title: m.Title,
Type: m.Type,
Source: m.Source,
URL: m.URL,
Tags: newTagsJSON(m.Tags),
FilesCount: files,
IsPrivate: m.IsPrivate,
}
if m.PublishedAt != nil {
out.PublishedAt = models.FormatDateTime(*m.PublishedAt)
}
return out
}
// materialDetailJSON is a published material the caller may see, with its
// body and files. CanManage is true for the caller who may change its access.
// Revision is the content revision an edit sends back.
type materialDetailJSON struct {
materialListJSON
Body *string `json:"body"`
Files []fileJSON `json:"files"`
CanManage bool `json:"can_manage"`
Revision uint `json:"revision"`
}
// fileJSON is one attached file.
type fileJSON struct {
ID uint `json:"id"`
URL string `json:"url"`
Name string `json:"name"`
Size int64 `json:"size"`
Mime string `json:"mime"`
}
// readingsSummary is the reading progress block of /dashboard.
type readingsSummary struct {
Total int64 `json:"total"`
Read int64 `json:"read"`
RequiredTotal int64 `json:"required_total"`
RequiredRead int64 `json:"required_read"`
}

View File

@@ -0,0 +1,121 @@
package api
import (
"encoding/json"
"strings"
"testing"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// TestReadingJSONCarriesMeetingID checks that meeting_id is always present
// in a reading, as a number or as null.
func TestReadingJSONCarriesMeetingID(t *testing.T) {
id := uint(4)
for _, tc := range []struct {
meeting *uint
want string
}{
{&id, `"meeting_id":4`},
{nil, `"meeting_id":null`},
} {
b, err := json.Marshal(readingJSON{ID: 1, Title: "Lektura", MeetingID: tc.meeting})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), tc.want) {
t.Errorf("reading JSON %s does not contain %s", b, tc.want)
}
}
}
// TestMaterialJSONCarriesMeetingID checks that meeting_id is always present
// in a material, as a number or as null.
func TestMaterialJSONCarriesMeetingID(t *testing.T) {
id := uint(4)
for _, tc := range []struct {
meeting *uint
want string
}{
{&id, `"meeting_id":4`},
{nil, `"meeting_id":null`},
} {
b, err := json.Marshal(newMaterialListJSON(models.Material{ID: 1, Title: "Materiał", Type: "pdf", MeetingID: tc.meeting}, 0))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), tc.want) {
t.Errorf("material JSON %s does not contain %s", b, tc.want)
}
}
}
// TestMaterialJSONCarriesPrivacy checks that is_private is always present in
// a material and that the detail carries can_manage, false by default.
func TestMaterialJSONCarriesPrivacy(t *testing.T) {
for _, tc := range []struct {
private bool
want string
}{
{true, `"is_private":true`},
{false, `"is_private":false`},
} {
b, err := json.Marshal(newMaterialListJSON(models.Material{ID: 1, Title: "Materiał", Type: "pdf", IsPrivate: tc.private}, 0))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), tc.want) {
t.Errorf("material JSON %s does not contain %s", b, tc.want)
}
}
b, err := json.Marshal(materialDetailJSON{materialListJSON: newMaterialListJSON(models.Material{ID: 1, Title: "Materiał", Type: "pdf"}, 0)})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"can_manage":false`) {
t.Errorf("material detail JSON %s does not contain can_manage false", b)
}
}
// TestMaterialJSONCarriesPinned checks that pinned is always present in a
// material row, false unless the caller set it, and that the detail carries
// the row's value.
func TestMaterialJSONCarriesPinned(t *testing.T) {
row := newMaterialListJSON(models.Material{ID: 1, Title: "Materiał", Type: "notatka"}, 0)
b, err := json.Marshal(row)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"pinned":false`) {
t.Errorf("material JSON %s does not contain pinned false", b)
}
row.Pinned = true
b, err = json.Marshal(row)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"pinned":true`) {
t.Errorf("pinned material JSON %s does not contain pinned true", b)
}
b, err = json.Marshal(materialDetailJSON{materialListJSON: row})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `"pinned":true`) {
t.Errorf("pinned material detail JSON %s does not contain pinned true", b)
}
}
// TestVisibleMaterialSQL checks the visibility fragment: public, the author,
// or a share of the caller, with the caller id bound twice.
func TestVisibleMaterialSQL(t *testing.T) {
got := visibleMaterialSQL("m")
for _, want := range []string{"m.is_private = FALSE", "m.author_user_id = ?", "jz_bm_material_shares", ".material_id = m.id"} {
if !strings.Contains(got, want) {
t.Errorf("visibleMaterialSQL(m) = %q, missing %q", got, want)
}
}
if n := strings.Count(got, "?"); n != 2 {
t.Errorf("visibleMaterialSQL(m) has %d placeholders, want 2", n)
}
}

934
controllers/api/manage.go Normal file
View File

@@ -0,0 +1,934 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"slices"
"strconv"
"strings"
"time"
"unicode"
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// The management API (/api/v1/bm) is what the console commands do, over
// HTTP: it runs behind golem15.user's shared API-token, scope, and permission
// middleware, not the students' jwt.auth.
// flag reads a boolean query parameter: 1 and true are on.
func flag(r *http.Request, name string) bool {
v := r.URL.Query().Get(name)
return v == "1" || v == "true"
}
func writeInvalid(w http.ResponseWriter, message string) {
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": message})
}
// body reads the request body and answers 413 or 400 itself when it cannot.
func body(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
raw, err := io.ReadAll(r.Body)
var tooLarge *http.MaxBytesError
switch {
case errors.As(err, &tooLarge):
wire.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": true, "message": "Request body too large."})
return nil, false
case err != nil:
wire.WriteJSON(w, http.StatusBadRequest, map[string]any{"error": true, "message": "Unreadable request body."})
return nil, false
}
return raw, true
}
type tokenJSON struct {
ID uint `json:"id"`
Name string `json:"name"`
Scopes []string `json:"scopes"`
ExpiresAt *string `json:"expires_at"`
}
// TokenInfo answers GET /me: the user and the token of the request, to
// check a token without changing anything.
func (h *Handlers) TokenInfo(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
out := map[string]any{"user_id": userID}
cred, _ := bouncer.Credential(r.Context())
if t, ok := cred.(*usermodels.APIToken); ok {
name := ""
if t.Name != nil {
name = *t.Name
}
tj := tokenJSON{ID: t.ID, Name: name, Scopes: wire.Slice(t.Scopes.Get())}
if t.ExpiresAt != nil {
s := models.FormatDateTime(*t.ExpiresAt)
tj.ExpiresAt = &s
}
out["token"] = tj
}
writeData(w, out)
}
type seedCountsJSON struct {
Created int `json:"created"`
Updated int `json:"updated"`
Unchanged int `json:"unchanged"`
Deleted int `json:"deleted"`
}
func newSeedCountsJSON(c classes.SeedCounts) seedCountsJSON {
return seedCountsJSON{Created: c.Created, Updated: c.Updated, Unchanged: c.Unchanged, Deleted: c.Deleted}
}
// ApplySeed answers POST /seed?dry_run=&prune=: bm:seed over HTTP. The body
// is the seed document; the answer is the summary the command prints. A
// document that does not parse or validate is a 422 and writes nothing.
func (h *Handlers) ApplySeed(w http.ResponseWriter, r *http.Request) {
raw, ok := body(w, r)
if !ok {
return
}
file, err := classes.ParseSeed(bytes.NewReader(raw))
if err == nil {
err = file.Validate()
}
if err != nil {
writeInvalid(w, err.Error())
return
}
db, ok := h.db(w, r)
if !ok {
return
}
opts := classes.SeedOptions{DryRun: flag(r, "dry_run"), Prune: flag(r, "prune")}
sum, err := classes.SeedWith(r.Context(), db, file, opts)
if err != nil {
writeOpaque500(w)
return
}
writeData(w, map[string]any{
"dry_run": opts.DryRun,
"prune": opts.Prune,
"summary": map[string]seedCountsJSON{
"meetings": newSeedCountsJSON(sum.Meetings),
"courses": newSeedCountsJSON(sum.Courses),
"class_sessions": newSeedCountsJSON(sum.ClassSessions),
"deadlines": newSeedCountsJSON(sum.Deadlines),
"readings": newSeedCountsJSON(sum.Readings),
},
"removed": wire.Slice(sum.Removed),
})
}
// managedMaterialJSON is a material as the management API shows it: drafts
// too, so published_at may be null, and private ones with their author and
// the users they are shared with.
type managedMaterialJSON struct {
ID uint `json:"id"`
CourseID *uint `json:"course_id"`
Course *courseRef `json:"course"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"`
Type string `json:"type"`
Body *string `json:"body"`
Source *string `json:"source"`
URL *string `json:"url"`
PublishedAt *string `json:"published_at"`
Tags []tagJSON `json:"tags"`
IsPrivate bool `json:"is_private"`
AuthorUserID *uint `json:"author_user_id"`
Author *userRefJSON `json:"author"`
Shares []userRefJSON `json:"shares"`
// Revision is the material's content revision, which a write may send
// back to be refused when the material changed since; UpdatedAt is
// when the row was last written.
Revision uint `json:"revision"`
UpdatedAt string `json:"updated_at"`
// Snippet is the matched passage of a search result, as on the
// student list; nil, and the key absent, without q.
Snippet any `json:"snippet,omitempty"`
}
// materialPeople are the authors and shares of a batch of materials, as
// loadMaterialPeople reads them.
type materialPeople struct {
authors map[uint]userRefJSON
shares map[uint][]userRefJSON
}
// loadMaterialPeople reads the authors and the shares of rows in two
// queries plus one for the shared users.
func loadMaterialPeople(db *gorm.DB, rows ...models.Material) (materialPeople, error) {
var authorIDs, materialIDs []uint
for _, m := range rows {
materialIDs = append(materialIDs, m.ID)
if m.AuthorUserID != nil {
authorIDs = append(authorIDs, *m.AuthorUserID)
}
}
authors, err := userRefsByID(db, authorIDs)
if err != nil {
return materialPeople{}, err
}
shares, err := materialShareRefs(db, materialIDs)
if err != nil {
return materialPeople{}, err
}
return materialPeople{authors: authors, shares: shares}, nil
}
func newManagedMaterialJSON(m models.Material, people materialPeople) managedMaterialJSON {
out := managedMaterialJSON{
ID: m.ID, CourseID: m.CourseID, Course: newCourseRef(m.Course), MeetingID: m.MeetingID, Title: m.Title, Type: m.Type,
Body: m.Body, Source: m.Source, URL: m.URL, Tags: newTagsJSON(m.Tags),
IsPrivate: m.IsPrivate, AuthorUserID: m.AuthorUserID, Shares: people.shares[m.ID],
Revision: m.Revision, UpdatedAt: models.FormatDateTime(m.UpdatedAt),
}
if m.AuthorUserID != nil {
if a, ok := people.authors[*m.AuthorUserID]; ok {
out.Author = &a
}
}
if out.Shares == nil {
out.Shares = []userRefJSON{}
}
if m.PublishedAt != nil {
s := models.FormatDateTime(*m.PublishedAt)
out.PublishedAt = &s
}
return out
}
// ManagedMaterials answers GET /materials?q=&include_body=: every material,
// drafts and private ones included, newest first. With q (2 to 100
// characters) the engine answers candidates, which are loaded in rank order
// with at most one snippet each; when the engine cannot answer the request
// is a 503. An MCP call gets the bodies only with include_body (see
// managedMaterialView) and the snippets as plain text.
func (h *Handlers) ManagedMaterials(w http.ResponseWriter, r *http.Request) {
in := query(r, "q", "include_body")
if !h.validate(w, r, in, manageMaterialsRules) {
return
}
var cands *classes.MaterialCandidates
if q := searchQuery(in); q != "" {
c, err := h.MaterialIndex.Search(r.Context(), classes.MaterialSearch{Q: q})
if err != nil {
writeSearchUnavailable(w)
return
}
cands = &c
}
db, ok := h.db(w, r)
if !ok {
return
}
var rows []models.Material
if cands == nil || len(cands.IDs) > 0 {
q := preloadMaterial(db)
if cands != nil {
q = q.Where("jz_bm_materials.id IN ?", cands.IDs).Order(rankOrder(cands.IDs))
} else {
q = q.Order("jz_bm_materials.id DESC")
}
if err := q.Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
}
people, err := loadMaterialPeople(db, rows...)
if err != nil {
writeOpaque500(w)
return
}
var files map[uint][]models.IndexedFile
if cands != nil {
files, err = snippetFiles(db, materialIDs(rows), cands.Hits)
if err != nil {
writeOpaque500(w)
return
}
}
mcp := viaMCP(r)
out := make([]any, 0, len(rows))
for _, m := range rows {
row := newManagedMaterialJSON(m, people)
if cands != nil {
if hit, ok := cands.Hits[m.ID]; ok {
row.Snippet = snippetValue(pickSnippet(hit, m, files[m.ID]), mcp)
}
}
out = append(out, managedMaterialView(row, mcp, includeBody(r)))
}
writeData(w, out)
}
// materialInput is the body of POST /materials and PUT /materials/{id}.
// Revision is the revision the writer last read: when sent and not the
// stored one the write is a 409 and nothing is written; absent means
// unchecked, so the write overwrites as callers that never send it expect
// (D-04).
type materialInput struct {
CourseID *uint `json:"course_id"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"`
Type string `json:"type"`
Body *string `json:"body"`
Source *string `json:"source"`
URL *string `json:"url"`
PublishedAt *string `json:"published_at"`
Tags *[]string `json:"tags"`
IsPrivate *bool `json:"is_private"`
AuthorUserID *uint `json:"author_user_id"`
ShareUserIDs *[]uint `json:"share_user_ids"`
Revision *uint `json:"revision"`
}
// materialDraft is a decoded and validated material body, ready to apply.
type materialDraft struct {
in materialInput
// hasPublishedAt tells a sent published_at (null included) from an
// absent one.
hasPublishedAt bool
// hasMeetingID tells a sent meeting_id (null included) from an absent
// one: absent keeps the stored meeting, so scripts that never send it
// keep working.
hasMeetingID bool
// hasAuthor tells a sent author_user_id (null included) from an absent
// one.
hasAuthor bool
publishedAt *time.Time
tags []models.Tag
// shares is the checked share_user_ids, when sent.
shares []uint
}
// readMaterial decodes and validates the body of POST /materials and
// PUT /materials/{id}. It answers 400, 413, 422 or 500 itself and returns
// false then.
func (h *Handlers) readMaterial(w http.ResponseWriter, r *http.Request, db *gorm.DB) (materialDraft, bool) {
raw, ok := body(w, r)
if !ok {
return materialDraft{}, false
}
d, err := decodeMaterial(raw)
if err != nil {
writeInvalid(w, "invalid JSON: "+err.Error())
return d, false
}
if !h.checkMaterial(w, db, &d, nil) {
return d, false
}
return d, true
}
// decodeMaterial decodes a material body, refusing unknown keys, and notes
// which of published_at, meeting_id and author_user_id were sent. It does
// not validate the values; checkMaterial does.
func decodeMaterial(raw []byte) (materialDraft, error) {
var d materialDraft
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&d.in); err != nil {
return d, err
}
var keys map[string]json.RawMessage
_ = json.Unmarshal(raw, &keys)
_, d.hasPublishedAt = keys["published_at"]
_, d.hasMeetingID = keys["meeting_id"]
_, d.hasAuthor = keys["author_user_id"]
return d, nil
}
// checkMaterial validates a decoded material body against db and fills in
// its published_at, tags and shares. Its messages join errs, which a caller
// may pre-fill with its own rules (nil means none); when there are any it
// answers one 422 with all of them, and on a database error a 500, and
// returns false then.
func (h *Handlers) checkMaterial(w http.ResponseWriter, db *gorm.DB, d *materialDraft, errs map[string][]string) bool {
if errs == nil {
errs = map[string][]string{}
}
in := &d.in
in.Title = strings.TrimSpace(in.Title)
if in.Title == "" || len(in.Title) > 255 {
errs["title"] = []string{"The title is required and may not be longer than 255 characters."}
}
if !slices.Contains(models.MaterialTypes, in.Type) {
errs["type"] = []string{"The type must be one of: " + strings.Join(models.MaterialTypes, ", ") + "."}
}
if in.Source != nil && len(*in.Source) > 500 {
errs["source"] = []string{"The source may not be longer than 500 characters."}
}
if in.URL != nil && len(*in.URL) > 2048 {
errs["url"] = []string{"The url may not be longer than 2048 characters."}
}
if in.PublishedAt != nil {
t, err := models.ParseDateTime(*in.PublishedAt)
if err != nil {
errs["published_at"] = []string{"The published_at is not a valid date and time."}
}
d.publishedAt = &t
}
if in.Tags != nil {
for _, name := range *in.Tags {
name = strings.TrimSpace(name)
slug := slugify(name)
if slug == "" || len(name) > 100 || len(slug) > 100 {
errs["tags"] = []string{"Each tag must be a name of 1 to 100 characters."}
break
}
if !slices.ContainsFunc(d.tags, func(t models.Tag) bool { return t.Slug == slug }) {
d.tags = append(d.tags, models.Tag{Name: name, Slug: slug})
}
}
}
if in.CourseID != nil {
var n int64
if err := db.Model(&models.Course{}).Where("id = ?", *in.CourseID).Count(&n).Error; err != nil {
writeOpaque500(w)
return false
}
if n == 0 {
errs["course_id"] = []string{"The selected course_id is invalid."}
}
}
if in.MeetingID != nil {
var n int64
if err := db.Model(&models.Meeting{}).Where("id = ?", *in.MeetingID).Count(&n).Error; err != nil {
writeOpaque500(w)
return false
}
if n == 0 {
errs["meeting_id"] = []string{"The selected meeting_id is invalid."}
}
}
if in.AuthorUserID != nil {
found, err := userRefsByID(db, []uint{*in.AuthorUserID})
if err != nil {
writeOpaque500(w)
return false
}
if _, ok := found[*in.AuthorUserID]; !ok {
errs["author_user_id"] = []string{"The selected author_user_id is invalid."}
}
}
if in.ShareUserIDs != nil {
clean, msg, err := cleanUserIDs(db, *in.ShareUserIDs)
if err != nil {
writeOpaque500(w)
return false
}
if msg != "" {
errs["share_user_ids"] = []string{msg}
}
d.shares = clean
}
if len(errs) > 0 {
writeValidation(w, errs)
return false
}
return true
}
// identity scopes a query to the materials with the draft's title and
// course: the identity POST /materials upserts on.
func (d materialDraft) identity(q *gorm.DB) *gorm.DB {
q = q.Where("title = ?", d.in.Title)
if d.in.CourseID != nil {
return q.Where("course_id = ?", *d.in.CourseID)
}
return q.Where("course_id IS NULL")
}
// apply writes the draft onto m inside tx. published_at: absent publishes
// a new material now and keeps an existing one as it is; null makes a
// draft; otherwise the sent time. meeting_id: absent keeps it; null clears
// it. tags: absent keeps them; otherwise the list replaces them, and unknown
// tags are created. is_private: absent keeps it (a new material is public).
// author_user_id: absent keeps it (a new material gets callerID); null
// clears it. share_user_ids: absent keeps the shares; otherwise the list
// replaces them.
func (d materialDraft) apply(tx *gorm.DB, m *models.Material, created bool, now time.Time, callerID uint) error {
in := d.in
m.CourseID, m.Title, m.Type = in.CourseID, in.Title, in.Type
m.Body, m.Source, m.URL = in.Body, in.Source, in.URL
if d.hasMeetingID {
m.MeetingID = in.MeetingID
}
if in.IsPrivate != nil {
m.IsPrivate = *in.IsPrivate
}
switch {
case d.hasAuthor:
m.AuthorUserID = in.AuthorUserID
case created && callerID != 0:
id := callerID
m.AuthorUserID = &id
}
switch {
case d.hasPublishedAt:
m.PublishedAt = d.publishedAt
case created:
m.PublishedAt = &now
}
if err := tx.Omit("Course", "Meeting", "Tags").Save(m).Error; err != nil {
return err
}
if in.ShareUserIDs != nil {
if err := replaceMaterialShares(tx, m.ID, d.shares); err != nil {
return err
}
}
if in.Tags == nil {
return nil
}
if err := tx.Where("material_id = ?", m.ID).Delete(&models.MaterialTag{}).Error; err != nil {
return err
}
for _, t := range d.tags {
var tag models.Tag
res := tx.Where("slug = ?", t.Slug).Limit(1).Find(&tag)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
tag = t
if err := tx.Create(&tag).Error; err != nil {
return err
}
}
if err := tx.Create(&models.MaterialTag{MaterialID: m.ID, TagID: tag.ID}).Error; err != nil {
return err
}
}
return nil
}
// writeManaged answers a write of r with the material id, reloaded with its
// course and tags, plus any extra top-level keys. Under MCP the answer never
// echoes the body.
func writeManaged(w http.ResponseWriter, r *http.Request, db *gorm.DB, id uint, status int, extra map[string]any) {
var out models.Material
if err := preloadMaterial(db).First(&out, id).Error; err != nil {
writeOpaque500(w)
return
}
people, err := loadMaterialPeople(db, out)
if err != nil {
writeOpaque500(w)
return
}
payload := map[string]any{"data": managedMaterialView(newManagedMaterialJSON(out, people), viaMCP(r), false)}
for k, v := range extra {
payload[k] = v
}
wire.WriteJSON(w, status, payload)
}
// UpsertMaterial answers POST /materials: it creates the material, or
// updates the one with the same title and course, so sending a document
// twice changes nothing. body, source and url are replaced as sent; see
// materialDraft.apply for published_at and tags. A renamed material is a
// new one here: PUT /materials/{id} renames. revision is checked only when
// the upsert updates an existing material, on its row locked for the write:
// a stale one is a 409 with the current version (writeConflict) and nothing
// is written. A create ignores it and starts at revision 1. The revision
// goes up only when the content changed (models.ReviseMaterial).
func (h *Handlers) UpsertMaterial(w http.ResponseWriter, r *http.Request) {
callerID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
d, ok := h.readMaterial(w, r, db)
if !ok {
return
}
var m models.Material
created, conflict := false, false
err := lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
res := d.identity(tx.Clauses(clause.Locking{Strength: "UPDATE"})).Order("id").Limit(1).Find(&m)
if res.Error != nil {
return res.Error
}
created = res.RowsAffected == 0
if created {
return d.apply(tx, &m, true, h.now(), callerID)
}
if staleRevision(d.in.Revision, m.Revision) {
conflict = true
return nil
}
before, err := models.MaterialContent(tx, m.ID)
if err != nil {
return err
}
if err := d.apply(tx, &m, false, h.now(), callerID); err != nil {
return err
}
return h.revise(ctx, tx, m.ID, before)
})
if err != nil {
writeOpaque500(w)
return
}
if conflict {
writeConflict(w, r, db, m.ID)
return
}
h.MaterialIndex.Sync(r.Context(), db, m.ID)
status := http.StatusOK
if created {
status = http.StatusCreated
}
writeManaged(w, r, db, m.ID, status, map[string]any{"created": created})
}
// UpdateMaterial answers PUT /materials/{id}: the same body as POST, applied
// to that material, so a title or course can change. A title and course
// another material already has is a 422, because POST would then be
// ambiguous. An unknown id is a 404. The row is locked for the write: a sent
// revision that is not the stored one is a 409 with the current version
// (writeConflict) and nothing is written; without revision the write
// overwrites. The revision goes up only when the content changed
// (models.ReviseMaterial).
func (h *Handlers) UpdateMaterial(w http.ResponseWriter, r *http.Request) {
callerID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return
}
d, ok := h.readMaterial(w, r, db)
if !ok {
return
}
var m models.Material
found, taken, conflict := false, false, false
err := lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
res := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return nil
}
found = true
if staleRevision(d.in.Revision, m.Revision) {
conflict = true
return nil
}
before, err := models.MaterialContent(tx, m.ID)
if err != nil {
return err
}
var n int64
if err := d.identity(tx.Model(&models.Material{})).Where("id <> ?", m.ID).Count(&n).Error; err != nil {
return err
}
if n > 0 {
taken = true
return nil
}
if err := d.apply(tx, &m, false, h.now(), callerID); err != nil {
return err
}
return h.revise(ctx, tx, m.ID, before)
})
switch {
case err != nil:
writeOpaque500(w)
case !found:
writeNotFound(w)
case conflict:
writeConflict(w, r, db, m.ID)
case taken:
writeValidation(w, map[string][]string{"title": {"Another material already has this title and course."}})
default:
h.MaterialIndex.Sync(r.Context(), db, m.ID)
writeManaged(w, r, db, m.ID, http.StatusOK, nil)
}
}
// managedMaterialDetailJSON is GET /materials/{id}: the material with its
// public files.
type managedMaterialDetailJSON struct {
managedMaterialJSON
Files []fileJSON `json:"files"`
}
// ManagedMaterial answers GET /materials/{id}: one material, draft or not,
// with its public files.
func (h *Handlers) ManagedMaterial(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return
}
h.writeMaterialDetail(w, r, db, uint(id), http.StatusOK)
}
// writeMaterialDetail answers r with the material id as GET /materials/{id}
// shows it, or 404 when there is none. Under MCP a GET carries the body only
// with include_body, and any other method's answer never does.
func (h *Handlers) writeMaterialDetail(w http.ResponseWriter, r *http.Request, db *gorm.DB, id uint, status int) {
h.writeMaterialDetailWith(w, r, db, id, status, nil)
}
// writeMaterialDetailWith is writeMaterialDetail with extra top-level keys
// beside data (the file warning of the inline upload).
func (h *Handlers) writeMaterialDetailWith(w http.ResponseWriter, r *http.Request, db *gorm.DB, id uint, status int, extra map[string]any) {
var m models.Material
res := preloadMaterial(db).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
var files []attach.File
if err := materialFiles(db, m).Order("sort_order, id").Find(&files).Error; err != nil {
writeOpaque500(w)
return
}
people, err := loadMaterialPeople(db, m)
if err != nil {
writeOpaque500(w)
return
}
out := managedMaterialDetailJSON{managedMaterialJSON: newManagedMaterialJSON(m, people), Files: make([]fileJSON, 0, len(files))}
for i := range files {
f := &files[i]
if !f.Public() {
continue
}
out.Files = append(out.Files, fileJSON{ID: f.ID, URL: f.URL(), Name: f.FileName, Size: f.FileSize, Mime: f.ContentType})
}
answer := map[string]any{"data": managedMaterialDetailView(out, viaMCP(r), r.Method == http.MethodGet && includeBody(r))}
for k, v := range extra {
answer[k] = v
}
wire.WriteJSON(w, status, answer)
}
// DeleteMaterial answers DELETE /materials/{id}.
func (h *Handlers) DeleteMaterial(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return
}
var keys []string
found := false
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
res := tx.Where("id = ?", id).Delete(&models.Material{})
if res.Error != nil || res.RowsAffected == 0 {
return res.Error
}
found = true
return attach.DeleteForOwner(tx, models.Material{}, strconv.FormatInt(id, 10), func(k []string) error {
keys = k
return nil
})
})
switch {
case err != nil:
writeOpaque500(w)
return
case !found:
writeNotFound(w)
return
}
// The delete statement has no primary key on its model, so no callback
// removes the document: remove it now that the transaction committed.
h.MaterialIndex.Remove(r.Context(), db, uint(id))
// The files go with the material: rows in the transaction, blobs after it.
if b := h.Bucket; b != nil && len(keys) > 0 {
if bucket := b(); bucket != nil {
_ = attach.DeleteKeys(r.Context(), bucket, keys)
}
}
w.WriteHeader(http.StatusNoContent)
}
// polish maps the Polish letters slugify cannot fold by case alone.
var polish = strings.NewReplacer("ą", "a", "ć", "c", "ę", "e", "ł", "l", "ń", "n", "ó", "o", "ś", "s", "ź", "z", "ż", "z")
// slugify turns a tag name into its slug: lower-case ASCII letters and
// digits, with a hyphen for every run of anything else.
func slugify(name string) string {
var b strings.Builder
hyphen := false
for _, r := range polish.Replace(strings.ToLower(name)) {
if r < unicode.MaxASCII && (unicode.IsLetter(r) || unicode.IsDigit(r)) {
if hyphen && b.Len() > 0 {
b.WriteByte('-')
}
hyphen = false
b.WriteRune(r)
continue
}
hyphen = true
}
return b.String()
}
// managedAccessChange loads the material of r by id and, unless decode
// refuses the body, applies the access change it returns inside a
// transaction with the claim rule (a material with no author gets the
// caller). It answers 404, 422 or 500 itself, and on success the material as
// writeManaged shows it, so under MCP the body is never echoed.
func (h *Handlers) managedAccessChange(w http.ResponseWriter, r *http.Request, decode func(db *gorm.DB, raw []byte) (isPrivate *bool, setShares bool, shares []uint, ok bool)) {
callerID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return
}
var m models.Material
res := db.Where("id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
raw, ok := body(w, r)
if !ok {
return
}
isPrivate, setShares, shares, ok := decode(db, raw)
if !ok {
return
}
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
return applyMaterialAccess(tx, &m, callerID, isPrivate, setShares, shares)
})
if err != nil {
writeOpaque500(w)
return
}
// An access change touches only visibility (and the author), which the
// search index does not hold, so it does not sync.
writeManaged(w, r, db, m.ID, http.StatusOK, nil)
}
// SetMaterialVisibility answers PATCH /materials/{id}/visibility, body
// {"is_private": bool}: private means only the author and the users it is
// shared with see the material. A material with no author gets the caller
// as author. An unknown id is a 404.
func (h *Handlers) SetMaterialVisibility(w http.ResponseWriter, r *http.Request) {
h.managedAccessChange(w, r, func(_ *gorm.DB, raw []byte) (*bool, bool, []uint, bool) {
var in struct {
IsPrivate *bool `json:"is_private"`
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeInvalid(w, "invalid JSON: "+err.Error())
return nil, false, nil, false
}
if in.IsPrivate == nil {
writeValidation(w, map[string][]string{"is_private": {"The is_private field is required and must be true or false."}})
return nil, false, nil, false
}
return in.IsPrivate, false, nil, true
})
}
// SetMaterialShares answers PUT /materials/{id}/shares, body
// {"user_ids": [id]}: the list (null meaning none) replaces the users the
// material is shared with. The claim rule is as for SetMaterialVisibility.
func (h *Handlers) SetMaterialShares(w http.ResponseWriter, r *http.Request) {
h.managedAccessChange(w, r, func(db *gorm.DB, raw []byte) (*bool, bool, []uint, bool) {
var in struct {
UserIDs []uint `json:"user_ids"`
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeInvalid(w, "invalid JSON: "+err.Error())
return nil, false, nil, false
}
var keys map[string]json.RawMessage
_ = json.Unmarshal(raw, &keys)
if _, ok := keys["user_ids"]; !ok {
writeValidation(w, map[string][]string{"user_ids": {"The user_ids field is required: a list of user ids, empty for none."}})
return nil, false, nil, false
}
clean, msg, err := cleanUserIDs(db, in.UserIDs)
if err != nil {
writeOpaque500(w)
return nil, false, nil, false
}
if msg != "" {
writeValidation(w, map[string][]string{"user_ids": {msg}})
return nil, false, nil, false
}
return nil, true, clean, true
})
}
// ManagedUsers answers GET /users: the id, display name and email of every
// user, to pick a material's author or shares.
func (h *Handlers) ManagedUsers(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
users, err := listUserRefs(db, 0)
if err != nil {
writeOpaque500(w)
return
}
writeData(w, users)
}

View File

@@ -0,0 +1,281 @@
package api
import (
"context"
"errors"
"io"
"mime/multipart"
"net/http"
"strconv"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// MaterialFileMaxBytes is the largest file the management API stores, the
// admin form's maxFilesize (50 MB).
const MaterialFileMaxBytes = 50 << 20
// MaterialFilesBodyLimit is the body cap of POST /materials/{id}/files: one
// file of MaterialFileMaxBytes plus the multipart framing.
const MaterialFilesBodyLimit = MaterialFileMaxBytes + 1<<20
// MaterialFilesMax is the most files a material holds, the admin form's
// maxFiles.
const MaterialFilesMax = 20
// fileLimits are the attach.Store rules of a material file: the default
// document and image extensions, up to MaterialFileMaxBytes.
var fileLimits = attach.Limits{MaxBytes: MaterialFileMaxBytes}
func (h *Handlers) bucket(w http.ResponseWriter) (*blob.Bucket, bool) {
var b *blob.Bucket
if h.Bucket != nil {
b = h.Bucket()
}
if b == nil {
writeOpaque500(w)
return nil, false
}
return b, true
}
func materialFiles(db *gorm.DB, m models.Material) *gorm.DB {
return db.Where("attachment_type = ? AND attachment_id = ? AND field = ?",
m.MorphName(), strconv.FormatUint(uint64(m.ID), 10), models.MaterialFilesField)
}
// findMaterial loads the material of the {id} path parameter and answers 404
// itself when there is none.
func findMaterial(w http.ResponseWriter, r *http.Request, db *gorm.DB) (models.Material, bool) {
var m models.Material
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return m, false
}
res := db.Where("id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
writeOpaque500(w)
return m, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return m, false
}
return m, true
}
// AttachMaterialFiles answers POST /materials/{id}/files: a multipart body
// whose "file" parts are stored as public files of the material, after the
// ones it has. Every part is checked by attach.Store (type, size); one
// refused part refuses the request and stores nothing. The answer is the
// material as GET /materials/{id} shows it, 201.
func (h *Handlers) AttachMaterialFiles(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
bucket, ok := h.bucket(w)
if !ok {
return
}
m, ok := findMaterial(w, r, db)
if !ok {
return
}
mr, err := r.MultipartReader()
if err != nil {
writeInvalid(w, "Send the files as multipart/form-data in parts named \"file\".")
return
}
var refusal string
// The blobs written are deleted again when the transaction did not commit.
stored, err := h.storeParts(r.Context(), db, bucket, m, mr, &refusal)
if err != nil || refusal != "" {
if len(stored) > 0 {
_ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, stored)
}
var tooLarge *http.MaxBytesError
switch {
case refusal != "":
writeValidation(w, map[string][]string{"file": {refusal}})
case errors.As(err, &tooLarge):
wire.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": true, "message": "Request body too large."})
default:
writeOpaque500(w)
}
return
}
h.writeMaterialDetail(w, r, db, m.ID, http.StatusCreated)
}
// storeParts stores and binds every "file" part in one transaction and
// queues the file text job in it. A
// refusal (no file, too many, a type or size attach.Store turns down) is
// set in *refusal and rolls back; the returned keys are the blobs written.
func (h *Handlers) storeParts(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, m models.Material, mr *multipart.Reader, refusal *string) ([]string, error) {
var keys []string
errRefused := errors.New("refused")
err := lagoon.Transaction(ctx, db, func(_ context.Context, tx *gorm.DB) error {
added := 0
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return err
}
if part.FormName() != "file" || part.FileName() == "" {
part.Close()
continue
}
f, why, err := storeMaterialFile(ctx, tx, bucket, m, part.FileName(), part, fileLimits)
part.Close()
if f != nil {
keys = append(keys, attach.BlobKeys(*f)...)
}
if err != nil {
return err
}
if why != "" {
*refusal = why
return errRefused
}
added++
}
if added == 0 {
*refusal = "No file: send at least one multipart part named \"file\"."
return errRefused
}
// The text job joins the transaction: it exists only when the
// files commit, and it syncs the material's document.
h.MaterialIndex.QueueExtract(ctx, tx, m.ID)
return nil
})
if errors.Is(err, errRefused) {
err = nil
}
return keys, err
}
// fileRefusal is a file the material routes turn down, with no error:
// Reason is "count" (the material holds MaterialFilesMax files), "size"
// (attach.ErrTooLarge) or "type" (a type attach.Store refuses), and Text the
// message of the answer. The zero value is no refusal.
type fileRefusal struct {
Reason string
Text string
}
// fileRefusalFor maps an attach.Store error to the refusal of file name
// under lim, and reports false for an error that is not a refusal (nil
// included). attach.ErrNotImage, the refusal of image mode, is a type
// refusal, not a 500.
func fileRefusalFor(err error, name string, lim attach.Limits) (fileRefusal, bool) {
switch {
case errors.Is(err, attach.ErrTooLarge):
return fileRefusal{Reason: "size", Text: name + ": the file is larger than " + sizeMB(lim.MaxBytes) + "."}, true
case errors.Is(err, attach.ErrFileType), errors.Is(err, attach.ErrMIMEType), errors.Is(err, attach.ErrNotImage):
return fileRefusal{Reason: "type", Text: name + ": this file type is not allowed."}, true
}
return fileRefusal{}, false
}
// storeMaterialUpload stores one file through attach.Store as a public file
// of m and binds it to the material, inside tx. It is the only way the API
// writes a material file: the multipart route, the inline (base64) route,
// the signed upload and the editor image route all come through it. The
// material's MaterialFilesMax cap and attach's extension, MIME, image and
// size checks (lim) apply. A refusal is returned with no error; the
// returned file, when not nil, has blobs the caller deletes when tx does
// not commit.
func storeMaterialUpload(ctx context.Context, tx *gorm.DB, bucket *blob.Bucket, m models.Material, name string, body io.Reader, lim attach.Limits) (*attach.File, fileRefusal, error) {
var have int64
if err := materialFiles(tx.Model(&attach.File{}), m).Count(&have).Error; err != nil {
return nil, fileRefusal{}, err
}
if have >= MaterialFilesMax {
return nil, fileRefusal{Reason: "count", Text: "A material holds at most " + strconv.Itoa(MaterialFilesMax) + " files."}, nil
}
f, err := attach.Store(ctx, tx, bucket, attach.Upload{FileName: name, Body: body, Public: true}, lim)
if why, ok := fileRefusalFor(err, name, lim); ok {
return nil, why, nil
}
if err != nil {
return nil, fileRefusal{}, err
}
err = tx.Model(&attach.File{}).Where("id = ?", f.ID).Updates(map[string]any{
"attachment_type": m.MorphName(),
"attachment_id": strconv.FormatUint(uint64(m.ID), 10),
"field": models.MaterialFilesField,
}).Error
return f, fileRefusal{}, err
}
// storeMaterialFile is storeMaterialUpload with the refusal as its text,
// for the management routes that answer only the text.
func storeMaterialFile(ctx context.Context, tx *gorm.DB, bucket *blob.Bucket, m models.Material, name string, body io.Reader, lim attach.Limits) (*attach.File, string, error) {
f, why, err := storeMaterialUpload(ctx, tx, bucket, m, name, body, lim)
return f, why.Text, err
}
// sizeMB names a byte limit in the refusal texts: 50 MB for 50 MiB, 3 MB
// for 3000000 bytes.
func sizeMB(n int64) string {
if n%(1<<20) == 0 {
return strconv.FormatInt(n>>20, 10) + " MB"
}
return strconv.FormatInt(n/1_000_000, 10) + " MB"
}
// DetachMaterialFile answers DELETE /materials/{id}/files/{file}: the file
// row goes (its extracted text with it), the material is resynced, then the
// blob and thumbnails go. A file of another material is a
// 404.
func (h *Handlers) DetachMaterialFile(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
bucket, ok := h.bucket(w)
if !ok {
return
}
m, ok := findMaterial(w, r, db)
if !ok {
return
}
fileID, ok := surf.IntParam(r, "file")
if !ok {
writeNotFound(w)
return
}
var f attach.File
res := materialFiles(db, m).Where("id = ?", fileID).Limit(1).Find(&f)
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
if err := db.Where("id = ?", f.ID).Delete(&attach.File{}).Error; err != nil {
writeOpaque500(w)
return
}
// The file's text row went with it (foreign-key cascade); the resync
// drops the text from the material's document.
h.MaterialIndex.Sync(r.Context(), db, m.ID)
// The row is gone, so the file is no longer served; a blob left behind
// by a failed delete is only disk space.
_ = attach.DeleteKeys(r.Context(), bucket, attach.BlobKeys(f))
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -0,0 +1,400 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"reflect"
"slices"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// The record routes of the management API: courses, meetings, class
// sessions, readings and deadlines, one by one, so a script changes a row
// without a seed run. A body is a JSON object keyed by column names; only the
// model's Fillable() columns are accepted (anything else is a 422), the
// model's Rules() are checked as in the admin, against the row as it would
// be saved, and so is TemporalErrors() where a model has it. A record is
// answered as an object of its columns, times as RFC 3339 in Europe/Warsaw
// and dates as YYYY-MM-DD.
// recordModel is what a managed model provides.
type recordModel interface {
TableName() string
Fillable() []string
Rules() map[string]string
}
type temporalChecker interface {
TemporalErrors() map[string][]string
}
// Record describes one managed table.
type Record[T any, PT interface {
*T
recordModel
}] struct {
// Filters are the columns a list may be filtered on (?column=value).
Filters []string
// Order is the ORDER BY of a list.
Order string
// References maps a foreign key column to the table it must exist in.
References map[string]string
}
func (rec Record[T, PT]) table() string { return PT(new(T)).TableName() }
// List answers GET /{records}: every row, filtered by the query parameters
// named in Filters.
func (rec Record[T, PT]) List(h *Handlers) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
q := db.Model(new(T))
for _, col := range rec.Filters {
v := r.URL.Query().Get(col)
switch {
case v == "":
continue
case v == "null":
q = q.Where(col + " IS NULL")
default:
q = q.Where(col+" = ?", v)
}
}
var rows []T
if err := q.Order(rec.Order).Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
out := make([]map[string]any, 0, len(rows))
for i := range rows {
out = append(out, recordJSON(&rows[i]))
}
writeData(w, out)
}
}
// Show answers GET /{records}/{id}.
func (rec Record[T, PT]) Show(h *Handlers) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
row, ok := rec.find(w, r, db)
if !ok {
return
}
writeData(w, recordJSON(row))
}
}
// Create answers POST /{records}: 201 with the new row.
func (rec Record[T, PT]) Create(h *Handlers) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
rec.save(w, r, h, db, new(T), true)
}
}
// Update answers PATCH /{records}/{id}: the sent columns change, the rest
// stay.
func (rec Record[T, PT]) Update(h *Handlers) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
row, ok := rec.find(w, r, db)
if !ok {
return
}
rec.save(w, r, h, db, row, false)
}
}
// Delete answers DELETE /{records}/{id}: 204. Dependent rows follow the
// foreign keys (reading progress goes with its reading).
func (rec Record[T, PT]) Delete(h *Handlers) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return
}
res := db.Where("id = ?", id).Delete(new(T))
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func (rec Record[T, PT]) find(w http.ResponseWriter, r *http.Request, db *gorm.DB) (*T, bool) {
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return nil, false
}
row := new(T)
res := db.Where("id = ?", id).Limit(1).Find(row)
if res.Error != nil {
writeOpaque500(w)
return nil, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return nil, false
}
return row, true
}
// save decodes the body onto row, validates the result and writes it.
func (rec Record[T, PT]) save(w http.ResponseWriter, r *http.Request, h *Handlers, db *gorm.DB, row *T, created bool) {
if _, ok := h.fillRecord(w, r, db, row, PT(row), rec.References, nil); !ok {
return
}
writeSaved(w, r, db, row, created)
}
// fillRecord decodes the JSON body onto row (only model.Fillable() keys),
// then checks model.Rules() and TemporalErrors() against the row as it
// would be saved, that every foreign key in references names an existing
// row, and extra (when given) for checks of its own. It answers 422 or 500
// itself and returns false when the row must not be saved; else it returns
// the row as a column map.
func (h *Handlers) fillRecord(w http.ResponseWriter, r *http.Request, db *gorm.DB, row any, model recordModel,
references map[string]string, extra func(check map[string]any, errs map[string][]string) error) (map[string]any, bool) {
raw, ok := body(w, r)
if !ok {
return nil, false
}
var in map[string]any
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&in); err != nil || in == nil {
writeInvalid(w, "The body must be a JSON object of columns.")
return nil, false
}
fillable := model.Fillable()
errs := map[string][]string{}
for key := range in {
if !slices.Contains(fillable, key) {
errs[key] = []string{"Unknown or read-only field; allowed: " + strings.Join(fillable, ", ") + "."}
}
}
if len(errs) > 0 {
writeValidation(w, errs)
return nil, false
}
values, fieldErrs := normalizeValues(row, in)
for k, v := range fieldErrs {
errs[k] = v
}
if len(errs) == 0 {
var typeErr *lagoon.FillTypeError
if err := lagoon.Fill(row, fillable, values, true); errors.As(err, &typeErr) {
errs[typeErr.Key] = []string{"The " + typeErr.Key + " has the wrong type."}
} else if err != nil {
writeOpaque500(w)
return nil, false
}
}
if len(errs) > 0 {
writeValidation(w, errs)
return nil, false
}
// The rules run on the row as it would be saved, so a PATCH of one
// column still meets the required ones.
check := recordJSON(row)
verrs, err := lagoon.Validate(r.Context(), db, row, model.Rules(), check, h.translator())
if err != nil {
writeOpaque500(w)
return nil, false
}
for k, v := range verrs {
errs[k] = v
}
if tc, ok := row.(temporalChecker); ok {
for k, v := range tc.TemporalErrors() {
errs[k] = append(errs[k], v...)
}
}
for col, table := range references {
id, ok := check[col].(uint)
if !ok || id == 0 {
continue
}
var n int64
if err := db.Table(table).Where("id = ?", id).Count(&n).Error; err != nil {
writeOpaque500(w)
return nil, false
}
if n == 0 {
errs[col] = append(errs[col], "The selected "+col+" is invalid.")
}
}
if extra != nil {
if err := extra(check, errs); err != nil {
writeOpaque500(w)
return nil, false
}
}
if len(errs) > 0 {
writeValidation(w, errs)
return nil, false
}
return check, true
}
// writeSaved saves row in a transaction and answers it as a column map, 201
// when created.
func writeSaved(w http.ResponseWriter, r *http.Request, db *gorm.DB, row any, created bool) {
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
return tx.Save(row).Error
})
if err != nil {
writeOpaque500(w)
return
}
status := http.StatusOK
if created {
status = http.StatusCreated
}
wire.WriteJSON(w, status, map[string]any{"data": recordJSON(row)})
}
var (
timeType = reflect.TypeOf(time.Time{})
dateType = reflect.TypeOf(lagoon.Date{})
)
// columns maps the column names of a model to their struct field indexes.
func columns(t reflect.Type) map[string]int {
out := map[string]int{}
for i := 0; i < t.NumField(); i++ {
for _, part := range strings.Split(t.Field(i).Tag.Get("gorm"), ";") {
if name, ok := strings.CutPrefix(part, "column:"); ok {
out[name] = i
}
}
}
return out
}
// normalizeValues turns the decoded JSON into what lagoon.Fill takes:
// numbers as int64 or float64, times parsed in Europe/Warsaw (RFC 3339 or
// "2006-01-02 15:04"), dates as YYYY-MM-DD, and "" as null for optional
// text.
func normalizeValues(row any, in map[string]any) (map[string]any, map[string][]string) {
t := reflect.TypeOf(row).Elem()
cols := columns(t)
out := make(map[string]any, len(in))
errs := map[string][]string{}
for key, v := range in {
ft := t.Field(cols[key]).Type
base := ft
if base.Kind() == reflect.Pointer {
base = base.Elem()
}
switch val := v.(type) {
case json.Number:
if base.Kind() == reflect.String {
// A room or code sent as a number ("room": 107).
out[key] = val.String()
continue
}
if i, err := val.Int64(); err == nil {
out[key] = i
} else if f, err := val.Float64(); err == nil {
out[key] = f
} else {
errs[key] = []string{"The " + key + " is not a number."}
}
continue
case string:
switch base {
case timeType:
tm, err := models.ParseDateTime(val)
if err != nil {
errs[key] = []string{"The " + key + " is not a valid date and time."}
continue
}
out[key] = tm
continue
case dateType:
d, err := models.ParseDate(val)
if err != nil {
errs[key] = []string{"The " + key + " is not a valid date (YYYY-MM-DD)."}
continue
}
out[key] = d
continue
}
if val == "" && ft.Kind() == reflect.Pointer {
out[key] = nil
continue
}
}
out[key] = v
}
return out, errs
}
// recordJSON is a row as an object of its columns.
func recordJSON(row any) map[string]any {
v := reflect.ValueOf(row).Elem()
cols := columns(v.Type())
out := make(map[string]any, len(cols))
for name, i := range cols {
f := v.Field(i)
if f.Kind() == reflect.Pointer {
if f.IsNil() {
out[name] = nil
continue
}
f = f.Elem()
}
switch x := f.Interface().(type) {
case time.Time:
if x.IsZero() {
out[name] = nil
} else {
out[name] = models.FormatDateTime(x)
}
case lagoon.Date:
if x.IsZero() {
out[name] = nil
} else {
out[name] = x.String()
}
default:
out[name] = x
}
}
return out
}

View File

@@ -0,0 +1,446 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"time"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/controllers"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Private materials: a material with is_private is visible only to its
// author and to the users it is shared with (jz_bm_material_shares). Every
// student read goes through visibleMaterials or, in raw SQL, through
// visibleMaterialSQL, so a private material never shows up elsewhere.
// visibleMaterialSQL is the visibility condition of the materials table
// under alias: public, written by the caller, or shared with the caller. It
// takes the args (userID, userID).
func visibleMaterialSQL(alias string) string {
return "(" + alias + ".is_private = FALSE OR " + alias + ".author_user_id = ? OR EXISTS (SELECT 1 FROM jz_bm_material_shares ms WHERE ms.material_id = " + alias + ".id AND ms.user_id = ?))"
}
// visibleMaterials scopes a material query to what the caller may see: a
// publication time that has passed and the visibility rule. It is the only
// scope student material reads may use.
func visibleMaterials(q *gorm.DB, now time.Time, userID uint) *gorm.DB {
return published(q, now).Where(visibleMaterialSQL("jz_bm_materials"), userID, userID)
}
// userRefJSON is a user as the material access lists show it.
type userRefJSON struct {
ID uint `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// newUserRef labels a user by "name surname", or by the email when both are
// empty.
func newUserRef(u usermodels.User) userRefJSON {
name := strings.TrimSpace(deref(u.Name) + " " + deref(u.Surname))
if name == "" {
name = u.Email
}
return userRefJSON{ID: u.ID, Name: name, Email: u.Email}
}
func selectUserRefs(db *gorm.DB) *gorm.DB {
return db.Model(&usermodels.User{}).Select("id", "name", "surname", "email")
}
// listUserRefs lists every user but excludeID (none when 0), by name.
func listUserRefs(db *gorm.DB, excludeID uint) ([]userRefJSON, error) {
q := selectUserRefs(db)
if excludeID != 0 {
q = q.Where("id <> ?", excludeID)
}
var users []usermodels.User
if err := q.Order("name, surname, email, id").Find(&users).Error; err != nil {
return nil, err
}
out := make([]userRefJSON, 0, len(users))
for _, u := range users {
out = append(out, newUserRef(u))
}
return out, nil
}
// userRefsByID returns the existing users among ids, keyed by id.
func userRefsByID(db *gorm.DB, ids []uint) (map[uint]userRefJSON, error) {
out := map[uint]userRefJSON{}
if len(ids) == 0 {
return out, nil
}
var users []usermodels.User
if err := selectUserRefs(db).Where("id IN ?", ids).Find(&users).Error; err != nil {
return nil, err
}
for _, u := range users {
out[u.ID] = newUserRef(u)
}
return out, nil
}
// materialShareRefs returns the users each material is shared with, by user
// id. Deleted users drop out.
func materialShareRefs(db *gorm.DB, materialIDs []uint) (map[uint][]userRefJSON, error) {
out := map[uint][]userRefJSON{}
if len(materialIDs) == 0 {
return out, nil
}
var rows []models.MaterialShare
if err := db.Where("material_id IN ?", materialIDs).Order("material_id, user_id").Find(&rows).Error; err != nil {
return nil, err
}
userIDs := make([]uint, 0, len(rows))
for _, row := range rows {
userIDs = append(userIDs, row.UserID)
}
users, err := userRefsByID(db, userIDs)
if err != nil {
return nil, err
}
for _, row := range rows {
if u, ok := users[row.UserID]; ok {
out[row.MaterialID] = append(out[row.MaterialID], u)
}
}
return out, nil
}
// maxShareUsers caps the users one material may be shared with.
const maxShareUsers = 200
// cleanUserIDs dedupes a share list and checks it: no zero ids, at most
// maxShareUsers, and every id an existing user. msg is the validation
// message when the list is refused.
func cleanUserIDs(db *gorm.DB, ids []uint) ([]uint, string, error) {
clean := make([]uint, 0, len(ids))
for _, id := range ids {
if id == 0 {
return nil, "Each user id must be a positive number.", nil
}
if !slices.Contains(clean, id) {
clean = append(clean, id)
}
}
if len(clean) > maxShareUsers {
return nil, "A material may be shared with at most " + strconv.Itoa(maxShareUsers) + " users.", nil
}
slices.Sort(clean)
if len(clean) == 0 {
return clean, "", nil
}
var n int64
if err := db.Model(&usermodels.User{}).Where("id IN ?", clean).Count(&n).Error; err != nil {
return nil, "", err
}
if int(n) != len(clean) {
return nil, "The selected user_ids are invalid.", nil
}
return clean, "", nil
}
// replaceMaterialShares makes userIDs the users the material is shared with.
func replaceMaterialShares(tx *gorm.DB, materialID uint, userIDs []uint) error {
if err := tx.Where("material_id = ?", materialID).Delete(&models.MaterialShare{}).Error; err != nil {
return err
}
for _, id := range userIDs {
if err := tx.Create(&models.MaterialShare{MaterialID: materialID, UserID: id}).Error; err != nil {
return err
}
}
return nil
}
// managesMaterials tells whether the user holds jz.bm.access_materials.
func (h *Handlers) managesMaterials(ctx context.Context, db *gorm.DB, userID uint) (bool, error) {
return ManagesMaterials(ctx, db, userID)
}
// ManagesMaterials tells whether the user holds jz.bm.access_materials. The
// realtime connection-token guard admits such users (D-20).
func ManagesMaterials(ctx context.Context, db *gorm.DB, userID uint) (bool, error) {
principal, err := userclasses.PrincipalByID(ctx, db, userID)
if err != nil {
return false, err
}
return principal != nil && cabana.Allows(principal, []string{controllers.PermMaterials}), nil
}
// CanWatchMaterial tells whether the user may follow material id's live
// revision channel (D-20): the material is visible to them at now and they
// may manage it (canManageMaterial). It reads current state on every call;
// a material they cannot see is false without an error.
func CanWatchMaterial(ctx context.Context, db *gorm.DB, now time.Time, userID, id uint) (bool, error) {
var m models.Material
res := visibleMaterials(db.WithContext(ctx), now, userID).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
return false, res.Error
}
if res.RowsAffected == 0 {
return false, nil
}
manager, err := ManagesMaterials(ctx, db, userID)
if err != nil {
return false, err
}
return canManageMaterial(m, userID, manager), nil
}
// canManageMaterial tells whether a material manager may change the
// material's access: it is theirs, or it has no author yet (the first change
// makes them its author).
func canManageMaterial(m models.Material, userID uint, manager bool) bool {
return manager && (m.AuthorUserID == nil || *m.AuthorUserID == userID)
}
// materialAccessJSON is GET /materials/{id}/access: the material's
// visibility, the users it is shared with and the users to pick from.
type materialAccessJSON struct {
MaterialID uint `json:"material_id"`
IsPrivate bool `json:"is_private"`
AuthorUserID *uint `json:"author_user_id"`
Shares []userRefJSON `json:"shares"`
Users []userRefJSON `json:"users"`
}
// materialAccessInput is the body of PUT /materials/{id}/access.
type materialAccessInput struct {
IsPrivate *bool `json:"is_private"`
UserIDs *[]uint `json:"user_ids"`
}
// managedMaterialForCaller loads a material the caller sees and may manage.
// It answers 404 or 500 itself and returns false then: a material the caller
// may not manage is a 404, so nothing hints that a private one exists.
func (h *Handlers) managedMaterialForCaller(w http.ResponseWriter, r *http.Request, db *gorm.DB, userID uint) (models.Material, bool) {
var m models.Material
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return m, false
}
res := visibleMaterials(db, h.now(), userID).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
writeOpaque500(w)
return m, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return m, false
}
manager, err := h.managesMaterials(r.Context(), db, userID)
if err != nil {
writeOpaque500(w)
return m, false
}
if !canManageMaterial(m, userID, manager) {
writeNotFound(w)
return m, false
}
return m, true
}
// writeForbidden answers 403 to a caller who may see a resource but not
// change it.
func writeForbidden(w http.ResponseWriter) {
wire.WriteJSON(w, http.StatusForbidden, map[string]any{"error": true, "message": "Forbidden."})
}
// editableMaterialForCaller loads the material of the {id} parameter for the
// author's routes (edit, unpublish, image upload). Unlike
// managedMaterialForCaller it tells "not yours" from "not there" (D-07): a
// material the caller cannot see (private and not theirs, a draft, not
// published yet, unknown) is a 404, and one they see but may not manage (no
// jz.bm.access_materials, or another author) a 403. Both helpers stay: the
// access panel keeps its 404. It answers itself and returns ok false then;
// manager tells whether the caller holds jz.bm.access_materials, for the
// re-check on the locked row.
func (h *Handlers) editableMaterialForCaller(w http.ResponseWriter, r *http.Request, db *gorm.DB, userID uint) (models.Material, bool, bool) {
var m models.Material
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return m, false, false
}
res := visibleMaterials(db, h.now(), userID).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
writeOpaque500(w)
return m, false, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return m, false, false
}
manager, err := h.managesMaterials(r.Context(), db, userID)
if err != nil {
writeOpaque500(w)
return m, false, false
}
if !canManageMaterial(m, userID, manager) {
writeForbidden(w)
return m, manager, false
}
return m, manager, true
}
// editOutcome is what lockEditableMaterial found on the locked row.
type editOutcome int
const (
editAllowed editOutcome = iota
// editGone: the material is no longer visible to the caller.
editGone
// editForbidden: the caller may no longer manage it.
editForbidden
)
// lockEditableMaterial re-loads material id inside tx, locked FOR UPDATE,
// and re-checks that the caller still sees it and may manage it, so a
// concurrent access or publication change cannot slip between the check
// of editableMaterialForCaller and the write.
func (h *Handlers) lockEditableMaterial(tx *gorm.DB, userID, id uint, manager bool) (models.Material, editOutcome, error) {
var m models.Material
res := visibleMaterials(tx.Clauses(clause.Locking{Strength: "UPDATE"}), h.now(), userID).
Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
return m, editGone, res.Error
}
if res.RowsAffected == 0 {
return m, editGone, nil
}
if !canManageMaterial(m, userID, manager) {
return m, editForbidden, nil
}
return m, editAllowed, nil
}
// writeMaterialAccess answers the access of m as the caller sees it.
func writeMaterialAccess(w http.ResponseWriter, db *gorm.DB, m models.Material, userID uint) {
shares, err := materialShareRefs(db, []uint{m.ID})
if err != nil {
writeOpaque500(w)
return
}
users, err := listUserRefs(db, userID)
if err != nil {
writeOpaque500(w)
return
}
out := materialAccessJSON{MaterialID: m.ID, IsPrivate: m.IsPrivate, AuthorUserID: m.AuthorUserID, Shares: shares[m.ID], Users: users}
if out.Shares == nil {
out.Shares = []userRefJSON{}
}
writeData(w, out)
}
// MaterialAccess answers GET /materials/{id}/access for the material's
// author (or any material manager while it has no author): its visibility,
// its shares and the users it can be shared with. Anyone else gets a 404.
func (h *Handlers) MaterialAccess(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
m, ok := h.managedMaterialForCaller(w, r, db, userID)
if !ok {
return
}
writeMaterialAccess(w, db, m, userID)
}
// UpdateMaterialAccess answers PUT /materials/{id}/access, body
// {"is_private": bool?, "user_ids": [id]?}: absent keys keep the stored
// value, and user_ids (null meaning none) replaces the shares. The first
// change of a material with no author makes the caller its author. Access is
// as for MaterialAccess.
func (h *Handlers) UpdateMaterialAccess(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
m, ok := h.managedMaterialForCaller(w, r, db, userID)
if !ok {
return
}
raw, ok := body(w, r)
if !ok {
return
}
var in materialAccessInput
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeInvalid(w, "invalid JSON: "+err.Error())
return
}
var shares []uint
if in.UserIDs != nil {
clean, msg, err := cleanUserIDs(db, *in.UserIDs)
if err != nil {
writeOpaque500(w)
return
}
if msg != "" {
writeValidation(w, map[string][]string{"user_ids": {msg}})
return
}
shares = clean
}
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
return applyMaterialAccess(tx, &m, userID, in.IsPrivate, in.UserIDs != nil, shares)
})
if err != nil {
writeOpaque500(w)
return
}
writeMaterialAccess(w, db, m, userID)
}
// applyMaterialAccess writes a visibility and share change onto m inside
// tx. A material with no author gets userID as author (the claim rule).
// Only is_private and author_user_id are updated; the shares are replaced
// when setShares. The search index holds none of these, so no caller syncs
// after it.
func applyMaterialAccess(tx *gorm.DB, m *models.Material, userID uint, isPrivate *bool, setShares bool, shares []uint) error {
if m.AuthorUserID == nil {
id := userID
m.AuthorUserID = &id
}
if isPrivate != nil {
m.IsPrivate = *isPrivate
}
err := tx.Model(&models.Material{}).Where("id = ?", m.ID).
Updates(map[string]any{"is_private": m.IsPrivate, "author_user_id": m.AuthorUserID}).Error
if err != nil {
return err
}
if !setShares {
return nil
}
return replaceMaterialShares(tx, m.ID, shares)
}

View File

@@ -0,0 +1,465 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"slices"
"strconv"
"strings"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// The author's routes (D-07): the student app edits, unpublishes and adds
// editor images to a material through them. They run under jwt.auth only,
// with no token twin (tokens and MCP write through the management API), and
// each one goes through editableMaterialForCaller: a material the caller
// cannot see is a 404, one they see but may not manage a 403. None of them
// changes the author, the publication time (except unpublish), is_private or
// the shares (D-08, D-10).
// maxEditTags caps the tags the student editor may give a material.
const maxEditTags = 4
// materialEditKeys are the keys of PUT /materials/{id}, all required.
var materialEditKeys = []string{"revision", "title", "type", "body", "source", "url", "meeting_id", "tags"}
// materialEditInput is the body of the student PUT /materials/{id} (D-09).
// It has no course, author, publication or access keys, so none can be sent
// (unknown keys are refused); the course is the stored one.
type materialEditInput struct {
Revision *uint `json:"revision"`
Title *string `json:"title"`
Type *string `json:"type"`
Body *string `json:"body"`
Source *string `json:"source"`
URL *string `json:"url"`
MeetingID *uint `json:"meeting_id"`
Tags *[]string `json:"tags"`
}
// decodeMaterialEdit decodes the edit body, refusing unknown keys (the
// error, answered as "invalid JSON"). The returned messages name every key
// that is missing, and revision, title, type or tags sent as null; the
// caller adds its own rules to them before checkMaterial.
func decodeMaterialEdit(raw []byte) (materialEditInput, map[string][]string, error) {
var in materialEditInput
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
return in, nil, err
}
var keys map[string]json.RawMessage
if err := json.Unmarshal(raw, &keys); err != nil {
return in, nil, err
}
errs := map[string][]string{}
for _, k := range materialEditKeys {
if _, ok := keys[k]; !ok {
errs[k] = []string{"The " + k + " field is required."}
}
}
for k, missing := range map[string]bool{
"revision": in.Revision == nil,
"title": in.Title == nil,
"type": in.Type == nil,
"tags": in.Tags == nil,
} {
if _, sent := keys[k]; sent && missing {
errs[k] = []string{"The " + k + " field is required."}
}
}
return in, errs, nil
}
// normalizeBody normalises a note body the way bm-notatka push does (A6):
// CRLF and CR become LF, surrounding whitespace goes, an empty body becomes
// null and any other ends with exactly one newline. So a web save, a pull
// and a push of the same text are byte-identical and never bump the
// revision.
func normalizeBody(b *string) *string {
if b == nil {
return nil
}
s := strings.ReplaceAll(*b, "\r\n", "\n")
s = strings.ReplaceAll(s, "\r", "\n")
s = strings.TrimSpace(s)
if s == "" {
return nil
}
s += "\n"
return &s
}
// hasWebScheme reports whether u starts with http:// or https://, in any
// case.
func hasWebScheme(u string) bool {
l := strings.ToLower(u)
return strings.HasPrefix(l, "http://") || strings.HasPrefix(l, "https://")
}
// checkMaterialEdit adds the student-only rules of the edit body to errs:
// at most maxEditTags distinct tags, every tag from the jz_bm_tags
// dictionary (the app never creates a tag, A2), and a url that is a web
// address.
func checkMaterialEdit(db *gorm.DB, in materialEditInput, errs map[string][]string) error {
if in.URL != nil && strings.TrimSpace(*in.URL) != "" && !hasWebScheme(*in.URL) {
errs["url"] = []string{"The url must start with http:// or https://."}
}
if in.Tags == nil {
return nil
}
var slugs []string
for _, name := range *in.Tags {
slug := slugify(strings.TrimSpace(name))
if slug != "" && !slices.Contains(slugs, slug) {
slugs = append(slugs, slug)
}
}
if len(slugs) > maxEditTags {
errs["tags"] = []string{"A material may have at most " + strconv.Itoa(maxEditTags) + " tags."}
return nil
}
if len(slugs) == 0 {
return nil
}
var n int64
if err := db.Model(&models.Tag{}).Where("slug IN ?", slugs).Distinct("slug").Count(&n).Error; err != nil {
return err
}
if int(n) != len(slugs) {
errs["tags"] = []string{"Pick the tags from the dictionary."}
}
return nil
}
// EditMaterial answers the student PUT /materials/{id} (D-09): the author
// (or any material manager while it has no author) saves the note's title,
// type, body, source, url, meeting and tags. Every key of
// materialEditInput is required and nothing else is accepted; the course,
// the author, the publication and the access stay as stored. revision is
// required: a stale one is a 409 with the current version
// (writeStudentConflict) and nothing is written (D-01, D-04). The row is
// locked FOR UPDATE and re-checked inside the transaction. The answer is
// the student detail, 200.
func (h *Handlers) EditMaterial(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
m, manager, ok := h.editableMaterialForCaller(w, r, db, userID)
if !ok {
return
}
raw, ok := body(w, r)
if !ok {
return
}
in, errs, err := decodeMaterialEdit(raw)
if err != nil {
writeInvalid(w, "invalid JSON: "+err.Error())
return
}
if err := checkMaterialEdit(db, in, errs); err != nil {
writeOpaque500(w)
return
}
d := materialDraft{
in: materialInput{
CourseID: m.CourseID,
MeetingID: in.MeetingID,
Title: deref(in.Title),
Type: deref(in.Type),
Body: normalizeBody(in.Body),
Source: in.Source,
URL: in.URL,
Tags: in.Tags,
Revision: in.Revision,
},
hasMeetingID: true,
}
if !h.checkMaterial(w, db, &d, errs) {
return
}
outcome := editAllowed
conflict, taken := false, false
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
cur, why, err := h.lockEditableMaterial(tx, userID, m.ID, manager)
if err != nil || why != editAllowed {
outcome = why
return err
}
if staleRevision(d.in.Revision, cur.Revision) {
conflict = true
return nil
}
// The course is the locked row's (Pitfall 3): apply writes it as
// sent, and the edit body never carries one.
d.in.CourseID = cur.CourseID
before, err := models.MaterialContent(tx, cur.ID)
if err != nil {
return err
}
var n int64
if err := d.identity(tx.Model(&models.Material{})).Where("id <> ?", cur.ID).Count(&n).Error; err != nil {
return err
}
if n > 0 {
taken = true
return nil
}
if err := d.apply(tx, &cur, false, h.now(), userID); err != nil {
return err
}
return h.revise(ctx, tx, cur.ID, before)
})
switch {
case err != nil:
writeOpaque500(w)
case outcome == editGone:
writeNotFound(w)
case outcome == editForbidden:
writeForbidden(w)
case conflict:
h.writeStudentConflict(w, r, db, userID, m.ID)
case taken:
writeValidation(w, map[string][]string{"title": {"Another material already has this title and course."}})
default:
h.MaterialIndex.Sync(r.Context(), db, m.ID)
out, found, err := h.loadMaterialDetail(r.Context(), db, userID, m.ID)
switch {
case err != nil:
writeOpaque500(w)
case !found:
writeNotFound(w)
default:
writeData(w, out)
}
}
}
// writeStudentConflict answers 409 to a student edit that sent a stale
// revision: the current revision, its updated_at and the material in the
// student detail shape (with its body), so the editor can show the server
// version. A material that vanished meanwhile is a 404.
func (h *Handlers) writeStudentConflict(w http.ResponseWriter, r *http.Request, db *gorm.DB, userID, id uint) {
out, found, err := h.loadMaterialDetail(r.Context(), db, userID, id)
if err != nil {
writeOpaque500(w)
return
}
if !found {
writeNotFound(w)
return
}
var row models.Material
if err := db.Select("id", "updated_at").Where("id = ?", id).Take(&row).Error; err != nil {
writeOpaque500(w)
return
}
wire.WriteJSON(w, http.StatusConflict, map[string]any{
"error": true,
"message": conflictMessage,
"revision": out.Revision,
"updated_at": models.FormatDateTime(row.UpdatedAt),
"data": out,
})
}
// imageLimits are the attach.Store rules of an editor image (D-16): image
// mode sniffs and decodes the bytes and admits only JPEG, PNG, GIF and
// WebP (never SVG), up to MaterialFileMaxBytes.
var imageLimits = attach.Limits{MaxBytes: MaterialFileMaxBytes, Image: true}
// Tags answers GET /tags: the tag dictionary the editor picks from (A2),
// every row of jz_bm_tags by name, to material managers; anyone else gets a
// 403.
func (h *Handlers) Tags(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
manager, err := h.managesMaterials(r.Context(), db, userID)
if err != nil {
writeOpaque500(w)
return
}
if !manager {
writeForbidden(w)
return
}
var tags []models.Tag
if err := db.Order("name, id").Find(&tags).Error; err != nil {
writeOpaque500(w)
return
}
writeData(w, newTagsJSON(tags))
}
// UnpublishMaterial answers POST /materials/{id}/unpublish (D-11, "Usuń" in
// the app): the material becomes a draft (published_at NULL), which the
// student API no longer serves, so even its author gets a 404 afterwards.
// Nothing is deleted: a push without --draft or /bmadmin publishes it
// again. The revision stays (D-03). The search document is resynced, not
// removed, because the management search keeps drafts. 204.
func (h *Handlers) UnpublishMaterial(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
m, manager, ok := h.editableMaterialForCaller(w, r, db, userID)
if !ok {
return
}
outcome := editAllowed
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
cur, why, err := h.lockEditableMaterial(tx, userID, m.ID, manager)
if err != nil || why != editAllowed {
outcome = why
return err
}
return tx.Model(&models.Material{}).Where("id = ?", cur.ID).Update("published_at", nil).Error
})
switch {
case err != nil:
writeOpaque500(w)
case outcome == editGone:
writeNotFound(w)
case outcome == editForbidden:
writeForbidden(w)
default:
h.MaterialIndex.Sync(r.Context(), db, m.ID)
w.WriteHeader(http.StatusNoContent)
}
}
// writeFileRefusal answers 422 to a refused editor image, with the reason
// (type, size or count) for the editor's message.
func writeFileRefusal(w http.ResponseWriter, why fileRefusal) {
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{
"message": why.Text,
"errors": map[string][]string{"file": {why.Text}},
"reason": why.Reason,
})
}
// UploadMaterialImage answers POST /materials/{id}/images (D-16): the first
// multipart part named "file" is stored as a public file of the material
// through storeMaterialUpload with imageLimits, and the file text job is
// queued in the same transaction. One image per request. The revision does
// not change: the body edit that links the image bumps it on save. 201
// {data: {id, url, name, size, mime}}; a refused file is a 422 with reason
// type, size or count, an over-limit body a 413.
func (h *Handlers) UploadMaterialImage(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
bucket, ok := h.bucket(w)
if !ok {
return
}
m, manager, ok := h.editableMaterialForCaller(w, r, db, userID)
if !ok {
return
}
mr, err := r.MultipartReader()
if err != nil {
writeInvalid(w, "Send the image as multipart/form-data in a part named \"file\".")
return
}
errRefused := errors.New("refused")
outcome := editAllowed
var stored *attach.File
var refusal fileRefusal
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
cur, why, err := h.lockEditableMaterial(tx, userID, m.ID, manager)
if err != nil || why != editAllowed {
outcome = why
return err
}
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return err
}
if part.FormName() != "file" || part.FileName() == "" {
part.Close()
continue
}
if stored != nil {
part.Close()
refusal = fileRefusal{Reason: "type", Text: "Send one image per request."}
return errRefused
}
f, why, err := storeMaterialUpload(ctx, tx, bucket, cur, part.FileName(), part, imageLimits)
part.Close()
if f != nil {
stored = f
}
if err != nil {
return err
}
if why.Reason != "" {
refusal = why
return errRefused
}
}
if stored == nil {
refusal = fileRefusal{Reason: "type", Text: "No image: send one multipart part named \"file\"."}
return errRefused
}
// The text job joins the transaction: it exists only when the file
// commits, and it syncs the material's document.
h.MaterialIndex.QueueExtract(ctx, tx, cur.ID)
return nil
})
if err != nil && stored != nil {
// The blobs written are deleted again: the transaction did not commit.
_ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored))
}
var tooLarge *http.MaxBytesError
switch {
case errors.Is(err, errRefused):
writeFileRefusal(w, refusal)
case errors.As(err, &tooLarge):
wire.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": true, "message": "Request body too large.", "reason": "size"})
case err != nil:
writeOpaque500(w)
case outcome == editGone:
writeNotFound(w)
case outcome == editForbidden:
writeForbidden(w)
default:
wire.WriteJSON(w, http.StatusCreated, map[string]any{"data": fileJSON{
ID: stored.ID, URL: stored.URL(), Name: stored.FileName, Size: stored.FileSize, Mime: stored.ContentType,
}})
}
}

View File

@@ -0,0 +1,184 @@
package api
import (
"errors"
"fmt"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
)
const fullEditBody = `{"revision":3,"title":"Notatka","type":"notatka","body":"Tekst","source":null,"url":null,"meeting_id":null,"tags":["lektura"]}`
// TestDecodeMaterialEdit checks the student edit body (D-09): every key is
// required, revision, title, type and tags may not be null, and unknown keys
// such as course_id or published_at are refused.
func TestDecodeMaterialEdit(t *testing.T) {
in, errs, err := decodeMaterialEdit([]byte(fullEditBody))
if err != nil {
t.Fatal(err)
}
if len(errs) != 0 {
t.Errorf("full body errors = %v, want none", errs)
}
if in.Revision == nil || *in.Revision != 3 || deref(in.Title) != "Notatka" || in.Tags == nil || len(*in.Tags) != 1 {
t.Errorf("full body decoded to %+v", in)
}
for _, key := range materialEditKeys {
raw := dropKey(t, fullEditBody, key)
_, errs, err := decodeMaterialEdit([]byte(raw))
if err != nil {
t.Errorf("without %s: decode error %v", key, err)
continue
}
if _, ok := errs[key]; !ok || len(errs) != 1 {
t.Errorf("without %s: errors = %v, want one on %s", key, errs, key)
}
}
for _, key := range []string{"revision", "title", "type", "tags"} {
raw := nullKey(t, fullEditBody, key)
_, errs, err := decodeMaterialEdit([]byte(raw))
if err != nil {
t.Errorf("null %s: decode error %v", key, err)
continue
}
if _, ok := errs[key]; !ok || len(errs) != 1 {
t.Errorf("null %s: errors = %v, want one on %s", key, errs, key)
}
}
for _, key := range []string{"body", "source", "url", "meeting_id"} {
_, errs, err := decodeMaterialEdit([]byte(nullKey(t, fullEditBody, key)))
if err != nil || len(errs) != 0 {
t.Errorf("null %s = %v %v, want no error", key, errs, err)
}
}
for _, extra := range []string{`"course_id":1`, `"published_at":null`, `"author_user_id":2`, `"is_private":true`, `"share_user_ids":[]`} {
raw := strings.TrimSuffix(fullEditBody, "}") + "," + extra + "}"
if _, _, err := decodeMaterialEdit([]byte(raw)); err == nil {
t.Errorf("body with %s decoded, want an unknown-field error", extra)
}
}
if _, _, err := decodeMaterialEdit([]byte(`[1]`)); err == nil {
t.Error("an array body decoded, want an error")
}
}
// dropKey removes key and its value from the flat JSON object raw.
func dropKey(t *testing.T, raw, key string) string {
t.Helper()
parts := splitTop(raw)
out := make([]string, 0, len(parts))
for _, p := range parts {
if !strings.HasPrefix(p, `"`+key+`":`) {
out = append(out, p)
}
}
if len(out) == len(parts) {
t.Fatalf("key %s not in %s", key, raw)
}
return "{" + strings.Join(out, ",") + "}"
}
// nullKey sets key to null in the flat JSON object raw.
func nullKey(t *testing.T, raw, key string) string {
t.Helper()
parts := splitTop(raw)
found := false
for i, p := range parts {
if strings.HasPrefix(p, `"`+key+`":`) {
parts[i] = `"` + key + `":null`
found = true
}
}
if !found {
t.Fatalf("key %s not in %s", key, raw)
}
return "{" + strings.Join(parts, ",") + "}"
}
// splitTop splits a flat JSON object into its "key":value members, keeping
// commas inside arrays.
func splitTop(raw string) []string {
inner := strings.TrimSuffix(strings.TrimPrefix(raw, "{"), "}")
var parts []string
depth, start := 0, 0
for i, c := range inner {
switch c {
case '[':
depth++
case ']':
depth--
case ',':
if depth == 0 {
parts = append(parts, inner[start:i])
start = i + 1
}
}
}
return append(parts, inner[start:])
}
// TestNormalizeBody checks the body normalisation of the edit route (A6):
// LF line ends, no surrounding blank lines, one trailing newline, and an
// empty or whitespace-only body as null.
func TestNormalizeBody(t *testing.T) {
s := func(v string) *string { return &v }
cases := []struct {
name string
in *string
want *string
}{
{"nil", nil, nil},
{"empty", s(""), nil},
{"whitespace", s(" \n\t\r\n "), nil},
{"crlf", s("a\r\nb\r\n"), s("a\nb\n")},
{"cr", s("a\rb"), s("a\nb\n")},
{"blank lines around", s("\n\n# Tytuł\n\ntekst\n\n\n"), s("# Tytuł\n\ntekst\n")},
{"no newline", s("tekst"), s("tekst\n")},
{"already normal", s("tekst\n"), s("tekst\n")},
}
for _, tc := range cases {
got := normalizeBody(tc.in)
switch {
case tc.want == nil && got != nil:
t.Errorf("%s: normalizeBody = %q, want nil", tc.name, *got)
case tc.want != nil && (got == nil || *got != *tc.want):
t.Errorf("%s: normalizeBody = %v, want %q", tc.name, got, *tc.want)
}
}
}
// TestFileRefusalReasons checks how attach.Store errors become refusals of
// the material file routes: size for ErrTooLarge, type for ErrFileType,
// ErrMIMEType and the image-mode ErrNotImage (no longer a 500), and no
// refusal for other errors.
func TestFileRefusalReasons(t *testing.T) {
cases := []struct {
err error
reason string
}{
{attach.ErrTooLarge, "size"},
{attach.ErrFileType, "type"},
{attach.ErrMIMEType, "type"},
{attach.ErrNotImage, "type"},
{fmt.Errorf("store: %w", attach.ErrNotImage), "type"},
}
for _, tc := range cases {
why, ok := fileRefusalFor(tc.err, "a.png", imageLimits)
if !ok || why.Reason != tc.reason || !strings.HasPrefix(why.Text, "a.png: ") {
t.Errorf("fileRefusalFor(%v) = %+v %v, want reason %s", tc.err, why, ok, tc.reason)
}
}
if why, _ := fileRefusalFor(attach.ErrTooLarge, "a.png", imageLimits); why.Text != "a.png: the file is larger than 50 MB." {
t.Errorf("size text = %q", why.Text)
}
for _, err := range []error{nil, errors.New("disk full")} {
if why, ok := fileRefusalFor(err, "a.png", imageLimits); ok {
t.Errorf("fileRefusalFor(%v) = %+v, want no refusal", err, why)
}
}
if !imageLimits.Image || imageLimits.MaxBytes != MaterialFileMaxBytes {
t.Errorf("imageLimits = %+v", imageLimits)
}
}

View File

@@ -0,0 +1,121 @@
package api
import (
"net/http"
"strconv"
"time"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// pinnedFirstOrder orders the plain material list for userID: the caller's
// own pins first, newest pin first, then the plain list's order (newest
// publication first). id breaks every tie, so pages are stable. userID is
// the authenticated caller's id, never request input, and is inlined as a
// parsed integer like rankOrder.
func pinnedFirstOrder(userID uint) string {
return "(SELECT p.pinned_at FROM jz_bm_material_pins p WHERE p.material_id = jz_bm_materials.id AND p.user_id = " +
strconv.FormatUint(uint64(userID), 10) +
") DESC NULLS LAST, jz_bm_materials.published_at DESC, jz_bm_materials.id DESC"
}
// pinnedMaterialIDs tells which of ids userID pinned. No ids is an empty
// answer without a query.
func pinnedMaterialIDs(db *gorm.DB, userID uint, ids []uint) (map[uint]bool, error) {
out := map[uint]bool{}
if len(ids) == 0 {
return out, nil
}
var pinned []uint
err := db.Model(&models.MaterialPin{}).
Where("user_id = ? AND material_id IN ?", userID, ids).
Pluck("material_id", &pinned).Error
if err != nil {
return nil, err
}
for _, id := range pinned {
out[id] = true
}
return out, nil
}
// pinTarget resolves {id} to a material userID may see and answers 404
// itself otherwise: the same 404 as the detail for an unknown id, a draft, a
// future publication or another user's private material, so nothing hints
// that a hidden material exists.
func pinTarget(w http.ResponseWriter, r *http.Request, db *gorm.DB, now time.Time, userID uint) (uint, bool) {
id, ok := surf.IntParam(r, "id")
if !ok || id <= 0 {
writeNotFound(w)
return 0, false
}
var m models.Material
res := visibleMaterials(db.Model(&models.Material{}), now, userID).
Where("jz_bm_materials.id = ?", id).
Select("jz_bm_materials.id").
Limit(1).
Find(&m)
if res.Error != nil {
writeOpaque500(w)
return 0, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return 0, false
}
return m.ID, true
}
// PinMaterial answers PUT /materials/{id}/pin: it pins a material the
// caller may see, for the caller only. Pinning again keeps the first
// pinned_at. A pin is personal and is not content: it writes only
// jz_bm_material_pins and leaves the material row as it is, so the
// material's version, what search finds and what an open editor sees stay
// the same. It answers 204.
func (h *Handlers) PinMaterial(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
materialID, ok := pinTarget(w, r, db, h.now(), userID)
if !ok {
return
}
err := db.Exec(`INSERT INTO jz_bm_material_pins (material_id, user_id, pinned_at) VALUES (?, ?, ?)
ON CONFLICT (material_id, user_id) DO NOTHING`, materialID, userID, h.now().UTC()).Error
if err != nil {
writeOpaque500(w)
return
}
w.WriteHeader(http.StatusNoContent)
}
// UnpinMaterial answers DELETE /materials/{id}/pin: it removes the caller's
// own pin from a material the caller may see. Clearing a material that is
// not pinned is not an error. Like PinMaterial it writes only
// jz_bm_material_pins and never the material itself. It answers 204.
func (h *Handlers) UnpinMaterial(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
materialID, ok := pinTarget(w, r, db, h.now(), userID)
if !ok {
return
}
if err := db.Where("material_id = ? AND user_id = ?", materialID, userID).Delete(&models.MaterialPin{}).Error; err != nil {
writeOpaque500(w)
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -0,0 +1,64 @@
package api_test
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"gorm.io/gorm"
)
// pinnedFirstQueries runs GET /materials?course=7&type=notatka as user on a
// dry-run database and returns its count and page queries.
func pinnedFirstQueries(t *testing.T, user uint) (string, string) {
t.Helper()
db, rec := dryDB(t)
h := &api.Handlers{DB: func() *gorm.DB { return db }}
req := httptest.NewRequest(http.MethodGet, "/materials?course=7&type=notatka", nil)
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user}))
w := httptest.NewRecorder()
h.Materials(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
var count, page string
for _, q := range rec.queries() {
switch {
case strings.HasPrefix(q, "SELECT count(*)"):
count = q
case strings.HasPrefix(q, "SELECT") && strings.Contains(q, `FROM "jz_bm_materials"`):
page = q
}
}
if count == "" || page == "" {
t.Fatalf("queries = %q, want a count and a page", rec.queries())
}
return count, page
}
// TestMaterialsPinnedFirstTrace checks the plain list's order: the caller's
// own pins first, then newest first with id as the tie-breaker, inside the
// same filters, while the count ignores pins.
func TestMaterialsPinnedFirstTrace(t *testing.T) {
count, page := pinnedFirstQueries(t, 5)
for name, q := range map[string]string{"count": count, "page": page} {
for _, want := range []string{"jz_bm_materials.course_id = 7", "jz_bm_materials.type = 'notatka'", "jz_bm_materials.is_private = FALSE"} {
if !strings.Contains(q, want) {
t.Errorf("%s query lacks %q:\n%s", name, want, q)
}
}
}
if want := "p.user_id = 5) DESC NULLS LAST, jz_bm_materials.published_at DESC, jz_bm_materials.id DESC"; !strings.Contains(page, want) {
t.Errorf("page query is not pinned first for user 5, want %q:\n%s", want, page)
}
if strings.Contains(count, "jz_bm_material_pins") {
t.Errorf("count query reads pins:\n%s", count)
}
_, other := pinnedFirstQueries(t, 6)
if !strings.Contains(other, "p.user_id = 6)") || strings.Contains(other, "p.user_id = 5") {
t.Errorf("page query of user 6 does not use only their pins:\n%s", other)
}
}

View File

@@ -0,0 +1,66 @@
package api
import (
"context"
"net/http"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// A write of a material's content may carry the revision the writer last
// read (D-01, D-04). When it does and the stored revision differs, the write
// is refused with 409 and nothing is written; when it does not, the write
// overwrites as before, so callers that never send a revision keep working.
// The compare and the write run on the row locked FOR UPDATE, so two writers
// holding the same revision cannot both succeed.
// conflictMessage is the message of a 409 answer to a stale revision.
const conflictMessage = "The material was changed since the revision you sent."
// staleRevision reports whether a write that sent revision sent must be
// refused: true when it sent one and it is not the stored one.
func staleRevision(sent *uint, stored uint) bool {
return sent != nil && *sent != stored
}
// revise bumps the revision of material id inside tx when its content
// differs from before (models.ReviseMaterial). Every content writer of the
// API calls it after its write. A bump also enqueues the live heads-up on
// tx (D-20), published only when the write commits; its failure never fails
// the write.
func (h *Handlers) revise(ctx context.Context, tx *gorm.DB, id uint, before string) error {
rev, bumped, err := models.ReviseMaterial(tx.WithContext(ctx), id, before)
if err != nil {
return err
}
if bumped {
h.Revisions.Revised(ctx, tx, id, rev)
}
return nil
}
// writeConflict answers 409 to a write that sent a stale revision, with the
// current revision, its updated_at and the material as the management API
// shows it, so the writer can diff or pull. Under MCP the body is left out,
// as in every other MCP answer.
func writeConflict(w http.ResponseWriter, r *http.Request, db *gorm.DB, id uint) {
var cur models.Material
if err := preloadMaterial(db).First(&cur, id).Error; err != nil {
writeOpaque500(w)
return
}
people, err := loadMaterialPeople(db, cur)
if err != nil {
writeOpaque500(w)
return
}
wire.WriteJSON(w, http.StatusConflict, map[string]any{
"error": true,
"message": conflictMessage,
"revision": cur.Revision,
"updated_at": models.FormatDateTime(cur.UpdatedAt),
"data": managedMaterialView(newManagedMaterialJSON(cur, people), viaMCP(r), false),
})
}

View File

@@ -0,0 +1,92 @@
package api
import (
"encoding/json"
"testing"
"time"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// TestDecodeMaterialRevision checks that revision is an optional key of the
// material body: sent, it decodes to a pointer; absent, to nil; and unknown
// keys are still refused.
func TestDecodeMaterialRevision(t *testing.T) {
d, err := decodeMaterial([]byte(`{"title":"Notatka","type":"notatka","revision":3}`))
if err != nil {
t.Fatal(err)
}
if d.in.Revision == nil || *d.in.Revision != 3 {
t.Errorf("revision = %v, want a pointer to 3", d.in.Revision)
}
d, err = decodeMaterial([]byte(`{"title":"Notatka","type":"notatka","meeting_id":null}`))
if err != nil {
t.Fatal(err)
}
if d.in.Revision != nil {
t.Errorf("absent revision = %v, want nil", *d.in.Revision)
}
if !d.hasMeetingID || d.hasPublishedAt || d.hasAuthor {
t.Errorf("key flags = meeting %v published %v author %v, want only meeting", d.hasMeetingID, d.hasPublishedAt, d.hasAuthor)
}
if _, err := decodeMaterial([]byte(`{"title":"Notatka","type":"notatka","rev":3}`)); err == nil {
t.Error("an unknown key was accepted")
}
}
// TestStaleRevision checks that only a sent revision different from the
// stored one is stale.
func TestStaleRevision(t *testing.T) {
one, two := uint(1), uint(2)
for _, tc := range []struct {
sent *uint
stored uint
want bool
}{
{nil, 1, false},
{nil, 7, false},
{&one, 1, false},
{&two, 1, true},
{&one, 2, true},
} {
if got := staleRevision(tc.sent, tc.stored); got != tc.want {
t.Errorf("staleRevision(%v, %d) = %v, want %v", tc.sent, tc.stored, got, tc.want)
}
}
}
// TestManagedMaterialJSONCarriesRevision checks that a managed material
// carries revision and updated_at.
func TestManagedMaterialJSONCarriesRevision(t *testing.T) {
m := models.Material{ID: 3, Title: "Notatka", Type: "notatka", Revision: 4, UpdatedAt: time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)}
b, err := json.Marshal(newManagedMaterialJSON(m, materialPeople{}))
if err != nil {
t.Fatal(err)
}
var keys map[string]any
if err := json.Unmarshal(b, &keys); err != nil {
t.Fatal(err)
}
if keys["revision"] != float64(4) {
t.Errorf("revision = %v in %s, want 4", keys["revision"], b)
}
if keys["updated_at"] != models.FormatDateTime(m.UpdatedAt) {
t.Errorf("updated_at = %v in %s, want %s", keys["updated_at"], b, models.FormatDateTime(m.UpdatedAt))
}
}
// TestMaterialJSONCarriesRevision checks that the student material detail
// carries revision.
func TestMaterialJSONCarriesRevision(t *testing.T) {
b, err := json.Marshal(materialDetailJSON{materialListJSON: materialListJSON{ID: 1, Title: "Notatka"}, Revision: 5})
if err != nil {
t.Fatal(err)
}
var keys map[string]any
if err := json.Unmarshal(b, &keys); err != nil {
t.Fatal(err)
}
if keys["revision"] != float64(5) {
t.Errorf("revision = %v in %s, want 5", keys["revision"], b)
}
}

View File

@@ -0,0 +1,184 @@
package api
import (
"net/http"
"strconv"
"strings"
"unicode/utf8"
"git.golem15.com/golem15/summercms/modules/beachcomber"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// Material search: the engine (beachcomber, Typesense) answers candidate ids
// only. Visibility, the filters, the total and the paging stay in SQL, and a
// row's snippet is read only once SQL returned that row, so a material the
// caller may not see never reaches the JSON, its count or a snippet.
// minSearchRunes is the shortest query that searches; a shorter one is
// ignored, as the student app does.
const minSearchRunes = 2
// searchQuery returns the trimmed q of in, or "" when it is shorter than
// minSearchRunes.
func searchQuery(in map[string]any) string {
q := strings.TrimSpace(str(in, "q"))
if utf8.RuneCountInString(q) < minSearchRunes {
return ""
}
return q
}
// writeSearchUnavailable answers a search the engine cannot serve: it is not
// configured or the call failed. The list without q keeps working.
func writeSearchUnavailable(w http.ResponseWriter) {
wire.WriteJSON(w, http.StatusServiceUnavailable, map[string]any{"error": true, "message": "Search is unavailable."})
}
// rankOrder orders rows by their position in ids, the engine's rank. The ids
// are parsed integers, so the array literal carries no caller text.
func rankOrder(ids []uint) string {
parts := make([]string, len(ids))
for i, id := range ids {
parts[i] = strconv.FormatUint(uint64(id), 10)
}
return "array_position(ARRAY[" + strings.Join(parts, ",") + "]::bigint[], jz_bm_materials.id), jz_bm_materials.id DESC"
}
// segmentJSON is one run of a snippet: the engine's plain text, verbatim,
// and whether it matched the query. It is never markup; the client renders
// it as text.
type segmentJSON struct {
Text string `json:"text"`
Hit bool `json:"hit"`
}
// snippetJSON is the one excerpt a search result shows. Source is "body" or
// "file" (FileName set); Lead and Trail say whether text was cut before or
// after the excerpt.
type snippetJSON struct {
Source string `json:"source"`
FileName *string `json:"file_name"`
Lead bool `json:"lead"`
Trail bool `json:"trail"`
Segments []segmentJSON `json:"segments"`
}
// pickSnippet returns the snippet of m from hit: the first body snippet,
// mapped one to one, or else the first file_texts snippet, with the name of
// the file at its array index in files (the IndexedFiles of m, in document
// order; nil when the index does not resolve). A file text is long and is
// not loaded for the page, so a file snippet is always cut on both sides.
// It is nil when the hit has neither. Call it only for a row the SQL
// re-gate returned.
func pickSnippet(hit beachcomber.Hit, m models.Material, files []models.IndexedFile) *snippetJSON {
for _, sn := range hit.Highlights {
if sn.Field != "body" || len(sn.Segments) == 0 {
continue
}
out := &snippetJSON{Source: "body", Segments: snippetSegments(sn)}
var joined strings.Builder
for _, seg := range sn.Segments {
joined.WriteString(seg.Text)
}
body := ""
if m.Body != nil {
body = models.MaterialPlainBody(*m.Body)
}
text := strings.TrimSpace(joined.String())
out.Lead = !strings.HasPrefix(body, text)
out.Trail = !strings.HasSuffix(body, text)
return out
}
for _, sn := range hit.Highlights {
if sn.Field != fileTextsField || len(sn.Segments) == 0 {
continue
}
out := &snippetJSON{Source: "file", Lead: true, Trail: true, Segments: snippetSegments(sn)}
if sn.ArrayIndex >= 0 && sn.ArrayIndex < len(files) {
name := files[sn.ArrayIndex].FileName
out.FileName = &name
}
return out
}
return nil
}
// fileTextsField is the document field of the attached files' texts.
const fileTextsField = "file_texts"
// snippetSegments maps the engine's segments one to one.
func snippetSegments(sn beachcomber.Snippet) []segmentJSON {
out := make([]segmentJSON, 0, len(sn.Segments))
for _, seg := range sn.Segments {
out = append(out, segmentJSON{Text: seg.Text, Hit: seg.Match})
}
return out
}
// hasFileSnippet reports whether hit carries a file_texts snippet and no
// body one, so its snippet needs the material's file names.
func hasFileSnippet(hit beachcomber.Hit) bool {
file := false
for _, sn := range hit.Highlights {
if len(sn.Segments) == 0 {
continue
}
switch sn.Field {
case "body":
return false
case fileTextsField:
file = true
}
}
return file
}
// snippetFiles loads, once per page, the indexed files (names only) of the
// rows whose snippet comes from a file. It reads nothing when no row needs
// it. ids are rows SQL returned.
func snippetFiles(db *gorm.DB, ids []uint, hits map[uint]beachcomber.Hit) (map[uint][]models.IndexedFile, error) {
var need []uint
for _, id := range ids {
if hit, ok := hits[id]; ok && hasFileSnippet(hit) {
need = append(need, id)
}
}
if len(need) == 0 {
return nil, nil
}
return models.IndexedFiles(db, need, false)
}
// flattenSnippet is a snippet as plain text, for MCP: the segment texts
// joined, with an ellipsis where text was cut.
func flattenSnippet(s *snippetJSON) string {
if s == nil {
return ""
}
var b strings.Builder
if s.Lead {
b.WriteString("…")
}
for _, seg := range s.Segments {
b.WriteString(seg.Text)
}
if s.Trail {
b.WriteString("…")
}
return b.String()
}
// snippetValue is the snippet key of a row: the struct, a plain string
// through MCP, or nil when there is none (the key is then left out).
func snippetValue(s *snippetJSON, mcp bool) any {
if s == nil {
return nil
}
if mcp {
return flattenSnippet(s)
}
return s
}

View File

@@ -0,0 +1,291 @@
package api_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"git.golem15.com/golem15/summercms/modules/beachcomber"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"git.golem15.com/jakub/sm-bm-plugin/internal/searchtest"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func segments(parts ...any) []beachcomber.Segment {
out := make([]beachcomber.Segment, 0, len(parts)/2)
for i := 0; i+1 < len(parts); i += 2 {
out = append(out, beachcomber.Segment{Text: parts[i].(string), Match: parts[i+1].(bool)})
}
return out
}
func TestMaterialSnippet(t *testing.T) {
body := "# Wstęp\n\nNa początku. Proces **globalizacji** zmienia państwa. Koniec tekstu."
m := models.Material{ID: 3, Body: &body}
hit := beachcomber.Hit{ID: "3", Highlights: []beachcomber.Snippet{
{Field: "title", ArrayIndex: -1, Segments: segments("Tytuł", true)},
{Field: "body", ArrayIndex: -1, Segments: segments("Proces ", false, "globalizacji", true, " zmienia <b>państwa</b>.", false)},
}}
s := api.PickSnippet(hit, m, nil)
if s == nil {
t.Fatal("no snippet")
}
if s.Source != "body" || s.FileName != nil {
t.Errorf("source %q file %v, want body and no file", s.Source, s.FileName)
}
if len(s.Segments) != 3 || s.Segments[1].Text != "globalizacji" || !s.Segments[1].Hit || s.Segments[0].Hit {
t.Errorf("segments = %+v", s.Segments)
}
if s.Segments[2].Text != " zmienia <b>państwa</b>." {
t.Errorf("segment text was changed: %q", s.Segments[2].Text)
}
if !s.Lead || !s.Trail {
t.Errorf("lead %v trail %v, want both (cut inside the body)", s.Lead, s.Trail)
}
b, err := json.Marshal(s)
if err != nil {
t.Fatal(err)
}
if got := string(b); !strings.Contains(got, `"source":"body","file_name":null,"lead":true,"trail":true,"segments":[{"text":"Proces ","hit":false}`) {
t.Errorf("JSON = %s", got)
}
// The whole body: neither lead nor trail.
short := "Krótka **notatka**"
whole := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "body", ArrayIndex: -1, Segments: segments("Krótka ", false, "notatka", true)}}}, models.Material{Body: &short}, nil)
if whole == nil || whole.Lead || whole.Trail {
t.Errorf("whole body snippet = %+v, want no lead or trail", whole)
}
// Start of the body only: trail but no lead.
start := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "body", ArrayIndex: -1, Segments: segments("Wstęp ", false, "Na", true)}}}, m, nil)
if start == nil || start.Lead || !start.Trail {
t.Errorf("start snippet = %+v, want trail only", start)
}
// A snippet on another field only, or none at all, gives no snippet.
if got := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "title", ArrayIndex: -1, Segments: segments("x", true)}}}, m, nil); got != nil {
t.Errorf("title-only hit gave %+v", got)
}
if got := api.PickSnippet(beachcomber.Hit{ID: "3"}, m, nil); got != nil {
t.Errorf("hit without highlights gave %+v", got)
}
// A match only in an attached file: the file snippet, named by the
// snippet's array index into the indexed files, cut on both sides.
files := []models.IndexedFile{{FileID: 7, FileName: "wstep.pdf"}, {FileID: 9, FileName: "rozdzial-2.pdf"}}
fileHit := beachcomber.Hit{Highlights: []beachcomber.Snippet{
{Field: "title", ArrayIndex: -1, Segments: segments("Tytuł", true)},
{Field: "file_texts", ArrayIndex: 1, Segments: segments("o ", false, "demokracji", true, " w Europie", false)},
}}
fs := api.PickSnippet(fileHit, m, files)
if fs == nil || fs.Source != "file" || fs.FileName == nil || *fs.FileName != "rozdzial-2.pdf" || !fs.Lead || !fs.Trail {
t.Fatalf("file snippet = %+v, want source file, rozdzial-2.pdf, lead and trail", fs)
}
if len(fs.Segments) != 3 || fs.Segments[1].Text != "demokracji" || !fs.Segments[1].Hit {
t.Errorf("file segments = %+v", fs.Segments)
}
fb, err := json.Marshal(fs)
if err != nil {
t.Fatal(err)
}
if got := string(fb); !strings.Contains(got, `"source":"file","file_name":"rozdzial-2.pdf","lead":true,"trail":true`) {
t.Errorf("file JSON = %s", got)
}
// The first file by index.
first := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "file_texts", ArrayIndex: 0, Segments: segments("x", true)}}}, m, files)
if first == nil || first.FileName == nil || *first.FileName != "wstep.pdf" {
t.Errorf("index 0 snippet = %+v, want wstep.pdf", first)
}
// An index the files do not resolve (out of range, -1, no files): no name.
for _, c := range []struct {
idx int
files []models.IndexedFile
}{{5, files}, {-1, files}, {0, nil}} {
got := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "file_texts", ArrayIndex: c.idx, Segments: segments("x", true)}}}, m, c.files)
if got == nil || got.Source != "file" || got.FileName != nil {
t.Errorf("index %d with %d files: snippet = %+v, want a file snippet with no name", c.idx, len(c.files), got)
}
}
// A body snippet is preferred over a file snippet, whatever the order.
both := beachcomber.Hit{Highlights: []beachcomber.Snippet{
{Field: "file_texts", ArrayIndex: 0, Segments: segments("plik", true)},
{Field: "body", ArrayIndex: -1, Segments: segments("Proces ", false, "globalizacji", true)},
}}
if got := api.PickSnippet(both, m, files); got == nil || got.Source != "body" || got.FileName != nil {
t.Errorf("body and file hit gave %+v, want the body snippet", got)
}
if !api.HasFileSnippet(fileHit) || api.HasFileSnippet(both) || api.HasFileSnippet(hit) {
t.Error("HasFileSnippet: want true for a file-only hit, false with a body snippet")
}
if got := api.FlattenSnippet(s); got != "…Proces globalizacji zmienia <b>państwa</b>.…" {
t.Errorf("FlattenSnippet = %q", got)
}
if got := api.FlattenSnippet(nil); got != "" {
t.Errorf("FlattenSnippet(nil) = %q", got)
}
if got := api.RankOrder([]uint{9, 3}); got != "array_position(ARRAY[9,3]::bigint[], jz_bm_materials.id), jz_bm_materials.id DESC" {
t.Errorf("RankOrder = %q", got)
}
}
func TestMaterialsSearchUnavailable(t *testing.T) {
h := noDB()
user := &bouncer.Principal{ID: 7}
code, body := serve(t, h.Materials, http.MethodGet, "/?q=globalizacja", user, nil)
if code != http.StatusServiceUnavailable || body["error"] != true || body["message"] != "Search is unavailable." {
t.Errorf("q without an index = %d %v, want 503 Search is unavailable.", code, body)
}
// One rune is no search: the list answers as without q (no database).
code, body = serve(t, h.Materials, http.MethodGet, "/?q=%20g%20", user, nil)
if code != http.StatusServiceUnavailable || body["message"] != "Database unavailable." {
t.Errorf("one-rune q = %d %v, want the no-database answer", code, body)
}
code, body = serve(t, h.Materials, http.MethodGet, "/", user, nil)
if code != http.StatusServiceUnavailable || body["message"] != "Database unavailable." {
t.Errorf("no q = %d %v, want the no-database answer", code, body)
}
// An unconfigured engine is the same 503.
h.MaterialIndex = classes.NewMaterialIndexer(searchtest.App(t))
code, body = serve(t, h.Materials, http.MethodGet, "/?q=globalizacja", user, nil)
if code != http.StatusServiceUnavailable || body["message"] != "Search is unavailable." {
t.Errorf("q with a null engine = %d %v, want 503 Search is unavailable.", code, body)
}
}
// sqlRecorder is a dry-run postgres handle that records every query it
// builds, with its arguments inlined.
type sqlRecorder struct {
mu sync.Mutex
sql []string
}
func (r *sqlRecorder) queries() []string {
r.mu.Lock()
defer r.mu.Unlock()
return append([]string(nil), r.sql...)
}
func dryDB(t *testing.T) (*gorm.DB, *sqlRecorder) {
t.Helper()
db, err := gorm.Open(postgres.New(postgres.Config{DSN: "host=127.0.0.1"}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
if err != nil {
t.Fatal(err)
}
rec := &sqlRecorder{}
err = db.Callback().Query().After("gorm:query").Register("test:record_sql", func(tx *gorm.DB) {
rec.mu.Lock()
defer rec.mu.Unlock()
rec.sql = append(rec.sql, tx.Dialector.Explain(tx.Statement.SQL.String(), tx.Statement.Vars...))
})
if err != nil {
t.Fatal(err)
}
return db, rec
}
func TestMaterialsSearchTrace(t *testing.T) {
stub := &searchtest.Stub{Hits: []searchtest.Hit{
{ID: "9"},
{ID: "3", Field: "body", Snippet: "o " + searchtest.HighlightStart + "globalizacji" + searchtest.HighlightEnd},
}}
db, rec := dryDB(t)
h := &api.Handlers{
DB: func() *gorm.DB { return db },
MaterialIndex: classes.NewMaterialIndexer(searchtest.App(t, searchtest.Start(t, stub)...)),
}
req := httptest.NewRequest(http.MethodGet, "/materials?q=globalizacja&course=7", nil)
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: 5}))
w := httptest.NewRecorder()
h.Materials(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
if n := len(stub.Searches()); n != 1 {
t.Errorf("searches = %d, want 1", n)
}
var count, page string
for _, q := range rec.queries() {
switch {
case strings.HasPrefix(q, "SELECT count(*)"):
count = q
case strings.HasPrefix(q, "SELECT") && strings.Contains(q, `FROM "jz_bm_materials"`):
page = q
}
}
if count == "" || page == "" {
t.Fatalf("queries = %q, want a count and a page", rec.queries())
}
for name, q := range map[string]string{"count": count, "page": page} {
for _, want := range []string{"jz_bm_materials.is_private = FALSE", "jz_bm_materials.published_at IS NOT NULL", "jz_bm_materials.course_id = 7", "jz_bm_materials.id IN (9,3)"} {
if !strings.Contains(q, want) {
t.Errorf("%s query lacks %q:\n%s", name, want, q)
}
}
}
if !strings.Contains(page, "array_position(ARRAY[9,3]::bigint[], jz_bm_materials.id)") {
t.Errorf("page query is not in rank order:\n%s", page)
}
if strings.Contains(page, "jz_bm_material_pins") {
t.Errorf("page query with q orders by pins, want the rank order only:\n%s", page)
}
var out struct {
Data []map[string]any `json:"data"`
Meta struct {
Total int `json:"total"`
} `json:"meta"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if out.Meta.Total != 0 || len(out.Data) != 0 {
t.Errorf("total %d data %v, want the dry SQL's 0 (never the engine's found)", out.Meta.Total, out.Data)
}
}
func TestManagedMaterialsSearch(t *testing.T) {
h := noDB()
user := &bouncer.Principal{ID: 7}
code, body := serve(t, h.ManagedMaterials, http.MethodGet, "/?q=globalizacja", user, nil)
if code != http.StatusServiceUnavailable || body["error"] != true || body["message"] != "Search is unavailable." {
t.Errorf("q without an index = %d %v, want 503 Search is unavailable.", code, body)
}
code, body = serve(t, h.ManagedMaterials, http.MethodGet, "/?q="+strings.Repeat("a", 101), user, nil)
if code != http.StatusUnprocessableEntity {
t.Errorf("q over 100 characters = %d %v, want 422", code, body)
} else if errs, _ := body["errors"].(map[string]any); errs["q"] == nil {
t.Errorf("422 errors %v have no q message", errs)
}
code, body = serve(t, h.ManagedMaterials, http.MethodGet, "/?q=a&include_body=true", user, nil)
if code != http.StatusServiceUnavailable || body["message"] != "Database unavailable." {
t.Errorf("one-rune q = %d %v, want the no-database answer", code, body)
}
}
func TestMaterialSnippetMCP(t *testing.T) {
body := "Wstęp. Proces globalizacji zmienia państwa. Koniec."
m := models.Material{Body: &body}
mid := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "body", ArrayIndex: -1, Segments: segments("Proces ", false, "globalizacji", true, " zmienia", false)}}}, m, nil)
if got := api.FlattenSnippet(mid); got != "…Proces globalizacji zmienia…" {
t.Errorf("middle = %q, want ellipses on both sides", got)
}
head := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "body", ArrayIndex: -1, Segments: segments("Wstęp", true, ". Proces", false)}}}, m, nil)
if got := api.FlattenSnippet(head); got != "Wstęp. Proces…" {
t.Errorf("head = %q, want a trailing ellipsis only", got)
}
tail := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "body", ArrayIndex: -1, Segments: segments("państwa. ", false, "Koniec", true, ".", false)}}}, m, nil)
if got := api.FlattenSnippet(tail); got != "…państwa. Koniec." {
t.Errorf("tail = %q, want a leading ellipsis only", got)
}
whole := api.PickSnippet(beachcomber.Hit{Highlights: []beachcomber.Snippet{{Field: "body", ArrayIndex: -1, Segments: segments(body, false)}}}, m, nil)
if got := api.FlattenSnippet(whole); got != body {
t.Errorf("whole = %q, want no ellipsis", got)
}
}

View File

@@ -0,0 +1,301 @@
package api
import (
"context"
"net/http"
"strconv"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/beachcomber"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// published scopes a material query to what students may see: a
// publication time that has passed. A NULL published_at is a draft.
func published(q *gorm.DB, now time.Time) *gorm.DB {
return q.Where("jz_bm_materials.published_at IS NOT NULL AND jz_bm_materials.published_at <= ?", now.UTC())
}
// materialFilter holds the validated filters of /materials.
type materialFilter struct {
CourseID uint
MeetingID uint
Tag string
Type string
}
func (f materialFilter) apply(q *gorm.DB) *gorm.DB {
if f.CourseID != 0 {
q = q.Where("jz_bm_materials.course_id = ?", f.CourseID)
}
if f.MeetingID != 0 {
q = q.Where("jz_bm_materials.meeting_id = ?", f.MeetingID)
}
if f.Type != "" {
q = q.Where("jz_bm_materials.type = ?", f.Type)
}
if f.Tag != "" {
q = q.Where(`EXISTS (SELECT 1 FROM jz_bm_material_tag mt JOIN jz_bm_tags t ON t.id = mt.tag_id
WHERE mt.material_id = jz_bm_materials.id AND t.slug = ?)`, f.Tag)
}
return q
}
func preloadMaterial(q *gorm.DB) *gorm.DB {
return q.Preload("Course").Preload("Tags", func(db *gorm.DB) *gorm.DB { return db.Order("jz_bm_tags.name") })
}
// listMaterials returns one page of the published materials userID may
// see. With ids nil the page lists the caller's pinned materials first
// (newest pin first), then newest first. With ids non-nil (search
// candidates in the engine's rank order) both the count and the page are
// also limited to ids and the page follows their order, where pins are only
// marked; the ids never widen what visibleMaterials and the filter allow.
// An empty ids is an empty page. The count never depends on pins.
func listMaterials(db *gorm.DB, now time.Time, userID uint, f materialFilter, ids []uint, page, perPage int) ([]materialListJSON, []models.Material, int64, error) {
if ids != nil && len(ids) == 0 {
return []materialListJSON{}, nil, 0, nil
}
q := f.apply(visibleMaterials(db.Model(&models.Material{}), now, userID))
if ids != nil {
q = q.Where("jz_bm_materials.id IN ?", ids)
}
var total int64
if err := q.Count(&total).Error; err != nil {
return nil, nil, 0, err
}
rowsQ := preloadMaterial(f.apply(visibleMaterials(db, now, userID)))
if ids != nil {
rowsQ = rowsQ.Where("jz_bm_materials.id IN ?", ids).Order(rankOrder(ids))
} else {
rowsQ = rowsQ.Order(pinnedFirstOrder(userID))
}
var rows []models.Material
err := rowsQ.Offset((page - 1) * perPage).Limit(perPage).Find(&rows).Error
if err != nil {
return nil, nil, 0, err
}
out, err := materialsJSON(db, userID, rows)
return out, rows, total, err
}
// materialsJSON builds list rows with their file counts and userID's own
// pins.
func materialsJSON(db *gorm.DB, userID uint, rows []models.Material) ([]materialListJSON, error) {
ids := make([]string, 0, len(rows))
for _, m := range rows {
ids = append(ids, strconv.FormatUint(uint64(m.ID), 10))
}
counts := map[string]int64{}
if len(ids) > 0 {
var found []struct {
AttachmentID string
Count int64
}
err := db.Model(&attach.File{}).
Select("attachment_id, COUNT(*) AS count").
Where("attachment_type = ? AND field = ? AND is_public AND attachment_id IN ?", models.Material{}.MorphName(), models.MaterialFilesField, ids).
Group("attachment_id").
Scan(&found).Error
if err != nil {
return nil, err
}
for _, row := range found {
counts[row.AttachmentID] = row.Count
}
}
pinned, err := pinnedMaterialIDs(db, userID, materialIDs(rows))
if err != nil {
return nil, err
}
out := make([]materialListJSON, 0, len(rows))
for _, m := range rows {
row := newMaterialListJSON(m, counts[strconv.FormatUint(uint64(m.ID), 10)])
row.Pinned = pinned[m.ID]
out = append(out, row)
}
return out, nil
}
// Materials answers GET /materials?q=&course=&meeting=&tag=&type=&page=&per_page=:
// a page of the published materials the caller may see, in the {data, meta}
// shape of lagoon.Paginate. With q (2 to 100 characters) the engine answers
// candidates, which SQL re-gates, counts and pages in rank order, each row
// with at most one snippet; when the engine cannot answer the request is a
// 503. Without q the caller's own pins come first (newest pin first), then
// newest first, and the engine is never called. With q the order is
// relevance and rows only carry pinned.
func (h *Handlers) Materials(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
in := query(r, "q", "course", "meeting", "tag", "type", "page", "per_page")
if !h.validate(w, r, in, materialsRules) {
return
}
filter := materialFilter{CourseID: uintParam(in, "course"), MeetingID: uintParam(in, "meeting"), Tag: strings.TrimSpace(str(in, "tag")), Type: str(in, "type")}
var cands *classes.MaterialCandidates
if q := searchQuery(in); q != "" {
c, err := h.MaterialIndex.Search(r.Context(), classes.MaterialSearch{Q: q, CourseID: filter.CourseID, MeetingID: filter.MeetingID, Type: filter.Type, Tag: filter.Tag})
if err != nil {
writeSearchUnavailable(w)
return
}
cands = &c
}
db, ok := h.db(w, r)
if !ok {
return
}
page := min(intParam(in, "page", 1), 100000)
perPage := intParam(in, "per_page", h.perPage())
var ids []uint
if cands != nil {
ids = cands.IDs
if ids == nil {
ids = []uint{}
}
}
out, rows, total, err := listMaterials(db, h.now(), userID, filter, ids, page, perPage)
if err != nil {
writeOpaque500(w)
return
}
if cands != nil {
files, err := snippetFiles(db, materialIDs(rows), cands.Hits)
if err != nil {
writeOpaque500(w)
return
}
attachSnippets(out, rows, cands.Hits, files, viaMCP(r))
}
writeJSONPage(w, lagoon.Paginate(out, page, perPage, total))
}
// attachSnippets sets the snippet of each list row from its Hit and, for a
// file snippet, the row's indexed files. rows are
// the rows SQL returned (they passed the re-gate), in the order of out; the
// Hit of an id SQL did not return is never read.
func attachSnippets(out []materialListJSON, rows []models.Material, hits map[uint]beachcomber.Hit, files map[uint][]models.IndexedFile, mcp bool) {
for i := range out {
if i >= len(rows) || rows[i].ID != out[i].ID {
continue
}
hit, ok := hits[rows[i].ID]
if !ok {
continue
}
out[i].Snippet = snippetValue(pickSnippet(hit, rows[i], files[rows[i].ID]), mcp)
}
}
// materialIDs are the ids of rows, in order.
func materialIDs(rows []models.Material) []uint {
ids := make([]uint, 0, len(rows))
for _, m := range rows {
ids = append(ids, m.ID)
}
return ids
}
// Material answers GET /materials/{id}: one published material the caller
// may see, with its body, tags and files. A draft, a future publication or
// another user's private material is a 404. can_manage tells the author (a
// material manager) that the access panel applies. An MCP call gets the body
// only with include_body (see materialView).
func (h *Handlers) Material(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
id, ok := surf.IntParam(r, "id")
if !ok || id <= 0 {
writeNotFound(w)
return
}
out, found, err := h.loadMaterialDetail(r.Context(), db, userID, uint(id))
if err != nil {
writeOpaque500(w)
return
}
if !found {
writeNotFound(w)
return
}
writeData(w, materialView(out, viaMCP(r), includeBody(r)))
}
// loadMaterialDetail builds the student detail of material id as userID
// sees it: the published, visible row with its course and tags, its public
// files, can_manage, the revision and the caller's own pin. found is false when the caller cannot
// see it. GET /materials/{id} and the author's routes answer with it.
func (h *Handlers) loadMaterialDetail(ctx context.Context, db *gorm.DB, userID, id uint) (materialDetailJSON, bool, error) {
var m models.Material
res := preloadMaterial(visibleMaterials(db, h.now(), userID)).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
return materialDetailJSON{}, false, res.Error
}
if res.RowsAffected == 0 {
return materialDetailJSON{}, false, nil
}
var files []attach.File
err := db.Where("attachment_type = ? AND attachment_id = ? AND field = ?", m.MorphName(), strconv.FormatUint(uint64(m.ID), 10), models.MaterialFilesField).
Order("sort_order, id").
Find(&files).Error
if err != nil {
return materialDetailJSON{}, false, err
}
out := materialDetailJSON{
materialListJSON: newMaterialListJSON(m, int64(len(files))),
Body: m.Body,
Files: make([]fileJSON, 0, len(files)),
Revision: m.Revision,
}
for i := range files {
f := &files[i]
if !f.Public() {
continue
}
out.Files = append(out.Files, fileJSON{ID: f.ID, URL: f.URL(), Name: f.FileName, Size: f.FileSize, Mime: f.ContentType})
}
out.FilesCount = int64(len(out.Files))
pinned, err := pinnedMaterialIDs(db, userID, []uint{m.ID})
if err != nil {
return materialDetailJSON{}, false, err
}
out.Pinned = pinned[m.ID]
if m.AuthorUserID == nil || *m.AuthorUserID == userID {
manager, err := h.managesMaterials(ctx, db, userID)
if err != nil {
return materialDetailJSON{}, false, err
}
out.CanManage = canManageMaterial(m, userID, manager)
}
return out, true, nil
}
// publishedMaterialsOfCourse lists a course's published materials that
// userID may see, newest first, for /courses/{id}. Rows carry the caller's
// pins but keep this order.
func publishedMaterialsOfCourse(db *gorm.DB, now time.Time, userID uint, courseID uint) ([]materialListJSON, error) {
var rows []models.Material
err := preloadMaterial(visibleMaterials(db, now, userID)).
Where("jz_bm_materials.course_id = ?", courseID).
Order("jz_bm_materials.published_at DESC, jz_bm_materials.id DESC").
Find(&rows).Error
if err != nil {
return nil, err
}
return materialsJSON(db, userID, rows)
}

View File

@@ -0,0 +1,85 @@
package api
import (
"net/http"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// The MCP view of the material answers (D-17, D-21): a material's body may
// hold transcript text, so an answer to an MCP tool call leaves it out
// unless the call asks for it with include_body, and a write answer never
// echoes it. Plain HTTP answers are unchanged.
// viaMCP reports whether r is an MCP tool call: a request pier dispatched
// in-process with the api_token marker. The marker lives on the context
// only, so an HTTP request can never carry it.
func viaMCP(r *http.Request) bool {
_, ok := bouncer.Dispatched(r.Context(), "api_token")
return ok
}
// includeBody reports whether r asks for the material body
// (include_body=true or 1).
func includeBody(r *http.Request) bool {
return flag(r, "include_body")
}
// bodyOmitted reports whether leaving body out hides content.
func bodyOmitted(body *string) bool {
return body != nil && *body != ""
}
// mcpMaterialDetailJSON is a published material under MCP without its body:
// the list fields and the files, with body_omitted when a non-empty body was
// left out. Body shadows the embedded one and stays nil.
type mcpMaterialDetailJSON struct {
materialDetailJSON
Body *string `json:"body,omitempty"`
BodyOmitted bool `json:"body_omitted,omitempty"`
}
// mcpManagedMaterialJSON is a managed material under MCP without its body.
type mcpManagedMaterialJSON struct {
managedMaterialJSON
Body *string `json:"body,omitempty"`
BodyOmitted bool `json:"body_omitted,omitempty"`
}
// mcpManagedMaterialDetailJSON is a managed material with its files under
// MCP without its body.
type mcpManagedMaterialDetailJSON struct {
mcpManagedMaterialJSON
Files []fileJSON `json:"files"`
}
// materialView is the answer of GET /materials/{id} (student): unchanged
// over plain HTTP; under MCP (mcp) without the body unless withBody.
func materialView(d materialDetailJSON, mcp, withBody bool) any {
if !mcp || withBody {
return d
}
return mcpMaterialDetailJSON{materialDetailJSON: d, BodyOmitted: bodyOmitted(d.Body)}
}
// managedMaterialView is a managed material: unchanged over plain HTTP;
// under MCP (mcp) without the body unless withBody (a write answer passes
// false, so it never echoes the body).
func managedMaterialView(m managedMaterialJSON, mcp, withBody bool) any {
if !mcp || withBody {
return m
}
return mcpManagedMaterialJSON{managedMaterialJSON: m, BodyOmitted: bodyOmitted(m.Body)}
}
// managedMaterialDetailView is a managed material with its files, under the
// same rule as managedMaterialView.
func managedMaterialDetailView(d managedMaterialDetailJSON, mcp, withBody bool) any {
if !mcp || withBody {
return d
}
return mcpManagedMaterialDetailJSON{
mcpManagedMaterialJSON: mcpManagedMaterialJSON{managedMaterialJSON: d.managedMaterialJSON, BodyOmitted: bodyOmitted(d.Body)},
Files: d.Files,
}
}

View File

@@ -0,0 +1,167 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// mcpRequest is a request as pier dispatches it in-process: the api_token
// marker with a principal on its context.
func mcpRequest(method, target string) *http.Request {
r := httptest.NewRequest(method, target, nil)
return r.WithContext(bouncer.WithDispatch(r.Context(), &bouncer.Dispatch{
Guards: []string{"api_token"},
Principal: &bouncer.Principal{ID: 7},
}))
}
// keysOf marshals v and returns its top-level JSON object.
func keysOf(t *testing.T, v any) map[string]any {
t.Helper()
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
t.Fatal(err)
}
return out
}
func TestViaMCP(t *testing.T) {
plain := httptest.NewRequest(http.MethodGet, "/", nil)
if viaMCP(plain) {
t.Error("a plain request is an MCP call")
}
if !viaMCP(mcpRequest(http.MethodGet, "/")) {
t.Error("a dispatched api_token request is not an MCP call")
}
backend := httptest.NewRequest(http.MethodGet, "/", nil)
backend = backend.WithContext(bouncer.WithDispatch(backend.Context(), &bouncer.Dispatch{
Guards: []string{"backend"},
Principal: &bouncer.Principal{ID: 7},
}))
if viaMCP(backend) {
t.Error("a backend dispatch is an MCP call of jz.bm")
}
for target, want := range map[string]bool{
"/": false,
"/?include_body=false": false,
"/?include_body=0": false,
"/?include_body=true": true,
"/?include_body=1": true,
} {
if got := includeBody(httptest.NewRequest(http.MethodGet, target, nil)); got != want {
t.Errorf("includeBody(%s) = %v, want %v", target, got, want)
}
}
}
func TestMCPMaterialView(t *testing.T) {
body := "transcript text"
url := "https://x.test/a"
detail := materialDetailJSON{
materialListJSON: materialListJSON{ID: 3, Title: "T", Type: "notatka", URL: &url, Tags: []tagJSON{}},
Body: &body,
Files: []fileJSON{{ID: 9, URL: "/storage/f.pdf", Name: "f.pdf", Size: 10, Mime: "application/pdf"}},
}
t.Run("plain request unchanged", func(t *testing.T) {
got := keysOf(t, materialView(detail, viaMCP(httptest.NewRequest(http.MethodGet, "/", nil)), false))
want := keysOf(t, detail)
gotRaw, _ := json.Marshal(got)
wantRaw, _ := json.Marshal(want)
if string(gotRaw) != string(wantRaw) {
t.Errorf("plain view = %s, want %s", gotRaw, wantRaw)
}
})
t.Run("MCP without include_body", func(t *testing.T) {
got := keysOf(t, materialView(detail, viaMCP(mcpRequest(http.MethodGet, "/")), includeBody(mcpRequest(http.MethodGet, "/"))))
if _, ok := got["body"]; ok {
t.Errorf("body present: %v", got)
}
if got["body_omitted"] != true {
t.Errorf("body_omitted = %v, want true", got["body_omitted"])
}
files, _ := got["files"].([]any)
if len(files) != 1 {
t.Fatalf("files = %v", got["files"])
}
f := files[0].(map[string]any)
for _, k := range []string{"id", "name", "size", "mime", "url"} {
if _, ok := f[k]; !ok {
t.Errorf("file lacks %s: %v", k, f)
}
}
if got["title"] != "T" || got["url"] != url {
t.Errorf("list fields lost: %v", got)
}
})
t.Run("MCP without include_body, empty body", func(t *testing.T) {
empty := detail
empty.Body = nil
got := keysOf(t, materialView(empty, true, false))
if _, ok := got["body"]; ok {
t.Errorf("body present: %v", got)
}
if _, ok := got["body_omitted"]; ok {
t.Errorf("body_omitted set for an empty body: %v", got)
}
})
t.Run("MCP with include_body", func(t *testing.T) {
got := keysOf(t, materialView(detail, true, includeBody(mcpRequest(http.MethodGet, "/?include_body=true"))))
if got["body"] != body {
t.Errorf("body = %v, want %q", got["body"], body)
}
if _, ok := got["body_omitted"]; ok {
t.Errorf("body_omitted set with include_body: %v", got)
}
})
managed := managedMaterialJSON{ID: 3, Title: "T", Type: "notatka", Body: &body, Tags: []tagJSON{}}
t.Run("managed plain unchanged", func(t *testing.T) {
got := keysOf(t, managedMaterialView(managed, false, false))
if got["body"] != body {
t.Errorf("plain managed body = %v", got["body"])
}
if _, ok := got["body_omitted"]; ok {
t.Errorf("plain managed has body_omitted: %v", got)
}
})
t.Run("managed MCP read", func(t *testing.T) {
got := keysOf(t, managedMaterialView(managed, true, false))
if _, ok := got["body"]; ok || got["body_omitted"] != true {
t.Errorf("managed MCP read = %v, want no body and body_omitted", got)
}
got = keysOf(t, managedMaterialView(managed, true, includeBody(mcpRequest(http.MethodGet, "/?include_body=1"))))
if got["body"] != body {
t.Errorf("managed MCP read with include_body = %v", got)
}
})
// A write answer passes withBody false whatever the request asks.
t.Run("managed MCP write never echoes the body", func(t *testing.T) {
got := keysOf(t, managedMaterialView(managed, true, false))
if _, ok := got["body"]; ok || got["body_omitted"] != true {
t.Errorf("managed MCP write = %v, want no body and body_omitted", got)
}
d := managedMaterialDetailJSON{managedMaterialJSON: managed, Files: []fileJSON{}}
got = keysOf(t, managedMaterialDetailView(d, true, false))
if _, ok := got["body"]; ok || got["body_omitted"] != true {
t.Errorf("managed MCP write detail = %v, want no body and body_omitted", got)
}
if _, ok := got["files"]; !ok {
t.Errorf("managed MCP write detail lost files: %v", got)
}
})
}

119
controllers/api/params.go Normal file
View File

@@ -0,0 +1,119 @@
package api
import (
"net/http"
"strconv"
"time"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// Rule tables of the query parameters, in the order the errors are listed.
// lagoon.ParseRules panics on a bad rule, so a mistake here stops start-up.
var (
dateRule = `nullable|regex:/^\d{4}-\d{2}-\d{2}$/|date`
// rangeRules check from and to alone; rangeRulesFrom also orders them
// when both are given.
rangeRules = []lagoon.RequestRule{
{Field: "from", Rules: lagoon.ParseRules(dateRule)},
{Field: "to", Rules: lagoon.ParseRules(dateRule)},
}
rangeRulesFrom = []lagoon.RequestRule{
{Field: "from", Rules: lagoon.ParseRules(dateRule)},
{Field: "to", Rules: lagoon.ParseRules(dateRule + "|after_or_equal:from")},
}
courseFilterRules = []lagoon.RequestRule{
{Field: "course", Rules: lagoon.ParseRules("nullable|integer|min:1")},
}
coursesRules = []lagoon.RequestRule{
{Field: "semester", Rules: lagoon.ParseRules("nullable|integer|between:1,4")},
}
materialsRules = []lagoon.RequestRule{
{Field: "course", Rules: lagoon.ParseRules("nullable|integer|min:1")},
{Field: "meeting", Rules: lagoon.ParseRules("nullable|integer|min:1")},
{Field: "tag", Rules: lagoon.ParseRules("nullable|string|max:100")},
{Field: "type", Rules: append(lagoon.ParseRules("nullable"), lagoon.In(models.MaterialTypes...))},
{Field: "page", Rules: lagoon.ParseRules("nullable|integer|min:1")},
{Field: "per_page", Rules: lagoon.ParseRules("nullable|integer|between:1,100")},
{Field: "q", Rules: lagoon.ParseRules("nullable|string|max:100")},
}
// manageMaterialsRules check the search of the management list.
manageMaterialsRules = []lagoon.RequestRule{
{Field: "q", Rules: lagoon.ParseRules("nullable|string|max:100")},
}
)
// query collects the named query parameters that are present into the input
// map lagoon.ValidateRequest takes. A repeated parameter keeps its first
// value.
func query(r *http.Request, names ...string) map[string]any {
q := r.URL.Query()
in := make(map[string]any, len(names))
for _, name := range names {
if vals, ok := q[name]; ok && len(vals) > 0 {
in[name] = vals[0]
}
}
return in
}
// validate checks in against rules and answers 422 itself when it fails.
func (h *Handlers) validate(w http.ResponseWriter, r *http.Request, in map[string]any, rules []lagoon.RequestRule) bool {
errs, err := lagoon.ValidateRequest(r.Context(), nil, in, rules, h.translator())
if err != nil {
writeOpaque500(w)
return false
}
if len(errs) > 0 {
writeValidation(w, errs)
return false
}
return true
}
// str returns a validated string parameter, or "" when it is absent.
func str(in map[string]any, name string) string {
s, _ := in[name].(string)
return s
}
// uintParam returns a validated positive integer parameter, or 0 when it is
// absent.
func uintParam(in map[string]any, name string) uint {
n, err := strconv.ParseUint(str(in, name), 10, 64)
if err != nil {
return 0
}
return uint(n)
}
// intParam returns a validated integer parameter, or def when it is absent.
func intParam(in map[string]any, name string, def int) int {
n, err := strconv.Atoi(str(in, name))
if err != nil {
return def
}
return n
}
// dayStart returns midnight in Europe/Warsaw of a validated YYYY-MM-DD
// parameter, and false when it is absent.
func dayStart(in map[string]any, name string) (time.Time, bool) {
s := str(in, name)
if s == "" {
return time.Time{}, false
}
d, err := models.ParseDate(s)
if err != nil {
return time.Time{}, false
}
return d.Time(models.Location), true
}
// today returns midnight of now's calendar day in Europe/Warsaw.
func today(now time.Time) time.Time {
y, m, d := now.In(models.Location).Date()
return time.Date(y, m, d, 0, 0, 0, 0, models.Location)
}

254
controllers/api/readings.go Normal file
View File

@@ -0,0 +1,254 @@
package api
import (
"net/http"
"time"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// readingRow is a reading joined with the caller's progress and ownership
// rows.
type readingRow struct {
models.Reading `gorm:"embedded"`
ReadAt *time.Time `gorm:"column:read_at"`
OwnedAt *time.Time `gorm:"column:owned_at"`
}
// listReadings returns the readings, optionally of one course, in course and
// reading order, each with the caller's read_at and owned_at.
func listReadings(db *gorm.DB, userID, courseID uint) ([]readingJSON, error) {
q := db.Table("jz_bm_readings AS r").
Select("r.*, p.read_at, o.owned_at").
Joins("JOIN jz_bm_courses c ON c.id = r.course_id").
Joins("LEFT JOIN jz_bm_reading_progress p ON p.reading_id = r.id AND p.user_id = ?", userID).
Joins("LEFT JOIN jz_bm_reading_ownership o ON o.reading_id = r.id AND o.user_id = ?", userID)
if courseID != 0 {
q = q.Where("r.course_id = ?", courseID)
}
var rows []readingRow
if err := q.Order("c.semester, c.sort_order, c.name, r.course_id, r.sort_order, r.id").Scan(&rows).Error; err != nil {
return nil, err
}
courses, err := coursesByID(db, readingCourseIDs(rows))
if err != nil {
return nil, err
}
out := make([]readingJSON, 0, len(rows))
for _, row := range rows {
item := readingJSON{
ID: row.ID,
CourseID: idOf(row.CourseID),
Course: newCourseRef(courses[idOf(row.CourseID)]),
MeetingID: row.MeetingID,
Title: row.Title,
Author: row.Author,
Source: row.Source,
URL: row.URL,
IsRequired: row.IsRequired,
SortOrder: row.SortOrder,
}
if row.ReadAt != nil {
s := models.FormatDateTime(*row.ReadAt)
item.ReadAt = &s
}
if row.OwnedAt != nil {
s := models.FormatDateTime(*row.OwnedAt)
item.OwnedAt = &s
}
out = append(out, item)
}
return out, nil
}
func readingCourseIDs(rows []readingRow) []uint {
seen := map[uint]bool{}
var ids []uint
for _, row := range rows {
if id := idOf(row.CourseID); !seen[id] {
seen[id] = true
ids = append(ids, id)
}
}
return ids
}
// coursesByID loads the given courses keyed by ID.
func coursesByID(db *gorm.DB, ids []uint) (map[uint]*models.Course, error) {
out := map[uint]*models.Course{}
if len(ids) == 0 {
return out, nil
}
var rows []models.Course
if err := db.Where("id IN ?", ids).Find(&rows).Error; err != nil {
return nil, err
}
for i := range rows {
out[rows[i].ID] = &rows[i]
}
return out, nil
}
// Readings answers GET /readings?course=ID: the reading lists with the
// caller's read state. An unknown course gives an empty list.
func (h *Handlers) Readings(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
in := query(r, "course")
if !h.validate(w, r, in, courseFilterRules) {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
out, err := listReadings(db, userID, uintParam(in, "course"))
if err != nil {
writeOpaque500(w)
return
}
writeData(w, out)
}
// progressJSON is the answer of the progress routes.
type progressJSON struct {
ReadingID uint `json:"reading_id"`
ReadAt *string `json:"read_at"`
}
// readingFor resolves {id} to an existing reading and answers 404 itself
// when there is none.
func readingFor(w http.ResponseWriter, r *http.Request, db *gorm.DB) (uint, bool) {
id, ok := surf.IntParam(r, "id")
if !ok {
writeNotFound(w)
return 0, false
}
var reading models.Reading
res := db.Select("id").Where("id = ? AND course_id IS NOT NULL", id).Limit(1).Find(&reading)
if res.Error != nil {
writeOpaque500(w)
return 0, false
}
if res.RowsAffected == 0 {
writeNotFound(w)
return 0, false
}
return reading.ID, true
}
// MarkRead answers PUT /readings/{id}/progress: it marks the reading read
// by the caller. Marking it again keeps the first read_at.
func (h *Handlers) MarkRead(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
readingID, ok := readingFor(w, r, db)
if !ok {
return
}
now := h.now().UTC()
err := db.Exec(`INSERT INTO jz_bm_reading_progress (reading_id, user_id, read_at) VALUES (?, ?, ?)
ON CONFLICT (reading_id, user_id) DO NOTHING`, readingID, userID, now).Error
if err != nil {
writeOpaque500(w)
return
}
var progress models.ReadingProgress
if err := db.Where("reading_id = ? AND user_id = ?", readingID, userID).Take(&progress).Error; err != nil {
writeOpaque500(w)
return
}
readAt := models.FormatDateTime(progress.ReadAt)
writeData(w, progressJSON{ReadingID: readingID, ReadAt: &readAt})
}
// UnmarkRead answers DELETE /readings/{id}/progress: it clears the caller's
// read mark. Clearing an unread reading is not an error.
func (h *Handlers) UnmarkRead(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
readingID, ok := readingFor(w, r, db)
if !ok {
return
}
if err := db.Where("reading_id = ? AND user_id = ?", readingID, userID).Delete(&models.ReadingProgress{}).Error; err != nil {
writeOpaque500(w)
return
}
writeData(w, progressJSON{ReadingID: readingID})
}
// ownershipJSON is the answer of the owned routes.
type ownershipJSON struct {
ReadingID uint `json:"reading_id"`
OwnedAt *string `json:"owned_at"`
}
// MarkOwned answers PUT /readings/{id}/owned: it marks the reading owned
// by the caller. Marking it again keeps the first owned_at.
func (h *Handlers) MarkOwned(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
readingID, ok := readingFor(w, r, db)
if !ok {
return
}
now := h.now().UTC()
err := db.Exec(`INSERT INTO jz_bm_reading_ownership (reading_id, user_id, owned_at) VALUES (?, ?, ?)
ON CONFLICT (reading_id, user_id) DO NOTHING`, readingID, userID, now).Error
if err != nil {
writeOpaque500(w)
return
}
var ownership models.ReadingOwnership
if err := db.Where("reading_id = ? AND user_id = ?", readingID, userID).Take(&ownership).Error; err != nil {
writeOpaque500(w)
return
}
ownedAt := models.FormatDateTime(ownership.OwnedAt)
writeData(w, ownershipJSON{ReadingID: readingID, OwnedAt: &ownedAt})
}
// UnmarkOwned answers DELETE /readings/{id}/owned: it clears the caller's
// owned mark. Clearing a reading that is not owned is not an error.
func (h *Handlers) UnmarkOwned(w http.ResponseWriter, r *http.Request) {
userID, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
readingID, ok := readingFor(w, r, db)
if !ok {
return
}
if err := db.Where("reading_id = ? AND user_id = ?", readingID, userID).Delete(&models.ReadingOwnership{}).Error; err != nil {
writeOpaque500(w)
return
}
writeData(w, ownershipJSON{ReadingID: readingID})
}

140
controllers/api/schedule.go Normal file
View File

@@ -0,0 +1,140 @@
package api
import (
"net/http"
"time"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// validRange validates ?from=&to= and returns the decoded input.
func (h *Handlers) validRange(w http.ResponseWriter, r *http.Request) (map[string]any, bool) {
in := query(r, "from", "to")
rules := rangeRules
if str(in, "from") != "" {
rules = rangeRulesFrom
}
return in, h.validate(w, r, in, rules)
}
// bounds turns validated from and to dates into a half-open instant range:
// from midnight of from to midnight after to, in Europe/Warsaw. Without
// from the lower bound is lower; without to there is no upper bound.
func bounds(in map[string]any, lower time.Time) (time.Time, *time.Time) {
if from, ok := dayStart(in, "from"); ok {
lower = from
}
if to, ok := dayStart(in, "to"); ok {
upper := to.AddDate(0, 0, 1)
return lower, &upper
}
return lower, nil
}
// preloadSession queries the class sessions students see, with their course
// and meeting. A session without a course is still pending on an unsaved
// course form and is left out.
func preloadSession(q *gorm.DB) *gorm.DB {
return q.Preload("Course").Preload("Meeting").Where("jz_bm_class_sessions.course_id IS NOT NULL")
}
// Schedule answers GET /schedule?from=YYYY-MM-DD&to=YYYY-MM-DD: the class
// sessions starting in the range, by start time. from defaults to today.
func (h *Handlers) Schedule(w http.ResponseWriter, r *http.Request) {
if _, ok := h.caller(w, r); !ok {
return
}
in, ok := h.validRange(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
lower, upper := bounds(in, today(h.now()))
q := preloadSession(db).Where("starts_at >= ?", lower.UTC())
if upper != nil {
q = q.Where("starts_at < ?", upper.UTC())
}
var rows []models.ClassSession
if err := q.Order("starts_at, id").Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
writeData(w, newSessionsJSON(rows))
}
// Meetings answers GET /meetings: every zjazd by number, with its session
// count.
func (h *Handlers) Meetings(w http.ResponseWriter, r *http.Request) {
if _, ok := h.caller(w, r); !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
var rows []models.Meeting
if err := db.Order("number, id").Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
counts, err := countBy(db, "jz_bm_class_sessions", "meeting_id")
if err != nil {
writeOpaque500(w)
return
}
out := make([]meetingJSON, 0, len(rows))
for _, m := range rows {
out = append(out, newMeetingJSON(m, counts[m.ID]))
}
writeData(w, out)
}
// Deadlines answers GET /deadlines?from=&to=. Without from it lists the
// deadlines not yet due; from and to are calendar days in Europe/Warsaw.
func (h *Handlers) Deadlines(w http.ResponseWriter, r *http.Request) {
if _, ok := h.caller(w, r); !ok {
return
}
in, ok := h.validRange(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
lower, upper := bounds(in, h.now())
q := db.Preload("Course").Where("due_at >= ?", lower.UTC())
if upper != nil {
q = q.Where("due_at < ?", upper.UTC())
}
var rows []models.Deadline
if err := q.Order("due_at, id").Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
writeData(w, newDeadlinesJSON(rows))
}
// countBy counts the rows of table per value of a nullable foreign key
// column. table and column are constants of this package, never input.
func countBy(db *gorm.DB, table, column string) (map[uint]int64, error) {
var rows []struct {
Key uint
Count int64
}
err := db.Table(table).
Select(column + " AS key, COUNT(*) AS count").
Where(column + " IS NOT NULL").
Group(column).
Scan(&rows).Error
out := make(map[uint]int64, len(rows))
for _, row := range rows {
out[row.Key] = row.Count
}
return out, err
}

382
controllers/api/uploads.go Normal file
View File

@@ -0,0 +1,382 @@
package api
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/controllers"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// Material files over MCP (D-10, D-11, D-18): a small file goes in as base64
// in one tool call (AttachMaterialInline). Every path stores through
// storeMaterialFile, so attach.Store and the material's file cap apply.
// MaterialInlineMaxBytes is the largest decoded file of POST
// /materials/{id}/files/inline. pier refuses MCP request bodies over 4 MiB,
// and base64 grows a file by a third, so about 3 MB is what fits (D-18).
const MaterialInlineMaxBytes = 3_000_000
// MaterialInlineBodyLimit is the body cap of POST
// /materials/{id}/files/inline: the base64 of MaterialInlineMaxBytes plus
// the JSON around it.
const MaterialInlineBodyLimit = 4_300_000
// MaterialFileWarning is the sentence every material file tool and answer
// carries (D-11).
const MaterialFileWarning = "Files attached to a material are public to anyone with the link."
// inlineFile is the body of POST /materials/{id}/files/inline.
type inlineFile struct {
Name string `json:"name"`
Mime string `json:"mime"`
ContentBase64 string `json:"content_base64"`
}
// decodeInline reads and checks the body of POST /materials/{id}/files/inline.
// The encoded content is measured before it is decoded, so an oversized one
// costs no decoding.
func decodeInline(raw []byte) (name string, mime string, data []byte, errs map[string][]string) {
var in inlineFile
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
return "", "", nil, map[string][]string{"json": {"Send a JSON object with name, content_base64 and optionally mime: " + err.Error()}}
}
errs = map[string][]string{}
name = strings.TrimSpace(in.Name)
if name == "" || len(name) > 255 {
errs["name"] = []string{"The name is required (the file name with its extension) and may not be longer than 255 characters."}
}
mime = strings.ToLower(strings.TrimSpace(in.Mime))
if mime != "" && (len(mime) > 100 || !strings.Contains(mime, "/") || strings.ContainsAny(mime, " \t;,")) {
errs["mime"] = []string{"The mime must be one MIME type such as application/pdf."}
}
switch {
case in.ContentBase64 == "":
errs["content_base64"] = []string{"The content_base64 is required."}
case len(in.ContentBase64) > base64.StdEncoding.EncodedLen(MaterialInlineMaxBytes)+inlineSlack(in.ContentBase64):
errs["content_base64"] = []string{"The file is larger than " + strconv.Itoa(MaterialInlineMaxBytes) + " bytes: use bm_manage_create_material_upload for larger files."}
default:
b, err := base64.StdEncoding.DecodeString(in.ContentBase64)
switch {
case err != nil:
errs["content_base64"] = []string{"The content_base64 is not valid standard base64."}
case len(b) == 0:
errs["content_base64"] = []string{"The file is empty."}
case len(b) > MaterialInlineMaxBytes:
errs["content_base64"] = []string{"The file is larger than " + strconv.Itoa(MaterialInlineMaxBytes) + " bytes: use bm_manage_create_material_upload for larger files."}
default:
data = b
}
}
if len(errs) > 0 {
return "", "", nil, errs
}
return name, mime, data, nil
}
// inlineSlack is the number of line breaks in s, which the base64 decoder
// skips: wrapped base64 is accepted at the same decoded size.
func inlineSlack(s string) int {
return strings.Count(s, "\n") + strings.Count(s, "\r")
}
// AttachMaterialInline answers POST /materials/{id}/files/inline: one file
// sent as JSON {name, mime?, content_base64}, stored as a public file of the
// material through attach.Store, at most MaterialInlineMaxBytes decoded. A
// sent mime must match the stored content type. The answer is the material
// as GET /materials/{id} shows it, with the public-file warning, 201.
func (h *Handlers) AttachMaterialInline(w http.ResponseWriter, r *http.Request) {
raw, ok := body(w, r)
if !ok {
return
}
name, mime, data, errs := decodeInline(raw)
if errs != nil {
writeValidation(w, errs)
return
}
db, ok := h.db(w, r)
if !ok {
return
}
bucket, ok := h.bucket(w)
if !ok {
return
}
m, ok := findMaterial(w, r, db)
if !ok {
return
}
lim := attach.Limits{MaxBytes: MaterialInlineMaxBytes}
if mime != "" {
lim.MIMETypes = []string{mime}
}
var stored *attach.File
var refusal string
err := lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
f, why, err := storeMaterialFile(ctx, tx, bucket, m, name, bytes.NewReader(data), lim)
stored, refusal = f, why
if err == nil && why == "" && f != nil {
// The text job joins the transaction and syncs the material.
h.MaterialIndex.QueueExtract(ctx, tx, m.ID)
}
return err
})
if err != nil || refusal != "" {
// The blob is deleted again when the transaction did not commit.
if stored != nil {
_ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored))
}
if refusal != "" {
writeValidation(w, map[string][]string{"file": {refusal}})
return
}
writeOpaque500(w)
return
}
h.writeMaterialDetailWith(w, r, db, m.ID, http.StatusCreated, map[string]any{"warning": MaterialFileWarning})
}
// Signed one-time uploads (D-10, D-12, D-19): for anything larger, the
// agent asks for an upload URL (CreateMaterialUpload) and sends the file
// with curl, so the bytes never pass through MCP. The upload route
// (SignedMaterialUpload) has no bearer: the ticket in its path is the
// credential. It is bound to one material and one user, valid
// classes.UploadTTL and works once; the user and the permission are
// checked again when it is redeemed.
// UploadPath is the path of the signed upload route; a ticket follows it.
// The plugin mounts the route at APIPrefix + "/uploads/{ticket}", and
// TestRoutes pins the two together.
const UploadPath = "/_bm/api/v1/uploads/"
// uploadKind is the ticket kind of a material file upload.
const uploadKind = "material"
// materialUploadJSON is the answer of CreateMaterialUpload.
type materialUploadJSON struct {
UploadURL string `json:"upload_url"`
ExpiresAt string `json:"expires_at"`
MaxBytes int `json:"max_bytes"`
Accept string `json:"accept"`
CurlExample string `json:"curl_example"`
Warning string `json:"warning"`
}
// uploadedFileJSON is the file in the answer of SignedMaterialUpload.
type uploadedFileJSON struct {
ID uint `json:"id"`
Name string `json:"name"`
Size int64 `json:"size"`
Mime string `json:"mime"`
URL string `json:"url"`
}
// CreateMaterialUpload answers POST /materials/{id}/files/upload-url: a
// signed, single-use URL, valid classes.UploadTTL, for one file upload to
// this material by the caller, with a curl example. No URL is issued
// without app.key or a cache (503).
func (h *Handlers) CreateMaterialUpload(w http.ResponseWriter, r *http.Request) {
user, ok := h.caller(w, r)
if !ok {
return
}
db, ok := h.db(w, r)
if !ok {
return
}
m, ok := findMaterial(w, r, db)
if !ok {
return
}
key, cache := h.uploadKey(), h.uploadCache()
if len(key) == 0 || cache == nil {
wire.WriteJSON(w, http.StatusServiceUnavailable, map[string]any{"error": true, "message": "Uploads are not configured."})
return
}
ticket, expires, err := classes.IssueUpload(r.Context(), cache, key, uploadKind, m.ID, user, h.now())
if err != nil {
writeOpaque500(w)
return
}
url := h.appBase(r) + UploadPath + ticket
wire.WriteJSON(w, http.StatusCreated, map[string]any{"data": materialUploadJSON{
UploadURL: url,
ExpiresAt: expires.UTC().Format(time.RFC3339),
MaxBytes: MaterialFileMaxBytes,
Accept: strings.Join(attach.DefaultFileExtensions, ", "),
CurlExample: "curl -fsS -F 'file=@<path>' '" + url + "'",
Warning: MaterialFileWarning,
}})
}
// SignedMaterialUpload answers POST /_bm/api/v1/uploads/{ticket}. The
// ticket is redeemed first (once; any failure is the same 403 before the
// database), then the ticket's user must still exist and hold
// jz.bm.access_materials, and the material must still exist. The body is
// multipart with exactly one part, named file, stored through
// storeMaterialFile with the material file limits.
func (h *Handlers) SignedMaterialUpload(w http.ResponseWriter, r *http.Request) {
ticket, err := classes.RedeemUpload(r.Context(), h.uploadCache(), h.uploadKey(), r.PathValue("ticket"), h.now())
if err != nil || ticket.Kind != uploadKind {
writeUploadForbidden(w)
return
}
db, ok := h.db(w, r)
if !ok {
return
}
principal, err := userclasses.PrincipalByID(r.Context(), db, ticket.User)
if err != nil {
writeOpaque500(w)
return
}
if principal == nil || !cabana.Allows(principal, []string{controllers.PermMaterials}) {
writeUploadForbidden(w)
return
}
var m models.Material
res := db.Where("id = ?", ticket.Target).Limit(1).Find(&m)
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected == 0 {
writeNotFound(w)
return
}
bucket, ok := h.bucket(w)
if !ok {
return
}
mr, err := r.MultipartReader()
if err != nil {
writeValidation(w, map[string][]string{"file": {singleFilePart}})
return
}
var stored *attach.File
var refusal string
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
part, err := mr.NextPart()
if err != nil && err != io.EOF {
return err
}
if err == io.EOF || part.FormName() != "file" || part.FileName() == "" {
if part != nil {
part.Close()
}
refusal = singleFilePart
return errUploadRefused
}
f, why, err := storeMaterialFile(ctx, tx, bucket, m, part.FileName(), part, fileLimits)
part.Close()
stored = f
if err != nil {
return err
}
if why != "" {
refusal = why
return errUploadRefused
}
if next, err := mr.NextPart(); err != io.EOF {
if next != nil {
next.Close()
}
if err != nil {
return err
}
refusal = singleFilePart
return errUploadRefused
}
// The text job joins the transaction and syncs the material.
h.MaterialIndex.QueueExtract(ctx, tx, m.ID)
return nil
})
if err != nil {
// The blob is deleted again when the transaction did not commit.
if stored != nil {
_ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored))
}
var tooLarge *http.MaxBytesError
switch {
case refusal != "":
writeValidation(w, map[string][]string{"file": {refusal}})
case errors.As(err, &tooLarge):
wire.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": true, "message": "Request body too large."})
default:
writeOpaque500(w)
}
return
}
url := stored.URL()
if strings.HasPrefix(url, "/") && !strings.HasPrefix(url, "//") {
url = h.appBase(r) + url
}
wire.WriteJSON(w, http.StatusCreated, map[string]any{
"data": map[string]any{
"material_id": m.ID,
"file": uploadedFileJSON{ID: stored.ID, Name: stored.FileName, Size: stored.FileSize, Mime: stored.ContentType, URL: url},
},
"warning": MaterialFileWarning,
})
}
// singleFilePart is the refusal of a signed upload body that is not one
// multipart part named file.
const singleFilePart = "Send exactly one file as multipart/form-data in a part named \"file\", for example curl -F 'file=@<path>'."
// errUploadRefused rolls back a refused signed upload.
var errUploadRefused = errors.New("api: upload refused")
// writeUploadForbidden is the one answer of every refused upload ticket.
func writeUploadForbidden(w http.ResponseWriter) {
wire.WriteJSON(w, http.StatusForbidden, map[string]any{"error": true, "message": "Invalid or expired upload URL."})
}
func (h *Handlers) uploadKey() []byte {
if h.UploadKey == nil {
return nil
}
return h.UploadKey()
}
func (h *Handlers) uploadCache() cooler.Cache {
if h.Cache == nil {
return nil
}
return h.Cache()
}
// appBase is the base of the absolute links of the upload answers (D-16):
// app.url, else jz.bm.public_url, else the scheme (TLS or
// X-Forwarded-Proto) and Host of the request.
func (h *Handlers) appBase(r *http.Request) string {
for _, base := range []string{h.AppURL, h.PublicURL} {
if base = strings.TrimRight(strings.TrimSpace(base), "/"); base != "" {
return base
}
}
scheme := "http"
if r.TLS != nil || strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https") {
scheme = "https"
}
return scheme + "://" + r.Host
}

View File

@@ -0,0 +1,169 @@
package api_test
import (
"context"
"encoding/base64"
"net/http"
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"gorm.io/gorm"
)
// TestDecodeInline (D-11, D-18) checks the body of POST
// /materials/{id}/files/inline before any database work.
func TestDecodeInline(t *testing.T) {
pdf := []byte("%PDF-1.4\n%notatki\n")
enc := base64.StdEncoding.EncodeToString(pdf)
t.Run("valid", func(t *testing.T) {
name, mime, data, errs := api.DecodeInline([]byte(`{"name":" notatki.pdf ","mime":"Application/PDF","content_base64":"` + enc + `"}`))
if errs != nil {
t.Fatalf("errors %v", errs)
}
if name != "notatki.pdf" || mime != "application/pdf" || string(data) != string(pdf) {
t.Errorf("got %q %q %q", name, mime, data)
}
})
t.Run("mime optional", func(t *testing.T) {
_, mime, data, errs := api.DecodeInline([]byte(`{"name":"a.pdf","content_base64":"` + enc + `"}`))
if errs != nil || mime != "" || len(data) != len(pdf) {
t.Errorf("got mime %q, %d bytes, errors %v", mime, len(data), errs)
}
})
big := strings.Repeat("A", base64.StdEncoding.EncodedLen(api.MaterialInlineMaxBytes)+4)
cases := []struct {
name, body, field, contains string
}{
{"missing name", `{"content_base64":"` + enc + `"}`, "name", ""},
{"blank name", `{"name":" ","content_base64":"` + enc + `"}`, "name", ""},
{"empty content", `{"name":"a.pdf","content_base64":""}`, "content_base64", ""},
{"missing content", `{"name":"a.pdf"}`, "content_base64", ""},
{"invalid base64", `{"name":"a.pdf","content_base64":"%%%not base64"}`, "content_base64", "base64"},
{"url-safe alphabet", `{"name":"a.pdf","content_base64":"-_-_"}`, "content_base64", "base64"},
{"unknown key", `{"name":"a.pdf","content_base64":"` + enc + `","path":"/etc/passwd"}`, "json", ""},
{"not an object", `[1,2]`, "json", ""},
{"bad mime", `{"name":"a.pdf","mime":"pdf","content_base64":"` + enc + `"}`, "mime", ""},
{"too large", `{"name":"a.pdf","content_base64":"` + big + `"}`, "content_base64", "bm_manage_create_material_upload"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, _, data, errs := api.DecodeInline([]byte(tc.body))
if data != nil {
t.Errorf("data returned with an invalid body")
}
msgs := errs[tc.field]
if len(msgs) == 0 {
t.Fatalf("errors %v have no %s entry", errs, tc.field)
}
if tc.contains != "" && !strings.Contains(msgs[0], tc.contains) {
t.Errorf("%s message %q does not name %q", tc.field, msgs[0], tc.contains)
}
})
}
}
// TestAttachMaterialInlineNoDatabase: an invalid body is a 422 before the
// database is looked up; a valid one without a database is a 503.
func TestAttachMaterialInlineNoDatabase(t *testing.T) {
user := &bouncer.Principal{ID: 7}
enc := base64.StdEncoding.EncodeToString([]byte("%PDF-1.4\n"))
valid := bodyRequest{noDB().AttachMaterialInline, http.MethodPost, "/", `{"name":"a.pdf","content_base64":"` + enc + `"}`}
if code, body := serveBody(t, valid, user); code != http.StatusServiceUnavailable {
t.Errorf("valid body without a database = %d %v, want 503", code, body)
}
dbLooked := false
h := &api.Handlers{DB: func() *gorm.DB { dbLooked = true; return nil }}
invalid := bodyRequest{h.AttachMaterialInline, http.MethodPost, "/", `{"name":"","content_base64":""}`}
code, body := serveBody(t, invalid, user)
if code != http.StatusUnprocessableEntity {
t.Errorf("invalid body = %d %v, want 422", code, body)
}
if errs, _ := body["errors"].(map[string]any); errs["name"] == nil || errs["content_base64"] == nil {
t.Errorf("errors %v lack name and content_base64", body["errors"])
}
if dbLooked {
t.Error("the database was looked up for an invalid body")
}
}
// TestSignedMaterialUploadRefusesBadTickets (D-12): a malformed, forged,
// never issued, expired, wrong-kind or used ticket gets the same 403 before
// the database is looked up.
func TestSignedMaterialUploadRefusesBadTickets(t *testing.T) {
key := []byte("app-key")
cache, err := cooler.NewMemoryCache("test:", 100)
if err != nil {
t.Fatal(err)
}
dbLooked := false
h := &api.Handlers{
DB: func() *gorm.DB { dbLooked = true; return nil },
UploadKey: func() []byte { return key },
Cache: func() cooler.Cache { return cache },
}
now := time.Now()
forged, _, err := classes.IssueUpload(context.Background(), cache, []byte("other-key"), "material", 1, 7, now)
if err != nil {
t.Fatal(err)
}
unissued, err := classes.SignUpload(key, classes.UploadTicket{Kind: "material", Target: 1, User: 7, Expires: now.Add(time.Minute), Nonce: strings.Repeat("0f", 16)})
if err != nil {
t.Fatal(err)
}
expired, _, err := classes.IssueUpload(context.Background(), cache, key, "material", 1, 7, now.Add(-classes.UploadTTL-time.Second))
if err != nil {
t.Fatal(err)
}
deck, _, err := classes.IssueUpload(context.Background(), cache, key, "deck", 1, 7, now)
if err != nil {
t.Fatal(err)
}
refused := map[string]string{
"empty": "",
"garbage": "not-a-ticket",
"two parts": "abc.def",
"forged": forged,
"unissued": unissued,
"expired": expired,
"wrong kind": deck,
}
for name, ticket := range refused {
code, body := serve(t, h.SignedMaterialUpload, http.MethodPost, "/", nil, map[string]string{"ticket": ticket})
if code != http.StatusForbidden || body["error"] != true || body["message"] != "Invalid or expired upload URL." {
t.Errorf("%s: %d %v, want 403 Invalid or expired upload URL.", name, code, body)
}
}
if dbLooked {
t.Error("the database was looked up for a refused ticket")
}
valid, _, err := classes.IssueUpload(context.Background(), cache, key, "material", 1, 7, now)
if err != nil {
t.Fatal(err)
}
if code, body := serve(t, h.SignedMaterialUpload, http.MethodPost, "/", nil, map[string]string{"ticket": valid}); code != http.StatusServiceUnavailable {
t.Errorf("valid ticket without a database = %d %v, want 503", code, body)
}
if code, body := serve(t, h.SignedMaterialUpload, http.MethodPost, "/", nil, map[string]string{"ticket": valid}); code != http.StatusForbidden {
t.Errorf("used ticket = %d %v, want 403", code, body)
}
}
// TestCreateMaterialUploadNeedsCaller: no signed-in user is a 401; a caller
// without a database is a 503.
func TestCreateMaterialUploadNeedsCaller(t *testing.T) {
h := noDB()
if code, body := serve(t, h.CreateMaterialUpload, http.MethodPost, "/", nil, map[string]string{"id": "1"}); code != http.StatusUnauthorized || body["error"] != true {
t.Errorf("without a caller = %d %v, want 401", code, body)
}
if code, body := serve(t, h.CreateMaterialUpload, http.MethodPost, "/", &bouncer.Principal{ID: 7}, map[string]string{"id": "1"}); code != http.StatusServiceUnavailable {
t.Errorf("without a database = %d %v, want 503", code, body)
}
}

View File

@@ -0,0 +1,41 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = classSessionsAdmin{}
_ pact.AdminRecordSource = classSessionsAdmin{}
_ pact.AdminPermissioned = classSessionsAdmin{}
)
// classSessionsAdmin is the admin controller for class sessions (zajęcia).
type classSessionsAdmin struct{ temporalHooks }
func (classSessionsAdmin) ID() string { return "jz.bm.class_sessions" }
func (classSessionsAdmin) ModelName() string { return "ClassSession" }
func (classSessionsAdmin) ConfigDir() string { return "controllers/class_sessions" }
// NewRecord returns the model the generic admin handlers query and fill.
func (classSessionsAdmin) NewRecord() any { return &models.ClassSession{} }
// RequiredPermissions is checked before any schema or record is served.
func (classSessionsAdmin) RequiredPermissions() []string {
return []string{PermSchedule}
}
// AdminFieldRelations binds the course and meeting pickers.
func (classSessionsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{
courseRelation("course_id"),
meetingRelation(),
}
}
// ClassSessionsController returns the jz.bm.class_sessions admin controller.
func ClassSessionsController() pact.AdminController { return classSessionsAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.sessions.form
form: ~/plugins/jz/bm/models/class_sessions/fields.yaml
modelClass: ClassSession
defaultRedirect: jz/bm/class_sessions
create:
redirect: jz/bm/class_sessions/update/:id
redirectClose: jz/bm/class_sessions
update:
redirect: jz/bm/class_sessions
redirectClose: jz/bm/class_sessions

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/class_sessions/columns.yaml
modelClass: ClassSession
title: jz.bm::lang.sessions.title
recordUrl: jz/bm/class_sessions/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: starts_at
direction: asc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

75
controllers/courses.go Normal file
View File

@@ -0,0 +1,75 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
"context"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = coursesAdmin{}
_ pact.AdminRecordSource = coursesAdmin{}
_ pact.AdminPermissioned = coursesAdmin{}
_ cabana.AdminRelationContractProvider = coursesAdmin{}
_ pact.RelationBeforeCreate = coursesAdmin{}
_ pact.RelationBeforeUpdate = coursesAdmin{}
)
// coursesAdmin is the admin controller for courses (przedmioty).
type coursesAdmin struct{}
func (coursesAdmin) ID() string { return "jz.bm.courses" }
func (coursesAdmin) ModelName() string { return "Course" }
func (coursesAdmin) ConfigDir() string { return "controllers/courses" }
// NewRecord returns the model the generic admin handlers query and fill.
func (coursesAdmin) NewRecord() any { return &models.Course{} }
// RequiredPermissions is checked before any schema or record is served.
func (coursesAdmin) RequiredPermissions() []string {
return []string{PermCourses}
}
// AdminRelationContracts binds the course form's relation managers for its
// readings and class sessions. course_id is nullable, so both work on a
// course that is not saved yet.
func (coursesAdmin) AdminRelationContracts() []cabana.RelationContract {
return []cabana.RelationContract{
{
Name: "readings",
Kind: cabana.RelationHasMany,
NewRelated: func() any { return &models.Reading{} },
ForeignKey: "course_id",
Columns: map[string]string{
"title": "title", "author": "author", "is_required": "is_required", "sort_order": "sort_order",
},
},
{
Name: "sessions",
Kind: cabana.RelationHasMany,
NewRelated: func() any { return &models.ClassSession{} },
ForeignKey: "course_id",
Columns: map[string]string{
"starts_at": "starts_at", "ends_at": "ends_at", "room": "room", "kind": "kind",
},
},
}
}
// RelationBeforeCreate and RelationBeforeUpdate check that a class session
// ends after it starts, as the class sessions screen does.
func (coursesAdmin) RelationBeforeCreate(_ context.Context, _ string, _, child any) error {
return checkTemporal(child)
}
func (coursesAdmin) RelationBeforeUpdate(_ context.Context, _ string, _, child any) error {
return checkTemporal(child)
}
// CoursesController returns the jz.bm.courses admin controller.
func CoursesController() pact.AdminController { return coursesAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.courses.form
form: ~/plugins/jz/bm/models/courses/fields.yaml
modelClass: Course
defaultRedirect: jz/bm/courses
create:
redirect: jz/bm/courses/update/:id
redirectClose: jz/bm/courses
update:
redirect: jz/bm/courses
redirectClose: jz/bm/courses

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/courses/columns.yaml
modelClass: Course
title: jz.bm::lang.courses.title
recordUrl: jz/bm/courses/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: sort_order
direction: asc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

View File

@@ -0,0 +1,46 @@
# Readings and class sessions are created, edited and deleted from the
# course form, also before the course is first saved (course_id is
# nullable). There is no link or unlink: a row without a course is only
# ever one pending on an unsaved form.
readings:
label: jz.bm::lang.courses.readings
view:
list:
columns:
title:
label: jz.bm::lang.common.title
searchable: true
author:
label: jz.bm::lang.readings.author
is_required:
label: jz.bm::lang.readings.is_required
sort_order:
label: jz.bm::lang.common.sort_order
toolbarButtons: create|update|delete
showSearch: true
manage:
form: ~/plugins/jz/bm/models/readings/fields_course.yaml
list:
columns:
title:
label: jz.bm::lang.common.title
sessions:
label: jz.bm::lang.courses.sessions
view:
list:
columns:
starts_at:
label: jz.bm::lang.sessions.starts_at
ends_at:
label: jz.bm::lang.sessions.ends_at
room:
label: jz.bm::lang.sessions.room
kind:
label: jz.bm::lang.sessions.kind
toolbarButtons: create|update|delete
manage:
form: ~/plugins/jz/bm/models/class_sessions/fields_course.yaml
list:
columns:
starts_at:
label: jz.bm::lang.sessions.starts_at

38
controllers/deadlines.go Normal file
View File

@@ -0,0 +1,38 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = deadlinesAdmin{}
_ pact.AdminRecordSource = deadlinesAdmin{}
_ pact.AdminPermissioned = deadlinesAdmin{}
)
// deadlinesAdmin is the admin controller for deadlines (terminarz).
type deadlinesAdmin struct{ temporalHooks }
func (deadlinesAdmin) ID() string { return "jz.bm.deadlines" }
func (deadlinesAdmin) ModelName() string { return "Deadline" }
func (deadlinesAdmin) ConfigDir() string { return "controllers/deadlines" }
// NewRecord returns the model the generic admin handlers query and fill.
func (deadlinesAdmin) NewRecord() any { return &models.Deadline{} }
// RequiredPermissions is checked before any schema or record is served.
func (deadlinesAdmin) RequiredPermissions() []string {
return []string{PermSchedule}
}
// AdminFieldRelations binds the course picker.
func (deadlinesAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{courseRelation("course_id")}
}
// DeadlinesController returns the jz.bm.deadlines admin controller.
func DeadlinesController() pact.AdminController { return deadlinesAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.deadlines.form
form: ~/plugins/jz/bm/models/deadlines/fields.yaml
modelClass: Deadline
defaultRedirect: jz/bm/deadlines
create:
redirect: jz/bm/deadlines/update/:id
redirectClose: jz/bm/deadlines
update:
redirect: jz/bm/deadlines
redirectClose: jz/bm/deadlines

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/deadlines/columns.yaml
modelClass: Deadline
title: jz.bm::lang.deadlines.title
recordUrl: jz/bm/deadlines/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: due_at
direction: asc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

67
controllers/hooks.go Normal file
View File

@@ -0,0 +1,67 @@
package controllers
import (
"context"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// Permission codes of the plugin's admin screens.
const (
PermCourses = "jz.bm.access_courses"
PermSchedule = "jz.bm.access_schedule"
PermMaterials = "jz.bm.access_materials"
)
// temporalHooks checks the order of a model's dates before every admin save
// and answers a bad value as a 422 on its field. lagoon.Validate cannot
// compare two fields, so the model checks them itself
// (models.TemporalValidator).
type temporalHooks struct{}
func (temporalHooks) FormBeforeCreate(_ context.Context, model any) error {
return checkTemporal(model)
}
func (temporalHooks) FormBeforeUpdate(_ context.Context, model any) error {
return checkTemporal(model)
}
func checkTemporal(model any) error {
v, ok := model.(models.TemporalValidator)
if !ok {
return nil
}
msgs := v.TemporalErrors()
if len(msgs) == 0 {
return nil
}
details := make(map[string]any, len(msgs))
for field, m := range msgs {
details[field] = m
}
return &cabana.ValidationError{Details: details}
}
// courseRelation is the belongsTo picker of a course_id column.
func courseRelation(foreignKey string) cabana.FieldRelationContract {
return cabana.FieldRelationContract{
Field: "course",
Kind: "belongsTo",
NewRelated: func() any { return &models.Course{} },
ForeignKey: foreignKey,
LabelColumn: "name",
}
}
// meetingRelation is the belongsTo picker of a meeting_id column (zjazd).
func meetingRelation() cabana.FieldRelationContract {
return cabana.FieldRelationContract{
Field: "meeting",
Kind: "belongsTo",
NewRelated: func() any { return &models.Meeting{} },
ForeignKey: "meeting_id",
LabelColumn: "number",
}
}

71
controllers/materials.go Normal file
View File

@@ -0,0 +1,71 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = materialsAdmin{}
_ pact.AdminRecordSource = materialsAdmin{}
_ pact.AdminPermissioned = materialsAdmin{}
)
// materialsAdmin is the admin controller for materials.
type materialsAdmin struct{ temporalHooks }
func (materialsAdmin) ID() string { return "jz.bm.materials" }
func (materialsAdmin) ModelName() string { return "Material" }
func (materialsAdmin) ConfigDir() string { return "controllers/materials" }
// NewRecord returns the model the generic admin handlers query and fill.
func (materialsAdmin) NewRecord() any { return &models.Material{} }
// RequiredPermissions is checked before any schema or record is served.
func (materialsAdmin) RequiredPermissions() []string {
return []string{PermMaterials}
}
// AdminFieldRelations binds the course and meeting pickers, the tags, the
// author picker and the users a private material is shared with. The
// author column is author_user_id, not user_id, which the backend refuses
// to fill from a body. The files field is bound by
// models.Material.AttachRelations.
func (materialsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{
courseRelation("course_id"),
meetingRelation(),
{
Field: "tags",
Kind: "belongsToMany",
NewRelated: func() any { return &models.Tag{} },
NewPivot: func() any { return &models.MaterialTag{} },
ParentForeignKey: "material_id",
RelatedForeignKey: "tag_id",
LabelColumn: "name",
},
{
Field: "author",
Kind: "belongsTo",
NewRelated: func() any { return &usermodels.User{} },
ForeignKey: "author_user_id",
LabelColumn: "email",
},
{
Field: "shared_with",
Kind: "belongsToMany",
NewRelated: func() any { return &usermodels.User{} },
NewPivot: func() any { return &models.MaterialShare{} },
ParentForeignKey: "material_id",
RelatedForeignKey: "user_id",
LabelColumn: "email",
},
}
}
// MaterialsController returns the jz.bm.materials admin controller.
func MaterialsController() pact.AdminController { return materialsAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.materials.form
form: ~/plugins/jz/bm/models/materials/fields.yaml
modelClass: Material
defaultRedirect: jz/bm/materials
create:
redirect: jz/bm/materials/update/:id
redirectClose: jz/bm/materials
update:
redirect: jz/bm/materials
redirectClose: jz/bm/materials

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/materials/columns.yaml
modelClass: Material
title: jz.bm::lang.materials.title
recordUrl: jz/bm/materials/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: created_at
direction: desc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

View File

@@ -0,0 +1,166 @@
package controllers
import (
"context"
"errors"
"sync"
"sync/atomic"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
var (
_ pact.FormBeforeUpdate = materialsAdmin{}
_ pact.FormAfterCreate = materialsAdmin{}
_ pact.FormAfterUpdate = materialsAdmin{}
_ pact.FormAfterDelete = materialsAdmin{}
)
// pendingRevisions holds, per material id, the content fingerprint
// (models.MaterialContent) FormBeforeUpdate took before an admin save, for
// FormAfterUpdate to compare. The row lock FormBeforeUpdate takes keeps one
// pending save per id at a time.
var pendingRevisions sync.Map
// MaterialIndex keeps the materials search index current once a write
// commits (classes.MaterialIndexer). QueueExtract enqueues the file text job
// inside tx. Its calls never fail the write.
type MaterialIndex interface {
SyncAfterCommit(ctx context.Context, tx *gorm.DB, id uint)
RemoveAfterCommit(ctx context.Context, tx *gorm.DB, id uint)
QueueExtract(ctx context.Context, tx *gorm.DB, id uint)
}
type materialIndexHolder struct{ ix MaterialIndex }
var materialIndex atomic.Value
// UseMaterialIndex installs the index the materials admin syncs after a
// save or delete; nil turns the syncs off. Boot installs it, because the
// generated controller value has no field to carry it.
func UseMaterialIndex(ix MaterialIndex) {
materialIndex.Store(materialIndexHolder{ix: ix})
}
func installedMaterialIndex() MaterialIndex {
h, _ := materialIndex.Load().(materialIndexHolder)
return h.ix
}
// MaterialRevisionNotifier publishes the live heads-up after an admin save
// bumped a material's revision (classes.MaterialRevisionNotifier). It
// enqueues on tx and never fails the save.
type MaterialRevisionNotifier interface {
Revised(ctx context.Context, tx *gorm.DB, id, revision uint)
}
type materialRevisionNotifierHolder struct{ n MaterialRevisionNotifier }
var materialRevisionNotifier atomic.Value
// UseMaterialRevisionNotifier installs the notifier the materials admin
// calls after a save bumped the revision; nil turns it off. Boot installs
// it, as UseMaterialIndex.
func UseMaterialRevisionNotifier(n MaterialRevisionNotifier) {
materialRevisionNotifier.Store(materialRevisionNotifierHolder{n: n})
}
func installedMaterialRevisionNotifier() MaterialRevisionNotifier {
h, _ := materialRevisionNotifier.Load().(materialRevisionNotifierHolder)
return h.n
}
// FormAfterCreate queues the file text job in the save transaction (the
// form's deferred files commit in the same one) and syncs the new material
// once it commits.
func (materialsAdmin) FormAfterCreate(ctx context.Context, model any) error {
return materialAfterCommit(ctx, model, false)
}
// FormBeforeUpdate runs the embedded date check, then, inside the save
// transaction, locks the material's row and snapshots its content for
// FormAfterUpdate. An admin save is not revision-checked (the form sends no
// revision); it only bumps the revision when the content changed, so a later
// push holding an older revision is refused instead of overwriting the
// admin edit. Outside a write (no transaction) it does nothing more.
func (c materialsAdmin) FormBeforeUpdate(ctx context.Context, model any) error {
if err := c.temporalHooks.FormBeforeUpdate(ctx, model); err != nil {
return err
}
m, ok := model.(*models.Material)
if !ok || m == nil {
return errors.New("materials admin: form model is not a material")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok || m.ID == 0 {
return nil
}
var locked int
if err := tx.Session(&gorm.Session{NewDB: true}).Raw("SELECT 1 FROM jz_bm_materials WHERE id = ? FOR UPDATE", m.ID).Scan(&locked).Error; err != nil {
return err
}
before, err := models.MaterialContent(tx, m.ID)
if err != nil {
return err
}
pendingRevisions.Store(m.ID, before)
return nil
}
// FormAfterUpdate bumps the revision when the save changed the material's
// content, and then enqueues the live heads-up on the save transaction
// (D-20), then queues the file text job in the save transaction and syncs
// the material once it commits. The compare runs here, not in
// FormBeforeUpdate, because the course, the zjazd and the tags are final
// only after the row write and the pivot sync. A revise error fails the save
// like any database error. A save that added no file queues a job that finds
// no new PDF and only resyncs; a file removed in the form leaves the
// document through the cascade and this sync.
func (materialsAdmin) FormAfterUpdate(ctx context.Context, model any) error {
m, ok := model.(*models.Material)
if !ok || m == nil {
return errors.New("materials admin: form model is not a material")
}
if pending, found := pendingRevisions.LoadAndDelete(m.ID); found {
if tx, ok := cabana.TxFromContext(ctx); ok {
rev, bumped, err := models.ReviseMaterial(tx, m.ID, pending.(string))
if err != nil {
return err
}
if n := installedMaterialRevisionNotifier(); bumped && n != nil {
n.Revised(ctx, tx, m.ID, rev)
}
}
}
return materialAfterCommit(ctx, model, false)
}
// FormAfterDelete removes the material's document once the delete commits.
func (materialsAdmin) FormAfterDelete(ctx context.Context, model any) error {
return materialAfterCommit(ctx, model, true)
}
// materialAfterCommit schedules the index work of an admin save on the save
// transaction. Only a model that is not a material is an error: the index
// never fails a save.
func materialAfterCommit(ctx context.Context, model any, remove bool) error {
m, ok := model.(*models.Material)
if !ok || m == nil {
return errors.New("materials admin: form model is not a material")
}
ix := installedMaterialIndex()
if ix == nil || m.ID == 0 {
return nil
}
tx, _ := cabana.TxFromContext(ctx)
if remove {
ix.RemoveAfterCommit(ctx, tx, m.ID)
return nil
}
ix.QueueExtract(ctx, tx, m.ID)
ix.SyncAfterCommit(ctx, tx, m.ID)
return nil
}

View File

@@ -0,0 +1,155 @@
package controllers
import (
"context"
"errors"
"slices"
"strconv"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// recordingIndex records the after-commit calls of the materials admin.
type recordingIndex struct {
calls []string
txs []*gorm.DB
}
func (r *recordingIndex) SyncAfterCommit(_ context.Context, tx *gorm.DB, id uint) {
r.calls = append(r.calls, "sync "+itoa(id))
r.txs = append(r.txs, tx)
}
func (r *recordingIndex) RemoveAfterCommit(_ context.Context, tx *gorm.DB, id uint) {
r.calls = append(r.calls, "remove "+itoa(id))
r.txs = append(r.txs, tx)
}
func (r *recordingIndex) QueueExtract(_ context.Context, tx *gorm.DB, id uint) {
r.calls = append(r.calls, "queue "+itoa(id))
r.txs = append(r.txs, tx)
}
func itoa(id uint) string { return strconv.FormatUint(uint64(id), 10) }
// recordingNotifier records the live revision events of the materials
// admin.
type recordingNotifier struct{ calls []string }
func (r *recordingNotifier) Revised(_ context.Context, _ *gorm.DB, id, revision uint) {
r.calls = append(r.calls, itoa(id)+"@"+itoa(revision))
}
func TestMaterialsAdminHooks(t *testing.T) {
t.Cleanup(func() { UseMaterialIndex(nil) })
var c materialsAdmin
ctx := context.Background()
m := &models.Material{ID: 7}
// No index installed: nothing to do, and no error.
UseMaterialIndex(nil)
for name, fn := range map[string]func(context.Context, any) error{"create": c.FormAfterCreate, "update": c.FormAfterUpdate, "delete": c.FormAfterDelete} {
if err := fn(ctx, m); err != nil {
t.Errorf("%s without an index: %v", name, err)
}
}
rec := &recordingIndex{}
UseMaterialIndex(rec)
if err := c.FormAfterCreate(ctx, m); err != nil {
t.Fatal(err)
}
if err := c.FormAfterUpdate(ctx, m); err != nil {
t.Fatal(err)
}
if err := c.FormAfterDelete(ctx, m); err != nil {
t.Fatal(err)
}
// Create and update queue the file text job (in the save transaction)
// before the after-commit sync; delete queues nothing.
if want := []string{"queue 7", "sync 7", "queue 7", "sync 7", "remove 7"}; !slices.Equal(rec.calls, want) {
t.Errorf("calls = %v, want %v", rec.calls, want)
}
// Outside a cabana write there is no transaction: the index then runs
// at once (lagoon.AfterCommit with a nil handle).
for i, tx := range rec.txs {
if tx != nil {
t.Errorf("call %d got a transaction outside a write", i)
}
}
// A model of another type is an error and schedules nothing.
rec.calls = nil
for name, fn := range map[string]func(context.Context, any) error{"create": c.FormAfterCreate, "update": c.FormAfterUpdate, "delete": c.FormAfterDelete} {
if err := fn(ctx, &models.Course{ID: 7}); err == nil {
t.Errorf("%s with a course: no error", name)
}
}
var nilMaterial *models.Material
if err := c.FormAfterUpdate(ctx, nilMaterial); err == nil {
t.Error("update with a nil material: no error")
}
if len(rec.calls) != 0 {
t.Errorf("calls for a wrong model = %v", rec.calls)
}
}
// TestMaterialsAdminRevision checks the revision hooks of the materials
// admin outside a database write: without a transaction they do nothing and
// store no snapshot, a model that is not a material is an error, and the
// embedded date check still runs first.
func TestMaterialsAdminRevision(t *testing.T) {
t.Cleanup(func() {
UseMaterialIndex(nil)
UseMaterialRevisionNotifier(nil)
})
UseMaterialIndex(nil)
notifier := &recordingNotifier{}
UseMaterialRevisionNotifier(notifier)
var c materialsAdmin
ctx := context.Background()
m := &models.Material{ID: 41, Title: "Notatka", Type: "notatka"}
if err := c.FormBeforeUpdate(ctx, m); err != nil {
t.Errorf("before update without a transaction: %v", err)
}
if _, found := pendingRevisions.Load(m.ID); found {
t.Error("before update without a transaction stored a snapshot")
}
if err := c.FormAfterUpdate(ctx, m); err != nil {
t.Errorf("after update without a transaction: %v", err)
}
// Outside a write nothing is revised, so nothing is announced.
if len(notifier.calls) != 0 {
t.Errorf("notifier called outside a transaction: %v", notifier.calls)
}
// Turning the notifier off is safe.
UseMaterialRevisionNotifier(nil)
if n := installedMaterialRevisionNotifier(); n != nil {
t.Errorf("notifier after UseMaterialRevisionNotifier(nil) = %v, want nil", n)
}
if err := c.FormAfterUpdate(ctx, m); err != nil {
t.Errorf("after update without a notifier: %v", err)
}
if err := c.FormBeforeUpdate(ctx, &models.Course{ID: 41}); err == nil {
t.Error("before update with a course: no error")
}
var nilMaterial *models.Material
if err := c.FormBeforeUpdate(ctx, nilMaterial); err == nil {
t.Error("before update with a nil material: no error")
}
at := func(h, m int) time.Time { return time.Date(2026, 10, 3, h, m, 0, 0, models.Location) }
bad := &models.ClassSession{StartsAt: at(8, 0), EndsAt: at(7, 0)}
var ve *cabana.ValidationError
if err := c.FormBeforeUpdate(ctx, bad); !errors.As(err, &ve) {
t.Errorf("before update with bad dates: err = %v, want a cabana.ValidationError", err)
} else if _, ok := ve.Details["ends_at"]; !ok {
t.Errorf("before update with bad dates: details %v name no ends_at", ve.Details)
}
}

32
controllers/meetings.go Normal file
View File

@@ -0,0 +1,32 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = meetingsAdmin{}
_ pact.AdminRecordSource = meetingsAdmin{}
_ pact.AdminPermissioned = meetingsAdmin{}
)
// meetingsAdmin is the admin controller for meetings (zjazdy).
type meetingsAdmin struct{ temporalHooks }
func (meetingsAdmin) ID() string { return "jz.bm.meetings" }
func (meetingsAdmin) ModelName() string { return "Meeting" }
func (meetingsAdmin) ConfigDir() string { return "controllers/meetings" }
// NewRecord returns the model the generic admin handlers query and fill.
func (meetingsAdmin) NewRecord() any { return &models.Meeting{} }
// RequiredPermissions is checked before any schema or record is served.
func (meetingsAdmin) RequiredPermissions() []string {
return []string{PermSchedule}
}
// MeetingsController returns the jz.bm.meetings admin controller.
func MeetingsController() pact.AdminController { return meetingsAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.meetings.form
form: ~/plugins/jz/bm/models/meetings/fields.yaml
modelClass: Meeting
defaultRedirect: jz/bm/meetings
create:
redirect: jz/bm/meetings/update/:id
redirectClose: jz/bm/meetings
update:
redirect: jz/bm/meetings
redirectClose: jz/bm/meetings

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/meetings/columns.yaml
modelClass: Meeting
title: jz.bm::lang.meetings.title
recordUrl: jz/bm/meetings/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: number
direction: asc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

38
controllers/readings.go Normal file
View File

@@ -0,0 +1,38 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = readingsAdmin{}
_ pact.AdminRecordSource = readingsAdmin{}
_ pact.AdminPermissioned = readingsAdmin{}
)
// readingsAdmin is the admin controller for readings (lektury).
type readingsAdmin struct{}
func (readingsAdmin) ID() string { return "jz.bm.readings" }
func (readingsAdmin) ModelName() string { return "Reading" }
func (readingsAdmin) ConfigDir() string { return "controllers/readings" }
// NewRecord returns the model the generic admin handlers query and fill.
func (readingsAdmin) NewRecord() any { return &models.Reading{} }
// RequiredPermissions is checked before any schema or record is served.
func (readingsAdmin) RequiredPermissions() []string {
return []string{PermCourses}
}
// AdminFieldRelations binds the course and meeting pickers.
func (readingsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{courseRelation("course_id"), meetingRelation()}
}
// ReadingsController returns the jz.bm.readings admin controller.
func ReadingsController() pact.AdminController { return readingsAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.readings.form
form: ~/plugins/jz/bm/models/readings/fields.yaml
modelClass: Reading
defaultRedirect: jz/bm/readings
create:
redirect: jz/bm/readings/update/:id
redirectClose: jz/bm/readings
update:
redirect: jz/bm/readings
redirectClose: jz/bm/readings

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/readings/columns.yaml
modelClass: Reading
title: jz.bm::lang.readings.title
recordUrl: jz/bm/readings/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: sort_order
direction: asc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

32
controllers/tags.go Normal file
View File

@@ -0,0 +1,32 @@
// Code generated by summer make. DO NOT EDIT.
package controllers
import (
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
var (
_ pact.AdminController = tagsAdmin{}
_ pact.AdminRecordSource = tagsAdmin{}
_ pact.AdminPermissioned = tagsAdmin{}
)
// tagsAdmin is the admin controller for material tags.
type tagsAdmin struct{}
func (tagsAdmin) ID() string { return "jz.bm.tags" }
func (tagsAdmin) ModelName() string { return "Tag" }
func (tagsAdmin) ConfigDir() string { return "controllers/tags" }
// NewRecord returns the model the generic admin handlers query and fill.
func (tagsAdmin) NewRecord() any { return &models.Tag{} }
// RequiredPermissions is checked before any schema or record is served.
func (tagsAdmin) RequiredPermissions() []string {
return []string{PermMaterials}
}
// TagsController returns the jz.bm.tags admin controller.
func TagsController() pact.AdminController { return tagsAdmin{} }

View File

@@ -0,0 +1,12 @@
name: jz.bm::lang.tags.form
form: ~/plugins/jz/bm/models/tags/fields.yaml
modelClass: Tag
defaultRedirect: jz/bm/tags
create:
redirect: jz/bm/tags/update/:id
redirectClose: jz/bm/tags
update:
redirect: jz/bm/tags
redirectClose: jz/bm/tags

View File

@@ -0,0 +1,15 @@
list: ~/plugins/jz/bm/models/tags/columns.yaml
modelClass: Tag
title: jz.bm::lang.tags.title
recordUrl: jz/bm/tags/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 50
perPageOptions: [20, 50, 100]
showCheckboxes: true
defaultSort:
column: name
direction: asc
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt

154
go.mod
View File

@@ -2,39 +2,185 @@ module git.golem15.com/jakub/sm-bm-plugin
go 1.27.0 go 1.27.0
toolchain go1.27.0
require ( require (
git.golem15.com/golem15/summercms v0.0.0 git.golem15.com/golem15/sm-chat-plugin v0.1.3
git.golem15.com/golem15/sm-chatchannels-plugin v0.0.0
git.golem15.com/golem15/sm-user-plugin v0.1.2
git.golem15.com/golem15/summercms v0.6.4
github.com/go-gormigrate/gormigrate/v2 v2.1.7 github.com/go-gormigrate/gormigrate/v2 v2.1.7
github.com/jackc/pgx/v5 v5.10.0
github.com/testcontainers/testcontainers-go v0.44.0
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
gocloud.dev v0.46.0
gorm.io/driver/postgres v1.6.3
gorm.io/gorm v1.31.2
) )
require ( require (
charm.land/bubbles/v2 v2.2.1 // indirect
charm.land/bubbletea/v2 v2.1.0 // indirect
charm.land/huh/v2 v2.0.3 // indirect
charm.land/lipgloss/v2 v2.0.6 // indirect
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aws/aws-sdk-go-v2 v1.41.9 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.20 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 // indirect
github.com/aws/smithy-go v1.26.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/catppuccin/go v0.2.0 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/harmonica v0.2.0 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
github.com/charmbracelet/x/ansi v0.11.9 // indirect
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.1 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.4 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect github.com/goccy/go-yaml v1.19.2 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/google/wire v0.7.0 // indirect
github.com/googleapis/gax-go/v2 v2.19.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.18.6 // indirect
github.com/knadh/koanf/maps v0.1.2 // indirect github.com/knadh/koanf/maps v0.1.2 // indirect
github.com/knadh/koanf/parsers/yaml v1.1.1 // indirect github.com/knadh/koanf/parsers/yaml v1.1.1 // indirect
github.com/knadh/koanf/providers/confmap v1.0.1 // indirect github.com/knadh/koanf/providers/confmap v1.0.1 // indirect
github.com/knadh/koanf/providers/env/v2 v2.0.1 // indirect github.com/knadh/koanf/providers/env/v2 v2.0.1 // indirect
github.com/knadh/koanf/providers/file v1.2.1 // indirect github.com/knadh/koanf/providers/file v1.2.1 // indirect
github.com/knadh/koanf/v2 v2.3.6 // indirect github.com/knadh/koanf/v2 v2.3.6 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/lib/pq v1.12.3 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/mattn/go-runewidth v0.0.30 // indirect
github.com/maypok86/otter/v2 v2.3.0 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect
github.com/moby/moby/api v1.55.0 // indirect
github.com/moby/moby/client v0.5.0 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/modelcontextprotocol/go-sdk v1.8.0 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/redis/go-redis/v9 v9.23.0 // indirect
github.com/riverqueue/river v0.47.0 // indirect
github.com/riverqueue/river/riverdriver v0.47.0 // indirect
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0 // indirect
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0 // indirect
github.com/riverqueue/river/rivershared v0.47.0 // indirect
github.com/riverqueue/river/rivertype v0.47.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/spf13/cobra v1.10.2 // indirect github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.9 // indirect github.com/spf13/pflag v1.0.9 // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/tidwall/gjson v1.19.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/wneessen/go-mail v0.8.1 // indirect github.com/wneessen/go-mail v0.8.1 // indirect
github.com/xo/terminfo v1.0.0 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yuin/goldmark v1.8.6 // indirect github.com/yuin/goldmark v1.8.6 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.57.0 // indirect golang.org/x/crypto v0.57.0 // indirect
golang.org/x/image v0.46.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect golang.org/x/sys v0.48.0 // indirect
golang.org/x/term v0.46.0 // indirect golang.org/x/term v0.46.0 // indirect
golang.org/x/text v0.42.0 // indirect golang.org/x/text v0.42.0 // indirect
gorm.io/gorm v1.31.2 // indirect golang.org/x/time v0.15.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.272.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
google.golang.org/grpc v1.79.3 // indirect
google.golang.org/protobuf v1.36.11 // indirect
) )
replace git.golem15.com/golem15/summercms => ../../../../summercms.go replace git.golem15.com/golem15/summercms => ../../../../summercms.go
replace git.golem15.com/golem15/sm-user-plugin => ../../golem15/user
replace git.golem15.com/golem15/sm-chat-plugin => ../../golem15/chat
replace git.golem15.com/golem15/sm-chatchannels-plugin => ../../golem15/chatchannels

312
go.sum
View File

@@ -1,15 +1,133 @@
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM=
cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc=
cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU=
cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE=
cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI=
cloud.google.com/go/storage v1.61.3 h1:VS//ZfBuPGDvakfD9xyPW1RGF1Vy3BWUoVZXgW1KMOg=
cloud.google.com/go/storage v1.61.3/go.mod h1:JtqK8BBB7TWv0HVGHubtUdzYYrakOQIsMLffZ2Z/HWk=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 h1:UnDZ/zFfG1JhH/DqxIZYU/1CUAlTUScoXD/LcM2Ykk8=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 h1:0s6TxfCu2KHkkZPnBfsQ2y5qia0jl3MMrmBhu3nCOYk=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/alicebob/miniredis/v2 v2.40.0 h1:6IgTQbvm2JiMYZ8yur/acNJzVjtSOWCelxXbk/LUBXc=
github.com/alicebob/miniredis/v2 v2.40.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
github.com/aws/aws-sdk-go-v2 v1.41.9/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
github.com/aws/aws-sdk-go-v2/config v1.32.20 h1:8VMDnWc/kEzxsI/1ngGM9mG81a8IGmIHD8KLcYGwagc=
github.com/aws/aws-sdk-go-v2/config v1.32.20/go.mod h1:PuwEpciweIXGULWeOeSTXtSbH4CW9mWdWrhdCKQI1sM=
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 h1:yuFzSV1U0aRNYCQGVaTY2zW2M/L93pYHnXnrJUphYhU=
github.com/aws/aws-sdk-go-v2/credentials v1.19.19/go.mod h1:7y63L1kGzeoDlJaQ3Z578KrnmfBut96JjvJUzGwR+YE=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25 h1:0w6dCiO8iez+YKwRhRBlL1CH/E3GTfdkuzrwj1by8vo=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25/go.mod h1:9FDWUothyr5RCRAHc45XOiVCzUR8n/IhCYX+uVqw6vk=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 h1:Uii3frf9ztec/ABM2/FSH9/z7PLzxfpG8h4RpkUFflQ=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25/go.mod h1:G6kntsA2GorAxDPbap6xgB2F+amSLUF8GJTi7PUoX44=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 h1:r1+/l6m+WaUJF9HISEsNOLHSNj5EXYQxK8VX6Cz9NlA=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25/go.mod h1:cKf+D+NMDK1LndD7BowHbBZPgR9V0/5HubH0PFWvA+c=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 h1:A1PmWU2zfkIm9EyFlJncFXL4W4phML+h8KjltUsCvNQ=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26/go.mod h1:dY4MRzXEizrD4hqtpKvWVGPX7QleSGGVY+EBolo1RmM=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 h1:dD3dhHNglpd98gs72my22Ndqi1hqQGllFFg1F+twfxg=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25/go.mod h1:0yAbjPfd64gG7mj85RW+fMEYdfBgCRZw8g/oWcL1pjc=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1 h1:1VwbP3qMNfxUDEXWki4rCE5iA+44VA1lokTz9HasGzw=
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1/go.mod h1:vUtyoSj0OPji3kjIVSc/GlKuWEiL33f/WFxl6dmpy/A=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19 h1:N6pIsdFOW1Kd9S4KyFKXdGRBojPPxkP32+uHFWLv4Hc=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19/go.mod h1:3gt5WJArFooNmyLONS+h/R4J+o86II8du38IgCwj9dE=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2 h1:hc+lBYiiTr8Zk4MTzIsQ92MeDWCIDvWGmzKUWOaBcOg=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2/go.mod h1:hU6fqB3OJA6/ePheD47LQnxvjYk6br6PtQxs+Q9ojvk=
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 h1:ErklX/7uhSbkAAeyQD/Y1OoQ9hO3SJXQNEgksORW3Js=
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3/go.mod h1:ULe4HCzfKPiR6R3HEurE3b1upEkuk8AkMrOKtaOxKO8=
github.com/aws/smithy-go v1.26.0 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/catppuccin/go v0.2.0 h1:ktBeIrIP42b/8FGiScP9sgrWOss3lw0Z5SktRoithGA=
github.com/catppuccin/go v0.2.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4jxsAuEs=
github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=
github.com/charmbracelet/x/exp/ordered v0.1.0/go.mod h1:5UHwmG+is5THxMyCJHNPCn2/ecI07aKNrW+LcResjJ8=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/charmbracelet/x/xpty v0.1.3 h1:eGSitii4suhzrISYH50ZfufV3v085BXQwIytcOdFSsw=
github.com/charmbracelet/x/xpty v0.1.3/go.mod h1:poPYpWuLDBFCKmKLDnhBp51ATa0ooD8FhypRwEFtH3Y=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
@@ -21,40 +139,102 @@ github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7np
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/go-gormigrate/gormigrate/v2 v2.1.7 h1:PdT4jVPbRb4R+0Ey2R0yJOdctVf4Whiq1Qi4necaZdg= github.com/go-gormigrate/gormigrate/v2 v2.1.7 h1:PdT4jVPbRb4R+0Ey2R0yJOdctVf4Whiq1Qi4necaZdg=
github.com/go-gormigrate/gormigrate/v2 v2.1.7/go.mod h1:3ouXglTuPrKF5+7cQyVGfvAXTU4vLMaYh9+EPl03uog= github.com/go-gormigrate/gormigrate/v2 v2.1.7/go.mod h1:3ouXglTuPrKF5+7cQyVGfvAXTU4vLMaYh9+EPl03uog=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.4 h1:9Rcod2ZPO6mOEG6b4GqyoHE/H6//Ze0RuhOo1hT1x0w=
github.com/go-playground/validator/v10 v10.30.4/go.mod h1:numpT+RPLE91R9oYWMY/R9zRgJBewr3IXHko4OISPpk=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-replayers/grpcreplay v1.3.0 h1:1Keyy0m1sIpqstQmgz307zhiJ1pV4uIlFds5weTmxbo=
github.com/google/go-replayers/grpcreplay v1.3.0/go.mod h1:v6NgKtkijC0d3e3RW8il6Sy5sqRVUwoQa4mHOGEy8DI=
github.com/google/go-replayers/httpreplay v1.2.0 h1:VM1wEyyjaoU53BwrOnaf9VhAyQQEEioJvFYxYcLRKzk=
github.com/google/go-replayers/httpreplay v1.2.0/go.mod h1:WahEFFZZ7a1P4VM1qEeHy+tME4bwyqPcwWbNlUI1Mcg=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc=
github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=
github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=
github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8=
github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE=
github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0=
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo= github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=
github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI= github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
github.com/knadh/koanf/parsers/yaml v1.1.1 h1:u70vV5IyaM0HvONh8HoqBC97oTgO33KcpZbTLiKVinU= github.com/knadh/koanf/parsers/yaml v1.1.1 h1:u70vV5IyaM0HvONh8HoqBC97oTgO33KcpZbTLiKVinU=
@@ -67,14 +247,30 @@ github.com/knadh/koanf/providers/file v1.2.1 h1:bEWbtQwYrA+W2DtdBrQWyXqJaJSG3KrP
github.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA= github.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA=
github.com/knadh/koanf/v2 v2.3.6 h1:JoQPSJmvS4aP0xNc8xMDr5tcrkSEInL23/Il7pITAKo= github.com/knadh/koanf/v2 v2.3.6 h1:JoQPSJmvS4aP0xNc8xMDr5tcrkSEInL23/Il7pITAKo=
github.com/knadh/koanf/v2 v2.3.6/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28= github.com/knadh/koanf/v2 v2.3.6/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/maypok86/otter/v2 v2.3.0 h1:8H8AVVFUSzJwIegKwv1uF5aGitTY+AIrtktg7OcLs8w=
github.com/maypok86/otter/v2 v2.3.0/go.mod h1:XgIdlpmL6jYz882/CAx1E4C1ukfgDKSaw4mWq59+7l8=
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
@@ -95,15 +291,44 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ= github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA= github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/riverqueue/river v0.47.0 h1:j8HOEyiOE8gRRhVS2wllKams372TH1WWiH6xCakXHqc=
github.com/riverqueue/river v0.47.0/go.mod h1:Wgmwx475ZBd8lQnNrJgyG2DWH7BfyNiSAtv0rC9bJBQ=
github.com/riverqueue/river/riverdriver v0.47.0 h1:qU8VkjdMl9plqeRg57SxsDUM/i/eECaSYejZ7HynC60=
github.com/riverqueue/river/riverdriver v0.47.0/go.mod h1:NOXl0fUiF1AT/TaQOjdx2A/c0Davn+SKbW8nAXWjfC4=
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0 h1:4wckhMlLN08F76/GWxGF6vlrbs5HCMuV01dpUnvOGI4=
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0/go.mod h1:EME1EGr7RU/vMUf61mpf9YXhsZJ+GlFk4AHrIHT+YdE=
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0 h1:5N9nvemhQwbUElMxASw4oEaYJ/v6hiS5Y9VcOQfdC5g=
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0/go.mod h1:ZboiXXZKC4+fTkxBxGRVmAsCuUu0NPYliqbWYuQAZyw=
github.com/riverqueue/river/rivershared v0.47.0 h1:jdtFsBexCvLqTXf8wnDnGXvB/eeOtPKQZAmThkjFpLs=
github.com/riverqueue/river/rivershared v0.47.0/go.mod h1:w8Pi1T+6ypyko5/hs9Mv7IIIKo4fAL9eXYnkVV/Y418=
github.com/riverqueue/river/rivertype v0.47.0 h1:SzNavtLGR4nMT1QkrEYQ7n96OMatYsn/z3aJWhewmv0=
github.com/riverqueue/river/rivertype v0.47.0/go.mod h1:XKkcRQR6zm8RR/JQa1Q2ywpj8uXQu21quPa4Lpw1Xhw=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
@@ -112,43 +337,130 @@ github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE= github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 h1:8fdv/9y3JMxjQ+ULAcOG8RtgeNu5t9XF9LolSXDuTwM=
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0/go.mod h1:CFr2LncGYokw+OKjXcr8ARCKG1SaC2UEnGxFBovE86g=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM=
github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pcM= github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pcM=
github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w= github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w=
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4= github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ=
go.opentelemetry.io/contrib/detectors/gcp v1.42.0/go.mod h1:W9zQ439utxymRrXsUOzZbFX4JhLxXU4+ZnCt8GG7yA8=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=
go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA=
google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA=
google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE=
google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw=
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 h1:CogIeEXn4qWYzzQU0QqvYBM8yDF9cFYzDq9ojSpv0Js=
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 h1:aJmi6DVGGIStN9Mobk/tZOOQUBbj0BPjZjjnOdoZKts=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.3 h1:bAn6O2pUa8LtpWEvL5NFU4+52Tfx8Ut7IVaIacCLcI0=
gorm.io/driver/postgres v1.6.3/go.mod h1:0c4fQA44XhOklXDkgtuKqysHCycTa5i9e3EIpDGCwXk=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=
pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=

42
internal/pdftest/pdf.go Normal file
View File

@@ -0,0 +1,42 @@
// Package pdftest builds small PDFs for the jz.bm tests. Only tests import
// it.
package pdftest
import (
"bytes"
"fmt"
"strings"
)
// OnePage is a one-page PDF that shows text in the base-14 Helvetica font,
// so pdftotext extracts it without any embedded font. text must be ASCII
// and hold no parentheses or backslashes. The xref offsets are computed from
// the objects as written.
func OnePage(text string) []byte {
if strings.ContainsAny(text, "()\\") {
panic("pdftest: text holds a parenthesis or a backslash")
}
stream := "BT /F1 24 Tf 72 700 Td (" + text + ") Tj ET"
objects := []string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
fmt.Sprintf("<< /Length %d >>\nstream\n%s\nendstream", len(stream), stream),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
}
var b bytes.Buffer
b.WriteString("%PDF-1.4\n")
offsets := make([]int, len(objects))
for i, obj := range objects {
offsets[i] = b.Len()
fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", i+1, obj)
}
xref := b.Len()
fmt.Fprintf(&b, "xref\n0 %d\n", len(objects)+1)
b.WriteString("0000000000 65535 f \n")
for _, off := range offsets {
fmt.Fprintf(&b, "%010d 00000 n \n", off)
}
fmt.Fprintf(&b, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(objects)+1, xref)
return b.Bytes()
}

View File

@@ -0,0 +1,205 @@
// Package searchtest is a Typesense stand-in for the jz.bm tests: an
// httptest server that answers the collection, import, delete and search
// endpoints the beachcomber typesense engine calls, and an app configured to
// talk to it. Only tests import it.
package searchtest
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
_ "git.golem15.com/golem15/summercms/modules/beachcomber/typesense"
"git.golem15.com/golem15/summercms/modules/compass"
)
// Index is the collection of the materials index.
const Index = "jz_bm_materials"
// HighlightStart and HighlightEnd are the highlight tags the typesense
// engine asks for (two private-use characters).
const (
HighlightStart = ""
HighlightEnd = ""
)
// Hit is one search answer: a document id and, optionally, the snippet of
// one field with the matched words between HighlightStart and HighlightEnd.
type Hit struct {
ID string
Field string
Snippet string
}
// Request is one request the stub received.
type Request struct {
Method string
Path string
Query url.Values
}
// Stub stands in for a Typesense server with one collection.
type Stub struct {
mu sync.Mutex
// Hits answer every search, in rank order.
Hits []Hit
// Status, when set, answers every request with that code.
Status int
exists bool
requests []Request
imported []map[string]any
removed []string
}
// ServeHTTP implements http.Handler.
func (s *Stub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
s.requests = append(s.requests, Request{Method: r.Method, Path: r.URL.Path, Query: r.URL.Query()})
if s.Status != 0 {
w.WriteHeader(s.Status)
_, _ = io.WriteString(w, `{"message":"stub failure"}`)
return
}
coll := "/collections/" + Index
switch {
case r.Method == http.MethodGet && r.URL.Path == coll:
if !s.exists {
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, `{"message":"Not Found"}`)
return
}
_, _ = io.WriteString(w, `{}`)
case r.Method == http.MethodPost && r.URL.Path == "/collections":
s.exists = true
w.WriteHeader(http.StatusCreated)
_, _ = io.WriteString(w, `{}`)
case r.Method == http.MethodDelete && r.URL.Path == coll:
if !s.exists {
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, `{"message":"Not Found"}`)
return
}
s.exists = false
_, _ = io.WriteString(w, `{}`)
case r.Method == http.MethodPost && r.URL.Path == coll+"/documents/import":
s.exists = true
sc := bufio.NewScanner(r.Body)
sc.Buffer(make([]byte, 0, 64*1024), 16<<20)
var answer []string
for sc.Scan() {
var doc map[string]any
if err := json.Unmarshal(sc.Bytes(), &doc); err == nil {
s.imported = append(s.imported, doc)
}
answer = append(answer, `{"success":true}`)
}
_, _ = io.WriteString(w, strings.Join(answer, "\n"))
case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, coll+"/documents/"):
s.removed = append(s.removed, strings.TrimPrefix(r.URL.Path, coll+"/documents/"))
_, _ = io.WriteString(w, `{}`)
case r.Method == http.MethodGet && r.URL.Path == coll+"/documents/search":
hits := make([]string, 0, len(s.Hits))
for _, h := range s.Hits {
id, _ := json.Marshal(h.ID)
highlights := "[]"
if h.Field != "" {
field, _ := json.Marshal(h.Field)
snippet, _ := json.Marshal(h.Snippet)
highlights = fmt.Sprintf(`[{"field":%s,"snippet":%s}]`, field, snippet)
}
hits = append(hits, fmt.Sprintf(`{"document":{"id":%s},"highlights":%s}`, id, highlights))
}
// found is deliberately larger than the hits, so a caller that
// exposed it would show.
_, _ = fmt.Fprintf(w, `{"found":%d,"hits":[%s]}`, len(s.Hits)+100, strings.Join(hits, ","))
default:
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, `{"message":"Not Found"}`)
}
}
// SetHits replaces the answer of every later search.
func (s *Stub) SetHits(hits ...Hit) {
s.mu.Lock()
defer s.mu.Unlock()
s.Hits = hits
}
// Requests returns the requests received so far.
func (s *Stub) Requests() []Request {
s.mu.Lock()
defer s.mu.Unlock()
return append([]Request(nil), s.requests...)
}
// Searches returns the search requests received so far.
func (s *Stub) Searches() []Request {
var out []Request
for _, r := range s.Requests() {
if r.Method == http.MethodGet && strings.HasSuffix(r.Path, "/documents/search") {
out = append(out, r)
}
}
return out
}
// Imported returns the documents upserted so far.
func (s *Stub) Imported() []map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
return append([]map[string]any(nil), s.imported...)
}
// Removed returns the document ids deleted so far.
func (s *Stub) Removed() []string {
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.removed...)
}
// Start serves stub on an httptest server closed with the test, and returns
// the SUMMER_SEARCH__* environment that points the typesense engine at it
// with a test-only key.
func Start(t testing.TB, stub *Stub) []string {
t.Helper()
srv := httptest.NewServer(stub)
t.Cleanup(srv.Close)
u, err := url.Parse(srv.URL)
if err != nil {
t.Fatal(err)
}
return []string{
"SUMMER_SEARCH__DRIVER=typesense",
"SUMMER_SEARCH__TYPESENSE__API_KEY=test-only-typesense-key",
"SUMMER_SEARCH__TYPESENSE__HOST=" + u.Hostname(),
"SUMMER_SEARCH__TYPESENSE__PORT=" + u.Port(),
"SUMMER_SEARCH__TYPESENSE__PROTOCOL=" + u.Scheme,
}
}
// App returns a bare application whose config holds env (and SUMMER_ENV
// testing) and an empty config directory.
func App(t testing.TB, env ...string) *backpack.App {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: jz-bm-test\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: append([]string{"SUMMER_ENV=testing"}, env...)})
if err != nil {
t.Fatal(err)
}
return backpack.New(cfg)
}

47
jobs.go Normal file
View File

@@ -0,0 +1,47 @@
package bm
import (
"context"
"errors"
"sync"
"git.golem15.com/golem15/summercms/modules/diary"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/jobs"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// pdfToolWarning is logged at most once per process when pdftotext is
// missing.
var pdfToolWarning sync.Once
// extractMaterialText runs one jz.bm.extract_material_text job: the text of
// the material's PDFs that have none yet is extracted and stored, then the
// material's search document is synced. A missing database or bucket is an
// error, so River retries; a missing pdftotext is logged once and the
// document is still synced.
func (p *Plugin) extractMaterialText(ctx context.Context, args jobs.ExtractMaterialTextArgs) error {
if p.app == nil {
return errors.New("jz.bm: app is not booted")
}
db, ok := p.app.Lookup[*gorm.DB]()
if !ok || db == nil {
return errors.New("jz.bm: database is not configured")
}
bucket, ok := p.app.Lookup[*blob.Bucket]()
if !ok || bucket == nil {
return errors.New("jz.bm: the uploads bucket is not configured")
}
_, err := classes.EnsureFileTexts(ctx, db, bucket, classes.DefaultPDFText(), args.MaterialID)
switch {
case errors.Is(err, classes.ErrPDFToolMissing):
pdfToolWarning.Do(func() {
diary.For("jz.bm").Warn("pdftotext not found; attached PDFs add no search text until poppler-utils is installed")
})
case err != nil:
return err
}
p.materialIndex.Sync(ctx, db, args.MaterialID)
return nil
}

View File

@@ -0,0 +1,15 @@
package jobs
// ExtractMaterialTextKind is the River kind of the file text extraction job.
const ExtractMaterialTextKind = "jz.bm.extract_material_text"
// ExtractMaterialTextArgs are the arguments of the job that extracts the
// text of a material's new PDFs and resyncs its search document. It is
// enqueued inside every attach transaction, so it exists only when the
// files committed.
type ExtractMaterialTextArgs struct {
MaterialID uint `json:"material_id"`
}
// Kind is the job kind.
func (ExtractMaterialTextArgs) Kind() string { return ExtractMaterialTextKind }

View File

@@ -0,0 +1,29 @@
package jobs_test
import (
"encoding/json"
"testing"
"git.golem15.com/jakub/sm-bm-plugin/jobs"
)
func TestExtractMaterialTextArgs(t *testing.T) {
args := jobs.ExtractMaterialTextArgs{MaterialID: 42}
if got := args.Kind(); got != "jz.bm.extract_material_text" {
t.Errorf("Kind = %q, want jz.bm.extract_material_text", got)
}
if jobs.ExtractMaterialTextKind != "jz.bm.extract_material_text" {
t.Errorf("ExtractMaterialTextKind = %q", jobs.ExtractMaterialTextKind)
}
b, err := json.Marshal(args)
if err != nil {
t.Fatal(err)
}
if string(b) != `{"material_id":42}` {
t.Errorf("JSON = %s, want {\"material_id\":42}", b)
}
var back jobs.ExtractMaterialTextArgs
if err := json.Unmarshal(b, &back); err != nil || back.MaterialID != 42 {
t.Errorf("round trip = %+v, %v", back, err)
}
}

View File

@@ -1 +1,109 @@
{} plugin:
name: BM studies
description: Courses, timetable, deadlines, readings and materials of the BM master's programme.
permissions:
access_courses: Manage courses and readings
access_schedule: Manage meetings, class sessions and deadlines
access_materials: Manage materials and tags
navigation:
courses: Courses
readings: Readings
meetings: Meetings
sessions: Class sessions
deadlines: Deadlines
materials: Materials
tags: Tags
common:
title: Title
description: Description
notes: Notes
course: Course
source: Source
url: URL
sort_order: Sort order
created_at: Created
none: — none —
meeting: For meeting
meeting_comment: The dashboard suggests this item before that meeting.
forms:
wyklad: Lecture
cwiczenia: Tutorial
konwersatorium: Conversatorium
seminarium: Seminar
inne: Other
courses:
readings: Readings
sessions: Class sessions
title: Courses
form: Course
name: Name
form_type: Form
code: Code
lecturer: Lecturer
semester: Semester
ects: ECTS
assessment: Assessment
assessment_comment: Such as egzamin or zaliczenie na ocenę.
elective_group: Elective group
elective_group_comment: Courses with the same value are alternatives to choose from, such as specjalnosc.
syllabus_url: Syllabus URL
meetings:
title: Meetings
form: Meeting
number: Meeting number
starts_on: From
ends_on: To
sessions:
title: Class sessions
form: Class session
meeting: Meeting
starts_at: Starts
ends_at: Ends
room: Room
kind: Kind
lecturer: Lecturer
lecturer_comment: Only when it differs from the course lecturer.
is_online: Online
deadlines:
title: Deadlines
form: Deadline
due_at: Due
kind: Kind
deadline_kinds:
zaliczenie: Credit
egzamin: Exam
praca: Paper
organizacyjne: Administrative
inne: Other
readings:
title: Readings
form: Reading
author: Author
is_required: Required
owned: Owned
materials:
title: Materials
form: Material
type: Type
body: Body (Markdown)
body_comment: A note in Markdown.
published_at: Published
files: Files
published_at_comment: Leave empty for a draft that students do not see.
tags: Tags
is_private: Private
is_private_comment: Only the author and the users it is shared with see a private material.
author: Author
author_comment: An author with the materials permission manages access in the student app.
shared_with: Shared with
shared_with_comment: Users who see a private material.
material_types:
pdf: PDF
notatka: Note
link: Link
inne: Other
tags:
title: Tags
form: Tag
name: Name
slug: Slug

109
lang/pl/lang.yaml Normal file
View File

@@ -0,0 +1,109 @@
plugin:
name: Studia BM
description: Przedmioty, plan zajęć, terminarz, lektury i materiały studiów magisterskich BM.
permissions:
access_courses: Zarządzanie przedmiotami i lekturami
access_schedule: Zarządzanie zjazdami, zajęciami i terminarzem
access_materials: Zarządzanie materiałami i tagami
navigation:
courses: Przedmioty
readings: Lektury
meetings: Zjazdy
sessions: Zajęcia
deadlines: Terminarz
materials: Materiały
tags: Tagi
common:
title: Tytuł
description: Opis
notes: Uwagi
course: Przedmiot
source: Źródło
url: Adres URL
sort_order: Kolejność
created_at: Utworzono
none: — brak —
meeting: Na zjazd
meeting_comment: Pulpit poleca tę pozycję przed tym zjazdem.
forms:
wyklad: Wykład
cwiczenia: Ćwiczenia
konwersatorium: Konwersatorium
seminarium: Seminarium
inne: Inne
courses:
readings: Lektury
sessions: Zajęcia
title: Przedmioty
form: Przedmiot
name: Nazwa
form_type: Forma zajęć
code: Kod
lecturer: Prowadzący
semester: Semestr
ects: ECTS
assessment: Forma zaliczenia
assessment_comment: Np. egzamin, zaliczenie na ocenę.
elective_group: Grupa do wyboru
elective_group_comment: Przedmioty o tej samej wartości są alternatywami do wyboru, np. specjalnosc.
syllabus_url: Sylabus (URL)
meetings:
title: Zjazdy
form: Zjazd
number: Numer zjazdu
starts_on: Od
ends_on: Do
sessions:
title: Zajęcia
form: Zajęcia
meeting: Zjazd
starts_at: Początek
ends_at: Koniec
room: Sala
kind: Rodzaj
lecturer: Prowadzący
lecturer_comment: Tylko gdy inny niż prowadzący przedmiotu.
is_online: Zdalnie
deadlines:
title: Terminarz
form: Termin
due_at: Termin
kind: Rodzaj
deadline_kinds:
zaliczenie: Zaliczenie
egzamin: Egzamin
praca: Praca
organizacyjne: Organizacyjne
inne: Inne
readings:
title: Lektury
form: Lektura
author: Autor
is_required: Obowiązkowa
owned: Mam
materials:
title: Materiały
form: Materiał
type: Typ
body: Treść (Markdown)
body_comment: Notatka w Markdownie.
published_at: Opublikowano
files: Pliki
published_at_comment: Puste pole to szkic, niewidoczny dla studentów.
tags: Tagi
is_private: Prywatny
is_private_comment: Prywatny materiał widzą tylko autor i osoby, którym go udostępniono.
author: Autor
author_comment: Autor z uprawnieniem do materiałów zarządza dostępem w aplikacji studenta.
shared_with: Udostępniono
shared_with_comment: Osoby, które widzą prywatny materiał.
material_types:
pdf: PDF
notatka: Notatka
link: Link
inne: Inne
tags:
title: Tagi
form: Tag
name: Nazwa
slug: Slug

550
management_token_test.go Normal file
View File

@@ -0,0 +1,550 @@
package bm_test
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/surf"
"gocloud.dev/blob"
_ "gocloud.dev/blob/memblob"
)
func TestManagementAPIUsesSharedTokenAndCurrentUserPermissions(t *testing.T) {
app, plugins, db := migrated(t)
var userID uint
if err := db.Raw(`
INSERT INTO users (email, password, must_change_password)
VALUES ('bm-shared-token@example.test', '', false)
RETURNING id`).Scan(&userID).Error; err != nil {
t.Fatal(err)
}
var groupID uint
if err := db.Raw(`
INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
VALUES ('BM API', 'bm-api', '{"jz.bm.access_courses":1}', NOW(), NOW())
RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, userID, groupID).Error; err != nil {
t.Fatal(err)
}
secret, token, err := userclasses.MintAPIToken("usr_", userID, "BM integration", []string{"read"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := db.Create(token).Error; err != nil {
t.Fatal(err)
}
handler, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
request := func(path string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Authorization", "Bearer "+secret)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
if rec := request("/api/v1/bm/courses"); rec.Code != http.StatusOK {
t.Fatalf("permitted courses request = %d %s", rec.Code, rec.Body.String())
}
if rec := request("/api/v1/bm/materials"); rec.Code != http.StatusForbidden {
t.Fatalf("ungranted materials request = %d %s", rec.Code, rec.Body.String())
}
if err := db.Model(&struct{}{}).Table("user_groups").Where("id = ?", groupID).Update("permissions", `{}`).Error; err != nil {
t.Fatal(err)
}
if rec := request("/api/v1/bm/courses"); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Forbidden") {
t.Fatalf("request after permission revocation = %d %s", rec.Code, rec.Body.String())
}
}
// TestManagementMaterialsUpsertAndUpdate drives the material routes of the
// management API with a write token: the upsert identity (title and course),
// the update by id with a rename and a draft, the identity conflict, and
// the 404s.
func TestManagementMaterialsUpsertAndUpdate(t *testing.T) {
app, plugins, db := migrated(t)
var userID uint
if err := db.Raw(`
INSERT INTO users (email, password, must_change_password)
VALUES ('bm-materials-token@example.test', '', false)
RETURNING id`).Scan(&userID).Error; err != nil {
t.Fatal(err)
}
var groupID uint
if err := db.Raw(`
INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
VALUES ('BM materials', 'bm-materials', '{"jz.bm.access_materials":1}', NOW(), NOW())
RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, userID, groupID).Error; err != nil {
t.Fatal(err)
}
secret, token, err := userclasses.MintAPIToken("usr_", userID, "BM notes", []string{"read", "write"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := db.Create(token).Error; err != nil {
t.Fatal(err)
}
handler, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
send := func(method, path string, payload any) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
var rd io.Reader
if payload != nil {
raw, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
rd = bytes.NewReader(raw)
}
req := httptest.NewRequest(method, path, rd)
req.Header.Set("Authorization", "Bearer "+secret)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
var out map[string]any
if rec.Body.Len() > 0 {
_ = json.Unmarshal(rec.Body.Bytes(), &out)
}
return rec, out
}
data := func(out map[string]any) map[string]any {
t.Helper()
d, _ := out["data"].(map[string]any)
if d == nil {
t.Fatalf("no data object in %v", out)
}
return d
}
idPath := func(id any) string { return "/api/v1/bm/materials/" + strconv.Itoa(int(id.(float64))) }
note := map[string]any{"title": "Definicje globalizacji", "type": "notatka", "body": "# Robertson\n\n> single place", "tags": []string{"Globalizacja", "Teoria 2"}}
rec, out := send(http.MethodPost, "/api/v1/bm/materials", note)
if rec.Code != http.StatusCreated || out["created"] != true {
t.Fatalf("create = %d %s", rec.Code, rec.Body.String())
}
first := data(out)
if first["published_at"] == nil {
t.Error("a new material without published_at is not published")
}
if tags, _ := first["tags"].([]any); len(tags) != 2 || tags[1].(map[string]any)["slug"] != "teoria-2" {
t.Errorf("tags = %v", first["tags"])
}
rec, out = send(http.MethodPost, "/api/v1/bm/materials", note)
if rec.Code != http.StatusOK || out["created"] != false || data(out)["id"] != first["id"] {
t.Fatalf("repeated upsert = %d %s", rec.Code, rec.Body.String())
}
rec, out = send(http.MethodGet, idPath(first["id"]), nil)
if rec.Code != http.StatusOK || data(out)["title"] != "Definicje globalizacji" {
t.Fatalf("show = %d %s", rec.Code, rec.Body.String())
}
if files, ok := data(out)["files"].([]any); !ok || len(files) != 0 {
t.Errorf("files = %v", data(out)["files"])
}
renamed := map[string]any{"title": "Definicje globalizacji (zjazd 2)", "type": "notatka", "body": "zmienione", "published_at": nil}
rec, out = send(http.MethodPut, idPath(first["id"]), renamed)
if rec.Code != http.StatusOK {
t.Fatalf("update = %d %s", rec.Code, rec.Body.String())
}
updated := data(out)
if updated["title"] != renamed["title"] || updated["body"] != "zmienione" || updated["published_at"] != nil {
t.Errorf("updated = %v", updated)
}
if tags, _ := updated["tags"].([]any); len(tags) != 2 {
t.Errorf("an update without tags changed them: %v", updated["tags"])
}
rec, out = send(http.MethodPost, "/api/v1/bm/materials", note)
if rec.Code != http.StatusCreated || data(out)["id"] == first["id"] {
t.Fatalf("upsert after the rename = %d %s", rec.Code, rec.Body.String())
}
second := data(out)
rec, out = send(http.MethodPut, idPath(second["id"]), renamed)
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"title"`) {
t.Fatalf("update onto a taken identity = %d %s", rec.Code, rec.Body.String())
}
for _, method := range []string{http.MethodGet, http.MethodPut} {
var payload any
if method == http.MethodPut {
payload = renamed
}
if rec, _ := send(method, "/api/v1/bm/materials/999999", payload); rec.Code != http.StatusNotFound {
t.Errorf("%s of an unknown id = %d %s", method, rec.Code, rec.Body.String())
}
}
if rec, _ := send(http.MethodDelete, idPath(first["id"]), nil); rec.Code != http.StatusNoContent {
t.Fatalf("delete = %d %s", rec.Code, rec.Body.String())
}
if rec, _ := send(http.MethodGet, idPath(first["id"]), nil); rec.Code != http.StatusNotFound {
t.Errorf("show after delete = %d", rec.Code)
}
// Visibility, author and shares: a new material is public, with the
// token user as author and no shares.
rec, out = send(http.MethodPost, "/api/v1/bm/materials", map[string]any{"title": "Notatki prywatne", "type": "notatka", "body": nil, "source": nil, "url": nil})
if rec.Code != http.StatusCreated {
t.Fatalf("create for access = %d %s", rec.Code, rec.Body.String())
}
own := data(out)
if own["is_private"] != false || own["author_user_id"] != float64(userID) {
t.Errorf("new material access = is_private %v author %v, want false and %d", own["is_private"], own["author_user_id"], userID)
}
if shares, ok := own["shares"].([]any); !ok || len(shares) != 0 {
t.Errorf("new material shares = %v, want []", own["shares"])
}
if rec, _ := send(http.MethodPut, idPath(own["id"]), map[string]any{"title": "Notatki prywatne", "type": "notatka", "body": nil, "source": nil, "url": nil, "share_user_ids": []uint{999999}}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "share_user_ids") {
t.Errorf("unknown share user = %d %s", rec.Code, rec.Body.String())
}
rec, out = send(http.MethodPatch, idPath(own["id"])+"/visibility", map[string]any{"is_private": true})
if rec.Code != http.StatusOK || data(out)["is_private"] != true {
t.Fatalf("visibility = %d %s", rec.Code, rec.Body.String())
}
var otherID uint
if err := db.Raw(`
INSERT INTO users (email, password, must_change_password)
VALUES ('bm-materials-reader@example.test', '', false)
RETURNING id`).Scan(&otherID).Error; err != nil {
t.Fatal(err)
}
rec, out = send(http.MethodPut, idPath(own["id"])+"/shares", map[string]any{"user_ids": []uint{otherID}})
if rec.Code != http.StatusOK {
t.Fatalf("shares = %d %s", rec.Code, rec.Body.String())
}
if shares, _ := data(out)["shares"].([]any); len(shares) != 1 || shares[0].(map[string]any)["id"] != float64(otherID) {
t.Errorf("shares = %v, want the reader", data(out)["shares"])
}
rec, out = send(http.MethodGet, "/api/v1/bm/users", nil)
if rec.Code != http.StatusOK {
t.Fatalf("users = %d %s", rec.Code, rec.Body.String())
}
seen := map[float64]bool{}
for _, u := range out["data"].([]any) {
seen[u.(map[string]any)["id"].(float64)] = true
}
if !seen[float64(userID)] || !seen[float64(otherID)] {
t.Errorf("users = %v, want both users", out["data"])
}
}
// TestManagementMaterialFiles uploads files to a material through the
// management API, refuses a disallowed type, detaches one file and deletes
// the material with the other, checking rows and blobs.
func TestManagementMaterialFiles(t *testing.T) {
app, plugins, db := migrated(t)
bucket, err := blob.OpenBucket(t.Context(), "mem://")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { bucket.Close() })
if err := app.Publish(bucket); err != nil {
t.Fatal(err)
}
var userID uint
if err := db.Raw(`
INSERT INTO users (email, password, must_change_password)
VALUES ('bm-files-token@example.test', '', false)
RETURNING id`).Scan(&userID).Error; err != nil {
t.Fatal(err)
}
var groupID uint
if err := db.Raw(`
INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
VALUES ('BM files', 'bm-files', '{"jz.bm.access_materials":1}', NOW(), NOW())
RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, userID, groupID).Error; err != nil {
t.Fatal(err)
}
secret, token, err := userclasses.MintAPIToken("usr_", userID, "BM files", []string{"read", "write"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := db.Create(token).Error; err != nil {
t.Fatal(err)
}
handler, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
do := func(req *http.Request) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
req.Header.Set("Authorization", "Bearer "+secret)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
var out map[string]any
if rec.Body.Len() > 0 {
_ = json.Unmarshal(rec.Body.Bytes(), &out)
}
return rec, out
}
upload := func(path string, files map[string][]byte) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
for name, content := range files {
fw, err := mw.CreateFormFile("file", name)
if err != nil {
t.Fatal(err)
}
fw.Write(content)
}
mw.Close()
req := httptest.NewRequest(http.MethodPost, path, &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
return do(req)
}
countFiles := func() int64 {
var n int64
if err := db.Table("system_files").Where("field = 'files'").Count(&n).Error; err != nil {
t.Fatal(err)
}
return n
}
raw, _ := json.Marshal(map[string]any{"title": "Podręcznik", "type": "pdf"})
req := httptest.NewRequest(http.MethodPost, "/api/v1/bm/materials", bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
rec, out := do(req)
if rec.Code != http.StatusCreated {
t.Fatalf("create = %d %s", rec.Code, rec.Body.String())
}
id := strconv.Itoa(int(out["data"].(map[string]any)["id"].(float64)))
base := "/api/v1/bm/materials/" + id
pdf := []byte("%PDF-1.4\n1 0 obj << >> endobj\ntrailer << >>\n%%EOF\n")
rec, out = upload(base+"/files", map[string][]byte{"wojna.pdf": pdf})
if rec.Code != http.StatusCreated {
t.Fatalf("upload = %d %s", rec.Code, rec.Body.String())
}
rec, out = upload(base+"/files", map[string][]byte{"plan.txt": []byte("plan zajęć\n")})
if rec.Code != http.StatusCreated {
t.Fatalf("second upload = %d %s", rec.Code, rec.Body.String())
}
files, _ := out["data"].(map[string]any)["files"].([]any)
if len(files) != 2 {
t.Fatalf("files after two uploads = %v", out["data"])
}
first := files[0].(map[string]any)
if first["name"] != "wojna.pdf" || first["mime"] != "application/pdf" || !strings.HasSuffix(first["url"].(string), ".pdf") {
t.Errorf("first file = %v", first)
}
if rec, _ := upload(base+"/files", map[string][]byte{"x.exe": []byte("MZ")}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("disallowed type = %d %s", rec.Code, rec.Body.String())
}
if rec, _ := upload(base+"/files", nil); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("no file = %d %s", rec.Code, rec.Body.String())
}
if rec, _ := upload("/api/v1/bm/materials/999999/files", map[string][]byte{"a.pdf": pdf}); rec.Code != http.StatusNotFound {
t.Errorf("unknown material = %d %s", rec.Code, rec.Body.String())
}
if n := countFiles(); n != 2 {
t.Fatalf("system_files rows = %d after refusals, want 2", n)
}
fileID := strconv.Itoa(int(first["id"].(float64)))
if rec, _ := do(httptest.NewRequest(http.MethodDelete, "/api/v1/bm/materials/999999/files/"+fileID, nil)); rec.Code != http.StatusNotFound {
t.Errorf("detach through another material = %d", rec.Code)
}
if rec, _ := do(httptest.NewRequest(http.MethodDelete, base+"/files/"+fileID, nil)); rec.Code != http.StatusNoContent {
t.Fatalf("detach = %d %s", rec.Code, rec.Body.String())
}
if n := countFiles(); n != 1 {
t.Errorf("system_files rows = %d after detach, want 1", n)
}
if rec, _ := do(httptest.NewRequest(http.MethodDelete, base, nil)); rec.Code != http.StatusNoContent {
t.Fatalf("delete material = %d %s", rec.Code, rec.Body.String())
}
if n := countFiles(); n != 0 {
t.Errorf("system_files rows = %d after deleting the material, want 0", n)
}
iter := bucket.List(nil)
if obj, err := iter.Next(t.Context()); err != io.EOF {
t.Errorf("a blob is left in the bucket: %v %v", obj, err)
}
}
// TestManagementRecords drives the record routes: create, partial update,
// validation (unknown column, rules, temporal order, a missing reference),
// list filters and delete, for courses, meetings, sessions, readings and
// deadlines.
func TestManagementRecords(t *testing.T) {
app, plugins, db := migrated(t)
var userID uint
if err := db.Raw(`
INSERT INTO users (email, password, must_change_password)
VALUES ('bm-records-token@example.test', '', false)
RETURNING id`).Scan(&userID).Error; err != nil {
t.Fatal(err)
}
var groupID uint
if err := db.Raw(`
INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
VALUES ('BM records', 'bm-records', '{"jz.bm.access_courses":1,"jz.bm.access_schedule":1}', NOW(), NOW())
RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, userID, groupID).Error; err != nil {
t.Fatal(err)
}
secret, token, err := userclasses.MintAPIToken("usr_", userID, "BM records", []string{"read", "write"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := db.Create(token).Error; err != nil {
t.Fatal(err)
}
handler, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
send := func(method, path string, payload any) (int, map[string]any) {
t.Helper()
var rd io.Reader
if payload != nil {
raw, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
rd = bytes.NewReader(raw)
}
req := httptest.NewRequest(method, "/api/v1/bm"+path, rd)
req.Header.Set("Authorization", "Bearer "+secret)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
var out map[string]any
if rec.Body.Len() > 0 {
_ = json.Unmarshal(rec.Body.Bytes(), &out)
}
return rec.Code, out
}
data := func(out map[string]any) map[string]any {
t.Helper()
d, _ := out["data"].(map[string]any)
if d == nil {
t.Fatalf("no data object in %v", out)
}
return d
}
id := func(d map[string]any) string { return strconv.Itoa(int(d["id"].(float64))) }
errorsOf := func(out map[string]any) map[string]any {
e, _ := out["errors"].(map[string]any)
return e
}
code, out := send(http.MethodPost, "/courses", map[string]any{"name": "Teoria", "form": "wyklad", "semester": 1, "code": "26-X"})
if code != http.StatusCreated {
t.Fatalf("create course = %d %v", code, out)
}
course := data(out)
code, out = send(http.MethodPatch, "/courses/"+id(course), map[string]any{"description": "Plan wykładów: 1. Wprowadzenie."})
if code != http.StatusOK || data(out)["description"] != "Plan wykładów: 1. Wprowadzenie." || data(out)["name"] != "Teoria" {
t.Fatalf("patch course = %d %v", code, out)
}
if code, out = send(http.MethodPatch, "/courses/"+id(course), map[string]any{"owner": 1}); code != http.StatusUnprocessableEntity || errorsOf(out)["owner"] == nil {
t.Errorf("course patch with an unknown column = %d %v", code, out)
}
if code, out = send(http.MethodPatch, "/courses/"+id(course), map[string]any{"form": "warsztat", "semester": 9}); code != http.StatusUnprocessableEntity || errorsOf(out)["form"] == nil || errorsOf(out)["semester"] == nil {
t.Errorf("course patch breaking the rules = %d %v", code, out)
}
if code, _ = send(http.MethodDelete, "/courses/"+id(course), nil); code != http.StatusMethodNotAllowed && code != http.StatusNotFound {
t.Errorf("course delete = %d, want no route", code)
}
code, out = send(http.MethodPost, "/meetings", map[string]any{"number": 1, "starts_on": "2026-10-03", "ends_on": "2026-10-04"})
if code != http.StatusCreated || data(out)["starts_on"] != "2026-10-03" {
t.Fatalf("create meeting = %d %v", code, out)
}
meeting := data(out)
if code, out = send(http.MethodPost, "/meetings", map[string]any{"number": 1, "starts_on": "2026-10-17", "ends_on": "2026-10-18"}); code != http.StatusUnprocessableEntity || errorsOf(out)["number"] == nil {
t.Errorf("duplicate meeting number = %d %v", code, out)
}
if code, out = send(http.MethodPatch, "/meetings/"+id(meeting), map[string]any{"notes": "online"}); code != http.StatusOK || data(out)["number"] != float64(1) {
t.Errorf("patch own meeting (unique on itself) = %d %v", code, out)
}
session := map[string]any{"course_id": course["id"], "meeting_id": meeting["id"], "starts_at": "2026-10-03 09:00", "ends_at": "2026-10-03 10:30", "room": "107"}
code, out = send(http.MethodPost, "/class-sessions", session)
if code != http.StatusCreated || data(out)["starts_at"] != "2026-10-03T09:00:00+02:00" {
t.Fatalf("create session = %d %v", code, out)
}
sess := data(out)
if code, out = send(http.MethodPatch, "/class-sessions/"+id(sess), map[string]any{"ends_at": "2026-10-03 08:00"}); code != http.StatusUnprocessableEntity || errorsOf(out)["ends_at"] == nil {
t.Errorf("session ending before it starts = %d %v", code, out)
}
if code, out = send(http.MethodPatch, "/class-sessions/"+id(sess), map[string]any{"room": "", "lecturer": "dr X", "is_online": true}); code != http.StatusOK || data(out)["room"] != nil || data(out)["is_online"] != true {
t.Errorf("patch session = %d %v", code, out)
}
if code, out = send(http.MethodPatch, "/class-sessions/"+id(sess), map[string]any{"room": 102}); code != http.StatusOK || data(out)["room"] != "102" {
t.Errorf("room sent as a number = %d %v", code, out)
}
if code, out = send(http.MethodPost, "/class-sessions", map[string]any{"course_id": 999999, "starts_at": "2026-10-03 09:00", "ends_at": "2026-10-03 10:00"}); code != http.StatusUnprocessableEntity || errorsOf(out)["course_id"] == nil {
t.Errorf("session of an unknown course = %d %v", code, out)
}
code, out = send(http.MethodPost, "/readings", map[string]any{"course_id": course["id"], "title": "Kuhn, Struktura rewolucji naukowych", "is_required": true})
if code != http.StatusCreated {
t.Fatalf("create reading = %d %v", code, out)
}
reading := data(out)
if code, out = send(http.MethodPost, "/readings", map[string]any{"course_id": course["id"]}); code != http.StatusUnprocessableEntity || errorsOf(out)["title"] == nil {
t.Errorf("reading without a title = %d %v", code, out)
}
if code, out = send(http.MethodGet, "/readings?course_id="+id(course), nil); code != http.StatusOK || len(out["data"].([]any)) != 1 {
t.Errorf("readings of the course = %d %v", code, out)
}
if code, out = send(http.MethodGet, "/readings?course_id=999999", nil); code != http.StatusOK || len(out["data"].([]any)) != 0 {
t.Errorf("readings of another course = %d %v", code, out)
}
code, out = send(http.MethodPost, "/deadlines", map[string]any{"title": "Egzamin", "due_at": "2027-01-30T12:00:00+01:00", "kind": "egzamin", "course_id": course["id"]})
if code != http.StatusCreated {
t.Fatalf("create deadline = %d %v", code, out)
}
deadline := data(out)
if code, out = send(http.MethodPatch, "/deadlines/"+id(deadline), map[string]any{"due_at": "jutro"}); code != http.StatusUnprocessableEntity || errorsOf(out)["due_at"] == nil {
t.Errorf("deadline with a bad time = %d %v", code, out)
}
if code, out = send(http.MethodPatch, "/deadlines/"+id(deadline), map[string]any{"course_id": nil}); code != http.StatusOK || data(out)["course_id"] != nil {
t.Errorf("deadline detached from the course = %d %v", code, out)
}
for _, path := range []string{"/readings/" + id(reading), "/deadlines/" + id(deadline), "/class-sessions/" + id(sess)} {
if code, _ := send(http.MethodDelete, path, nil); code != http.StatusNoContent {
t.Errorf("delete %s = %d", path, code)
}
if code, _ := send(http.MethodGet, path, nil); code != http.StatusNotFound {
t.Errorf("get %s after delete = %d", path, code)
}
}
}

View File

@@ -0,0 +1,156 @@
package bm_test
import (
"net/http"
"slices"
"testing"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// TestMaterialAccessAgainstDatabase checks the visibility rule of private
// materials in the student reads (list, detail, course detail and counters)
// for the author, a user a material is shared with and another user, and
// the author's access endpoints with the claim rule.
func TestMaterialAccessAgainstDatabase(t *testing.T) {
app, plugins, gdb := migrated(t)
seedFixture(t, plugins, "testdata/seed.example.json")
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatalf("Assemble: %v", err)
}
authorID := createUser(t, gdb, "author@example.test")
bobID := createUser(t, gdb, "bob@example.test")
carolID := createUser(t, gdb, "carol@example.test")
var groupID uint
if err := gdb.Raw(`
INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
VALUES ('BM materials', 'bm-materials', '{"jz.bm.access_materials":1}', NOW(), NOW())
RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
if err := gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, authorID, groupID).Error; err != nil {
t.Fatal(err)
}
author := apiClient{t: t, h: h, token: tokenFor(t, authorID)}
bob := apiClient{t: t, h: h, token: tokenFor(t, bobID)}
carol := apiClient{t: t, h: h, token: tokenFor(t, carolID)}
const base = "/_bm/api/v1"
var course models.Course
if err := gdb.Order("id").Take(&course).Error; err != nil {
t.Fatal(err)
}
insert := func(title string, private bool, authorUserID *uint) uint {
t.Helper()
var id uint
err := gdb.Raw(`INSERT INTO jz_bm_materials (course_id, title, type, published_at, is_private, author_user_id)
VALUES (?, ?, 'notatka', NOW() - INTERVAL '1 day', ?, ?) RETURNING id`, course.ID, title, private, authorUserID).Scan(&id).Error
if err != nil {
t.Fatal(err)
}
return id
}
pub := insert("Publiczny", false, nil)
priv := insert("Prywatny autora", true, &authorID)
shared := insert("Udostępniony Bobowi", true, &authorID)
if err := gdb.Create(&models.MaterialShare{MaterialID: shared, UserID: bobID}).Error; err != nil {
t.Fatal(err)
}
ids := func(rows []map[string]any) []string {
out := make([]string, 0, len(rows))
for _, row := range rows {
out = append(out, id(row["id"]))
}
slices.Sort(out)
return out
}
sorted := func(in ...uint) []string {
out := make([]string, 0, len(in))
for _, v := range in {
out = append(out, jsonID(v))
}
slices.Sort(out)
return out
}
courseMaterials := func(c apiClient) ([]string, float64) {
t.Helper()
detail := obj(c.ok("GET", base+"/courses/"+jsonID(course.ID))["data"])
raw, _ := detail["materials"].([]any)
rows := make([]map[string]any, 0, len(raw))
for _, r := range raw {
rows = append(rows, r.(map[string]any))
}
n, _ := obj(detail["counts"])["materials"].(float64)
return ids(rows), n
}
for _, tc := range []struct {
name string
client apiClient
want []string
}{
{"carol", carol, sorted(pub)},
{"bob", bob, sorted(pub, shared)},
{"author", author, sorted(pub, priv, shared)},
} {
if got := ids(list(tc.client.ok("GET", base+"/materials"))); !slices.Equal(got, tc.want) {
t.Errorf("%s /materials = %v, want %v", tc.name, got, tc.want)
}
got, n := courseMaterials(tc.client)
if !slices.Equal(got, tc.want) || int(n) != len(tc.want) {
t.Errorf("%s course materials = %v (count %v), want %v", tc.name, got, n, tc.want)
}
}
carol.want(http.StatusNotFound, "GET", base+"/materials/"+jsonID(priv), "")
bob.want(http.StatusNotFound, "GET", base+"/materials/"+jsonID(priv), "")
detail := obj(author.ok("GET", base+"/materials/"+jsonID(priv))["data"])
if detail["can_manage"] != true || detail["is_private"] != true {
t.Errorf("author detail = %v, want can_manage and is_private", detail)
}
if d := obj(bob.ok("GET", base+"/materials/"+jsonID(shared))["data"]); d["can_manage"] != false {
t.Errorf("bob detail of the shared material = %v, want can_manage false", d)
}
// The access endpoints are the author's (a manager) only.
access := base + "/materials/" + jsonID(priv) + "/access"
carol.want(http.StatusNotFound, "GET", access, "")
bob.want(http.StatusNotFound, "GET", access, "")
carol.want(http.StatusNotFound, "PUT", access, `{"is_private":false}`)
bob.want(http.StatusNotFound, "PUT", base+"/materials/"+jsonID(shared)+"/access", `{"is_private":false}`)
got := obj(author.ok("GET", access)["data"])
if got["is_private"] != true {
t.Errorf("access = %v", got)
}
if shares, ok := got["shares"].([]any); !ok || len(shares) != 0 {
t.Errorf("shares = %v, want []", got["shares"])
}
var users []string
for _, u := range got["users"].([]any) {
users = append(users, id(u.(map[string]any)["id"]))
}
if !slices.Contains(users, jsonID(bobID)) || !slices.Contains(users, jsonID(carolID)) || slices.Contains(users, jsonID(authorID)) {
t.Errorf("users = %v, want bob and carol without the author", users)
}
author.want(http.StatusUnprocessableEntity, "PUT", access, `{"user_ids":[999999]}`)
author.want(http.StatusUnprocessableEntity, "PUT", access, `{"author_user_id":1}`)
put := obj(author.want(http.StatusOK, "PUT", access, `{"user_ids":[`+jsonID(carolID)+`]}`)["data"])
if shares, _ := put["shares"].([]any); len(shares) != 1 || id(obj(shares[0])["id"]) != jsonID(carolID) {
t.Errorf("shares after PUT = %v", put["shares"])
}
carol.ok("GET", base+"/materials/"+jsonID(priv))
// The claim rule: changing an author-less material makes the caller its
// author.
pubAccess := base + "/materials/" + jsonID(pub) + "/access"
claimed := obj(author.want(http.StatusOK, "PUT", pubAccess, `{"is_private":true}`)["data"])
if claimed["is_private"] != true || id(claimed["author_user_id"]) != jsonID(authorID) {
t.Errorf("claimed = %v", claimed)
}
carol.want(http.StatusNotFound, "GET", base+"/materials/"+jsonID(pub), "")
if got := ids(list(carol.ok("GET", base+"/materials"))); !slices.Equal(got, sorted(priv)) {
t.Errorf("carol /materials after the claim = %v, want only the shared one", got)
}
}

Some files were not shown because too many files have changed in this diff Show More