Compare commits

...

109 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
365 changed files with 16385 additions and 307 deletions

284
README.md
View File

@@ -16,11 +16,12 @@ Timestamps are stored in UTC (`TIMESTAMPTZ`) and written in RFC 3339 in Europe/W
## Features ## 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`, and `CalendarFeed` (one per user). - 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). - 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. - 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 without `published_at` is a draft; a material whose `published_at` lies in the future is not shown yet.
- 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 rows; deleting a user deletes the user's calendar feed. - 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. - 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. - `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.
@@ -43,12 +44,32 @@ Every route except the calendar feed itself needs `Authorization: Bearer <golem1
| GET | `/_bm/api/v1/readings` | `course` (ID) | Readings with the caller's `read_at` | | 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) | | PUT | `/_bm/api/v1/readings/{id}/progress` | | Marks the reading read (idempotent) |
| DELETE | `/_bm/api/v1/readings/{id}/progress` | | Clears the mark (idempotent) | | DELETE | `/_bm/api/v1/readings/{id}/progress` | | Clears the mark (idempotent) |
| GET | `/_bm/api/v1/materials` | `course`, `tag` (slug), `type`, `page`, `per_page` (1–100) | One page of published materials | | PUT | `/_bm/api/v1/readings/{id}/owned` | | Marks the reading owned (idempotent) |
| GET | `/_bm/api/v1/materials/{id}` | | One published material with body, tags and files | | 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` | | 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 | | 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` | | 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 | | 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 ### Shared shapes
@@ -81,21 +102,21 @@ A deadline (`kind` is one of `zaliczenie`, `egzamin`, `praca`, `organizacyjne`,
{"id": 1, "title": "…", "due_at": "2026-10-05T23:59:00+02:00", "kind": "organizacyjne", "description": null, "course_id": null, "course": null} {"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): A reading (`read_at` is the caller's, or null; `meeting_id` is the zjazd the reading is meant for, null when none):
```json ```json
{"id": 1, "course_id": 1, "course": {…}, "title": "…", "author": null, "source": null, "url": null, {"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"} "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): 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 ```json
{"id": 1, "course_id": 1, "course": {…}, "title": "…", "type": "notatka", "source": null, "url": null, {"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} "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 published materials): A course with counters (`readings_read` is the caller's; `materials` counts the published materials the caller may see):
```json ```json
{"id": 1, "code": null, "name": "…", "form": "wyklad", "lecturer": "…", "semester": 1, "ects": 8, {"id": 1, "code": null, "name": "…", "form": "wyklad", "lecturer": "…", "semester": 1, "ects": 8,
@@ -132,9 +153,9 @@ A course with counters (`readings_read` is the caller's; `materials` counts publ
`/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. `/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 ### 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. The progress routes answer: `/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 ```json
{"data": {"reading_id": 7, "read_at": "2026-10-02T21:15:04+02:00"}} {"data": {"reading_id": 7, "read_at": "2026-10-02T21:15:04+02:00"}}
@@ -142,19 +163,109 @@ A course with counters (`readings_read` is the caller's; `materials` counts publ
Marking a read reading again keeps the first `read_at`. Clearing answers `read_at: null`, also when the reading was not marked. 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} ### GET /materials, GET /materials/{id}
```json ```json
{"data": [<material>, …], "meta": {"current_page": 1, "last_page": 1, "per_page": 20, "total": 2}} {"data": [<material>, …], "meta": {"current_page": 1, "last_page": 1, "per_page": 20, "total": 2}}
``` ```
Newest publication first. The detail adds the Markdown body and the public files; `url` starts with `storage.uploads.public_path_prefix`: 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 ```json
{"data": {…material…, "body": "# …", {"data": {…material…, "body": "# …",
"files": [{"id": 3, "url": "/storage/uploads/5f1/d0c/2e9/5f1d0c2e9a7b4c3d8e6f.pdf", "name": "wyklad.pdf", "size": 123456, "mime": "application/pdf"}]}} "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 ### Calendar feed
The calendar-feed routes answer the caller's feed: The calendar-feed routes answer the caller's feed:
@@ -185,6 +296,120 @@ The calendar is RFC 5545 (CRLF lines folded at 75 octets, escaped TEXT) with tim
`DTSTAMP` and `LAST-MODIFIED` are the row's `updated_at`, so an unchanged timetable gives the same bytes. `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 ## 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/`. 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/`.
@@ -199,7 +424,7 @@ Controllers (admin API path `<backend.uri>/api/v1/jz/bm/<name>`), all in the "St
| `jz.bm.meetings`, `jz.bm.class_sessions`, `jz.bm.deadlines` | `jz.bm.access_schedule` | | `jz.bm.meetings`, `jz.bm.class_sessions`, `jz.bm.deadlines` | `jz.bm.access_schedule` |
| `jz.bm.materials`, `jz.bm.tags` | `jz.bm.access_materials` | | `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. 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`). 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. 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.
@@ -213,8 +438,35 @@ Defaults in `config/config.yaml`, read as `jz.bm.<key>`:
| `jz.bm.dashboard_limit` | `5` | Sessions and deadlines on `/dashboard`. | | `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`. | | `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 ## 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 ### bm:seed
```sh ```sh
@@ -260,7 +512,7 @@ The file format (every top-level array is optional, and nullable fields may be l
## Dependencies ## Dependencies
- SummerCMS framework modules: `pact`, `party`, `backpack`, `surf`, `wire`, `bouncer`, `lagoon` (with `lagoon/attach`), `cabana`, `bonfire`, `phrasebook`. - 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. - 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. - GORM and gormigrate. Tests also use testcontainers-go and pgx.

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)
}

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
}

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)
}
}
}

View File

@@ -62,6 +62,7 @@ type SeedSession struct {
EndsAt string `json:"ends_at"` EndsAt string `json:"ends_at"`
Room *string `json:"room"` Room *string `json:"room"`
Kind *string `json:"kind"` Kind *string `json:"kind"`
Lecturer *string `json:"lecturer"`
IsOnline bool `json:"is_online"` IsOnline bool `json:"is_online"`
Notes *string `json:"notes"` Notes *string `json:"notes"`
} }
@@ -377,6 +378,7 @@ func SeedWith(ctx context.Context, db *gorm.DB, f *SeedFile, opts SeedOptions) (
setInstant(&s.EndsAt, end) setInstant(&s.EndsAt, end)
s.Room = nz(in.Room) s.Room = nz(in.Room)
s.Kind = nz(in.Kind) s.Kind = nz(in.Kind)
s.Lecturer = nz(in.Lecturer)
s.IsOnline = in.IsOnline s.IsOnline = in.IsOnline
s.Notes = nz(in.Notes) s.Notes = nz(in.Notes)
}) })

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

@@ -9,3 +9,20 @@ dashboard_limit: 5
# the calendar feed URL and the course links inside the feed. Empty means # the calendar feed URL and the course links inside the feed. Empty means
# the scheme and Host of the request. # the scheme and Host of the request.
public_url: "" 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)
}
}

View File

@@ -11,9 +11,14 @@ import (
"sort" "sort"
"time" "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/bouncer"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/wire" "git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gocloud.dev/blob"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -33,10 +38,49 @@ type Handlers struct {
PerPage int PerPage int
// DashboardLimit is the number of sessions and deadlines on /dashboard. // DashboardLimit is the number of sessions and deadlines on /dashboard.
DashboardLimit int 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 // PublicURL is the absolute base URL of the application
// (jz.bm.public_url), used for the calendar feed URL and the links in // (jz.bm.public_url), used for the calendar feed URL and the links in
// it. Empty means the scheme and Host of the request. // it. Empty means the scheme and Host of the request.
PublicURL string 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 { func (h *Handlers) now() time.Time {

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)
}

View File

@@ -23,7 +23,7 @@ func (c courseRow) counts() courseCounts {
} }
// coursesWithCounts selects courses with their session, reading and // coursesWithCounts selects courses with their session, reading and
// published material counts and the caller's read readings. // visible published material counts and the caller's read readings.
func coursesWithCounts(db *gorm.DB, userID uint, now time.Time) *gorm.DB { func coursesWithCounts(db *gorm.DB, userID uint, now time.Time) *gorm.DB {
return db.Table("jz_bm_courses AS c").Select(`c.*, 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_class_sessions s WHERE s.course_id = c.id) AS sessions_count,
@@ -31,7 +31,7 @@ func coursesWithCounts(db *gorm.DB, userID uint, now time.Time) *gorm.DB {
(SELECT COUNT(*) FROM jz_bm_reading_progress p JOIN jz_bm_readings r ON r.id = p.reading_id (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, 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 (SELECT COUNT(*) FROM jz_bm_materials m WHERE m.course_id = c.id
AND m.published_at IS NOT NULL AND m.published_at <= ?) AS materials_count`, userID, now.UTC()) 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 // Courses answers GET /courses?semester=N: every course in programme order
@@ -103,7 +103,7 @@ func (h *Handlers) Course(w http.ResponseWriter, r *http.Request) {
writeOpaque500(w) writeOpaque500(w)
return return
} }
materials, err := publishedMaterialsOfCourse(db, now, row.ID) materials, err := publishedMaterialsOfCourse(db, now, userID, row.ID)
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
return return

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

@@ -38,24 +38,67 @@ func serve(t *testing.T, h http.HandlerFunc, method, target string, user *bounce
func handlers(h *api.Handlers) map[string]http.HandlerFunc { func handlers(h *api.Handlers) map[string]http.HandlerFunc {
return map[string]http.HandlerFunc{ return map[string]http.HandlerFunc{
"dashboard": h.Dashboard, "dashboard": h.Dashboard,
"courses": h.Courses, "courses": h.Courses,
"course": h.Course, "course": h.Course,
"schedule": h.Schedule, "schedule": h.Schedule,
"meetings": h.Meetings, "meetings": h.Meetings,
"deadlines": h.Deadlines, "deadlines": h.Deadlines,
"readings": h.Readings, "readings": h.Readings,
"mark": h.MarkRead, "mark": h.MarkRead,
"unmark": h.UnmarkRead, "unmark": h.UnmarkRead,
"materials": h.Materials, "own": h.MarkOwned,
"material": h.Material, "unown": h.UnmarkOwned,
"feed": h.CalendarFeed, "materials": h.Materials,
"feed-put": h.UpdateCalendarFeed, "material": h.Material,
"rotate": h.RotateCalendarFeed, "pin": h.PinMaterial,
"feed-del": h.DeleteCalendarFeed, "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) { func TestEveryHandlerNeedsACaller(t *testing.T) {
for name, fn := range handlers(noDB()) { for name, fn := range handlers(noDB()) {
code, body := serve(t, fn, http.MethodGet, "/", nil, map[string]string{"id": "1"}) code, body := serve(t, fn, http.MethodGet, "/", nil, map[string]string{"id": "1"})
@@ -63,6 +106,12 @@ func TestEveryHandlerNeedsACaller(t *testing.T) {
t.Errorf("%s without a principal = %d %v, want 401", name, code, body) 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) { func TestEveryHandlerNeedsADatabase(t *testing.T) {
@@ -73,6 +122,12 @@ func TestEveryHandlerNeedsADatabase(t *testing.T) {
t.Errorf("%s without a database = %d %v, want 503", name, code, body) 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. // A nil DB func is the same as an unpublished database.
code, _ := serve(t, (&api.Handlers{}).Meetings, http.MethodGet, "/", user, nil) code, _ := serve(t, (&api.Handlers{}).Meetings, http.MethodGet, "/", user, nil)
if code != http.StatusServiceUnavailable { if code != http.StatusServiceUnavailable {
@@ -101,7 +156,9 @@ func TestQueryValidation(t *testing.T) {
{"materials page zero", h.Materials, "/?page=0", "page"}, {"materials page zero", h.Materials, "/?page=0", "page"},
{"materials per_page too large", h.Materials, "/?per_page=1000", "per_page"}, {"materials per_page too large", h.Materials, "/?per_page=1000", "per_page"},
{"materials course negative", h.Materials, "/?course=-1", "course"}, {"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 tag too long", h.Materials, "/?tag=" + longTag(), "tag"},
{"materials q too long", h.Materials, "/?q=" + longTag(), "q"},
} }
for _, tc := range cases { for _, tc := range cases {
code, body := serve(t, tc.fn, http.MethodGet, tc.target, user, nil) code, body := serve(t, tc.fn, http.MethodGet, tc.target, user, nil)
@@ -141,6 +198,7 @@ func TestValidQueriesReachTheDatabase(t *testing.T) {
{h.Readings, "/?course=3"}, {h.Readings, "/?course=3"},
{h.Courses, "/?semester=2"}, {h.Courses, "/?semester=2"},
{h.Materials, "/?course=1&tag=geopolityka&type=pdf&page=2&per_page=10"}, {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 { 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) t.Errorf("%s = %d %v, want to pass validation (503 without a database)", tc.target, code, body)

View File

@@ -17,6 +17,7 @@ type courseRef struct {
Code *string `json:"code"` Code *string `json:"code"`
Name string `json:"name"` Name string `json:"name"`
Form string `json:"form"` Form string `json:"form"`
Lecturer *string `json:"lecturer"`
Semester int `json:"semester"` Semester int `json:"semester"`
} }
@@ -24,7 +25,7 @@ func newCourseRef(c *models.Course) *courseRef {
if c == nil { if c == nil {
return nil return nil
} }
return &courseRef{ID: c.ID, Code: c.Code, Name: c.Name, Form: c.Form, Semester: c.Semester} 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. // courseJSON is a course's own fields.
@@ -105,6 +106,7 @@ type sessionJSON struct {
EndsAt string `json:"ends_at"` EndsAt string `json:"ends_at"`
Room *string `json:"room"` Room *string `json:"room"`
Kind *string `json:"kind"` Kind *string `json:"kind"`
Lecturer *string `json:"lecturer"`
Notes *string `json:"notes"` Notes *string `json:"notes"`
IsOnline bool `json:"is_online"` IsOnline bool `json:"is_online"`
Course *courseRef `json:"course"` Course *courseRef `json:"course"`
@@ -119,6 +121,7 @@ func newSessionJSON(s models.ClassSession) sessionJSON {
EndsAt: models.FormatDateTime(s.EndsAt), EndsAt: models.FormatDateTime(s.EndsAt),
Room: s.Room, Room: s.Room,
Kind: s.Kind, Kind: s.Kind,
Lecturer: s.Lecturer,
Notes: s.Notes, Notes: s.Notes,
IsOnline: s.IsOnline, IsOnline: s.IsOnline,
Course: newCourseRef(s.Course), Course: newCourseRef(s.Course),
@@ -165,11 +168,12 @@ func newDeadlinesJSON(rows []models.Deadline) []deadlineJSON {
return out return out
} }
// readingJSON is one reading with the caller's read state. // readingJSON is one reading with the caller's read and owned state.
type readingJSON struct { type readingJSON struct {
ID uint `json:"id"` ID uint `json:"id"`
CourseID uint `json:"course_id"` CourseID uint `json:"course_id"`
Course *courseRef `json:"course"` Course *courseRef `json:"course"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"` Title string `json:"title"`
Author *string `json:"author"` Author *string `json:"author"`
Source *string `json:"source"` Source *string `json:"source"`
@@ -177,6 +181,7 @@ type readingJSON struct {
IsRequired bool `json:"is_required"` IsRequired bool `json:"is_required"`
SortOrder int `json:"sort_order"` SortOrder int `json:"sort_order"`
ReadAt *string `json:"read_at"` ReadAt *string `json:"read_at"`
OwnedAt *string `json:"owned_at"`
} }
// tagJSON is one material tag. // tagJSON is one material tag.
@@ -194,11 +199,12 @@ func newTagsJSON(tags []models.Tag) []tagJSON {
return out return out
} }
// materialListJSON is a published material in a list. // materialListJSON is a published material the caller may see, in a list.
type materialListJSON struct { type materialListJSON struct {
ID uint `json:"id"` ID uint `json:"id"`
CourseID *uint `json:"course_id"` CourseID *uint `json:"course_id"`
Course *courseRef `json:"course"` Course *courseRef `json:"course"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"` Title string `json:"title"`
Type string `json:"type"` Type string `json:"type"`
Source *string `json:"source"` Source *string `json:"source"`
@@ -206,6 +212,13 @@ type materialListJSON struct {
PublishedAt string `json:"published_at"` PublishedAt string `json:"published_at"`
Tags []tagJSON `json:"tags"` Tags []tagJSON `json:"tags"`
FilesCount int64 `json:"files_count"` 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 { func newMaterialListJSON(m models.Material, files int64) materialListJSON {
@@ -213,12 +226,14 @@ func newMaterialListJSON(m models.Material, files int64) materialListJSON {
ID: m.ID, ID: m.ID,
CourseID: m.CourseID, CourseID: m.CourseID,
Course: newCourseRef(m.Course), Course: newCourseRef(m.Course),
MeetingID: m.MeetingID,
Title: m.Title, Title: m.Title,
Type: m.Type, Type: m.Type,
Source: m.Source, Source: m.Source,
URL: m.URL, URL: m.URL,
Tags: newTagsJSON(m.Tags), Tags: newTagsJSON(m.Tags),
FilesCount: files, FilesCount: files,
IsPrivate: m.IsPrivate,
} }
if m.PublishedAt != nil { if m.PublishedAt != nil {
out.PublishedAt = models.FormatDateTime(*m.PublishedAt) out.PublishedAt = models.FormatDateTime(*m.PublishedAt)
@@ -226,11 +241,15 @@ func newMaterialListJSON(m models.Material, files int64) materialListJSON {
return out return out
} }
// materialDetailJSON is a published material with its body and files. // 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 { type materialDetailJSON struct {
materialListJSON materialListJSON
Body *string `json:"body"` Body *string `json:"body"`
Files []fileJSON `json:"files"` Files []fileJSON `json:"files"`
CanManage bool `json:"can_manage"`
Revision uint `json:"revision"`
} }
// fileJSON is one attached file. // fileJSON is one attached file.

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)
}
}

View File

@@ -8,6 +8,7 @@ import (
"io" "io"
"net/http" "net/http"
"slices" "slices"
"strconv"
"strings" "strings"
"time" "time"
"unicode" "unicode"
@@ -15,11 +16,13 @@ import (
usermodels "git.golem15.com/golem15/sm-user-plugin/models" usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer" "git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/lagoon" "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/surf"
"git.golem15.com/golem15/summercms/modules/wire" "git.golem15.com/golem15/summercms/modules/wire"
"git.golem15.com/jakub/sm-bm-plugin/classes" "git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models" "git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause"
) )
// The management API (/api/v1/bm) is what the console commands do, over // The management API (/api/v1/bm) is what the console commands do, over
@@ -134,11 +137,13 @@ func (h *Handlers) ApplySeed(w http.ResponseWriter, r *http.Request) {
} }
// managedMaterialJSON is a material as the management API shows it: drafts // managedMaterialJSON is a material as the management API shows it: drafts
// too, so published_at may be null. // too, so published_at may be null, and private ones with their author and
// the users they are shared with.
type managedMaterialJSON struct { type managedMaterialJSON struct {
ID uint `json:"id"` ID uint `json:"id"`
CourseID *uint `json:"course_id"` CourseID *uint `json:"course_id"`
Course *courseRef `json:"course"` Course *courseRef `json:"course"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"` Title string `json:"title"`
Type string `json:"type"` Type string `json:"type"`
Body *string `json:"body"` Body *string `json:"body"`
@@ -146,12 +151,63 @@ type managedMaterialJSON struct {
URL *string `json:"url"` URL *string `json:"url"`
PublishedAt *string `json:"published_at"` PublishedAt *string `json:"published_at"`
Tags []tagJSON `json:"tags"` 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"`
} }
func newManagedMaterialJSON(m models.Material) managedMaterialJSON { // 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{ out := managedMaterialJSON{
ID: m.ID, CourseID: m.CourseID, Course: newCourseRef(m.Course), Title: m.Title, Type: m.Type, 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), 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 { if m.PublishedAt != nil {
s := models.FormatDateTime(*m.PublishedAt) s := models.FormatDateTime(*m.PublishedAt)
@@ -160,47 +216,78 @@ func newManagedMaterialJSON(m models.Material) managedMaterialJSON {
return out return out
} }
// ManagedCourses answers GET /courses: every course, for the course_id of // ManagedMaterials answers GET /materials?q=&include_body=: every material,
// a material. // drafts and private ones included, newest first. With q (2 to 100
func (h *Handlers) ManagedCourses(w http.ResponseWriter, r *http.Request) { // characters) the engine answers candidates, which are loaded in rank order
db, ok := h.db(w, r) // with at most one snippet each; when the engine cannot answer the request
if !ok { // is a 503. An MCP call gets the bodies only with include_body (see
return // managedMaterialView) and the snippets as plain text.
}
var rows []models.Course
if err := db.Order("semester, sort_order, name, id").Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
out := make([]courseJSON, 0, len(rows))
for _, c := range rows {
out = append(out, newCourseJSON(c))
}
writeData(w, out)
}
// ManagedMaterials answers GET /materials: every material, drafts
// included, newest first.
func (h *Handlers) ManagedMaterials(w http.ResponseWriter, r *http.Request) { 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) db, ok := h.db(w, r)
if !ok { if !ok {
return return
} }
var rows []models.Material var rows []models.Material
if err := preloadMaterial(db).Order("jz_bm_materials.id DESC").Find(&rows).Error; err != nil { 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) writeOpaque500(w)
return return
} }
out := make([]managedMaterialJSON, 0, len(rows)) 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 { for _, m := range rows {
out = append(out, newManagedMaterialJSON(m)) 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) writeData(w, out)
} }
// materialInput is the body of POST /materials. // 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 { type materialInput struct {
CourseID *uint `json:"course_id"` CourseID *uint `json:"course_id"`
MeetingID *uint `json:"meeting_id"`
Title string `json:"title"` Title string `json:"title"`
Type string `json:"type"` Type string `json:"type"`
Body *string `json:"body"` Body *string `json:"body"`
@@ -208,33 +295,81 @@ type materialInput struct {
URL *string `json:"url"` URL *string `json:"url"`
PublishedAt *string `json:"published_at"` PublishedAt *string `json:"published_at"`
Tags *[]string `json:"tags"` 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"`
} }
// UpsertMaterial answers POST /materials: it creates the material, or // materialDraft is a decoded and validated material body, ready to apply.
// updates the one with the same title and course, so sending a document type materialDraft struct {
// twice changes nothing. body, source and url are replaced as sent. in materialInput
// published_at: absent publishes a new material now and keeps an existing // hasPublishedAt tells a sent published_at (null included) from an
// one as it is; null makes a draft; otherwise a timestamp as in the seed // absent one.
// file. tags: absent keeps them; otherwise the list of tag names replaces hasPublishedAt bool
// them, and unknown tags are created. // hasMeetingID tells a sent meeting_id (null included) from an absent
func (h *Handlers) UpsertMaterial(w http.ResponseWriter, r *http.Request) { // 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) raw, ok := body(w, r)
if !ok { if !ok {
return return materialDraft{}, false
} }
var in materialInput 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 := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields() dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil { if err := dec.Decode(&d.in); err != nil {
writeInvalid(w, "invalid JSON: "+err.Error()) return d, err
return
} }
var keys map[string]json.RawMessage var keys map[string]json.RawMessage
_ = json.Unmarshal(raw, &keys) _ = json.Unmarshal(raw, &keys)
_, hasPublishedAt := keys["published_at"] _, 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) in.Title = strings.TrimSpace(in.Title)
errs := map[string][]string{}
if in.Title == "" || len(in.Title) > 255 { if in.Title == "" || len(in.Title) > 255 {
errs["title"] = []string{"The title is required and may not be longer than 255 characters."} errs["title"] = []string{"The title is required and may not be longer than 255 characters."}
} }
@@ -247,15 +382,13 @@ func (h *Handlers) UpsertMaterial(w http.ResponseWriter, r *http.Request) {
if in.URL != nil && len(*in.URL) > 2048 { if in.URL != nil && len(*in.URL) > 2048 {
errs["url"] = []string{"The url may not be longer than 2048 characters."} errs["url"] = []string{"The url may not be longer than 2048 characters."}
} }
var publishedAt *time.Time
if in.PublishedAt != nil { if in.PublishedAt != nil {
t, err := models.ParseDateTime(*in.PublishedAt) t, err := models.ParseDateTime(*in.PublishedAt)
if err != nil { if err != nil {
errs["published_at"] = []string{"The published_at is not a valid date and time."} errs["published_at"] = []string{"The published_at is not a valid date and time."}
} }
publishedAt = &t d.publishedAt = &t
} }
var tags []models.Tag
if in.Tags != nil { if in.Tags != nil {
for _, name := range *in.Tags { for _, name := range *in.Tags {
name = strings.TrimSpace(name) name = strings.TrimSpace(name)
@@ -264,94 +397,354 @@ func (h *Handlers) UpsertMaterial(w http.ResponseWriter, r *http.Request) {
errs["tags"] = []string{"Each tag must be a name of 1 to 100 characters."} errs["tags"] = []string{"Each tag must be a name of 1 to 100 characters."}
break break
} }
if !slices.ContainsFunc(tags, func(t models.Tag) bool { return t.Slug == slug }) { if !slices.ContainsFunc(d.tags, func(t models.Tag) bool { return t.Slug == slug }) {
tags = append(tags, models.Tag{Name: name, Slug: slug}) d.tags = append(d.tags, models.Tag{Name: name, Slug: slug})
} }
} }
} }
db, ok := h.db(w, r)
if !ok {
return
}
if in.CourseID != nil { if in.CourseID != nil {
var n int64 var n int64
if err := db.Model(&models.Course{}).Where("id = ?", *in.CourseID).Count(&n).Error; err != nil { if err := db.Model(&models.Course{}).Where("id = ?", *in.CourseID).Count(&n).Error; err != nil {
writeOpaque500(w) writeOpaque500(w)
return return false
} }
if n == 0 { if n == 0 {
errs["course_id"] = []string{"The selected course_id is invalid."} 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 { if len(errs) > 0 {
writeValidation(w, errs) 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 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 var m models.Material
created := false created, conflict := false, false
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error { err := lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
q := tx.Where("title = ?", in.Title) res := d.identity(tx.Clauses(clause.Locking{Strength: "UPDATE"})).Order("id").Limit(1).Find(&m)
if in.CourseID != nil {
q = q.Where("course_id = ?", *in.CourseID)
} else {
q = q.Where("course_id IS NULL")
}
res := q.Order("id").Limit(1).Find(&m)
if res.Error != nil { if res.Error != nil {
return res.Error return res.Error
} }
created = res.RowsAffected == 0 created = res.RowsAffected == 0
m.CourseID, m.Title, m.Type = in.CourseID, in.Title, in.Type if created {
m.Body, m.Source, m.URL = in.Body, in.Source, in.URL return d.apply(tx, &m, true, h.now(), callerID)
switch {
case hasPublishedAt:
m.PublishedAt = publishedAt
case created:
now := h.now()
m.PublishedAt = &now
} }
if err := tx.Omit("Course", "Tags").Save(&m).Error; err != nil { if staleRevision(d.in.Revision, m.Revision) {
return err conflict = true
}
if in.Tags == nil {
return nil return nil
} }
if err := tx.Where("material_id = ?", m.ID).Delete(&models.MaterialTag{}).Error; err != nil { before, err := models.MaterialContent(tx, m.ID)
if err != nil {
return err return err
} }
for _, t := range tags { if err := d.apply(tx, &m, false, h.now(), callerID); err != nil {
var tag models.Tag return err
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 return h.revise(ctx, tx, m.ID, before)
}) })
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
return return
} }
var out models.Material if conflict {
if err := preloadMaterial(db).First(&out, m.ID).Error; err != nil { writeConflict(w, r, db, m.ID)
writeOpaque500(w)
return return
} }
h.MaterialIndex.Sync(r.Context(), db, m.ID)
status := http.StatusOK status := http.StatusOK
if created { if created {
status = http.StatusCreated status = http.StatusCreated
} }
wire.WriteJSON(w, status, map[string]any{"data": newManagedMaterialJSON(out), "created": created}) 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}. // DeleteMaterial answers DELETE /materials/{id}.
@@ -365,15 +758,36 @@ func (h *Handlers) DeleteMaterial(w http.ResponseWriter, r *http.Request) {
writeNotFound(w) writeNotFound(w)
return return
} }
res := db.Where("id = ?", id).Delete(&models.Material{}) var keys []string
if res.Error != nil { 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) writeOpaque500(w)
return return
} case !found:
if res.RowsAffected == 0 {
writeNotFound(w) writeNotFound(w)
return 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) w.WriteHeader(http.StatusNoContent)
} }
@@ -398,3 +812,123 @@ func slugify(name string) string {
} }
return b.String() 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

