Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c8ad7dd6d |
No files matched your search
@@ -1,19 +0,0 @@
|
||||
# Normalise line endings in the repository.
|
||||
* text=auto eol=lf
|
||||
|
||||
# What stays in the repository but is not part of the package that Composer installs (Packagist builds
|
||||
# the dist archive from `git archive`, which leaves these out).
|
||||
# Because of that, every CI job that checks out must run in an image with git (webdevops/php has it):
|
||||
# without git, actions/checkout downloads that same archive and the .gitea/ scripts are missing.
|
||||
/.gitattributes export-ignore
|
||||
/.gitea export-ignore
|
||||
/.gitignore export-ignore
|
||||
/dev export-ignore
|
||||
/scripts export-ignore
|
||||
/TOKENS.md export-ignore
|
||||
/AGENTS.md export-ignore
|
||||
/CLAUDE.md export-ignore
|
||||
/tests export-ignore
|
||||
/ui export-ignore
|
||||
/phpunit.xml export-ignore
|
||||
/pint.json export-ignore
|
||||
@@ -1,26 +0,0 @@
|
||||
## Vraag
|
||||
<!-- Wat was de vraag of de opdracht? Eén of twee zinnen, in de woorden van wie het vroeg. -->
|
||||
|
||||
## Wat is er gedaan
|
||||
<!-- Beknopte lijst: per punt één regel. -->
|
||||
-
|
||||
|
||||
## Zo test je het
|
||||
<!-- Een checklist die af te vinken is: waar klik je, wat moet je zien. -->
|
||||
- [ ]
|
||||
|
||||
## Zelf getest
|
||||
<!-- Wat is er al gecontroleerd, en hoe (tests, handmatig, op welke omgeving). Ook wat niet getest is. -->
|
||||
-
|
||||
|
||||
## Tijd en tokens
|
||||
<!-- De regel(s) uit TOKENS.md van deze PR: uren, tokens, model. -->
|
||||
|
||||
## Onderhoud
|
||||
<!-- Is er onderhoud meegenomen (updates, opruimen, documentatie)? Anders: Niets. -->
|
||||
|
||||
## Met de hand te doen
|
||||
<!-- Wat moet er na het mergen nog met de hand gebeuren (secrets, .env, instellingen)? Anders: Niets. -->
|
||||
|
||||
## Vervolgstappen
|
||||
<!-- Wat ligt er nog, wat is bewust niet gedaan? Anders: Geen. -->
|
||||
@@ -1,76 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Turns on auto-merge for a pull request to a release branch (`release/vX.Y.Z`).
|
||||
|
||||
Run by the `release-automerge` job whenever such a pull request is opened or updated. Gitea then
|
||||
merges it by itself once the required check is green, so features flow into the release branch
|
||||
without anyone pressing the button. A pull request to anything else is left alone: `production`
|
||||
is merged by hand.
|
||||
|
||||
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (a token that may edit pull requests),
|
||||
PULL_REQUEST_NUMBER. Optional: AUTO_MERGE_PREFIX (default "release/"), MERGE_STYLE (default "merge").
|
||||
Standard library only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
URL = os.environ.get("GT_URL", "").rstrip("/")
|
||||
OWNER = os.environ.get("GT_OWNER", "")
|
||||
REPO = os.environ.get("GT_REPO", "")
|
||||
TOKEN = os.environ.get("GT_TOKEN", "")
|
||||
NUMBER = os.environ.get("PULL_REQUEST_NUMBER", "").lstrip("#")
|
||||
PREFIX = os.environ.get("AUTO_MERGE_PREFIX") or "release/"
|
||||
MERGE_STYLE = os.environ.get("MERGE_STYLE") or "merge"
|
||||
|
||||
ALREADY_ON = object()
|
||||
|
||||
|
||||
def api(method, path, body=None):
|
||||
request = urllib.request.Request(
|
||||
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
method=method,
|
||||
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
text = response.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = e.read().decode()
|
||||
# A second push runs this job again while auto-merge is still on: that is what was wanted.
|
||||
if e.code == 409 and "already scheduled to auto merge" in detail:
|
||||
return ALREADY_ON
|
||||
sys.exit(f"Gitea API {method} {path} failed: {e.code} {detail}")
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def main():
|
||||
if not (URL and OWNER and REPO and TOKEN and NUMBER.isdigit()):
|
||||
sys.exit("GT_URL, GT_OWNER, GT_REPO, GT_TOKEN and PULL_REQUEST_NUMBER are required.")
|
||||
|
||||
pull = api("GET", f"pulls/{NUMBER}") or {}
|
||||
base_ref = (pull.get("base") or {}).get("ref", "")
|
||||
|
||||
if not base_ref.startswith(PREFIX):
|
||||
print(f"Pull request #{NUMBER} targets {base_ref}, not {PREFIX}*: left alone.")
|
||||
return
|
||||
if pull.get("state") != "open" or pull.get("merged"):
|
||||
print(f"Pull request #{NUMBER} is not open: nothing to do.")
|
||||
return
|
||||
|
||||
answer = api("POST", f"pulls/{NUMBER}/merge", {
|
||||
"do": MERGE_STYLE,
|
||||
"merge_when_checks_succeed": True,
|
||||
"delete_branch_after_merge": False,
|
||||
})
|
||||
if answer is ALREADY_ON:
|
||||
print(f"Auto-merge was already on for pull request #{NUMBER}.")
|
||||
return
|
||||
print(f"Auto-merge is on for pull request #{NUMBER}: it merges once the required check is green.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,89 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PR CI: does this pull request follow the development cycle?
|
||||
|
||||
develop -> feature/*, fix/*, ... -> release/vX.Y.Z -> production
|
||||
(collects features) (release: tag + Packagist)
|
||||
production -> develop (the sync after a release, by the pipeline)
|
||||
|
||||
Pull requests go to a release branch or to production, never to develop.
|
||||
- to `release/vX.Y.Z`: the release must not be out yet (its version is above the latest tag),
|
||||
and the pull request does not come from production, develop or another release branch.
|
||||
- to `production`: only from `release/vX.Y.Z`, with a version above the latest tag, a section
|
||||
for it in CHANGELOG.md, and no "version" in composer.json (Packagist reads the tag).
|
||||
The one other way in is `renovate/*`: the nightly dependency update of the homelab (release.py makes a
|
||||
patch release of it, unless a release branch is open).
|
||||
|
||||
Environment: BASE_REF, HEAD_REF. Run in a checkout with the tags (fetch-depth 0).
|
||||
Standard library + git only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import semver # noqa: E402
|
||||
|
||||
|
||||
def tags():
|
||||
result = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True)
|
||||
return result.stdout.split()
|
||||
|
||||
|
||||
def problems(base, head, existing_tags, changelog, composer):
|
||||
found = []
|
||||
newest = semver.latest(existing_tags)
|
||||
|
||||
if base == "production":
|
||||
if head.startswith("renovate/"):
|
||||
return []
|
||||
version = semver.release_version(head)
|
||||
if version is None:
|
||||
return [f"A pull request to production comes from a branch named release/vX.Y.Z, not from {head or '?'}."]
|
||||
found += above_latest(version, newest)
|
||||
if changelog is None or semver.changelog_section(changelog, version) is None:
|
||||
found.append(f"CHANGELOG.md has no section '## v{semver.text(version)}' for this release.")
|
||||
if isinstance(composer, dict) and "version" in composer:
|
||||
found.append("composer.json must not have a \"version\": Packagist takes the version from the tag.")
|
||||
return found
|
||||
|
||||
if base.startswith("release/"):
|
||||
version = semver.release_version(base)
|
||||
if version is None:
|
||||
return [f"{base} is not a release branch name: use release/vX.Y.Z."]
|
||||
found += above_latest(version, newest, "That release is already out: start the next one.")
|
||||
if head in ("production", "develop") or head.startswith("release/"):
|
||||
found.append(f"A release branch takes features (feature/*, fix/*), not {head}.")
|
||||
return found
|
||||
|
||||
return [f"Pull requests go to release/vX.Y.Z or to production, not to {base or '?'}: develop only takes the sync after a release."]
|
||||
|
||||
|
||||
def above_latest(version, newest, hint="The version of a release must be above the latest tag."):
|
||||
if newest is not None and version <= newest:
|
||||
return [f"v{semver.text(version)} is not above the latest tag v{semver.text(newest)}. {hint}"]
|
||||
return []
|
||||
|
||||
|
||||
def main():
|
||||
base = os.environ.get("BASE_REF", "").strip()
|
||||
head = os.environ.get("HEAD_REF", "").strip()
|
||||
|
||||
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else None
|
||||
try:
|
||||
composer = json.load(open("composer.json", encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
composer = None
|
||||
|
||||
found = problems(base, head, tags(), changelog, composer)
|
||||
for line in found:
|
||||
print(f"::error::{line}")
|
||||
if found:
|
||||
return 1
|
||||
print(f"{head} -> {base}: follows the development cycle.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,82 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PR CI: a pull request must add its row to TOKENS.md.
|
||||
|
||||
TOKENS.md holds one row per piece of work: the tokens of the AI model that
|
||||
went into it and the hours that were worked on it. This check compares the
|
||||
rows of the pull request with the rows on the branch it goes to, and fails
|
||||
when the pull request brings no new row. The new rows are printed, so every
|
||||
pull request shows in its log what it cost.
|
||||
|
||||
Exempt, because nobody worked on them: the release pull request of the
|
||||
pipeline (release/*), the dependency updates (renovate/*), and a pull
|
||||
request that only carries one long-lived branch into another (production
|
||||
into staging, staging into production, develop).
|
||||
|
||||
Environment (set by the workflow):
|
||||
BASE_REF the branch the pull request goes to
|
||||
HEAD_REF the branch the pull request comes from
|
||||
PR_AUTHOR who opened it
|
||||
|
||||
Standard library only.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
LEDGER = "TOKENS.md"
|
||||
EXEMPT_PREFIXES = ("release/", "renovate/")
|
||||
EXEMPT_BRANCHES = ("production", "staging", "develop")
|
||||
EXEMPT_AUTHORS = ("deploy-bot", "renovate-bot")
|
||||
|
||||
|
||||
def rows(text):
|
||||
"""The rows of the table: the lines that start with a date."""
|
||||
return [line.strip() for line in text.splitlines() if line.startswith("| 20")]
|
||||
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
|
||||
|
||||
def main():
|
||||
base = os.environ.get("BASE_REF", "").strip()
|
||||
head = os.environ.get("HEAD_REF", "").strip()
|
||||
author = os.environ.get("PR_AUTHOR", "").strip()
|
||||
|
||||
if head.startswith(EXEMPT_PREFIXES) or head in EXEMPT_BRANCHES or author in EXEMPT_AUTHORS:
|
||||
print(f"No row needed: {head or 'this pull request'} by {author or 'unknown'} is not a piece of work.")
|
||||
return 0
|
||||
|
||||
if not base:
|
||||
print("BASE_REF is not set: cannot tell which branch this pull request goes to.")
|
||||
return 1
|
||||
|
||||
if not os.path.exists(LEDGER):
|
||||
print(f"{LEDGER} is missing. See AGENTS.md, 'Token usage and hours'.")
|
||||
return 1
|
||||
|
||||
fetch = git("fetch", "--quiet", "--no-tags", "--depth=1", "origin", base)
|
||||
if fetch.returncode != 0:
|
||||
print(f"Could not fetch {base}: {fetch.stderr.strip()}")
|
||||
return 1
|
||||
|
||||
shown = git("show", f"FETCH_HEAD:{LEDGER}")
|
||||
before = set(rows(shown.stdout)) if shown.returncode == 0 else set()
|
||||
with open(LEDGER, encoding="utf-8") as handle:
|
||||
new = [row for row in rows(handle.read()) if row not in before]
|
||||
|
||||
if not new:
|
||||
print(f"This pull request adds no row to {LEDGER}.")
|
||||
print("Every pull request records what went into it: the tokens of the AI model and the hours.")
|
||||
print("Add the row with dev/token-usage.py (see AGENTS.md, 'Token usage and hours') and push again.")
|
||||
return 1
|
||||
|
||||
print(f"{len(new)} new row(s) in {LEDGER}:")
|
||||
for row in new:
|
||||
print(" " + row)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,65 +0,0 @@
|
||||
"""Tells Packagist that the package has a new version, and submits the package when it is not there yet.
|
||||
|
||||
Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its
|
||||
own poll. The first time Packagist answers 404 (it does not know the package): then the package is
|
||||
submitted through the create-package API, and Packagist reads every tag that is already there.
|
||||
While PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
|
||||
|
||||
Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret
|
||||
of the repository), PACKAGE_URL (the public address of the repository).
|
||||
The token goes in the request and never in the log. Standard library only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
USER = os.environ.get("PACKAGIST_USERNAME", "").strip()
|
||||
TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip()
|
||||
PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip()
|
||||
|
||||
|
||||
def call(endpoint, user, token, url):
|
||||
"""POST to the API of Packagist; returns the HTTP status. Raises HTTPError with the answer on a refusal."""
|
||||
query = urllib.parse.urlencode({"username": user, "apiToken": token})
|
||||
request = urllib.request.Request(
|
||||
f"https://packagist.org/api/{endpoint}?{query}",
|
||||
data=json.dumps({"repository": {"url": url}}).encode(),
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.status
|
||||
|
||||
|
||||
def notify(user, token, url):
|
||||
"""Tells Packagist about the package; submits it first when Packagist does not know it. Returns what happened."""
|
||||
try:
|
||||
return f"Packagist answered {call('update-package', user, token, url)}: it will read the new tag."
|
||||
except urllib.error.HTTPError as e:
|
||||
# Never echo the request (it holds the token); the answer of Packagist says enough.
|
||||
if e.code != 404:
|
||||
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
|
||||
|
||||
try:
|
||||
return f"Packagist did not know the package: submitted it (answer {call('create-package', user, token, url)}). It reads every tag that is there."
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.exit(f"Packagist did not know the package, and refused to submit it: {e.code} {e.read().decode()[:300]}")
|
||||
|
||||
|
||||
def main():
|
||||
if not (USER and TOKEN):
|
||||
print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. "
|
||||
"Set both as secrets of the repository.")
|
||||
return
|
||||
if not PACKAGE_URL.startswith("https://"):
|
||||
sys.exit("PACKAGE_URL must be the public https address of the repository.")
|
||||
|
||||
print(notify(USER, TOKEN, PACKAGE_URL))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,93 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Removes feature branches that nobody has touched for 30 days.
|
||||
|
||||
A branch is removed when all of this is true:
|
||||
- its name starts with one of PRUNE_PREFIXES (default `feature/,fix/`): production, develop and the
|
||||
release branches are never touched;
|
||||
- its last commit is older than PRUNE_DAYS (default 30);
|
||||
- no pull request from it is open (an open pull request is work in progress, however quiet).
|
||||
|
||||
A branch that had a pull request can be brought back from that pull request in Gitea ("Restore branch"),
|
||||
and a merged one is in its target anyway. DRY_RUN=1 only says what would be removed.
|
||||
|
||||
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may delete branches), and optionally PRUNE_DAYS,
|
||||
PRUNE_PREFIXES, DRY_RUN. Standard library only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
URL = os.environ.get("GT_URL", "").rstrip("/")
|
||||
OWNER = os.environ.get("GT_OWNER", "")
|
||||
REPO = os.environ.get("GT_REPO", "")
|
||||
TOKEN = os.environ.get("GT_TOKEN", "")
|
||||
DAYS = int(os.environ.get("PRUNE_DAYS") or 30)
|
||||
PREFIXES = tuple(p.strip() for p in (os.environ.get("PRUNE_PREFIXES") or "feature/,fix/").split(",") if p.strip())
|
||||
DRY_RUN = os.environ.get("DRY_RUN", "").strip().lower() in ("1", "true", "yes")
|
||||
NEVER = ("production", "develop")
|
||||
|
||||
|
||||
def api(method, path):
|
||||
request = urllib.request.Request(
|
||||
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
|
||||
method=method,
|
||||
headers={"Authorization": f"token {TOKEN}"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
text = response.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def pages(path):
|
||||
"""Every item of a paged list."""
|
||||
page, found = 1, []
|
||||
while True:
|
||||
items = api("GET", f"{path}{'&' if '?' in path else '?'}page={page}&limit=50") or []
|
||||
found += items
|
||||
if len(items) < 50:
|
||||
return found
|
||||
page += 1
|
||||
|
||||
|
||||
def stale(branches, open_heads, now):
|
||||
"""The names to remove, with how many days they were quiet."""
|
||||
limit = now - timedelta(days=DAYS)
|
||||
names = []
|
||||
for branch in branches:
|
||||
name = branch["name"]
|
||||
if name in NEVER or name.startswith("release/") or not name.startswith(PREFIXES) or name in open_heads:
|
||||
continue
|
||||
moment = datetime.fromisoformat(branch["commit"]["timestamp"].replace("Z", "+00:00"))
|
||||
if moment < limit:
|
||||
names.append((name, (now - moment).days))
|
||||
return names
|
||||
|
||||
|
||||
def main():
|
||||
if not (URL and OWNER and REPO and TOKEN):
|
||||
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
|
||||
|
||||
open_heads = {(pull.get("head") or {}).get("ref") for pull in pages("pulls?state=open")}
|
||||
old = stale(pages("branches"), open_heads, datetime.now(timezone.utc))
|
||||
|
||||
if not old:
|
||||
print(f"No {'/'.join(p.rstrip('/') for p in PREFIXES)} branch has been quiet for {DAYS} days.")
|
||||
return
|
||||
for name, days in old:
|
||||
if DRY_RUN:
|
||||
print(f"Would remove {name} (quiet for {days} days).")
|
||||
else:
|
||||
api("DELETE", "branches/" + urllib.parse.quote(name, safe=""))
|
||||
print(f"Removed {name} (quiet for {days} days).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,154 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Release step of the `Release` workflow: tag what was just merged into production.
|
||||
|
||||
A push to production is a release when it is the merge of a `release/vX.Y.Z` pull request. This
|
||||
finds that version (from the pull request Gitea knows for the commit, or from the merge message),
|
||||
and makes the release `vX.Y.Z` on that commit, with the changelog section as its text. Gitea
|
||||
makes the tag; Packagist picks the tag up in the next step.
|
||||
|
||||
The other way into production is the nightly dependency update of the homelab, a pull request from
|
||||
`renovate/*`. That makes a patch release too: the version above the latest tag with the patch raised by
|
||||
one (v0.5.0 -> v0.5.1), its text the title and description of the pull request. Renovate makes one pull
|
||||
request per night, so that is at most one patch release a night. When a release branch is open (a version
|
||||
above the latest tag) it makes none: the update goes out with that release.
|
||||
|
||||
Runs again on the same commit without harm: a tag that is already there on that commit is fine.
|
||||
A push that is neither (a hotfix pushed by an admin, say) makes no release and says so.
|
||||
|
||||
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create releases), COMMIT_HASH.
|
||||
Standard library + git only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import semver # noqa: E402
|
||||
|
||||
URL = os.environ.get("GT_URL", "").rstrip("/")
|
||||
OWNER = os.environ.get("GT_OWNER", "")
|
||||
REPO = os.environ.get("GT_REPO", "")
|
||||
TOKEN = os.environ.get("GT_TOKEN", "")
|
||||
COMMIT = os.environ.get("COMMIT_HASH", "").strip()
|
||||
|
||||
|
||||
def api(method, path, body=None, allow=()):
|
||||
request = urllib.request.Request(
|
||||
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
method=method,
|
||||
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
text = response.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code in allow:
|
||||
return None
|
||||
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def pull_of(commit):
|
||||
"""The pull request that made this commit, or None."""
|
||||
return api("GET", f"commits/{commit}/pull", allow=(404,))
|
||||
|
||||
|
||||
def release_branch_of(commit, pull=None):
|
||||
"""The release branch whose pull request made this commit, or None."""
|
||||
head = ((pull or {}).get("head") or {}).get("ref", "")
|
||||
if semver.release_version(head):
|
||||
return head
|
||||
|
||||
# Gitea's own merge message: "Merge pull request 'title' (#7) from release/v1.2.0 into production".
|
||||
message = subprocess.run(["git", "log", "-1", "--pretty=%s", commit], capture_output=True, text=True).stdout
|
||||
found = re.search(r"from (release/v\d+\.\d+\.\d+) into production", message)
|
||||
return found.group(1) if found else None
|
||||
|
||||
|
||||
def next_patch(newest):
|
||||
"""v0.5.0 -> (0, 5, 1); None without a tag to count from."""
|
||||
return None if newest is None else (newest[0], newest[1], newest[2] + 1)
|
||||
|
||||
|
||||
def release_is_open(branches, newest):
|
||||
"""True when one of the branches is a release/vX.Y.Z above the latest tag."""
|
||||
return any((v := semver.release_version(b)) and (newest is None or v > newest) for b in branches)
|
||||
|
||||
|
||||
def dependency_release(commit, pull):
|
||||
"""Makes the patch release for a merged renovate/* pull request; says why when it makes none."""
|
||||
tags = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True).stdout.split()
|
||||
already = subprocess.run(["git", "tag", "--points-at", commit], capture_output=True, text=True).stdout.split()
|
||||
if any(semver.tag_version(tag) for tag in already):
|
||||
print(f"{commit[:8]} is already tagged ({' '.join(already)}): nothing to do.")
|
||||
return
|
||||
|
||||
newest = semver.latest(tags)
|
||||
version = next_patch(newest)
|
||||
if version is None:
|
||||
print("No tag to count from: no release made.")
|
||||
return
|
||||
|
||||
branches = [b["name"] for b in api("GET", "branches?limit=100") or []]
|
||||
if release_is_open(branches, newest):
|
||||
print("A release branch is open: this update goes out with it, no patch release made.")
|
||||
return
|
||||
|
||||
tag = f"v{semver.text(version)}"
|
||||
title = (pull.get("title") or "Dependency update").strip()
|
||||
body = (pull.get("body") or "").strip()
|
||||
notes = f"- {title}" + (f"\n\n{body}" if body else "")
|
||||
publish(tag, commit, notes)
|
||||
|
||||
|
||||
def publish(tag, commit, notes):
|
||||
api("POST", "releases", {
|
||||
"tag_name": tag,
|
||||
"target_commitish": commit,
|
||||
"name": tag,
|
||||
"body": notes,
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
})
|
||||
print(f"Released {tag} on {commit[:8]}.")
|
||||
|
||||
|
||||
def main():
|
||||
if not (URL and OWNER and REPO and TOKEN):
|
||||
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", COMMIT):
|
||||
sys.exit("COMMIT_HASH must be the full commit hash.")
|
||||
|
||||
pull = pull_of(COMMIT)
|
||||
branch = release_branch_of(COMMIT, pull)
|
||||
if branch is None:
|
||||
if ((pull or {}).get("head") or {}).get("ref", "").startswith("renovate/"):
|
||||
dependency_release(COMMIT, pull)
|
||||
else:
|
||||
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z or renovate/* pull request: no release made.")
|
||||
return
|
||||
|
||||
version = semver.release_version(branch)
|
||||
tag = f"v{semver.text(version)}"
|
||||
|
||||
existing = api("GET", f"releases/tags/{tag}", allow=(404,))
|
||||
if existing:
|
||||
print(f"{tag} already exists: nothing to do.")
|
||||
return
|
||||
|
||||
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else ""
|
||||
notes = semver.changelog_section(changelog, version)
|
||||
if notes is None:
|
||||
sys.exit(f"CHANGELOG.md has no section for {tag}: the release pull request should have been stopped by PR CI.")
|
||||
|
||||
publish(tag, COMMIT, notes)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,44 +0,0 @@
|
||||
"""Version helpers shared by the release scripts. Standard library only."""
|
||||
|
||||
import re
|
||||
|
||||
# A version is always three numbers: 1.4.0. The tag has a v in front (v1.4.0), the branch is release/v1.4.0.
|
||||
VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")
|
||||
RELEASE_BRANCH = re.compile(r"release/v(\d+)\.(\d+)\.(\d+)")
|
||||
TAG = re.compile(r"v(\d+)\.(\d+)\.(\d+)")
|
||||
|
||||
|
||||
def release_version(branch):
|
||||
"""The version of a `release/vX.Y.Z` branch as a tuple, or None when it is not one."""
|
||||
match = RELEASE_BRANCH.fullmatch(branch or "")
|
||||
return tuple(int(part) for part in match.groups()) if match else None
|
||||
|
||||
|
||||
def tag_version(tag):
|
||||
match = TAG.fullmatch(tag or "")
|
||||
return tuple(int(part) for part in match.groups()) if match else None
|
||||
|
||||
|
||||
def latest(tags):
|
||||
"""The highest version among the tags that are versions, or None."""
|
||||
versions = [version for version in (tag_version(tag) for tag in tags) if version]
|
||||
return max(versions) if versions else None
|
||||
|
||||
|
||||
def text(version):
|
||||
return ".".join(str(part) for part in version)
|
||||
|
||||
|
||||
def changelog_section(changelog, version):
|
||||
"""The body under `## vX.Y.Z` of the changelog, up to the next `## `; None when there is no such heading."""
|
||||
heading = re.compile(rf"^##\s+v?{re.escape(text(version))}(\s|$)")
|
||||
lines = changelog.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if heading.match(line):
|
||||
body = []
|
||||
for following in lines[index + 1:]:
|
||||
if following.startswith("## "):
|
||||
break
|
||||
body.append(following)
|
||||
return "\n".join(body).strip()
|
||||
return None
|
||||
@@ -1,67 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Starts a release: makes the branch release/vX.Y.Z from develop.
|
||||
|
||||
Features are pull requests to that branch (they merge by themselves when CI is green). When the release
|
||||
is ready, a pull request from it to production makes the release.
|
||||
|
||||
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create branches), VERSION (1.4.0, or v1.4.0).
|
||||
Standard library only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import semver # noqa: E402
|
||||
|
||||
URL = os.environ.get("GT_URL", "").rstrip("/")
|
||||
OWNER = os.environ.get("GT_OWNER", "")
|
||||
REPO = os.environ.get("GT_REPO", "")
|
||||
TOKEN = os.environ.get("GT_TOKEN", "")
|
||||
|
||||
|
||||
def api(method, path, body=None, allow=()):
|
||||
request = urllib.request.Request(
|
||||
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
method=method,
|
||||
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
text = response.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code in allow:
|
||||
return None
|
||||
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def main():
|
||||
if not (URL and OWNER and REPO and TOKEN):
|
||||
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
|
||||
|
||||
given = os.environ.get("VERSION", "").strip().lstrip("v")
|
||||
if not semver.VERSION.fullmatch(given):
|
||||
sys.exit(f"'{given}' is not a version: use three numbers, like 1.4.0.")
|
||||
version = tuple(int(part) for part in given.split("."))
|
||||
|
||||
tags = [tag["name"] for tag in api("GET", "tags?limit=50") or []]
|
||||
newest = semver.latest(tags)
|
||||
if newest is not None and version <= newest:
|
||||
sys.exit(f"v{given} is not above the latest tag v{semver.text(newest)}.")
|
||||
|
||||
name = f"release/v{given}"
|
||||
if api("GET", f"branches/{name}", allow=(404,)):
|
||||
sys.exit(f"{name} already exists.")
|
||||
|
||||
api("POST", "branches", {"new_branch_name": name, "old_branch_name": "develop"})
|
||||
print(f"{name} made from develop. Make features as pull requests to it; when it is ready, open one to production.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,82 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sync step of the `Release` workflow: merge production into develop.
|
||||
|
||||
Runs after a release, so `develop` always contains what is live. Features are made from develop, so
|
||||
it must be on the latest production before the next release is started.
|
||||
`develop` takes direct pushes (only `production` and the release branches are protected),
|
||||
so this is a plain merge and push: fast-forward when possible, otherwise a
|
||||
merge commit `chore: sync production into develop`.
|
||||
|
||||
A conflict fails the step on purpose. The release itself is done by then; the
|
||||
red build is the signal that `develop` holds something production does not
|
||||
and needs a merge by hand.
|
||||
|
||||
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (an access token
|
||||
that may push to develop), COMMIT_HASH (the commit this job released; defaults
|
||||
to the tip of production). SYNC_REMOTE overrides the clone URL (local testing).
|
||||
|
||||
Standard library + git only.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import urllib.request
|
||||
|
||||
URL = os.environ.get("GT_URL", "").rstrip("/")
|
||||
OWNER = os.environ.get("GT_OWNER", "")
|
||||
REPO = os.environ.get("GT_REPO", "")
|
||||
TOKEN = os.environ.get("GT_TOKEN", "")
|
||||
REMOTE = os.environ.get("SYNC_REMOTE", "")
|
||||
MESSAGE = "chore: sync production into develop"
|
||||
|
||||
|
||||
def git(repo, *args, check=True):
|
||||
result = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True)
|
||||
if check and result.returncode != 0:
|
||||
raise SystemExit(f"git {' '.join(args[:2])} failed: {result.stderr.strip()}")
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
user = os.environ.get("GT_BOT_USER") or "sync"
|
||||
remote = REMOTE
|
||||
if not remote:
|
||||
if not (URL and OWNER and REPO and TOKEN):
|
||||
raise SystemExit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required")
|
||||
remote = f"https://{user}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git"
|
||||
|
||||
repo = os.path.join(tempfile.mkdtemp(), "repo")
|
||||
result = subprocess.run(["git", "clone", "--quiet", "--branch", "develop", remote, repo],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
raise SystemExit(f"Could not clone develop: {result.stderr.strip()}")
|
||||
git(repo, "config", "user.name", user)
|
||||
git(repo, "config", "user.email", f"{user}@iriks-it.nl")
|
||||
|
||||
commit = os.environ.get("COMMIT_HASH", "").strip()
|
||||
source = commit if re.fullmatch(r"[0-9a-f]{40}", commit) else "origin/production"
|
||||
short = git(repo, "rev-parse", "--short", source).stdout.strip()
|
||||
|
||||
if git(repo, "merge-base", "--is-ancestor", source, "HEAD", check=False).returncode == 0:
|
||||
print(f"develop already contains production ({short}) — nothing to do.")
|
||||
return
|
||||
|
||||
merge = git(repo, "merge", "--no-edit", "-m", MESSAGE, source, check=False)
|
||||
if merge.returncode != 0:
|
||||
conflicts = git(repo, "diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
|
||||
raise SystemExit(
|
||||
f"production ({short}) does not merge cleanly into develop — merge it by hand.\n"
|
||||
f"Conflicting files:\n{conflicts or merge.stdout.strip() or merge.stderr.strip()}"
|
||||
)
|
||||
|
||||
push = git(repo, "push", "--quiet", "origin", "HEAD:refs/heads/develop", check=False)
|
||||
if push.returncode != 0:
|
||||
raise SystemExit(f"Could not push develop: {push.stderr.strip()}")
|
||||
print(f"develop now contains production ({short}).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,198 +0,0 @@
|
||||
"""Tests of the release scripts: `python3 -m unittest discover -s .gitea/scripts` (run by the `flow` job)."""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import check_flow # noqa: E402
|
||||
import packagist # noqa: E402
|
||||
import prune_branches # noqa: E402
|
||||
import release # noqa: E402
|
||||
import semver # noqa: E402
|
||||
|
||||
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
|
||||
CHANGELOG = "# Changelog\n\n## v0.11.0 - 2026-12-10\n\n- A feature\n- Another\n\n## v0.10.0 - 2026-12-01\n\n- Older\n"
|
||||
|
||||
|
||||
class Versions(unittest.TestCase):
|
||||
def test_release_branch(self):
|
||||
self.assertEqual(semver.release_version("release/v1.2.3"), (1, 2, 3))
|
||||
for wrong in ("release/1.2.3", "release/v1.2", "feature/x", "release/v1.2.3-rc1", "", None):
|
||||
self.assertIsNone(semver.release_version(wrong))
|
||||
|
||||
def test_latest_is_numeric_not_alphabetical(self):
|
||||
self.assertEqual(semver.latest(TAGS), (0, 10, 0))
|
||||
self.assertIsNone(semver.latest(["x"]))
|
||||
|
||||
def test_changelog_section(self):
|
||||
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 11, 0)), "- A feature\n- Another")
|
||||
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 10, 0)), "- Older")
|
||||
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 0)))
|
||||
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 1)))
|
||||
|
||||
|
||||
class Flow(unittest.TestCase):
|
||||
def check(self, base, head, tags=TAGS, changelog=CHANGELOG, composer=None):
|
||||
return check_flow.problems(base, head, tags, changelog, composer or {"name": "x/y"})
|
||||
|
||||
def test_release_to_production(self):
|
||||
self.assertEqual(self.check("production", "release/v0.11.0"), [])
|
||||
|
||||
def test_production_also_takes_the_nightly_renovate_branch(self):
|
||||
self.assertEqual(self.check("production", "renovate/deps-20261205"), [])
|
||||
self.assertTrue(self.check("production", "renovate"))
|
||||
|
||||
def test_production_only_from_a_release_branch(self):
|
||||
self.assertTrue(self.check("production", "feature/x"))
|
||||
self.assertTrue(self.check("production", "develop"))
|
||||
|
||||
def test_release_must_be_above_the_latest_tag(self):
|
||||
self.assertTrue(self.check("production", "release/v0.10.0"))
|
||||
self.assertTrue(self.check("production", "release/v0.9.0"))
|
||||
|
||||
def test_release_needs_its_changelog_section(self):
|
||||
self.assertTrue(self.check("production", "release/v0.12.0"))
|
||||
self.assertTrue(self.check("production", "release/v0.11.0", changelog=None))
|
||||
|
||||
def test_composer_json_has_no_version(self):
|
||||
self.assertTrue(self.check("production", "release/v0.11.0", composer={"version": "0.11.0"}))
|
||||
|
||||
def test_features_into_an_open_release_branch(self):
|
||||
self.assertEqual(self.check("release/v0.11.0", "feature/x"), [])
|
||||
self.assertEqual(self.check("release/v0.11.0", "fix/y"), [])
|
||||
|
||||
def test_nothing_into_a_release_that_is_out(self):
|
||||
self.assertTrue(self.check("release/v0.10.0", "feature/x"))
|
||||
|
||||
def test_a_release_branch_takes_no_long_lived_branch(self):
|
||||
for head in ("production", "develop", "release/v0.12.0"):
|
||||
self.assertTrue(self.check("release/v0.11.0", head))
|
||||
|
||||
def test_nothing_goes_to_develop_or_anything_else(self):
|
||||
self.assertTrue(self.check("develop", "feature/x"))
|
||||
self.assertTrue(self.check("main", "feature/x"))
|
||||
|
||||
def test_first_release_without_tags(self):
|
||||
self.assertEqual(self.check("production", "release/v0.1.0", tags=[], changelog="## v0.1.0 - x\n\n- a\n"), [])
|
||||
|
||||
|
||||
class Prune(unittest.TestCase):
|
||||
NOW = datetime(2026, 12, 4, tzinfo=timezone.utc)
|
||||
|
||||
def branch(self, name, day):
|
||||
return {"name": name, "commit": {"timestamp": f"{day}T10:00:00Z"}}
|
||||
|
||||
def names(self, branches, open_heads=()):
|
||||
return [name for name, _ in prune_branches.stale(branches, set(open_heads), self.NOW)]
|
||||
|
||||
def test_removes_only_quiet_feature_and_fix_branches(self):
|
||||
branches = [
|
||||
self.branch("feature/old", "2026-10-01"), self.branch("fix/old", "2026-11-01"),
|
||||
self.branch("feature/new", "2026-11-20"), self.branch("feature/edge", "2026-11-05"),
|
||||
]
|
||||
self.assertEqual(self.names(branches), ["feature/old", "fix/old"])
|
||||
|
||||
def test_never_removes_the_long_lived_branches(self):
|
||||
old = "2025-01-01"
|
||||
branches = [self.branch(n, old) for n in ("production", "develop", "release/v0.1.0", "renovate/x", "other")]
|
||||
self.assertEqual(self.names(branches), [])
|
||||
|
||||
def test_keeps_a_branch_with_an_open_pull_request(self):
|
||||
self.assertEqual(self.names([self.branch("feature/old", "2026-01-01")], open_heads=["feature/old"]), [])
|
||||
|
||||
|
||||
def load_hermes():
|
||||
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "dev", "token-usage-hermes.py")
|
||||
spec = importlib.util.spec_from_file_location("token_usage_hermes", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class HermesTokens(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.hermes = load_hermes()
|
||||
self.con = sqlite3.connect(":memory:")
|
||||
self.con.execute("CREATE TABLE sessions (id TEXT, parent_session_id TEXT, model TEXT, api_call_count INT, output_tokens INT, input_tokens INT, cache_write_tokens INT, cache_read_tokens INT)")
|
||||
self.con.executemany("INSERT INTO sessions VALUES (?,?,?,?,?,?,?,?)", [
|
||||
("main", None, "model-a", 10, 1000, 20, 300, 4000),
|
||||
("helper", "main", "model-b", 3, 200, 5, 0, 50),
|
||||
("grandchild", "helper", "model-b", 2, 100, 1, 0, 10),
|
||||
("other", None, "model-a", 99, 9, 9, 9, 9),
|
||||
])
|
||||
|
||||
def test_children_through_every_level(self):
|
||||
self.assertEqual(self.hermes.expand_children(self.con, ["main"]), ["grandchild", "helper", "main"])
|
||||
|
||||
def test_one_row_per_model_with_the_hours_on_the_first_only(self):
|
||||
_, per_model, missing = self.hermes.totals(self.con, ["main", "helper", "grandchild", "nope"])
|
||||
self.assertEqual(missing, {"nope"})
|
||||
rows = self.hermes.lines(per_model, "Work", "2026-12-04", "", 1.5)
|
||||
self.assertEqual(rows[0], "| 2026-12-04 | Work | | model-a | 10 | 1.000 | 20 | 300 | 4.000 | 1,50 |")
|
||||
self.assertEqual(rows[1], "| 2026-12-04 | Work | | model-b | 5 | 300 | 6 | 0 | 60 | 0,00 |")
|
||||
|
||||
def test_hours_are_never_invented(self):
|
||||
_, per_model, _ = self.hermes.totals(self.con, ["main"])
|
||||
self.assertTrue(self.hermes.lines(per_model, "Work", "2026-12-04", "", None)[0].endswith("| 4.000 | |"))
|
||||
|
||||
|
||||
class DependencyRelease(unittest.TestCase):
|
||||
def test_the_next_patch(self):
|
||||
self.assertEqual(release.next_patch((0, 5, 0)), (0, 5, 1))
|
||||
self.assertEqual(release.next_patch((1, 2, 9)), (1, 2, 10))
|
||||
self.assertIsNone(release.next_patch(None))
|
||||
|
||||
def test_an_open_release_takes_the_update_with_it(self):
|
||||
branches = ["production", "develop", "release/v0.4.0", "release/v0.5.0", "renovate/deps-1"]
|
||||
self.assertFalse(release.release_is_open(branches, (0, 5, 0)))
|
||||
self.assertTrue(release.release_is_open(branches, (0, 4, 0)))
|
||||
self.assertTrue(release.release_is_open(branches + ["release/v0.5.1"], (0, 5, 0)))
|
||||
|
||||
|
||||
class PackagistNotice(unittest.TestCase):
|
||||
def run_notice(self, answers):
|
||||
"""Runs notify() with fake answers per endpoint (a status number, or an HTTP error code as a string)."""
|
||||
import io
|
||||
import urllib.error
|
||||
|
||||
calls = []
|
||||
|
||||
def fake(endpoint, user, token, url):
|
||||
calls.append(endpoint)
|
||||
answer = answers[endpoint]
|
||||
if isinstance(answer, str):
|
||||
raise urllib.error.HTTPError("x", int(answer), "refused", {}, io.BytesIO(b"nope"))
|
||||
return answer
|
||||
|
||||
original = packagist.call
|
||||
packagist.call = fake
|
||||
try:
|
||||
return packagist.notify("u", "t", "https://example.org/r"), calls
|
||||
finally:
|
||||
packagist.call = original
|
||||
|
||||
def test_a_known_package_is_only_updated(self):
|
||||
message, calls = self.run_notice({"update-package": 202})
|
||||
self.assertEqual(calls, ["update-package"])
|
||||
self.assertIn("202", message)
|
||||
|
||||
def test_an_unknown_package_is_submitted(self):
|
||||
message, calls = self.run_notice({"update-package": "404", "create-package": 202})
|
||||
self.assertEqual(calls, ["update-package", "create-package"])
|
||||
self.assertIn("submitted", message)
|
||||
|
||||
def test_another_refusal_is_not_submitted(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
self.run_notice({"update-package": "403", "create-package": 202})
|
||||
|
||||
def test_a_refused_submission_fails(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
self.run_notice({"update-package": "404", "create-package": "400"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,188 +0,0 @@
|
||||
name: PR CI
|
||||
|
||||
# Pull requests go to a release branch (features) or to production (the release). develop only takes
|
||||
# the sync after a release. See README.md, "Development cycle".
|
||||
on:
|
||||
pull_request:
|
||||
branches: ['release/**', production]
|
||||
|
||||
env:
|
||||
COMPOSER_NO_INTERACTION: '1'
|
||||
|
||||
jobs:
|
||||
# Does the pull request follow the cycle: right branches, a version above the latest tag, a changelog
|
||||
# section for a release.
|
||||
flow:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: tests of the release scripts
|
||||
run: python3 -m unittest discover -s .gitea/scripts
|
||||
|
||||
- name: development cycle
|
||||
run: |
|
||||
git config --global --add safe.directory "$(pwd)"
|
||||
python3 .gitea/scripts/check_flow.py
|
||||
env:
|
||||
BASE_REF: ${{ github.base_ref }}
|
||||
HEAD_REF: ${{ github.head_ref }}
|
||||
|
||||
# Every piece of work records its tokens and hours (TOKENS.md). Exempt: release/*, renovate/*, bots.
|
||||
ledger:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: token ledger updated
|
||||
run: |
|
||||
git config --global --add safe.directory "$(pwd)"
|
||||
python3 .gitea/scripts/check_tokens.py
|
||||
env:
|
||||
BASE_REF: ${{ github.base_ref }}
|
||||
HEAD_REF: ${{ github.head_ref }}
|
||||
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
|
||||
# Style and tests, with the newest dependencies the constraints allow and with the oldest: a package
|
||||
# has to work for everyone in between.
|
||||
test:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
dependencies: [stable, lowest]
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: cache composer downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.composer/cache
|
||||
key: composer-${{ matrix.dependencies }}-${{ hashFiles('composer.json') }}
|
||||
restore-keys: |
|
||||
composer-${{ matrix.dependencies }}-
|
||||
|
||||
- name: composer validate
|
||||
run: composer validate --strict --no-check-lock
|
||||
|
||||
- name: install dependencies (${{ matrix.dependencies }})
|
||||
env:
|
||||
COMPOSER_MAX_PARALLEL_HTTP: '4'
|
||||
run: |
|
||||
flags="--prefer-stable --prefer-dist"
|
||||
[ "${{ matrix.dependencies }}" = "lowest" ] && flags="--prefer-lowest $flags"
|
||||
for attempt in 1 2 3; do
|
||||
composer update $flags && exit 0
|
||||
echo "composer failed (attempt $attempt of 3), trying again" >&2
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: lint (pint)
|
||||
if: matrix.dependencies == 'stable'
|
||||
run: vendor/bin/pint --test
|
||||
|
||||
- name: pest tests
|
||||
run: vendor/bin/pest
|
||||
|
||||
# The screens (ui/) are built into resources/dist, which is committed so a site needs no Node. Check that the
|
||||
# sources type-check and that the committed bundle is what the sources build to. The node image has git (see below).
|
||||
ui:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: install
|
||||
run: cd ui && npm ci --no-audit --no-fund
|
||||
|
||||
- name: type check
|
||||
run: cd ui && npm run typecheck
|
||||
|
||||
- name: build
|
||||
run: cd ui && npm run build
|
||||
|
||||
- name: the committed bundle is up to date
|
||||
run: |
|
||||
git config --global --add safe.directory "$(pwd)"
|
||||
git diff --exit-code -- resources/dist || { echo "resources/dist is out of date: run 'npm run build' in ui/ and commit it" >&2; exit 1; }
|
||||
|
||||
# Known vulnerabilities in the dependencies, and secrets or bad settings in the repository.
|
||||
security:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: cache composer downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.composer/cache
|
||||
key: composer-security-${{ hashFiles('composer.json') }}
|
||||
restore-keys: |
|
||||
composer-security-
|
||||
|
||||
- name: install dependencies
|
||||
env:
|
||||
COMPOSER_MAX_PARALLEL_HTTP: '4'
|
||||
run: |
|
||||
for attempt in 1 2 3; do
|
||||
composer update --prefer-stable --prefer-dist --no-scripts && exit 0
|
||||
echo "composer failed (attempt $attempt of 3), trying again" >&2
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: composer audit
|
||||
run: composer audit
|
||||
|
||||
# Pull requests to a release branch merge by themselves when the check below is green.
|
||||
# Every job that checks out runs in an image with git: without git the checkout is the archive of the
|
||||
# repository, which leaves out what .gitattributes export-ignores (.gitea/ with these scripts).
|
||||
release-automerge:
|
||||
runs-on: docker
|
||||
needs: pr-ci
|
||||
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: enable auto-merge
|
||||
run: python3 .gitea/scripts/auto_merge.py
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }}
|
||||
|
||||
# The one check the branch protection asks for (`PR CI / pr-ci (pull_request)`): green only when
|
||||
# every job above is. Do not rename it without changing the protection rule.
|
||||
pr-ci:
|
||||
runs-on: docker
|
||||
needs: [flow, ledger, test, ui, security]
|
||||
if: always()
|
||||
container:
|
||||
image: alpine:3.20
|
||||
steps:
|
||||
- name: all checks green
|
||||
run: |
|
||||
echo "flow=${{ needs.flow.result }} ledger=${{ needs.ledger.result }} test=${{ needs.test.result }} ui=${{ needs.ui.result }} security=${{ needs.security.result }}"
|
||||
[ "${{ needs.flow.result }}" = "success" ] && [ "${{ needs.ledger.result }}" = "success" ] && [ "${{ needs.test.result }}" = "success" ] && [ "${{ needs.ui.result }}" = "success" ] && [ "${{ needs.security.result }}" = "success" ]
|
||||
@@ -1,30 +0,0 @@
|
||||
name: Prune branches
|
||||
|
||||
# Every night: remove feature/* and fix/* branches that nobody touched for 30 days and that have no
|
||||
# open pull request. production, develop and the release branches are never removed.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '15 4 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: 'Only say what would be removed (1) or remove it (0)'
|
||||
default: '1'
|
||||
|
||||
jobs:
|
||||
prune:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: remove quiet branches
|
||||
run: python3 .gitea/scripts/prune_branches.py
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
@@ -1,106 +0,0 @@
|
||||
name: Release
|
||||
|
||||
# A push to production is the merge of a release pull request. Check it once more, tag it, tell
|
||||
# Packagist, and bring develop up to date, so the next features start from what was released.
|
||||
on:
|
||||
push:
|
||||
branches: [production]
|
||||
|
||||
concurrency:
|
||||
group: release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: cache composer downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.composer/cache
|
||||
key: composer-release-${{ hashFiles('composer.json') }}
|
||||
restore-keys: |
|
||||
composer-release-
|
||||
|
||||
- name: install dependencies
|
||||
env:
|
||||
COMPOSER_MAX_PARALLEL_HTTP: '4'
|
||||
run: |
|
||||
for attempt in 1 2 3; do
|
||||
composer update --prefer-stable --prefer-dist && exit 0
|
||||
echo "composer failed (attempt $attempt of 3), trying again" >&2
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: pest tests
|
||||
run: vendor/bin/pest
|
||||
|
||||
- name: composer audit
|
||||
run: composer audit
|
||||
|
||||
tag:
|
||||
runs-on: docker
|
||||
needs: verify
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: release
|
||||
run: |
|
||||
git config --global --add safe.directory "$(pwd)"
|
||||
python3 .gitea/scripts/release.py
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
COMMIT_HASH: ${{ github.sha }}
|
||||
|
||||
# Needs the secrets PACKAGIST_USERNAME and PACKAGIST_TOKEN on the repository, and the package
|
||||
# submitted on packagist.org once. Without them this step only says so.
|
||||
packagist:
|
||||
runs-on: docker
|
||||
needs: tag
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: tell Packagist
|
||||
run: python3 .gitea/scripts/packagist.py
|
||||
env:
|
||||
PACKAGIST_USERNAME: ${{ secrets.PACKAGIST_USERNAME }}
|
||||
PACKAGIST_TOKEN: ${{ secrets.PACKAGIST_TOKEN }}
|
||||
PACKAGE_URL: https://git.iriks.casa/iriks-it/laravel-manager
|
||||
|
||||
# Last: merge what was released into develop. Runs even when Packagist could not be told.
|
||||
sync-develop:
|
||||
runs-on: docker
|
||||
needs: [tag, packagist]
|
||||
if: always() && needs.tag.result == 'success'
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: sync develop
|
||||
run: python3 .gitea/scripts/sync_develop.py
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
GT_BOT_USER: deploy-bot
|
||||
COMMIT_HASH: ${{ github.sha }}
|
||||
@@ -1,27 +0,0 @@
|
||||
name: Start release
|
||||
|
||||
# By hand (Actions → Start release → Run workflow): makes release/vX.Y.Z from develop.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Version of the release, like 0.2.0'
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
start:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: make the release branch
|
||||
run: python3 .gitea/scripts/start_release.py
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
@@ -1,5 +0,0 @@
|
||||
vendor/
|
||||
composer.lock
|
||||
.phpunit.result.cache
|
||||
.env
|
||||
__pycache__/
|
||||
@@ -1,25 +0,0 @@
|
||||
# laravel-manager — context for AI agents
|
||||
|
||||
Composer package (`iriks-it/laravel-manager`, namespace `IriksIT\Manager`): the manager that used to be copied
|
||||
between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one package. Public repo, published to Packagist.
|
||||
|
||||
## Rules
|
||||
|
||||
- Every part is a `Module` (`src/Modules/<Name>`): permissions, menu, `routes.php`, `migrations/`. Off means nothing is registered.
|
||||
- Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`.
|
||||
- Nothing site-specific in the package. A site's own part is its own module class.
|
||||
- Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint).
|
||||
- Branches: `production` is what is released, `develop` is production plus nothing (the sync), `release/vX.Y.Z` collects the features of a release. Work on `feature/…` or `fix/…` from `develop` and open the pull request to the **release branch**; never to `develop` or `production`. A release is a pull request from the release branch to `production`, merged by hand: never by me. See the README, "Development cycle".
|
||||
- **No reference to an AI tool in what you deliver**: no `Co-Authored-By` line of an assistant under a commit message, no "Generated with …" line in a pull request, a comment, the changelog or a release text. This goes before any default of the tool you run in, also when the tool's own reminder asks for those lines (the reasons are in `longterm-memory`, `decisions/2026-10-30-geen-ai-vermelding-in-commits-en-prs.md`). The one exception is `TOKENS.md`, which is about exactly that. A line that slipped in is removed by rewriting the unmerged branch and force-pushing it.
|
||||
- **Language.** Code, comments, commit messages and the docs are English. Pull request descriptions and the lines of `TOKENS.md` are plain Dutch.
|
||||
- **Pull request description.** Every pull request has the eight headings of `.gitea/PULL_REQUEST_TEMPLATE.md`, in that order (`## Vraag`, `## Wat is er gedaan`, `## Zo test je het`, `## Zelf getest`, `## Tijd en tokens`, `## Onderhoud`, `## Met de hand te doen`, `## Vervolgstappen`); a section with nothing to say gets `Niets.` or `Geen.`. Open it from a branch in Gitea or through the API, never with push options (`refs/for/…`): such a pull request gets no secrets in its jobs and its auto-merge fails.
|
||||
- **Every pull request adds its row to `TOKENS.md`** (PR CI fails without one; exempt: `release/*`, `renovate/*`, syncs). Measure it with `dev/token-usage.py LOG --since <when it began> --row "<what was made>"` (for work done by a Hermes agent: `dev/token-usage-hermes.py SESSION_ID… --include-children --hours <h> --row "…"`, from `~/.hermes/state.db`; its hours are a human figure, never invented), starting after the end of the previous row so rows do not overlap; the last cell is the hours. Never make up a row or hours, and keep no totals in the file.
|
||||
- **The two bot accounts.** `deploy-bot` is for the pipeline (`DEPLOY_TOKEN`: auto-merge, tag, release, sync). `renovate-bot` is only for Renovate: no workflow or script here uses its token, and never add a secret for it.
|
||||
- **Nothing runs weekly in a repository.** Security and updates are the homelab's: Trivy every night (03:00) and after every release, the dependency round every night (04:00, branches `renovate/*`). A repository's own pipeline does `composer audit` (or the equivalent) on every pull request and on every release, and nothing on a schedule. Do not add a `schedule:` trigger; the nightly branch pruning is the one exception.
|
||||
- **Security first.** Validate at system boundaries, never trust raw request data, and never introduce the OWASP top-10 (injection, XSS, …). This package is public: no real addresses, names, tokens or client details in code, tests, docs or defaults. In a migration a moment that may not be null is `dateTime`, never `timestamp` (the MySQL of the servers gives such a `timestamp` a default by itself and refuses a second one in a table).
|
||||
|
||||
## Open decisions
|
||||
|
||||
1. Frontend: decided and built: the screens are in the package (`ui/`, built into `resources/dist`, committed; PR CI checks it is up to date). Still open: a theme editor in the manager, and a `host` mode that publishes the sources for a site to build itself.
|
||||
2. Moving the rest from bouwbedrijf.iriks-it.nl: reviews (still a read-only list). Users, media, posts, pages with fields, resources, revisions, audit log and statistics are done, with their screens. Leave out what is site-specific (the IriksIT API disk, client names): this repo is public. Still open: two-factor login, cropping pictures, automated tests of the screens in CI.
|
||||
3. Decided in 0.5.0: groups stay the default and the host's roles are added next to them (`manager.permissions`: `mode` groups, host or merge; `roles` or a `PermissionResolver`). A host that wants to replace the groups screens entirely is not planned.
|
||||
@@ -4,6 +4,45 @@ Every release has a section here, named after its version (for example `v0.1.0 -
|
||||
heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of
|
||||
the section is the text of the release in Gitea.
|
||||
|
||||
## v0.7.0 - 2026-12-04
|
||||
|
||||
- Per account a primary group (and any number of secondary ones): the primary group is the label of the account and sets its start screen; what the
|
||||
account may do stays the sum of all its groups. A group can name a start screen. New migration: `is_primary` on the group-user table and `start` on groups.
|
||||
- The settings screen (module `settings`, whole face only): switch parts of the manager and features of the site on or off and set the keys and addresses of
|
||||
integrations (the IriksIT API, Turnstile) from the manager, with the rights `settings.manage` and `settings.secrets`. Works at once (database plus one compiled
|
||||
file laid over the config, also with `config:cache`), optionally written into `.env` too (`manager.settings.write_env`). Sites add their own with
|
||||
`manager.settings.definitions`. New migration: `settings`.
|
||||
- More commands: `manager:settings` (list, get, set, reset, refresh; secrets are typed hidden), `manager:users`, `manager:user-password`, `manager:media-prune`
|
||||
(unused media, or files no row knows; nothing is deleted without `--delete`) and `manager:import media` (the rows of a site's own media table, with `--set` for a value every row gets).
|
||||
- `php artisan manager:media-move <disk>`: moves the files of the media library to another disk (for example to `iriksit`), keeping their addresses, with `--dry-run`, `--from`, `--limit`, `--verify` and `--delete-source`. Safe to run again.
|
||||
- The disk `iriksit`: media files at the IriksIT API (`MANAGER_MEDIA_DISK=iriksit`, `manager.media.iriksit`), with a table that remembers which
|
||||
path is which id (new migration `storage_files`) and `php artisan manager:storage-check` to try it. New requirement: `league/flysystem`.
|
||||
|
||||
## v0.6.0 - 2026-12-04
|
||||
|
||||
- Per account: the face of the manager (the whole one or the simple one) is stored on the account and wins over what its rights give; an administrator sets it
|
||||
on the accounts screen, an account with `manager.switch` (or `manager.full`) sets it itself. The language (Dutch or English) is a choice in the profile
|
||||
and applies on the server too, inside the manager only. New migration: `locale` and `tutorial` on the user settings.
|
||||
- The tour: an administrator switches it on for an account (accounts screen); the account gets it at its next load, and finishing or skipping it is stored
|
||||
(`PUT /manager/profile/tutorial`), so it does not come back until it is switched on again.
|
||||
- The simple face, made usable: posts, pages, media and the lists of `manager.resources` are marked `simple` by default (so with `simple_view` on, a simple
|
||||
account has something to work with), menu items and lists take a `hint` (a line of explanation), a field takes `advanced` (left out of the simple face)
|
||||
and `help` (shown under the field). The simple face has a start page of big buttons with a line of explanation, and bigger type and calmer spacing everywhere.
|
||||
- The tour: a playful walk through the manager with a mascot (a card beside what it points at, steps for exactly what this account sees, Back/Next, dots).
|
||||
It can be stopped at any moment (the cross, Escape or the link) and that is remembered per account, whether it was finished or not; it comes back only when
|
||||
an administrator switches it on again, and an account that has had it can start it again ("Show the tour", in the menu and the profile). The pictures are
|
||||
`resources/mascot/<name>.webp|png` (or a folder of the site: `manager.mascot.path`); a picture that is missing is a paw. A module adds steps with `tutorial()`.
|
||||
|
||||
## v0.5.2 - 2026-12-04
|
||||
|
||||
- The mirror for Packagist gets a clean tree per release (no tests, `ui/`, `dev/`, `TOKENS.md`, `.gitea/` or agent files), with no history and no
|
||||
branch, so `composer require` installs less and this repository can be private. `mirror_tags.sh`, with tests; `out/` is export-ignored too.
|
||||
|
||||
## v0.5.1 - 2026-12-04
|
||||
|
||||
- Packagist shows only the releases: the Release workflow pushes the tags to a mirror (`iriks-it/laravel-manager-packagist`) that has only a `production` branch with a note (no `composer.json`, so no version),
|
||||
and Packagist reads that, so the `dev-…` versions of every branch are gone.
|
||||
|
||||
## v0.5.0 - 2026-12-04
|
||||
|
||||
- Names that can move: `route_name` for the route-name prefix, `tables` for a table of its own per short name (on top of `table_prefix`),
|
||||
|
||||
@@ -144,6 +144,44 @@ Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembe
|
||||
- Where a file is used: other modules or your app register a source with
|
||||
`app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do.
|
||||
- No SVG: it can carry scripts.
|
||||
- **Files at the IriksIT API** (the disk `iriksit`): set `MANAGER_MEDIA_DISK=iriksit` and `MANAGER_IRIKSIT_URL` (the address of the
|
||||
API with its version, for example `https://api.iriks-it.nl/v1`), `MANAGER_IRIKSIT_EMAIL` and `MANAGER_IRIKSIT_PASSWORD`. The account needs
|
||||
the permissions `storage.read` and `storage.write`. Run the migrations (table `storage_files`), then `php artisan manager:storage-check`
|
||||
writes, reads and deletes a test file and says what fails. The API keeps a file under an id of its own; the table remembers
|
||||
which path of the disk is which id, and a location without a slash that is not in the table is taken for an id (a row of a site's older code
|
||||
keeps working). Tokens are kept encrypted in the cache of the app. There are no folders and no listing on this disk.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `manager:install`, `manager:doctor [--json]` | Set the manager up, and check that it is wired in (for people and agents). |
|
||||
| `manager:create-user` | A super admin. |
|
||||
| `manager:users [--json]` | The accounts with their groups. |
|
||||
| `manager:user-password <email> [--generate]` | A new password for an account (typed hidden, never an argument). |
|
||||
| `manager:settings list|get|set|reset|refresh` | The settings screen in the terminal; a secret is typed hidden or read from `--stdin`. |
|
||||
| `manager:import posts|pages|reviews|media` | Copy the rows of a site's own table (`--map`, `--set=disk=iriksit`, `--dry-run`). |
|
||||
| `manager:storage-check [--disk]` | Write, read and delete a test file on the disk of the media library. |
|
||||
| `manager:media-move <disk>` | Move the library to another disk, keeping every address (`--dry-run`, `--verify`, `--delete-source`). |
|
||||
| `manager:media-prune` | List media nothing uses any more (`--older-than`), or files no row knows (`--orphans`); `--delete` removes. |
|
||||
| `manager:audit-prune`, `manager:unban`, `manager:make-theme` | Housekeeping of the audit log, bans and themes. |
|
||||
|
||||
## Settings module
|
||||
|
||||
A screen (`/manager/settings`, only in the whole face of the manager) where an account with `settings.manage` switches parts of the manager on and off and
|
||||
changes settings, and an account with `settings.secrets` also changes keys, passwords and addresses (the IriksIT API, Turnstile, the disk of the media).
|
||||
|
||||
- A change is kept in the table `settings` (secrets encrypted) and in one compiled file, `bootstrap/cache/manager-settings.php`, that is laid over the config while
|
||||
the app starts. So it works at once, on every server that shares the database, with or without `config:cache`, and a request reads one file from opcache, not the
|
||||
database. "Refresh now" writes that file again and empties the caches. Without the file the table is read.
|
||||
- `manager.settings.write_env` (`MANAGER_SETTINGS_WRITE_ENV`, off by default): also write the changed value into `.env`, when that file may be written. The old
|
||||
one is kept as `.env.manager-backup`. Only variables that a definition names are ever written.
|
||||
- Only what is defined can be set: the parts of the manager, the integrations of the package, and the site's own in `manager.settings.definitions`
|
||||
(`'site.contact_form' => ['label' => 'Contact form', 'type' => 'toggle', 'group' => 'Site']`; the key is the config path it overrides, so
|
||||
`config('site.contact_form')` has the answer). A module of your own can add some with a `settings()` method.
|
||||
- What can send a password or a file elsewhere (secrets, addresses, accounts, disks) needs `settings.secrets` and the password of whoever saves it. A secret is
|
||||
never sent to a browser; it is only said to be set. Clearing one is "back to what the config says".
|
||||
- A part that is switched on and misses its tables is named: run `php artisan migrate`.
|
||||
|
||||
## Pages module
|
||||
|
||||
@@ -261,7 +299,7 @@ Nobody opens a pull request to `develop`, and `production` and the release branc
|
||||
| When | What runs |
|
||||
|---|---|
|
||||
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`: the job fails on any advisory). The check `PR CI / pr-ci` is green when all are. |
|
||||
| Push to production | verify (Pest, `composer audit`), tag and release, Packagist, sync develop; then the homelab scans production with Trivy |
|
||||
| Push to production | verify (Pest, `composer audit`), tag and release, the tags to the mirror `laravel-manager-packagist`, Packagist, sync develop; then the homelab scans production with Trivy |
|
||||
| Every night | the homelab scans every repository with Trivy (03:00) and updates its dependencies (04:00): nothing runs weekly in this repository |
|
||||
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
|
||||
|
||||
@@ -277,6 +315,13 @@ Nothing here runs on a weekly schedule; the checks hang on the moments that matt
|
||||
merged the Release workflow makes a patch release of it (v0.5.0 → v0.5.1, text from the pull request), tells Packagist and syncs `develop`:
|
||||
one a night at most. While a release branch is open there is no patch release; the update goes out with that release. A critical advisory on the installed version skips the 48 hours.
|
||||
|
||||
Packagist reads the mirror `iriks-it/laravel-manager-packagist`, not this repository, because it shows every branch of the
|
||||
repository it reads as a `dev-…` version. For every release the Release workflow (`.gitea/scripts/mirror_tags.sh`) puts a clean
|
||||
tree on the mirror: what `git archive` of the tag gives, so without what `.gitattributes` marks `export-ignore` (tests, `ui/`,
|
||||
`dev/`, `TOKENS.md`, `.gitea/`, the agent files), as a commit with no history and no branch, and pushes only its tag. The mirror
|
||||
has one branch, `production`, that only holds a note (no `composer.json`, so no version); nothing else is ever pushed there. Packagist
|
||||
and `composer require` only see the mirror, so this repository can be private. (Versions up to v0.5.1 on the mirror are the full tree.)
|
||||
|
||||
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
|
||||
`PACKAGIST_TOKEN` (until they are set that step only says so). When Packagist does not know the package yet, that step
|
||||
submits it through the create-package API; after that it only tells Packagist about each new tag.
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
# Tokenverbruik en uren van dit project
|
||||
|
||||
Per stuk werk een rij; zie `dev/token-usage.py`.
|
||||
|
||||
| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | Uren |
|
||||
|---|---|---|---|---:|---:|---:|---:|---:|---:|
|
||||
| 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 |
|
||||
| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 |
|
||||
| 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 |
|
||||
| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |
|
||||
| 2026-12-04 | Opstart van de release gerepareerd en oude featurebranches na 30 dagen automatisch opruimen | - | claude-sonnet-5-5 | 14 | 14.499 | 32 | 14.175 | 4.138.947 | 0,08 |
|
||||
| 2026-12-04 | De eerste release gestart en het LICENSE-bestand (MIT) toegevoegd voor Packagist | - | claude-sonnet-5-5 | 13 | 14.884 | 32 | 14.810 | 3.953.265 | 0,07 |
|
||||
| 2026-12-04 | Changelog van de eerste release ingevuld en de release klaargezet | - | claude-sonnet-5-5 | 8 | 7.421 | 16 | 15.226 | 2.534.041 | 0,02 |
|
||||
| 2026-12-04 | De changelog van de eerste release hersteld, de kop stond verkeerd | - | claude-sonnet-5-5 | 5 | 3.535 | 10 | 6.917 | 1.656.465 | 0,03 |
|
||||
| 2026-12-04 | Composer-cache en herhaalpogingen in alle CI-jobs, zodat haperende downloads de pipeline niet meer breken | - | claude-sonnet-5-5 | 74 | 80.637 | 164 | 167.489 | 21.208.458 | 0,65 |
|
||||
| 2026-12-04 | Auditlog en banbeheer als module 'audit' overgenomen uit bouwbedrijf, met tests, en de gedeelde regels van de andere repo's in AGENTS.md | - | claude-sonnet-5-5 | 38 | 49.634 | 82 | 92.591 | 5.342.800 | 0,18 |
|
||||
| 2026-12-04 | Bezoekersstatistieken als module 'statistics' overgenomen uit bouwbedrijf: paginaweergaven zonder cookies, bronnen, bots en export | - | claude-sonnet-5-5 | 12 | 16.807 | 24 | 20.717 | 2.545.198 | 0,03 |
|
||||
| 2026-12-04 | Token-script telt de aanroepen van de adviseur (een ander model) mee, als eigen rij met het eigen model | - | claude-sonnet-5-5 | 29 | 22.281 | 64 | 55.197 | 5.142.066 | 0,07 |
|
||||
| 2026-12-01 | Adviseur-aanroep bij het eerdere werk (CI, release en eerste modules), die in de rijen erboven nog niet meetelde | - | claude-fable-5-2 | 1 | 10.012 | 115.261 | 0 | 0 | 0,00 |
|
||||
| 2026-12-04 | Adviseur-aanroepen bij de auditmodule en het banbeheer, die in de rij erboven nog niet meetelden | - | claude-fable-5-2 | 2 | 25.967 | 246.202 | 0 | 0 | 0,00 |
|
||||
| 2026-12-04 | Het Hermes-tokenscript uit bouwbedrijf overgenomen, met dezelfde rijen per model als het hoofdscript | - | claude-sonnet-5-5 | 9 | 7.044 | 20 | 15.263 | 2.258.010 | 0,01 |
|
||||
| 2026-12-04 | Wekelijkse update van de versiebereiken van afhankelijkheden, als pull request naar de open release | - | claude-sonnet-5-5 | 6 | 7.611 | 12 | 10.963 | 1.632.350 | 0,01 |
|
||||
| 2026-12-04 | De commit zonder AI-vermelding hersteld in de release, de uitleg over de nachtelijke scans gecorrigeerd en de notities in longterm-memory gemaakt | - | claude-sonnet-5-5 | 29 | 16.997 | 72 | 21.381 | 8.975.420 | 0,11 |
|
||||
| 2026-12-04 | De Packagist-stap meldt het pakket zelf aan als Packagist het nog niet kent | - | claude-sonnet-5-5 | 13 | 7.095 | 30 | 11.993 | 4.256.820 | 0,06 |
|
||||
| 2026-12-04 | Installatie en gezondheidscheck voor AI (manager:install en manager:doctor) met een stappengids voor agents | - | claude-sonnet-5-5 | 12 | 12.112 | 28 | 64.789 | 2.344.181 | 0,04 |
|
||||
| 2026-12-04 | Installatie en gezondheidscheck voor AI (manager:install en manager:doctor) met een stappengids voor agents | - | claude-fable-5-2 | 1 | 17.440 | 362.597 | 0 | 0 | 0,00 |
|
||||
| 2026-12-04 | Schermen in het pakket: eigen login, profiel, menu en berichten, thema's per gebruiker en voor de huisstijl van de site | - | claude-sonnet-5-5 | 51 | 60.198 | 102 | 94.747 | 7.947.787 | 0,19 |
|
||||
| 2026-12-04 | Schermen voor gebruikers, groepen, categorieën en tags, pagina's en reviews | - | claude-sonnet-5-5 | 11 | 13.236 | 24 | 21.715 | 2.310.933 | 0,06 |
|
||||
| 2026-12-04 | Schermen voor media (met kiezer voor de omslag), de auditlog met blokkades en de statistieken | - | claude-sonnet-5-5 | 23 | 23.335 | 46 | 42.961 | 5.678.787 | 0,06 |
|
||||
| 2026-12-04 | De stappengids en de installatie verbeterd na de proef met een verse agent | - | claude-sonnet-5-5 | 25 | 21.844 | 50 | 35.997 | 6.551.164 | 0,10 |
|
||||
| 2026-12-04 | De stappengids en de installatie verbeterd na de proef met een verse agent | - | claude-haiku-5-5 | 11 | 8.233 | 22 | 51.184 | 444.805 | 0,00 |
|
||||
| 2026-12-04 | Changelog van v0.4.0, wiki en notitie in longterm-memory | - | claude-sonnet-5-5 | 7 | 3.891 | 14 | 5.215 | 1.999.583 | 0,01 |
|
||||
| 2026-12-04 | De wekelijkse workflow werkt ook de npm-pakketten van de schermen bij, met 48 uur wachttijd en een nieuwe bundel | - | claude-sonnet-5-5 | 9 | 9.971 | 22 | 15.191 | 3.032.384 | 0,05 |
|
||||
| 2026-12-04 | TypeScript 7 niet voorstellen zolang vue-tsc het niet draait, en de PR van de eerste run rechtgezet | - | claude-sonnet-5-5 | 10 | 4.340 | 26 | 4.489 | 3.503.406 | 0,05 |
|
||||
| 2026-12-04 | Namen die kunnen verhuizen (route_name, tables) en manager:import voor bestaande gegevens | - | claude-sonnet-5-5 | 25 | 17.827 | 54 | 72.997 | 2.216.503 | 0,09 |
|
||||
| 2026-12-04 | Namen die kunnen verhuizen (route_name, tables) en manager:import voor bestaande gegevens | - | claude-fable-5-2 | 1 | 5.062 | 61.001 | 0 | 0 | 0,00 |
|
||||
| 2026-12-04 | Teksten van de server vertaalbaar met lang-bestanden en een Nederlandse vertaling | - | claude-sonnet-5-5 | 14 | 11.377 | 28 | 23.146 | 1.520.289 | 0,02 |
|
||||
| 2026-12-04 | Menu met secties, iconen en volgorde, en de simpele weergave naast de volledige | - | claude-sonnet-5-5 | 23 | 20.663 | 46 | 31.486 | 3.202.624 | 0,05 |
|
||||
| 2026-12-04 | Echte pagina's met velden, een veldenschema en het formulier in de schermen | - | claude-sonnet-5-5 | 17 | 20.944 | 34 | 31.958 | 2.886.715 | 0,07 |
|
||||
| 2026-12-04 | Lijsten zonder code (resources) en een eigen bundel met schermen van de site | - | claude-sonnet-5-5 | 27 | 29.948 | 54 | 45.009 | 5.852.776 | 0,08 |
|
||||
| 2026-12-04 | Revisies: geschiedenis van berichten en pagina's, met terugzetten | - | claude-sonnet-5-5 | 6 | 12.423 | 12 | 14.609 | 1.461.419 | 0,03 |
|
||||
| 2026-12-04 | De editor: opmaakknoppen, foto's in de tekst, voorbeeld en een scherpstelpunt in de bibliotheek | - | claude-sonnet-5-5 | 15 | 18.397 | 30 | 28.742 | 3.931.230 | 0,07 |
|
||||
| 2026-12-04 | Het telscript en de Blade-component voor de publieke pagina's van de statistieken | - | claude-sonnet-5-5 | 8 | 9.037 | 16 | 15.948 | 2.254.948 | 0,04 |
|
||||
| 2026-12-04 | Loginhaken: eigen velden en controles, en Turnstile | - | claude-sonnet-5-5 | 4 | 9.009 | 8 | 9.515 | 1.178.544 | 0,02 |
|
||||
| 2026-12-04 | Rollen van de site naast de groepen van het pakket | - | claude-sonnet-5-5 | 3 | 5.308 | 6 | 8.235 | 921.246 | 0,01 |
|
||||
| 2026-12-04 | Controle op namen die de site al gebruikt, en de documenten van 0.5.0 rechtgezet | - | claude-sonnet-5-5 | 9 | 7.281 | 18 | 12.115 | 2.881.457 | 0,03 |
|
||||
| 2026-12-04 | Trivy uit de PR-jobs (schijf van de runners vol), opruimen en wekelijkse prune | - | claude-sonnet-5-5 | 20 | 9.723 | 44 | 94.863 | 1.460.150 | 0,15 |
|
||||
| 2026-12-04 | Niets meer wekelijks: nachtelijke scan en updates, Trivy na een release, docs | - | claude-sonnet-5-5 | 27 | 19.377 | 58 | 41.226 | 2.879.048 | 0,63 |
|
||||
| 2026-12-04 | Patch-release voor de nachtelijke renovate-update | - | claude-sonnet-5-5 | 24 | 17.609 | 54 | 35.165 | 3.038.359 | 0,16 |
|
||||
@@ -16,7 +16,8 @@
|
||||
"illuminate/routing": "^13.0",
|
||||
"illuminate/support": "^13.0",
|
||||
"illuminate/validation": "^13.0",
|
||||
"league/commonmark": "^2.6"
|
||||
"league/commonmark": "^2.6",
|
||||
"league/flysystem": "^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"orchestra/testbench": "^11.0",
|
||||
|
||||
@@ -54,6 +54,7 @@ return [
|
||||
Modules\Statistics\StatisticsModule::class,
|
||||
Modules\Resources\ResourcesModule::class,
|
||||
Modules\Revisions\RevisionsModule::class,
|
||||
Modules\Settings\SettingsModule::class,
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -71,6 +72,7 @@ return [
|
||||
'statistics' => env('MANAGER_STATISTICS', false),
|
||||
'resources' => true,
|
||||
'revisions' => env('MANAGER_REVISIONS', true),
|
||||
'settings' => true,
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -90,6 +92,15 @@ return [
|
||||
// File extensions the library accepts. SVG is deliberately missing: it can carry scripts.
|
||||
'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'],
|
||||
|
||||
// The disk `iriksit` keeps files at the IriksIT API (set `disk` to `iriksit`). The account needs the permissions
|
||||
// `storage.read` and `storage.write`. Leave this empty for any other disk.
|
||||
'iriksit' => [
|
||||
'url' => env('MANAGER_IRIKSIT_URL'),
|
||||
'email' => env('MANAGER_IRIKSIT_EMAIL'),
|
||||
'password' => env('MANAGER_IRIKSIT_PASSWORD'),
|
||||
'timeout' => 300,
|
||||
],
|
||||
|
||||
// Visitors loading files per minute per address (the `media-files` rate limiter).
|
||||
'per_minute' => 600,
|
||||
],
|
||||
@@ -165,7 +176,8 @@ return [
|
||||
| Lists the site manages without code of its own: a form, a list, permissions (`<key>.view`, `<key>.manage`)
|
||||
| and a menu item for each. `model` keeps the records in a model of the site (the field keys are its
|
||||
| attributes); without it they go into the package's own table. Fields: see `pages`.
|
||||
| 'services' => ['label' => 'Services', 'singular' => 'Service', 'model' => App\Models\Service::class,
|
||||
| A `hint` is the line under the item on the simple start page.
|
||||
| 'services' => ['label' => 'Services', 'hint' => 'What you offer', 'singular' => 'Service', 'model' => App\Models\Service::class,
|
||||
| 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => ['name' => ['type' => 'text', 'required' => true], ...]]
|
||||
*/
|
||||
'resources' => [],
|
||||
@@ -221,6 +233,22 @@ return [
|
||||
*/
|
||||
'simple_view' => (bool) env('MANAGER_SIMPLE_VIEW', false),
|
||||
|
||||
/*
|
||||
| The pictures of the tour: a folder with `welcome`, `point`, `calm`, `write`, `photos`, `pages`, `undo`, `oops`, `party`, `profile` and
|
||||
| `peek` (`.webp` or `.png`). Null: the set of the package. A picture that is missing is replaced by a paw.
|
||||
*/
|
||||
'mascot' => ['path' => null],
|
||||
|
||||
/*
|
||||
| The settings screen (module `settings`, whole face of the manager only). Changes are kept in the database and in one compiled file
|
||||
| and work at once. `write_env` also writes the changed value into .env, when that file may be written (it is left alone otherwise).
|
||||
| `definitions` adds settings of the site's own, by the config path they override:
|
||||
| 'site.contact_form' => ['label' => 'Contact form', 'type' => 'toggle', 'group' => 'Site', 'env' => 'CONTACT_FORM'].
|
||||
| Types: toggle, text, url, number, select (with `options`), secret (never shown again). A definition with `sensitive` => true needs the
|
||||
| right `settings.secrets` and the password of whoever saves it.
|
||||
*/
|
||||
'settings' => ['write_env' => (bool) env('MANAGER_SETTINGS_WRITE_ENV', false), 'definitions' => []],
|
||||
|
||||
/*
|
||||
| Prefix for the tables of the package.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** The language an account chose, and where it stands with the tour (null, `pending`, `done` or `skipped`). */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table(Names::table('user_settings'), function (Blueprint $table) {
|
||||
$table->string('locale', 5)->nullable()->after('view');
|
||||
$table->string('tutorial', 10)->nullable()->after('locale');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table(Names::table('user_settings'), function (Blueprint $table) {
|
||||
$table->dropColumn(['locale', 'tutorial']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Adds up the exact tokens of one or more Hermes sessions, for TOKENS.md.
|
||||
|
||||
Companion to `dev/token-usage.py` (which reads a Claude Code session log). This script is for work
|
||||
done by a Hermes agent (any of the Aristocats): Hermes keeps its sessions in its own SQLite file,
|
||||
`~/.hermes/state.db`, and has no `.jsonl` log, so a TOKENS.md row for Hermes work comes from this
|
||||
script, never from a guess.
|
||||
|
||||
Usage: dev/token-usage-hermes.py SESSION_ID [SESSION_ID ...] [--include-children]
|
||||
[--state-db PATH] [--date 2026-12-04]
|
||||
[--row "Wat er is gemaakt" [--version v0.2.0]] [--hours 1.5]
|
||||
|
||||
Pass every session that did the work: the session of the agent itself and, with --include-children,
|
||||
every session it started (a helper agent has `parent_session_id` set, also through several levels).
|
||||
Helper agents are part of the work: their tokens are added to the row.
|
||||
|
||||
Like `dev/token-usage.py`, the row is made per model, because the price differs per model: when the
|
||||
helper sessions ran on another model than the main session there is one row for each, the model with
|
||||
the most steps first, and the hours are on the first row only.
|
||||
|
||||
There is no reliable signal for the time worked in state.db, so this script never invents the hours:
|
||||
give them with --hours (a plain human figure: how long did the work take), or leave the cell empty and
|
||||
fill it in by hand.
|
||||
|
||||
Standard library only.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
DEFAULT_STATE_DB = "~/.hermes/state.db"
|
||||
|
||||
|
||||
def expand_children(con, seed_ids):
|
||||
"""The given sessions plus every session whose parent is, through any number of levels, one of them."""
|
||||
seen = set(seed_ids)
|
||||
frontier = list(seed_ids)
|
||||
|
||||
while frontier:
|
||||
placeholders = ",".join("?" for _ in frontier)
|
||||
found = con.execute(f"SELECT id FROM sessions WHERE parent_session_id IN ({placeholders})", frontier).fetchall()
|
||||
frontier = [row[0] for row in found if row[0] not in seen]
|
||||
seen.update(frontier)
|
||||
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def totals(con, session_ids):
|
||||
"""Steps, output, input, written to the cache, read from the cache: in all and per model; and the ids not found."""
|
||||
placeholders = ",".join("?" for _ in session_ids)
|
||||
rows = con.execute(
|
||||
f"""SELECT id, model, api_call_count, output_tokens, input_tokens, cache_write_tokens, cache_read_tokens
|
||||
FROM sessions WHERE id IN ({placeholders})""",
|
||||
list(session_ids),
|
||||
).fetchall()
|
||||
|
||||
row = [0, 0, 0, 0, 0]
|
||||
per_model = {}
|
||||
|
||||
for _id, model, *counts in rows:
|
||||
add = [count or 0 for count in counts]
|
||||
mine = per_model.setdefault(model or "?", [0, 0, 0, 0, 0])
|
||||
|
||||
for index, value in enumerate(add):
|
||||
row[index] += value
|
||||
mine[index] += value
|
||||
|
||||
return row, per_model, set(session_ids) - {row[0] for row in rows}
|
||||
|
||||
|
||||
def number(value):
|
||||
return f"{value:,}".replace(",", ".")
|
||||
|
||||
|
||||
def show(name, row):
|
||||
steps, out, new, written, read = row
|
||||
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
|
||||
|
||||
|
||||
def lines(per_model, text, day, version, hours):
|
||||
"""The rows for the table: one per model, the model with the most steps first, the hours on that row only."""
|
||||
result = []
|
||||
|
||||
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
|
||||
if position > 0:
|
||||
cell = "0,00"
|
||||
else:
|
||||
cell = "" if hours is None else f"{hours:.2f}".replace(".", ",")
|
||||
|
||||
cells = [day, text, version or "", model] + [number(value) for value in per_model[model]] + [cell]
|
||||
result.append("| " + " | ".join(cells) + " |")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("session_ids", nargs="+")
|
||||
parser.add_argument("--state-db", default=DEFAULT_STATE_DB)
|
||||
parser.add_argument("--include-children", action="store_true")
|
||||
parser.add_argument("--row")
|
||||
parser.add_argument("--version", default="")
|
||||
parser.add_argument("--date", default=datetime.now(timezone.utc).strftime("%Y-%m-%d"))
|
||||
parser.add_argument("--hours", type=float, default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
path = os.path.expanduser(args.state_db)
|
||||
|
||||
if not os.path.exists(path):
|
||||
sys.exit(f"No Hermes state file at {path} (use --state-db).")
|
||||
|
||||
con = sqlite3.connect(path)
|
||||
session_ids = expand_children(con, args.session_ids) if args.include_children else args.session_ids
|
||||
|
||||
if args.include_children:
|
||||
print(f"sessions counted (given + children): {', '.join(session_ids)}", file=sys.stderr)
|
||||
|
||||
row, per_model, missing = totals(con, session_ids)
|
||||
|
||||
if missing:
|
||||
print(f"WARNING: not found in state.db, not counted: {', '.join(sorted(missing))}", file=sys.stderr)
|
||||
|
||||
show("sessions", row)
|
||||
|
||||
if args.row:
|
||||
if not per_model:
|
||||
per_model = {"?": [0, 0, 0, 0, 0]}
|
||||
|
||||
if args.hours is None:
|
||||
print("NOTE: no --hours given: fill in the Uren cell by hand, do not invent a figure.", file=sys.stderr)
|
||||
|
||||
print("\n".join(lines(per_model, args.row, args.date, args.version, args.hours)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,152 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Adds up the tokens of a Claude Code session log, for TOKENS.md.
|
||||
|
||||
Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00]
|
||||
[--row "Wat er is gemaakt" [--version v0.2.0]]
|
||||
|
||||
With --row it also prints the line(s) for the table of TOKENS.md, with the hours as the last cell.
|
||||
|
||||
Helper agents (subagents) are part of the work: their tokens are added to the row. The row is made
|
||||
per model, because the price differs per model: when helper agents ran on another model than the
|
||||
session, there is one row for each, and the hours are on the first row only.
|
||||
|
||||
The hours are the time that was worked in the period: from one entry of the log to the next,
|
||||
the time between an answer and the next request included, pauses of more than half an hour
|
||||
left out.
|
||||
|
||||
LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of
|
||||
helper agents in the folder `<session>/subagents` next to it are shown separately and also counted in the row. The moments
|
||||
are UTC, as in the log. An answer of the model can be in the log more than once; it is counted
|
||||
once, by its message id.
|
||||
|
||||
Standard library only.
|
||||
"""
|
||||
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def answers(path):
|
||||
"""The usage of every answer in a log, by message id, with its moment."""
|
||||
found = {}
|
||||
with open(path, encoding="utf-8") as log:
|
||||
for line in log:
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
message = entry.get("message") or {}
|
||||
if entry.get("type") == "assistant" and message.get("usage") and message.get("id"):
|
||||
found[message["id"]] = (message["usage"], entry.get("timestamp", ""), message.get("model"))
|
||||
# The advisor (another, stronger model) runs inside an answer: its tokens are in the
|
||||
# iterations of that answer and are not part of the usage of the answer itself.
|
||||
for number, iteration in enumerate(message["usage"].get("iterations") or []):
|
||||
if iteration.get("type") == "advisor_message":
|
||||
found[f'{message["id"]}:advisor:{number}'] = (iteration, entry.get("timestamp", ""), iteration.get("model"))
|
||||
return found
|
||||
|
||||
|
||||
PAUSE = 30 * 60
|
||||
|
||||
|
||||
def hours(path, since, until):
|
||||
"""The hours worked in the period, by the moments in the main log; pauses longer than PAUSE are left out."""
|
||||
from datetime import datetime
|
||||
|
||||
moments = []
|
||||
with open(path, encoding="utf-8", errors="replace") as log:
|
||||
for line in log:
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if entry.get("isSidechain") or entry.get("type") not in ("user", "assistant") or not entry.get("timestamp"):
|
||||
continue
|
||||
moments.append(entry["timestamp"])
|
||||
moments.sort()
|
||||
|
||||
seconds = 0.0
|
||||
for start, end in zip(moments, moments[1:]):
|
||||
# A step counts for the period it starts in.
|
||||
if (since and start[:16] < since) or (until and start[:16] >= until):
|
||||
continue
|
||||
gap = (datetime.fromisoformat(end.replace("Z", "+00:00")) - datetime.fromisoformat(start.replace("Z", "+00:00"))).total_seconds()
|
||||
if gap <= PAUSE:
|
||||
seconds += gap
|
||||
return seconds / 3600
|
||||
|
||||
|
||||
def total(found, since, until):
|
||||
"""Steps, output, input, written to the cache, read from the cache; and the same per model."""
|
||||
row = [0, 0, 0, 0, 0]
|
||||
per_model = {}
|
||||
for usage, moment, model in found.values():
|
||||
if (since and moment[:16] < since) or (until and moment[:16] >= until):
|
||||
continue
|
||||
# Entries the client made itself (model "<synthetic>") hold no tokens and no work.
|
||||
if model and model.startswith("<"):
|
||||
continue
|
||||
add = [
|
||||
1,
|
||||
usage.get("output_tokens", 0),
|
||||
usage.get("input_tokens", 0),
|
||||
usage.get("cache_creation_input_tokens", 0),
|
||||
usage.get("cache_read_input_tokens", 0),
|
||||
]
|
||||
model = model or "?"
|
||||
mine = per_model.setdefault(model, [0, 0, 0, 0, 0])
|
||||
for index, value in enumerate(add):
|
||||
row[index] += value
|
||||
mine[index] += value
|
||||
return row, per_model
|
||||
|
||||
|
||||
def number(value):
|
||||
return f"{value:,}".replace(",", ".")
|
||||
|
||||
|
||||
def show(name, row):
|
||||
steps, out, new, written, read = row
|
||||
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
names = ("--since", "--until", "--row", "--version")
|
||||
option = lambda name: args[args.index(name) + 1] if name in args else None
|
||||
since, until = option("--since"), option("--until")
|
||||
paths = [arg for index, arg in enumerate(args) if arg not in names and (index == 0 or args[index - 1] not in names)]
|
||||
|
||||
if len(paths) != 1:
|
||||
sys.exit(__doc__)
|
||||
|
||||
session = answers(paths[0])
|
||||
row, _ = total(session, since, until)
|
||||
show("session", row)
|
||||
worked_hours = hours(paths[0], since, until)
|
||||
print(f"hours worked: {worked_hours:.2f}")
|
||||
|
||||
helpers = {}
|
||||
for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")):
|
||||
helpers.update(answers(path))
|
||||
if helpers:
|
||||
show("helper agents", total(helpers, since, until)[0])
|
||||
|
||||
if option("--row"):
|
||||
# Session and helper agents together, one row per model.
|
||||
everything = {**session, **{"helper:" + key: value for key, value in helpers.items()}}
|
||||
_, per_model = total(everything, since, until)
|
||||
if not per_model:
|
||||
per_model = {"?": [0, 0, 0, 0, 0]}
|
||||
day = (since or "")[:10] or "JJJJ-MM-DD"
|
||||
# The model with the most steps first; the hours go on that row only.
|
||||
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
|
||||
worked = f"{worked_hours:.2f}" if position == 0 else "0.00"
|
||||
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in per_model[model]] + [worked.replace(".", ",")]
|
||||
print("| " + " | ".join(cells) + " |")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 45 KiB |
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true">
|
||||
<testsuites>
|
||||
<testsuite name="Feature">
|
||||
<directory>tests/Feature</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<include>
|
||||
<directory>src</directory>
|
||||
</include>
|
||||
</source>
|
||||
</phpunit>
|
||||
@@ -1,3 +1,3 @@
|
||||
/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--radius-sm:.25rem;--radius-lg:.5rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-fiLine truncated
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-lg:.5rem;--radius-xl:.75rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fieldLine truncated
|
||||
/*$vite$:1*/
|
||||
@@ -1,7 +1,7 @@
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,S=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),ee=Object.prototype.toString,C=e=>ee.call(e),te=e=>C(e).slice(8,-1),w=e=>C(e)===`[object Object]`,T=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=n(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=1e4,ie=e=>{let t=Object.create(null),n=0;return(r=>{let i=t[r];return i===void 0?(++n>re&&(t=Object.create(null),n=1),t[r]=e(r)):i})},ae=/-\w/g,E=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),oe=/\B([A-Z])/g,se=ie(e=>e.replace(oe,`-$1`).toLowerCase()),ce=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),le=ie(e=>e?`on${ce(e)}`:``),D=(e,t)=>!Object.is(e,t),ue=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},de=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},fe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},pe=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},me,he=()=>me||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ge=n(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function _e(e){if(p(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=y(r)?xe(r):_e(r);if(i)for(let e in i)t[e]=i[e]}return t}if(y(e)||x(e))return e}var ve=/;(?![^(]*\))/g,ye=/:([^]+)/,be=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function xe(e){let t={};return e.replace(be,e=>e.startsWith(`/*`)?``:e).split(ve).forEach(e=>{if(e){let n=e.split(ye);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function O(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;n<e.length;n++){let r=O(e[n]);r&&(t+=r+` `)}else if(x(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Se(e){if(!e)return null;let{class:t,style:n}=e;return t&&!y(t)&&(e.class=O(t)),n&&(e.style=_e(n)),e}var Ce=`itemscope,allowfullscreen,disablepictureinpicture,disableremoteplayback,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`,we=n(Ce);Ce+``;function Te(e){return!!e||e===``}function Ee(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Ae(e[i],t[i],n);return r}function De(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Ae(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Oe(e,t,n){let r=m(e),i=m(t);if(r||i||(r=h(e),i=h(t),r||i))return r&&i?De(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=f(e,r),a=f(t,r);if(i&&!a||!i&&a||!Ae(e[r],t[r],n))return!1}return Me(e)===Me(t)}function ke(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Ae(e,t,n){if(e===t)return!0;let r=g(e),i=g(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=b(e),i=b(t),r||i?e===t:(r=p(e),i=p(t),r||i?r&&i?ke(e,t,n,Ee):!1:(r=x(e),i=x(t),r||i?!r||!i?!1:ke(e,t,n,Oe):String(e)===String(t))))}function je(e,t){return e.findIndex(e=>Ae(e,t))}function Me(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Ne=e=>!!(e&&e.__v_isRef===!0),k=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Ne(e)?k(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:b(t)?Fe(t):x(t)&&!p(t)&&!w(t)?String(t):t,Fe=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Ie(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Le,Re=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&Le&&(Le.active?(this.parent=Le,this.index=(Le.scopes||(Le.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return thLine truncated
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,S=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),ee=Object.prototype.toString,C=e=>ee.call(e),te=e=>C(e).slice(8,-1),w=e=>C(e)===`[object Object]`,T=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=n(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=1e4,ie=e=>{let t=Object.create(null),n=0;return(r=>{let i=t[r];return i===void 0?(++n>re&&(t=Object.create(null),n=1),t[r]=e(r)):i})},ae=/-\w/g,E=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),oe=/\B([A-Z])/g,se=ie(e=>e.replace(oe,`-$1`).toLowerCase()),ce=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),le=ie(e=>e?`on${ce(e)}`:``),ue=(e,t)=>!Object.is(e,t),de=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},fe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},pe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},me=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},he,ge=()=>he||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},_e=n(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ve(e){if(p(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=y(r)?Se(r):ve(r);if(i)for(let e in i)t[e]=i[e]}return t}if(y(e)||x(e))return e}var ye=/;(?![^(]*\))/g,be=/:([^]+)/,xe=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Se(e){let t={};return e.replace(xe,e=>e.startsWith(`/*`)?``:e).split(ye).forEach(e=>{if(e){let n=e.split(be);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(x(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Ce(e){if(!e)return null;let{class:t,style:n}=e;return t&&!y(t)&&(e.class=D(t)),n&&(e.style=ve(n)),e}var we=`itemscope,allowfullscreen,disablepictureinpicture,disableremoteplayback,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`,Te=n(we);we+``;function Ee(e){return!!e||e===``}function De(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=je(e[i],t[i],n);return r}function Oe(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&je(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function ke(e,t,n){let r=m(e),i=m(t);if(r||i||(r=h(e),i=h(t),r||i))return r&&i?Oe(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=f(e,r),a=f(t,r);if(i&&!a||!i&&a||!je(e[r],t[r],n))return!1}return Ne(e)===Ne(t)}function Ae(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function je(e,t,n){if(e===t)return!0;let r=g(e),i=g(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=b(e),i=b(t),r||i?e===t:(r=p(e),i=p(t),r||i?r&&i?Ae(e,t,n,De):!1:(r=x(e),i=x(t),r||i?!r||!i?!1:Ae(e,t,n,ke):String(e)===String(t))))}function Me(e,t){return e.findIndex(e=>je(e,t))}function Ne(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Pe=e=>!!(e&&e.__v_isRef===!0),O=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Pe(e)?O(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}:b(t)?Ie(t):x(t)&&!p(t)&&!w(t)?String(t):t,Ie=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Le(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Re,ze=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&Re&&(Re.active?(this.parent=Re,this.index=(Re.scopes||(Re.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return tLine truncated
|
||||
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
|
||||
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ne(a)||a[0]===`.`||t&&!ne(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Rs(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ms(()=>{x&&Rs(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u,d)=>{u||=!!t.dynamicChildren;let p=t.children,m=p.length,h=t.type===B,g=!1;for(let t=0;t<m;t++){let _=u?p[t]:p[t]=Ps(p[t]),v=_.type===_s;h&&e&&wi(e)&&e.data===`]`&&(d=e),e&&e!==d?(v&&!u&&t+1<m&&Ps(p[t+1]).type===_s&&(l(i(e.data.slice(_.children.length)),r,a(e)),e.data=_.children),e=f(e,_,o,s,c,u)):v&&!_.children?l(_.el=i(``),r,d):(g||(g=!0,Ai(r,1)||bi()),n(null,_,r,d,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,wo(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=he().requestIdleCallback||(e=>setTimeout(e,1)),Ii=he().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(Ri(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t<e.children.length;t++)if(i(e.children[t])===!1)return!1}r.observe(e)};return n(e=>{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return L({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Us;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Yn(t,e,13,!r,!0)};if(s&&e.suspense||Xs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?K(r,{error:e}):null));let a=N(!1),c=N(),d=N(!!i),f,m;return Ve(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted|
Line truncated
|
||||
`))),e[cu]=au(i);let a=r||i.props&&i.props.type===`number`;xl(e,t?`change`:`input`,t=>{t.target.composing||e[cu](uu(e.value,n,a))}),(n||a)&&xl(e,`change`,()=>{e.value=uu(e.value,n,a)}),t||(xl(e,`compositionstart`,ou),xl(e,`compositionend`,su),xl(e,`change`,su))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[lu];delete e[lu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[cu](uu(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[cu]=au(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?fe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},du={deep:!0,created(e,t,n){e[cu]=au(n),xl(e,`change`,()=>{let t=e._modelValue,n=_u(e),r=e.checked,i=e[cu];if(p(t)){let e=je(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(vu(e,r))})},mounted:fu,beforeUpdate(e,t,n){e[cu]=au(n),fu(e,t,n)}};function fu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=je(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=Ae(t,vu(e,!0))}e.checked!==i&&(e.checked=i)}var pu={created(e,{value:t},n){e.checked=Ae(t,n.props.value),e[cu]=au(n),xl(e,`change`,()=>{e[cu](_u(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[cu]=au(r),t!==n&&(e.checked=Ae(t,r.props.value))}},mu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,xl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?fe(_u(e)):_u(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[cu](i)}finally{ir(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[cu]=au(r)},mounted(e,{value:t,modifiers:{number:n}}){gu(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[cu]=au(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&hu(t,r[1],r[0])||gu(e,t,n)}};function hu(e,t,n){if(!n||p(e))return Ae(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function gu(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;a<o;a++){let o=e.options[a],s=_u(o);if(r){if(i){let e=typeof s;o.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(s)):je(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(fe(s))}else if(Ae(_u(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function _u(e){return`_value`in e?e._value:e.value}function vu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var yu={created(e,t,n){xu(e,t,n,null,`created`)},mounted(e,t,n){xu(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){xu(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){xu(e,t,n,r,`updated`)}};function bu(e,t){switch(e){case`SELECT`:return mu;case`TEXTAREA`:return Y;default:switch(t){case`checkbox`:return du;case`radio`:return pu;default:return Y}}}function xu(e,t,n,r,i){let a=bu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Su(){Y.getSSRProps=({value:e})=>({value:e}),pu.getSSRProps=({value:e},t)=>{if(t.props&&Ae(t.props.value,e))return{checked:!0}},du.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&je(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},yu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=bu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var Cu=[`ctrl`,`shift`,`alt`,`meta`],wu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>Cu.some(n=>e[`${n}Key`]&&!t.includes(n))},Tu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=wu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Eu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Eu[e]===r))return e(n)})},Ou=l({patchProp:Nl},kc),ku,Au=!1;function ju(){return ku||=Uo(Ou)}function Mu(){return ku=Au?ku:Wo(Ou),Au=!0,ku}var Nu=((...e)=>{ju().render(...e)}),Pu=((...e)=>{Mu().hydrate(...e)}),Fu=((...e)=>{let t=ju().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Ru(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType===
Line truncated
|
||||
`)&&(ji(e,0)||xi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ne(a)||a[0]===`.`||t&&!ne(a)||u&&u.includes(a)){if(Oi(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&un(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&zs(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&hs(()=>{x&&zs(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u,d)=>{u||=!!t.dynamicChildren;let p=t.children,m=p.length,h=t.type===z,g=!1;for(let t=0;t<m;t++){let _=u?p[t]:p[t]=Fs(p[t]),v=_.type===vs;h&&e&&Ti(e)&&e.data===`]`&&(d=e),e&&e!==d?(v&&!u&&t+1<m&&Fs(p[t+1]).type===vs&&(l(i(e.data.slice(_.children.length)),r,a(e)),e.data=_.children),e=f(e,_,o,s,c,u)):v&&!_.children?l(_.el=i(``),r,d):(g||(g=!0,ji(r,1)||xi()),n(null,_,r,d,o,s,wi(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&Ti(f)&&f.data===`]`?a(t.anchor=f):(xi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Ni(e,t)||xi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,wi(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,To(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ti(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Di=new Set([`src`,`srcset`,`href`,`poster`]);function Oi(e,t,n){return Di.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var ki=`data-allow-mismatch`,Ai={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ji(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(ki);)e=e.parentElement;return Mi(e&&e.getAttribute(ki),t)}function Mi(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Ai[t])}}function Ni(e,t){return ji(e.parentElement,1)||Pi(e)||Fi(t)}function Pi(e){return e.nodeType===1&&Mi(e.getAttribute(ki),1)}function Fi({props:e}){let t=e&&e[ki];return typeof t==`string`&&Mi(t,1)}var Ii=ge().requestIdleCallback||(e=>setTimeout(e,1)),Li=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ri=(e=1e4)=>t=>{let n=Ii(t,{timeout:e});return()=>Li(n)};function zi(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var Bi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(zi(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t<e.children.length;t++)if(i(e.children[t])===!1)return!1}r.observe(e)};return n(e=>{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Vi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Hi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Ui(e,t){if(Ti(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ti(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Wi=e=>!!e.type.__asyncLoader;function Gi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return I({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Ui(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Ws;if(mi(e),u)return()=>Ki(u,e);let t=t=>{l=null,Xn(t,e,13,!r,!0)};if(s&&e.suspense||Zs)return p().then(t=>()=>Ki(t,e)).catch(e=>(t(e),()=>r?G(r,{error:e}):null));let a=M(!1),c=M(),d=M(!!i),f,m;return He(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted|
Line truncated
|
||||
`))),e[lu]=ou(i);let a=r||i.props&&i.props.type===`number`;Sl(e,t?`change`:`input`,t=>{t.target.composing||e[lu](du(e.value,n,a))}),(n||a)&&Sl(e,`change`,()=>{e.value=du(e.value,n,a)}),t||(Sl(e,`compositionstart`,su),Sl(e,`compositionend`,cu),Sl(e,`change`,cu))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[uu];delete e[uu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[lu](du(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[lu]=ou(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},fu={deep:!0,created(e,t,n){e[lu]=ou(n),Sl(e,`change`,()=>{let t=e._modelValue,n=vu(e),r=e.checked,i=e[lu];if(p(t)){let e=Me(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(yu(e,r))})},mounted:pu,beforeUpdate(e,t,n){e[lu]=ou(n),pu(e,t,n)}};function pu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=Me(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,yu(e,!0))}e.checked!==i&&(e.checked=i)}var mu={created(e,{value:t},n){e.checked=je(t,n.props.value),e[lu]=ou(n),Sl(e,`change`,()=>{e[lu](vu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[lu]=ou(r),t!==n&&(e.checked=je(t,r.props.value))}},hu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,Sl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(vu(e)):vu(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[lu](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[lu]=ou(r)},mounted(e,{value:t,modifiers:{number:n}}){_u(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[lu]=ou(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&gu(t,r[1],r[0])||_u(e,t,n)}};function gu(e,t,n){if(!n||p(e))return je(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function _u(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;a<o;a++){let o=e.options[a],s=vu(o);if(r){if(i){let e=typeof s;o.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(s)):Me(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(pe(s))}else if(je(vu(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function vu(e){return`_value`in e?e._value:e.value}function yu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var bu={created(e,t,n){Su(e,t,n,null,`created`)},mounted(e,t,n){Su(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){Su(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){Su(e,t,n,r,`updated`)}};function xu(e,t){switch(e){case`SELECT`:return hu;case`TEXTAREA`:return J;default:switch(t){case`checkbox`:return fu;case`radio`:return mu;default:return J}}}function Su(e,t,n,r,i){let a=xu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Cu(){J.getSSRProps=({value:e})=>({value:e}),mu.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},fu.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&Me(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},bu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=xu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var wu=[`ctrl`,`shift`,`alt`,`meta`],Tu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>wu.some(n=>e[`${n}Key`]&&!t.includes(n))},Eu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=Tu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Ou=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Du[e]===r))return e(n)})},ku=l({patchProp:Pl},Ac),Au,ju=!1;function Mu(){return Au||=Wo(ku)}function Nu(){return Au=ju?Au:Go(ku),ju=!0,Au}var Pu=((...e)=>{Mu().render(...e)}),Fu=((...e)=>{Nu().hydrate(...e)}),Iu=((...e)=>{let t=Mu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=zu(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType===
Line truncated
|
||||
`,t.selectionStart-1)+1,o=t.selectionEnd,s=n.modelValue.slice(a,o).split(`
|
||||
`).map(t=>e+t).join(`
|
||||
`);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=``;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await qu.post(`${X.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(H(),U(`div`,null,[G(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":P(Z)(`Formatting`)},[G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:P(Z)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,P(Z)(`bold`))},`B`,8,Ld),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:P(Z)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,P(Z)(`italic`))},`I`,8,Rd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,zd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,Bd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Vd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,P(Z)(`text`))},`🔗`,8,Hd),P(l)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},k(P(Z)(`Photo`)),9,Ud)):J(``,!0),G(`span`,Wd,[G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},k(P(Z)(`Write`)),3),G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},k(P(Z)(`Preview`)),3)])],8,Id),I(G(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,Gd),[[$c,a.value===`write`]]),a.value===`preview`?(H(),U(`div`,Kd,[s.value?(H(),U(`p`,qd,k(P(Z)(`Loading…`)),1)):(H(),U(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,Jd))])):J(``,!0),c.value?(H(),W(Fd,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):J(``,!0)]))}}),Xd={class:`m-card mt-6 max-w-3xl p-5`},Zd={class:`font-display text-lg font-bold`},Qd={key:0,class:`mt-2 text-sm text-muted`},$d={key:1,class:`mt-2 text-sm text-muted`},ef={key:2,class:`mt-3 divide-y divide-line`},tf={class:`flex flex-wrap items-center justify-between gap-2`},nf=[`aria-expanded`,`onClick`],rf={class:`font-semibold`},af={key:0,class:`text-muted`},of={key:1,class:`m-badge ml-2`},sf={class:`block text-xs text-muted`},cf=[`onClick`],lf={key:0,class:`mt-2 space-y-2 text-sm`},uf={class:`text-xs font-semibold uppercase tracking-wide text-muted`},df={class:`whitespace-pre-wrap break-words`},ff=L({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=N([]),r=N(!1),i=N(null),a=N(!0),o=`${X.base}/revisions/${t.type}/${t.id}`;ia(async()=>{try{let e=await qu.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Z(`Put this version back? The text now is kept in the history.`))&&(await qu.post(`${o}/${e.id}/restore`),$(Z(`The earlier version is back.`)),await x1())}let c=e=>new Date(e).toLocaleString(X.locale||void 0);return(e,t)=>(H(),U(`section`,Xd,[G(`h2`,Zd,k(P(Z)(`History`)),1),a.value?(H(),U(`p`,Qd,k(P(Z)(`Loading…`)),1)):n.value.length?(H(),U(`ul`,ef,[(H(!0),U(B,null,R(n.value,e=>(H(),U(`li`,{key:e.id,class:`py-3`},[G(`div`,tf,[G(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[G(`span`,rf,k(c(e.created_at)),1),e.user?(H(),U(`span`,af,` · `+k(e.user),1)):J(``,!0),e.current?(H(),U(`span`,of,k(P(Z)(`Now`)),1)):J(``,!0),G(`span`,sf,k(e.changed.join(`, `)),1)],8,nf),r.value&&!e.current?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},k(P(Z)(`Put back`)),9,cf)):J(``,!0)]),i.value===e.id?(H(),U(`dl`,lf,[(H(!0),U(B,null,R(e.values,(e,t)=>(H(),U(`div`,{key:t},[G(`dt`,uf,k(t),1),G(`dd`,df,k(e),1)]))),128))])):J(``,!0)]))),128))])):(H(),U(`p`,$d,k(P(Z)(`Nothing here yet.`)),1))]))}}),pf={class:`mb-6 flex items-center justify-between gap-3`},mf={class:`font-display text-2xl font-bold`},hf={for:`title`,class:`m-label`},gf={key:0,class:`m-error`},_f={class:`grid gap-5 sm:grid-cols-2`},vf={for:`slug`,class:`m-label`},yf={key:0,class:`m-error`},bf={for:`category`,class:`m-lab
Line truncated
|
||||
`);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=``;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await X.post(`${Y.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(V(),H(`div`,null,[W(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":N(Z)(`Formatting`)},[W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:N(Z)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,N(Z)(`bold`))},`B`,8,Gd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:N(Z)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,N(Z)(`italic`))},`I`,8,Kd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,qd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,Jd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Yd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,N(Z)(`text`))},`🔗`,8,Xd),N(l)?(V(),H(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},O(N(Z)(`Photo`)),9,Zd)):q(``,!0),W(`span`,Qd,[W(`button`,{type:`button`,class:D([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},O(N(Z)(`Write`)),3),W(`button`,{type:`button`,class:D([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},O(N(Z)(`Preview`)),3)])],8,Wd),F(W(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,$d),[[el,a.value===`write`]]),a.value===`preview`?(V(),H(`div`,ef,[s.value?(V(),H(`p`,tf,O(N(Z)(`Loading…`)),1)):(V(),H(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,nf))])):q(``,!0),c.value?(V(),U(Ud,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):q(``,!0)]))}}),af={class:`m-card mt-6 max-w-3xl p-5`},of={class:`font-display text-lg font-bold`},sf={key:0,class:`mt-2 text-sm text-muted`},cf={key:1,class:`mt-2 text-sm text-muted`},lf={key:2,class:`mt-3 divide-y divide-line`},uf={class:`flex flex-wrap items-center justify-between gap-2`},df=[`aria-expanded`,`onClick`],ff={class:`font-semibold`},pf={key:0,class:`text-muted`},mf={key:1,class:`m-badge ml-2`},hf={class:`block text-xs text-muted`},gf=[`onClick`],_f={key:0,class:`mt-2 space-y-2 text-sm`},vf={class:`text-xs font-semibold uppercase tracking-wide text-muted`},yf={class:`whitespace-pre-wrap break-words`},bf=I({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=M([]),r=M(!1),i=M(null),a=M(!0),o=`${Y.base}/revisions/${t.type}/${t.id}`;aa(async()=>{try{let e=await X.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Z(`Put this version back? The text now is kept in the history.`))&&(await X.post(`${o}/${e.id}/restore`),$(Z(`The earlier version is back.`)),await y0())}let c=e=>new Date(e).toLocaleString(Y.locale||void 0);return(e,t)=>(V(),H(`section`,af,[W(`h2`,of,O(N(Z)(`History`)),1),a.value?(V(),H(`p`,sf,O(N(Z)(`Loading…`)),1)):n.value.length?(V(),H(`ul`,lf,[(V(!0),H(z,null,L(n.value,e=>(V(),H(`li`,{key:e.id,class:`py-3`},[W(`div`,uf,[W(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[W(`span`,ff,O(c(e.created_at)),1),e.user?(V(),H(`span`,pf,` · `+O(e.user),1)):q(``,!0),e.current?(V(),H(`span`,mf,O(N(Z)(`Now`)),1)):q(``,!0),W(`span`,hf,O(e.changed.join(`, `)),1)],8,df),r.value&&!e.current?(V(),H(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},O(N(Z)(`Put back`)),9,gf)):q(``,!0)]),i.value===e.id?(V(),H(`dl`,_f,[(V(!0),H(z,null,L(e.values,(e,t)=>(V(),H(`div`,{key:t},[W(`dt`,vf,O(t),1),W(`dd`,yf,O(e),1)]))),128))])):q(``,!0)]))),128))])):(V(),H(`p`,cf,O(N(Z)(`Nothing here yet.`)),1))]))}}),xf={class:`mb-6 flex items-center justify-between gap-3`},Sf={class:`font-display text-2xl font-bold`},Cf={for:`title`,class:`m-label`},wf={key:0,class:`m-error`},Tf={class:`grid gap-5 sm:grid-cols-2`},Ef={for:`slug`,class:`m-label`},Df={key:0,class:`m-error`},Of={for:`category`,class:`m-label`
Line truncated
|
||||
@@ -112,5 +112,29 @@
|
||||
"Put an earlier version of a post or page back": "Een eerdere versie van een bericht of pagina terugzetten",
|
||||
"Put an earlier version back": "Een eerdere versie teruggezet",
|
||||
"Opened the history of a text": "De geschiedenis van een tekst geopend",
|
||||
"Prove you are not a program, then log in again.": "Laat zien dat je geen programma bent en log dan opnieuw in."
|
||||
"Prove you are not a program, then log in again.": "Laat zien dat je geen programma bent en log dan opnieuw in.",
|
||||
"Finished or skipped the tour": "Rondleiding afgerond of overgeslagen",
|
||||
"Write and put news on your website": "Schrijf nieuws en zet het op je website",
|
||||
"Change the texts and photos of your pages": "Pas de teksten en foto's van je pagina's aan",
|
||||
"Your photos and files": "Je foto's en bestanden",
|
||||
"Settings": "Instellingen",
|
||||
"Switch parts and features on or off and change settings": "Onderdelen en functies aan- of uitzetten en instellingen wijzigen",
|
||||
"Change keys, passwords and addresses of integrations": "Sleutels, wachtwoorden en adressen van koppelingen wijzigen",
|
||||
"Changed the settings": "Instellingen gewijzigd",
|
||||
"Refreshed the settings": "Instellingen ververst",
|
||||
"Opened the settings": "Instellingen geopend",
|
||||
"This setting does not exist or you may not change it.": "Deze instelling bestaat niet of je mag hem niet wijzigen.",
|
||||
"This value is not valid.": "Deze waarde is niet geldig.",
|
||||
"Type your own password to change this.": "Typ je eigen wachtwoord om dit te wijzigen.",
|
||||
"Parts of the manager": "Onderdelen van de manager",
|
||||
"IriksIT API": "IriksIT API",
|
||||
"Login": "Inloggen",
|
||||
"Site": "Site",
|
||||
"Disk for new media files": "Schijf voor nieuwe mediabestanden",
|
||||
"IriksIT API: address": "IriksIT API: adres",
|
||||
"IriksIT API: account": "IriksIT API: account",
|
||||
"IriksIT API: password": "IriksIT API: wachtwoord",
|
||||
"Turnstile: site key": "Turnstile: sitesleutel",
|
||||
"Turnstile: secret key": "Turnstile: geheime sleutel",
|
||||
"With its version, for example https://api.iriks-it.nl/v1": "Met de versie erbij, bijvoorbeeld https://api.iriks-it.nl/v1"
|
||||
}
|
||||
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 79 KiB |
@@ -3,8 +3,10 @@
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Http\Controllers\AssetController;
|
||||
use IriksIT\Manager\Http\Controllers\LoginController;
|
||||
use IriksIT\Manager\Http\Controllers\MascotController;
|
||||
|
||||
// Outside `auth`: the login of the manager (the page itself is the shell, the answer is JSON) and its built files.
|
||||
Route::get('/_assets/{file}', AssetController::class)->name('assets')->where('file', '[a-z.]+');
|
||||
Route::get('/_assets/mascot/{name}', MascotController::class)->name('mascot')->where('name', '[a-z]+');
|
||||
Route::get('/login', fn () => abort(404))->name('login'); // the shell answers browsers before this runs
|
||||
Route::post('/login', [LoginController::class, 'store'])->name('login.store')->middleware('throttle:manager-login');
|
||||
@@ -10,6 +10,7 @@ Route::get('/', DashboardController::class)->name('dashboard');
|
||||
Route::get('/profile', [ProfileController::class, 'show'])->name('profile.show');
|
||||
Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update');
|
||||
Route::put('/profile/view', [ProfileController::class, 'view'])->name('profile.view');
|
||||
Route::put('/profile/tutorial', [ProfileController::class, 'tutorial'])->name('profile.tutorial');
|
||||
Route::post('/markdown', MarkdownController::class)->name('markdown.preview')->middleware('throttle:120,1');
|
||||
Route::post('/logout', [LoginController::class, 'destroy'])->name('logout');
|
||||
|
||||
|
||||
@@ -20,7 +20,17 @@ trait HasManagerAccess
|
||||
/** @return BelongsToMany<Group, $this> */
|
||||
public function managerGroups(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id');
|
||||
return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id')->withPivot('is_primary');
|
||||
}
|
||||
|
||||
/**
|
||||
* The group this account is filed under: a label and a start screen, nothing more. What the account may do is
|
||||
* always the sum of all its groups, the primary one included.
|
||||
*/
|
||||
public function managerPrimaryGroup(): ?Group
|
||||
{
|
||||
// A group that was attached without a choice (by the site itself) makes the first one the primary one.
|
||||
return $this->managerGroups->first(fn (Group $group) => (bool) $group->pivot->is_primary) ?? $this->managerGroups->sortBy('id')->first();
|
||||
}
|
||||
|
||||
public function isManagerSuperAdmin(): bool
|
||||
|
||||
@@ -16,14 +16,15 @@ use IriksIT\Manager\Support\Importer;
|
||||
*/
|
||||
class ImportCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:import {target : posts, pages or reviews}
|
||||
protected $signature = 'manager:import {target : posts, pages, reviews or media}
|
||||
{--table= : Table to read (default: config manager.import.<target>.table)}
|
||||
{--connection= : Database connection of that table (default: the default one)}
|
||||
{--map=* : package_column=source_column, repeat for each column that is named differently}
|
||||
{--set=* : package_column=value, a value for every row that has none (for media: --set=disk=iriksit)}
|
||||
{--limit= : Only the first rows}
|
||||
{--dry-run : Count what would happen and write nothing}';
|
||||
|
||||
protected $description = 'Copy the existing posts, pages or reviews of the site into the package tables';
|
||||
protected $description = 'Copy the existing posts, pages, reviews or media rows of the site into the package tables';
|
||||
|
||||
public function handle(Importer $importer): int
|
||||
{
|
||||
@@ -50,9 +51,22 @@ class ImportCommand extends Command
|
||||
$map[trim($to)] = trim($from);
|
||||
}
|
||||
|
||||
$fixed = [];
|
||||
|
||||
foreach ((array) $this->option('set') as $pair) {
|
||||
if (! str_contains((string) $pair, '=')) {
|
||||
$this->error("--set wants package_column=value, got {$pair}");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
[$column, $value] = explode('=', (string) $pair, 2);
|
||||
$fixed[trim($column)] = $value;
|
||||
}
|
||||
|
||||
try {
|
||||
$connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null));
|
||||
$result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null);
|
||||
$result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null, $fixed);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$this->error($e->getMessage());
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Modules\Media\MediaLibrary;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Moves the files of the media library to another disk, for instance from this server to the IriksIT API. The address of a file
|
||||
* does not change, so nothing that uses it needs editing. Safe to run again: what already lives on the disk is skipped, and a
|
||||
* file that fails stays where it was.
|
||||
*
|
||||
* php artisan manager:media-move iriksit --dry-run
|
||||
* php artisan manager:media-move iriksit --from=public --verify --delete-source
|
||||
*/
|
||||
class MediaMoveCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:media-move {to : The disk to move the files to}
|
||||
{--from= : Only move the files that are on this disk}
|
||||
{--limit=0 : Move at most this many files (0 = all)}
|
||||
{--verify : Read each copy back and compare it with the checksum}
|
||||
{--delete-source : Delete the original after the copy was checked}
|
||||
{--dry-run : Only show what would be moved}';
|
||||
|
||||
protected $description = 'Move the files of the media library to another disk';
|
||||
|
||||
public function handle(MediaLibrary $library): int
|
||||
{
|
||||
$to = (string) $this->argument('to');
|
||||
|
||||
if (config("filesystems.disks.{$to}") === null) {
|
||||
$this->error("There is no disk called {$to}.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$limit = max((int) $this->option('limit'), 0);
|
||||
$maxBytes = max(1, (int) config('manager.media.max_file_mb')) * 1024 * 1024;
|
||||
[$moved, $skipped, $failed] = [0, 0, 0];
|
||||
|
||||
$query = Media::query()->where('disk', '!=', $to)->when($this->option('from'), fn ($q, $from) => $q->where('disk', $from))->orderBy('id');
|
||||
|
||||
foreach ($query->get() as $media) {
|
||||
if ($limit > 0 && $moved + $failed >= $limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
$label = "#{$media->id} {$media->filename}";
|
||||
|
||||
if (! Storage::disk($media->disk)->exists($media->location)) {
|
||||
$this->warn("{$label}: not on the `{$media->disk}` disk, skipped.");
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) $media->size > $maxBytes) {
|
||||
$this->warn("{$label}: larger than manager.media.max_file_mb, stays where it is.");
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($dryRun) {
|
||||
$this->line("{$label}: would be moved from `{$media->disk}`.");
|
||||
$moved++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$library->move($media, $to, (bool) $this->option('delete-source'), (bool) $this->option('verify'));
|
||||
} catch (MediaStorageException|Throwable $e) {
|
||||
$this->error("{$label}: could not be moved, left where it is ({$e->getMessage()})");
|
||||
$failed++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line("{$label}: moved.");
|
||||
$moved++;
|
||||
}
|
||||
|
||||
$this->info(($dryRun ? 'Would move' : 'Moved')." {$moved}, skipped {$skipped}, failed {$failed}.");
|
||||
|
||||
if (! $dryRun && $failed === 0 && config('manager.media.disk') !== $to) {
|
||||
$this->warn("manager.media.disk is not `{$to}` yet: new uploads still go to `".config('manager.media.disk').'`.');
|
||||
}
|
||||
|
||||
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Modules\Media\MediaLibrary;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Finds files of the media library that nothing uses any more (no post, page or other registered source holds their address),
|
||||
* and with `--delete` removes them. Nothing is deleted without `--delete`, and only files older than `--older-than` days.
|
||||
* `--orphans` looks for the opposite: files on a disk that no row knows (only for a disk that can list its files).
|
||||
*
|
||||
* php artisan manager:media-prune --older-than=30
|
||||
* php artisan manager:media-prune --older-than=30 --delete
|
||||
* php artisan manager:media-prune --orphans --disk=public
|
||||
*/
|
||||
class MediaPruneCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:media-prune
|
||||
{--older-than=30 : Only files that were added more than this many days ago}
|
||||
{--delete : Really delete (without this it only lists)}
|
||||
{--orphans : List (and with --delete, remove) files on the disk that no media row knows}
|
||||
{--disk= : For --orphans: the disk to look at (default: the disk of the media library)}';
|
||||
|
||||
protected $description = 'Find media files that nothing uses any more, and delete them on request';
|
||||
|
||||
public function handle(MediaLibrary $library): int
|
||||
{
|
||||
return $this->option('orphans') ? $this->orphans() : $this->unused($library);
|
||||
}
|
||||
|
||||
private function unused(MediaLibrary $library): int
|
||||
{
|
||||
$days = max(0, (int) $this->option('older-than'));
|
||||
$candidates = Media::query()->where('created_at', '<', now()->subDays($days))->orderBy('id')->get();
|
||||
$counts = $library->usageCounts($candidates);
|
||||
$found = $deleted = $failed = 0;
|
||||
|
||||
foreach ($candidates as $media) {
|
||||
if (($counts[$media->id] ?? 0) > 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$found++;
|
||||
$label = "#{$media->id} {$media->filename} (".round($media->size / 1024).' KB)';
|
||||
|
||||
if (! $this->option('delete')) {
|
||||
$this->line("{$label}: not used.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$library->delete($media);
|
||||
$this->line("{$label}: deleted.");
|
||||
$deleted++;
|
||||
} catch (Throwable $e) {
|
||||
$this->error("{$label}: could not be deleted ({$e->getMessage()})");
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->info($this->option('delete') ? "Deleted {$deleted}, failed {$failed}." : "{$found} not used. Run again with --delete to remove them.");
|
||||
|
||||
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
private function orphans(): int
|
||||
{
|
||||
$name = (string) ($this->option('disk') ?: config('manager.media.disk'));
|
||||
$known = Media::query()->where('disk', $name)->pluck('location')->flip();
|
||||
$disk = Storage::disk($name);
|
||||
|
||||
try {
|
||||
$files = $disk->allFiles('media');
|
||||
} catch (Throwable) {
|
||||
$files = [];
|
||||
}
|
||||
|
||||
if ($files === [] && Media::query()->where('disk', $name)->exists()) {
|
||||
$this->warn("The disk `{$name}` cannot list its files (or has none), so there is nothing to compare.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$found = 0;
|
||||
|
||||
foreach ($files as $file) {
|
||||
if ($known->has($file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$found++;
|
||||
$this->line($this->option('delete') ? "{$file}: ".($disk->delete($file) ? 'deleted.' : 'could not be deleted.') : "{$file}: no row knows it.");
|
||||
}
|
||||
|
||||
$this->info($this->option('delete') ? "Looked at {$found} unknown files." : "{$found} files that no row knows. Run again with --delete to remove them.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Support\Settings\Definitions;
|
||||
use IriksIT\Manager\Support\Settings\Store;
|
||||
use IriksIT\Manager\Support\Settings\Writer;
|
||||
|
||||
/**
|
||||
* The settings screen in the terminal, for scripts, deploys and agents. Whoever may run this may change everything, so there is
|
||||
* no password or right to ask for. A secret is never printed, and its value is typed hidden (or read from standard input), never
|
||||
* given as an argument that would stay in the history of the shell.
|
||||
*
|
||||
* php artisan manager:settings list
|
||||
* php artisan manager:settings set manager.modules.reviews true
|
||||
* php artisan manager:settings set manager.media.iriksit.password (asks, hidden)
|
||||
* echo "$SECRET" | php artisan manager:settings set manager.login.turnstile.secret --stdin
|
||||
* php artisan manager:settings reset manager.modules.reviews
|
||||
* php artisan manager:settings refresh
|
||||
*/
|
||||
class SettingsCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:settings {action : list, get, set, reset or refresh}
|
||||
{key? : The config path of the setting, like manager.modules.reviews}
|
||||
{value? : The new value (not for a secret)}
|
||||
{--stdin : Read the value from standard input (for a secret in a script)}
|
||||
{--json : list: print JSON}';
|
||||
|
||||
protected $description = 'List, read, change or reset the settings of the settings screen';
|
||||
|
||||
public function handle(Definitions $definitions, Store $store, Writer $writer): int
|
||||
{
|
||||
$action = (string) $this->argument('action');
|
||||
|
||||
if ($action === 'refresh') {
|
||||
$this->info($writer->refresh() ? 'Refreshed.' : 'The caches are emptied, but the file bootstrap/cache/manager-settings.php could not be written.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($action === 'list') {
|
||||
return $this->list($definitions, $store);
|
||||
}
|
||||
|
||||
if (! in_array($action, ['get', 'set', 'reset'], true)) {
|
||||
$this->error('Use one of: list, get, set, reset, refresh.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$key = (string) $this->argument('key');
|
||||
$definition = $definitions->find($key);
|
||||
|
||||
if ($definition === null) {
|
||||
$this->error("There is no setting {$key}. See: php artisan manager:settings list");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($action === 'get') {
|
||||
$this->line($definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($action === 'reset') {
|
||||
$result = $writer->apply([$key => null]);
|
||||
$this->info("{$key} is back to what the config says.".($result['file_written'] ? '' : ' (The compiled file could not be written.)'));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
return $this->set($definitions, $writer, $definition);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $definition */
|
||||
private function set(Definitions $definitions, Writer $writer, array $definition): int
|
||||
{
|
||||
$key = $definition['key'];
|
||||
|
||||
if ($this->option('stdin')) {
|
||||
$raw = rtrim((string) stream_get_contents(STDIN), "\r\n");
|
||||
} elseif ($definition['type'] === 'secret') {
|
||||
if ($this->argument('value') !== null) {
|
||||
$this->error('Do not type a secret as an argument: it stays in the history of the shell. Leave it out to be asked, or use --stdin.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$raw = (string) $this->secret($definition['label']);
|
||||
} else {
|
||||
$raw = $this->argument('value');
|
||||
|
||||
if ($raw === null) {
|
||||
$this->error('Which value? php artisan manager:settings set '.$key.' <value>');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$value = $definitions->cast($definition, $raw);
|
||||
} catch (\InvalidArgumentException) {
|
||||
$this->error('This value is not valid for '.$key.' ('.$definition['type'].').');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$result = $writer->apply([$key => $value]);
|
||||
$this->info("{$key} is set.".($result['env_written'] ? ' Written into .env too.' : '').($result['file_written'] ? '' : ' (The compiled file could not be written: run `manager:settings refresh` when it can.)'));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function list(Definitions $definitions, Store $store): int
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
foreach ($definitions->all() as $key => $definition) {
|
||||
$rows[] = [
|
||||
'key' => $key,
|
||||
'type' => $definition['type'],
|
||||
'value' => $definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)),
|
||||
'saved' => $store->has($key),
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->table(['Setting', 'Type', 'Value', 'Saved here'], array_map(fn ($row) => [$row['key'], $row['type'], $row['value'], $row['saved'] ? 'yes' : ''], $rows));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function show(mixed $value): string
|
||||
{
|
||||
return is_bool($value) ? ($value ? 'true' : 'false') : (string) ($value ?? '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Tries the disk of the media library the way a real upload would: writes a small file, reads it back, checks that it is
|
||||
* the same and deletes it again. Leaves nothing behind (when the delete fails, it says which file is left).
|
||||
*
|
||||
* php artisan manager:storage-check [--disk=iriksit]
|
||||
*/
|
||||
class StorageCheckCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:storage-check {--disk= : The disk to try; default: the disk of the media library}';
|
||||
|
||||
protected $description = 'Write, read and delete a test file on the disk of the media library';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$name = (string) ($this->option('disk') ?: config('manager.media.disk'));
|
||||
$disk = Storage::disk($name);
|
||||
$location = 'manager-check/'.bin2hex(random_bytes(6)).'.txt';
|
||||
$content = 'manager storage check '.now()->toIso8601String();
|
||||
|
||||
$this->line("Disk: {$name}");
|
||||
|
||||
try {
|
||||
$step = 'write';
|
||||
if (! $disk->put($location, $content)) {
|
||||
$this->components->error('The file could not be written. See the log of the app for the reason.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->components->info('Written.');
|
||||
|
||||
$step = 'read';
|
||||
$back = $disk->get($location);
|
||||
if ($back !== $content) {
|
||||
$this->components->error('What was read back is not what was written.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->components->info('Read back: the same.');
|
||||
|
||||
$step = 'delete';
|
||||
if (! $disk->delete($location)) {
|
||||
$this->components->error("The test file could not be deleted: {$location}");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->components->info('Deleted.');
|
||||
} catch (MediaStorageException|Throwable $e) {
|
||||
$this->components->error("Could not {$step}: ".$e->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->components->info('The storage works.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* The accounts of the manager, with their groups. `--json` for scripts and agents.
|
||||
*
|
||||
* php artisan manager:users [--json]
|
||||
*/
|
||||
class UserListCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:users {--json : Print JSON}';
|
||||
|
||||
protected $description = 'List the accounts of the manager with their groups';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
$rows = [];
|
||||
|
||||
foreach ($model::query()->with('managerGroups')->orderBy('id')->get() as $user) {
|
||||
$primary = $user->managerPrimaryGroup();
|
||||
|
||||
$rows[] = [
|
||||
'id' => $user->getKey(),
|
||||
'name' => (string) $user->name,
|
||||
'email' => (string) $user->email,
|
||||
'super_admin' => $user->isManagerSuperAdmin(),
|
||||
'primary_group' => $primary?->name,
|
||||
'groups' => $user->managerGroups->pluck('name')->sort()->values()->all(),
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->table(['Id', 'Name', 'Email', 'Super admin', 'Primary group', 'Groups'], array_map(
|
||||
fn ($row) => [$row['id'], $row['name'], $row['email'], $row['super_admin'] ? 'yes' : '', $row['primary_group'] ?? '', implode(', ', $row['groups'])],
|
||||
$rows,
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Sets a new password for an account, for someone who cannot log in. Typed hidden by default; `--generate` makes a long random
|
||||
* one and shows it once. The password is never an argument (it would stay in the history of the shell).
|
||||
*
|
||||
* php artisan manager:user-password someone@example.com [--generate]
|
||||
*/
|
||||
class UserPasswordCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:user-password {email : The email address of the account}
|
||||
{--generate : Make a random password and show it once}';
|
||||
|
||||
protected $description = 'Set a new password for an account of the manager';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
$user = $model::query()->where('email', strtolower((string) $this->argument('email')))->first();
|
||||
|
||||
if ($user === null) {
|
||||
$this->error('There is no account with that email address.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($this->option('generate')) {
|
||||
$password = Str::password(20, symbols: false);
|
||||
} else {
|
||||
$password = (string) $this->secret('New password (min 12 characters)');
|
||||
|
||||
if (mb_strlen($password) < 12) {
|
||||
$this->error('The password must be at least 12 characters.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($password !== (string) $this->secret('Once more')) {
|
||||
$this->error('The two passwords are not the same.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
$user->forceFill(['password' => Hash::make($password)])->save();
|
||||
$this->info("New password for {$user->email} is set.");
|
||||
$this->option('generate') && $this->line($password);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* The pictures of the tour. A picture is `<name>.webp` or `<name>.png` in `manager.mascot.path` (default: resources/mascot of
|
||||
* the package); a site can give its own set by pointing the path at a folder of its own. A picture that is not there is
|
||||
* answered with a small paw, so the tour works before the pictures do.
|
||||
*/
|
||||
class MascotController
|
||||
{
|
||||
/** What the tour asks for. */
|
||||
public const NAMES = ['welcome', 'point', 'calm', 'write', 'photos', 'pages', 'undo', 'oops', 'party', 'profile', 'peek'];
|
||||
|
||||
private const TYPES = ['webp' => 'image/webp', 'png' => 'image/png'];
|
||||
|
||||
public function __invoke(string $name): BinaryFileResponse|Response
|
||||
{
|
||||
abort_unless(in_array($name, self::NAMES, true), 404);
|
||||
|
||||
$folder = rtrim((string) (config('manager.mascot.path') ?: __DIR__.'/../../../resources/mascot'), '/');
|
||||
|
||||
foreach (self::TYPES as $extension => $type) {
|
||||
if (is_file($path = "$folder/$name.$extension")) {
|
||||
return response()->file($path, ['Content-Type' => $type, 'Cache-Control' => 'public, max-age=86400', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
}
|
||||
|
||||
return response(self::paw(), 200, ['Content-Type' => 'image/svg+xml', 'Cache-Control' => 'public, max-age=300', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
/** A paw: the stand-in for every picture that is not there yet. */
|
||||
private static function paw(): string
|
||||
{
|
||||
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><g fill="#f43f7a">'
|
||||
.'<ellipse cx="64" cy="84" rx="26" ry="22"/><ellipse cx="26" cy="58" rx="11" ry="15" transform="rotate(-20 26 58)"/>'
|
||||
.'<ellipse cx="50" cy="38" rx="11" ry="15" transform="rotate(-8 50 38)"/><ellipse cx="78" cy="38" rx="11" ry="15" transform="rotate(8 78 38)"/>'
|
||||
.'<ellipse cx="102" cy="58" rx="11" ry="15" transform="rotate(20 102 58)"/></g></svg>';
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ class ProfileController
|
||||
'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(),
|
||||
'groups' => method_exists($user, 'managerGroups') ? $user->managerGroups()->pluck('name')->values() : [],
|
||||
'theme' => $themes->keyFor($user),
|
||||
'locale' => UserSetting::value($user, 'locale') ?? app()->getLocale(),
|
||||
'locales' => UserSetting::LOCALES,
|
||||
'tutorial' => UserSetting::value($user, 'tutorial'),
|
||||
'themes' => config('manager.user_themes')
|
||||
? collect($themes->all())->map(fn (array $theme, string $key) => ['key' => $key, 'label' => __($theme['label']), 'colors' => $theme['colors']])->values()
|
||||
: [],
|
||||
@@ -36,11 +39,20 @@ class ProfileController
|
||||
abort_unless($menu->maySwitch($request->user()), 403);
|
||||
|
||||
$data = $request->validate(['view' => ['required', Rule::in([Menu::FULL, Menu::SIMPLE])]]);
|
||||
UserSetting::query()->updateOrCreate(['user_id' => $request->user()->getKey()], ['view' => $data['view']]);
|
||||
UserSetting::put($request->user(), ['view' => $data['view']]);
|
||||
|
||||
return response()->json(['view' => $data['view']]);
|
||||
}
|
||||
|
||||
/** Where the account stands with the tour: finished, skipped, or (to look at it again) pending. Any account may, for itself. */
|
||||
public function tutorial(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['state' => ['required', Rule::in(UserSetting::TUTORIAL)]]);
|
||||
UserSetting::put($request->user(), ['tutorial' => $data['state']]);
|
||||
|
||||
return response()->json(['tutorial' => $data['state']]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Themes $themes): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
@@ -51,6 +63,7 @@ class ProfileController
|
||||
'current_password' => ['nullable', 'string', 'max:200'],
|
||||
'password' => ['nullable', 'string', 'min:12', 'max:200', 'confirmed'],
|
||||
'theme' => ['nullable', 'string', Rule::in(array_keys($themes->all()))],
|
||||
'locale' => ['nullable', 'string', Rule::in(UserSetting::LOCALES)],
|
||||
]);
|
||||
|
||||
if (($data['password'] ?? '') !== '' && ! Hash::check((string) ($data['current_password'] ?? ''), $user->getAuthPassword())) {
|
||||
@@ -62,7 +75,11 @@ class ProfileController
|
||||
$user->save();
|
||||
|
||||
if (config('manager.user_themes') && $request->has('theme')) {
|
||||
UserSetting::query()->updateOrCreate(['user_id' => $user->getKey()], ['theme' => $data['theme'] ?: null]);
|
||||
UserSetting::put($user, ['theme' => $data['theme'] ?: null]);
|
||||
}
|
||||
|
||||
if ($request->has('locale')) {
|
||||
UserSetting::put($user, ['locale' => $data['locale'] ?: null]);
|
||||
}
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
|
||||
@@ -10,8 +10,8 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The screens are one page that asks the JSON routes for its data. A browser that opens a manager address gets that
|
||||
* page; the page itself, and anything else that asks for JSON, gets the data. Downloads (route names `*.export`) and the
|
||||
* built files are left alone.
|
||||
* page; the page itself, and anything else that asks for JSON, gets the data. Downloads (route names `*.export`), the
|
||||
* built files and the pictures of the tour are left alone.
|
||||
*/
|
||||
class ServeShell
|
||||
{
|
||||
@@ -23,7 +23,7 @@ class ServeShell
|
||||
|
||||
$name = (string) $request->route()?->getName();
|
||||
|
||||
if ($name === Names::route('assets') || str_ends_with($name, '.export')) {
|
||||
if (in_array($name, [Names::route('assets'), Names::route('mascot')], true) || str_ends_with($name, '.export')) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The language an account chose applies to everything the manager says to it (menu, messages, the shell), inside the
|
||||
* manager's routes only: the site's own pages keep the language of the site. Nothing chosen: the language of the app.
|
||||
*/
|
||||
class SetLocale
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$chosen = UserSetting::value($request->user(), 'locale');
|
||||
|
||||
if (in_array($chosen, UserSetting::LOCALES, true)) {
|
||||
app()->setLocale($chosen);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,17 @@
|
||||
namespace IriksIT\Manager;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Filesystem\FilesystemAdapter;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use IriksIT\Manager\Support\IriksStorage;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use League\Flysystem\Filesystem;
|
||||
|
||||
class ManagerServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -20,13 +24,16 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
|
||||
|
||||
// What was set on the settings screen goes over the config before anything reads it.
|
||||
Support\Settings\Store::overlay();
|
||||
|
||||
$this->app->singleton(Support\MediaUsage::class);
|
||||
$this->app->singleton(Support\AuditTrail::class);
|
||||
$this->app->singleton(Modules\Posts\PostLabels::class);
|
||||
|
||||
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
|
||||
// A config that was published before resources existed does not list their module.
|
||||
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class])),
|
||||
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class, Modules\Settings\SettingsModule::class])),
|
||||
$app['config']->get('manager.modules', []),
|
||||
));
|
||||
}
|
||||
@@ -42,8 +49,11 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
|
||||
$this->app['router']->aliasMiddleware('manager.auth', Http\Middleware\Authenticate::class);
|
||||
$this->app['router']->aliasMiddleware('manager.shell', Http\Middleware\ServeShell::class);
|
||||
$this->app['router']->aliasMiddleware('manager.locale', Http\Middleware\SetLocale::class);
|
||||
RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip()));
|
||||
|
||||
$this->registerIriksStorage();
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
if ($module->migrations() !== null) {
|
||||
$this->loadMigrationsFrom($module->migrations());
|
||||
@@ -57,13 +67,31 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
}
|
||||
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class]);
|
||||
$this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class, Console\StorageCheckCommand::class, Console\MediaMoveCommand::class, Console\SettingsCommand::class, Console\UserListCommand::class, Console\UserPasswordCommand::class, Console\MediaPruneCommand::class]);
|
||||
}
|
||||
|
||||
$this->registerGates($modules);
|
||||
$this->registerRoutes($modules);
|
||||
}
|
||||
|
||||
/**
|
||||
* The disk `iriksit`: files at the IriksIT API. A site that wants it sets `manager.media.disk` to `iriksit` (or any disk
|
||||
* of its own with `driver` => `iriksit` in config/filesystems.php) and gives the address and the account
|
||||
* in `manager.media.iriksit`. The disk is added here when the site has not made one itself.
|
||||
*/
|
||||
private function registerIriksStorage(): void
|
||||
{
|
||||
Storage::extend('iriksit', function ($app, array $config) {
|
||||
$adapter = new IriksStorage\Adapter(new IriksStorage\Client($config));
|
||||
|
||||
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
|
||||
});
|
||||
|
||||
if (config('filesystems.disks.iriksit') === null) {
|
||||
config(['filesystems.disks.iriksit' => ['driver' => 'iriksit', ...(array) config('manager.media.iriksit', [])]]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One gate per permission, and no Gate::before: a package must never answer for abilities
|
||||
* of the host app. A super admin passes inside hasManagerPermission, for these gates only.
|
||||
@@ -89,7 +117,7 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php'));
|
||||
}
|
||||
|
||||
Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')])
|
||||
Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), 'manager.locale', ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')])
|
||||
->prefix(config('manager.path'))
|
||||
->name(Names::routePrefix())
|
||||
->group(function () use ($modules) {
|
||||
|
||||
@@ -5,10 +5,28 @@ namespace IriksIT\Manager\Models;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** What one account chose for itself in the manager (its theme and which face of the manager it looks at). */
|
||||
/** What one account chose for itself in the manager: its theme, which face of the manager it looks at, its language and where it stands with the tour. */
|
||||
class UserSetting extends Model
|
||||
{
|
||||
protected $fillable = ['user_id', 'theme', 'view'];
|
||||
protected $fillable = ['user_id', 'theme', 'view', 'locale', 'tutorial'];
|
||||
|
||||
/** The languages the screens come in. */
|
||||
public const LOCALES = ['en', 'nl'];
|
||||
|
||||
/** Where an account stands with the tour: `pending` shows it at the next load; `done` and `skipped` never again until it is set to pending. */
|
||||
public const TUTORIAL = ['pending', 'done', 'skipped'];
|
||||
|
||||
/** What this account chose (a row is made when it has none yet). */
|
||||
public static function put(object $user, array $values): void
|
||||
{
|
||||
static::query()->updateOrCreate(['user_id' => $user->getKey()], $values);
|
||||
}
|
||||
|
||||
/** One value of what this account chose, or null. */
|
||||
public static function value(?object $user, string $column): ?string
|
||||
{
|
||||
return $user === null || $user->getKey() === null ? null : static::query()->where('user_id', $user->getKey())->value($column);
|
||||
}
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
|
||||
@@ -55,6 +55,18 @@ abstract class BaseModule implements Module
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps this module adds to the tour. Each: `title` and `text` (English, translated through `__()`), an optional `image` (one of
|
||||
* the pictures of the tour, `MascotController::NAMES`), `menu` (the short route name of a menu item to point at, like `reviews.index`)
|
||||
* and `permission` (the step is left out for an account without it). The contract `Module` does not know this: a module without it adds none.
|
||||
*
|
||||
* @return list<array{title: string, text: string, image?: string, menu?: string, permission?: string}>
|
||||
*/
|
||||
public function tutorial(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [];
|
||||
|
||||
@@ -55,6 +55,56 @@ class MediaLibrary
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a file to another disk: copy it (the same location on the new disk), check the size (and, with $verify, what comes
|
||||
* back), only then point the row at the new disk and, when asked, delete the original. The address of the file does not
|
||||
* change, because it holds the id of the row. A file that is already there is not copied again.
|
||||
*
|
||||
* @throws MediaStorageException with the file still where it was
|
||||
*/
|
||||
public function move(Media $media, string $disk, bool $deleteSource = false, bool $verify = false): void
|
||||
{
|
||||
$from = Storage::disk($media->disk);
|
||||
$to = Storage::disk($disk);
|
||||
|
||||
$wrote = false;
|
||||
|
||||
if (! $to->exists($media->location)) {
|
||||
$stream = $this->open($media);
|
||||
|
||||
try {
|
||||
$stored = $to->put($media->location, $stream);
|
||||
} finally {
|
||||
is_resource($stream) && fclose($stream);
|
||||
}
|
||||
|
||||
if ($stored === false) {
|
||||
throw new MediaStorageException('The file could not be written to the new disk.');
|
||||
}
|
||||
|
||||
$wrote = true;
|
||||
}
|
||||
|
||||
if ($to->size($media->location) !== (int) $media->size) {
|
||||
$wrote && $to->delete($media->location);
|
||||
|
||||
throw new MediaStorageException('The copy on the new disk is not the size of the original.');
|
||||
}
|
||||
|
||||
if ($verify && $media->checksum !== null && hash('sha256', (string) $to->get($media->location)) !== $media->checksum) {
|
||||
$wrote && $to->delete($media->location);
|
||||
|
||||
throw new MediaStorageException('The copy on the new disk is not the same as the original.');
|
||||
}
|
||||
|
||||
$source = $media->disk;
|
||||
$media->update(['disk' => $disk]);
|
||||
|
||||
if ($deleteSource && $source !== $disk) {
|
||||
Storage::disk($source)->delete($media->location);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How full the library is: what all files together take, how much it may hold
|
||||
* (`manager.media.max_total_gb`) and what is left. In bytes.
|
||||
|
||||
@@ -28,7 +28,7 @@ class MediaModule extends BaseModule
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['media'];
|
||||
return ['media', 'storage_files'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
@@ -44,7 +44,7 @@ class MediaModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view'],
|
||||
['label' => 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view', 'simple' => true, 'hint' => 'Your photos and files'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// The IriksIT API knows a file by an id of its own: this remembers which id belongs to which path of the `iriksit` disk.
|
||||
Schema::create(Names::table('storage_files'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('path')->unique();
|
||||
$table->string('remote_id', 100);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('storage_files'));
|
||||
}
|
||||
};
|
||||
@@ -40,7 +40,7 @@ class PagesModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit'],
|
||||
['label' => 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit', 'simple' => true, 'hint' => 'Change the texts and photos of your pages'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ class PostsModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view'],
|
||||
['label' => 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view', 'simple' => true, 'hint' => 'Write and put news on your website'],
|
||||
['label' => 'Categories and tags', 'route' => Names::route('labels.index'), 'permission' => 'posts.labels'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ class ResourcesModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view'],
|
||||
fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view', 'simple' => true, 'hint' => $resource['hint']],
|
||||
Resources::all(),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Settings;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Settings\Definitions;
|
||||
use IriksIT\Manager\Support\Settings\EnvFile;
|
||||
use IriksIT\Manager\Support\Settings\Store;
|
||||
use IriksIT\Manager\Support\Settings\Writer;
|
||||
|
||||
/**
|
||||
* The settings screen. Only in the whole face of the manager (a simple account gets a 403, whatever its rights). What changes
|
||||
* how a password or a file travels (secrets, addresses, accounts, disks) also needs `settings.secrets` and the password of the
|
||||
* account that saves it. A secret is never sent to the browser: it is only said to be set.
|
||||
*/
|
||||
class SettingsController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Definitions $definitions,
|
||||
private readonly Store $store,
|
||||
private readonly EnvFile $env,
|
||||
private readonly Writer $writer,
|
||||
private readonly ModuleRegistry $modules,
|
||||
private readonly Menu $menu,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
|
||||
$groups = [];
|
||||
|
||||
foreach ($this->definitions->all() as $key => $definition) {
|
||||
if (! $this->mayChange($request, $definition)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = config($key);
|
||||
|
||||
$groups[__($definition['group'])][] = [
|
||||
'key' => $key,
|
||||
'label' => __($definition['label']),
|
||||
'type' => $definition['type'],
|
||||
'help' => $definition['help'] === null ? null : __($definition['help']),
|
||||
'options' => $definition['options'],
|
||||
'sensitive' => $definition['sensitive'],
|
||||
// A secret says only whether it is set.
|
||||
'value' => $definition['type'] === 'secret' ? null : $value,
|
||||
'set' => $definition['type'] === 'secret' ? filled($value) : null,
|
||||
'saved' => $this->store->has($key),
|
||||
];
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'groups' => collect($groups)->map(fn (array $items, string $name) => ['name' => $name, 'items' => $items])->values(),
|
||||
'write_env' => (bool) config('manager.settings.write_env'),
|
||||
'env_writable' => $this->env->writable(),
|
||||
'config_cached' => app()->configurationIsCached(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
$request->validate(['values' => ['present', 'array'], 'reset' => ['nullable', 'array'], 'reset.*' => ['string'], 'password' => ['nullable', 'string', 'max:200']]);
|
||||
|
||||
$changes = [];
|
||||
$sensitive = false;
|
||||
|
||||
foreach ($request->array('values') as $key => $raw) {
|
||||
$definition = $this->definitions->find((string) $key);
|
||||
|
||||
if ($definition === null || ! $this->mayChange($request, $definition)) {
|
||||
throw ValidationException::withMessages(['values' => __('This setting does not exist or you may not change it.')]);
|
||||
}
|
||||
|
||||
// A secret that is left empty is left alone (the browser sends an empty field as null): clearing one is `reset`.
|
||||
if ($definition['type'] === 'secret' && ($raw === '' || $raw === null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$value = $raw === null ? null : $this->definitions->cast($definition, $raw);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages(['values.'.$key => __('This value is not valid.')]);
|
||||
}
|
||||
|
||||
if ($value !== null && $value === config($key) && ! $this->store->has($key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$changes[$key] = $value;
|
||||
$sensitive = $sensitive || $definition['sensitive'];
|
||||
}
|
||||
|
||||
// `reset`: back to what the config (and .env) says.
|
||||
foreach ($request->array('reset') as $key) {
|
||||
$definition = $this->definitions->find((string) $key);
|
||||
|
||||
if ($definition === null || ! $this->mayChange($request, $definition)) {
|
||||
throw ValidationException::withMessages(['reset' => __('This setting does not exist or you may not change it.')]);
|
||||
}
|
||||
|
||||
$changes[$key] = null;
|
||||
$sensitive = $sensitive || $definition['sensitive'];
|
||||
}
|
||||
|
||||
if ($sensitive && ! Hash::check((string) $request->input('password'), (string) $request->user()->getAuthPassword())) {
|
||||
throw ValidationException::withMessages(['password' => __('Type your own password to change this.')]);
|
||||
}
|
||||
|
||||
$result = $this->writer->apply($changes, $request->user()->getAuthIdentifier());
|
||||
|
||||
return response()->json([
|
||||
'saved' => true,
|
||||
'changed' => count($changes),
|
||||
...$result,
|
||||
'migrate' => $this->pendingMigrations(array_keys($changes)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Writes the compiled file again and empties what caches the old values. */
|
||||
public function refresh(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
|
||||
$written = $this->writer->refresh();
|
||||
|
||||
return response()->json(['refreshed' => true, 'file_written' => $written]);
|
||||
}
|
||||
|
||||
private function onlyFull(Request $request): void
|
||||
{
|
||||
abort_if($this->menu->view($request->user()) === Menu::SIMPLE, 403);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $definition */
|
||||
private function mayChange(Request $request, array $definition): bool
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
return (! $definition['sensitive'] || Gate::forUser($user)->allows('settings.secrets'))
|
||||
&& ($definition['permission'] === null || Gate::forUser($user)->allows($definition['permission']));
|
||||
}
|
||||
|
||||
/**
|
||||
* The parts that were switched on and miss a table: the screen tells to run `php artisan migrate`.
|
||||
*
|
||||
* @param list<string> $keys
|
||||
* @return list<string>
|
||||
*/
|
||||
private function pendingMigrations(array $keys): array
|
||||
{
|
||||
$labels = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (! str_starts_with($key, 'manager.modules.') || ! config($key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($this->modules->all() as $module) {
|
||||
if ('manager.modules.'.$module->key() === $key && collect($module->tables())->contains(fn (string $table) => ! Schema::hasTable(Names::table($table)))) {
|
||||
$labels[] = $module->label();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $labels;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Settings;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* The settings screen: which parts and features are on, and the keys and addresses of integrations, all changeable from the
|
||||
* manager by an account with the right, in the whole face of the manager only. A change is saved (secrets encrypted) and works at
|
||||
* once; see Support\Settings.
|
||||
*/
|
||||
class SettingsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'settings';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Settings';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['settings'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('settings.manage', 'Switch parts and features on or off and change settings', 'Settings'),
|
||||
new Permission('settings.secrets', 'Change keys, passwords and addresses of integrations', 'Settings', needs: ['settings.manage']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Settings', 'route' => Names::route('settings.index'), 'permission' => 'settings.manage', 'icon' => 'cog', 'simple' => false]];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return ['settings.update' => ['Changed the settings'], 'settings.refresh' => ['Refreshed the settings']];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['settings.index' => 'Opened the settings'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create(Names::table('settings'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('key', 150)->unique();
|
||||
// JSON; a secret is encrypted.
|
||||
$table->text('value')->nullable();
|
||||
$table->boolean('is_secret')->default(false);
|
||||
$table->unsignedBigInteger('updated_by')->nullable();
|
||||
$table->dateTime('created_at')->nullable();
|
||||
$table->dateTime('updated_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('settings'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Settings\SettingsController;
|
||||
|
||||
Route::middleware('can:settings.manage')->group(function () {
|
||||
Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');
|
||||
Route::put('/settings', [SettingsController::class, 'update'])->name('settings.update');
|
||||
Route::post('/settings/refresh', [SettingsController::class, 'refresh'])->name('settings.refresh');
|
||||
});
|
||||
@@ -7,9 +7,12 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
|
||||
/**
|
||||
* The accounts of the manager and the groups each is in.
|
||||
@@ -36,7 +39,9 @@ class AccountController
|
||||
'email' => $user->email,
|
||||
'is_super_admin' => $user->isManagerSuperAdmin(),
|
||||
'is_you' => $user->is($me),
|
||||
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name])->values(),
|
||||
'view' => UserSetting::value($user, 'view'),
|
||||
'tutorial' => UserSetting::value($user, 'tutorial'),
|
||||
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name, 'primary' => (bool) $group->pivot->is_primary])->values(),
|
||||
'can_change' => $me->managerOutranks($user),
|
||||
'can_delete' => $me->managerOutranks($user) && ! $user->is($me),
|
||||
])->values(),
|
||||
@@ -61,7 +66,8 @@ class AccountController
|
||||
$model = $this->model();
|
||||
$user = new $model;
|
||||
$user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save();
|
||||
$user->managerGroups()->sync($groups);
|
||||
$user->managerGroups()->sync($this->withPrimary($groups, $request));
|
||||
$this->settings($request, $user);
|
||||
|
||||
return response()->json(['id' => $user->getKey()], 201);
|
||||
}
|
||||
@@ -89,9 +95,11 @@ class AccountController
|
||||
$user->save();
|
||||
|
||||
if ($groups !== null) {
|
||||
$user->managerGroups()->sync($groups);
|
||||
$user->managerGroups()->sync($this->withPrimary($groups, $request));
|
||||
}
|
||||
|
||||
$this->settings($request, $user);
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
@@ -112,6 +120,27 @@ class AccountController
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which face of the manager the account looks at (`full`, `simple`, or empty for what its rights give) and whether
|
||||
* it gets the tour at its next load. Only what the form sent is changed.
|
||||
*/
|
||||
private function settings(Request $request, $user): void
|
||||
{
|
||||
$values = [];
|
||||
|
||||
if ($request->exists('view')) {
|
||||
$values['view'] = $request->input('view') ?: null;
|
||||
}
|
||||
|
||||
if ($request->exists('tutorial')) {
|
||||
$values['tutorial'] = $request->boolean('tutorial') ? 'pending' : (UserSetting::value($user, 'tutorial') === 'pending' ? 'skipped' : UserSetting::value($user, 'tutorial'));
|
||||
}
|
||||
|
||||
if ($values !== []) {
|
||||
UserSetting::put($user, $values);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return class-string<Authenticatable&Model> */
|
||||
private function model(): string
|
||||
{
|
||||
@@ -131,6 +160,9 @@ class AccountController
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'groups' => ['array'],
|
||||
'groups.*' => ['integer'],
|
||||
'primary_group' => ['nullable', 'integer'],
|
||||
'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])],
|
||||
'tutorial' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -150,6 +182,21 @@ class AccountController
|
||||
return ['name' => $request->string('name')->trim()->toString(), 'email' => $email];
|
||||
}
|
||||
|
||||
/**
|
||||
* The ticked groups as a sync map: exactly one of them is the primary one (the one that was asked for, else the first),
|
||||
* and none when there are no groups.
|
||||
*
|
||||
* @param list<int> $ids
|
||||
* @return array<int, array{is_primary: bool}>
|
||||
*/
|
||||
private function withPrimary(array $ids, Request $request): array
|
||||
{
|
||||
$asked = $request->integer('primary_group');
|
||||
$primary = in_array($asked, $ids, true) ? $asked : ($ids[0] ?? null);
|
||||
|
||||
return collect($ids)->mapWithKeys(fn (int $id) => [$id => ['is_primary' => $id === $primary]])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the groups that were ticked. One that does not exist, or that gives more than
|
||||
* the account that is logged in has, is refused.
|
||||
|
||||
@@ -23,6 +23,7 @@ class GroupController
|
||||
'id' => $group->id,
|
||||
'name' => $group->name,
|
||||
'description' => $group->description,
|
||||
'start' => $group->start,
|
||||
'permissions' => $group->allowed(),
|
||||
'accounts' => $group->users_count,
|
||||
])->values(),
|
||||
@@ -57,7 +58,7 @@ class GroupController
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/** @return array{name: string, description: string|null, permissions: list<string>} */
|
||||
/** @return array{name: string, description: string|null, start: string|null, permissions: list<string>} */
|
||||
private function validated(Request $request, ?Group $group = null): array
|
||||
{
|
||||
$table = Names::table('groups');
|
||||
@@ -65,6 +66,7 @@ class GroupController
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'start' => ['nullable', 'string', 'max:200', 'regex:#^/[A-Za-z0-9/_.-]*$#'],
|
||||
'permissions' => ['array'],
|
||||
'permissions.*' => ['string', Rule::in($this->modules->permissionValues())],
|
||||
]);
|
||||
@@ -74,6 +76,7 @@ class GroupController
|
||||
return [
|
||||
'name' => $request->string('name')->trim()->toString(),
|
||||
'description' => $description !== '' ? $description : null,
|
||||
'start' => $request->filled('start') ? $request->string('start')->toString() : null,
|
||||
'permissions' => $this->modules->complete($request->array('permissions')),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table(Names::table('group_user'), fn (Blueprint $table) => $table->boolean('is_primary')->default(false));
|
||||
Schema::table(Names::table('groups'), fn (Blueprint $table) => $table->string('start', 200)->nullable());
|
||||
|
||||
// An account that is in groups already gets the first of them as its primary one.
|
||||
$pivot = Names::table('group_user');
|
||||
|
||||
foreach (DB::table($pivot)->select('user_id', DB::raw('min(group_id) as first'))->groupBy('user_id')->get() as $row) {
|
||||
DB::table($pivot)->where('user_id', $row->user_id)->where('group_id', $row->first)->update(['is_primary' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table(Names::table('groups'), fn (Blueprint $table) => $table->dropColumn('start'));
|
||||
Schema::table(Names::table('group_user'), fn (Blueprint $table) => $table->dropColumn('is_primary'));
|
||||
}
|
||||
};
|
||||
@@ -14,7 +14,8 @@ use Illuminate\Validation\Rule;
|
||||
* Types: `text` (one line), `textarea` (paragraphs), `markdown` (a long text in Markdown), `lines` (one item
|
||||
* per line), `media` (a picture from the media library; the value is its address), `url`, `number`, `date`,
|
||||
* `toggle` (a switch) and `select` (needs `options`: a list of values, or value => label). `required`, `default` and
|
||||
* `rules` (extra Laravel rules) are optional on every type.
|
||||
* `rules` (extra Laravel rules) are optional on every type. `help` is a line of explanation under the field; `advanced`
|
||||
* hides the field in the simple face of the manager (it keeps its value).
|
||||
*/
|
||||
final class Fields
|
||||
{
|
||||
@@ -26,7 +27,7 @@ final class Fields
|
||||
* The definitions in one shape, with a key, a label and a known type; what is wrong is dropped.
|
||||
*
|
||||
* @param array<array-key, mixed> $fields key => definition
|
||||
* @return array<string, array{key: string, label: string, type: string, help: ?string, required: bool, default: mixed, options: array<string, string>, max: ?int, rules: list<mixed>}>
|
||||
* @return array<string, array{key: string, label: string, type: string, help: ?string, advanced: bool, required: bool, default: mixed, options: array<string, string>, max: ?int, rules: list<mixed>}>
|
||||
*/
|
||||
public static function normalize(array $fields): array
|
||||
{
|
||||
@@ -55,6 +56,7 @@ final class Fields
|
||||
'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'type' => $type,
|
||||
'help' => isset($field['help']) ? (string) $field['help'] : null,
|
||||
'advanced' => (bool) ($field['advanced'] ?? false),
|
||||
'required' => (bool) ($field['required'] ?? false),
|
||||
'default' => $field['default'] ?? self::empty($type),
|
||||
'options' => $options,
|
||||
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\Review;
|
||||
@@ -37,6 +38,13 @@ final class Importer
|
||||
'required' => ['slug', 'title'],
|
||||
'key' => ['slug'],
|
||||
],
|
||||
// The rows only; the files stay where they are. `disk` and `location` say where (use `--set=disk=iriksit` when the source has no disk column).
|
||||
'media' => [
|
||||
'model' => Media::class,
|
||||
'columns' => ['disk', 'location', 'name', 'filename', 'mime_type', 'size', 'checksum', 'width', 'height', 'alt', 'focus_x', 'focus_y'],
|
||||
'required' => ['location', 'filename'],
|
||||
'key' => ['disk', 'location'],
|
||||
],
|
||||
'reviews' => [
|
||||
'model' => Review::class,
|
||||
'columns' => ['author', 'place', 'rating', 'body', 'is_visible'],
|
||||
@@ -47,9 +55,10 @@ final class Importer
|
||||
|
||||
/**
|
||||
* @param array<string, string> $map package column => column of the source table; same name when left out
|
||||
* @param array<string, string> $fixed package column => a value for every row that has none of its own
|
||||
* @return array{created: int, updated: int, skipped: int, problems: list<string>}
|
||||
*/
|
||||
public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null): array
|
||||
public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null, array $fixed = []): array
|
||||
{
|
||||
$spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS)));
|
||||
|
||||
@@ -75,6 +84,26 @@ final class Importer
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($fixed as $column => $value) {
|
||||
if (! in_array($column, $spec['columns'], true)) {
|
||||
throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns']));
|
||||
}
|
||||
|
||||
if (! isset($values[$column]) || $values[$column] === '') {
|
||||
$values[$column] = $this->convert($column, $value);
|
||||
}
|
||||
}
|
||||
|
||||
if ($target === 'media') {
|
||||
foreach (['disk' => config('manager.media.disk'), 'mime_type' => 'application/octet-stream', 'size' => 0] as $column => $default) {
|
||||
if (! isset($values[$column]) || $values[$column] === '') {
|
||||
$values[$column] = $default;
|
||||
}
|
||||
}
|
||||
|
||||
$values['name'] = ($values['name'] ?? '') !== '' ? $values['name'] : pathinfo((string) ($values['filename'] ?? ''), PATHINFO_FILENAME);
|
||||
}
|
||||
|
||||
if ($target === 'posts' || $target === 'pages') {
|
||||
$values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? ''));
|
||||
}
|
||||
@@ -106,6 +135,7 @@ final class Importer
|
||||
return match ($column) {
|
||||
'tags' => $this->tags($value),
|
||||
'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
||||
'size', 'width', 'height' => $value === null || $value === '' ? null : max(0, (int) $value),
|
||||
'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)),
|
||||
'published_at' => $value === null || $value === '' ? null : $value,
|
||||
default => is_string($value) ? trim($value) : $value,
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\IriksStorage;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use League\Flysystem\Config;
|
||||
use League\Flysystem\DirectoryAttributes;
|
||||
use League\Flysystem\FileAttributes;
|
||||
use League\Flysystem\FilesystemAdapter;
|
||||
use League\Flysystem\UnableToCopyFile;
|
||||
use League\Flysystem\UnableToCreateDirectory;
|
||||
use League\Flysystem\UnableToDeleteDirectory;
|
||||
use League\Flysystem\UnableToDeleteFile;
|
||||
use League\Flysystem\UnableToMoveFile;
|
||||
use League\Flysystem\UnableToReadFile;
|
||||
use League\Flysystem\UnableToRetrieveMetadata;
|
||||
use League\Flysystem\UnableToSetVisibility;
|
||||
use League\Flysystem\UnableToWriteFile;
|
||||
|
||||
/**
|
||||
* A Laravel disk (`driver` => `iriksit`) whose files live at the IriksIT API. The API knows files by an id of its own, not
|
||||
* by a path, so every path that is written is remembered next to that id (table `storage_files`). A path that has no entry
|
||||
* and no slash is taken for an id itself: that is how media rows that were made by a site's own code (the id as location)
|
||||
* keep working. There are no folders, no visibility and no listing.
|
||||
*/
|
||||
class Adapter implements FilesystemAdapter
|
||||
{
|
||||
public function __construct(private readonly Client $client) {}
|
||||
|
||||
public function fileExists(string $path): bool
|
||||
{
|
||||
$id = $this->id($path);
|
||||
|
||||
if ($id === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->client->details($id) !== null;
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToRetrieveMetadata::create($path, 'exists', $e->getMessage(), $e);
|
||||
}
|
||||
}
|
||||
|
||||
public function directoryExists(string $path): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write(string $path, string $contents, Config $config): void
|
||||
{
|
||||
$stream = fopen('php://temp', 'r+b');
|
||||
fwrite($stream, $contents);
|
||||
rewind($stream);
|
||||
|
||||
try {
|
||||
$this->writeStream($path, $stream, $config);
|
||||
} finally {
|
||||
// The HTTP client closes what it sent itself.
|
||||
if (is_resource($stream)) {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function writeStream(string $path, $contents, Config $config): void
|
||||
{
|
||||
try {
|
||||
$stored = $this->client->store($contents, basename($path));
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToWriteFile::atLocation($path, $e->getMessage(), $e);
|
||||
}
|
||||
|
||||
DB::table($this->table())->updateOrInsert(['path' => $path], ['remote_id' => $stored['id']]);
|
||||
}
|
||||
|
||||
public function read(string $path): string
|
||||
{
|
||||
$stream = $this->readStream($path);
|
||||
$contents = stream_get_contents($stream);
|
||||
is_resource($stream) && fclose($stream);
|
||||
|
||||
return $contents === false ? throw UnableToReadFile::fromLocation($path) : $contents;
|
||||
}
|
||||
|
||||
public function readStream(string $path)
|
||||
{
|
||||
$id = $this->id($path) ?? throw UnableToReadFile::fromLocation($path, 'There is no such file.');
|
||||
|
||||
try {
|
||||
$body = $this->client->open($id);
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToReadFile::fromLocation($path, $e->getMessage(), $e);
|
||||
}
|
||||
|
||||
$stream = fopen('php://temp', 'r+b');
|
||||
while (! $body->eof()) {
|
||||
fwrite($stream, $body->read(1024 * 1024));
|
||||
}
|
||||
$body->close();
|
||||
rewind($stream);
|
||||
|
||||
return $stream;
|
||||
}
|
||||
|
||||
public function delete(string $path): void
|
||||
{
|
||||
$id = $this->id($path);
|
||||
|
||||
if ($id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->client->delete($id);
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToDeleteFile::atLocation($path, $e->getMessage(), $e);
|
||||
}
|
||||
|
||||
DB::table($this->table())->where('path', $path)->delete();
|
||||
}
|
||||
|
||||
public function deleteDirectory(string $path): void
|
||||
{
|
||||
throw UnableToDeleteDirectory::atLocation($path, 'The IriksIT storage has no folders.');
|
||||
}
|
||||
|
||||
public function createDirectory(string $path, Config $config): void
|
||||
{
|
||||
throw UnableToCreateDirectory::atLocation($path, 'The IriksIT storage has no folders.');
|
||||
}
|
||||
|
||||
public function setVisibility(string $path, string $visibility): void
|
||||
{
|
||||
throw UnableToSetVisibility::atLocation($path, 'The IriksIT storage has no visibility.');
|
||||
}
|
||||
|
||||
public function visibility(string $path): FileAttributes
|
||||
{
|
||||
throw UnableToRetrieveMetadata::visibility($path, 'The IriksIT storage has no visibility.');
|
||||
}
|
||||
|
||||
public function mimeType(string $path): FileAttributes
|
||||
{
|
||||
$details = $this->details($path, 'mime_type');
|
||||
|
||||
return new FileAttributes($path, null, null, null, $details['mime_type'] ?? throw UnableToRetrieveMetadata::mimeType($path));
|
||||
}
|
||||
|
||||
public function lastModified(string $path): FileAttributes
|
||||
{
|
||||
$created = $this->details($path, 'last_modified')['created_at'] ?? null;
|
||||
|
||||
return new FileAttributes($path, null, null, $created !== null ? strtotime($created) ?: null : throw UnableToRetrieveMetadata::lastModified($path));
|
||||
}
|
||||
|
||||
public function fileSize(string $path): FileAttributes
|
||||
{
|
||||
return new FileAttributes($path, $this->details($path, 'file_size')['size']);
|
||||
}
|
||||
|
||||
/** @return iterable<FileAttributes|DirectoryAttributes> */
|
||||
public function listContents(string $path, bool $deep): iterable
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function move(string $source, string $destination, Config $config): void
|
||||
{
|
||||
throw UnableToMoveFile::fromLocationTo($source, $destination);
|
||||
}
|
||||
|
||||
public function copy(string $source, string $destination, Config $config): void
|
||||
{
|
||||
throw UnableToCopyFile::fromLocationTo($source, $destination);
|
||||
}
|
||||
|
||||
/** @return array{size: int, mime_type: string|null, created_at: string|null} */
|
||||
private function details(string $path, string $what): array
|
||||
{
|
||||
$id = $this->id($path) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
|
||||
|
||||
try {
|
||||
return $this->client->details($id) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToRetrieveMetadata::create($path, $what, $e->getMessage(), $e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The id the API gave to what was written at this path, or the path itself when it looks like an id. */
|
||||
private function id(string $path): ?string
|
||||
{
|
||||
$id = DB::table($this->table())->where('path', $path)->value('remote_id');
|
||||
|
||||
if (is_string($id)) {
|
||||
return $id;
|
||||
}
|
||||
|
||||
return $path !== '' && ! str_contains($path, '/') ? $path : null;
|
||||
}
|
||||
|
||||
private function table(): string
|
||||
{
|
||||
return Names::table('storage_files');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\IriksStorage;
|
||||
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Talks to the IriksIT API (the `/storage` part of it): logs in with an account, keeps the token and the refresh token
|
||||
* (encrypted) in the cache, renews them, and stores, opens, describes and deletes files. The account needs the
|
||||
* `storage.read` and `storage.write` permissions. Every failure is a MediaStorageException; what the API says goes into
|
||||
* its message (never an address, a token or a password).
|
||||
*/
|
||||
class Client
|
||||
{
|
||||
private const TOKEN = 'manager.iriksit.token';
|
||||
|
||||
private const REFRESH = 'manager.iriksit.refresh';
|
||||
|
||||
/** @param array{url?: string|null, email?: string|null, password?: string|null, timeout?: int|string|null} $config */
|
||||
public function __construct(private readonly array $config) {}
|
||||
|
||||
/** Whether an address and an account are set at all. */
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->value('url') !== '' && $this->value('email') !== '' && $this->value('password') !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a file. The `id` that comes back is the only handle to it afterwards.
|
||||
*
|
||||
* @param resource $stream
|
||||
* @return array{id: string, size: int, mime_type: string|null, checksum: string|null}
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function store($stream, string $filename): array
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->attach('file', $stream, $filename)->post($this->url('/storage'), ['priority' => 'normal']));
|
||||
$data = $response->json('data');
|
||||
|
||||
if ($response->failed() || ! is_array($data) || ! is_string($data['id'] ?? null) || $data['id'] === '') {
|
||||
throw $this->failure('store a file', $response);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $data['id'],
|
||||
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
|
||||
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
|
||||
'checksum' => is_string($data['checksum'] ?? null) ? $data['checksum'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The content of a file as a stream; read it and close it.
|
||||
*
|
||||
* @throws MediaStorageException with status 404 when the API does not know the file
|
||||
*/
|
||||
public function open(string $id): StreamInterface
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->withOptions(['stream' => true])->get($this->url('/storage/'.rawurlencode($id).'/download')));
|
||||
|
||||
if ($response->status() !== 200) {
|
||||
throw $this->failure('download a file', $response);
|
||||
}
|
||||
|
||||
return $response->toPsrResponse()->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* What the API knows of a file, or null when it does not know it.
|
||||
*
|
||||
* @return array{size: int, mime_type: string|null, created_at: string|null}|null
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function details(string $id): ?array
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->get($this->url('/storage/'.rawurlencode($id))));
|
||||
|
||||
if ($response->status() === 404) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = $response->json('data');
|
||||
|
||||
if ($response->failed() || ! is_array($data)) {
|
||||
throw $this->failure('read a file', $response);
|
||||
}
|
||||
|
||||
return [
|
||||
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
|
||||
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
|
||||
'created_at' => is_string($data['created_at'] ?? null) ? $data['created_at'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a file. One the API no longer knows counts as deleted.
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function delete(string $id): void
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->delete($this->url('/storage/'.rawurlencode($id))));
|
||||
|
||||
if ($response->failed() && $response->status() !== 404) {
|
||||
throw $this->failure('delete a file', $response);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the account can log in at all: the check behind a "test the connection" button.
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function check(): void
|
||||
{
|
||||
$this->token();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a call with the current token. A 401 means the token was revoked on the API's side: forget it, log in
|
||||
* again and try once more.
|
||||
*
|
||||
* @param \Closure(PendingRequest): Response $call
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
private function call(\Closure $call): Response
|
||||
{
|
||||
try {
|
||||
$response = $call($this->request($this->token()));
|
||||
|
||||
if ($response->status() !== 401) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
Cache::forget(self::TOKEN);
|
||||
Cache::forget(self::REFRESH);
|
||||
|
||||
return $call($this->request($this->token()));
|
||||
} catch (MediaStorageException $e) {
|
||||
throw $e;
|
||||
} catch (Throwable) {
|
||||
throw new MediaStorageException('The IriksIT storage could not be reached.');
|
||||
}
|
||||
}
|
||||
|
||||
private function request(string $token): PendingRequest
|
||||
{
|
||||
$timeout = $this->config['timeout'] ?? null;
|
||||
|
||||
return Http::acceptJson()->withoutRedirecting()->withToken($token)->connectTimeout(5)->timeout(is_numeric($timeout) ? (int) $timeout : 300);
|
||||
}
|
||||
|
||||
/** @throws MediaStorageException */
|
||||
private function token(): string
|
||||
{
|
||||
$token = $this->cached(self::TOKEN);
|
||||
|
||||
if ($token !== null) {
|
||||
return $token;
|
||||
}
|
||||
|
||||
$refresh = $this->cached(self::REFRESH);
|
||||
|
||||
if ($refresh !== null) {
|
||||
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)->withToken($refresh)->post($this->url('/auth/refresh'));
|
||||
|
||||
if ($response->successful() && ($kept = $this->keep($response->json('data'))) !== null) {
|
||||
return $kept;
|
||||
}
|
||||
|
||||
Cache::forget(self::REFRESH);
|
||||
}
|
||||
|
||||
if (! $this->isConfigured()) {
|
||||
throw new MediaStorageException('No IriksIT account is set for the storage (address, email and password).');
|
||||
}
|
||||
|
||||
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)
|
||||
->post($this->url('/auth/login'), ['email' => $this->value('email'), 'password' => $this->value('password')]);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new MediaStorageException("The IriksIT login failed (HTTP {$response->status()}).", $response->status());
|
||||
}
|
||||
|
||||
return $this->keep($response->json('data')) ?? throw new MediaStorageException('The IriksIT API sent a login answer without a token.');
|
||||
}
|
||||
|
||||
/** Remembers the tokens of a login answer until they expire (a minute early) and returns the access token. */
|
||||
private function keep(mixed $data): ?string
|
||||
{
|
||||
if (! is_array($data) || ! is_string($data['token'] ?? null) || $data['token'] === '' || ! is_string($data['expire'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Cache::put(self::TOKEN, Crypt::encryptString($data['token']), Carbon::parse($data['expire'])->subMinute());
|
||||
|
||||
if (is_string($data['refresh_token'] ?? null) && is_string($data['refresh_expire'] ?? null)) {
|
||||
Cache::put(self::REFRESH, Crypt::encryptString($data['refresh_token']), Carbon::parse($data['refresh_expire'])->subMinute());
|
||||
}
|
||||
|
||||
return $data['token'];
|
||||
}
|
||||
|
||||
private function cached(string $key): ?string
|
||||
{
|
||||
$value = Cache::get($key);
|
||||
|
||||
try {
|
||||
return is_string($value) ? Crypt::decryptString($value) : null;
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function failure(string $action, Response $response): MediaStorageException
|
||||
{
|
||||
$reason = $response->json('message');
|
||||
$detail = is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : '';
|
||||
$retry = $response->header('Retry-After');
|
||||
|
||||
return new MediaStorageException(
|
||||
"The IriksIT storage could not {$action} (HTTP {$response->status()}{$detail}).",
|
||||
$response->status(),
|
||||
is_numeric($retry) ? (int) $retry : null,
|
||||
);
|
||||
}
|
||||
|
||||
private function url(string $path): string
|
||||
{
|
||||
return rtrim($this->value('url'), '/').$path;
|
||||
}
|
||||
|
||||
private function value(string $key): string
|
||||
{
|
||||
$value = $this->config[$key] ?? '';
|
||||
|
||||
return is_string($value) ? trim($value) : '';
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,9 @@ use IriksIT\Manager\Models\UserSetting;
|
||||
/**
|
||||
* The menu one account sees, and the face of the manager it looks at: the full one, or (when config
|
||||
* `simple_view` is on) the simple one with only the items marked `simple`. An account with the permission
|
||||
* `manager.full` (and a super admin) gets the full face; one with `manager.switch` starts in the simple
|
||||
* face and may change; everyone else always gets the simple face. What it chose is remembered per account.
|
||||
* `manager.full` (and a super admin) gets the full face; everyone else the simple face, unless something is stored for
|
||||
* the account: an administrator sets it on the accounts screen, an account with `manager.switch` (or `manager.full`)
|
||||
* sets it itself. What is stored wins; only the account's own switch needs the permission.
|
||||
*/
|
||||
final class Menu
|
||||
{
|
||||
@@ -25,17 +26,14 @@ final class Menu
|
||||
return self::FULL;
|
||||
}
|
||||
|
||||
$full = $this->hasFull($user);
|
||||
// What is stored wins: an administrator sets it for an account, an account that may switch sets it itself.
|
||||
$stored = UserSetting::value($user, 'view');
|
||||
|
||||
if ($this->maySwitch($user)) {
|
||||
$chosen = $user->getKey() === null ? null : UserSetting::query()->where('user_id', $user->getKey())->value('view');
|
||||
|
||||
if (in_array($chosen, [self::FULL, self::SIMPLE], true)) {
|
||||
return $chosen;
|
||||
}
|
||||
if (in_array($stored, [self::FULL, self::SIMPLE], true)) {
|
||||
return $stored;
|
||||
}
|
||||
|
||||
return $full ? self::FULL : self::SIMPLE;
|
||||
return $this->hasFull($user) ? self::FULL : self::SIMPLE;
|
||||
}
|
||||
|
||||
public function maySwitch(?object $user): bool
|
||||
@@ -69,6 +67,7 @@ final class Menu
|
||||
'label' => $item['label'],
|
||||
'href' => isset($item['route']) ? route($item['route'], $item['params'] ?? [], false) : (string) $item['url'],
|
||||
'section' => $item['section'] ?? null,
|
||||
'hint' => $item['hint'] ?? null,
|
||||
'icon' => $item['icon'] ?? null,
|
||||
'new_tab' => ($item['new_tab'] ?? false) ?: null,
|
||||
], fn ($value) => $value !== null);
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace IriksIT\Manager\Support;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Contracts\Module;
|
||||
use IriksIT\Manager\Exceptions\ModuleException;
|
||||
use IriksIT\Manager\Http\Controllers\MascotController;
|
||||
|
||||
/**
|
||||
* Knows which modules exist and which of them are on for this site.
|
||||
@@ -172,6 +173,7 @@ final class ModuleRegistry
|
||||
...$item,
|
||||
'label' => __($item['label']),
|
||||
...(isset($item['section']) ? ['section' => __($item['section'])] : []),
|
||||
...(isset($item['hint']) && $item['hint'] !== null ? ['hint' => __($item['hint'])] : []),
|
||||
'order' => (int) ($item['order'] ?? 100),
|
||||
'simple' => (bool) ($item['simple'] ?? false),
|
||||
], $items);
|
||||
@@ -182,6 +184,34 @@ final class ModuleRegistry
|
||||
return array_values($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* The steps the modules add to the tour, for an account with these permissions.
|
||||
*
|
||||
* @param list<string> $allowed
|
||||
* @return list<array{title: string, text: string, image: ?string, href: ?string}>
|
||||
*/
|
||||
public function tutorial(array $allowed): array
|
||||
{
|
||||
$steps = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
foreach (method_exists($module, 'tutorial') ? $module->tutorial() : [] as $step) {
|
||||
if (! isset($step['title'], $step['text']) || (isset($step['permission']) && ! in_array($step['permission'], $allowed, true))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$steps[] = [
|
||||
'title' => __($step['title']),
|
||||
'text' => __($step['text']),
|
||||
'image' => isset($step['image']) && in_array($step['image'], MascotController::NAMES, true) ? $step['image'] : null,
|
||||
'href' => isset($step['menu']) ? route(Names::route($step['menu']), [], false) : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit-log names of what is done: the modules' own plus the core's.
|
||||
*
|
||||
@@ -189,7 +219,7 @@ final class ModuleRegistry
|
||||
*/
|
||||
public function actions(): array
|
||||
{
|
||||
$actions = ['profile.update' => ['Changed own account'], 'profile.view' => ['Switched between the simple and the whole manager']];
|
||||
$actions = ['profile.update' => ['Changed own account'], 'profile.view' => ['Switched between the simple and the whole manager'], 'profile.tutorial' => ['Finished or skipped the tour']];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
$actions = [...$actions, ...$module->actions()];
|
||||
|
||||
@@ -40,6 +40,7 @@ final class Resources
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'hint' => isset($definition['hint']) ? (string) $definition['hint'] : null,
|
||||
'singular' => (string) ($definition['singular'] ?? $definition['label'] ?? $key),
|
||||
'model' => is_string($model) && is_subclass_of($model, Eloquent::class) ? $model : null,
|
||||
'fields' => $fields,
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* What can be set from the settings screen. A definition is keyed by the config path it overrides (`manager.modules.reviews`)
|
||||
* and has: `label`, `type` (toggle, text, url, number, select, secret), `group`, optional `help`, `options` (select: value => label),
|
||||
* `env` (the .env variable that is written along when the site allows it) and `permission` (a right on top of `settings.manage`).
|
||||
* A secret is never sent back to a browser.
|
||||
*
|
||||
* They come from three places: the parts of the manager, the integrations the package knows (Turnstile, the IriksIT API) and
|
||||
* the site itself (`manager.settings.definitions`, and `settings()` of a module of its own). Nothing else can be set: a key that
|
||||
* is not defined is refused, so the screen can never write an arbitrary setting or .env line.
|
||||
*/
|
||||
class Definitions
|
||||
{
|
||||
public const TYPES = ['toggle', 'text', 'url', 'number', 'select', 'secret'];
|
||||
|
||||
public function __construct(private readonly ModuleRegistry $modules) {}
|
||||
|
||||
/** @return array<string, array<string, mixed>> keyed by config path */
|
||||
public function all(): array
|
||||
{
|
||||
$all = [];
|
||||
|
||||
foreach ([...$this->parts(), ...$this->integrations(), ...$this->fromModules(), ...(array) config('manager.settings.definitions', [])] as $key => $definition) {
|
||||
$key = is_string($key) ? $key : (string) ($definition['config'] ?? '');
|
||||
$definition = $this->normalise($key, (array) $definition);
|
||||
|
||||
if ($definition !== null) {
|
||||
$all[$key] = $definition;
|
||||
}
|
||||
}
|
||||
|
||||
return $all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns what was typed into the value of the setting, or says it is no good.
|
||||
*
|
||||
* @param array<string, mixed> $definition
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function cast(array $definition, mixed $raw): mixed
|
||||
{
|
||||
$bad = fn () => throw new \InvalidArgumentException('This value is not valid.');
|
||||
|
||||
return match ($definition['type']) {
|
||||
'toggle' => is_bool($raw) || in_array($raw, [0, 1, '0', '1', 'true', 'false'], true) ? filter_var($raw, FILTER_VALIDATE_BOOLEAN) : $bad(),
|
||||
'number' => is_numeric($raw) ? $raw + 0 : $bad(),
|
||||
'select' => is_string($raw) && array_key_exists($raw, $definition['options']) ? $raw : $bad(),
|
||||
'url' => is_string($raw) && mb_strlen($raw) <= 500 && preg_match('#^https?://[^\s<>"\']+$#i', $raw) === 1 ? $raw : $bad(),
|
||||
default => is_string($raw) && mb_strlen($raw) <= 1000 && preg_match('/[\r\n\0]/', $raw) !== 1 ? trim($raw) : $bad(),
|
||||
};
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
public function find(string $key): ?array
|
||||
{
|
||||
return $this->all()[$key] ?? null;
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function parts(): array
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach ($this->modules->all() as $module) {
|
||||
// Users and media are the core: without them there is no manager.
|
||||
if (in_array($module->key(), ['users', 'media', 'settings'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts['manager.modules.'.$module->key()] = [
|
||||
'label' => $module->label(),
|
||||
'type' => 'toggle',
|
||||
'group' => 'Parts of the manager',
|
||||
'env' => 'MANAGER_'.strtoupper($module->key()),
|
||||
];
|
||||
}
|
||||
|
||||
return $parts;
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function integrations(): array
|
||||
{
|
||||
$disks = array_keys((array) config('filesystems.disks', []));
|
||||
|
||||
return [
|
||||
'manager.media.disk' => ['label' => 'Disk for new media files', 'type' => 'select', 'group' => 'Media', 'sensitive' => true, 'options' => array_combine($disks, $disks), 'env' => 'MANAGER_MEDIA_DISK'],
|
||||
'manager.media.iriksit.url' => ['label' => 'IriksIT API: address', 'type' => 'url', 'group' => 'IriksIT API', 'sensitive' => true, 'help' => 'With its version, for example https://api.iriks-it.nl/v1', 'env' => 'MANAGER_IRIKSIT_URL'],
|
||||
'manager.media.iriksit.email' => ['label' => 'IriksIT API: account', 'type' => 'text', 'group' => 'IriksIT API', 'sensitive' => true, 'env' => 'MANAGER_IRIKSIT_EMAIL'],
|
||||
'manager.media.iriksit.password' => ['label' => 'IriksIT API: password', 'type' => 'secret', 'group' => 'IriksIT API', 'env' => 'MANAGER_IRIKSIT_PASSWORD'],
|
||||
'manager.login.turnstile.site_key' => ['label' => 'Turnstile: site key', 'type' => 'text', 'group' => 'Login', 'sensitive' => true, 'env' => 'MANAGER_TURNSTILE_SITE_KEY'],
|
||||
'manager.login.turnstile.secret' => ['label' => 'Turnstile: secret key', 'type' => 'secret', 'group' => 'Login', 'env' => 'MANAGER_TURNSTILE_SECRET'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function fromModules(): array
|
||||
{
|
||||
$found = [];
|
||||
|
||||
foreach ($this->modules->active() as $module) {
|
||||
if (method_exists($module, 'settings')) {
|
||||
foreach ((array) $module->settings() as $key => $definition) {
|
||||
$found[$key] = $definition;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null null when the definition is no good: it is left out, never half used */
|
||||
private function normalise(string $key, array $definition): ?array
|
||||
{
|
||||
$type = $definition['type'] ?? 'text';
|
||||
|
||||
if (preg_match('/^[a-z][a-z0-9_]*(\.[a-zA-Z0-9_-]+)+$/', $key) !== 1 || ! in_array($type, self::TYPES, true) || ! is_string($definition['label'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$env = $definition['env'] ?? null;
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'config' => $key,
|
||||
'label' => $definition['label'],
|
||||
'type' => $type,
|
||||
'group' => is_string($definition['group'] ?? null) ? $definition['group'] : 'Site',
|
||||
'help' => is_string($definition['help'] ?? null) ? $definition['help'] : null,
|
||||
'options' => $type === 'select' ? (array) ($definition['options'] ?? []) : [],
|
||||
'env' => is_string($env) && preg_match('/^[A-Z][A-Z0-9_]*$/', $env) === 1 ? $env : null,
|
||||
'permission' => is_string($definition['permission'] ?? null) ? $definition['permission'] : null,
|
||||
// What can send a password or a file somewhere else (an address, an account, a disk) needs the right for secrets too, and the password of whoever saves it.
|
||||
'sensitive' => $type === 'secret' || (bool) ($definition['sensitive'] ?? false),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
/**
|
||||
* Writes variables into the .env file of the app, when the site allows it (`manager.settings.write_env`) and the file may be
|
||||
* written. Only variables that a definition names are ever written, and a value that could break the file (a line break, a
|
||||
* null byte) is refused. The file is rewritten as a whole: the old one is kept as `.env.manager-backup`, the new one is
|
||||
* written next to it and moved over in one step, with the permissions of the old one.
|
||||
*/
|
||||
class EnvFile
|
||||
{
|
||||
public function __construct(private readonly ?string $path = null) {}
|
||||
|
||||
public function path(): string
|
||||
{
|
||||
return $this->path ?? app()->environmentFilePath();
|
||||
}
|
||||
|
||||
public function writable(): bool
|
||||
{
|
||||
return is_file($this->path()) && is_writable($this->path()) && is_writable(dirname($this->path()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|int|float|bool|null> $pairs variable => value (null removes nothing: the line is left alone)
|
||||
*/
|
||||
public function set(array $pairs): bool
|
||||
{
|
||||
$pairs = array_filter($pairs, fn ($value) => $value !== null);
|
||||
|
||||
if ($pairs === [] || ! $this->writable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($pairs as $name => $value) {
|
||||
if (preg_match('/^[A-Z][A-Z0-9_]*$/', (string) $name) !== 1 || preg_match('/[\r\n\0]/', (string) $this->text($value)) === 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$lock = fopen($this->path().'.manager-lock', 'c');
|
||||
|
||||
if ($lock === false || ! flock($lock, LOCK_EX)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$old = (string) file_get_contents($this->path());
|
||||
$lines = preg_split('/\R/', $old) ?: [];
|
||||
$left = $pairs;
|
||||
|
||||
foreach ($lines as $i => $line) {
|
||||
if (preg_match('/^\s*([A-Z][A-Z0-9_]*)\s*=/', $line, $found) === 1 && array_key_exists($found[1], $left)) {
|
||||
$lines[$i] = $found[1].'='.$this->quote($left[$found[1]]);
|
||||
unset($left[$found[1]]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($left as $name => $value) {
|
||||
$lines[] = $name.'='.$this->quote($value);
|
||||
}
|
||||
|
||||
$new = rtrim(implode("\n", $lines), "\n")."\n";
|
||||
$temporary = $this->path().'.'.bin2hex(random_bytes(4)).'.tmp';
|
||||
|
||||
if (@copy($this->path(), $this->path().'.manager-backup') === false || @file_put_contents($temporary, $new) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@chmod($temporary, fileperms($this->path()) & 0777);
|
||||
|
||||
if (! @rename($temporary, $this->path())) {
|
||||
@unlink($temporary);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} finally {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
}
|
||||
}
|
||||
|
||||
private function text(mixed $value): string
|
||||
{
|
||||
return is_bool($value) ? ($value ? 'true' : 'false') : (string) $value;
|
||||
}
|
||||
|
||||
private function quote(mixed $value): string
|
||||
{
|
||||
$text = $this->text($value);
|
||||
|
||||
if (preg_match('/^[A-Za-z0-9_.:\/@+,-]*$/', $text) === 1) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $text).'"';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* What was set from the settings screen. The table is the truth (with a history of who and when); every change also writes
|
||||
* one compiled file (`bootstrap/cache/manager-settings.php`, secrets in it stay encrypted) that is laid over the config
|
||||
* while the app starts, so a request reads one file from opcache and never asks the database. That works with `config:cache`
|
||||
* too, because it is applied after the config was loaded. Without the file (it could not be written) the table is read once.
|
||||
*/
|
||||
class Store
|
||||
{
|
||||
public function __construct(private readonly Definitions $definitions) {}
|
||||
|
||||
public static function file(): string
|
||||
{
|
||||
return app()->bootstrapPath('cache/manager-settings.php');
|
||||
}
|
||||
|
||||
/** Lays the saved settings over the config. Called while the provider registers; it must never fail the app. */
|
||||
public static function overlay(): void
|
||||
{
|
||||
try {
|
||||
$values = is_file(self::file()) ? (array) (include self::file()) : self::fromTable();
|
||||
|
||||
foreach ($values as $key => $value) {
|
||||
if (is_array($value) && array_key_exists('__enc', $value)) {
|
||||
$value = json_decode(Crypt::decryptString((string) $value['__enc']), true);
|
||||
}
|
||||
|
||||
config([$key => $value]);
|
||||
}
|
||||
} catch (Throwable) {
|
||||
// A missing table (before the first migrate), a changed APP_KEY, a broken file: the config keeps what it had.
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private static function fromTable(): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach (DB::table(Names::table('settings'))->get() as $row) {
|
||||
$values[$row->key] = $row->is_secret ? ['__enc' => $row->value] : json_decode((string) $row->value, true);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves values (null: back to what the config says) and rewrites the compiled file. Returns whether that file could be written.
|
||||
*
|
||||
* @param array<string, mixed> $values by config path, already checked against the definitions
|
||||
*/
|
||||
public function put(array $values, mixed $userId = null): bool
|
||||
{
|
||||
$table = Names::table('settings');
|
||||
|
||||
DB::transaction(function () use ($values, $table, $userId) {
|
||||
foreach ($values as $key => $value) {
|
||||
$definition = $this->definitions->find($key);
|
||||
|
||||
if ($value === null || $definition === null) {
|
||||
DB::table($table)->where('key', $key)->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$secret = $definition['type'] === 'secret';
|
||||
$stored = $secret ? Crypt::encryptString(json_encode($value)) : json_encode($value);
|
||||
|
||||
DB::table($table)->updateOrInsert(['key' => $key], ['value' => $stored, 'is_secret' => $secret, 'updated_by' => $userId, 'updated_at' => now(), 'created_at' => now()]);
|
||||
}
|
||||
});
|
||||
|
||||
return $this->compile();
|
||||
}
|
||||
|
||||
/** Writes the compiled file from the table: to a temporary file first, then moved over the old one in one step. */
|
||||
public function compile(): bool
|
||||
{
|
||||
$known = $this->definitions->all();
|
||||
$values = array_filter(self::fromTable(), fn ($value, $key) => isset($known[$key]), ARRAY_FILTER_USE_BOTH);
|
||||
$file = self::file();
|
||||
$temporary = $file.'.'.bin2hex(random_bytes(4)).'.tmp';
|
||||
|
||||
try {
|
||||
if (@file_put_contents($temporary, '<?php return '.var_export($values, true).';'.PHP_EOL, LOCK_EX) === false || ! @rename($temporary, $file)) {
|
||||
@unlink($temporary);
|
||||
|
||||
return false;
|
||||
}
|
||||
} catch (Throwable) {
|
||||
@unlink($temporary);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function_exists('opcache_invalidate') && @opcache_invalidate($file, true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether a setting has been saved here (and so wins over .env). */
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return DB::table(Names::table('settings'))->where('key', $key)->exists();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Throwable;
|
||||
|
||||
/** Saves changes to settings: the table and the compiled file, the config of this request, and `.env` when the site allows it. */
|
||||
class Writer
|
||||
{
|
||||
public function __construct(private readonly Definitions $definitions, private readonly Store $store, private readonly EnvFile $env) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes config path => value; null puts the setting back to what the config says
|
||||
* @return array{file_written: bool, env_written: bool}
|
||||
*/
|
||||
public function apply(array $changes, mixed $userId = null): array
|
||||
{
|
||||
if ($changes === []) {
|
||||
return ['file_written' => true, 'env_written' => false];
|
||||
}
|
||||
|
||||
$written = $this->store->put($changes, $userId);
|
||||
|
||||
foreach ($changes as $key => $value) {
|
||||
config([$key => $value ?? config($key)]);
|
||||
}
|
||||
|
||||
return ['file_written' => $written, 'env_written' => $this->writeEnv($changes)];
|
||||
}
|
||||
|
||||
/** Writes the compiled file again and empties what caches the old values. */
|
||||
public function refresh(): bool
|
||||
{
|
||||
$written = $this->store->compile();
|
||||
function_exists('opcache_reset') && @opcache_reset();
|
||||
$this->recache();
|
||||
|
||||
return $written;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $changes */
|
||||
private function writeEnv(array $changes): bool
|
||||
{
|
||||
if (! config('manager.settings.write_env')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$pairs = [];
|
||||
|
||||
foreach ($changes as $key => $value) {
|
||||
$env = $this->definitions->find($key)['env'] ?? null;
|
||||
|
||||
if ($env !== null && $value !== null) {
|
||||
$pairs[$env] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$done = $this->env->set($pairs);
|
||||
$done && $this->recache();
|
||||
|
||||
return $done;
|
||||
}
|
||||
|
||||
private function recache(): void
|
||||
{
|
||||
if (! app()->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Artisan::call('config:cache');
|
||||
} catch (Throwable) {
|
||||
// The overlay still applies on top of a config cache that is a bit old.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\ManagerServiceProvider;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
|
||||
/** What the first page of the screens needs to know: who, what they may do, the menu and the look. */
|
||||
class Shell
|
||||
@@ -26,6 +27,10 @@ class Shell
|
||||
));
|
||||
|
||||
$navigation = $this->menu->for($user, $allowed);
|
||||
$base = '/'.trim((string) config('manager.path'), '/');
|
||||
$primary = $user !== null && method_exists($user, 'managerPrimaryGroup') ? $user->managerPrimaryGroup() : null;
|
||||
// The start screen of the primary group, when this account has it in its menu.
|
||||
$start = $primary?->start !== null && in_array($base.$primary->start, array_column($navigation, 'href'), true) ? $base.$primary->start : null;
|
||||
|
||||
$extensions = array_values(array_filter(
|
||||
(array) config('manager.extensions', []),
|
||||
@@ -46,12 +51,20 @@ class Shell
|
||||
'name' => (string) ($user->name ?? ''),
|
||||
'email' => (string) ($user->email ?? ''),
|
||||
'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(),
|
||||
'group' => $primary?->name,
|
||||
],
|
||||
'start' => $start,
|
||||
'permissions' => $allowed,
|
||||
'navigation' => $navigation,
|
||||
'extensions' => $user === null ? [] : $extensions,
|
||||
'view' => $this->menu->view($user),
|
||||
'can_switch' => $this->menu->maySwitch($user),
|
||||
'simple_view' => (bool) config('manager.simple_view'),
|
||||
'tutorial' => UserSetting::value($user, 'tutorial') === 'pending',
|
||||
'tutorial_state' => UserSetting::value($user, 'tutorial'),
|
||||
'tutorial_steps' => $user === null ? [] : $this->modules->tutorial($allowed),
|
||||
'mascot' => '/'.trim((string) config('manager.path'), '/').'/_assets/mascot/',
|
||||
'locales' => UserSetting::LOCALES,
|
||||
'theme' => $key,
|
||||
'can_login' => Route::has(Names::route('login')),
|
||||
'login_fields' => $user === null ? $this->loginChecks->fields() : [],
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Tests;
|
||||
|
||||
/** A site with every module switched on. */
|
||||
abstract class AllModulesTestCase extends TestCase
|
||||
{
|
||||
protected array $modules = ['reviews' => true, 'audit' => true, 'statistics' => true, 'pages' => true, 'posts' => true];
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Tests;
|
||||
|
||||
/** A site that switched the optional audit log on (and reviews, so every module is on). */
|
||||
abstract class AuditOnTestCase extends TestCase
|
||||
{
|
||||
protected array $modules = ['audit' => true, 'reviews' => true, 'statistics' => true];
|
||||
|
||||
protected function defineEnvironment($app): void
|
||||
{
|
||||
parent::defineEnvironment($app);
|
||||
|
||||
$app['config']->set('manager.audit.never_ban', ['10.9.9.9']);
|
||||
$app['config']->set('manager.audit.whole_site_bans', true);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Auth\Events\Failed;
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Facades\Manager;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
it('has no audit log, bans, tables or rights unless the site switched it on', function () {
|
||||
expect(Route::has('manager.audit.index'))->toBeFalse()
|
||||
->and(Schema::hasTable('manager_audit_logs'))->toBeFalse()
|
||||
->and(Schema::hasTable('manager_ip_bans'))->toBeFalse()
|
||||
->and(Manager::permissionValues())->not->toContain('audit.view', 'audit.manage');
|
||||
|
||||
// A failed login goes by without a trace, and without a table to write to.
|
||||
event(new Failed('web', null, ['email' => '[email protected]']));
|
||||
});
|
||||
|
||||
it('does not schedule the prune command when the audit log is off', function () {
|
||||
$commands = collect(app(Schedule::class)->events())->map(fn ($event) => $event->command)->implode(' ');
|
||||
|
||||
expect($commands)->not->toContain('manager:audit-prune');
|
||||
});
|
||||
@@ -1,298 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Auth\Events\Failed;
|
||||
use Illuminate\Auth\Events\Login;
|
||||
use Illuminate\Auth\Events\Logout;
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Facades\Manager;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Models\AuditSetting;
|
||||
use IriksIT\Manager\Models\IpBan;
|
||||
use IriksIT\Manager\Models\IpNote;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Modules\Audit\IpBans;
|
||||
use IriksIT\Manager\Tests\AuditOnTestCase;
|
||||
|
||||
uses(AuditOnTestCase::class);
|
||||
|
||||
function fromAddress(string $ip): array
|
||||
{
|
||||
return ['REMOTE_ADDR' => $ip];
|
||||
}
|
||||
|
||||
function failLogin(string $ip, int $times = 1): void
|
||||
{
|
||||
for ($i = 0; $i < $times; $i++) {
|
||||
request()->server->set('REMOTE_ADDR', $ip);
|
||||
event(new Failed('web', null, ['email' => '[email protected]']));
|
||||
}
|
||||
}
|
||||
|
||||
describe('what is switched on', function () {
|
||||
it('has the tables, routes and rights of the audit log', function () {
|
||||
expect(Route::has('manager.audit.index'))->toBeTrue()
|
||||
->and(Schema::hasTable('manager_audit_logs'))->toBeTrue()
|
||||
->and(Schema::hasTable('manager_ip_bans'))->toBeTrue()
|
||||
->and(Manager::permissionValues())->toContain('audit.view', 'audit.manage');
|
||||
});
|
||||
|
||||
it('gives every route of the manager a name in the log', function () {
|
||||
$labelled = [...array_keys(Manager::actions()), ...array_keys(Manager::views())];
|
||||
|
||||
$missing = collect(Route::getRoutes()->getRoutes())
|
||||
->filter(fn ($route) => str_starts_with($route->uri(), config('manager.path').'/') || $route->uri() === config('manager.path'))
|
||||
->map(fn ($route) => $route->getName())
|
||||
->filter(fn ($name) => is_string($name) && str_starts_with($name, 'manager.'))
|
||||
->map(fn ($name) => substr($name, 8))
|
||||
// The login and the built files are outside `auth` (nobody is known there); a logout is logged by Laravel's Logout event.
|
||||
->reject(fn ($name) => $name === '' || in_array($name, [...$labelled, 'assets', 'login', 'login.store', 'logout', 'markdown.preview'], true))
|
||||
->values()->all();
|
||||
|
||||
expect($missing)->toBe([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('logins', function () {
|
||||
it('writes down a login, a logout and a failed login', function () {
|
||||
$user = makeUser(name: 'Ada');
|
||||
|
||||
event(new Login('web', $user, false));
|
||||
event(new Logout('web', $user));
|
||||
event(new Failed('web', $user, ['email' => $user->email]));
|
||||
|
||||
expect(AuditLog::orderBy('id')->pluck('event')->all())->toBe(['login', 'logout', 'login_failed']);
|
||||
expect(AuditLog::where('event', 'login')->sole()->user_name)->toBe('Ada');
|
||||
expect(AuditLog::where('event', 'login_failed')->sole()->email)->toBe($user->email);
|
||||
});
|
||||
|
||||
it('bans an address after too many failed logins, and not one that is never banned', function () {
|
||||
failLogin('10.0.0.5', 9);
|
||||
expect(IpBan::count())->toBe(0);
|
||||
|
||||
failLogin('10.0.0.5');
|
||||
$ban = IpBan::sole();
|
||||
expect($ban->ip)->toBe('10.0.0.5')->and($ban->automatic)->toBeTrue()->and($ban->whole_site)->toBeFalse();
|
||||
|
||||
failLogin('10.9.9.9', 30);
|
||||
expect(IpBan::where('ip', '10.9.9.9')->exists())->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not ban by itself when the rule is off', function () {
|
||||
AuditSetting::current()->forceFill(['id' => 1, 'auto_ban' => false])->save();
|
||||
|
||||
failLogin('10.0.0.6', 30);
|
||||
|
||||
expect(IpBan::count())->toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what an account does', function () {
|
||||
beforeEach(fn () => $this->actingAs(makeUser(['posts.view', 'posts.write'], name: 'Writer')));
|
||||
|
||||
it('writes down a change with what it made', function () {
|
||||
$this->postJson('/manager/posts', ['title' => 'Hello', 'body' => 'Text', 'is_published' => false])->assertCreated();
|
||||
|
||||
$line = AuditLog::where('event', 'action')->sole();
|
||||
expect($line->summary)->toBe('Created a post')
|
||||
->and($line->user_name)->toBe('Writer')
|
||||
->and($line->subject_type)->toBe('post')
|
||||
->and($line->subject_label)->toBe('Hello')
|
||||
->and($line->ip)->not->toBeNull();
|
||||
});
|
||||
|
||||
it('writes down a page that is opened once within five minutes', function () {
|
||||
$this->getJson('/manager/posts')->assertOk();
|
||||
$this->getJson('/manager/posts')->assertOk();
|
||||
|
||||
expect(AuditLog::where('event', 'viewed')->sole()->summary)->toBe('Opened the posts');
|
||||
});
|
||||
|
||||
it('writes down what the account was not allowed to do, and not a form with a mistake', function () {
|
||||
$this->deleteJson('/manager/posts/1')->assertForbidden();
|
||||
$this->postJson('/manager/posts', [])->assertStatus(422);
|
||||
|
||||
expect(AuditLog::where('event', 'refused')->sole()->summary)->toBe('Was not allowed: deleted a post')
|
||||
->and(AuditLog::where('event', 'action')->count())->toBe(0);
|
||||
});
|
||||
|
||||
it('never keeps what was typed, only the fields a module listed', function () {
|
||||
$this->actingAs(makeUser(['posts.view', 'posts.labels']));
|
||||
$this->postJson('/manager/labels', ['type' => 'tag', 'name' => 'secret-ish', 'password' => 'hunter2'])->assertCreated();
|
||||
|
||||
$line = AuditLog::where('action', 'labels.store')->sole();
|
||||
expect($line->details)->toBe(['input' => ['type' => 'tag', 'name' => 'secret-ish']]);
|
||||
expect(json_encode(AuditLog::all()))->not->toContain('hunter2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('subjects of changes and deletes', function () {
|
||||
it('names what was changed and what was deleted', function () {
|
||||
$this->actingAs(makeUser(['posts.view', 'posts.write', 'posts.delete'], name: 'Editor'));
|
||||
$post = Post::create(['title' => 'Old title', 'slug' => 'old', 'body' => 'x']);
|
||||
|
||||
$this->putJson("/manager/posts/{$post->id}", ['title' => 'New title', 'body' => 'x', 'is_published' => false])->assertOk();
|
||||
$this->deleteJson("/manager/posts/{$post->id}")->assertOk();
|
||||
|
||||
expect(AuditLog::where('action', 'posts.update')->sole()->subject_label)->toBe('New title')
|
||||
->and(AuditLog::where('action', 'posts.destroy')->sole()->subject_label)->toBe('New title');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the prune schedule', function () {
|
||||
it('runs daily when the audit log is on', function () {
|
||||
$commands = collect(app(Schedule::class)->events())->map(fn ($event) => $event->command)->implode(' ');
|
||||
|
||||
expect($commands)->toContain('manager:audit-prune');
|
||||
});
|
||||
});
|
||||
|
||||
describe('seeing the log', function () {
|
||||
it('needs audit.view', function () {
|
||||
$this->actingAs(makeUser());
|
||||
$this->getJson('/manager/audit')->assertForbidden();
|
||||
|
||||
$this->actingAs(makeUser(['audit.view']));
|
||||
$this->getJson('/manager/audit')->assertOk()->assertJsonPath('can_manage', false);
|
||||
});
|
||||
|
||||
it('filters the lines and pages through them', function () {
|
||||
$user = makeUser(['audit.view'], name: 'Viewer');
|
||||
event(new Failed('web', null, ['email' => '[email protected]']));
|
||||
event(new Login('web', $user, false));
|
||||
$this->actingAs($user);
|
||||
|
||||
$this->getJson('/manager/audit?show=failed')->assertOk()
|
||||
->assertJsonCount(1, 'entries')->assertJsonPath('entries.0.event', 'login_failed')
|
||||
->assertJsonPath('summary.logins', 1)->assertJsonPath('summary.failed', 1);
|
||||
});
|
||||
|
||||
it('links a line to its post only while the post exists', function () {
|
||||
$post = Post::create(['title' => 'Linked', 'slug' => 'linked', 'body' => 'x']);
|
||||
$this->actingAs(makeUser(['audit.view', 'posts.write']));
|
||||
$this->postJson('/manager/posts', ['title' => 'Another', 'body' => 'x', 'is_published' => false])->assertCreated();
|
||||
|
||||
$url = $this->getJson('/manager/audit?show=actions')->json('entries.0.subject.url');
|
||||
expect($url)->toBe('/manager/posts/'.Post::where('title', 'Another')->value('id').'/edit')->and($post->exists)->toBeTrue();
|
||||
});
|
||||
});
|
||||
|
||||
describe('bans', function () {
|
||||
beforeEach(fn () => $this->actingAs(makeUser(['audit.view', 'audit.manage'], name: 'Boss')));
|
||||
|
||||
it('bans by hand, writes it down, and lifts it again', function () {
|
||||
$this->postJson('/manager/audit/bans', ['ip' => '10.1.1.1', 'reason' => 'Scraper', 'minutes' => 0])->assertCreated();
|
||||
|
||||
$ban = IpBan::sole();
|
||||
expect($ban->automatic)->toBeFalse()->and($ban->expires_at)->toBeNull()->and($ban->user_name)->toBe('Boss');
|
||||
expect(AuditLog::where('action', 'audit.bans.store')->sole()->subject_label)->toBe('10.1.1.1');
|
||||
|
||||
$this->deleteJson("/manager/audit/bans/{$ban->id}")->assertOk();
|
||||
expect(IpBan::count())->toBe(0);
|
||||
});
|
||||
|
||||
it('needs audit.manage to ban', function () {
|
||||
$this->actingAs(makeUser(['audit.view']));
|
||||
|
||||
$this->postJson('/manager/audit/bans', ['ip' => '10.1.1.1', 'minutes' => 0])->assertForbidden();
|
||||
});
|
||||
|
||||
it('refuses to ban yourself or an address that is never banned', function () {
|
||||
$this->postJson('/manager/audit/bans', ['ip' => '127.0.0.1', 'minutes' => 0])->assertStatus(422)->assertJsonValidationErrors('ip');
|
||||
$this->postJson('/manager/audit/bans', ['ip' => '10.9.9.9', 'minutes' => 0])->assertStatus(422)->assertJsonValidationErrors('ip');
|
||||
|
||||
expect(IpBan::count())->toBe(0);
|
||||
});
|
||||
|
||||
it('bans and lifts a whole group of addresses', function () {
|
||||
foreach (['10.2.0.1', '10.2.0.2', '127.0.0.1'] as $ip) {
|
||||
$this->putJson('/manager/audit/notes', ['ip' => $ip, 'note' => 'farm', 'group' => 'Farm'])->assertOk();
|
||||
}
|
||||
|
||||
$this->postJson('/manager/audit/groups/ban', ['group' => 'Farm', 'minutes' => 60])->assertCreated()
|
||||
->assertJsonPath('banned', 2)->assertJsonPath('skipped', 1);
|
||||
expect(IpBan::count())->toBe(2);
|
||||
|
||||
$this->postJson('/manager/audit/groups/unban', ['group' => 'Farm'])->assertOk()->assertJsonPath('lifted', 2);
|
||||
expect(IpBan::count())->toBe(0);
|
||||
});
|
||||
|
||||
it('writes and removes the note about an address', function () {
|
||||
$this->putJson('/manager/audit/notes', ['ip' => '::1', 'note' => 'home'])->assertOk();
|
||||
expect(IpNote::sole()->note)->toBe('home');
|
||||
|
||||
$this->putJson('/manager/audit/notes', ['ip' => '::1', 'note' => '', 'group' => ''])->assertOk();
|
||||
expect(IpNote::count())->toBe(0);
|
||||
});
|
||||
|
||||
it('keeps the log no longer than the site promises', function () {
|
||||
$rules = ['auto_ban' => true, 'max_failures' => 5, 'window_minutes' => 10, 'ban_minutes' => 0];
|
||||
|
||||
$this->putJson('/manager/audit/settings', [...$rules, 'keep_days' => 91])->assertStatus(422)->assertJsonValidationErrors('keep_days');
|
||||
$this->putJson('/manager/audit/settings', [...$rules, 'keep_days' => 30])->assertOk();
|
||||
|
||||
expect(AuditSetting::current()->rules()['keep_days'])->toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a banned address', function () {
|
||||
it('is kept out of the manager with a 403, or a 429 when it was banned by itself', function () {
|
||||
app(IpBans::class)->ban('10.3.0.1', 'Scraper', 0, null);
|
||||
failLogin('10.3.0.2', 10);
|
||||
|
||||
$this->actingAs(makeUser(superAdmin: true));
|
||||
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.0.1'))->assertForbidden();
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.0.2'))->assertStatus(429)->assertHeader('Retry-After');
|
||||
$this->get('/manager/posts', fromAddress('10.3.0.1'))->assertForbidden()->assertSee('blocked from the manager');
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.0.9'))->assertOk();
|
||||
|
||||
expect(IpBan::where('ip', '10.3.0.1')->value('hits'))->toBe(2);
|
||||
});
|
||||
|
||||
it('gets the banned answer, not the login page, as a guest', function () {
|
||||
app(IpBans::class)->ban('10.3.2.1', null, 0, null);
|
||||
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.2.1'))->assertForbidden();
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.2.2'))->assertUnauthorized();
|
||||
});
|
||||
|
||||
it('is let back in when the ban ends or is lifted on the server', function () {
|
||||
app(IpBans::class)->ban('10.3.1.1', null, 10, null);
|
||||
$this->actingAs(makeUser(superAdmin: true));
|
||||
$this->travel(11)->minutes();
|
||||
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.1.1'))->assertOk();
|
||||
|
||||
app(IpBans::class)->ban('10.3.1.2', null, 0, null);
|
||||
$this->artisan('manager:unban', ['ip' => '10.3.1.2'])->assertSuccessful();
|
||||
$this->getJson('/manager/posts', fromAddress('10.3.1.2'))->assertOk();
|
||||
});
|
||||
|
||||
it('is kept off the whole site by a ban for the whole site, and no other address', function () {
|
||||
Route::get('/hello', fn () => 'hello');
|
||||
app(IpBans::class)->ban('10.4.0.1', null, 0, null, wholeSite: true);
|
||||
app(IpBans::class)->ban('10.4.0.2', null, 0, null);
|
||||
|
||||
$this->get('/hello', fromAddress('10.4.0.1'))->assertForbidden();
|
||||
$this->get('/hello', fromAddress('10.4.0.2'))->assertOk();
|
||||
$this->get('/hello', fromAddress('10.4.0.3'))->assertOk();
|
||||
});
|
||||
});
|
||||
|
||||
describe('pruning', function () {
|
||||
it('deletes old lines and ended bans, and keeps the notes', function () {
|
||||
AuditLog::create(['event' => 'login', 'summary' => 'old', 'created_at' => now()->subDays(120)]);
|
||||
AuditLog::create(['event' => 'login', 'summary' => 'new', 'created_at' => now()->subDays(10)]);
|
||||
IpBan::create(['ip' => '10.5.0.1', 'expires_at' => now()->subDays(100), 'created_at' => now()->subDays(101)]);
|
||||
IpBan::create(['ip' => '10.5.0.2', 'expires_at' => null, 'created_at' => now()->subDays(101)]);
|
||||
IpNote::create(['ip' => '10.5.0.1', 'note' => 'stays']);
|
||||
|
||||
$this->artisan('manager:audit-prune')->assertSuccessful();
|
||||
|
||||
expect(AuditLog::pluck('summary')->all())->toBe(['new'])
|
||||
->and(IpBan::pluck('ip')->all())->toBe(['10.5.0.2'])
|
||||
->and(IpNote::count())->toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
// The installer publishes the config into the app, here the skeleton in vendor/: leave it as it was.
|
||||
beforeEach(function () {
|
||||
$this->hadConfig = file_exists(config_path('manager.php'));
|
||||
$this->env = file_exists(base_path('.env')) ? file_get_contents(base_path('.env')) : null;
|
||||
});
|
||||
afterEach(function () {
|
||||
$this->hadConfig || @unlink(config_path('manager.php'));
|
||||
$this->env === null ? @unlink(base_path('.env')) : file_put_contents(base_path('.env'), $this->env);
|
||||
});
|
||||
|
||||
function doctorReport(): array
|
||||
{
|
||||
Artisan::call('manager:doctor', ['--json' => true]);
|
||||
|
||||
return json_decode(Artisan::output(), true);
|
||||
}
|
||||
|
||||
it('reports a healthy setup as JSON with exit code 0', function () {
|
||||
$report = doctorReport();
|
||||
$status = collect($report['checks'])->pluck('status', 'check');
|
||||
|
||||
expect($status['user_trait'])->toBe('ok')
|
||||
->and($status['tables'])->toBe('ok')
|
||||
->and($status['routes'])->toBe('ok')
|
||||
->and($report['ok'])->toBeTrue();
|
||||
});
|
||||
|
||||
it('fails with a fix when the user model is not a class', function () {
|
||||
config(['manager.user_model' => 'Nope\\User']);
|
||||
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'user_model');
|
||||
|
||||
expect($check['status'])->toBe('fail')->and($check['fix'])->toContain('MANAGER_USER_MODEL');
|
||||
expect(Artisan::call('manager:doctor'))->toBe(1);
|
||||
});
|
||||
|
||||
it('warns when there is no super admin yet', function () {
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'super_admin');
|
||||
|
||||
expect($check['status'])->toBe('warn')->and($check['fix'])->toContain('manager:create-user');
|
||||
});
|
||||
|
||||
it('lists the tables of the active modules', function () {
|
||||
$tables = collect(app(ModuleRegistry::class)->active())->flatMap->tables();
|
||||
|
||||
expect($tables)->toContain('media', 'posts');
|
||||
});
|
||||
|
||||
it('refuses an unknown module in the installer', function () {
|
||||
expect(Artisan::call('manager:install', ['--modules' => 'users,nonsense']))->toBe(1);
|
||||
});
|
||||
|
||||
it('writes the switches to .env', function () {
|
||||
$env = base_path('.env');
|
||||
|
||||
Artisan::call('manager:install', ['--modules' => 'users,media,posts', '--path' => 'admin']);
|
||||
|
||||
$written = file_get_contents($env);
|
||||
|
||||
expect($written)->toContain('MANAGER_PATH=admin')->toContain('MANAGER_AUDIT=false')->toContain('MANAGER_POSTS=true');
|
||||
});
|
||||
|
||||
it('leaves the check to a new process after it changed the switches', function () {
|
||||
Artisan::call('manager:install', ['--path' => 'admin']);
|
||||
|
||||
expect(Artisan::output())->toContain('manager:doctor')->not->toContain('[OK]');
|
||||
});
|
||||
|
||||
it('finds no shared names in a clean setup', function () {
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
|
||||
expect($check['message'])->toBe('No route name or address is shared with the site.');
|
||||
});
|
||||
|
||||
it('warns when the site uses a route name of the manager, and says what to set', function () {
|
||||
Route::get('/home', fn () => 'x')->name('manager.dashboard');
|
||||
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
|
||||
|
||||
expect($check['status'])->toBe('warn')->and($check['message'])->toContain('manager.dashboard')->and($check['fix'])->toContain('route_name');
|
||||
});
|
||||
|
||||
it('warns when the site has routes under the address of the manager', function () {
|
||||
Route::get('/manager/reports', fn () => 'x');
|
||||
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
|
||||
|
||||
expect($check['status'])->toBe('warn')->and($check['message'])->toContain('manager/reports');
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Tests\AuditOnTestCase;
|
||||
|
||||
uses(AuditOnTestCase::class);
|
||||
|
||||
it('renders the preview the way the site does, with raw HTML escaped', function () {
|
||||
$this->actingAs(makeUser(['posts.view']));
|
||||
|
||||
$html = $this->postJson('/manager/markdown', ['text' => "## Hi\n\n**bold** \n\n<script>alert(1)</script>"])->assertOk()->json('html');
|
||||
|
||||
expect($html)->toContain('<h2>Hi</h2>', '<strong>bold</strong>', '<img src="/media/a.jpg" alt="alt"')
|
||||
->and($html)->not->toContain('<script>');
|
||||
});
|
||||
|
||||
it('answers only to those who are logged in, and is not written in the audit log', function () {
|
||||
$this->postJson('/manager/markdown', ['text' => 'x'])->assertUnauthorized();
|
||||
|
||||
$this->actingAs(makeUser(['posts.view']));
|
||||
$this->postJson('/manager/markdown', ['text' => 'x'])->assertOk();
|
||||
$this->postJson('/manager/markdown', ['text' => str_repeat('a', 200001)])->assertJsonValidationErrors(['text']);
|
||||
|
||||
expect(AuditLog::query()->where('action', 'markdown.preview')->count())->toBe(0);
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
<?php
|
||||
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
it('loads the bundle of the site next to its own, and maps vue to the Vue of the screens', function () {
|
||||
config(['manager.extensions' => ['/build/manager-extra.js', 'https://cdn.example.com/x.js', 'javascript:alert(1)', '//evil.example/x.js', 'http://plain.example/x.js', '/a b.js']]);
|
||||
$this->actingAs(makeUser(superAdmin: true));
|
||||
|
||||
$html = $this->get('/manager')->assertOk()->getContent();
|
||||
|
||||
expect($html)->toContain('"extensions":["/build/manager-extra.js","https://cdn.example.com/x.js"]');
|
||||
expect($html)->toContain('type="importmap"')->and($html)->toContain('/manager/_assets/vue.js')
|
||||
->and($html)->not->toContain('javascript:alert')->and($html)->not->toContain('evil.example')->and($html)->not->toContain('plain.example');
|
||||
});
|
||||
|
||||
it('has no import map when the site has no bundle', function () {
|
||||
$this->actingAs(makeUser(superAdmin: true));
|
||||
|
||||
expect($this->get('/manager')->getContent())->not->toContain('importmap');
|
||||
});
|
||||
|
||||
it('serves the vue shim and the screens', function () {
|
||||
$this->get('/manager/_assets/vue.js')->assertOk()->assertHeader('Content-Type', 'application/javascript');
|
||||
$this->get('/manager/_assets/manager.js')->assertOk();
|
||||
$this->get('/manager/_assets/other.js')->assertNotFound();
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\Review;
|
||||
use IriksIT\Manager\Tests\ReviewsOnTestCase;
|
||||
|
||||
uses(ReviewsOnTestCase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
Schema::create('articles', function ($table) {
|
||||
$table->id();
|
||||
$table->string('headline')->nullable();
|
||||
$table->string('url_name')->nullable();
|
||||
$table->text('content')->nullable();
|
||||
$table->string('labels')->nullable();
|
||||
$table->string('published')->nullable();
|
||||
});
|
||||
|
||||
DB::table('articles')->insert([
|
||||
['headline' => 'First news', 'url_name' => null, 'content' => 'Hello', 'labels' => 'a, b', 'published' => '2026-01-02 10:00:00'],
|
||||
['headline' => 'Draft', 'url_name' => 'my-draft', 'content' => 'Later', 'labels' => '["x"]', 'published' => null],
|
||||
['headline' => 'No text', 'url_name' => 'no-text', 'content' => '', 'labels' => null, 'published' => null],
|
||||
]);
|
||||
|
||||
$this->map = ['--map' => ['title=headline', 'slug=url_name', 'body=content', 'tags=labels', 'published_at=published']];
|
||||
});
|
||||
|
||||
it('copies rows into the package and repeats without duplicating', function () {
|
||||
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles'] + $this->map)
|
||||
->expectsOutputToContain('2 created, 0 updated, 1 skipped')->assertSuccessful();
|
||||
|
||||
expect(Post::query()->count())->toBe(2)
|
||||
->and(Post::query()->where('slug', 'first-news')->first()->tags)->toBe(['a', 'b'])
|
||||
->and(Post::query()->where('slug', 'my-draft')->first()->tags)->toBe(['x'])
|
||||
->and(Post::query()->where('slug', 'my-draft')->first()->published_at)->toBeNull();
|
||||
|
||||
DB::table('articles')->where('url_name', 'my-draft')->update(['content' => 'Changed']);
|
||||
|
||||
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles'] + $this->map)
|
||||
->expectsOutputToContain('0 created, 2 updated, 1 skipped');
|
||||
|
||||
expect(Post::query()->count())->toBe(2)
|
||||
->and(Post::query()->where('slug', 'my-draft')->value('body'))->toBe('Changed');
|
||||
});
|
||||
|
||||
it('writes nothing on a dry run and never touches the source', function () {
|
||||
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles', '--dry-run' => true] + $this->map)
|
||||
->expectsOutputToContain('Dry run: 2 created');
|
||||
|
||||
expect(Post::query()->count())->toBe(0)->and(DB::table('articles')->count())->toBe(3);
|
||||
});
|
||||
|
||||
it('refuses what it does not know', function () {
|
||||
$this->artisan('manager:import', ['target' => 'cars', '--table' => 'articles'])->assertFailed();
|
||||
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles', '--map' => ['colour=x']])->assertFailed();
|
||||
$this->artisan('manager:import', ['target' => 'posts'])->assertFailed();
|
||||
});
|
||||
|
||||
it('reads its settings from the config and imports reviews', function () {
|
||||
Schema::create('quotes', function ($table) {
|
||||
$table->id();
|
||||
$table->string('who');
|
||||
$table->text('said');
|
||||
$table->integer('stars')->nullable();
|
||||
});
|
||||
DB::table('quotes')->insert([['who' => 'A', 'said' => 'Fine', 'stars' => 9]]);
|
||||
config(['manager.import.reviews' => ['table' => 'quotes', 'map' => ['author' => 'who', 'body' => 'said', 'rating' => 'stars']]]);
|
||||
|
||||
$this->artisan('manager:import', ['target' => 'reviews'])->assertSuccessful();
|
||||
|
||||
expect(Review::query()->first()->rating)->toBe(5);
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Auth\Events\Failed;
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Support\Login\BaseLoginCheck;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
class NeedsCode extends BaseLoginCheck
|
||||
{
|
||||
public function fields(): array
|
||||
{
|
||||
return [['name' => 'code', 'type' => 'text', 'label' => 'Code', 'autocomplete' => 'one-time-code']];
|
||||
}
|
||||
|
||||
public function after(Request $request, Authenticatable $user): void
|
||||
{
|
||||
if ($request->input('code') !== '123456') {
|
||||
throw ValidationException::withMessages(['code' => 'The code is not right.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = makeUser(superAdmin: true);
|
||||
$this->user->forceFill(['password' => Hash::make('a-long-enough-password')])->save();
|
||||
$this->login = fn (array $extra = []) => $this->postJson('/manager/login', ['email' => $this->user->email, 'password' => 'a-long-enough-password'] + $extra);
|
||||
});
|
||||
|
||||
it('logs in as before when no check is set', function () {
|
||||
($this->login)()->assertOk()->assertJsonPath('redirect', '/manager');
|
||||
$this->assertAuthenticated();
|
||||
});
|
||||
|
||||
it('asks a second factor of the site after the password, and counts a refusal as a failed login', function () {
|
||||
config(['manager.login.checks' => [NeedsCode::class]]);
|
||||
$failed = 0;
|
||||
Event::listen(Failed::class, function () use (&$failed) {
|
||||
$failed++;
|
||||
});
|
||||
|
||||
($this->login)(['code' => '000000'])->assertJsonValidationErrors(['code']);
|
||||
$this->assertGuest();
|
||||
expect($failed)->toBe(1);
|
||||
|
||||
($this->login)(['code' => '123456'])->assertOk();
|
||||
$this->assertAuthenticated();
|
||||
});
|
||||
|
||||
it('shows the fields of the checks on the form', function () {
|
||||
config(['manager.login.checks' => [NeedsCode::class, 'Not\\A\\Check']]);
|
||||
|
||||
$this->get('/manager/login')->assertOk()->assertSee('"login_fields":[{"name":"code"', false);
|
||||
});
|
||||
|
||||
describe('turnstile', function () {
|
||||
beforeEach(fn () => config(['manager.login.turnstile' => ['site_key' => 'site-key', 'secret' => 'secret-key']]));
|
||||
|
||||
it('needs a token that Cloudflare accepts, and checks before the password', function () {
|
||||
Http::fake(['challenges.cloudflare.com/*' => Http::response(['success' => true])]);
|
||||
|
||||
($this->login)()->assertJsonValidationErrors(['turnstile']);
|
||||
($this->login)(['turnstile' => 'token'])->assertOk();
|
||||
|
||||
Http::assertSent(fn ($request) => $request['secret'] === 'secret-key' && $request['response'] === 'token');
|
||||
});
|
||||
|
||||
it('refuses a token Cloudflare does not accept, and everything when Cloudflare is unreachable', function () {
|
||||
Http::fake(['challenges.cloudflare.com/*' => Http::response(['success' => false])]);
|
||||
($this->login)(['turnstile' => 'bad'])->assertJsonValidationErrors(['turnstile']);
|
||||
|
||||
Http::fake(['challenges.cloudflare.com/*' => Http::response('', 500)]);
|
||||
($this->login)(['turnstile' => 'token'])->assertJsonValidationErrors(['turnstile']);
|
||||
|
||||
Http::fake(fn () => throw new ConnectionException('down'));
|
||||
($this->login)(['turnstile' => 'token'])->assertJsonValidationErrors(['turnstile']);
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
it('puts the widget on the form', function () {
|
||||
$this->get('/manager/login')->assertSee('"type":"turnstile","site_key":"site-key"', false);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Tests\MediaOffTestCase;
|
||||
|
||||
uses(MediaOffTestCase::class);
|
||||
|
||||
it('has no routes, no public file route and no table for a site without media', function () {
|
||||
expect(Route::has('manager.media.index'))->toBeFalse()
|
||||
->and(Route::has('manager.media.file'))->toBeFalse()
|
||||
->and(Schema::hasTable('manager_media'))->toBeFalse();
|
||||
|
||||
$this->get('/media-files/1/x.png/view')->assertNotFound();
|
||||
});
|
||||
@@ -1,128 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
function png(string $name = 'My Photo.png'): UploadedFile
|
||||
{
|
||||
return UploadedFile::fake()->createWithContent($name, file_get_contents(__DIR__.'/../Fixtures/pixel.png'));
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
Storage::fake('public');
|
||||
$this->actingAs(makeUser(['media.delete', 'media.edit', 'media.upload']));
|
||||
});
|
||||
|
||||
describe('uploading', function () {
|
||||
it('stores a file on the disk and records it', function () {
|
||||
$item = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.3, 'focus_y' => 0.65])->assertCreated()->json('item');
|
||||
|
||||
$media = Media::sole();
|
||||
Storage::disk('public')->assertExists($media->location);
|
||||
expect($item['url'])->toBe("/media-files/{$media->id}/my-photo.png/view")
|
||||
->and($item)->not->toHaveKeys(['disk', 'location'])
|
||||
->and($media->name)->toBe('My Photo')
|
||||
->and($media->width)->toBe(1)
|
||||
->and($media->checksum)->toBe(hash_file('sha256', __DIR__.'/../Fixtures/pixel.png'))
|
||||
->and($media->focus_x)->toBe(0.3)
|
||||
->and(Media::focusFor($item['url']))->toBe('30% 65%')
|
||||
->and(Media::focusFor('/somewhere/else'))->toBeNull();
|
||||
});
|
||||
|
||||
it('refuses what is not allowed: svg, too big, no room', function () {
|
||||
$svg = UploadedFile::fake()->createWithContent('x.svg', '<svg xmlns="http://www.w3.org/2000/svg"/>');
|
||||
$this->postJson('/manager/media', ['file' => $svg])->assertJsonValidationErrors('file');
|
||||
|
||||
config(['manager.media.max_file_mb' => 1]);
|
||||
$this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('big.pdf', 2048, 'application/pdf')])->assertJsonValidationErrors('file');
|
||||
|
||||
config(['manager.media.max_total_gb' => 0.000001]);
|
||||
$this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('a.pdf', 5, 'application/pdf')])->assertStatus(422)->assertJsonPath('storage.limit', 1000);
|
||||
expect(Media::count())->toBe(0);
|
||||
});
|
||||
|
||||
it('needs the permission', function () {
|
||||
$this->actingAs(makeUser(['media.view']));
|
||||
|
||||
$this->postJson('/manager/media', ['file' => png()])->assertForbidden();
|
||||
$this->getJson('/manager/media/items')->assertOk();
|
||||
});
|
||||
});
|
||||
|
||||
describe('changing and deleting', function () {
|
||||
it('renames and keeps the focus point unless one is sent', function () {
|
||||
$id = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.1, 'focus_y' => 0.2])->json('item.id');
|
||||
|
||||
$this->putJson("/manager/media/{$id}", ['name' => 'New', 'alt' => ' A cat '])->assertOk()->assertJsonPath('item.alt', 'A cat');
|
||||
expect(Media::find($id)->focus_y)->toBe(0.2);
|
||||
|
||||
$this->putJson("/manager/media/{$id}", ['name' => 'New', 'focus_x' => 0.5])->assertJsonValidationErrors('focus_y');
|
||||
});
|
||||
|
||||
it('deletes the file and the row', function () {
|
||||
$this->postJson('/manager/media', ['file' => png()]);
|
||||
$media = Media::sole();
|
||||
|
||||
$this->deleteJson("/manager/media/{$media->id}")->assertOk();
|
||||
|
||||
Storage::disk('public')->assertMissing($media->location);
|
||||
expect(Media::count())->toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usage', function () {
|
||||
it('counts where a file is used, through the registered sources of the modules that are on', function () {
|
||||
$id = $this->postJson('/manager/media', ['file' => png()])->json('item.id');
|
||||
Post::create(['slug' => 'a', 'title' => 'A', 'body' => "See "]);
|
||||
|
||||
expect(collect($this->getJson('/manager/media/items')->json('items'))->firstWhere('id', $id)['usage_count'])->toBe(1);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('the file for visitors', function () {
|
||||
beforeEach(function () {
|
||||
$this->postJson('/manager/media', ['file' => png()]);
|
||||
$this->media = Media::sole();
|
||||
auth()->logout();
|
||||
$this->app['auth']->forgetGuards();
|
||||
});
|
||||
|
||||
it('is served without logging in, with caching headers', function () {
|
||||
$response = $this->get($this->media->url())->assertOk()->assertHeader('Content-Type', 'image/png');
|
||||
|
||||
expect($response->headers->get('Cache-Control'))->toContain('immutable')
|
||||
->and($response->headers->get('X-Content-Type-Options'))->toBe('nosniff')
|
||||
->and($response->headers->has('Set-Cookie'))->toBeFalse()
|
||||
->and($response->streamedContent())->toBe(file_get_contents(__DIR__.'/../Fixtures/pixel.png'));
|
||||
});
|
||||
|
||||
it('answers 304 for a known ETag and a part for a range', function () {
|
||||
$etag = '"'.$this->media->checksum.'"';
|
||||
$this->get($this->media->url(), ['If-None-Match' => $etag])->assertStatus(304);
|
||||
|
||||
$part = $this->get($this->media->url(), ['Range' => 'bytes=0-9'])->assertStatus(206)->assertHeader('Content-Range', "bytes 0-9/{$this->media->size}");
|
||||
expect($part->streamedContent())->toBe(substr(file_get_contents(__DIR__.'/../Fixtures/pixel.png'), 0, 10));
|
||||
|
||||
$this->get($this->media->url(), ['Range' => 'bytes=9999-'])->assertStatus(416);
|
||||
});
|
||||
|
||||
it('offers anything that is not a safe type as a download', function () {
|
||||
$this->media->update(['mime_type' => 'text/html']);
|
||||
|
||||
$this->get($this->media->url())->assertHeader('Content-Type', 'application/octet-stream')
|
||||
->assertHeader('Content-Disposition', 'attachment; filename="my-photo.png"');
|
||||
});
|
||||
|
||||
it('is 404 when the row or the file is gone', function () {
|
||||
$this->get('/media-files/9999/x.png/view')->assertNotFound();
|
||||
|
||||
Storage::disk('public')->delete($this->media->location);
|
||||
$this->get($this->media->url())->assertNotFound();
|
||||
});
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Tests\SimpleViewTestCase;
|
||||
|
||||
uses(SimpleViewTestCase::class);
|
||||
|
||||
function menuOf($test, $user): array
|
||||
{
|
||||
return $test->actingAs($user)->getJson('/manager')->assertOk()->json('navigation');
|
||||
}
|
||||
|
||||
it('puts sections, icons and order on the menu, and adds links of the site', function () {
|
||||
config(['manager.menu.links' => [['label' => 'Leads', 'url' => '/manager/leads', 'section' => 'Content', 'order' => 6, 'new_tab' => true]]]);
|
||||
config(['manager.menu.items' => [...config('manager.menu.items'), 'labels.index' => ['hidden' => true]]]);
|
||||
|
||||
$items = collect(app(ModuleRegistry::class)->navigation());
|
||||
|
||||
expect($items->first())->toMatchArray(['label' => 'Posts', 'section' => 'Content', 'icon' => 'file', 'order' => 5, 'simple' => true])
|
||||
->and($items->pluck('label')->slice(0, 2)->values()->all())->toBe(['Posts', 'Leads'])
|
||||
->and($items->pluck('label'))->not->toContain('Categories and tags')
|
||||
->and($items->firstWhere('label', 'Leads'))->toMatchArray(['url' => '/manager/leads', 'new_tab' => true]);
|
||||
});
|
||||
|
||||
it('keeps the old shape of a menu item working', function () {
|
||||
$item = collect(app(ModuleRegistry::class)->navigation())->firstWhere('label', 'Media');
|
||||
|
||||
expect($item)->toMatchArray(['label' => 'Media', 'permission' => 'media.view', 'simple' => false, 'order' => 100])
|
||||
->and($item['route'])->toBe('manager.media.index');
|
||||
});
|
||||
|
||||
it('shows an account with only the switch permission the simple face first, and lets it change', function () {
|
||||
$user = makeUser(['posts.view', 'media.view', 'manager.switch']);
|
||||
|
||||
expect(collect(menuOf($this, $user))->pluck('label')->all())->toBe(['Posts']);
|
||||
|
||||
$this->putJson('/manager/profile/view', ['view' => 'full'])->assertOk();
|
||||
|
||||
expect(collect(menuOf($this, $user))->pluck('label')->all())->toBe(['Posts', 'Media'])
|
||||
->and(UserSetting::query()->where('user_id', $user->id)->value('view'))->toBe('full');
|
||||
|
||||
$this->putJson('/manager/profile/view', ['view' => 'nonsense'])->assertUnprocessable();
|
||||
});
|
||||
|
||||
it('gives the full face to an account with the full permission, and the simple face to all others for good', function () {
|
||||
$full = makeUser(['posts.view', 'media.view', 'manager.full']);
|
||||
$plain = makeUser(['posts.view', 'media.view']);
|
||||
|
||||
expect(collect(menuOf($this, $full))->pluck('label')->all())->toBe(['Posts', 'Media']);
|
||||
expect(collect(menuOf($this, $plain))->pluck('label')->all())->toBe(['Posts']);
|
||||
|
||||
$this->putJson('/manager/profile/view', ['view' => 'full'])->assertForbidden();
|
||||
});
|
||||
|
||||
it('lets a super admin see everything and switch', function () {
|
||||
$admin = makeUser(superAdmin: true);
|
||||
|
||||
expect(collect(menuOf($this, $admin))->pluck('label'))->toContain('Posts', 'Media');
|
||||
|
||||
$this->putJson('/manager/profile/view', ['view' => 'simple'])->assertOk();
|
||||
|
||||
expect(collect(menuOf($this, $admin))->pluck('label')->all())->toBe(['Posts']);
|
||||
});
|
||||
|
||||
it('offers the two permissions in the group form only when the simple face is on', function () {
|
||||
expect(collect(app(ModuleRegistry::class)->permissionValues()))->toContain('manager.full', 'manager.switch');
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Facades\Manager;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
it('has users and media on and reviews off by default', function () {
|
||||
expect(Manager::enabled('users'))->toBeTrue()
|
||||
->and(Manager::enabled('media'))->toBeTrue()
|
||||
->and(Manager::enabled('reviews'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('adds no routes, tables or permissions for a module that is off', function () {
|
||||
expect(Route::has('manager.reviews.index'))->toBeFalse()
|
||||
->and(Schema::hasTable('manager_reviews'))->toBeFalse()
|
||||
->and(Manager::permissions())->not->toHaveKey('reviews.manage')
|
||||
->and(collect(Manager::navigation())->pluck('label'))->not->toContain('Reviews');
|
||||
});
|
||||
|
||||
it('adds all of it for a module that is on', function () {
|
||||
expect(Route::has('manager.posts.index'))->toBeTrue()
|
||||
->and(Schema::hasTable('manager_posts'))->toBeTrue()
|
||||
->and(Manager::permissions())->toHaveKey('posts.publish');
|
||||
});
|
||||
|
||||
it('lets a super admin in and keeps others out without the permission', function () {
|
||||
$this->actingAs(makeUser(superAdmin: true))->getJson('/manager/posts')->assertOk();
|
||||
$this->actingAs(makeUser())->getJson('/manager/posts')->assertForbidden();
|
||||
});
|
||||
|
||||
it('gives a group member the permissions of the group, with what they need', function () {
|
||||
$user = makeUser(['posts.publish']);
|
||||
|
||||
expect($user->managerPermissions())->toBe(['posts.view', 'posts.write', 'posts.publish']);
|
||||
$this->actingAs($user)->getJson('/manager/posts')->assertOk();
|
||||
$this->actingAs($user)->getJson('/manager/pages')->assertForbidden();
|
||||
});
|
||||
|
||||
it('forgets what a switched-off module allowed', function () {
|
||||
$group = Group::create(['name' => 'Old', 'permissions' => ['posts.view', 'reviews.manage']]);
|
||||
|
||||
expect($group->allowed())->toBe(['posts.view']);
|
||||
});
|
||||
|
||||
it('does not answer for abilities of the host app', function () {
|
||||
expect(Gate::forUser(makeUser(superAdmin: true))->allows('host.something'))->toBeFalse();
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
it('keeps the names of every earlier version by default', function () {
|
||||
expect(Names::route('posts.index'))->toBe('manager.posts.index')
|
||||
->and(Names::table('posts'))->toBe('manager_posts')
|
||||
->and(Route::has('manager.dashboard'))->toBeTrue()
|
||||
->and(Route::has('manager.media.file'))->toBeTrue()
|
||||
->and(Schema::hasTable('manager_posts'))->toBeTrue()
|
||||
->and(Schema::hasTable('manager_media'))->toBeTrue();
|
||||
});
|
||||