mirror of
https://github.com/wekan/wekan.git
synced 2026-11-18 05:45:02 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ab41c8003 | ||
|
|
b2284f577e | ||
|
|
15adf1bb2d | ||
|
|
17161a8355 | ||
|
|
2c23273c11 | ||
|
|
25d33cec36 | ||
|
|
0f2179988b | ||
|
|
d5937f6d38 | ||
|
|
7c0ae509ac | ||
|
|
42b4e51f85 | ||
|
|
66a19c4bd4 | ||
|
|
5e036dc544 | ||
|
|
973c2ad901 | ||
|
|
dd3f71c951 | ||
|
|
6b9086d2a8 | ||
|
|
9ddbc777dd | ||
|
|
65bf215cbe |
No files matched your search
+496
@@ -86,6 +86,502 @@ them up next.
|
||||
same `params.user` feeds both the e-mail notification text, where the full name is intended, and the webhook payload,
|
||||
where a username is expected; the safe change is to ADD a `username` field to the webhook rather than repurpose `user`).
|
||||
|
||||
# v9.97 2026-07-17 WeKan ® release
|
||||
|
||||
This release adds the following new features:
|
||||
|
||||
- **Snap: SELF-HEALING attachments — the fixes below apply themselves automatically on
|
||||
upgrade, no commands needed** ([#6473](https://github.com/wekan/wekan/issues/6473),
|
||||
`snap-src/bin/attachment-repair` (new), `snap-src/bin/wekan-control`,
|
||||
`snap-src/bin/migration-control`, `snap-src/bin/wekan-force-migrate`,
|
||||
`releases/migrate-mongodb-to-ferretdb.mjs`, `snap-src/bin/migrate-mongo3-to-ferretdb.mjs`,
|
||||
`snapcraft.yaml`, `snapcraft-core26.yaml`). The snap auto-refreshes on ~15k servers, so a fix
|
||||
that needs `snap run wekan.migrate` typed by hand does not reach most of them — and a full
|
||||
re-migration would be WRONG anyway, because it rebuilds FerretDB from the frozen MongoDB
|
||||
source and would lose boards/cards users created on FerretDB since migrating. Instead, on
|
||||
every start on FerretDB, `wekan-control` now launches `attachment-repair` in the
|
||||
**background**: it starts a temporary source mongod (7.x or the bundled 3.2 reader — the
|
||||
MongoDB data was never modified, so everything is recoverable) and runs the migration
|
||||
importer in a new **incremental FILES_ONLY mode** that **checks what is already migrated
|
||||
and migrates only what is missing**: text collections are never touched, every attachment/
|
||||
avatar whose target record is on `fs` with the file actually on disk is verified and
|
||||
skipped, records deleted by users since the migration are never resurrected, and only the
|
||||
missing binaries/records are extracted — so on healthy servers the repair is a fast no-op
|
||||
and on #6473-affected servers the attachments simply appear, live, while WeKan runs. It
|
||||
runs **once** (marker `$SNAP_COMMON/.attachments-files-v2-done`; a fresh successful
|
||||
migration pre-writes it, `snap run wekan.migrate` clears it, failures retry on the next
|
||||
start without ever blocking WeKan from starting), and a manual
|
||||
`snap run wekan.repair-attachments` command is registered too. The importer itself now
|
||||
stamps the migration marker with `filesVersion` (currently 2) and, when it finds a marker
|
||||
with an older `filesVersion` — or `FILES_ONLY=true` in the environment — automatically
|
||||
switches to this incremental repair, so **Docker/source installs get the same self-healing**
|
||||
by simply re-running the same importer command they migrated with. Verified end-to-end
|
||||
against two live FerretDB instances with the real importer: a broken-migration target
|
||||
(missing CollectionFS record, gridFsFileId-only record, marker without filesVersion) was
|
||||
repaired — record re-created with its card linkage, binary extracted, record repointed —
|
||||
while a board renamed on FerretDB after the migration stayed untouched, and the second run
|
||||
exited immediately as already-migrated. Behavioral tests (positive + negative) drive the
|
||||
real bash script with stubbed snap tooling: `tests/attachmentRepair.test.cjs`. Thanks to
|
||||
mueschel and xet7.
|
||||
|
||||
- **All platforms: startup schema upgrade — WeKan now CHECKS on start that data from EVERY old
|
||||
WeKan version has been migrated to the newest database structure, and migrates only what is
|
||||
missing** ([#6473](https://github.com/wekan/wekan/issues/6473) follow-up,
|
||||
[#1959](https://github.com/wekan/wekan/issues/1959), [#1971](https://github.com/wekan/wekan/issues/1971),
|
||||
`server/lib/schemaUpgradeSteps.js` (new), `server/startupSchemaUpgrade.js` (new),
|
||||
`server/migrations/ensureValidSwimlaneIds.js`, `server/imports.js`). WeKan v0.9–v8.00 ran
|
||||
startup migrations; v8.01 disabled them (large databases meant long downtime) in favour of
|
||||
read-time compatibility — which covers the swimlane era but not everything, so text data
|
||||
from old versions could sit invisible in the database. The new startup upgrade reinstates
|
||||
the safety net without the downtime: **version-gated** (the `_wekan_migration` marker stores
|
||||
the WeKan version and datetime of the previous successful re-check, so while the version is
|
||||
unchanged a boot costs ONE `findOne` — a full re-check is mandatory only after a new WeKan
|
||||
release, or `WEKAN_FORCE_SCHEMA_UPGRADE=true`; opt out with `WEKAN_SKIP_SCHEMA_UPGRADE=true`),
|
||||
**non-blocking** (runs in the background, WeKan serves immediately), with a **live migration
|
||||
dashboard at `/schema-upgrade-status`** on every platform that shows the Admin Panel product
|
||||
name when one is set (not "WeKan") plus per-step progress, and **fast on big databases**
|
||||
(bounded existence probes, `distinct()` set-joins instead of card scans, and server-side
|
||||
`updateMany` batches instead of per-document round trips — thousands of cards never mean
|
||||
thousands of queries). Steps, each verified against `git show v8.00:server/migrations.js`
|
||||
and each idempotent: `archived-flag-backfill` (docs missing `archived` never match the
|
||||
`archived: false` view queries — whole boards/lists/cards were invisible in the Swimlanes
|
||||
and Lists views), `swimlane-structure` (every board gets a visible swimlane, every list/card
|
||||
a `swimlaneId`, cards with a dangling `listId` are rescued to a visible list — and, fixing
|
||||
#1959 and #1971, unarchived cards whose swimlane was DELETED, ARCHIVED or belongs to another
|
||||
board are reassigned to the board's first visible swimlane, so everything is visible in both
|
||||
the Swimlanes view and the Lists view; the card-insert hook now also validates
|
||||
client-supplied swimlaneIds so new cards can never land under a deleted/archived swimlane
|
||||
again), `checklist-items-embedded` (pre-v0.79 embedded `checklist.items[]` extracted to the
|
||||
`ChecklistItems` collection — the text was in the database but never shown),
|
||||
`customfields-boardIds` (pre-v2.49 scalar `boardId` → `boardIds` array — old custom field
|
||||
definitions and their card values were orphaned), `board-allows-defaults` (the ~33
|
||||
defaultValue-true `allows*` flags backfilled — a missing flag rendered as false and HID
|
||||
existing descriptions/checklists/comments/attachments), `board-members-isactive` (members
|
||||
without `isActive` were denied board access), `board-permission-lowercase` ('PUBLIC' boards
|
||||
had silently become member-only), and `fs-path-heal` (filesystem attachments/avatars whose
|
||||
recorded path predates the current WRITABLE_PATH layout — v6.10-18 `uploads/<coll>`,
|
||||
v6.19-v8.4x `WRITABLE_PATH/<coll>`, CFS→ostrio temp files — are located and repointed/copied
|
||||
into the current layout). A step that fails or leaves unresolved work never blocks WeKan
|
||||
from starting and keeps the version un-stamped so the next boot re-checks. 36+ unit tests
|
||||
with negative cases (`tests/schemaUpgradeSteps.test.cjs`), plus verified end-to-end against
|
||||
a live FerretDB (SQLite) with old-shape seed data: all 8 steps migrate correctly and the
|
||||
second boot is gated to a no-op. Thanks to mueschel and xet7.
|
||||
|
||||
- **Migration speed: batched writes and preloaded lookups instead of per-document round trips**
|
||||
(5-hour migrations reported; `releases/migrate-mongodb-to-ferretdb.mjs`). The text phase now
|
||||
copies each batch with ONE unordered `insertMany` round trip (falling back to per-document
|
||||
`replaceOne` upserts only for batches that hit duplicates on resumed/re-run migrations), and
|
||||
the attachment/avatar phases preload the target's metadata records once per bucket instead
|
||||
of one `findOne` per file (bounded: collections over 100k records fall back to per-file
|
||||
lookups). The startup schema upgrade uses the same philosophy (`distinct()`/`updateMany`).
|
||||
Thanks to mueschel and xet7.
|
||||
|
||||
and fixes the following bugs:
|
||||
|
||||
- **OAuth2/OIDC: `OAUTH2_LOGIN_STYLE=redirect` was ignored — a popup always opened**
|
||||
([#5695](https://github.com/wekan/wekan/issues/5695), `packages/wekan-oidc/oidc_client.js`,
|
||||
`server/authentication.js`, `server/models/settings.js`, `client/components/main/layouts.js`).
|
||||
The setting was stored correctly in the OIDC service configuration, but the login button
|
||||
always passed `loginStyle: 'popup'`, and Meteor's `OAuth._loginStyle` gives the caller's
|
||||
option precedence — so the admin's redirect setting silently lost on every login (and the
|
||||
Meteor-internal `loginStyle` option even leaked into the provider's authorization URL). The
|
||||
client now honors a configured `loginStyle: 'redirect'` over the button's generic popup
|
||||
default (explicit caller choices still win; Safari-private-mode popup fallback kept) and no
|
||||
longer leaks the option to the provider. Also repaired the existing
|
||||
`OIDC_REDIRECTION_ENABLED=true` "go straight to the provider" feature, which was doubly
|
||||
broken since the Meteor 3 port: `isOidcRedirectionEnabled` inspected a Promise (always
|
||||
false), and the client handler assigned an undeclared variable (strict-mode ReferenceError).
|
||||
Behavioral tests drive the real client code in a VM against Meteor's loginStyle precedence:
|
||||
`tests/oauth2LoginStyle.test.cjs` (12 tests, positive + negative). Thanks to ArturRuta and
|
||||
xet7.
|
||||
|
||||
- **Deleting a user left "ghost users" on boards and cards**
|
||||
([#1289](https://github.com/wekan/wekan/issues/1289), `models/users.js`, new
|
||||
`models/lib/userDeletionCleanup.js`): every deletion path (admin method, self-service
|
||||
delete, `DELETE /api/users/:userId`) removed only the user document, leaving dangling
|
||||
references — empty-avatar board members that could not be removed, stale card
|
||||
members/assignees/watchers, orphaned avatar files — reproducible for 8 years. A server-side
|
||||
`Users.after.remove` hook now prunes `boards.members/watchers`,
|
||||
`cards.members/assignees/watchers`, `lists.watchers` and the user's avatar files on every
|
||||
deletion path; activities and comments are deliberately kept for history (their rendering
|
||||
is already null-guarded). Tests: `tests/userDeletionCleanup.test.cjs` (6). Thanks to
|
||||
chotaire and xet7.
|
||||
- **Swimlanes jumped up and down when starting/ending a card drag**
|
||||
([#2877](https://github.com/wekan/wekan/issues/2877), `client/components/boards/boardBody.css`):
|
||||
drag start hid every list's "+ Add Card" composer link with `display: none`, collapsing its
|
||||
row — lists shrank, auto-height swimlanes shrank, and every swimlane below jumped up ~23px
|
||||
(and back down on drop), shifting the drop target under the cursor mid-drag (root cause
|
||||
proven by frame-diffing the issue's own GIF). The composer now hides with
|
||||
`visibility: hidden`, keeping its layout box, so nothing moves; collapsed multi-selection
|
||||
cards stay collapsed intentionally (they preview the post-drop list). Tests:
|
||||
`tests/swimlaneDragJump.test.cjs` (8). Thanks to xet7.
|
||||
- **Dragging a card toward an off-screen list never auto-scrolled the board**
|
||||
([#443](https://github.com/wekan/wekan/issues/443), `client/components/lists/list.js`, new
|
||||
`imports/lib/boardAutoScroll.js`): the horizontal auto-scroll targeted `.board-canvas`,
|
||||
which only overflows vertically since the swimlane layout — its scrollLeftMax was always 0,
|
||||
so the guard never fired and users had to drop on an intermediate list and scroll by hand.
|
||||
Edge-proximity auto-scroll now drives the `.js-lists` lane actually under the pointer
|
||||
(clamped, overshoot-safe), with vertical scrolling kept on the canvas. Tests:
|
||||
`tests/boardAutoScroll.test.cjs` (15, incl. a proof the old no-overflow target could never
|
||||
scroll). Thanks to anhenghuang, AlexanderS and xet7.
|
||||
- **Board Rules: the Card Title Filter did nothing on several triggers — and rules created
|
||||
via the REST API never fired at all** ([#2345](https://github.com/wekan/wekan/issues/2345),
|
||||
[#2674](https://github.com/wekan/wekan/issues/2674),
|
||||
`client/components/rules/triggers/boardTriggers.js`, `.jade`, `server/rulesHelper.js`,
|
||||
`server/models/rules.js`, new `models/lib/ruleCardTitleFilter.js`, `docs/API/Rules.md`,
|
||||
`docs/API/REST-API.md`, `api.py`): the generic moved/archive trigger builders never saved
|
||||
the filter (and a trigger doc MISSING the field can never satisfy the matcher's `$in`, so
|
||||
those rules fired for nothing); a set filter never showed in the rule details; archive
|
||||
activities carry no card title so their filters compared against undefined; and REST-created
|
||||
rules skipped the wildcard defaulting entirely — the exact "remove user when moved away"
|
||||
rule from #2674 silently never ran. Filters are now stored (empty → `*`), shown in the rule
|
||||
description, matched with the title resolved from the card when the activity lacks it,
|
||||
legacy field-less triggers keep matching, the API normalizes missing matching fields to
|
||||
wildcards and validates types, and the rule actions no longer crash on unresolvable
|
||||
usernames or member-less cards. The Rules REST API is now documented (`docs/API/Rules.md`)
|
||||
and listed in api.py's help with the #2674 two-rule example. Tests:
|
||||
`tests/rulesCardTitleFilter.test.cjs` (12) and `tests/rulesApiTriggerNormalize.test.cjs`
|
||||
(19). Thanks to InfoSec812, sfahrenholz and xet7.
|
||||
- **Sandstorm: username uniqueness probe was case-sensitive and raced concurrent logins**
|
||||
([#574](https://github.com/wekan/wekan/issues/574), `sandstorm.js`, new
|
||||
`models/lib/sandstormUsername.js`): deriving `max`, `max1`, … from the preferred handle
|
||||
matched exact case only (an existing `Max` did not stop a new `max`) and the check-then-set
|
||||
window let a concurrent insert claim the name first, aborting the hook with E11000. The
|
||||
probe is now an anchored, escaped, case-insensitive regex and the claim retries the next
|
||||
number on a duplicate-key loss. Tests: `tests/sandstormUsername.test.cjs` (11). Thanks to
|
||||
mitar and xet7.
|
||||
- **Inviting a second user whose email shares a local part failed with a bare "403"**
|
||||
([#619](https://github.com/wekan/wekan/issues/619), `server/models/users.js`, new
|
||||
`models/lib/inviteeUsername.js`): inviting `cats@foo.com` creates user "cats"; inviting
|
||||
`cats@facebook.com` then crashed into Meteor's raw `403 Username already exists`. The
|
||||
invitee's username now probes `cats`, `cats1`, `cats2`, … to the first free variant, and
|
||||
exhaustion raises the translated `error-username-taken` instead of a number. Tests:
|
||||
`tests/inviteeUsername.test.cjs` (11, incl. the literal reported scenario). Thanks to
|
||||
lemoer and xet7.
|
||||
- **Date pickers ignored the configured default time and stored 12:00**
|
||||
([#1502](https://github.com/wekan/wekan/issues/1502), `client/lib/datepicker.js`, new
|
||||
`imports/lib/datePickerTime.js`): the due-date picker configures a 17:00 default (and
|
||||
now() for received/start/end), but an inverted guard applied it only when the card ALREADY
|
||||
had a date — exactly when it is unnecessary — so empty time fields fell back to a
|
||||
hard-coded 12:00 on save. The default now pre-fills empty pickers and backs the submit
|
||||
fallback; existing dates keep their own time. The issue's original AM/PM parse mismatch was
|
||||
already resolved by the native date/time inputs (79b94824e). Tests:
|
||||
`tests/datePickerDefaultTime.test.cjs` (10). Thanks to Vlasterx, saschafoerster,
|
||||
suncobran and xet7.
|
||||
- **Dragging a card while someone added a card to the target list dropped it into the WRONG
|
||||
swimlane** ([#2769](https://github.com/wekan/wekan/issues/2769), new
|
||||
`client/lib/cardDragGeometry.js`, `client/components/lists/listBody.js`): jQuery UI sortable
|
||||
snapshots container geometry at drag start; a mid-drag DOM insertion (another user's new
|
||||
card, or the drag's own composer auto-close) shifted every swimlane below while the cached
|
||||
rectangles stayed put — the drop landed in the neighbouring swimlane with no visible
|
||||
placeholder. A MutationObserver now refreshes the active drag's geometry on real mid-drag
|
||||
layout changes (sortable's own churn filtered out). Tests:
|
||||
`tests/cardDragGeometry.test.cjs` (13). Thanks to hever and xet7.
|
||||
- **Board import lost card dates** ([#1992](https://github.com/wekan/wekan/issues/1992),
|
||||
`models/wekanCreator.js`, new `models/lib/importedCardDates.js`): the importer derived
|
||||
`createdAt` only from a `createCard` activity (absent in Sandstorm/pruned exports — dates
|
||||
silently reset to import time) and never imported `receivedAt`/`endAt` at all. All five date
|
||||
fields now restore with sane fallbacks (activity → the card's own exported date → import
|
||||
time), and the card creator falls back to the exported userId. The missing-cards half of the
|
||||
report was already fixed by 68e0032c6. Tests: `tests/importedCardDates.test.cjs` (13).
|
||||
Thanks to xet7.
|
||||
- **Archiving a swimlane made its cards disappear — and restore brought back an empty
|
||||
swimlane** ([#2292](https://github.com/wekan/wekan/issues/2292), `models/swimlanes.js`, new
|
||||
`models/lib/swimlaneArchive.js`): only the swimlane document was flagged; its unarchived
|
||||
cards became invisible everywhere (board views render unarchived swimlanes, Archive lists
|
||||
archived docs). Archiving a swimlane now archives its cards (mirroring lists), and restore
|
||||
brings back exactly the cards archived WITH it — individually archived cards stay archived.
|
||||
Tests: `tests/archiveSwimlaneCards.test.cjs` (11). Thanks to Cactusbone and xet7.
|
||||
- **"Move/Copy selection to board" wrote `sort: NaN` to every card**
|
||||
([#2494](https://github.com/wekan/wekan/issues/2494), `imports/reactiveCache.js`): the
|
||||
client-side `noCache` card lookup returned a PROMISE since the Meteor 3 port, so the max-sort
|
||||
read was `undefined` and every moved card got NaN — cards appeared and disappeared and could
|
||||
not be reordered. The uncached client path is synchronous minimongo again. Tests:
|
||||
`tests/reactiveCacheNoCacheCard.test.cjs` (8, incl. a proof the pre-fix routing yields NaN).
|
||||
Thanks to Vermeille and xet7.
|
||||
- **Subtask "View it" did nothing when the subtask lives on another board**
|
||||
([#1853](https://github.com/wekan/wekan/issues/1853),
|
||||
`client/components/cards/subtaskViewHelpers.js`, `subtasks.js`): the original crash
|
||||
(`board._id` of undefined) had become a silent no-op guard — when the deposit board is not
|
||||
in minimongo the button just did nothing. Navigation now falls back to the subtask's own
|
||||
boardId (the route loads the board), and truly broken subtasks warn instead of dying.
|
||||
Tests: `tests/subtaskViewNavigation.test.cjs` (11). Thanks to Vanclief and xet7.
|
||||
- **Labels/members could not be dragged onto cards added after the board rendered**
|
||||
([#1554](https://github.com/wekan/wekan/issues/1554), `client/components/lists/list.js`):
|
||||
the droppable-initializing autorun lost its reactive dependency in 7673c77c5 (2023), so it
|
||||
ran once per list render and later-added minicards silently rejected sidebar drags until the
|
||||
board was re-entered ("works after search-and-back"). Dependency restored via the
|
||||
ReactiveCache. Tests: `tests/labelDragDroppable.test.cjs` (3). Thanks to Miffe and xet7.
|
||||
- **"Add filtered cards to selection" swept cards from OTHER boards into bulk actions**
|
||||
([#2306](https://github.com/wekan/wekan/issues/2306), `client/lib/filter.js`,
|
||||
`client/lib/multiSelection.js`, new `models/lib/boardScopedSelection.js`): the filter
|
||||
selector carried no boardId, and minimongo legitimately holds foreign-board cards (linked
|
||||
boards, dialogs, notifications) — a bulk archive could silently mutate other boards. The
|
||||
selection and its bulk-action selector are now board-scoped, and foreign ids are rejected at
|
||||
insertion. Tests: `tests/boardScopedSelection.test.cjs` (17, incl. the exact reported
|
||||
repro). Thanks to IcedQuinn and xet7.
|
||||
- **REST API: login tokens could never be revoked** ([#1437](https://github.com/wekan/wekan/issues/1437),
|
||||
`server/apiAuthRoutes.js`, new `models/lib/apiLogout.js`): every `POST /users/login` minted
|
||||
another ~90-day resume token with no way to invalidate any of them. New `POST /users/logout`
|
||||
revokes the presented token (or all of the user's tokens with `{"all": true}`), always scoped
|
||||
to the authenticated user. Tests: `tests/apiLogout.test.cjs` (12). Thanks to
|
||||
ppouliot and xet7.
|
||||
- **Editing one checklist item and clicking another left BOTH edit forms open — and
|
||||
submitting overwrote the new item's title with the previous item's text**
|
||||
([#2418](https://github.com/wekan/wekan/issues/2418), `client/lib/inlinedform.js`, new
|
||||
`client/lib/inlinedFormManager.js`): since a 2021 change, the "close the previously opened
|
||||
inline form" call was a silent no-op (the escape action is disabled for click execution),
|
||||
and the submit handlers grab the template's FIRST textarea — with two forms open the wrong
|
||||
form's text was saved. Subtasks reproduced the full bug; checklists' workaround corrupted
|
||||
the open-form tracker so Escape closed the whole card pane. A small state manager restores
|
||||
the single-open-form invariant (opening a form closes the previous one, without closing
|
||||
popups — preserving the 2021 intent). Tests: `tests/inlinedFormSingleOpen.test.cjs`
|
||||
(9, incl. the exact reported repro chain). Thanks to Beebo89 and xet7.
|
||||
- **Advanced Filter never matched date custom fields** ([#2989](https://github.com/wekan/wekan/issues/2989),
|
||||
`client/lib/filter.js`, new `imports/lib/advancedFilter.js`): the tokenizer treated every `/`
|
||||
as a regex delimiter even inside quotes, so `'Date de fin' == '06/04/2020'` broke tokenizing
|
||||
and the filter silently did nothing; and date custom fields store Date OBJECTS while the
|
||||
selectors compared strings/parseInt — `==`/`<`/`>` could never match and `!=` matched
|
||||
everything. Dates typed in the user's date format (day-first respected) now build half-open
|
||||
Date-range selectors (`==` means "that day"), with the legacy behavior untouched for
|
||||
non-date fields. Tests: `tests/advancedFilterDate.test.cjs` (14, incl. a proof the old
|
||||
selector shape never matched a stored Date). Thanks to k1ng440 and xet7.
|
||||
- **Cards could not be reordered by drag in lists full of subtask cards — with silent
|
||||
data loss on multi-selection drops** ([#3826](https://github.com/wekan/wekan/issues/3826),
|
||||
`server/models/cards.js`, `client/components/lists/list.js`, new
|
||||
`models/lib/cardSortRepair.js`): `addSubtaskCard` inserted EVERY subtask card with the
|
||||
constant `sort: -1`, so such lists contained only tied sorts; dropping between two equal
|
||||
sorts computes a zero increment, the move modifier came out empty and the card snapped
|
||||
back — and a multi-selection drop wrote the SAME sort to every selected card, permanently
|
||||
destroying their order. Subtask cards now append with a unique sort, and the drop handler
|
||||
detects degenerate (tied/inverted) gaps and repairs the siblings' sorts to a strict order
|
||||
before recomputing the drop index. Tests: `tests/subtaskCardReorder.test.cjs` (14).
|
||||
Thanks to jayki and xet7.
|
||||
- **Cross-board subtask full path disappeared after refresh**
|
||||
([#3453](https://github.com/wekan/wekan/issues/3453), `server/publications/boards.js`, new
|
||||
`server/lib/subtaskAncestors.js`): the board publication shipped only the DIRECT parent
|
||||
cards, while the full-path label walks the whole ancestor chain client-side — after F5 the
|
||||
grandparents were missing from minimongo and the path truncated/vanished. The publication
|
||||
now walks and publishes the full ancestor chain (batched per level, cycle-safe, tolerant of
|
||||
deleted ancestors). Tests: `tests/subtaskAncestors.test.cjs` (11). Thanks to
|
||||
MPeti1 and xet7.
|
||||
- **Linked cards: phantom empty custom-field rows and a template TypeError on every render**
|
||||
(from [#3748](https://github.com/wekan/wekan/issues/3748), `models/cards.js`, new
|
||||
`models/lib/customFieldsWD.js`): a linked card keeps the ORIGINAL board's custom-field
|
||||
snapshot; unresolvable definitions rendered as empty `{}` placeholders — a phantom row per
|
||||
entry and `Cannot read properties of undefined (reading 'type')` from the card details
|
||||
template (also reachable on normal cards with deleted definitions). Unmatched entries are
|
||||
now skipped. The rest of #3748 is by design: linked cards are pointers that mirror the
|
||||
original; label/custom-field ids are board-scoped, and name-based inheritance is the COPY
|
||||
feature. Tests: `tests/customFieldsWD.test.cjs` (9). Thanks to peterbecich and xet7.
|
||||
- **Archive sidebar: Restore/Delete links floated ambiguously between two archived cards**
|
||||
([#3199](https://github.com/wekan/wekan/issues/3199),
|
||||
`client/components/sidebar/sidebarArchives.jade`, `sidebar.css`): each card and its links
|
||||
were loose siblings with near-equal spacing above and below, so the links seemed to belong
|
||||
to the card underneath. Each archived card is now grouped with its own links in one
|
||||
container with a clear separator gap below (RTL-safe logical properties, theme-neutral).
|
||||
Tests: `tests/archiveLinkGrouping.test.cjs` (9). Thanks to fxkr and xet7.
|
||||
- **Attachments uploaded inside card comments: listing in the card's Attachments section is
|
||||
now guaranteed and regression-locked** ([#3843](https://github.com/wekan/wekan/issues/3843),
|
||||
new `models/lib/attachmentMeta.js`, `client/lib/utils.js`): the rich comment editor already
|
||||
uploads into the same Attachments collection with the same card meta as the Attachments
|
||||
popup, so they DO list — but nothing pinned that invariant and the meta was built in two
|
||||
places. One shared, null-safe builder now feeds both paths, with tests pinning that gallery
|
||||
queries key on `meta.cardId` with no source filter (and that board backgrounds stay
|
||||
excluded). Tests: `tests/commentAttachmentsList.test.cjs` (12). Thanks to
|
||||
jghaanstra and xet7.
|
||||
- **Maximized card rendered at the wrong place after scrolling in Swimlanes view**
|
||||
([#4822](https://github.com/wekan/wekan/issues/4822), `client/components/cards/cardDetails.css`):
|
||||
the legacy maximized-pane CSS had no `position` of its own, so the pane stayed an in-flow
|
||||
item inside the scrolled board canvas (off-screen after scrolling down); the desktop-mode
|
||||
floating-window rules also out-specified every maximize geometry rule, and inline drag
|
||||
offsets survived maximizing. The maximized pane is now viewport-`fixed` with explicit insets
|
||||
that beat both the floating-window rules and stale drag offsets (drag position is restored
|
||||
on minimize), RTL-safe via logical properties. A cascade-resolver regression test pins the
|
||||
behavior against the real stylesheet and fails on the pre-fix CSS:
|
||||
`tests/maximizedCardPosition.test.cjs` (11 tests). Thanks to pravdomil and xet7.
|
||||
- **LDAP group filter locked out admins and rejected multiple groups**
|
||||
([#4036](https://github.com/wekan/wekan/issues/4036), `packages/wekan-ldap/server/ldap.js`):
|
||||
with `LDAP_GROUP_FILTER_ENABLE=true`, only members of the single
|
||||
`LDAP_GROUP_FILTER_GROUP_NAME` group could log in — an admin who was only in
|
||||
`LDAP_SYNC_ADMIN_GROUPS` could not log in at all, and a comma-separated group list produced
|
||||
the literal filter `(cn=A,B)` that matches nothing. The filter now ORs across every
|
||||
comma-separated group name and, when admin sync is enabled, also admits the admin-sync
|
||||
groups. Thanks to zeisss-mercedes and xet7.
|
||||
- **Board invitation emails could carry a dead invitation code — and signup then failed with
|
||||
"The invitation code doesn't exist"** ([#4043](https://github.com/wekan/wekan/issues/4043),
|
||||
`server/models/settings.js`, `server/models/users.js`, new `models/lib/invitationCodeEmail.js`):
|
||||
re-inviting an unregistered user re-sent the SAME stale code (invalidated by an earlier
|
||||
OAuth2 signup or deleted account) instead of regenerating it; a failed SMTP send deleted a
|
||||
previously delivered, still-valid code; codes were mailed without checking they exist and
|
||||
are valid; the invitee address was only lowercased client-side; and the signup hook deleted
|
||||
the code BEFORE the account insert was committed, so a failed insert burned the code for
|
||||
every retry. Re-invites now regenerate stale codes (still-valid ones are kept so earlier
|
||||
emails keep working), sends fail loudly on unusable codes, rollback only removes codes the
|
||||
failed send itself created, and consumption happens only after a successful signup. Tests:
|
||||
`tests/invitationCodeEmail.test.cjs` (14). Thanks to jkoenig134 and xet7.
|
||||
- **Japanese/Chinese UI: the add-card button and footer links wrapped mid-word**
|
||||
([#4023](https://github.com/wekan/wekan/issues/4023), `client/components/forms/forms.css`):
|
||||
CJK text has no spaces, so the narrow add-card composer footer broke 追加 / リンク / 検索 /
|
||||
テンプレート between any two characters. The composer/edit footers now use
|
||||
`word-break: keep-all` with `flex-wrap: wrap` (wrapping between links, never inside a word)
|
||||
and `white-space: nowrap` on the button and each link group; Latin wrapping is unchanged and
|
||||
the negative tests pin that no global word-break was introduced. Tests:
|
||||
`tests/cjkLabelWrap.test.cjs` (9). Thanks to yuki-snow1823, Sylvain2703 and xet7.
|
||||
- **Users added to a team AFTER the team was assigned to a board never became board members —
|
||||
and the Admin Panel bulk team add/remove silently did nothing**
|
||||
([#4593](https://github.com/wekan/wekan/issues/4593), `server/models/users.js`,
|
||||
`client/components/settings/peopleBody.js`, new `models/lib/teamBoardMemberSync.js`):
|
||||
assigning a team to a board snapshotted its then-current members, so later joiners could see
|
||||
the board via publications but every authority gate (`hasMember`, card/list mutations,
|
||||
attachment downloads, export) denied them; and the Admin Panel "Add/Remove team to selected
|
||||
users" used a direct client-side `Users.update` that server permissions silently deny.
|
||||
`editUser`/`createUser` now add new team members to all boards their teams are assigned to
|
||||
(never touching existing member entries, skipping template boards), and the bulk actions go
|
||||
through the admin `editUser` method. Tests: `tests/teamBoardMemberSync.test.cjs` (13).
|
||||
Thanks to szymonsztuka and xet7.
|
||||
- **LDAP background sync only worked once per user** ([#4654](https://github.com/wekan/wekan/issues/4654),
|
||||
`packages/wekan-ldap/server/ldap.js`, `sync.js`, new `userIdFilter.js`): `getUserById` crashed or built the
|
||||
invalid filter `(|(=user))` when `LDAP_UNIQUE_IDENTIFIER_FIELD` was unset/empty (it never consulted
|
||||
`LDAP_USER_SEARCH_FIELD`, where the stored id actually comes from), and the username sync passed `$set` as
|
||||
query OPTIONS to `findOneAsync` — logging "Syncing user username" while writing nothing. New shared
|
||||
`buildUserIdFilter()` ORs across both configured fields, `idAttribute` is persisted on new LDAP users, and
|
||||
the username sync actually updates. Tests: `tests/ldapUserIdFilter.test.cjs` (11). Thanks to fabianrbz and xet7.
|
||||
- **All Boards page: per-list card counts and member avatars never showed** ([#5174](https://github.com/wekan/wekan/issues/5174),
|
||||
[#4825](https://github.com/wekan/wekan/issues/4825), new `models/lib/boardTileData.js`,
|
||||
`server/publications/boards.js`, `client/components/boards/boardsList.js`, `.jade`): the helpers were stubbed
|
||||
to `[]` to stop the #4214 reactive "icons dance", and the gating flags were never published. New non-reactive
|
||||
`getAllBoardsTileData` method (one boards query, one lists query, one grouped card count) fetched once per
|
||||
page visit; per-board "Show card count per list"/"Show Board members avatars" settings enforced strictly both
|
||||
ways. Tests: `tests/boardTileData.test.cjs` (17). Thanks to mueschel, Miuler and xet7.
|
||||
- **Lists rendered with different widths by default** ([#5659](https://github.com/wekan/wekan/issues/5659),
|
||||
new `models/lib/listWidth.js`, `client/components/lists/list.js`, `listHeader.js`, `models/users.js`): the
|
||||
default width was duplicated in four resolution paths that disagreed (270 vs 272), so lists on the same
|
||||
(public) board could differ with no customization. Single source of truth (272), all paths normalize
|
||||
out-of-range values the same way; customized widths still win. Tests: `tests/listWidthDefaults.test.cjs` (12).
|
||||
Thanks to butteredCat-2021 and xet7.
|
||||
- **Declining a board invitation kept the board active in the member's overview** ([#4730](https://github.com/wekan/wekan/issues/4730),
|
||||
`server/models/boards.js`, new `models/lib/boardInvites.js`): the decline flow called `quitBoard` (deactivate)
|
||||
then `acceptInvite`, which unconditionally REACTIVATED membership — it also let any removed member re-add
|
||||
themselves. `quitBoard` now clears the pending invitation (and works for stale-invite-only users);
|
||||
`acceptInvite` only activates when an invitation actually exists. Tests: `tests/boardInvites.test.cjs` (11).
|
||||
Thanks to Griiimm and xet7.
|
||||
- **After migrating a user from password to LDAP, the old local password still logged in**
|
||||
([#4419](https://github.com/wekan/wekan/issues/4419), new `server/lib/ldapPasswordLoginGuard.js`,
|
||||
`server/authentication.js`): a `validateLoginAttempt` hook now rejects password-service logins for
|
||||
`authenticationMethod: 'ldap'` users while LDAP is enabled — respecting the `LDAP_LOGIN_FALLBACK=true`
|
||||
feature, never touching other services or session resumes, and opt-out-able with
|
||||
`LDAP_MIGRATION_ALLOW_PASSWORD_LOGIN=true` so no deployment is hard-locked. Tests:
|
||||
`tests/ldapPasswordLoginGuard.test.cjs` (12). Thanks to preciousamorc and xet7.
|
||||
- **`LDAP_ENCRYPTION=true` (the documented value) silently connected WITHOUT encryption**
|
||||
([#4158](https://github.com/wekan/wekan/issues/4158), new `packages/wekan-ldap/server/encryptionSetting.js`,
|
||||
`ldap.js`, `docs/Login/LDAP.md`): only the undocumented `ssl`/`tls` values did anything, and any other value
|
||||
(including `true`, which JSON-parses to a boolean) meant silent plaintext. Now `true`→LDAPS,
|
||||
`starttls`→STARTTLS, legacy `ssl`/`tls` keep their historical meanings with a deprecation notice, and unknown
|
||||
values log a clear warning listing the accepted ones. Tests: `tests/ldapEncryptionSetting.test.cjs` (22).
|
||||
Thanks to farwayer and xet7.
|
||||
- **OIDC login onto an existing account wiped the profile — avatars and templates disappeared**
|
||||
([#4560](https://github.com/wekan/wekan/issues/4560), `server/models/users.js`): the
|
||||
`OAUTH2_MERGE_EXISTING_USERS` merge path replaced the whole `profile` with the OIDC-derived one, losing
|
||||
`avatarUrl`, `templatesBoardId` (+ template swimlanes), language and preferences. The merge now preserves the
|
||||
stored profile and only fills gaps/updates the asserted fullname; the fail-closed linking rules
|
||||
(GHSA-mp7g-hj5q-gxhq) are untouched. Tests: `tests/oidcProfileMerge.test.cjs` (7, fails on pre-fix code).
|
||||
Thanks to LeoLu-eng and xet7.
|
||||
|
||||
- **OAuth2/OIDC: concurrent logins could contaminate each other's user data — users saw stale
|
||||
or missing emails/username/teams, and the database could disagree with the UI**
|
||||
([#4897](https://github.com/wekan/wekan/issues/4897), `packages/wekan-oidc/oidc_server.js`,
|
||||
`packages/wekan-oidc/loginHandler.js`). The OIDC server flow kept `profile`, `serviceData`
|
||||
and `userinfo` as MODULE-SCOPE variables shared by every login of every user: fields the
|
||||
current login did not overwrite leaked from the previous user's login (refreshToken,
|
||||
whitelisted id-token claims, branch-dependent email), and because the handler awaits the
|
||||
token/userinfo requests, two interleaved logins wrote into the SAME objects — a login could
|
||||
complete carrying another user's id/email/username, updating the wrong user document. The
|
||||
`PROPAGATE_OIDC_DATA` group/attribute path additionally ran on implicit GLOBALS
|
||||
(`teamArray`, `isAdmin`, `user_email`, …) with awaits between assignment and use, so
|
||||
concurrent logins could write one user's email/teams/admin flag onto another user's document
|
||||
— real database corruption, matching the "web interface shows different data vs mongodb"
|
||||
report. All login state is now per-login locals, the login handler compares actual values
|
||||
(the old username/fullname comparisons compared a string to an object, always true), and a
|
||||
regression test proves isolation under concurrent logins and fails against the pre-fix code:
|
||||
`tests/oidcLoginStateIsolation.test.cjs` (11 tests, positive + negative). Thanks to
|
||||
gerardo-junior and xet7.
|
||||
|
||||
- **Snap/Docker: after the MongoDB → FerretDB migration ALL CollectionFS-era attachments were
|
||||
missing** ([#6473](https://github.com/wekan/wekan/issues/6473),
|
||||
`releases/migrate-mongodb-to-ferretdb.mjs`, `snap-src/bin/migrate-mongo3-to-ferretdb.mjs`,
|
||||
`snap-src/bin/migrate-gridfs-to-fs.mjs`). Real CollectionFS (old WeKan's
|
||||
`FS.Store.GridFS('attachments')`) stores each file's GridFS id at **`copies.<bucket>.key`**
|
||||
(`copies.attachments.key` / `copies.avatars.key`) — but the importers only looked at
|
||||
`original.gridFsFileId`, `gridFsFileId` and `copies.gridfs.key`, none of which exist in that
|
||||
layout. So the modern importer "skipped" every file **silently** and the MongoDB 3.x importer
|
||||
extracted the binaries but never created an attachment record (and the records it did create
|
||||
lost their `meta.cardId`/`boardId`, which CollectionFS keeps at the record's TOP level — an
|
||||
attachment without `meta.cardId` shows on no card). Either way the migration reported success
|
||||
with zero attachments visible. A new shared `resolveCfsGridFsId()` resolves the id from all
|
||||
four layouts (`original.gridFsFileId`, `gridFsFileId`, `copies.<bucket>.key`,
|
||||
`copies.gridfs.key`, then any `copies.*.key`), the modern importer now **drives extraction
|
||||
from `cfs_gridfs.<bucket>.files` itself** (so a missing/empty `cfs.<bucket>.filerecord`
|
||||
collection no longer skips everything — binaries without a filerecord are still extracted to
|
||||
disk), the mongo3 importer copies the top-level `boardId`/`cardId`/`listId`/`swimlaneId`/
|
||||
`userId` into `meta`, and filerecords whose binary cannot be located are **reported as
|
||||
errors** on the migration dashboard instead of being silently dropped. If you already
|
||||
migrated and attachments are missing, run the migration again: `snap run wekan.migrate`
|
||||
(the source MongoDB data was never modified). Behavioral positive/negative tests:
|
||||
`tests/migrationAttachmentExtraction.test.cjs`. Thanks to mueschel and xet7.
|
||||
|
||||
- **Snap/Docker: Meteor-Files attachments stored in GridFS without a `storage: 'gridfs'` flag
|
||||
were left pointing at a GridFS that no longer exists after migration**
|
||||
([#6473](https://github.com/wekan/wekan/issues/6473), `releases/migrate-mongodb-to-ferretdb.mjs`,
|
||||
`snap-src/bin/migrate-gridfs-to-fs.mjs`). WeKan's own `getFileStrategy` serves a version from
|
||||
GridFS when its storage flag says `'gridfs'` **or** it carries a
|
||||
`versions.*.meta.gridFsFileId` reference — those reference-only records worked fine on
|
||||
MongoDB, but the migration's file phase only matched `versions.original.storage: 'gridfs'`,
|
||||
so their binaries were never extracted and the record kept pointing into the void (404 after
|
||||
the switch). The record scan now matches both forms (and every version, not just
|
||||
`original`), and a **second, bucket-driven sweep** walks `<bucket>.files` by its
|
||||
`metadata.fileId` back-reference (the way WeKan writes GridFS uploads), recovering binaries
|
||||
even when the record's flags say nothing about GridFS. Any GridFS-flagged version whose
|
||||
binary genuinely cannot be located is reported on the dashboard. Thanks to mueschel and xet7.
|
||||
|
||||
- **Admin Panel > Attachments showed "/data" as the Filesystem Storage path on every
|
||||
platform** ([#6473](https://github.com/wekan/wekan/issues/6473),
|
||||
`client/components/settings/attachments.js`, `client/components/settings/settingBody.js`,
|
||||
`server/models/attachmentStorageSettings.js`, `models/lib/attachmentStoragePath.js`). The
|
||||
Blaze helpers computed the path from `process.env.WRITABLE_PATH` **in the browser**, where
|
||||
`process.env` never has it, so the page always fell back to "/data" — a path that does not
|
||||
exist on a Snap install (the real path is `/var/snap/wekan/common/files/attachments`),
|
||||
sending admins hunting for a directory that was never there. The client now asks the server
|
||||
via a new admin-only `getAttachmentStoragePaths` method, whose Snap-aware computation
|
||||
(shared, dependency-free `models/lib/attachmentStoragePath.js` — WRITABLE_PATH already ends
|
||||
in `/files` on Snap, `/files` is appended elsewhere) is also used for the settings document's
|
||||
default filesystem path, which pointed at `/data/attachments` instead of
|
||||
`/data/files/attachments` on Docker. Unit tests with negative cases:
|
||||
`tests/attachmentStoragePath.test.cjs`. Thanks to mueschel and xet7.
|
||||
|
||||
- **Snap: `snap run wekan.database ferretdb` looked like it re-ran the migration — it only
|
||||
switches databases** ([#6473](https://github.com/wekan/wekan/issues/6473),
|
||||
`snap-src/bin/wekan-database`). Running it while already on FerretDB printed "WeKan now uses
|
||||
FerretDB (SQLite)." and users reasonably read that as "migration done" while their
|
||||
attachments stayed missing. It now says when nothing was switched, states that the command
|
||||
does NOT migrate data, and names the command that does: `snap run wekan.migrate`. Thanks to
|
||||
mueschel and xet7.
|
||||
|
||||
- **FerretDB (SQLite) rejected documents with literal dotted field names, silently dropping
|
||||
them during migration** ([#6473](https://github.com/wekan/wekan/issues/6473),
|
||||
[wekan/FerretDB](https://github.com/wekan/FerretDB) `internal/types/document_validation.go`).
|
||||
MongoDB has accepted documents with literal `.` in field names since 3.6, and data migrated
|
||||
from a real MongoDB can legitimately contain them — but FerretDB v1's document validation
|
||||
rejected every such document (*"invalid key: … (key must not contain '.' sign)"*), and since
|
||||
per-item migration errors are deliberately non-fatal (#6466), those documents simply went
|
||||
missing. Fixed in the bundled wekan/FerretDB fork: dotted keys are stored and round-tripped
|
||||
literally with MongoDB's own semantics (query/update paths still treat `.` as a path
|
||||
separator), while the other key rules (`$` prefix, duplicates, UTF-8) still reject. Verified
|
||||
end-to-end against a live FerretDB (SQLite): insert, nested `$set`, round-trip, and the
|
||||
negative cases. Thanks to mueschel and xet7.
|
||||
|
||||
Thanks to above GitHub users for their contributions and translators for their translations.
|
||||
|
||||
# v9.96 2026-07-16 WeKan ® release
|
||||
|
||||
This release adds the following updates:
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ LABEL org.opencontainers.image.source="https://github.com/wekan/wekan"
|
||||
# TARGETARCH and TARGETVARIANT are automatically provided by Docker Buildx
|
||||
ARG TARGETARCH
|
||||
ARG TARGETVARIANT
|
||||
ARG VERSION=9.96
|
||||
ARG VERSION=9.97
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
ENV BUILD_DEPS="apt-utils gnupg wget bzip2 g++ curl libarchive-tools build-essential git ca-certificates python3 unzip"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
appId: wekan-public/apps/77b94f60-dec9-0136-304e-16ff53095928
|
||||
appVersion: "v9.96.0"
|
||||
appVersion: "v9.97.0"
|
||||
files:
|
||||
userUploads:
|
||||
- README.md
|
||||
|
||||
@@ -132,6 +132,16 @@ If *nix: chmod +x api.py => ./api.py users
|
||||
python3 api.py getcardsettings BOARDID # Get board-level card settings (allows* toggles, cardAging, cardAgingDays1/2/3)
|
||||
python3 api.py setcardsetting BOARDID KEY VALUE # Set one board card setting, e.g. allowsDueDate true, cardAging true, cardAgingDays1 5
|
||||
|
||||
Board Automation Rules API (IFTTT, Issue #2674):
|
||||
python3 api.py listrules BOARDID # List automation rules of a board
|
||||
python3 api.py getrule BOARDID RULEID # Get one rule with its trigger and action
|
||||
python3 api.py addrule BOARDID TITLE TRIGGER_JSON ACTION_JSON # Add rule. Missing trigger matching fields default to the '*' wildcard
|
||||
python3 api.py editrule BOARDID RULEID PATCH_JSON # Edit rule: {"title":..,"trigger":{..},"action":{..}}
|
||||
python3 api.py removerule BOARDID RULEID # Remove rule (and its trigger + action)
|
||||
# Example (Issue #2674) - add member when card moved TO list, remove member when moved AWAY FROM list:
|
||||
# python3 api.py addrule BOARDID 'Add on move to Doing' '{"activityType":"moveCard","listName":"Doing"}' '{"actionType":"addMember","username":"someuser"}'
|
||||
# python3 api.py addrule BOARDID 'Remove on move from Doing' '{"activityType":"moveCard","oldListName":"Doing"}' '{"actionType":"removeMember","username":"someuser"}'
|
||||
|
||||
Admin API:
|
||||
python3 api.py newuser USERNAME EMAIL PASSWORD
|
||||
|
||||
@@ -1773,6 +1783,18 @@ if arguments >= 1:
|
||||
# python3 api.py addrule BOARDID 'Archive after 90 days' \
|
||||
# '{"activityType":"scheduledTrigger","scheduleKind":"aging","listName":"Completed","days":90,"atTime":"03:00"}' \
|
||||
# '{"actionType":"archive"}'
|
||||
#
|
||||
# Example (Issue #2674 - add a user to the card when it is moved TO a list, and
|
||||
# remove the user again when the card is moved AWAY FROM that list). Trigger
|
||||
# matching fields that are omitted (userId, swimlaneName, cardTitle, and the
|
||||
# unused one of listName/oldListName) are stored as the '*' wildcard by the
|
||||
# server, so the rules fire for any user/swimlane/card title:
|
||||
# python3 api.py addrule BOARDID 'Add member on move to Doing' \
|
||||
# '{"activityType":"moveCard","listName":"Doing"}' \
|
||||
# '{"actionType":"addMember","username":"someuser"}'
|
||||
# python3 api.py addrule BOARDID 'Remove member on move from Doing' \
|
||||
# '{"activityType":"moveCard","oldListName":"Doing"}' \
|
||||
# '{"actionType":"removeMember","username":"someuser"}'
|
||||
|
||||
if arguments >= 2 and sys.argv[1] == 'listrules':
|
||||
boardid = sys.argv[2]
|
||||
|
||||
@@ -316,7 +316,19 @@ body.desktop-mode .board-wrapper .board-canvas .board-overlay {
|
||||
display: none !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
.board-wrapper .board-canvas.is-dragging-active .open-minicard-composer,
|
||||
/* #2877 "Wekan swimlane jumps when moving card": while a card is dragged the
|
||||
"+ Add Card" composer link is hidden, but hiding it with `display: none`
|
||||
collapsed the bottom row of EVERY list at drag start (and restored it on
|
||||
drop). With auto-height swimlanes the whole swimlane shrank/grew by the
|
||||
composer's height, so all swimlanes below visibly jumped up and back down.
|
||||
`visibility: hidden` hides the link just the same but keeps its box in the
|
||||
layout, so nothing moves when a drag starts or ends. */
|
||||
.board-wrapper .board-canvas.is-dragging-active .open-minicard-composer {
|
||||
visibility: hidden;
|
||||
}
|
||||
/* Checked cards of a multi-selection ARE the payload being dragged, so
|
||||
removing them from the flow (showing the list as it will look after the
|
||||
drop) is intentional — keep display: none here. */
|
||||
.board-wrapper .board-canvas.is-dragging-active .minicard-wrapper.is-checked {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -197,14 +197,19 @@ template(name="boardList")
|
||||
span.board-list-item-name(title="{{boardOpenAndMoveHint}}")
|
||||
+viewer
|
||||
= title
|
||||
//- #5174 / #4825: the per-board allows* flags are
|
||||
//- resolved server-side into the one-shot tile data
|
||||
//- (the raw fields are not even published to this
|
||||
//- page), so the show* helpers below gate the whole
|
||||
//- block consistently for every board.
|
||||
unless currentSetting.hideBoardMemberList
|
||||
if allowsBoardMemberList
|
||||
if showBoardMemberList _id
|
||||
.minicard-members
|
||||
each member in boardMembers _id
|
||||
a.name
|
||||
+userAvatar(userId=member noRemove=true)
|
||||
unless currentSetting.hideCardCounterList
|
||||
if allowsCardCounterList
|
||||
if showCardCounterList _id
|
||||
.minicard-lists.flex.flex-wrap
|
||||
each list in boardLists _id
|
||||
.item
|
||||
|
||||
@@ -132,16 +132,6 @@ function saveWorkspace(workspaceId, { name, icon }) {
|
||||
}
|
||||
|
||||
Template.boardList.helpers({
|
||||
hideCardCounterList() {
|
||||
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
|
||||
return Utils.isMiniScreen() && Session.get('currentBoard'); */
|
||||
return true;
|
||||
},
|
||||
hideBoardMemberList() {
|
||||
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
|
||||
return Utils.isMiniScreen() && Session.get('currentBoard'); */
|
||||
return true;
|
||||
},
|
||||
BoardMultiSelection() {
|
||||
return BoardMultiSelection;
|
||||
},
|
||||
@@ -193,6 +183,15 @@ Template.boardList.onCreated(function () {
|
||||
Meteor.call('getMyShareableGroups', (err, res) => {
|
||||
if (!err && res) this.shareableGroups.set(res);
|
||||
});
|
||||
// #5174 / #4825: per-board tile data (per-list card counts + member ids) for
|
||||
// the All Boards tiles, computed server-side and fetched exactly ONCE here —
|
||||
// deliberately NOT inside an autorun and NOT from reactive getLists/getCards
|
||||
// cursors, so the #4214 "icons random dance" (a reactive re-render loop on
|
||||
// this page, which is why the old helpers were stubbed out) cannot return.
|
||||
this.boardTileDataVar = new ReactiveVar({});
|
||||
Meteor.call('getAllBoardsTileData', (err, res) => {
|
||||
if (!err && res) this.boardTileDataVar.set(res);
|
||||
});
|
||||
let currUser = ReactiveCache.getCurrentUser();
|
||||
let userLanguage;
|
||||
if (currUser && currUser.profile) {
|
||||
@@ -598,25 +597,32 @@ Template.boardList.helpers({
|
||||
.slice()
|
||||
.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
|
||||
},
|
||||
// #5174 / #4825: the board tiles' per-list card-count line and member avatar
|
||||
// row. Data comes from the one-shot getAllBoardsTileData method fetch in
|
||||
// onCreated (see there) — NOT from reactive getLists/getCards cursors, which
|
||||
// caused the #4214 "icons random dance" and got these helpers stubbed to []
|
||||
// (hiding the counters/avatars for everyone). The show* helpers resolve the
|
||||
// per-board opt-in flags (allowsCardCounterList / allowsBoardMemberList,
|
||||
// board sidebar "Show at All Boards page"), strictly, server-side — so a
|
||||
// board with the checkbox off (or never set) consistently shows nothing.
|
||||
boardLists(boardId) {
|
||||
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
|
||||
const lists = ReactiveCache.getLists({ 'boardId': boardId, 'archived': false },{sort: ['sort','asc']});
|
||||
const ret = lists.map(list => {
|
||||
let cardCount = ReactiveCache.getCards({ 'boardId': boardId, 'listId': list._id }).length;
|
||||
return `${list.title}: ${cardCount}`;
|
||||
});
|
||||
return ret;
|
||||
*/
|
||||
return [];
|
||||
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
|
||||
return (tile && tile.showLists && tile.lists) || [];
|
||||
},
|
||||
|
||||
boardMembers(boardId) {
|
||||
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
|
||||
const lists = ReactiveCache.getBoard(boardId)
|
||||
const boardMembers = lists?.members.map(member => member.userId);
|
||||
return boardMembers;
|
||||
*/
|
||||
return [];
|
||||
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
|
||||
return (tile && tile.showMembers && tile.memberIds) || [];
|
||||
},
|
||||
|
||||
showCardCounterList(boardId) {
|
||||
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
|
||||
return !!(tile && tile.showLists && tile.lists && tile.lists.length);
|
||||
},
|
||||
|
||||
showBoardMemberList(boardId) {
|
||||
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
|
||||
return !!(tile && tile.showMembers && tile.memberIds && tile.memberIds.length);
|
||||
},
|
||||
|
||||
isStarred() {
|
||||
|
||||
@@ -180,6 +180,33 @@ body.desktop-mode .card-details:not(.card-details-popup):not(.card-details-colla
|
||||
bottom: 8px;
|
||||
}
|
||||
|
||||
/* #4822: the MAXIMIZED card must be anchored to the VIEWPORT (position: fixed
|
||||
with viewport insets), never laid out inside — or measured from — the
|
||||
scrolled swimlane/board container. Historically the maximized pane was an
|
||||
in-flow flex/float item of its swimlane, so after scrolling down in the
|
||||
swimlanes view it rendered at the swimlane's position in the tall scrolled
|
||||
canvas (off-screen) instead of over the viewport.
|
||||
All four insets are !important for two reasons:
|
||||
1. The floating-window rules above (top: 8px / inset-inline-end: 8px /
|
||||
width: min(650px, 90vw), specificity up to 0,5,1) otherwise override the
|
||||
lower-specificity .card-details-maximized geometry entirely, leaving the
|
||||
Maximize button a no-op.
|
||||
2. The drag handle writes inline left/top styles onto the card; a card that
|
||||
was dragged and then maximized must not keep the stale dragged offsets
|
||||
(an off-viewport inline top is exactly the "wrong place" of #4822).
|
||||
Only !important declarations beat inline styles. */
|
||||
body.desktop-mode .card-details.card-details-maximized:not(.card-details-popup):not(.card-details-collapsed) {
|
||||
position: fixed !important;
|
||||
top: 8px !important;
|
||||
inset-inline-start: 8px !important;
|
||||
inset-inline-end: 8px !important;
|
||||
bottom: 8px !important;
|
||||
width: auto !important;
|
||||
height: auto !important;
|
||||
max-width: none !important;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
/* Collapsed card state - hide content and set height to title row only */
|
||||
.card-details.card-details-collapsed .card-details-canvas > *:not(.card-details-header) {
|
||||
display: none !important;
|
||||
@@ -442,6 +469,12 @@ body.desktop-mode .card-details.card-details-collapsed {
|
||||
flex-shrink: 0;
|
||||
flex-basis: calc(100% - 20px);
|
||||
will-change: flex-basis;
|
||||
/* #4822: declare the position strategy explicitly. The maximized pane must
|
||||
be fixed to the viewport in its own right — never an in-flow flex/float
|
||||
item of the scrolled swimlane container, and never dependent on the
|
||||
sibling .card-details rule (or the body.desktop-mode rules) happening to
|
||||
supply position: fixed. */
|
||||
position: fixed;
|
||||
overflow-y: auto;
|
||||
overflow-x: auto;
|
||||
background: #f7f7f7;
|
||||
|
||||
@@ -17,24 +17,69 @@ export function canNavigateToSubtaskBoard(board) {
|
||||
// the parent card again, and so the behaviour is unit-testable.
|
||||
//
|
||||
// Returns the FlowRouter 'card' route params taken from the subtask, or
|
||||
// undefined when the subtask's board is not loaded yet (see #4762 guard).
|
||||
// undefined for a malformed subtask (no usable card id / board id).
|
||||
//
|
||||
// #1853: "Subtask board id missing: cannot read property _id of undefined".
|
||||
// The subtask often lives on ANOTHER board (the deposit/target board) whose
|
||||
// document is not in minimongo while the parent card's board is open. In that
|
||||
// case subtask.board() yields nothing; instead of crashing (the original
|
||||
// TypeError) or silently doing nothing (the post-#4762 behaviour), fall back
|
||||
// to the subtask's own boardId and the default 'board' slug — the 'card'
|
||||
// route action only uses :boardId/:cardId (config/router.js) and its
|
||||
// subscriptions load the board, so navigation succeeds without a reload.
|
||||
// 'board' is the model's own default slug (models/boards.js).
|
||||
export function subtaskNavTarget(subtask) {
|
||||
if (!subtask) {
|
||||
return undefined;
|
||||
}
|
||||
const board = typeof subtask.board === 'function' ? subtask.board() : undefined;
|
||||
if (!canNavigateToSubtaskBoard(board)) {
|
||||
return undefined;
|
||||
}
|
||||
// Prefer the real card id (resolves linked subtask cards to their source);
|
||||
// fall back to the plain _id when getRealId is unavailable (e.g. in tests).
|
||||
const cardId =
|
||||
typeof subtask.getRealId === 'function' ? subtask.getRealId() : subtask._id;
|
||||
return {
|
||||
boardId: board._id,
|
||||
slug: board.slug,
|
||||
cardId,
|
||||
swimlaneId: subtask.swimlaneId,
|
||||
listId: subtask.listId,
|
||||
};
|
||||
(typeof subtask.getRealId === 'function' ? subtask.getRealId() : undefined) ||
|
||||
subtask._id;
|
||||
if (!cardId) {
|
||||
// Malformed subtask document: nothing sane to navigate to.
|
||||
return undefined;
|
||||
}
|
||||
const board = typeof subtask.board === 'function' ? subtask.board() : undefined;
|
||||
if (canNavigateToSubtaskBoard(board)) {
|
||||
return {
|
||||
boardId: board._id,
|
||||
slug: board.slug,
|
||||
cardId,
|
||||
swimlaneId: subtask.swimlaneId,
|
||||
listId: subtask.listId,
|
||||
};
|
||||
}
|
||||
if (subtask.boardId) {
|
||||
// Board doc missing locally (#1853 / #4762): navigate by id and let the
|
||||
// route load the board. The slug segment is cosmetic for the card route.
|
||||
return {
|
||||
boardId: subtask.boardId,
|
||||
slug: 'board',
|
||||
cardId,
|
||||
swimlaneId: subtask.swimlaneId,
|
||||
listId: subtask.listId,
|
||||
};
|
||||
}
|
||||
// No board reference at all: broken subtask, don't navigate (and don't
|
||||
// throw — the caller shows a warning instead).
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Same idea for the "Go to board" popup entry (js-go-to-subtask-board):
|
||||
// prefer the loaded board's id/slug, fall back to the subtask's boardId so a
|
||||
// not-yet-subscribed deposit board is still reachable (#1853).
|
||||
export function subtaskBoardNavTarget(subtask) {
|
||||
if (!subtask) {
|
||||
return undefined;
|
||||
}
|
||||
const board = typeof subtask.board === 'function' ? subtask.board() : undefined;
|
||||
if (canNavigateToSubtaskBoard(board)) {
|
||||
return { id: board._id, slug: board.slug };
|
||||
}
|
||||
if (subtask.boardId) {
|
||||
return { id: subtask.boardId, slug: 'board' };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -3,7 +3,10 @@ import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
|
||||
import Cards from '/models/cards';
|
||||
import { Filter } from '/client/lib/filter';
|
||||
import { subtaskStatusLabel } from './subtaskStatusHelpers';
|
||||
import { subtaskNavTarget } from './subtaskViewHelpers';
|
||||
import {
|
||||
subtaskNavTarget,
|
||||
subtaskBoardNavTarget,
|
||||
} from './subtaskViewHelpers';
|
||||
import { Utils } from '/client/lib/utils';
|
||||
|
||||
Template.subtasks.events({
|
||||
@@ -125,20 +128,34 @@ Template.subtaskActionsPopup.events({
|
||||
const subtask = Template.currentData().subtask;
|
||||
// #3743: open the SUBTASK card itself, not the parent/current card.
|
||||
// subtaskNavTarget derives boardId/slug/cardId from the subtask only.
|
||||
// #4762: it also returns undefined while the subtask's board is not
|
||||
// loaded yet (ReactiveCache miss), mirroring js-go-to-subtask-board.
|
||||
// #1853 / #4762: when the subtask's board (often a DIFFERENT deposit
|
||||
// board) is not in minimongo yet, it falls back to the subtask's own
|
||||
// boardId so the route loads the board — no TypeError, no dead button.
|
||||
// It only returns undefined for a truly broken subtask document.
|
||||
const target = subtaskNavTarget(subtask);
|
||||
if (target) {
|
||||
FlowRouter.go('card', target);
|
||||
} else {
|
||||
// Broken subtask (no card id / board id): warn instead of throwing.
|
||||
console.warn(
|
||||
'Cannot view subtask: missing board/card id on subtask',
|
||||
subtask && subtask._id,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
'click .js-go-to-subtask-board'() {
|
||||
const subtask = Template.currentData().subtask;
|
||||
const board = subtask.board();
|
||||
if (board) {
|
||||
// #1853: fall back to subtask.boardId when the board doc is not loaded.
|
||||
const target = subtaskBoardNavTarget(subtask);
|
||||
if (target) {
|
||||
Popup.close();
|
||||
FlowRouter.go('board', { id: board._id, slug: board.slug });
|
||||
FlowRouter.go('board', target);
|
||||
} else {
|
||||
console.warn(
|
||||
'Cannot go to subtask board: missing board id on subtask',
|
||||
subtask && subtask._id,
|
||||
);
|
||||
}
|
||||
},
|
||||
'click .js-delete-subtask' : Popup.afterConfirm('subtaskDelete', async function () {
|
||||
|
||||
@@ -298,6 +298,25 @@ textarea::-moz-placeholder {
|
||||
font-size: clamp(20px, 4vw, 26px);
|
||||
margin: 0.5vh 1.5vw;
|
||||
}
|
||||
/* CJK (Japanese/Chinese/Korean) labels contain no spaces, so browsers may
|
||||
insert a line break between any two characters. In the narrow add-card /
|
||||
edit footers this made short labels such as "追加" (Add) and "リンク"
|
||||
(Link) wrap mid-word. `word-break: keep-all` forbids breaks inside CJK
|
||||
words while leaving Latin wrapping behavior unchanged, and `flex-wrap`
|
||||
lets the footer wrap between its links instead of inside them.
|
||||
See https://github.com/wekan/wekan/issues/4023 */
|
||||
.edit-controls,
|
||||
.add-controls {
|
||||
flex-wrap: wrap;
|
||||
word-break: keep-all;
|
||||
}
|
||||
.edit-controls button[type=submit],
|
||||
.add-controls button[type=submit] {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.add-controls .quiet {
|
||||
white-space: nowrap;
|
||||
}
|
||||
[type="checkbox"]:not(:checked),
|
||||
[type="checkbox"]:checked {
|
||||
position: absolute;
|
||||
|
||||
+122
-50
@@ -3,6 +3,11 @@ import { TAPi18n } from '/imports/i18n';
|
||||
import { EscapeActions } from '/client/lib/escapeActions';
|
||||
import { MultiSelection } from '/client/lib/multiSelection';
|
||||
import { Utils } from '/client/lib/utils';
|
||||
import Cards from '/models/cards';
|
||||
import {
|
||||
isDegenerateSortGap,
|
||||
computeRepairedDropIndex,
|
||||
} from '/models/lib/cardSortRepair';
|
||||
require('/client/lib/jquery-ui.js')
|
||||
|
||||
const { calculateIndex } = Utils;
|
||||
@@ -19,9 +24,17 @@ const { calculateIndex } = Utils;
|
||||
//
|
||||
// The old per-list "min width / max width / automatic" knobs are gone — the
|
||||
// rendered width is now a single hard value (see list.jade).
|
||||
//
|
||||
// #5659: the default/minimum width and the resolution order live in ONE
|
||||
// Meteor-free module shared with models/users.js, so every path (member,
|
||||
// anonymous public-board visitor, fixed mode) falls back to the SAME default
|
||||
// and all lists render the same width when nothing is customized.
|
||||
// ---------------------------------------------------------------------------
|
||||
const DEFAULT_LIST_WIDTH = 272;
|
||||
const MIN_LIST_WIDTH = 270;
|
||||
import {
|
||||
DEFAULT_LIST_WIDTH,
|
||||
MIN_LIST_WIDTH,
|
||||
resolveListWidth,
|
||||
} from '/models/lib/listWidth';
|
||||
|
||||
function isPersonalListWidth(boardId) {
|
||||
const board = ReactiveCache.getBoard(boardId);
|
||||
@@ -122,25 +135,28 @@ function saveAnonFixedListWidth(boardId, width) {
|
||||
|
||||
function effectiveListWidth(list) {
|
||||
if (!list) return DEFAULT_LIST_WIDTH;
|
||||
// #5729 In fixed width mode every list renders at the single shared value.
|
||||
if (isFixedListWidth(list.boardId)) {
|
||||
return fixedListWidthValue(list.boardId);
|
||||
// #5659: all inputs are gathered here, but the fallback order and the ONE
|
||||
// default width live in models/lib/listWidth.js (shared + unit tested).
|
||||
const fixedEnabled = isFixedListWidth(list.boardId);
|
||||
const personalMode = isPersonalListWidth(list.boardId);
|
||||
let personalWidth = null;
|
||||
if (personalMode) {
|
||||
const user = ReactiveCache.getCurrentUser();
|
||||
if (user) {
|
||||
const widths = user.getListWidths();
|
||||
personalWidth = widths[list.boardId] && widths[list.boardId][list._id];
|
||||
} else {
|
||||
personalWidth = readAnonListWidth(list.boardId, list._id);
|
||||
}
|
||||
}
|
||||
const shared =
|
||||
typeof list.width === 'number' && list.width >= MIN_LIST_WIDTH
|
||||
? list.width
|
||||
: DEFAULT_LIST_WIDTH;
|
||||
if (!isPersonalListWidth(list.boardId)) {
|
||||
return shared;
|
||||
}
|
||||
const user = ReactiveCache.getCurrentUser();
|
||||
if (user) {
|
||||
const widths = user.getListWidths();
|
||||
const w = widths[list.boardId] && widths[list.boardId][list._id];
|
||||
return typeof w === 'number' && w >= MIN_LIST_WIDTH ? w : shared;
|
||||
}
|
||||
const w = readAnonListWidth(list.boardId, list._id);
|
||||
return w || shared;
|
||||
return resolveListWidth({
|
||||
// #5729 In fixed width mode every list renders at the single shared value.
|
||||
fixedEnabled,
|
||||
fixedWidth: fixedEnabled ? fixedListWidthValue(list.boardId) : null,
|
||||
sharedWidth: list.width,
|
||||
personalMode,
|
||||
personalWidth,
|
||||
});
|
||||
}
|
||||
|
||||
// Can the current user change THIS list's width by dragging?
|
||||
@@ -276,7 +292,35 @@ Template.list.onRendered(function () {
|
||||
const prevCardDom = ui.item.prev('.js-minicard').get(0);
|
||||
const nextCardDom = ui.item.next('.js-minicard').get(0);
|
||||
const nCards = MultiSelection.isActive() ? MultiSelection.count() : 1;
|
||||
const sortIndex = calculateIndex(prevCardDom, nextCardDom, nCards);
|
||||
let sortIndex = calculateIndex(prevCardDom, nextCardDom, nCards);
|
||||
|
||||
// #3826: cards created by the "add subtask" flow were all inserted with
|
||||
// a constant sort of -1, so a list full of subtask cards contains only
|
||||
// ties. No number lies strictly between two equal sorts, so
|
||||
// calculateIndex returns base === neighbour sort with increment 0: the
|
||||
// write is then discarded by Card.move()'s no-op guard and the card
|
||||
// snaps back (and a multi-selection drop would give every selected card
|
||||
// the SAME sort, losing their relative order). When the drop landed in
|
||||
// such a degenerate gap, capture the target list's sibling cards in
|
||||
// their current visual order (before sortable('cancel') reshuffles the
|
||||
// DOM) so their sorts can be repaired below.
|
||||
const prevCardData = prevCardDom ? Blaze.getData(prevCardDom) : null;
|
||||
const nextCardData = nextCardDom ? Blaze.getData(nextCardDom) : null;
|
||||
let orderedSiblingCards = null;
|
||||
if (
|
||||
isDegenerateSortGap(
|
||||
prevCardData ? prevCardData.sort : null,
|
||||
nextCardData ? nextCardData.sort : null,
|
||||
)
|
||||
) {
|
||||
orderedSiblingCards = ui.item
|
||||
.parent()
|
||||
.children(itemsSelector)
|
||||
.not(ui.item)
|
||||
.toArray()
|
||||
.map(el => Blaze.getData(el))
|
||||
.filter(Boolean);
|
||||
}
|
||||
const listData = Blaze.getData(ui.item.parents('.list').get(0));
|
||||
const listId = listData._id;
|
||||
const currentBoard = Utils.getCurrentBoard();
|
||||
@@ -303,6 +347,25 @@ Template.list.onRendered(function () {
|
||||
// Blaze with the below query.
|
||||
$cards.sortable('cancel');
|
||||
|
||||
// #3826: the drop landed between two cards whose sorts do not strictly
|
||||
// increase (duplicate -1 sorts from subtask creation, or legacy data).
|
||||
// Repair the sibling sorts with the minimal bumps that make the visible
|
||||
// order strictly increasing, then recompute the drop index from the
|
||||
// repaired neighbours: base now falls strictly between them and the
|
||||
// increment is strictly positive (distinct sorts for a multi-selection).
|
||||
if (orderedSiblingCards && prevCardData && nextCardData) {
|
||||
const repairedDrop = computeRepairedDropIndex(
|
||||
orderedSiblingCards,
|
||||
prevCardData,
|
||||
nextCardData,
|
||||
nCards,
|
||||
);
|
||||
repairedDrop.updates.forEach(u => {
|
||||
Cards.update(u._id, { $set: { sort: u.sort } });
|
||||
});
|
||||
sortIndex = { base: repairedDrop.base, increment: repairedDrop.increment };
|
||||
}
|
||||
|
||||
if (MultiSelection.isActive()) {
|
||||
ReactiveCache.getCards(MultiSelection.getMongoSelector(), { sort: ['sort'] }).forEach((card, i) => {
|
||||
const newSwimlaneId = targetSwimlaneId
|
||||
@@ -326,37 +389,39 @@ Template.list.onRendered(function () {
|
||||
if (boardComponent) boardComponent.setIsDragging(false);
|
||||
},
|
||||
sort(event, ui) {
|
||||
const $boardCanvas = $('.board-canvas');
|
||||
const boardCanvas = $boardCanvas[0];
|
||||
|
||||
if (event.pageX < 10) { // scroll to the left
|
||||
boardCanvas.scrollLeft -= 15;
|
||||
ui.helper[0].offsetLeft -= 15;
|
||||
// #443: the HORIZONTAL scroller is the .js-lists lane (.swimlane has
|
||||
// overflow: auto), NOT .board-canvas, which only overflows vertically —
|
||||
// the old code compared against a scrollLeftMax of 0 and never fired, so
|
||||
// dragging a card toward an off-screen list never auto-scrolled the board.
|
||||
const { computeEdgeScroll, findLaneUnderPointer } = require('/imports/lib/boardAutoScroll');
|
||||
const lanes = document.querySelectorAll('.js-lists');
|
||||
const rects = Array.prototype.map.call(lanes, el => el.getBoundingClientRect());
|
||||
const laneIndex = findLaneUnderPointer(rects, event.clientX, event.clientY);
|
||||
if (laneIndex !== -1) {
|
||||
const nextLeft = computeEdgeScroll({
|
||||
pointer: event.clientX,
|
||||
lowEdge: rects[laneIndex].left,
|
||||
highEdge: rects[laneIndex].right,
|
||||
scrollPos: lanes[laneIndex].scrollLeft,
|
||||
scrollSize: lanes[laneIndex].scrollWidth,
|
||||
clientSize: lanes[laneIndex].clientWidth,
|
||||
});
|
||||
if (nextLeft !== null) lanes[laneIndex].scrollLeft = nextLeft;
|
||||
}
|
||||
if (
|
||||
event.pageX > boardCanvas.offsetWidth - 10 &&
|
||||
boardCanvas.scrollLeft < $boardCanvas.data('scrollLeftMax') // don't scroll more than possible
|
||||
) { // scroll to the right
|
||||
boardCanvas.scrollLeft += 15;
|
||||
// vertical auto-scroll stays on the board canvas
|
||||
const canvas = document.querySelector('.board-canvas');
|
||||
if (canvas) {
|
||||
const crect = canvas.getBoundingClientRect();
|
||||
const nextTop = computeEdgeScroll({
|
||||
pointer: event.clientY,
|
||||
lowEdge: crect.top,
|
||||
highEdge: crect.bottom,
|
||||
scrollPos: canvas.scrollTop,
|
||||
scrollSize: canvas.scrollHeight,
|
||||
clientSize: canvas.clientHeight,
|
||||
});
|
||||
if (nextTop !== null) canvas.scrollTop = nextTop;
|
||||
}
|
||||
if (
|
||||
event.pageY > boardCanvas.offsetHeight - 10 &&
|
||||
event.pageY + boardCanvas.scrollTop < $boardCanvas.data('scrollTopMax') // don't scroll more than possible
|
||||
) { // scroll to the bottom
|
||||
boardCanvas.scrollTop += 15;
|
||||
}
|
||||
if (event.pageY < 10) { // scroll to the top
|
||||
boardCanvas.scrollTop -= 15;
|
||||
}
|
||||
},
|
||||
activate(event, ui) {
|
||||
const $boardCanvas = $('.board-canvas');
|
||||
const boardCanvas = $boardCanvas[0];
|
||||
// scrollTopMax and scrollLeftMax only available at Firefox (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTopMax)
|
||||
// https://www.it-swarm.com.de/de/javascript/so-erhalten-sie-den-maximalen-dokument-scrolltop-wert/1069126844/
|
||||
$boardCanvas.data('scrollTopMax', boardCanvas.scrollHeight - boardCanvas.clientTop);
|
||||
// https://stackoverflow.com/questions/5138373/how-do-i-get-the-max-value-of-scrollleft/5704386#5704386
|
||||
$boardCanvas.data('scrollLeftMax', boardCanvas.scrollWidth - boardCanvas.clientWidth);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -384,6 +449,13 @@ Template.list.onRendered(function () {
|
||||
const currentBoardId = Tracker.nonreactive(() => {
|
||||
return Session.get('currentBoard');
|
||||
});
|
||||
// #1554: reactive dependency so newly added / re-rendered minicards are
|
||||
// (re)initialized as droppable for label/member drags. The dependency
|
||||
// (Cards.find(...).fetch()) was dropped in 7673c77c5, so the autorun ran
|
||||
// ONCE per list render and cards added afterwards silently rejected
|
||||
// sidebar label/member drops until the board was re-entered. Re-running
|
||||
// .droppable() on initialized elements is an idempotent option refresh.
|
||||
ReactiveCache.getCards({ boardId: currentBoardId });
|
||||
Tracker.afterFlush(() => {
|
||||
$cards.find(itemsSelector).droppable({
|
||||
hoverClass: 'draggable-hover-card',
|
||||
|
||||
@@ -13,6 +13,10 @@ import { isLinkableCardTarget } from '/models/lib/linkedCardTarget';
|
||||
import { listCardsSelector } from '/models/lib/swimlaneFilter';
|
||||
import { sortCardsByTitle } from '/models/lib/sortCardsByTitle';
|
||||
import { isLazyCards, BoardListCardCounts, windowCountId } from '/client/lib/lazyCards';
|
||||
import {
|
||||
mutationsChangeDragGeometry,
|
||||
findActiveCardDrag,
|
||||
} from '/client/lib/cardDragGeometry';
|
||||
import autosize from 'autosize';
|
||||
|
||||
// SubsManager removed for Meteor 3 migration
|
||||
@@ -453,6 +457,80 @@ Template.listBody.events({
|
||||
},
|
||||
});
|
||||
|
||||
// #2769 Card lands in the WRONG swimlane when it is dropped while a connected
|
||||
// list's layout changed mid-drag. jQuery UI sortable snapshots the geometry
|
||||
// of every connected `.js-minicards` container once at drag start
|
||||
// (_mouseStart runs refreshPositions() BEFORE the `start` callback) and only
|
||||
// re-snapshots after its own placeholder moves — never when Blaze mutates the
|
||||
// DOM. Two such mutations routinely happen during a drag: another user's
|
||||
// newly added card is reactively inserted into the target list (the issue's
|
||||
// "target column where a new card is being added"), and the dragging user's
|
||||
// own open add-card composer is closed by the `start` callback's
|
||||
// EscapeActions call, AFTER the snapshot. Every list/swimlane below the
|
||||
// change then shifts vertically while the cached rectangles stay put, so the
|
||||
// drop resolves against a stale map: the placeholder is parked in the
|
||||
// neighbouring swimlane's copy of the list (hence the reporter's "no drop
|
||||
// shadow in the target column") and the stop handler's
|
||||
// ui.item.parents('.swimlane') (client/components/lists/list.js) faithfully
|
||||
// persists that wrong swimlane.
|
||||
// Fix: watch each list's minicards for REAL DOM changes (Blaze insertions and
|
||||
// removals — not jQuery UI's own placeholder/helper churn, which the library
|
||||
// already follows with its own refresh) and re-cache the active drag's
|
||||
// geometry with sortable('refresh'). The decision helpers are pure and unit
|
||||
// tested in tests/cardDragGeometry.test.cjs.
|
||||
Template.listBody.onRendered(function () {
|
||||
const minicardsEl = this.find('.js-minicards');
|
||||
if (!minicardsEl || typeof MutationObserver === 'undefined') {
|
||||
return;
|
||||
}
|
||||
this.dragGeometryRefreshQueued = false;
|
||||
this.dragGeometryObserver = new MutationObserver(mutations => {
|
||||
// Cheapest gate first: no drag helper on the page means no drag at all
|
||||
// (this observer also fires on every ordinary reactive card update).
|
||||
if (!document.getElementsByClassName('ui-sortable-helper').length) {
|
||||
return;
|
||||
}
|
||||
if (!mutationsChangeDragGeometry(mutations)) {
|
||||
return;
|
||||
}
|
||||
if (this.dragGeometryRefreshQueued) {
|
||||
return;
|
||||
}
|
||||
this.dragGeometryRefreshQueued = true;
|
||||
// Coalesce bursts (Blaze can insert several nodes per flush); by the time
|
||||
// the timeout runs, this tick's layout is final and measurable.
|
||||
setTimeout(() => {
|
||||
this.dragGeometryRefreshQueued = false;
|
||||
const active = findActiveCardDrag(
|
||||
$('.js-minicards')
|
||||
.toArray()
|
||||
.map(el => $.data(el, 'ui-sortable')),
|
||||
);
|
||||
if (active) {
|
||||
try {
|
||||
// Re-collects the items of every connected container and re-measures
|
||||
// all container rectangles, so the pointer is matched against the
|
||||
// CURRENT layout for the rest of the drag.
|
||||
active.refresh();
|
||||
} catch (e) {
|
||||
// A failed re-measure must never break the drag itself.
|
||||
}
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
this.dragGeometryObserver.observe(minicardsEl, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
});
|
||||
|
||||
Template.listBody.onDestroyed(function () {
|
||||
if (this.dragGeometryObserver) {
|
||||
this.dragGeometryObserver.disconnect();
|
||||
this.dragGeometryObserver = null;
|
||||
}
|
||||
});
|
||||
|
||||
function toggleValueInReactiveArray(reactiveValue, value) {
|
||||
const array = reactiveValue.get();
|
||||
const valueIndex = array.indexOf(value);
|
||||
|
||||
@@ -9,6 +9,13 @@ import { isHexColor, toHex } from '/models/lib/contrastColor';
|
||||
import { MultiSelection } from '/client/lib/multiSelection';
|
||||
import { Utils } from '/client/lib/utils';
|
||||
import { lazyListCardCount } from '/client/lib/lazyCards';
|
||||
// #5659: single source of truth for the default/minimum list width, shared
|
||||
// with client/components/lists/list.js and models/users.js.
|
||||
import {
|
||||
DEFAULT_LIST_WIDTH,
|
||||
MIN_LIST_WIDTH,
|
||||
normalizeListWidth,
|
||||
} from '/models/lib/listWidth';
|
||||
|
||||
let listsColors;
|
||||
Meteor.startup(() => {
|
||||
@@ -562,12 +569,12 @@ function readAnonFixedListWidth(boardId) {
|
||||
if (stored) {
|
||||
const widths = JSON.parse(stored);
|
||||
const w = widths[boardId];
|
||||
if (typeof w === 'number' && w >= 270) return w;
|
||||
if (typeof w === 'number' && w >= MIN_LIST_WIDTH) return w;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Error reading fixed list width from localStorage:', e);
|
||||
}
|
||||
return 272;
|
||||
return DEFAULT_LIST_WIDTH;
|
||||
}
|
||||
|
||||
function isFixedListWidth(boardId) {
|
||||
@@ -611,8 +618,7 @@ Template.setListWidthPopup.helpers({
|
||||
if (isFixedListWidth(list.boardId)) {
|
||||
return fixedListWidthValue(list.boardId);
|
||||
}
|
||||
const shared =
|
||||
typeof list.width === 'number' && list.width >= 270 ? list.width : 272;
|
||||
const shared = normalizeListWidth(list.width);
|
||||
if (!isPersonalListWidth(list.boardId)) {
|
||||
return shared;
|
||||
}
|
||||
@@ -620,7 +626,7 @@ Template.setListWidthPopup.helpers({
|
||||
if (user) {
|
||||
const widths = user.getListWidths();
|
||||
const w = widths[list.boardId] && widths[list.boardId][list._id];
|
||||
return typeof w === 'number' && w >= 270 ? w : shared;
|
||||
return normalizeListWidth(w, shared);
|
||||
}
|
||||
return shared;
|
||||
},
|
||||
@@ -702,7 +708,7 @@ Template.setListWidthPopup.events({
|
||||
const boardId = list.boardId;
|
||||
const width = parseInt(tpl.$('.list-width-value').val(), 10);
|
||||
|
||||
if (!width || width < 270) {
|
||||
if (!width || width < MIN_LIST_WIDTH) {
|
||||
tpl.$('.list-width-error').click();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,10 @@ Template.userFormsLayout.onCreated(function () {
|
||||
Meteor.call('isOidcRedirectionEnabled', (_, result) => {
|
||||
if (result) {
|
||||
AccountsTemplates.options.socialLoginStyle = 'redirect';
|
||||
options = {
|
||||
// #5695: this is an ES module, so the body runs in strict mode and
|
||||
// the previous undeclared `options = {...}` assignment threw a
|
||||
// ReferenceError, breaking the OIDC_REDIRECTION_ENABLED auto-login.
|
||||
const options = {
|
||||
loginStyle: AccountsTemplates.options.socialLoginStyle,
|
||||
};
|
||||
Meteor.loginWithOidc(options);
|
||||
|
||||
@@ -106,6 +106,9 @@ template(name="boardCardTitlePopup")
|
||||
form
|
||||
label
|
||||
| {{_ 'boardCardTitlePopup-title'}}
|
||||
input.js-card-filter-name(type="text" value=title autofocus)
|
||||
//- #2345: cardTitleFilter is passed as the popup's data context by the
|
||||
//- js-open-card-title-popup handler so reopening the popup shows the
|
||||
//- filter that is already set (it used to always render empty).
|
||||
input.js-card-filter-name(type="text" value=cardTitleFilter autofocus)
|
||||
input.js-card-filter-button.primary.wide(type="submit" value="{{_ 'set-filter'}}")
|
||||
|
||||
@@ -1,4 +1,31 @@
|
||||
import { TAPi18n } from '/imports/i18n';
|
||||
import { Utils } from '/client/lib/utils';
|
||||
import {
|
||||
cardTitleFilterOrWildcard,
|
||||
appendCardTitleFilterToDesc,
|
||||
} from '/models/lib/ruleCardTitleFilter';
|
||||
|
||||
// #2345: fallback reference to the live boardTriggers template instance, so the
|
||||
// card-title-filter popup can still store its value even if the Blaze
|
||||
// data-context walk in Popup.getOpenerComponent() does not resolve (same
|
||||
// module-level pattern as cardActions.js' sharedCardColorButtonValue).
|
||||
let activeBoardTriggersTemplate = null;
|
||||
|
||||
// #2345: the trigger description is assembled from the wizard's DOM text, which
|
||||
// never includes the card-title filter (it lives in a popup). Append it so the
|
||||
// created rule's details actually show the filter.
|
||||
function descWithCardTitleFilter(desc, cardTitle) {
|
||||
let label = 'card title filter';
|
||||
try {
|
||||
const translated = TAPi18n.__('boardCardTitlePopup-title');
|
||||
if (translated && translated !== 'boardCardTitlePopup-title') {
|
||||
label = translated.toLowerCase();
|
||||
}
|
||||
} catch (e) {
|
||||
// keep the English fallback label
|
||||
}
|
||||
return appendCardTitleFilterToDesc(desc, cardTitle, label);
|
||||
}
|
||||
|
||||
Template.boardTriggers.onCreated(function () {
|
||||
this.provaVar = new ReactiveVar('');
|
||||
@@ -7,6 +34,13 @@ Template.boardTriggers.onCreated(function () {
|
||||
this.setNameFilter = (name) => {
|
||||
this.cardTitleFilters[this.currentPopupTriggerId] = name;
|
||||
};
|
||||
activeBoardTriggersTemplate = this;
|
||||
});
|
||||
|
||||
Template.boardTriggers.onDestroyed(function () {
|
||||
if (activeBoardTriggersTemplate === this) {
|
||||
activeBoardTriggersTemplate = null;
|
||||
}
|
||||
});
|
||||
|
||||
Template.boardTriggers.events({
|
||||
@@ -14,16 +48,24 @@ Template.boardTriggers.events({
|
||||
const funct = Popup.open('boardCardTitle');
|
||||
const divId = $(event.currentTarget.parentNode.parentNode).attr('id');
|
||||
tpl.currentPopupTriggerId = divId;
|
||||
funct.call(this, event);
|
||||
// #2345: hand the already-stored filter to the popup as its data context so
|
||||
// reopening it shows the current value instead of an empty input.
|
||||
funct.call({ cardTitleFilter: tpl.cardTitleFilters[divId] || '' }, event);
|
||||
},
|
||||
'click .js-add-create-trigger'(event, tpl) {
|
||||
const desc = Utils.getTriggerActionDesc(event, tpl);
|
||||
const datas = Template.currentData();
|
||||
const listName = tpl.find('#create-list-name').value;
|
||||
const swimlaneName = tpl.find('#create-swimlane-name').value;
|
||||
const boardId = Session.get('currentBoard');
|
||||
const divId = $(event.currentTarget.parentNode).attr('id');
|
||||
const cardTitle = tpl.cardTitleFilters[divId];
|
||||
// #2345: an unset/empty filter is stored as the '*' wildcard so the trigger
|
||||
// document always carries a cardTitle field (the server matches with
|
||||
// cardTitle: { $in: [...] }, which a document missing the field never satisfies).
|
||||
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
|
||||
const desc = descWithCardTitleFilter(
|
||||
Utils.getTriggerActionDesc(event, tpl),
|
||||
cardTitle,
|
||||
);
|
||||
// move to generic funciont
|
||||
datas.triggerVar.set({
|
||||
activityType: 'createCard',
|
||||
@@ -36,13 +78,16 @@ Template.boardTriggers.events({
|
||||
},
|
||||
'click .js-add-moved-trigger'(event, tpl) {
|
||||
const datas = Template.currentData();
|
||||
const desc = Utils.getTriggerActionDesc(event, tpl);
|
||||
const swimlaneName = tpl.find('#create-swimlane-name-2').value;
|
||||
const actionSelected = tpl.find('#move-action').value;
|
||||
const listName = tpl.find('#move-list-name').value;
|
||||
const boardId = Session.get('currentBoard');
|
||||
const divId = $(event.currentTarget.parentNode).attr('id');
|
||||
const cardTitle = tpl.cardTitleFilters[divId];
|
||||
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
|
||||
const desc = descWithCardTitleFilter(
|
||||
Utils.getTriggerActionDesc(event, tpl),
|
||||
cardTitle,
|
||||
);
|
||||
if (actionSelected === 'moved-to') {
|
||||
datas.triggerVar.set({
|
||||
activityType: 'moveCard',
|
||||
@@ -68,12 +113,22 @@ Template.boardTriggers.events({
|
||||
},
|
||||
'click .js-add-gen-moved-trigger'(event, tpl) {
|
||||
const datas = Template.currentData();
|
||||
const desc = Utils.getTriggerActionDesc(event, tpl);
|
||||
const boardId = Session.get('currentBoard');
|
||||
const divId = $(event.currentTarget.parentNode).attr('id');
|
||||
// #2345: this trigger ignored the card-title-filter popup entirely AND
|
||||
// stored no cardTitle field at all — and since the server matches triggers
|
||||
// with cardTitle: { $in: [...] }, a moveCard trigger without the field
|
||||
// never fired for any card. Store the filter (or the '*' wildcard).
|
||||
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
|
||||
const desc = descWithCardTitleFilter(
|
||||
Utils.getTriggerActionDesc(event, tpl),
|
||||
cardTitle,
|
||||
);
|
||||
|
||||
datas.triggerVar.set({
|
||||
activityType: 'moveCard',
|
||||
boardId,
|
||||
cardTitle,
|
||||
swimlaneName: '*',
|
||||
listName: '*',
|
||||
oldListName: '*',
|
||||
@@ -82,13 +137,20 @@ Template.boardTriggers.events({
|
||||
},
|
||||
'click .js-add-arch-trigger'(event, tpl) {
|
||||
const datas = Template.currentData();
|
||||
const desc = Utils.getTriggerActionDesc(event, tpl);
|
||||
const actionSelected = tpl.find('#arch-action').value;
|
||||
const boardId = Session.get('currentBoard');
|
||||
const divId = $(event.currentTarget.parentNode).attr('id');
|
||||
// #2345: the archive/unarchive trigger also dropped the card-title filter.
|
||||
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
|
||||
const desc = descWithCardTitleFilter(
|
||||
Utils.getTriggerActionDesc(event, tpl),
|
||||
cardTitle,
|
||||
);
|
||||
if (actionSelected === 'archived') {
|
||||
datas.triggerVar.set({
|
||||
activityType: 'archivedCard',
|
||||
boardId,
|
||||
cardTitle,
|
||||
desc,
|
||||
});
|
||||
}
|
||||
@@ -96,6 +158,7 @@ Template.boardTriggers.events({
|
||||
datas.triggerVar.set({
|
||||
activityType: 'restoredCard',
|
||||
boardId,
|
||||
cardTitle,
|
||||
desc,
|
||||
});
|
||||
}
|
||||
@@ -104,15 +167,27 @@ Template.boardTriggers.events({
|
||||
|
||||
Template.boardCardTitlePopup.events({
|
||||
submit(event) {
|
||||
// #2345: preventDefault FIRST — if anything below throws, a real form
|
||||
// submit would reload the page and silently drop the filter.
|
||||
event.preventDefault();
|
||||
const title = $(event.target)
|
||||
.find('.js-card-filter-name')
|
||||
.val()
|
||||
.trim();
|
||||
const opener = Popup.getOpenerComponent();
|
||||
if (opener?.setNameFilter) {
|
||||
let opener = null;
|
||||
try {
|
||||
opener = Popup.getOpenerComponent();
|
||||
} catch (e) {
|
||||
opener = null;
|
||||
}
|
||||
if (!opener || typeof opener.setNameFilter !== 'function') {
|
||||
// #2345: fall back to the live boardTriggers instance when the Blaze
|
||||
// data-context walk cannot resolve the opener.
|
||||
opener = activeBoardTriggersTemplate;
|
||||
}
|
||||
if (opener && typeof opener.setNameFilter === 'function') {
|
||||
opener.setNameFilter(title);
|
||||
}
|
||||
event.preventDefault();
|
||||
Popup.back();
|
||||
},
|
||||
});
|
||||
@@ -234,6 +234,15 @@ Template.attachments.onCreated(function () {
|
||||
this.activeSection = new ReactiveVar('move');
|
||||
this.storageSettingsSubscription = Meteor.subscribe('attachmentStorageSettings');
|
||||
this.attachmentStorageSettings = new ReactiveVar(null);
|
||||
// #6473: the real storage paths only exist on the SERVER (WRITABLE_PATH is a
|
||||
// server environment variable — process.env in the browser never has it, so
|
||||
// computing the path client-side always showed the misleading "/data").
|
||||
this.storagePaths = new ReactiveVar(null);
|
||||
Meteor.call('getAttachmentStoragePaths', (err, paths) => {
|
||||
if (!err && paths) {
|
||||
this.storagePaths.set(paths);
|
||||
}
|
||||
});
|
||||
this.attachmentLimitUnits = new ReactiveVar({
|
||||
attachmentsUploadMaxBytes: 'mb',
|
||||
attachmentsDownloadMaxBytes: 'mb',
|
||||
@@ -537,16 +546,20 @@ Template.attachments.helpers({
|
||||
isS3Active() {
|
||||
return Template.instance().activeSection.get() === 's3';
|
||||
},
|
||||
// #6473: these paths come from the getAttachmentStoragePaths server method —
|
||||
// WRITABLE_PATH is a server-side environment variable, so reading
|
||||
// process.env here in the browser always produced the misleading "/data".
|
||||
filesystemPath() {
|
||||
return process.env.WRITABLE_PATH || '/data';
|
||||
const paths = Template.instance().storagePaths.get();
|
||||
return paths ? paths.writablePath : '';
|
||||
},
|
||||
attachmentsPath() {
|
||||
const writablePath = process.env.WRITABLE_PATH || '/data';
|
||||
return `${writablePath}/attachments`;
|
||||
const paths = Template.instance().storagePaths.get();
|
||||
return paths ? paths.attachments : '';
|
||||
},
|
||||
avatarsPath() {
|
||||
const writablePath = process.env.WRITABLE_PATH || '/data';
|
||||
return `${writablePath}/avatars`;
|
||||
const paths = Template.instance().storagePaths.get();
|
||||
return paths ? paths.avatars : '';
|
||||
},
|
||||
filesystemEnabled() {
|
||||
const tpl = Template.instance();
|
||||
|
||||
@@ -1171,31 +1171,30 @@ Template.modifyTeamsUsers.events({
|
||||
selectedEltValue = selectedElt.options[selectedElt.selectedIndex].text;
|
||||
selectedEltValueId = selectedElt.options[selectedElt.selectedIndex].value;
|
||||
|
||||
// #4593: `teams` is a forbidden field for direct client-side Users.update
|
||||
// (see server/permissions/users.js: only the owner may update, and never
|
||||
// `teams`), so the previous Users.update() calls here were silently denied
|
||||
// by the server and the bulk team assignment never persisted — a user
|
||||
// "added" to a team this way never saw the boards that team is assigned
|
||||
// to. Use the admin-only `editUser` method instead, which persists the
|
||||
// change and also grants the user membership of the boards the gained
|
||||
// team is assigned to.
|
||||
if(document.getElementById('addAction').checked){
|
||||
for(let i = 0; i < selectedUserChkBoxUserIds.length; i++){
|
||||
currentUser = ReactiveCache.getUser(selectedUserChkBoxUserIds[i]);
|
||||
userTms = currentUser.teams;
|
||||
if(userTms == undefined || userTms.length == 0){
|
||||
userTms = [];
|
||||
// Copy, so the cached minimongo document is not mutated in place.
|
||||
userTms = (currentUser.teams || []).slice();
|
||||
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
|
||||
if(currUserTeamIndex == -1){
|
||||
userTms.push({
|
||||
"teamId": selectedEltValueId,
|
||||
"teamDisplayName": selectedEltValue,
|
||||
})
|
||||
}
|
||||
else if(userTms.length > 0)
|
||||
{
|
||||
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
|
||||
if(currUserTeamIndex == -1){
|
||||
userTms.push({
|
||||
"teamId": selectedEltValueId,
|
||||
"teamDisplayName": selectedEltValue,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Users.update(selectedUserChkBoxUserIds[i], {
|
||||
$set:{
|
||||
teams: userTms
|
||||
Meteor.call('editUser', selectedUserChkBoxUserIds[i], { teams: userTms }, (error) => {
|
||||
if (error) {
|
||||
console.error('Error updating user teams:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1203,18 +1202,15 @@ Template.modifyTeamsUsers.events({
|
||||
else{
|
||||
for(let i = 0; i < selectedUserChkBoxUserIds.length; i++){
|
||||
currentUser = ReactiveCache.getUser(selectedUserChkBoxUserIds[i]);
|
||||
userTms = currentUser.teams;
|
||||
if(userTms !== undefined || userTms.length > 0)
|
||||
{
|
||||
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
|
||||
if(currUserTeamIndex != -1){
|
||||
userTms.splice(currUserTeamIndex, 1);
|
||||
}
|
||||
userTms = (currentUser.teams || []).slice();
|
||||
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
|
||||
if(currUserTeamIndex != -1){
|
||||
userTms.splice(currUserTeamIndex, 1);
|
||||
}
|
||||
|
||||
Users.update(selectedUserChkBoxUserIds[i], {
|
||||
$set:{
|
||||
teams: userTms
|
||||
Meteor.call('editUser', selectedUserChkBoxUserIds[i], { teams: userTms }, (error) => {
|
||||
if (error) {
|
||||
console.error('Error updating user teams:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -255,6 +255,14 @@ Template.setting.onCreated(function () {
|
||||
this.webhookSetting = new ReactiveVar(false);
|
||||
this.attachmentSettings = new ReactiveVar(false);
|
||||
this.attachmentStorageSettings = new ReactiveVar(null);
|
||||
// #6473: real storage paths come from the server (WRITABLE_PATH does not
|
||||
// exist in the browser's process.env, which always showed "/data").
|
||||
this.storagePaths = new ReactiveVar(null);
|
||||
Meteor.call('getAttachmentStoragePaths', (err, paths) => {
|
||||
if (!err && paths) {
|
||||
this.storagePaths.set(paths);
|
||||
}
|
||||
});
|
||||
this.attachmentLimitUnits = new ReactiveVar({
|
||||
attachmentsUploadMaxBytes: 'mb',
|
||||
attachmentsDownloadMaxBytes: 'mb',
|
||||
@@ -393,18 +401,22 @@ Template.setting.helpers({
|
||||
},
|
||||
|
||||
// Attachment settings helpers
|
||||
// #6473: these come from the getAttachmentStoragePaths server method —
|
||||
// WRITABLE_PATH is a server-side environment variable, so reading
|
||||
// process.env here in the browser always produced the misleading "/data".
|
||||
filesystemPath() {
|
||||
return process.env.WRITABLE_PATH || '/data';
|
||||
const paths = Template.instance().storagePaths.get();
|
||||
return paths ? paths.writablePath : '';
|
||||
},
|
||||
|
||||
attachmentsPath() {
|
||||
const writablePath = process.env.WRITABLE_PATH || '/data';
|
||||
return `${writablePath}/attachments`;
|
||||
const paths = Template.instance().storagePaths.get();
|
||||
return paths ? paths.attachments : '';
|
||||
},
|
||||
|
||||
avatarsPath() {
|
||||
const writablePath = process.env.WRITABLE_PATH || '/data';
|
||||
return `${writablePath}/avatars`;
|
||||
const paths = Template.instance().storagePaths.get();
|
||||
return paths ? paths.avatars : '';
|
||||
},
|
||||
|
||||
gridfsEnabled() {
|
||||
|
||||
@@ -259,6 +259,23 @@ body.grey-icons-enabled .sidebar .sidebar-content ul.sidebar-list li > a .fa.fa-
|
||||
z-index: 0;
|
||||
inset-inline-start: 5px;
|
||||
}
|
||||
/* #3199: In the Archive sidebar's Cards tab each card's Restore/Delete links
|
||||
used to sit BETWEEN two archived cards with near-equal spacing, so users
|
||||
could not tell which card they belonged to. Group each card with its own
|
||||
links: no gap between the card and its links, and a clear separator gap
|
||||
below the whole group before the next card. Spacing-only, so it works in
|
||||
every board color/theme; logical properties keep it RTL-safe. */
|
||||
.archived-card-item {
|
||||
margin-block-end: 1.6em;
|
||||
}
|
||||
.archived-card-item .minicard-wrapper {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.archived-card-item p.quiet {
|
||||
margin-block-start: 2px;
|
||||
margin-block-end: 0;
|
||||
padding-inline-start: 4px;
|
||||
}
|
||||
.archived-lists .archived-lists-item {
|
||||
border-top: 1px solid #ccc;
|
||||
clear: both;
|
||||
|
||||
@@ -16,23 +16,27 @@ template(name="archivesSidebar")
|
||||
| -
|
||||
a.js-delete-all-cards {{_ 'delete-all'}}
|
||||
each archivedCards
|
||||
.minicard-wrapper.js-minicard
|
||||
+minicard(this)
|
||||
if currentUser.isBoardMember
|
||||
unless isWorker
|
||||
unless currentUser.isReadOnly
|
||||
unless currentUser.isReadAssignedOnly
|
||||
p.quiet
|
||||
if this.archivedAt
|
||||
| {{_ 'archived-at' }}
|
||||
| | {{ displayDate this.archivedAt 'LLL' }}
|
||||
br
|
||||
a.js-restore-card {{_ 'restore'}}
|
||||
if currentUser.isBoardAdmin
|
||||
| -
|
||||
a.js-delete-card {{_ 'delete'}}
|
||||
if cardIsInArchivedList
|
||||
p.quiet.small ({{_ 'warn-list-archived'}})
|
||||
//- #3199: keep each archived card and ITS Restore/Delete links in
|
||||
//- one wrapper so the links visually group with the card above
|
||||
//- them instead of floating ambiguously between two cards.
|
||||
.archived-card-item
|
||||
.minicard-wrapper.js-minicard
|
||||
+minicard(this)
|
||||
if currentUser.isBoardMember
|
||||
unless isWorker
|
||||
unless currentUser.isReadOnly
|
||||
unless currentUser.isReadAssignedOnly
|
||||
p.quiet
|
||||
if this.archivedAt
|
||||
| {{_ 'archived-at' }}
|
||||
| | {{ displayDate this.archivedAt 'LLL' }}
|
||||
br
|
||||
a.js-restore-card {{_ 'restore'}}
|
||||
if currentUser.isBoardAdmin
|
||||
| -
|
||||
a.js-delete-card {{_ 'delete'}}
|
||||
if cardIsInArchivedList
|
||||
p.quiet.small ({{_ 'warn-list-archived'}})
|
||||
else
|
||||
p.no-items-message {{_ 'no-archived-cards'}}
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for keeping jQuery UI sortable's cached drag geometry in sync
|
||||
// with the real card layout. Extracted so the decision logic is unit-testable
|
||||
// in plain Node without Meteor (mirrors models/lib/cardSortRepair.js).
|
||||
//
|
||||
// #2769 "Card moves to wrong swimlane when moving to target column where a
|
||||
// new card is being added": jQuery UI sortable snapshots the geometry of
|
||||
// every connected `.js-minicards` container ONCE at drag start
|
||||
// (sortable._mouseStart calls refreshPositions() BEFORE it fires the `start`
|
||||
// callback) and only re-snapshots after its OWN placeholder rearranges. It
|
||||
// never notices DOM changes made by anyone else. Two such changes routinely
|
||||
// happen DURING a card drag:
|
||||
//
|
||||
// * another user submits the open add-card composer, so Blaze reactively
|
||||
// inserts the new minicard into a connected list (the issue's "target
|
||||
// column where a new card is being added"), and
|
||||
// * the dragging user's own open composer is closed by the `start`
|
||||
// callback's EscapeActions.executeUpTo('popup-close')
|
||||
// (client/components/lists/list.js) — i.e. AFTER the snapshot was taken.
|
||||
//
|
||||
// Either way, every list and swimlane below the change shifts vertically
|
||||
// while the cached rectangles stay where they were, so the pointer is matched
|
||||
// against a stale map: the placeholder is parked in the NEIGHBOURING
|
||||
// swimlane's copy of the list (which is why the reporter saw no drop shadow
|
||||
// in the column they were aiming at), and the `stop` handler's
|
||||
// ui.item.parents('.swimlane') then faithfully reports that wrong swimlane —
|
||||
// the card "disappears and reappears in the swimlane below".
|
||||
//
|
||||
// The wiring lives in client/components/lists/listBody.js (a MutationObserver
|
||||
// per list body that calls sortable('refresh') on the active drag). The
|
||||
// decisions worth testing in isolation are below:
|
||||
// 1. whether a mutation batch represents a REAL layout change (a Blaze
|
||||
// insertion/removal) as opposed to jQuery UI's own placeholder/helper
|
||||
// churn, which happens on every mousemove and must not trigger anything,
|
||||
// and
|
||||
// 2. which sortable instance (if any) is the active card drag whose
|
||||
// geometry needs re-caching.
|
||||
|
||||
// jQuery UI marks the elements it moves around itself during a drag: the drop
|
||||
// shadow ("ui-sortable-placeholder") and the dragged clone
|
||||
// ("ui-sortable-helper"). Their insertions/removals are part of the drag and
|
||||
// already followed by the library's own refreshPositions; reacting to them
|
||||
// would just do the same work twice on every mousemove.
|
||||
function nodeChangesDragGeometry(node) {
|
||||
if (!node || node.nodeType !== 1) {
|
||||
// Text/comment nodes: no box of their own worth re-snapshotting for.
|
||||
return false;
|
||||
}
|
||||
const classList = node.classList;
|
||||
if (!classList || typeof classList.contains !== 'function') {
|
||||
// An element we cannot classify still occupies layout space.
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
!classList.contains('ui-sortable-placeholder') &&
|
||||
!classList.contains('ui-sortable-helper')
|
||||
);
|
||||
}
|
||||
|
||||
// Does this MutationObserver batch contain at least one real DOM change
|
||||
// (an element other than jQuery UI's own drag artefacts was added or
|
||||
// removed)? Only then is the drag geometry snapshot stale.
|
||||
function mutationsChangeDragGeometry(mutations) {
|
||||
if (!mutations) return false;
|
||||
for (let i = 0; i < mutations.length; i += 1) {
|
||||
const mutation = mutations[i];
|
||||
if (!mutation || mutation.type !== 'childList') continue;
|
||||
const added = mutation.addedNodes || [];
|
||||
const removed = mutation.removedNodes || [];
|
||||
for (let j = 0; j < added.length; j += 1) {
|
||||
if (nodeChangesDragGeometry(added[j])) return true;
|
||||
}
|
||||
for (let j = 0; j < removed.length; j += 1) {
|
||||
if (nodeChangesDragGeometry(removed[j])) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Given the sortable instances of every card container on the board, return
|
||||
// the one an active card drag started from — that instance owns the cached
|
||||
// geometry of ALL connected containers (its refresh() re-collects items and
|
||||
// re-measures every container). Returns null when no card drag is running,
|
||||
// e.g. when the observed change was an ordinary reactive update, or the
|
||||
// leftover DOM churn of sortable('cancel') after the drag already ended
|
||||
// (sortable sets `dragging` back to false before its stop event fires).
|
||||
function findActiveCardDrag(instances) {
|
||||
if (!instances) return null;
|
||||
for (let i = 0; i < instances.length; i += 1) {
|
||||
const instance = instances[i];
|
||||
if (instance && instance.dragging === true && instance.currentItem) {
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
nodeChangesDragGeometry,
|
||||
mutationsChangeDragGeometry,
|
||||
findActiveCardDrag,
|
||||
};
|
||||
+25
-25
@@ -3,11 +3,12 @@ import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { ReactiveCache } from '/imports/reactiveCache';
|
||||
import { getCurrentCardFromContext } from '/client/lib/currentCard';
|
||||
import { normalizeDigits } from '/imports/lib/dateUtils';
|
||||
|
||||
// Helper to check if a date is valid
|
||||
function isValidDate(date) {
|
||||
return date instanceof Date && !isNaN(date);
|
||||
}
|
||||
import {
|
||||
isValidDate,
|
||||
formatTime,
|
||||
initialTimeValue,
|
||||
fallbackSubmitTime,
|
||||
} from '/imports/lib/datePickerTime';
|
||||
|
||||
// Format date as YYYY-MM-DD
|
||||
function formatDate(date) {
|
||||
@@ -18,14 +19,6 @@ function formatDate(date) {
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
// Format time as HH:mm
|
||||
function formatTime(date) {
|
||||
if (!isValidDate(date)) return '';
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
return `${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up datepicker state on a template instance.
|
||||
* Call from onCreated. Stores state on tpl.datePicker.
|
||||
@@ -53,18 +46,21 @@ export function setupDatePicker(tpl, { defaultTime = '1970-01-01 08:00:00', init
|
||||
*/
|
||||
export function datePickerRendered(tpl) {
|
||||
const dp = tpl.datePicker;
|
||||
if (isValidDate(dp.date.get())) {
|
||||
const dateInput = tpl.find('#date');
|
||||
const timeInput = tpl.find('#time');
|
||||
const dateInput = tpl.find('#date');
|
||||
const timeInput = tpl.find('#time');
|
||||
|
||||
if (dateInput) {
|
||||
dateInput.value = formatDate(dp.date.get());
|
||||
}
|
||||
if (timeInput && !timeInput.value && dp.defaultTime) {
|
||||
const defaultDate = new Date(dp.defaultTime);
|
||||
timeInput.value = formatTime(defaultDate);
|
||||
} else if (timeInput && isValidDate(dp.date.get())) {
|
||||
timeInput.value = formatTime(dp.date.get());
|
||||
if (dateInput && isValidDate(dp.date.get())) {
|
||||
dateInput.value = formatDate(dp.date.get());
|
||||
}
|
||||
// Pre-fill the time input: an existing card date keeps its own time; a
|
||||
// card without this date gets the configured default (e.g. 17:00 for due
|
||||
// dates) instead of an empty field that would silently save as 12:00
|
||||
// (#1502). The template already fills the input for existing dates, so
|
||||
// only ever write into an empty input.
|
||||
if (timeInput && !timeInput.value) {
|
||||
const initial = initialTimeValue(dp.date.get(), dp.defaultTime);
|
||||
if (initial) {
|
||||
timeInput.value = initial;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,8 +143,12 @@ export function datePickerEvents({ storeDate, deleteDate }) {
|
||||
|
||||
// Normalize any non-Latin digits (e.g. Persian/Arabic-Indic) before
|
||||
// parsing so due/start/end dates work in those locales (#5752).
|
||||
// An empty time falls back to the popup's configured default time
|
||||
// (e.g. 17:00 for due dates), then 12:00 (#1502).
|
||||
const dateValue = normalizeDigits(evt.target.date.value);
|
||||
const timeValue = normalizeDigits(evt.target.time.value) || '12:00'; // Default to 12:00 if no time given
|
||||
const timeValue =
|
||||
normalizeDigits(evt.target.time.value) ||
|
||||
fallbackSubmitTime(tpl.datePicker.defaultTime);
|
||||
|
||||
if (!dateValue) {
|
||||
tpl.datePicker.error.set('invalid-date');
|
||||
|
||||
+87
-60
@@ -21,7 +21,14 @@ import {
|
||||
fromNow,
|
||||
calendar
|
||||
} from '/imports/lib/dateUtils';
|
||||
import {
|
||||
tokenizeAdvancedFilter,
|
||||
parseAdvancedFilterDate,
|
||||
buildDateValueSelector,
|
||||
} from '/imports/lib/advancedFilter';
|
||||
import { weekRange } from '/models/lib/weekStart';
|
||||
import { Session } from 'meteor/session';
|
||||
import { boardScopedFilterSelector } from '/models/lib/boardScopedSelection';
|
||||
// Sidebar is imported late to avoid circular dependency (sidebar.js needs its
|
||||
// jade template loaded first, but router.js → filter.js would load it too early)
|
||||
let _Sidebar;
|
||||
@@ -322,55 +329,9 @@ class AdvancedFilter {
|
||||
}
|
||||
|
||||
_filterToCommands() {
|
||||
const commands = [];
|
||||
let current = '';
|
||||
let string = false;
|
||||
let regex = false;
|
||||
let wasString = false;
|
||||
let ignore = false;
|
||||
for (let i = 0; i < this._filter.length; i++) {
|
||||
const char = this._filter.charAt(i);
|
||||
if (ignore) {
|
||||
ignore = false;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
if (char === '/') {
|
||||
string = !string;
|
||||
if (string) regex = true;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
// eslint-disable-next-line quotes
|
||||
if (char === "'") {
|
||||
string = !string;
|
||||
if (string) wasString = true;
|
||||
continue;
|
||||
}
|
||||
if (char === '\\' && !string) {
|
||||
ignore = true;
|
||||
continue;
|
||||
}
|
||||
if (char === ' ' && !string) {
|
||||
commands.push({
|
||||
cmd: current,
|
||||
string: wasString,
|
||||
regex,
|
||||
});
|
||||
wasString = false;
|
||||
current = '';
|
||||
continue;
|
||||
}
|
||||
current += char;
|
||||
}
|
||||
if (current !== '') {
|
||||
commands.push({
|
||||
cmd: current,
|
||||
string: wasString,
|
||||
regex,
|
||||
});
|
||||
}
|
||||
return commands;
|
||||
// #2989: tokenizing lives in /imports/lib/advancedFilter.js so slashes
|
||||
// inside quoted values (dates like '06/04/2020') stay literal strings.
|
||||
return tokenizeAdvancedFilter(this._filter);
|
||||
}
|
||||
|
||||
_fieldNameToId(field) {
|
||||
@@ -397,6 +358,36 @@ class AdvancedFilter {
|
||||
return value;
|
||||
}
|
||||
|
||||
// #2989: date custom fields store Date objects (the date picker calls
|
||||
// card.setCustomField(id, date)), so comparing them against the typed
|
||||
// string / parseInt() number can never match. When the field is date-typed
|
||||
// and the value parses as a date, compare with a Date range instead.
|
||||
// Returns the operator document for 'customFields.value', or null to fall
|
||||
// back to the generic string/number selector.
|
||||
_customFieldDateSelector(field, str, op) {
|
||||
const found = ReactiveCache.getCustomField({
|
||||
name: field,
|
||||
});
|
||||
if (!found || found.type !== 'date') return null;
|
||||
// Disambiguate '06/04/2020' (both parts <= 12) with the user's date
|
||||
// format preference: day-first formats (DD/MM/YYYY, DD.MM.YYYY) read it
|
||||
// as 6 April, otherwise it is read month-first as 4 June.
|
||||
let dayFirst = false;
|
||||
try {
|
||||
const user = ReactiveCache.getCurrentUser();
|
||||
const dateFormat =
|
||||
user && typeof user.getDateFormat === 'function'
|
||||
? user.getDateFormat()
|
||||
: 'YYYY-MM-DD';
|
||||
dayFirst = /^D/.test(dateFormat);
|
||||
} catch (error) {
|
||||
dayFirst = false;
|
||||
}
|
||||
const range = parseAdvancedFilterDate(str, { dayFirst });
|
||||
if (!range) return null;
|
||||
return buildDateValueSelector(op, range);
|
||||
}
|
||||
|
||||
_arrayToSelector(commands) {
|
||||
try {
|
||||
//let changed = false;
|
||||
@@ -471,7 +462,11 @@ class AdvancedFilter {
|
||||
} else {
|
||||
commands[i] = {
|
||||
'customFields._id': this._fieldNameToId(field),
|
||||
'customFields.value': {
|
||||
'customFields.value': this._customFieldDateSelector(
|
||||
field,
|
||||
str,
|
||||
commands[i].cmd,
|
||||
) || {
|
||||
$in: [this._fieldValueToId(field, str), parseInt(str, 10)],
|
||||
},
|
||||
};
|
||||
@@ -500,7 +495,11 @@ class AdvancedFilter {
|
||||
} else {
|
||||
commands[i] = {
|
||||
'customFields._id': this._fieldNameToId(field),
|
||||
'customFields.value': {
|
||||
'customFields.value': this._customFieldDateSelector(
|
||||
field,
|
||||
str,
|
||||
commands[i].cmd,
|
||||
) || {
|
||||
$not: {
|
||||
$in: [this._fieldValueToId(field, str), parseInt(str, 10)],
|
||||
},
|
||||
@@ -521,7 +520,11 @@ class AdvancedFilter {
|
||||
const str = commands[i + 1].cmd;
|
||||
commands[i] = {
|
||||
'customFields._id': this._fieldNameToId(field),
|
||||
'customFields.value': {
|
||||
'customFields.value': this._customFieldDateSelector(
|
||||
field,
|
||||
str,
|
||||
commands[i].cmd,
|
||||
) || {
|
||||
$gt: parseInt(str, 10),
|
||||
},
|
||||
};
|
||||
@@ -540,7 +543,11 @@ class AdvancedFilter {
|
||||
const str = commands[i + 1].cmd;
|
||||
commands[i] = {
|
||||
'customFields._id': this._fieldNameToId(field),
|
||||
'customFields.value': {
|
||||
'customFields.value': this._customFieldDateSelector(
|
||||
field,
|
||||
str,
|
||||
commands[i].cmd,
|
||||
) || {
|
||||
$gte: parseInt(str, 10),
|
||||
},
|
||||
};
|
||||
@@ -558,7 +565,11 @@ class AdvancedFilter {
|
||||
const str = commands[i + 1].cmd;
|
||||
commands[i] = {
|
||||
'customFields._id': this._fieldNameToId(field),
|
||||
'customFields.value': {
|
||||
'customFields.value': this._customFieldDateSelector(
|
||||
field,
|
||||
str,
|
||||
commands[i].cmd,
|
||||
) || {
|
||||
$lt: parseInt(str, 10),
|
||||
},
|
||||
};
|
||||
@@ -577,7 +588,11 @@ class AdvancedFilter {
|
||||
const str = commands[i + 1].cmd;
|
||||
commands[i] = {
|
||||
'customFields._id': this._fieldNameToId(field),
|
||||
'customFields.value': {
|
||||
'customFields.value': this._customFieldDateSelector(
|
||||
field,
|
||||
str,
|
||||
commands[i].cmd,
|
||||
) || {
|
||||
$lte: parseInt(str, 10),
|
||||
},
|
||||
};
|
||||
@@ -772,11 +787,23 @@ export const Filter = {
|
||||
|
||||
mongoSelector(additionalSelector) {
|
||||
const filterSelector = this._getMongoSelector();
|
||||
if (additionalSelector === undefined) return filterSelector;
|
||||
else
|
||||
return {
|
||||
$and: [filterSelector, additionalSelector],
|
||||
};
|
||||
if (additionalSelector === undefined) {
|
||||
// #2306: a call without an additional selector means "all cards
|
||||
// matching the filter" (e.g. the filter sidebar's "To selection"
|
||||
// button). The client cache may also hold cards from OTHER boards
|
||||
// (a board being navigated away from, linked-board subscriptions,
|
||||
// notifications, popup card data, ...), so scope the query to the
|
||||
// board currently being viewed. Callers that pass an additional
|
||||
// selector are already scoped to a list/swimlane/card of the current
|
||||
// board.
|
||||
return boardScopedFilterSelector(
|
||||
filterSelector,
|
||||
Session.get('currentBoard'),
|
||||
);
|
||||
}
|
||||
return {
|
||||
$and: [filterSelector, additionalSelector],
|
||||
};
|
||||
},
|
||||
|
||||
reset() {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
|
||||
// Pure state transitions for the "only one inlined form open at a time"
|
||||
// invariant — extracted so it is unit-testable without a DOM / Meteor
|
||||
// (see tests/inlinedFormSingleOpen.test.cjs).
|
||||
//
|
||||
// #2418 ("Checklist item gets overwritten by previous item when selecting
|
||||
// another item with mouse"): opening a checklist item's edit form while
|
||||
// another item was already in edit mode did not close the previous form.
|
||||
// With two edit forms open at once, the submit handlers (which locate the
|
||||
// textarea with a template-wide `tpl.find('textarea.js-edit-checklist-item')`,
|
||||
// i.e. FIRST match in DOM order) read the OTHER form's textarea and
|
||||
// overwrote the submitted item with the previous item's text.
|
||||
//
|
||||
// Root cause in current code: the `.js-open-inlined-form` click handler
|
||||
// tried to close the previously opened form with
|
||||
// `EscapeActions.clickExecute(evt.target, 'inlinedForm')`, but the
|
||||
// 'inlinedForm' escape action is registered with `enabledOnClick: false`,
|
||||
// and EscapeActions._execute skips such actions for click executions
|
||||
// (`isEnabled = enabledOnClick || !isClick`). So the call was silently a
|
||||
// no-op and the previous form stayed open. (Regression from 8c3ce4bb7,
|
||||
// 2021-10-19, which replaced `EscapeActions.executeUpTo('inlinedForm')`
|
||||
// with `clickExecute` to stop popups from closing.)
|
||||
//
|
||||
// A secondary corruption: the close/submit/destroy paths reset the shared
|
||||
// `currentlyOpenedForm` tracker UNCONDITIONALLY, so closing a stale form
|
||||
// (e.g. checklists' "click all .js-close-inlined-form" workaround) nulled
|
||||
// the tracker for a DIFFERENT, still-open form — after which Escape no
|
||||
// longer closed the open form but fell through to closing the whole
|
||||
// card-details pane.
|
||||
//
|
||||
// The functions below centralize the transitions and fix both problems:
|
||||
// - openForm() explicitly closes the previously tracked form, without
|
||||
// touching popups (preserving the 8c3ce4bb7 intent).
|
||||
// - closeForm()/forgetForm() only reset the tracker when the form being
|
||||
// closed/destroyed IS the tracked one.
|
||||
//
|
||||
// `tracker` is a ReactiveVar-like object ({ get(), set(v) }) holding the
|
||||
// currently opened form; a "form" is any object with an `isOpen`
|
||||
// ReactiveVar-like property.
|
||||
|
||||
/** Open `form`, closing the previously tracked form (if any and different). */
|
||||
function openForm(tracker, form) {
|
||||
const previous = tracker.get();
|
||||
if (previous && previous !== form && previous.isOpen) {
|
||||
previous.isOpen.set(false);
|
||||
}
|
||||
if (form && form.isOpen) {
|
||||
form.isOpen.set(true);
|
||||
}
|
||||
tracker.set(form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close `form`. Resets the tracker ONLY when `form` is the tracked one, so
|
||||
* closing a stale/already-closed form cannot orphan another open form.
|
||||
*/
|
||||
function closeForm(tracker, form) {
|
||||
if (form && form.isOpen) {
|
||||
form.isOpen.set(false);
|
||||
}
|
||||
if (tracker.get() === form) {
|
||||
tracker.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop tracking `form` without touching its own state (template destroyed).
|
||||
* Only resets the tracker when `form` is the tracked one.
|
||||
*/
|
||||
function forgetForm(tracker, form) {
|
||||
if (tracker.get() === form) {
|
||||
tracker.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { openForm, closeForm, forgetForm };
|
||||
+19
-11
@@ -16,6 +16,11 @@ import { Template } from 'meteor/templating';
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { Tracker } from 'meteor/tracker';
|
||||
import { EscapeActions } from '/client/lib/escapeActions';
|
||||
import {
|
||||
openForm,
|
||||
closeForm,
|
||||
forgetForm,
|
||||
} from '/client/lib/inlinedFormManager';
|
||||
|
||||
// We can only have one inlined form element opened at a time
|
||||
const currentlyOpenedForm = new ReactiveVar(null);
|
||||
@@ -44,7 +49,9 @@ Template.inlinedForm.onRendered(function () {
|
||||
});
|
||||
|
||||
Template.inlinedForm.onDestroyed(function () {
|
||||
currentlyOpenedForm.set(null);
|
||||
// Only reset the tracker if THIS instance is the tracked one; destroying
|
||||
// an unrelated instance must not orphan another still-open form.
|
||||
forgetForm(currentlyOpenedForm, this);
|
||||
});
|
||||
|
||||
Template.inlinedForm.helpers({
|
||||
@@ -55,14 +62,19 @@ Template.inlinedForm.helpers({
|
||||
|
||||
Template.inlinedForm.events({
|
||||
'click .js-close-inlined-form'(evt, tpl) {
|
||||
tpl.isOpen.set(false);
|
||||
currentlyOpenedForm.set(null);
|
||||
closeForm(currentlyOpenedForm, tpl);
|
||||
},
|
||||
'click .js-open-inlined-form'(evt, tpl) {
|
||||
evt.preventDefault();
|
||||
EscapeActions.clickExecute(evt.target, 'inlinedForm');
|
||||
tpl.isOpen.set(true);
|
||||
currentlyOpenedForm.set(tpl);
|
||||
// #2418: clickExecute above does NOT close the previously opened form:
|
||||
// the 'inlinedForm' escape action is registered with
|
||||
// `enabledOnClick: false`, so click executions skip it. With the old
|
||||
// form left open, submitting the new one located the wrong textarea
|
||||
// (template-wide first match) and overwrote the item with the previous
|
||||
// item's text. Close the previous form explicitly instead (this keeps
|
||||
// popups open, which is why clickExecute replaced executeUpTo here).
|
||||
openForm(currentlyOpenedForm, tpl);
|
||||
},
|
||||
'keydown form textarea'(evt, tpl) {
|
||||
if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {
|
||||
@@ -73,8 +85,7 @@ Template.inlinedForm.events({
|
||||
const data = Template.currentData();
|
||||
if (data.autoclose !== false) {
|
||||
Tracker.afterFlush(() => {
|
||||
tpl.isOpen.set(false);
|
||||
currentlyOpenedForm.set(null);
|
||||
closeForm(currentlyOpenedForm, tpl);
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -86,10 +97,7 @@ EscapeActions.register(
|
||||
() => {
|
||||
const form = currentlyOpenedForm.get();
|
||||
if (form) {
|
||||
if (form.isOpen) {
|
||||
form.isOpen.set(false);
|
||||
currentlyOpenedForm.set(null);
|
||||
}
|
||||
closeForm(currentlyOpenedForm, form);
|
||||
}
|
||||
},
|
||||
() => {
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { ReactiveVar } from 'meteor/reactive-var';
|
||||
import { Session } from 'meteor/session';
|
||||
import { ReactiveCache } from '/imports/reactiveCache';
|
||||
import { Filter } from '/client/lib/filter';
|
||||
import { EscapeActions } from '/client/lib/escapeActions';
|
||||
import { Utils } from '/client/lib/utils';
|
||||
import {
|
||||
boardScopedSelectionSelector,
|
||||
cardIdsOnBoard,
|
||||
} from '/models/lib/boardScopedSelection';
|
||||
|
||||
// Late-bind Sidebar to avoid circular dependency (sidebar.js needs its template first)
|
||||
let _Sidebar;
|
||||
@@ -78,9 +83,15 @@ export const MultiSelection = {
|
||||
},
|
||||
|
||||
getMongoSelector() {
|
||||
return Filter.mongoSelector({
|
||||
_id: { $in: this._selectedCards.get() },
|
||||
});
|
||||
// #2306: scope the selection to the board currently being viewed so bulk
|
||||
// actions (archive, move, label, ...) never touch cards that were
|
||||
// selected on a previously visited board.
|
||||
return Filter.mongoSelector(
|
||||
boardScopedSelectionSelector(
|
||||
this._selectedCards.get(),
|
||||
Session.get('currentBoard'),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
isActive() {
|
||||
@@ -147,6 +158,12 @@ export const MultiSelection = {
|
||||
|
||||
toggle(cardIds, options = {}) {
|
||||
cardIds = typeof cardIds === 'string' ? [cardIds] : cardIds;
|
||||
// #2306: never let cards that verifiably live on ANOTHER board enter the
|
||||
// selection (e.g. handed over by a caller that queried the client card
|
||||
// cache without a board scope).
|
||||
cardIds = cardIdsOnBoard(cardIds, Session.get('currentBoard'), id =>
|
||||
ReactiveCache.getCard(id),
|
||||
);
|
||||
options = {
|
||||
add: true,
|
||||
remove: true,
|
||||
|
||||
@@ -67,14 +67,27 @@ describe('subtaskNavTarget (#3743)', function() {
|
||||
expect(target.cardId).to.not.equal(parentCard._id);
|
||||
});
|
||||
|
||||
it('returns undefined when the subtask board is not loaded yet (#4762)', function() {
|
||||
it('falls back to the subtask boardId when its board is not loaded (#1853/#4762)', function() {
|
||||
// The deposit/target board is often ANOTHER board that is not in
|
||||
// minimongo while the parent board is open; navigation must still work
|
||||
// (the card route loads the board), it must not throw or no-op.
|
||||
const subtask = makeSubtask();
|
||||
subtask.board = () => undefined;
|
||||
expect(subtaskNavTarget(subtask)).to.equal(undefined);
|
||||
const target = subtaskNavTarget(subtask);
|
||||
expect(target.boardId).to.equal('subtaskBoardId');
|
||||
expect(target.slug).to.equal('board');
|
||||
expect(target.cardId).to.equal('subtaskRealId');
|
||||
});
|
||||
|
||||
it('returns undefined for a missing subtask', function() {
|
||||
expect(subtaskNavTarget(undefined)).to.equal(undefined);
|
||||
expect(subtaskNavTarget(null)).to.equal(undefined);
|
||||
});
|
||||
|
||||
it('returns undefined for a broken subtask with no board reference at all', function() {
|
||||
const subtask = makeSubtask();
|
||||
subtask.board = () => undefined;
|
||||
subtask.boardId = undefined;
|
||||
expect(subtaskNavTarget(subtask)).to.equal(undefined);
|
||||
});
|
||||
});
|
||||
+8
-11
@@ -5,6 +5,7 @@ import { findWhere, where, uniqBy, groupBy, indexBy, debounce, once } from '/imp
|
||||
import Settings from '/models/settings';
|
||||
import Users from '/models/users';
|
||||
import { computeBoardBackground } from '/models/lib/boardBackground';
|
||||
import { buildCardAttachmentMeta } from '/models/lib/attachmentMeta';
|
||||
|
||||
export const Utils = {
|
||||
async setBackgroundImage(url) {
|
||||
@@ -595,18 +596,14 @@ export const Utils = {
|
||||
})
|
||||
);
|
||||
},
|
||||
// Shared by every card attachment upload path — the card Attachments popup,
|
||||
// the clipboard upload AND images uploaded inside card comments through the
|
||||
// rich text editor (client/components/main/editor.js). Keeping the meta
|
||||
// identical (same meta.cardId) is what makes comment attachments appear in
|
||||
// the card's Attachments list (#3843); the actual logic lives in
|
||||
// models/lib/attachmentMeta.js so it can be unit tested.
|
||||
getCommonAttachmentMetaFrom(card) {
|
||||
const meta = {};
|
||||
if (card.isLinkedCard()) {
|
||||
meta.boardId = ReactiveCache.getCard(card.linkedId).boardId;
|
||||
meta.cardId = card.linkedId;
|
||||
} else {
|
||||
meta.boardId = card.boardId;
|
||||
meta.swimlaneId = card.swimlaneId;
|
||||
meta.listId = card.listId;
|
||||
meta.cardId = card._id;
|
||||
}
|
||||
return meta;
|
||||
return buildCardAttachmentMeta(card, id => ReactiveCache.getCard(id));
|
||||
},
|
||||
// Collection helpers (replacing underscore.js)
|
||||
findWhere,
|
||||
|
||||
@@ -46,6 +46,14 @@ When calling a production Wekan server, ensure it is running via HTTPS and has a
|
||||
| `POST` | `/api/boards/:boardId/lists/:listId/cards` | [Add a card to a list, board, and swimlane.](Cards.md#add-card-to-list-board-swimlane) |
|
||||
| `PUT` | `/api/boards/:boardId/lists/:fromListId/cards/:cardId` | [Update a card.](Cards.md#update-a-card) |
|
||||
| `DELETE` | `/api/boards/:boardId/lists/:listId/cards/:cardId` | [Delete a card.](Cards.md#update-a-card) |
|
||||
### Rules (Board Automation / IFTTT)
|
||||
| HTTP Method | Url | Short Description |
|
||||
| :--- | :--- | :--- |
|
||||
| `GET` | `/api/boards/:boardId/rules` | [List all automation rules of a board.](Rules.md#list-rules) |
|
||||
| `GET` | `/api/boards/:boardId/rules/:ruleId` | [Get one rule with its trigger and action.](Rules.md#get-one-rule) |
|
||||
| `POST` | `/api/boards/:boardId/rules` | [Add an automation rule, e.g. add/remove a member when a card is moved to/from a list (#2674).](Rules.md#add-a-rule) |
|
||||
| `PUT` | `/api/boards/:boardId/rules/:ruleId` | [Edit a rule's title, trigger and/or action.](Rules.md#edit-a-rule) |
|
||||
| `DELETE` | `/api/boards/:boardId/rules/:ruleId` | [Remove a rule and its trigger and action.](Rules.md#delete-a-rule) |
|
||||
### Board Domain Sharing
|
||||
| HTTP Method | Url | Short Description |
|
||||
| :--- | :--- | :--- |
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
# Rules (Board Automation / IFTTT) REST API
|
||||
|
||||
Board automation rules ("IFTTT rules") link a **trigger** (an event on the
|
||||
board) to an **action** (what happens to the card/board). The REST API embeds
|
||||
the full trigger and action inline, so a rule is self-contained.
|
||||
|
||||
This API makes the workflow of
|
||||
[issue #2674](https://github.com/wekan/wekan/issues/2674) scriptable: add a
|
||||
user to a card when it is moved **to** a list, and remove the user again when
|
||||
the card is moved **away from** that list.
|
||||
|
||||
## Summary
|
||||
|
||||
| HTTP Method | Url | Short Description |
|
||||
| :--- | :--- | :--- |
|
||||
| `GET` | `/api/boards/:boardId/rules` | List all automation rules of a board |
|
||||
| `GET` | `/api/boards/:boardId/rules/:ruleId` | Get one rule (with its trigger and action) |
|
||||
| `POST` | `/api/boards/:boardId/rules` | Add an automation rule |
|
||||
| `PUT` | `/api/boards/:boardId/rules/:ruleId` | Edit a rule's title, trigger and/or action |
|
||||
| `DELETE` | `/api/boards/:boardId/rules/:ruleId` | Remove a rule (and its trigger and action) |
|
||||
|
||||
All endpoints require a `Bearer` token; write endpoints require board write
|
||||
access (BoardAdmin).
|
||||
|
||||
## Trigger matching and the `*` wildcard
|
||||
|
||||
The rule engine matches an incoming board activity against **every** matching
|
||||
field of the trigger's `activityType` (for example `moveCard` matches on
|
||||
`boardId`, `listName`, `oldListName`, `userId`, `swimlaneName`, `cardTitle`).
|
||||
A field set to `'*'` matches anything.
|
||||
|
||||
You only need to supply the fields you want to constrain: any matching field
|
||||
missing from the trigger you POST/PUT is stored as the `'*'` wildcard
|
||||
automatically. (Before this normalization existed, an API-created trigger
|
||||
that omitted a field such as `userId` could never match any activity, so the
|
||||
rule silently never fired — the bug reported in issue #2674.)
|
||||
|
||||
### Trigger `activityType` values
|
||||
|
||||
| `activityType` | fires when | matching fields |
|
||||
| :--- | :--- | :--- |
|
||||
| `createCard` | a card is created | `boardId`, `listName`, `userId`, `swimlaneName`, `cardTitle` |
|
||||
| `moveCard` | a card is moved to/from a list or swimlane | `boardId`, `listName` (destination), `oldListName` (source), `userId`, `swimlaneName`, `cardTitle` |
|
||||
| `archivedCard` / `restoredCard` | a card is archived / unarchived | `boardId`, `userId`, `cardTitle` |
|
||||
| `joinMember` / `unjoinMember` | a member is added to / removed from a card | `boardId`, `username`, `userId` |
|
||||
| `addChecklist` / `removeChecklist` / `completeChecklist` / `uncompleteChecklist` | checklist events | `boardId`, `checklistName`, `userId` |
|
||||
| `addedChecklistItem` / `removedChecklistItem` / `checkedItem` / `uncheckedItem` | checklist item events | `boardId`, `checklistItemName`, `userId` |
|
||||
| `addAttachment` / `deleteAttachment` | attachment events | `boardId`, `userId` |
|
||||
| `addedLabel` / `removedLabel` | label events | `boardId`, `labelId`, `userId` |
|
||||
| `scheduledTrigger` | time-based (due/aging/recurring); see `scheduleKind`, `days`, `atTime` | evaluated by the scheduler, not by activities |
|
||||
|
||||
For a card moved **to** a list, constrain `listName` (the destination list's
|
||||
title). For a card moved **away from** a list, constrain `oldListName` (the
|
||||
source list's title) and leave `listName` as `'*'`.
|
||||
|
||||
### Action `actionType` values
|
||||
|
||||
`moveCardToTop`, `moveCardToBottom`, `sendEmail`, `setDate`, `updateDate`,
|
||||
`removeDate`, `setDateRelative`, `archive`, `unarchive`, `setColor`,
|
||||
`addLabel`, `removeLabel`, `addMember`, `removeMember`, `checkAll`,
|
||||
`uncheckAll`, `checkItem`, `uncheckItem`, `addChecklist`, `removeChecklist`,
|
||||
`addChecklistWithItems`, `addSwimlane`, `createCard`, `linkCard`,
|
||||
`markCardComplete`, `markCardIncomplete`, `sortList`, `moveAllCardsInList`.
|
||||
|
||||
The member actions take a `username`:
|
||||
|
||||
* `{"actionType": "addMember", "username": "someuser"}` — add the user to the card
|
||||
* `{"actionType": "removeMember", "username": "someuser"}` — remove the user from the card
|
||||
* `{"actionType": "removeMember", "username": "*"}` — remove **all** members from the card
|
||||
|
||||
## List rules
|
||||
|
||||
```shell
|
||||
curl -H "Authorization: Bearer TOKEN" \
|
||||
-X GET \
|
||||
http://localhost:3000/api/boards/BOARDID/rules
|
||||
```
|
||||
|
||||
## Get one rule
|
||||
|
||||
```shell
|
||||
curl -H "Authorization: Bearer TOKEN" \
|
||||
-X GET \
|
||||
http://localhost:3000/api/boards/BOARDID/rules/RULEID
|
||||
```
|
||||
|
||||
Result example:
|
||||
|
||||
```json
|
||||
{
|
||||
"_id": "8gDW2AtwbpNbqSyEw",
|
||||
"title": "Remove member when moved away from Doing",
|
||||
"trigger": {
|
||||
"activityType": "moveCard",
|
||||
"listName": "*",
|
||||
"oldListName": "Doing",
|
||||
"swimlaneName": "*",
|
||||
"cardTitle": "*",
|
||||
"userId": "*"
|
||||
},
|
||||
"action": {
|
||||
"actionType": "removeMember",
|
||||
"username": "someuser"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Add a rule
|
||||
|
||||
```shell
|
||||
curl -H "Authorization: Bearer TOKEN" \
|
||||
-H "Content-type: application/json" \
|
||||
-X POST \
|
||||
http://localhost:3000/api/boards/BOARDID/rules \
|
||||
-d '{
|
||||
"title": "Add member when moved to Doing",
|
||||
"trigger": { "activityType": "moveCard", "listName": "Doing" },
|
||||
"action": { "actionType": "addMember", "username": "someuser" }
|
||||
}'
|
||||
```
|
||||
|
||||
### Full example: issue #2674 workflow
|
||||
|
||||
Add the user when a card is moved **to** the list "Doing", remove the user
|
||||
again when the card is moved **away from** "Doing":
|
||||
|
||||
```shell
|
||||
# Rule 1: card moved TO "Doing" -> add member
|
||||
curl -H "Authorization: Bearer TOKEN" -H "Content-type: application/json" -X POST \
|
||||
http://localhost:3000/api/boards/BOARDID/rules \
|
||||
-d '{ "title": "Add member on move to Doing",
|
||||
"trigger": { "activityType": "moveCard", "listName": "Doing" },
|
||||
"action": { "actionType": "addMember", "username": "someuser" } }'
|
||||
|
||||
# Rule 2: card moved AWAY FROM "Doing" -> remove member
|
||||
curl -H "Authorization: Bearer TOKEN" -H "Content-type: application/json" -X POST \
|
||||
http://localhost:3000/api/boards/BOARDID/rules \
|
||||
-d '{ "title": "Remove member on move from Doing",
|
||||
"trigger": { "activityType": "moveCard", "oldListName": "Doing" },
|
||||
"action": { "actionType": "removeMember", "username": "someuser" } }'
|
||||
```
|
||||
|
||||
The omitted trigger fields (`listName` in rule 2, `oldListName` in rule 1,
|
||||
plus `userId`, `swimlaneName`, `cardTitle`) are stored as `'*'` wildcards.
|
||||
|
||||
## Edit a rule
|
||||
|
||||
Any of `title`, `trigger` and `action` may be supplied; a supplied trigger or
|
||||
action document replaces the stored fields. When the supplied trigger includes
|
||||
an `activityType`, its missing matching fields are defaulted to `'*'` too.
|
||||
|
||||
```shell
|
||||
curl -H "Authorization: Bearer TOKEN" \
|
||||
-H "Content-type: application/json" \
|
||||
-X PUT \
|
||||
http://localhost:3000/api/boards/BOARDID/rules/RULEID \
|
||||
-d '{ "action": { "actionType": "removeMember", "username": "*" } }'
|
||||
```
|
||||
|
||||
## Delete a rule
|
||||
|
||||
Removes the rule together with its trigger and action documents.
|
||||
|
||||
```shell
|
||||
curl -H "Authorization: Bearer TOKEN" \
|
||||
-X DELETE \
|
||||
http://localhost:3000/api/boards/BOARDID/rules/RULEID
|
||||
```
|
||||
|
||||
## Python CLI (api.py)
|
||||
|
||||
The bundled `api.py` exposes the same capability:
|
||||
|
||||
```shell
|
||||
python3 api.py listrules BOARDID
|
||||
python3 api.py getrule BOARDID RULEID
|
||||
python3 api.py addrule BOARDID 'TITLE' 'TRIGGER_JSON' 'ACTION_JSON'
|
||||
python3 api.py editrule BOARDID RULEID 'PATCH_JSON'
|
||||
python3 api.py removerule BOARDID RULEID
|
||||
|
||||
# Issue #2674: remove a user from the card when it is moved away from a list
|
||||
python3 api.py addrule BOARDID 'Remove member on move from Doing' \
|
||||
'{"activityType":"moveCard","oldListName":"Doing"}' \
|
||||
'{"actionType":"removeMember","username":"someuser"}'
|
||||
```
|
||||
+6
-1
@@ -385,7 +385,12 @@ services:
|
||||
# LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS :
|
||||
# example : LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS=true
|
||||
- LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS=false
|
||||
# LDAP_ENCRYPTION : If using LDAPS
|
||||
# LDAP_ENCRYPTION : Connection encryption. Accepted values:
|
||||
# 'true' : LDAPS, TLS from the first byte (usually port 636)
|
||||
# 'starttls' : connect unencrypted (usually port 389), then upgrade with STARTTLS
|
||||
# 'false' : no encryption (default; strongly advised against)
|
||||
# Deprecated but still working: 'ssl' (same as 'true'), 'tls' (same as 'starttls').
|
||||
# Any other value logs a warning and means no encryption.
|
||||
# example : LDAP_ENCRYPTION=true
|
||||
- LDAP_ENCRYPTION=false
|
||||
# LDAP_CA_CERT : The certification for the LDAPS server
|
||||
|
||||
@@ -10,7 +10,7 @@ This is without container (without Docker or Snap).
|
||||
|
||||
Right click and download files 1-4:
|
||||
|
||||
1. [wekan-9.96-win64.zip](https://github.com/wekan/wekan/releases/download/v9.96/wekan-9.96-win64.zip) or newest available at https://github.com/wekan/wekan/releases/
|
||||
1. [wekan-9.97-win64.zip](https://github.com/wekan/wekan/releases/download/v9.97/wekan-9.97-win64.zip) or newest available at https://github.com/wekan/wekan/releases/
|
||||
|
||||
2. [node.exe](https://nodejs.org/dist/latest-v24.x/win-x64/node.exe)
|
||||
|
||||
@@ -22,7 +22,7 @@ Right click and download files 1-4:
|
||||
|
||||
6. Double click `mongodb-windows-x86_64-7.0.34-signed.msi` . In installer, uncheck downloading MongoDB compass.
|
||||
|
||||
7. Unzip `wekan-9.96-win64.zip` , inside it is directory `bundle`, to it copy other files:
|
||||
7. Unzip `wekan-9.97-win64.zip` , inside it is directory `bundle`, to it copy other files:
|
||||
|
||||
```
|
||||
bundle (directory)
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
// Pure helpers for the sidebar "Advanced filter" (no Meteor imports, so the
|
||||
// logic is unit-testable with plain Node — see tests/advancedFilterDate.test.cjs).
|
||||
//
|
||||
// #2989 "Date custom field, filter problem": filtering a date-type custom
|
||||
// field with `'Date de fin' == '06/04/2020'` never matched anything, for two
|
||||
// independent reasons fixed here:
|
||||
//
|
||||
// 1. Tokenizer: inside a '…'-quoted value every '/' toggled the tokenizer's
|
||||
// string mode (it is also the regex delimiter), so '06/04/2020' came out
|
||||
// flagged as a regex and the whole filter string failed to parse (the
|
||||
// filter silently fell back to the last valid selector).
|
||||
// 2. Selector: date custom-field values are stored as Date objects (the date
|
||||
// picker calls card.setCustomField(id, date)), but the '==' selector
|
||||
// compared them with {$in: ['06/04/2020', NaN]} — a string and a number
|
||||
// never equal a BSON date, so '==' matched nothing while '!=' matched
|
||||
// everything. parseAdvancedFilterDate()/buildDateValueSelector() translate
|
||||
// the typed date into a Date range selector instead.
|
||||
|
||||
// --- Tokenizer ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Split an advanced-filter string into commands.
|
||||
* Returns [{cmd, string, regex}, …]:
|
||||
* - '…' quotes a literal string (may contain spaces and slashes),
|
||||
* - /…/ delimits a regex (only when not inside a '…' string),
|
||||
* - '\' escapes the next character outside strings,
|
||||
* - space separates commands.
|
||||
*/
|
||||
export function tokenizeAdvancedFilter(filter) {
|
||||
const commands = [];
|
||||
let current = '';
|
||||
let string = false;
|
||||
let regex = false;
|
||||
let wasString = false;
|
||||
let ignore = false;
|
||||
for (let i = 0; i < filter.length; i++) {
|
||||
const char = filter.charAt(i);
|
||||
if (ignore) {
|
||||
ignore = false;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
// '/' starts/ends a regex — but inside a '…'-quoted string it is a plain
|
||||
// character (#2989: dates like '06/04/2020' must stay literal strings).
|
||||
if (char === '/' && (!string || regex)) {
|
||||
string = !string;
|
||||
if (string) regex = true;
|
||||
current += char;
|
||||
continue;
|
||||
}
|
||||
// eslint-disable-next-line quotes
|
||||
if (char === "'" && !regex) {
|
||||
string = !string;
|
||||
if (string) wasString = true;
|
||||
continue;
|
||||
}
|
||||
if (char === '\\' && !string) {
|
||||
ignore = true;
|
||||
continue;
|
||||
}
|
||||
if (char === ' ' && !string) {
|
||||
commands.push({
|
||||
cmd: current,
|
||||
string: wasString,
|
||||
regex,
|
||||
});
|
||||
wasString = false;
|
||||
regex = false;
|
||||
current = '';
|
||||
continue;
|
||||
}
|
||||
current += char;
|
||||
}
|
||||
if (current !== '') {
|
||||
commands.push({
|
||||
cmd: current,
|
||||
string: wasString,
|
||||
regex,
|
||||
});
|
||||
}
|
||||
return commands;
|
||||
}
|
||||
|
||||
// --- Date parsing ------------------------------------------------------------
|
||||
|
||||
// YYYY-MM-DD / YYYY/MM/DD / YYYY.MM.DD, optional " HH:mm[:ss]" (or T separator)
|
||||
const YMD_RE = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/;
|
||||
// DD/MM/YYYY or MM/DD/YYYY (separators -, / or .), optional time as above
|
||||
const DMY_RE = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/;
|
||||
|
||||
function buildRange(year, month, day, hour, minute, second) {
|
||||
// Validate by round-trip: new Date() rolls over out-of-range components
|
||||
// (e.g. 31 February becomes 2/3 March), which must be rejected.
|
||||
const hasTime = hour !== undefined;
|
||||
const hasSeconds = second !== undefined;
|
||||
const h = hasTime ? Number(hour) : 0;
|
||||
const min = hasTime ? Number(minute) : 0;
|
||||
const s = hasSeconds ? Number(second) : 0;
|
||||
const start = new Date(year, month - 1, day, h, min, s);
|
||||
if (
|
||||
start.getFullYear() !== year ||
|
||||
start.getMonth() !== month - 1 ||
|
||||
start.getDate() !== day ||
|
||||
start.getHours() !== h ||
|
||||
start.getMinutes() !== min ||
|
||||
start.getSeconds() !== s
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
let end;
|
||||
if (hasSeconds) {
|
||||
end = new Date(year, month - 1, day, h, min, s + 1);
|
||||
} else if (hasTime) {
|
||||
end = new Date(year, month - 1, day, h, min + 1);
|
||||
} else {
|
||||
end = new Date(year, month - 1, day + 1);
|
||||
}
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a date typed in the advanced filter into a {start, end} range
|
||||
* (half-open: start inclusive, end exclusive) in the local timezone.
|
||||
* The range spans the given day, minute or second depending on how much
|
||||
* precision the user typed. Returns null when the string is not a date.
|
||||
*
|
||||
* options.dayFirst resolves ambiguous "a/b/yyyy" input (both a and b <= 12):
|
||||
* true reads it day-first (DD/MM/YYYY, e.g. French locale), false month-first.
|
||||
* Unambiguous input (one component > 12) ignores the flag.
|
||||
*/
|
||||
export function parseAdvancedFilterDate(str, options = {}) {
|
||||
if (typeof str !== 'string') return null;
|
||||
const dayFirst = !!options.dayFirst;
|
||||
const trimmed = str.trim();
|
||||
let m = trimmed.match(YMD_RE);
|
||||
if (m) {
|
||||
return buildRange(
|
||||
Number(m[1]),
|
||||
Number(m[2]),
|
||||
Number(m[3]),
|
||||
m[4],
|
||||
m[5],
|
||||
m[6],
|
||||
);
|
||||
}
|
||||
m = trimmed.match(DMY_RE);
|
||||
if (m) {
|
||||
const a = Number(m[1]);
|
||||
const b = Number(m[2]);
|
||||
const year = Number(m[3]);
|
||||
let day;
|
||||
let month;
|
||||
if (a > 12 && b <= 12) {
|
||||
day = a;
|
||||
month = b;
|
||||
} else if (b > 12 && a <= 12) {
|
||||
day = b;
|
||||
month = a;
|
||||
} else if (dayFirst) {
|
||||
day = a;
|
||||
month = b;
|
||||
} else {
|
||||
month = a;
|
||||
day = b;
|
||||
}
|
||||
return buildRange(year, month, day, m[4], m[5], m[6]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Selector building -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build the Mongo operator document for 'customFields.value' comparing a
|
||||
* Date-typed custom field against the {start, end} range from
|
||||
* parseAdvancedFilterDate(). Returns null for unknown operators.
|
||||
*/
|
||||
export function buildDateValueSelector(op, range) {
|
||||
if (!range) return null;
|
||||
switch (op) {
|
||||
case '=':
|
||||
case '==':
|
||||
case '===':
|
||||
return { $gte: range.start, $lt: range.end };
|
||||
case '!=':
|
||||
case '!==':
|
||||
return { $not: { $gte: range.start, $lt: range.end } };
|
||||
case '>':
|
||||
case 'gt':
|
||||
case 'Gt':
|
||||
case 'GT':
|
||||
return { $gte: range.end };
|
||||
case '>=':
|
||||
case '>==':
|
||||
case 'gte':
|
||||
case 'Gte':
|
||||
case 'GTE':
|
||||
return { $gte: range.start };
|
||||
case '<':
|
||||
case 'lt':
|
||||
case 'Lt':
|
||||
case 'LT':
|
||||
return { $lt: range.start };
|
||||
case '<=':
|
||||
case '<==':
|
||||
case 'lte':
|
||||
case 'Lte':
|
||||
case 'LTE':
|
||||
return { $lt: range.end };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for auto-scrolling the board while a card is dragged near an
|
||||
// edge. Extracted so the decision logic is unit-testable in plain Node
|
||||
// without Meteor (same pattern as client/lib/cardDragGeometry.js and
|
||||
// imports/lib/advancedFilter.js). See tests/boardAutoScroll.test.cjs.
|
||||
//
|
||||
// #443 "Cannot automatically slide when moving item from list to list":
|
||||
// dragging a card towards a list that is outside the viewport does not
|
||||
// scroll the board, so the user has to drop the card on an intermediate
|
||||
// list and scroll manually.
|
||||
//
|
||||
// The card sortable's `sort` callback (client/components/lists/list.js) does
|
||||
// contain horizontal auto-scroll code, but it mutates
|
||||
// `$('.board-canvas')[0].scrollLeft`. Since the swimlane layout, the element
|
||||
// that actually overflows horizontally is the lane that holds the lists —
|
||||
// `.swimlane.js-lists` (`.swimlane { display: flex; overflow: auto }` in
|
||||
// client/components/swimlanes/swimlanes.css) — in BOTH board views
|
||||
// (swimlanes.jade renders `.swimlane.js-lists.js-swimlane` per swimlane and
|
||||
// `.swimlane.list-group.js-lists` in Lists mode). `.board-canvas` only
|
||||
// scrolls vertically (boardBody.css: `overflow-y: auto`), so its
|
||||
// scrollWidth === clientWidth: the old guard
|
||||
// `boardCanvas.scrollLeft < (scrollWidth - clientWidth)` compares 0 < 0 and
|
||||
// the right-scroll branch never fires, while the left-scroll branch
|
||||
// decrements a scrollLeft that is already 0. jQuery UI's own `scroll` option
|
||||
// cannot help either: sortable takes `this.placeholder.scrollParent()` ONCE
|
||||
// at drag start, which resolves to the list body (the vertical card
|
||||
// scroller), never the lane.
|
||||
//
|
||||
// These helpers compute WHAT to scroll (the lane under the pointer, found by
|
||||
// hit-testing lane rectangles) and BY HOW MUCH (an edge-proximity step,
|
||||
// clamped to the real scroll range). The caller applies the returned value:
|
||||
//
|
||||
// const lanes = document.querySelectorAll('.js-lists');
|
||||
// const i = findLaneUnderPointer([...lanes].map(l =>
|
||||
// l.getBoundingClientRect()), event.clientX, event.clientY);
|
||||
// if (i !== -1) {
|
||||
// const lane = lanes[i];
|
||||
// const rect = lane.getBoundingClientRect();
|
||||
// const next = computeEdgeScroll({
|
||||
// pointer: event.clientX,
|
||||
// lowEdge: rect.left,
|
||||
// highEdge: rect.right,
|
||||
// scrollPos: lane.scrollLeft,
|
||||
// scrollSize: lane.scrollWidth,
|
||||
// clientSize: lane.clientWidth,
|
||||
// });
|
||||
// if (next !== null) lane.scrollLeft = next;
|
||||
// }
|
||||
|
||||
// How close (px) to an edge the pointer must be before scrolling starts.
|
||||
// The old code used 10px from the viewport edge, which was nearly impossible
|
||||
// to hit while holding a card; 40px matches common kanban implementations.
|
||||
const EDGE_SIZE = 40;
|
||||
|
||||
// How far (px) to scroll per sort/mousemove event (same speed as the old
|
||||
// board-canvas code and the sortable `scrollSpeed: 10..15` range).
|
||||
const SCROLL_STEP = 15;
|
||||
|
||||
// Compute the next scroll position along ONE axis, or null when nothing
|
||||
// should change. Axis-agnostic: pass clientX/left/right/scrollLeft/
|
||||
// scrollWidth/clientWidth for horizontal, clientY/top/bottom/scrollTop/
|
||||
// scrollHeight/clientHeight for vertical.
|
||||
//
|
||||
// pointer current pointer coordinate (viewport space, e.g. clientX)
|
||||
// lowEdge scroller's near edge (rect.left / rect.top)
|
||||
// highEdge scroller's far edge (rect.right / rect.bottom)
|
||||
// scrollPos scroller's current scrollLeft / scrollTop
|
||||
// scrollSize scroller's scrollWidth / scrollHeight
|
||||
// clientSize scroller's clientWidth / clientHeight
|
||||
//
|
||||
// Returns the clamped new scroll position, or null when the pointer is not
|
||||
// in an edge zone, the element cannot scroll further in that direction, or
|
||||
// it does not overflow at all (this is exactly why the old code was a no-op:
|
||||
// for .board-canvas, scrollSize - clientSize is 0 horizontally).
|
||||
function computeEdgeScroll({
|
||||
pointer,
|
||||
lowEdge,
|
||||
highEdge,
|
||||
scrollPos,
|
||||
scrollSize,
|
||||
clientSize,
|
||||
edgeSize = EDGE_SIZE,
|
||||
step = SCROLL_STEP,
|
||||
}) {
|
||||
const maxScroll = Math.max(0, scrollSize - clientSize);
|
||||
if (maxScroll === 0) {
|
||||
// No overflow on this axis: nothing to scroll.
|
||||
return null;
|
||||
}
|
||||
const distLow = pointer - lowEdge;
|
||||
const distHigh = highEdge - pointer;
|
||||
const inLow = distLow < edgeSize;
|
||||
const inHigh = distHigh < edgeSize;
|
||||
// A negative distance means the pointer was dragged slightly PAST the
|
||||
// edge (the sortable helper can hover outside the lane box); that still
|
||||
// counts as being in that edge zone. When the element is so small that
|
||||
// both zones overlap, the nearer edge wins.
|
||||
if (inLow && (!inHigh || distLow <= distHigh)) {
|
||||
const next = Math.max(0, scrollPos - step);
|
||||
return next < scrollPos ? next : null;
|
||||
}
|
||||
if (inHigh) {
|
||||
const next = Math.min(maxScroll, scrollPos + step);
|
||||
return next > scrollPos ? next : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Given the bounding rectangles ({left, right, top, bottom}) of every
|
||||
// horizontal lane on the board (each `.js-lists` element — one per swimlane
|
||||
// in Swimlanes view, a single one in Lists view), return the index of the
|
||||
// lane the pointer is currently over, or -1. The drag may hover a DIFFERENT
|
||||
// swimlane than the one the card came from; the lane under the pointer is
|
||||
// the one the user is aiming at, so that is the one to scroll.
|
||||
function findLaneUnderPointer(laneRects, pointerX, pointerY) {
|
||||
if (!laneRects) return -1;
|
||||
for (let i = 0; i < laneRects.length; i += 1) {
|
||||
const r = laneRects[i];
|
||||
if (
|
||||
r &&
|
||||
pointerX >= r.left &&
|
||||
pointerX <= r.right &&
|
||||
pointerY >= r.top &&
|
||||
pointerY <= r.bottom
|
||||
) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
EDGE_SIZE,
|
||||
SCROLL_STEP,
|
||||
computeEdgeScroll,
|
||||
findLaneUnderPointer,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
// Time-default resolution for the card date pickers (due/start/end/received,
|
||||
// vote and poker end, date custom fields). Meteor-free so it can be unit
|
||||
// tested with plain Node (see tests/datePickerDefaultTime.test.cjs).
|
||||
//
|
||||
// Issue #1502 ("Add Feature: Set default time for time field"): each date
|
||||
// popup configures an intended default time — 17:00 for due dates, the
|
||||
// current time for received/start/end — via setupDatePicker({ defaultTime }).
|
||||
// The old rendered logic only applied that default inside an
|
||||
// `if (isValidDate(existing date))` guard, i.e. only when the card ALREADY
|
||||
// had a date, in which case the input was already filled with that date's
|
||||
// own time. For a card without a date (the only case a default is for) the
|
||||
// time input stayed empty and submitting stored a hard-coded 12:00.
|
||||
//
|
||||
// These helpers make the behavior explicit:
|
||||
// - a card date that exists always shows (and keeps) its own time;
|
||||
// - a missing date pre-fills the input with the configured default;
|
||||
// - an empty time at submit falls back to the configured default, then 12:00.
|
||||
|
||||
// Whether `date` is a real, valid Date instance.
|
||||
function isValidDate(date) {
|
||||
return date instanceof Date && !isNaN(date);
|
||||
}
|
||||
|
||||
// Format a Date's local time as 'HH:mm' (24-hour, zero-padded) — the exact
|
||||
// value format of a native <input type="time">, in every locale.
|
||||
function formatTime(date) {
|
||||
if (!isValidDate(date)) return '';
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
return `${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
// Parse a configured default-time string (e.g. '1970-01-01 17:00:00' or a
|
||||
// full 'YYYY-MM-DD HH:mm' timestamp) into 'HH:mm', or '' when absent/invalid.
|
||||
function defaultTimeValue(defaultTime) {
|
||||
if (!defaultTime) return '';
|
||||
const d = new Date(defaultTime);
|
||||
return formatTime(d);
|
||||
}
|
||||
|
||||
// The 'HH:mm' value the picker's time input should initially show:
|
||||
// - `date` valid (card already has this date) -> that date's own time,
|
||||
// never the default;
|
||||
// - otherwise -> the configured default time;
|
||||
// - no (or unparseable) default -> '' (leave the input empty).
|
||||
function initialTimeValue(date, defaultTime) {
|
||||
if (isValidDate(date)) return formatTime(date);
|
||||
return defaultTimeValue(defaultTime);
|
||||
}
|
||||
|
||||
// The 'HH:mm' to store when the form is submitted with an empty time field:
|
||||
// the configured default when one parses, else the legacy 12:00.
|
||||
function fallbackSubmitTime(defaultTime) {
|
||||
return defaultTimeValue(defaultTime) || '12:00';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isValidDate,
|
||||
formatTime,
|
||||
initialTimeValue,
|
||||
fallbackSubmitTime,
|
||||
};
|
||||
@@ -1180,11 +1180,33 @@ const ReactiveCache = {
|
||||
}
|
||||
},
|
||||
getCard(idOrFirstObjectSelector = null, options = {}, noCache = false) {
|
||||
if (Meteor.isServer || noCache === true) {
|
||||
if (Meteor.isServer) {
|
||||
return ReactiveCacheServer.getCard(idOrFirstObjectSelector, options);
|
||||
} else {
|
||||
return ReactiveCacheClient.getCard(idOrFirstObjectSelector, options);
|
||||
}
|
||||
if (noCache === true) {
|
||||
// #2494 (cards sent to another board appear/disappear when reordering):
|
||||
// on the CLIENT, `noCache` must bypass the DataCache but stay
|
||||
// SYNCHRONOUS like every other client-side ReactiveCache getter.
|
||||
// Routing it to the async ReactiveCacheServer.getCard returned a
|
||||
// Promise; synchronous callers such as the multi-select "Move/Copy
|
||||
// selection" max-sort lookup (client/components/sidebar/
|
||||
// sidebarFilters.js getMaxSortForList) read `.sort` off that Promise,
|
||||
// got `undefined`, and wrote `sort: NaN` to every card moved to the
|
||||
// target list — the cards then landed at unpredictable positions,
|
||||
// hid behind each other and could not be reordered. Minimongo's
|
||||
// findOne is synchronous on the client, and callers that `await`
|
||||
// this call (models/cards.js getSort, models/boards.js
|
||||
// getNextCardNumber) work unchanged when given a plain document.
|
||||
if (
|
||||
idOrFirstObjectSelector === null ||
|
||||
idOrFirstObjectSelector === undefined ||
|
||||
idOrFirstObjectSelector === ''
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return Cards.findOne(idOrFirstObjectSelector, options);
|
||||
}
|
||||
return ReactiveCacheClient.getCard(idOrFirstObjectSelector, options);
|
||||
},
|
||||
getCards(selector = {}, options = {}, getQuery = false) {
|
||||
if (Meteor.isServer) {
|
||||
|
||||
+8
-39
@@ -1299,51 +1299,20 @@ Cards.helpers({
|
||||
|
||||
// customFields with definitions
|
||||
customFieldsWD() {
|
||||
// get all definitions
|
||||
// get all definitions attached to this card's CURRENT board
|
||||
const definitions = ReactiveCache.getCustomFields({
|
||||
boardIds: { $in: [this.boardId] },
|
||||
});
|
||||
if (!definitions) {
|
||||
return {};
|
||||
}
|
||||
// match right definition to each field
|
||||
if (!this.customFields) return [];
|
||||
const ret = this.customFields.map(customField => {
|
||||
const definition = definitions.find(definition => {
|
||||
return definition._id === customField._id;
|
||||
});
|
||||
if (!definition) {
|
||||
return {};
|
||||
}
|
||||
//search for "True Value" which is for DropDowns other then the Value (which is the id)
|
||||
let trueValue = customField.value;
|
||||
if (
|
||||
definition.settings.dropdownItems &&
|
||||
definition.settings.dropdownItems.length > 0
|
||||
) {
|
||||
for (let i = 0; i < definition.settings.dropdownItems.length; i++) {
|
||||
if (definition.settings.dropdownItems[i]._id === customField.value) {
|
||||
trueValue = definition.settings.dropdownItems[i].name;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
_id: customField._id,
|
||||
value: customField.value,
|
||||
trueValue,
|
||||
definition,
|
||||
};
|
||||
});
|
||||
// at linked cards custom fields definition is not found
|
||||
ret.sort(
|
||||
(a, b) =>
|
||||
a.definition !== undefined &&
|
||||
b.definition !== undefined &&
|
||||
a.definition.name !== undefined &&
|
||||
b.definition.name !== undefined &&
|
||||
a.definition.name.localeCompare(b.definition.name),
|
||||
);
|
||||
return ret;
|
||||
// #3748: entries whose definition is not attached to THIS board are
|
||||
// skipped — on a cross-board linked card the customFields snapshot copied
|
||||
// by Cards.link() references the ORIGINAL board's definitions, and the old
|
||||
// `{}` placeholders rendered phantom empty rows in the card details and
|
||||
// threw in the cardCustomField getTemplate helper.
|
||||
const { buildCustomFieldsWD } = require('./lib/customFieldsWD');
|
||||
return buildCustomFieldsWD(this.customFields, definitions);
|
||||
},
|
||||
|
||||
colorClass() {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helper for the POST /users/logout REST endpoint (issue #1437: "Old
|
||||
// tokens are not replaced or set invalid"). Extracted so the request
|
||||
// validation / Mongo-update planning is unit-testable in plain Node without
|
||||
// Meteor (mirrors models/lib/restLabel.js and models/lib/boardSortReorder.js).
|
||||
//
|
||||
// #1437: the REST API has always had POST /users/login (which mints a new
|
||||
// resume login token on every call) but never a logout, so tokens acquired
|
||||
// via the API could not be invalidated — they simply piled up in
|
||||
// services.resume.loginTokens until their ~90 day expiry ("I have probably
|
||||
// created 50+ valid tokens recently"). A leaked token therefore stayed valid
|
||||
// with no server-side way to revoke it short of editing the database.
|
||||
//
|
||||
// buildLogoutPlan validates the (already-authenticated) request and yields a
|
||||
// definite outcome for the route handler:
|
||||
// - { ok: true, all, selector, modifier } -> caller runs
|
||||
// Meteor.users.updateAsync(selector, modifier) and reports success.
|
||||
// - { ok: false, status, error, reason } -> caller sends that JSON error.
|
||||
//
|
||||
// Two modes:
|
||||
// - default: revoke ONLY the token presented in the Authorization header
|
||||
// ($pull of its hashed form) — other sessions (e.g. the browser GUI)
|
||||
// stay logged in;
|
||||
// - { "all": true } in the request body: revoke EVERY resume token of the
|
||||
// user ("logout everywhere"), cleaning up any accumulated/leaked tokens.
|
||||
|
||||
// Truthy spellings accepted for the `all` flag. Body parsing may deliver a
|
||||
// boolean (JSON body) or a string (urlencoded body), so accept both.
|
||||
function wantsAllSessions(rawAll) {
|
||||
if (rawAll === true) return true;
|
||||
if (typeof rawAll === 'string') {
|
||||
const s = rawAll.trim().toLowerCase();
|
||||
return s === 'true' || s === '1' || s === 'yes';
|
||||
}
|
||||
if (rawAll === 1) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function buildLogoutPlan(request) {
|
||||
const { userId, hashedToken, all } =
|
||||
request && typeof request === 'object' ? request : {};
|
||||
if (typeof userId !== 'string' || userId.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'unauthorized',
|
||||
reason:
|
||||
'You must be logged in to log out. Send your token as an Authorization: Bearer header.',
|
||||
};
|
||||
}
|
||||
|
||||
const everywhere = wantsAllSessions(all);
|
||||
|
||||
if (everywhere) {
|
||||
return {
|
||||
ok: true,
|
||||
all: true,
|
||||
selector: { _id: userId },
|
||||
modifier: { $set: { 'services.resume.loginTokens': [] } },
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof hashedToken !== 'string' || hashedToken.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'unauthorized',
|
||||
reason: 'No login token found on the request.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
all: false,
|
||||
selector: { _id: userId },
|
||||
modifier: { $pull: { 'services.resume.loginTokens': { hashedToken } } },
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildLogoutPlan,
|
||||
wantsAllSessions,
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helper: build the `meta` object stored on every card attachment
|
||||
// (Attachments FilesCollection, ostrio:files). Kept side-effect free so it can
|
||||
// be unit tested without a database or the Meteor client environment.
|
||||
//
|
||||
// This single builder is shared by ALL card attachment upload paths:
|
||||
// - the card Attachments popup and clipboard upload
|
||||
// (client/components/cards/attachments.js), and
|
||||
// - images uploaded inside card COMMENTS / the card description through the
|
||||
// rich text editor (client/components/main/editor.js, summernote
|
||||
// onImageUpload), via Utils.getCommonAttachmentMetaFrom().
|
||||
//
|
||||
// Because comment uploads carry the exact same `meta.cardId` as direct card
|
||||
// uploads, they are listed in the card's Attachments section, whose queries
|
||||
// all key on `meta.cardId` (Template.attachmentGallery in
|
||||
// client/components/cards/attachments.js and Cards.helpers.attachments in
|
||||
// models/cards.js) with no `meta.source` filtering. That is the behaviour
|
||||
// requested in https://github.com/wekan/wekan/issues/3843 — an attachment
|
||||
// added in a card comment must stay linked to (and visible in) the card's
|
||||
// global attachment list.
|
||||
//
|
||||
// For a linked card the attachment is attached to the REAL card (linkedId),
|
||||
// so it shows up on the original card and on every linked copy.
|
||||
//
|
||||
// `getCardById` resolves the real card of a linked card (the client passes
|
||||
// ReactiveCache.getCard). A missing/null card yields an empty meta rather
|
||||
// than throwing, so a failed lookup cannot crash an upload handler.
|
||||
function buildCardAttachmentMeta(card, getCardById) {
|
||||
const meta = {};
|
||||
if (!card) {
|
||||
return meta;
|
||||
}
|
||||
if (typeof card.isLinkedCard === 'function' && card.isLinkedCard()) {
|
||||
const realCard =
|
||||
typeof getCardById === 'function' ? getCardById(card.linkedId) : null;
|
||||
if (realCard) {
|
||||
meta.boardId = realCard.boardId;
|
||||
}
|
||||
meta.cardId = card.linkedId;
|
||||
} else {
|
||||
meta.boardId = card.boardId;
|
||||
meta.swimlaneId = card.swimlaneId;
|
||||
meta.listId = card.listId;
|
||||
meta.cardId = card._id;
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
module.exports = { buildCardAttachmentMeta };
|
||||
@@ -0,0 +1,34 @@
|
||||
// Pure, dependency-free storage path computation (no Meteor imports) so it can
|
||||
// be unit tested directly with plain Node. Used by the attachment storage
|
||||
// settings (Admin Panel > Attachments) and kept in sync with the path logic in
|
||||
// models/attachments.js, models/avatars.js and server/initializeDirs.js.
|
||||
//
|
||||
// #6473: the Admin Panel used to compute these paths ON THE CLIENT from
|
||||
// process.env.WRITABLE_PATH, which never exists in a browser, so it always
|
||||
// showed "/data" — a path that does not exist on a Snap install
|
||||
// (WRITABLE_PATH=$SNAP_COMMON/files there). The real paths are:
|
||||
// - Docker (WRITABLE_PATH=/data): /data/files/{attachments,avatars}
|
||||
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/{attachments,avatars}
|
||||
// - Dev (WRITABLE_PATH unset): <cwd>/files/{attachments,avatars}
|
||||
//
|
||||
// Snap already appends '/files' to WRITABLE_PATH, so that case is detected and
|
||||
// '/files' is not appended twice.
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* Compute the real attachment/avatar storage paths for a given base path.
|
||||
* @param {string} [basePath] WRITABLE_PATH (falls back to process.cwd())
|
||||
* @return {{writablePath: string, attachments: string, avatars: string}}
|
||||
*/
|
||||
function computeStoragePaths(basePath) {
|
||||
const base = basePath || process.cwd();
|
||||
const endsWithFiles = base.endsWith('/files') || base.endsWith('\\files');
|
||||
const root = endsWithFiles ? base : path.join(base, 'files');
|
||||
return {
|
||||
writablePath: base,
|
||||
attachments: path.join(root, 'attachments'),
|
||||
avatars: path.join(root, 'avatars'),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { computeStoragePaths };
|
||||
@@ -0,0 +1,75 @@
|
||||
'use strict';
|
||||
|
||||
// Pure decision helpers for board invitation accept / decline (quit) flows.
|
||||
// Extracted so the logic is unit-testable in plain Node without Meteor
|
||||
// (mirrors models/lib/boardSortReorder.js).
|
||||
//
|
||||
// #4730 ("Bugs in adding and removing users"):
|
||||
//
|
||||
// Case 2 of the issue — "User A declines the invitation but still sees board 1
|
||||
// in the personal overview" — was caused by the decline handler on the All
|
||||
// Boards page (client/components/boards/boardsList.js), which calls
|
||||
// `quitBoard` (deactivates the member entry) and then `acceptInvite` to clear
|
||||
// the invitation. The old server-side `acceptInvite` unconditionally set
|
||||
// `members.$.isActive = true`, immediately RE-ACTIVATING the membership that
|
||||
// `quitBoard` had just deactivated — so the declined board stayed in the
|
||||
// user's personal overview as an active membership.
|
||||
//
|
||||
// The same unconditional re-activation also let any user with a deactivated
|
||||
// member entry (i.e. someone an admin had removed from the board) re-add
|
||||
// themselves simply by calling `Meteor.call('acceptInvite', boardId)` — the
|
||||
// "adding and removing user A again doesn't fix it" half of Case 1.
|
||||
//
|
||||
// Fix: activating a membership through acceptInvite is only legitimate while
|
||||
// the user actually holds an invitation (profile.invitedBoards contains the
|
||||
// board id). Declining is made robust by having quitBoard clear the pending
|
||||
// invitation itself, so the follow-up acceptInvite call finds no invitation
|
||||
// and becomes a no-op. quitBoard also succeeds (instead of throwing
|
||||
// error-board-notAMember) for a user who holds a stale invitation without a
|
||||
// member entry — e.g. after an admin removed them — so a stuck invited board
|
||||
// can always be removed from the personal overview.
|
||||
|
||||
// Whether the given user profile holds a pending invitation to boardId.
|
||||
function isInvitedToBoard(profile, boardId) {
|
||||
if (!boardId) return false;
|
||||
const invitedBoards = (profile && profile.invitedBoards) || [];
|
||||
return Array.isArray(invitedBoards) && invitedBoards.includes(boardId);
|
||||
}
|
||||
|
||||
// Decide what `quitBoard` (leave board / decline invitation) must do.
|
||||
// - A member quits: deactivate the member entry, and clear any pending
|
||||
// invitation so a later acceptInvite cannot resurrect the membership.
|
||||
// - A non-member with a pending (stale) invitation: just clear the invitation
|
||||
// and report success, so the board disappears from the personal overview.
|
||||
// - Neither member nor invited: nothing to quit — error.
|
||||
function planQuitBoard({ isMember, isInvited }) {
|
||||
if (!isMember && !isInvited) {
|
||||
return {
|
||||
ok: false,
|
||||
removeMember: false,
|
||||
pullInvite: false,
|
||||
error: 'error-board-notAMember',
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
removeMember: !!isMember,
|
||||
pullInvite: !!isInvited,
|
||||
};
|
||||
}
|
||||
|
||||
// Decide what `acceptInvite` must do. Only a user actually holding an
|
||||
// invitation may (re)activate their member entry; for anyone else the call is
|
||||
// a no-op (#4730: this is what used to re-activate declined/removed members).
|
||||
function planAcceptInvite({ isInvited }) {
|
||||
if (!isInvited) {
|
||||
return { ok: false, pullInvite: false, activateMember: false };
|
||||
}
|
||||
return { ok: true, pullInvite: true, activateMember: true };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isInvitedToBoard,
|
||||
planQuitBoard,
|
||||
planAcceptInvite,
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
// Pure, Meteor-free helpers that scope the Filter / MultiSelection card
|
||||
// selectors to a single board. Extracted so they are unit-testable in plain
|
||||
// Node (mirrors models/lib/calendarFilter.js and models/lib/swimlaneFilter.js).
|
||||
//
|
||||
// #2306 ("filter to selection"): the filter sidebar's "To selection" button
|
||||
// queried the client card cache with ONLY the Filter's selector — no boardId —
|
||||
// so it swept up matching cards from every board present in Minimongo (cards
|
||||
// from a board being navigated away from, linked-board subscriptions, the
|
||||
// notifications drawer, popup card data, ...). A later bulk action (archive,
|
||||
// move, label, ...) on the selection then silently mutated cards on other
|
||||
// boards. These helpers AND a `boardId` clause into the relevant selectors so
|
||||
// both the selection query and every bulk action stay contained to the board
|
||||
// the user is looking at.
|
||||
|
||||
// Scope a Filter selector (the object produced by Filter._getMongoSelector())
|
||||
// to one board. Without a boardId (e.g. on a non-board page) the selector is
|
||||
// returned unchanged. The board clause is combined via `$and` so it can never
|
||||
// collide with the Filter's own top-level `$or`.
|
||||
function boardScopedFilterSelector(filterSelector, boardId) {
|
||||
const base =
|
||||
filterSelector && typeof filterSelector === 'object' ? filterSelector : {};
|
||||
if (!boardId) return base;
|
||||
return { $and: [base, { boardId }] };
|
||||
}
|
||||
|
||||
// Selector for the cards of a multi-selection, scoped to one board. Bulk
|
||||
// actions iterate the cards this selector matches, so even if a stale
|
||||
// selection still holds ids from a previously visited board (the selection is
|
||||
// not always reset on every navigation path), those foreign cards are never
|
||||
// touched.
|
||||
function boardScopedSelectionSelector(selectedCardIds, boardId) {
|
||||
const selector = {
|
||||
_id: { $in: Array.isArray(selectedCardIds) ? selectedCardIds : [] },
|
||||
};
|
||||
if (boardId) selector.boardId = boardId;
|
||||
return selector;
|
||||
}
|
||||
|
||||
// Keep only the card ids that belong to `boardId`. `getCard` is a lookup
|
||||
// (id -> card doc or undefined/null). Ids whose card cannot be found or has no
|
||||
// boardId are kept (they cannot be positively identified as foreign, and a
|
||||
// card missing from the cache cannot be acted on anyway); ids whose card
|
||||
// verifiably lives on ANOTHER board are dropped. Without a boardId or lookup
|
||||
// function the input is returned unchanged.
|
||||
function cardIdsOnBoard(cardIds, boardId, getCard) {
|
||||
if (!Array.isArray(cardIds)) return cardIds;
|
||||
if (!boardId || typeof getCard !== 'function') return cardIds;
|
||||
return cardIds.filter(cardId => {
|
||||
const card = getCard(cardId);
|
||||
return !card || !card.boardId || card.boardId === boardId;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
boardScopedFilterSelector,
|
||||
boardScopedSelectionSelector,
|
||||
cardIdsOnBoard,
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for the All Boards page board tiles: the per-list card-count
|
||||
// line ("To Do: 3 Doing: 1 ...") and the board-member avatar row shown on
|
||||
// each board tile. Extracted so the decision logic is unit-testable in plain
|
||||
// Node without Meteor (mirrors models/lib/boardSortReorder.js).
|
||||
//
|
||||
// Background (#5174 screenshots / #4825 / #4214):
|
||||
// - The original client helpers computed the counts from reactive
|
||||
// ReactiveCache.getLists()/getCards() cursors inside the tile helpers,
|
||||
// which made the All Boards icons re-render in a loop ("icons random
|
||||
// dance", #4214). They were stubbed out to `return []`, so NO tile ever
|
||||
// showed its card counts or member avatars again, regardless of the
|
||||
// Admin Panel settings (hideCardCounterList / hideBoardMemberList) or the
|
||||
// per-board flags.
|
||||
// - Before the stubbing, tiles rendered inconsistently (#4825: "Show card
|
||||
// count per list doesn't deactivate", members never shown): the per-board
|
||||
// flags (allowsCardCounterList / allowsBoardMemberList, opt-in, default
|
||||
// false) were evaluated loosely and boards created before the feature
|
||||
// (#4691) have no field at all.
|
||||
//
|
||||
// The fix: a Meteor method (getAllBoardsTileData, server/publications/
|
||||
// boards.js) computes everything ONCE server-side — list titles + card counts
|
||||
// via a single grouped query, member ids from the board doc — and the client
|
||||
// stores the result in a ReactiveVar it sets exactly once (no reactive
|
||||
// cursors), so #4214 cannot return. These helpers are the pure core:
|
||||
//
|
||||
// - showsCardCounterList / showsBoardMemberList: the per-board flags are
|
||||
// honored STRICTLY (=== true). Disabled or missing flag -> hidden, for
|
||||
// every board, deterministically (fixes both directions of #4825).
|
||||
// - buildBoardTileData: folds boards + lists + card counts into the map the
|
||||
// tiles render from, already gated by those flags so a disabled board
|
||||
// never even carries the data.
|
||||
|
||||
// Whether this board opted in to showing the per-list card counter line on
|
||||
// its All Boards tile. The schema default is false (opt-in via the board
|
||||
// sidebar "Show card count per list" checkbox); boards created before the
|
||||
// feature existed have no field, which must mean "off" — not "sometimes on"
|
||||
// (#4825).
|
||||
function showsCardCounterList(board) {
|
||||
return !!(board && board.allowsCardCounterList === true);
|
||||
}
|
||||
|
||||
// Whether this board opted in to showing the member avatar row on its tile
|
||||
// ("Show Board members avatars" checkbox). Same strict semantics.
|
||||
function showsBoardMemberList(board) {
|
||||
return !!(board && board.allowsBoardMemberList === true);
|
||||
}
|
||||
|
||||
// One entry of the tile's card-counter line, e.g. "To Do: 3".
|
||||
function formatListCount(title, count) {
|
||||
const n = typeof count === 'number' && count > 0 ? count : 0;
|
||||
return `${title || ''}: ${n}`;
|
||||
}
|
||||
|
||||
// Fold card docs (only their listId is needed) into { listId: count }. Used
|
||||
// by the server method as the portable alternative to a $group aggregation.
|
||||
function countCardsByListId(cards) {
|
||||
const counts = {};
|
||||
(cards || []).forEach((card) => {
|
||||
if (card && card.listId) {
|
||||
counts[card.listId] = (counts[card.listId] || 0) + 1;
|
||||
}
|
||||
});
|
||||
return counts;
|
||||
}
|
||||
|
||||
// Build the per-board tile data map:
|
||||
// { [boardId]: { showLists, showMembers, lists: ['Title: N', ...],
|
||||
// memberIds: ['userId', ...] } }
|
||||
//
|
||||
// - boards: board docs with _id, members, allowsCardCounterList,
|
||||
// allowsBoardMemberList.
|
||||
// - lists: list docs with _id, boardId, title, sort (non-archived lists of
|
||||
// the boards that show counters). Rendered in board order (sort asc, title
|
||||
// as tiebreaker), like the lists on the board itself.
|
||||
// - cardCountByListId: { listId: count } for non-archived cards.
|
||||
//
|
||||
// Boards whose flag is off (or missing) get empty arrays, so the tile shows
|
||||
// nothing for them even if a caller forgets to check the show* flags.
|
||||
function buildBoardTileData(boards, lists, cardCountByListId) {
|
||||
const counts = cardCountByListId || {};
|
||||
const tiles = {};
|
||||
(boards || []).forEach((board) => {
|
||||
if (!board || !board._id) return;
|
||||
const showMembers = showsBoardMemberList(board);
|
||||
tiles[board._id] = {
|
||||
showLists: showsCardCounterList(board),
|
||||
showMembers,
|
||||
lists: [],
|
||||
memberIds: showMembers
|
||||
? (board.members || [])
|
||||
.filter((m) => m && m.userId && m.isActive !== false)
|
||||
.map((m) => m.userId)
|
||||
: [],
|
||||
};
|
||||
});
|
||||
const orderedLists = (lists || []).slice().sort((a, b) => {
|
||||
const sa = a && typeof a.sort === 'number' ? a.sort : 0;
|
||||
const sb = b && typeof b.sort === 'number' ? b.sort : 0;
|
||||
if (sa !== sb) return sa - sb;
|
||||
return String((a && a.title) || '').localeCompare(String((b && b.title) || ''));
|
||||
});
|
||||
orderedLists.forEach((list) => {
|
||||
if (!list || !list.boardId || !list._id) return;
|
||||
const tile = tiles[list.boardId];
|
||||
if (!tile || !tile.showLists) return;
|
||||
tile.lists.push(formatListCount(list.title, counts[list._id]));
|
||||
});
|
||||
return tiles;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
showsCardCounterList,
|
||||
showsBoardMemberList,
|
||||
formatListCount,
|
||||
countCardsByListId,
|
||||
buildBoardTileData,
|
||||
};
|
||||
@@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for repairing duplicate/inverted card `sort` values when a card
|
||||
// is drag-dropped between two neighbours. Extracted so the decision logic is
|
||||
// unit-testable in plain Node without Meteor (mirrors models/lib/boardSortReorder.js).
|
||||
//
|
||||
// #3826 (cannot reorder cards in a list full of subtask cards): every card
|
||||
// created through the "add subtask" flow used to be inserted with a constant
|
||||
// `sort: -1`, so a list populated by subtasks contains ONLY ties. Dropping a
|
||||
// card between two cards whose sorts are equal is unsolvable for the
|
||||
// drag-index math (client/lib/utils.js calculateIndexData): no number lies
|
||||
// strictly between -1 and -1, so it returned base === -1 with increment 0.
|
||||
// The dropped card's sort was already -1, Card.move()'s no-op guard
|
||||
// (models/lib/cardMoveModifier.js) discarded the write, and the card snapped
|
||||
// back to its old place. Worse, a multi-selection drop wrote the SAME sort to
|
||||
// every selected card (increment 0), permanently destroying their relative
|
||||
// order — the data-loss noted in triage.
|
||||
//
|
||||
// The wiring lives in client/components/lists/list.js (sortable `stop`
|
||||
// handler); the pieces below are the decisions worth testing in isolation:
|
||||
// 1. whether the drop landed in a "degenerate" gap that needs repair,
|
||||
// 2. the minimal set of sort rewrites that makes the visible order strictly
|
||||
// increasing, and
|
||||
// 3. the drop index (base + increment) computed from the repaired
|
||||
// neighbours, guaranteed to fall strictly between them and to give every
|
||||
// card of a multi-selection a distinct sort.
|
||||
|
||||
// A drop between two neighbours is degenerate when both neighbours exist and
|
||||
// their sorts do not strictly increase (ties from constant-sort inserts,
|
||||
// legacy inverted data, or non-numeric garbage). Drops at the very top or
|
||||
// bottom of a list (a single neighbour) always have room and never need
|
||||
// repair.
|
||||
function isDegenerateSortGap(prevSort, nextSort) {
|
||||
if (prevSort === undefined || prevSort === null) return false;
|
||||
if (nextSort === undefined || nextSort === null) return false;
|
||||
// Also catches NaN / non-numeric sorts: NaN comparisons are false.
|
||||
return !(Number(nextSort) - Number(prevSort) > 0);
|
||||
}
|
||||
|
||||
// Given the sibling cards of the drop target in their current VISUAL order
|
||||
// (excluding the dragged card), return the minimal `{ _id, sort }` rewrites
|
||||
// that make the sequence strictly increasing. Cards already in strictly
|
||||
// increasing positions are left untouched (no needless writes / reactive
|
||||
// churn); each offender is bumped to `previous + 1`.
|
||||
function computeMonotonicSortRepair(orderedCards) {
|
||||
const updates = [];
|
||||
let last = null;
|
||||
(orderedCards || []).forEach(card => {
|
||||
if (!card || !card._id) return;
|
||||
let sort = Number(card.sort);
|
||||
if (!Number.isFinite(sort) || (last !== null && sort <= last)) {
|
||||
sort = last === null ? 0 : last + 1;
|
||||
updates.push({ _id: card._id, sort });
|
||||
}
|
||||
last = sort;
|
||||
});
|
||||
return updates;
|
||||
}
|
||||
|
||||
// Repair the sibling sorts and compute the drop index between `prevCard` and
|
||||
// `nextCard` (both `{ _id, sort }`, both members of `orderedCards`). Returns
|
||||
// {
|
||||
// updates, // sort rewrites to persist for the sibling cards
|
||||
// base, // sort for the (first) dropped card
|
||||
// increment, // spacing for the 2nd..nth card of a multi-selection drop
|
||||
// }
|
||||
// After the repair the neighbours strictly increase, so `base` lies strictly
|
||||
// between them and `increment` is strictly positive: every card of a
|
||||
// multi-selection keeps a distinct sort (no order data-loss), and the write is
|
||||
// never equal to a neighbour's sort (so it can not be dropped as a no-op).
|
||||
function computeRepairedDropIndex(orderedCards, prevCard, nextCard, nCards = 1) {
|
||||
const updates = computeMonotonicSortRepair(orderedCards);
|
||||
const repaired = {};
|
||||
updates.forEach(u => {
|
||||
repaired[u._id] = u.sort;
|
||||
});
|
||||
const sortOf = card =>
|
||||
card && card._id && Object.prototype.hasOwnProperty.call(repaired, card._id)
|
||||
? repaired[card._id]
|
||||
: Number(card && card.sort);
|
||||
const prevSort = sortOf(prevCard);
|
||||
const nextSort = sortOf(nextCard);
|
||||
const n = Number(nCards) >= 1 ? Number(nCards) : 1;
|
||||
const increment = (nextSort - prevSort) / (n + 1);
|
||||
const base = prevSort + increment;
|
||||
return { updates, base, increment };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isDegenerateSortGap,
|
||||
computeMonotonicSortRepair,
|
||||
computeRepairedDropIndex,
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
// #3748: match a card's `customFields` entries to the custom-field definitions
|
||||
// attached to the card's CURRENT board ("customFields With Definitions").
|
||||
//
|
||||
// Linked cards are by design pointers that mirror the original card; labels and
|
||||
// custom-field DEFINITIONS are board-scoped, so they are deliberately not
|
||||
// inherited across boards (that remapping-by-name behaviour belongs to the
|
||||
// COPY path — Cards.copy()/mapCustomFieldsToBoard — not to links). However,
|
||||
// Cards.link() deep-copies the original document, so a cross-board linked card
|
||||
// carries a `customFields` snapshot whose definition ids do not exist on the
|
||||
// viewing board. The old customFieldsWD() returned an empty `{}` placeholder
|
||||
// for every unmatched entry, which rendered a phantom empty row in the card
|
||||
// details and made the `cardCustomField` template's getTemplate() helper throw
|
||||
// "TypeError: Cannot read properties of undefined (reading 'type')" on every
|
||||
// render. Unmatched entries must be SKIPPED instead.
|
||||
|
||||
// A dropdown custom field stores the selected item's id as `value`; the
|
||||
// human-readable "true value" is the matching dropdown item's name. Any other
|
||||
// field type (or an id that no longer matches an item) keeps the raw value.
|
||||
function resolveTrueValue(definition, value) {
|
||||
const items =
|
||||
definition && definition.settings && definition.settings.dropdownItems;
|
||||
if (Array.isArray(items)) {
|
||||
for (const item of items) {
|
||||
if (item && item._id === value) {
|
||||
return item.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// customFields: the card's own `customFields` array ([{_id, value}, ...]).
|
||||
// definitions: the CustomFields definitions attached to the card's board.
|
||||
// Returns [{_id, value, trueValue, definition}, ...] sorted by definition
|
||||
// name, with entries whose definition is not on this board left out.
|
||||
function buildCustomFieldsWD(customFields, definitions) {
|
||||
if (!Array.isArray(customFields) || !Array.isArray(definitions)) {
|
||||
return [];
|
||||
}
|
||||
const ret = [];
|
||||
for (const customField of customFields) {
|
||||
if (!customField) {
|
||||
continue;
|
||||
}
|
||||
const definition = definitions.find(
|
||||
def => def && def._id === customField._id,
|
||||
);
|
||||
if (!definition) {
|
||||
// e.g. a linked card's snapshot from the original board, or a definition
|
||||
// that was deleted / detached from this board.
|
||||
continue;
|
||||
}
|
||||
ret.push({
|
||||
_id: customField._id,
|
||||
value: customField.value,
|
||||
trueValue: resolveTrueValue(definition, customField.value),
|
||||
definition,
|
||||
});
|
||||
}
|
||||
ret.sort((a, b) => {
|
||||
const aName = a.definition.name;
|
||||
const bName = b.definition.name;
|
||||
if (aName === undefined || bName === undefined) {
|
||||
return 0;
|
||||
}
|
||||
return aName.localeCompare(bName);
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
module.exports = { buildCustomFieldsWD, resolveTrueValue };
|
||||
@@ -0,0 +1,51 @@
|
||||
// #1992: restore ALL card date fields when importing a WeKan board export.
|
||||
//
|
||||
// The exporter (models/exporter.js) dumps full card documents, so an export
|
||||
// carries createdAt, receivedAt, startAt, dueAt and endAt. The importer
|
||||
// (models/wekanCreator.js) previously restored only startAt and dueAt, and
|
||||
// derived createdAt exclusively from a matching `createCard` activity — but
|
||||
// Sandstorm exports and old/pruned boards often have no such activity, so the
|
||||
// card's creation date silently reset to the import time ("dates missing" in
|
||||
// the issue). receivedAt and endAt were dropped for every import.
|
||||
//
|
||||
// This module is pure (no Meteor) so it can be unit-tested with plain Node.
|
||||
|
||||
/**
|
||||
* Parse a date-ish value (ISO string or Date) into a valid Date, or null.
|
||||
* Invalid values return null instead of an Invalid Date so a corrupt field in
|
||||
* a foreign/hand-edited export can never fail collection2 validation and
|
||||
* abort the whole card insert (which would make cards go missing).
|
||||
*/
|
||||
function toValidDateOrNull(value) {
|
||||
if (!value) return null;
|
||||
const d = new Date(value);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the date fields for a card being imported.
|
||||
*
|
||||
* @param {Object} card the card object from the export
|
||||
* @param {String|Date|null} activityCreatedAt creation date recovered from the
|
||||
* export's `createCard` activity, when one exists (takes precedence,
|
||||
* matching the importer's historical behaviour)
|
||||
* @param {Date} now fallback timestamp (the import operation's shared date)
|
||||
* @returns {{createdAt: Date, receivedAt: ?Date, startAt: ?Date, dueAt: ?Date, endAt: ?Date}}
|
||||
*/
|
||||
function importedCardDates(card, activityCreatedAt, now) {
|
||||
const fallbackNow =
|
||||
now instanceof Date && !isNaN(now.getTime()) ? now : new Date();
|
||||
const createdAt =
|
||||
toValidDateOrNull(activityCreatedAt) ||
|
||||
toValidDateOrNull(card && card.createdAt) ||
|
||||
fallbackNow;
|
||||
return {
|
||||
createdAt,
|
||||
receivedAt: toValidDateOrNull(card && card.receivedAt),
|
||||
startAt: toValidDateOrNull(card && card.startAt),
|
||||
dueAt: toValidDateOrNull(card && card.dueAt),
|
||||
endAt: toValidDateOrNull(card && card.endAt),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { importedCardDates, toValidDateOrNull };
|
||||
@@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for the "invite by email" flow (Meteor method `sendInvitation`
|
||||
// in server/models/settings.js). Extracted so the rules that guarantee "an
|
||||
// invitation email always carries a code that will validate at sign-up" are
|
||||
// unit-testable without Meteor.
|
||||
//
|
||||
// #4043 ("Sometimes user get board invitation by mail without invitation
|
||||
// code"): recipients received an invitation email whose code the sign-up form
|
||||
// then rejected with "The invitation code doesn't exist". Sign-up only accepts
|
||||
// a code whose stored document matches { code, email, valid: true }
|
||||
// (server/models/users.js onCreateUser), so the SENDING side must guarantee:
|
||||
// 1. the stored email is lowercase — the sign-up form lowercases the typed
|
||||
// address and MongoDB string matching is case sensitive, so a mixed-case
|
||||
// invitation document can never match (normalizeInviteEmail);
|
||||
// 2. a RE-INVITE never re-sends a stale code: when the stored invitation is
|
||||
// no longer valid (e.g. consumed and left with valid:false) or has no
|
||||
// usable code, a fresh code must overwrite the old one with `valid`
|
||||
// restored to true (buildReinviteModifier) — this is the fix proposed in
|
||||
// the #4043 thread ("send a new invitation code that overwrites the last
|
||||
// one");
|
||||
// 3. an email is only sent for an invitation document that exists, has a
|
||||
// non-empty string code, and is still valid (isInvitationCodeSendable) —
|
||||
// otherwise fail loudly instead of mailing a dead code;
|
||||
// 4. a failed SMTP send may only roll back (delete) an invitation code that
|
||||
// was created by this very invite; deleting a PRE-EXISTING document would
|
||||
// silently invalidate the code already delivered in an earlier email
|
||||
// (shouldRemoveInvitationOnEmailFailure).
|
||||
|
||||
// Lowercase + trim an invitee address so the stored invitation email always
|
||||
// matches the (lowercased) address the user signs up with. Non-strings
|
||||
// normalize to '' (callers skip empty results).
|
||||
function normalizeInviteEmail(email) {
|
||||
if (typeof email !== 'string') {
|
||||
return '';
|
||||
}
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
// True when `code` is a non-empty string — the only shape the sign-up lookup
|
||||
// { code: <string from the form>, valid: true } can ever match. Legacy or
|
||||
// hand-inserted documents may carry a Number code, which MongoDB will never
|
||||
// match against the form's string.
|
||||
function hasUsableCode(invitation) {
|
||||
return Boolean(
|
||||
invitation &&
|
||||
typeof invitation.code === 'string' &&
|
||||
invitation.code.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
// An invitation email may only be sent for a document that exists, carries a
|
||||
// usable code, and has not been invalidated (valid === false). A missing
|
||||
// `valid` field (legacy documents predating the field's defaultValue) counts
|
||||
// as valid.
|
||||
function isInvitationCodeSendable(invitation) {
|
||||
return hasUsableCode(invitation) && invitation.valid !== false;
|
||||
}
|
||||
|
||||
// Build the Mongo modifier for re-inviting an email that already has an
|
||||
// invitation document. Always refreshes boardsToBeInvited; additionally
|
||||
// overwrites the code (and restores valid:true) when the stored one could
|
||||
// never validate at sign-up — stale (valid:false), missing, empty, or not a
|
||||
// string. `generateCode` supplies the new code (coerced to String so it
|
||||
// matches the form input type regardless of the generator).
|
||||
function buildReinviteModifier(invitation, boards, generateCode) {
|
||||
const $set = { boardsToBeInvited: boards };
|
||||
if (!invitation || invitation.valid === false || !hasUsableCode(invitation)) {
|
||||
$set.code = String(generateCode());
|
||||
$set.valid = true;
|
||||
}
|
||||
return { $set };
|
||||
}
|
||||
|
||||
// After an SMTP failure, only an invitation created by this very invite call
|
||||
// may be deleted (nothing was ever delivered for it). A pre-existing document
|
||||
// must survive, because its code was already delivered in an earlier email.
|
||||
function shouldRemoveInvitationOnEmailFailure({ isNewInvitation } = {}) {
|
||||
return isNewInvitation === true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeInviteEmail,
|
||||
hasUsableCode,
|
||||
isInvitationCodeSendable,
|
||||
buildReinviteModifier,
|
||||
shouldRemoveInvitationOnEmailFailure,
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for deriving a username for a NEW user invited to a board by
|
||||
// email address (Meteor method `inviteUserToBoard` in server/models/users.js).
|
||||
// Extracted so the username-collision rules are unit-testable without Meteor.
|
||||
//
|
||||
// #619 ("Not possible to invite multiple users with similar email
|
||||
// addresses"): inviting cats@foo.com creates a user named "cats" (the email
|
||||
// local part). Inviting cats@facebook.com afterwards passed the bare local
|
||||
// part to Accounts.createUser again, which threw Meteor's raw
|
||||
// `Error 403: Username already exists.` — surfaced in the Add-Member popup as
|
||||
// an "inaccurate error: 403". The invitee's username is an implementation
|
||||
// detail here (the human typed an EMAIL, not a username), so instead of
|
||||
// failing, the caller should pick the first free variant of the local part:
|
||||
// "cats", "cats1", "cats2", … up to a bounded number of attempts.
|
||||
|
||||
// Lowercased local part of an email address ("Cats@Foo.com" -> "cats").
|
||||
// Mirrors the normalization inviteUserToBoard applies (whole address is
|
||||
// lowercased before splitting). Returns '' for non-strings and for strings
|
||||
// without a usable local part (no '@', or '@' first), so callers can treat
|
||||
// falsy as "not an email".
|
||||
function usernameFromEmail(email) {
|
||||
if (typeof email !== 'string') {
|
||||
return '';
|
||||
}
|
||||
const normalized = email.trim().toLowerCase();
|
||||
const posAt = normalized.indexOf('@');
|
||||
if (posAt <= 0) {
|
||||
return '';
|
||||
}
|
||||
return normalized.substring(0, posAt);
|
||||
}
|
||||
|
||||
// Derive a username for a new invitee that does not collide with an existing
|
||||
// account: the email local part itself when free, otherwise the first free
|
||||
// "<localPart><n>" (n = 1, 2, …). `isUsernameTaken(candidate)` is supplied by
|
||||
// the caller (sync or async, e.g. a ReactiveCache.getUser lookup) so this
|
||||
// stays a pure, Meteor-free module.
|
||||
//
|
||||
// Returns null when the email has no usable local part or when every
|
||||
// candidate within `maxAttempts` is taken — callers must treat null as
|
||||
// "could not create the user" and raise a proper, translatable error instead
|
||||
// of letting Accounts.createUser throw a raw 403.
|
||||
async function deriveUniqueInviteeUsername(
|
||||
email,
|
||||
isUsernameTaken,
|
||||
{ maxAttempts = 100 } = {},
|
||||
) {
|
||||
if (typeof isUsernameTaken !== 'function') {
|
||||
throw new TypeError('isUsernameTaken must be a function');
|
||||
}
|
||||
const base = usernameFromEmail(email);
|
||||
if (!base) {
|
||||
return null;
|
||||
}
|
||||
if (!(await isUsernameTaken(base))) {
|
||||
return base;
|
||||
}
|
||||
for (let suffix = 1; suffix < maxAttempts; suffix += 1) {
|
||||
const candidate = `${base}${suffix}`;
|
||||
if (!(await isUsernameTaken(candidate))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
usernameFromEmail,
|
||||
deriveUniqueInviteeUsername,
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
'use strict';
|
||||
|
||||
// #5659 "List Width settings do not affect Public Board".
|
||||
//
|
||||
// The default list width used to be duplicated (and DISAGREE) across the
|
||||
// width-resolution paths:
|
||||
// - client/components/lists/list.js -> 272 (DEFAULT_LIST_WIDTH)
|
||||
// - client/components/lists/listHeader.js -> 272/270 hardcoded literals
|
||||
// - models/lists.js (schema defaultValue) -> 272
|
||||
// - models/users.js getListWidth() -> 270
|
||||
// - models/users.js getListWidthFromStorage() (anonymous/public-board
|
||||
// storage path) -> 270
|
||||
// - models/users.js getFixedListWidth() -> 272
|
||||
//
|
||||
// Depending on which path resolved a given list's width (logged-in member
|
||||
// profile, anonymous localStorage on a public board, the shared lists.width,
|
||||
// or fixed-width mode), the fallback "default" differed, so lists on the SAME
|
||||
// board could render at different widths even though nobody had customized
|
||||
// anything — most visibly for logged-out visitors of public boards.
|
||||
//
|
||||
// This module is the single source of truth. It is Meteor-free so it can be
|
||||
// unit tested in plain Node (see tests/listWidthDefaults.test.cjs) and is
|
||||
// imported by both the client width helpers and the user model helpers.
|
||||
|
||||
// The one default width every list renders at when no customization exists.
|
||||
const DEFAULT_LIST_WIDTH = 272;
|
||||
// The minimum width a customized list may have (matches the resize handle,
|
||||
// the Set-Width popup validation and the server-side setFixedListWidth check).
|
||||
const MIN_LIST_WIDTH = 270;
|
||||
|
||||
// A width "counts" (may override the default) only when it is a real, finite
|
||||
// number within the allowed range.
|
||||
function isValidListWidth(width) {
|
||||
return (
|
||||
typeof width === 'number' &&
|
||||
Number.isFinite(width) &&
|
||||
width >= MIN_LIST_WIDTH
|
||||
);
|
||||
}
|
||||
|
||||
// Normalize a stored width: return it when valid, otherwise the fallback
|
||||
// (the board-wide default unless the caller supplies another).
|
||||
function normalizeListWidth(width, fallback = DEFAULT_LIST_WIDTH) {
|
||||
return isValidListWidth(width) ? width : fallback;
|
||||
}
|
||||
|
||||
// Resolve the width ONE list renders at, given the viewer's context:
|
||||
// - fixedEnabled / fixedWidth : the viewer's per-board "same width for all
|
||||
// lists" mode (#5729). When on, every list uses the single fixedWidth.
|
||||
// - sharedWidth : lists.width — the board-wide width shared by
|
||||
// all viewers (#6409), including logged-out visitors of public boards.
|
||||
// - personalMode : board.allowsPersonalListWidth.
|
||||
// - personalWidth : the viewer's own width for this list
|
||||
// (profile for logged-in users, localStorage for anonymous ones). Only
|
||||
// consulted in personal mode.
|
||||
//
|
||||
// With NO customization at all this always returns DEFAULT_LIST_WIDTH, for
|
||||
// every list and every viewer — which is what keeps all lists of a public
|
||||
// board the same width by default.
|
||||
function resolveListWidth(options) {
|
||||
const {
|
||||
fixedEnabled = false,
|
||||
fixedWidth = null,
|
||||
sharedWidth = null,
|
||||
personalMode = false,
|
||||
personalWidth = null,
|
||||
} = options || {};
|
||||
if (fixedEnabled) {
|
||||
return normalizeListWidth(fixedWidth);
|
||||
}
|
||||
const shared = normalizeListWidth(sharedWidth);
|
||||
if (!personalMode) {
|
||||
return shared;
|
||||
}
|
||||
return normalizeListWidth(personalWidth, shared);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_LIST_WIDTH,
|
||||
MIN_LIST_WIDTH,
|
||||
isValidListWidth,
|
||||
normalizeListWidth,
|
||||
resolveListWidth,
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
'use strict';
|
||||
|
||||
// #2345 "basic card title filter rules issue".
|
||||
//
|
||||
// The board-rule triggers ("when a card is created / moved / archived ...")
|
||||
// offer a magnifier popup that lets the user restrict the trigger to cards
|
||||
// whose title matches a filter. Three things were broken:
|
||||
//
|
||||
// 1. The generic "when a card is moved" and the archive/unarchive triggers
|
||||
// never stored the filter at all — worse, they stored NO `cardTitle`
|
||||
// field, and because the server matches triggers with
|
||||
// `cardTitle: { $in: [...] }`, a trigger document that lacks the field
|
||||
// can never match an activity that carries a card title, so those rules
|
||||
// never fired for anything.
|
||||
// 2. A stored filter never appeared in the trigger's human-readable
|
||||
// description ("When a card is moved to list X" — no trace of "Part A"),
|
||||
// which is exactly what the issue reporter complained about.
|
||||
// 3. Old trigger documents created before the fix (without a `cardTitle`
|
||||
// field) must keep behaving as "match every card".
|
||||
//
|
||||
// These helpers are pure (no Meteor imports) so both the client wizard and
|
||||
// server/rulesHelper.js share one tested implementation.
|
||||
|
||||
// Normalize the raw popup input into the value stored on the trigger document.
|
||||
// An empty / whitespace-only / missing filter means "match every card", which
|
||||
// the rules engine expresses with the '*' wildcard (this matches the UI note:
|
||||
// "leave a field empty to match every possible value").
|
||||
function cardTitleFilterOrWildcard(raw) {
|
||||
if (typeof raw !== 'string') return '*';
|
||||
const trimmed = raw.trim();
|
||||
return trimmed === '' ? '*' : trimmed;
|
||||
}
|
||||
|
||||
// Build the list of trigger `cardTitle` values that match an activity whose
|
||||
// card title is `activityCardTitle`, used as `cardTitle: { $in: [...] }` when
|
||||
// looking up triggers. A trigger matches when its stored filter is:
|
||||
// - the exact card title,
|
||||
// - any single word of the card title (historic behaviour: the title is
|
||||
// split on non-word characters),
|
||||
// - the '*' wildcard (no filter set), or
|
||||
// - null / a missing field (legacy triggers saved without a cardTitle —
|
||||
// in MongoDB `$in: [null, ...]` also matches documents lacking the field,
|
||||
// which keeps pre-fix rules firing as "every card").
|
||||
function cardTitleMatchList(activityCardTitle) {
|
||||
const matches = ['*', null];
|
||||
if (activityCardTitle !== undefined && activityCardTitle !== null) {
|
||||
const title = String(activityCardTitle);
|
||||
return title
|
||||
.split(/\W/)
|
||||
.filter(word => word !== '')
|
||||
.concat([title])
|
||||
.concat(matches);
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
// Pure predicate mirroring the $in semantics above: does a trigger stored with
|
||||
// `filter` fire for a card titled `cardTitle`? (A missing/null filter — legacy
|
||||
// trigger — matches everything, like the wildcard.)
|
||||
function cardTitleFilterMatches(filter, cardTitle) {
|
||||
if (filter === undefined || filter === null) return true;
|
||||
return cardTitleMatchList(cardTitle).includes(filter);
|
||||
}
|
||||
|
||||
// Append the filter to the trigger's human-readable description so the rule
|
||||
// list / rule details show it ("when a card is moved to list x (card title
|
||||
// filter: "Part A")"). A wildcard/empty filter leaves the description alone.
|
||||
function appendCardTitleFilterToDesc(desc, cardTitle, label) {
|
||||
const base = typeof desc === 'string' ? desc : '';
|
||||
if (!cardTitle || cardTitle === '*') return base;
|
||||
const tag = label && typeof label === 'string' ? label : 'card title filter';
|
||||
return `${base} (${tag}: "${cardTitle}")`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
cardTitleFilterOrWildcard,
|
||||
cardTitleMatchList,
|
||||
cardTitleFilterMatches,
|
||||
appendCardTitleFilterToDesc,
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
'use strict';
|
||||
|
||||
// Pure helpers for deriving a unique WeKan username from a Sandstorm
|
||||
// preferredHandle (used by the Users.after.insert hook in sandstorm.js), split
|
||||
// out so they can be unit-tested in plain Node (tests/*.test.cjs) without a
|
||||
// Meteor context.
|
||||
//
|
||||
// Fixes #574 "Sandstorm - generation of unique usernames":
|
||||
// - The uniqueness probe must be CASE-INSENSITIVE. Meteor usernames are
|
||||
// case-preserving but case-insensitively unique, while the old exact-match
|
||||
// query was case-sensitive: an existing 'Max' did not stop a new 'max',
|
||||
// producing two accounts that Meteor's account machinery considers the
|
||||
// same username.
|
||||
// - The handle must be regex-escaped before interpolation into the probe so
|
||||
// a handle containing regex metacharacters is matched literally (Sandstorm
|
||||
// promises lower-case ASCII letters/digits/underscores, but we must not
|
||||
// rely on that for query correctness).
|
||||
// - The probe -> update window is racy: a concurrent insert can claim the
|
||||
// probed name between our find and our update. accounts-base keeps a
|
||||
// unique index on `username`, so the losing update throws a MongoDB
|
||||
// E11000 duplicate-key error; instead of letting that abort the insert
|
||||
// hook we catch it and retry with the next appended number.
|
||||
|
||||
// 'max' + 0 -> 'max', 'max' + 1 -> 'max1', ... (historical numbering: the
|
||||
// first fallback is 'max1', there is no 'max0').
|
||||
function generateUniqueUsername(username, appendNumber) {
|
||||
return username + String(appendNumber === 0 ? '' : appendNumber);
|
||||
}
|
||||
|
||||
// Escape regex metacharacters so the text is matched literally.
|
||||
function escapeForRegex(text) {
|
||||
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
// Anchored, case-insensitive matcher for a username candidate, safe to put in
|
||||
// a Mongo `username:` selector.
|
||||
function usernameCaseInsensitiveRegex(username) {
|
||||
return new RegExp(`^${escapeForRegex(username)}$`, 'i');
|
||||
}
|
||||
|
||||
// True for MongoDB's duplicate-key error (unique index violation) in the
|
||||
// shapes the Node driver / Meteor surface it: numeric code 11000/11001, or an
|
||||
// E11000 marker in the message/errmsg.
|
||||
function isDuplicateKeyError(error) {
|
||||
if (!error) return false;
|
||||
if (error.code === 11000 || error.code === 11001) return true;
|
||||
const text = `${error.message || ''} ${error.errmsg || ''}`;
|
||||
return text.includes('E11000') || text.includes('E11001');
|
||||
}
|
||||
|
||||
// Walk appendNumber upward until `isTakenAsync(candidate)` reports the name
|
||||
// free, then hand the candidate to `claimAsync(candidate)` (the DB update).
|
||||
// If claiming throws a duplicate-key error — another session raced us to the
|
||||
// same name — move on to the next number instead of crashing. Any other error
|
||||
// propagates unchanged. Resolves to the username that was actually claimed.
|
||||
async function claimUniqueUsername(base, isTakenAsync, claimAsync) {
|
||||
for (let appendNumber = 0; ; appendNumber += 1) {
|
||||
const candidate = generateUniqueUsername(base, appendNumber);
|
||||
if (await isTakenAsync(candidate)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await claimAsync(candidate);
|
||||
return candidate;
|
||||
} catch (error) {
|
||||
if (!isDuplicateKeyError(error)) {
|
||||
throw error;
|
||||
}
|
||||
// Lost the race for this candidate; try the next number.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateUniqueUsername,
|
||||
escapeForRegex,
|
||||
usernameCaseInsensitiveRegex,
|
||||
isDuplicateKeyError,
|
||||
claimUniqueUsername,
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
|
||||
// Pure, Meteor-free helpers for the swimlane archive/restore card cascade.
|
||||
// Extracted so the cascade decisions are unit-testable in plain Node
|
||||
// (mirrors models/lib/defaultSwimlane.js / models/lib/swimlaneFilter.js).
|
||||
//
|
||||
// #2292 ("Archive a swimlane drives to deletion of all cards included"):
|
||||
// archiving a swimlane used to flag ONLY the swimlane document. Its cards
|
||||
// stayed `archived: false` but became invisible everywhere — the board views
|
||||
// only render unarchived swimlanes, and the Archive sidebar only lists
|
||||
// documents with `archived: true`, so the cards showed up in neither. Worse,
|
||||
// the startup schema upgrade (server/lib/schemaUpgradeSteps.js,
|
||||
// `swimlane-structure`, #1959/#1971) treats "unarchived card under an
|
||||
// ARCHIVED swimlane" as broken state and reassigns such cards to a visible
|
||||
// swimlane — so after a server restart the archived swimlane was emptied for
|
||||
// good and restoring it produced an empty swimlane, exactly as reported.
|
||||
//
|
||||
// The fix mirrors the existing list cascade (models/lists.js archive()/
|
||||
// restore(), which archive/restore the list's cards with card.archive() /
|
||||
// card.restore()): archiving a swimlane archives its still-unarchived cards
|
||||
// so they are visible in Archive and restorable, and restoring the swimlane
|
||||
// restores the cards that were archived WITH it — not cards the user had
|
||||
// individually archived beforehand.
|
||||
|
||||
// Cards that must be archived together with the swimlane: every card of the
|
||||
// swimlane that is not archived yet. Already-archived cards are left alone so
|
||||
// their own archivedAt (and their place in the user's Archive history) is not
|
||||
// overwritten by the swimlane cascade.
|
||||
function cardsToArchiveWithSwimlane(cards) {
|
||||
return (cards || []).filter(card => card && card.archived !== true);
|
||||
}
|
||||
|
||||
// Cards that must be restored together with the swimlane: archived cards of
|
||||
// the swimlane whose archivedAt is at/after the swimlane's own archivedAt —
|
||||
// i.e. the ones the archive cascade above archived (the swimlane's archivedAt
|
||||
// is stamped before the per-card archivedAt). Cards the user archived
|
||||
// individually BEFORE archiving the swimlane keep their archived state.
|
||||
// A swimlane archived before this fix has cascade-untouched cards (and may
|
||||
// even lack archivedAt), so nothing is restored for it — its unarchived cards
|
||||
// were never hidden by an `archived` flag in the first place.
|
||||
function cardsToRestoreWithSwimlane(cards, swimlaneArchivedAt) {
|
||||
if (!swimlaneArchivedAt) return [];
|
||||
const archivedAtMs = new Date(swimlaneArchivedAt).getTime();
|
||||
if (Number.isNaN(archivedAtMs)) return [];
|
||||
return (cards || []).filter(card => {
|
||||
if (!card || card.archived !== true || !card.archivedAt) return false;
|
||||
const cardArchivedAtMs = new Date(card.archivedAt).getTime();
|
||||
return !Number.isNaN(cardArchivedAtMs) && cardArchivedAtMs >= archivedAtMs;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { cardsToArchiveWithSwimlane, cardsToRestoreWithSwimlane };
|
||||
@@ -0,0 +1,108 @@
|
||||
'use strict';
|
||||
|
||||
// Pure decision logic for keeping board memberships in sync when a user's
|
||||
// teams change. Extracted so it is unit-testable without Meteor
|
||||
// (see tests/teamBoardMemberSync.test.cjs).
|
||||
//
|
||||
// #4593 ("The new added user that was assigned to existing team cannot be
|
||||
// applied to kanban with the right authority"): when a team is assigned to a
|
||||
// board through the board sidebar (addBoardTeamPopup), every user who is in
|
||||
// the team AT THAT MOMENT is pushed into board.members as a normal member.
|
||||
// But a user added to the team AFTERWARDS never got a member entry: the
|
||||
// publications grant them read visibility of the board (boards / board
|
||||
// publications match `teams.teamId`), yet every authority check that gates
|
||||
// interaction — board.hasMember() (models/boards.js), allowIsBoardMember*()
|
||||
// (server/lib/utils.js), Attachments.protected (models/attachments.server.js)
|
||||
// and board.isVisibleBy() (export) — only looks at board.members. So the new
|
||||
// team member could at best view the board read-only, could not download its
|
||||
// attachments, and had strictly less authority than teammates who happened to
|
||||
// be in the team when it was assigned.
|
||||
//
|
||||
// These helpers compute, from a user's old and new team lists, which boards
|
||||
// must gain the user as a member so a late-joining team member ends up with
|
||||
// the same authority the team's original members received.
|
||||
|
||||
// Return the de-duplicated teamId strings of a user.teams-shaped array
|
||||
// (`[{ teamId, teamDisplayName }, ...]`). Tolerates a missing/invalid list and
|
||||
// entries without a teamId.
|
||||
function teamIdsOf(teams) {
|
||||
if (!Array.isArray(teams)) return [];
|
||||
const ids = [];
|
||||
const seen = new Set();
|
||||
teams.forEach(team => {
|
||||
const id = team && team.teamId;
|
||||
if (!id || typeof id !== 'string' || seen.has(id)) return;
|
||||
seen.add(id);
|
||||
ids.push(id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
// Team ids present in newTeams but not in oldTeams — the teams the user just
|
||||
// gained. Removals are intentionally NOT reported: a user removed from a team
|
||||
// may also have been invited to a board individually, and membership data
|
||||
// cannot tell those apart, so team-loss cleanup stays the explicit board-admin
|
||||
// action it always was (removeBoardTeamPopup).
|
||||
function gainedTeamIds(oldTeams, newTeams) {
|
||||
const before = new Set(teamIdsOf(oldTeams));
|
||||
return teamIdsOf(newTeams).filter(id => !before.has(id));
|
||||
}
|
||||
|
||||
// The member entry a team-derived user receives: a plain active, non-admin
|
||||
// member, exactly like the entries addBoardTeamPopup creates and with the
|
||||
// same fully-defaulted flags reconcileBoardTeamMembers assigns to members
|
||||
// introduced through the team-management path.
|
||||
function newTeamBoardMemberEntry(userId) {
|
||||
return {
|
||||
userId,
|
||||
isAdmin: false,
|
||||
isActive: true,
|
||||
isNoComments: false,
|
||||
isCommentOnly: false,
|
||||
isWorker: false,
|
||||
isNormalAssignedOnly: false,
|
||||
isCommentAssignedOnly: false,
|
||||
isReadOnly: false,
|
||||
isReadAssignedOnly: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Given the candidate board documents (each with at least _id, type, teams,
|
||||
// members), the user id and the team ids the user just gained, return the ids
|
||||
// of the boards the user must be added to as a member:
|
||||
// - the board must have one of the gained teams assigned AND active,
|
||||
// - template boards/containers are skipped (#5850: sharing on those is
|
||||
// group-only; the members tab shows only the creator),
|
||||
// - a user with ANY existing member entry (even inactive) is left untouched,
|
||||
// so an explicit per-board decision (e.g. a deactivated member) is never
|
||||
// silently overridden by a team change.
|
||||
function boardsToAddMemberTo(boards, userId, gainedIds) {
|
||||
if (!userId || typeof userId !== 'string') return [];
|
||||
if (!Array.isArray(boards) || !Array.isArray(gainedIds) || !gainedIds.length) {
|
||||
return [];
|
||||
}
|
||||
const gained = new Set(gainedIds);
|
||||
const ids = [];
|
||||
boards.forEach(board => {
|
||||
if (!board || !board._id) return;
|
||||
if (board.type === 'template-board' || board.type === 'template-container') {
|
||||
return;
|
||||
}
|
||||
const teams = Array.isArray(board.teams) ? board.teams : [];
|
||||
const sharedWithGainedTeam = teams.some(
|
||||
team => team && team.isActive === true && gained.has(team.teamId),
|
||||
);
|
||||
if (!sharedWithGainedTeam) return;
|
||||
const members = Array.isArray(board.members) ? board.members : [];
|
||||
if (members.some(member => member && member.userId === userId)) return;
|
||||
ids.push(board._id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
teamIdsOf,
|
||||
gainedTeamIds,
|
||||
newTeamBoardMemberEntry,
|
||||
boardsToAddMemberTo,
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
'use strict';
|
||||
|
||||
// Cleanup planning for user deletion (issue #1289: "Error after deleting a
|
||||
// user").
|
||||
//
|
||||
// Deleting a user — Admin Panel / People (Meteor method `removeUser`), the
|
||||
// self-service "delete account" button, or `DELETE /api/users/:userId` — only
|
||||
// removed the `users` document itself. Every reference to that user stayed
|
||||
// behind as a dangling id:
|
||||
//
|
||||
// - boards.members ([{ userId, isAdmin, ... }]) -> "ghost" members with
|
||||
// empty avatars that confused boards for years (see the issue thread:
|
||||
// 2017, 2019, 2021, 2022 and 2025 reports),
|
||||
// - boards.watchers ([{ userId, level }], complexWatchable),
|
||||
// - cards.members ([userId]),
|
||||
// - cards.assignees ([userId]),
|
||||
// - cards.watchers ([userId], simpleWatchable),
|
||||
// - lists.watchers ([userId], simpleWatchable),
|
||||
// - the user's uploaded avatar files (Avatars FilesCollection).
|
||||
//
|
||||
// While the client now null-guards missing users (so nothing crashes any
|
||||
// more), the ghost references themselves previously had to be cleaned up by
|
||||
// hand, board by board, or by editing MongoDB directly. This module computes
|
||||
// the cleanup a user deletion implies; models/users.js applies it from a
|
||||
// `Users.after.remove` collection hook, so every deletion path (method, REST,
|
||||
// direct removeAsync) is covered.
|
||||
//
|
||||
// Activities and comments authored by the user are intentionally KEPT — the
|
||||
// issue discussion settled on preserving history ("Replacing the username of
|
||||
// every deleted user ... leaves a lot of conversations indecipherable"), and
|
||||
// their rendering handles a missing author.
|
||||
//
|
||||
// Pure and Meteor-free so tests/userDeletionCleanup.test.cjs can exercise it
|
||||
// in plain Node (same pattern as models/lib/apiLogout.js and
|
||||
// models/lib/teamBoardMemberSync.js).
|
||||
|
||||
// A userId acceptable in a Mongo selector: a non-empty string. Anything else
|
||||
// (undefined, null, objects — including selector-injection attempts like
|
||||
// { $ne: null } — numbers, empty string) yields no cleanup plan.
|
||||
function isValidUserId(userId) {
|
||||
return typeof userId === 'string' && userId.length > 0;
|
||||
}
|
||||
|
||||
// Build the collection-by-collection cleanup implied by deleting `userId`.
|
||||
// Returns null when userId is not a valid id (callers skip cleanup entirely
|
||||
// rather than run an overly-broad selector).
|
||||
//
|
||||
// Shapes follow the schemas:
|
||||
// boards.members / boards.watchers hold OBJECTS with a userId field, so the
|
||||
// $pull argument is a sub-document match ({ members: { userId } });
|
||||
// cards.members / cards.assignees / cards.watchers / lists.watchers hold
|
||||
// plain userId STRINGS, so the $pull argument is the id itself.
|
||||
function buildUserDeletionCleanupPlan(userId) {
|
||||
if (!isValidUserId(userId)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
boards: {
|
||||
selector: {
|
||||
$or: [{ 'members.userId': userId }, { 'watchers.userId': userId }],
|
||||
},
|
||||
modifier: {
|
||||
$pull: { members: { userId }, watchers: { userId } },
|
||||
},
|
||||
},
|
||||
cards: {
|
||||
selector: {
|
||||
$or: [{ members: userId }, { assignees: userId }, { watchers: userId }],
|
||||
},
|
||||
modifier: {
|
||||
$pull: { members: userId, assignees: userId, watchers: userId },
|
||||
},
|
||||
},
|
||||
lists: {
|
||||
selector: { watchers: userId },
|
||||
modifier: { $pull: { watchers: userId } },
|
||||
},
|
||||
avatars: {
|
||||
// Avatars is an ostrio:files FilesCollection: removeAsync(selector)
|
||||
// deletes both the records and the stored files, returning the number
|
||||
// removed (0 when none match — no throw).
|
||||
selector: { userId },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Apply a cleanup plan against the given collections. Collections are
|
||||
// dependency-injected ({ boards, cards, lists, avatars }) so the logic is
|
||||
// unit-testable with fakes; any collection may be omitted and is then
|
||||
// skipped. boards/cards/lists need `updateAsync(selector, modifier, options)`
|
||||
// (multi-update), avatars needs `removeAsync(selector)`.
|
||||
//
|
||||
// Returns { boards, cards, lists, avatars } — the per-collection counts the
|
||||
// drivers reported (0 for skipped collections).
|
||||
async function applyUserDeletionCleanup(plan, collections) {
|
||||
const result = { boards: 0, cards: 0, lists: 0, avatars: 0 };
|
||||
if (!plan || !collections) {
|
||||
return result;
|
||||
}
|
||||
const { boards, cards, lists, avatars } = collections;
|
||||
if (boards && typeof boards.updateAsync === 'function') {
|
||||
result.boards =
|
||||
(await boards.updateAsync(plan.boards.selector, plan.boards.modifier, {
|
||||
multi: true,
|
||||
})) || 0;
|
||||
}
|
||||
if (cards && typeof cards.updateAsync === 'function') {
|
||||
result.cards =
|
||||
(await cards.updateAsync(plan.cards.selector, plan.cards.modifier, {
|
||||
multi: true,
|
||||
})) || 0;
|
||||
}
|
||||
if (lists && typeof lists.updateAsync === 'function') {
|
||||
result.lists =
|
||||
(await lists.updateAsync(plan.lists.selector, plan.lists.modifier, {
|
||||
multi: true,
|
||||
})) || 0;
|
||||
}
|
||||
if (avatars && typeof avatars.removeAsync === 'function') {
|
||||
result.avatars = (await avatars.removeAsync(plan.avatars.selector)) || 0;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isValidUserId,
|
||||
buildUserDeletionCleanupPlan,
|
||||
applyUserDeletionCleanup,
|
||||
};
|
||||
+25
-1
@@ -524,7 +524,22 @@ Swimlanes.helpers({
|
||||
await list.archive();
|
||||
}
|
||||
}
|
||||
return await Swimlanes.updateAsync(this._id, { $set: { archived: true, archivedAt: new Date() } });
|
||||
// #2292: archive the swimlane's cards WITH it, mirroring the card cascade
|
||||
// of Lists.archive() (models/lists.js). Without this the cards stayed
|
||||
// `archived: false` under an archived swimlane — invisible in every board
|
||||
// view AND in the Archive sidebar, and reassigned to another swimlane by
|
||||
// the startup rescue of #1959/#1971 (server/lib/schemaUpgradeSteps.js),
|
||||
// so restoring the swimlane later found it empty. The swimlane's
|
||||
// archivedAt is captured BEFORE the per-card archive() calls stamp each
|
||||
// card's archivedAt, so restore() below can recognise the cards that were
|
||||
// archived with the swimlane. Cards already archived by the user keep
|
||||
// their own archivedAt (see models/lib/swimlaneArchive.js).
|
||||
const { cardsToArchiveWithSwimlane } = require('./lib/swimlaneArchive');
|
||||
const archivedAt = new Date();
|
||||
for (const card of cardsToArchiveWithSwimlane(await this.allCards())) {
|
||||
await card.archive();
|
||||
}
|
||||
return await Swimlanes.updateAsync(this._id, { $set: { archived: true, archivedAt } });
|
||||
},
|
||||
|
||||
async restore() {
|
||||
@@ -533,6 +548,15 @@ Swimlanes.helpers({
|
||||
await list.restore();
|
||||
}
|
||||
}
|
||||
// #2292: restore the cards that were archived WITH this swimlane by
|
||||
// archive() above (their archivedAt is at/after the swimlane's),
|
||||
// mirroring the card cascade of Lists.restore() (models/lists.js). Cards
|
||||
// the user archived individually BEFORE archiving the swimlane stay
|
||||
// archived (see models/lib/swimlaneArchive.js).
|
||||
const { cardsToRestoreWithSwimlane } = require('./lib/swimlaneArchive');
|
||||
for (const card of cardsToRestoreWithSwimlane(await this.allCards(), this.archivedAt)) {
|
||||
await card.restore();
|
||||
}
|
||||
return await Swimlanes.updateAsync(this._id, { $set: { archived: false } });
|
||||
},
|
||||
|
||||
|
||||
+53
-7
@@ -5,6 +5,14 @@ import InviteToBoardRolesSettings, {
|
||||
INVITE_TO_BOARD_ROLES_ID,
|
||||
INVITE_TO_BOARD_ROLES_DEFAULT,
|
||||
} from '/models/inviteToBoardRolesSettings';
|
||||
// #5659: the default/minimum list width must be the SAME on every resolution
|
||||
// path (it used to be 270 here but 272 in the client and the lists schema, so
|
||||
// lists could fall back to different "defaults" on public boards).
|
||||
import {
|
||||
DEFAULT_LIST_WIDTH,
|
||||
MIN_LIST_WIDTH,
|
||||
normalizeListWidth,
|
||||
} from '/models/lib/listWidth';
|
||||
// import { Index, MongoDBEngine } from 'meteor/easy:search'; // Temporarily disabled due to compatibility issues
|
||||
const { SimpleSchema } = require('/imports/simpleSchema');
|
||||
const Users = Meteor.users;
|
||||
@@ -1077,8 +1085,7 @@ Users.helpers({
|
||||
// #5729 The single width applied to every list when fixed width mode is on.
|
||||
getFixedListWidth(boardId) {
|
||||
const { fixedListWidths = {} } = this.profile || {};
|
||||
const w = fixedListWidths[boardId];
|
||||
return typeof w === 'number' && w >= 270 ? w : 272;
|
||||
return normalizeListWidth(fixedListWidths[boardId]);
|
||||
},
|
||||
|
||||
invitedBoards() {
|
||||
@@ -1168,9 +1175,11 @@ Users.helpers({
|
||||
getListWidth(boardId, listId) {
|
||||
const listWidths = this.getListWidths();
|
||||
if (listWidths[boardId] && listWidths[boardId][listId]) {
|
||||
return listWidths[boardId][listId];
|
||||
// #5659: normalize so an out-of-range stored value can not make one
|
||||
// list's width differ from the shared default everyone else sees.
|
||||
return normalizeListWidth(listWidths[boardId][listId]);
|
||||
} else {
|
||||
return 270; //TODO(mark-i-m): default?
|
||||
return DEFAULT_LIST_WIDTH;
|
||||
}
|
||||
},
|
||||
getListConstraints() {
|
||||
@@ -1451,7 +1460,7 @@ Users.helpers({
|
||||
if (widths[boardId] && widths[boardId][listId]) {
|
||||
const width = widths[boardId][listId];
|
||||
// Validate it's a valid number
|
||||
if (validators.isValidNumber(width, 270, 1000)) {
|
||||
if (validators.isValidNumber(width, MIN_LIST_WIDTH, 1000)) {
|
||||
return width;
|
||||
}
|
||||
}
|
||||
@@ -1460,7 +1469,8 @@ Users.helpers({
|
||||
}
|
||||
}
|
||||
|
||||
return 270; // Return default width
|
||||
// #5659: same default as every other width-resolution path.
|
||||
return DEFAULT_LIST_WIDTH;
|
||||
},
|
||||
|
||||
setListWidthToStorage(boardId, listId, width) {
|
||||
@@ -1470,7 +1480,7 @@ Users.helpers({
|
||||
}
|
||||
|
||||
// Validate width before storing
|
||||
if (!validators.isValidNumber(width, 270, 1000)) {
|
||||
if (!validators.isValidNumber(width, MIN_LIST_WIDTH, 1000)) {
|
||||
console.warn('Invalid list width:', width);
|
||||
return false;
|
||||
}
|
||||
@@ -1949,6 +1959,42 @@ Users.helpers({
|
||||
});
|
||||
|
||||
if (Meteor.isServer) {
|
||||
// #1289 ("Error after deleting a user"): deleting a user (Admin Panel
|
||||
// `removeUser` method, self-service account delete, or
|
||||
// DELETE /api/users/:userId) removed only the users document and left
|
||||
// dangling references everywhere — "ghost" board members with empty
|
||||
// avatars, stale card members/assignees and watcher entries — that
|
||||
// previously had to be cleaned up by hand or by editing the database.
|
||||
// This after.remove hook runs for every deletion path (they all go through
|
||||
// Users.removeAsync / Meteor.users.removeAsync on this same collection) and
|
||||
// prunes those references. Activities/comments are intentionally kept so
|
||||
// history stays readable; see models/lib/userDeletionCleanup.js.
|
||||
const {
|
||||
buildUserDeletionCleanupPlan,
|
||||
applyUserDeletionCleanup,
|
||||
} = require('/models/lib/userDeletionCleanup');
|
||||
Users.after.remove(async function(currentUserId, doc) {
|
||||
try {
|
||||
const plan = buildUserDeletionCleanupPlan(doc && doc._id);
|
||||
if (!plan) return;
|
||||
await applyUserDeletionCleanup(plan, {
|
||||
boards: Boards,
|
||||
// Required lazily: cards/lists/avatars are not imported at the top of
|
||||
// this shared model, and avatars.js must only resolve server-side
|
||||
// config when actually needed here.
|
||||
cards: require('/models/cards').default,
|
||||
lists: require('/models/lists').default,
|
||||
avatars: require('/models/avatars').default,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[userDeletionCleanup] Failed to prune references of deleted user',
|
||||
doc && doc._id,
|
||||
error,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Meteor.methods({
|
||||
// Permanently dismiss the current global announcement for the logged-in
|
||||
// user (#6051). The version is computed server-side from the current
|
||||
|
||||
+20
-6
@@ -8,6 +8,7 @@ import { BOARD_COLORS, CARD_COLORS, SWIMLANE_COLORS } from '/models/metadata/col
|
||||
import Users from '/models/users';
|
||||
import { generateUniversalAttachmentUrl } from '/models/lib/universalUrlGenerator';
|
||||
import { planImportedBoardMember } from '/models/lib/importedBoardMemberPlan';
|
||||
import { importedCardDates } from '/models/lib/importedCardDates';
|
||||
import {
|
||||
getImportExportSecuritySettings,
|
||||
anonymizedUserWord,
|
||||
@@ -435,23 +436,36 @@ export class WekanCreator {
|
||||
if (!listId) {
|
||||
listId = await this._createDefaultList(boardId);
|
||||
}
|
||||
// #1992: restore every card date carried in the export. createdAt
|
||||
// prefers the export's createCard activity but falls back to the
|
||||
// card's own createdAt (Sandstorm and old/pruned exports have no
|
||||
// createCard activity, which used to reset the creation date to the
|
||||
// import time); receivedAt and endAt were previously dropped entirely.
|
||||
const cardDates = importedCardDates(
|
||||
card,
|
||||
this.createdAt.cards[card._id],
|
||||
this._now(),
|
||||
);
|
||||
const cardToCreate = {
|
||||
archived: card.archived,
|
||||
boardId,
|
||||
cardNumber: card.cardNumber || (await boardObj.getNextCardNumber()),
|
||||
// very old boards won't have a creation activity so no creation date
|
||||
createdAt: this._now(this.createdAt.cards[card._id]),
|
||||
createdAt: cardDates.createdAt,
|
||||
dateLastActivity: this._now(),
|
||||
description: card.description,
|
||||
listId,
|
||||
swimlaneId: this.swimlanes[card.swimlaneId] || this._defaultSwimlaneId,
|
||||
sort: card.sort,
|
||||
title: card.title,
|
||||
// we attribute the card to its creator if available
|
||||
userId: this._user(this.createdBy.cards[card._id]),
|
||||
// we attribute the card to its creator if available: the createCard
|
||||
// activity's author when present, else the userId stored on the
|
||||
// exported card itself (again, Sandstorm/old exports lack activities).
|
||||
userId: this._user(this.createdBy.cards[card._id] || card.userId),
|
||||
isOvertime: card.isOvertime || false,
|
||||
startAt: card.startAt ? this._now(card.startAt) : null,
|
||||
dueAt: card.dueAt ? this._now(card.dueAt) : null,
|
||||
receivedAt: cardDates.receivedAt,
|
||||
startAt: cardDates.startAt,
|
||||
dueAt: cardDates.dueAt,
|
||||
endAt: cardDates.endAt,
|
||||
spentTime: card.spentTime || null,
|
||||
};
|
||||
// add labels
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "wekan",
|
||||
"version": "v9.96.0",
|
||||
"version": "v9.97.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wekan",
|
||||
"version": "v9.96.0",
|
||||
"version": "v9.97.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wekan",
|
||||
"version": "v9.96.0",
|
||||
"version": "v9.97.0",
|
||||
"description": "Open-Source kanban",
|
||||
"private": true,
|
||||
"repository": {
|
||||
@@ -25,7 +25,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"test": "meteor test --once --driver-package meteortesting:mocha",
|
||||
"test:unit:node": "node tests/filenameSanitizer.test.cjs && node tests/cardBoardConsistency.test.cjs && node tests/cardUrl.test.cjs && node tests/defaultSwimlane.test.cjs && node tests/cardMoveModifier.test.cjs && node tests/authenticationMethod.test.cjs && node tests/linkedCardTarget.test.cjs && node tests/staleWhileRevalidate.test.cjs && node tests/restArrayParam.test.cjs && node tests/minicardLabelHeight.test.cjs && node tests/dateUtils.normalizeDigits.test.cjs && node tests/reconcileBoardTeamMembers.test.cjs && node tests/rulesBoardSelector.test.cjs && node tests/ruleActionResolve.test.cjs && node tests/boardBackground.test.cjs && node tests/weekStart.test.cjs && node tests/ldapUsernameSlug.test.cjs && node tests/ldapGroupAllowlist.test.cjs && node tests/htmljsArrayContent.test.cjs && node tests/cardDescriptionDraft.test.cjs && node tests/commentDraft.test.cjs && node tests/attachmentDeleteGuard.test.cjs && node tests/ruleMoveAction.test.cjs && node tests/snapMigrationRecovery.test.cjs && node tests/cpuExec.test.cjs && node tests/cpuExecWiring.test.cjs && node tests/ferretdbHasData.test.cjs && node tests/ferretdbPolling.test.cjs && node tests/uiDensity.test.cjs && node tests/editorSubmitKey.test.cjs && node tests/isoWeek.test.cjs && node tests/boardCopyDefaults.test.cjs && node tests/linkedCardTitle.test.cjs && node tests/commentActivity.test.cjs && node tests/swimlaneSort.test.cjs && node tests/subtaskCopy.test.cjs && node tests/subtasksDefaultBoard.test.cjs && node tests/scrollbarCss.test.cjs && node tests/minicardBidiIsolation.test.cjs && node tests/notificationCleanup.test.cjs && node tests/cardSearch.test.cjs && node tests/linkedCardMembers.test.cjs && node tests/verificationEmail.test.cjs && node tests/boardSortReorder.test.cjs && node tests/checklistItemTitles.test.cjs && node tests/swimlaneFilter.test.cjs && node tests/popupOffset.test.cjs && node tests/linkedCardCover.test.cjs && node tests/inviteEmailLanguage.test.cjs && node tests/domainTablePage.test.cjs && node tests/mongoSelectorSafety.test.cjs && node tests/cardsLoading.test.cjs && node tests/base64Chunk.test.cjs && node tests/backupPaths.test.cjs && node tests/backupCron.test.cjs && node tests/avatarUrlSafety.test.cjs && node tests/importedUserReconciliationPlan.test.cjs && node tests/ldapPhoto.test.cjs && node tests/importedBoardMemberPlan.test.cjs && node tests/unit/resetPasswordEmail.test.js",
|
||||
"test:unit:node": "node tests/filenameSanitizer.test.cjs && node tests/cardBoardConsistency.test.cjs && node tests/cardUrl.test.cjs && node tests/defaultSwimlane.test.cjs && node tests/cardMoveModifier.test.cjs && node tests/authenticationMethod.test.cjs && node tests/linkedCardTarget.test.cjs && node tests/staleWhileRevalidate.test.cjs && node tests/restArrayParam.test.cjs && node tests/minicardLabelHeight.test.cjs && node tests/dateUtils.normalizeDigits.test.cjs && node tests/reconcileBoardTeamMembers.test.cjs && node tests/rulesBoardSelector.test.cjs && node tests/ruleActionResolve.test.cjs && node tests/boardBackground.test.cjs && node tests/weekStart.test.cjs && node tests/ldapUsernameSlug.test.cjs && node tests/ldapGroupAllowlist.test.cjs && node tests/htmljsArrayContent.test.cjs && node tests/cardDescriptionDraft.test.cjs && node tests/commentDraft.test.cjs && node tests/attachmentDeleteGuard.test.cjs && node tests/ruleMoveAction.test.cjs && node tests/snapMigrationRecovery.test.cjs && node tests/migrationAttachmentExtraction.test.cjs && node tests/attachmentRepair.test.cjs && node tests/attachmentStoragePath.test.cjs && node tests/schemaUpgradeSteps.test.cjs && node tests/cpuExec.test.cjs && node tests/cpuExecWiring.test.cjs && node tests/ferretdbHasData.test.cjs && node tests/ferretdbPolling.test.cjs && node tests/uiDensity.test.cjs && node tests/editorSubmitKey.test.cjs && node tests/isoWeek.test.cjs && node tests/boardCopyDefaults.test.cjs && node tests/linkedCardTitle.test.cjs && node tests/commentActivity.test.cjs && node tests/swimlaneSort.test.cjs && node tests/subtaskCopy.test.cjs && node tests/subtasksDefaultBoard.test.cjs && node tests/scrollbarCss.test.cjs && node tests/minicardBidiIsolation.test.cjs && node tests/notificationCleanup.test.cjs && node tests/cardSearch.test.cjs && node tests/linkedCardMembers.test.cjs && node tests/verificationEmail.test.cjs && node tests/boardSortReorder.test.cjs && node tests/checklistItemTitles.test.cjs && node tests/swimlaneFilter.test.cjs && node tests/popupOffset.test.cjs && node tests/linkedCardCover.test.cjs && node tests/inviteEmailLanguage.test.cjs && node tests/domainTablePage.test.cjs && node tests/mongoSelectorSafety.test.cjs && node tests/cardsLoading.test.cjs && node tests/base64Chunk.test.cjs && node tests/backupPaths.test.cjs && node tests/backupCron.test.cjs && node tests/avatarUrlSafety.test.cjs && node tests/importedUserReconciliationPlan.test.cjs && node tests/ldapPhoto.test.cjs && node tests/importedBoardMemberPlan.test.cjs && node tests/unit/resetPasswordEmail.test.js",
|
||||
"test:unit:all": "npm run test:unit:node && node tests/cards.stickers.test.js && node tests/stickers.test.js && node tests/stickers.packs.test.js && node tests/linkCardPopup.test.js && node tests/trelloCreator.import.test.js && node tests/trelloImport.maplink.test.js && node tests/trelloImport.zip.test.js && node tests/wekanCreator.import.test.js && node tests/wekanCreator.inconsistent.test.js && node tests/unit/oauth2-admin-groups.test.js",
|
||||
"test:watch": "meteor test --driver-package meteortesting:mocha",
|
||||
"test:e2e": "node tests/e2e/list-regressions.js",
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
// #4158 "Documentation/configuration of LDAP_ENCRYPTION". Historically the
|
||||
// code only understood two magic strings, and both were misleadingly named:
|
||||
//
|
||||
// - 'ssl' meant LDAPS (connect to e.g. port 636, TLS from the first byte),
|
||||
// which was only discoverable by reading the source;
|
||||
// - 'tls' meant STARTTLS (connect plaintext, then upgrade), even though the
|
||||
// wiki claimed 'tls' was "more secure than standard LDAPS" (untrue);
|
||||
// - the documented value 'true' NEVER worked: settings_get() JSON-parses
|
||||
// the env string 'true' into boolean true, which matched neither 'ssl'
|
||||
// nor 'tls', so WeKan silently connected WITHOUT encryption;
|
||||
// - any other value (typos, 'TRUE', 'StartTLS', ...) also silently meant
|
||||
// "no encryption".
|
||||
//
|
||||
// normalizeLdapEncryption() maps every raw LDAP_ENCRYPTION value onto one of
|
||||
// three explicit connection modes and, where appropriate, a warning for the
|
||||
// admin. It never throws and never silently guesses:
|
||||
//
|
||||
// raw value (case-insensitive) -> mode warning
|
||||
// -----------------------------------------------------------------------
|
||||
// 'true' / boolean true -> 'tls' - (LDAPS)
|
||||
// 'ssl' (legacy) -> 'tls' deprecation: use 'true'
|
||||
// 'starttls' -> 'starttls' -
|
||||
// 'tls' (legacy) -> 'starttls' deprecation: use 'starttls'
|
||||
// 'false' / boolean false / '' /
|
||||
// undefined / null -> 'off' -
|
||||
// anything else -> 'off' clear warning listing the
|
||||
// accepted values
|
||||
//
|
||||
// Backwards compatibility: the legacy values keep their historical meaning
|
||||
// ('ssl' -> LDAPS, 'tls' -> STARTTLS); they only gain a one-line deprecation
|
||||
// notice. Unknown values still result in an unencrypted connection (as
|
||||
// before), but now log loudly instead of failing silent.
|
||||
//
|
||||
// The function is dependency-free (no Meteor, no Log) so it can be unit
|
||||
// tested with plain Node; the caller (ldap.js) decides how to emit warnings.
|
||||
//
|
||||
// CommonJS module.exports so it can be `import`ed by the ecmascript package
|
||||
// and `require`d directly by the plain-Node unit test.
|
||||
|
||||
const ACCEPTED_VALUES_HELP =
|
||||
"accepted values are 'true' (LDAPS), 'starttls' (STARTTLS) and 'false' (no encryption); " +
|
||||
"the legacy values 'ssl' (same as 'true') and 'tls' (same as 'starttls') also still work";
|
||||
|
||||
function normalizeLdapEncryption(value) {
|
||||
// settings_get() JSON-parses 'true'/'false' env strings into booleans, so
|
||||
// accept booleans as well as strings.
|
||||
if (value === true) {
|
||||
return { mode: 'tls' };
|
||||
}
|
||||
if (value === undefined || value === null || value === false) {
|
||||
return { mode: 'off' };
|
||||
}
|
||||
|
||||
const normalized = String(value).trim().toLowerCase();
|
||||
|
||||
switch (normalized) {
|
||||
case '':
|
||||
case 'false':
|
||||
return { mode: 'off' };
|
||||
case 'true':
|
||||
return { mode: 'tls' };
|
||||
case 'ssl':
|
||||
return {
|
||||
mode: 'tls',
|
||||
warning:
|
||||
"LDAP_ENCRYPTION='ssl' is deprecated, please use LDAP_ENCRYPTION='true' instead (both mean LDAPS; 'ssl' keeps working for now)",
|
||||
};
|
||||
case 'starttls':
|
||||
return { mode: 'starttls' };
|
||||
case 'tls':
|
||||
return {
|
||||
mode: 'starttls',
|
||||
warning:
|
||||
"LDAP_ENCRYPTION='tls' is deprecated, please use LDAP_ENCRYPTION='starttls' instead (both mean STARTTLS; 'tls' keeps working for now)",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
mode: 'off',
|
||||
warning:
|
||||
`LDAP_ENCRYPTION='${value}' is not a valid value, connecting WITHOUT encryption; ${ACCEPTED_VALUES_HELP}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { normalizeLdapEncryption, ACCEPTED_VALUES_HELP };
|
||||
@@ -1,5 +1,18 @@
|
||||
import { Client } from 'ldapts';
|
||||
import { Log } from 'meteor/logging';
|
||||
import { normalizeLdapEncryption } from './encryptionSetting';
|
||||
import { buildUserIdFilter } from './userIdFilter';
|
||||
|
||||
// #4158: warn about a deprecated/invalid LDAP_ENCRYPTION value only once per
|
||||
// distinct message, not on every single login attempt (LDAP instantiates a
|
||||
// new connection per login).
|
||||
const encryptionWarningsShown = new Set();
|
||||
function warnOnceAboutEncryption(warning) {
|
||||
if (warning && !encryptionWarningsShown.has(warning)) {
|
||||
encryptionWarningsShown.add(warning);
|
||||
Log.warn(warning);
|
||||
}
|
||||
}
|
||||
|
||||
// copied from https://github.com/ldapjs/node-ldapjs/blob/a113953e0d91211eb945d2a3952c84b7af6de41c/lib/filters/index.js#L167
|
||||
function escapedToHex (str) {
|
||||
@@ -53,7 +66,10 @@ export default class LDAP {
|
||||
timeout : this.constructor.settings_get('LDAP_TIMEOUT'),
|
||||
connect_timeout : this.constructor.settings_get('LDAP_CONNECT_TIMEOUT'),
|
||||
idle_timeout : this.constructor.settings_get('LDAP_IDLE_TIMEOUT'),
|
||||
encryption : this.constructor.settings_get('LDAP_ENCRYPTION'),
|
||||
// #4158: normalized to 'tls' (LDAPS), 'starttls' or 'off'. Accepts the
|
||||
// documented 'true'/'starttls'/'false' plus the legacy 'ssl'/'tls'
|
||||
// (deprecated but still working); anything else warns and means 'off'.
|
||||
encryption : normalizeLdapEncryption(this.constructor.settings_get('LDAP_ENCRYPTION')).mode,
|
||||
ca_cert : this.constructor.settings_get('LDAP_CA_CERT'),
|
||||
reject_unauthorized : this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') !== undefined ? this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') : true,
|
||||
Authentication : this.constructor.settings_get('LDAP_AUTHENTIFICATION'),
|
||||
@@ -117,8 +133,14 @@ export default class LDAP {
|
||||
tlsOptions.ca = ca;
|
||||
}
|
||||
|
||||
// #4158: surface a deprecation notice for legacy values ('ssl', 'tls')
|
||||
// and a clear warning for unknown values instead of failing silently.
|
||||
warnOnceAboutEncryption(
|
||||
normalizeLdapEncryption(this.constructor.settings_get('LDAP_ENCRYPTION')).warning,
|
||||
);
|
||||
|
||||
let url;
|
||||
if (this.options.encryption === 'ssl') {
|
||||
if (this.options.encryption === 'tls') {
|
||||
url = `ldaps://${this.options.host}:${this.options.port}`;
|
||||
} else {
|
||||
url = `ldap://${this.options.host}:${this.options.port}`;
|
||||
@@ -133,7 +155,7 @@ export default class LDAP {
|
||||
strictDN : false,
|
||||
};
|
||||
|
||||
if (this.options.encryption === 'ssl') {
|
||||
if (this.options.encryption === 'tls') {
|
||||
clientOptions.tlsOptions = tlsOptions;
|
||||
}
|
||||
|
||||
@@ -141,7 +163,7 @@ export default class LDAP {
|
||||
|
||||
this.client = new Client(clientOptions);
|
||||
|
||||
if (this.options.encryption === 'tls') {
|
||||
if (this.options.encryption === 'starttls') {
|
||||
// Set host parameter for tls.connect which is used by starttls. This shouldn't be needed in newer nodejs versions (e.g v5.6.0).
|
||||
// https://github.com/RocketChat/Rocket.Chat/issues/2035
|
||||
tlsOptions.host = this.options.host;
|
||||
@@ -322,16 +344,24 @@ export default class LDAP {
|
||||
async getUserById(id, attribute) {
|
||||
await this.bindIfNecessary();
|
||||
|
||||
const Unique_Identifier_Field = this.constructor.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD').split(',');
|
||||
|
||||
const escapedValue = hexToLdapEscaped(id);
|
||||
let filter;
|
||||
|
||||
if (attribute) {
|
||||
filter = `(${attribute}=${escapedValue})`;
|
||||
} else {
|
||||
const filters = Unique_Identifier_Field.map((item) => `(${item}=${escapedValue})`);
|
||||
filter = `(|${filters.join('')})`;
|
||||
// #4654: the stored services.ldap.id may come from LDAP_UNIQUE_IDENTIFIER_FIELD
|
||||
// or, when that is unset/empty, from LDAP_USER_SEARCH_FIELD (see
|
||||
// getLdapUserUniqueID in sync.js), so search over both attribute lists.
|
||||
// The old code read only LDAP_UNIQUE_IDENTIFIER_FIELD and crashed
|
||||
// (undefined.split) or built the invalid filter "(|(=value))" when it was
|
||||
// unset/empty, so background sync never updated existing users.
|
||||
const filter = buildUserIdFilter(
|
||||
attribute,
|
||||
escapedValue,
|
||||
this.constructor.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD'),
|
||||
this.constructor.settings_get('LDAP_USER_SEARCH_FIELD'),
|
||||
);
|
||||
|
||||
if (!filter) {
|
||||
Log.error('Can\'t search user by id: neither LDAP_UNIQUE_IDENTIFIER_FIELD nor LDAP_USER_SEARCH_FIELD is configured');
|
||||
return;
|
||||
}
|
||||
|
||||
const searchOptions = {
|
||||
@@ -463,7 +493,21 @@ export default class LDAP {
|
||||
}
|
||||
|
||||
if (this.options.group_filter_group_id_attribute !== '') {
|
||||
filter.push(`(${this.options.group_filter_group_id_attribute}=${this.options.group_filter_group_name})`);
|
||||
// #4036: LDAP_GROUP_FILTER_GROUP_NAME accepts a comma-separated list, and
|
||||
// members of LDAP_SYNC_ADMIN_GROUPS may also log in when admin sync is on
|
||||
// (previously an admin only in the admin group was locked out entirely).
|
||||
const names = String(this.options.group_filter_group_name || '')
|
||||
.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
if (this.constructor.settings_get('LDAP_SYNC_ADMIN_STATUS') === true) {
|
||||
names.push(...String(this.constructor.settings_get('LDAP_SYNC_ADMIN_GROUPS') || '')
|
||||
.split(',').map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
const clauses = names.map((n) => `(${this.options.group_filter_group_id_attribute}=${n})`);
|
||||
if (clauses.length === 1) {
|
||||
filter.push(clauses[0]);
|
||||
} else if (clauses.length > 1) {
|
||||
filter.push(`(|${clauses.join('')})`);
|
||||
}
|
||||
}
|
||||
filter.push(')');
|
||||
|
||||
|
||||
@@ -246,7 +246,10 @@ export async function syncUserData(user, ldapUser) {
|
||||
const username = slug(getLdapUsername(ldapUser));
|
||||
if (user && user._id && username !== user.username) {
|
||||
log_info('Syncing user username', user.username, '->', username);
|
||||
await Meteor.users.findOneAsync({ _id: user._id }, { $set: { username }});
|
||||
// #4654: this was findOne/findOneAsync with the $set passed as the
|
||||
// options argument, which performs no write — username changes in the
|
||||
// directory were logged as synced but never saved.
|
||||
await Meteor.users.updateAsync({ _id: user._id }, { $set: { username }});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,10 +341,12 @@ export async function addLdapUser(ldapUser, username, password) {
|
||||
userObject.ldap = true;
|
||||
userObject._id = await Accounts.createUserAsync(userObject);
|
||||
|
||||
// Add the services.ldap identifiers
|
||||
// Add the services.ldap identifiers. #4654: also persist idAttribute so
|
||||
// the background sync (getUserById in ldap.js) can search by the exact
|
||||
// attribute the id was taken from instead of guessing from settings.
|
||||
await Meteor.users.updateAsync({ _id: userObject._id }, {
|
||||
$set: {
|
||||
'services.ldap': { id: uniqueId.value },
|
||||
'services.ldap': { id: uniqueId.value, idAttribute: uniqueId.attribute },
|
||||
'emails.0.verified': true,
|
||||
'authenticationMethod': 'ldap',
|
||||
}});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
// #4654: build the LDAP search filter used to re-find an existing user by the
|
||||
// stored services.ldap.id during background sync
|
||||
// (LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED).
|
||||
//
|
||||
// The stored id is produced by getLdapUserUniqueID() in sync.js, which takes
|
||||
// the first non-empty attribute from LDAP_UNIQUE_IDENTIFIER_FIELD and falls
|
||||
// back to LDAP_USER_SEARCH_FIELD. The lookup therefore has to consider both
|
||||
// settings too. Previously getUserById() used only LDAP_UNIQUE_IDENTIFIER_FIELD:
|
||||
// when that variable was unset it crashed (undefined.split), aborting the whole
|
||||
// sync run, and when it was set but empty it produced the invalid filter
|
||||
// "(|(=value))" seen in the issue logs — either way existing users were never
|
||||
// updated after the first import ("Can't sync user").
|
||||
|
||||
// Split a comma-separated attribute list setting into non-empty names.
|
||||
// Mirrors the whitespace handling of getLdapUserUniqueID()/getBufferAttributes().
|
||||
function splitFieldSetting(value) {
|
||||
if (typeof value !== 'string' || value === '') {
|
||||
return [];
|
||||
}
|
||||
return value.replace(/\s/g, '').split(',').filter(Boolean);
|
||||
}
|
||||
|
||||
// attribute: the stored services.ldap.idAttribute when known (searched as-is);
|
||||
// escapedValue: the id value already escaped for use inside an LDAP filter;
|
||||
// uniqueIdentifierFieldSetting / userSearchFieldSetting: the raw settings values.
|
||||
// Returns the filter string, or null when no usable attribute is configured.
|
||||
function buildUserIdFilter(attribute, escapedValue, uniqueIdentifierFieldSetting, userSearchFieldSetting) {
|
||||
if (attribute) {
|
||||
return `(${attribute}=${escapedValue})`;
|
||||
}
|
||||
|
||||
const fields = splitFieldSetting(uniqueIdentifierFieldSetting)
|
||||
.concat(splitFieldSetting(userSearchFieldSetting));
|
||||
const uniqueFields = [...new Set(fields)];
|
||||
|
||||
if (uniqueFields.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const filters = uniqueFields.map((field) => `(${field}=${escapedValue})`);
|
||||
return filters.length === 1 ? filters[0] : `(|${filters.join('')})`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
splitFieldSetting,
|
||||
buildUserIdFilter,
|
||||
};
|
||||
@@ -3,8 +3,7 @@
|
||||
// objString = ["Org","Team"] for method mapping
|
||||
async function createObject(initArr, objString)
|
||||
{
|
||||
functionName = objString === "Org" ? 'setCreateOrgFromOidc' : 'setCreateTeamFromOidc';
|
||||
creationString = 'setCreate'+ objString + 'FromOidc';
|
||||
const functionName = objString === "Org" ? 'setCreateOrgFromOidc' : 'setCreateTeamFromOidc';
|
||||
return await Meteor.callAsync(functionName,
|
||||
initArr[0],//displayName
|
||||
initArr[1],//desc
|
||||
@@ -15,7 +14,7 @@ async function createObject(initArr, objString)
|
||||
}
|
||||
async function updateObject(initArr, objString)
|
||||
{
|
||||
functionName = objString === "Org" ? 'setOrgAllFieldsFromOidc' : 'setTeamAllFieldsFromOidc';
|
||||
const functionName = objString === "Org" ? 'setOrgAllFieldsFromOidc' : 'setTeamAllFieldsFromOidc';
|
||||
return await Meteor.callAsync(functionName,
|
||||
initArr[0],//team || org Object
|
||||
initArr[1],//displayName
|
||||
@@ -32,7 +31,7 @@ async function updateObject(initArr, objString)
|
||||
//e.g. collection = "team"
|
||||
function contains(userObjs, obj, collection)
|
||||
{
|
||||
id = collection+'Id';
|
||||
const id = collection+'Id';
|
||||
|
||||
if(typeof userObjs == "undefined" || !userObjs.length)
|
||||
{
|
||||
@@ -98,26 +97,33 @@ oauth2AdminStatusFromGroups: function (groups)
|
||||
// isAdmin: [true, false] -> admin group becomes admin in wekan
|
||||
// isOrganization: [true, false] -> creates org and adds to user
|
||||
// displayName: "string"
|
||||
// #4897: every variable in here used to be an implicit GLOBAL (teamArray,
|
||||
// orgArray, isAdmin, teams, orgs, group, org, team, ...) shared by all
|
||||
// concurrent OIDC logins. This function awaits inside its loop, so two logins
|
||||
// interleaved and pushed each other's teams/orgs/admin flags onto the same
|
||||
// arrays before writing them to the wrong user document. All state is local
|
||||
// now, and the collection is addressed as Meteor.users instead of relying on
|
||||
// a `users` global leaked by the caller.
|
||||
addGroupsWithAttributes: async function (user, groups){
|
||||
teamArray=[];
|
||||
orgArray=[];
|
||||
isAdmin = [];
|
||||
teams = user.teams;
|
||||
orgs = user.orgs;
|
||||
for (group of groups)
|
||||
const teamArray=[];
|
||||
const orgArray=[];
|
||||
const isAdmin = [];
|
||||
const teams = user.teams;
|
||||
const orgs = user.orgs;
|
||||
for (const group of groups)
|
||||
{
|
||||
initAttributes = [
|
||||
const initAttributes = [
|
||||
group.displayName,
|
||||
group.desc || group.displayName,
|
||||
group.shortName ||group.displayName,
|
||||
group.website || group.displayName, group.isActive || false];
|
||||
|
||||
isOrg = group.isOrganisation || false;
|
||||
forceCreate = group.forceCreate|| false;
|
||||
const isOrg = group.isOrganisation || false;
|
||||
const forceCreate = group.forceCreate|| false;
|
||||
isAdmin.push(group.isAdmin || false);
|
||||
if (isOrg)
|
||||
{
|
||||
org = await Org.findOneAsync({"orgDisplayName": group.displayName});
|
||||
let org = await Org.findOneAsync({"orgDisplayName": group.displayName});
|
||||
if(org)
|
||||
{
|
||||
if(contains(orgs, org, "org"))
|
||||
@@ -136,14 +142,14 @@ addGroupsWithAttributes: async function (user, groups){
|
||||
{
|
||||
continue;
|
||||
}
|
||||
orgHash = {'orgId': org._id, 'orgDisplayName': group.displayName};
|
||||
const orgHash = {'orgId': org._id, 'orgDisplayName': group.displayName};
|
||||
orgArray.push(orgHash);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
//start team routine
|
||||
team = await Team.findOneAsync({"teamDisplayName": group.displayName});
|
||||
let team = await Team.findOneAsync({"teamDisplayName": group.displayName});
|
||||
if (team)
|
||||
{
|
||||
if(contains(teams, team, "team"))
|
||||
@@ -162,7 +168,7 @@ addGroupsWithAttributes: async function (user, groups){
|
||||
{
|
||||
continue;
|
||||
}
|
||||
teamHash = {'teamId': team._id, 'teamDisplayName': group.displayName};
|
||||
const teamHash = {'teamId': team._id, 'teamDisplayName': group.displayName};
|
||||
teamArray.push(teamHash);
|
||||
}
|
||||
}
|
||||
@@ -170,32 +176,33 @@ addGroupsWithAttributes: async function (user, groups){
|
||||
// hence user will get admin privileges in wekan
|
||||
// E.g. Admin rights will be withdrawn if no group in oidc provider has isAdmin set to true
|
||||
|
||||
await users.updateAsync({ _id: user._id }, { $set: {isAdmin: isAdmin.some(i => (i === true))}});
|
||||
teams = {'teams': {'$each': teamArray}};
|
||||
orgs = {'orgs': {'$each': orgArray}};
|
||||
await users.updateAsync({ _id: user._id }, { $push: teams});
|
||||
await users.updateAsync({ _id: user._id }, { $push: orgs});
|
||||
await Meteor.users.updateAsync({ _id: user._id }, { $set: {isAdmin: isAdmin.some(i => (i === true))}});
|
||||
await Meteor.users.updateAsync({ _id: user._id }, { $push: {'teams': {'$each': teamArray}}});
|
||||
await Meteor.users.updateAsync({ _id: user._id }, { $push: {'orgs': {'$each': orgArray}}});
|
||||
// remove temporary oidc data from user collection
|
||||
await users.updateAsync({ _id: user._id }, { $unset: {"services.oidc.groups": []}});
|
||||
await Meteor.users.updateAsync({ _id: user._id }, { $unset: {"services.oidc.groups": []}});
|
||||
|
||||
return;
|
||||
},
|
||||
|
||||
changeUsername: async function(user, name)
|
||||
{
|
||||
username = {'username': name};
|
||||
if (user.username != username) await users.updateAsync({ _id: user._id }, { $set: username});
|
||||
// #4897: `username` was an implicit global; use a local and update via
|
||||
// Meteor.users so this no longer depends on a leaked `users` global.
|
||||
if (user.username !== name) await Meteor.users.updateAsync({ _id: user._id }, { $set: {'username': name}});
|
||||
},
|
||||
changeFullname: async function(user, name)
|
||||
{
|
||||
username = {'profile.fullname': name};
|
||||
if (user.username != username) await users.updateAsync({ _id: user._id }, { $set: username});
|
||||
if ((user.profile || {}).fullname !== name) await Meteor.users.updateAsync({ _id: user._id }, { $set: {'profile.fullname': name}});
|
||||
},
|
||||
addEmail: async function(user, email)
|
||||
{
|
||||
user_email = user.emails || [];
|
||||
var contained = false;
|
||||
position = 0;
|
||||
// #4897: `user_email` and `position` were implicit globals shared between
|
||||
// concurrent logins — one login's email list could be spliced/unshifted by
|
||||
// another login before being $set on this user's document.
|
||||
let user_email = user.emails || [];
|
||||
let contained = false;
|
||||
let position = 0;
|
||||
for (const [count, mail_hash] of Object.entries(user_email))
|
||||
{
|
||||
if (mail_hash['address'] === email)
|
||||
@@ -213,8 +220,7 @@ addEmail: async function(user, email)
|
||||
if(!contained)
|
||||
{
|
||||
user_email.unshift({'address': email, 'verified': true});
|
||||
user_email = {'emails': user_email};
|
||||
await users.updateAsync({ _id: user._id }, { $set: user_email});
|
||||
await Meteor.users.updateAsync({ _id: user._id }, { $set: {'emails': user_email}});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,29 @@ Oidc.requestCredential = function (options, credentialRequestCompleteCallback) {
|
||||
if (result) {
|
||||
var config = result;
|
||||
var credentialToken = Random.secret();
|
||||
var loginStyle = OAuth._loginStyle('oidc', config, options);
|
||||
// options
|
||||
options = options || {};
|
||||
// Fix #5695: OAUTH2_LOGIN_STYLE=redirect was never honored. The
|
||||
// useraccounts social-login button always passes
|
||||
// { loginStyle: 'popup' } (its client-side socialLoginStyle default),
|
||||
// and OAuth._loginStyle() lets a caller option override the loginStyle
|
||||
// stored in the service configuration. The admin's OAUTH2_LOGIN_STYLE
|
||||
// env var is authoritative for redirect: when the service is configured
|
||||
// with loginStyle 'redirect', drop the generic popup default so the
|
||||
// full-page redirect flow is used. An explicit
|
||||
// { loginStyle: 'redirect' } from a caller (the OIDC_REDIRECTION_ENABLED
|
||||
// auto-login) keeps working regardless of the configured style, and
|
||||
// popup remains the default when OAUTH2_LOGIN_STYLE is unset or popup.
|
||||
if (config.loginStyle === 'redirect') {
|
||||
options.loginStyle = 'redirect';
|
||||
}
|
||||
// OAuth._loginStyle still falls back to popup when sessionStorage is
|
||||
// unavailable (e.g. Safari private mode), which the redirect flow needs.
|
||||
var loginStyle = OAuth._loginStyle('oidc', config, options);
|
||||
// loginStyle is a Meteor-internal choice, not an OAuth2/OIDC parameter;
|
||||
// don't leak it to the provider in the authorization URL built below
|
||||
// (the URL used to contain "...&loginStyle=popup&...", see #5695).
|
||||
delete options.loginStyle;
|
||||
options.client_id = config.clientId;
|
||||
options.response_type = options.response_type || 'code';
|
||||
options.redirect_uri = OAuth._redirectUri('oidc', config);
|
||||
|
||||
@@ -18,13 +18,23 @@ if (process.env.OAUTH2_CA_CERT !== undefined) {
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
var profile = {};
|
||||
var serviceData = {};
|
||||
var userinfo = {};
|
||||
|
||||
OAuth.registerService('oidc', 2, null, async function (query) {
|
||||
var debug = process.env.DEBUG === 'true';
|
||||
|
||||
// #4897: these MUST be fresh per-login objects. They used to be module-level
|
||||
// (`var serviceData = {}` etc. shared by every login of every user), so:
|
||||
// * fields a login did not overwrite leaked in from the PREVIOUS login of a
|
||||
// DIFFERENT user (e.g. refreshToken is only set when the provider sends
|
||||
// one, and idTokenWhitelistFields were Object.assign-ed cumulatively), and
|
||||
// * two logins running concurrently (this handler awaits the token,
|
||||
// userinfo and two Meteor.callAsync calls) interleaved writes to the SAME
|
||||
// object, so a user could intermittently be created/updated with another
|
||||
// user's id/email/username — the "web interface shows different data than
|
||||
// MongoDB" reports.
|
||||
var profile = {};
|
||||
var serviceData = {};
|
||||
var userinfo = {};
|
||||
|
||||
var token = await getToken(query);
|
||||
if (debug) console.log('XXX: register token:', token);
|
||||
|
||||
@@ -121,7 +131,8 @@ OAuth.registerService('oidc', 2, null, async function (query) {
|
||||
// therefore: keep admin privileges for wekan as before
|
||||
if(Array.isArray(serviceData.groups) && serviceData.groups.length && typeof serviceData.groups[0] === "string" )
|
||||
{
|
||||
user = await Meteor.users.findOneAsync({'_id': serviceData.id});
|
||||
// #4897: `user` was an implicit global shared by concurrent logins.
|
||||
const user = await Meteor.users.findOneAsync({'_id': serviceData.id});
|
||||
|
||||
serviceData.groups.forEach(function(groupName, i)
|
||||
{
|
||||
@@ -373,8 +384,11 @@ Meteor.methods({
|
||||
|
||||
var propagateOidcData = process.env.PROPAGATE_OIDC_DATA || false;
|
||||
if (propagateOidcData) {
|
||||
users= Meteor.users;
|
||||
user = await users.findOneAsync({'services.oidc.id': userId});
|
||||
// #4897: `users`/`user` were implicit globals shared by concurrent
|
||||
// logins; between the awaits below another login could reassign `user`,
|
||||
// so this login's email/fullname/username got written onto ANOTHER
|
||||
// user's document. loginHandler.js now uses Meteor.users directly.
|
||||
const user = await Meteor.users.findOneAsync({'services.oidc.id': userId});
|
||||
|
||||
if(user) {
|
||||
//updates/creates Groups and user admin privileges accordingly if not undefined
|
||||
|
||||
+39
-11
@@ -3,7 +3,7 @@
|
||||
|
||||
<head>
|
||||
<meta charset="utf8" />
|
||||
<title>WeKan REST API v9.96</title>
|
||||
<title>WeKan REST API v9.97</title>
|
||||
<!-- needed for adaptive design -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
@@ -423,7 +423,7 @@ data-styled.g139[id="sc-iIvZUO"]{content:"kAmnlO,"}/*!sc*/
|
||||
55.627 l 55.6165,55.627 -231.245496,231.24803 c -127.185,127.1864
|
||||
-231.5279,231.248 -231.873,231.248 -0.3451,0 -104.688,
|
||||
-104.0616 -231.873,-231.248 z
|
||||
" fill="currentColor"></path></g></svg></div></div><div class="sc-jtyQFi ldXCvc api-content"><div class="sc-eCQgVK jleRXN"><div class="sc-iCECmn lhRBUS"><div class="sc-hKVpXn kktglN api-info"><h1 class="sc-fuztkK sc-ctiVdb eRMVDe cBgvIi">Wekan REST API<!-- --> <span>(<!-- -->v9.96<!-- -->)</span></h1><p>Download OpenAPI specification<!-- -->:</p><div class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"></div><div data-role="redoc-summary" html="" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"></div><div data-role="redoc-description" html="<p>The REST API allows you to control and extend Wekan with ease.</p>
|
||||
" fill="currentColor"></path></g></svg></div></div><div class="sc-jtyQFi ldXCvc api-content"><div class="sc-eCQgVK jleRXN"><div class="sc-iCECmn lhRBUS"><div class="sc-hKVpXn kktglN api-info"><h1 class="sc-fuztkK sc-ctiVdb eRMVDe cBgvIi">Wekan REST API<!-- --> <span>(<!-- -->v9.97<!-- -->)</span></h1><p>Download OpenAPI specification<!-- -->:</p><div class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"></div><div data-role="redoc-summary" html="" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"></div><div data-role="redoc-description" html="<p>The REST API allows you to control and extend Wekan with ease.</p>
|
||||
<p>If you are an end-user and not a dev or a tester, <a href="https://github.com/wekan/wekan/issues/new">create an issue</a> to request new APIs.</p>
|
||||
<blockquote>
|
||||
<p>All API calls in the documentation are made using <code>curl</code>. However, you are free to use Java / Python / PHP / Golang / Ruby / Swift / Objective-C / Rust / Scala / C# or any other programming languages.</p>
|
||||
@@ -1632,9 +1632,19 @@ e.g. <code>{ "created": 3, "cardIds": ["abc", &quo
|
||||
</div></div></div></td></tr></tbody></table></div><div><h3 class="sc-fINhYD hgNHCh">Responses</h3><div><button class="sc-cbuLjy iSTZHA"><svg class="sc-dYjPD gngmNp" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg><strong class="sc-fXmTIC cqDULz">200<!-- --> </strong><div html="<p>200 response</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa sc-ciCrSJ fiNpIH dNfUH dDDioG"><p>200 response</p>
|
||||
</div></button></div></div></div><div class="sc-jSppWd sc-gKkgUA fpMlmc bdQQyo"><div class="sc-fXwuWv fYxpnv"><button class="sc-jWMFtl jzaJhV"><span type="get" class="sc-eEFuoE hlSrtW http-verb get">get</span><span class="sc-FpjRO dsIRaZ">/api/boards/{board}/rules</span><svg class="sc-dYjPD bQKUih" style="margin-right:-25px" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></button><div aria-hidden="true" class="sc-fmtEmb tUxhh"><div class="sc-ljIcGq bAnPPh"><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"></div><div tabindex="0" role="button"><div class="sc-jlJOIR PEJyb"><span></span>/api/boards/{board}/rules</div></div></div></div></div><div><h3 class="sc-kEbgWM iamDfj"> <!-- -->Response samples<!-- --> </h3><div class="sc-cxxQMU kibfTX" data-rttabs="true"><ul class="react-tabs__tab-list" role="tablist"><li class="tab-success react-tabs__tab--selected" role="tab" id="tab_R_9p5cq_0" aria-selected="true" aria-disabled="false" aria-controls="panel_R_9p5cq_0" tabindex="0" data-rttab="true">200</li></ul><div class="react-tabs__tab-panel react-tabs__tab-panel--selected" role="tabpanel" id="panel_R_9p5cq_0" aria-labelledby="tab_R_9p5cq_0"><div><div class="sc-cNSlRw bMFMGt"><span class="sc-bBzIOb BuCyN">Content type</span><div class="sc-dPqFhK kgKexQ">application/json</div></div><div class="sc-hUheUT jUCYlq"><div class="sc-cTZdpT hHzuQA"><div class="sc-giQkEn dzKJV"><button><div class="sc-jcgtOs feYhXE">Copy</div></button><button> Expand all </button><button> Collapse all </button></div><div tabindex="0" class="sc-iJSMbW fiNpIH sc-jNDflC jgTAJz"><div class="redoc-json"><code><button class="collapser" aria-label="collapse"></button><span class="token punctuation">[</span><span class="ellipsis"></span><ul class="array collapsible"><li><div class="hoverable "><button class="collapser" aria-label="collapse"></button><span class="token punctuation">{</span><span class="ellipsis"></span><ul class="obj collapsible"><li><div class="hoverable collapsed"><span class="property token string">"_id"</span>: <span class="token string">"string"</span><span class="token punctuation">,</span></div></li><li><div class="hoverable collapsed"><span class="property token string">"title"</span>: <span class="token string">"string"</span><span class="token punctuation">,</span></div></li><li><div class="hoverable collapsed"><span class="property token string">"trigger"</span>: <span class="token punctuation">{ }</span><span class="token punctuation">,</span></div></li><li><div class="hoverable collapsed"><span class="property token string">"action"</span>: <span class="token punctuation">{ }</span></div></li></ul><span class="token punctuation">}</span></div></li></ul><span class="token punctuation">]</span></code></div></div></div></div></div></div></div></div></div></div></div><div id="tag/Rules/operation/new_board_rule" data-section-id="tag/Rules/operation/new_board_rule" class="sc-eCQgVK grDwca"><div data-section-id="operation/new_board_rule" id="operation/new_board_rule" class="sc-iCECmn lhRBUS"><div class="sc-hKVpXn kktglN"><h2 class="sc-qdQOe MOVBZ"><a class="sc-crPgjm jmoZom" href="#tag/Rules/operation/new_board_rule" aria-label="tag/Rules/operation/new_board_rule"></a>Add an automation rule to a board<!-- --> </h2><div class="sc-iFUzrA ktZmcf"><div html="<p>The trigger and action are embedded inline. See the Rules
|
||||
documentation for the available trigger activityTypes and action actionTypes.</p>
|
||||
documentation for the available trigger activityTypes and action actionTypes.
|
||||
Trigger matching fields that are omitted (e.g. userId, listName,
|
||||
swimlaneName, cardTitle) default to the &#39;*&#39; wildcard, so e.g. issue #2674&#39;s
|
||||
&quot;remove a member when a card is moved away from a list&quot; only needs
|
||||
trigger {activityType: &#39;moveCard&#39;, oldListName: &#39;...&#39;} and
|
||||
action {actionType: &#39;removeMember&#39;, username: &#39;...&#39;}.</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"><p>The trigger and action are embedded inline. See the Rules
|
||||
documentation for the available trigger activityTypes and action actionTypes.</p>
|
||||
documentation for the available trigger activityTypes and action actionTypes.
|
||||
Trigger matching fields that are omitted (e.g. userId, listName,
|
||||
swimlaneName, cardTitle) default to the '*' wildcard, so e.g. issue #2674's
|
||||
"remove a member when a card is moved away from a list" only needs
|
||||
trigger {activityType: 'moveCard', oldListName: '...'} and
|
||||
action {actionType: 'removeMember', username: '...'}.</p>
|
||||
</div></div><div class="sc-fuYIqi kGZLat"><div class="sc-dalEhJ jdqJPb"><h5 class="sc-iqkkDd sc-jQQpTv kcvrhp kEkHzF">Authorizations:</h5><svg class="sc-dYjPD bEEWJa" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></div><div class="sc-jTPGds cVAkzL"><span class="sc-dtnsVa dVYuXz"><span class="sc-hPfayn hzxDQO"><i>UserSecurity</i></span></span></div></div><div><h5 class="sc-iqkkDd kcvrhp">path<!-- --> Parameters</h5><table class="sc-hHopjF bsjUmE"><tbody><tr class="last "><td kind="field" title="board" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">board</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the board ID</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"><p>the board ID</p>
|
||||
</div></div></div></td></tr></tbody></table></div><h5 class="sc-iqkkDd kcvrhp">Request Body schema: <span class="sc-gXvOjn kxMqOs">multipart/form-data</span><div class="sc-gSILEF sc-eIYgEQ sc-dTCDEk jMRTsl dHYagA bxWqzP">required</div></h5><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"></div><table class="sc-hHopjF bsjUmE"><tbody><tr class=""><td kind="field" title="title" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">title</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the rule title</p>
|
||||
@@ -1646,9 +1656,19 @@ e.g. <code>{ "created": 3, "cardIds": ["abc", &quo
|
||||
</div></div></div></td></tr></tbody></table><div><h3 class="sc-fINhYD hgNHCh">Responses</h3><div><button class="sc-cbuLjy iSTZHA"><svg class="sc-dYjPD gngmNp" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg><strong class="sc-fXmTIC cqDULz">200<!-- --> </strong><div html="<p>200 response</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa sc-ciCrSJ fiNpIH dNfUH dDDioG"><p>200 response</p>
|
||||
</div></button></div></div></div><div class="sc-jSppWd sc-gKkgUA fpMlmc bdQQyo"><div class="sc-fXwuWv fYxpnv"><button class="sc-jWMFtl jzaJhV"><span type="post" class="sc-eEFuoE hOENFc http-verb post">post</span><span class="sc-FpjRO dsIRaZ">/api/boards/{board}/rules</span><svg class="sc-dYjPD bQKUih" style="margin-right:-25px" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></button><div aria-hidden="true" class="sc-fmtEmb tUxhh"><div class="sc-ljIcGq bAnPPh"><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"></div><div tabindex="0" role="button"><div class="sc-jlJOIR PEJyb"><span></span>/api/boards/{board}/rules</div></div></div></div></div><div><h3 class="sc-kEbgWM iamDfj"> <!-- -->Response samples<!-- --> </h3><div class="sc-cxxQMU kibfTX" data-rttabs="true"><ul class="react-tabs__tab-list" role="tablist"><li class="tab-success react-tabs__tab--selected" role="tab" id="tab_R_9p7cq_0" aria-selected="true" aria-disabled="false" aria-controls="panel_R_9p7cq_0" tabindex="0" data-rttab="true">200</li></ul><div class="react-tabs__tab-panel react-tabs__tab-panel--selected" role="tabpanel" id="panel_R_9p7cq_0" aria-labelledby="tab_R_9p7cq_0"><div><div class="sc-cNSlRw bMFMGt"><span class="sc-bBzIOb BuCyN">Content type</span><div class="sc-dPqFhK kgKexQ">application/json</div></div><div class="sc-hUheUT jUCYlq"><div class="sc-cTZdpT hHzuQA"><div class="sc-giQkEn dzKJV"><button><div class="sc-jcgtOs feYhXE">Copy</div></button></div><div tabindex="0" class="sc-iJSMbW fiNpIH sc-jNDflC jgTAJz"><div class="redoc-json"><code><button class="collapser" aria-label="collapse"></button><span class="token punctuation">{</span><span class="ellipsis"></span><ul class="obj collapsible"><li><div class="hoverable "><span class="property token string">"_id"</span>: <span class="token string">"string"</span><span class="token punctuation">,</span></div></li><li><div class="hoverable "><span class="property token string">"triggerId"</span>: <span class="token string">"string"</span><span class="token punctuation">,</span></div></li><li><div class="hoverable "><span class="property token string">"actionId"</span>: <span class="token string">"string"</span></div></li></ul><span class="token punctuation">}</span></code></div></div></div></div></div></div></div></div></div></div></div><div id="tag/Rules/operation/new_board_rule" data-section-id="tag/Rules/operation/new_board_rule" class="sc-eCQgVK grDwca"><div data-section-id="operation/new_board_rule" id="operation/new_board_rule" class="sc-iCECmn lhRBUS"><div class="sc-hKVpXn kktglN"><h2 class="sc-qdQOe MOVBZ"><a class="sc-crPgjm jmoZom" href="#tag/Rules/operation/new_board_rule" aria-label="tag/Rules/operation/new_board_rule"></a>Add an automation rule to a board<!-- --> </h2><div class="sc-iFUzrA ktZmcf"><div html="<p>The trigger and action are embedded inline. See the Rules
|
||||
documentation for the available trigger activityTypes and action actionTypes.</p>
|
||||
documentation for the available trigger activityTypes and action actionTypes.
|
||||
Trigger matching fields that are omitted (e.g. userId, listName,
|
||||
swimlaneName, cardTitle) default to the &#39;*&#39; wildcard, so e.g. issue #2674&#39;s
|
||||
&quot;remove a member when a card is moved away from a list&quot; only needs
|
||||
trigger {activityType: &#39;moveCard&#39;, oldListName: &#39;...&#39;} and
|
||||
action {actionType: &#39;removeMember&#39;, username: &#39;...&#39;}.</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"><p>The trigger and action are embedded inline. See the Rules
|
||||
documentation for the available trigger activityTypes and action actionTypes.</p>
|
||||
documentation for the available trigger activityTypes and action actionTypes.
|
||||
Trigger matching fields that are omitted (e.g. userId, listName,
|
||||
swimlaneName, cardTitle) default to the '*' wildcard, so e.g. issue #2674's
|
||||
"remove a member when a card is moved away from a list" only needs
|
||||
trigger {activityType: 'moveCard', oldListName: '...'} and
|
||||
action {actionType: 'removeMember', username: '...'}.</p>
|
||||
</div></div><div class="sc-fuYIqi kGZLat"><div class="sc-dalEhJ jdqJPb"><h5 class="sc-iqkkDd sc-jQQpTv kcvrhp kEkHzF">Authorizations:</h5><svg class="sc-dYjPD bEEWJa" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></div><div class="sc-jTPGds cVAkzL"><span class="sc-dtnsVa dVYuXz"><span class="sc-hPfayn hzxDQO"><i>UserSecurity</i></span></span></div></div><div><h5 class="sc-iqkkDd kcvrhp">path<!-- --> Parameters</h5><table class="sc-hHopjF bsjUmE"><tbody><tr class="last "><td kind="field" title="board" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">board</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the board ID</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"><p>the board ID</p>
|
||||
</div></div></div></td></tr></tbody></table></div><h5 class="sc-iqkkDd kcvrhp">Request Body schema: <span class="sc-gXvOjn kxMqOs">multipart/form-data</span><div class="sc-gSILEF sc-eIYgEQ sc-dTCDEk jMRTsl dHYagA bxWqzP">required</div></h5><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"></div><table class="sc-hHopjF bsjUmE"><tbody><tr class=""><td kind="field" title="title" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">title</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the rule title</p>
|
||||
@@ -1672,9 +1692,13 @@ e.g. <code>{ "created": 3, "cardIds": ["abc", &quo
|
||||
</div></div></div></td></tr></tbody></table></div><div><h3 class="sc-fINhYD hgNHCh">Responses</h3><div><button class="sc-cbuLjy iSTZHA"><svg class="sc-dYjPD gngmNp" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg><strong class="sc-fXmTIC cqDULz">200<!-- --> </strong><div html="<p>200 response</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa sc-ciCrSJ fiNpIH dNfUH dDDioG"><p>200 response</p>
|
||||
</div></button></div></div></div><div class="sc-jSppWd sc-gKkgUA fpMlmc bdQQyo"><div class="sc-fXwuWv fYxpnv"><button class="sc-jWMFtl jzaJhV"><span type="get" class="sc-eEFuoE hlSrtW http-verb get">get</span><span class="sc-FpjRO dsIRaZ">/api/boards/{board}/rules/{rule}</span><svg class="sc-dYjPD bQKUih" style="margin-right:-25px" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></button><div aria-hidden="true" class="sc-fmtEmb tUxhh"><div class="sc-ljIcGq bAnPPh"><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"></div><div tabindex="0" role="button"><div class="sc-jlJOIR PEJyb"><span></span>/api/boards/{board}/rules/{rule}</div></div></div></div></div><div><h3 class="sc-kEbgWM iamDfj"> <!-- -->Response samples<!-- --> </h3><div class="sc-cxxQMU kibfTX" data-rttabs="true"><ul class="react-tabs__tab-list" role="tablist"><li class="tab-success react-tabs__tab--selected" role="tab" id="tab_R_9pdcq_0" aria-selected="true" aria-disabled="false" aria-controls="panel_R_9pdcq_0" tabindex="0" data-rttab="true">200</li></ul><div class="react-tabs__tab-panel react-tabs__tab-panel--selected" role="tabpanel" id="panel_R_9pdcq_0" aria-labelledby="tab_R_9pdcq_0"><div><div class="sc-cNSlRw bMFMGt"><span class="sc-bBzIOb BuCyN">Content type</span><div class="sc-dPqFhK kgKexQ">application/json</div></div><div class="sc-hUheUT jUCYlq"><div class="sc-cTZdpT hHzuQA"><div class="sc-giQkEn dzKJV"><button><div class="sc-jcgtOs feYhXE">Copy</div></button><button> Expand all </button><button> Collapse all </button></div><div tabindex="0" class="sc-iJSMbW fiNpIH sc-jNDflC jgTAJz"><div class="redoc-json"><code><button class="collapser" aria-label="collapse"></button><span class="token punctuation">{</span><span class="ellipsis"></span><ul class="obj collapsible"><li><div class="hoverable "><span class="property token string">"_id"</span>: <span class="token string">"string"</span><span class="token punctuation">,</span></div></li><li><div class="hoverable "><span class="property token string">"title"</span>: <span class="token string">"string"</span><span class="token punctuation">,</span></div></li><li><div class="hoverable "><span class="property token string">"trigger"</span>: <span class="token punctuation">{ }</span><span class="token punctuation">,</span></div></li><li><div class="hoverable "><span class="property token string">"action"</span>: <span class="token punctuation">{ }</span></div></li></ul><span class="token punctuation">}</span></code></div></div></div></div></div></div></div></div></div></div></div><div id="tag/Rules/operation/edit_board_rule" data-section-id="tag/Rules/operation/edit_board_rule" class="sc-eCQgVK grDwca"><div data-section-id="operation/edit_board_rule" id="operation/edit_board_rule" class="sc-iCECmn lhRBUS"><div class="sc-hKVpXn kktglN"><h2 class="sc-qdQOe MOVBZ"><a class="sc-crPgjm jmoZom" href="#tag/Rules/operation/edit_board_rule" aria-label="tag/Rules/operation/edit_board_rule"></a>Edit an automation rule<!-- --> </h2><div class="sc-iFUzrA ktZmcf"><div html="<p>Any of title, trigger and action may be supplied; the trigger
|
||||
and action documents are replaced ($set) when present.</p>
|
||||
and action documents are replaced ($set) when present. A supplied trigger
|
||||
that includes an activityType gets its missing matching fields defaulted
|
||||
to the &#39;*&#39; wildcard, like on creation.</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"><p>Any of title, trigger and action may be supplied; the trigger
|
||||
and action documents are replaced ($set) when present.</p>
|
||||
and action documents are replaced ($set) when present. A supplied trigger
|
||||
that includes an activityType gets its missing matching fields defaulted
|
||||
to the '*' wildcard, like on creation.</p>
|
||||
</div></div><div class="sc-fuYIqi kGZLat"><div class="sc-dalEhJ jdqJPb"><h5 class="sc-iqkkDd sc-jQQpTv kcvrhp kEkHzF">Authorizations:</h5><svg class="sc-dYjPD bEEWJa" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></div><div class="sc-jTPGds cVAkzL"><span class="sc-dtnsVa dVYuXz"><span class="sc-hPfayn hzxDQO"><i>UserSecurity</i></span></span></div></div><div><h5 class="sc-iqkkDd kcvrhp">path<!-- --> Parameters</h5><table class="sc-hHopjF bsjUmE"><tbody><tr class=""><td kind="field" title="board" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">board</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the board ID</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"><p>the board ID</p>
|
||||
</div></div></div></td></tr><tr class="last "><td kind="field" title="rule" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">rule</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the rule ID</p>
|
||||
@@ -1688,9 +1712,13 @@ e.g. <code>{ "created": 3, "cardIds": ["abc", &quo
|
||||
</div></div></div></td></tr></tbody></table><div><h3 class="sc-fINhYD hgNHCh">Responses</h3><div><button class="sc-cbuLjy iSTZHA"><svg class="sc-dYjPD gngmNp" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg><strong class="sc-fXmTIC cqDULz">200<!-- --> </strong><div html="<p>200 response</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa sc-ciCrSJ fiNpIH dNfUH dDDioG"><p>200 response</p>
|
||||
</div></button></div></div></div><div class="sc-jSppWd sc-gKkgUA fpMlmc bdQQyo"><div class="sc-fXwuWv fYxpnv"><button class="sc-jWMFtl jzaJhV"><span type="put" class="sc-eEFuoE dQBYof http-verb put">put</span><span class="sc-FpjRO dsIRaZ">/api/boards/{board}/rules/{rule}</span><svg class="sc-dYjPD bQKUih" style="margin-right:-25px" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></button><div aria-hidden="true" class="sc-fmtEmb tUxhh"><div class="sc-ljIcGq bAnPPh"><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"></div><div tabindex="0" role="button"><div class="sc-jlJOIR PEJyb"><span></span>/api/boards/{board}/rules/{rule}</div></div></div></div></div><div><h3 class="sc-kEbgWM iamDfj"> <!-- -->Response samples<!-- --> </h3><div class="sc-cxxQMU kibfTX" data-rttabs="true"><ul class="react-tabs__tab-list" role="tablist"><li class="tab-success react-tabs__tab--selected" role="tab" id="tab_R_9pfcq_0" aria-selected="true" aria-disabled="false" aria-controls="panel_R_9pfcq_0" tabindex="0" data-rttab="true">200</li></ul><div class="react-tabs__tab-panel react-tabs__tab-panel--selected" role="tabpanel" id="panel_R_9pfcq_0" aria-labelledby="tab_R_9pfcq_0"><div><div class="sc-cNSlRw bMFMGt"><span class="sc-bBzIOb BuCyN">Content type</span><div class="sc-dPqFhK kgKexQ">application/json</div></div><div class="sc-hUheUT jUCYlq"><div class="sc-cTZdpT hHzuQA"><div class="sc-giQkEn dzKJV"><button><div class="sc-jcgtOs feYhXE">Copy</div></button></div><div tabindex="0" class="sc-iJSMbW fiNpIH sc-jNDflC jgTAJz"><div class="redoc-json"><code><button class="collapser" aria-label="collapse"></button><span class="token punctuation">{</span><span class="ellipsis"></span><ul class="obj collapsible"><li><div class="hoverable "><span class="property token string">"_id"</span>: <span class="token string">"string"</span></div></li></ul><span class="token punctuation">}</span></code></div></div></div></div></div></div></div></div></div></div></div><div id="tag/Rules/operation/edit_board_rule" data-section-id="tag/Rules/operation/edit_board_rule" class="sc-eCQgVK grDwca"><div data-section-id="operation/edit_board_rule" id="operation/edit_board_rule" class="sc-iCECmn lhRBUS"><div class="sc-hKVpXn kktglN"><h2 class="sc-qdQOe MOVBZ"><a class="sc-crPgjm jmoZom" href="#tag/Rules/operation/edit_board_rule" aria-label="tag/Rules/operation/edit_board_rule"></a>Edit an automation rule<!-- --> </h2><div class="sc-iFUzrA ktZmcf"><div html="<p>Any of title, trigger and action may be supplied; the trigger
|
||||
and action documents are replaced ($set) when present.</p>
|
||||
and action documents are replaced ($set) when present. A supplied trigger
|
||||
that includes an activityType gets its missing matching fields defaulted
|
||||
to the &#39;*&#39; wildcard, like on creation.</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH ewCFMV"><p>Any of title, trigger and action may be supplied; the trigger
|
||||
and action documents are replaced ($set) when present.</p>
|
||||
and action documents are replaced ($set) when present. A supplied trigger
|
||||
that includes an activityType gets its missing matching fields defaulted
|
||||
to the '*' wildcard, like on creation.</p>
|
||||
</div></div><div class="sc-fuYIqi kGZLat"><div class="sc-dalEhJ jdqJPb"><h5 class="sc-iqkkDd sc-jQQpTv kcvrhp kEkHzF">Authorizations:</h5><svg class="sc-dYjPD bEEWJa" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></div><div class="sc-jTPGds cVAkzL"><span class="sc-dtnsVa dVYuXz"><span class="sc-hPfayn hzxDQO"><i>UserSecurity</i></span></span></div></div><div><h5 class="sc-iqkkDd kcvrhp">path<!-- --> Parameters</h5><table class="sc-hHopjF bsjUmE"><tbody><tr class=""><td kind="field" title="board" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">board</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the board ID</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"><p>the board ID</p>
|
||||
</div></div></div></td></tr><tr class="last "><td kind="field" title="rule" class="sc-hCcPtG sc-fFCZOx jFNAwF lcdEEX"><span class="sc-ieCSdj kkMuqc"></span><span class="property-name">rule</span><div class="sc-gSILEF sc-eIYgEQ jMRTsl dHYagA">required</div></td><td class="sc-bjLslk gLpZiQ"><div><div><span class="sc-gSILEF sc-lbpDNm jMRTsl NncTE"></span><span class="sc-gSILEF sc-iNyHtD jMRTsl kUjPnZ">string</span></div> <div><div html="<p>the rule ID</p>
|
||||
@@ -1975,7 +2003,7 @@ comment-only / worker members are rejected).</p>
|
||||
" class="sc-iJSMbW sc-cBEgGa sc-ciCrSJ fiNpIH dNfUH dDDioG"><p>Attachment not found</p>
|
||||
</div></button></div></div></div><div class="sc-jSppWd sc-gKkgUA fpMlmc bdQQyo"><div class="sc-fXwuWv fYxpnv"><button class="sc-jWMFtl jzaJhV"><span type="delete" class="sc-eEFuoE iINwyG http-verb delete">delete</span><span class="sc-FpjRO dsIRaZ">/api/attachment/delete/{attachmentId}</span><svg class="sc-dYjPD bQKUih" style="margin-right:-25px" version="1.1" viewBox="0 0 24 24" x="0" xmlns="http://www.w3.org/2000/svg" y="0" aria-hidden="true"><polygon points="17.3 8.3 12 13.6 6.7 8.3 5.3 9.7 12 16.4 18.7 9.7 "></polygon></svg></button><div aria-hidden="true" class="sc-fmtEmb tUxhh"><div class="sc-ljIcGq bAnPPh"><div html="" class="sc-iJSMbW sc-cBEgGa fiNpIH bAoMjv"></div><div tabindex="0" role="button"><div class="sc-jlJOIR PEJyb"><span></span>/api/attachment/delete/{attachmentId}</div></div></div></div></div></div></div></div></div><div class="sc-ekVkVN bjzTxL"></div></div></div>
|
||||
<script>
|
||||
const __redoc_state = {"menu":{"activeItemIdx":-1},"spec":{"data":{"openapi":"3.0.0","info":{"title":"Wekan REST API","version":"v9.96","description":"The REST API allows you to control and extend Wekan with ease.\n\nIf you are an end-user and not a dev or a tester, [create an issue](https://github.com/wekan/wekan/issues/new) to request new APIs.\n\n> All API calls in the documentation are made using `curl`. However, you are free to use Java / Python / PHP / Golang / Ruby / Swift / Objective-C / Rust / Scala / C# or any other programming languages.\n\n# Production Security Concerns\nWhen calling a production Wekan server, ensure it is running via HTTPS and has a valid SSL Certificate. The login method requires you to post your username and password in plaintext, which is why we highly suggest only calling the REST login api over HTTPS. Also, few things to note:\n\n* Only call via HTTPS\n* Implement a timed authorization token expiration strategy\n* Ensure the calling user only has permissions for what they are calling and no more\n"},"paths":{"/users/login":{"post":{"operationId":"login","summary":"Login with REST API","tags":["Login"],"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["username","password"],"properties":{"username":{"description":"Your username\n","type":"string"},"password":{"description":"Your password\n","type":"string","format":"password"}}}},"application/x-www-form-urlencoded":{"schema":{"type":"object","required":["username","password"],"properties":{"username":{"description":"Your username\n","type":"string"},"password":{"description":"Your password\n","type":"string","format":"password"}}}}},"description":"Login credentials","required":true},"responses":{"200":{"description":"Successful authentication","content":{"*/*":{"schema":{"type":"object","required":["id","token","tokenExpires"],"properties":{"id":{"type":"string","description":"User ID"},"token":{"type":"string","description":"Authentication token\n"},"tokenExpires":{"type":"string","format":"date-time","description":"Token expiration date\n"}}}}}},"400":{"description":"Error in authentication\n","content":{"*/*":{"schema":{"type":"object","properties":{"error":{"type":"string"},"reason":{"type":"string"}}}}}},"default":{"description":"Error in authentication\n"}}}},"/users/register":{"post":{"operationId":"register","summary":"Register with REST API","description":"Notes:\n - You will need to provide the token for any of the authenticated methods.\n","tags":["Login"],"requestBody":{"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"username":{"description":"Your username\n","type":"string"},"password":{"description":"Your password\n","type":"string","format":"password"},"email":{"description":"Your email\n","type":"string"}},"required":["username","password","email"]}}},"required":true},"responses":{"200":{"description":"Successful registration","content":{"*/*":{"schema":{"items":{"properties":{"id":{"type":"string"},"token":{"type":"string"},"tokenExpires":{"type":"string"}}}}}}},"400":{"description":"Error in registration\n","content":{"*/*":{"schema":{"items":{"properties":{"error":{"type":"number"},"reason":{"type":"string"}}}}}}},"default":{"description":"Error in registration\n"}}}},"/api/admin/attachment-settings":{"get":{"operationId":"get_attachment_settings","summary":"Get the attachment storage / upload-block settings (GlobalAdmin)","description":"Only the global admin can call this. Returns the Admin Panel >\n Attachments settings document, including `limitSettings.attachmentsUploadBlocked`\n and `limitSettings.avatarsUploadBlocked` plus the size limits. Cloud-storage\n secret keys (S3 secretAccessKey, Azure accountKey/connectionString, GCS\n credentials) are masked and never returned; a boolean `<field>Set` marker\n shows whether a value exists.\n","tags":["AttachmentStorageSettings","Settings"],"security":[{"UserSecurity":[]}],"responses":{"200":{"description":"200 response","content":{"application/json":{"schema":{"type":"Object"}}}}}},"put":{"operationId":"update_attachment_settings","summary":"Update the attachment storage / upload-block settings (GlobalAdmin)","description":"Only the global admin can call this. The request body is a\n partial settings object (for example\n `{\"limitSettings\": {\"avatarsUploadBlocked\": true}}`). It is applied through\n the same update path as the `updateAttachmentStorageSettings` Meteor method,\n so validation and `$set` semantics are identical: cloud-storage secrets left\n blank are preserved. The masked, updated settings document is returned.\n","tags":["AttachmentStorageSettings","Settings"],"security":[{"UserSecurity":[]}],"responses":{"200":{"description":"200 response","content":{"application/json":{"schema":{"type":"Object"}}}}}}},"/api/admin/domains":{"get":{"operationId":"get_admin_domains","summary":"List email domains with their user counts (GlobalAdmin)","description":"Only the gLine truncated
|
||||
const __redoc_state = {"menu":{"activeItemIdx":-1},"spec":{"data":{"openapi":"3.0.0","info":{"title":"Wekan REST API","version":"v9.97","description":"The REST API allows you to control and extend Wekan with ease.\n\nIf you are an end-user and not a dev or a tester, [create an issue](https://github.com/wekan/wekan/issues/new) to request new APIs.\n\n> All API calls in the documentation are made using `curl`. However, you are free to use Java / Python / PHP / Golang / Ruby / Swift / Objective-C / Rust / Scala / C# or any other programming languages.\n\n# Production Security Concerns\nWhen calling a production Wekan server, ensure it is running via HTTPS and has a valid SSL Certificate. The login method requires you to post your username and password in plaintext, which is why we highly suggest only calling the REST login api over HTTPS. Also, few things to note:\n\n* Only call via HTTPS\n* Implement a timed authorization token expiration strategy\n* Ensure the calling user only has permissions for what they are calling and no more\n"},"paths":{"/users/login":{"post":{"operationId":"login","summary":"Login with REST API","tags":["Login"],"requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["username","password"],"properties":{"username":{"description":"Your username\n","type":"string"},"password":{"description":"Your password\n","type":"string","format":"password"}}}},"application/x-www-form-urlencoded":{"schema":{"type":"object","required":["username","password"],"properties":{"username":{"description":"Your username\n","type":"string"},"password":{"description":"Your password\n","type":"string","format":"password"}}}}},"description":"Login credentials","required":true},"responses":{"200":{"description":"Successful authentication","content":{"*/*":{"schema":{"type":"object","required":["id","token","tokenExpires"],"properties":{"id":{"type":"string","description":"User ID"},"token":{"type":"string","description":"Authentication token\n"},"tokenExpires":{"type":"string","format":"date-time","description":"Token expiration date\n"}}}}}},"400":{"description":"Error in authentication\n","content":{"*/*":{"schema":{"type":"object","properties":{"error":{"type":"string"},"reason":{"type":"string"}}}}}},"default":{"description":"Error in authentication\n"}}}},"/users/register":{"post":{"operationId":"register","summary":"Register with REST API","description":"Notes:\n - You will need to provide the token for any of the authenticated methods.\n","tags":["Login"],"requestBody":{"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"username":{"description":"Your username\n","type":"string"},"password":{"description":"Your password\n","type":"string","format":"password"},"email":{"description":"Your email\n","type":"string"}},"required":["username","password","email"]}}},"required":true},"responses":{"200":{"description":"Successful registration","content":{"*/*":{"schema":{"items":{"properties":{"id":{"type":"string"},"token":{"type":"string"},"tokenExpires":{"type":"string"}}}}}}},"400":{"description":"Error in registration\n","content":{"*/*":{"schema":{"items":{"properties":{"error":{"type":"number"},"reason":{"type":"string"}}}}}}},"default":{"description":"Error in registration\n"}}}},"/api/admin/attachment-settings":{"get":{"operationId":"get_attachment_settings","summary":"Get the attachment storage / upload-block settings (GlobalAdmin)","description":"Only the global admin can call this. Returns the Admin Panel >\n Attachments settings document, including `limitSettings.attachmentsUploadBlocked`\n and `limitSettings.avatarsUploadBlocked` plus the size limits. Cloud-storage\n secret keys (S3 secretAccessKey, Azure accountKey/connectionString, GCS\n credentials) are masked and never returned; a boolean `<field>Set` marker\n shows whether a value exists.\n","tags":["AttachmentStorageSettings","Settings"],"security":[{"UserSecurity":[]}],"responses":{"200":{"description":"200 response","content":{"application/json":{"schema":{"type":"Object"}}}}}},"put":{"operationId":"update_attachment_settings","summary":"Update the attachment storage / upload-block settings (GlobalAdmin)","description":"Only the global admin can call this. The request body is a\n partial settings object (for example\n `{\"limitSettings\": {\"avatarsUploadBlocked\": true}}`). It is applied through\n the same update path as the `updateAttachmentStorageSettings` Meteor method,\n so validation and `$set` semantics are identical: cloud-storage secrets left\n blank are preserved. The masked, updated settings document is returned.\n","tags":["AttachmentStorageSettings","Settings"],"security":[{"UserSecurity":[]}],"responses":{"200":{"description":"200 response","content":{"application/json":{"schema":{"type":"Object"}}}}}}},"/api/admin/domains":{"get":{"operationId":"get_admin_domains","summary":"List email domains with their user counts (GlobalAdmin)","description":"Only the gLine truncated
|
||||
|
||||
var container = document.getElementById('redoc');
|
||||
Redoc.hydrate(__redoc_state, container);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
swagger: '2.0'
|
||||
info:
|
||||
title: Wekan REST API
|
||||
version: v9.96
|
||||
version: v9.97
|
||||
description: |
|
||||
The REST API allows you to control and extend Wekan with ease.
|
||||
|
||||
@@ -2958,6 +2958,11 @@ paths:
|
||||
description: |
|
||||
The trigger and action are embedded inline. See the Rules
|
||||
documentation for the available trigger activityTypes and action actionTypes.
|
||||
Trigger matching fields that are omitted (e.g. userId, listName,
|
||||
swimlaneName, cardTitle) default to the '*' wildcard, so e.g. issue #2674's
|
||||
"remove a member when a card is moved away from a list" only needs
|
||||
trigger {activityType: 'moveCard', oldListName: '...'} and
|
||||
action {actionType: 'removeMember', username: '...'}.
|
||||
tags:
|
||||
- Rules
|
||||
- Rules
|
||||
@@ -3050,7 +3055,9 @@ paths:
|
||||
summary: Edit an automation rule
|
||||
description: |
|
||||
Any of title, trigger and action may be supplied; the trigger
|
||||
and action documents are replaced ($set) when present.
|
||||
and action documents are replaced ($set) when present. A supplied trigger
|
||||
that includes an activityType gets its missing matching fields defaulted
|
||||
to the '*' wildcard, like on creation.
|
||||
tags:
|
||||
- Rules
|
||||
- Rules
|
||||
|
||||
@@ -99,6 +99,16 @@ const ATTACH_DIR = path.join(WRITABLE, 'files', 'attachments');
|
||||
const AVATAR_DIR = path.join(WRITABLE, 'files', 'avatars');
|
||||
const MARKER_COLL = '_wekan_migration'; // written to target when done
|
||||
const SCHEMA_VER = 843; // v8.43
|
||||
// #6473: version of the FILE (attachment/avatar) extraction logic. Bump this whenever a
|
||||
// file-phase bug fix means already-migrated installs must be RE-SCANNED: a marker whose
|
||||
// filesVersion is older than this triggers an automatic, incremental files-only REPAIR run
|
||||
// (text data is left alone; only binaries/records that are missing are migrated). v2 =
|
||||
// the #6473 fixes (copies.<bucket>.key resolution, files-collection-driven CFS extraction,
|
||||
// gridFsFileId-without-storage-flag matching, <bucket>.files sweep).
|
||||
const FILES_VERSION = 2;
|
||||
// Run ONLY the file phases against an existing target (set by the snap's
|
||||
// attachment-repair). Also turned on automatically when the marker's filesVersion is old.
|
||||
const FILES_ONLY = process.env.FILES_ONLY === 'true';
|
||||
|
||||
// ── Progress state (shared between HTTP server and migration logic) ─────────
|
||||
const state = {
|
||||
@@ -259,9 +269,16 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// A background repair run (#6473) starts while WeKan itself is coming up on the web
|
||||
// port, so the dashboard port can be taken (or 0 = ephemeral). Never crash over it —
|
||||
// the dashboard is a convenience, the migration/repair itself matters.
|
||||
server.on('error', (err) => {
|
||||
console.log(`[migrate] Progress dashboard not available (${err.code || err.message}); continuing without it.`);
|
||||
});
|
||||
server.listen(PORT, () => {
|
||||
console.log(`[migrate] Progress dashboard: http://localhost:${PORT}/`);
|
||||
console.log(`[migrate] JSON status: http://localhost:${PORT}/migration-status`);
|
||||
const actualPort = server.address()?.port ?? PORT;
|
||||
console.log(`[migrate] Progress dashboard: http://localhost:${actualPort}/`);
|
||||
console.log(`[migrate] JSON status: http://localhost:${actualPort}/migration-status`);
|
||||
});
|
||||
|
||||
// ── Filesystem helpers ─────────────────────────────────────────────────────
|
||||
@@ -574,6 +591,38 @@ function destFilePath(dir, idHex, originalName) {
|
||||
return { fullPath: path.join(dir, base), basename: base };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the GridFS ObjectId of a CollectionFS filerecord (#6473).
|
||||
*
|
||||
* Real CollectionFS (old WeKan, FS.Store.GridFS named after the bucket) stores
|
||||
* the GridFS file id at `copies.<storeName>.key` where the store name equals
|
||||
* the bucket name — `copies.attachments.key` / `copies.avatars.key`. The old
|
||||
* lookup only tried `original.gridFsFileId`, `gridFsFileId` and
|
||||
* `copies.gridfs.key`, NONE of which exist in that layout, so every attachment
|
||||
* was silently "skipped" and the migration still reported success — the exact
|
||||
* "all attachments are missing" of #6473. Try, in order:
|
||||
* 1. original.gridFsFileId / gridFsFileId (newer intermediate layouts)
|
||||
* 2. copies.<bucketName>.key (real CollectionFS layout)
|
||||
* 3. copies.gridfs.key (legacy fallback kept for safety)
|
||||
* 4. the first copies.*.key found (renamed stores)
|
||||
* Returns null when the record carries no GridFS reference at all.
|
||||
*/
|
||||
function resolveCfsGridFsId(record, bucketName) {
|
||||
if (!record || typeof record !== 'object') return null;
|
||||
const original = record.original || {};
|
||||
if (original.gridFsFileId) return original.gridFsFileId;
|
||||
if (record.gridFsFileId) return record.gridFsFileId;
|
||||
const copies = record.copies;
|
||||
if (copies && typeof copies === 'object') {
|
||||
if (copies[bucketName] && copies[bucketName].key) return copies[bucketName].key;
|
||||
if (copies.gridfs && copies.gridfs.key) return copies.gridfs.key;
|
||||
for (const copy of Object.values(copies)) {
|
||||
if (copy && copy.key) return copy.key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Schema upgrade helpers ─────────────────────────────────────────────────
|
||||
/**
|
||||
* During the copy phase we call this on every document of a given collection
|
||||
@@ -582,11 +631,16 @@ function destFilePath(dir, idHex, originalName) {
|
||||
* Each transformer is pure: takes a doc, returns a doc (or null to skip).
|
||||
*/
|
||||
function upgradeBoard(doc) {
|
||||
// Only migrationVersion is stamped. The old comprehensiveMigrationCompleted /
|
||||
// fixMissingListsCompleted stamps made WeKan's on-demand repair tools
|
||||
// (fixMissingListsMigration, comprehensiveBoardMigration) permanently skip
|
||||
// imported boards — while this importer covers LESS than those tools (e.g.
|
||||
// cards with a dangling listId). The startup schema upgrade
|
||||
// (server/lib/schemaUpgradeSteps.js) now rescues those on every platform,
|
||||
// and the repair tools stay usable.
|
||||
return {
|
||||
...doc,
|
||||
migrationVersion: SCHEMA_VER,
|
||||
comprehensiveMigrationCompleted: true,
|
||||
fixMissingListsCompleted: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -696,13 +750,23 @@ async function copyCollection(srcDb, tgtDb, collName, transformer) {
|
||||
const flush = async () => {
|
||||
if (batch.length === 0) return;
|
||||
if (!DRY_RUN) {
|
||||
for (const doc of batch) {
|
||||
try {
|
||||
await tgt.replaceOne({ _id: doc._id }, doc, { upsert: true });
|
||||
state.collections[collName].done++;
|
||||
} catch (err) {
|
||||
state.collections[collName].errors++;
|
||||
pushError(`${collName}/${doc._id}: ${err.message}`);
|
||||
// SPEED (#6473 follow-up: a big migration took 5 hours): ONE insertMany
|
||||
// round trip per batch — the common case is a fresh, empty target where
|
||||
// every insert succeeds. Only when the batch hits duplicates (a resumed
|
||||
// or re-run migration) fall back to per-document replaceOne upserts for
|
||||
// THIS batch, which also isolates any per-document error.
|
||||
try {
|
||||
await tgt.insertMany(batch, { ordered: false });
|
||||
state.collections[collName].done += batch.length;
|
||||
} catch {
|
||||
for (const doc of batch) {
|
||||
try {
|
||||
await tgt.replaceOne({ _id: doc._id }, doc, { upsert: true });
|
||||
state.collections[collName].done++;
|
||||
} catch (err) {
|
||||
state.collections[collName].errors++;
|
||||
pushError(`${collName}/${doc._id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -803,48 +867,67 @@ async function run() {
|
||||
}
|
||||
} catch (e) { /* keep default product name */ }
|
||||
|
||||
// Check idempotency marker
|
||||
// Check idempotency marker. #6473: the marker also carries filesVersion — the version
|
||||
// of the FILE extraction logic that produced the target's attachments/avatars. A
|
||||
// COMPLETED migration whose filesVersion is older than FILES_VERSION is not re-done:
|
||||
// it gets an automatic, INCREMENTAL files-only REPAIR — the text data (which may have
|
||||
// been changed by users since the migration) is never touched, and only binaries and
|
||||
// records that are actually missing are migrated; everything already on disk and
|
||||
// pointed at by its record is verified and skipped.
|
||||
const markerColl = tgtDb.collection(MARKER_COLL);
|
||||
const marker = await markerColl.findOne({ _id: 'completed' });
|
||||
const filesCurrent = !!marker && (marker.filesVersion || 1) >= FILES_VERSION;
|
||||
let repairMode = FILES_ONLY;
|
||||
if (marker && marker.schemaVersion >= SCHEMA_VER && !process.env.FORCE_MIGRATE) {
|
||||
console.log('[migrate] Already migrated (schema v' + marker.schemaVersion + '). Exiting.');
|
||||
state.phase = 'already-migrated';
|
||||
state.phase_detail = 'Schema v' + marker.schemaVersion + ' already present in target';
|
||||
state.success = true;
|
||||
// A previous boot already migrated attachments, avatars and text data:
|
||||
// reclaim the old MongoDB disk space now (runs once, tracked by the marker).
|
||||
try { await compactSource(srcDb, markerColl); } catch (e) { pushError('compact: ' + e.message); }
|
||||
state.finishedAt = new Date().toISOString();
|
||||
await srcClient.close();
|
||||
await tgtClient.close();
|
||||
setTimeout(() => process.exit(0), 3000);
|
||||
return;
|
||||
if (filesCurrent && !FILES_ONLY) {
|
||||
console.log('[migrate] Already migrated (schema v' + marker.schemaVersion + ', files v' + (marker.filesVersion || 1) + '). Exiting.');
|
||||
state.phase = 'already-migrated';
|
||||
state.phase_detail = 'Schema v' + marker.schemaVersion + ' already present in target';
|
||||
state.success = true;
|
||||
// A previous boot already migrated attachments, avatars and text data:
|
||||
// reclaim the old MongoDB disk space now (runs once, tracked by the marker).
|
||||
try { await compactSource(srcDb, markerColl); } catch (e) { pushError('compact: ' + e.message); }
|
||||
state.finishedAt = new Date().toISOString();
|
||||
await srcClient.close();
|
||||
await tgtClient.close();
|
||||
setTimeout(() => process.exit(0), 3000);
|
||||
return;
|
||||
}
|
||||
repairMode = true;
|
||||
console.log(`[migrate] Migration is complete (schema v${marker.schemaVersion}) but its file phase is v${marker.filesVersion || 1} < v${FILES_VERSION}: running an incremental files-only repair. Text data is left untouched; only missing attachments/avatars are migrated.`);
|
||||
}
|
||||
if (repairMode) {
|
||||
state.phase = 'repairing-files';
|
||||
state.phase_detail = 'Incremental attachment/avatar repair — text data untouched';
|
||||
}
|
||||
|
||||
// ── 1. Build lookup maps needed for schema upgrades ────────────────────
|
||||
state.phase = 'analyzing';
|
||||
state.phase_detail = 'Building swimlane/list lookup maps…';
|
||||
console.log('[migrate] Analyzing source schema…');
|
||||
|
||||
// boardId → first swimlaneId (for orphaned lists/cards)
|
||||
// (skipped in repair mode: they only feed the text-copy transformers)
|
||||
const defaultSwimlaneIdFor = {};
|
||||
const swimlaneCursor = srcDb.collection('swimlanes').find({ archived: false }, {
|
||||
projection: { _id: 1, boardId: 1, sort: 1 }, sort: { sort: 1 },
|
||||
});
|
||||
for await (const sw of swimlaneCursor) {
|
||||
if (!defaultSwimlaneIdFor[sw.boardId]) {
|
||||
defaultSwimlaneIdFor[sw.boardId] = String(sw._id);
|
||||
}
|
||||
}
|
||||
await swimlaneCursor.close();
|
||||
|
||||
// listId → swimlaneId (so orphaned cards can inherit from their list)
|
||||
const listSwimlaneMap = {};
|
||||
const listCursor = srcDb.collection('lists').find({}, { projection: { _id: 1, swimlaneId: 1 } });
|
||||
for await (const ls of listCursor) {
|
||||
listSwimlaneMap[String(ls._id)] = ls.swimlaneId || '';
|
||||
if (!repairMode) {
|
||||
state.phase = 'analyzing';
|
||||
state.phase_detail = 'Building swimlane/list lookup maps…';
|
||||
console.log('[migrate] Analyzing source schema…');
|
||||
|
||||
// boardId → first swimlaneId (for orphaned lists/cards)
|
||||
const swimlaneCursor = srcDb.collection('swimlanes').find({ archived: false }, {
|
||||
projection: { _id: 1, boardId: 1, sort: 1 }, sort: { sort: 1 },
|
||||
});
|
||||
for await (const sw of swimlaneCursor) {
|
||||
if (!defaultSwimlaneIdFor[sw.boardId]) {
|
||||
defaultSwimlaneIdFor[sw.boardId] = String(sw._id);
|
||||
}
|
||||
}
|
||||
await swimlaneCursor.close();
|
||||
|
||||
// listId → swimlaneId (so orphaned cards can inherit from their list)
|
||||
const listCursor = srcDb.collection('lists').find({}, { projection: { _id: 1, swimlaneId: 1 } });
|
||||
for await (const ls of listCursor) {
|
||||
listSwimlaneMap[String(ls._id)] = ls.swimlaneId || '';
|
||||
}
|
||||
await listCursor.close();
|
||||
}
|
||||
await listCursor.close();
|
||||
|
||||
// ── 2. Ensure target filesystem directories exist ───────────────────────
|
||||
if (!DRY_RUN) {
|
||||
@@ -870,6 +953,10 @@ async function run() {
|
||||
]);
|
||||
|
||||
// ── 4. Copy all plain collections ─────────────────────────────────────
|
||||
// Repair mode NEVER touches text collections: users may have added/changed
|
||||
// boards and cards on FerretDB since the original migration, and re-copying
|
||||
// from the frozen MongoDB source would overwrite or resurrect data.
|
||||
if (!repairMode) {
|
||||
state.phase = 'migrating-collections';
|
||||
for (const name of allColls) {
|
||||
// FerretDB v1 rejects collection names containing a dot ("invalid key: '<name>' (key must
|
||||
@@ -903,8 +990,10 @@ async function run() {
|
||||
completedCollections.add(name);
|
||||
saveCheckpoint(true); // persist progress to WRITABLE_PATH after each collection
|
||||
}
|
||||
} // end !repairMode (text collections)
|
||||
|
||||
// ── 5. Also ensure boards without a swimlane have one in the target ────
|
||||
if (!repairMode) {
|
||||
state.phase = 'ensuring-swimlanes';
|
||||
state.phase_detail = 'Creating default swimlanes for boards that have none…';
|
||||
if (!DRY_RUN) {
|
||||
@@ -979,9 +1068,10 @@ async function run() {
|
||||
}
|
||||
await orphanCursor.close();
|
||||
}
|
||||
} // end !repairMode (swimlane/orphan fixes)
|
||||
|
||||
// ── 7. Extract GridFS / CollectionFS binary files to filesystem ─────────
|
||||
state.phase = 'migrating-files';
|
||||
state.phase = repairMode ? 'repairing-files' : 'migrating-files';
|
||||
|
||||
// Close both clients and exit (staying up 60 s so the dashboard's disk-space error can be
|
||||
// read) when the file phase stops for lack of disk space.
|
||||
@@ -992,6 +1082,32 @@ async function run() {
|
||||
setTimeout(() => process.exit(1), 60_000);
|
||||
};
|
||||
|
||||
// SPEED (#6473 follow-up): preload the TARGET's attachment/avatar metadata ONCE
|
||||
// per bucket instead of one findOne round trip per file — per-document round
|
||||
// trips were a main reason a big migration took 5 hours. The records are small
|
||||
// metadata documents; a very large collection (>100k records) falls back to
|
||||
// per-file lookups to bound memory.
|
||||
const TGT_PRELOAD_LIMIT = 100_000;
|
||||
const tgtRecCache = {};
|
||||
async function getTgtRec(collName, id) {
|
||||
if (tgtRecCache[collName] === undefined) {
|
||||
tgtRecCache[collName] = null;
|
||||
try {
|
||||
const n = await tgtDb.collection(collName).countDocuments({});
|
||||
if (n <= TGT_PRELOAD_LIMIT) {
|
||||
const map = new Map();
|
||||
const cur = tgtDb.collection(collName).find({}, { projection: { name: 1, versions: 1 } });
|
||||
for await (const d of cur) map.set(String(d._id), d);
|
||||
await cur.close();
|
||||
tgtRecCache[collName] = map;
|
||||
}
|
||||
} catch { /* keep per-file lookups */ }
|
||||
}
|
||||
const map = tgtRecCache[collName];
|
||||
if (map) return map.get(String(id)) || null;
|
||||
try { return await tgtDb.collection(collName).findOne({ _id: id }); } catch { return null; }
|
||||
}
|
||||
|
||||
// Measure up front how many files and how many BYTES must be extracted (both the
|
||||
// CollectionFS GridFS files and the Meteor-Files-in-GridFS records), so the dashboard can
|
||||
// show "file N of TOTAL" and a per-file bar, and so we can STOP before extracting anything
|
||||
@@ -1003,15 +1119,25 @@ async function run() {
|
||||
try { state.current.total += await srcDb.collection(`cfs_gridfs.${b}.files`).countDocuments(); } catch {}
|
||||
try { const r = await srcDb.collection(`cfs_gridfs.${b}.files`).aggregate([{ $group: { _id: null, s: { $sum: '$length' } } }]).toArray(); state.filesTotalBytes += r.length ? Number(r[0].s) || 0 : 0; } catch {}
|
||||
}
|
||||
// #6473: a Meteor-Files version is in GridFS when its storage flag says so OR it
|
||||
// carries a meta.gridFsFileId reference (the same rule WeKan's getFileStrategy
|
||||
// uses) — records with only the reference used to be missed entirely.
|
||||
const MF_GRIDFS_QUERY = { $or: [
|
||||
{ 'versions.original.storage': 'gridfs' },
|
||||
{ 'versions.original.meta.gridFsFileId': { $exists: true, $ne: null } },
|
||||
] };
|
||||
for (const c of mfColls) {
|
||||
try { state.current.total += await srcDb.collection(c).countDocuments({ 'versions.original.storage': 'gridfs' }); } catch {}
|
||||
try { const r = await srcDb.collection(c).aggregate([{ $match: { 'versions.original.storage': 'gridfs' } }, { $group: { _id: null, s: { $sum: '$versions.original.size' } } }]).toArray(); state.filesTotalBytes += r.length ? Number(r[0].s) || 0 : 0; } catch {}
|
||||
try { state.current.total += await srcDb.collection(c).countDocuments(MF_GRIDFS_QUERY); } catch {}
|
||||
try { const r = await srcDb.collection(c).aggregate([{ $match: MF_GRIDFS_QUERY }, { $group: { _id: null, s: { $sum: '$versions.original.size' } } }]).toArray(); state.filesTotalBytes += r.length ? Number(r[0].s) || 0 : 0; } catch {}
|
||||
}
|
||||
updateDiskFree(WRITABLE, true);
|
||||
console.log(`[migrate] Files to extract: ${state.current.total} (${(state.filesTotalBytes / 1048576).toFixed(0)} MB)${state.diskFree >= 0 ? `; disk free ${(state.diskFree / 1048576).toFixed(0)} MB` : '; free space unknown — will stop on a write failure'}.`);
|
||||
// Up-front check ONLY when free space is measurable. If it will not all fit, stop before
|
||||
// extracting anything so a full disk can never corrupt MongoDB.
|
||||
if (!DRY_RUN && state.filesTotalBytes > 0 && state.diskFree >= 0 && state.diskFree < state.filesTotalBytes + DISK_MIN_FREE) {
|
||||
// extracting anything so a full disk can never corrupt MongoDB. NOT in repair mode: there
|
||||
// most (often all) files are already on disk and need no new space, so requiring room for
|
||||
// the full set again would falsely abort healthy repairs — the per-file
|
||||
// ensureDiskForFile() guard still protects every actual write.
|
||||
if (!DRY_RUN && !repairMode && state.filesTotalBytes > 0 && state.diskFree >= 0 && state.diskFree < state.filesTotalBytes + DISK_MIN_FREE) {
|
||||
state.abort = true; state.success = false; state.phase = 'error';
|
||||
state.additionalBytesNeeded = Math.max(0, state.filesTotalBytes + DISK_MIN_FREE - state.diskFree);
|
||||
pushError(`FATAL: not enough disk space to migrate all files: ${(state.filesTotalBytes / 1048576).toFixed(0)} MB of attachments/avatars must be extracted, only ${(state.diskFree / 1048576).toFixed(0)} MB free — need ${(state.additionalBytesNeeded / 1048576).toFixed(0)} MB more. Stopped before extracting to avoid MongoDB data corruption.`);
|
||||
@@ -1022,33 +1148,71 @@ async function run() {
|
||||
|
||||
async function migrateGridFs(bucketName, destDir, fileStateKey) {
|
||||
const filesCollName = `cfs_gridfs.${bucketName}.files`;
|
||||
if (!allColls.includes(filesCollName)) return;
|
||||
const haveBucket = allColls.includes(filesCollName);
|
||||
const haveFilerecords = allColls.includes(`cfs.${bucketName}.filerecord`);
|
||||
// A CFS FileSystem-store database (ATTACHMENTS_STORE_PATH era, WeKan
|
||||
// v3.12–v6.09) may have filerecords but NO cfs_gridfs collections at all —
|
||||
// returning early here silently lost every such attachment.
|
||||
if (!haveBucket && !haveFilerecords) return;
|
||||
|
||||
state.phase_detail = `Extracting ${bucketName} files from GridFS…`;
|
||||
console.log(`[migrate] Extracting GridFS bucket: ${bucketName} → ${destDir}`);
|
||||
console.log(`[migrate] Extracting CollectionFS bucket: ${bucketName} → ${destDir}`);
|
||||
|
||||
const bucket = new GridFSBucket(srcDb, { bucketName: `cfs_gridfs.${bucketName}` });
|
||||
const filesCol = srcDb.collection(filesCollName);
|
||||
const metaCursor = srcDb.collection(`cfs.${bucketName}.filerecord`).find({});
|
||||
const filesCol = haveBucket ? srcDb.collection(filesCollName) : null;
|
||||
const bucket = haveBucket ? new GridFSBucket(srcDb, { bucketName: `cfs_gridfs.${bucketName}` }) : null;
|
||||
|
||||
state.files[fileStateKey].total = await filesCol.countDocuments();
|
||||
state.files[fileStateKey].total = haveBucket ? await filesCol.countDocuments() : 0;
|
||||
|
||||
for await (const record of metaCursor) {
|
||||
const original = record.original || {};
|
||||
const gridFsId = original.gridFsFileId || record.gridFsFileId || (record.copies && record.copies.gridfs && record.copies.gridfs.key);
|
||||
if (!gridFsId) {
|
||||
state.files[fileStateKey].skipped++;
|
||||
continue;
|
||||
// #6473: join the CollectionFS filerecords (original name, board/card links)
|
||||
// to the GridFS files by their RESOLVED GridFS id — but DRIVE the extraction
|
||||
// from the GridFS files collection itself. The old loop iterated the
|
||||
// filerecords and skipped any record whose GridFS id it could not resolve, so
|
||||
// the id living at copies.<bucket>.key (the real CollectionFS layout) — or a
|
||||
// missing cfs.<bucket>.filerecord collection — silently skipped EVERY file
|
||||
// while the migration still reported success.
|
||||
//
|
||||
// A key that is NOT a 24-hex ObjectId is a CFS **FileSystem store** key
|
||||
// (ATTACHMENTS_STORE_PATH era): the value is the file's NAME on disk
|
||||
// ("<collection>-<id>-<name>"), not a GridFS id — handled separately below.
|
||||
const HEX24 = /^[0-9a-f]{24}$/i;
|
||||
const recordByGridId = new Map();
|
||||
const fsStoreRecords = [];
|
||||
let danglingRecords = 0; // filerecords carrying no GridFS reference at all
|
||||
if (haveFilerecords) {
|
||||
const metaCursor = srcDb.collection(`cfs.${bucketName}.filerecord`).find({});
|
||||
for await (const record of metaCursor) {
|
||||
const gid = resolveCfsGridFsId(record, bucketName);
|
||||
if (gid && HEX24.test(String(gid))) recordByGridId.set(String(gid), record);
|
||||
else if (gid) fsStoreRecords.push({ record, key: String(gid) });
|
||||
else danglingRecords++;
|
||||
}
|
||||
await metaCursor.close();
|
||||
}
|
||||
if (danglingRecords > 0) {
|
||||
pushError(`${bucketName}: ${danglingRecords} CollectionFS filerecord(s) carry no GridFS reference; their binaries cannot be located.`);
|
||||
state.files[fileStateKey].errors += danglingRecords;
|
||||
}
|
||||
state.current.total += fsStoreRecords.length;
|
||||
state.files[fileStateKey].total += fsStoreRecords.length;
|
||||
|
||||
const originalName = original.name || record.filename || String(record._id);
|
||||
const size = original.size || 0;
|
||||
const { fullPath, basename } = destFilePath(destDir, String(record._id), originalName);
|
||||
const matchedGridIds = new Set(); // hex filerecords whose GridFS file was found
|
||||
let orphanFiles = 0; // GridFS files with no filerecord (extracted, kept on disk)
|
||||
const gfCursor = haveBucket ? filesCol.find({}) : null;
|
||||
if (gfCursor)
|
||||
for await (const gf of gfCursor) {
|
||||
const gridFsId = gf._id;
|
||||
const record = recordByGridId.get(String(gridFsId)) || null;
|
||||
if (record) matchedGridIds.add(String(gridFsId));
|
||||
const original = (record && record.original) || {};
|
||||
const recordId = record ? String(record._id) : String(gridFsId);
|
||||
const originalName = original.name || (record && record.filename) || gf.filename || recordId;
|
||||
const size = gf.length || original.size || 0;
|
||||
const { fullPath, basename } = destFilePath(destDir, recordId, originalName);
|
||||
|
||||
// Extracted by an earlier run that was interrupted: count it and move on. This is
|
||||
// what makes a resumed migration cheap — re-extracting gigabytes of unchanged
|
||||
// attachments is the slowest part of the whole job.
|
||||
const resumeKey = `${bucketName}:${record._id}`;
|
||||
const resumeKey = `${bucketName}:${recordId}`;
|
||||
const done = alreadyExtracted(resumeKey);
|
||||
if (done) {
|
||||
fileIndex++;
|
||||
@@ -1057,9 +1221,30 @@ async function run() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// #6473: ALREADY MIGRATED? Check the TARGET itself — record present, version on
|
||||
// 'fs', file actually on disk. This is what makes the automatic startup repair
|
||||
// INCREMENTAL: servers whose migration worked verify-and-skip every file quickly,
|
||||
// and only what is genuinely missing gets migrated.
|
||||
if (!DRY_RUN && record) {
|
||||
try {
|
||||
const tgtRec = await getTgtRec(bucketName, record._id);
|
||||
const tv = tgtRec && tgtRec.versions && tgtRec.versions.original;
|
||||
if (tv && tv.storage === 'fs' && tv.path && fs.existsSync(tv.path)) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(tv.size) || 0;
|
||||
let onDiskSize = Number(tv.size) || 0;
|
||||
try { onDiskSize = fs.statSync(tv.path).size; } catch { /* keep record size */ }
|
||||
completedFiles.set(resumeKey, { path: tv.path, size: onDiskSize });
|
||||
saveCheckpoint();
|
||||
continue;
|
||||
}
|
||||
} catch { /* fall through to extraction */ }
|
||||
}
|
||||
|
||||
// STOP (not skip) if this file plus the safety margin will not fit: a full disk can
|
||||
// corrupt the still-running source MongoDB. Roll back and report how much more is needed.
|
||||
if (!DRY_RUN && !ensureDiskForFile(destDir, size, originalName)) { await metaCursor.close(); onDiskAbort(); return; }
|
||||
if (!DRY_RUN && !ensureDiskForFile(destDir, size, originalName)) { await gfCursor.close(); onDiskAbort(); return; }
|
||||
|
||||
fileIndex++;
|
||||
state.current = { active: true, kind: fileStateKey, name: originalName, size, done: 0, index: fileIndex, total: state.current.total };
|
||||
@@ -1077,34 +1262,145 @@ async function run() {
|
||||
state.files[fileStateKey].bytes += bytes;
|
||||
state.current.done = bytes;
|
||||
|
||||
// CREATE the Meteor-Files record in the bare <bucket> collection from the CollectionFS
|
||||
// filerecord, pointing at the on-disk file. The cfs.<bucket>.filerecord collection is
|
||||
// NOT copied as text (FerretDB rejects its dotted name), so this is where the record is
|
||||
// made. replaceOne(upsert:true) so it works whether or not one already exists.
|
||||
const mfRecord = cfsRecordToMeteorFile(record, bucketName, basename);
|
||||
mfRecord.path = fullPath;
|
||||
mfRecord.size = bytes;
|
||||
if (mfRecord.versions && mfRecord.versions.original) {
|
||||
mfRecord.versions.original.path = fullPath;
|
||||
mfRecord.versions.original.size = bytes;
|
||||
mfRecord.versions.original.storage = 'fs';
|
||||
if (record) {
|
||||
// CREATE the Meteor-Files record in the bare <bucket> collection from the CollectionFS
|
||||
// filerecord, pointing at the on-disk file. The cfs.<bucket>.filerecord collection is
|
||||
// NOT copied as text (FerretDB rejects its dotted name), so this is where the record is
|
||||
// made. replaceOne(upsert:true) so it works whether or not one already exists.
|
||||
const mfRecord = cfsRecordToMeteorFile(record, bucketName, basename);
|
||||
mfRecord.path = fullPath;
|
||||
mfRecord.size = bytes;
|
||||
if (mfRecord.versions && mfRecord.versions.original) {
|
||||
mfRecord.versions.original.path = fullPath;
|
||||
mfRecord.versions.original.size = bytes;
|
||||
mfRecord.versions.original.storage = 'fs';
|
||||
}
|
||||
mfRecord.meta = { ...(mfRecord.meta || {}), originalFilename: originalName, storedBasename: basename, source: 'cfs-migration' };
|
||||
await tgtDb.collection(bucketName).replaceOne({ _id: record._id }, mfRecord, { upsert: true });
|
||||
} else {
|
||||
// No filerecord: there is no board/card to attach the file to, so no record is
|
||||
// created — but the binary IS extracted and kept on disk (<gridFsId>_<name>)
|
||||
// instead of being silently lost.
|
||||
orphanFiles++;
|
||||
}
|
||||
mfRecord.meta = { ...(mfRecord.meta || {}), originalFilename: originalName, storedBasename: basename, source: 'cfs-migration' };
|
||||
await tgtDb.collection(bucketName).replaceOne({ _id: record._id }, mfRecord, { upsert: true });
|
||||
// Only now is this file really done: bytes on disk AND a record pointing at them.
|
||||
// Only now is this file really done: bytes on disk AND (when a filerecord
|
||||
// exists) a record pointing at them.
|
||||
completedFiles.set(resumeKey, { path: fullPath, size: bytes });
|
||||
saveCheckpoint();
|
||||
} catch (err) {
|
||||
if (err && (err.code === 'ENOSPC' || err.code === 'EDQUOT')) flagDiskFull('write failed: ' + err.code);
|
||||
pushError(`GridFS extract ${bucketName}/${record._id}: ${err.message}`);
|
||||
pushError(`GridFS extract ${bucketName}/${recordId}: ${err.message}`);
|
||||
state.files[fileStateKey].errors++;
|
||||
// Clean up partial file
|
||||
try { fs.unlinkSync(fullPath); } catch { /* ignore */ }
|
||||
} finally { state.current.active = false; }
|
||||
|
||||
if (state.abort) { await metaCursor.close(); onDiskAbort(); return; }
|
||||
if (state.abort) { await gfCursor.close(); onDiskAbort(); return; }
|
||||
}
|
||||
if (gfCursor) await gfCursor.close();
|
||||
if (orphanFiles > 0) {
|
||||
console.log(`[migrate] ${bucketName}: ${orphanFiles} GridFS file(s) had no CollectionFS filerecord; extracted to ${destDir} without a database record.`);
|
||||
}
|
||||
|
||||
// ── CFS FileSystem-store filerecords (ATTACHMENTS_STORE_PATH era, v3.12–v6.09) ──
|
||||
// copies.<bucket>.key is the file's NAME under the CFS FileSystem store dir. Copy
|
||||
// the binary into the current layout and create the Meteor-Files record.
|
||||
let fsStoreMissing = 0;
|
||||
for (const { record, key } of fsStoreRecords) {
|
||||
const original = record.original || {};
|
||||
const recordId = String(record._id);
|
||||
const originalName = original.name || record.filename || recordId;
|
||||
const resumeKey = `${bucketName}:${recordId}`;
|
||||
|
||||
const done = alreadyExtracted(resumeKey);
|
||||
if (done) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(done.size) || 0;
|
||||
continue;
|
||||
}
|
||||
// Already migrated? (incremental repair — same check as the GridFS loop)
|
||||
if (!DRY_RUN) {
|
||||
try {
|
||||
const tgtRec = await getTgtRec(bucketName, record._id);
|
||||
const tv = tgtRec && tgtRec.versions && tgtRec.versions.original;
|
||||
if (tv && tv.storage === 'fs' && tv.path && fs.existsSync(tv.path)) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(tv.size) || 0;
|
||||
let onDiskSize = Number(tv.size) || 0;
|
||||
try { onDiskSize = fs.statSync(tv.path).size; } catch { /* keep record size */ }
|
||||
completedFiles.set(resumeKey, { path: tv.path, size: onDiskSize });
|
||||
saveCheckpoint();
|
||||
continue;
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
|
||||
// Locate the binary: ATTACHMENTS_STORE_PATH (the env the old store used; the
|
||||
// operator carries it over), an absolute key, or a cfs/files dir moved under
|
||||
// WRITABLE_PATH.
|
||||
const candidates = [];
|
||||
if (path.isAbsolute(key)) candidates.push(key);
|
||||
for (const dir of [process.env.ATTACHMENTS_STORE_PATH, process.env.AVATARS_STORE_PATH]) {
|
||||
if (dir) candidates.push(path.join(dir, key));
|
||||
}
|
||||
candidates.push(path.join(WRITABLE, 'cfs', 'files', bucketName, key));
|
||||
candidates.push(path.join(WRITABLE, 'files', 'cfs', bucketName, key));
|
||||
let srcPath = null;
|
||||
for (const c of candidates) {
|
||||
try { if (fs.statSync(c).isFile()) { srcPath = c; break; } } catch { /* next */ }
|
||||
}
|
||||
if (!srcPath) { fsStoreMissing++; continue; }
|
||||
|
||||
const size = (() => { try { return fs.statSync(srcPath).size; } catch { return original.size || 0; } })();
|
||||
const { fullPath, basename } = destFilePath(destDir, recordId, originalName);
|
||||
if (!DRY_RUN && !ensureDiskForFile(destDir, size, originalName)) { onDiskAbort(); return; }
|
||||
|
||||
fileIndex++;
|
||||
state.current = { active: true, kind: fileStateKey, name: originalName, size, done: 0, index: fileIndex, total: state.current.total };
|
||||
if (DRY_RUN) {
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += size;
|
||||
state.current.active = false;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
fs.copyFileSync(srcPath, fullPath);
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += size;
|
||||
state.current.done = size;
|
||||
const mfRecord = cfsRecordToMeteorFile(record, bucketName, basename);
|
||||
mfRecord.path = fullPath;
|
||||
mfRecord.size = size;
|
||||
if (mfRecord.versions && mfRecord.versions.original) {
|
||||
mfRecord.versions.original.path = fullPath;
|
||||
mfRecord.versions.original.size = size;
|
||||
mfRecord.versions.original.storage = 'fs';
|
||||
}
|
||||
mfRecord.meta = { ...(mfRecord.meta || {}), originalFilename: originalName, storedBasename: basename, source: 'cfs-migration' };
|
||||
await tgtDb.collection(bucketName).replaceOne({ _id: record._id }, mfRecord, { upsert: true });
|
||||
completedFiles.set(resumeKey, { path: fullPath, size });
|
||||
saveCheckpoint();
|
||||
} catch (err) {
|
||||
if (err && (err.code === 'ENOSPC' || err.code === 'EDQUOT')) flagDiskFull('write failed: ' + err.code);
|
||||
pushError(`CFS fs-store copy ${bucketName}/${recordId}: ${err.message}`);
|
||||
state.files[fileStateKey].errors++;
|
||||
try { fs.unlinkSync(fullPath); } catch { /* ignore */ }
|
||||
} finally { state.current.active = false; }
|
||||
if (state.abort) { onDiskAbort(); return; }
|
||||
}
|
||||
if (fsStoreMissing > 0) {
|
||||
pushError(`${bucketName}: ${fsStoreMissing} CollectionFS FileSystem-store file(s) not found on disk — set ATTACHMENTS_STORE_PATH to the old store directory and re-run the repair.`);
|
||||
state.files[fileStateKey].errors += fsStoreMissing;
|
||||
}
|
||||
|
||||
// Hex filerecords whose GridFS binary no longer exists: report, never silently drop.
|
||||
const missingBinaries = [...recordByGridId.keys()].filter(k => !matchedGridIds.has(k)).length;
|
||||
if (missingBinaries > 0) {
|
||||
pushError(`${bucketName}: ${missingBinaries} CollectionFS filerecord(s) reference a GridFS file that no longer exists; their binaries cannot be recovered.`);
|
||||
state.files[fileStateKey].errors += missingBinaries;
|
||||
}
|
||||
await metaCursor.close();
|
||||
}
|
||||
|
||||
await migrateGridFs('attachments', ATTACH_DIR, 'attachments');
|
||||
@@ -1115,98 +1411,237 @@ async function run() {
|
||||
saveCheckpoint(true);
|
||||
|
||||
// Also migrate any attachments that are already in Meteor-Files format but stored
|
||||
// in GridFS (storage === 'gridfs') — move binary to filesystem and update record.
|
||||
// in GridFS — move the binary to the filesystem and update the record. #6473: a
|
||||
// version is in GridFS when its storage flag says 'gridfs' OR it carries a
|
||||
// meta.gridFsFileId reference (the same rule WeKan's getFileStrategy uses to pick
|
||||
// the read backend). The old query matched only storage === 'gridfs' on the
|
||||
// 'original' version, so records carrying just the reference — which WORKED on
|
||||
// MongoDB — were left pointing at a GridFS that does not exist in FerretDB. A
|
||||
// second, bucket-driven pass then sweeps <bucket>.files by its metadata.fileId
|
||||
// (the way WeKan writes GridFS uploads), so a binary is recovered even when its
|
||||
// record's flags say nothing about GridFS.
|
||||
state.phase_detail = 'Migrating Meteor-Files GridFS records to filesystem…';
|
||||
let mfAborted = false;
|
||||
for (const [collName, destDir, fileStateKey] of [
|
||||
['attachments', ATTACH_DIR, 'attachments'],
|
||||
['avatars', AVATAR_DIR, 'avatars'],
|
||||
]) {
|
||||
if (mfAborted) break;
|
||||
if (!allColls.includes(collName)) continue;
|
||||
const col = srcDb.collection(collName);
|
||||
const cursor = col.find({ 'versions.original.storage': 'gridfs' });
|
||||
const bucket = new GridFSBucket(srcDb, { bucketName: collName });
|
||||
// Every (record, version) the record-driven pass walked this run — the bucket
|
||||
// sweep must not double-count them.
|
||||
const seenByRecordPass = new Set();
|
||||
// GridFS-marked versions whose binary could not be located yet; the bucket
|
||||
// sweep resolves them by metadata.fileId, anything left is reported.
|
||||
const unresolved = new Set();
|
||||
|
||||
for await (const doc of cursor) {
|
||||
const gridFsId = doc.versions?.original?.meta?.gridFsFileId;
|
||||
if (!gridFsId) continue;
|
||||
const originalName = doc.name || String(doc._id);
|
||||
const size = (doc.versions && doc.versions.original && doc.versions.original.size) || doc.size || 0;
|
||||
const { fullPath, basename } = destFilePath(destDir, String(doc._id), originalName);
|
||||
const resumeKeyFor = (recordId, versionName) =>
|
||||
versionName === 'original' ? `${collName}:${recordId}` : `${collName}.${versionName}:${recordId}`;
|
||||
|
||||
const resumeKey = `${collName}:${doc._id}`;
|
||||
const done = alreadyExtracted(resumeKey);
|
||||
if (done) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(done.size) || 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!DRY_RUN && !ensureDiskForFile(destDir, size, originalName)) { await cursor.close(); onDiskAbort(); await finishAbort(); return; }
|
||||
// Extract one GridFS file and (when updateRecord) repoint the target record's
|
||||
// version at the on-disk file. Returns false when the migration must stop.
|
||||
const moveOne = async (recordId, versionName, gridFsId, originalName, size, updateRecord) => {
|
||||
const idHex = versionName === 'original' ? String(recordId) : `${recordId}-${versionName}`;
|
||||
const { fullPath, basename } = destFilePath(destDir, idHex, originalName);
|
||||
if (!DRY_RUN && !ensureDiskForFile(destDir, size, originalName)) { onDiskAbort(); return false; }
|
||||
|
||||
fileIndex++;
|
||||
state.current = { active: true, kind: fileStateKey, name: originalName, size, done: 0, index: fileIndex, total: state.current.total };
|
||||
|
||||
if (DRY_RUN) { state.files[fileStateKey].done++; state.current.active = false; continue; }
|
||||
if (DRY_RUN) { state.files[fileStateKey].done++; state.current.active = false; return true; }
|
||||
|
||||
try {
|
||||
const bytes = await extractGridFsFile(bucket, gridFsId, fullPath, (w) => { state.current.done = w; updateDiskFree(destDir); });
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += bytes;
|
||||
state.current.done = bytes;
|
||||
await tgtDb.collection(collName).updateOne(
|
||||
{ _id: doc._id },
|
||||
{
|
||||
$set: {
|
||||
path: fullPath,
|
||||
'meta.storedBasename': basename,
|
||||
'meta.originalFilename': originalName,
|
||||
'versions.original.path': fullPath,
|
||||
'versions.original.storage': 'fs',
|
||||
'versions.original.meta': {},
|
||||
},
|
||||
},
|
||||
);
|
||||
completedFiles.set(resumeKey, { path: fullPath, size: bytes });
|
||||
if (updateRecord) {
|
||||
const set = {
|
||||
[`versions.${versionName}.path`]: fullPath,
|
||||
[`versions.${versionName}.storage`]: 'fs',
|
||||
// Drop the version's meta (and with it gridFsFileId) — otherwise WeKan's
|
||||
// getFileStrategy keeps choosing the GridFS backend, where the data no
|
||||
// longer lives, and the download 404s.
|
||||
[`versions.${versionName}.meta`]: {},
|
||||
};
|
||||
if (versionName === 'original') {
|
||||
set.path = fullPath;
|
||||
set['meta.storedBasename'] = basename;
|
||||
set['meta.originalFilename'] = originalName;
|
||||
}
|
||||
await tgtDb.collection(collName).updateOne({ _id: recordId }, { $set: set });
|
||||
}
|
||||
completedFiles.set(resumeKeyFor(recordId, versionName), { path: fullPath, size: bytes });
|
||||
saveCheckpoint();
|
||||
} catch (err) {
|
||||
if (err && (err.code === 'ENOSPC' || err.code === 'EDQUOT')) flagDiskFull('write failed: ' + err.code);
|
||||
pushError(`Move GridFS→fs ${collName}/${doc._id}: ${err.message}`);
|
||||
pushError(`Move GridFS→fs ${collName}/${recordId}: ${err.message}`);
|
||||
state.files[fileStateKey].errors++;
|
||||
try { fs.unlinkSync(fullPath); } catch { /* ignore */ }
|
||||
} finally { state.current.active = false; }
|
||||
return !state.abort;
|
||||
};
|
||||
|
||||
if (state.abort) { await cursor.close(); onDiskAbort(); await finishAbort(); return; }
|
||||
// ── Pass A: record-driven (any version flagged gridfs or carrying gridFsFileId) ──
|
||||
const cursor = col.find(MF_GRIDFS_QUERY);
|
||||
for await (const doc of cursor) {
|
||||
// #6473: the SOURCE record is frozen (MongoDB is never modified), so on a
|
||||
// re-run it stays flagged gridfs forever. Ask the TARGET what actually still
|
||||
// needs doing — that is what makes the automatic startup repair incremental.
|
||||
let tgtDoc = null;
|
||||
if (!DRY_RUN) {
|
||||
tgtDoc = await getTgtRec(collName, doc._id);
|
||||
}
|
||||
for (const [versionName, version] of Object.entries(doc.versions || {})) {
|
||||
if (!version || typeof version !== 'object') continue;
|
||||
const marked = version.storage === 'gridfs' || (version.meta && version.meta.gridFsFileId);
|
||||
if (!marked) continue;
|
||||
|
||||
const resumeKey = resumeKeyFor(String(doc._id), versionName);
|
||||
seenByRecordPass.add(resumeKey);
|
||||
|
||||
// ALREADY MIGRATED: the target's version is on the filesystem and the file
|
||||
// exists — verify-and-skip.
|
||||
const tv = tgtDoc && tgtDoc.versions && tgtDoc.versions[versionName];
|
||||
if (tv && tv.storage === 'fs' && tv.path && fs.existsSync(tv.path)) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(tv.size) || 0;
|
||||
let onDiskSize = Number(tv.size) || 0;
|
||||
try { onDiskSize = fs.statSync(tv.path).size; } catch { /* keep record size */ }
|
||||
completedFiles.set(resumeKey, { path: tv.path, size: onDiskSize });
|
||||
saveCheckpoint();
|
||||
continue;
|
||||
}
|
||||
// Repair mode: the record was DELETED in the target since the migration —
|
||||
// do not resurrect its binary.
|
||||
if (repairMode && !tgtDoc) continue;
|
||||
|
||||
const done = alreadyExtracted(resumeKey);
|
||||
if (done) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(done.size) || 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
const gridFsId = version.meta && version.meta.gridFsFileId;
|
||||
if (!gridFsId) {
|
||||
// Flagged as GridFS but carries no file id — the bucket sweep below can
|
||||
// still find the binary by its metadata.fileId back-reference.
|
||||
unresolved.add(resumeKey);
|
||||
continue;
|
||||
}
|
||||
const originalName = doc.name || String(doc._id);
|
||||
const size = version.size || doc.size || 0;
|
||||
if (!await moveOne(String(doc._id), versionName, gridFsId, originalName, size, true)) {
|
||||
await cursor.close(); mfAborted = true; break;
|
||||
}
|
||||
}
|
||||
if (mfAborted) break;
|
||||
}
|
||||
if (!mfAborted) await cursor.close();
|
||||
if (mfAborted) break;
|
||||
|
||||
// ── Pass B: bucket-driven sweep of <bucket>.files by metadata.fileId ──
|
||||
if (allColls.includes(`${collName}.files`)) {
|
||||
const bfCursor = srcDb.collection(`${collName}.files`).find({});
|
||||
for await (const gf of bfCursor) {
|
||||
const md = gf.metadata || {};
|
||||
const recordId = md.fileId ? String(md.fileId) : String(gf._id);
|
||||
const versionName = md.versionName || 'original';
|
||||
const resumeKey = resumeKeyFor(recordId, versionName);
|
||||
// Pass A already handled+counted it — EXCEPT the unresolved ones (flagged
|
||||
// gridfs but no gridFsFileId), which are exactly what this sweep recovers.
|
||||
if (seenByRecordPass.has(resumeKey) && !unresolved.has(resumeKey)) continue;
|
||||
|
||||
// Ask the TARGET (the live database — the source is frozen) what this
|
||||
// record looks like now.
|
||||
const record = md.fileId ? await getTgtRec(collName, md.fileId) : null;
|
||||
const recVersion = record && record.versions && record.versions[versionName];
|
||||
// The record's version already lives happily on the filesystem: this bucket
|
||||
// file is a stale leftover of an earlier move — leave both alone.
|
||||
if (recVersion && recVersion.storage === 'fs' && recVersion.path && fs.existsSync(recVersion.path)) continue;
|
||||
// Repair mode: the record was DELETED in the target since the migration —
|
||||
// do not resurrect its binary.
|
||||
if (repairMode && md.fileId && !record) continue;
|
||||
|
||||
const done = alreadyExtracted(resumeKey);
|
||||
if (done) {
|
||||
fileIndex++;
|
||||
state.files[fileStateKey].done++;
|
||||
state.files[fileStateKey].bytes += Number(done.size) || 0;
|
||||
unresolved.delete(resumeKey);
|
||||
continue;
|
||||
}
|
||||
|
||||
const originalName = (record && record.name) || gf.filename || recordId;
|
||||
const size = gf.length || 0;
|
||||
// Work the up-front count could not know about (unresolved ones were counted).
|
||||
if (!unresolved.has(resumeKey)) state.current.total++;
|
||||
if (!await moveOne(recordId, versionName, gf._id, originalName, size, !!record)) {
|
||||
await bfCursor.close(); mfAborted = true; break;
|
||||
}
|
||||
unresolved.delete(resumeKey);
|
||||
}
|
||||
if (!mfAborted) await bfCursor.close();
|
||||
if (mfAborted) break;
|
||||
}
|
||||
|
||||
if (unresolved.size > 0) {
|
||||
pushError(`${collName}: ${unresolved.size} GridFS-flagged version(s) whose binary could not be located in ${collName}.files; they cannot be extracted.`);
|
||||
state.files[fileStateKey].errors += unresolved.size;
|
||||
}
|
||||
await cursor.close();
|
||||
}
|
||||
if (mfAborted) { onDiskAbort(); await finishAbort(); return; }
|
||||
|
||||
// ── 8. Write completion marker ─────────────────────────────────────────
|
||||
if (!DRY_RUN) {
|
||||
await markerColl.replaceOne(
|
||||
{ _id: 'completed' },
|
||||
{
|
||||
_id: 'completed',
|
||||
schemaVersion: SCHEMA_VER,
|
||||
completedAt: new Date(),
|
||||
sourceUrl: SOURCE_URL,
|
||||
targetUrl: TARGET_URL,
|
||||
dryRun: DRY_RUN,
|
||||
collections: Object.fromEntries(
|
||||
Object.entries(state.collections).map(([k, v]) => [k, { done: v.done, errors: v.errors }])
|
||||
),
|
||||
files: state.files,
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
saveCheckpoint(true);
|
||||
if (repairMode) {
|
||||
// #6473: an incremental repair only STAMPS the marker's filesVersion (plus the
|
||||
// repair stats); the original migration record — collections copied, when, from
|
||||
// where — must stay intact, and a repair must never fabricate a "completed"
|
||||
// marker where none exists.
|
||||
if (marker) {
|
||||
await markerColl.updateOne(
|
||||
{ _id: 'completed' },
|
||||
{ $set: { filesVersion: FILES_VERSION, filesRepairedAt: new Date(), filesRepair: state.files } },
|
||||
).catch(e => pushError('marker filesVersion update: ' + e.message));
|
||||
}
|
||||
saveCheckpoint(true);
|
||||
} else {
|
||||
await markerColl.replaceOne(
|
||||
{ _id: 'completed' },
|
||||
{
|
||||
_id: 'completed',
|
||||
schemaVersion: SCHEMA_VER,
|
||||
filesVersion: FILES_VERSION,
|
||||
completedAt: new Date(),
|
||||
sourceUrl: SOURCE_URL,
|
||||
targetUrl: TARGET_URL,
|
||||
dryRun: DRY_RUN,
|
||||
collections: Object.fromEntries(
|
||||
Object.entries(state.collections).map(([k, v]) => [k, { done: v.done, errors: v.errors }])
|
||||
),
|
||||
files: state.files,
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
saveCheckpoint(true);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 8b. Reclaim old MongoDB disk space now that everything is migrated ──
|
||||
try { await compactSource(srcDb, markerColl); } catch (e) { pushError('compact: ' + e.message); }
|
||||
// (skipped in repair mode — compact already ran after the original migration)
|
||||
if (!repairMode) {
|
||||
try { await compactSource(srcDb, markerColl); } catch (e) { pushError('compact: ' + e.message); }
|
||||
}
|
||||
|
||||
// ── 9. Ensure indexes on commonly-queried fields ───────────────────────
|
||||
if (!DRY_RUN) {
|
||||
// (skipped in repair mode — they were created by the original migration)
|
||||
if (!DRY_RUN && !repairMode) {
|
||||
state.phase = 'creating-indexes';
|
||||
state.phase_detail = 'Creating indexes on target…';
|
||||
try {
|
||||
@@ -1236,7 +1671,9 @@ async function run() {
|
||||
if (totalErrors === 0) {
|
||||
state.phase = 'completed';
|
||||
state.success = true;
|
||||
console.log('[migrate] ✓ Migration completed successfully.');
|
||||
console.log(repairMode
|
||||
? `[migrate] ✓ Attachment repair completed: ${state.files.attachments.done} attachments, ${state.files.avatars.done} avatars verified/migrated.`
|
||||
: '[migrate] ✓ Migration completed successfully.');
|
||||
} else {
|
||||
state.phase = 'completed-with-errors';
|
||||
// #6466: per-item errors (one unparsable document, one attachment/avatar that
|
||||
@@ -1271,6 +1708,11 @@ Environment variables:
|
||||
BATCH_SIZE Docs per write batch (default: 200)
|
||||
DRY_RUN true = no writes (default: false)
|
||||
FORCE_MIGRATE true = ignore done marker (default: false)
|
||||
FILES_ONLY true = incremental attachment/avatar repair only: text
|
||||
data is left untouched, already-migrated files are
|
||||
verified and skipped, only missing binaries/records are
|
||||
migrated. Also turned on automatically when the target's
|
||||
migration marker has filesVersion < ${FILES_VERSION}.
|
||||
|
||||
Files are written to:
|
||||
\$WRITABLE_PATH/files/attachments/
|
||||
|
||||
@@ -22,10 +22,10 @@ const pkgdef :Spk.PackageDefinition = (
|
||||
appTitle = (defaultText = "Wekan"),
|
||||
# The name of the app as it is displayed to the user.
|
||||
|
||||
appVersion = 996,
|
||||
appVersion = 997,
|
||||
# Increment this for every release.
|
||||
|
||||
appMarketingVersion = (defaultText = "9.96~2026-07-16"),
|
||||
appMarketingVersion = (defaultText = "9.97~2026-07-17"),
|
||||
# Human-readable presentation of the app version.
|
||||
|
||||
minUpgradableAppVersion = 0,
|
||||
|
||||
+25
-22
@@ -9,6 +9,10 @@ import { Accounts } from 'meteor/accounts-base';
|
||||
// server boot. Import them explicitly.
|
||||
import Users from '/models/users';
|
||||
import Activities from '/models/activities';
|
||||
import {
|
||||
claimUniqueUsername,
|
||||
usernameCaseInsensitiveRegex,
|
||||
} from '/models/lib/sandstormUsername';
|
||||
|
||||
// Sandstorm context is detected using the METEOR_SETTINGS environment variable
|
||||
// in the package definition.
|
||||
@@ -326,29 +330,28 @@ if (isSandstorm && Meteor.isServer) {
|
||||
// Sandstorm doesn't enforce this property -- see #352. Our strategy to
|
||||
// generate unique usernames from the Sandstorm `preferredHandle` is to
|
||||
// append a number that we increment until we generate a username that no
|
||||
// one already uses (eg, 'max', 'max1', 'max2').
|
||||
function generateUniqueUsername(username, appendNumber) {
|
||||
return username + String(appendNumber === 0 ? '' : appendNumber);
|
||||
}
|
||||
|
||||
// one already uses (eg, 'max', 'max1', 'max2'). Meteor usernames are
|
||||
// case-preserving but case-insensitively unique, so the probe uses an
|
||||
// anchored case-insensitive regex (escaped, see #574), and the update is
|
||||
// retried with the next number when a concurrent insert wins the race to
|
||||
// the same name (unique-index duplicate-key error).
|
||||
const username = doc.services.sandstorm.preferredHandle;
|
||||
let appendNumber = 0;
|
||||
while (
|
||||
await Meteor.users.findOneAsync({
|
||||
_id: { $ne: doc._id },
|
||||
username: generateUniqueUsername(username, appendNumber),
|
||||
})
|
||||
) {
|
||||
appendNumber += 1;
|
||||
}
|
||||
|
||||
await Users.updateAsync(doc._id, {
|
||||
$set: {
|
||||
username: generateUniqueUsername(username, appendNumber),
|
||||
'profile.fullname': doc.services.sandstorm.name,
|
||||
'profile.avatarUrl': doc.services.sandstorm.picture,
|
||||
},
|
||||
});
|
||||
await claimUniqueUsername(
|
||||
username,
|
||||
async candidate =>
|
||||
!!(await Meteor.users.findOneAsync({
|
||||
_id: { $ne: doc._id },
|
||||
username: usernameCaseInsensitiveRegex(candidate),
|
||||
})),
|
||||
candidate =>
|
||||
Users.updateAsync(doc._id, {
|
||||
$set: {
|
||||
username: candidate,
|
||||
'profile.fullname': doc.services.sandstorm.name,
|
||||
'profile.avatarUrl': doc.services.sandstorm.picture,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await updateUserPermissions(doc._id, doc.services.sandstorm.permissions);
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ const { Accounts } = require('meteor/accounts-base');
|
||||
const { WebApp } = require('meteor/webapp');
|
||||
const { check, Match } = require('meteor/check');
|
||||
const { sendJsonResult } = require('/server/apiMiddleware');
|
||||
const { buildLogoutPlan } = require('/models/lib/apiLogout');
|
||||
|
||||
const NonEmptyString = Match.Where(function (x) {
|
||||
check(x, String);
|
||||
@@ -100,6 +101,60 @@ WebApp.handlers.post('/users/login', async function (req, res) {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /users/logout
|
||||
// Fixes #1437 ("Old tokens are not replaced or set invalid"): the API could
|
||||
// mint tokens via /users/login but never revoke them, so old/leaked tokens
|
||||
// stayed valid until their expiry. Authenticate with the token to revoke
|
||||
// (Authorization: Bearer <token>); by default only that token is removed.
|
||||
// Send { "all": true } in the body to revoke every login token of the user.
|
||||
// ---------------------------------------------------------------------------
|
||||
WebApp.handlers.options('/users/logout', function (req, res) {
|
||||
sendJsonResult(res);
|
||||
});
|
||||
|
||||
WebApp.handlers.post('/users/logout', async function (req, res) {
|
||||
try {
|
||||
// req.userId / req.authToken are set by the apiMiddleware bearer-token
|
||||
// and authenticateByToken middleware (loaded above via require).
|
||||
const hashedToken = req.authToken
|
||||
? Accounts._hashLoginToken(req.authToken)
|
||||
: null;
|
||||
const plan = buildLogoutPlan({
|
||||
userId: req.userId,
|
||||
hashedToken,
|
||||
all: req.body && req.body.all,
|
||||
});
|
||||
|
||||
if (!plan.ok) {
|
||||
sendJsonResult(res, {
|
||||
code: plan.status,
|
||||
data: { error: plan.error, reason: plan.reason },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await Meteor.users.updateAsync(plan.selector, plan.modifier);
|
||||
|
||||
sendJsonResult(res, {
|
||||
data: {
|
||||
message: plan.all
|
||||
? 'All login tokens have been invalidated.'
|
||||
: "You've been logged out!",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
res.statusCode = error.statusCode || 500;
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
error: error.error || error.message || 'Logout failed',
|
||||
reason: error.reason || error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /users/register
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { ReactiveCache } from '/imports/reactiveCache';
|
||||
|
||||
const {
|
||||
shouldRejectPasswordLogin,
|
||||
LDAP_PASSWORD_LOGIN_DISABLED_REASON,
|
||||
} = require('/server/lib/ldapPasswordLoginGuard');
|
||||
|
||||
// Authentication helpers — exported for use by API routes and model files
|
||||
export const Authentication = {
|
||||
async checkUserId(userId) {
|
||||
@@ -84,6 +89,31 @@ Meteor.startup(() => {
|
||||
return !user.loginDisabled;
|
||||
});
|
||||
|
||||
// #4419 (Severity:Security): after a user is migrated from local password
|
||||
// login to LDAP (authenticationMethod: 'ldap'), the stale local password in
|
||||
// services.password would otherwise still work. Reject password-service
|
||||
// logins for LDAP users — but only while LDAP is actually enabled, never for
|
||||
// other services ('ldap', 'resume', 'oidc', 'cas', 'saml', …), never when
|
||||
// LDAP_LOGIN_FALLBACK=true (that feature intentionally routes LDAP logins
|
||||
// through the password service), and never when the operator opted out with
|
||||
// LDAP_MIGRATION_ALLOW_PASSWORD_LOGIN=true. Full decision logic and
|
||||
// rationale live in server/lib/ldapPasswordLoginGuard.js.
|
||||
Accounts.validateLoginAttempt(function(options) {
|
||||
if (
|
||||
shouldRejectPasswordLogin({
|
||||
serviceName: options.type,
|
||||
user: options.user,
|
||||
env: process.env,
|
||||
})
|
||||
) {
|
||||
throw new Meteor.Error(
|
||||
'ldap-password-login-disabled',
|
||||
LDAP_PASSWORD_LOGIN_DISABLED_REASON,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if (Meteor.isServer) {
|
||||
if (
|
||||
process.env.ORACLE_OIM_ENABLED === 'true' ||
|
||||
@@ -94,7 +124,13 @@ Meteor.startup(() => {
|
||||
{ service: 'oidc' },
|
||||
{
|
||||
$set: {
|
||||
loginStyle: process.env.OAUTH2_LOGIN_STYLE || 'redirect',
|
||||
// #5695: the client now honors a configured 'redirect' style, so
|
||||
// the fallback here must stay 'popup' to keep popup the default
|
||||
// behavior when OAUTH2_LOGIN_STYLE is not set.
|
||||
loginStyle:
|
||||
process.env.OAUTH2_LOGIN_STYLE === 'redirect'
|
||||
? 'redirect'
|
||||
: 'popup',
|
||||
clientId: process.env.OAUTH2_CLIENT_ID,
|
||||
secret: process.env.OAUTH2_SECRET,
|
||||
serverUrl: process.env.OAUTH2_SERVER_URL,
|
||||
@@ -116,7 +152,13 @@ Meteor.startup(() => {
|
||||
{ service: 'oidc' },
|
||||
{
|
||||
$set: {
|
||||
loginStyle: process.env.OAUTH2_LOGIN_STYLE || 'redirect',
|
||||
// #5695: the client now honors a configured 'redirect' style, so
|
||||
// the fallback here must stay 'popup' to keep popup the default
|
||||
// behavior when OAUTH2_LOGIN_STYLE is not set.
|
||||
loginStyle:
|
||||
process.env.OAUTH2_LOGIN_STYLE === 'redirect'
|
||||
? 'redirect'
|
||||
: 'popup',
|
||||
clientId: process.env.OAUTH2_CLIENT_ID,
|
||||
secret: process.env.OAUTH2_SECRET,
|
||||
serverUrl: process.env.OAUTH2_SERVER_URL,
|
||||
|
||||
@@ -195,6 +195,9 @@ import '/server/migrations/fixMissingListsMigration';
|
||||
import '/server/migrations/migrateAttachments';
|
||||
import '/server/migrations/restoreAllArchived';
|
||||
import '/server/migrations/restoreLostCards';
|
||||
// #6473: startup schema upgrade — checks what old-version data is already
|
||||
// migrated and migrates only the rest (all platforms, both databases).
|
||||
import '/server/startupSchemaUpgrade';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// 12. Server — notifications
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// Pure, dependency-free helper (no Meteor imports) so it can be unit tested
|
||||
// directly with plain Node. Used by the `Accounts.validateLoginAttempt` hook
|
||||
// registered in server/authentication.js.
|
||||
//
|
||||
// #4419 (Severity:Security): when an instance migrates a user from local
|
||||
// password login to LDAP (Admin Panel sets `authenticationMethod: 'ldap'`),
|
||||
// the user's old `services.password` hash is left in place, so the stale —
|
||||
// possibly weaker — local password KEEPS working alongside the LDAP password.
|
||||
// The safe fix (per this repo's own triage in CHANGELOG.md "TODO Later") is to
|
||||
// reject password-service login attempts for such users at validation time
|
||||
// instead of destructively `$unset`-ing `services.password`.
|
||||
//
|
||||
// The decision is deliberately conservative. A password-service login attempt
|
||||
// is rejected ONLY when ALL of the following hold:
|
||||
//
|
||||
// 1. The attempted login service is 'password' (`attempt.type` from
|
||||
// Meteor's validateLoginAttempt). All other services — 'ldap', 'oidc',
|
||||
// 'cas', 'saml', 'resume' (session token resume), … — are never touched,
|
||||
// so existing sessions and every non-password login flow keep working.
|
||||
// 2. The user document has `authenticationMethod === 'ldap'`. Users without
|
||||
// the field, or with any other value ('password', 'oauth2', 'cas',
|
||||
// 'saml', 'imported', …), are never rejected.
|
||||
// 3. LDAP is actually enabled in this deployment: LDAP_ENABLE=true
|
||||
// (same env check as isLdapEnabled() in server/models/settings.js). If
|
||||
// LDAP has been turned off — e.g. an instance de-LDAPed or a directory
|
||||
// decommissioned — password login must keep working so admins are never
|
||||
// locked out.
|
||||
// 4. LDAP_LOGIN_FALLBACK is NOT enabled. With LDAP_LOGIN_FALLBACK=true the
|
||||
// wekan-ldap login handler *intentionally* falls back to the local
|
||||
// password service and syncs the LDAP password into
|
||||
// `services.password` on every LDAP login (see
|
||||
// packages/wekan-ldap/server/loginHandler.js). That fallback surfaces in
|
||||
// validateLoginAttempt with type 'password', so rejecting it would break
|
||||
// the documented fallback feature.
|
||||
// 5. The operator has not opted out. Setting
|
||||
// LDAP_MIGRATION_ALLOW_PASSWORD_LOGIN=true restores the old behavior
|
||||
// (local password login stays valid for LDAP-migrated users), so no
|
||||
// deployment can be hard-locked by upgrading WeKan. Document/announce
|
||||
// this var wherever LDAP env vars are documented.
|
||||
//
|
||||
// The same rule applies to every user — admins are not treated differently.
|
||||
|
||||
'use strict';
|
||||
|
||||
// Error reason shown to the user when the guard rejects the login.
|
||||
const LDAP_PASSWORD_LOGIN_DISABLED_REASON =
|
||||
'Use LDAP login; local password login is disabled for this account';
|
||||
|
||||
// Mirrors the truthiness convention used across server/models/settings.js
|
||||
// (isLdapEnabled etc.): env vars are the string 'true', but a literal boolean
|
||||
// true is also accepted.
|
||||
function envFlagIsTrue(value) {
|
||||
return value === 'true' || value === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether a login attempt must be rejected because the account was
|
||||
* migrated to LDAP but still carries a stale local password.
|
||||
*
|
||||
* @param {Object} params
|
||||
* @param {string} params.serviceName - the login service of the attempt
|
||||
* (Meteor's `attempt.type`), e.g. 'password', 'ldap', 'resume', 'oidc'.
|
||||
* @param {Object|undefined} params.user - the user document of the attempt
|
||||
* (may be undefined for unknown-user attempts).
|
||||
* @param {Object|undefined} params.env - the environment (process.env).
|
||||
* @return {boolean} true when the password-service login must be rejected.
|
||||
*/
|
||||
function shouldRejectPasswordLogin({ serviceName, user, env } = {}) {
|
||||
const environment = env || {};
|
||||
|
||||
// (1) Only the local password service is ever guarded.
|
||||
if (serviceName !== 'password') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// (2) Only users explicitly migrated to LDAP.
|
||||
if (!user || user.authenticationMethod !== 'ldap') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// (3) Only when LDAP is enabled in this deployment; otherwise password
|
||||
// login must keep working (never lock admins out of a de-LDAPed instance).
|
||||
if (!envFlagIsTrue(environment.LDAP_ENABLE)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// (4) LDAP_LOGIN_FALLBACK intentionally logs LDAP users in through the
|
||||
// password service; do not break that feature.
|
||||
if (envFlagIsTrue(environment.LDAP_LOGIN_FALLBACK)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// (5) Operator opt-out: keep the pre-#4419-fix behavior.
|
||||
if (envFlagIsTrue(environment.LDAP_MIGRATION_ALLOW_PASSWORD_LOGIN)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
shouldRejectPasswordLogin,
|
||||
LDAP_PASSWORD_LOGIN_DISABLED_REASON,
|
||||
};
|
||||
@@ -0,0 +1,808 @@
|
||||
// ============================================================================
|
||||
// Startup schema upgrade (#6473 follow-up): bring TEXT DATA from EVERY old
|
||||
// WeKan version to the newest database structure — on all platforms (Snap,
|
||||
// Docker, Sandstorm, source) and regardless of database (MongoDB or
|
||||
// FerretDB/SQLite, both speak the same wire protocol via the driver `Db`
|
||||
// handle this module receives).
|
||||
//
|
||||
// WeKan v0.9–v8.00 ran `Migrations.add(...)` steps at startup; v8.01 disabled
|
||||
// them (large databases caused long downtime) in favour of read-time
|
||||
// compatibility — which covers the swimlane era but NOT everything. Data that
|
||||
// jumped straight from an old version (or an old backup/Sandstorm grain) to
|
||||
// current WeKan can still hold pre-migration shapes that today's code simply
|
||||
// does not show: the text is in the database, but invisible.
|
||||
//
|
||||
// This module reinstates the safety net WITHOUT the downtime problem:
|
||||
// - VERSION-GATED: the `_wekan_migration` marker stores the WeKan version and
|
||||
// datetime of the last successful re-check. While the version is unchanged,
|
||||
// a boot costs ONE findOne — the re-check is mandatory only after a new
|
||||
// WeKan release (or WEKAN_FORCE_SCHEMA_UPGRADE=true).
|
||||
// - After a version change it RE-CHECKS everything and migrates ONLY what is
|
||||
// missing, using the fastest available query shapes for big databases
|
||||
// (thousands of cards): bounded findOne/countDocuments existence probes,
|
||||
// distinct() joins instead of full scans, and server-side updateMany
|
||||
// batches instead of per-document round trips.
|
||||
// - Every step is idempotent, so an interrupted boot resumes safely, and a
|
||||
// step failure never blocks WeKan from starting.
|
||||
// - Progress is published (getUpgradeState) for the migration dashboard,
|
||||
// which shows the Admin Panel product name when one is set.
|
||||
//
|
||||
// Steps (each replicates a v8.00 `server/migrations.js` step that has no
|
||||
// replacement in current WeKan, verified against `git show v8.00:server/migrations.js`):
|
||||
// archived-flag-backfill old docs missing `archived` never match the
|
||||
// archived:false view queries -> invisible
|
||||
// swimlane-structure add-swimlanes (v0.65) + dangling-listId rescue +
|
||||
// #1959/#1971 Swimlanes-view visibility rescue
|
||||
// (cards under deleted/archived/foreign swimlanes)
|
||||
// checklist-items-embedded add-checklist-items (v0.79): embedded
|
||||
// checklist.items[] -> ChecklistItems collection
|
||||
// customfields-boardIds mutate-boardIds-in-customfields (v2.49):
|
||||
// scalar boardId -> boardIds array
|
||||
// board-allows-defaults the add-*-allowed steps (v2.9–v5.43): missing
|
||||
// allows* flags render as undefined=false and HIDE
|
||||
// existing description/checklist/comment text
|
||||
// board-members-isactive add-member-isactive-field: members without
|
||||
// isActive are denied board access by
|
||||
// isActiveMember()
|
||||
// board-permission-lowercase lowercase-board-permission: 'PUBLIC' boards
|
||||
// silently became member-only
|
||||
// fs-path-heal filesystem attachments/avatars whose recorded
|
||||
// path predates the current WRITABLE_PATH layout
|
||||
// (v6.10-18 uploads/<coll>, v6.19-v8.4x
|
||||
// WRITABLE_PATH/<coll>, CFS->ostrio temp files):
|
||||
// locate the binary and repoint/copy it
|
||||
//
|
||||
// Pure, dependency-free (no Meteor imports) so it can be unit tested with
|
||||
// plain Node against a driver-compatible Db object. The Meteor wrapper (and
|
||||
// the /schema-upgrade-status dashboard) is server/startupSchemaUpgrade.js.
|
||||
// ============================================================================
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { computeStoragePaths } = require('../../models/lib/attachmentStoragePath');
|
||||
|
||||
const MARKER_COLL = '_wekan_migration';
|
||||
const MARKER_ID = 'schema-upgrade';
|
||||
|
||||
// Meteor-style random document ids (Random.id(): 17 chars, unmistakable set),
|
||||
// so upgraded documents look exactly like app-created ones.
|
||||
const ID_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz';
|
||||
function randomId(len = 17) {
|
||||
const bytes = crypto.randomBytes(len);
|
||||
let out = '';
|
||||
for (let i = 0; i < len; i++) out += ID_CHARS[bytes[i] % ID_CHARS.length];
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── live progress state for the migration dashboard ─────────────────────────
|
||||
const upgradeState = {
|
||||
running: false,
|
||||
product: 'WeKan', // Admin Panel product name when set
|
||||
appVersion: '',
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
currentStep: '',
|
||||
gated: false, // true = skipped because the version was unchanged
|
||||
steps: {}, // name -> {status: pending|checking|running|done|skipped|error, fixed, unresolved, error}
|
||||
lastCheck: null, // {version, at} of the previous successful re-check
|
||||
};
|
||||
function getUpgradeState() { return upgradeState; }
|
||||
function resetState(appVersion) {
|
||||
upgradeState.running = true;
|
||||
upgradeState.product = 'WeKan';
|
||||
upgradeState.appVersion = appVersion || '';
|
||||
upgradeState.startedAt = new Date();
|
||||
upgradeState.finishedAt = null;
|
||||
upgradeState.currentStep = '';
|
||||
upgradeState.gated = false;
|
||||
upgradeState.steps = {};
|
||||
for (const s of steps) upgradeState.steps[s.name] = { status: 'pending', fixed: 0, unresolved: 0 };
|
||||
}
|
||||
|
||||
// Board feature flags with schema defaultValue: true. SimpleSchema applies
|
||||
// defaults ON INSERT ONLY, and the templates do raw property access — a board
|
||||
// created before the flag existed reads `undefined`, which renders as FALSE
|
||||
// and hides existing text (descriptions, checklists, comments, attachments).
|
||||
// Kept in sync with models/boards.js by tests/schemaUpgradeSteps.test.cjs.
|
||||
const BOARD_ALLOWS_TRUE_DEFAULTS = [
|
||||
'allowsSubtasks', 'allowsSubtasksOnMinicard',
|
||||
'allowsAttachments', 'allowsAttachmentsOnMinicard',
|
||||
'allowsChecklists', 'allowsChecklistsOnMinicard',
|
||||
'allowsComments',
|
||||
'allowsDescriptionTitle', 'allowsDescriptionTitleOnMinicard',
|
||||
'allowsDescriptionText',
|
||||
'allowsCoverAttachmentOnMinicard',
|
||||
'allowsActivities',
|
||||
'allowsLabels', 'allowsLabelsOnMinicard',
|
||||
'allowsCreator',
|
||||
'allowsAssignee', 'allowsAssigneeOnMinicard',
|
||||
'allowsMembers', 'allowsMembersOnMinicard',
|
||||
'allowsRequestedBy', 'allowsRequestedByOnMinicard',
|
||||
'allowsCardSortingByNumber',
|
||||
'allowsShowLists',
|
||||
'allowsAssignedBy', 'allowsAssignedByOnMinicard',
|
||||
'allowsReceivedDate', 'allowsReceivedDateOnMinicard',
|
||||
'allowsStartDate', 'allowsStartDateOnMinicard',
|
||||
'allowsEndDate', 'allowsEndDateOnMinicard',
|
||||
'allowsDueDate', 'allowsDueDateOnMinicard',
|
||||
];
|
||||
|
||||
const MISSING_OR_EMPTY = { $in: [null, ''] }; // matches missing, null and ''
|
||||
|
||||
// ── individual steps ─────────────────────────────────────────────────────────
|
||||
// Each step: { name, check(db,ctx) -> boolean (work exists),
|
||||
// run(db,ctx) -> {fixed, unresolved} } — all idempotent, and all
|
||||
// using bounded/batched queries so big databases stay fast.
|
||||
|
||||
const steps = [
|
||||
{
|
||||
// Old (LibreBoard-era) documents can lack the `archived` field entirely —
|
||||
// and every board/list/card query in current WeKan filters with
|
||||
// `archived: false`, which a MISSING field does not match. Such boards,
|
||||
// swimlanes, lists and cards are invisible in BOTH the Swimlanes view and
|
||||
// the Lists view although their data is intact. One updateMany per
|
||||
// collection backfills the default. Must run FIRST: the visibility rescue
|
||||
// below relies on `archived: false` matching.
|
||||
name: 'archived-flag-backfill',
|
||||
async check(db) {
|
||||
for (const coll of ['boards', 'swimlanes', 'lists', 'cards']) {
|
||||
if (await db.collection(coll).findOne({ archived: { $exists: false } }, { projection: { _id: 1 } })) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
for (const coll of ['boards', 'swimlanes', 'lists', 'cards']) {
|
||||
const r = await db.collection(coll).updateMany(
|
||||
{ archived: { $exists: false } },
|
||||
{ $set: { archived: false } },
|
||||
);
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
}
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// add-swimlanes (v0.65) + the dangling-listId rescue that the disabled
|
||||
// repair tools used to provide, PLUS the Swimlanes-view visibility rescue
|
||||
// of #1959/#1971: every board gets a swimlane, every list/card gets a
|
||||
// swimlaneId, cards whose listId points nowhere are rescued to a visible
|
||||
// list, and unarchived cards whose swimlaneId points at a DELETED,
|
||||
// ARCHIVED or other-board swimlane (invisible in Swimlanes view) are
|
||||
// reassigned to the board's first visible swimlane — so all lists and
|
||||
// cards are visible in both the Swimlanes view and the Lists view.
|
||||
name: 'swimlane-structure',
|
||||
async check(db) {
|
||||
// bounded existence probes — no scans. NOTE: lists with EMPTY swimlaneId
|
||||
// are deliberately NOT backfilled — a shared board-wide list ('') renders
|
||||
// in every swimlane via myLists()'s null/'' fallback, and stamping it to
|
||||
// one swimlane would HIDE it from all other swimlanes in Swimlanes view.
|
||||
if (await db.collection('cards').findOne({ swimlaneId: MISSING_OR_EMPTY }, { projection: { _id: 1 } })) return true;
|
||||
// set-joins via distinct(): result sizes are bounded by the number of
|
||||
// lists/swimlanes/boards, never by the number of cards
|
||||
const boardIds = (await db.collection('boards').distinct('_id')).map(String);
|
||||
const swimlaneBoards = new Set((await db.collection('swimlanes').distinct('boardId')).map(String));
|
||||
if (boardIds.some(b => !swimlaneBoards.has(b))) return true;
|
||||
const listIds = new Set((await db.collection('lists').distinct('_id')).map(String));
|
||||
const usedListIds = (await db.collection('cards').distinct('listId')).map(String);
|
||||
if (usedListIds.some(id => id && id !== 'null' && id !== 'undefined' && !listIds.has(id))) return true;
|
||||
// #1959/#1971: any unarchived card under a deleted/archived/foreign swimlane?
|
||||
const visibleSwimlaneOfBoard = await loadVisibleSwimlanes(db);
|
||||
const usedSwimlaneIds = (await db.collection('cards').distinct('swimlaneId', { archived: false })).map(String);
|
||||
for (const swId of usedSwimlaneIds) {
|
||||
if (!swId || swId === 'null' || swId === 'undefined') continue;
|
||||
const owner = visibleSwimlaneOfBoard.byId.get(swId);
|
||||
if (!owner) return true; // deleted or archived swimlane
|
||||
// same-board check needs the referencing boards (bounded by board count)
|
||||
const boards = (await db.collection('cards').distinct('boardId', { swimlaneId: swId, archived: false })).map(String);
|
||||
if (boards.some(b => b !== owner)) return true; // foreign swimlane
|
||||
}
|
||||
return false;
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
const now = new Date();
|
||||
// a VISIBLE (unarchived, non-template) default swimlane per board —
|
||||
// boards and swimlanes are few. #1959: assigning to any first swimlane
|
||||
// could pick an archived one, and the card stayed invisible.
|
||||
const boards = await db.collection('boards').find({}, { projection: { _id: 1 } }).toArray();
|
||||
let visible = await loadVisibleSwimlanes(db);
|
||||
const defaultSwimlaneOf = new Map(visible.firstOfBoard);
|
||||
for (const b of boards) {
|
||||
const boardId = String(b._id);
|
||||
if (!defaultSwimlaneOf.has(boardId)) {
|
||||
const sw = { _id: randomId(), title: 'Default', boardId, archived: false, sort: 0, type: 'swimlane', createdAt: now, modifiedAt: now, updatedAt: now };
|
||||
await db.collection('swimlanes').insertOne(sw);
|
||||
defaultSwimlaneOf.set(boardId, String(sw._id));
|
||||
visible.byId.set(String(sw._id), boardId);
|
||||
fixed++;
|
||||
}
|
||||
}
|
||||
// missing swimlaneId on CARDS: ONE server-side updateMany per board — no
|
||||
// per-document round trips, no matter how many thousands of cards.
|
||||
// Lists are NOT stamped (see check() note: '' means shared across swimlanes).
|
||||
for (const [boardId, swId] of defaultSwimlaneOf) {
|
||||
const r = await db.collection('cards').updateMany(
|
||||
{ boardId, swimlaneId: MISSING_OR_EMPTY },
|
||||
{ $set: { swimlaneId: swId } },
|
||||
);
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
}
|
||||
// dangling listId rescue: distinct() finds the bad ids (bounded by the
|
||||
// number of lists ever referenced), then one updateMany per (bad id, board)
|
||||
const lists = await db.collection('lists').find({}, { projection: { _id: 1, boardId: 1, swimlaneId: 1, sort: 1 } }).toArray();
|
||||
const listIds = new Set(lists.map(l => String(l._id)));
|
||||
const firstListOf = new Map();
|
||||
for (const l of lists.sort((a, b2) => (a.sort || 0) - (b2.sort || 0))) {
|
||||
if (!firstListOf.has(String(l.boardId))) firstListOf.set(String(l.boardId), l);
|
||||
}
|
||||
const rescuedListOf = new Map();
|
||||
const badListIds = (await db.collection('cards').distinct('listId'))
|
||||
.map(String).filter(id => id && id !== 'null' && id !== 'undefined' && !listIds.has(id));
|
||||
for (const badId of badListIds) {
|
||||
const boardsOfBad = (await db.collection('cards').distinct('boardId', { listId: badId })).map(String);
|
||||
for (const boardId of boardsOfBad) {
|
||||
let target = firstListOf.get(boardId) || rescuedListOf.get(boardId);
|
||||
if (!target) {
|
||||
target = { _id: randomId(), title: 'Rescued Data', boardId, swimlaneId: defaultSwimlaneOf.get(boardId) || '', archived: false, sort: 0, type: 'list', createdAt: now, modifiedAt: now, updatedAt: now };
|
||||
await db.collection('lists').insertOne(target);
|
||||
rescuedListOf.set(boardId, target);
|
||||
}
|
||||
const r = await db.collection('cards').updateMany(
|
||||
{ boardId, listId: badId },
|
||||
{ $set: { listId: String(target._id), swimlaneId: String(target.swimlaneId || defaultSwimlaneOf.get(boardId) || '') } },
|
||||
);
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
}
|
||||
}
|
||||
// #1959/#1971: unarchived cards whose swimlaneId points at a DELETED,
|
||||
// ARCHIVED or other-board swimlane never render in the Swimlanes view.
|
||||
// distinct() bounds the work by the number of referenced swimlanes; the
|
||||
// fix is one updateMany per (bad swimlane, board).
|
||||
const usedSwimlaneIds = (await db.collection('cards').distinct('swimlaneId', { archived: false })).map(String);
|
||||
for (const swId of usedSwimlaneIds) {
|
||||
if (!swId || swId === 'null' || swId === 'undefined') continue;
|
||||
const owner = visible.byId.get(swId);
|
||||
const boardsOfSw = (await db.collection('cards').distinct('boardId', { swimlaneId: swId, archived: false })).map(String);
|
||||
for (const boardId of boardsOfSw) {
|
||||
if (owner === boardId) continue; // visible swimlane on the right board
|
||||
const target = defaultSwimlaneOf.get(boardId);
|
||||
if (!target || target === swId) continue;
|
||||
const r = await db.collection('cards').updateMany(
|
||||
{ boardId, swimlaneId: swId, archived: false },
|
||||
{ $set: { swimlaneId: target } },
|
||||
);
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
}
|
||||
}
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// v7.98 'per-swimlane lists' era: the migrate-lists-to-per-swimlane step
|
||||
// stamped every list to the default swimlane (hiding it from every other
|
||||
// swimlane in today's Swimlanes view), and the v8.07–v8.19 board-open
|
||||
// repair DUPLICATED lists per swimlane (rendering duplicate columns per
|
||||
// title in today's board-wide Lists view). Current WeKan renders shared
|
||||
// lists (swimlaneId '') in every swimlane, so: merge same-title copies
|
||||
// back into ONE shared list — cards keep their own swimlaneId, preserving
|
||||
// per-swimlane grouping and order, and card/list drag between swimlanes
|
||||
// keeps working — then clear the stamped swimlaneIds. Copies the user
|
||||
// RENAMED differently per swimlane are deliberately kept as their own
|
||||
// lists (merging them would lose the distinct names). Boards are detected
|
||||
// by the era's own markers (fixMissingListsCompleted /
|
||||
// comprehensiveMigrationCompleted), duplicate titles, or a list whose
|
||||
// cards disagree with its stamped swimlane; healthy boards are untouched.
|
||||
name: 'merge-per-swimlane-lists',
|
||||
async check(db) {
|
||||
if (await db.collection('boards').findOne(
|
||||
{ $or: [{ fixMissingListsCompleted: true }, { comprehensiveMigrationCompleted: true }] },
|
||||
{ projection: { _id: 1 } },
|
||||
)) return true;
|
||||
const boardIds = (await db.collection('lists').distinct('boardId', { swimlaneId: { $nin: [null, ''] }, type: { $ne: 'template-list' } })).map(String);
|
||||
for (const boardId of boardIds) {
|
||||
const lists = await db.collection('lists').find(
|
||||
{ boardId, type: { $ne: 'template-list' } },
|
||||
{ projection: { title: 1, swimlaneId: 1, archived: 1 } },
|
||||
).toArray();
|
||||
const seen = new Set();
|
||||
for (const l of lists) {
|
||||
if (l.archived === true) continue;
|
||||
if (seen.has(l.title)) return true; // per-swimlane duplicate copies
|
||||
seen.add(l.title);
|
||||
}
|
||||
for (const l of lists) {
|
||||
if (!l.swimlaneId) continue;
|
||||
// Shape A (v7.98 stamp): cards of another swimlane point at this list
|
||||
if (await db.collection('cards').findOne(
|
||||
{ listId: String(l._id), swimlaneId: { $nin: [String(l.swimlaneId), null, ''] } },
|
||||
{ projection: { _id: 1 } },
|
||||
)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
const markerBoards = (await db.collection('boards').find(
|
||||
{ $or: [{ fixMissingListsCompleted: true }, { comprehensiveMigrationCompleted: true }] },
|
||||
{ projection: { _id: 1 } },
|
||||
).toArray()).map(b => String(b._id));
|
||||
const stampedBoards = (await db.collection('lists').distinct('boardId', { swimlaneId: { $nin: [null, ''] }, type: { $ne: 'template-list' } })).map(String);
|
||||
for (const boardId of new Set([...markerBoards, ...stampedBoards])) {
|
||||
const lists = await db.collection('lists').find(
|
||||
{ boardId, type: { $ne: 'template-list' } },
|
||||
{ projection: { title: 1, swimlaneId: 1, archived: 1, sort: 1, createdAt: 1 } },
|
||||
).toArray();
|
||||
// Only act on boards that actually show an era symptom (duplicate titles
|
||||
// or a card/list swimlane mismatch or the marker) — a healthy natively
|
||||
// per-swimlane board is left exactly as it is.
|
||||
const unarchived = lists.filter(l => l.archived !== true);
|
||||
const titleCount = new Map();
|
||||
for (const l of unarchived) titleCount.set(l.title, (titleCount.get(l.title) || 0) + 1);
|
||||
let mismatch = false;
|
||||
if (!markerBoards.includes(boardId) && ![...titleCount.values()].some(n => n > 1)) {
|
||||
for (const l of unarchived) {
|
||||
if (!l.swimlaneId) continue;
|
||||
if (await db.collection('cards').findOne(
|
||||
{ listId: String(l._id), swimlaneId: { $nin: [String(l.swimlaneId), null, ''] } },
|
||||
{ projection: { _id: 1 } },
|
||||
)) { mismatch = true; break; }
|
||||
}
|
||||
if (!mismatch) continue;
|
||||
}
|
||||
// merge same-title unarchived copies into one canonical shared list
|
||||
const groups = new Map();
|
||||
for (const l of unarchived) {
|
||||
const g = groups.get(l.title) || [];
|
||||
g.push(l);
|
||||
groups.set(l.title, g);
|
||||
}
|
||||
for (const group of groups.values()) {
|
||||
if (group.length < 2) continue;
|
||||
group.sort((a, b) =>
|
||||
((a.swimlaneId ? 1 : 0) - (b.swimlaneId ? 1 : 0)) ||
|
||||
((a.createdAt || 0) - (b.createdAt || 0)) ||
|
||||
((a.sort || 0) - (b.sort || 0)));
|
||||
const canonical = group[0];
|
||||
for (const m of group.slice(1)) {
|
||||
// cards KEEP their swimlaneId — only the column pointer moves
|
||||
await db.collection('cards').updateMany({ listId: String(m._id) }, { $set: { listId: String(canonical._id) } });
|
||||
try { await db.collection('activities').updateMany({ listId: String(m._id) }, { $set: { listId: String(canonical._id) } }); } catch { /* history relink is best-effort */ }
|
||||
await db.collection('lists').deleteOne({ _id: m._id });
|
||||
fixed++;
|
||||
}
|
||||
}
|
||||
// shared lists render in EVERY swimlane via the '' fallback
|
||||
const r = await db.collection('lists').updateMany(
|
||||
{ boardId, type: { $ne: 'template-list' }, swimlaneId: { $nin: [null, ''] } },
|
||||
{ $set: { swimlaneId: '' } },
|
||||
);
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
// drop the era markers so the on-demand repair tools are usable again
|
||||
await db.collection('boards').updateOne(
|
||||
{ _id: boardId },
|
||||
{ $unset: { fixMissingListsCompleted: 1, fixMissingListsCompletedAt: 1, comprehensiveMigrationCompleted: 1 } },
|
||||
);
|
||||
}
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// add-checklist-items (v0.79): before 2018 checklist items lived embedded
|
||||
// in checklist.items[]; current WeKan reads ONLY the ChecklistItems
|
||||
// collection, so embedded items are invisible although their text is in
|
||||
// the database. Extract them exactly like the original migration did,
|
||||
// then $unset the embedded array. The find is targeted ('items.0' exists),
|
||||
// so only affected checklists are ever read.
|
||||
name: 'checklist-items-embedded',
|
||||
async check(db) {
|
||||
return !!await db.collection('checklists').findOne({ 'items.0': { $exists: true } }, { projection: { _id: 1 } });
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
const now = new Date();
|
||||
const cursor = db.collection('checklists').find({ 'items.0': { $exists: true } });
|
||||
for await (const checklist of cursor) {
|
||||
const items = (checklist.items || []).slice().sort((a, b) => (a.sort || 0) - (b.sort || 0));
|
||||
// one query for already-extracted duplicates (interrupted-boot resume)
|
||||
const existing = await db.collection('checklistItems')
|
||||
.find({ checklistId: String(checklist._id) }, { projection: { title: 1, sort: 1, isFinished: 1 } }).toArray();
|
||||
const seen = new Set(existing.map(i => `${i.title}\u0000${i.sort}\u0000${!!i.isFinished}`));
|
||||
const docs = [];
|
||||
for (let index = 0; index < items.length; index++) {
|
||||
const item = items[index] || {};
|
||||
const doc = {
|
||||
_id: randomId(),
|
||||
title: item.title ? item.title : 'Checklist',
|
||||
sort: index,
|
||||
isFinished: !!item.isFinished,
|
||||
checklistId: String(checklist._id),
|
||||
cardId: String(checklist.cardId || ''),
|
||||
createdAt: now,
|
||||
modifiedAt: now,
|
||||
};
|
||||
if (seen.has(`${doc.title}\u0000${doc.sort}\u0000${doc.isFinished}`)) continue;
|
||||
docs.push(doc);
|
||||
}
|
||||
if (docs.length) {
|
||||
// batched insert — one round trip per checklist, not per item
|
||||
await db.collection('checklistItems').insertMany(docs, { ordered: false });
|
||||
fixed += docs.length;
|
||||
}
|
||||
await db.collection('checklists').updateOne({ _id: checklist._id }, { $unset: { items: 1 } });
|
||||
}
|
||||
await cursor.close();
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// mutate-boardIds-in-customfields (v2.49): custom field definitions used a
|
||||
// scalar boardId; everything in current WeKan queries the boardIds array,
|
||||
// so old definitions (names, dropdown texts) and their card values were
|
||||
// orphaned.
|
||||
name: 'customfields-boardIds',
|
||||
async check(db) {
|
||||
return !!await db.collection('customFields').findOne({ boardId: { $exists: true } }, { projection: { _id: 1 } });
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
const cursor = db.collection('customFields').find({ boardId: { $exists: true } });
|
||||
for await (const cf of cursor) {
|
||||
const update = { $unset: { boardId: '' } };
|
||||
if (!Array.isArray(cf.boardIds) || cf.boardIds.length === 0) {
|
||||
update.$set = { boardIds: [String(cf.boardId)] };
|
||||
}
|
||||
await db.collection('customFields').updateOne({ _id: cf._id }, update);
|
||||
fixed++;
|
||||
}
|
||||
await cursor.close();
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// The add-*-allowed steps (v2.9–v5.43): schema defaults fire on insert
|
||||
// only, and the card-details templates do raw property access — a missing
|
||||
// allows* flag hides existing description/checklist/comment/attachment
|
||||
// text even though it is all still in the database. Backfill the
|
||||
// defaultValue:true flags with server-side updateMany batches.
|
||||
name: 'board-allows-defaults',
|
||||
async check(db) {
|
||||
return !!await db.collection('boards').findOne(
|
||||
{ $or: BOARD_ALLOWS_TRUE_DEFAULTS.map(f => ({ [f]: { $exists: false } })) },
|
||||
{ projection: { _id: 1 } },
|
||||
);
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
for (const f of BOARD_ALLOWS_TRUE_DEFAULTS) {
|
||||
const r = await db.collection('boards').updateMany(
|
||||
{ [f]: { $exists: false } },
|
||||
{ $set: { [f]: true } },
|
||||
);
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
}
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// add-member-isactive-field: members without isActive are treated as
|
||||
// INACTIVE by isActiveMember()/activeMembers — pre-2015 board members
|
||||
// were silently denied access. Explicit isActive:false is respected.
|
||||
// $elemMatch keeps the query server-side; if the backend rejects it we
|
||||
// fall back to a projection scan of boards (a small collection).
|
||||
name: 'board-members-isactive',
|
||||
async check(db, ctx) {
|
||||
try {
|
||||
return !!await db.collection('boards').findOne(
|
||||
{ members: { $elemMatch: { isActive: { $exists: false } } } },
|
||||
{ projection: { _id: 1 } },
|
||||
);
|
||||
} catch (e) {
|
||||
ctx.log(`board-members-isactive: $elemMatch probe unsupported (${e.message}); scanning boards`);
|
||||
const cursor = db.collection('boards').find({ 'members.0': { $exists: true } }, { projection: { members: 1 } });
|
||||
for await (const b of cursor) {
|
||||
if ((b.members || []).some(m => m && m.isActive === undefined)) { await cursor.close(); return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
let cursor;
|
||||
try {
|
||||
cursor = db.collection('boards').find(
|
||||
{ members: { $elemMatch: { isActive: { $exists: false } } } },
|
||||
{ projection: { members: 1 } },
|
||||
);
|
||||
// touch the cursor so an unsupported operator throws HERE
|
||||
await cursor.hasNext?.();
|
||||
} catch {
|
||||
cursor = db.collection('boards').find({ 'members.0': { $exists: true } }, { projection: { members: 1 } });
|
||||
}
|
||||
for await (const b of cursor) {
|
||||
const members = b.members || [];
|
||||
if (!members.some(m => m && m.isActive === undefined)) continue;
|
||||
const patched = members.map(m => (m && m.isActive === undefined ? { ...m, isActive: true } : m));
|
||||
await db.collection('boards').updateOne({ _id: b._id }, { $set: { members: patched } });
|
||||
fixed++;
|
||||
}
|
||||
await cursor.close();
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// lowercase-board-permission: LibreBoard-era 'PUBLIC'/'PRIVATE' values —
|
||||
// current code compares permission === 'public', so an uppercase public
|
||||
// board silently became member-only.
|
||||
name: 'board-permission-lowercase',
|
||||
async check(db) {
|
||||
return !!await db.collection('boards').findOne(
|
||||
{ permission: { $in: ['PUBLIC', 'PRIVATE', 'Public', 'Private'] } },
|
||||
{ projection: { _id: 1 } },
|
||||
);
|
||||
},
|
||||
async run(db) {
|
||||
let fixed = 0;
|
||||
for (const [from, to] of [['PUBLIC', 'public'], ['Public', 'public'], ['PRIVATE', 'private'], ['Private', 'private']]) {
|
||||
const r = await db.collection('boards').updateMany({ permission: from }, { $set: { permission: to } });
|
||||
fixed += (r && r.modifiedCount) || 0;
|
||||
}
|
||||
return { fixed, unresolved: 0 };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// fs-path-heal: filesystem-stored attachments/avatars whose recorded path
|
||||
// predates the current layout. WeKan's historical fs locations/naming:
|
||||
// v6.10-18 WRITABLE_PATH/uploads/<coll>/<name> (Meteor-Files temp)
|
||||
// v6.10 WRITABLE_PATH/<oldId>-<name> (CFS->ostrio migration)
|
||||
// v6.19-8.4x WRITABLE_PATH/<coll>/<id>[-original-...] (pre-/files layout)
|
||||
// current <files root>/<coll>/<id> or <id>_<name> or <id>-<version>-<name>
|
||||
// A record whose version.path no longer exists gets its binary located in
|
||||
// those places and copied/repointed into the current directory. Records
|
||||
// with NO storage flag and NO gridFsFileId (failed v6.10-18 GridFS copies)
|
||||
// are healed the same way. Marked done only when nothing is left broken,
|
||||
// so a temporarily-unmounted volume retries on the next boot.
|
||||
name: 'fs-path-heal',
|
||||
async check(db, ctx) {
|
||||
return (await findBrokenFsVersions(db, ctx, true)).length > 0;
|
||||
},
|
||||
async run(db, ctx) {
|
||||
const broken = await findBrokenFsVersions(db, ctx, false);
|
||||
let fixed = 0, unresolved = 0;
|
||||
for (const item of broken) {
|
||||
const healed = await healOne(db, ctx, item);
|
||||
if (healed) fixed++; else unresolved++;
|
||||
}
|
||||
return { fixed, unresolved };
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Visible swimlanes (not archived, not templates) — the ones the Swimlanes
|
||||
// view actually renders. Swimlanes are few, so one projected fetch is cheap.
|
||||
// byId: swimlaneId -> boardId; firstOfBoard: boardId -> swimlaneId (by sort).
|
||||
async function loadVisibleSwimlanes(db) {
|
||||
const byId = new Map();
|
||||
const firstOfBoard = new Map();
|
||||
const all = await db.collection('swimlanes')
|
||||
.find({}, { projection: { _id: 1, boardId: 1, archived: 1, type: 1, sort: 1 } }).toArray();
|
||||
for (const s of all.sort((a, b) => (a.sort || 0) - (b.sort || 0))) {
|
||||
if (s.archived === true || s.type === 'template-swimlane') continue;
|
||||
byId.set(String(s._id), String(s.boardId));
|
||||
if (!firstOfBoard.has(String(s.boardId))) firstOfBoard.set(String(s.boardId), String(s._id));
|
||||
}
|
||||
return { byId, firstOfBoard };
|
||||
}
|
||||
|
||||
// A version needs healing when it is (or defaults to) filesystem storage but
|
||||
// its recorded path does not exist on disk.
|
||||
function versionNeedsHeal(doc, version) {
|
||||
if (!version || typeof version !== 'object') return false;
|
||||
const hasGridRef = !!(version.meta && version.meta.gridFsFileId);
|
||||
const isFs = version.storage === 'fs' || (!version.storage && !hasGridRef);
|
||||
if (!isFs) return false;
|
||||
if (version.path && fs.existsSync(version.path)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
async function findBrokenFsVersions(db, ctx, firstOnly) {
|
||||
const out = [];
|
||||
for (const coll of ['attachments', 'avatars']) {
|
||||
// The disk check cannot be expressed as a query, but the scan reads only
|
||||
// the metadata fields it needs; attachments collections hold metadata
|
||||
// documents (small), not binaries.
|
||||
const cursor = db.collection(coll).find({}, { projection: { name: 1, versions: 1 } });
|
||||
for await (const doc of cursor) {
|
||||
for (const [versionName, version] of Object.entries(doc.versions || {})) {
|
||||
if (versionNeedsHeal(doc, version)) {
|
||||
out.push({ coll, doc, versionName, version });
|
||||
if (firstOnly) { await cursor.close(); return out; }
|
||||
}
|
||||
}
|
||||
}
|
||||
await cursor.close();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function healOne(db, ctx, { coll, doc, versionName, version }) {
|
||||
const destDir = coll === 'avatars' ? ctx.paths.avatars : ctx.paths.attachments;
|
||||
const writable = ctx.paths.writablePath;
|
||||
const filesRoot = path.dirname(destDir); // <writable>[/files]
|
||||
const id = String(doc._id);
|
||||
const name = doc.name || id;
|
||||
const base = version.path ? path.basename(String(version.path).replace(/\\/g, '/')) : '';
|
||||
|
||||
const candidates = [];
|
||||
if (base) candidates.push(path.join(destDir, base));
|
||||
candidates.push(path.join(destDir, id)); // v6.85+ naming
|
||||
candidates.push(path.join(destDir, `${id}-${versionName}-${name}`)); // moveToStorage naming
|
||||
candidates.push(path.join(destDir, `${id}_${name}`)); // importer naming
|
||||
// v6.10-18 temp dir and v6.10 CFS->ostrio temp files lived directly under
|
||||
// WRITABLE_PATH; on layouts where the current root added '/files', check both.
|
||||
for (const root of new Set([filesRoot, writable])) {
|
||||
if (base) candidates.push(path.join(root, 'uploads', coll, base));
|
||||
candidates.push(path.join(root, 'uploads', coll, id));
|
||||
candidates.push(path.join(root, `${id}-${name}`));
|
||||
if (base) candidates.push(path.join(root, coll, base)); // pre-/files layout
|
||||
candidates.push(path.join(root, coll, id));
|
||||
}
|
||||
|
||||
let found = null;
|
||||
for (const c of candidates) {
|
||||
try { if (fs.statSync(c).isFile()) { found = c; break; } } catch { /* next */ }
|
||||
}
|
||||
if (!found) {
|
||||
// last resort: prefix scan of the current directory
|
||||
try {
|
||||
const p1 = `${id}-${versionName}-`, p2 = `${id}-original-`, p3 = `${id}_`;
|
||||
const hit = fs.readdirSync(destDir).find(e => e === id || e.startsWith(p1) || e.startsWith(p2) || e.startsWith(p3));
|
||||
if (hit) found = path.join(destDir, hit);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
if (!found) return false;
|
||||
|
||||
let finalPath = found;
|
||||
if (path.resolve(path.dirname(found)) !== path.resolve(destDir)) {
|
||||
// copy (never move — the old dir may be shared/backed up) into the current layout
|
||||
finalPath = path.join(destDir, `${id}-${versionName}-${path.basename(found)}`.slice(0, 220));
|
||||
try {
|
||||
fs.mkdirSync(destDir, { recursive: true });
|
||||
fs.copyFileSync(found, finalPath);
|
||||
} catch (e) {
|
||||
ctx.log(`heal ${coll}/${id}: copy failed: ${e.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const set = {
|
||||
[`versions.${versionName}.path`]: finalPath,
|
||||
[`versions.${versionName}.storage`]: 'fs',
|
||||
};
|
||||
try { set[`versions.${versionName}.size`] = fs.statSync(finalPath).size; } catch { /* keep */ }
|
||||
if (versionName === 'original') set.path = finalPath;
|
||||
await db.collection(coll).updateOne({ _id: doc._id }, { $set: set });
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── orchestrator ─────────────────────────────────────────────────────────────
|
||||
/**
|
||||
* Check what is already migrated and migrate all the rest.
|
||||
*
|
||||
* VERSION-GATED: the marker records {version, at} of the last successful
|
||||
* re-check. While the running WeKan version is unchanged, the whole run is
|
||||
* ONE findOne — a full re-check is mandatory only after a release upgrade
|
||||
* (or with options.force / WEKAN_FORCE_SCHEMA_UPGRADE=true). A run that
|
||||
* leaves unresolved work (or a failed step) does NOT record the version, so
|
||||
* the next boot re-checks.
|
||||
*
|
||||
* @param db mongodb driver Db (MongoDB or FerretDB — same wire protocol)
|
||||
* @param options {log?, writablePath?, appVersion?, force?}
|
||||
* @return {{ran: string[], skipped: string[], results: Object, gated: boolean}}
|
||||
*/
|
||||
async function runSchemaUpgrade(db, options = {}) {
|
||||
const log = options.log || (() => {});
|
||||
const appVersion = options.appVersion || '';
|
||||
const force = options.force || process.env.WEKAN_FORCE_SCHEMA_UPGRADE === 'true';
|
||||
const ctx = {
|
||||
log,
|
||||
paths: computeStoragePaths(options.writablePath !== undefined ? options.writablePath : process.env.WRITABLE_PATH),
|
||||
};
|
||||
const markerColl = db.collection(MARKER_COLL);
|
||||
const marker = (await markerColl.findOne({ _id: MARKER_ID })) || {};
|
||||
resetState(appVersion);
|
||||
upgradeState.lastCheck = marker.lastCheck || null;
|
||||
|
||||
// Migration dashboards show the Admin Panel product name when one is set.
|
||||
try {
|
||||
const s = await db.collection('settings').findOne({ productName: { $exists: true } }, { projection: { productName: 1 } });
|
||||
if (s && typeof s.productName === 'string' && s.productName.trim()) upgradeState.product = s.productName.trim();
|
||||
} catch { /* keep default */ }
|
||||
|
||||
// Version gate: unchanged release + previous re-check was clean -> one findOne, done.
|
||||
if (!force && marker.lastCheck && marker.lastCheck.version === appVersion) {
|
||||
log(`schema already re-checked for version ${appVersion} at ${marker.lastCheck.at}; skipping (set WEKAN_FORCE_SCHEMA_UPGRADE=true to force).`);
|
||||
upgradeState.running = false;
|
||||
upgradeState.gated = true;
|
||||
upgradeState.finishedAt = new Date();
|
||||
for (const s of steps) upgradeState.steps[s.name].status = 'skipped';
|
||||
return { ran: [], skipped: steps.map(s => s.name), results: {}, gated: true };
|
||||
}
|
||||
|
||||
const ran = [], skipped = [], results = {};
|
||||
let clean = true;
|
||||
|
||||
for (const step of steps) {
|
||||
const st = upgradeState.steps[step.name];
|
||||
upgradeState.currentStep = step.name;
|
||||
try {
|
||||
st.status = 'checking';
|
||||
const needed = await step.check(db, ctx);
|
||||
if (!needed) {
|
||||
st.status = 'skipped';
|
||||
skipped.push(step.name);
|
||||
continue;
|
||||
}
|
||||
log(`running ${step.name} ...`);
|
||||
st.status = 'running';
|
||||
const res = await step.run(db, ctx);
|
||||
st.status = 'done';
|
||||
st.fixed = res.fixed;
|
||||
st.unresolved = res.unresolved || 0;
|
||||
results[step.name] = res;
|
||||
ran.push(step.name);
|
||||
log(`${step.name}: fixed ${res.fixed}${res.unresolved ? `, unresolved ${res.unresolved} (will retry next start)` : ''}`);
|
||||
if (res.unresolved) clean = false;
|
||||
// per-step record for the dashboard/history
|
||||
await markerColl.updateOne(
|
||||
{ _id: MARKER_ID },
|
||||
{ $set: { [`steps.${step.name}`]: { doneAt: new Date(), fixed: res.fixed, unresolved: res.unresolved || 0 } } },
|
||||
{ upsert: true },
|
||||
).catch(() => {});
|
||||
} catch (e) {
|
||||
// Never break startup over an upgrade step — log and retry next boot.
|
||||
clean = false;
|
||||
st.status = 'error';
|
||||
st.error = e.message;
|
||||
log(`${step.name} FAILED (will retry next start): ${e.message}`);
|
||||
results[step.name] = { error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
upgradeState.currentStep = '';
|
||||
upgradeState.running = false;
|
||||
upgradeState.finishedAt = new Date();
|
||||
|
||||
// Record the re-check ONLY when everything is clean — an unresolved or
|
||||
// failed step keeps the version un-stamped so the next boot re-checks.
|
||||
if (clean) {
|
||||
const lastCheck = { version: appVersion, at: new Date() };
|
||||
upgradeState.lastCheck = lastCheck;
|
||||
await markerColl.updateOne(
|
||||
{ _id: MARKER_ID },
|
||||
{ $set: { lastCheck } },
|
||||
{ upsert: true },
|
||||
).catch(e => log('marker lastCheck update failed: ' + e.message));
|
||||
}
|
||||
return { ran, skipped, results, gated: false };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
runSchemaUpgrade,
|
||||
getUpgradeState,
|
||||
steps,
|
||||
BOARD_ALLOWS_TRUE_DEFAULTS,
|
||||
randomId,
|
||||
versionNeedsHeal,
|
||||
MARKER_COLL,
|
||||
MARKER_ID,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
// #3453 "Full path display of subtasks cards disappears after a refresh of the
|
||||
// subtask board".
|
||||
//
|
||||
// When a board's "Subtasks settings" present subtasks with
|
||||
// 'prefix-with-full-path', the minicard renders `parentString(' > ')`, which
|
||||
// walks the subtask's WHOLE ancestor chain client-side via
|
||||
// ReactiveCache.getCard (models/cards.js parentList()/parentString()). After a
|
||||
// hard refresh (F5) of the subtask board, minimongo only contains what the
|
||||
// `board` publication ships. The publication's "Parent cards (for subtasks)"
|
||||
// child used to publish only the DIRECT parents of the board's cards, so any
|
||||
// grandparent living on another board was missing and the displayed path was
|
||||
// truncated (or, before the parent-cards child existed at all, vanished
|
||||
// entirely — the original #3453 report).
|
||||
//
|
||||
// collectAncestorIds() computes the FULL ancestor id set, level by level, so
|
||||
// the publication can ship every card document the full-path prefix needs. It
|
||||
// is pure and dependency-injected (no Meteor/Mongo imports): the caller
|
||||
// supplies an async batch lookup, which keeps the traversal unit-testable with
|
||||
// plain Node and keeps the server code to one query per ancestor level.
|
||||
//
|
||||
// Cycle safety: a card must never become its own ancestor (#3328), but corrupt
|
||||
// or legacy data may still contain loops — the `seen` set guarantees the walk
|
||||
// terminates and returns each ancestor id exactly once.
|
||||
|
||||
/**
|
||||
* Collect the ids of ALL ancestors reachable from the given direct-parent ids.
|
||||
*
|
||||
* @param {Array<string>} seedParentIds Direct parent ids of the cards on the
|
||||
* board (falsy entries and duplicates are ignored).
|
||||
* @param {function(Array<string>): Promise<Array<{_id: string, parentId?: string}>>} fetchParents
|
||||
* Async batch lookup: given card ids, resolves the matching card docs
|
||||
* (at least `_id` and `parentId`). Missing/deleted ids may simply be
|
||||
* absent from the result.
|
||||
* @returns {Promise<Array<string>>} every ancestor id, each exactly once.
|
||||
* Ids whose documents no longer exist are still included (they match
|
||||
* nothing when published, which is harmless).
|
||||
*/
|
||||
async function collectAncestorIds(seedParentIds, fetchParents) {
|
||||
const seen = new Set();
|
||||
let frontier = [];
|
||||
for (const id of Array.isArray(seedParentIds) ? seedParentIds : []) {
|
||||
if (id && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
frontier.push(id);
|
||||
}
|
||||
}
|
||||
while (frontier.length > 0) {
|
||||
const docs = (await fetchParents(frontier)) || [];
|
||||
const next = [];
|
||||
for (const doc of docs) {
|
||||
const parentId = doc && doc.parentId;
|
||||
if (parentId && !seen.has(parentId)) {
|
||||
seen.add(parentId);
|
||||
next.push(parentId);
|
||||
}
|
||||
}
|
||||
frontier = next;
|
||||
}
|
||||
return Array.from(seen);
|
||||
}
|
||||
|
||||
module.exports = { collectAncestorIds };
|
||||
@@ -210,6 +210,29 @@ async function getOrCreateRescuedSwimlane(boardId) {
|
||||
function addSwimlaneIdValidationHooks() {
|
||||
// Card insert hook
|
||||
Cards.before.insert(async function(userId, doc) {
|
||||
// #1959/#1971: a client-supplied swimlaneId can point at a DELETED or
|
||||
// ARCHIVED swimlane (adding cards in the Lists view reuses stale ids,
|
||||
// and dragging re-assigns to a default swimlane that may be archived).
|
||||
// Such cards exist but never render in the Swimlanes view. Validate the
|
||||
// id and fall back to the board's first VISIBLE swimlane.
|
||||
if (doc.swimlaneId) {
|
||||
const valid = await Swimlanes.findOneAsync({
|
||||
_id: doc.swimlaneId,
|
||||
boardId: doc.boardId,
|
||||
archived: false,
|
||||
});
|
||||
if (!valid) {
|
||||
const fallback = await Swimlanes.findOneAsync({
|
||||
boardId: doc.boardId,
|
||||
type: { $ne: 'template-swimlane' },
|
||||
archived: false,
|
||||
}, { sort: { sort: 1 } });
|
||||
if (fallback) {
|
||||
console.warn(`Card insert pointed at a missing/archived swimlane ${doc.swimlaneId}; using ${fallback._id}`);
|
||||
doc.swimlaneId = fallback._id;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!doc.swimlaneId) {
|
||||
const board = await Boards.findOneAsync(doc.boardId);
|
||||
if (board) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { WebApp } from 'meteor/webapp';
|
||||
import { Authentication } from '/server/authentication';
|
||||
import { sendJsonResult } from '/server/apiMiddleware';
|
||||
import { refreshCloudStorageFromSettings, testCloudConnection } from '/models/lib/cloudStorage';
|
||||
import { computeStoragePaths } from '/models/lib/attachmentStoragePath';
|
||||
|
||||
// Secret fields per cloud provider — never published to the client and only
|
||||
// overwritten when a non-empty replacement value is supplied.
|
||||
@@ -174,6 +175,21 @@ async function compactCollectionsOnNode(nodeDb, candidates, force = false) {
|
||||
}
|
||||
|
||||
Meteor.methods({
|
||||
// #6473: the Admin Panel > Attachments page used to render these paths from
|
||||
// process.env.WRITABLE_PATH ON THE CLIENT, where process.env never has it, so
|
||||
// it always showed "/data" — a path that does not exist on a Snap install.
|
||||
// The client now asks the server for the real, Snap-aware paths.
|
||||
async getAttachmentStoragePaths() {
|
||||
if (!this.userId) {
|
||||
throw new Meteor.Error('not-authorized', 'Must be logged in');
|
||||
}
|
||||
const user = await ReactiveCache.getUser(this.userId);
|
||||
if (!user || !user.isAdmin) {
|
||||
throw new Meteor.Error('not-authorized', 'Admin access required');
|
||||
}
|
||||
return computeStoragePaths(process.env.WRITABLE_PATH);
|
||||
},
|
||||
|
||||
async getAttachmentStorageSettings() {
|
||||
if (!this.userId) {
|
||||
throw new Meteor.Error('not-authorized', 'Must be logged in');
|
||||
@@ -193,7 +209,11 @@ Meteor.methods({
|
||||
enabled: true,
|
||||
read: true,
|
||||
write: true,
|
||||
path: process.env.WRITABLE_PATH ? `${process.env.WRITABLE_PATH}/attachments` : '/data/attachments',
|
||||
// #6473: the REAL storage path (Snap-aware: WRITABLE_PATH may already
|
||||
// end in /files), not `${WRITABLE_PATH}/attachments`, which pointed
|
||||
// at a directory that does not exist on Docker (/data/attachments
|
||||
// instead of /data/files/attachments).
|
||||
path: computeStoragePaths(process.env.WRITABLE_PATH).attachments,
|
||||
},
|
||||
gridfs: {
|
||||
enabled: true,
|
||||
|
||||
+43
-4
@@ -8,6 +8,11 @@ import { Authentication } from '/server/authentication';
|
||||
import { sendJsonResult } from '/server/apiMiddleware';
|
||||
import { allowIsBoardAdmin, boardMemberRoleToFlags } from '/server/lib/utils';
|
||||
import { reconcileBoardTeamMembers } from '/models/lib/reconcileBoardTeamMembers';
|
||||
import {
|
||||
isInvitedToBoard,
|
||||
planQuitBoard,
|
||||
planAcceptInvite,
|
||||
} from '/models/lib/boardInvites';
|
||||
import { buildBoardLabel } from '/models/lib/restLabel';
|
||||
import { LABEL_COLORS } from '/models/metadata/colors';
|
||||
import { filterUserBoards } from '/server/lib/boardListFilter';
|
||||
@@ -204,12 +209,31 @@ Meteor.methods({
|
||||
}
|
||||
|
||||
const userId = this.userId;
|
||||
const index = board.memberIndex(userId);
|
||||
if (index < 0) {
|
||||
throw new Meteor.Error('error-board-notAMember');
|
||||
const user = await ReactiveCache.getUser(userId);
|
||||
// #4730: quitting (or declining an invitation to) a board must also clear
|
||||
// the pending invitation, otherwise a follow-up acceptInvite call — the
|
||||
// decline flow on the All Boards page issues one — re-activates the
|
||||
// membership and the declined board stays in the personal overview. A user
|
||||
// holding only a stale invitation (no member entry, e.g. after an admin
|
||||
// removed them) may also quit: their invitation is cleared instead of
|
||||
// throwing error-board-notAMember, so the board can always be removed
|
||||
// from the personal overview.
|
||||
const plan = planQuitBoard({
|
||||
isMember: board.memberIndex(userId) >= 0,
|
||||
isInvited: isInvitedToBoard(user && user.profile, boardId),
|
||||
});
|
||||
if (!plan.ok) {
|
||||
throw new Meteor.Error(plan.error);
|
||||
}
|
||||
|
||||
await board.removeMember(userId);
|
||||
if (plan.pullInvite) {
|
||||
await Users.updateAsync(userId, {
|
||||
$pull: { 'profile.invitedBoards': boardId },
|
||||
});
|
||||
}
|
||||
if (plan.removeMember) {
|
||||
await board.removeMember(userId);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -220,6 +244,20 @@ Meteor.methods({
|
||||
throw new Meteor.Error('error-board-doesNotExist');
|
||||
}
|
||||
|
||||
// #4730: only a user actually holding an invitation to this board may
|
||||
// (re)activate their member entry. Previously this method set
|
||||
// members.$.isActive = true unconditionally, which (a) re-activated the
|
||||
// membership right after the decline flow's quitBoard call, so a declined
|
||||
// board stayed in the personal overview, and (b) let a member an admin had
|
||||
// removed re-add themselves by calling this method directly.
|
||||
const user = await ReactiveCache.getUser(this.userId);
|
||||
const plan = planAcceptInvite({
|
||||
isInvited: isInvitedToBoard(user && user.profile, boardId),
|
||||
});
|
||||
if (!plan.ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await Meteor.users.updateAsync(this.userId, {
|
||||
$pull: {
|
||||
'profile.invitedBoards': boardId,
|
||||
@@ -238,6 +276,7 @@ Meteor.methods({
|
||||
},
|
||||
},
|
||||
);
|
||||
return true;
|
||||
},
|
||||
|
||||
async myLabelNames() {
|
||||
|
||||
+14
-1
@@ -95,6 +95,19 @@ Meteor.methods({
|
||||
const customFields = subtaskCustomFields(boardCustomFields);
|
||||
|
||||
const cardNumber = await targetBoard.getNextCardNumber();
|
||||
// #3826: a constant `sort: -1` made EVERY subtask card tie, so a list full
|
||||
// of subtask cards could not be reordered by drag (no number lies strictly
|
||||
// between two equal sorts; the computed index equalled the card's own sort
|
||||
// and the move was discarded as a no-op). Append with a unique sort at the
|
||||
// end of the target list instead — with the old all-ties data the cards
|
||||
// effectively rendered in insertion order anyway, so the visible placement
|
||||
// is unchanged while new subtasks no longer pile up duplicate sorts.
|
||||
const lastCard = await Cards.findOneAsync(
|
||||
{ listId: targetList._id, archived: false },
|
||||
{ sort: { sort: -1 }, fields: { sort: 1 } },
|
||||
);
|
||||
const sort =
|
||||
lastCard && Number.isFinite(lastCard.sort) ? lastCard.sort + 1 : 0;
|
||||
const _id = await Cards.insertAsync({
|
||||
title: trimmed,
|
||||
parentId: parentCardId,
|
||||
@@ -104,7 +117,7 @@ Meteor.methods({
|
||||
customFields,
|
||||
listId: targetList._id,
|
||||
boardId: targetBoard._id,
|
||||
sort: -1,
|
||||
sort,
|
||||
swimlaneId,
|
||||
type: 'cardType-card',
|
||||
cardNumber,
|
||||
|
||||
+45
-3
@@ -3,6 +3,7 @@ import { WebApp } from 'meteor/webapp';
|
||||
import { Authentication } from '/server/authentication';
|
||||
import { sendJsonResult } from '/server/apiMiddleware';
|
||||
import { ReactiveCache } from '/imports/reactiveCache';
|
||||
import { TriggersDef } from '/server/triggersDef';
|
||||
import Rules from '/models/rules';
|
||||
import Triggers from '/models/triggers';
|
||||
import Actions from '/models/actions';
|
||||
@@ -31,6 +32,31 @@ function strip(doc) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// #2674 ("Rule: remove USER from card when move"): the rule matcher
|
||||
// (server/rulesHelper.js buildMatchingFieldsMap) queries EVERY matching field
|
||||
// of the trigger's activityType with {$in: [<activity value>, '*']}. A Mongo
|
||||
// $in never matches a document that LACKS the field, so a trigger created over
|
||||
// REST without e.g. userId / listName / swimlaneName / cardTitle could never
|
||||
// match any activity and its rule silently never fired — exactly the "user is
|
||||
// added when the card moves to the list, but never removed when it moves away"
|
||||
// failure of #2674. The Rules UI wizard (sanitizeObject) and the rules JSON
|
||||
// import (normalizeTrigger) both default missing matching fields to the '*'
|
||||
// wildcard; do the same for API-created/edited triggers. Trigger kinds not
|
||||
// driven by activities (scheduledTrigger, button — not in TriggersDef) are
|
||||
// left untouched.
|
||||
function normalizeTriggerDoc(trigger) {
|
||||
const out = { ...trigger };
|
||||
const def = TriggersDef[out.activityType];
|
||||
if (def) {
|
||||
def.matchingFields.forEach(field => {
|
||||
if (out[field] === undefined || out[field] === null || out[field] === '') {
|
||||
out[field] = '*';
|
||||
}
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function serializeRule(rule) {
|
||||
const trigger = await ReactiveCache.getTrigger(rule.triggerId);
|
||||
const action = await ReactiveCache.getAction(rule.actionId);
|
||||
@@ -98,6 +124,11 @@ if (Meteor.isServer) {
|
||||
*
|
||||
* @description The trigger and action are embedded inline. See the Rules
|
||||
* documentation for the available trigger activityTypes and action actionTypes.
|
||||
* Trigger matching fields that are omitted (e.g. userId, listName,
|
||||
* swimlaneName, cardTitle) default to the '*' wildcard, so e.g. issue #2674's
|
||||
* "remove a member when a card is moved away from a list" only needs
|
||||
* trigger {activityType: 'moveCard', oldListName: '...'} and
|
||||
* action {actionType: 'removeMember', username: '...'}.
|
||||
*
|
||||
* @param {string} boardId the board ID
|
||||
* @param {string} title the rule title
|
||||
@@ -113,7 +144,16 @@ if (Meteor.isServer) {
|
||||
if (!trigger || !action) {
|
||||
throw new Meteor.Error('bad-request', 'trigger and action are required');
|
||||
}
|
||||
const triggerId = await Triggers.insertAsync({ ...strip(trigger), boardId: paramBoardId });
|
||||
if (!trigger.activityType) {
|
||||
throw new Meteor.Error('bad-request', 'trigger.activityType is required');
|
||||
}
|
||||
if (!action.actionType) {
|
||||
throw new Meteor.Error('bad-request', 'action.actionType is required');
|
||||
}
|
||||
const triggerId = await Triggers.insertAsync({
|
||||
...normalizeTriggerDoc(strip(trigger)),
|
||||
boardId: paramBoardId,
|
||||
});
|
||||
const actionId = await Actions.insertAsync({ ...strip(action), boardId: paramBoardId });
|
||||
const ruleId = await Rules.insertAsync({
|
||||
title: title || 'API rule',
|
||||
@@ -133,7 +173,9 @@ if (Meteor.isServer) {
|
||||
* @summary Edit an automation rule
|
||||
*
|
||||
* @description Any of title, trigger and action may be supplied; the trigger
|
||||
* and action documents are replaced ($set) when present.
|
||||
* and action documents are replaced ($set) when present. A supplied trigger
|
||||
* that includes an activityType gets its missing matching fields defaulted
|
||||
* to the '*' wildcard, like on creation.
|
||||
*
|
||||
* @param {string} boardId the board ID
|
||||
* @param {string} ruleId the rule ID
|
||||
@@ -157,7 +199,7 @@ if (Meteor.isServer) {
|
||||
}
|
||||
if (req.body.trigger) {
|
||||
await Triggers.updateAsync(rule.triggerId, {
|
||||
$set: { ...strip(req.body.trigger), boardId: paramBoardId },
|
||||
$set: { ...normalizeTriggerDoc(strip(req.body.trigger)), boardId: paramBoardId },
|
||||
});
|
||||
}
|
||||
if (req.body.action) {
|
||||
|
||||
+60
-13
@@ -11,6 +11,12 @@ import { ensureIndex } from '/server/lib/mongoStartup';
|
||||
import { Authentication } from '/server/authentication';
|
||||
import { sendJsonResult } from '/server/apiMiddleware';
|
||||
const { parseCardsLoadingEnv } = require('/models/lib/cardsLoading');
|
||||
const {
|
||||
normalizeInviteEmail,
|
||||
isInvitationCodeSendable,
|
||||
buildReinviteModifier,
|
||||
shouldRemoveInvitationOnEmailFailure,
|
||||
} = require('/models/lib/invitationCodeEmail');
|
||||
|
||||
const getReactiveCache = () => require('/imports/reactiveCache').ReactiveCache;
|
||||
const getTAPi18n = () => require('/imports/i18n').TAPi18n;
|
||||
@@ -45,8 +51,17 @@ function loadOidcConfig(service) {
|
||||
return ServiceConfiguration.configurations.findOneAsync({ service });
|
||||
}
|
||||
|
||||
async function sendInvitationEmail(_id) {
|
||||
async function sendInvitationEmail(_id, { isNewInvitation = true } = {}) {
|
||||
const icode = await getReactiveCache().getInvitationCode(_id);
|
||||
// #4043: never send an invitation email without a code that will validate at
|
||||
// sign-up (the sign-up lookup requires { code: <string>, valid: true }).
|
||||
// Fail loudly instead of mailing a dead code.
|
||||
if (!isInvitationCodeSendable(icode)) {
|
||||
throw new Meteor.Error(
|
||||
'invitation-code-invalid',
|
||||
'Invitation email not sent: the invitation code is missing or no longer valid',
|
||||
);
|
||||
}
|
||||
const author = await getReactiveCache().getCurrentUser();
|
||||
try {
|
||||
const authorUser = await getReactiveCache().getUser(icode.authorId);
|
||||
@@ -74,7 +89,12 @@ async function sendInvitationEmail(_id) {
|
||||
language: lang,
|
||||
});
|
||||
} catch (e) {
|
||||
await InvitationCodes.removeAsync(_id);
|
||||
// #4043: only roll back a code created by this very invite. A pre-existing
|
||||
// invitation was already delivered in an earlier email; deleting it here
|
||||
// would silently invalidate the code that email carries.
|
||||
if (shouldRemoveInvitationOnEmailFailure({ isNewInvitation })) {
|
||||
await InvitationCodes.removeAsync(_id);
|
||||
}
|
||||
throw new Meteor.Error('email-fail', e.message);
|
||||
}
|
||||
}
|
||||
@@ -230,7 +250,12 @@ Meteor.methods({
|
||||
throw new Meteor.Error('not-allowed');
|
||||
}
|
||||
|
||||
for (const email of emails) {
|
||||
for (const rawEmail of emails) {
|
||||
// #4043: store the invitee address lowercase — the sign-up form
|
||||
// lowercases the typed address and MongoDB string matching is case
|
||||
// sensitive, so a mixed-case invitation document never matches at
|
||||
// registration ("The invitation code doesn't exist").
|
||||
const email = normalizeInviteEmail(rawEmail);
|
||||
if (email && SimpleSchema.RegEx.Email.test(email)) {
|
||||
const userExist = await getReactiveCache().getUser({ email });
|
||||
if (userExist) {
|
||||
@@ -243,12 +268,30 @@ Meteor.methods({
|
||||
|
||||
const invitation = await getReactiveCache().getInvitationCode({ email });
|
||||
if (invitation) {
|
||||
await InvitationCodes.updateAsync(invitation, {
|
||||
$set: { boardsToBeInvited: boards },
|
||||
});
|
||||
await sendInvitationEmail(invitation._id);
|
||||
// #4043: a re-invite must never re-send a stale code. When the
|
||||
// stored invitation is no longer valid (or has no usable code), a
|
||||
// fresh code overwrites it with valid restored to true, so the
|
||||
// emailed code always passes the sign-up lookup
|
||||
// { code, email, valid: true }.
|
||||
const modifier = buildReinviteModifier(invitation, boards, () =>
|
||||
getRandomNum(100000, 999999),
|
||||
);
|
||||
const updated = await InvitationCodes.updateAsync(
|
||||
invitation._id,
|
||||
modifier,
|
||||
);
|
||||
if (!updated) {
|
||||
rc = -1;
|
||||
throw new Meteor.Error(
|
||||
'invitation-generated-fail',
|
||||
'Failed to update invitation code',
|
||||
);
|
||||
}
|
||||
await sendInvitationEmail(invitation._id, { isNewInvitation: false });
|
||||
} else {
|
||||
const code = getRandomNum(100000, 999999);
|
||||
// String(...) so the stored code always matches the (string) code
|
||||
// typed into the sign-up form, without relying on schema autoConvert.
|
||||
const code = String(getRandomNum(100000, 999999));
|
||||
const _id = await InvitationCodes.insertAsync({
|
||||
code,
|
||||
email,
|
||||
@@ -397,11 +440,15 @@ Meteor.methods({
|
||||
return !(process.env.PASSWORD_LOGIN_ENABLED === 'false');
|
||||
},
|
||||
|
||||
isOidcRedirectionEnabled() {
|
||||
return (
|
||||
process.env.OIDC_REDIRECTION_ENABLED === 'true' &&
|
||||
Object.keys(loadOidcConfig('oidc')).length > 0
|
||||
);
|
||||
// #5695: loadOidcConfig() returns a Promise since the Meteor 3 async
|
||||
// migration (findOneAsync). Object.keys(<Promise>) is always [], so this
|
||||
// method returned false even with OIDC_REDIRECTION_ENABLED=true and a
|
||||
// configured oidc service, silently disabling the auto-redirect login.
|
||||
// Await the config before inspecting it.
|
||||
async isOidcRedirectionEnabled() {
|
||||
if (process.env.OIDC_REDIRECTION_ENABLED !== 'true') return false;
|
||||
const config = await loadOidcConfig('oidc');
|
||||
return !!config && Object.keys(config).length > 0;
|
||||
},
|
||||
|
||||
async getServiceConfiguration(service) {
|
||||
|
||||
+84
-7
@@ -25,6 +25,45 @@ import { expiredNotificationActivityIds } from '/models/lib/notificationCleanup'
|
||||
import { chooseInviteEmailLanguage } from '/models/lib/inviteEmailLanguage';
|
||||
import { paginateDomains } from '/models/lib/domainTablePage';
|
||||
import { orgsToAutoAddForEmail } from '/models/lib/orgAutoAddByDomain';
|
||||
import {
|
||||
gainedTeamIds,
|
||||
newTeamBoardMemberEntry,
|
||||
boardsToAddMemberTo,
|
||||
} from '/models/lib/teamBoardMemberSync';
|
||||
|
||||
// #4593: when a team is assigned to a board (addBoardTeamPopup), every user in
|
||||
// the team at that moment is pushed into board.members as a normal member — but
|
||||
// a user added to the team afterwards never was, so they ended up with strictly
|
||||
// less authority than their teammates: the publications let them view the board
|
||||
// (teams.teamId match) while every interaction gate (board.hasMember,
|
||||
// allowIsBoardMember*, Attachments.protected, board.isVisibleBy for export)
|
||||
// only looks at board.members. This grants a user who just gained team(s) the
|
||||
// same normal membership on every board those teams are assigned to. Existing
|
||||
// member entries (even deactivated ones) are never touched, template boards are
|
||||
// skipped, and team REMOVAL intentionally does not remove board members (a
|
||||
// member may also have been invited individually; explicit cleanup remains the
|
||||
// board admin's removeBoardTeamPopup action). Failures are logged, never fatal
|
||||
// to the user update that triggered the sync.
|
||||
const addUserToTeamBoards = async (userId, oldTeams, newTeams) => {
|
||||
try {
|
||||
const gained = gainedTeamIds(oldTeams, newTeams);
|
||||
if (!gained.length) return;
|
||||
const boards = await ReactiveCache.getBoards(
|
||||
{ teams: { $elemMatch: { teamId: { $in: gained }, isActive: true } } },
|
||||
{ fields: { _id: 1, type: 1, teams: 1, members: 1 } },
|
||||
);
|
||||
for (const boardId of boardsToAddMemberTo(boards, userId, gained)) {
|
||||
// Guarded push: never create a duplicate entry if the user became a
|
||||
// member through another path between the read above and this write.
|
||||
await Boards.updateAsync(
|
||||
{ _id: boardId, 'members.userId': { $ne: userId } },
|
||||
{ $push: { members: newTeamBoardMemberEntry(userId) } },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('addUserToTeamBoards failed:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const getTAPi18n = () => require('/imports/i18n').TAPi18n;
|
||||
const isSandstorm =
|
||||
@@ -261,6 +300,12 @@ Meteor.methods({
|
||||
if (updateData.orgs !== undefined) updateObject.orgs = updateData.orgs;
|
||||
|
||||
await Users.updateAsync(targetUserId, { $set: updateObject });
|
||||
|
||||
// #4593: a user who just gained team(s) must also gain membership of the
|
||||
// boards those teams are assigned to, like the team's original members did.
|
||||
if (updateData.teams !== undefined) {
|
||||
await addUserToTeamBoards(targetUserId, targetUser.teams, updateData.teams);
|
||||
}
|
||||
},
|
||||
|
||||
async setListSortBy(value) {
|
||||
@@ -698,6 +743,10 @@ Meteor.methods({
|
||||
teams: userTeamsArray,
|
||||
},
|
||||
});
|
||||
// #4593: a user created directly into team(s) must gain membership of
|
||||
// the boards those teams are assigned to, like the teams' existing
|
||||
// members already have.
|
||||
await addUserToTeamBoards(user._id, [], userTeamsArray);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -856,7 +905,16 @@ Meteor.methods({
|
||||
throw new Meteor.Error('error-user-notCreated');
|
||||
}
|
||||
const email = username.toLowerCase();
|
||||
username = email.substring(0, posAt);
|
||||
// #619: the invitee's username is derived from the email local part; a
|
||||
// collision with an existing user (e.g. cats@foo.com then
|
||||
// cats@facebook.com) made Accounts.createUser throw a raw
|
||||
// "403 Username already exists". Probe cats, cats1, cats2, ... instead.
|
||||
const { deriveUniqueInviteeUsername } = require('/models/lib/inviteeUsername');
|
||||
username = await deriveUniqueInviteeUsername(
|
||||
email,
|
||||
async candidate => !!(await ReactiveCache.getUser({ username: candidate })),
|
||||
);
|
||||
if (username === null) throw new Meteor.Error('error-username-taken');
|
||||
if (username.includes('/') || email.includes('/')) {
|
||||
return false;
|
||||
}
|
||||
@@ -1219,7 +1277,25 @@ Accounts.onCreateUser(async (options, user) => {
|
||||
existingUser.services[service] = user.services[service];
|
||||
existingUser.emails = user.emails;
|
||||
existingUser.username = user.username;
|
||||
existingUser.profile = user.profile;
|
||||
// #4560 ("User Profile is reset when changing the authentication method
|
||||
// from LDAP to OIDC"): merge the profile, do not replace it. The previous
|
||||
// wholesale `existingUser.profile = user.profile` re-inserted the linked
|
||||
// account with ONLY the freshly built OIDC profile (initials, fullname,
|
||||
// boardView), wiping profile.avatarUrl, profile.templatesBoardId and the
|
||||
// template swimlane ids, language, notification/preference fields, etc. —
|
||||
// the reporter's "templates and avatars disappeared". Keep every existing
|
||||
// profile field, fill gaps from the OIDC-derived profile, and take the
|
||||
// provider's fullname/initials only when the provider actually asserted a
|
||||
// fullname (otherwise user.profile.fullname is just a fallback to the
|
||||
// username and must not overwrite a real stored name).
|
||||
existingUser.profile = {
|
||||
...user.profile,
|
||||
...(existingUser.profile || {}),
|
||||
};
|
||||
if (user.services.oidc.fullname) {
|
||||
existingUser.profile.fullname = user.profile.fullname;
|
||||
existingUser.profile.initials = user.profile.initials;
|
||||
}
|
||||
existingUser.authenticationMethod = user.authenticationMethod;
|
||||
|
||||
await Meteor.users.removeAsync({ _id: user._id });
|
||||
@@ -1265,11 +1341,12 @@ Accounts.onCreateUser(async (options, user) => {
|
||||
boardView: 'board-view-swimlanes',
|
||||
};
|
||||
|
||||
Meteor.setTimeout(() => {
|
||||
InvitationCodes.removeAsync({ _id: invitationCode._id }).catch(error => {
|
||||
console.error('Failed to remove invitation code after signup:', error);
|
||||
});
|
||||
}, 200);
|
||||
// #4043: do NOT delete the invitation code here — this hook runs BEFORE the
|
||||
// account insert is committed, so a failed insert (duplicate username/email,
|
||||
// validation error) used to destroy the code anyway and every retry got
|
||||
// "The invitation code doesn't exist". Consumption is handled after a
|
||||
// SUCCESSFUL insert by Users.after.insert, which marks the code used; and a
|
||||
// re-invite now regenerates a stale code (models/lib/invitationCodeEmail.js).
|
||||
return user;
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,14 @@ import Org from "../../models/org";
|
||||
import Team from "../../models/team";
|
||||
import Attachments from '../../models/attachments';
|
||||
import Boards from '/models/boards';
|
||||
import Cards from '/models/cards';
|
||||
import { localizeBoardMemberAvatars } from '/server/lib/localizeAvatar';
|
||||
import { collectAncestorIds } from '/server/lib/subtaskAncestors';
|
||||
import {
|
||||
showsCardCounterList,
|
||||
countCardsByListId,
|
||||
buildBoardTileData,
|
||||
} from '/models/lib/boardTileData';
|
||||
|
||||
// When CARDS_LOADING=lazy (Admin Panel / Features), the board publication must
|
||||
// NOT ship every card / checklist into the client's minimongo — each list loads
|
||||
@@ -288,6 +295,105 @@ Meteor.methods({
|
||||
const ids = boards.slice(start, start + perPage).map(b => b._id);
|
||||
return { ids, total };
|
||||
},
|
||||
|
||||
// #5174 / #4825 (follow-up to #4214): the data behind the All Boards board
|
||||
// tiles — the per-list card-count line and the member avatar row. Computed
|
||||
// ONCE per request, entirely server-side (one boards query, one lists query,
|
||||
// one grouped card count), and returned as a plain map keyed by board id.
|
||||
// The client stores it in a ReactiveVar it sets exactly once, instead of the
|
||||
// old reactive getLists()/getCards() cursors inside the tile helpers that
|
||||
// caused the "icons random dance" (#4214) and were therefore stubbed out —
|
||||
// which in turn hid the counters/avatars for everyone.
|
||||
//
|
||||
// The per-board opt-in flags (allowsCardCounterList / allowsBoardMemberList,
|
||||
// board sidebar "Show at All Boards page") are resolved here with strict
|
||||
// semantics — missing flag means OFF — so every tile renders consistently
|
||||
// (#4825). The Admin Panel hideCardCounterList / hideBoardMemberList
|
||||
// settings remain enforced by the template on top of this.
|
||||
async getAllBoardsTileData() {
|
||||
const userId = this.userId;
|
||||
if (!Match.test(userId, String) || !userId) {
|
||||
return {};
|
||||
}
|
||||
const user = await ReactiveCache.getUser(userId);
|
||||
if (!user) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Same visibility selector as getAllBoardsPage / the `boards` publication,
|
||||
// restricted to real boards (template-container tiles never show these).
|
||||
const selector = {
|
||||
archived: false,
|
||||
type: 'board',
|
||||
$or: [
|
||||
{ permission: 'public' },
|
||||
{ members: { $elemMatch: { userId, isActive: true } } },
|
||||
{ orgs: { $elemMatch: { orgId: { $in: user.orgIds() }, isActive: true } } },
|
||||
{ teams: { $elemMatch: { teamId: { $in: user.teamIds() }, isActive: true } } },
|
||||
{ domains: { $elemMatch: { domain: { $in: user.emailDomains() }, isActive: true } } },
|
||||
],
|
||||
};
|
||||
|
||||
let boards = await ReactiveCache.getBoards(
|
||||
selector,
|
||||
{
|
||||
fields: {
|
||||
_id: 1,
|
||||
members: 1,
|
||||
allowsCardCounterList: 1,
|
||||
allowsBoardMemberList: 1,
|
||||
},
|
||||
},
|
||||
true,
|
||||
);
|
||||
boards = typeof boards.fetchAsync === 'function'
|
||||
? await boards.fetchAsync()
|
||||
: (typeof boards.fetch === 'function' ? boards.fetch() : boards);
|
||||
|
||||
// Lists and card counts are only needed for boards that opted in to the
|
||||
// card-counter line.
|
||||
const countedBoardIds = boards
|
||||
.filter(board => showsCardCounterList(board))
|
||||
.map(board => board._id);
|
||||
|
||||
let lists = [];
|
||||
const cardCounts = {};
|
||||
if (countedBoardIds.length) {
|
||||
lists = await ReactiveCache.getLists(
|
||||
{ boardId: { $in: countedBoardIds }, archived: false },
|
||||
{ fields: { _id: 1, boardId: 1, title: 1, sort: 1 } },
|
||||
true,
|
||||
);
|
||||
lists = typeof lists.fetchAsync === 'function'
|
||||
? await lists.fetchAsync()
|
||||
: (typeof lists.fetch === 'function' ? lists.fetch() : lists);
|
||||
|
||||
try {
|
||||
// One grouped count for all boards on the page instead of a count per
|
||||
// list (and instead of shipping every card to the client, which is
|
||||
// what the old reactive helpers effectively did).
|
||||
const rows = await Cards.rawCollection()
|
||||
.aggregate([
|
||||
{ $match: { boardId: { $in: countedBoardIds }, archived: false } },
|
||||
{ $group: { _id: '$listId', n: { $sum: 1 } } },
|
||||
])
|
||||
.toArray();
|
||||
rows.forEach(row => {
|
||||
if (row && row._id) cardCounts[row._id] = row.n;
|
||||
});
|
||||
} catch (error) {
|
||||
// Aggregation may be unavailable on some storage backends; fall back
|
||||
// to fetching only the cards' listId and folding in memory.
|
||||
const cards = await Cards.find(
|
||||
{ boardId: { $in: countedBoardIds }, archived: false },
|
||||
{ fields: { listId: 1 } },
|
||||
).fetchAsync();
|
||||
Object.assign(cardCounts, countCardsByListId(cards));
|
||||
}
|
||||
}
|
||||
|
||||
return buildBoardTileData(boards, lists, cardCounts);
|
||||
},
|
||||
});
|
||||
|
||||
Meteor.publish('archivedBoards', async function() {
|
||||
@@ -550,7 +656,21 @@ publishComposite('board', async function(boardId, isArchived) {
|
||||
const parentIds = cards.filter(c => c.parentId).map(c => c.parentId);
|
||||
if (parentIds.length === 0) return null;
|
||||
|
||||
return await ReactiveCache.getCards({ _id: { $in: parentIds } }, {}, true);
|
||||
// #3453: the 'prefix-with-full-path' subtask setting renders the
|
||||
// WHOLE ancestor chain (models/cards.js parentString()), and the
|
||||
// ancestors of a cross-board subtask live on the parent board, so
|
||||
// they are not covered by any other cursor of this publication.
|
||||
// Publishing only the direct parents truncated the path after a hard
|
||||
// refresh — walk every level so the full path survives F5.
|
||||
const ancestorIds = await collectAncestorIds(parentIds, ids =>
|
||||
ReactiveCache.getCards(
|
||||
{ _id: { $in: ids } },
|
||||
{ fields: { _id: 1, parentId: 1 } },
|
||||
false,
|
||||
),
|
||||
);
|
||||
|
||||
return await ReactiveCache.getCards({ _id: { $in: ancestorIds } }, {}, true);
|
||||
}
|
||||
},
|
||||
// Linked cards (cardType-linkedCard)
|
||||
|
||||
+45
-9
@@ -9,6 +9,7 @@ import Checklists from '/models/checklists';
|
||||
import Swimlanes from '/models/swimlanes';
|
||||
import { relativeDateOffset } from '/models/lib/relativeDateOffset';
|
||||
import { resolveRuleSwimlaneId, resolveRuleListId } from '/models/lib/ruleActionResolve';
|
||||
import { cardTitleMatchList } from '/models/lib/ruleCardTitleFilter';
|
||||
|
||||
// #5536: robustly resolve a destination board's default swimlane, tolerating a
|
||||
// board that lacks a swimlane literally titled 'Default' (renamed/translated) or
|
||||
@@ -131,10 +132,27 @@ export const RulesHelper = {
|
||||
value = oldSwimlane.title;
|
||||
}
|
||||
}
|
||||
let matchesList = [value, '*'];
|
||||
if ((field === 'cardTitle') && (value !== undefined)) {
|
||||
matchesList = value.split(/\W/).concat(matchesList);
|
||||
if (field === 'cardTitle') {
|
||||
// #2345: archivedCard/restoredCard activities carry no cardTitle, so a
|
||||
// "when a card is archived" trigger with a title filter could never be
|
||||
// enforced. Resolve the title from the activity's card instead.
|
||||
if (value === undefined && activity.cardId) {
|
||||
const card = await ReactiveCache.getCard(activity.cardId);
|
||||
if (card) {
|
||||
value = card.title;
|
||||
}
|
||||
}
|
||||
// #2345: cardTitleMatchList() matches the exact title, its single
|
||||
// words, the '*' wildcard, and null — the latter also matches trigger
|
||||
// documents saved WITHOUT a cardTitle field (the old wizard's generic
|
||||
// "when a card is moved" / archive triggers), which otherwise never
|
||||
// satisfy a $in query and made those rules fire for nothing.
|
||||
matchingMap[field] = {
|
||||
$in: cardTitleMatchList(value),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
const matchesList = [value, '*'];
|
||||
matchingMap[field] = {
|
||||
$in: matchesList,
|
||||
};
|
||||
@@ -385,19 +403,37 @@ export const RulesHelper = {
|
||||
if (action.actionType === 'removeLabel') {
|
||||
card.removeLabel(action.labelId);
|
||||
}
|
||||
// #2674: resolve the username defensively for the member actions. A rule
|
||||
// whose username no longer resolves (user renamed/deleted, or a typo in an
|
||||
// API-created rule) crashed here on `undefined._id`; the activity hook
|
||||
// swallows the error, so the rule silently "did nothing" — the classic
|
||||
// "member is added on move-to but never removed on move-from" report. Warn
|
||||
// instead of crashing, and await the writes so failures are not lost.
|
||||
if (action.actionType === 'addMember') {
|
||||
const memberId = (await ReactiveCache.getUser({ username: action.username }))._id;
|
||||
card.assignMember(memberId);
|
||||
const member = await ReactiveCache.getUser({ username: action.username });
|
||||
if (member) {
|
||||
await card.assignMember(member._id);
|
||||
} else {
|
||||
console.warn(
|
||||
`WeKan rule action addMember: user "${action.username}" not found; skipping.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (action.actionType === 'removeMember') {
|
||||
if (action.username === '*') {
|
||||
const members = card.members;
|
||||
const members = card.members || [];
|
||||
for (let i = 0; i < members.length; i++) {
|
||||
card.unassignMember(members[i]);
|
||||
await card.unassignMember(members[i]);
|
||||
}
|
||||
} else {
|
||||
const memberId = (await ReactiveCache.getUser({ username: action.username }))._id;
|
||||
card.unassignMember(memberId);
|
||||
const member = await ReactiveCache.getUser({ username: action.username });
|
||||
if (member) {
|
||||
await card.unassignMember(member._id);
|
||||
} else {
|
||||
console.warn(
|
||||
`WeKan rule action removeMember: user "${action.username}" not found; skipping.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// #5283: the checklist (and checklist item) may not exist on the card — guard
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// ============================================================================
|
||||
// Startup schema upgrade (#6473 follow-up): on start, check that data from
|
||||
// every old WeKan version is migrated to the newest database structure and
|
||||
// migrate only what is missing — all platforms (Snap, Docker, Sandstorm,
|
||||
// source), both databases (MongoDB and FerretDB).
|
||||
//
|
||||
// VERSION-GATED: the `_wekan_migration` marker stores the WeKan version and
|
||||
// datetime of the previous successful re-check. While the version is
|
||||
// unchanged a boot costs ONE findOne; a full re-check is mandatory only after
|
||||
// a new WeKan release. Force one with WEKAN_FORCE_SCHEMA_UPGRADE=true; opt
|
||||
// out entirely with WEKAN_SKIP_SCHEMA_UPGRADE=true.
|
||||
//
|
||||
// The upgrade runs in the BACKGROUND (WeKan serves immediately) and publishes
|
||||
// live progress at /schema-upgrade-status (HTML dashboard, ?json for raw
|
||||
// state). The dashboard shows the Admin Panel product name when one is set.
|
||||
//
|
||||
// The actual steps live in server/lib/schemaUpgradeSteps.js (pure, driver-
|
||||
// based, unit-tested by tests/schemaUpgradeSteps.test.cjs, batched
|
||||
// updateMany/distinct queries so big databases stay fast).
|
||||
// ============================================================================
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { MongoInternals } from 'meteor/mongo';
|
||||
import { WebApp } from 'meteor/webapp';
|
||||
import { runSchemaUpgrade, getUpgradeState } from '/server/lib/schemaUpgradeSteps';
|
||||
|
||||
function escHtml(s) {
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// Live migration dashboard — same spirit as the MongoDB→FerretDB importer
|
||||
// dashboards, available on every platform while WeKan runs.
|
||||
WebApp.handlers.get('/schema-upgrade-status', (req, res) => {
|
||||
const state = getUpgradeState();
|
||||
if ('json' in (req.query || {})) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(state, null, 2));
|
||||
return;
|
||||
}
|
||||
const rows = Object.entries(state.steps).map(([name, s]) => {
|
||||
const color = s.status === 'error' ? '#f77' : s.status === 'running' || s.status === 'checking' ? '#fb7' : s.status === 'done' ? '#7f7' : '#aaa';
|
||||
return `<tr><td>${escHtml(name)}</td><td style="color:${color}">${escHtml(s.status)}</td>`
|
||||
+ `<td>${s.fixed || 0}</td><td class="${s.unresolved ? 'fail' : ''}">${s.unresolved || 0}</td>`
|
||||
+ `<td>${s.error ? escHtml(s.error) : ''}</td></tr>`;
|
||||
}).join('');
|
||||
const product = escHtml(state.product || 'WeKan');
|
||||
const phase = state.running
|
||||
? `Checking / migrating… (${escHtml(state.currentStep || '')})`
|
||||
: state.gated
|
||||
? `Already re-checked for version ${escHtml(state.appVersion)} — nothing to do`
|
||||
: state.finishedAt ? 'Completed' : 'Not started yet';
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">${state.running ? '<meta http-equiv="refresh" content="3">' : ''}
|
||||
<title>${product} Schema Upgrade</title>
|
||||
<style>body{font-family:monospace;background:#111;color:#ddd;padding:1em 2em}h1{color:#7bf}
|
||||
table{border-collapse:collapse}td,th{padding:4px 10px;border-bottom:1px solid #333;text-align:left}
|
||||
th{color:#aaa;font-size:.85em}.fail{color:#f77}</style></head><body>
|
||||
<h1>${product} Schema Upgrade</h1>
|
||||
<p>Status: <strong>${phase}</strong></p>
|
||||
<p style="color:#aaa">WeKan version: ${escHtml(state.appVersion || '?')}
|
||||
${state.lastCheck ? ` · previous re-check: ${escHtml(state.lastCheck.version)} at ${escHtml(String(state.lastCheck.at))}` : ''}
|
||||
${state.startedAt ? ` · started: ${escHtml(String(state.startedAt))}` : ''}
|
||||
${state.finishedAt ? ` · finished: ${escHtml(String(state.finishedAt))}` : ''}</p>
|
||||
<table><tr><th>Step</th><th>Status</th><th>Fixed</th><th>Unresolved</th><th>Error</th></tr>${rows}</table>
|
||||
<p style="color:#aaa">A re-check is mandatory only after a new ${product} release; while the version
|
||||
is unchanged, startup costs a single database read. Raw state: <a href="/schema-upgrade-status?json" style="color:#7bf">JSON</a></p>
|
||||
</body></html>`);
|
||||
});
|
||||
|
||||
Meteor.startup(() => {
|
||||
if (process.env.WEKAN_SKIP_SCHEMA_UPGRADE === 'true') {
|
||||
console.log('[schema-upgrade] skipped (WEKAN_SKIP_SCHEMA_UPGRADE=true)');
|
||||
return;
|
||||
}
|
||||
// Deliberately NOT awaited: WeKan starts serving immediately; the upgrade
|
||||
// runs in the background and reports at /schema-upgrade-status.
|
||||
(async () => {
|
||||
try {
|
||||
const db = MongoInternals.defaultRemoteCollectionDriver()?.mongo?.db;
|
||||
if (!db) {
|
||||
console.warn('[schema-upgrade] no database handle at startup; skipping (will retry next start)');
|
||||
return;
|
||||
}
|
||||
let appVersion = '';
|
||||
try { appVersion = require('/package.json').version || ''; } catch { /* keep '' */ }
|
||||
const { ran, gated } = await runSchemaUpgrade(db, {
|
||||
appVersion,
|
||||
log: (...args) => console.log('[schema-upgrade]', ...args),
|
||||
});
|
||||
if (!gated && ran.length > 0) {
|
||||
console.log(`[schema-upgrade] upgraded old-version data: ${ran.join(', ')}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[schema-upgrade] failed (WeKan continues; retried next start):', error.message);
|
||||
}
|
||||
})();
|
||||
});
|
||||
Executable
+193
@@ -0,0 +1,193 @@
|
||||
#!/bin/bash
|
||||
# attachment-repair — automatic, incremental attachment/avatar repair (#6473).
|
||||
#
|
||||
# Older MongoDB → FerretDB migrations silently lost attachments (CollectionFS
|
||||
# copies.<bucket>.key was never resolved; Meteor-Files records carrying only a
|
||||
# gridFsFileId reference were skipped). The source MongoDB data was NEVER
|
||||
# modified, so everything is recoverable. This script runs in the BACKGROUND at
|
||||
# every WeKan start (wekan-control) when the snap is on FerretDB and, ONCE:
|
||||
# 1. starts a temporary source mongod (7.x, or the bundled 3.2 for old data)
|
||||
# on port 27099 — read-only use, the data is never modified;
|
||||
# 2. runs the migration importer in FILES_ONLY mode against the LIVE FerretDB:
|
||||
# text collections are left completely untouched, files already migrated
|
||||
# are verified (record on 'fs' + file on disk) and skipped, and ONLY the
|
||||
# missing attachments/avatars are migrated;
|
||||
# 3. on success writes $SNAP_COMMON/.attachments-files-v2-done so it never
|
||||
# runs again ("v2" matches FILES_VERSION in migrate-mongodb-to-ferretdb.mjs
|
||||
# — bump both together when a future file-phase fix needs a re-scan).
|
||||
# A failure leaves the marker absent, so the next start retries. WeKan starts
|
||||
# and serves normally the whole time; repaired attachments appear as they are
|
||||
# migrated (Meteor re-polls the queries).
|
||||
set -u
|
||||
|
||||
COMMON="${SNAP_COMMON:-/var/snap/${SNAP_INSTANCE_NAME:-${SNAP_NAME:-wekan}}/common}"
|
||||
MARKER="$COMMON/.attachments-files-v2-done"
|
||||
LOCK="$COMMON/.attachment-repair.pid"
|
||||
SRC_PORT="${REPAIR_SRC_PORT:-27099}" # temp source mongod (same as migration-control)
|
||||
SRC_PIDFILE="$COMMON/attachment-repair-mongod.pid"
|
||||
LOGF="$COMMON/attachment-repair-mongod.log"
|
||||
NODE="$SNAP/bin/node"
|
||||
DB_EVAL="$SNAP/bin/db-eval"
|
||||
IMPORTER_MODERN="$SNAP/bin/migrate-mongodb-to-ferretdb.mjs"
|
||||
IMPORTER_3="$SNAP/bin/migrate-mongo3-to-ferretdb.mjs"
|
||||
MM="$SNAP/migratemongo" # MongoDB 3.2 tools (amd64)
|
||||
MM_LIB="$MM/lib/x86_64-linux-gnu"
|
||||
WAIT_SECS="${REPAIR_WAIT_SECS:-60}" # max wait for the live FerretDB
|
||||
|
||||
log() { echo "[attachment-repair] $*"; }
|
||||
|
||||
# ── Guards: run at most once, only when there is something to do ─────────────
|
||||
[ -f "$MARKER" ] && exit 0
|
||||
|
||||
if [ -f "$COMMON/.wekan-maintenance" ]; then
|
||||
log "maintenance mode is on; skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Only meaningful when WeKan runs on FerretDB. Before the switch, the normal
|
||||
# migration path (migration-control, with the fixed importers) covers files.
|
||||
if [ "$(snapctl get database 2>/dev/null)" != "ferretdb" ]; then
|
||||
log "database is not ferretdb; nothing to repair yet."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! bash "$SNAP/bin/ferretdb-has-data"; then
|
||||
log "no FerretDB (SQLite) data yet; skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# No MongoDB source data left on this machine: there is nothing to repair FROM,
|
||||
# and never will be — mark done so this never probes again.
|
||||
if [ ! -f "$COMMON/WiredTiger" ] && ! ls "$COMMON"/collection-*.wt >/dev/null 2>&1; then
|
||||
log "no MongoDB source data in $COMMON; nothing to repair. Marking done."
|
||||
touch "$MARKER" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Single instance across restarts (WeKan can be restarted while a repair runs).
|
||||
if [ -f "$LOCK" ]; then
|
||||
p="$(cat "$LOCK" 2>/dev/null)"
|
||||
if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then
|
||||
log "a repair is already running (pid $p); skipping."
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo $$ > "$LOCK"
|
||||
|
||||
stop_src() {
|
||||
if [ -f "$SRC_PIDFILE" ]; then
|
||||
local p; p="$(cat "$SRC_PIDFILE" 2>/dev/null)"
|
||||
if [ -n "$p" ]; then
|
||||
"$DB_EVAL" shutdown "mongodb://127.0.0.1:$SRC_PORT/?directConnection=true" >/dev/null 2>&1 || true
|
||||
sleep 1
|
||||
kill "$p" 2>/dev/null || true
|
||||
sleep 1
|
||||
kill -9 "$p" 2>/dev/null || true
|
||||
fi
|
||||
rm -f "$SRC_PIDFILE"
|
||||
fi
|
||||
}
|
||||
cleanup() { stop_src; rm -f "$LOCK"; }
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# ── The LIVE FerretDB is the repair target ────────────────────────────────────
|
||||
# Same address wekan-control builds MONGO_URL from (defaults 127.0.0.1:27019).
|
||||
BIND_IP="${MONGODB_BIND_IP:-127.0.0.1}"
|
||||
DB_PORT="${MONGODB_PORT:-27019}"
|
||||
TARGET_URL="${REPAIR_TARGET_URL:-mongodb://$BIND_IP:$DB_PORT/wekan}"
|
||||
waited=0
|
||||
until "$DB_EVAL" ping "mongodb://$BIND_IP:$DB_PORT/?directConnection=true" >/dev/null 2>&1; do
|
||||
waited=$((waited + 2))
|
||||
if [ "$waited" -ge "$WAIT_SECS" ]; then
|
||||
log "FerretDB not reachable on $BIND_IP:$DB_PORT after ${WAIT_SECS}s; will retry on the next start."
|
||||
exit 1
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
export LC_ALL=C
|
||||
export LD_LIBRARY_PATH="$SNAP/lib:$SNAP/lib/x86_64-linux-gnu:$SNAP/lib/aarch64-linux-gnu:${LD_LIBRARY_PATH:-}"
|
||||
|
||||
# RAM-aware WiredTiger cache for the temporary source mongod, like
|
||||
# migration-control: mongod's own ~50%-of-RAM default is too much next to the
|
||||
# running FerretDB + WeKan (#6454). Quarter of (RAM - 1 GB), min 1, cap 8.
|
||||
if [ -n "${MIGRATION_MONGOD_CACHE_GB:-}" ]; then
|
||||
SRC_WT_CACHE_GB="${MIGRATION_MONGOD_CACHE_GB}"
|
||||
else
|
||||
_mem_kb=$(awk '/^MemTotal:/{print $2}' /proc/meminfo 2>/dev/null)
|
||||
[ -z "${_mem_kb:-}" ] && _mem_kb=2097152
|
||||
_mem_gb=$(( _mem_kb / 1024 / 1024 ))
|
||||
SRC_WT_CACHE_GB=$(( (_mem_gb - 1) / 4 ))
|
||||
[ "${SRC_WT_CACHE_GB}" -lt 1 ] && SRC_WT_CACHE_GB=1
|
||||
[ "${SRC_WT_CACHE_GB}" -gt 8 ] && SRC_WT_CACHE_GB=8
|
||||
fi
|
||||
|
||||
# ── Start the temporary source mongod (7.x first, then the 3.2 reader) ───────
|
||||
start_mongod() { # $1 = mongod binary, $2 = LD_LIBRARY_PATH prefix, $3 = extra args, $4 = cpu-exec features
|
||||
rm -f "$SRC_PIDFILE"
|
||||
LD_LIBRARY_PATH="${2:+$2:}$LD_LIBRARY_PATH" bash "$SNAP/bin/cpu-exec" --features "${4:-}" "$1" \
|
||||
--dbpath "$COMMON" --bind_ip 127.0.0.1 --port "$SRC_PORT" \
|
||||
--logpath "$LOGF" --logappend --fork --pidfilepath "$SRC_PIDFILE" ${3:-} >/dev/null 2>&1
|
||||
}
|
||||
ready_via_node() {
|
||||
local i=0 p
|
||||
while [ $i -lt 45 ]; do
|
||||
"$DB_EVAL" ping "mongodb://127.0.0.1:$SRC_PORT/?directConnection=true" >/dev/null 2>&1 && return 0
|
||||
p="$(cat "$SRC_PIDFILE" 2>/dev/null)"
|
||||
if [ -n "$p" ] && ! kill -0 "$p" 2>/dev/null; then return 1; fi
|
||||
i=$((i+1)); sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
ready_via_legacy() {
|
||||
local i=0
|
||||
while [ $i -lt 20 ]; do
|
||||
LD_LIBRARY_PATH="$MM_LIB:$LD_LIBRARY_PATH" "$MM/bin/mongo" --port "$SRC_PORT" --quiet \
|
||||
--eval 'db.adminCommand({ping:1}).ok' 2>/dev/null | grep -q 1 && return 0
|
||||
i=$((i+1)); sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
MONGOD7_CPU_FEATURES="x86_64=avx,aarch64=atomics"
|
||||
rc=1
|
||||
log "checking whether the source data opens with mongod 7 ..."
|
||||
if start_mongod "$SNAP/bin/mongod" "" "--wiredTigerCacheSizeGB ${SRC_WT_CACHE_GB}" "$MONGOD7_CPU_FEATURES" && ready_via_node; then
|
||||
log "modern MongoDB source. Running the incremental FILES_ONLY repair against $TARGET_URL ..."
|
||||
NODE_PATH="$SNAP/programs/server/node_modules" \
|
||||
SOURCE_MONGO_URL="mongodb://127.0.0.1:$SRC_PORT/wekan?directConnection=true" \
|
||||
TARGET_MONGO_URL="$TARGET_URL" \
|
||||
WRITABLE_PATH="$COMMON" \
|
||||
FILES_ONLY=true \
|
||||
MIGRATION_PORT=0 \
|
||||
"$NODE" "$IMPORTER_MODERN"
|
||||
rc=$?
|
||||
else
|
||||
stop_src
|
||||
if [ -x "$MM/bin/mongod" ] && [ -x "$MM/bin/mongo" ] && [ -f "$IMPORTER_3" ] \
|
||||
&& start_mongod "$MM/bin/mongod" "$MM_LIB" "" "" && ready_via_legacy; then
|
||||
log "MongoDB 3.x source. Running the incremental FILES_ONLY repair against $TARGET_URL ..."
|
||||
NODE_PATH="$SNAP/programs/server/node_modules" \
|
||||
MONGO_BIN_DIR="$MM/bin" \
|
||||
MONGO_LIB="$MM_LIB" \
|
||||
SRC_PORT="$SRC_PORT" \
|
||||
SRC_DB="wekan" \
|
||||
TARGET_MONGO_URL="$TARGET_URL" \
|
||||
FILES_DIR="$COMMON/files" \
|
||||
FILES_ONLY=true \
|
||||
MIGRATION_PORT=0 \
|
||||
"$NODE" "$IMPORTER_3"
|
||||
rc=$?
|
||||
else
|
||||
log "the MongoDB source data opens with neither mongod 7 nor the bundled 3.2 reader; will retry on the next start."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$rc" -eq 0 ]; then
|
||||
log "repair completed. Marking done ($MARKER)."
|
||||
touch "$MARKER" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
log "repair did not complete (importer rc=$rc); will retry on the next start."
|
||||
exit 1
|
||||
@@ -54,6 +54,30 @@ function sanitizeFilename(name) {
|
||||
return name || 'file';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the GridFS ObjectId of a CollectionFS filerecord (#6473). Real
|
||||
* CollectionFS (old WeKan, FS.Store.GridFS named after the bucket) stores it at
|
||||
* `copies.<storeName>.key` where the store name equals the bucket name —
|
||||
* `copies.attachments.key` / `copies.avatars.key`. The old lookup only tried
|
||||
* `original.gridFsFileId`, which does not exist in that layout, so every
|
||||
* CollectionFS attachment was silently skipped.
|
||||
*/
|
||||
function resolveCfsGridFsId(record, bucketName) {
|
||||
if (!record || typeof record !== 'object') return null;
|
||||
const original = record.original || {};
|
||||
if (original.gridFsFileId) return original.gridFsFileId;
|
||||
if (record.gridFsFileId) return record.gridFsFileId;
|
||||
const copies = record.copies;
|
||||
if (copies && typeof copies === 'object') {
|
||||
if (copies[bucketName] && copies[bucketName].key) return copies[bucketName].key;
|
||||
if (copies.gridfs && copies.gridfs.key) return copies.gridfs.key;
|
||||
for (const copy of Object.values(copies)) {
|
||||
if (copy && copy.key) return copy.key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function uniquePath(dir, idHex, originalName) {
|
||||
const safe = sanitizeFilename(originalName);
|
||||
let base = `${idHex}_${safe}`;
|
||||
@@ -94,29 +118,54 @@ let done = 0, skipped = 0, errors = 0;
|
||||
async function migrateCollection(collName, destDir, bucketPrefix) {
|
||||
const filesCollName = `${bucketPrefix}.files`;
|
||||
const allColls = (await db.listCollections().toArray()).map(c => c.name);
|
||||
if (!allColls.includes(filesCollName)) return;
|
||||
// #6473: do NOT return early when the CollectionFS bucket is missing — a pure
|
||||
// Meteor-Files database (any install born >= v6.10) has only <coll>.files,
|
||||
// and returning here made this tool a silent no-op for it.
|
||||
const haveCfsBucket = allColls.includes(filesCollName);
|
||||
const haveMfBucket = allColls.includes(`${collName}.files`);
|
||||
if (!haveCfsBucket && !haveMfBucket) return;
|
||||
|
||||
console.log(`[gridfs-migrate] Processing ${bucketPrefix} → ${destDir}`);
|
||||
const bucket = new GridFSBucket(db, { bucketName: bucketPrefix });
|
||||
console.log(`[gridfs-migrate] Processing ${collName} → ${destDir}`);
|
||||
// #6473: each source remembers WHICH GridFS bucket holds its binary —
|
||||
// CollectionFS filerecords point into cfs_gridfs.<coll>, Meteor-Files records
|
||||
// point into the <coll> bucket. Reading them all through the CFS bucket made
|
||||
// every Meteor-Files extraction fail.
|
||||
const cfsBucket = haveCfsBucket ? new GridFSBucket(db, { bucketName: bucketPrefix }) : null;
|
||||
const mfBucket = haveMfBucket ? new GridFSBucket(db, { bucketName: collName }) : null;
|
||||
|
||||
// Try CFS filerecord collection first, then fall back to Meteor-Files docs
|
||||
const sources = [];
|
||||
if (allColls.includes(`cfs.${collName}.filerecord`)) {
|
||||
if (haveCfsBucket && allColls.includes(`cfs.${collName}.filerecord`)) {
|
||||
const cursor = db.collection(`cfs.${collName}.filerecord`).find({});
|
||||
for await (const rec of cursor) {
|
||||
sources.push({ id: rec._id, gridFsId: rec.original?.gridFsFileId, name: rec.original?.name });
|
||||
// #6473: resolve the GridFS id from copies.<bucket>.key too (real
|
||||
// CollectionFS layout), not just original.gridFsFileId.
|
||||
sources.push({ id: rec._id, gridFsId: resolveCfsGridFsId(rec, collName), name: rec.original?.name, bucket: cfsBucket, filesCollName });
|
||||
}
|
||||
await cursor.close();
|
||||
}
|
||||
// Also handle Meteor-Files docs already in target that are marked storage:'gridfs'
|
||||
const mfCursor = db.collection(collName).find({ 'versions.original.storage': 'gridfs' });
|
||||
for await (const doc of mfCursor) {
|
||||
sources.push({ id: doc._id, gridFsId: doc.versions?.original?.meta?.gridFsFileId, name: doc.name });
|
||||
// Also handle Meteor-Files docs marked storage:'gridfs' OR carrying a
|
||||
// meta.gridFsFileId reference (#6473: the same rule WeKan's getFileStrategy
|
||||
// uses — records with only the reference were previously missed).
|
||||
if (mfBucket) {
|
||||
const mfCursor = db.collection(collName).find({ $or: [
|
||||
{ 'versions.original.storage': 'gridfs' },
|
||||
{ 'versions.original.meta.gridFsFileId': { $exists: true, $ne: null } },
|
||||
] });
|
||||
for await (const doc of mfCursor) {
|
||||
sources.push({ id: doc._id, gridFsId: doc.versions?.original?.meta?.gridFsFileId, name: doc.name, bucket: mfBucket, filesCollName: `${collName}.files` });
|
||||
}
|
||||
await mfCursor.close();
|
||||
}
|
||||
await mfCursor.close();
|
||||
|
||||
for (const src of sources) {
|
||||
if (!src.gridFsId) { skipped++; continue; }
|
||||
if (!src.gridFsId) {
|
||||
// #6473: report — a GridFS-flagged record with no locatable binary is
|
||||
// exactly how attachments go silently missing.
|
||||
console.error(`[gridfs-migrate] ${collName}/${src.id}: GridFS reference missing; cannot extract.`);
|
||||
errors++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const originalName = src.name || String(src.id);
|
||||
const { fullPath, basename } = uniquePath(destDir, String(src.id), originalName);
|
||||
@@ -124,10 +173,11 @@ async function migrateCollection(collName, destDir, bucketPrefix) {
|
||||
// Already extracted
|
||||
if (fs.existsSync(fullPath)) { skipped++; continue; }
|
||||
|
||||
// Disk space check
|
||||
// Disk space check (#6473: look the size up in the SOURCE's own files
|
||||
// collection — CFS and Meteor-Files binaries live in different buckets)
|
||||
let fileSize = 0;
|
||||
try {
|
||||
const meta = await db.collection(filesCollName).findOne({ _id: new ObjectId(src.gridFsId) });
|
||||
const meta = await db.collection(src.filesCollName).findOne({ _id: new ObjectId(src.gridFsId) });
|
||||
fileSize = meta?.length || 0;
|
||||
} catch {}
|
||||
if (!hasEnoughSpace(destDir, fileSize)) {
|
||||
@@ -137,7 +187,7 @@ async function migrateCollection(collName, destDir, bucketPrefix) {
|
||||
}
|
||||
|
||||
try {
|
||||
const bytes = await extractFile(bucket, src.gridFsId, fullPath);
|
||||
const bytes = await extractFile(src.bucket, src.gridFsId, fullPath);
|
||||
done++;
|
||||
console.log(`[gridfs-migrate] ${basename} (${(bytes/1024).toFixed(1)} KB)`);
|
||||
|
||||
|
||||
@@ -114,6 +114,12 @@ const SRC_DB = process.env.SRC_DB || 'wekan';
|
||||
const TARGET_URL = process.env.TARGET_MONGO_URL || 'mongodb://127.0.0.1:27098/wekan';
|
||||
const FILES_DIR = process.env.FILES_DIR || path.join(process.env.WRITABLE_PATH || '/data', 'files');
|
||||
const PORT = parseInt(process.env.MIGRATION_PORT || '8080', 10);
|
||||
// #6473: FILES_ONLY=true = incremental attachment/avatar repair against an existing,
|
||||
// LIVE target (set by the snap's attachment-repair on startup): the text collections
|
||||
// are left completely untouched (users may have changed them since the original
|
||||
// migration), already-migrated files are verified and skipped, and only missing
|
||||
// binaries/records are migrated.
|
||||
const FILES_ONLY = process.env.FILES_ONLY === 'true';
|
||||
// Optional: write the final migration state here as JSON so an admin UI can read
|
||||
// it later (e.g. WeKan on Sandstorm — Admin Panel / Attachments / Sandstorm).
|
||||
const STATUS_FILE = process.env.STATUS_FILE || '';
|
||||
@@ -357,6 +363,10 @@ ${currentHtml}
|
||||
<h2>Activity</h2><pre>${state.log.slice(-15).map(esc).join('\n') || '(waiting…)'}</pre>
|
||||
<h2>Errors</h2>${state.errors.slice(-15).reverse().map(e => `<div style="color:#c0392b">${esc(e)}</div>`).join('') || '<p class="muted">None</p>'}
|
||||
</div></body></html>`);
|
||||
}).on('error', (e) => {
|
||||
// A background FILES_ONLY repair runs while WeKan itself owns the web port (#6473):
|
||||
// the dashboard is a convenience — never crash the repair over EADDRINUSE.
|
||||
console.log(`[migrate3] progress dashboard not available (${e.code || e.message}); continuing without it.`);
|
||||
}).listen(PORT, () => console.log(`[migrate3] progress at http://localhost:${PORT}`));
|
||||
|
||||
// ── run a mongo CLI tool with the old libraries on LD_LIBRARY_PATH ────────────
|
||||
@@ -424,6 +434,39 @@ function legacyToV2(line) {
|
||||
|
||||
function ensureDir(p) { fs.mkdirSync(p, { recursive: true }); }
|
||||
|
||||
/**
|
||||
* Resolve the GridFS ObjectId of a CollectionFS filerecord (#6473).
|
||||
*
|
||||
* Real CollectionFS (old WeKan, FS.Store.GridFS named after the bucket) stores
|
||||
* the GridFS file id at `copies.<storeName>.key` where the store name equals
|
||||
* the bucket name — `copies.attachments.key` / `copies.avatars.key`. The old
|
||||
* lookup only tried `original.gridFsFileId`, `gridFsFileId` and
|
||||
* `copies.gridfs.key`, NONE of which exist in that layout, so no filerecord was
|
||||
* ever matched to its GridFS file: the binaries were extracted but no
|
||||
* attachment record was created, and every attachment was missing (#6473).
|
||||
* Try, in order:
|
||||
* 1. original.gridFsFileId / gridFsFileId (newer intermediate layouts)
|
||||
* 2. copies.<bucketName>.key (real CollectionFS layout)
|
||||
* 3. copies.gridfs.key (legacy fallback kept for safety)
|
||||
* 4. the first copies.*.key found (renamed stores)
|
||||
* Returns null when the record carries no GridFS reference at all.
|
||||
*/
|
||||
function resolveCfsGridFsId(record, bucketName) {
|
||||
if (!record || typeof record !== 'object') return null;
|
||||
const original = record.original || {};
|
||||
if (original.gridFsFileId) return original.gridFsFileId;
|
||||
if (record.gridFsFileId) return record.gridFsFileId;
|
||||
const copies = record.copies;
|
||||
if (copies && typeof copies === 'object') {
|
||||
if (copies[bucketName] && copies[bucketName].key) return copies[bucketName].key;
|
||||
if (copies.gridfs && copies.gridfs.key) return copies.gridfs.key;
|
||||
for (const copy of Object.values(copies)) {
|
||||
if (copy && copy.key) return copy.key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Resumable progress checkpoint ────────────────────────────────────────────
|
||||
// This migration can run for hours, and being interrupted part-way (snap refresh to a
|
||||
// new revision, `snap stop`, reboot, power loss) is normal rather than exceptional.
|
||||
@@ -662,6 +705,12 @@ async function run() {
|
||||
]);
|
||||
|
||||
// ── text collections (everything except the GridFS chunk/file collections) ──
|
||||
// #6473: FILES_ONLY repair NEVER touches text collections — users may have
|
||||
// added/changed boards and cards on FerretDB since the original migration, and
|
||||
// re-copying from the frozen MongoDB source would overwrite or resurrect data.
|
||||
if (FILES_ONLY) {
|
||||
logline('FILES_ONLY: skipping text collections; incremental attachment/avatar repair only.');
|
||||
} else {
|
||||
state.phase = 'migrating-collections';
|
||||
for (const name of all) {
|
||||
// FerretDB v1 rejects collection names containing a dot ("invalid key: '<name>' (key must
|
||||
@@ -690,6 +739,7 @@ async function run() {
|
||||
completedCollections.add(name);
|
||||
saveCheckpoint(true); // a collection boundary is worth a guaranteed write
|
||||
}
|
||||
} // end !FILES_ONLY (text collections)
|
||||
|
||||
// ── GridFS attachments + avatars -> filesystem ──────────────────────────────
|
||||
state.phase = 'migrating-files';
|
||||
@@ -721,12 +771,12 @@ async function run() {
|
||||
const filerecords = all.includes(`cfs.${bucket}.filerecord`) ? exportDocs(`cfs.${bucket}.filerecord`) : [];
|
||||
const byGridId = new Map();
|
||||
for (const fr of filerecords) {
|
||||
const gid = (fr.original && fr.original.gridFsFileId) || fr.gridFsFileId ||
|
||||
(fr.copies && fr.copies.gridfs && fr.copies.gridfs.key);
|
||||
const gid = resolveCfsGridFsId(fr, bucket);
|
||||
if (gid) byGridId.set(String(gid), fr);
|
||||
}
|
||||
const gfFiles = exportDocs(filesColl);
|
||||
logline(`${bucket}: ${gfFiles.length} GridFS files to extract -> ${destDir}`);
|
||||
let orphanFiles = 0; // GridFS files with no filerecord (extracted, kept on disk)
|
||||
for (const gf of gfFiles) {
|
||||
const fid = gf._id;
|
||||
const fr = byGridId.get(String(fid)) || {};
|
||||
@@ -742,6 +792,24 @@ async function run() {
|
||||
state.files[key].done++; state.files[key].bytes += Number(alreadyDone.size) || 0;
|
||||
continue;
|
||||
}
|
||||
// #6473: ALREADY MIGRATED? Check the TARGET itself — record present, version on
|
||||
// 'fs', file actually on disk. This makes the automatic startup repair
|
||||
// INCREMENTAL: healthy installs verify-and-skip, only what is missing migrates.
|
||||
if (fr._id) {
|
||||
try {
|
||||
const tgtRec = await db.collection(bucket).findOne({ _id: fr._id });
|
||||
const tv = tgtRec && tgtRec.versions && tgtRec.versions.original;
|
||||
if (tv && tv.storage === 'fs' && tv.path && fs.existsSync(tv.path)) {
|
||||
fileIndex++;
|
||||
state.files[key].done++; state.files[key].bytes += Number(tv.size) || 0;
|
||||
let onDiskSize = Number(tv.size) || 0;
|
||||
try { onDiskSize = fs.statSync(tv.path).size; } catch { /* keep record size */ }
|
||||
completedFiles.set(resumeKey, { path: tv.path, size: onDiskSize });
|
||||
saveCheckpoint();
|
||||
continue;
|
||||
}
|
||||
} catch { /* fall through to extraction */ }
|
||||
}
|
||||
if (!ensureDiskForFile(destDir, size, name)) { onDiskAbort(); return; }
|
||||
// Stream the file from its chunks (sorted by n) straight to disk, one chunk at a
|
||||
// time (bounded RAM), publishing live per-file progress for the dashboard.
|
||||
@@ -754,13 +822,34 @@ async function run() {
|
||||
finally { fs.closeSync(fd); }
|
||||
state.current.done = written;
|
||||
state.files[key].done++; state.files[key].bytes += written;
|
||||
// Meteor-Files record pointing at the filesystem path.
|
||||
// Meteor-Files record pointing at the filesystem path. #6473: real
|
||||
// CollectionFS filerecords keep boardId/cardId/... at the TOP level (not
|
||||
// under meta), so copy them into meta explicitly — a record without
|
||||
// meta.cardId is never shown on any card.
|
||||
if (fr._id) {
|
||||
const frMeta = fr.meta || {};
|
||||
await db.collection(bucket).replaceOne({ _id: fr._id }, {
|
||||
_id: fr._id, name, size: written, path: dest,
|
||||
versions: { original: { path: dest, storage: 'fs', size: written } },
|
||||
meta: { ...(fr.meta || {}), source: 'cfs-cli-migration', originalFilename: name },
|
||||
type: original.type || 'application/octet-stream',
|
||||
versions: { original: { path: dest, storage: 'fs', size: written, type: original.type || 'application/octet-stream' } },
|
||||
meta: {
|
||||
...frMeta,
|
||||
boardId: frMeta.boardId || fr.boardId || '',
|
||||
cardId: frMeta.cardId || fr.cardId || '',
|
||||
listId: frMeta.listId || fr.listId || '',
|
||||
swimlaneId: frMeta.swimlaneId || fr.swimlaneId || '',
|
||||
userId: frMeta.userId || fr.userId || '',
|
||||
source: 'cfs-cli-migration', originalFilename: name,
|
||||
cfsOriginalId: String(fr._id),
|
||||
},
|
||||
userId: frMeta.userId || fr.userId || '',
|
||||
collectionName: bucket,
|
||||
}, { upsert: true });
|
||||
} else {
|
||||
// No filerecord: there is no board/card to attach the file to, so no
|
||||
// record is created — but the binary IS extracted and kept on disk
|
||||
// instead of being silently lost.
|
||||
orphanFiles++;
|
||||
}
|
||||
// Done only now: bytes on disk AND a record pointing at them.
|
||||
completedFiles.set(resumeKey, { path: dest, size: written });
|
||||
@@ -769,6 +858,7 @@ async function run() {
|
||||
finally { state.current.active = false; }
|
||||
if (state.abort) { onDiskAbort(); return; }
|
||||
}
|
||||
if (orphanFiles > 0) logline(`${bucket}: ${orphanFiles} GridFS file(s) had no CollectionFS filerecord; extracted without a database record.`);
|
||||
logline(`${bucket}: extracted ${state.files[key].done} files (${(state.files[key].bytes / 1048576).toFixed(1)} MB)`);
|
||||
}
|
||||
|
||||
@@ -801,6 +891,24 @@ async function run() {
|
||||
state.files[key].done++; state.files[key].bytes += Number(alreadyDone.size) || 0;
|
||||
continue;
|
||||
}
|
||||
// #6473: ALREADY MIGRATED? Verify against the TARGET record — version on 'fs'
|
||||
// and the file on disk means nothing to do (incremental startup repair). And in
|
||||
// FILES_ONLY mode a record DELETED from the target since the migration must not
|
||||
// have its binary resurrected.
|
||||
try {
|
||||
const tgtRec = await db.collection(bucket).findOne({ _id: recId });
|
||||
const tv = tgtRec && tgtRec.versions && tgtRec.versions[versionName];
|
||||
if (tv && tv.storage === 'fs' && tv.path && fs.existsSync(tv.path)) {
|
||||
fileIndex++;
|
||||
state.files[key].done++; state.files[key].bytes += Number(tv.size) || 0;
|
||||
let onDiskSize = Number(tv.size) || 0;
|
||||
try { onDiskSize = fs.statSync(tv.path).size; } catch { /* keep record size */ }
|
||||
completedFiles.set(resumeKey, { path: tv.path, size: onDiskSize });
|
||||
saveCheckpoint();
|
||||
continue;
|
||||
}
|
||||
if (FILES_ONLY && !tgtRec) continue;
|
||||
} catch { /* fall through to extraction */ }
|
||||
if (!ensureDiskForFile(destDir, size, name)) { onDiskAbort(); return; }
|
||||
fileIndex++;
|
||||
state.current = { active: true, kind: key, name, size, done: 0, index: fileIndex, total: state.current.total };
|
||||
|
||||
@@ -241,6 +241,10 @@ finish_success() {
|
||||
log "FerretDB SQLite verified (${sq:-?})${wal:+; WAL log present}."
|
||||
log "Migration succeeded. Switching to FerretDB (SQLite); MongoDB will be shut down."
|
||||
touch "$MARKER"
|
||||
# #6473: this migration ran with the CURRENT (fixed) file extraction, so the startup
|
||||
# attachment-repair has nothing to do — mark it done up front. Keep the marker name in
|
||||
# sync with attachment-repair and FILES_VERSION in migrate-mongodb-to-ferretdb.mjs.
|
||||
touch "$SNAP_COMMON/.attachments-files-v2-done" 2>/dev/null || true
|
||||
# #6458/#6466: clear mongodb-control's start-failure counter — the migration
|
||||
# completing is exactly the recovery those failures were counting toward.
|
||||
rm -f "$SNAP_COMMON/.mongod-start-failures" 2>/dev/null || true
|
||||
|
||||
@@ -137,6 +137,14 @@ if [ "ferretdb" = "${DATABASE}" ]; then
|
||||
sleep 5
|
||||
done
|
||||
echo "FerretDB is ready."
|
||||
# #6473: SELF-HEALING attachments. Older MongoDB -> FerretDB migrations silently
|
||||
# lost attachments/avatars (CollectionFS copies.<bucket>.key was never resolved;
|
||||
# gridFsFileId-only Meteor-Files records were skipped). The MongoDB source data
|
||||
# was never modified, so everything is recoverable: run an automatic, INCREMENTAL
|
||||
# files-only repair in the background — it verifies what is already migrated,
|
||||
# migrates only what is missing, never touches text data, runs once (marker
|
||||
# $SNAP_COMMON/.attachments-files-v2-done) and never blocks WeKan from starting.
|
||||
bash "$SNAP/bin/attachment-repair" > "$SNAP_COMMON/attachment-repair.log" 2>&1 &
|
||||
elif [ "true" != "${DISABLE_MONGODB}" ]; then
|
||||
# Make sure the MongoDB service is enabled and running first; if it was left
|
||||
# stopped/disabled, enable and start it now so WeKan does not wait here forever.
|
||||
|
||||
@@ -28,11 +28,20 @@ case "${1:-}" in
|
||||
echo "Migrate first: snap run ${svc}.migrate (then: snap run ${svc}.database ferretdb)"
|
||||
exit 1
|
||||
fi
|
||||
snapctl set database=ferretdb 2>/dev/null || true
|
||||
snapctl stop --disable "${svc}.mongodb" 2>/dev/null || true
|
||||
snapctl start --enable "${svc}.ferretdb" 2>/dev/null || true
|
||||
snapctl restart "${svc}.wekan" 2>/dev/null || true
|
||||
echo "WeKan now uses FerretDB (SQLite)."
|
||||
# #6473: users ran `wekan.database ferretdb` expecting it to re-run the
|
||||
# migration — it only SWITCHES databases. Say so, and point at the command
|
||||
# that actually re-migrates, so "still no attachments" has a next step.
|
||||
if [ "$(snapctl get database 2>/dev/null)" = "ferretdb" ]; then
|
||||
echo "WeKan is already using FerretDB (SQLite); nothing switched."
|
||||
else
|
||||
snapctl set database=ferretdb 2>/dev/null || true
|
||||
snapctl stop --disable "${svc}.mongodb" 2>/dev/null || true
|
||||
snapctl start --enable "${svc}.ferretdb" 2>/dev/null || true
|
||||
snapctl restart "${svc}.wekan" 2>/dev/null || true
|
||||
echo "WeKan now uses FerretDB (SQLite)."
|
||||
fi
|
||||
echo "Note: this command only selects the database, it does NOT migrate data."
|
||||
echo "If data (for example attachments) is missing, re-run the full migration: snap run ${svc}.migrate"
|
||||
;;
|
||||
*)
|
||||
echo "Current database: $(snapctl get database 2>/dev/null || true)"
|
||||
|
||||
@@ -29,6 +29,9 @@ snapctl stop "${svc}.mongodb" 2>/dev/null || true
|
||||
# The source MongoDB data (WiredTiger files in $COMMON) is NOT touched.
|
||||
rm -f "$COMMON/.migration-to-ferretdb-done"
|
||||
rm -f "$COMMON/migration-progress.json"
|
||||
# #6473: a forced fresh migration re-does the file phase too, and finish_success
|
||||
# re-writes this marker — clear it so the startup attachment-repair state matches.
|
||||
rm -f "$COMMON/.attachments-files-v2-done"
|
||||
rm -rf "${COMMON:?}/files/db/"* 2>/dev/null || true
|
||||
|
||||
# Put the snap back on mongodb so the normal path (mongodb-control -> migration-control) runs;
|
||||
|
||||
@@ -127,6 +127,13 @@ apps:
|
||||
command: ./bin/wekan-force-migrate
|
||||
plugs: [network, network-bind]
|
||||
|
||||
# #6473: incremental attachment/avatar repair (runs automatically in the
|
||||
# background on every start; this command is for running it by hand, e.g.
|
||||
# after deleting $SNAP_COMMON/.attachments-files-v2-done).
|
||||
repair-attachments:
|
||||
command: ./bin/attachment-repair
|
||||
plugs: [network, network-bind]
|
||||
|
||||
maintenance:
|
||||
command: ./bin/wekan-maintenance
|
||||
plugs: [network, network-bind]
|
||||
|
||||
+11
-4
@@ -15,7 +15,7 @@
|
||||
# base: core24 (not core26) · no build-base: devel · grade: stable
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
name: wekan
|
||||
version: '9.96'
|
||||
version: '9.97'
|
||||
base: core24
|
||||
confinement: strict
|
||||
grade: stable
|
||||
@@ -130,6 +130,13 @@ apps:
|
||||
command: ./bin/wekan-force-migrate
|
||||
plugs: [network, network-bind]
|
||||
|
||||
# #6473: incremental attachment/avatar repair (runs automatically in the
|
||||
# background on every start; this command is for running it by hand, e.g.
|
||||
# after deleting $SNAP_COMMON/.attachments-files-v2-done).
|
||||
repair-attachments:
|
||||
command: ./bin/attachment-repair
|
||||
plugs: [network, network-bind]
|
||||
|
||||
maintenance:
|
||||
command: ./bin/wekan-maintenance
|
||||
plugs: [network, network-bind]
|
||||
@@ -250,13 +257,13 @@ parts:
|
||||
riscv64) WEKAN_ARCH="riscv64" ;;
|
||||
*) echo "Unsupported architecture: ${CRAFT_ARCH_BUILD_FOR}"; exit 1 ;;
|
||||
esac
|
||||
WEKAN_ZIP="wekan-9.96-${WEKAN_ARCH}.zip"
|
||||
WEKAN_ZIP="wekan-9.97-${WEKAN_ARCH}.zip"
|
||||
echo "Cleaning environment first"
|
||||
rm -rf .build
|
||||
mkdir .build
|
||||
cd .build
|
||||
#wget https://github.com/wekan/wekan/releases/download/v9.96/wekan-9.96-amd64.zip
|
||||
wget "https://github.com/wekan/wekan/releases/download/v9.96/${WEKAN_ZIP}"
|
||||
#wget https://github.com/wekan/wekan/releases/download/v9.97/wekan-9.97-amd64.zip
|
||||
wget "https://github.com/wekan/wekan/releases/download/v9.97/${WEKAN_ZIP}"
|
||||
unzip "${WEKAN_ZIP}"
|
||||
rm "${WEKAN_ZIP}"
|
||||
# Fix: bcrypt 5.0.1 (Meteor accounts-password) ships node-addon-api@3
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"uuid":"35f0e3fa-6c42-4d90-b45d-feb8ef847671","telemetry":false}
|
||||
@@ -0,0 +1,252 @@
|
||||
'use strict';
|
||||
|
||||
// Plain-Node unit test (no Meteor) for the sidebar Advanced Filter's handling
|
||||
// of date-type custom fields.
|
||||
// Run: ELECTRON_RUN_AS_NODE=1 <node> tests/advancedFilterDate.test.cjs
|
||||
//
|
||||
// Regression guard for #2989 ("Date custom field, filter problem"):
|
||||
// `'Date de fin' == '06/04/2020'` never matched any card, while '!=' matched
|
||||
// everything. Two independent defects:
|
||||
// 1. The tokenizer treated every '/' as a regex delimiter, even inside a
|
||||
// '…'-quoted value, so '06/04/2020' toggled string-mode twice and came
|
||||
// out flagged as a regex — the whole filter failed to parse.
|
||||
// 2. Date custom-field values are stored as Date objects (the date picker
|
||||
// calls card.setCustomField(id, date)), but '==' built
|
||||
// {$in: ['06/04/2020', NaN]} — a string and NaN never equal a BSON
|
||||
// date. parseAdvancedFilterDate()/buildDateValueSelector() now build a
|
||||
// Date-range selector instead.
|
||||
//
|
||||
// The logic lives in /imports/lib/advancedFilter.js (an ES module used by
|
||||
// client/lib/filter.js), loaded here with a dynamic import().
|
||||
|
||||
const assert = require('assert');
|
||||
|
||||
let passed = 0;
|
||||
const tests = [];
|
||||
function test(name, fn) {
|
||||
tests.push([name, fn]);
|
||||
}
|
||||
|
||||
// Minimal evaluator for the operator documents the filter builds against a
|
||||
// single stored 'customFields.value' — enough of Mongo/minimongo semantics
|
||||
// ($gte/$lt/$gt/$lte/$in/$not with BSON type bracketing: a Date only ever
|
||||
// compares to another Date) to show which cards a selector matches.
|
||||
function matchValue(selector, value) {
|
||||
if (selector instanceof RegExp) {
|
||||
return typeof value === 'string' && selector.test(value);
|
||||
}
|
||||
const comparable = (a, b) =>
|
||||
(a instanceof Date && b instanceof Date) ||
|
||||
(typeof a === 'number' && typeof b === 'number') ||
|
||||
(typeof a === 'string' && typeof b === 'string');
|
||||
const toV = x => (x instanceof Date ? x.getTime() : x);
|
||||
for (const [op, arg] of Object.entries(selector)) {
|
||||
switch (op) {
|
||||
case '$gte':
|
||||
if (!(comparable(value, arg) && toV(value) >= toV(arg))) return false;
|
||||
break;
|
||||
case '$gt':
|
||||
if (!(comparable(value, arg) && toV(value) > toV(arg))) return false;
|
||||
break;
|
||||
case '$lte':
|
||||
if (!(comparable(value, arg) && toV(value) <= toV(arg))) return false;
|
||||
break;
|
||||
case '$lt':
|
||||
if (!(comparable(value, arg) && toV(value) < toV(arg))) return false;
|
||||
break;
|
||||
case '$in':
|
||||
if (
|
||||
!arg.some(
|
||||
x =>
|
||||
(comparable(value, x) && toV(value) === toV(x)) ||
|
||||
(Number.isNaN(x) && Number.isNaN(value)),
|
||||
)
|
||||
)
|
||||
return false;
|
||||
break;
|
||||
case '$not':
|
||||
if (matchValue(arg, value)) return false;
|
||||
break;
|
||||
default:
|
||||
throw new Error(`matchValue: unsupported operator ${op}`);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const {
|
||||
tokenizeAdvancedFilter,
|
||||
parseAdvancedFilterDate,
|
||||
buildDateValueSelector,
|
||||
} = await import('../imports/lib/advancedFilter.js');
|
||||
|
||||
// --- Tokenizer -------------------------------------------------------------
|
||||
|
||||
test('#2989: slashes inside a quoted value stay a literal string, not a regex', () => {
|
||||
const cmds = tokenizeAdvancedFilter("'Date de fin' == '06/04/2020'");
|
||||
assert.strictEqual(cmds.length, 3);
|
||||
assert.deepStrictEqual(cmds[0], {
|
||||
cmd: 'Date de fin',
|
||||
string: true,
|
||||
regex: false,
|
||||
});
|
||||
assert.strictEqual(cmds[1].cmd, '==');
|
||||
// Before the fix this token came out as {cmd: '06/04/2020', regex: true},
|
||||
// whose later regex parse threw and silently invalidated the whole filter.
|
||||
assert.deepStrictEqual(cmds[2], {
|
||||
cmd: '06/04/2020',
|
||||
string: true,
|
||||
regex: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('regexes outside quotes still tokenize as regexes', () => {
|
||||
const cmds = tokenizeAdvancedFilter("'Test' == /to.o/i");
|
||||
assert.strictEqual(cmds.length, 3);
|
||||
assert.strictEqual(cmds[2].cmd, '/to.o/i');
|
||||
assert.strictEqual(cmds[2].regex, true);
|
||||
});
|
||||
|
||||
test('regex flag does not leak into the following commands', () => {
|
||||
const cmds = tokenizeAdvancedFilter("'f' == /x/ and 'g' == 'y'");
|
||||
assert.strictEqual(cmds.length, 7);
|
||||
assert.strictEqual(cmds[2].regex, true); // the /x/ regex itself
|
||||
assert.strictEqual(cmds[6].cmd, 'y');
|
||||
assert.strictEqual(cmds[6].regex, false); // 'y' is a plain string
|
||||
});
|
||||
|
||||
test('quoted strings may contain spaces; escaped spaces work outside quotes', () => {
|
||||
assert.deepStrictEqual(tokenizeAdvancedFilter("'a b c'"), [
|
||||
{ cmd: 'a b c', string: true, regex: false },
|
||||
]);
|
||||
assert.deepStrictEqual(tokenizeAdvancedFilter('a\\ b'), [
|
||||
{ cmd: 'a b', string: false, regex: false },
|
||||
]);
|
||||
});
|
||||
|
||||
// --- Date parsing ----------------------------------------------------------
|
||||
|
||||
test('ISO YYYY-MM-DD parses to the local day range', () => {
|
||||
const r = parseAdvancedFilterDate('2020-04-06');
|
||||
assert.ok(r);
|
||||
assert.deepStrictEqual(r.start, new Date(2020, 3, 6));
|
||||
assert.deepStrictEqual(r.end, new Date(2020, 3, 7));
|
||||
});
|
||||
|
||||
test("#2989: '06/04/2020' is 6 April for day-first users, 4 June otherwise", () => {
|
||||
const fr = parseAdvancedFilterDate('06/04/2020', { dayFirst: true });
|
||||
assert.deepStrictEqual(fr.start, new Date(2020, 3, 6));
|
||||
const us = parseAdvancedFilterDate('06/04/2020', { dayFirst: false });
|
||||
assert.deepStrictEqual(us.start, new Date(2020, 5, 4));
|
||||
});
|
||||
|
||||
test('unambiguous day/month order wins over the dayFirst flag', () => {
|
||||
const a = parseAdvancedFilterDate('25/12/2020', { dayFirst: false });
|
||||
assert.deepStrictEqual(a.start, new Date(2020, 11, 25));
|
||||
const b = parseAdvancedFilterDate('12/25/2020', { dayFirst: true });
|
||||
assert.deepStrictEqual(b.start, new Date(2020, 11, 25));
|
||||
});
|
||||
|
||||
test('a time component narrows the range to the minute (or second)', () => {
|
||||
const m = parseAdvancedFilterDate('2020-04-06 14:30');
|
||||
assert.deepStrictEqual(m.start, new Date(2020, 3, 6, 14, 30));
|
||||
assert.deepStrictEqual(m.end, new Date(2020, 3, 6, 14, 31));
|
||||
const s = parseAdvancedFilterDate('2020-04-06 14:30:05');
|
||||
assert.deepStrictEqual(s.start, new Date(2020, 3, 6, 14, 30, 5));
|
||||
assert.deepStrictEqual(s.end, new Date(2020, 3, 6, 14, 30, 6));
|
||||
});
|
||||
|
||||
test('non-dates and impossible dates return null (negative cases)', () => {
|
||||
assert.strictEqual(parseAdvancedFilterDate('toto'), null);
|
||||
assert.strictEqual(parseAdvancedFilterDate(''), null);
|
||||
assert.strictEqual(parseAdvancedFilterDate('42'), null);
|
||||
assert.strictEqual(parseAdvancedFilterDate('31/02/2020'), null); // rollover
|
||||
assert.strictEqual(parseAdvancedFilterDate('2020-13-01'), null);
|
||||
assert.strictEqual(parseAdvancedFilterDate('2020-04-06 25:00'), null);
|
||||
assert.strictEqual(parseAdvancedFilterDate(undefined), null);
|
||||
});
|
||||
|
||||
// --- Selector building + end-to-end matching -------------------------------
|
||||
|
||||
test("#2989 scenario: '==' a date now matches cards stored with a Date value", () => {
|
||||
// The date picker stores a Date (with whatever time was picked).
|
||||
const stored = new Date(2020, 3, 6, 10, 15); // 6 April 2020 10:15 local
|
||||
const range = parseAdvancedFilterDate('06/04/2020', { dayFirst: true });
|
||||
const eq = buildDateValueSelector('==', range);
|
||||
assert.deepStrictEqual(eq, { $gte: range.start, $lt: range.end });
|
||||
assert.strictEqual(matchValue(eq, stored), true);
|
||||
// Negative: a card dated the day after must NOT match.
|
||||
assert.strictEqual(matchValue(eq, new Date(2020, 3, 7, 0, 0)), false);
|
||||
// Negative: the OLD selector shape never matched the stored Date.
|
||||
const old = { $in: ['06/04/2020', parseInt('06/04/2020', 10)] };
|
||||
assert.strictEqual(matchValue(old, stored), false);
|
||||
});
|
||||
|
||||
test("'!=' matches other days but not the named day", () => {
|
||||
const range = parseAdvancedFilterDate('2020-04-06');
|
||||
const ne = buildDateValueSelector('!=', range);
|
||||
assert.deepStrictEqual(ne, {
|
||||
$not: { $gte: range.start, $lt: range.end },
|
||||
});
|
||||
assert.strictEqual(matchValue(ne, new Date(2020, 3, 6, 23, 59)), false);
|
||||
assert.strictEqual(matchValue(ne, new Date(2020, 3, 7)), true);
|
||||
assert.strictEqual(matchValue(ne, new Date(2020, 3, 5, 23, 59)), true);
|
||||
});
|
||||
|
||||
test('range operators use day boundaries', () => {
|
||||
const range = parseAdvancedFilterDate('2020-04-06');
|
||||
const inDay = new Date(2020, 3, 6, 12, 0);
|
||||
const before = new Date(2020, 3, 5, 12, 0);
|
||||
const after = new Date(2020, 3, 7, 12, 0);
|
||||
const gt = buildDateValueSelector('>', range);
|
||||
assert.strictEqual(matchValue(gt, after), true);
|
||||
assert.strictEqual(matchValue(gt, inDay), false);
|
||||
assert.strictEqual(matchValue(gt, before), false);
|
||||
const gte = buildDateValueSelector('>=', range);
|
||||
assert.strictEqual(matchValue(gte, inDay), true);
|
||||
assert.strictEqual(matchValue(gte, before), false);
|
||||
const lt = buildDateValueSelector('<', range);
|
||||
assert.strictEqual(matchValue(lt, before), true);
|
||||
assert.strictEqual(matchValue(lt, inDay), false);
|
||||
const lte = buildDateValueSelector('<=', range);
|
||||
assert.strictEqual(matchValue(lte, inDay), true);
|
||||
assert.strictEqual(matchValue(lte, after), false);
|
||||
// word-form operators map like their symbols
|
||||
assert.deepStrictEqual(buildDateValueSelector('gte', range), gte);
|
||||
assert.deepStrictEqual(buildDateValueSelector('LT', range), lt);
|
||||
});
|
||||
|
||||
test('unknown operators and missing ranges return null (negative cases)', () => {
|
||||
const range = parseAdvancedFilterDate('2020-04-06');
|
||||
assert.strictEqual(buildDateValueSelector('~=', range), null);
|
||||
assert.strictEqual(buildDateValueSelector('==', null), null);
|
||||
});
|
||||
|
||||
test('text custom fields are untouched: a non-date value yields no date selector', () => {
|
||||
// filter.js only calls the date path when the field's type === 'date';
|
||||
// even then, unparsable input falls back to the legacy selector because
|
||||
// parseAdvancedFilterDate() returns null.
|
||||
assert.strictEqual(parseAdvancedFilterDate('toto'), null);
|
||||
assert.strictEqual(
|
||||
buildDateValueSelector('==', parseAdvancedFilterDate('toto')),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
// --- Runner ----------------------------------------------------------------
|
||||
|
||||
for (const [name, fn] of tests) {
|
||||
try {
|
||||
await fn();
|
||||
passed += 1;
|
||||
console.log(' ok -', name);
|
||||
} catch (err) {
|
||||
console.error(' FAIL -', name);
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
console.log(`${passed}/${tests.length} tests passed`);
|
||||
if (passed !== tests.length) process.exitCode = 1;
|
||||
})();
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user