@@ -1,14 +1,17 @@
package api package api
import ( import (
"context"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"git.golem15.com/golem15/summercms/modules/beachcomber"
"git.golem15.com/golem15/summercms/modules/lagoon" "git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach" "git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/surf" "git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/models" "git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -21,15 +24,19 @@ func published(q *gorm.DB, now time.Time) *gorm.DB {
// materialFilter holds the validated filters of /materials. // materialFilter holds the validated filters of /materials.
type materialFilter struct { type materialFilter struct {
CourseID uint CourseID uint
Tag string MeetingID uint
Type string Tag string
Type string
} }
func (f materialFilter) apply(q *gorm.DB) *gorm.DB { func (f materialFilter) apply(q *gorm.DB) *gorm.DB {
if f.CourseID != 0 { if f.CourseID != 0 {
q = q.Where("jz_bm_materials.course_id = ?", f.CourseID) 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 != "" { if f.Type != "" {
q = q.Where("jz_bm_materials.type = ?", f.Type) q = q.Where("jz_bm_materials.type = ?", f.Type)
} }
@@ -44,27 +51,43 @@ 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") }) return q.Preload("Course").Preload("Tags", func(db *gorm.DB) *gorm.DB { return db.Order("jz_bm_tags.name") })
} }
// listMaterials returns one page of published materials, newest first. // listMaterials returns one page of the published materials userID may
func listMaterials(db *gorm.DB, now time.Time, f materialFilter, page, perPage int) ([]materialListJSON, int64, error) { // see. With ids nil the page lists the caller's pinned materials first
q := f.apply(published(db.Model(&models.Material{}), now)) // (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 var total int64
if err := q.Count(&total).Error; err != nil { if err := q.Count(&total).Error; err != nil {
return nil, 0, err 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 var rows []models.Material
err := preloadMaterial(f.apply(published(db, now))). err := rowsQ.Offset((page - 1) * perPage).Limit(perPage).Find(&rows).Error
Order("jz_bm_materials.published_at DESC, jz_bm_materials.id DESC").
Offset((page - 1) * perPage).Limit(perPage).
Find(&rows).Error
if err != nil { if err != nil {
return nil, 0, err return nil, nil, 0, err
} }
out, err := materialsJSON(db, rows) out, err := materialsJSON(db, userID, rows)
return out, total, err return out, rows, total, err
} }
// materialsJSON builds list rows with their file counts. // materialsJSON builds list rows with their file counts and userID's own
func materialsJSON(db *gorm.DB, rows []models.Material) ([]materialListJSON, error) { // pins.
func materialsJSON(db *gorm.DB, userID uint, rows []models.Material) ([]materialListJSON, error) {
ids := make([]string, 0, len(rows)) ids := make([]string, 0, len(rows))
for _, m := range rows { for _, m := range rows {
ids = append(ids, strconv.FormatUint(uint64(m.ID), 10)) ids = append(ids, strconv.FormatUint(uint64(m.ID), 10))
@@ -87,42 +110,109 @@ func materialsJSON(db *gorm.DB, rows []models.Material) ([]materialListJSON, err
counts[row.AttachmentID] = row.Count counts[row.AttachmentID] = row.Count
} }
} }
pinned, err := pinnedMaterialIDs(db, userID, materialIDs(rows))
if err != nil {
return nil, err
}
out := make([]materialListJSON, 0, len(rows)) out := make([]materialListJSON, 0, len(rows))
for _, m := range rows { for _, m := range rows {
out = append(out, newMaterialListJSON(m, counts[strconv.FormatUint(uint64(m.ID), 10)])) row := newMaterialListJSON(m, counts[strconv.FormatUint(uint64(m.ID), 10)])
row.Pinned = pinned[m.ID]
out = append(out, row)
} }
return out, nil return out, nil
} }
// Materials answers GET /materials?course=&tag=&type=&page=&per_page=: a // Materials answers GET /materials?q=&course=&meeting=&tag=&type=&page=&per_page=:
// page of published materials in the {data, meta} shape of lagoon.Paginate. // 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) { func (h *Handlers) Materials(w http.ResponseWriter, r *http.Request) {
if _, ok := h.caller(w, r); !ok { userID, ok := h.caller(w, r)
if !ok {
return return
} }
in := query(r, "course", "tag", "type", "page", "per_page") in := query(r, "q", "course", "meeting", "tag", "type", "page", "per_page")
if !h.validate(w, r, in, materialsRules) { if !h.validate(w, r, in, materialsRules) {
return 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) db, ok := h.db(w, r)
if !ok { if !ok {
return return
} }
filter := materialFilter{CourseID: uintParam(in, "course"), Tag: strings.TrimSpace(str(in, "tag")), Type: str(in, "type")}
page := min(intParam(in, "page", 1), 100000) page := min(intParam(in, "page", 1), 100000)
perPage := intParam(in, "per_page", h.perPage()) perPage := intParam(in, "per_page", h.perPage())
rows, total, err := listMaterials(db, h.now(), filter, page, 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 { if err != nil {
writeOpaque500(w) writeOpaque500(w)
return return
} }
writeJSONPage(w, lagoon.Paginate(rows, page, perPage, total)) 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))
} }
// Material answers GET /materials/{id}: one published material with its // attachSnippets sets the snippet of each list row from its Hit and, for a
// body, tags and files. A draft or a future publication is a 404. // 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) { func (h *Handlers) Material(w http.ResponseWriter, r *http.Request) {
if _, ok := h.caller(w, r); !ok { userID, ok := h.caller(w, r)
if !ok {
return return
} }
db, ok := h.db(w, r) db, ok := h.db(w, r)
@@ -130,32 +220,47 @@ func (h *Handlers) Material(w http.ResponseWriter, r *http.Request) {
return return
} }
id, ok := surf.IntParam(r, "id") id, ok := surf.IntParam(r, "id")
if !ok { if !ok || id <= 0 {
writeNotFound(w) writeNotFound(w)
return return
} }
var m models.Material out, found, err := h.loadMaterialDetail(r.Context(), db, userID, uint(id))
res := preloadMaterial(published(db, h.now())).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m) if err != nil {
if res.Error != nil {
writeOpaque500(w) writeOpaque500(w)
return return
} }
if res.RowsAffected == 0 { if !found {
writeNotFound(w) writeNotFound(w)
return 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 var files []attach.File
err := db.Where("attachment_type = ? AND attachment_id = ? AND field = ?", m.MorphName(), strconv.FormatUint(uint64(m.ID), 10), models.MaterialFilesField). err := db.Where("attachment_type = ? AND attachment_id = ? AND field = ?", m.MorphName(), strconv.FormatUint(uint64(m.ID), 10), models.MaterialFilesField).
Order("sort_order, id"). Order("sort_order, id").
Find(&files).Error Find(&files).Error
if err != nil { if err != nil {
writeOpaque500(w) return materialDetailJSON{}, false, err
return
} }
out := materialDetailJSON{ out := materialDetailJSON{
materialListJSON: newMaterialListJSON(m, int64(len(files))), materialListJSON: newMaterialListJSON(m, int64(len(files))),
Body: m.Body, Body: m.Body,
Files: make([]fileJSON, 0, len(files)), Files: make([]fileJSON, 0, len(files)),
Revision: m.Revision,
} }
for i := range files { for i := range files {
f := &files[i] f := &files[i]
@@ -165,19 +270,32 @@ func (h *Handlers) Material(w http.ResponseWriter, r *http.Request) {
out.Files = append(out.Files, fileJSON{ID: f.ID, URL: f.URL(), Name: f.FileName, Size: f.FileSize, Mime: f.ContentType}) 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)) out.FilesCount = int64(len(out.Files))
writeData(w, out) 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, newest // publishedMaterialsOfCourse lists a course's published materials that
// first, for /courses/{id}. // userID may see, newest first, for /courses/{id}. Rows carry the caller's
func publishedMaterialsOfCourse(db *gorm.DB, now time.Time, courseID uint) ([]materialListJSON, error) { // pins but keep this order.
func publishedMaterialsOfCourse(db *gorm.DB, now time.Time, userID uint, courseID uint) ([]materialListJSON, error) {
var rows []models.Material var rows []models.Material
err := preloadMaterial(published(db, now)). err := preloadMaterial(visibleMaterials(db, now, userID)).
Where("jz_bm_materials.course_id = ?", courseID). Where("jz_bm_materials.course_id = ?", courseID).
Order("jz_bm_materials.published_at DESC, jz_bm_materials.id DESC"). Order("jz_bm_materials.published_at DESC, jz_bm_materials.id DESC").
Find(&rows).Error Find(&rows).Error
if err != nil { if err != nil {
return nil, err return nil, err
} }
return materialsJSON(db, rows) 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)
}
})
}

View File

@@ -32,10 +32,16 @@ var (
} }
materialsRules = []lagoon.RequestRule{ materialsRules = []lagoon.RequestRule{
{Field: "course", Rules: lagoon.ParseRules("nullable|integer|min:1")}, {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: "tag", Rules: lagoon.ParseRules("nullable|string|max:100")},
{Field: "type", Rules: append(lagoon.ParseRules("nullable"), lagoon.In(models.MaterialTypes...))}, {Field: "type", Rules: append(lagoon.ParseRules("nullable"), lagoon.In(models.MaterialTypes...))},
{Field: "page", Rules: lagoon.ParseRules("nullable|integer|min:1")}, {Field: "page", Rules: lagoon.ParseRules("nullable|integer|min:1")},
{Field: "per_page", Rules: lagoon.ParseRules("nullable|integer|between:1,100")}, {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")},
} }
) )

View File

@@ -9,19 +9,22 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// readingRow is a reading joined with the caller's progress row. // readingRow is a reading joined with the caller's progress and ownership
// rows.
type readingRow struct { type readingRow struct {
models.Reading `gorm:"embedded"` models.Reading `gorm:"embedded"`
ReadAt *time.Time `gorm:"column:read_at"` 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 // listReadings returns the readings, optionally of one course, in course and
// reading order, each with the caller's read_at. // reading order, each with the caller's read_at and owned_at.
func listReadings(db *gorm.DB, userID, courseID uint) ([]readingJSON, error) { func listReadings(db *gorm.DB, userID, courseID uint) ([]readingJSON, error) {
q := db.Table("jz_bm_readings AS r"). q := db.Table("jz_bm_readings AS r").
Select("r.*, p.read_at"). Select("r.*, p.read_at, o.owned_at").
Joins("JOIN jz_bm_courses c ON c.id = r.course_id"). 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_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 { if courseID != 0 {
q = q.Where("r.course_id = ?", courseID) q = q.Where("r.course_id = ?", courseID)
} }
@@ -39,6 +42,7 @@ func listReadings(db *gorm.DB, userID, courseID uint) ([]readingJSON, error) {
ID: row.ID, ID: row.ID,
CourseID: idOf(row.CourseID), CourseID: idOf(row.CourseID),
Course: newCourseRef(courses[idOf(row.CourseID)]), Course: newCourseRef(courses[idOf(row.CourseID)]),
MeetingID: row.MeetingID,
Title: row.Title, Title: row.Title,
Author: row.Author, Author: row.Author,
Source: row.Source, Source: row.Source,
@@ -50,6 +54,10 @@ func listReadings(db *gorm.DB, userID, courseID uint) ([]readingJSON, error) {
s := models.FormatDateTime(*row.ReadAt) s := models.FormatDateTime(*row.ReadAt)
item.ReadAt = &s item.ReadAt = &s
} }
if row.OwnedAt != nil {
s := models.FormatDateTime(*row.OwnedAt)
item.OwnedAt = &s
}
out = append(out, item) out = append(out, item)
} }
return out, nil return out, nil
@@ -185,3 +193,62 @@ func (h *Handlers) UnmarkRead(w http.ResponseWriter, r *http.Request) {
} }
writeData(w, progressJSON{ReadingID: readingID}) 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})
}

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

@@ -33,13 +33,7 @@ func (classSessionsAdmin) RequiredPermissions() []string {
func (classSessionsAdmin) AdminFieldRelations() []cabana.FieldRelationContract { func (classSessionsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{ return []cabana.FieldRelationContract{
courseRelation("course_id"), courseRelation("course_id"),
{ meetingRelation(),
Field: "meeting",
Kind: "belongsTo",
NewRelated: func() any { return &models.Meeting{} },
ForeignKey: "meeting_id",
LabelColumn: "number",
},
} }
} }

View File

@@ -54,3 +54,14 @@ func courseRelation(foreignKey string) cabana.FieldRelationContract {
LabelColumn: "name", 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",
}
}

View File

@@ -3,6 +3,7 @@
package controllers package controllers
import ( import (
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana" "git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/models" "git.golem15.com/jakub/sm-bm-plugin/models"
@@ -29,11 +30,15 @@ func (materialsAdmin) RequiredPermissions() []string {
return []string{PermMaterials} return []string{PermMaterials}
} }
// AdminFieldRelations binds the course picker and the tags. The files field // AdminFieldRelations binds the course and meeting pickers, the tags, the
// is bound by models.Material.AttachRelations. // 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 { func (materialsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{ return []cabana.FieldRelationContract{
courseRelation("course_id"), courseRelation("course_id"),
meetingRelation(),
{ {
Field: "tags", Field: "tags",
Kind: "belongsToMany", Kind: "belongsToMany",
@@ -43,6 +48,22 @@ func (materialsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
RelatedForeignKey: "tag_id", RelatedForeignKey: "tag_id",
LabelColumn: "name", 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",
},
} }
} }

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)
}
}

View File

@@ -29,9 +29,9 @@ func (readingsAdmin) RequiredPermissions() []string {
return []string{PermCourses} return []string{PermCourses}
} }
// AdminFieldRelations binds the course picker. // AdminFieldRelations binds the course and meeting pickers.
func (readingsAdmin) AdminFieldRelations() []cabana.FieldRelationContract { func (readingsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{courseRelation("course_id")} return []cabana.FieldRelationContract{courseRelation("course_id"), meetingRelation()}
} }
// ReadingsController returns the jz.bm.readings admin controller. // ReadingsController returns the jz.bm.readings admin controller.

71
go.mod
View File

