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 | ||
|
|
e4e73e8b80 | ||
|
|
c83284811c | ||
|
|
643a296595 | ||
|
|
2d76e1cb92 | ||
|
|
4fc918c245 | ||
|
|
d7ca7360ff | ||
|
|
fcce2e1cea | ||
|
|
a91203b158 | ||
|
|
794346e396 | ||
|
|
ed19445d30 | ||
|
|
1193f3a4b5 | ||
|
|
98ba5fcc9d | ||
|
|
b735f23045 | ||
|
|
7491c37feb | ||
|
|
503601515a | ||
|
|
10d5006d2e | ||
|
|
2513c782f7 | ||
|
|
c1cae29544 | ||
|
|
98dae04c2d | ||
|
|
4e15057277 |
No files matched your search
@@ -45,6 +45,12 @@ name: Release All Platforms
|
||||
# its .zip to the Release. Windows/macOS strip the Linux FerretDB back
|
||||
# out (MongoDB-only). Decoupled from `release` so a slow/flaky build
|
||||
# never blocks it
|
||||
# - build-sandstorm: built AFTER release, builds the Sandstorm .spk package
|
||||
# (same steps as the standalone sandstorm.yml workflow, which still
|
||||
# exists for testing the .spk build on its own) and attaches
|
||||
# wekan-<version>-sandstorm.spk to the Release. Non-blocking: the
|
||||
# Sandstorm build is the experimental/fragile part of CI, so it
|
||||
# never fails the release
|
||||
# - docker: builds and pushes the multi-arch image (amd64, arm64, ppc64le, s390x,
|
||||
# riscv64) to Docker Hub, Quay.io, GHCR
|
||||
# - snap: builds the snap on Launchpad from the default core24 snapcraft.yaml
|
||||
@@ -62,6 +68,8 @@ name: Release All Platforms
|
||||
# SNAP_AUTH - Snap Store credentials (output of `snapcraft export-login`)
|
||||
# LP_CREDENTIALS - base64 of the Launchpad credentials file used by
|
||||
# `snapcraft remote-build` (see releases/snap-build.sh notes)
|
||||
# SANDSTORM_KEYRING - base64 of ~/.sandstorm-keyring; meteor-spk signs the .spk
|
||||
# with the WeKan Sandstorm app's private key from this keyring
|
||||
# WEKAN_REPO_TOKEN - Personal Access Token with write access to wekan/wekan.fi
|
||||
# and wekan/charts, used by the website + charts jobs to push
|
||||
# to those repos (the built-in GITHUB_TOKEN only covers
|
||||
@@ -301,7 +309,7 @@ jobs:
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential g++ make python3 curl wget zip unzip
|
||||
sudo apt-get install -y build-essential g++ make python3 curl wget zip unzip qemu-user-static
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
@@ -353,6 +361,16 @@ jobs:
|
||||
# Self-contained launcher (defaults to FerretDB SQLite + WRITABLE_PATH).
|
||||
cp releases/ferretdb/start-wekan.sh .build/bundle/
|
||||
chmod +x .build/bundle/start-wekan.sh
|
||||
# #6458: cpu-exec + same-arch qemu-user. cpu-exec runs any bundled
|
||||
# binary that declares required CPU features (e.g. an external
|
||||
# MongoDB 5+: AVX on x86_64) through qemu-user emulation on CPUs
|
||||
# that lack them — including hypervisors that mask AVX. Every Linux
|
||||
# bundle ships its own arch's qemu-user; other arches overwrite
|
||||
# these below.
|
||||
cp snap-src/bin/cpu-exec .build/bundle/cpu-exec
|
||||
chmod +x .build/bundle/cpu-exec
|
||||
cp /usr/bin/qemu-x86_64-static .build/bundle/qemu-x86_64
|
||||
chmod +x .build/bundle/qemu-x86_64
|
||||
|
||||
- name: Create amd64 zip
|
||||
run: |
|
||||
@@ -376,7 +394,7 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential g++ make python3 curl unzip zip
|
||||
sudo apt-get install -y build-essential g++ make python3 curl unzip zip qemu-user-static
|
||||
|
||||
- name: Download amd64 bundle
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -422,6 +440,13 @@ jobs:
|
||||
curl -fSL --retry 5 --retry-delay 10 -o "bundle/$t" "$MT/$t-arm64"
|
||||
chmod +x "bundle/$t"
|
||||
done
|
||||
# #6458: replace the inherited amd64 qemu-user with this arch's own
|
||||
# (cpu-exec is a shell script and stays as inherited). qemu-aarch64
|
||||
# lets ARMv8.0 hosts (Raspberry Pi 4 and older) run binaries that
|
||||
# need ARMv8.2-A, like MongoDB 5+.
|
||||
rm -f bundle/qemu-x86_64
|
||||
cp /usr/bin/qemu-aarch64-static bundle/qemu-aarch64
|
||||
chmod +x bundle/qemu-aarch64
|
||||
|
||||
- name: Create arm64 zip
|
||||
run: |
|
||||
@@ -510,6 +535,8 @@ jobs:
|
||||
rm -f bundle/node bundle/ferretdb bundle/.ferretdb-default bundle/start-wekan.sh
|
||||
rm -f bundle/bsondump bundle/mongodump bundle/mongoexport bundle/mongofiles \
|
||||
bundle/mongoimport bundle/mongorestore bundle/mongostat bundle/mongotop
|
||||
# Linux-only cpu-exec + qemu-user (#6458) make no sense on Windows.
|
||||
rm -f bundle/cpu-exec bundle/qemu-x86_64
|
||||
# Fix: bcrypt 5.0.1 (Meteor accounts-password) ships node-addon-api@3
|
||||
# which fails to compile on Node.js 24. Replace with bcrypt 6.0.0.
|
||||
BCRYPT_DIR="$(pwd)/bundle/programs/server/npm/node_modules/meteor/accounts-password/node_modules/bcrypt"
|
||||
@@ -617,6 +644,9 @@ jobs:
|
||||
# inherited from the amd64 base bundle with the macOS builds (added in a
|
||||
# later step). The POSIX launcher start-wekan.sh works on macOS, so keep it.
|
||||
rm -f bundle/node bundle/ferretdb bundle/.ferretdb-default
|
||||
# Linux-only cpu-exec + qemu-user (#6458): qemu-user does not exist for
|
||||
# macOS (Apple Silicon needs no AVX emulation anyway).
|
||||
rm -f bundle/cpu-exec bundle/qemu-x86_64
|
||||
rm -f bundle/bsondump bundle/mongodump bundle/mongoexport bundle/mongofiles \
|
||||
bundle/mongoimport bundle/mongorestore bundle/mongostat bundle/mongotop
|
||||
# Fix: bcrypt 5.0.1 (Meteor accounts-password) ships node-addon-api@3
|
||||
@@ -777,6 +807,21 @@ jobs:
|
||||
# launcher. /bundle is the host bundle/ dir (see -v mount above).
|
||||
cp /opt/node/bin/node /bundle/node
|
||||
chmod +x /bundle/node
|
||||
# #6458: replace the inherited amd64 qemu-user with THIS arch own
|
||||
# same-arch qemu-user (from the target-arch distro, so it runs on
|
||||
# this arch), used by bundle/cpu-exec to emulate CPU features a
|
||||
# binary needs but the host CPU lacks. Tolerant: if the package
|
||||
# is unavailable on this arch, the bundle just ships without it
|
||||
# (cpu-exec then falls back to a system qemu-user, or reports).
|
||||
rm -f /bundle/qemu-x86_64
|
||||
if apt-get install -y -q qemu-user-static >/dev/null 2>&1 && \
|
||||
[ -x "/usr/bin/qemu-$(uname -m)-static" ]; then
|
||||
cp "/usr/bin/qemu-$(uname -m)-static" "/bundle/qemu-$(uname -m)"
|
||||
chmod +x "/bundle/qemu-$(uname -m)"
|
||||
echo "Bundled qemu-$(uname -m) for cpu-exec."
|
||||
else
|
||||
echo "qemu-user-static not available for $(uname -m); bundle ships without a bundled qemu-user."
|
||||
fi
|
||||
'
|
||||
|
||||
- name: Embed FerretDB (${{ matrix.arch }}) into the bundle
|
||||
@@ -814,6 +859,128 @@ jobs:
|
||||
GH_REPO: ${{ github.repository }}
|
||||
run: gh release upload "v${VERSION}" "wekan-${VERSION}-${{ matrix.arch }}.zip" --clobber
|
||||
|
||||
# ─── 7c. Build the Sandstorm .spk and attach it to the Release ───────────────
|
||||
# Same steps as the standalone sandstorm.yml workflow (kept for building/testing
|
||||
# the .spk on its own without a full release); here it builds from the release
|
||||
# tag and attaches wekan-<version>-sandstorm.spk to the GitHub Release.
|
||||
#
|
||||
# EXPERIMENTAL in CI (same caveats as sandstorm.yml):
|
||||
# * Sandstorm needs unprivileged user namespaces; GitHub's Ubuntu runners are VMs
|
||||
# that allow them, but this is the fragile part.
|
||||
# * meteor-spk SIGNS the .spk with the app private key from the Sandstorm keyring;
|
||||
# provide it as the SANDSTORM_KEYRING secret (base64 of ~/.sandstorm-keyring).
|
||||
#
|
||||
# continue-on-error: the experimental Sandstorm build must NOT fail the release;
|
||||
# like the other post-`release` bundle jobs it only attaches its artifact.
|
||||
build-sandstorm:
|
||||
needs: [prepare, release]
|
||||
continue-on-error: true
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
VERSION: ${{ needs.prepare.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: refs/tags/v${{ needs.prepare.outputs.version }}
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Enable unprivileged user namespaces (Ubuntu 24.04 restricts them)
|
||||
# Ubuntu 24.04's AppArmor defaults kernel.apparmor_restrict_unprivileged_userns=1,
|
||||
# which blocks the unprivileged user namespaces that the Sandstorm install and
|
||||
# the spk supervisor rely on (the "fragile part" noted above). Relax it so
|
||||
# `install.sandstorm.io` and meteor-spk can create sandboxes on the runner.
|
||||
# `|| true`: on kernels/runners without these knobs, setting them is a no-op.
|
||||
run: |
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true
|
||||
sudo sysctl -w kernel.unprivileged_userns_clone=1 2>/dev/null || true
|
||||
|
||||
- name: Install system dependencies and Meteor
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y p7zip-full wget curl build-essential g++ make python3 unzip xz-utils git qemu-user-static
|
||||
if [ ! -f "$HOME/.meteor/meteor" ]; then curl https://install.meteor.com/ | sh; fi
|
||||
echo "$HOME/.meteor" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Install Sandstorm (dev, unattended)
|
||||
# Installed BEFORE assembling the deps: build-deps.sh's [bridge] step copies
|
||||
# the modern /opt/sandstorm/latest/bin/sandstorm-http-bridge over the ancient
|
||||
# bundled one, so the Sandstorm install must be in place first.
|
||||
run: curl https://install.sandstorm.io | sudo bash -s -- -d
|
||||
|
||||
- name: Assemble modern meteor-spk.deps (Node 24 + FerretDB + Mongo 3.x CLIs)
|
||||
# Base = upstream meteor-spk 0.6.0 from dl.sandstorm.io (has mongod 3.0 +
|
||||
# niscud). build-deps.sh swaps in Node 24, adds FerretDB + the Mongo 3.x
|
||||
# CLIs + the migration launcher/importer, keeps niscud, and swaps in the
|
||||
# modern sandstorm-http-bridge from the Sandstorm install above. No dependency
|
||||
# on the retired releases.wekan.team or the old projects.7z.
|
||||
run: |
|
||||
bash sandstorm-src/build-deps.sh
|
||||
echo "$HOME/projects/meteor-spk/meteor-spk-0.6.0" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Restore the Sandstorm signing keyring
|
||||
env:
|
||||
SANDSTORM_KEYRING: ${{ secrets.SANDSTORM_KEYRING }}
|
||||
run: |
|
||||
if [ -n "${SANDSTORM_KEYRING:-}" ]; then
|
||||
# meteor-spk / spk read the app signing key from ~/.sandstorm-keyring —
|
||||
# a FILE directly in $HOME (see the pack crash path
|
||||
# "/home/runner/.sandstorm-keyring"). Write it exactly there, NOT to
|
||||
# ~/.sandstorm/sandstorm-keyring, or `meteor-spk pack` aborts with
|
||||
# "open(~/.sandstorm-keyring): No such file or directory".
|
||||
printf '%s' "$SANDSTORM_KEYRING" | base64 -d > "$HOME/.sandstorm-keyring"
|
||||
chmod 600 "$HOME/.sandstorm-keyring"
|
||||
echo "Restored ~/.sandstorm-keyring ($(wc -c < "$HOME/.sandstorm-keyring") bytes)."
|
||||
else
|
||||
echo "::error::SANDSTORM_KEYRING secret is not set. meteor-spk pack signs the .spk with the WeKan Sandstorm app's private key, which lives in this keyring, so packing cannot proceed without it. Add the base64 of your ~/.sandstorm-keyring file as the SANDSTORM_KEYRING repository secret (e.g. 'base64 -w0 ~/.sandstorm-keyring')."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Install Meteor npm dependencies
|
||||
# PUPPETEER_SKIP_DOWNLOAD: puppeteer is a devDependency used only by tests,
|
||||
# not by the server, so it never belongs in the packed .spk. Skipping its
|
||||
# Chromium download (~150 MB) avoids any risk of it bloating the build and
|
||||
# speeds up CI.
|
||||
env:
|
||||
PUPPETEER_SKIP_DOWNLOAD: '1'
|
||||
run: |
|
||||
(meteor update --npm 2>/dev/null || true) && meteor npm install
|
||||
|
||||
- name: Build the Sandstorm .spk
|
||||
id: build
|
||||
env:
|
||||
PUPPETEER_SKIP_DOWNLOAD: '1'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Version-named (not timestamped like sandstorm.yml): the release re-runs
|
||||
# idempotently with --clobber replacing the same asset.
|
||||
SPK="wekan-${VERSION}-sandstorm.spk"
|
||||
meteor-spk pack "$SPK"
|
||||
# Report the packed size and warn if it exceeds Cloudflare's 100 MB upload
|
||||
# cap (a proxied browser upload to a Cloudflare-fronted Sandstorm 413s above
|
||||
# this; install via a DNS-only host / SSH tunnel, or trim further).
|
||||
SPK_BYTES=$(stat -c%s "$SPK")
|
||||
echo "Packed $SPK: $((SPK_BYTES/1024/1024)) MiB ($SPK_BYTES bytes)"
|
||||
if [ "$SPK_BYTES" -gt $((100*1024*1024)) ]; then
|
||||
echo "::warning::$SPK is $((SPK_BYTES/1024/1024)) MiB — over Cloudflare's 100 MB upload limit. Upload via a DNS-only host / SSH tunnel to Sandstorm, or trim the bundle further."
|
||||
fi
|
||||
ls -la "$SPK"
|
||||
echo "spk=$SPK" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ steps.build.outputs.spk }}
|
||||
path: ${{ steps.build.outputs.spk }}
|
||||
retention-days: 7
|
||||
|
||||
- name: Attach the .spk to the GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: gh release upload "v${VERSION}" "${{ steps.build.outputs.spk }}" --clobber
|
||||
|
||||
# ─── 8. Build and push the multi-arch Docker image to all registries ────────
|
||||
# Mirrors releases/docker-build.sh step 3 (multi-arch buildx --push).
|
||||
# Needs `release` because the Dockerfile downloads wekan-<version>-<arch>.zip
|
||||
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
- name: Install system dependencies and Meteor
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y p7zip-full wget curl build-essential g++ make python3 unzip xz-utils git
|
||||
sudo apt-get install -y p7zip-full wget curl build-essential g++ make python3 unzip xz-utils git qemu-user-static
|
||||
if [ ! -f "$HOME/.meteor/meteor" ]; then curl https://install.meteor.com/ | sh; fi
|
||||
echo "$HOME/.meteor" >> "$GITHUB_PATH"
|
||||
|
||||
|
||||
+739
@@ -86,6 +86,745 @@ 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:
|
||||
|
||||
- **Releases now include the Sandstorm .spk package** (`.github/workflows/release-all.yml`).
|
||||
The release-all workflow got a new `build-sandstorm` job that runs after the GitHub Release
|
||||
is created: it builds the Sandstorm package from the release tag with the same steps as the
|
||||
standalone sandstorm.yml workflow and attaches `wekan-<version>-sandstorm.spk` to the
|
||||
Release. The job is non-blocking (`continue-on-error`), so the experimental Sandstorm build
|
||||
never fails or delays the rest of the release. The standalone sandstorm.yml workflow still
|
||||
exists for building and testing the .spk on its own without doing a full release. Thanks
|
||||
to xet7.
|
||||
|
||||
- [Bump websocket-driver from 0.7.4 to 0.7.5](https://github.com/wekan/wekan/pull/6462).
|
||||
Thanks to dependabot.
|
||||
|
||||
- **New general `cpu-exec` + bundled qemu-user: every WeKan platform now runs binaries that need
|
||||
missing CPU features through emulation automatically**
|
||||
([#6458](https://github.com/wekan/wekan/issues/6458), `snap-src/bin/cpu-exec`,
|
||||
`snap-src/bin/mongodb-control`, `snap-src/bin/migration-control`, `.github/workflows/release-all.yml`,
|
||||
`.github/workflows/sandstorm.yml`, `sandstorm-src/build-deps.sh`, `releases/ferretdb/start-wekan.sh`,
|
||||
`releases/ferretdb/wekan-entrypoint.sh`, `docs/Databases/mongodb-avx-qemu.md`,
|
||||
`docs/Databases/mongodb-raspi4-qemu.md`). The #6458 report turned out to run inside a hypervisor
|
||||
that MASKS AVX — and the snap's old per-tool AVX wrappers (amd64-only, PATH-based) were bypassed
|
||||
by every absolute-path `mongod` invocation. The new `cpu-exec` helper is one general mechanism
|
||||
for all scripts, sandboxes, platforms and CPUs: `cpu-exec --features x86_64=avx,aarch64=atomics
|
||||
<binary> [args]` checks `/proc/cpuinfo` and, when a required feature is missing, transparently
|
||||
re-runs the binary through a same-architecture qemu-user (bundled first, then system); with no
|
||||
declared features it is a plain zero-overhead exec, so every binary can be routed through it
|
||||
(`WEKAN_REQUIRED_CPU_FEATURES` declares requirements externally). The Snap's mongodb-control and
|
||||
migration-control now run every mongod 7 through it — so MongoDB works (slower) on CPUs without
|
||||
AVX and the migration can READ modern MongoDB data there, with the FerretDB switch/migration
|
||||
fallbacks unchanged; `aarch64=atomics` covers MongoDB's ARMv8.2-A requirement (Raspberry Pi 4
|
||||
and older lack it). release-all.yml now ships `cpu-exec` plus this-arch's static qemu-user in
|
||||
every Linux bundle .zip (amd64/arm64/ppc64le/s390x/riscv64 — stripped from the Windows/macOS
|
||||
bundles, where qemu-user does not exist), which flows into the Docker image and the Snap
|
||||
automatically, and the Sandstorm .spk gets both via build-deps.sh; the bundle launcher and
|
||||
Docker entrypoint route node/ferretdb through it. Thanks to a1bert01 and xet7.
|
||||
|
||||
- **Added regression tests, with negative cases, for all of the fixes below** (`tests/htmljsArrayContent.test.cjs`,
|
||||
`tests/cardDescriptionDraft.test.cjs`, `tests/commentDraft.test.cjs`, `tests/attachmentDeleteGuard.test.cjs`,
|
||||
`tests/ruleMoveAction.test.cjs`, `tests/snapMigrationRecovery.test.cjs`, `tests/ferretdbPolling.test.cjs`,
|
||||
`tests/uiDensity.test.cjs`, `tests/cpuExec.test.cjs` — a BEHAVIORAL test that executes the real
|
||||
cpu-exec against fake /proc/cpuinfo files and a fake qemu-user, covering direct exec, qemu fallback,
|
||||
missing-qemu error, per-arch scoping and env overrides —, `tests/cpuExecWiring.test.cjs` — pins the
|
||||
cpu-exec DELIVERY pipeline: every Linux bundle in release-all.yml embeds cpu-exec plus its own
|
||||
arch's qemu-user (arm64/extra arches replace the inherited amd64 one, tolerantly), the Windows and
|
||||
macOS bundles strip both, qemu-user-static is installed in every bundle-building job, the Sandstorm
|
||||
.spk ships both via build-deps.sh, the Docker entrypoint and bundle launcher route ferretdb/node
|
||||
through cpu-exec WITH direct-exec fallbacks for bundles that lack it, and the snap ships it via the
|
||||
snap-src helpers part —, `tests/subtasksDefaultBoard.test.cjs` (see the #6456 entry below), and `tests/ferretdbHasData.test.cjs` — a BEHAVIORAL test executing the real snap-src/bin/ferretdb-has-data guard (the check that gates every switch to FerretDB) against crafted directories: non-empty .sqlite passes with no -wal sidecar required, while a 0-byte .sqlite from a failed migration, sidecar-only leftovers, a directory named *.sqlite, and empty/missing directories are all rejected — all
|
||||
wired into `test:unit:node` in `package.json`; plus Go table tests in the wekan/FerretDB fork's
|
||||
`internal/backends/sqlite/query_test.go` and the fork's integration-test fixes (OTel exporter
|
||||
skipped with a single log line when no collector is listening, and valid span contexts without a
|
||||
collector so `TestOtelComment` passes — details in the fork's own CHANGELOG Upcoming). The htmljs test exercises the vendored
|
||||
compiler's Tag constructor directly (array content vs. attributes, #6459) and the draft tests run the real
|
||||
extracted `normalize`/`normalizeTrigger` functions; the UI tests guard the #6465 density fixes in the repo's
|
||||
CSS-guard style (base font 14px, card details docking right of the board instead of over its own card, compact
|
||||
admin table headers, un-clipped zoom pill, one-click board settings cog). The FerretDB Go tests pin the SQLite
|
||||
filter-pushdown semantics: which strings are pushdown-safe, exact WHERE/args for `_id` and top-level equality
|
||||
filters, and that dotted paths, operators, non-strings and unsafe strings stay with the in-Go filter. Thanks
|
||||
to xet7.
|
||||
|
||||
and fixes the following bugs:
|
||||
|
||||
- **Subtasks: creating a subtask crashed with "Exception while invoking method 'addSubtaskCard'"**
|
||||
([#6456](https://github.com/wekan/wekan/issues/6456), `models/boards.js`,
|
||||
`tests/subtasksDefaultBoard.test.cjs`). The lazily-creating getters for the default subtasks
|
||||
helper board and its landing list still used the SYNC `Boards.insert` / `Swimlanes.insert` /
|
||||
`Lists.insert` / `Boards.update` APIs, which Meteor 3 removed from the server — so the
|
||||
`addSubtaskCard` method's async path crashed with *"insert is not available on the server.
|
||||
Please use insertAsync() instead"* the first time a board needed its `^Board^` helper board
|
||||
created (the list creator additionally read `getDefaultSwimline()._id`, which on the Meteor 3
|
||||
server is a Promise, so it could never have worked). The sync getters are now PURE (no
|
||||
creation — also matching the #3868/#2256 rule that only the server may create these), and the
|
||||
server-side lazy creation lives in `getDefaultSubtasksBoardAsync`/`getDefaultSubtasksListAsync`
|
||||
using the async APIs. The never-called date-settings twins, which had the same sync calls and
|
||||
no server-only guard at all, are pure getters now too. With a regression test guarding that no
|
||||
sync collection writes come back to `models/boards.js`. Thanks to sjohnen and xet7.
|
||||
|
||||
- **GUI: the "More" menu of cards was completely empty, so cards could not be deleted from it**
|
||||
([#6459](https://github.com/wekan/wekan/issues/6459),
|
||||
`npm-packages/meteor-jade-loader/lib/vendor/htmljs.js`, `client/components/lists/listHeader.jade`).
|
||||
A WeKan-local vm-sandbox patch in the vendored jade compiler's htmljs made
|
||||
`isConstructedObject(Array)` return `false` (upstream returns `true`), so a tag whose inline text
|
||||
compiles to an ARRAY — the `label {{_ 'source-board'}}:` and `label {{_ 'parent-card'}}:` lines in
|
||||
cardMorePopup — got its content array mis-assigned as the tag's *attributes*. At runtime Blaze then
|
||||
found a template view object inside the attributes and threw *"The basic TransformingVisitor does
|
||||
not support foreign objects in attributes"* on every render, killing the whole popup — including
|
||||
the card Delete link. The tag constructor now treats an array first-argument as content, like
|
||||
upstream htmljs. Also fixed the list "More" popup's copy-link input, which was always empty because
|
||||
it referenced a `rootUrl` helper that does not exist (now `absoluteUrl`). Board and swimlane menus
|
||||
intentionally offer archive (delete lives in Sidebar → Archive), so only the card menu was actually
|
||||
broken. Thanks to thku and xet7.
|
||||
|
||||
- **Cards: the "You have an unsaved description" warning could never be cleared by saving**
|
||||
([#6455](https://github.com/wekan/wekan/issues/6455), reincarnation of
|
||||
[#1287](https://github.com/wekan/wekan/issues/1287), `client/components/cards/cardDetails.js`,
|
||||
`client/components/cards/cardDescription.js`). Two bugs: closing the description editor only
|
||||
*avoided adding* a draft when the text matched the saved description — it never *removed* a
|
||||
pre-existing draft record, so once the warning appeared, "View it" → Save could not clear it, only
|
||||
Discard could. And the comparison matched a per-line-whitespace-stripped draft against the raw
|
||||
stored description (or `null` when empty), so descriptions with Markdown `" "` hard-breaks
|
||||
re-created a phantom draft on every save. Saving now removes the draft record explicitly, and both
|
||||
sides of the comparison are normalized the same way. Thanks to C0rn3j and xet7.
|
||||
|
||||
- **Comments: a comment being written was lost when the card was closed or a click landed outside
|
||||
the card** ([#5547](https://github.com/wekan/wekan/issues/5547),
|
||||
`client/components/activities/comments.js`). The comment-draft machinery existed (the form even
|
||||
prefills from it) but had been disarmed since 2019: the escape handler that saved the draft was
|
||||
gated on a "form is open" flag that nothing ever set — the setter was removed back then because the
|
||||
handler also *cleared the visible text* on every outside click. Now the draft is saved continuously
|
||||
(debounced) while typing and flushed when the form is torn down, submit removes the draft, and the
|
||||
escape handler no longer clears the visible text — so an unfinished comment survives closing the
|
||||
card, and reopening the card restores it into the form. Thanks to Finnlife, webenefits and xet7.
|
||||
|
||||
- **Attachments: deleting an attachment could log a client-side "Removed nonexistent document"
|
||||
exception even though the delete succeeded**
|
||||
([#5282](https://github.com/wekan/wekan/issues/5282),
|
||||
`client/components/cards/attachments.js`). Same class as the fixed #3252 for comments and
|
||||
checklists: under publication churn the attachment document can already be evicted from Minimongo
|
||||
when the confirm handler runs, and removing a missing _id throws. The delete now only runs when
|
||||
the document is still in the local cache — the comment/checklist guards' missing sibling. Thanks
|
||||
to lupuszr and xet7.
|
||||
|
||||
- **Rules: the "move card to top/bottom" actions did nothing**
|
||||
([#6472](https://github.com/wekan/wekan/issues/6472), `server/rulesHelper.js`,
|
||||
`client/components/rules/actions/boardActions.js`, `client/components/rules/rulesImportExport.js`,
|
||||
`server/rulesButton.js`, `models/lists.js`). A pile-up of five bugs, all silent because the
|
||||
activity hook swallows rule-action errors: (1) an unresolved destination list (typo'd, renamed,
|
||||
case-mismatched, or on another board) crashed on `list.cardsUnfiltered` — now it falls back to the
|
||||
card's current list; (2) the classic rule wizard's generic "move to top/bottom" stored the field as
|
||||
`listTitle`, which the rule engine never reads (`listName`) — so every such rule created from the
|
||||
wizard has never worked; (3) an empty destination list made `Math.min()/Math.max()` of nothing
|
||||
write a corrupt `sort: ±Infinity`; (4) the rules JSON/CSV import created rules with raw client
|
||||
inserts that the board-admin-only allow rules reject into minimongo limbo — it now uses the same
|
||||
`rules.createRule` server method as the wizard, and defaults missing trigger matching fields (e.g.
|
||||
`userId`) to the `*` wildcard so hand-written JSON matches; (5) `rules.createRule` let an empty
|
||||
`boardId: ''` from a not-yet-loaded board selector override the real board. Also fixed the
|
||||
server-side orphaned-cards fallback in `List.cards()/cardsUnfiltered()`, which silently never
|
||||
applied because an async lookup was read synchronously. Thanks to jmb26240 and xet7.
|
||||
|
||||
- **GUI: desktop density regressions from the v7.98–v8.18 mobile UI work**
|
||||
([#6465](https://github.com/wekan/wekan/issues/6465), `client/components/main/layouts.css`,
|
||||
`client/components/cards/cardDetails.css`, `client/components/main/header.css`,
|
||||
`client/components/settings/peopleBody.jade`, `client/components/settings/settingBody.css`,
|
||||
`client/components/boards/boardHeader.jade`). Restores the WeKan 6.09 desktop look users asked
|
||||
for: the base font is back to 14px (the `clamp(...2.5vw...)` introduced in v7.98 and raised in
|
||||
v8.02 resolved to 18px on any window wider than 720px — +28.5% on every font, button and input,
|
||||
the "everything is way too big" complaint) and headings back to 22/18/16px; the card details
|
||||
window no longer opens as a huge floating sheet ON TOP of its own card — it docks to the right
|
||||
edge like the classic side panel (still movable by its drag handle), with 6.09's 20px content
|
||||
padding instead of ~48px white borders, a 3px corner radius, and without the v8.18 rule that
|
||||
forced ALL card text to the title's size; the All Boards page header band is back to 6.09's
|
||||
compact padding; the Admin Panel Organizations/Teams tables no longer explode column widths
|
||||
("Select all / Unselect all" header links are now compact icons and header cells may wrap); the
|
||||
zoom pill no longer renders cut off (fixed-pixel pill inside the 28px quick-access row); and
|
||||
board settings opens with ONE click from a new cog button in the board header (the sidebar path
|
||||
still works). Follow-ups caught by the Playwright suite: archiving or deleting a card now also
|
||||
CLOSES its details window (the card id stayed in the openCards session list, so the right-docked
|
||||
window kept rendering exactly over the archives sidebar and intercepted its Restore/Delete
|
||||
clicks), and an OPEN sidebar now stacks above the card window (z-index 2002 vs 2001) so the
|
||||
sidebar is always usable while a card is open. With Playwright coverage: a new spec proves board
|
||||
settings opens in one click from the header cog (and that the popup closes again), and the
|
||||
archives spec's board-menu click is scoped to the sidebar instance since the cog made the bare
|
||||
class selector ambiguous. Note: a missing watch "eye" icon is the Admin Panel → Features →
|
||||
Notifications "disable watch" setting, not a regression. Thanks to Mintyt, csonkaoszimt,
|
||||
micha141076 and xet7.
|
||||
|
||||
- **Snap: WeKan served "502 Bad Gateway" forever when mongod could not start — including on CPUs
|
||||
without AVX ("Illegal instruction")** ([#6458](https://github.com/wekan/wekan/issues/6458),
|
||||
[#6466](https://github.com/wekan/wekan/issues/6466), `snap-src/bin/mongodb-control`,
|
||||
`snap-src/bin/migration-control`). MongoDB 5.0+ x86_64 binaries require AVX; on CPUs without it
|
||||
mongod dies instantly with SIGILL (exit 132). mongodb-control never checked the mongod fork's
|
||||
exit status: it pinged the dead port for ~10 minutes, snapd restarted the service, and the cycle
|
||||
repeated forever — same limbo as when the data files are still MongoDB 3.x ("This version of
|
||||
MongoDB is too recent"). Now there is an AVX pre-flight and the fork/final-start exit codes are
|
||||
checked: if a COMPLETED FerretDB migration exists the snap switches to it; otherwise the
|
||||
MongoDB → FerretDB migration is (re)run — FerretDB is pure Go + SQLite and the 3.x reader uses
|
||||
the bundled MongoDB 3.2 tools, so neither needs AVX — with a 3-attempt counter so a persistently
|
||||
failing migration cannot ping-pong, and clear log guidance (`snap run wekan.migrate`).
|
||||
migration-control also skips the pointless mongod 7 probe when AVX is missing. Thanks to kiarn
|
||||
and xet7.
|
||||
|
||||
- **Snap: a migration that finished with a few per-item errors ("Avatars Errors") deleted the
|
||||
fully-copied FerretDB database and left the snap serving 502 Bad Gateway**
|
||||
([#6466](https://github.com/wekan/wekan/issues/6466), `snap-src/bin/migrate-mongo3-to-ferretdb.mjs`,
|
||||
`releases/migrate-mongodb-to-ferretdb.mjs`, `snap-src/bin/migration-control`). Both importers
|
||||
treated ≥10 logged errors of ANY kind as failure — but per-item errors (one document that fails
|
||||
JSON parsing, one avatar that fails to extract) don't invalidate everything that DID copy. The
|
||||
failure path then discarded the whole migrated SQLite, set `migrate=off`, and "fell back" to
|
||||
MongoDB — impossible for a 6.09 upgrade, whose 3.x data files the bundled mongod 7 cannot open,
|
||||
producing the reported endless `db-eval.mjs ping` loop and 502. Per-item errors are now logged
|
||||
but non-fatal (only real failures — disk full, unreachable target/source — still fail), and a
|
||||
failed 3.x-source migration keeps the partial FerretDB SQLite plus its checkpoint and RESUMES on
|
||||
the next start instead of deleting hours of copied data. Thanks to Nissulya, S0QR2, lezioul,
|
||||
usrflo and xet7.
|
||||
|
||||
- **Snap/Bundle: FerretDB v1 pinned 250–400% CPU and boards took minutes to load after migration**
|
||||
([#6467](https://github.com/wekan/wekan/issues/6467),
|
||||
[#6468](https://github.com/wekan/wekan/issues/6468), `snap-src/bin/wekan-control`,
|
||||
`releases/ferretdb/start-wekan.sh`, and the wekan/FerretDB fork). Two sides. WeKan side: with
|
||||
FerretDB there is no oplog, so Meteor observes every query by POLLING — and its defaults re-run
|
||||
every observed query 50 ms after ANY write and at least every 10 s, which on an active board
|
||||
multiplies into hundreds of full queries per second; with FerretDB the snap and the bundle
|
||||
launcher now default to `METEOR_POLLING_THROTTLE_MS=2000` / `METEOR_POLLING_INTERVAL_MS=30000`
|
||||
(overridable; own changes still appear instantly, other users' changes may take ~2 s longer).
|
||||
FerretDB side (fork v1.28): real filter pushdown so `{boardId: X}` uses the SQLite expression
|
||||
indexes instead of decoding the whole 53k-card collection per query, a connection pool cap of
|
||||
2×CPUs (was 100 — dozens of concurrent full scans thrashing the pure-Go SQLite mutexes were the
|
||||
reported 821k futex calls/30 s), and inserts no longer take the registry's global write lock.
|
||||
Thanks to anlx-sw, markusst1982 and xet7.
|
||||
|
||||
- **LDAP: group search filters were double-escaped and broke group filtering**
|
||||
([#6460](https://github.com/wekan/wekan/issues/6460),
|
||||
[PR #6469](https://github.com/wekan/wekan/pull/6469), `packages/wekan-ldap/server/ldap.js`).
|
||||
The group filter was post-processed with a global backslash-doubling replace, a leftover
|
||||
workaround from the ldapjs era that predates the proper `escapedToHex` hex escaping. It turned
|
||||
already-correct RFC 4515 escapes like `\5c` and `\28` (an AD DN with an escaped comma, a group
|
||||
name with parentheses) into `\\5c`/`\\28`, which ldapts' strict filter parser rejects with
|
||||
*"Invalid escaped hex character"* — so group filtering, admin-status sync and role sync failed
|
||||
for exactly those directories. The redundant replace is removed; injection protection is
|
||||
unchanged (`escapedToHex` still hex-escapes the username). Thanks to ChristianMa97.
|
||||
|
||||
- **LDAP: enabling org/team sync made every LDAP login fail with 'forbidden'**
|
||||
([#6461](https://github.com/wekan/wekan/issues/6461),
|
||||
[PR #6470](https://github.com/wekan/wekan/pull/6470), `packages/wekan-ldap/server/loginHandler.js`,
|
||||
`packages/wekan-ldap/server/sync.js`). On the server, a nested `Meteor.callAsync` inherits the
|
||||
current method invocation's `connection`, so when the login handler called the
|
||||
`setUserOrgsTeamsFromLdap` method, its admin guard saw the client's `login` connection with no
|
||||
logged-in user yet and rejected the sync — and the unhandled rejection failed the whole login.
|
||||
(The nightly cron sync runs outside a method invocation, so it was unaffected — which is why
|
||||
this hid.) The login-time sync call now clears the inherited invocation context so it is a true
|
||||
server-to-server call, and org/team sync is additionally wrapped so an optional-enrichment
|
||||
failure is logged instead of blocking login. The same PR also throws the account-creation error
|
||||
from `addLdapUser` at the right point (it was previously used as a user object first), fixes
|
||||
external-avatar localization to use `Avatars.writeAsync` (the callback-style `write` no longer
|
||||
exists in ostrio:files 3.x, so localizing avatars silently did nothing), and adds `*`/`?`
|
||||
wildcard support with unit tests to the `LDAP_SYNC_ORGANIZATIONS_GROUPS` /
|
||||
`LDAP_SYNC_TEAMS_GROUPS` allowlists. Thanks to ChristianMa97 and xet7.
|
||||
|
||||
Thanks to above GitHub users for their contributions and translators for their translations.
|
||||
|
||||
# v9.95 2026-07-15 WeKan ® release
|
||||
|
||||
This release fixes the following bugs:
|
||||
|
||||
+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.95
|
||||
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.95.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]
|
||||
|
||||
@@ -10,7 +10,61 @@ const commentFormIsOpen = new ReactiveVar(false);
|
||||
// Empty string means a new top-level comment.
|
||||
const replyToCommentId = new ReactiveVar('');
|
||||
|
||||
// #5547: persist the comment draft (debounced) into UnsavedEdits while the user
|
||||
// types, so a comment in progress survives closing the card, clicking outside
|
||||
// it, or navigating away — the form prefills from {{getUnsavedValue
|
||||
// 'cardComment' ...}} on the next open. Historical note: the click-open flag
|
||||
// that armed the old escape-time draft save was removed in 2019 (3b3950369)
|
||||
// because the escape handler CLEARED the visible text; since then nothing saved
|
||||
// the draft at all, so any close of the card discarded the comment.
|
||||
let commentDraftTimer = null;
|
||||
let commentDraftPending = null; // { cardId, value }
|
||||
|
||||
function commentDraftWrite({ cardId, value }) {
|
||||
if (!cardId) return;
|
||||
const draftKey = { fieldName: 'cardComment', docId: cardId };
|
||||
if ((value || '').trim()) {
|
||||
UnsavedEdits.set(draftKey, value);
|
||||
} else {
|
||||
UnsavedEdits.reset(draftKey);
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleCommentDraftSave(cardId, value) {
|
||||
commentDraftPending = { cardId, value };
|
||||
if (commentDraftTimer) clearTimeout(commentDraftTimer);
|
||||
commentDraftTimer = setTimeout(() => {
|
||||
commentDraftTimer = null;
|
||||
const pending = commentDraftPending;
|
||||
commentDraftPending = null;
|
||||
if (pending) commentDraftWrite(pending);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// Run a pending (debounced) save immediately — e.g. the card is closing.
|
||||
function flushCommentDraftSave() {
|
||||
if (commentDraftTimer) {
|
||||
clearTimeout(commentDraftTimer);
|
||||
commentDraftTimer = null;
|
||||
}
|
||||
const pending = commentDraftPending;
|
||||
commentDraftPending = null;
|
||||
if (pending) commentDraftWrite(pending);
|
||||
}
|
||||
|
||||
// Drop any pending save — the comment was submitted, so there is no draft.
|
||||
function cancelCommentDraftSave() {
|
||||
if (commentDraftTimer) {
|
||||
clearTimeout(commentDraftTimer);
|
||||
commentDraftTimer = null;
|
||||
}
|
||||
commentDraftPending = null;
|
||||
}
|
||||
|
||||
Template.commentForm.onDestroyed(function () {
|
||||
// #5547: the card can close without the escape handler ever running (the X
|
||||
// button, a route change); make sure the last keystrokes reach the draft.
|
||||
flushCommentDraftSave();
|
||||
commentFormIsOpen.set(false);
|
||||
$('.note-popover').hide();
|
||||
});
|
||||
@@ -28,6 +82,15 @@ Template.commentForm.helpers({
|
||||
});
|
||||
|
||||
Template.commentForm.events({
|
||||
// #5547: arm the escape handler below (it saves the draft and closes the
|
||||
// form); this flag had no setter since 2019, so the handler never ran.
|
||||
'focus .js-new-comment-input'() {
|
||||
commentFormIsOpen.set(true);
|
||||
},
|
||||
// #5547: keep the draft continuously saved (debounced) while typing.
|
||||
'input .js-new-comment-input'(evt) {
|
||||
scheduleCommentDraftSave(Utils.getCurrentCardId(), evt.currentTarget.value);
|
||||
},
|
||||
'submit .js-new-comment-form'(evt, tpl) {
|
||||
const input = tpl.$('.js-new-comment-input');
|
||||
const text = input.val().trim();
|
||||
@@ -48,6 +111,13 @@ Template.commentForm.events({
|
||||
cardId,
|
||||
parentId: parentId || '',
|
||||
});
|
||||
// #5547: the comment is saved — cancel any debounced draft save still in
|
||||
// flight and remove the stored draft so it does not resurface next open.
|
||||
cancelCommentDraftSave();
|
||||
UnsavedEdits.reset({
|
||||
fieldName: 'cardComment',
|
||||
docId: Utils.getCurrentCardId(),
|
||||
});
|
||||
replyToCommentId.set('');
|
||||
resetCommentInput(input);
|
||||
Tracker.flush();
|
||||
@@ -159,13 +229,20 @@ EscapeActions.register(
|
||||
docId: Utils.getCurrentCardId(),
|
||||
};
|
||||
const commentInput = $('.js-new-comment-input');
|
||||
const draft = commentInput.val().trim();
|
||||
const draft = (commentInput.val() || '').trim();
|
||||
cancelCommentDraftSave();
|
||||
if (draft) {
|
||||
UnsavedEdits.set(draftKey, draft);
|
||||
} else {
|
||||
UnsavedEdits.reset(draftKey);
|
||||
}
|
||||
resetCommentInput(commentInput);
|
||||
// #5547: do NOT clear the input — clearing it on every click outside the
|
||||
// comment box is exactly the "comment text disappearing" bug that got this
|
||||
// handler disarmed in 2019 (3b3950369). The draft is saved above; if the
|
||||
// card stays open, the text stays visible; if the card closes, the next
|
||||
// open prefills the form from the draft.
|
||||
commentInput.blur();
|
||||
commentFormIsOpen.set(false);
|
||||
},
|
||||
() => {
|
||||
return commentFormIsOpen.get();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -159,6 +159,12 @@ template(name="boardHeaderBar")
|
||||
i.fa.fa-times-thin
|
||||
|
||||
.separator
|
||||
//- #6465: one-click board settings — the boardMenu popup used to need
|
||||
//- two clicks (open sidebar, then Boardeinstellungen). The click
|
||||
//- handler already exists in boardHeader.js ('click .js-open-board-menu').
|
||||
if currentUser.isBoardMember
|
||||
a.board-header-btn.js-open-board-menu(title="{{_ 'boardMenuPopup-title'}}")
|
||||
i.fa.fa-cog
|
||||
a.board-header-btn.js-toggle-sidebar(title="{{_ 'sidebar-open'}} {{_ 'or'}} {{_ 'sidebar-close'}}")
|
||||
i.fa.fa-bars
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -49,7 +49,14 @@ Template.attachmentGallery.events({
|
||||
if (card && card.coverId === this._id) {
|
||||
await card.unsetCover();
|
||||
}
|
||||
await Attachments.removeAsync(this._id);
|
||||
// #5282 (same class as #3252 for comments/checklists): only remove if the
|
||||
// doc is still in the local cache. Under publication churn the attachment
|
||||
// can already be evicted from Minimongo, and removing a missing _id
|
||||
// throws "Removed nonexistent document" even though the delete itself
|
||||
// succeeded on the server.
|
||||
if (this._id && ReactiveCache.getAttachment(this._id)) {
|
||||
await Attachments.removeAsync(this._id);
|
||||
}
|
||||
Popup.back();
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { UnsavedEdits } from '/client/lib/unsavedEdits';
|
||||
|
||||
const descriptionFormIsOpen = new ReactiveVar(false);
|
||||
|
||||
Template.descriptionForm.onDestroyed(function () {
|
||||
@@ -16,6 +18,10 @@ Template.descriptionForm.events({
|
||||
event.preventDefault();
|
||||
const description = tpl.currentComponent ? tpl.currentComponent().getValue() : tpl.$('textarea').val();
|
||||
await this.setDescription(description);
|
||||
// #6455: a successful save means there is no unsaved draft anymore; clear
|
||||
// any pre-existing draft record so the "You have an unsaved description"
|
||||
// warning does not stick around after saving.
|
||||
UnsavedEdits.reset({ fieldName: 'cardDescription', docId: this._id });
|
||||
},
|
||||
// Pressing Ctrl+Enter should submit the form
|
||||
'keydown form textarea'(evt, tpl) {
|
||||
|
||||
@@ -129,50 +129,82 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Desktop mode: position card below board header */
|
||||
/* Desktop mode: position card below board header.
|
||||
#6465: the floating window used to span nearly the whole board (insets
|
||||
20px/20px from BOTH edges, top-left anchored) — right on top of the card it
|
||||
belongs to, with big rounded borders. Dock it to the END edge (right in LTR)
|
||||
like the classic 6.09 side panel instead: the board and the card stay
|
||||
visible, and the drag handle still moves it anywhere. */
|
||||
body.desktop-mode .card-details:not(.card-details-popup) {
|
||||
position: fixed;
|
||||
width: auto;
|
||||
max-width: 800px;
|
||||
flex-basis: auto;
|
||||
border-radius: 8px;
|
||||
border-radius: 3px;
|
||||
z-index: 2001;
|
||||
}
|
||||
|
||||
/* Default position for first card or when dragged */
|
||||
body.desktop-mode .card-details:not(.card-details-popup):not([style*="left"]):not([style*="top"]) {
|
||||
top: 8px;
|
||||
inset-inline-start: 20px;
|
||||
inset-inline-end: 20px;
|
||||
bottom: 20px;
|
||||
inset-inline-start: auto;
|
||||
inset-inline-end: 8px;
|
||||
width: min(650px, 90vw);
|
||||
bottom: 8px;
|
||||
}
|
||||
|
||||
/* Stagger positions for multiple cards using nth-of-type */
|
||||
/* Stagger positions for multiple cards using nth-of-type (from the end edge) */
|
||||
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(1) {
|
||||
top: 8px;
|
||||
inset-inline-start: 20px;
|
||||
inset-inline-end: 8px;
|
||||
}
|
||||
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(2) {
|
||||
top: 38px;
|
||||
inset-inline-start: 50px;
|
||||
inset-inline-end: 38px;
|
||||
}
|
||||
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(3) {
|
||||
top: 68px;
|
||||
inset-inline-start: 80px;
|
||||
inset-inline-end: 68px;
|
||||
}
|
||||
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(4) {
|
||||
top: 98px;
|
||||
inset-inline-start: 110px;
|
||||
inset-inline-end: 98px;
|
||||
}
|
||||
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(5) {
|
||||
top: 128px;
|
||||
inset-inline-start: 140px;
|
||||
inset-inline-end: 128px;
|
||||
}
|
||||
|
||||
/* For expanded cards, set dimensions */
|
||||
body.desktop-mode .card-details:not(.card-details-popup):not(.card-details-collapsed) {
|
||||
inset-inline-end: 20px;
|
||||
bottom: 20px;
|
||||
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 */
|
||||
@@ -192,7 +224,9 @@ body.desktop-mode .card-details.card-details-collapsed {
|
||||
}
|
||||
.card-details .card-details-canvas {
|
||||
width: auto;
|
||||
padding: 0 2.5vw;
|
||||
/* #6465: fixed 20px as in 6.09 — 2.5vw was ~48px of white border per side
|
||||
on a FullHD screen. */
|
||||
padding: 0 20px;
|
||||
}
|
||||
.card-details .card-details-header {
|
||||
margin: 0 -20px 5px;
|
||||
@@ -300,25 +334,14 @@ body.desktop-mode .card-details.card-details-collapsed {
|
||||
float: inline-end;
|
||||
}
|
||||
|
||||
/* Unify all card text to match title size */
|
||||
/* #6465: the "unify all card text to match title size" block (v8.18) forced
|
||||
EVERY element in card details to the base font size with line-height 1.5,
|
||||
flattening the 6.09 hierarchy where labels/metadata were smaller than body
|
||||
text — a big part of the "card window is WAAAY too big" complaint. Removed:
|
||||
components keep their own sizes again. */
|
||||
.card-details {
|
||||
font-size: 1em;
|
||||
}
|
||||
.card-details p,
|
||||
.card-details span,
|
||||
.card-details div,
|
||||
.card-details a,
|
||||
.card-details label,
|
||||
.card-details input,
|
||||
.card-details textarea,
|
||||
.card-details select,
|
||||
.card-details button,
|
||||
.card-details .card-details-item-title,
|
||||
.card-details .card-label,
|
||||
.card-details .viewer {
|
||||
font-size: inherit;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.card-details .card-details-header .card-details-watch {
|
||||
font-size: 17px;
|
||||
padding-inline-start: 7px;
|
||||
@@ -446,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;
|
||||
|
||||
@@ -867,6 +867,12 @@ Template.cardDetails.events({
|
||||
// permission denial that otherwise vanished with no feedback.
|
||||
try {
|
||||
await card.setDescription(description);
|
||||
// #6455: a successful save means there is no unsaved draft anymore.
|
||||
// Clear the record explicitly instead of relying on the inlined form's
|
||||
// close-time draft/description comparison, which can run before the
|
||||
// updated description is visible and leave a stale "You have an unsaved
|
||||
// description" warning behind.
|
||||
UnsavedEdits.reset({ fieldName: 'cardDescription', docId: card._id });
|
||||
} catch (error) {
|
||||
alert(error?.reason || error?.message || 'Failed to save description');
|
||||
}
|
||||
@@ -1367,10 +1373,24 @@ Template.inlinedCardDescription.onCreated(function () {
|
||||
|
||||
this._close = (isReset = false) => {
|
||||
if (this.isOpen.get() && !isReset) {
|
||||
const draft = (this._getValue() || '').trim();
|
||||
// #6455: normalize BOTH sides the same way before comparing. The textarea
|
||||
// value has per-line trailing whitespace stripped (_getValue), while
|
||||
// getDescription() returns the raw stored text — or null for an empty
|
||||
// description. Comparing them raw made the comparison permanently unequal
|
||||
// for descriptions containing Markdown " \n" hard breaks (or after
|
||||
// emptying the description), re-creating the phantom draft on every save.
|
||||
const normalize = (s) => (s || '').replaceAll(/[ \f\r\t\v]+$/gm, '').trim();
|
||||
const draft = normalize(this._getValue());
|
||||
const card = getCurrentCardFromContext();
|
||||
if (card && draft !== card.getDescription()) {
|
||||
if (card && draft !== normalize(card.getDescription())) {
|
||||
UnsavedEdits.set(this._getUnsavedEditKey(), this._getValue());
|
||||
} else {
|
||||
// #6455: closing with the draft equal to the saved description must
|
||||
// REMOVE any pre-existing unsaved-edits record. Previously this branch
|
||||
// did nothing, so once a draft record existed, pressing Save ("View it"
|
||||
// -> Save) could never clear the "You have an unsaved description"
|
||||
// warning — only Discard could.
|
||||
UnsavedEdits.reset(this._getUnsavedEditKey());
|
||||
}
|
||||
}
|
||||
this.isOpen.set(false);
|
||||
@@ -1467,6 +1487,15 @@ Template.cardDetailsActionsPopup.events({
|
||||
Popup.close();
|
||||
if (!card) return;
|
||||
await card.archive();
|
||||
// #6465 follow-up: archiving must also CLOSE the card's details window.
|
||||
// The card id stayed in the openCards session list, so the floating window
|
||||
// kept rendering above the board — and, docked to the right edge, exactly
|
||||
// over the archives sidebar someone restoring the card would open next,
|
||||
// intercepting its Restore/Delete clicks.
|
||||
Session.set('openCards', (Session.get('openCards') || []).filter((id) => id !== card._id));
|
||||
if (Session.get('currentCard') === card._id) {
|
||||
Session.set('currentCard', null);
|
||||
}
|
||||
Utils.goBoardId(card.boardId);
|
||||
}),
|
||||
'click .js-more': Popup.open('cardMore'),
|
||||
@@ -2217,6 +2246,12 @@ Template.cardMorePopup.events({
|
||||
// verify that there are no linked cards
|
||||
if (ReactiveCache.getCards({ linkedId: card._id }).length === 0) {
|
||||
Cards.remove(card._id);
|
||||
// #6465 follow-up: like archiving, deleting must close the card's
|
||||
// details window (drop it from the openCards session list).
|
||||
Session.set('openCards', (Session.get('openCards') || []).filter((id) => id !== card._id));
|
||||
if (Session.get('currentCard') === card._id) {
|
||||
Session.set('currentCard', null);
|
||||
}
|
||||
} else {
|
||||
// TODO: Maybe later we can list where the linked cards are.
|
||||
// Now here is popup with a hint that the card cannot be deleted
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -208,7 +208,10 @@ template(name="listMorePopup")
|
||||
span {{_ 'link-list'}}
|
||||
= ' '
|
||||
i.fa(class="{{#if currentBoard.isPublic}}fa-globe{{else}}fa-lock{{/if}}")
|
||||
input.inline-input(type="text" readonly value="{{ rootUrl }}")
|
||||
//- #6459: was {{ rootUrl }}, a helper that does not exist anywhere, so the
|
||||
//- link input was always empty. absoluteUrl resolves a URL via a card on
|
||||
//- this list.
|
||||
input.inline-input(type="text" readonly value="{{ absoluteUrl }}")
|
||||
| {{_ 'added'}}
|
||||
span.date(title=list.createdAt) {{ displayDate createdAt 'LLL' }}
|
||||
//unless currentUser.isWorker
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -290,15 +290,19 @@ body:not(.board-view) #header #header-main-bar h1 {
|
||||
}
|
||||
|
||||
/* Zoom Controls in Header */
|
||||
/* #6465: compact fixed-pixel pill. The vh/vw padding+shadow made the pill
|
||||
taller than the 28px overflow-hidden quick-access row, so it rendered cut
|
||||
off at every window size. */
|
||||
#header-quick-access .zoom-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5vw;
|
||||
gap: 4px;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
padding: 0.5vh 1vw;
|
||||
border-radius: 0.5vw;
|
||||
box-shadow: 0 0.2vh 0.5vh rgba(0,0,0,0.1);
|
||||
margin: 0 1vw;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
|
||||
margin: 0 8px;
|
||||
max-height: 24px;
|
||||
float: inline-start;
|
||||
}
|
||||
|
||||
|
||||
@@ -157,8 +157,14 @@ input,
|
||||
select,
|
||||
textarea,
|
||||
button {
|
||||
font: clamp(14px, 2.5vw, 18px) Roboto, Poppins, "Helvetica Neue", Arial, Helvetica, sans-serif;
|
||||
line-height: 1.4;
|
||||
/* #6465: back to the WeKan 6.09 desktop density. The clamp() introduced in
|
||||
v7.98 (20e9cf114) and raised in v8.02 (67b078b80) resolved to 18px on any
|
||||
window wider than 720px — +28.5% on EVERY font, input and button versus
|
||||
6.09's 14px — which is the "everything is way too big" regression. Mobile
|
||||
readability is handled by the mobile media queries, not by inflating the
|
||||
desktop base font. */
|
||||
font: 14px Roboto, Poppins, "Helvetica Neue", Arial, Helvetica, sans-serif;
|
||||
line-height: 18px;
|
||||
color: #4d4d4d;
|
||||
/* Improve text rendering */
|
||||
-webkit-font-smoothing: antialiased;
|
||||
@@ -217,8 +223,10 @@ body.mobile-mode #content {
|
||||
margin-top: 30vh;
|
||||
}
|
||||
#content > .wrapper {
|
||||
margin-top: 1vh;
|
||||
padding: 2vh 2vw;
|
||||
/* #6465: 6.09 values; 2vh/2vw padding was ~21x38px on FullHD — the huge
|
||||
empty header band on the All Boards page. */
|
||||
margin-top: 10px;
|
||||
padding: 15px;
|
||||
}
|
||||
#modal {
|
||||
position: absolute;
|
||||
@@ -264,13 +272,15 @@ body.mobile-mode #content {
|
||||
float: inline-end;
|
||||
font-size: clamp(18px, 4vw, 24px);
|
||||
}
|
||||
/* #6465: heading sizes back to the 6.09 values (22/18/16px) — the vw clamps
|
||||
resolved to 24/20/18px on desktop and compounded the density regression. */
|
||||
h1 {
|
||||
font-size: clamp(18px, 4vw, 24px);
|
||||
font-size: 22px;
|
||||
line-height: 1.2em;
|
||||
margin: 0 0 1vh;
|
||||
}
|
||||
h2 {
|
||||
font-size: clamp(16px, 3.5vw, 20px);
|
||||
font-size: 18px;
|
||||
line-height: 1.2em;
|
||||
margin: 0 0 0.8vh;
|
||||
}
|
||||
@@ -278,7 +288,7 @@ h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
font-size: clamp(14px, 3vw, 18px);
|
||||
font-size: 16px;
|
||||
line-height: 1.25em;
|
||||
margin: 0 0 0.6vh;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -134,7 +134,11 @@ Template.boardActions.events({
|
||||
// documents land in minimongo limbo when the wizard subscription stops.
|
||||
Meteor.call('rules.createRule', boardId, ruleName, trigger, {
|
||||
actionType,
|
||||
listTitle: '*',
|
||||
// #6472: was `listTitle: '*'` since the original rules implementation,
|
||||
// but performAction reads action.listName/action.swimlaneName — so every
|
||||
// generic "move to top/bottom" rule created by this wizard did nothing.
|
||||
listName: '*',
|
||||
swimlaneName: '*',
|
||||
boardId,
|
||||
desc,
|
||||
});
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { ReactiveCache } from '/imports/reactiveCache';
|
||||
import { TAPi18n } from '/imports/i18n';
|
||||
import Papa from 'papaparse';
|
||||
import Actions from '/models/actions';
|
||||
import Rules from '/models/rules';
|
||||
import Triggers from '/models/triggers';
|
||||
|
||||
const RULES_FORMAT = 'wekan-rules-1.0.0';
|
||||
const STRIP_FIELDS = ['_id', 'boardId', 'createdAt', 'modifiedAt', 'updatedAt'];
|
||||
@@ -33,14 +30,43 @@ function collectBoardRules(boardId) {
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
// #6472: the trigger matcher (server/rulesHelper.js buildMatchingFieldsMap)
|
||||
// queries every matching field of the trigger type with {$in: [value, '*']} —
|
||||
// a trigger DOCUMENT that lacks one of those fields can never match. Hand-
|
||||
// written or third-party JSON often omits fields like userId, so default every
|
||||
// known matching field to the '*' wildcard when absent. Extra fields on
|
||||
// trigger types that do not use them are harmless (never queried).
|
||||
const TRIGGER_MATCHING_FIELDS = [
|
||||
'userId', 'username', 'cardTitle', 'listName', 'oldListName',
|
||||
'swimlaneName', 'checklistName', 'checklistItemName', 'labelId',
|
||||
'attachmentName',
|
||||
];
|
||||
|
||||
function normalizeTrigger(trigger) {
|
||||
const out = { ...trigger };
|
||||
TRIGGER_MATCHING_FIELDS.forEach(f => {
|
||||
if (out[f] === undefined || out[f] === null || out[f] === '') out[f] = '*';
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
// Insert an array of {title, trigger, action} onto the given target board.
|
||||
function importRules(rulesArray, boardId) {
|
||||
let count = 0;
|
||||
(rulesArray || []).forEach(entry => {
|
||||
if (!entry || !entry.trigger || !entry.action) return;
|
||||
const triggerId = Triggers.insert({ ...stripDoc(entry.trigger), boardId });
|
||||
const actionId = Actions.insert({ ...stripDoc(entry.action), boardId });
|
||||
Rules.insert({ title: entry.title || 'Imported rule', triggerId, actionId, boardId });
|
||||
// #6472: create via the rules.createRule server method (like the rules
|
||||
// wizard since #5536) instead of three optimistic client inserts — those
|
||||
// are rejected by the board-admin-only allow() rules for non-admins and
|
||||
// land in minimongo limbo: the imported rule LOOKS created but never
|
||||
// exists on the server, so it silently does nothing until it vanishes.
|
||||
Meteor.call(
|
||||
'rules.createRule',
|
||||
boardId,
|
||||
entry.title || 'Imported rule',
|
||||
normalizeTrigger(stripDoc(entry.trigger)),
|
||||
stripDoc(entry.action),
|
||||
);
|
||||
count += 1;
|
||||
});
|
||||
return count;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -146,21 +146,27 @@ template(name="orgGeneral")
|
||||
th
|
||||
| {{_ 'org-shared-templates'}}
|
||||
br
|
||||
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="true") {{_ 'select-all'}}
|
||||
| /
|
||||
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="false") {{_ 'unselect-all'}}
|
||||
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="true", title="{{_ 'select-all'}}")
|
||||
i.fa.fa-check-square-o
|
||||
|
|
||||
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="false", title="{{_ 'unselect-all'}}")
|
||||
i.fa.fa-square-o
|
||||
th
|
||||
| {{_ 'org-propagate-members-to-boards'}}
|
||||
br
|
||||
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="true") {{_ 'select-all'}}
|
||||
| /
|
||||
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="false") {{_ 'unselect-all'}}
|
||||
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="true", title="{{_ 'select-all'}}")
|
||||
i.fa.fa-check-square-o
|
||||
|
|
||||
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="false", title="{{_ 'unselect-all'}}")
|
||||
i.fa.fa-square-o
|
||||
th
|
||||
| {{_ 'org-sync-members-from-auth'}}
|
||||
br
|
||||
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="true") {{_ 'select-all'}}
|
||||
| /
|
||||
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="false") {{_ 'unselect-all'}}
|
||||
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="true", title="{{_ 'select-all'}}")
|
||||
i.fa.fa-check-square-o
|
||||
|
|
||||
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="false", title="{{_ 'unselect-all'}}")
|
||||
i.fa.fa-square-o
|
||||
tbody
|
||||
tr
|
||||
each org in orgList
|
||||
@@ -187,21 +193,27 @@ template(name="teamGeneral")
|
||||
th
|
||||
| {{_ 'team-shared-templates'}}
|
||||
br
|
||||
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="true") {{_ 'select-all'}}
|
||||
| /
|
||||
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="false") {{_ 'unselect-all'}}
|
||||
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="true", title="{{_ 'select-all'}}")
|
||||
i.fa.fa-check-square-o
|
||||
|
|
||||
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="false", title="{{_ 'unselect-all'}}")
|
||||
i.fa.fa-square-o
|
||||
th
|
||||
| {{_ 'team-propagate-members-to-boards'}}
|
||||
br
|
||||
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="true") {{_ 'select-all'}}
|
||||
| /
|
||||
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="false") {{_ 'unselect-all'}}
|
||||
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="true", title="{{_ 'select-all'}}")
|
||||
i.fa.fa-check-square-o
|
||||
|
|
||||
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="false", title="{{_ 'unselect-all'}}")
|
||||
i.fa.fa-square-o
|
||||
th
|
||||
| {{_ 'team-sync-members-from-auth'}}
|
||||
br
|
||||
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="true") {{_ 'select-all'}}
|
||||
| /
|
||||
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="false") {{_ 'unselect-all'}}
|
||||
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="true", title="{{_ 'select-all'}}")
|
||||
i.fa.fa-check-square-o
|
||||
|
|
||||
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="false", title="{{_ 'unselect-all'}}")
|
||||
i.fa.fa-square-o
|
||||
tbody
|
||||
tr
|
||||
each team in teamList
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,11 +117,17 @@
|
||||
}
|
||||
|
||||
/* Force tables to always trigger horizontal scrolling */
|
||||
.setting-content .content-body .main-body table td,
|
||||
.setting-content .content-body .main-body table th {
|
||||
.setting-content .content-body .main-body table td {
|
||||
white-space: nowrap;
|
||||
min-width: 120px;
|
||||
}
|
||||
/* #6465: headers may wrap — nowrap on long header labels (e.g. the org/team
|
||||
feature columns) blew the column widths up to the whole label length. */
|
||||
.setting-content .content-body .main-body table th {
|
||||
white-space: normal;
|
||||
min-width: 120px;
|
||||
max-width: 240px;
|
||||
}
|
||||
|
||||
/* Ensure there's enough content to trigger vertical scrolling */
|
||||
.setting-content .content-body .main-body {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -197,6 +197,11 @@ body.grey-icons-enabled .sidebar .sidebar-content ul.sidebar-list li > a .fa.fa-
|
||||
}
|
||||
.board-sidebar.is-open {
|
||||
display: block;
|
||||
/* #6465 follow-up: the card details window docks to the right edge with
|
||||
z-index 2001 — the same place this sidebar opens. When the user opens the
|
||||
sidebar, the sidebar must win, or its content (e.g. the archives
|
||||
Restore/Delete links) sits unreachable UNDER the card window. */
|
||||
z-index: 2002;
|
||||
}
|
||||
.board-widget h4 {
|
||||
margin: 5px 0;
|
||||
@@ -254,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,
|
||||
|
||||
@@ -686,13 +686,15 @@ services:
|
||||
# When true, sync a user's LDAP groups as Wekan Organizations.
|
||||
#- LDAP_SYNC_ORGANIZATIONS=false
|
||||
#
|
||||
# Comma separated allowlist of LDAP group names to sync as Organizations. Empty = all of the user's groups.
|
||||
# Comma separated allowlist of LDAP group names/patterns to sync as Organizations.
|
||||
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
|
||||
#- LDAP_SYNC_ORGANIZATIONS_GROUPS=
|
||||
#
|
||||
# When true, sync a user's LDAP groups as Wekan Teams.
|
||||
#- LDAP_SYNC_TEAMS=false
|
||||
#
|
||||
# Comma separated allowlist of LDAP group names to sync as Teams. Empty = all of the user's groups.
|
||||
# Comma separated allowlist of LDAP group names/patterns to sync as Teams.
|
||||
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
|
||||
#- LDAP_SYNC_TEAMS_GROUPS=
|
||||
#---------------------------------------------------------------------
|
||||
# Login to LDAP automatically with HTTP header.
|
||||
|
||||
@@ -920,13 +920,15 @@ services:
|
||||
# When true, sync a user's LDAP groups as Wekan Organizations.
|
||||
#- LDAP_SYNC_ORGANIZATIONS=false
|
||||
#
|
||||
# Comma separated allowlist of LDAP group names to sync as Organizations. Empty = all of the user's groups.
|
||||
# Comma separated allowlist of LDAP group names/patterns to sync as Organizations.
|
||||
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
|
||||
#- LDAP_SYNC_ORGANIZATIONS_GROUPS=
|
||||
#
|
||||
# When true, sync a user's LDAP groups as Wekan Teams.
|
||||
#- LDAP_SYNC_TEAMS=false
|
||||
#
|
||||
# Comma separated allowlist of LDAP group names to sync as Teams. Empty = all of the user's groups.
|
||||
# Comma separated allowlist of LDAP group names/patterns to sync as Teams.
|
||||
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
|
||||
#- LDAP_SYNC_TEAMS_GROUPS=
|
||||
#---------------------------------------------------------------------
|
||||
# Login to LDAP automatically with HTTP header.
|
||||
|
||||
+4
-2
@@ -713,13 +713,15 @@ services:
|
||||
# When true, sync a user's LDAP groups as Wekan Organizations.
|
||||
#- LDAP_SYNC_ORGANIZATIONS=false
|
||||
#
|
||||
# Comma separated allowlist of LDAP group names to sync as Organizations. Empty = all of the user's groups.
|
||||
# Comma separated allowlist of LDAP group names/patterns to sync as Organizations.
|
||||
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
|
||||
#- LDAP_SYNC_ORGANIZATIONS_GROUPS=
|
||||
#
|
||||
# When true, sync a user's LDAP groups as Wekan Teams.
|
||||
#- LDAP_SYNC_TEAMS=false
|
||||
#
|
||||
# Comma separated allowlist of LDAP group names to sync as Teams. Empty = all of the user's groups.
|
||||
# Comma separated allowlist of LDAP group names/patterns to sync as Teams.
|
||||
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
|
||||
#- LDAP_SYNC_TEAMS_GROUPS=
|
||||
#---------------------------------------------------------------------
|
||||
# Login to LDAP automatically with HTTP header.
|
||||
|
||||
@@ -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"}'
|
||||
```
|
||||
@@ -1,3 +1,32 @@
|
||||
## Built-in: WeKan cpu-exec runs binaries with qemu-user automatically
|
||||
|
||||
Since WeKan 9.96 (issue [#6458](https://github.com/wekan/wekan/issues/6458)), WeKan ships a general
|
||||
`cpu-exec` helper on every Linux platform — in the Snap (`$SNAP/bin/cpu-exec`), in every
|
||||
`wekan-<version>-<arch>.zip` bundle (`bundle/cpu-exec`, next to a same-arch `qemu-<arch>` static
|
||||
binary), in the Docker image (`/build/cpu-exec`) and in the Sandstorm .spk. It checks
|
||||
`/proc/cpuinfo` for the CPU features a binary needs and, when one is missing, transparently re-runs
|
||||
the binary through qemu-user (which implements the full modern instruction set):
|
||||
|
||||
```
|
||||
cpu-exec --features x86_64=avx,aarch64=atomics mongod --dbpath ...
|
||||
```
|
||||
|
||||
- With no `--features` (or no entry for the current architecture) it is a plain `exec` — zero
|
||||
overhead, safe for every binary.
|
||||
- `WEKAN_REQUIRED_CPU_FEATURES` (same syntax) overrides `--features`, so any script or user can
|
||||
declare requirements without editing commands.
|
||||
- qemu-user lookup order: `$WEKAN_QEMU_USER`, `qemu-<arch>` next to cpu-exec (the bundle),
|
||||
`$SNAP/qemu-<arch>`, the Snap's `migratemongo/avx/qemu-x86_64`, then `qemu-<arch>`/
|
||||
`qemu-<arch>-static` on `$PATH` (install with `sudo apt install qemu-user-static`).
|
||||
- `aarch64=atomics` (LSE, ARMv8.1) is the practical `/proc/cpuinfo` proxy for MongoDB's ARMv8.2-A
|
||||
requirement: Raspberry Pi 3/4 (Cortex-A53/A72) lack it, ARMv8.2-A cores have it.
|
||||
|
||||
The Snap's `mongodb-control` and `migration-control` run every `mongod 7` invocation through
|
||||
cpu-exec, so WeKan's MongoDB works (slower) on CPUs without AVX — including hypervisors/sandboxes
|
||||
that mask AVX — and the MongoDB → FerretDB migration can read modern MongoDB data there too.
|
||||
FerretDB (pure Go + SQLite) needs no special CPU features and is the native-speed alternative:
|
||||
`snap run wekan.migrate`.
|
||||
|
||||
## Meteor podcast about using MongoDB at unsupported CPUs
|
||||
|
||||
- https://www.youtube.com/watch?v=bnU9bUVeN04
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
## Built-in: WeKan cpu-exec does this automatically
|
||||
|
||||
Since WeKan 9.96, the manual wrapper below is built in: every Linux WeKan bundle/Snap/Docker
|
||||
image ships a general `cpu-exec` helper (plus a same-arch `qemu-<arch>` static binary in the
|
||||
bundles) that runs any binary through qemu-user automatically when the CPU lacks features the
|
||||
binary needs — e.g. MongoDB 5+ on Raspberry Pi 4 and older (ARMv8.0, no ARMv8.2-A):
|
||||
|
||||
```
|
||||
cpu-exec --features x86_64=avx,aarch64=atomics mongod --config /etc/mongod.conf
|
||||
```
|
||||
|
||||
See [mongodb-avx-qemu.md](mongodb-avx-qemu.md) for details. The manual steps below still work
|
||||
for a system-wide MongoDB outside WeKan.
|
||||
|
||||
## Meteor podcast about using MongoDB at unsupported CPUs
|
||||
|
||||
- https://www.youtube.com/watch?v=bnU9bUVeN04
|
||||
|
||||
+12
-4
@@ -179,12 +179,15 @@ Source). On Snap use the lower-case dash-separated equivalent (for example
|
||||
- `LDAP_SYNC_ORGANIZATIONS` (default `false`) — when `true`, a user's LDAP groups
|
||||
are synced into that user's Wekan **Organizations**.
|
||||
- `LDAP_SYNC_ORGANIZATIONS_GROUPS` (default empty) — comma-separated list of LDAP
|
||||
group names to sync as Organizations. Leave empty to sync all of the user's
|
||||
groups.
|
||||
group names/patterns to sync as Organizations. Leave empty to sync all of the
|
||||
user's groups. Supports wildcards: `*` (any number of characters) and `?`
|
||||
(single character).
|
||||
- `LDAP_SYNC_TEAMS` (default `false`) — when `true`, a user's LDAP groups are
|
||||
synced into that user's Wekan **Teams**.
|
||||
- `LDAP_SYNC_TEAMS_GROUPS` (default empty) — comma-separated list of LDAP group
|
||||
names to sync as Teams. Leave empty to sync all of the user's groups.
|
||||
names/patterns to sync as Teams. Leave empty to sync all of the user's
|
||||
groups. Supports wildcards: `*` (any number of characters) and `?` (single
|
||||
character).
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -382,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.95-win64.zip](https://github.com/wekan/wekan/releases/download/v9.95/wekan-9.95-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.95-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) {
|
||||
|
||||
+54
-79
@@ -1668,17 +1668,27 @@ Boards.helpers({
|
||||
// that belong to itself.
|
||||
getDefaultSubtasksBoardId() {
|
||||
// #3868 / #5788 / #2256: only the SERVER may auto-create the default
|
||||
// subtasks board (+ its swimlane). On the client the board's
|
||||
// subtasksDefaultBoardId can momentarily read as unset (e.g. the helper
|
||||
// board is not in the published set "if you don't navigate through All
|
||||
// Boards first"), and creating it client-side produced a new board/swimlane
|
||||
// on every subtask creation. Server-authoritative creation happens once.
|
||||
if (
|
||||
Meteor.isServer &&
|
||||
(this.subtasksDefaultBoardId === null ||
|
||||
this.subtasksDefaultBoardId === undefined)
|
||||
) {
|
||||
this.subtasksDefaultBoardId = Boards.insert({
|
||||
// subtasks board (+ its swimlane) — and #6456: on Meteor 3 the server may
|
||||
// not use the sync insert/update APIs either ("insert is not available on
|
||||
// the server"), which made addSubtaskCard throw here. This is now a PURE
|
||||
// getter; the server-side creation lives in getDefaultSubtasksBoardAsync
|
||||
// (the only path the addSubtaskCard method uses).
|
||||
return this.subtasksDefaultBoardId;
|
||||
},
|
||||
|
||||
getDefaultSubtasksBoard() {
|
||||
return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
|
||||
},
|
||||
|
||||
async getDefaultSubtasksBoardAsync() {
|
||||
let boardId = this.getDefaultSubtasksBoardId();
|
||||
|
||||
// #6456: server-authoritative lazy creation, once, with the async APIs
|
||||
// (the sync Boards.insert/Swimlanes.insert/Boards.update this used to rely
|
||||
// on throw on the Meteor 3 server, so creating a subtask crashed with
|
||||
// "Exception while invoking method 'addSubtaskCard'").
|
||||
if (!boardId && Meteor.isServer) {
|
||||
boardId = await Boards.insertAsync({
|
||||
title: `^${this.title}^`,
|
||||
permission: this.permission,
|
||||
members: sanitizeBoardMembers(this.members),
|
||||
@@ -1690,25 +1700,14 @@ Boards.helpers({
|
||||
),
|
||||
});
|
||||
|
||||
Swimlanes.insert({
|
||||
await Swimlanes.insertAsync({
|
||||
title: getTranslatedString('default', 'Default'),
|
||||
boardId: this.subtasksDefaultBoardId,
|
||||
});
|
||||
Boards.update(this._id, {
|
||||
$set: {
|
||||
subtasksDefaultBoardId: this.subtasksDefaultBoardId,
|
||||
},
|
||||
boardId,
|
||||
});
|
||||
await this.setSubtasksDefaultBoardId(boardId);
|
||||
this.subtasksDefaultBoardId = boardId;
|
||||
}
|
||||
return this.subtasksDefaultBoardId;
|
||||
},
|
||||
|
||||
getDefaultSubtasksBoard() {
|
||||
return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
|
||||
},
|
||||
|
||||
async getDefaultSubtasksBoardAsync() {
|
||||
const boardId = this.getDefaultSubtasksBoardId();
|
||||
if (!boardId) {
|
||||
return null;
|
||||
}
|
||||
@@ -1722,32 +1721,13 @@ Boards.helpers({
|
||||
|
||||
//Date Settings option such as received date, start date and so on.
|
||||
getDefaultDateSettingsBoardId() {
|
||||
if (
|
||||
this.dateSettingsDefaultBoardId === null ||
|
||||
this.dateSettingsDefaultBoardId === undefined
|
||||
) {
|
||||
this.dateSettingsDefaultBoardId = Boards.insert({
|
||||
title: `^${this.title}^`,
|
||||
permission: this.permission,
|
||||
members: sanitizeBoardMembers(this.members),
|
||||
color: this.color,
|
||||
description: getTranslatedString(
|
||||
'default-dates-board',
|
||||
`Default dates board for ${this.title}`,
|
||||
{ board: this.title },
|
||||
),
|
||||
});
|
||||
|
||||
Swimlanes.insert({
|
||||
title: getTranslatedString('default', 'Default'),
|
||||
boardId: this.dateSettingsDefaultBoardId,
|
||||
});
|
||||
Boards.update(this._id, {
|
||||
$set: {
|
||||
dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
|
||||
},
|
||||
});
|
||||
}
|
||||
// #6456 (same class): PURE getter. The lazy sync creation this used had
|
||||
// BOTH bug classes — no Meteor.isServer guard (client-side creation on
|
||||
// every reactive read, the #2256/#3868 duplicate-boards class) and the
|
||||
// sync Boards.insert/Swimlanes.insert/Boards.update APIs that throw on the
|
||||
// Meteor 3 server. Nothing in the codebase calls it today; if a feature
|
||||
// needs the dates helper board again, add an async server-side ensure like
|
||||
// getDefaultSubtasksBoardAsync.
|
||||
return this.dateSettingsDefaultBoardId;
|
||||
},
|
||||
|
||||
@@ -1756,21 +1736,10 @@ Boards.helpers({
|
||||
},
|
||||
|
||||
getDefaultSubtasksListId() {
|
||||
// #3868 / #5788 / #2256: server-only auto-creation of the default subtasks
|
||||
// list (see getDefaultSubtasksBoardId) so the client cannot create
|
||||
// duplicate lists when the field momentarily reads as unset.
|
||||
if (
|
||||
Meteor.isServer &&
|
||||
(this.subtasksDefaultListId === null ||
|
||||
this.subtasksDefaultListId === undefined)
|
||||
) {
|
||||
this.subtasksDefaultListId = Lists.insert({
|
||||
title: getTranslatedString('queue', 'Queue'),
|
||||
boardId: this._id,
|
||||
swimlaneId: this.getDefaultSwimline()._id, // Set default swimlane for subtasks list
|
||||
});
|
||||
this.setSubtasksDefaultListId(this.subtasksDefaultListId);
|
||||
}
|
||||
// #3868 / #5788 / #2256 / #6456: PURE getter — client-side creation
|
||||
// duplicated lists, and the sync Lists.insert this used on the server
|
||||
// throws on Meteor 3. Server-side creation lives in
|
||||
// getDefaultSubtasksListAsync.
|
||||
return this.subtasksDefaultListId;
|
||||
},
|
||||
|
||||
@@ -1779,7 +1748,23 @@ Boards.helpers({
|
||||
},
|
||||
|
||||
async getDefaultSubtasksListAsync() {
|
||||
const listId = this.getDefaultSubtasksListId();
|
||||
let listId = this.getDefaultSubtasksListId();
|
||||
|
||||
// #6456: server-authoritative lazy creation with the async APIs (the sync
|
||||
// Lists.insert + getDefaultSwimline() this relied on throw on the Meteor 3
|
||||
// server — getDefaultSwimline's sync ReactiveCache read even returns a
|
||||
// Promise there, so .._id was never valid).
|
||||
if (!listId && Meteor.isServer) {
|
||||
const swimlane = await this.getDefaultSwimlineAsync();
|
||||
listId = await Lists.insertAsync({
|
||||
title: getTranslatedString('queue', 'Queue'),
|
||||
boardId: this._id,
|
||||
swimlaneId: swimlane ? swimlane._id : undefined, // Set default swimlane for subtasks list
|
||||
});
|
||||
await this.setSubtasksDefaultListId(listId);
|
||||
this.subtasksDefaultListId = listId;
|
||||
}
|
||||
|
||||
if (!listId) {
|
||||
return null;
|
||||
}
|
||||
@@ -1792,17 +1777,7 @@ Boards.helpers({
|
||||
},
|
||||
|
||||
getDefaultDateSettingsListId() {
|
||||
if (
|
||||
this.dateSettingsDefaultListId === null ||
|
||||
this.dateSettingsDefaultListId === undefined
|
||||
) {
|
||||
this.dateSettingsDefaultListId = Lists.insert({
|
||||
title: getTranslatedString('queue', 'Queue'),
|
||||
boardId: this._id,
|
||||
swimlaneId: this.getDefaultSwimline()._id, // Set default swimlane for date settings list
|
||||
});
|
||||
this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
|
||||
}
|
||||
// #6456 (same class): PURE getter — see getDefaultDateSettingsBoardId.
|
||||
return this.dateSettingsDefaultListId;
|
||||
},
|
||||
|
||||
|
||||
+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,
|
||||
};
|
||||
+36
-22
@@ -331,15 +331,25 @@ Lists.helpers({
|
||||
if (!swimlaneId) {
|
||||
return undefined;
|
||||
}
|
||||
// Only the first swimlane surfaces orphaned cards.
|
||||
const pick = (swimlanes) => {
|
||||
if (!swimlanes || !swimlanes.length || swimlanes[0]._id !== swimlaneId) {
|
||||
return undefined;
|
||||
}
|
||||
return swimlanes.map(s => s._id).filter(id => id !== swimlaneId);
|
||||
};
|
||||
const swimlanes = ReactiveCache.getSwimlanes(
|
||||
{ boardId: this.boardId, archived: false },
|
||||
{ sort: ['sort'] },
|
||||
);
|
||||
// Only the first swimlane surfaces orphaned cards.
|
||||
if (!swimlanes.length || swimlanes[0]._id !== swimlaneId) {
|
||||
return undefined;
|
||||
// On the SERVER ReactiveCache.getSwimlanes returns a Promise; reading
|
||||
// .length off it made this always return undefined there (the orphan
|
||||
// fallback silently never applied server-side). Resolve it instead; the
|
||||
// client path stays synchronous.
|
||||
if (swimlanes && typeof swimlanes.then === 'function') {
|
||||
return swimlanes.then(pick);
|
||||
}
|
||||
return swimlanes.map(s => s._id).filter(id => id !== swimlaneId);
|
||||
return pick(swimlanes);
|
||||
},
|
||||
|
||||
cards(swimlaneId) {
|
||||
@@ -348,28 +358,32 @@ Lists.helpers({
|
||||
// bare top-level `$or`, so it never competes with the board Filter's own
|
||||
// top-level `$or` when the two selectors are combined.
|
||||
// #6443: also surface orphaned cards in the first swimlane.
|
||||
const selector = listCardsSelector(
|
||||
this._id,
|
||||
swimlaneId,
|
||||
this.orphanedCardsSwimlaneIds(swimlaneId),
|
||||
);
|
||||
const filterSelector =
|
||||
typeof Filter !== 'undefined' && typeof Filter.mongoSelector === 'function'
|
||||
? Filter.mongoSelector(selector)
|
||||
: selector;
|
||||
const ret = ReactiveCache.getCards(filterSelector, { sort: ['sort'] });
|
||||
return ret;
|
||||
const query = (orphanedIds) => {
|
||||
const selector = listCardsSelector(this._id, swimlaneId, orphanedIds);
|
||||
const filterSelector =
|
||||
typeof Filter !== 'undefined' && typeof Filter.mongoSelector === 'function'
|
||||
? Filter.mongoSelector(selector)
|
||||
: selector;
|
||||
return ReactiveCache.getCards(filterSelector, { sort: ['sort'] });
|
||||
};
|
||||
const orphaned = this.orphanedCardsSwimlaneIds(swimlaneId);
|
||||
if (orphaned && typeof orphaned.then === 'function') {
|
||||
return orphaned.then(query); // server (async ReactiveCache)
|
||||
}
|
||||
return query(orphaned);
|
||||
},
|
||||
|
||||
cardsUnfiltered(swimlaneId) {
|
||||
// Same swimlane-membership fallback as cards() (#6441/#6443), without the Filter.
|
||||
const selector = listCardsSelector(
|
||||
this._id,
|
||||
swimlaneId,
|
||||
this.orphanedCardsSwimlaneIds(swimlaneId),
|
||||
);
|
||||
const ret = ReactiveCache.getCards(selector, { sort: ['sort'] });
|
||||
return ret;
|
||||
const query = (orphanedIds) =>
|
||||
ReactiveCache.getCards(listCardsSelector(this._id, swimlaneId, orphanedIds), {
|
||||
sort: ['sort'],
|
||||
});
|
||||
const orphaned = this.orphanedCardsSwimlaneIds(swimlaneId);
|
||||
if (orphaned && typeof orphaned.then === 'function') {
|
||||
return orphaned.then(query); // server (async ReactiveCache)
|
||||
}
|
||||
return query(orphaned);
|
||||
},
|
||||
|
||||
allCards(swimlaneId) {
|
||||
|
||||
+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
|
||||
|
||||
+10
-1
@@ -408,7 +408,16 @@ var makeTagConstructor = function (tagName) {
|
||||
var attrs = arguments.length && arguments[0]; // 19
|
||||
if (attrs && (typeof attrs === 'object')) { // 20
|
||||
// Treat vanilla JS object as an attributes dictionary. // 21
|
||||
if (! HTML.isConstructedObject(attrs)) { // 22
|
||||
// Patched (WeKan #6459): an ARRAY first argument is tag CONTENT, never an
|
||||
// attributes dictionary. The vm-sandbox patch below made
|
||||
// isConstructedObject(Array) === false (upstream htmljs returns true), so a
|
||||
// tag whose inline text compiles to an array — e.g. the jade line
|
||||
// `label {{_ 'source-board'}}:`, i.e. [TemplateTag, ":"] — got its content
|
||||
// array assigned to instance.attrs. blaze-tools then serialized it as
|
||||
// HTML.Attrs(...), and at runtime Blaze._expandAttributes threw "The basic
|
||||
// TransformingVisitor does not support foreign objects in attributes",
|
||||
// rendering the whole cardMorePopup (with the Delete option) empty.
|
||||
if (! Array.isArray(attrs) && ! HTML.isConstructedObject(attrs)) { // 22
|
||||
instance.attrs = attrs; // 23
|
||||
i++; // 24
|
||||
} else if (attrs instanceof HTML.Attrs) { // 25
|
||||
|
||||
Generated
+5
-5
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "wekan",
|
||||
"version": "v9.95.0",
|
||||
"version": "v9.97.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wekan",
|
||||
"version": "v9.95.0",
|
||||
"version": "v9.97.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -12235,9 +12235,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/websocket-driver": {
|
||||
"version": "0.7.4",
|
||||
"resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz",
|
||||
"integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==",
|
||||
"version": "0.7.5",
|
||||
"resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.5.tgz",
|
||||
"integrity": "sha512-ZL2+3c7kMBdIRCMz6l8jQMHyGVxj+UL+xVk74Ombiciboca8rHa15L86B19E5oh1pL9Ii/uj54gtsIrZGMo6zA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wekan",
|
||||
"version": "v9.95.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/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/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",
|
||||
|
||||
@@ -19,6 +19,9 @@ Package.onUse(function(api) {
|
||||
|
||||
api.use('accounts-base', 'server');
|
||||
api.use('accounts-password', 'server');
|
||||
// DDP._CurrentMethodInvocation: server/sync.js clears the inherited login
|
||||
// invocation context so the org/team sync method call is server-to-server.
|
||||
api.use('ddp', 'server');
|
||||
api.use('quave:synced-cron', 'server');
|
||||
api.addFiles('client/loginHelper.js', 'client');
|
||||
|
||||
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
|
||||
// Parse a comma-separated LDAP group allowlist into trimmed non-empty patterns.
|
||||
// Empty/unset means "no restriction".
|
||||
function parseGroupAllowlist(value) {
|
||||
if (typeof value !== 'string' || value.trim() === '') {
|
||||
return [];
|
||||
}
|
||||
return value.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function normalizeGroupName(value) {
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim();
|
||||
return v === '' ? null : v;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
const normalized = normalizeGroupName(entry);
|
||||
if (normalized) {
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = String(value).trim();
|
||||
return v === '' ? null : v;
|
||||
}
|
||||
|
||||
function escapeRegExpChar(ch) {
|
||||
return /[\\^$.*+?()[\]{}|]/.test(ch) ? `\\${ch}` : ch;
|
||||
}
|
||||
|
||||
// Convert a simple glob pattern to RegExp.
|
||||
// Supported wildcards:
|
||||
// * -> any number of characters
|
||||
// ? -> exactly one character
|
||||
function globToRegExp(pattern) {
|
||||
let source = '^';
|
||||
for (const ch of String(pattern)) {
|
||||
if (ch === '*') {
|
||||
source += '.*';
|
||||
} else if (ch === '?') {
|
||||
source += '.';
|
||||
} else {
|
||||
source += escapeRegExpChar(ch);
|
||||
}
|
||||
}
|
||||
source += '$';
|
||||
return new RegExp(source);
|
||||
}
|
||||
|
||||
function groupNameMatchesAllowPattern(groupName, pattern) {
|
||||
const normalizedGroupName = normalizeGroupName(groupName);
|
||||
if (!normalizedGroupName || typeof pattern !== 'string' || pattern === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!pattern.includes('*') && !pattern.includes('?')) {
|
||||
return normalizedGroupName === pattern;
|
||||
}
|
||||
|
||||
return globToRegExp(pattern).test(normalizedGroupName);
|
||||
}
|
||||
|
||||
function filterGroupsByAllowlist(userGroups, allowPatterns) {
|
||||
const groups = Array.isArray(userGroups)
|
||||
? userGroups
|
||||
.map((groupName) => normalizeGroupName(groupName))
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
if (!Array.isArray(allowPatterns) || allowPatterns.length === 0) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return groups.filter((groupName) =>
|
||||
allowPatterns.some((pattern) => groupNameMatchesAllowPattern(groupName, pattern)),
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseGroupAllowlist,
|
||||
normalizeGroupName,
|
||||
groupNameMatchesAllowPattern,
|
||||
filterGroupsByAllowlist,
|
||||
};
|
||||
@@ -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 = {
|
||||
@@ -420,7 +450,7 @@ export default class LDAP {
|
||||
// Escape the username to prevent LDAP injection
|
||||
const escapedUsername = escapedToHex(username);
|
||||
const searchOptions = {
|
||||
filter: filter.join('').replace(/#{username}/g, escapedUsername).replace(/\\/g, "\\\\"),
|
||||
filter: filter.join('').replace(/#{username}/g, escapedUsername),
|
||||
scope : 'sub',
|
||||
};
|
||||
|
||||
@@ -463,14 +493,28 @@ 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(')');
|
||||
|
||||
// Escape the username to prevent LDAP injection
|
||||
const escapedUsername = escapedToHex(username);
|
||||
const searchOptions = {
|
||||
filter: filter.join('').replace(/#{username}/g, escapedUsername).replace(/\\/g, "\\\\"),
|
||||
filter: filter.join('').replace(/#{username}/g, escapedUsername),
|
||||
scope : 'sub',
|
||||
};
|
||||
|
||||
|
||||
@@ -2,6 +2,16 @@ import {slug, getLdapUsername, getLdapEmail, getLdapUserUniqueID, syncUserData,
|
||||
import LDAP from './ldap';
|
||||
import { log_debug, log_info, log_warn, log_error } from './logger';
|
||||
|
||||
// Org/team sync is optional enrichment; failed sync must not block login.
|
||||
async function syncUserGroupsToOrgsTeamsSafe(ldap, ldapUser, userId) {
|
||||
try {
|
||||
await syncUserGroupsToOrgsTeams(ldap, ldapUser, userId);
|
||||
} catch (error) {
|
||||
const reason = error && (error.reason || error.message || error.error);
|
||||
log_warn('LDAP org/team sync failed during login; continuing without org/team sync', reason);
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackDefaultAccountSystem(bind, username, password) {
|
||||
if (typeof username === 'string') {
|
||||
if (username.indexOf('@') === -1) {
|
||||
@@ -199,9 +209,9 @@ Accounts.registerLoginHandler('ldap', async function(loginRequest) {
|
||||
}
|
||||
|
||||
// #4737: sync LDAP groups as Organizations/Teams at login too (default off).
|
||||
await syncUserGroupsToOrgsTeams(ldap, ldapUser, user._id);
|
||||
await syncUserGroupsToOrgsTeamsSafe(ldap, ldapUser, user._id);
|
||||
|
||||
await Meteor.users.updateAsync(user._id, update_data );
|
||||
await Meteor.users.updateAsync({ _id: user._id }, update_data);
|
||||
|
||||
await syncUserData(user, ldapUser);
|
||||
|
||||
@@ -229,6 +239,10 @@ Accounts.registerLoginHandler('ldap', async function(loginRequest) {
|
||||
|
||||
const result = await addLdapUser(ldapUser, username, loginRequest.ldapPass);
|
||||
|
||||
if (result instanceof Error) {
|
||||
throw result;
|
||||
}
|
||||
|
||||
if (LDAP.settings_get('LDAP_SYNC_ADMIN_STATUS') === true) {
|
||||
log_debug('Updating admin status');
|
||||
const targetGroups = LDAP.settings_get('LDAP_SYNC_ADMIN_GROUPS').split(',');
|
||||
@@ -247,12 +261,7 @@ Accounts.registerLoginHandler('ldap', async function(loginRequest) {
|
||||
}
|
||||
|
||||
// #4737: sync LDAP groups as Organizations/Teams for the new user (default off).
|
||||
await syncUserGroupsToOrgsTeams(ldap, ldapUser, result.userId);
|
||||
|
||||
|
||||
if (result instanceof Error) {
|
||||
throw result;
|
||||
}
|
||||
await syncUserGroupsToOrgsTeamsSafe(ldap, ldapUser, result.userId);
|
||||
|
||||
return result;
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { SyncedCron } from 'meteor/quave:synced-cron';
|
||||
import { DDP } from 'meteor/ddp';
|
||||
import limax from 'limax';
|
||||
import LDAP from './ldap';
|
||||
import { slugifyPreservingHyphens } from './usernameSlug';
|
||||
import { parseGroupAllowlist, filterGroupsByAllowlist } from './groupAllowlist';
|
||||
import { log_debug, log_info, log_warn, log_error } from './logger';
|
||||
import { getLdapPhotoBuffer } from './ldapPhoto';
|
||||
|
||||
@@ -18,15 +20,6 @@ Object.defineProperty(Object.prototype, "getLDAPValue", {
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
// #4737: parse a comma-separated LDAP group allowlist setting into a trimmed,
|
||||
// non-empty array. Returns [] when unset/empty, meaning "no restriction".
|
||||
function parseGroupAllowlist(value) {
|
||||
if (typeof value !== 'string' || value.trim() === '') {
|
||||
return [];
|
||||
}
|
||||
return value.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export function slug(text) {
|
||||
if (LDAP.settings_get('LDAP_UTF8_NAMES_SLUGIFY') !== true) {
|
||||
return text;
|
||||
@@ -253,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 }});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,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',
|
||||
}});
|
||||
@@ -422,6 +420,21 @@ export async function importNewUsers(ldap) {
|
||||
log_info('Import finished. Users imported:', count);
|
||||
}
|
||||
|
||||
// #6461: invoke the app-side LDAP org/team sync as a true server-to-server call.
|
||||
// A plain Meteor.callAsync here would inherit the CURRENT method invocation —
|
||||
// the server's applyAsync copies its userId AND connection into the nested call
|
||||
// — and during login that is the client's `login` method call, so the admin
|
||||
// guard in setUserOrgsTeamsFromLdap saw a client connection with no logged-in
|
||||
// user yet and rejected the sync with 'forbidden'. Clearing the invocation
|
||||
// context makes applyAsync use userId:null/connection:null — the documented
|
||||
// internal path the method's guard allows — while still going through the
|
||||
// normal method dispatch (check() audits, EJSON argument cloning).
|
||||
async function callLdapOrgTeamSyncInternal(userId, groupNames, asOrganization) {
|
||||
return await DDP._CurrentMethodInvocation.withValue(undefined, () =>
|
||||
Meteor.callAsync('setUserOrgsTeamsFromLdap', userId, groupNames, asOrganization),
|
||||
);
|
||||
}
|
||||
|
||||
// #4737: optionally sync a user's LDAP groups as Wekan Organizations and/or
|
||||
// Teams. Opt-in via LDAP_SYNC_ORGANIZATIONS / LDAP_SYNC_TEAMS (default off). The
|
||||
// optional comma-separated allowlists LDAP_SYNC_ORGANIZATIONS_GROUPS /
|
||||
@@ -445,17 +458,17 @@ export async function syncUserGroupsToOrgsTeams(ldap, ldapUser, userId) {
|
||||
|
||||
if (syncOrgs) {
|
||||
const allow = parseGroupAllowlist(LDAP.settings_get('LDAP_SYNC_ORGANIZATIONS_GROUPS'));
|
||||
const names = allow.length ? userGroups.filter((g) => allow.includes(g)) : userGroups;
|
||||
const names = filterGroupsByAllowlist(userGroups, allow);
|
||||
if (names.length > 0) {
|
||||
await Meteor.callAsync('setUserOrgsTeamsFromLdap', userId, names, true);
|
||||
await callLdapOrgTeamSyncInternal(userId, names, true);
|
||||
}
|
||||
}
|
||||
|
||||
if (syncTeams) {
|
||||
const allow = parseGroupAllowlist(LDAP.settings_get('LDAP_SYNC_TEAMS_GROUPS'));
|
||||
const names = allow.length ? userGroups.filter((g) => allow.includes(g)) : userGroups;
|
||||
const names = filterGroupsByAllowlist(userGroups, allow);
|
||||
if (names.length > 0) {
|
||||
await Meteor.callAsync('setUserOrgsTeamsFromLdap', userId, names, false);
|
||||
await callLdapOrgTeamSyncInternal(userId, names, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.95</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.95<!-- -->)</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.95","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.95
|
||||
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
|
||||
|
||||
@@ -69,11 +69,28 @@ FERRET_PID=""
|
||||
stop_ferret() { [ -n "$FERRET_PID" ] && kill "$FERRET_PID" 2>/dev/null || true; }
|
||||
trap 'stop_ferret; exit 0' INT TERM
|
||||
|
||||
# #6467/#6468: with FerretDB (no oplog) Meteor observes queries by POLLING, and
|
||||
# its defaults (re-poll 50 ms after any write, at least every 10 s) hammer the
|
||||
# database. Calmer polling defaults; other users' changes may take ~2 s extra to
|
||||
# appear. Overridable by exporting different values before running this script.
|
||||
if [ "$want_ferret" = true ]; then
|
||||
export METEOR_POLLING_THROTTLE_MS="${METEOR_POLLING_THROTTLE_MS:-2000}"
|
||||
export METEOR_POLLING_INTERVAL_MS="${METEOR_POLLING_INTERVAL_MS:-30000}"
|
||||
fi
|
||||
|
||||
# #6458: $DIR/cpu-exec runs a binary through the bundled same-arch qemu-user
|
||||
# when the CPU lacks features the binary declares (WEKAN_REQUIRED_CPU_FEATURES,
|
||||
# e.g. "x86_64=avx" for an external MongoDB 5+). node and ferretdb are baseline
|
||||
# builds needing no special features, so with none declared this is a plain
|
||||
# exec — but every binary launch here is feature-safe on every platform.
|
||||
CPU_EXEC="$DIR/cpu-exec"
|
||||
[ -x "$CPU_EXEC" ] || CPU_EXEC=""
|
||||
|
||||
while true; do
|
||||
if [ "$want_ferret" = true ]; then
|
||||
export DO_NOT_TRACK=1 FERRETDB_TELEMETRY=disable
|
||||
echo "Starting bundled FerretDB v1 (SQLite) on $FERRETDB_LISTEN_ADDR (data: $FERRETDB_SQLITE_DIR) ..."
|
||||
"$FERRETDB_BIN" \
|
||||
${CPU_EXEC:+"$CPU_EXEC"} "$FERRETDB_BIN" \
|
||||
--handler=sqlite \
|
||||
--sqlite-url="file:$FERRETDB_SQLITE_DIR/" \
|
||||
--listen-addr="$FERRETDB_LISTEN_ADDR" \
|
||||
@@ -85,7 +102,7 @@ while true; do
|
||||
fi
|
||||
|
||||
echo "Starting WeKan on $ROOT_URL (port $PORT), files under $WRITABLE_PATH ..."
|
||||
"$NODE" "$DIR/main.js" || true
|
||||
${CPU_EXEC:+"$CPU_EXEC"} "$NODE" "$DIR/main.js" || true
|
||||
|
||||
stop_ferret
|
||||
FERRET_PID=""
|
||||
|
||||
@@ -51,15 +51,32 @@ if [ "$want_ferret" = true ]; then
|
||||
# let it be re-enabled). DO_NOT_TRACK/FERRETDB_TELEMETRY are belt-and-suspenders.
|
||||
export DO_NOT_TRACK=1 FERRETDB_TELEMETRY=disable
|
||||
echo "Starting bundled FerretDB v1 (SQLite) on $FERRETDB_LISTEN_ADDR ..."
|
||||
"$FERRETDB_BIN" \
|
||||
--handler=sqlite \
|
||||
--sqlite-url="file:$FERRETDB_SQLITE_DIR/" \
|
||||
--listen-addr="$FERRETDB_LISTEN_ADDR" \
|
||||
--telemetry=disable \
|
||||
--log-level=error &
|
||||
# #6458: /build/cpu-exec runs a binary through the bundled same-arch
|
||||
# qemu-user when the CPU lacks features the binary declares (via
|
||||
# WEKAN_REQUIRED_CPU_FEATURES, e.g. "x86_64=avx"). node and ferretdb are
|
||||
# baseline builds needing no special features, so with none declared this is
|
||||
# a plain exec — but every binary launch here is feature-safe.
|
||||
if [ -x /build/cpu-exec ]; then
|
||||
/build/cpu-exec "$FERRETDB_BIN" \
|
||||
--handler=sqlite \
|
||||
--sqlite-url="file:$FERRETDB_SQLITE_DIR/" \
|
||||
--listen-addr="$FERRETDB_LISTEN_ADDR" \
|
||||
--telemetry=disable \
|
||||
--log-level=error &
|
||||
else
|
||||
"$FERRETDB_BIN" \
|
||||
--handler=sqlite \
|
||||
--sqlite-url="file:$FERRETDB_SQLITE_DIR/" \
|
||||
--listen-addr="$FERRETDB_LISTEN_ADDR" \
|
||||
--telemetry=disable \
|
||||
--log-level=error &
|
||||
fi
|
||||
FERRET_PID=$!
|
||||
trap 'kill "$FERRET_PID" 2>/dev/null || true' EXIT INT TERM
|
||||
fi
|
||||
|
||||
ulimit -s 65500
|
||||
if [ -x /build/cpu-exec ]; then
|
||||
exec /build/cpu-exec node /build/main.js
|
||||
fi
|
||||
exec node /build/main.js
|
||||
@@ -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,10 +1671,19 @@ 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';
|
||||
state.success = totalErrors < 10; // treat <10 isolated errors as success
|
||||
// #6466: per-item errors (one unparsable document, one attachment/avatar that
|
||||
// fails to extract) must NOT fail the whole migration — everything that DID
|
||||
// copy is valid. The old `totalErrors < 10` threshold turned ten cosmetic
|
||||
// per-item errors into a non-zero exit, which made the snap's
|
||||
// migration-control discard the fully-copied FerretDB SQLite and leave WeKan
|
||||
// serving 502 Bad Gateway. Fatal conditions (disk-full, unreachable
|
||||
// source/target) already set state.success = false and never reach here.
|
||||
if (state.success !== false) state.success = true;
|
||||
console.log(`[migrate] ⚠ Migration done with ${totalErrors} error(s). See dashboard.`);
|
||||
}
|
||||
state.finishedAt = new Date().toISOString();
|
||||
@@ -1264,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 = 995,
|
||||
appVersion = 997,
|
||||
# Increment this for every release.
|
||||
|
||||
appMarketingVersion = (defaultText = "9.95~2026-07-15"),
|
||||
appMarketingVersion = (defaultText = "9.97~2026-07-17"),
|
||||
# Human-readable presentation of the app version.
|
||||
|
||||
minUpgradableAppVersion = 0,
|
||||
|
||||
@@ -113,6 +113,19 @@ chmod +x "$DEPS/migratemongo/bin/"*
|
||||
echo "==> [6/7] Launcher + importer"
|
||||
cp -f "$REPO/sandstorm-src/start.js" "$DEPS/start.js"
|
||||
cp -f "$REPO/snap-src/bin/migrate-mongo3-to-ferretdb.mjs" "$DEPS/migrate-mongo3-to-ferretdb.mjs"
|
||||
# #6458: cpu-exec + qemu-user — run any binary that needs CPU features the
|
||||
# grain host lacks (e.g. AVX for MongoDB 5+) through qemu-user emulation.
|
||||
# The bundled mongod 3.0/niscud need no special features, so this is
|
||||
# future-proofing; tolerant when qemu-user-static is not installed.
|
||||
cp -f "$REPO/snap-src/bin/cpu-exec" "$DEPS/bin/cpu-exec"
|
||||
chmod +x "$DEPS/bin/cpu-exec"
|
||||
if [ -x /usr/bin/qemu-x86_64-static ]; then
|
||||
cp -f /usr/bin/qemu-x86_64-static "$DEPS/bin/qemu-x86_64"
|
||||
chmod +x "$DEPS/bin/qemu-x86_64"
|
||||
echo " bundled qemu-x86_64 for cpu-exec"
|
||||
else
|
||||
echo " qemu-user-static not installed; spk ships cpu-exec without a bundled qemu-user"
|
||||
fi
|
||||
|
||||
echo "==> [7/7] niscud + old node_modules kept for the niscu->3.0 stage:"
|
||||
ls -la "$DEPS/bin/niscud" "$DEPS/node_modules/mongodb" >/dev/null 2>&1 \
|
||||
|
||||
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user