@@ -3,21 +3,62 @@ module git.golem15.com/jakub/sm-bm-plugin
go 1.27.0 go 1.27.0
require ( require (
git.golem15.com/golem15/sm-user-plugin v0.0.0 git.golem15.com/golem15/sm-chat-plugin v0.1.3
git.golem15.com/golem15/summercms v0.0.0 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/jackc/pgx/v5 v5.10.0
github.com/testcontainers/testcontainers-go v0.44.0 github.com/testcontainers/testcontainers-go v0.44.0
github.com/testcontainers/testcontainers-go/modules/postgres 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 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 dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/Microsoft/go-winio v0.6.2 // 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/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.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 v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect github.com/containerd/log v0.1.0 // indirect
@@ -27,6 +68,7 @@ require (
github.com/distribution/reference v0.6.0 // indirect github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.7.0 // indirect github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.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/ebitengine/purego v0.10.1 // indirect
github.com/felixge/httpsnoop v1.1.0 // 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
@@ -40,8 +82,11 @@ require (
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/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/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/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/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
@@ -57,9 +102,14 @@ require (
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/leodido/go-urn v1.5.0 // indirect
github.com/lib/pq v1.12.3 // 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/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
github.com/magiconair/properties v1.8.10 // 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/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect github.com/moby/go-archive v0.2.0 // indirect
@@ -70,16 +120,22 @@ require (
github.com/moby/sys/user v0.4.0 // indirect github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // 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/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // 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 v0.47.0 // indirect
github.com/riverqueue/river/riverdriver 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/riverdatabasesql v0.47.0 // indirect
github.com/riverqueue/river/riverdriver/riverpgxv5 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/rivershared v0.47.0 // indirect
github.com/riverqueue/river/rivertype 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/shirou/gopsutil/v4 v4.26.6 // indirect
github.com/sirupsen/logrus v1.9.4 // 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
@@ -92,6 +148,8 @@ require (
github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.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 github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect
@@ -101,23 +159,28 @@ require (
go.opentelemetry.io/otel/sdk 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/sdk/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace 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
gocloud.dev v0.46.0 // 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/image v0.46.0 // indirect
golang.org/x/net v0.58.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/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
golang.org/x/time v0.15.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.272.0 // indirect google.golang.org/api v0.272.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
google.golang.org/grpc v1.79.3 // indirect google.golang.org/grpc v1.79.3 // indirect
google.golang.org/protobuf v1.36.11 // indirect google.golang.org/protobuf v1.36.11 // indirect
gorm.io/driver/postgres v1.6.3 // 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-user-plugin => ../../golem15/user
replace git.golem15.com/golem15/sm-chat-plugin => ../../golem15/chat
replace git.golem15.com/golem15/sm-chatchannels-plugin => ../../golem15/chatchannels

104
go.sum
View File

@@ -1,5 +1,13 @@
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= 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 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= 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 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM=
@@ -28,8 +36,14 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc= 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 h1:0s6TxfCu2KHkkZPnBfsQ2y5qia0jl3MMrmBhu3nCOYk=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc= 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 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 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 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
@@ -68,10 +82,50 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 h1:ErklX/7uhSbkAAeyQD/Y1OoQ9hO3
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3/go.mod h1:ULe4HCzfKPiR6R3HEurE3b1upEkuk8AkMrOKtaOxKO8= 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 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= 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 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= 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=
@@ -96,6 +150,8 @@ github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf
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 v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
@@ -139,6 +195,14 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 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 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 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 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= 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=
@@ -149,6 +213,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA
github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= 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 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE=
github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA= 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 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0=
@@ -167,6 +233,8 @@ 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=
@@ -183,16 +251,26 @@ 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/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 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= 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 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o= 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=
@@ -213,6 +291,10 @@ 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=
@@ -224,6 +306,8 @@ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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 h1:j8HOEyiOE8gRRhVS2wllKams372TH1WWiH6xCakXHqc=
github.com/riverqueue/river v0.47.0/go.mod h1:Wgmwx475ZBd8lQnNrJgyG2DWH7BfyNiSAtv0rC9bJBQ= 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 h1:qU8VkjdMl9plqeRg57SxsDUM/i/eECaSYejZ7HynC60=
@@ -236,9 +320,15 @@ github.com/riverqueue/river/rivershared v0.47.0 h1:jdtFsBexCvLqTXf8wnDnGXvB/eeOt
github.com/riverqueue/river/rivershared v0.47.0/go.mod h1:w8Pi1T+6ypyko5/hs9Mv7IIIKo4fAL9eXYnkVV/Y418= 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 h1:SzNavtLGR4nMT1QkrEYQ7n96OMatYsn/z3aJWhewmv0=
github.com/riverqueue/river/rivertype v0.47.0/go.mod h1:XKkcRQR6zm8RR/JQa1Q2ywpj8uXQu21quPa4Lpw1Xhw= 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 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= 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=
@@ -277,10 +367,18 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
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 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ=
@@ -301,6 +399,8 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRk
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= 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 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= 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=
@@ -310,6 +410,8 @@ gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM= 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.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 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
@@ -332,6 +434,8 @@ 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 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= 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 h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= 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 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=

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

@@ -23,6 +23,8 @@ common:
sort_order: Sort order sort_order: Sort order
created_at: Created created_at: Created
none: — none — none: — none —
meeting: For meeting
meeting_comment: The dashboard suggests this item before that meeting.
forms: forms:
wyklad: Lecture wyklad: Lecture
cwiczenia: Tutorial cwiczenia: Tutorial
@@ -59,6 +61,8 @@ sessions:
ends_at: Ends ends_at: Ends
room: Room room: Room
kind: Kind kind: Kind
lecturer: Lecturer
lecturer_comment: Only when it differs from the course lecturer.
is_online: Online is_online: Online
deadlines: deadlines:
title: Deadlines title: Deadlines
@@ -76,6 +80,7 @@ readings:
form: Reading form: Reading
author: Author author: Author
is_required: Required is_required: Required
owned: Owned
materials: materials:
title: Materials title: Materials
form: Material form: Material
@@ -86,6 +91,12 @@ materials:
files: Files files: Files
published_at_comment: Leave empty for a draft that students do not see. published_at_comment: Leave empty for a draft that students do not see.
tags: Tags 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: material_types:
pdf: PDF pdf: PDF
notatka: Note notatka: Note

View File

@@ -23,6 +23,8 @@ common:
sort_order: Kolejność sort_order: Kolejność
created_at: Utworzono created_at: Utworzono
none: — brak — none: — brak —
meeting: Na zjazd
meeting_comment: Pulpit poleca tę pozycję przed tym zjazdem.
forms: forms:
wyklad: Wykład wyklad: Wykład
cwiczenia: Ćwiczenia cwiczenia: Ćwiczenia
@@ -59,6 +61,8 @@ sessions:
ends_at: Koniec ends_at: Koniec
room: Sala room: Sala
kind: Rodzaj kind: Rodzaj
lecturer: Prowadzący
lecturer_comment: Tylko gdy inny niż prowadzący przedmiotu.
is_online: Zdalnie is_online: Zdalnie
deadlines: deadlines:
title: Terminarz title: Terminarz
@@ -76,6 +80,7 @@ readings:
form: Lektura form: Lektura
author: Autor author: Autor
is_required: Obowiązkowa is_required: Obowiązkowa
owned: Mam
materials: materials:
title: Materiały title: Materiały
form: Materiał form: Materiał
@@ -86,6 +91,12 @@ materials:
files: Pliki files: Pliki
published_at_comment: Puste pole to szkic, niewidoczny dla studentów. published_at_comment: Puste pole to szkic, niewidoczny dla studentów.
tags: Tagi 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: material_types:
pdf: PDF pdf: PDF
notatka: Notatka notatka: Notatka

View File

@@ -1,13 +1,20 @@
package bm_test package bm_test
import ( import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strconv"
"strings" "strings"
"testing" "testing"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes" userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/surf" "git.golem15.com/golem15/summercms/modules/surf"
"gocloud.dev/blob"
_ "gocloud.dev/blob/memblob"
) )
func TestManagementAPIUsesSharedTokenAndCurrentUserPermissions(t *testing.T) { func TestManagementAPIUsesSharedTokenAndCurrentUserPermissions(t *testing.T) {
@@ -63,3 +70,481 @@ RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatalf("request after permission revocation = %d %s", rec.Code, rec.Body.String()) 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)
}
}

View File

@@ -0,0 +1,278 @@
package bm_test
import (
"bytes"
"encoding/json"
"image"
"image/png"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gocloud.dev/blob"
_ "gocloud.dev/blob/memblob"
)
// TestMaterialEditAgainstDatabase checks the author's student routes
// (D-07..D-11, D-16) against Postgres: who may edit (the author; 403 for
// another manager or a non-manager; 404 for what the caller cannot see),
// the revision check with the server version in the 409, the edit body's
// rules, that an edit keeps the course and the author, the tag dictionary,
// unpublish to drafts and the editor image upload with its refusals.
func TestMaterialEditAgainstDatabase(t *testing.T) {
app, plugins, gdb := migrated(t)
seedFixture(t, plugins, "testdata/seed.example.json")
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)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatalf("Assemble: %v", err)
}
authorID := createUser(t, gdb, "edit-author@example.test")
otherID := createUser(t, gdb, "edit-other@example.test")
plainID := createUser(t, gdb, "edit-plain@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-edit', '{"jz.bm.access_materials":1}', NOW(), NOW())
RETURNING id`).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
for _, uid := range []uint{authorID, otherID} {
if err := gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, uid, groupID).Error; err != nil {
t.Fatal(err)
}
}
author := apiClient{t: t, h: h, token: tokenFor(t, authorID)}
other := apiClient{t: t, h: h, token: tokenFor(t, otherID)}
plain := apiClient{t: t, h: h, token: tokenFor(t, plainID)}
const base = "/_bm/api/v1"
for _, tag := range [][2]string{{"Lektura", "lektura"}, {"Cyber", "cyber"}, {"Wojna", "wojna"}, {"Pokój", "pokoj"}, {"Prawo", "prawo"}} {
if err := gdb.Exec(`INSERT INTO jz_bm_tags (name, slug, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`, tag[0], tag[1]).Error; err != nil {
t.Fatal(err)
}
}
var course models.Course
if err := gdb.Order("id").Take(&course).Error; err != nil {
t.Fatal(err)
}
var meeting models.Meeting
if err := gdb.Order("number").Take(&meeting).Error; err != nil {
t.Fatal(err)
}
insert := func(title string, private, draft bool, authorUserID *uint) uint {
t.Helper()
published := "NOW() - INTERVAL '1 day'"
if draft {
published = "NULL"
}
var id uint
err := gdb.Raw(`INSERT INTO jz_bm_materials (course_id, title, type, body, published_at, is_private, author_user_id)
VALUES (?, ?, 'notatka', 'Stara treść', `+published+`, ?, ?) RETURNING id`, course.ID, title, private, authorUserID).Scan(&id).Error
if err != nil {
t.Fatal(err)
}
return id
}
own := insert("Notatka autora", false, false, &authorID)
othersPrivate := insert("Prywatna innego", true, false, &otherID)
draft := insert("Szkic autora", false, true, &authorID)
insert("Zajęty tytuł", false, false, &authorID)
edit := func(revision uint, mutate func(map[string]any)) string {
t.Helper()
b := map[string]any{
"revision": revision,
"title": "Nowy tytuł",
"type": "notatka",
"body": "\r\n# Nagłówek\r\n\r\ntekst\r\n\r\n",
"source": nil,
"url": "https://example.test/a",
"meeting_id": meeting.ID,
"tags": []string{"Lektura", "cyber"},
}
if mutate != nil {
mutate(b)
}
raw, err := json.Marshal(b)
if err != nil {
t.Fatal(err)
}
return string(raw)
}
path := func(id uint) string { return base + "/materials/" + jsonID(id) }
row := func(id uint) models.Material {
t.Helper()
var m models.Material
if err := gdb.Where("id = ?", id).Take(&m).Error; err != nil {
t.Fatal(err)
}
return m
}
// The author saves: revision +1, the body normalised, course and author
// kept, the meeting and tags as sent.
saved := obj(author.want(http.StatusOK, "PUT", path(own), edit(1, nil))["data"])
if saved["revision"] != float64(2) || saved["body"] != "# Nagłówek\n\ntekst\n" || saved["title"] != "Nowy tytuł" {
t.Errorf("saved = %v, want revision 2 and the normalised body", saved)
}
if id(saved["course_id"]) != jsonID(course.ID) || id(saved["meeting_id"]) != jsonID(meeting.ID) {
t.Errorf("saved course/meeting = %v/%v", saved["course_id"], saved["meeting_id"])
}
if tags, _ := saved["tags"].([]any); len(tags) != 2 {
t.Errorf("saved tags = %v, want 2", saved["tags"])
}
if m := row(own); m.AuthorUserID == nil || *m.AuthorUserID != authorID || m.CourseID == nil || *m.CourseID != course.ID || m.PublishedAt == nil || m.IsPrivate {
t.Errorf("row after the edit = %+v, want author, course and publication kept", m)
}
var tagCount int64
gdb.Model(&models.Tag{}).Count(&tagCount)
if tagCount != 5 {
t.Errorf("tags = %d, want the 5 of the dictionary (none created)", tagCount)
}
// A stale revision: 409 with the server version, nothing written.
conflict := author.want(http.StatusConflict, "PUT", path(own), edit(1, func(b map[string]any) { b["body"] = "Inna treść" }))
if conflict["revision"] != float64(2) || conflict["error"] != true || conflict["updated_at"] == nil {
t.Errorf("409 = %v, want revision 2", conflict)
}
if d := obj(conflict["data"]); d["body"] != "# Nagłówek\n\ntekst\n" || d["revision"] != float64(2) {
t.Errorf("409 data = %v, want the stored body", d)
}
if m := row(own); m.Body == nil || *m.Body != "# Nagłówek\n\ntekst\n" {
t.Errorf("body after the 409 = %v", m.Body)
}
// Who may write: 403 for what the caller sees but may not manage, 404
// for what they cannot see.
other.want(http.StatusForbidden, "PUT", path(own), edit(2, nil))
plain.want(http.StatusForbidden, "PUT", path(own), edit(2, nil))
author.want(http.StatusNotFound, "PUT", path(othersPrivate), edit(1, nil))
author.want(http.StatusNotFound, "PUT", path(draft), edit(1, nil))
author.want(http.StatusNotFound, "PUT", path(999999), edit(1, nil))
// The edit body's rules.
for name, mutate := range map[string]func(map[string]any){
"5 tags": func(b map[string]any) { b["tags"] = []string{"lektura", "cyber", "wojna", "pokoj", "prawo"} },
"unknown tag": func(b map[string]any) { b["tags"] = []string{"nieznany"} },
"ftp url": func(b map[string]any) { b["url"] = "ftp://example.test/a" },
"missing key": func(b map[string]any) { delete(b, "title") },
"published_at": func(b map[string]any) { b["published_at"] = nil },
"course_id": func(b map[string]any) { b["course_id"] = course.ID },
"null tags": func(b map[string]any) { b["tags"] = nil },
"no revision": func(b map[string]any) { delete(b, "revision") },
"bad meeting": func(b map[string]any) { b["meeting_id"] = 999999 },
"taken title": func(b map[string]any) { b["title"] = "Zajęty tytuł" },
} {
code, out := author.send("PUT", path(own), edit(2, mutate))
if code != http.StatusUnprocessableEntity {
t.Errorf("%s = %d %v, want 422", name, code, out)
}
}
if m := row(own); m.Revision != 2 {
t.Errorf("revision after the refused edits = %d, want 2", m.Revision)
}
// An unchanged save keeps the revision.
if again := obj(author.want(http.StatusOK, "PUT", path(own), edit(2, nil))["data"]); again["revision"] != float64(2) {
t.Errorf("unchanged save revision = %v, want 2", again["revision"])
}
// The tag dictionary: managers only, by name.
var names []string
for _, tag := range list(author.ok("GET", base+"/tags")) {
names = append(names, tag["name"].(string))
}
if strings.Join(names, ",") != "Cyber,Lektura,Pokój,Prawo,Wojna" {
t.Errorf("tags = %v, want the dictionary by name", names)
}
plain.want(http.StatusForbidden, "GET", base+"/tags", "")
// Editor images: one PNG per request, public, no revision bump.
pngBytes := func() []byte {
t.Helper()
var buf bytes.Buffer
if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}()
upload := func(c apiClient, materialID uint, name string, content []byte) (int, map[string]any) {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, err := mw.CreateFormFile("file", name)
if err != nil {
t.Fatal(err)
}
fw.Write(content)
mw.Close()
req := httptest.NewRequest("POST", path(materialID)+"/images", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+c.token)
rec := httptest.NewRecorder()
c.h.ServeHTTP(rec, req)
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("upload %s = %d, not JSON: %s", name, rec.Code, rec.Body.String())
}
return rec.Code, out
}
code, out := upload(author, own, "obraz.png", pngBytes)
if code != http.StatusCreated {
t.Fatalf("PNG upload = %d %v, want 201", code, out)
}
if img := obj(out["data"]); !strings.HasPrefix(img["url"].(string), "/storage/app/uploads/public/") || img["mime"] != "image/png" || img["name"] != "obraz.png" {
t.Errorf("uploaded image = %v", img)
}
if m := row(own); m.Revision != 2 {
t.Errorf("revision after the upload = %d, want 2", m.Revision)
}
if code, out := upload(author, own, "image.png", []byte("to nie jest obrazek")); code != http.StatusUnprocessableEntity || out["reason"] != "type" {
t.Errorf("text as image.png = %d %v, want 422 reason type", code, out)
}
if code, out := upload(author, own, "rysunek.svg", []byte(`<svg xmlns="http://www.w3.org/2000/svg"/>`)); code != http.StatusUnprocessableEntity || out["reason"] != "type" {
t.Errorf("SVG = %d %v, want 422 reason type", code, out)
}
if code, out := upload(other, own, "obraz.png", pngBytes); code != http.StatusForbidden {
t.Errorf("another manager's upload = %d %v, want 403", code, out)
}
if code, out := upload(author, othersPrivate, "obraz.png", pngBytes); code != http.StatusNotFound {
t.Errorf("upload to an invisible material = %d %v, want 404", code, out)
}
for i := 1; i < 20; i++ {
if code, out := upload(author, own, "obraz.png", pngBytes); code != http.StatusCreated {
t.Fatalf("upload %d = %d %v, want 201", i+1, code, out)
}
}
if code, out := upload(author, own, "obraz.png", pngBytes); code != http.StatusUnprocessableEntity || out["reason"] != "count" {
t.Errorf("21st file = %d %v, want 422 reason count", code, out)
}
if d := obj(author.ok("GET", path(own))["data"]); d["files_count"] != float64(20) {
t.Errorf("files_count = %v, want 20", d["files_count"])
}
// Unpublish: a draft, 404 even for the author afterwards, revision kept.
other.want(http.StatusForbidden, "POST", path(own)+"/unpublish", "")
author.want(http.StatusNotFound, "POST", path(othersPrivate)+"/unpublish", "")
if code, _ := author.send("POST", path(own)+"/unpublish", ""); code != http.StatusNoContent {
t.Fatalf("unpublish = %d, want 204", code)
}
author.want(http.StatusNotFound, "GET", path(own), "")
if m := row(own); m.PublishedAt != nil || m.Revision != 2 || m.AuthorUserID == nil || *m.AuthorUserID != authorID {
t.Errorf("row after unpublish = %+v, want a draft at revision 2 with its author", m)
}
author.want(http.StatusNotFound, "POST", path(own)+"/unpublish", "")
author.want(http.StatusNotFound, "PUT", path(own), edit(2, nil))
}

View File

@@ -0,0 +1,178 @@
package bm_test
import (
"bytes"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"os/exec"
"slices"
"strconv"
"strings"
"testing"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/internal/pdftest"
"git.golem15.com/jakub/sm-bm-plugin/internal/searchtest"
"git.golem15.com/jakub/sm-bm-plugin/jobs"
"gocloud.dev/blob"
_ "gocloud.dev/blob/memblob"
)
// TestMaterialFileTextAgainstDatabase drives file search end to end against
// a migrated database and a Typesense stand-in: an inline PDF attach queues
// one extraction job in its transaction, the extraction stores the PDF's
// text, the sync sends it as file_texts, and a detach drops the text row
// (cascade) and resyncs the document without it.
func TestMaterialFileTextAgainstDatabase(t *testing.T) {
stub := &searchtest.Stub{}
app, plugins, gdb := migratedWith(t, searchtest.Start(t, stub)...)
if _, err := exec.LookPath("pdftotext"); err != nil {
t.Skip("pdftotext is not installed (poppler-utils)")
}
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)
}
handler, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
managerID := createUser(t, gdb, "files-manager@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 (?, ?)`, managerID, groupID).Error; err != nil {
t.Fatal(err)
}
secret, token, err := userclasses.MintAPIToken("usr_", managerID, "BM file text", []string{"read", "write"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := gdb.Create(token).Error; err != nil {
t.Fatal(err)
}
send := func(method, path string, payload any) (int, map[string]any) {
t.Helper()
var buf bytes.Buffer
if payload != nil {
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
t.Fatal(err)
}
}
req := httptest.NewRequest(method, path, &buf)
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.Code, out
}
code, out := send(http.MethodPost, "/api/v1/bm/materials", map[string]any{"title": "Wykład z PDF", "type": "notatka"})
if code != http.StatusCreated {
t.Fatalf("POST material = %d %v", code, out)
}
materialID := id(obj(out["data"])["id"])
n, _ := strconv.ParseUint(materialID, 10, 64)
mid := uint(n)
const phrase = "Globalizacja i demokracja"
code, out = send(http.MethodPost, "/api/v1/bm/materials/"+materialID+"/files/inline", map[string]any{
"name": "wyklad.pdf",
"content_base64": base64.StdEncoding.EncodeToString(pdftest.OnePage(phrase)),
})
if code != http.StatusCreated {
t.Fatalf("inline attach = %d %v", code, out)
}
var queued int64
if err := gdb.Raw(`SELECT COUNT(*) FROM river_job WHERE kind = ?`, jobs.ExtractMaterialTextKind).Scan(&queued).Error; err != nil {
t.Fatal(err)
}
if queued != 1 {
t.Errorf("river_job rows of kind %s = %d, want 1", jobs.ExtractMaterialTextKind, queued)
}
pdf := classes.DefaultPDFText()
pdf.TempDir = t.TempDir()
added, err := classes.EnsureFileTexts(t.Context(), gdb, bucket, pdf, mid)
if err != nil || added != 1 {
t.Fatalf("EnsureFileTexts = %d, %v, want 1 row", added, err)
}
var texts []string
if err := gdb.Raw(`SELECT text FROM jz_bm_material_file_texts WHERE material_id = ?`, mid).Scan(&texts).Error; err != nil {
t.Fatal(err)
}
if len(texts) != 1 || !strings.Contains(texts[0], phrase) {
t.Fatalf("text rows = %q, want one holding %q", texts, phrase)
}
// A second run finds nothing new.
if again, err := classes.EnsureFileTexts(t.Context(), gdb, bucket, pdf, mid); err != nil || again != 0 {
t.Errorf("second EnsureFileTexts = %d, %v, want 0", again, err)
}
lastDoc := func() map[string]any {
t.Helper()
var doc map[string]any
for _, d := range stub.Imported() {
if d["id"] == materialID {
doc = d
}
}
if doc == nil {
t.Fatalf("material %s was never upserted", materialID)
}
return doc
}
ix := classes.NewMaterialIndexer(app)
ix.Sync(t.Context(), gdb, mid)
fileTexts, _ := lastDoc()["file_texts"].([]any)
if len(fileTexts) != 1 || !strings.Contains(fileTexts[0].(string), phrase) {
t.Errorf("upserted file_texts = %v, want the PDF's text", lastDoc()["file_texts"])
}
var fileIDs []uint
if err := gdb.Raw(`SELECT id FROM system_files WHERE attachment_id = ? AND field = 'files'`, materialID).Scan(&fileIDs).Error; err != nil {
t.Fatal(err)
}
if len(fileIDs) != 1 {
t.Fatalf("files = %v, want one", fileIDs)
}
before := len(stub.Imported())
code, out = send(http.MethodDelete, "/api/v1/bm/materials/"+materialID+"/files/"+strconv.FormatUint(uint64(fileIDs[0]), 10), nil)
if code != http.StatusNoContent {
t.Fatalf("detach = %d %v", code, out)
}
var left int64
if err := gdb.Raw(`SELECT COUNT(*) FROM jz_bm_material_file_texts WHERE material_id = ?`, mid).Scan(&left).Error; err != nil {
t.Fatal(err)
}
if left != 0 {
t.Errorf("text rows after detach = %d, want 0 (cascade)", left)
}
if len(stub.Imported()) <= before {
t.Fatal("the detach did not resync the material")
}
if _, ok := lastDoc()["file_texts"]; ok {
t.Errorf("the document after detach still has file_texts: %v", lastDoc())
}
if slices.Contains(stub.Removed(), materialID) {
t.Error("the detach removed the material's document instead of resyncing it")
}
}

View File

@@ -0,0 +1,189 @@
package bm_test
import (
"net/http"
"slices"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// TestMaterialPinsAgainstDatabase checks personal pins: the pinned-first
// order of the plain list within the filters and across pages, the pinned
// flag on list rows, the detail and the course materials, that another
// user's list ignores the pins, the 404 for materials the caller cannot
// see, idempotent pin and unpin, that a pin leaves the material's revision
// and updated_at alone, and the cascade on material delete.
func TestMaterialPinsAgainstDatabase(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")
carolID := createUser(t, gdb, "carol@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 course models.Course
if err := gdb.Order("id").Take(&course).Error; err != nil {
t.Fatal(err)
}
insert := func(title, typ, published 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 (?, ?, ?, `+published+`, ?, ?) RETURNING id`, course.ID, title, typ, private, authorUserID).Scan(&id).Error
if err != nil {
t.Fatal(err)
}
return id
}
m1 := insert("M1", "notatka", "NOW() - INTERVAL '3 days'", false, nil)
m2 := insert("M2", "notatka", "NOW() - INTERVAL '2 days'", false, nil)
m3 := insert("M3", "pdf", "NOW() - INTERVAL '1 day'", false, nil)
mp := insert("MP", "notatka", "NOW() - INTERVAL '1 day'", true, &carolID)
md := insert("MD", "notatka", "NULL", false, nil)
type row struct {
id string
pinned bool
}
rowsOf := func(rows []map[string]any) []row {
out := make([]row, 0, len(rows))
for _, r := range rows {
pinned, ok := r["pinned"].(bool)
if !ok {
t.Errorf("row %v has no boolean pinned", r)
}
out = append(out, row{id(r["id"]), pinned})
}
return out
}
want := func(pairs ...any) []row {
out := make([]row, 0, len(pairs)/2)
for i := 0; i+1 < len(pairs); i += 2 {
out = append(out, row{jsonID(pairs[i].(uint)), pairs[i+1].(bool)})
}
return out
}
listOf := func(c apiClient, query string) []row {
t.Helper()
return rowsOf(list(c.ok("GET", base+"/materials"+query)))
}
check := func(name string, got, wantRows []row) {
t.Helper()
if !slices.Equal(got, wantRows) {
t.Errorf("%s = %v, want %v", name, got, wantRows)
}
}
pinPath := func(id uint) string { return base + "/materials/" + jsonID(id) + "/pin" }
pinnedAt := func(id uint) time.Time {
t.Helper()
var at time.Time
if err := gdb.Raw(`SELECT pinned_at FROM jz_bm_material_pins WHERE material_id = ? AND user_id = ?`, id, aliceID).Scan(&at).Error; err != nil {
t.Fatal(err)
}
return at
}
type version struct {
Revision uint
UpdatedAt time.Time
}
versionOf := func(id uint) version {
t.Helper()
var v version
if err := gdb.Raw(`SELECT revision, updated_at FROM jz_bm_materials WHERE id = ?`, id).Scan(&v).Error; err != nil {
t.Fatal(err)
}
return v
}
// (a) Nothing pinned: newest publication first.
check("alice before pins", listOf(alice, "?per_page=100"), want(m3, false, m2, false, m1, false))
// (b) Pinning is idempotent, keeps the first pinned_at and is not content.
before := versionOf(m1)
alice.want(http.StatusNoContent, "PUT", pinPath(m1), "")
first := pinnedAt(m1)
alice.want(http.StatusNoContent, "PUT", pinPath(m1), "")
if again := pinnedAt(m1); !again.Equal(first) {
t.Errorf("pinned_at after a second PUT = %v, want the first %v", again, first)
}
if after := versionOf(m1); after.Revision != before.Revision || !after.UpdatedAt.Equal(before.UpdatedAt) {
t.Errorf("material after pins = %+v, want unchanged %+v", after, before)
}
// (c) Pins first, newest pin first, then newest publication.
alice.want(http.StatusNoContent, "PUT", pinPath(m2), "")
if err := gdb.Exec(`UPDATE jz_bm_material_pins SET pinned_at = NOW() - INTERVAL '1 hour' WHERE material_id = ?`, m1).Error; err != nil {
t.Fatal(err)
}
if err := gdb.Exec(`UPDATE jz_bm_material_pins SET pinned_at = NOW() - INTERVAL '2 hours' WHERE material_id = ?`, m2).Error; err != nil {
t.Fatal(err)
}
check("alice with pins", listOf(alice, "?per_page=100"), want(m1, true, m2, true, m3, false))
// (d) Pages are stable and the total counts as before.
for page, wantID := range []uint{m1, m2, m3} {
body := alice.ok("GET", base+"/materials?per_page=1&page="+jsonID(uint(page+1)))
got := rowsOf(list(body))
if len(got) != 1 || got[0].id != jsonID(wantID) {
t.Errorf("page %d = %v, want %d", page+1, got, wantID)
}
if total := obj(body["meta"])["total"]; total != 3.0 {
t.Errorf("page %d total = %v, want 3", page+1, total)
}
}
// (e) Filters apply to pinned rows too.
check("alice type=pdf", listOf(alice, "?type=pdf"), want(m3, false))
check("alice type=notatka", listOf(alice, "?type=notatka"), want(m1, true, m2, true))
// (f) Pins are personal.
check("bob", listOf(bob, "?per_page=100"), want(m3, false, m2, false, m1, false))
if pinned := obj(bob.ok("GET", base+"/materials/"+jsonID(m1))["data"])["pinned"]; pinned != false {
t.Errorf("bob's detail of M1 pinned = %v, want false", pinned)
}
if pinned := obj(alice.ok("GET", base+"/materials/"+jsonID(m1))["data"])["pinned"]; pinned != true {
t.Errorf("alice's detail of M1 pinned = %v, want true", pinned)
}
// (g) The course materials carry the flag and keep newest first.
detail := obj(alice.ok("GET", base+"/courses/"+jsonID(course.ID))["data"])
raw, _ := detail["materials"].([]any)
courseRows := make([]map[string]any, 0, len(raw))
for _, r := range raw {
courseRows = append(courseRows, r.(map[string]any))
}
check("alice course materials", rowsOf(courseRows), want(m3, false, m2, true, m1, true))
// (h) A material the caller cannot see is a 404 either way.
for _, hidden := range []uint{mp, md, 999999} {
alice.want(http.StatusNotFound, "PUT", pinPath(hidden), "")
alice.want(http.StatusNotFound, "DELETE", pinPath(hidden), "")
}
if c := count(t, gdb, "jz_bm_material_pins"); c != 2 {
t.Errorf("pins after the 404s = %d, want 2", c)
}
// (i) Unpinning is idempotent.
alice.want(http.StatusNoContent, "DELETE", pinPath(m2), "")
alice.want(http.StatusNoContent, "DELETE", pinPath(m2), "")
check("alice after unpin", listOf(alice, "?per_page=100"), want(m1, true, m3, false, m2, false))
// (j) The token twin's write scope is pinned by TestTokenMirrorRoutes;
// this package has no personal-token helper, so it is not driven here.
// (k) The pin goes with the material.
if err := gdb.Exec(`DELETE FROM jz_bm_materials WHERE id = ?`, m1).Error; err != nil {
t.Fatal(err)
}
if c := count(t, gdb, "jz_bm_material_pins"); c != 0 {
t.Errorf("pins after deleting M1 = %d, want 0", c)
}
}

View File

@@ -0,0 +1,216 @@
package bm_test
import (
"bytes"
"encoding/json"
"io"
"maps"
"net/http"
"net/http/httptest"
"strconv"
"testing"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// TestMaterialRevisionAgainstDatabase checks the revision of materials
// through the management API (D-01..D-05): a new material is at revision 1;
// a write with a stale revision is a 409 with the current version and
// changes nothing; a write without revision overwrites; only content
// changes bump; and the student detail shows the same revision.
func TestMaterialRevisionAgainstDatabase(t *testing.T) {
app, plugins, db := migrated(t)
seedFixture(t, plugins, "testdata/seed.example.json")
var courses []models.Course
if err := db.Order("id").Limit(2).Find(&courses).Error; err != nil {
t.Fatal(err)
}
if len(courses) < 2 {
t.Fatalf("the fixture has %d courses, want 2", len(courses))
}
userID := createUser(t, db, "bm-revision@example.test")
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)
}
student := apiClient{t: t, h: handler, token: tokenFor(t, userID)}
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, 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.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
}
note := map[string]any{"title": "Rewizje", "type": "notatka", "course_id": courses[0].ID, "body": "pierwsza\n", "tags": []string{"Globalizacja"}}
code, out := send(http.MethodPost, "/api/v1/bm/materials", note)
if code != http.StatusCreated {
t.Fatalf("create = %d %v", code, out)
}
created := data(out)
if created["revision"] != float64(1) || created["updated_at"] == nil {
t.Fatalf("created = %v, want revision 1 and updated_at", created)
}
path := "/api/v1/bm/materials/" + strconv.Itoa(int(created["id"].(float64)))
studentPath := "/_bm/api/v1/materials/" + strconv.Itoa(int(created["id"].(float64)))
revisionOf := func() float64 {
t.Helper()
code, out := send(http.MethodGet, path, nil)
if code != http.StatusOK {
t.Fatalf("show = %d %v", code, out)
}
r, _ := data(out)["revision"].(float64)
return r
}
if r := revisionOf(); r != 1 {
t.Fatalf("new material revision = %v, want 1", r)
}
with := func(changes map[string]any) map[string]any {
out := maps.Clone(note)
maps.Copy(out, changes)
return out
}
code, out = send(http.MethodPut, path, with(map[string]any{"body": "druga\n", "revision": 1}))
if code != http.StatusOK || data(out)["revision"] != float64(2) {
t.Fatalf("PUT with the current revision = %d %v, want 200 and revision 2", code, out)
}
note["body"] = "druga\n"
code, out = send(http.MethodPut, path, with(map[string]any{"body": "nieaktualna\n", "revision": 1}))
if code != http.StatusConflict {
t.Fatalf("PUT with a stale revision = %d %v, want 409", code, out)
}
if out["error"] != true || out["revision"] != float64(2) || out["updated_at"] == nil || out["message"] == nil {
t.Errorf("409 body = %v, want error, message, revision 2 and updated_at", out)
}
if data(out)["body"] != "druga\n" {
t.Errorf("409 data.body = %v, want the stored body", data(out)["body"])
}
var stored models.Material
if err := db.First(&stored, created["id"]).Error; err != nil {
t.Fatal(err)
}
if stored.Body == nil || *stored.Body != "druga\n" || stored.Revision != 2 {
t.Errorf("after the 409 the row is body %v revision %d, want unchanged", stored.Body, stored.Revision)
}
code, out = send(http.MethodPut, path, with(map[string]any{"body": "trzecia\n"}))
if code != http.StatusOK || data(out)["revision"] != float64(3) {
t.Fatalf("PUT without revision = %d %v, want 200 and revision 3", code, out)
}
note["body"] = "trzecia\n"
for name, changes := range map[string]map[string]any{
"published_at only": {"published_at": "2026-10-01T10:00:00+02:00"},
"is_private only": {"is_private": true},
"identical content": {},
"identical, current": {"revision": 3},
} {
code, out = send(http.MethodPut, path, with(changes))
if code != http.StatusOK || data(out)["revision"] != float64(3) {
t.Errorf("PUT with %s = %d %v, want 200 and revision 3", name, code, out)
}
}
code, out = send(http.MethodPut, path, with(map[string]any{"tags": []string{"Globalizacja", "Teoria"}}))
if code != http.StatusOK || data(out)["revision"] != float64(4) {
t.Fatalf("PUT changing the tags = %d %v, want revision 4", code, out)
}
note["tags"] = []string{"Teoria", "Globalizacja"}
code, out = send(http.MethodPut, path, note)
if code != http.StatusOK || data(out)["revision"] != float64(4) {
t.Errorf("PUT with the same tags reordered = %d %v, want revision 4", code, out)
}
code, out = send(http.MethodPut, path, with(map[string]any{"course_id": courses[1].ID}))
if code != http.StatusOK || data(out)["revision"] != float64(5) {
t.Fatalf("PUT changing the course = %d %v, want revision 5", code, out)
}
note["course_id"] = courses[1].ID
detail := obj(student.ok(http.MethodGet, studentPath)["data"])
if detail["revision"] != float64(5) {
t.Errorf("student detail revision = %v, want 5", detail["revision"])
}
// POST upserts on title and course: updating the existing material it
// checks a sent revision like PUT; creating one it ignores it.
const upsert = "/api/v1/bm/materials"
code, out = send(http.MethodPost, upsert, with(map[string]any{"body": "nieaktualna\n", "revision": 4}))
if code != http.StatusConflict || out["revision"] != float64(5) {
t.Fatalf("POST with a stale revision = %d %v, want 409 and revision 5", code, out)
}
if err := db.First(&stored, created["id"]).Error; err != nil {
t.Fatal(err)
}
if stored.Body == nil || *stored.Body != "trzecia\n" || stored.Revision != 5 {
t.Errorf("after the POST 409 the row is body %v revision %d, want unchanged", stored.Body, stored.Revision)
}
code, out = send(http.MethodPost, upsert, with(map[string]any{"revision": 5}))
if code != http.StatusOK || out["created"] != false || data(out)["revision"] != float64(5) {
t.Errorf("POST with the current revision and the same content = %d %v, want 200 and revision 5", code, out)
}
code, out = send(http.MethodPost, upsert, with(map[string]any{"body": "czwarta\n", "revision": 5}))
if code != http.StatusOK || out["created"] != false || data(out)["revision"] != float64(6) {
t.Fatalf("POST with the current revision and a new body = %d %v, want 200 and revision 6", code, out)
}
note["body"] = "czwarta\n"
code, out = send(http.MethodPost, upsert, with(map[string]any{"is_private": false}))
if code != http.StatusOK || data(out)["revision"] != float64(6) {
t.Errorf("POST without revision changing only is_private = %d %v, want revision 6", code, out)
}
code, out = send(http.MethodPost, upsert, with(map[string]any{"body": "piąta\n"}))
if code != http.StatusOK || data(out)["revision"] != float64(7) {
t.Errorf("POST without revision and a new body = %d %v, want 200 and revision 7", code, out)
}
code, out = send(http.MethodPost, upsert, map[string]any{"title": "Nowa z rewizją", "type": "notatka", "body": "nowa\n", "revision": 9})
if code != http.StatusCreated || out["created"] != true || data(out)["revision"] != float64(1) {
t.Errorf("POST creating with a revision = %d %v, want 201 and revision 1", code, out)
}
}

View File

@@ -0,0 +1,148 @@
package bm_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/internal/searchtest"
)
// TestMaterialSearchAgainstDatabase drives the material search end to end
// against a migrated database and a Typesense stand-in: every management
// write syncs the index, a delete removes the document, and a search whose
// candidates include a draft and another user's private material shows a
// student only the public one, counted in SQL, with no snippet of the
// hidden rows.
func TestMaterialSearchAgainstDatabase(t *testing.T) {
stub := &searchtest.Stub{}
app, plugins, gdb := migratedWith(t, searchtest.Start(t, stub)...)
handler, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
managerID := createUser(t, gdb, "manager@example.test")
otherID := createUser(t, gdb, "other@example.test")
studentID := createUser(t, gdb, "student@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 (?, ?)`, managerID, groupID).Error; err != nil {
t.Fatal(err)
}
secret, token, err := userclasses.MintAPIToken("usr_", managerID, "BM search", []string{"read", "write"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := gdb.Create(token).Error; err != nil {
t.Fatal(err)
}
send := func(method, path string, payload any) (int, map[string]any) {
t.Helper()
var buf bytes.Buffer
if payload != nil {
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
t.Fatal(err)
}
}
req := httptest.NewRequest(method, path, &buf)
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.Code, out
}
create := func(payload map[string]any) string {
t.Helper()
code, out := send(http.MethodPost, "/api/v1/bm/materials", payload)
if code != http.StatusCreated {
t.Fatalf("POST %v = %d %v", payload, code, out)
}
return id(obj(out["data"])["id"])
}
public := create(map[string]any{"title": "Globalizacja publiczna", "type": "notatka", "body": "Tekst o **globalizacji** dla wszystkich."})
draft := create(map[string]any{"title": "Globalizacja szkic", "type": "notatka", "body": "szkic", "published_at": nil})
private := create(map[string]any{"title": "Globalizacja prywatna", "type": "notatka", "body": "tajne", "is_private": true, "author_user_id": otherID})
var upserted []string
for _, doc := range stub.Imported() {
upserted = append(upserted, doc["id"].(string))
}
for _, want := range []string{public, draft, private} {
if !slices.Contains(upserted, want) {
t.Errorf("material %s was not upserted (upserts %v)", want, upserted)
}
}
extra := create(map[string]any{"title": "Do usunięcia", "type": "link"})
if code, out := send(http.MethodDelete, "/api/v1/bm/materials/"+extra, nil); code != http.StatusNoContent {
t.Fatalf("DELETE = %d %v", code, out)
}
if !slices.Contains(stub.Removed(), extra) {
t.Errorf("removed = %v, want %s", stub.Removed(), extra)
}
mark := func(word string) string { return searchtest.HighlightStart + word + searchtest.HighlightEnd }
stub.SetHits(
searchtest.Hit{ID: private, Field: "body", Snippet: mark("tajne")},
searchtest.Hit{ID: draft, Field: "body", Snippet: mark("szkic")},
searchtest.Hit{ID: public, Field: "body", Snippet: "Tekst o " + mark("globalizacji") + " dla wszystkich."},
)
student := apiClient{t: t, h: handler, token: tokenFor(t, studentID)}
req := httptest.NewRequest(http.MethodGet, "/_bm/api/v1/materials?q=globalizacja", nil)
req.Header.Set("Authorization", "Bearer "+student.token)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("search = %d %s", rec.Code, rec.Body.String())
}
raw := rec.Body.String()
for _, hidden := range []string{"tajne", "szkic", "Globalizacja prywatna", "Globalizacja szkic"} {
if strings.Contains(raw, hidden) {
t.Errorf("search answer leaks %q: %s", hidden, raw)
}
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
rows := list(body)
if len(rows) != 1 || id(rows[0]["id"]) != public {
t.Fatalf("rows = %v, want only %s", rows, public)
}
if total := obj(body["meta"])["total"]; total != float64(1) {
t.Errorf("meta.total = %v, want 1 (the SQL count, not the engine's found)", total)
}
snippet := obj(rows[0]["snippet"])
if snippet["source"] != "body" {
t.Errorf("snippet = %v, want the public body snippet", rows[0]["snippet"])
}
// Without q the list never asks the engine.
before := len(stub.Searches())
plain := student.ok(http.MethodGet, "/_bm/api/v1/materials")
if len(stub.Searches()) != before {
t.Error("the list without q called the engine")
}
for _, row := range list(plain) {
if _, ok := row["snippet"]; ok {
t.Errorf("row without q carries a snippet: %v", row)
}
}
}

View File

@@ -0,0 +1,185 @@
package bm_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"strconv"
"testing"
"time"
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"git.golem15.com/jakub/sm-bm-plugin/models"
"gorm.io/gorm"
)
// The realtime config of the material watch test: the Centrifugo driver, so
// Emit enqueues broadcast jobs.
const (
watchProxySecret = "material-watch-proxy-secret-0123456789"
watchTokenSecret = "bm-test-only-material-watch-token-secret-32b"
watchAppKey = "bm-test-only-material-watch-app-key"
)
// TestMaterialWatchAgainstDatabase checks the live revision heads-up (D-20)
// against Postgres: who may follow materials:{id} (api.CanWatchMaterial),
// and that a management PUT which changes the content queues exactly one
// broadcast on the material's channel while a visibility-only PUT queues
// none.
func TestMaterialWatchAgainstDatabase(t *testing.T) {
app, plugins, db := migratedWith(t,
"SUMMER_REALTIME__DRIVER=centrifugo",
"SUMMER_REALTIME__CENTRIFUGO__PROXY_SECRET="+watchProxySecret,
"SUMMER_REALTIME__CENTRIFUGO__TOKEN_SECRET="+watchTokenSecret,
"SUMMER_APP__KEY="+watchAppKey,
)
seedFixture(t, plugins, "testdata/seed.example.json")
var course models.Course
if err := db.Order("id").First(&course).Error; err != nil {
t.Fatal(err)
}
author := createUser(t, db, "bm-watch-author@example.test")
other := createUser(t, db, "bm-watch-other@example.test")
student := createUser(t, db, "bm-watch-student@example.test")
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)
}
for _, id := range []uint{author, other} {
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, id, groupID).Error; err != nil {
t.Fatal(err)
}
}
now := time.Now()
past := now.Add(-time.Hour)
insert := func(title string, published *time.Time, private bool, authorID *uint) uint {
t.Helper()
var id uint
err := db.Raw(`
INSERT INTO jz_bm_materials (course_id, title, type, body, published_at, is_private, author_user_id, created_at, updated_at)
VALUES (?, ?, 'notatka', 'tekst', ?, ?, ?, NOW(), NOW())
RETURNING id`, course.ID, title, published, private, authorID).Scan(&id).Error
if err != nil {
t.Fatal(err)
}
return id
}
authored := insert("Autorska", &past, false, &author)
orphan := insert("Bez autora", &past, false, nil)
hidden := insert("Prywatna", &past, true, nil)
draft := insert("Szkic", nil, false, nil)
for _, c := range []struct {
name string
userID uint
id uint
want bool
}{
{"the author manager", author, authored, true},
{"another manager on an authored material", other, authored, false},
{"any manager on a material with no author", other, orphan, true},
{"a non-manager", student, orphan, false},
{"a private material the user cannot see", other, hidden, false},
{"a draft", other, draft, false},
{"an unknown material", author, draft + 1000, false},
} {
got, err := api.CanWatchMaterial(t.Context(), db, now, c.userID, c.id)
if err != nil {
t.Errorf("%s: %v", c.name, err)
continue
}
if got != c.want {
t.Errorf("%s: CanWatchMaterial = %v, want %v", c.name, got, c.want)
}
}
secret, token, err := userclasses.MintAPIToken("usr_", author, "BM watch", []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()
raw, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(method, path, bytes.NewReader(raw))
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
_ = json.Unmarshal(rec.Body.Bytes(), &out)
return rec.Code, out
}
note := map[string]any{"title": "Na żywo", "type": "notatka", "course_id": course.ID, "body": "pierwsza\n"}
code, out := send(http.MethodPost, "/api/v1/bm/materials", note)
if code != http.StatusCreated {
t.Fatalf("create = %d %v", code, out)
}
d, _ := out["data"].(map[string]any)
id := uint(d["id"].(float64))
path := "/api/v1/bm/materials/" + strconv.FormatUint(uint64(id), 10)
channel := classes.MaterialChannel(id)
if n := revisionJobs(t, db, channel); n != 0 {
t.Fatalf("create queued %d revision broadcasts, want 0", n)
}
note["body"] = "druga\n"
if code, out := send(http.MethodPut, path, note); code != http.StatusOK {
t.Fatalf("content PUT = %d %v", code, out)
}
if n := revisionJobs(t, db, channel); n != 1 {
t.Fatalf("content PUT queued %d revision broadcasts on %s, want 1", n, channel)
}
note["is_private"] = true
if code, out := send(http.MethodPut, path, note); code != http.StatusOK {
t.Fatalf("visibility PUT = %d %v", code, out)
}
if n := revisionJobs(t, db, channel); n != 1 {
t.Errorf("visibility PUT changed the revision broadcasts to %d, want still 1", n)
}
}
// revisionJobs counts the queued broadcast jobs that announce a material
// revision on channel.
func revisionJobs(t *testing.T, db *gorm.DB, channel string) int {
t.Helper()
var rows []string
if err := db.Raw(`SELECT args::text FROM river_job WHERE kind = 'summer.broadcast'`).Scan(&rows).Error; err != nil {
t.Fatal(err)
}
n := 0
for _, raw := range rows {
var args struct {
Channels []string `json:"channels"`
Event string `json:"event"`
}
if err := json.Unmarshal([]byte(raw), &args); err != nil {
t.Fatal(err)
}
if args.Event == classes.MaterialRevisedEvent && slices.Contains(args.Channels, channel) {
n++
}
}
return n
}

18
mcp.go Normal file
View File

@@ -0,0 +1,18 @@
package bm
import (
"git.golem15.com/golem15/summercms/modules/pact"
)
var _ pact.HasMCP = (*Plugin)(nil)
// MCP declares the plugin's MCP tools. They are exposed with the bm_ prefix,
// bind token-guarded routes only (the token twins of the student API under
// TokenPrefix and the management API under ManagePrefix), run as the
// signed-in user under golem15.user's "user" guard, and their titles and
// descriptions are static text, never built from data.
func (p *Plugin) MCP() pact.MCP {
tools := append(studentTools(), checklistTools()...)
tools = append(tools, manageTools()...)
return pact.MCP{Tools: append(tools, fileTools()...)}
}

125
mcp_checklists.go Normal file
View File

@@ -0,0 +1,125 @@
package bm
import (
"net/http"
"git.golem15.com/golem15/summercms/modules/pact"
)
// checklistsInput is the input of bm_checklists.
type checklistsInput struct {
Meeting uint `json:"meeting,omitempty" query:"meeting" jsonschema:"only checklists of this zjazd (meeting) id"`
}
// checklistIDInput names one of the student's checklists.
type checklistIDInput struct {
ID uint `json:"id" path:"id" jsonschema:"the checklist id, as listed by bm_checklists"`
}
// checklistItemIDInput names one item of the student's checklists.
type checklistItemIDInput struct {
ID uint `json:"id" path:"id" jsonschema:"the checklist item id, as listed by bm_checklist"`
}
// createChecklistInput is the body of bm_create_checklist.
type createChecklistInput struct {
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing zjazd (meeting) id, as listed by bm_meetings"`
Title string `json:"title" jsonschema:"title, at most 255 characters, e.g. Zjazd 4"`
Description *string `json:"description,omitempty" jsonschema:"description, at most 10000 characters"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position among the student's checklists, an integer"`
}
// updateChecklistInput is the body of bm_update_checklist.
type updateChecklistInput struct {
ID uint `json:"id" path:"id" jsonschema:"the checklist id"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing zjazd (meeting) id; null clears it"`
Title *string `json:"title,omitempty" jsonschema:"title, at most 255 characters; required, so not null"`
Description *string `json:"description,omitempty" jsonschema:"description, at most 10000 characters"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position among the student's checklists, an integer"`
}
// addChecklistItemInput is the body of bm_add_checklist_item.
type addChecklistItemInput struct {
ID uint `json:"id" path:"id" jsonschema:"the checklist id"`
Kind *string `json:"kind,omitempty" jsonschema:"one of: lektura, artykul, ksiazka, prezentacja, zadanie, inne (default zadanie)"`
Title string `json:"title" jsonschema:"title, at most 500 characters"`
Notes *string `json:"notes,omitempty" jsonschema:"notes, at most 10000 characters"`
URL *string `json:"url,omitempty" jsonschema:"link, at most 2048 characters"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
ReadingID *uint `json:"reading_id,omitempty" jsonschema:"an existing reading id; the item is then done exactly when the reading is marked read"`
DeadlineID *uint `json:"deadline_id,omitempty" jsonschema:"an existing deadline id"`
MaterialID *uint `json:"material_id,omitempty" jsonschema:"an existing material id"`
PresentationSlug *string `json:"presentation_slug,omitempty" jsonschema:"slug of one of the student's own presentation decks"`
DueAt *string `json:"due_at,omitempty" jsonschema:"when it should be done: RFC 3339 or YYYY-MM-DD HH:MM in Europe/Warsaw"`
EstimateMinutes *int `json:"estimate_minutes,omitempty" jsonschema:"estimated work in minutes, 0 to 10000"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position in the checklist, an integer (default: last)"`
}
// updateChecklistItemInput is the body of bm_update_checklist_item.
type updateChecklistItemInput struct {
ID uint `json:"id" path:"id" jsonschema:"the checklist item id"`
ChecklistID *uint `json:"checklist_id,omitempty" jsonschema:"move the item to another of the student's checklists"`
Kind *string `json:"kind,omitempty" jsonschema:"one of: lektura, artykul, ksiazka, prezentacja, zadanie, inne"`
Title *string `json:"title,omitempty" jsonschema:"title, at most 500 characters; required, so not null"`
Notes *string `json:"notes,omitempty" jsonschema:"notes, at most 10000 characters"`
URL *string `json:"url,omitempty" jsonschema:"link, at most 2048 characters"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
ReadingID *uint `json:"reading_id,omitempty" jsonschema:"an existing reading id; the item is then done exactly when the reading is marked read"`
DeadlineID *uint `json:"deadline_id,omitempty" jsonschema:"an existing deadline id"`
MaterialID *uint `json:"material_id,omitempty" jsonschema:"an existing material id"`
PresentationSlug *string `json:"presentation_slug,omitempty" jsonschema:"slug of one of the student's own presentation decks"`
DueAt *string `json:"due_at,omitempty" jsonschema:"when it should be done: RFC 3339 or YYYY-MM-DD HH:MM in Europe/Warsaw"`
EstimateMinutes *int `json:"estimate_minutes,omitempty" jsonschema:"estimated work in minutes, 0 to 10000"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position in the checklist, an integer (default: last)"`
}
// The sentences of the checklist tool descriptions.
const (
checklistsPrivate = " Checklists are the signed-in student's own; another student's id answers 404."
checklistAnswer = " Returns the checklist with its progress (total, done, percent weighed by estimate_minutes, minutes_total, minutes_done, minutes_left) and its items."
itemAnswer = " Returns the item with its done mark and the reading, deadline, material, course or deck it points at."
checklistInvalid = " Unknown fields and invalid values answer 422 with the errors per field."
)
// checklistTools are the student's checklist tools over the token twins of
// the student API.
func checklistTools() []pact.MCPTool {
tool := func(name, title, desc, method, path string, input any) pact.MCPTool {
return pact.MCPTool{Name: name, Title: title, Description: desc + checklistsPrivate, Guard: "user", Method: method, Path: TokenPrefix + path, Input: input}
}
unmark := tool("unmark_checklist_item_done", "Unmark a checklist item as done",
"Clears the done mark of a checklist item; for an item with a reading it removes the student's read mark of that reading."+itemAnswer+needsScopeWrite,
http.MethodDelete, "/checklist-items/{id}/done", checklistItemIDInput{})
unmark.Destructive = boolPtr(false)
unmark.Idempotent = boolPtr(true)
return []pact.MCPTool{
tool("checklists", "BM checklists",
"Lists the student's checklists (e.g. the preparation for a zjazd) with zjazd and progress, without items."+needsScopeRead,
http.MethodGet, "/checklists", checklistsInput{}),
tool("checklist", "BM checklist",
"Returns one of the student's checklists."+checklistAnswer+needsScopeRead,
http.MethodGet, "/checklists/{id}", checklistIDInput{}),
tool("create_checklist", "Create a checklist",
"Creates a checklist for the student, optionally for one zjazd."+checklistAnswer+checklistInvalid+needsScopeWrite,
http.MethodPost, "/checklists", createChecklistInput{}),
tool("update_checklist", "Update a checklist",
"Changes the sent fields of one of the student's checklists; the rest stay."+checklistAnswer+checklistInvalid+needsScopeWrite,
http.MethodPatch, "/checklists/{id}", updateChecklistInput{}),
tool("delete_checklist", "Delete a checklist",
"Deletes one of the student's checklists with its items, for good; reading marks stay."+needsScopeWrite,
http.MethodDelete, "/checklists/{id}", checklistIDInput{}),
tool("add_checklist_item", "Add a checklist item",
"Adds an item (a reading, article, book, presentation, task) to one of the student's checklists, last unless sort_order is given."+itemAnswer+checklistInvalid+needsScopeWrite,
http.MethodPost, "/checklists/{id}/items", addChecklistItemInput{}),
tool("update_checklist_item", "Update a checklist item",
"Changes the sent fields of one checklist item; the rest stay."+itemAnswer+checklistInvalid+needsScopeWrite,
http.MethodPatch, "/checklist-items/{id}", updateChecklistItemInput{}),
tool("delete_checklist_item", "Delete a checklist item",
"Deletes one checklist item for good; a reading mark stays."+needsScopeWrite,
http.MethodDelete, "/checklist-items/{id}", checklistItemIDInput{}),
tool("mark_checklist_item_done", "Mark a checklist item as done",
"Marks a checklist item done; for an item with a reading it marks that reading read (the reading list shows it). Marking again keeps the first time."+itemAnswer+needsScopeWrite,
http.MethodPut, "/checklist-items/{id}/done", checklistItemIDInput{}),
unmark,
}
}

46
mcp_files.go Normal file
View File

@@ -0,0 +1,46 @@
package bm
import (
"net/http"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
)
// attachMaterialFileInput is the input of bm_manage_attach_material_file.
type attachMaterialFileInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id"`
Name string `json:"name" jsonschema:"file name with extension, for example notatki.pdf"`
Mime string `json:"mime,omitempty" jsonschema:"optional MIME type; the stored type must match"`
ContentBase64 string `json:"content_base64" jsonschema:"standard base64, at most 3000000 bytes decoded; use bm_manage_create_material_upload for larger files"`
}
// detachMaterialFileInput is the input of bm_manage_detach_material_file.
type detachMaterialFileInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id"`
File uint `json:"file" path:"file" jsonschema:"the file id, as listed in the files of bm_manage_show_material"`
}
// fileTools are the material file tools over the management API (D-10,
// D-11, D-17): attach a small file as base64, get a signed one-time upload
// URL for a larger one, and detach a file. Every description carries the
// public-file warning and says no file contents are returned.
func fileTools() []pact.MCPTool {
tool := func(name, title, desc, method, path string, input any) pact.MCPTool {
return pact.MCPTool{Name: name, Title: title, Description: desc, Guard: "user", Method: method, Path: ManagePrefix + path, Input: input}
}
return []pact.MCPTool{
tool("manage_attach_material_file", "Attach a file to a material",
"Attaches one file sent as standard base64 (at most 3000000 bytes decoded; for larger files use bm_manage_create_material_upload) to a material, after its files; a material holds at most 20. The extension and the content are checked; a sent mime must match the content. Returns the material with its files (id, absolute link, name, size and type) and a warning; 404 when the material is unknown, 422 when the file is refused. "+
api.MaterialFileWarning+" "+MCPMaterialPrivacy+writeMaterials,
http.MethodPost, "/materials/{id}/files/inline", attachMaterialFileInput{}),
tool("manage_create_material_upload", "Get an upload URL for a material file",
"Returns a one-time upload URL for one file of this material, valid for 10 minutes, bound to this material and to you, and usable once: send the file with the returned curl_example (curl -F 'file=@<path>' '<upload_url>') from a shell, so the bytes never pass through MCP. At most 50 MB, one of the listed accept extensions; the answer also has expires_at, max_bytes and a warning. A used, expired or forged URL gets 403. 404 when the material is unknown, 503 when uploads are not configured. "+
api.MaterialFileWarning+" "+MCPMaterialPrivacy+writeMaterials,
http.MethodPost, "/materials/{id}/files/upload-url", idInput{}),
tool("manage_detach_material_file", "Detach a file from a material",
"Deletes one file of a material, its row and its stored blob, so its link stops working; 404 when the material or the file is unknown or the file belongs to another material."+deleteForever+" "+
api.MaterialFileWarning+" "+MCPMaterialPrivacy+writeMaterials,
http.MethodDelete, "/materials/{id}/files/{file}", detachMaterialFileInput{}),
}
}

142
mcp_links.go Normal file
View File

@@ -0,0 +1,142 @@
package bm
import (
"bytes"
"encoding/json"
"mime"
"net/http"
"strconv"
"strings"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// MiddlewareMCPLinks makes the links of an MCP answer absolute (D-16). It
// runs after user.api_token on the token twins of the student API and on the
// management API.
const MiddlewareMCPLinks = "jz.bm.mcp-links"
// mcpLinks rewrites the 2xx JSON answer of an MCP tool call (a request pier
// dispatched in-process with the api_token marker): every string under a key
// named url or ending in _url that starts with a single / gets the
// application's base URL in front, so an agent can follow it. Any other
// request passes straight through, unbuffered and byte for byte.
func (p *Plugin) mcpLinks(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, ok := bouncer.Dispatched(r.Context(), "api_token"); !ok {
next.ServeHTTP(w, r)
return
}
rec := &linkRecorder{header: http.Header{}}
next.ServeHTTP(rec, r)
status := rec.status
if status == 0 {
status = http.StatusOK
}
out := rec.body.Bytes()
if status >= 200 && status < 300 && isJSON(rec.header.Get("Content-Type")) && len(out) > 0 {
if rewritten, ok := absoluteLinks(out, p.linkBase(r)); ok {
out = rewritten
rec.header.Set("Content-Length", strconv.Itoa(len(out)))
}
}
for k, v := range rec.header {
w.Header()[k] = v
}
w.WriteHeader(status)
_, _ = w.Write(out)
})
}
// linkBase is the base of the absolute links: app.url, else
// jz.bm.public_url, else the scheme (TLS or X-Forwarded-Proto) and Host of
// the request (pier copies both onto the request it dispatches).
func (p *Plugin) linkBase(r *http.Request) string {
if p.app != nil && p.app.Config != nil {
for _, key := range []string{"app.url", "jz.bm.public_url"} {
if base := strings.TrimRight(strings.TrimSpace(p.app.Config.String(key)), "/"); base != "" {
return base
}
}
}
scheme := "http"
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
scheme = "https"
}
return scheme + "://" + r.Host
}
// isJSON reports whether a Content-Type is JSON.
func isJSON(contentType string) bool {
mt, _, err := mime.ParseMediaType(contentType)
return err == nil && (mt == "application/json" || strings.HasSuffix(mt, "+json"))
}
// absoluteLinks decodes body (numbers kept exactly), prefixes its relative
// links with base and encodes it again. It reports false when body is not a
// single JSON value, so the caller sends it unchanged.
func absoluteLinks(body []byte, base string) ([]byte, bool) {
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
var v any
if err := dec.Decode(&v); err != nil {
return nil, false
}
if dec.More() {
return nil, false
}
v = rewriteLinks(v, "", base)
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, false
}
return buf.Bytes(), true
}
// rewriteLinks walks v; key is the object key v sits under ("" inside an
// array or at the top).
func rewriteLinks(v any, key, base string) any {
switch t := v.(type) {
case map[string]any:
for k, child := range t {
t[k] = rewriteLinks(child, k, base)
}
return t
case []any:
for i, child := range t {
t[i] = rewriteLinks(child, "", base)
}
return t
case string:
if (key == "url" || strings.HasSuffix(key, "_url")) && strings.HasPrefix(t, "/") && !strings.HasPrefix(t, "//") {
return base + t
}
return t
default:
return v
}
}
// linkRecorder buffers a handler's answer so mcpLinks can rewrite it.
type linkRecorder struct {
header http.Header
status int
body bytes.Buffer
}
func (l *linkRecorder) Header() http.Header { return l.header }
func (l *linkRecorder) WriteHeader(status int) {
if l.status == 0 {
l.status = status
}
}
func (l *linkRecorder) Write(b []byte) (int, error) {
if l.status == 0 {
l.status = http.StatusOK
}
return l.body.Write(b)
}

359
mcp_manage.go Normal file
View File

@@ -0,0 +1,359 @@
package bm
import (
"net/http"
"git.golem15.com/golem15/summercms/modules/pact"
)
// The sentences the management tool descriptions end with (D-15): the scope
// and the permission code the route checks.
const (
readCourses = " Needs scope read and the jz.bm.access_courses permission."
writeCourses = " Needs scope write and the jz.bm.access_courses permission."
readSchedule = " Needs scope read and the jz.bm.access_schedule permission."
writeSchedule = " Needs scope write and the jz.bm.access_schedule permission."
readMaterials = " Needs scope read and the jz.bm.access_materials permission."
writeMaterials = " Needs scope write and the jz.bm.access_materials permission."
)
// Shared description fragments (D-22).
const (
recordAnswer = " Returns the row as an object of its columns (id, created_at and updated_at included); times are RFC 3339 in Europe/Warsaw, dates YYYY-MM-DD."
invalidAnswer = " A value that breaks a rule is refused with 422 and the errors per field."
patchSemantics = " Only the fields sent change; null or an empty string clears an optional column."
deleteForever = " The delete cannot be undone."
replacedAsSent = " body, source and url are replaced as sent (null clears them): read the material with include_body true first to keep its body."
// revisionChecked ends the material write descriptions (D-05).
revisionChecked = " With revision, a write to a material changed since that revision is refused with 409 and the current revision; without it the write overwrites."
)
// --- courses -------------------------------------------------------------
// listCoursesInput filters bm_manage_list_courses.
type listCoursesInput struct {
Semester int `json:"semester,omitempty" query:"semester" jsonschema:"only courses of this semester, 1 to 4"`
Form string `json:"form,omitempty" query:"form" jsonschema:"only courses of this form, one of: wyklad, cwiczenia, konwersatorium, seminarium, inne"`
Code string `json:"code,omitempty" query:"code" jsonschema:"only the course with this code; null for courses without one"`
}
// createCourseInput is the body of bm_manage_create_course.
type createCourseInput struct {
Code *string `json:"code,omitempty" jsonschema:"course code, at most 50 characters"`
Name string `json:"name" jsonschema:"course name, at most 255 characters"`
Form string `json:"form" jsonschema:"one of: wyklad, cwiczenia, konwersatorium, seminarium, inne"`
Lecturer *string `json:"lecturer,omitempty" jsonschema:"lecturer, at most 255 characters, with the title as the university writes it"`
Semester int `json:"semester" jsonschema:"semester, 1 to 4"`
ECTS *float64 `json:"ects,omitempty" jsonschema:"ECTS points, 0 to 60"`
Assessment *string `json:"assessment,omitempty" jsonschema:"form of assessment, at most 100 characters"`
ElectiveGroup *string `json:"elective_group,omitempty" jsonschema:"elective group, at most 100 characters"`
Description *string `json:"description,omitempty" jsonschema:"description"`
SyllabusURL *string `json:"syllabus_url,omitempty" jsonschema:"syllabus link, at most 2048 characters"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position within the semester, an integer"`
}
// updateCourseInput is the body of bm_manage_update_course.
type updateCourseInput struct {
ID uint `json:"id" path:"id" jsonschema:"the course id"`
Code *string `json:"code,omitempty" jsonschema:"course code, at most 50 characters"`
Name *string `json:"name,omitempty" jsonschema:"course name, at most 255 characters; required, so not null"`
Form *string `json:"form,omitempty" jsonschema:"one of: wyklad, cwiczenia, konwersatorium, seminarium, inne"`
Lecturer *string `json:"lecturer,omitempty" jsonschema:"lecturer, at most 255 characters"`
Semester *int `json:"semester,omitempty" jsonschema:"semester, 1 to 4"`
ECTS *float64 `json:"ects,omitempty" jsonschema:"ECTS points, 0 to 60"`
Assessment *string `json:"assessment,omitempty" jsonschema:"form of assessment, at most 100 characters"`
ElectiveGroup *string `json:"elective_group,omitempty" jsonschema:"elective group, at most 100 characters"`
Description *string `json:"description,omitempty" jsonschema:"description"`
SyllabusURL *string `json:"syllabus_url,omitempty" jsonschema:"syllabus link, at most 2048 characters"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position within the semester, an integer"`
}
// --- meetings ------------------------------------------------------------
// createMeetingInput is the body of bm_manage_create_meeting.
type createMeetingInput struct {
Number int `json:"number" jsonschema:"the zjazd number, 1 or more, unique"`
StartsOn string `json:"starts_on" jsonschema:"first day, YYYY-MM-DD"`
EndsOn string `json:"ends_on" jsonschema:"last day, YYYY-MM-DD, not before starts_on"`
Notes *string `json:"notes,omitempty" jsonschema:"notes"`
}
// updateMeetingInput is the body of bm_manage_update_meeting.
type updateMeetingInput struct {
ID uint `json:"id" path:"id" jsonschema:"the meeting id"`
Number *int `json:"number,omitempty" jsonschema:"the zjazd number, 1 or more, unique"`
StartsOn *string `json:"starts_on,omitempty" jsonschema:"first day, YYYY-MM-DD"`
EndsOn *string `json:"ends_on,omitempty" jsonschema:"last day, YYYY-MM-DD, not before starts_on"`
Notes *string `json:"notes,omitempty" jsonschema:"notes"`
}
// --- class sessions ------------------------------------------------------
// listClassSessionsInput filters bm_manage_list_class_sessions.
type listClassSessionsInput struct {
CourseID string `json:"course_id,omitempty" query:"course_id" jsonschema:"only sessions of this course id; null for sessions without a course"`
MeetingID string `json:"meeting_id,omitempty" query:"meeting_id" jsonschema:"only sessions of this meeting (zjazd) id; null for sessions without one"`
}
// createClassSessionInput is the body of bm_manage_create_class_session.
type createClassSessionInput struct {
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing meeting (zjazd) id"`
StartsAt string `json:"starts_at" jsonschema:"start time: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-03 08:00"`
EndsAt string `json:"ends_at" jsonschema:"end time, after starts_at: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-03 09:30"`
Room *string `json:"room,omitempty" jsonschema:"room, at most 100 characters"`
Kind *string `json:"kind,omitempty" jsonschema:"kind of class, at most 100 characters"`
Lecturer *string `json:"lecturer,omitempty" jsonschema:"lecturer, at most 255 characters"`
Notes *string `json:"notes,omitempty" jsonschema:"notes"`
IsOnline *bool `json:"is_online,omitempty" jsonschema:"true when the class is online"`
}
// updateClassSessionInput is the body of bm_manage_update_class_session.
type updateClassSessionInput struct {
ID uint `json:"id" path:"id" jsonschema:"the class session id"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing meeting (zjazd) id; null clears it"`
StartsAt *string `json:"starts_at,omitempty" jsonschema:"start time: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-03 08:00"`
EndsAt *string `json:"ends_at,omitempty" jsonschema:"end time, after starts_at: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-03 09:30"`
Room *string `json:"room,omitempty" jsonschema:"room, at most 100 characters"`
Kind *string `json:"kind,omitempty" jsonschema:"kind of class, at most 100 characters"`
Lecturer *string `json:"lecturer,omitempty" jsonschema:"lecturer, at most 255 characters"`
Notes *string `json:"notes,omitempty" jsonschema:"notes"`
IsOnline *bool `json:"is_online,omitempty" jsonschema:"true when the class is online"`
}
// --- readings ------------------------------------------------------------
// listReadingsInput filters bm_manage_list_readings.
type listReadingsInput struct {
CourseID string `json:"course_id,omitempty" query:"course_id" jsonschema:"only readings of this course id; null for readings without a course"`
MeetingID string `json:"meeting_id,omitempty" query:"meeting_id" jsonschema:"only readings of this meeting (zjazd) id; null for readings without one"`
IsRequired string `json:"is_required,omitempty" query:"is_required" jsonschema:"true for required readings only, false for optional ones only"`
}
// createReadingInput is the body of bm_manage_create_reading.
type createReadingInput struct {
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing meeting (zjazd) id"`
Title string `json:"title" jsonschema:"title, at most 500 characters"`
Author *string `json:"author,omitempty" jsonschema:"author, at most 255 characters"`
Source *string `json:"source,omitempty" jsonschema:"source (book, journal, chapter), at most 500 characters"`
URL *string `json:"url,omitempty" jsonschema:"link, at most 2048 characters"`
IsRequired *bool `json:"is_required,omitempty" jsonschema:"true when the reading is required"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position within the course, an integer"`
}
// updateReadingInput is the body of bm_manage_update_reading.
type updateReadingInput struct {
ID uint `json:"id" path:"id" jsonschema:"the reading id"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing meeting (zjazd) id; null clears it"`
Title *string `json:"title,omitempty" jsonschema:"title, at most 500 characters; required, so not null"`
Author *string `json:"author,omitempty" jsonschema:"author, at most 255 characters"`
Source *string `json:"source,omitempty" jsonschema:"source (book, journal, chapter), at most 500 characters"`
URL *string `json:"url,omitempty" jsonschema:"link, at most 2048 characters"`
IsRequired *bool `json:"is_required,omitempty" jsonschema:"true when the reading is required"`
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position within the course, an integer"`
}
// --- deadlines -----------------------------------------------------------
// listDeadlinesInput filters bm_manage_list_deadlines.
type listDeadlinesInput struct {
CourseID string `json:"course_id,omitempty" query:"course_id" jsonschema:"only deadlines of this course id; null for deadlines without a course"`
Kind string `json:"kind,omitempty" query:"kind" jsonschema:"only deadlines of this kind, one of: zaliczenie, egzamin, praca, organizacyjne, inne"`
}
// createDeadlineInput is the body of bm_manage_create_deadline.
type createDeadlineInput struct {
Title string `json:"title" jsonschema:"title, at most 255 characters"`
DueAt string `json:"due_at" jsonschema:"due time: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-03 23:59"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id"`
Kind string `json:"kind" jsonschema:"one of: zaliczenie, egzamin, praca, organizacyjne, inne"`
Description *string `json:"description,omitempty" jsonschema:"description"`
}
// updateDeadlineInput is the body of bm_manage_update_deadline.
type updateDeadlineInput struct {
ID uint `json:"id" path:"id" jsonschema:"the deadline id"`
Title *string `json:"title,omitempty" jsonschema:"title, at most 255 characters; required, so not null"`
DueAt *string `json:"due_at,omitempty" jsonschema:"due time: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-03 23:59"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id; null clears it"`
Kind *string `json:"kind,omitempty" jsonschema:"one of: zaliczenie, egzamin, praca, organizacyjne, inne"`
Description *string `json:"description,omitempty" jsonschema:"description"`
}
// --- materials -----------------------------------------------------------
// listManagedMaterialsInput is the input of bm_manage_list_materials.
type listManagedMaterialsInput struct {
Q string `json:"q,omitempty" query:"q" jsonschema:"full-text search over the title, tags, source, course, link, body and the text of attached PDFs, 2 to 100 characters; results then come by relevance, each with a short plain-text snippet when the match is in the body or a file"`
IncludeBody bool `json:"include_body,omitempty" query:"include_body" jsonschema:"true to include each material's body (it may hold transcript text)"`
}
// showManagedMaterialInput is the input of bm_manage_show_material.
type showManagedMaterialInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id"`
IncludeBody bool `json:"include_body,omitempty" query:"include_body" jsonschema:"true to include the material's body (it may hold transcript text)"`
}
// saveMaterialInput is the body of bm_manage_save_material. body, source
// and url have no omitempty: the route replaces them as sent, so the agent
// must state each (null clears it).
type saveMaterialInput struct {
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id; together with title it identifies the material (absent or null: no course)"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing meeting (zjazd) id; absent keeps the stored one, null clears it"`
Title string `json:"title" jsonschema:"title, 1 to 255 characters"`
Type string `json:"type" jsonschema:"one of: pdf, notatka, link, inne"`
Body *string `json:"body" jsonschema:"Markdown body, or null for none; replaced as sent"`
Source *string `json:"source" jsonschema:"source, at most 500 characters, or null; replaced as sent"`
URL *string `json:"url" jsonschema:"link, at most 2048 characters, or null; replaced as sent"`
PublishedAt *string `json:"published_at,omitempty" jsonschema:"publication time: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-16 20:00; absent publishes a new material now and keeps an existing one as it is; null makes a draft"`
Tags *[]string `json:"tags,omitempty" jsonschema:"topic tag names (1 to 100 characters each); absent keeps the tags, a list replaces them; tags hold topics only, the zjazd is set with meeting_id, never with a tag"`
IsPrivate *bool `json:"is_private,omitempty" jsonschema:"true makes the material private: only its author and the users it is shared with see it; absent keeps it, a new material is public"`
AuthorUserID *uint `json:"author_user_id,omitempty" jsonschema:"the author's user id from bm_manage_list_users; absent keeps it, a new material gets the caller as author; null clears it"`
ShareUserIDs *[]uint `json:"share_user_ids,omitempty" jsonschema:"user ids from bm_manage_list_users the material is shared with (at most 200); absent keeps the shares, a list replaces them"`
Revision *uint `json:"revision,omitempty" jsonschema:"the revision you last read (bm_manage_show_material); a material changed since then is refused with 409 and its current revision; absent overwrites"`
}
// updateMaterialInput is the body of bm_manage_update_material.
type updateMaterialInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id"`
CourseID *uint `json:"course_id,omitempty" jsonschema:"an existing course id (absent or null: no course)"`
MeetingID *uint `json:"meeting_id,omitempty" jsonschema:"an existing meeting (zjazd) id; absent keeps the stored one, null clears it"`
Title string `json:"title" jsonschema:"title, 1 to 255 characters"`
Type string `json:"type" jsonschema:"one of: pdf, notatka, link, inne"`
Body *string `json:"body" jsonschema:"Markdown body, or null for none; replaced as sent"`
Source *string `json:"source" jsonschema:"source, at most 500 characters, or null; replaced as sent"`
URL *string `json:"url" jsonschema:"link, at most 2048 characters, or null; replaced as sent"`
PublishedAt *string `json:"published_at,omitempty" jsonschema:"publication time: RFC 3339, or Europe/Warsaw wall clock such as 2026-10-16 20:00; absent keeps it; null makes a draft"`
Tags *[]string `json:"tags,omitempty" jsonschema:"topic tag names (1 to 100 characters each); absent keeps the tags, a list replaces them; tags hold topics only, the zjazd is set with meeting_id, never with a tag"`
IsPrivate *bool `json:"is_private,omitempty" jsonschema:"true makes the material private: only its author and the users it is shared with see it; absent keeps it, a new material is public"`
AuthorUserID *uint `json:"author_user_id,omitempty" jsonschema:"the author's user id from bm_manage_list_users; absent keeps it, a new material gets the caller as author; null clears it"`
ShareUserIDs *[]uint `json:"share_user_ids,omitempty" jsonschema:"user ids from bm_manage_list_users the material is shared with (at most 200); absent keeps the shares, a list replaces them"`
Revision *uint `json:"revision,omitempty" jsonschema:"the revision you last read (bm_manage_show_material); a material changed since then is refused with 409 and its current revision; absent overwrites"`
}
// materialVisibilityInput is the body of bm_manage_set_material_visibility.
type materialVisibilityInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id"`
IsPrivate bool `json:"is_private" jsonschema:"true: only the author and the users it is shared with see it; false: every student sees it"`
}
// materialSharesInput is the body of bm_manage_set_material_shares.
type materialSharesInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id"`
UserIDs []uint `json:"user_ids" jsonschema:"user ids from bm_manage_list_users, at most 200; the list replaces the shares, an empty list removes them"`
}
// manageTools are the tools over the management API (/api/v1/bm): typed
// CRUD of the BM tables (D-13). The routes' user.scope and user.permission
// middleware filter the listing, so only a user whose groups hold the
// jz.bm.access_* codes sees them, and write tools only with the write
// grant. There is no tool for POST /seed or GET /me, and no dry_run (D-14).
func manageTools() []pact.MCPTool {
tool := func(name, title, desc, method, path string, input any) pact.MCPTool {
return pact.MCPTool{Name: name, Title: title, Description: desc, Guard: "user", Method: method, Path: ManagePrefix + path, Input: input}
}
g, po, pa, pu, d := http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodPut, http.MethodDelete
return []pact.MCPTool{
tool("manage_list_courses", "List courses (manage)",
"Lists every course as rows of columns, ordered by semester and position, optionally filtered."+readCourses,
g, "/courses", listCoursesInput{}),
tool("manage_show_course", "Show a course (manage)",
"Returns one course; 404 when unknown."+recordAnswer+readCourses,
g, "/courses/{id}", idInput{}),
tool("manage_create_course", "Create a course",
"Creates a course."+recordAnswer+invalidAnswer+writeCourses,
po, "/courses", createCourseInput{}),
tool("manage_update_course", "Update a course",
"Updates one course."+patchSemantics+recordAnswer+invalidAnswer+writeCourses,
pa, "/courses/{id}", updateCourseInput{}),
tool("manage_list_meetings", "List meetings (manage)",
"Lists every zjazd (meeting) as rows of columns, ordered by number."+readSchedule,
g, "/meetings", noInput{}),
tool("manage_show_meeting", "Show a meeting (manage)",
"Returns one zjazd (meeting); 404 when unknown."+recordAnswer+readSchedule,
g, "/meetings/{id}", idInput{}),
tool("manage_create_meeting", "Create a meeting",
"Creates a zjazd (meeting)."+recordAnswer+invalidAnswer+writeSchedule,
po, "/meetings", createMeetingInput{}),
tool("manage_update_meeting", "Update a meeting",
"Updates one zjazd (meeting)."+patchSemantics+recordAnswer+invalidAnswer+writeSchedule,
pa, "/meetings/{id}", updateMeetingInput{}),
tool("manage_list_class_sessions", "List class sessions (manage)",
"Lists every class session as rows of columns, ordered by start time, optionally filtered by course or meeting."+readSchedule,
g, "/class-sessions", listClassSessionsInput{}),
tool("manage_show_class_session", "Show a class session (manage)",
"Returns one class session; 404 when unknown."+recordAnswer+readSchedule,
g, "/class-sessions/{id}", idInput{}),
tool("manage_create_class_session", "Create a class session",
"Creates a class session; course_id and meeting_id must exist."+recordAnswer+invalidAnswer+writeSchedule,
po, "/class-sessions", createClassSessionInput{}),
tool("manage_update_class_session", "Update a class session",
"Updates one class session."+patchSemantics+recordAnswer+invalidAnswer+writeSchedule,
pa, "/class-sessions/{id}", updateClassSessionInput{}),
tool("manage_delete_class_session", "Delete a class session",
"Deletes one class session; 404 when unknown."+deleteForever+writeSchedule,
d, "/class-sessions/{id}", idInput{}),
tool("manage_list_readings", "List readings (manage)",
"Lists every reading as rows of columns, ordered by course and position, optionally filtered."+readCourses,
g, "/readings", listReadingsInput{}),
tool("manage_show_reading", "Show a reading (manage)",
"Returns one reading; 404 when unknown."+recordAnswer+readCourses,
g, "/readings/{id}", idInput{}),
tool("manage_create_reading", "Create a reading",
"Creates a reading; course_id and meeting_id must exist."+recordAnswer+invalidAnswer+writeCourses,
po, "/readings", createReadingInput{}),
tool("manage_update_reading", "Update a reading",
"Updates one reading."+patchSemantics+recordAnswer+invalidAnswer+writeCourses,
pa, "/readings/{id}", updateReadingInput{}),
tool("manage_delete_reading", "Delete a reading",
"Deletes one reading with every student's read and owned marks of it; 404 when unknown."+deleteForever+writeCourses,
d, "/readings/{id}", idInput{}),
tool("manage_list_deadlines", "List deadlines (manage)",
"Lists every deadline as rows of columns, ordered by due time, optionally filtered by course or kind."+readSchedule,
g, "/deadlines", listDeadlinesInput{}),
tool("manage_show_deadline", "Show a deadline (manage)",
"Returns one deadline; 404 when unknown."+recordAnswer+readSchedule,
g, "/deadlines/{id}", idInput{}),
tool("manage_create_deadline", "Create a deadline",
"Creates a deadline; course_id must exist."+recordAnswer+invalidAnswer+writeSchedule,
po, "/deadlines", createDeadlineInput{}),
tool("manage_update_deadline", "Update a deadline",
"Updates one deadline."+patchSemantics+recordAnswer+invalidAnswer+writeSchedule,
pa, "/deadlines/{id}", updateDeadlineInput{}),
tool("manage_delete_deadline", "Delete a deadline",
"Deletes one deadline; 404 when unknown."+deleteForever+writeSchedule,
d, "/deadlines/{id}", idInput{}),
tool("manage_list_materials", "List materials (manage)",
"Lists every material, drafts and private ones included, newest first, or by relevance with q, with course, zjazd, type, source, link, publication time and tags (and the snippet with q); 503 when search is unavailable. "+MCPMaterialPrivacy+readMaterials,
g, "/materials", listManagedMaterialsInput{}),
tool("manage_show_material", "Show a material (manage)",
"Returns one material, draft or not, with its revision and its public files (id, absolute link, name, size and type); 404 when unknown. "+MCPMaterialPrivacy+readMaterials,
g, "/materials/{id}", showManagedMaterialInput{}),
tool("manage_save_material", "Save a material",
"Creates a material, or updates the one with the same title and course (answer created true or false); a renamed material is a new one here, use bm_manage_update_material to rename. is_private, author_user_id and share_user_ids set its visibility, author and shares (a new material is public, with the caller as author)."+replacedAsSent+revisionChecked+" "+MCPMaterialPrivacy+invalidAnswer+writeMaterials,
po, "/materials", saveMaterialInput{}),
tool("manage_update_material", "Update a material",
"Updates one material, so its title or course can change; 404 when unknown, 422 when another material has the same title and course. is_private, author_user_id and share_user_ids change its visibility, author and shares when sent."+replacedAsSent+revisionChecked+" "+MCPMaterialPrivacy+invalidAnswer+writeMaterials,
pu, "/materials/{id}", updateMaterialInput{}),
tool("manage_delete_material", "Delete a material",
"Deletes one material with all its files; 404 when unknown."+deleteForever+" "+MCPMaterialPrivacy+writeMaterials,
d, "/materials/{id}", idInput{}),
tool("manage_set_material_visibility", "Set a material's visibility",
"Makes a material private or public: private means only its author and the users it is shared with see it in the student app and the student tools, public means every student; a material without an author gets the caller as author; 404 when unknown. "+MCPMaterialPrivacy+invalidAnswer+writeMaterials,
pa, "/materials/{id}/visibility", materialVisibilityInput{}),
tool("manage_set_material_shares", "Share a material with users",
"Sets the users a material is shared with: the list replaces them (an empty list removes them); shares matter only while the material is private; ids come from bm_manage_list_users; a material without an author gets the caller as author; 404 when unknown. "+MCPMaterialPrivacy+invalidAnswer+writeMaterials,
pu, "/materials/{id}/shares", materialSharesInput{}),
tool("manage_list_users", "List users (manage)",
"Lists the id, display name and email of every user, to pick a material's author or the users it is shared with."+readMaterials,
g, "/users", noInput{}),
}
}

220
mcp_student.go Normal file
View File

@@ -0,0 +1,220 @@
package bm
import (
"net/http"
"git.golem15.com/golem15/summercms/modules/pact"
)
// MCPMaterialPrivacy is the sentence every material tool description
// carries (D-17, D-21).
const MCPMaterialPrivacy = "Returns metadata and links, never whole file contents; with q a material may carry a short plain-text snippet of the matched passage, possibly from an attached file; a material's body (possible transcript text) is left out unless include_body is true."
// The sentences every student tool description ends with (D-15).
const (
needsScopeRead = " Needs scope read."
needsScopeWrite = " Needs scope write."
)
// noInput is the input of a tool that takes no arguments.
type noInput struct{}
// idInput names one record by its id.
type idInput struct {
ID uint `json:"id" path:"id" jsonschema:"the record id, as listed by the matching list tool"`
}
// readingIDInput names one reading by its id.
type readingIDInput struct {
ID uint `json:"id" path:"id" jsonschema:"the reading id, as listed by bm_readings or bm_course"`
}
// materialIDInput names one material by its id.
type materialIDInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id, as listed by bm_materials, bm_material or bm_course"`
}
// coursesInput is the input of bm_courses.
type coursesInput struct {
Semester int `json:"semester,omitempty" query:"semester" jsonschema:"only courses of this semester, 1 to 4"`
}
// rangeInput is the input of bm_schedule and bm_deadlines.
type rangeInput struct {
From string `json:"from,omitempty" query:"from" jsonschema:"first day, YYYY-MM-DD (default: today)"`
To string `json:"to,omitempty" query:"to" jsonschema:"last day (inclusive), YYYY-MM-DD, not before from (default: no end)"`
}
// readingsInput is the input of bm_readings.
type readingsInput struct {
Course uint `json:"course,omitempty" query:"course" jsonschema:"only readings of this course id"`
}
// materialsInput is the input of bm_materials.
type materialsInput struct {
Q string `json:"q,omitempty" query:"q" jsonschema:"full-text search over the title, tags, source, course, link, body and the text of attached PDFs, 2 to 100 characters; results then come by relevance, each with a short plain-text snippet when the match is in the body or a file"`
Course uint `json:"course,omitempty" query:"course" jsonschema:"only materials of this course id"`
Meeting uint `json:"meeting,omitempty" query:"meeting" jsonschema:"only materials of this zjazd (meeting) id"`
Tag string `json:"tag,omitempty" query:"tag" jsonschema:"only materials with this tag slug, at most 100 characters"`
Type string `json:"type,omitempty" query:"type" jsonschema:"only materials of this type, one of: pdf, notatka, link, inne"`
Page int `json:"page,omitempty" query:"page" jsonschema:"page number, 1 or more (default 1)"`
PerPage int `json:"per_page,omitempty" query:"per_page" jsonschema:"materials per page, 1 to 100"`
}
// materialInput is the input of bm_material.
type materialInput struct {
ID uint `json:"id" path:"id" jsonschema:"the material id, as listed by bm_materials"`
IncludeBody bool `json:"include_body,omitempty" query:"include_body" jsonschema:"true to include the material's body (it may hold transcript text)"`
}
// boolPtr returns a pointer to b, for the tool annotations.
func boolPtr(b bool) *bool { return &b }
// studentTools are the tools over the token twins of the student API. Each
// call runs as the session's user, who reaches only their own progress and
// published data, as on the HTTP API (D-09).
func studentTools() []pact.MCPTool {
return []pact.MCPTool{
{
Name: "dashboard",
Title: "BM dashboard",
Description: "Returns the student's dashboard: the next class sessions, the deadlines not yet due, the zjazd (meeting) under way today and the next one, and the student's reading progress counts." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/dashboard",
Input: noInput{},
},
{
Name: "courses",
Title: "BM courses",
Description: "Lists the programme's courses with code, form, lecturer, semester, ECTS, assessment, syllabus link and counters." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/courses",
Input: coursesInput{},
},
{
Name: "course",
Title: "BM course",
Description: "Returns one course with its description, syllabus link, counters, class sessions, readings (with the student's read and owned marks) and the published materials the student may see (public ones and private ones they wrote or that are shared with them)." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/courses/{id}",
Input: idInput{},
},
{
Name: "schedule",
Title: "BM schedule",
Description: "Lists the class sessions starting in a date range (default: from today, no end) with course, zjazd, start and end time, room, kind, lecturer, notes and whether the class is online." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/schedule",
Input: rangeInput{},
},
{
Name: "meetings",
Title: "BM meetings",
Description: "Lists the zjazdy (weekend meetings) with number, first and last day, notes and the number of class sessions in each." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/meetings",
Input: noInput{},
},
{
Name: "deadlines",
Title: "BM deadlines",
Description: "Lists the deadlines due in a date range (default: from today, no end) with title, due time, kind, course and description." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/deadlines",
Input: rangeInput{},
},
{
Name: "readings",
Title: "BM readings",
Description: "Lists readings with author, source, link, course, zjazd, whether required, and the student's read and owned marks." + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/readings",
Input: readingsInput{},
},
{
Name: "mark_reading_read",
Title: "Mark a reading as read",
Description: "Marks a reading as read by the signed-in student and returns the reading id with the read time. Marking again keeps the first time." + needsScopeWrite,
Guard: "user",
Method: http.MethodPut,
Path: TokenPrefix + "/readings/{id}/progress",
Input: readingIDInput{},
},
{
Name: "unmark_reading_read",
Title: "Unmark a reading as read",
Description: "Removes the signed-in student's read mark from a reading (it can be marked again) and returns the reading id with an empty read time." + needsScopeWrite,
Guard: "user",
Method: http.MethodDelete,
Path: TokenPrefix + "/readings/{id}/progress",
Input: readingIDInput{},
Destructive: boolPtr(false),
Idempotent: boolPtr(true),
},
{
Name: "mark_reading_owned",
Title: "Mark a reading as owned",
Description: "Marks that the signed-in student has a copy of a reading and returns the reading id with the owned time." + needsScopeWrite,
Guard: "user",
Method: http.MethodPut,
Path: TokenPrefix + "/readings/{id}/owned",
Input: readingIDInput{},
},
{
Name: "unmark_reading_owned",
Title: "Unmark a reading as owned",
Description: "Removes the signed-in student's owned mark from a reading (it can be marked again) and returns the reading id with an empty owned time." + needsScopeWrite,
Guard: "user",
Method: http.MethodDelete,
Path: TokenPrefix + "/readings/{id}/owned",
Input: readingIDInput{},
Destructive: boolPtr(false),
Idempotent: boolPtr(true),
},
{
Name: "materials",
Title: "BM materials",
Description: "Lists a page of the published materials the student may see (public ones and private ones they wrote or that are shared with them): without q the student's own pinned materials first (newest pin first), then newest first; with q by relevance (pins are then only marked). Each row has title, type, course, zjazd, source, link, tags, file count and whether the student pinned it (and the snippet with q), plus the page meta. " + MCPMaterialPrivacy + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/materials",
Input: materialsInput{},
},
{
Name: "material",
Title: "BM material",
Description: "Returns one published material the student may see (public ones and private ones they wrote or that are shared with them) with its tags, its files (id, absolute link, name, size and type) and whether the student pinned it. " + MCPMaterialPrivacy + needsScopeRead,
Guard: "user",
Method: http.MethodGet,
Path: TokenPrefix + "/materials/{id}",
Input: materialInput{},
},
{
Name: "pin_material",
Title: "Pin a material",
Description: "Pins a material the signed-in student may see, for this student only (nobody else sees the pin): bm_materials without q then lists it first, newest pin first, and the material answers carry pinned true. Pinning again keeps the first pin time. Answers with no content; a material the student cannot see is not found. " + MCPMaterialPrivacy + needsScopeWrite,
Guard: "user",
Method: http.MethodPut,
Path: TokenPrefix + "/materials/{id}/pin",
Input: materialIDInput{},
},
{
Name: "unpin_material",
Title: "Unpin a material",
Description: "Removes the signed-in student's own pin from a material (it can be pinned again); unpinning a material that is not pinned is not an error. Answers with no content. " + MCPMaterialPrivacy + needsScopeWrite,
Guard: "user",
Method: http.MethodDelete,
Path: TokenPrefix + "/materials/{id}/pin",
Input: materialIDInput{},
Destructive: boolPtr(false),
Idempotent: boolPtr(true),
},
}
}

773
mcp_test.go Normal file
View File

@@ -0,0 +1,773 @@
package bm_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"slices"
"strconv"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/pier"
"git.golem15.com/golem15/summercms/modules/surf"
bm "git.golem15.com/jakub/sm-bm-plugin"
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
// mountHost adapts a built surf router to pier.Host for a compile-only
// mount: pier compiles every declared tool against the real route table.
type mountHost struct{ r *surf.Router }
func (h mountHost) Routes() []pier.RouteInfo {
var out []pier.RouteInfo
for _, ri := range h.r.Routes() {
out = append(out, pier.RouteInfo{Method: ri.Method, Pattern: ri.Pattern, PluginID: ri.PluginID, Middleware: ri.Middleware})
}
return out
}
func (h mountHost) Handler(method, pattern string) (http.Handler, bool) {
return h.r.Handler(method, pattern)
}
func (mountHost) MountStream(string, string, http.Handler, ...string) error { return nil }
func (mountHost) MountJSON(string, string, http.Handler) error { return nil }
func (h mountHost) Owner(method, path string) (string, bool) {
for _, ri := range h.r.Routes() {
if ri.Method == method && ri.Pattern == path {
return ri.PluginID, true
}
}
return "", false
}
// pinnedTools is the sorted tool list of golem15.user plus jz.bm.
var pinnedTools = []string{
"bm_add_checklist_item",
"bm_checklist",
"bm_checklists",
"bm_course",
"bm_courses",
"bm_create_checklist",
"bm_dashboard",
"bm_deadlines",
"bm_delete_checklist",
"bm_delete_checklist_item",
"bm_manage_attach_material_file",
"bm_manage_create_class_session",
"bm_manage_create_course",
"bm_manage_create_deadline",
"bm_manage_create_material_upload",
"bm_manage_create_meeting",
"bm_manage_create_reading",
"bm_manage_delete_class_session",
"bm_manage_delete_deadline",
"bm_manage_delete_material",
"bm_manage_delete_reading",
"bm_manage_detach_material_file",
"bm_manage_list_class_sessions",
"bm_manage_list_courses",
"bm_manage_list_deadlines",
"bm_manage_list_materials",
"bm_manage_list_meetings",
"bm_manage_list_readings",
"bm_manage_list_users",
"bm_manage_save_material",
"bm_manage_set_material_shares",
"bm_manage_set_material_visibility",
"bm_manage_show_class_session",
"bm_manage_show_course",
"bm_manage_show_deadline",
"bm_manage_show_material",
"bm_manage_show_meeting",
"bm_manage_show_reading",
"bm_manage_update_class_session",
"bm_manage_update_course",
"bm_manage_update_deadline",
"bm_manage_update_material",
"bm_manage_update_meeting",
"bm_manage_update_reading",
"bm_mark_checklist_item_done",
"bm_mark_reading_owned",
"bm_mark_reading_read",
"bm_material",
"bm_materials",
"bm_meetings",
"bm_pin_material",
"bm_readings",
"bm_schedule",
"bm_unmark_checklist_item_done",
"bm_unmark_reading_owned",
"bm_unmark_reading_read",
"bm_unpin_material",
"bm_update_checklist",
"bm_update_checklist_item",
"user_me",
}
// queryKeys are the query keys each handler reads, by tool name: the
// student handlers' query(r, ...) and the management record Filters
// (routes.go) plus include_body of the material views. A tool query field
// outside these would be sent and silently ignored.
var queryKeys = map[string][]string{
"manage_list_courses": {"semester", "form", "code"},
"manage_list_class_sessions": {"course_id", "meeting_id"},
"manage_list_readings": {"course_id", "meeting_id", "is_required"},
"manage_list_deadlines": {"course_id", "kind"},
"manage_list_materials": {"q", "include_body"},
"manage_show_material": {"include_body"},
"courses": {"semester"},
"schedule": {"from", "to"},
"deadlines": {"from", "to"},
"readings": {"course"},
"checklists": {"meeting"},
"materials": {"q", "course", "meeting", "tag", "type", "page", "per_page"},
"material": {"include_body"},
}
// bmTools returns jz.bm's declared tools.
func bmTools() []pact.MCPTool {
return (&bm.Plugin{}).MCP().Tools
}
// TestBMMCP (criterion 4, D-09, D-14, D-15) mounts pier against golem15.user
// and jz.bm without a database and pins the compiled tools; every tool binds
// a token-guarded jz.bm route, names its scope, and reads only keys the
// route reads. Runs under -short.
func TestBMMCP(t *testing.T) {
tools := bmTools()
t.Run("compiles", func(t *testing.T) {
app := backpack.New(testConfig(t))
if err := app.Config.Set("app.url", "https://bm.example.test"); err != nil {
t.Fatal(err)
}
plugins := activate(t, app)
router, err := surf.BuildRouter(app, plugins)
if err != nil {
t.Fatalf("BuildRouter: %v", err)
}
if err := app.Config.Set(pier.EnabledKey, true); err != nil {
t.Fatal(err)
}
if err := pier.Mount(mountHost{r: router}, app, plugins); err != nil {
t.Fatalf("pier.Mount: %v", err)
}
p, ok := app.Lookup[*pier.Pier]()
if !ok {
t.Fatal("pier was not mounted")
}
if got := p.ToolNames(); !slices.Equal(got, pinnedTools) {
t.Fatalf("compiled tools %v, want %v", got, pinnedTools)
}
})
t.Run("routes", func(t *testing.T) {
for _, tool := range tools {
if !strings.HasPrefix(tool.Path, bm.TokenPrefix+"/") && !strings.HasPrefix(tool.Path, bm.ManagePrefix+"/") {
t.Errorf("%s binds %s, outside %s and %s", tool.Name, tool.Path, bm.TokenPrefix, bm.ManagePrefix)
}
if tool.Guard != "user" {
t.Errorf("%s: Guard %q, want user", tool.Name, tool.Guard)
}
}
})
t.Run("descriptions", func(t *testing.T) {
for _, tool := range tools {
if !strings.Contains(tool.Description, "Needs scope read") && !strings.Contains(tool.Description, "Needs scope write") {
t.Errorf("%s: description does not name its scope: %q", tool.Name, tool.Description)
}
if tool.Title == "" {
t.Errorf("%s has no title", tool.Name)
}
}
})
t.Run("inputs", func(t *testing.T) {
for _, tool := range tools {
rt := reflect.TypeOf(tool.Input)
for rt.Kind() == reflect.Pointer {
rt = rt.Elem()
}
if rt.Kind() != reflect.Struct {
t.Errorf("%s: input is %s, not a struct", tool.Name, rt.Kind())
continue
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
key, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if key == "dry_run" {
t.Errorf("%s has a dry_run field (D-14)", tool.Name)
}
switch {
case f.Tag.Get("path") != "":
if !strings.Contains(tool.Path, "{"+f.Tag.Get("path")+"}") {
t.Errorf("%s.%s: path tag %q not in %s", tool.Name, f.Name, f.Tag.Get("path"), tool.Path)
}
case f.Tag.Get("query") != "":
if !slices.Contains(queryKeys[tool.Name], f.Tag.Get("query")) {
t.Errorf("%s.%s: query key %q is not one the handler reads", tool.Name, f.Name, f.Tag.Get("query"))
}
default:
if tool.Method == http.MethodGet || tool.Method == http.MethodDelete {
t.Errorf("%s.%s: a %s tool carries a body field %q", tool.Name, f.Name, tool.Method, key)
}
}
}
}
})
t.Run("management", func(t *testing.T) {
testManageTools(t, tools)
})
}
// recordModel is what the management record tests read of a model.
type recordModel interface {
Fillable() []string
Rules() map[string]string
}
// manageTables maps a management path segment to its model (nil for
// materials and users), its permission code and whether the route can
// delete.
var manageTables = map[string]struct {
model recordModel
perm string
deletable bool
}{
"courses": {models.Course{}, "jz.bm.access_courses", false},
"meetings": {models.Meeting{}, "jz.bm.access_schedule", false},
"class-sessions": {models.ClassSession{}, "jz.bm.access_schedule", true},
"readings": {models.Reading{}, "jz.bm.access_courses", true},
"deadlines": {models.Deadline{}, "jz.bm.access_schedule", true},
"materials": {nil, "jz.bm.access_materials", true},
"users": {nil, "jz.bm.access_materials", false},
}
// materialBodyKeys are the keys POST and PUT /materials read (materialInput).
var materialBodyKeys = []string{"course_id", "meeting_id", "title", "type", "body", "source", "url", "published_at", "tags", "is_private", "author_user_id", "share_user_ids", "revision"}
// accessBodyKeys are the body keys of each material access tool, exactly,
// and whether each is optional.
var accessBodyKeys = map[string]map[string]bool{
"manage_set_material_visibility": {"is_private": false},
"manage_set_material_shares": {"user_ids": false},
}
// bodyFields returns the JSON keys of a tool input's body fields and
// whether each is optional (omitempty).
func bodyFields(input any) map[string]bool {
rt := reflect.TypeOf(input)
for rt.Kind() == reflect.Pointer {
rt = rt.Elem()
}
out := map[string]bool{}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.Tag.Get("path") != "" || f.Tag.Get("query") != "" {
continue
}
key, opts, _ := strings.Cut(f.Tag.Get("json"), ",")
out[key] = strings.Contains(opts, "omitempty")
}
return out
}
// requiredColumns are the columns whose rules start with or contain
// required.
func requiredColumns(m recordModel) []string {
var out []string
for col, rule := range m.Rules() {
if slices.Contains(strings.Split(rule, "|"), "required") {
out = append(out, col)
}
}
return out
}
// testManageTools (D-13, D-14, D-15, D-22) checks the management tools
// against the routes and the models.
func testManageTools(t *testing.T, tools []pact.MCPTool) {
t.Helper()
deletes := map[string]bool{}
manage := 0
for _, tool := range tools {
if !strings.HasPrefix(tool.Name, "manage_") {
if !strings.HasPrefix(tool.Path, bm.TokenPrefix+"/") {
t.Errorf("%s binds %s, outside the token twins", tool.Name, tool.Path)
}
continue
}
manage++
if !strings.HasPrefix(tool.Path, bm.ManagePrefix+"/") {
t.Errorf("%s binds %s, outside %s", tool.Name, tool.Path, bm.ManagePrefix)
continue
}
rest := strings.TrimPrefix(tool.Path, bm.ManagePrefix+"/")
segment, _, _ := strings.Cut(rest, "/")
table, ok := manageTables[segment]
if !ok {
t.Errorf("%s binds %s, not a managed table (seed and me are not tools)", tool.Name, tool.Path)
continue
}
if !strings.Contains(tool.Description, "Needs scope") || !strings.Contains(tool.Description, "jz.bm.access_") {
t.Errorf("%s: description names no scope or permission: %q", tool.Name, tool.Description)
}
if !strings.Contains(tool.Description, table.perm) {
t.Errorf("%s: description does not name %s", tool.Name, table.perm)
}
if tool.Method == http.MethodDelete {
deletes[segment] = true
if !table.deletable {
t.Errorf("%s deletes %s, which the route cannot", tool.Name, segment)
}
if !strings.Contains(tool.Description, "cannot be undone") {
t.Errorf("%s: description does not say the delete cannot be undone", tool.Name)
}
}
fields := bodyFields(tool.Input)
if segment == "materials" && strings.Contains(rest, "/files") {
testFileTool(t, tool, fields)
if tool.Method == http.MethodDelete {
deletes[segment] = true
}
continue
}
if segment == "materials" && (strings.HasSuffix(rest, "/visibility") || strings.HasSuffix(rest, "/shares")) {
if want, ok := accessBodyKeys[tool.Name]; !ok || !reflect.DeepEqual(fields, want) {
t.Errorf("%s: body keys %v, want %v", tool.Name, fields, accessBodyKeys[tool.Name])
}
if !strings.Contains(tool.Description, bm.MCPMaterialPrivacy) {
t.Errorf("%s: description lacks the material privacy sentence", tool.Name)
}
continue
}
if segment == "materials" {
if !strings.Contains(tool.Description, bm.MCPMaterialPrivacy) {
t.Errorf("%s: description lacks the material privacy sentence", tool.Name)
}
for key := range fields {
if !slices.Contains(materialBodyKeys, key) {
t.Errorf("%s: body key %q is not a material key", tool.Name, key)
}
}
if tool.Method == http.MethodPost || tool.Method == http.MethodPut {
for _, key := range []string{"title", "type", "body", "source", "url"} {
if optional, ok := fields[key]; !ok || optional {
t.Errorf("%s: %s must be a required field (present %v)", tool.Name, key, ok)
}
}
if !strings.Contains(tool.Description, "replaced as sent") {
t.Errorf("%s: description does not say body, source and url are replaced as sent", tool.Name)
}
}
continue
}
if table.model == nil {
continue
}
fillable := table.model.Fillable()
for key := range fields {
if !slices.Contains(fillable, key) {
t.Errorf("%s: body key %q is not a Fillable column of %s", tool.Name, key, segment)
}
}
switch tool.Method {
case http.MethodPost:
for _, col := range fillable {
if _, ok := fields[col]; !ok {
t.Errorf("%s: Fillable column %s has no field", tool.Name, col)
}
}
for _, col := range requiredColumns(table.model) {
if optional, ok := fields[col]; !ok || optional {
t.Errorf("%s: required column %s is not a required field", tool.Name, col)
}
}
case http.MethodPatch:
for _, col := range fillable {
if optional, ok := fields[col]; !ok || !optional {
t.Errorf("%s: column %s must be an optional field (present %v)", tool.Name, col, ok)
}
}
}
}
if manage != manageToolCount {
t.Errorf("%d management tools, want %d", manage, manageToolCount)
}
want := map[string]bool{"class-sessions": true, "readings": true, "deadlines": true, "materials": true}
if !reflect.DeepEqual(deletes, want) {
t.Errorf("delete tools for %v, want %v", deletes, want)
}
}
// manageToolCount is the number of management tools: 28 record and
// material tools, the material file tools, the two material access tools
// and the user list.
const manageToolCount = 34
// fileBodyKeys are the body keys of each material file tool, exactly.
var fileBodyKeys = map[string]map[string]bool{
"manage_attach_material_file": {"name": false, "mime": true, "content_base64": false},
"manage_detach_material_file": {},
"manage_create_material_upload": {},
}
// testFileTool (D-10, D-11, D-17) checks one material file tool: its body
// keys, the public-file warning and the privacy sentence, and that the
// detach tool is destructive.
func testFileTool(t *testing.T, tool pact.MCPTool, fields map[string]bool) {
t.Helper()
want, ok := fileBodyKeys[tool.Name]
if !ok {
t.Errorf("%s: not a known material file tool", tool.Name)
return
}
if !reflect.DeepEqual(fields, want) {
t.Errorf("%s: body keys (optional) %v, want %v", tool.Name, fields, want)
}
if !strings.Contains(tool.Description, api.MaterialFileWarning) {
t.Errorf("%s: description lacks the public-file warning", tool.Name)
}
if !strings.Contains(tool.Description, bm.MCPMaterialPrivacy) {
t.Errorf("%s: description lacks the material privacy sentence", tool.Name)
}
if !strings.Contains(tool.Description, "Needs scope write and the jz.bm.access_materials permission") {
t.Errorf("%s: description does not name scope write and jz.bm.access_materials", tool.Name)
}
rt := reflect.TypeOf(tool.Input)
idPath := false
for i := 0; i < rt.NumField(); i++ {
if rt.Field(i).Tag.Get("path") == "id" {
idPath = true
}
}
if !idPath {
t.Errorf("%s: no id path field", tool.Name)
}
if tool.Name == "manage_create_material_upload" {
for _, s := range []string{"10 minutes", "curl", "50 MB", "once"} {
if !strings.Contains(tool.Description, s) {
t.Errorf("%s: description does not mention %q", tool.Name, s)
}
}
}
if tool.Name == "manage_detach_material_file" {
if tool.Method != http.MethodDelete || (tool.Destructive != nil && !*tool.Destructive) {
t.Errorf("%s is not destructive (method %s)", tool.Name, tool.Method)
}
} else if tool.Method == http.MethodDelete || (tool.Destructive != nil && *tool.Destructive) {
t.Errorf("%s is destructive", tool.Name)
}
}
// studentRoutes are the routes mountStudent registers, in order.
var studentRoutes = []string{
"GET /dashboard",
"GET /courses",
"GET /courses/{id}",
"GET /schedule",
"GET /meetings",
"GET /deadlines",
"GET /readings",
"PUT /readings/{id}/progress",
"DELETE /readings/{id}/progress",
"PUT /readings/{id}/owned",
"DELETE /readings/{id}/owned",
"GET /materials",
"GET /materials/{id}",
"PUT /materials/{id}/pin",
"DELETE /materials/{id}/pin",
"GET /checklists",
"POST /checklists",
"GET /checklists/{id}",
"PATCH /checklists/{id}",
"DELETE /checklists/{id}",
"POST /checklists/{id}/items",
"PATCH /checklist-items/{id}",
"DELETE /checklist-items/{id}",
"PUT /checklist-items/{id}/done",
"DELETE /checklist-items/{id}/done",
}
// authorRoutes are the author's material routes under APIPrefix: JWT only,
// with no token twin.
var authorRoutes = []string{
"GET /materials/{id}/access",
"PUT /materials/{id}/access",
"PUT /materials/{id}",
"GET /tags",
"POST /materials/{id}/unpublish",
"POST /materials/{id}/images",
}
// TestTokenMirrorRoutes is the invariant of the two student surfaces: every
// student route exists under APIPrefix (jwt.auth, no user.* middleware) and
// under TokenPrefix (user.api_token, the token bucket and the matching
// scope, no jwt.auth); the calendar feed and the chat have no twin.
func TestTokenMirrorRoutes(t *testing.T) {
app := backpack.New(testConfig(t))
plugins := activate(t, app)
router, err := surf.BuildRouter(app, plugins)
if err != nil {
t.Fatalf("BuildRouter: %v", err)
}
byRoute := map[string][]string{}
for _, rt := range router.Routes() {
if rt.PluginID != "jz.bm" {
continue
}
byRoute[rt.Method+" "+rt.Pattern] = rt.Middleware
if strings.HasPrefix(rt.Pattern, bm.TokenPrefix+"/") {
rest := strings.TrimPrefix(rt.Pattern, bm.TokenPrefix)
if !slices.Contains(studentRoutes, rt.Method+" "+rest) {
t.Errorf("%s %s under the token prefix is not a student route", rt.Method, rt.Pattern)
}
}
}
for _, route := range studentRoutes {
method, pattern, _ := strings.Cut(route, " ")
jwt, ok := byRoute[method+" "+bm.APIPrefix+pattern]
if !ok {
t.Errorf("%s %s is not registered", method, bm.APIPrefix+pattern)
} else {
if !slices.Contains(jwt, "jwt.auth") {
t.Errorf("%s %s lacks jwt.auth: %v", method, bm.APIPrefix+pattern, jwt)
}
if slices.ContainsFunc(jwt, func(name string) bool { return strings.HasPrefix(name, "user.") }) {
t.Errorf("%s %s carries user.* middleware: %v", method, bm.APIPrefix+pattern, jwt)
}
}
tok, ok := byRoute[method+" "+bm.TokenPrefix+pattern]
if !ok {
t.Errorf("%s %s (the token twin) is not registered", method, bm.TokenPrefix+pattern)
continue
}
scope := "user.scope:write"
if method == http.MethodGet {
scope = "user.scope:read"
}
for _, name := range []string{"user.api_token", "throttle:jz.bm.token", scope} {
if !slices.Contains(tok, name) {
t.Errorf("%s %s lacks %s: %v", method, bm.TokenPrefix+pattern, name, tok)
}
}
if slices.Contains(tok, "jwt.auth") {
t.Errorf("%s %s carries jwt.auth: %v", method, bm.TokenPrefix+pattern, tok)
}
if slices.Index(tok, "user.api_token") > slices.Index(tok, "throttle:jz.bm.token") {
t.Errorf("%s %s: the token bucket runs before the guard: %v", method, bm.TokenPrefix+pattern, tok)
}
}
for route := range byRoute {
if strings.Contains(route, bm.TokenPrefix+"/calendar-feed") || strings.Contains(route, bm.TokenPrefix+"/chat") {
t.Errorf("%s has a token twin", route)
}
}
// The author's routes (D-07) are JWT-only, like the access panel.
for _, route := range authorRoutes {
method, pattern, _ := strings.Cut(route, " ")
jwt, ok := byRoute[method+" "+bm.APIPrefix+pattern]
if !ok {
t.Errorf("%s %s is not registered", method, bm.APIPrefix+pattern)
} else if !slices.Contains(jwt, "jwt.auth") {
t.Errorf("%s %s lacks jwt.auth: %v", method, bm.APIPrefix+pattern, jwt)
}
if _, ok := byRoute[method+" "+bm.TokenPrefix+pattern]; ok {
t.Errorf("%s %s has a token twin", method, bm.TokenPrefix+pattern)
}
}
}
// dispatched returns r as pier dispatches it in-process: the api_token
// marker with principal id on its context.
func dispatched(r *http.Request, id uint) *http.Request {
return r.WithContext(bouncer.WithDispatch(r.Context(), &bouncer.Dispatch{
Guards: []string{"api_token"},
Principal: &bouncer.Principal{ID: id},
}))
}
// TestMCPLinks (D-16): under MCP every string under url or *_url that starts
// with a single / becomes absolute; other keys, protocol-relative and
// absolute URLs, error answers and plain HTTP answers are left alone.
func TestMCPLinks(t *testing.T) {
const answer = `{"data":{"url":"/storage/x","files":[{"url":"/storage/y","name":"/n"}],"syllabus_url":"/sylabusy/z.pdf","link":"https://x.test/a","other":"/keep","cdn_url":"//cdn.test/a","abs_url":"https://y.test/b","count":12345678901234567890,"nested":{"items":[{"thumb_url":"/t.png"}]}}}`
mw := (&bm.Plugin{}).Middlewares()[bm.MiddlewareMCPLinks]
if mw == nil {
t.Fatalf("%s is not exported", bm.MiddlewareMCPLinks)
}
handler := func(status int, body string) http.Handler {
return mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
}
t.Run("plain HTTP untouched", func(t *testing.T) {
rec := httptest.NewRecorder()
handler(http.StatusOK, answer).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if rec.Body.String() != answer {
t.Errorf("plain answer = %s, want it unchanged", rec.Body.String())
}
})
t.Run("MCP answer absolute", func(t *testing.T) {
rec := httptest.NewRecorder()
handler(http.StatusOK, answer).ServeHTTP(rec, dispatched(httptest.NewRequest(http.MethodGet, "/", nil), 7))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
if cl := rec.Header().Get("Content-Length"); cl != strconv.Itoa(rec.Body.Len()) {
t.Errorf("Content-Length = %s, body is %d bytes", cl, rec.Body.Len())
}
dec := json.NewDecoder(bytes.NewReader(rec.Body.Bytes()))
dec.UseNumber()
var got struct {
Data map[string]any `json:"data"`
}
if err := dec.Decode(&got); err != nil {
t.Fatalf("decode %s: %v", rec.Body.String(), err)
}
d := got.Data
want := map[string]string{
"url": "http://example.com/storage/x",
"syllabus_url": "http://example.com/sylabusy/z.pdf",
"link": "https://x.test/a",
"other": "/keep",
"cdn_url": "//cdn.test/a",
"abs_url": "https://y.test/b",
}
for k, v := range want {
if d[k] != v {
t.Errorf("%s = %v, want %s", k, d[k], v)
}
}
file := d["files"].([]any)[0].(map[string]any)
if file["url"] != "http://example.com/storage/y" || file["name"] != "/n" {
t.Errorf("files[0] = %v", file)
}
thumb := d["nested"].(map[string]any)["items"].([]any)[0].(map[string]any)
if thumb["thumb_url"] != "http://example.com/t.png" {
t.Errorf("nested thumb_url = %v", thumb["thumb_url"])
}
if n, _ := d["count"].(json.Number); n.String() != "12345678901234567890" {
t.Errorf("count = %v, want the number kept exactly", d["count"])
}
})
t.Run("MCP forwarded scheme", func(t *testing.T) {
rec := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Host = "bm.example.test"
r.Header.Set("X-Forwarded-Proto", "https")
handler(http.StatusOK, `{"url":"/a"}`).ServeHTTP(rec, dispatched(r, 7))
if !strings.Contains(rec.Body.String(), `"https://bm.example.test/a"`) {
t.Errorf("answer = %s", rec.Body.String())
}
})
t.Run("MCP error untouched", func(t *testing.T) {
const notFound = `{"error":"not_found","url":"/x"}`
rec := httptest.NewRecorder()
handler(http.StatusNotFound, notFound).ServeHTTP(rec, dispatched(httptest.NewRequest(http.MethodGet, "/", nil), 7))
if rec.Code != http.StatusNotFound || rec.Body.String() != notFound {
t.Errorf("error answer = %d %s", rec.Code, rec.Body.String())
}
})
}
// TestManageBucketKey (research Pitfall 6): a dispatched management call is
// throttled per user, a bearer request per token hash, a bare one per IP;
// the token twins are throttled per user.
func TestManageBucketKey(t *testing.T) {
buckets := (&bm.Plugin{}).Buckets()
manage, ok := buckets["jz.bm.manage"]
if !ok {
t.Fatal("jz.bm.manage is not declared")
}
if manage.Max != 120 {
t.Errorf("jz.bm.manage Max = %d, want 120", manage.Max)
}
if got := manage.Key(dispatched(httptest.NewRequest(http.MethodGet, "/", nil), 7)); got != "jz.bm.manage.user|7" {
t.Errorf("dispatched key = %q, want jz.bm.manage.user|7", got)
}
bearer := httptest.NewRequest(http.MethodGet, "/", nil)
bearer.Header.Set("Authorization", "Bearer usr_secret")
if got := manage.Key(bearer); !strings.HasPrefix(got, "jz.bm.manage.token|") || strings.Contains(got, "usr_secret") {
t.Errorf("bearer key = %q, want the token hash", got)
}
if got := manage.Key(httptest.NewRequest(http.MethodGet, "/", nil)); !strings.HasPrefix(got, "jz.bm.manage.ip|") {
t.Errorf("bare key = %q, want the IP", got)
}
ip, ok := buckets["jz.bm.upload-ip"]
if !ok || ip.Max != 10 {
t.Errorf("jz.bm.upload-ip declared %v with Max %d, want 10", ok, ip.Max)
} else if got := ip.Key(httptest.NewRequest(http.MethodPost, "/", nil)); !strings.HasPrefix(got, "jz.bm.upload.ip|") {
t.Errorf("upload IP key = %q", got)
}
ticket, ok := buckets["jz.bm.upload-ticket"]
if !ok || ticket.Max != 3 {
t.Errorf("jz.bm.upload-ticket declared %v with Max %d, want 3", ok, ticket.Max)
} else {
r := httptest.NewRequest(http.MethodPost, "/", nil)
r.SetPathValue("ticket", "secret-ticket.mac")
sum := sha256.Sum256([]byte("secret-ticket.mac"))
if got, want := ticket.Key(r), "jz.bm.upload.ticket|"+hex.EncodeToString(sum[:])[:32]; got != want {
t.Errorf("upload ticket key = %q, want %q", got, want)
}
}
token, ok := buckets["jz.bm.token"]
if !ok {
t.Fatal("jz.bm.token is not declared")
}
r := httptest.NewRequest(http.MethodGet, "/", nil)
r = r.WithContext(bouncer.WithUser(context.Background(), &bouncer.Principal{ID: 7}))
if got := token.Key(r); got != "jz.bm.token|u:7" {
t.Errorf("token twin key = %q, want jz.bm.token|u:7", got)
}
}
// TestAuthorBucketKeys: the author's material routes are throttled per user,
// each under its own name, so an editor's saves and uploads never use up
// the unpublish budget.
func TestAuthorBucketKeys(t *testing.T) {
buckets := (&bm.Plugin{}).Buckets()
req := httptest.NewRequest(http.MethodPut, "/", nil)
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: 7}))
keys := map[string]bool{}
for name, max := range map[string]int{"jz.bm.material-edit": 30, "jz.bm.material-images": 30, "jz.bm.material-unpublish": 10} {
b, ok := buckets[name]
if !ok {
t.Errorf("%s is not declared", name)
continue
}
if b.Max != max {
t.Errorf("%s Max = %d, want %d", name, b.Max, max)
}
key := b.Key(req)
if key != name+"|u:7" {
t.Errorf("%s key = %q, want %s|u:7", name, key, name)
}
keys[key] = true
if got := b.Key(httptest.NewRequest(http.MethodPut, "/", nil)); !strings.HasPrefix(got, name+"|ip:") {
t.Errorf("%s bare key = %q, want the IP", name, got)
}
}
if len(keys) != 3 {
t.Errorf("keys = %v, want three distinct counters", keys)
}
}

45
models/checklist.go Normal file
View File

@@ -0,0 +1,45 @@
package models
import (
"time"
"gorm.io/gorm"
)
// Checklist is a user's own list of things to do, usually the preparation
// for one zjazd. Only its owner (a golem15.user users row) sees it.
type Checklist struct {
ID uint `gorm:"column:id;primaryKey"`
UserID uint `gorm:"column:user_id"`
MeetingID *uint `gorm:"column:meeting_id"`
Meeting *Meeting `gorm:"foreignKey:MeetingID"`
Title string `gorm:"column:title"`
Description *string `gorm:"column:description"`
SortOrder int `gorm:"column:sort_order"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
// TableName is the plugin table.
func (Checklist) TableName() string { return "jz_bm_checklists" }
// Fillable lists the columns the student API may set; user_id comes from
// the caller.
func (Checklist) Fillable() []string {
return []string{"meeting_id", "title", "description", "sort_order"}
}
// Rules are checked by the student API on every save.
func (Checklist) Rules() map[string]string {
return map[string]string{
"title": "required|max:255",
"description": "nullable|max:10000",
"sort_order": "nullable|integer",
}
}
// BeforeSave stores NULL for empty optional text.
func (c *Checklist) BeforeSave(*gorm.DB) error {
blank(&c.Description)
return nil
}

64
models/checklist_item.go Normal file
View File

@@ -0,0 +1,64 @@
package models
import (
"time"
"gorm.io/gorm"
)
// ChecklistItemKinds lists the allowed ChecklistItem.Kind values.
var ChecklistItemKinds = []string{"lektura", "artykul", "ksiazka", "prezentacja", "zadanie", "inne"}
// ChecklistItem is one entry of a Checklist. It may point at a reading, a
// deadline, a material or a course, and name a deck of golem15.presentations
// by slug. An item with a reading is done when the checklist's owner has
// read it (ReadingProgress); any other item is done when DoneAt is set.
type ChecklistItem struct {
ID uint `gorm:"column:id;primaryKey"`
ChecklistID uint `gorm:"column:checklist_id"`
Kind string `gorm:"column:kind"`
Title string `gorm:"column:title"`
Notes *string `gorm:"column:notes"`
URL *string `gorm:"column:url"`
CourseID *uint `gorm:"column:course_id"`
ReadingID *uint `gorm:"column:reading_id"`
DeadlineID *uint `gorm:"column:deadline_id"`
MaterialID *uint `gorm:"column:material_id"`
PresentationSlug *string `gorm:"column:presentation_slug"`
DueAt *time.Time `gorm:"column:due_at"`
EstimateMinutes *int `gorm:"column:estimate_minutes"`
SortOrder int `gorm:"column:sort_order"`
DoneAt *time.Time `gorm:"column:done_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
// TableName is the plugin table.
func (ChecklistItem) TableName() string { return "jz_bm_checklist_items" }
// Fillable lists the columns the student API may set. checklist_id moves an
// item to another of the caller's checklists; done_at is set by the done
// routes only.
func (ChecklistItem) Fillable() []string {
return []string{"checklist_id", "kind", "title", "notes", "url", "course_id", "reading_id", "deadline_id",
"material_id", "presentation_slug", "due_at", "estimate_minutes", "sort_order"}
}
// Rules are checked by the student API on every save.
func (ChecklistItem) Rules() map[string]string {
return map[string]string{
"kind": "required|in:lektura,artykul,ksiazka,prezentacja,zadanie,inne",
"title": "required|max:500",
"notes": "nullable|max:10000",
"url": "nullable|max:2048",
"presentation_slug": "nullable|max:255",
"estimate_minutes": "nullable|integer|min:0|max:10000",
"sort_order": "nullable|integer",
}
}
// BeforeSave stores NULL for empty optional text.
func (i *ChecklistItem) BeforeSave(*gorm.DB) error {
blank(&i.Notes, &i.URL, &i.PresentationSlug)
return nil
}

View File

@@ -19,6 +19,7 @@ type ClassSession struct {
EndsAt time.Time `gorm:"column:ends_at"` EndsAt time.Time `gorm:"column:ends_at"`
Room *string `gorm:"column:room"` Room *string `gorm:"column:room"`
Kind *string `gorm:"column:kind"` Kind *string `gorm:"column:kind"`
Lecturer *string `gorm:"column:lecturer"`
Notes *string `gorm:"column:notes"` Notes *string `gorm:"column:notes"`
IsOnline bool `gorm:"column:is_online"` IsOnline bool `gorm:"column:is_online"`
CreatedAt time.Time `gorm:"column:created_at"` CreatedAt time.Time `gorm:"column:created_at"`
@@ -31,7 +32,7 @@ func (ClassSession) TableName() string { return "jz_bm_class_sessions" }
// Fillable lists the columns mass assignment may set. course_id and // Fillable lists the columns mass assignment may set. course_id and
// meeting_id are set through the admin relation pickers. // meeting_id are set through the admin relation pickers.
func (ClassSession) Fillable() []string { func (ClassSession) Fillable() []string {
return []string{"course_id", "meeting_id", "starts_at", "ends_at", "room", "kind", "notes", "is_online"} return []string{"course_id", "meeting_id", "starts_at", "ends_at", "room", "kind", "lecturer", "notes", "is_online"}
} }
// Rules are checked by the admin API on every save. // Rules are checked by the admin API on every save.
@@ -41,6 +42,7 @@ func (ClassSession) Rules() map[string]string {
"ends_at": "required", "ends_at": "required",
"room": "nullable|max:100", "room": "nullable|max:100",
"kind": "nullable|max:100", "kind": "nullable|max:100",
"lecturer": "nullable|max:255",
"is_online": "boolean", "is_online": "boolean",
} }
} }
@@ -57,6 +59,6 @@ func (s *ClassSession) TemporalErrors() map[string][]string {
// BeforeSave stores NULL for empty optional text. // BeforeSave stores NULL for empty optional text.
func (s *ClassSession) BeforeSave(*gorm.DB) error { func (s *ClassSession) BeforeSave(*gorm.DB) error {
blank(&s.Room, &s.Kind, &s.Notes) blank(&s.Room, &s.Kind, &s.Lecturer, &s.Notes)
return nil return nil
} }

View File

@@ -35,10 +35,15 @@ fields:
label: jz.bm::lang.sessions.kind label: jz.bm::lang.sessions.kind
type: text type: text
span: right span: right
lecturer:
label: jz.bm::lang.sessions.lecturer
comment: jz.bm::lang.sessions.lecturer_comment
type: text
span: left
is_online: is_online:
label: jz.bm::lang.sessions.is_online label: jz.bm::lang.sessions.is_online
type: switch type: switch
span: left span: right
notes: notes:
label: jz.bm::lang.common.notes label: jz.bm::lang.common.notes
type: textarea type: textarea

View File

@@ -26,10 +26,15 @@ fields:
label: jz.bm::lang.sessions.kind label: jz.bm::lang.sessions.kind
type: text type: text
span: right span: right
lecturer:
label: jz.bm::lang.sessions.lecturer
comment: jz.bm::lang.sessions.lecturer_comment
type: text
span: left
is_online: is_online:
label: jz.bm::lang.sessions.is_online label: jz.bm::lang.sessions.is_online
type: switch type: switch
span: left span: right
notes: notes:
label: jz.bm::lang.common.notes label: jz.bm::lang.common.notes
type: textarea type: textarea

View File

@@ -18,19 +18,29 @@ const MaterialFilesField = "files"
// Material is a study material: a note, a link or uploaded files, optionally // Material is a study material: a note, a link or uploaded files, optionally
// tied to a course. A material without published_at is a draft and is not // tied to a course. A material without published_at is a draft and is not
// served by the API. // served by the API. A private material is visible only to its author and to
// the users it is shared with (MaterialShare); a public one to every student.
type Material struct { type Material struct {
ID uint `gorm:"column:id;primaryKey"` ID uint `gorm:"column:id;primaryKey"`
CourseID *uint `gorm:"column:course_id"` CourseID *uint `gorm:"column:course_id"`
Course *Course `gorm:"foreignKey:CourseID"` Course *Course `gorm:"foreignKey:CourseID"`
Title string `gorm:"column:title"` MeetingID *uint `gorm:"column:meeting_id"`
Type string `gorm:"column:type"` Meeting *Meeting `gorm:"foreignKey:MeetingID"`
Body *string `gorm:"column:body"` Title string `gorm:"column:title"`
Source *string `gorm:"column:source"` Type string `gorm:"column:type"`
URL *string `gorm:"column:url"` Body *string `gorm:"column:body"`
PublishedAt *time.Time `gorm:"column:published_at"` Source *string `gorm:"column:source"`
CreatedAt time.Time `gorm:"column:created_at"` URL *string `gorm:"column:url"`
UpdatedAt time.Time `gorm:"column:updated_at"` PublishedAt *time.Time `gorm:"column:published_at"`
IsPrivate bool `gorm:"column:is_private"`
AuthorUserID *uint `gorm:"column:author_user_id"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
// Revision goes up by one on every content change (ReviseMaterial).
// It is read-only for GORM, so a full-row Save of a stale in-memory
// model never writes an old revision back; only ReviseMaterial changes
// it.
Revision uint `gorm:"column:revision;->"`
Tags []Tag `gorm:"many2many:jz_bm_material_tag;joinForeignKey:material_id;joinReferences:tag_id"` Tags []Tag `gorm:"many2many:jz_bm_material_tag;joinForeignKey:material_id;joinReferences:tag_id"`
} }
@@ -43,7 +53,7 @@ func (Material) MorphName() string { return `Jz\Bm\Models\Material` }
// Fillable lists the columns mass assignment may set. // Fillable lists the columns mass assignment may set.
func (Material) Fillable() []string { func (Material) Fillable() []string {
return []string{"course_id", "title", "type", "body", "source", "url", "published_at"} return []string{"course_id", "meeting_id", "title", "type", "body", "source", "url", "published_at", "is_private", "author_user_id"}
} }
// Rules are checked by the admin API on every save. // Rules are checked by the admin API on every save.

View File

@@ -0,0 +1,18 @@
package models
import "time"
// MaterialFileText is the text extracted from one PDF attached to a
// material. An empty Text means the file was extracted and held none (a
// scan or a broken PDF). Truncated is set when the text was cut at the
// extraction cap. The row goes with its file (foreign-key cascade).
type MaterialFileText struct {
FileID uint `gorm:"column:file_id;primaryKey;autoIncrement:false"`
MaterialID uint `gorm:"column:material_id"`
Text string `gorm:"column:text"`
Truncated bool `gorm:"column:truncated"`
ExtractedAt time.Time `gorm:"column:extracted_at"`
}
// TableName is the file text table.
func (MaterialFileText) TableName() string { return "jz_bm_material_file_texts" }

16
models/material_pin.go Normal file
View File

@@ -0,0 +1,16 @@
package models
import "time"
// MaterialPin is a personal pin: one row per material and user (a
// golem15.user users row). Only that user sees it, and it lists the
// material first on their own Materiały list.
type MaterialPin struct {
ID uint `gorm:"column:id;primaryKey"`
MaterialID uint `gorm:"column:material_id"`
UserID uint `gorm:"column:user_id"`
PinnedAt time.Time `gorm:"column:pinned_at"`
}
// TableName is the plugin table.
func (MaterialPin) TableName() string { return "jz_bm_material_pins" }

114
models/material_revision.go Normal file
View File

@@ -0,0 +1,114 @@
package models
import (
"encoding/json"
"slices"
"strings"
"gorm.io/gorm"
)
// A material's revision counts changes to its content only (D-03): the
// title, type, body, source, url, course, zjazd (meeting) and tag set.
// Visibility, shares, publication, the author and attached files never bump
// it, so a writer holding an older revision is refused only when the note
// itself changed since.
// materialFingerprint is the content of a material that its revision
// counts, in a fixed key order.
type materialFingerprint 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"`
Tags []string `json:"tags"`
}
// MaterialFingerprint is the comparable form of m's content with the given
// tag slugs: two materials with the same fingerprint have the same content
// under D-03. Blank optional text counts as null, as BeforeSave stores it,
// and the tag order does not matter. published_at, is_private, the author
// and the shares are not inputs.
func MaterialFingerprint(m Material, tagSlugs []string) string {
body, source, url := m.Body, m.Source, m.URL
blank(&body, &source, &url)
tags := slices.Clone(tagSlugs)
if tags == nil {
tags = []string{}
}
slices.Sort(tags)
raw, _ := json.Marshal(materialFingerprint{
CourseID: m.CourseID,
MeetingID: m.MeetingID,
Title: m.Title,
Type: m.Type,
Body: body,
Source: source,
URL: url,
Tags: tags,
})
return string(raw)
}
// materialState reads the content fingerprint and the revision of material
// id through tx; a missing row is gorm.ErrRecordNotFound.
func materialState(tx *gorm.DB, id uint) (string, uint, error) {
db := tx.Session(&gorm.Session{NewDB: true})
var m Material
res := db.Select("id", "course_id", "meeting_id", "title", "type", "body", "source", "url", "revision").
Where("id = ?", id).Limit(1).Find(&m)
if res.Error != nil {
return "", 0, res.Error
}
if res.RowsAffected == 0 {
return "", 0, gorm.ErrRecordNotFound
}
var slugs []string
err := db.Table(Tag{}.TableName()).
Joins("JOIN "+MaterialTag{}.TableName()+" ON "+MaterialTag{}.TableName()+".tag_id = "+Tag{}.TableName()+".id").
Where(MaterialTag{}.TableName()+".material_id = ?", id).
Pluck(Tag{}.TableName()+".slug", &slugs).Error
if err != nil {
return "", 0, err
}
for i := range slugs {
slugs[i] = strings.TrimSpace(slugs[i])
}
return MaterialFingerprint(m, slugs), m.Revision, nil
}
// MaterialContent reads the content fingerprint (MaterialFingerprint) of
// material id and its tags through tx. A writer takes it before a write and
// hands it to ReviseMaterial after; a missing row is gorm.ErrRecordNotFound.
func MaterialContent(tx *gorm.DB, id uint) (string, error) {
fp, _, err := materialState(tx, id)
return fp, err
}
// ReviseMaterial bumps the revision of material id by one when its content
// read through tx differs from before (a MaterialContent taken before the
// write), and answers the revision the row has then and whether it went
// up. Only content counts (D-03): a write that changed only visibility,
// shares, publication or files, or that sent identical content, keeps the
// revision. It is the only writer of the revision column, which GORM treats
// as read-only.
func ReviseMaterial(tx *gorm.DB, id uint, before string) (uint, bool, error) {
after, current, err := materialState(tx, id)
if err != nil {
return 0, false, err
}
if after == before {
return current, false, nil
}
var revision uint
err = tx.Session(&gorm.Session{NewDB: true}).
Raw("UPDATE jz_bm_materials SET revision = revision + 1 WHERE id = ? RETURNING revision", id).
Scan(&revision).Error
if err != nil {
return 0, false, err
}
return revision, true, nil
}

View File

@@ -0,0 +1,63 @@
package models_test
import (
"testing"
"time"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
func TestMaterialFingerprint(t *testing.T) {
str := func(s string) *string { return &s }
id := func(n uint) *uint { return &n }
base := func() models.Material {
return models.Material{
ID: 7, CourseID: id(1), MeetingID: id(2), Title: "Definicje", Type: "notatka",
Body: str("# Robertson\n"), Source: str("wykład"), URL: str("https://example.test/a"),
}
}
tags := []string{"globalizacja", "teoria-2"}
want := models.MaterialFingerprint(base(), tags)
if got := models.MaterialFingerprint(base(), []string{"teoria-2", "globalizacja"}); got != want {
t.Errorf("tag order changed the fingerprint: %s != %s", got, want)
}
changes := map[string]func(m *models.Material, tags *[]string){
"title": func(m *models.Material, _ *[]string) { m.Title = "Inne" },
"type": func(m *models.Material, _ *[]string) { m.Type = "link" },
"body": func(m *models.Material, _ *[]string) { m.Body = str("# Robertson\n\nwięcej\n") },
"source": func(m *models.Material, _ *[]string) { m.Source = str("seminarium") },
"url": func(m *models.Material, _ *[]string) { m.URL = str("https://example.test/b") },
"course": func(m *models.Material, _ *[]string) { m.CourseID = id(3) },
"no course": func(m *models.Material, _ *[]string) { m.CourseID = nil },
"meeting": func(m *models.Material, _ *[]string) { m.MeetingID = id(4) },
"tag": func(_ *models.Material, tags *[]string) { *tags = append(*tags, "nowy") },
"untag": func(_ *models.Material, tags *[]string) { *tags = (*tags)[:1] },
}
for name, change := range changes {
m, ts := base(), append([]string(nil), tags...)
change(&m, &ts)
if got := models.MaterialFingerprint(m, ts); got == want {
t.Errorf("a %s change kept the fingerprint", name)
}
}
empty, null := base(), base()
empty.Body, empty.Source, empty.URL = str(""), str(" "), str("")
null.Body, null.Source, null.URL = nil, nil, nil
if models.MaterialFingerprint(empty, tags) != models.MaterialFingerprint(null, tags) {
t.Error("blank and nil optional text give different fingerprints")
}
if models.MaterialFingerprint(base(), nil) != models.MaterialFingerprint(base(), []string{}) {
t.Error("nil and empty tag lists give different fingerprints")
}
now := time.Now()
other := base()
other.ID, other.PublishedAt, other.IsPrivate, other.AuthorUserID = 8, &now, true, id(9)
other.UpdatedAt, other.Revision = now, 5
if got := models.MaterialFingerprint(other, tags); got != want {
t.Errorf("published_at, is_private, author, id or revision changed the fingerprint: %s != %s", got, want)
}
}

237
models/material_search.go Normal file
View File

@@ -0,0 +1,237 @@
package models
import (
"context"
"regexp"
"strconv"
"strings"
"gorm.io/gorm"
)
// A material is kept in the search index jz_bm_materials (beachcomber). The
// index holds every material, drafts and private ones included: visibility
// is enforced only in SQL, where the engine's ids are candidates that the
// student queries re-gate. This file is hand-written; material.go is
// generated.
// SearchableAs is the index name without the search.prefix.
func (Material) SearchableAs() string { return "jz_bm_materials" }
// ShouldBeSearchable is true for every material: the index carries no
// visibility, so drafts and private materials are indexed too.
func (m *Material) ShouldBeSearchable() bool { return m != nil }
// ToSearchableArray builds the document of the material. beachcomber reloads
// the row by primary key without preloads, so the course, the meeting number
// and the tags are loaded here.
func (m *Material) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]any, error) {
db = db.WithContext(ctx)
var course *Course
if m.CourseID != nil {
var c Course
res := db.Where("id = ?", *m.CourseID).Limit(1).Find(&c)
if res.Error != nil {
return nil, res.Error
}
if res.RowsAffected > 0 {
course = &c
}
}
meetingNumber := 0
if m.MeetingID != nil {
var mt Meeting
res := db.Where("id = ?", *m.MeetingID).Limit(1).Find(&mt)
if res.Error != nil {
return nil, res.Error
}
if res.RowsAffected > 0 {
meetingNumber = mt.Number
}
}
var tags []Tag
err := db.Model(&Tag{}).
Joins("JOIN jz_bm_material_tag mt ON mt.tag_id = jz_bm_tags.id").
Where("mt.material_id = ?", m.ID).
Order("jz_bm_tags.name").
Find(&tags).Error
if err != nil {
return nil, err
}
files, err := IndexedFiles(db, []uint{m.ID}, true)
if err != nil {
return nil, err
}
texts := make([]string, 0, len(files[m.ID]))
for _, f := range files[m.ID] {
texts = append(texts, f.Text)
}
return MaterialDocument(*m, course, meetingNumber, tags, texts), nil
}
// IndexedFile is one entry of a material document's file_texts: the file,
// its name and, when asked for, its extracted text.
type IndexedFile struct {
FileID uint
FileName string
Text string
}
// IndexedFiles returns, per material id, the files whose text the search
// document holds, in document order: the current public files of the
// material's files field that have a non-empty extracted text, by
// sort_order (nulls last) and id. It is the one query that decides what
// file_texts holds, so a snippet's array index maps back to a file through
// it. A detached file is no longer a current file, so its text drops out
// even before the cascade removes it. The text is read only when withText.
func IndexedFiles(db *gorm.DB, materialIDs []uint, withText bool) (map[uint][]IndexedFile, error) {
out := map[uint][]IndexedFile{}
if len(materialIDs) == 0 {
return out, nil
}
ids := make([]string, 0, len(materialIDs))
for _, id := range materialIDs {
ids = append(ids, strconv.FormatUint(uint64(id), 10))
}
cols := "system_files.id AS file_id, system_files.file_name, system_files.attachment_id"
if withText {
cols += ", t.text"
}
var rows []struct {
FileID uint
FileName string
AttachmentID string
Text string
}
err := db.Table("system_files").
Select(cols).
Joins("JOIN jz_bm_material_file_texts t ON t.file_id = system_files.id").
Where("system_files.attachment_type = ? AND system_files.field = ? AND system_files.is_public", Material{}.MorphName(), MaterialFilesField).
Where("system_files.attachment_id IN ?", ids).
Where("t.text <> ''").
Order("system_files.attachment_id, system_files.sort_order NULLS LAST, system_files.id").
Scan(&rows).Error
if err != nil {
return nil, err
}
for _, r := range rows {
n, err := strconv.ParseUint(r.AttachmentID, 10, 64)
if err != nil {
continue
}
id := uint(n)
out[id] = append(out[id], IndexedFile{FileID: r.FileID, FileName: r.FileName, Text: r.Text})
}
return out, nil
}
// MaterialDocument is the search document of m with its course, meeting
// number (0 when none), tags in order and the texts of its attached files.
// Absent numbers are 0, so filters and the sort tiebreak never see a
// missing value.
func MaterialDocument(m Material, course *Course, meetingNumber int, tags []Tag, fileTexts []string) map[string]any {
doc := map[string]any{
"id": strconv.FormatUint(uint64(m.ID), 10),
"title": m.Title,
"type": m.Type,
"course_id": int64(0),
"meeting_id": int64(0),
"published_at": int64(0),
}
if m.Source != nil && strings.TrimSpace(*m.Source) != "" {
doc["source"] = *m.Source
}
if m.URL != nil && strings.TrimSpace(*m.URL) != "" {
doc["url"] = *m.URL
}
if m.CourseID != nil {
doc["course_id"] = int64(*m.CourseID)
}
if m.MeetingID != nil {
doc["meeting_id"] = int64(*m.MeetingID)
}
if m.PublishedAt != nil {
doc["published_at"] = m.PublishedAt.Unix()
}
if course != nil {
label := course.Name
if course.Code != nil && strings.TrimSpace(*course.Code) != "" {
label = strings.TrimSpace(label + " " + strings.TrimSpace(*course.Code))
}
doc["course"] = label
}
if meetingNumber > 0 {
doc["meeting_number"] = meetingNumber
}
names := make([]string, 0, len(tags))
slugs := make([]string, 0, len(tags))
for _, t := range tags {
names = append(names, t.Name)
slugs = append(slugs, t.Slug)
}
doc["tags"] = names
doc["tag_slugs"] = slugs
if m.Body != nil {
if body := MaterialPlainBody(*m.Body); body != "" {
doc["body"] = body
}
}
if len(fileTexts) > 0 {
doc["file_texts"] = fileTexts
}
return doc
}
// SearchIndexSchema is the Typesense collection schema. It applies only when
// the collection is created; bm:materials-reindex --fresh recreates it.
// Every field is stored (a search leaves body and file_texts out of the
// answer instead), and no field sets a locale: the default one folds
// diacritics, so lodz finds Łódź.
func (Material) SearchIndexSchema() map[string]any {
return map[string]any{
"fields": []map[string]any{
{"name": "id", "type": "string"},
{"name": "title", "type": "string"},
{"name": "source", "type": "string", "optional": true},
{"name": "url", "type": "string", "optional": true},
{"name": "tags", "type": "string[]", "optional": true},
{"name": "tag_slugs", "type": "string[]", "optional": true},
{"name": "course", "type": "string", "optional": true},
{"name": "course_id", "type": "int64"},
{"name": "meeting_id", "type": "int64"},
{"name": "meeting_number", "type": "int32", "optional": true},
{"name": "type", "type": "string"},
{"name": "published_at", "type": "int64"},
{"name": "body", "type": "string", "optional": true},
{"name": "file_texts", "type": "string[]", "optional": true},
},
}
}
var (
mdImage = regexp.MustCompile(`!\[([^\]]*)\]\([^)]*\)`)
mdLink = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
mdHeading = regexp.MustCompile(`(?m)^[ \t]{0,3}#{1,6}[ \t]+`)
mdQuote = regexp.MustCompile(`(?m)^([ \t]{0,3}>[ \t]?)+`)
mdList = regexp.MustCompile(`(?m)^[ \t]*([-+*]|\d+[.)])[ \t]+`)
mdEmphasis = regexp.MustCompile(`\*+|~~`)
mdUnderStart = regexp.MustCompile(`(^|[^\p{L}\p{N}_])_+`)
mdUnderEnd = regexp.MustCompile(`_+([^\p{L}\p{N}_]|$)`)
)
// MaterialPlainBody drops the Markdown syntax of a material body (heading
// hashes, blockquote and list markers, emphasis, inline code ticks, link
// and image syntax down to their text) and collapses white space, so the
// index holds and highlights only words.
func MaterialPlainBody(body string) string {
s := strings.ReplaceAll(body, "`", "")
s = mdImage.ReplaceAllString(s, "$1")
s = mdLink.ReplaceAllString(s, "$1")
s = mdHeading.ReplaceAllString(s, "")
s = mdQuote.ReplaceAllString(s, "")
s = mdList.ReplaceAllString(s, "")
s = mdEmphasis.ReplaceAllString(s, "")
s = mdUnderStart.ReplaceAllString(s, "$1")
s = mdUnderEnd.ReplaceAllString(s, "$1")
return strings.Join(strings.Fields(s), " ")
}

View File

@@ -0,0 +1,134 @@
package models_test
import (
"slices"
"testing"
"time"
"git.golem15.com/jakub/sm-bm-plugin/models"
)
func TestMaterialSearchSchema(t *testing.T) {
m := models.Material{}
if got := m.SearchableAs(); got != "jz_bm_materials" {
t.Errorf("SearchableAs = %q, want jz_bm_materials", got)
}
fields, ok := m.SearchIndexSchema()["fields"].([]map[string]any)
if !ok || len(fields) == 0 {
t.Fatalf("schema fields = %#v", m.SearchIndexSchema()["fields"])
}
byName := map[string]map[string]any{}
for _, f := range fields {
name, _ := f["name"].(string)
typ, _ := f["type"].(string)
if name == "" || typ == "" {
t.Errorf("field without a name or type: %v", f)
}
if _, ok := f["locale"]; ok {
t.Errorf("field %s sets a locale; the default one folds Polish diacritics", name)
}
if store, ok := f["store"]; ok && store == false {
t.Errorf("field %s turns storage off", name)
}
byName[name] = f
}
for _, name := range []string{"body", "file_texts"} {
f, ok := byName[name]
if !ok {
t.Errorf("schema has no %s field", name)
continue
}
if f["optional"] != true {
t.Errorf("%s is not optional", name)
}
}
if byName["body"]["type"] != "string" || byName["file_texts"]["type"] != "string[]" {
t.Errorf("body %v, file_texts %v: want string and string[]", byName["body"]["type"], byName["file_texts"]["type"])
}
for _, name := range []string{"id", "title", "source", "url", "tags", "tag_slugs", "course", "course_id", "meeting_id", "meeting_number", "type", "published_at"} {
if _, ok := byName[name]; !ok {
t.Errorf("schema has no %s field", name)
}
}
if !(&m).ShouldBeSearchable() {
t.Error("a material is not searchable")
}
var nilMaterial *models.Material
if nilMaterial.ShouldBeSearchable() {
t.Error("a nil material is searchable")
}
}
func TestMaterialDocument(t *testing.T) {
plain := models.MaterialPlainBody("# Nagłówek\n\nTekst **pogrubienie** i _kursywa_ oraz [tekst](https://x) i ![obraz](a.png).\n\n> cytat\n> dalej\n\n- punkt `kod` snake_case")
want := "Nagłówek Tekst pogrubienie i kursywa oraz tekst i obraz. cytat dalej punkt kod snake_case"
if plain != want {
t.Errorf("MaterialPlainBody =\n%q\nwant\n%q", plain, want)
}
code := "BM-12"
course := &models.Course{ID: 4, Name: "Bezpieczeństwo", Code: &code}
courseID, meetingID := uint(4), uint(9)
at := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC)
body := "## Wstęp\n\n**Globalizacja** w praktyce"
source := "Giddens"
m := models.Material{ID: 12, Title: "Globalizacja", Type: "notatka", CourseID: &courseID, MeetingID: &meetingID, PublishedAt: &at, Body: &body, Source: &source}
tags := []models.Tag{{Name: "Globalizacja", Slug: "globalizacja"}, {Name: "Polityka", Slug: "polityka"}}
doc := models.MaterialDocument(m, course, 3, tags, []string{"tekst pliku"})
checks := map[string]any{
"id": "12",
"title": "Globalizacja",
"type": "notatka",
"source": "Giddens",
"course": "Bezpieczeństwo BM-12",
"course_id": int64(4),
"meeting_id": int64(9),
"meeting_number": 3,
"published_at": at.Unix(),
"body": "Wstęp Globalizacja w praktyce",
}
for k, v := range checks {
if doc[k] != v {
t.Errorf("doc[%s] = %#v, want %#v", k, doc[k], v)
}
}
if got, _ := doc["tags"].([]string); !slices.Equal(got, []string{"Globalizacja", "Polityka"}) {
t.Errorf("tags = %v", doc["tags"])
}
if got, _ := doc["tag_slugs"].([]string); !slices.Equal(got, []string{"globalizacja", "polityka"}) {
t.Errorf("tag_slugs = %v", doc["tag_slugs"])
}
if got, _ := doc["file_texts"].([]string); !slices.Equal(got, []string{"tekst pliku"}) {
t.Errorf("file_texts = %v", doc["file_texts"])
}
// File texts keep their order (the IndexedFiles order); an empty list
// leaves the key out.
ordered := models.MaterialDocument(m, course, 3, tags, []string{"pierwszy plik", "drugi plik", "trzeci plik"})
if got, _ := ordered["file_texts"].([]string); !slices.Equal(got, []string{"pierwszy plik", "drugi plik", "trzeci plik"}) {
t.Errorf("file_texts = %v, want the three texts in order", ordered["file_texts"])
}
if _, ok := models.MaterialDocument(m, course, 3, tags, []string{})["file_texts"]; ok {
t.Error("an empty file text list carries file_texts")
}
// No code, no course id, no meeting, a draft, no files.
bare := models.MaterialDocument(models.Material{ID: 5, Title: "Szkic", Type: "inne"}, &models.Course{Name: "Teoria"}, 0, nil, nil)
if bare["course"] != "Teoria" {
t.Errorf("course without code = %v", bare["course"])
}
for _, k := range []string{"course_id", "meeting_id", "published_at"} {
if bare[k] != int64(0) {
t.Errorf("bare %s = %#v, want 0", k, bare[k])
}
}
for _, k := range []string{"meeting_number", "file_texts", "body", "source", "url"} {
if _, ok := bare[k]; ok {
t.Errorf("bare document carries %s", k)
}
}
none := models.MaterialDocument(models.Material{ID: 6, Title: "X", Type: "link"}, nil, 0, nil, nil)
if _, ok := none["course"]; ok {
t.Error("a material without a course carries course")
}
}

11
models/material_share.go Normal file
View File

@@ -0,0 +1,11 @@
package models
// MaterialShare is the pivot row between a private material and a user it
// is shared with.
type MaterialShare struct {
MaterialID uint `gorm:"column:material_id;primaryKey"`
UserID uint `gorm:"column:user_id;primaryKey"`
}
// TableName is the pivot table.
func (MaterialShare) TableName() string { return "jz_bm_material_shares" }

View File

@@ -4,10 +4,17 @@ columns:
searchable: true searchable: true
type: type:
label: jz.bm::lang.materials.type label: jz.bm::lang.materials.type
is_private:
label: jz.bm::lang.materials.is_private
type: switch
course: course:
label: jz.bm::lang.common.course label: jz.bm::lang.common.course
relation: course relation: course
select: name select: name
meeting:
label: jz.bm::lang.common.meeting
relation: meeting
select: number
published_at: published_at:
label: jz.bm::lang.materials.published_at label: jz.bm::lang.materials.published_at
created_at: created_at:

View File

@@ -28,6 +28,18 @@ fields:
firstDay: 1 firstDay: 1
span: right span: right
comment: jz.bm::lang.materials.published_at_comment comment: jz.bm::lang.materials.published_at_comment
is_private:
label: jz.bm::lang.materials.is_private
type: switch
span: left
comment: jz.bm::lang.materials.is_private_comment
author:
label: jz.bm::lang.materials.author
type: relation
nameFrom: email
span: right
emptyOption: jz.bm::lang.common.none
comment: jz.bm::lang.materials.author_comment
source: source:
label: jz.bm::lang.common.source label: jz.bm::lang.common.source
type: text type: text
@@ -36,10 +48,22 @@ fields:
label: jz.bm::lang.common.url label: jz.bm::lang.common.url
type: text type: text
span: right span: right
meeting:
label: jz.bm::lang.common.meeting
type: relation
nameFrom: number
span: left
emptyOption: jz.bm::lang.common.none
comment: jz.bm::lang.common.meeting_comment
tags: tags:
label: jz.bm::lang.materials.tags label: jz.bm::lang.materials.tags
type: relation type: relation
nameFrom: name nameFrom: name
shared_with:
label: jz.bm::lang.materials.shared_with
type: relation
nameFrom: email
comment: jz.bm::lang.materials.shared_with_comment
files: files:
label: jz.bm::lang.materials.files label: jz.bm::lang.materials.files
type: fileupload type: fileupload

View File

@@ -13,6 +13,8 @@ type Reading struct {
ID uint `gorm:"column:id;primaryKey"` ID uint `gorm:"column:id;primaryKey"`
CourseID *uint `gorm:"column:course_id"` CourseID *uint `gorm:"column:course_id"`
Course *Course `gorm:"foreignKey:CourseID"` Course *Course `gorm:"foreignKey:CourseID"`
MeetingID *uint `gorm:"column:meeting_id"`
Meeting *Meeting `gorm:"foreignKey:MeetingID"`
Title string `gorm:"column:title"` Title string `gorm:"column:title"`
Author *string `gorm:"column:author"` Author *string `gorm:"column:author"`
Source *string `gorm:"column:source"` Source *string `gorm:"column:source"`
@@ -28,7 +30,7 @@ func (Reading) TableName() string { return "jz_bm_readings" }
// Fillable lists the columns mass assignment may set. // Fillable lists the columns mass assignment may set.
func (Reading) Fillable() []string { func (Reading) Fillable() []string {
return []string{"course_id", "title", "author", "source", "url", "is_required", "sort_order"} return []string{"course_id", "meeting_id", "title", "author", "source", "url", "is_required", "sort_order"}
} }
// Rules are checked by the admin API on every save. // Rules are checked by the admin API on every save.

View File

@@ -0,0 +1,16 @@
package models
import "time"
// ReadingOwnership records that a user (a golem15.user users row) owns a
// copy of a reading. One row per reading and user, kept apart from the read
// mark in ReadingProgress.
type ReadingOwnership struct {
ID uint `gorm:"column:id;primaryKey"`
ReadingID uint `gorm:"column:reading_id"`
UserID uint `gorm:"column:user_id"`
OwnedAt time.Time `gorm:"column:owned_at"`
}
// TableName is the plugin table.
func (ReadingOwnership) TableName() string { return "jz_bm_reading_ownership" }

View File

@@ -31,3 +31,10 @@ fields:
type: number type: number
span: left span: left
default: 0 default: 0
meeting:
label: jz.bm::lang.common.meeting
type: relation
nameFrom: number
span: right
emptyOption: jz.bm::lang.common.none
comment: jz.bm::lang.common.meeting_comment

View File

@@ -1,5 +1,6 @@
# The reading form inside the course form's relation manager: the course is # The reading form inside the course form's relation manager: the course is
# the parent, so there is no course picker. # the parent, so there is no course picker, and a relation form has no
# relation pickers, so the meeting (zjazd) is set on the readings screen.
fields: fields:
title: title:
label: jz.bm::lang.common.title label: jz.bm::lang.common.title

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