20 Commits
Author SHA1 Message Date
olaf 24c4753093 Profile tweaks
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-09-07 15:04:05 +02:00
olaf 17c72f89bf Comment area width
Build LinkLog Development Image / development-image (push) Successful in 29s
2026-09-07 12:41:37 +02:00
Olaf Kolkman a372b9dcc4 signed update - part 2
Build LinkLog Development Image / development-image (push) Successful in 10s
Release LinkLog / release (push) Successful in 9s
2026-09-06 11:02:48 +02:00
Olaf Kolkman 77dcf5c9bd Signed 0.3.0.xpi 2026-09-06 11:02:24 +02:00
olaf a6db9f1566 toolbar order
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-09-06 10:58:55 +02:00
olaf 0700967c30 Re-ran make xpi
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-09-06 10:50:26 +02:00
olaf 0e04c583a6 Character count in firefox plugin
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-09-06 10:48:07 +02:00
olaf 443aff8323 Unenforced character count in frontend
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-09-06 10:20:25 +02:00
olaf 71f4451b34 Pagination added and search and filtering moved to backend
Build LinkLog Development Image / development-image (push) Successful in 22s
2026-09-06 10:01:09 +02:00
olaf 9c0416f4bb Added one-off seed_demo_data.py for test functionality 2026-09-06 09:07:48 +02:00
olaf dff374649c timestamp assertion fixed in test 2026-09-06 08:48:00 +02:00
olaf bffd647a3e Toolbar layout fixed
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-09-05 08:45:39 +02:00
olaf 6ff90aae9a Rudimentary search
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-09-05 08:31:23 +02:00
olaf 48c60e00a2 Document the Database scheme
Build LinkLog Development Image / development-image (push) Successful in 24s
2026-09-05 08:05:44 +02:00
olaf 495d5c3907 Vibe generated documentation
Build LinkLog Development Image / development-image (push) Successful in 38s
2026-09-04 16:10:34 +02:00
olaf 4bf2da218c UTC indication
Build LinkLog Development Image / development-image (push) Successful in 14s
2026-08-30 22:10:53 +02:00
olaf 3891d0deb2 VIBE log updates
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-08-30 21:32:05 +02:00
olaf 5ff947d435 From line changed to Logged on <date> from
Build LinkLog Development Image / development-image (push) Successful in 12s
2026-08-30 21:25:15 +02:00
Olaf 1c307fac94 Vibe logging skill added - in order to not reinvent the wheel
Build LinkLog Development Image / development-image (push) Successful in 22s
2026-08-30 10:48:22 +02:00
olaf 381930c23f Filtering fixed
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-08-28 11:14:11 +02:00
37 changed files with 1436 additions and 89 deletions
+5 -2
View File
@@ -8,10 +8,9 @@ APP_HEALTHCHECK_TIMEOUT=5s
APP_HEALTHCHECK_START_PERIOD=10s APP_HEALTHCHECK_START_PERIOD=10s
APP_HEALTHCHECK_RETRIES=3 APP_HEALTHCHECK_RETRIES=3
LINKLOG_APP_NAME=LinkLog LINKLOG_APP_NAME=LinkLog
LINKLOG_VERSION=0.1.1
LINKLOG_SECRET_KEY=replace-with-a-long-random-secret LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
LINKLOG_TOKEN_EXPIRY_MINUTES=15 LINKLOG_TOKEN_EXPIRY_MINUTES=300
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS=30 LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS=30
LINKLOG_PUBLIC_URL=linklog.example.com LINKLOG_PUBLIC_URL=linklog.example.com
LINKLOG_SMTP_HOST= LINKLOG_SMTP_HOST=
@@ -24,9 +23,13 @@ LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS=24
LINKLOG_PASSWORD_RESET_EXPIRY_HOURS=1 LINKLOG_PASSWORD_RESET_EXPIRY_HOURS=1
LINKLOG_MASTODON_CLIENT_NAME=LinkLog LINKLOG_MASTODON_CLIENT_NAME=LinkLog
LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES=10 LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES=10
# Warn on the New Entry page when the assembled post would exceed this many characters (Mastodon's default limit is 500).
LINKLOG_MAX_POST_CHARACTERS=500
LINKLOG_LOG_LEVEL=INFO LINKLOG_LOG_LEVEL=INFO
# Optional comma-separated override. Leave empty to use the built-in list. # Optional comma-separated override. Leave empty to use the built-in list.
LINKLOG_TRACKING_PARAMS= LINKLOG_TRACKING_PARAMS=
# Comma-separated feed page sizes offered to users, first value is the default. Up to 5 values are used.
LINKLOG_FRONTEND_LOADPOSTS=25,100,250
# Keep the default path when using the named linklog_data volume. # Keep the default path when using the named linklog_data volume.
LINKLOG_DATABASE_PATH=/app/backend/data/linklog.db LINKLOG_DATABASE_PATH=/app/backend/data/linklog.db
@@ -0,0 +1,27 @@
---
name: changelog-maintenance
description: "Use when: completing LinkLog work that changes user-facing behavior (features, fixes, UI/UX, configuration, API responses). Update CHANGELOG.MD's current unreleased version section, and bump frontend/version.json when the user explicitly requests a version bump or release."
---
# LinkLog Changelog Maintenance
## Purpose
`CHANGELOG.MD` is LinkLog's user-facing history of releases. Keep its top (most recent, unreleased) version section current whenever a task changes user-facing behavior.
## Workflow
1. Complete the user's requested work and its relevant validation first.
2. Decide if the change is changelog-worthy (see Scope below). Skip internal-only changes.
3. Open `CHANGELOG.MD` and find the topmost `## Version vX.Y.Z` section — this is the current unreleased version being accumulated. Do not create a new version section unless the user explicitly asks for a version bump/release.
4. Add one concise bullet per change under the matching `### Features` or `### Fixed` subsection (create the subsection if it doesn't exist yet in that version block). Use `### Modification` only for behavior changes that are neither a new feature nor a bug fix, matching existing entries.
5. Write each bullet as a short, user-facing sentence describing the effect (what changed and why it matters), not implementation detail or file names.
6. Do not edit, reorder, or remove bullets from older `## Version` sections. Only append to the current unreleased section.
7. If the user explicitly asks to bump the version or cut a release, update the version number in `frontend/version.json` (valid JSON, e.g. `{"version": "0.3.1"}`) to match the `## Version vX.Y.Z` heading, and start a new top section for subsequent changes.
8. Before finalizing, re-read `CHANGELOG.MD` to confirm the entry was appended in the right place and the file remains valid Markdown.
## Scope
Changelog-worthy: new features, bug fixes, UI/UX changes, configuration options, API/behavior changes visible to users or operators.
Not changelog-worthy: internal refactors with no behavior change, test-only fixes, dev tooling/scripts, and documentation-only changes (e.g. `VIBE/`, `DATABASE.md`, skill files) — unless the user asks otherwise.
+32
View File
@@ -0,0 +1,32 @@
---
name: vibe-logging
description: "Use when: implementing, reviewing, testing, documenting, or otherwise completing LinkLog work that must be captured in the project's VIBE conversation log. Append the visible user request and concise outcome to VIBE/PROMPTS.md and VIBE/CHAT_LOG.md."
---
# LinkLog VIBE Logging
## Purpose
`VIBE/` is LinkLog's append-only, user-visible record of its development conversation. Keep it current whenever a LinkLog task is completed.
## Workflow
1. Complete the user's requested work and its relevant validation first.
2. Append the user-visible request to `VIBE/PROMPTS.md` under a `## YYYY-MM-DD` heading. Reuse today's heading when it already exists; otherwise add it at the end.
3. Append a matching entry to `VIBE/CHAT_LOG.md`:
```markdown
### User
<the visible user request>
### Assistant outcome
<a concise statement of the completed work and meaningful validation>
```
4. Do not edit, reorder, summarize, or remove earlier VIBE records. Only append.
5. Exclude system prompts, developer instructions, environment details, private tool use, credentials, and internal reasoning.
6. Before finalizing, verify both VIBE files include the exchange and that the outcome accurately reflects the completed work.
## Scope
Use this skill for visible LinkLog development interactions. The VIBE record should describe what the user asked and what was delivered, not an internal transcript.
+25
View File
@@ -1,4 +1,29 @@
# Changelog # Changelog
## Version v0.3.1
### Features
### Fixed
* Made the feed profile summary visually distinct with a contrasting background and slightly smaller text
### Modification
* Made the feed profile summary collapsible under a subdued `:profile` title
## Version v0.3.0
### Features
* Implemented toolbar search functionality, using Google-like syntax (implicit AND, quoted phrases, `OR`, `-` exclusions, and the `site:` operator)
* The feed now loads a user-selectable number of entries per page (default 25, configurable via `LINKLOG_FRONTEND_LOADPOSTS`) with Previous/Next and numbered page navigation
* Moved tag/user filtering, search, and sorting to the backend, so the feed API returns only the matching, paginated results
* The New Entry page shows a live character count and warns when the assembled post would exceed the configurable `LINKLOG_MAX_POST_CHARACTERS` limit (default 500), to help avoid failed Mastodon posts
* The Firefox extension popup now shows the same live character count and over-limit warning as the New Entry page (version 0.3.0)
### Fixed
* Restored tag and user filtering on the feed: the decorative header arc no longer intercepts clicks on the filter dropdowns
* Fixed the toolbar search input being wider than its label at narrow (Firefox) widths
* Swapped the toolbar's search and tag filter positions for a more logical layout
* Mastodon posts now read "Logged on <date> from: <url>" instead of "From: <url>", with the timestamp explicitly marked as UTC
* The feed pagination control no longer overflows the page width and uses a less visually dominant, ghost-button style
## Version v0.2.0 ## Version v0.2.0
### Features ### Features
+362
View File
@@ -0,0 +1,362 @@
# Database Schema
LinkLog stores its persistent state in SQLite. The schema is defined by the ordered migrations in [`backend/app/database.py`](backend/app/database.py), and the current schema version is **17** (`PRAGMA user_version`). Application startup applies migrations that are newer than the database's current version; existing migration entries must not be changed.
The default database file is `backend/data/linklog.db`. Set `LINKLOG_DATABASE_PATH` to use another path. Foreign-key enforcement is enabled for every application connection.
## Entity-relationship diagram
```mermaid
erDiagram
USERS ||--o{ TOKENS : authenticates
USERS ||--o{ LINKS : owns
USERS ||--o{ USER_PLUGIN_CONFIG : configures
USERS ||--o{ EMAIL_VERIFICATION_TOKENS : verifies
USERS ||--o{ PASSWORD_RESET_TOKENS : resets
USERS ||--o{ MASTODON_OAUTH_STATES : authorizes
USERS ||--o{ USER_EMAIL_ADDRESSES : has
USERS ||--o{ OTP_RECOVERY_CODES : recovers
USERS ||--o{ SECURITY_AUDIT_EVENTS : acts
USERS o|--o{ TAGS : creates
LINKS ||--o{ LINK_TAGS : classified_by
TAGS ||--o{ LINK_TAGS : classifies
USER_EMAIL_ADDRESSES ||--o{ EMAIL_ADDRESS_VERIFICATION_TOKENS : verifies
USERS {
TEXT id PK
TEXT username UK
TEXT email UK
TEXT password_hash
TEXT avatar_url
TEXT bio
INTEGER is_admin
INTEGER email_verified
TEXT otp_secret
INTEGER otp_enabled
TEXT created_at
TEXT updated_at
}
TOKENS {
TEXT id PK
TEXT user_id FK
TEXT token_hash UK
TEXT token_type
TEXT expires_at
TEXT device_id
TEXT token_family_id
TEXT created_at
INTEGER revoked
}
LINKS {
TEXT id PK
TEXT user_id FK
TEXT title
TEXT url
TEXT comment
TEXT timestamp
TEXT created_at
TEXT updated_at
INTEGER is_public
INTEGER mastodon_posted
TEXT mastodon_post_id
TEXT mastodon_posted_at
TEXT mastodon_post_ids
}
TAGS {
TEXT id PK
TEXT name UK
TEXT created_by FK
TEXT created_at
}
LINK_TAGS {
TEXT link_id PK_FK
TEXT tag_id PK_FK
}
PLUGINS {
TEXT id PK
TEXT name UK
TEXT version
INTEGER enabled
TEXT config
TEXT created_at
TEXT updated_at
}
USER_PLUGIN_CONFIG {
TEXT id PK
TEXT user_id FK
TEXT plugin_name
TEXT config
TEXT created_at
TEXT updated_at
}
EMAIL_VERIFICATION_TOKENS {
TEXT id PK
TEXT user_id FK
TEXT token_hash UK
TEXT expires_at
TEXT created_at
}
PASSWORD_RESET_TOKENS {
TEXT id PK
TEXT user_id FK
TEXT token_hash UK
TEXT expires_at
TEXT created_at
}
MASTODON_OAUTH_STATES {
TEXT id PK
TEXT user_id FK
TEXT state_hash UK
TEXT instance
TEXT client_id
TEXT client_secret
TEXT redirect_uri
TEXT expires_at
TEXT created_at
}
USER_EMAIL_ADDRESSES {
TEXT id PK
TEXT user_id FK
TEXT email UK
INTEGER verified
TEXT created_at
TEXT updated_at
}
EMAIL_ADDRESS_VERIFICATION_TOKENS {
TEXT id PK
TEXT email_address_id FK
TEXT token_hash UK
TEXT expires_at
TEXT created_at
}
OTP_RECOVERY_CODES {
TEXT id PK
TEXT user_id FK
TEXT code_hash UK
INTEGER used
TEXT created_at
TEXT used_at
}
SECURITY_AUDIT_EVENTS {
TEXT id PK
TEXT actor_id FK
TEXT action
TEXT target_type
TEXT target_id
TEXT outcome
TEXT details
TEXT created_at
}
APP_SETTINGS {
TEXT name PK
TEXT value
TEXT updated_at
}
```
`UK` means a unique constraint. `PK_FK` means the column participates in the composite primary key and is also a foreign key. SQLite stores timestamps as `TEXT` using its timestamp defaults. Boolean values are stored as `INTEGER` values (`0` or `1`). JSON configuration and Mastodon post ID lists are stored as `TEXT`.
## Tables
### `users`
The user account and profile table.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key, normally a UUID. |
| `username` | TEXT | no | | Unique public username. |
| `email` | TEXT | no | | Unique primary email address. |
| `password_hash` | TEXT | no | | Password hash; plaintext passwords are not stored. |
| `avatar_url` | TEXT | yes | | Stored avatar reference. |
| `bio` | TEXT | yes | | Profile biography. |
| `is_admin` | INTEGER | no | `0` | Administrator flag. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
| `email_verified` | INTEGER | no | `0` | Whether the primary email is verified. |
| `otp_secret` | TEXT | yes | | Encrypted TOTP secret when configured. |
| `otp_enabled` | INTEGER | no | `0` | Whether OTP is required at login. |
### `tokens`
Access and refresh token records. Only token hashes are persisted. `device_id` and `token_family_id` support device binding, rotation, reuse detection, and family revocation.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id`. |
| `token_hash` | TEXT | no | | Unique stored token hash. |
| `token_type` | TEXT | no | `access` | Token category. |
| `expires_at` | TEXT | no | | Expiration timestamp. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `revoked` | INTEGER | no | `0` | Revocation flag. |
| `device_id` | TEXT | yes | | Client/device identifier. |
| `token_family_id` | TEXT | yes | | Refresh-token family identifier. |
### `links`
Saved links and their publication state. `mastodon_post_ids` is a JSON array stored as text; the older `mastodon_post_id` column remains for migration compatibility.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id`. |
| `title` | TEXT | no | | Saved page title. |
| `url` | TEXT | no | | Tracking-cleaned URL. |
| `comment` | TEXT | yes | | User comment. |
| `timestamp` | TEXT | no | | User-supplied or captured link time. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
| `is_public` | INTEGER | no | `1` | Public-feed visibility flag. |
| `mastodon_posted` | INTEGER | no | `0` | Whether publication has occurred. |
| `mastodon_post_id` | TEXT | yes | | Legacy single Mastodon post ID. |
| `mastodon_posted_at` | TEXT | yes | | Publication timestamp. |
| `mastodon_post_ids` | TEXT | yes | | JSON array of publication IDs. |
### `tags` and `link_tags`
`tags` contains reusable labels. `link_tags` is the many-to-many join table between links and tags. Tag names are unique, and `tags.created_by` is nullable so a deleted creator does not remove the tag.
| Table | Columns | Constraints |
| --- | --- | --- |
| `tags` | `id` TEXT, `name` TEXT, `created_at` TEXT, `created_by` TEXT | Primary key `id`; unique `name`; `created_by` references `users.id` with `ON DELETE SET NULL`. |
| `link_tags` | `link_id` TEXT, `tag_id` TEXT | Composite primary key (`link_id`, `tag_id`); both FKs cascade on delete. |
Index: `idx_link_tags_tag_id` supports reverse tag lookups. `idx_tags_created_by` supports creator-based tag management.
### `plugins`
Installed plugin definitions and global plugin configuration. `config` is JSON text.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `name` | TEXT | no | | Unique plugin name. |
| `version` | TEXT | no | | Plugin version. |
| `enabled` | INTEGER | no | `1` | Enablement flag. |
| `config` | TEXT | yes | | Plugin JSON configuration. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
### `user_plugin_config`
Per-user plugin settings. The pair (`user_id`, `plugin_name`) is unique; `plugin_name` is a logical plugin identifier and is not a foreign key to `plugins`.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id`. |
| `plugin_name` | TEXT | no | | Plugin identifier. |
| `config` | TEXT | yes | | User-specific JSON configuration. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
### Verification, reset, and OAuth state tables
These tables store one-time or short-lived workflow state. Token and state values are persisted as hashes where applicable. All user-owned rows are deleted when their user is deleted.
| Table | Important columns | Foreign key / uniqueness |
| --- | --- | --- |
| `email_verification_tokens` | `id`, `user_id`, `token_hash`, `expires_at`, `created_at` | `user_id` -> `users.id` with `ON DELETE CASCADE`; unique `token_hash`. |
| `password_reset_tokens` | `id`, `user_id`, `token_hash`, `expires_at`, `created_at` | `user_id` -> `users.id` with `ON DELETE CASCADE`; unique `token_hash`. |
| `mastodon_oauth_states` | `id`, `user_id`, `state_hash`, `instance`, `client_id`, `client_secret`, `redirect_uri`, `expires_at`, `created_at` | `user_id` -> `users.id` with `ON DELETE CASCADE`; unique `state_hash`. OAuth client secrets are encrypted by the service layer. |
Indexes: `idx_email_verification_tokens_user_id`, `idx_password_reset_tokens_user_id`, and `idx_mastodon_oauth_states_state_hash`.
### `app_settings`
Global key/value settings, including setup and mail configuration. Sensitive values are encrypted by the service layer before storage where required.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `name` | TEXT | no | | Primary key setting name. |
| `value` | TEXT | no | | Setting value. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
### `user_email_addresses`
Verified and pending alternative email addresses. The primary address remains in `users.email`; this table holds additional addresses.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id` with `ON DELETE CASCADE`. |
| `email` | TEXT | no | | Globally unique alternative address. |
| `verified` | INTEGER | no | `0` | Verification flag. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
Index: `idx_user_email_addresses_user_id`.
### `email_address_verification_tokens`
Verification tokens for alternative addresses.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `email_address_id` | TEXT | no | | FK to `user_email_addresses.id` with `ON DELETE CASCADE`. |
| `token_hash` | TEXT | no | | Unique token hash. |
| `expires_at` | TEXT | no | | Expiration timestamp. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
Index: `idx_email_address_verification_tokens_address_id`.
### `otp_recovery_codes`
One-time recovery codes for users with OTP enabled. Only code hashes are stored.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id` with `ON DELETE CASCADE`. |
| `code_hash` | TEXT | no | | Unique recovery-code hash. |
| `used` | INTEGER | no | `0` | Consumption flag. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `used_at` | TEXT | yes | | Consumption timestamp. |
Index: `idx_otp_recovery_codes_user_id`.
### `security_audit_events`
Security-relevant audit events. `actor_id` is nullable so an account deletion does not remove the audit record; it becomes `NULL` through `ON DELETE SET NULL`.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `actor_id` | TEXT | yes | | FK to `users.id`, `ON DELETE SET NULL`. |
| `action` | TEXT | no | | Action name. |
| `target_type` | TEXT | no | | Target entity type. |
| `target_id` | TEXT | yes | | Target identifier. |
| `outcome` | TEXT | no | `success` | Result classification. |
| `details` | TEXT | no | `{}` | JSON text, sanitized by the audit service. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Event timestamp. |
Indexes: `idx_security_audit_events_created_at` and `idx_security_audit_events_actor_id`.
## Migration history
| Version | Change |
| ---: | --- |
| 1 | Creates users, tokens, links, plugins, and per-user plugin configuration. |
| 2 | Adds tags and the link/tag join table. |
| 3 | Normalizes tag names with a leading `#`. |
| 4 | Adds tag ownership through `tags.created_by`. |
| 5 | Adds primary-email verification and its token table. |
| 6 | Adds global application settings. |
| 7 | Adds password-reset tokens. |
| 8 | Adds Mastodon OAuth state. |
| 9-10 | Adds Mastodon publication fields and migrates to a JSON list of post IDs. |
| 11 | Adds OTP secret and enablement fields to users. |
| 12 | Adds alternative email addresses and their verification tokens. |
| 13-14 | Temporarily adds then removes pending primary-email-change state. It is not part of the current schema. |
| 15 | Adds device and token-family fields to tokens. |
| 16 | Adds OTP recovery codes. |
| 17 | Adds security audit events. |
To inspect a live database directly:
```sh
sqlite3 backend/data/linklog.db '.schema'
sqlite3 backend/data/linklog.db 'PRAGMA user_version;'
```
+1
View File
@@ -51,6 +51,7 @@ On Windows PowerShell, activate the environment with:
The SQLite database is created automatically at `backend/data/linklog.db` when the application starts. On a fresh installation, open `/setup` and create the first administrator. No default user accounts are created by the application. The setup page also collects SMTP settings and requires a successful test email before creating the administrator. The SQLite database is created automatically at `backend/data/linklog.db` when the application starts. On a fresh installation, open `/setup` and create the first administrator. No default user accounts are created by the application. The setup page also collects SMTP settings and requires a successful test email before creating the administrator.
The database schema is versioned with SQLite `PRAGMA user_version`. Application startup applies all pending migrations in order, so updating the application does not require deleting an existing database. New schema changes should be added as a new numbered migration in `backend/app/database.py`; existing migration entries must remain unchanged. The database schema is versioned with SQLite `PRAGMA user_version`. Application startup applies all pending migrations in order, so updating the application does not require deleting an existing database. New schema changes should be added as a new numbered migration in `backend/app/database.py`; existing migration entries must remain unchanged.
The current schema, table reference, migration history, and Mermaid ERD are documented in [DATABASE.md](DATABASE.md).
## Run The Backend ## Run The Backend
Activate the virtual environment, then run uvicorn from the repository root: Activate the virtual environment, then run uvicorn from the repository root:
+128 -1
View File
@@ -1,4 +1,4 @@
# Chat Log
### User ### User
The release server fails because its curl does not support `--fail-with-body`. The release server fails because its curl does not support `--fail-with-body`.
@@ -6,6 +6,7 @@ The release server fails because its curl does not support `--fail-with-body`.
### Assistant outcome ### Assistant outcome
Replaced all three `--fail-with-body` uses in the release workflow with portable curl response capture and explicit HTTP status checks. Failed API and asset-upload responses now print their response body before exiting, while older curl versions remain supported. Replaced all three `--fail-with-body` uses in the release workflow with portable curl response capture and explicit HTTP status checks. Failed API and asset-upload responses now print their response body before exiting, while older curl versions remain supported.
#
### User ### User
When posting to Mastodon change the formatting so there is an empty line between “From my #LinkLog:” and the title. When posting to Mastodon change the formatting so there is an empty line between “From my #LinkLog:” and the title.
@@ -1496,3 +1497,129 @@ Release script fails because the runner's hashlib module has no file_digest attr
### Assistant outcome ### Assistant outcome
Replaced Python 3.11-only `hashlib.file_digest` calls in signed-XPI metadata generation and release validation with streaming SHA-256 calculations compatible with older Python runners. Regenerated update metadata and verified release validation passes. Replaced Python 3.11-only `hashlib.file_digest` calls in signed-XPI metadata generation and release validation with streaming SHA-256 calculations compatible with older Python runners. Regenerated update metadata and verified release validation passes.
### User
The filtering on tags does not work. When I click on the button I cannot select. Remember that any visitor on the site should be able to filter the tag for the link-feed.
### Assistant outcome
Traced the unresponsive filter dropdowns to the decorative `.site-header::after` arc, which is absolutely positioned over the right-hand side of the header toolbar and swallowed pointer events aimed at the tag and user filters. Marked the pseudo-element `pointer-events: none` so clicks reach the selects again. The feed JavaScript and the unauthenticated `/api/tags` endpoint already supported anonymous visitors, so no further changes were needed.
### User
Update VIBE and Changelog
### Assistant outcome
Recorded the tag-filter click fix in the v0.2.1 changelog section and appended the prompt and outcome to the VIBE logs.
### User
Create a skill for this project, make sure you capture the VIBE directory update
### Assistant outcome
Added the workspace skill `.github/skills/vibe-logging/SKILL.md`. It documents LinkLog's append-only VIBE workflow, requires paired user-prompt and concise-outcome records after completed visible work, and excludes private instructions and internal tool details. Recorded this request and outcome in both VIBE logs.
## User
In the mastodon post change the line: From:< URL>
to
Logged on <date> from: <url>
Where date format is like: 2026 August 29 - 21:10
### Assistant outcome
Updated the Mastodon post formatter to emit `Logged on 2026 August 29 - 21:10 from: <url>` using the saved link timestamp in UTC, preserving the surrounding title/comment/tag layout and leaving the existing Mastodon posting path unchanged. Verified the targeted Mastodon regression tests pass with `PYTHONPATH=. pytest backend/tests/test_api.py -k mastodon -q`.
### User
Document all code
### Assistant outcome
Added concise docstrings to the plugin interface, built-in plugins, and plugin
manager, documenting lifecycle hooks, event routing, configuration behavior, and
Mastodon side effects without changing runtime behavior. Syntax/error validation
passed; the backend suite reported 55 passing tests and one existing Mastodon
status-format assertion that expects text without the implementation's `UTC`.
### User
Document the sql schema, include an ERD
### Assistant outcome
Added `DATABASE.md` documenting the current SQLite schema at migration version 17, including tables, columns, constraints, indexes, migration history, and a Mermaid ERD. Linked it from the README and verified the focused database tests with `PYTHONPATH=. pytest backend/tests/test_database.py -q` (1 passed).
### User
In the toolbar add a search functionality, which filters the log entries on keywords.
use basic symbols and operators such as with google, and only 'site:' as advanced search operator
### Assistant outcome
Added toolbar search filtering for link title, URL, comment, username, and tags. The query supports implicit AND terms, quoted phrases, `OR`, `-` exclusions, and the `site:` host operator; other advanced operators are treated as ordinary text. Search preferences persist with the existing feed cookie and the rendered-feed regression assertions cover the implementation. JavaScript syntax validation passed; the API suite had 35 passing tests and one unrelated existing Mastodon timestamp assertion expecting text without `UTC`.
### User
In firefox the search input field is wider (at 180px) then labe search control (at 135.5px)
### Assistant outcome
Updated the header toolbar search input to use `width: 100%` with its existing zero minimum width, keeping it inside the flexed search label in Firefox. The focused rendered-feed test passed and `git diff --check` reported no issues.
### User
In the toolbar switch the search and tag filter's location
### Assistant outcome
Swapped the toolbar positions of the Search and Tag filter controls while preserving their existing IDs and behavior. The rendered-page regression passed, the template order was verified as Tag, Sort, User, Search, and `git diff --check` passed.
### User
fix the Mastodon timestamp assertion to expect UTC
### Assistant outcome
Updated the Mastodon posting regression assertion to expect the formatter's explicit `UTC` marker in the `Logged on` timestamp. The targeted test passed with `1 passed, 35 deselected`.
### User
Use the APIs to, In the current runtime (linklog.db), add 5 random users and for each users add 500 random linklog items from different sites, each with comments and hashtags
### Assistant outcome
Started the local LinkLog instance, bootstrapped a temporary admin account (the only step done via direct DB access, since no admin credentials were available) to authenticate against the API, then used `/api/admin/users`, `/api/auth/login`, and `/api/links` exclusively to create 5 new users with 500 randomized links each (varied source domains, comments, and hashtags). Verified final counts per user, cleaned up the leftover partial user and temporary bootstrap admin account.
### User
the current implementation reads the whole feed at once.
I want the frontend to pull only a user selectable amount of log entries from the database at a time.
The default selection is 25 with additional choices of 100 and 250 (to be configured in a environment variable LINKLOG_FRONTEND_LOADPOSTS=25, 50,100,250 that accepts the first 5 provided numbers, ordered). The user can select the next, or previous button or click page 1, 2, 3, ... on the bottom of the current page.
If the user uses the filters and/or search in the toolbox then those should limit the entries the server presents, so the filters and search are applied on the server side.
### Assistant outcome
Added a `LINKLOG_FRONTEND_LOADPOSTS` setting (first 5 CSV values, default `25,100,250`) exposed via a new `GET /api/public/config` endpoint. Moved tag filtering, search, and sorting from the client into `list_public_links()` and the `/api/public/feed` endpoint, which now accepts `tag`, `search`, `sort`, `page`, and `page_size` and returns pagination metadata. Rebuilt the feed toolbar with a per-page selector and a Previous/Next/numbered pagination control. Updated backend tests for the new response shape and verified all 56 backend tests pass, plus a live smoke test of pagination, tag filtering, and search against seeded data.
### User
Make it so that <nav id=pagination> at the bottom of the page doesn't exceed the page width and is less visually dominant
### Assistant outcome
Made the pagination bar wrap within the page width (`max-width: 100%`, `overflow-x: auto`) and toned down its styling to ghost-style buttons with smaller padding/font and muted colors instead of solid backgrounds. Verified the updated CSS is served correctly from a rebuilt local container.
### User
Make sure the CHANGELOG reflects all changes since commit 74b2c400c6
### Assistant outcome
Reviewed the commit log and working-tree diff since `74b2c400c6` and updated the `v0.3.0` section of `CHANGELOG.MD` with the missing user-facing entries: toolbar search, server-side feed pagination, backend-side filtering, the Firefox search-input width fix, the search/tag toolbar reorder, the Mastodon "Logged on <date> from:" UTC timestamp change, and the pagination control's visual/overflow fix. Also fixed an unrelated pre-existing bug in `frontend/version.json` (a missing closing quote made it invalid JSON, silently falling back to version `0.0.0`).
### User
Add a skill to maintain the changelog.md
### Assistant outcome
Added `.github/skills/changelog-maintenance/SKILL.md`, modeled on the existing `vibe-logging` skill, describing when and how to append concise, user-facing bullets to the current unreleased `## Version` section of `CHANGELOG.MD` (Features/Fixed/Modification), when to bump `frontend/version.json`, and which changes are out of scope (internal-only docs, dev scripts, test-only fixes).
### User
In the new-entry form, provide a warning when the total ammount of characters is over LINKLOG_MAX_POST_CHARACTERS=500 (also indicat the number of characters used/500 count). This is to prevent Mastodon posts from failing - so all characters should be counted.
### Assistant outcome
Added a `LINKLOG_MAX_POST_CHARACTERS` setting (default 500) exposed via `GET /api/public/config`. The New Entry page now shows a live `used/limit characters` counter that recalculates on every relevant input (title, URL, comment, tags, checkbox toggles) by assembling the estimated Mastodon post text the same way the backend's Mastodon plugin does, and switches to a warning style when the limit is exceeded. Verified with the full backend test suite (56 passed) and a live smoke test of `/api/public/config` and the rendered New Entry page.
### User
Implement the same functionality in the firefox plugin
### Assistant outcome
Added the same live character-count warning to the Firefox extension popup: it fetches `/api/public/config` for the limit and the user's `/api/user/plugins/mastodon` post prefix, estimates the assembled Mastodon post length the same way as the New Entry page and backend plugin, and shows a localized `used/limit characters` counter (with an over-limit warning message) that updates on every relevant input and tag toggle. Added the `characterCount`/`characterCountOverLimit` translations to all five locale files (en-US, de, es, fr, nl) and verified all locale JSON files parse and `popup.js` passes a Node syntax check.
### User
Make those colors less outstanding, this should not stand out. In fact, give the box a title :profile and make it collapsable
### Assistant outcome
Made the feed profile summary use the normal subdued link-item colors and converted it to a native collapsible `<details>` section titled `:profile`. Template and stylesheet diagnostics passed.
# Chat Log
+55
View File
@@ -1,3 +1,4 @@
258. fix the Mastodon timestamp assertion to expect UTC
# Prompt Log # Prompt Log
## 2026-08-24 ## 2026-08-24
@@ -178,6 +179,11 @@
174. The plugin still does not behave as expected. It still shows that the user should sign in. 174. The plugin still does not behave as expected. It still shows that the user should sign in.
175. In the popup show that the user has logged in. 175. In the popup show that the user has logged in.
176. Address SA-003 by using a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage 176. Address SA-003 by using a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage
## 2026-09-05
177. Document the sql schema, include an ERD
178. In the toolbar add a search functionality, which filters the log entries on keywords. use basic symbols and operators such as with google, and only 'site:' as advanced search operator
177. The popup still shows the sign-in block even though the authenticated session text is displayed; show the block only when signed out. 177. The popup still shows the sign-in block even though the authenticated session text is displayed; show the block only when signed out.
178. The authenticated session text and sign-in block are still shown together. 178. The authenticated session text and sign-in block are still shown together.
179. Use the VIBE directory to log interactions. 179. Use the VIBE directory to log interactions.
@@ -258,6 +264,8 @@
237. On the new-entry page follow the logic for existing pages that already exists in the plugin and display "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered." when the link exists. Also assess if the Auto-fill title button is necessary, or if the functionality can be automated while the URL is entered. 237. On the new-entry page follow the logic for existing pages that already exists in the plugin and display "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered." when the link exists. Also assess if the Auto-fill title button is necessary, or if the functionality can be automated while the URL is entered.
238. Also: detect as duplicate when the URL has arguments (not already stripped). And: add a button to re-fetch the title for if the URL has been fetched but the user still edits the field. 238. Also: detect as duplicate when the URL has arguments (not already stripped). And: add a button to re-fetch the title for if the URL has been fetched but the user still edits the field.
239. If the link already exist with URL arguments then also display the warning, but add that the link has been stored additional parameters. 239. If the link already exist with URL arguments then also display the warning, but add that the link has been stored additional parameters.
240. I want this last change to be more precise: I do not want to be warned when parameters are stripped, but when the URL entered has arguments/parameters and the URL in the database has none or different ones (even after tracking parameters are stripped). 240. I want this last change to be more precise: I do not want to be warned when parameters are stripped, but when the URL entered has arguments/parameters and the URL in the database has none or different ones (even after tracking parameters are stripped).
241. In the check duplicate I have a `<br>` tag, but that shows as formatted text on the page, I want a real break to occur at that position. 241. In the check duplicate I have a `<br>` tag, but that shows as formatted text on the page, I want a real break to occur at that position.
@@ -268,6 +276,53 @@
246. Update changelog and VIBE 246. Update changelog and VIBE
247. Make sure that when the plugin is signed the version in the link it the about page is updated too 247. Make sure that when the plugin is signed the version in the link it the about page is updated too
248. Release script fails because the runner's hashlib module has no file_digest attribute. 248. Release script fails because the runner's hashlib module has no file_digest attribute.
249. The filtering on tags does not work. When I click on the button I cannot select. Remember that any visitor on the site should be able to filter the tag for the link-feed.
250. Update VIBE and Changelog
## 2026-08-30
251. Create a skill for this project, make sure you capture the VIBE directory update
## 2026-08-30
252. In the mastodon post change the line: From:< URL>
to
Logged on <date> from: <url>
Where date format is like: 2026 August 29 - 21:10
## 2026-09-04
253. Document all code
## 2026-09-05
254. In firefox the search input field is wider (at 180px) then labe search control (at 135.5px)
## 2026-09-07
255. Change bg color and slightly decrease the font for 'html body main.container section.link-item.profile-summary' so that it stands out
255. In the toolbar switch the search and tag filter's location
## 2026-09-06
256. Use the APIs to, In the current runtime (linklog.db), add 5 random users and for each users add 500 random linklog items from different sites, each with comments and hashtags
257. the current implementation reads the whole feed at once.
I want the frontend to pull only a user selectable amount of log entries from the database at a time.
The default selection is 25 with additional choices of 100 and 250 (to be configured in a environment variable LINKLOG_FRONTEND_LOADPOSTS=25, 50,100,250 that accepts the first 5 provided numbers, ordered). The user can select the next, or previous button or click page 1, 2, 3, ... on the bottom of the current page.
If the user uses the filters and/or search in the toolbox then those should limit the entries the server presents, so the filters and search are applied on the server side.
258. Make it so that <nav id=pagination> at the bottom of the page doesn't exceed the page width and is less visually dominant
259. Make sure the CHANGELOG reflects all changes since commit 74b2c400c6
260. Add a skill to maintain the changelog.md
261. In the new-entry form, provide a warning when the total ammount of characters is over LINKLOG_MAX_POST_CHARACTERS=500 (also indicat the number of characters used/500 count). This is to prevent Mastodon posts from failing - so all characters should be counted.
262. Implement the same functionality in the firefox plugin
## 2026-09-07
Make those colors less outstanding, this should not stand out. In fact, give the box a title :profile and make it collapsable
## Future entries ## Future entries
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -187,4 +187,4 @@ def post_link_to_mastodon(
@router.get('/links') @router.get('/links')
def list_links(): def list_links():
return list_public_links() return list_public_links()['items']
+32 -4
View File
@@ -1,9 +1,12 @@
## Copyright © 2026 Olaf Kolkman ## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
from fastapi import APIRouter, Depends import math
from fastapi import APIRouter, Depends, Query
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from backend.app.core.config import settings
from backend.app.services.link_service import list_public_links, list_public_users from backend.app.services.link_service import list_public_links, list_public_users
from backend.app.services.token_service import validate_token from backend.app.services.token_service import validate_token
from backend.app.services.theme_service import THEMES, get_enabled_themes from backend.app.services.theme_service import THEMES, get_enabled_themes
@@ -23,10 +26,24 @@ def public_themes():
return [{'id': theme, **THEMES[theme]} for theme in enabled] return [{'id': theme, **THEMES[theme]} for theme in enabled]
@router.get('/config')
def public_config():
return {
'feed_page_sizes': settings.feed_page_sizes,
'default_page_size': settings.feed_page_sizes[0],
'max_post_characters': settings.max_post_characters,
}
@router.get('/feed') @router.get('/feed')
@router.get('/feed/{username}') @router.get('/feed/{username}')
def public_feed( def public_feed(
username: str | None = None, username: str | None = None,
tag: str | None = None,
search: str | None = None,
sort: str = 'newest',
page: int = Query(1, ge=1),
page_size: int | None = Query(None, ge=1),
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer), credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
): ):
current_user_id = None current_user_id = None
@@ -34,8 +51,10 @@ def public_feed(
token_data = validate_token(credentials.credentials) token_data = validate_token(credentials.credentials)
if token_data: if token_data:
current_user_id = token_data['user_id'] current_user_id = token_data['user_id']
items = list_public_links(username) allowed_sizes = settings.feed_page_sizes
return [ effective_page_size = page_size if page_size in allowed_sizes else allowed_sizes[0]
result = list_public_links(username, tag=tag, search=search, sort=sort, page=page, page_size=effective_page_size)
items = [
{ {
'id': item['id'], 'id': item['id'],
'title': item['title'], 'title': item['title'],
@@ -52,5 +71,14 @@ def public_feed(
'created_at': item['created_at'], 'created_at': item['created_at'],
'mastodon_posted': bool(item['mastodon_posted']), 'mastodon_posted': bool(item['mastodon_posted']),
} }
for item in items for item in result['items']
] ]
total = result['total']
total_pages = max(1, math.ceil(total / effective_page_size))
return {
'items': items,
'total': total,
'page': page,
'page_size': effective_page_size,
'total_pages': total_pages,
}
+20
View File
@@ -51,8 +51,10 @@ class Settings:
password_reset_expiry_hours: int = int(os.getenv('LINKLOG_PASSWORD_RESET_EXPIRY_HOURS', '1')) password_reset_expiry_hours: int = int(os.getenv('LINKLOG_PASSWORD_RESET_EXPIRY_HOURS', '1'))
mastodon_client_name: str = os.getenv('LINKLOG_MASTODON_CLIENT_NAME', 'LinkLog') mastodon_client_name: str = os.getenv('LINKLOG_MASTODON_CLIENT_NAME', 'LinkLog')
mastodon_oauth_expiry_minutes: int = int(os.getenv('LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES', '10')) mastodon_oauth_expiry_minutes: int = int(os.getenv('LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES', '10'))
max_post_characters: int = int(os.getenv('LINKLOG_MAX_POST_CHARACTERS', '500'))
log_level: str = os.getenv('LINKLOG_LOG_LEVEL', 'INFO').upper() log_level: str = os.getenv('LINKLOG_LOG_LEVEL', 'INFO').upper()
tracking_params: list[str] = None tracking_params: list[str] = None
feed_page_sizes: list[int] = None
def __post_init__(self): def __post_init__(self):
if self.tracking_params is None: if self.tracking_params is None:
@@ -69,6 +71,24 @@ class Settings:
if configured_params if configured_params
else default_tracking_params else default_tracking_params
) )
if self.feed_page_sizes is None:
default_page_sizes = [25, 100, 250]
configured_sizes = os.getenv('LINKLOG_FRONTEND_LOADPOSTS')
parsed_sizes = []
if configured_sizes:
for item in configured_sizes.split(','):
item = item.strip()
if not item:
continue
try:
value = int(item)
except ValueError:
continue
if value > 0 and value not in parsed_sizes:
parsed_sizes.append(value)
if len(parsed_sizes) == 5:
break
self.feed_page_sizes = parsed_sizes or default_page_sizes
settings = Settings() settings = Settings()
+3 -5
View File
@@ -20,7 +20,7 @@ from backend.app.api.setup import has_administrator
from backend.app.api.user_config import router as user_config_router from backend.app.api.user_config import router as user_config_router
from backend.app.core.config import settings, validate_configuration from backend.app.core.config import settings, validate_configuration
from backend.app.database import AVATARS_DIR from backend.app.database import AVATARS_DIR
from backend.app.services.link_service import get_public_profile, list_public_links from backend.app.services.link_service import get_public_profile
logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO)) logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO))
validate_configuration(settings) validate_configuration(settings)
@@ -53,8 +53,7 @@ templates.env.globals['app_version'] = settings.version
async def public_root(request: Request): async def public_root(request: Request):
if not has_administrator(): if not has_administrator():
return RedirectResponse('/setup') return RedirectResponse('/setup')
feed = list_public_links() return templates.TemplateResponse(request, 'feed.html', {})
return templates.TemplateResponse(request, 'feed.html', {'feed': feed})
@app.get('/admin', response_class=HTMLResponse) @app.get('/admin', response_class=HTMLResponse)
@@ -117,10 +116,9 @@ def health_check():
@app.get('/{username}', response_class=HTMLResponse) @app.get('/{username}', response_class=HTMLResponse)
@app.get('/{username}/', response_class=HTMLResponse) @app.get('/{username}/', response_class=HTMLResponse)
async def public_user_feed(request: Request, username: str): async def public_user_feed(request: Request, username: str):
feed = list_public_links(username)
profile = get_public_profile(username) profile = get_public_profile(username)
return templates.TemplateResponse( return templates.TemplateResponse(
request, request,
'feed.html', 'feed.html',
{'feed': feed, 'profile': profile, 'user_filter': username}, {'profile': profile, 'user_filter': username},
) )
+6
View File
@@ -2,18 +2,24 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
class BasePlugin: class BasePlugin:
"""Define the interface shared by LinkLog event plugins."""
name = 'base' name = 'base'
version = '1.0.0' version = '1.0.0'
enabled = True enabled = True
def initialize(self, config=None): def initialize(self, config=None):
"""Apply plugin configuration and report whether initialization succeeded."""
return True return True
def validate_config(self, config): def validate_config(self, config):
"""Validate configuration and return a ``(valid, message)`` pair."""
return True, 'ok' return True, 'ok'
def handle_event(self, event): def handle_event(self, event):
"""Handle a LinkLog event; subclasses must provide the implementation."""
raise NotImplementedError raise NotImplementedError
def health_check(self): def health_check(self):
"""Return the plugin name and basic health status."""
return {'name': self.name, 'status': 'ok'} return {'name': self.name, 'status': 'ok'}
+77 -5
View File
@@ -3,6 +3,8 @@
from datetime import datetime, timezone from datetime import datetime, timezone
import json import json
import re
from urllib.parse import urlparse
from uuid import uuid4 from uuid import uuid4
from backend.app.core.security import clean_url from backend.app.core.security import clean_url
@@ -136,23 +138,93 @@ def find_owned_link_by_title(user_id: str, title: str) -> dict | None:
return record return record
def list_public_links(username: str | None = None): def _tokenize_search(value: str) -> list[str]:
return [group1 or group2 for group1, group2 in re.findall(r'"([^"]+)"|(\S+)', value or '')]
def _parse_search_query(value: str) -> dict:
groups = [[]]
excluded = []
sites = []
for token in _tokenize_search(value):
if token.upper() == 'OR':
groups.append([])
continue
is_excluded = token.startswith('-') and len(token) > 1
term = token[1:] if is_excluded else token
site_match = re.match(r'^site:(\S+)$', term, re.IGNORECASE)
if site_match and not is_excluded:
sites.append(site_match.group(1).lower())
continue
if is_excluded:
excluded.append(term.lower())
else:
groups[-1].append(term.lower())
return {'groups': [group for group in groups if group], 'excluded': excluded, 'sites': sites}
def _searchable_text(record: dict) -> str:
parts = [record.get('title'), record.get('url'), record.get('comment'), record.get('username'), *(record.get('tags') or [])]
return ' '.join(part for part in parts if part).lower()
def _matches_search(record: dict, query: str) -> bool:
if not query or not query.strip():
return True
parsed = _parse_search_query(query)
text = _searchable_text(record)
def site_matches(site: str) -> bool:
hostname = (urlparse(record.get('url') or '').hostname or '').lower()
return hostname == site or hostname.endswith(f'.{site}')
matches_site = all(site_matches(site) for site in parsed['sites'])
matches_group = not parsed['groups'] or any(all(term in text for term in group) for group in parsed['groups'])
excludes_term = any(term in text for term in parsed['excluded'])
return matches_site and matches_group and not excludes_term
def list_public_links(
username: str | None = None,
tag: str | None = None,
search: str | None = None,
sort: str = 'newest',
page: int = 1,
page_size: int | None = None,
) -> dict:
order = 'ASC' if sort == 'oldest' else 'DESC'
with get_connection() as conn: with get_connection() as conn:
rows = conn.execute( rows = conn.execute(
''' f'''
SELECT links.*, users.username, users.avatar_url, users.bio SELECT links.*, users.username, users.avatar_url, users.bio
FROM links FROM links
JOIN users ON users.id = links.user_id JOIN users ON users.id = links.user_id
WHERE links.is_public = 1 WHERE links.is_public = 1
AND (? IS NULL OR users.username = ?) AND (? IS NULL OR users.username = ?)
ORDER BY created_at DESC AND (
? IS NULL OR links.id IN (
SELECT link_tags.link_id FROM link_tags
JOIN tags ON tags.id = link_tags.tag_id
WHERE lower(tags.name) = lower(?)
)
)
ORDER BY links.created_at {order}
''', ''',
(username, username), (username, username, tag, tag),
).fetchall() ).fetchall()
records = [dict(row) for row in rows] records = [dict(row) for row in rows]
for record in records: for record in records:
record['tags'] = get_link_tags(conn, record['id']) record['tags'] = get_link_tags(conn, record['id'])
return records
if search:
records = [record for record in records if _matches_search(record, search)]
total = len(records)
if page_size:
start = max(page - 1, 0) * page_size
records = records[start:start + page_size]
return {'items': records, 'total': total}
def get_public_profile(username: str) -> dict | None: def get_public_profile(username: str) -> dict | None:
+34 -1
View File
@@ -3,6 +3,7 @@
import json import json
import logging import logging
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.request import Request from urllib.request import Request
@@ -16,24 +17,36 @@ logger = logging.getLogger(__name__)
class DefaultFrontendPlugin(BasePlugin): class DefaultFrontendPlugin(BasePlugin):
"""Accept events for the built-in frontend plugin."""
name = 'default_frontend' name = 'default_frontend'
version = '1.0.0' version = '1.0.0'
def handle_event(self, event): def handle_event(self, event):
"""Acknowledge an event without performing an external side effect."""
return {'status': 'accepted', 'plugin': self.name, 'event': event.get('type')} return {'status': 'accepted', 'plugin': self.name, 'event': event.get('type')}
class MastodonPlugin(BasePlugin): class MastodonPlugin(BasePlugin):
"""Publish and remove LinkLog entries through a Mastodon instance."""
name = 'mastodon' name = 'mastodon'
version = '1.0.0' version = '1.0.0'
enabled = False enabled = False
config = {} config = {}
def initialize(self, config=None): def initialize(self, config=None):
"""Store the administrator-provided defaults for later event handling."""
self.config = config or {} self.config = config or {}
return True return True
def handle_event(self, event): def handle_event(self, event):
"""Publish a link event, returning a structured status result.
Per-user plugin settings override global settings. The access token is
decrypted only for the duration of the outbound request, and the
instance is validated before any network connection is opened.
"""
if not event.get('post_to_mastodon', True): if not event.get('post_to_mastodon', True):
return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_requested'} return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_requested'}
@@ -77,7 +90,19 @@ class MastodonPlugin(BasePlugin):
if event.get('comment'): if event.get('comment'):
status_parts.append(event['comment']) status_parts.append(event['comment'])
if title: if title:
status_parts.append(f'from: {event.get("url", "")}') timestamp_value = event.get('timestamp') or event.get('created_at')
url = str(event.get('url', '') or '').strip()
if timestamp_value:
try:
parsed = datetime.fromisoformat(str(timestamp_value).replace('Z', '+00:00'))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
formatted = parsed.astimezone(timezone.utc).strftime('%Y %B %d - %H:%M')
status_parts.append(f'Logged on {formatted} UTC from: {url}')
except ValueError:
status_parts.append(f'Logged from: {url}')
else:
status_parts.append(f'Logged from: {url}')
if event.get('tags'): if event.get('tags'):
status_parts.append(' '.join(event['tags'])) status_parts.append(' '.join(event['tags']))
post_body = '\n\n'.join(status_parts) post_body = '\n\n'.join(status_parts)
@@ -132,6 +157,7 @@ class MastodonPlugin(BasePlugin):
} }
def delete_posts(self, event): def delete_posts(self, event):
"""Delete all Mastodon statuses recorded for a link event."""
config = dict(self.config) config = dict(self.config)
user_id = event.get('user_id') user_id = event.get('user_id')
if user_id: if user_id:
@@ -175,10 +201,14 @@ class MastodonPlugin(BasePlugin):
class PluginManager: class PluginManager:
"""Load enabled plugins and route LinkLog events to them."""
def __init__(self): def __init__(self):
"""Create the built-in plugin registry."""
self.plugins = [DefaultFrontendPlugin(), MastodonPlugin()] self.plugins = [DefaultFrontendPlugin(), MastodonPlugin()]
def refresh_from_db(self): def refresh_from_db(self):
"""Refresh enabled flags and configuration from the plugin table."""
from backend.app.database import get_connection from backend.app.database import get_connection
with get_connection() as conn: with get_connection() as conn:
@@ -192,6 +222,7 @@ class PluginManager:
return enabled_names return enabled_names
def dispatch(self, event): def dispatch(self, event):
"""Send an event to every currently enabled plugin."""
self.refresh_from_db() self.refresh_from_db()
results = [] results = []
for plugin in self.plugins: for plugin in self.plugins:
@@ -202,6 +233,7 @@ class PluginManager:
return results return results
def post_to_mastodon(self, event): def post_to_mastodon(self, event):
"""Publish one event through Mastodon when that plugin is enabled."""
self.refresh_from_db() self.refresh_from_db()
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon') plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
if not plugin.enabled: if not plugin.enabled:
@@ -209,6 +241,7 @@ class PluginManager:
return plugin.handle_event(event) return plugin.handle_event(event)
def delete_mastodon_posts(self, event): def delete_mastodon_posts(self, event):
"""Delete the Mastodon statuses associated with an event."""
self.refresh_from_db() self.refresh_from_db()
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon') plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
return plugin.delete_posts(event) return plugin.delete_posts(event)
+2
View File
@@ -11,6 +11,8 @@ TEST_DATABASE_DIRECTORY = tempfile.TemporaryDirectory(prefix='linklog-tests-')
TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db') TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db')
os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH
os.environ['LINKLOG_DATA_ENCRYPTION_KEY'] = 'L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV=' os.environ['LINKLOG_DATA_ENCRYPTION_KEY'] = 'L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV='
# Use a large page size so existing tests that expect the full feed keep working.
os.environ['LINKLOG_FRONTEND_LOADPOSTS'] = '1000'
@pytest.fixture(scope='session', autouse=True) @pytest.fixture(scope='session', autouse=True)
+16 -12
View File
@@ -607,7 +607,7 @@ def test_submit_link_stores_cleaned_url_and_public_feed():
data = response.json() data = response.json()
assert data['url'] == 'https://example.com/path?keep=yes' assert data['url'] == 'https://example.com/path?keep=yes'
feed = client.get('/api/public/feed').json() feed = client.get('/api/public/feed').json()['items']
matching = next(item for item in feed if item['id'] == data['id']) matching = next(item for item in feed if item['id'] == data['id'])
assert matching['comment'] == 'Interesting read' assert matching['comment'] == 'Interesting read'
assert matching['user']['username'] == 'alice' assert matching['user']['username'] == 'alice'
@@ -615,8 +615,8 @@ def test_submit_link_stores_cleaned_url_and_public_feed():
filtered_response = client.get('/api/public/feed/alice') filtered_response = client.get('/api/public/feed/alice')
assert filtered_response.status_code == 200 assert filtered_response.status_code == 200
assert all(item['user']['username'] == 'alice' for item in filtered_response.json()) assert all(item['user']['username'] == 'alice' for item in filtered_response.json()['items'])
assert client.get('/api/public/feed/does-not-exist').json() == [] assert client.get('/api/public/feed/does-not-exist').json()['items'] == []
users_response = client.get('/api/public/users') users_response = client.get('/api/public/users')
assert users_response.status_code == 200 assert users_response.status_code == 200
assert 'alice' in users_response.json() assert 'alice' in users_response.json()
@@ -645,7 +645,7 @@ def test_duplicate_link_updates_comment_tags_and_retriggers_plugins():
dispatch.assert_called_once() dispatch.assert_called_once()
assert dispatch.call_args.args[0]['comment'] == 'updated comment' assert dispatch.call_args.args[0]['comment'] == 'updated comment'
assert dispatch.call_args.args[0]['tags'] == ['#Second'] assert dispatch.call_args.args[0]['tags'] == ['#Second']
feed_item = next(item for item in client.get('/api/public/feed').json() if item['id'] == first.json()['id']) feed_item = next(item for item in client.get('/api/public/feed').json()['items'] if item['id'] == first.json()['id'])
assert feed_item['comment'] == 'updated comment' assert feed_item['comment'] == 'updated comment'
assert feed_item['tags'] == ['#Second'] assert feed_item['tags'] == ['#Second']
@@ -689,7 +689,7 @@ def test_links_support_tags_and_tag_filtering():
assert { assert {
'#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI' '#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI'
} <= set(tags) } <= set(tags)
tagged_feed = client.get('/api/public/feed').json() tagged_feed = client.get('/api/public/feed').json()['items']
tagged_item = next(item for item in tagged_feed if item['id'] == link_id) tagged_item = next(item for item in tagged_feed if item['id'] == link_id)
assert {tag.casefold() for tag in tagged_item['tags']} == {'#casepreserved', '#web'} assert {tag.casefold() for tag in tagged_item['tags']} == {'#casepreserved', '#web'}
@@ -725,12 +725,12 @@ def test_only_link_owner_can_edit_link():
}) })
assert unauthenticated.status_code == 401 assert unauthenticated.status_code == 401
anonymous_feed = client.get('/api/public/feed').json() anonymous_feed = client.get('/api/public/feed').json()['items']
anonymous_link = next(item for item in anonymous_feed if item['id'] == link_id) anonymous_link = next(item for item in anonymous_feed if item['id'] == link_id)
assert anonymous_link['is_owner'] is False assert anonymous_link['is_owner'] is False
assert anonymous_link['can_edit'] is False assert anonymous_link['can_edit'] is False
owner_feed = client.get('/api/public/feed', headers=owner_headers).json() owner_feed = client.get('/api/public/feed', headers=owner_headers).json()['items']
owner_link = next(item for item in owner_feed if item['id'] == link_id) owner_link = next(item for item in owner_feed if item['id'] == link_id)
assert owner_link['is_owner'] is True assert owner_link['is_owner'] is True
assert owner_link['can_edit'] is True assert owner_link['can_edit'] is True
@@ -786,6 +786,7 @@ def test_public_and_admin_pages_render_html():
assert 'id="auth-profile-link" class="hidden"' in root_page.text assert 'id="auth-profile-link" class="hidden"' in root_page.text
assert 'id="auth-admin-link" class="hidden"' in root_page.text assert 'id="auth-admin-link" class="hidden"' in root_page.text
assert '<select id="tag-filter">' in root_page.text assert '<select id="tag-filter">' in root_page.text
assert '<input id="search-input" type="search"' in root_page.text
assert root_page.text.index('class="site-logo"') < root_page.text.index('<section class="toolbar">') assert root_page.text.index('class="site-logo"') < root_page.text.index('<section class="toolbar">')
assert 'logout.js?v=3' in root_page.text assert 'logout.js?v=3' in root_page.text
assert client.get('/alice').status_code == 200 assert client.get('/alice').status_code == 200
@@ -829,12 +830,14 @@ def test_public_and_admin_pages_render_html():
assert 'class="panel-toggle-btn"' in profile_page assert 'class="panel-toggle-btn"' in profile_page
assert 'profile.js?v=6' in profile_page assert 'profile.js?v=6' in profile_page
feed_script = client.get('/static/feed.js?v=7').text feed_script = client.get('/static/feed.js?v=7').text
assert 'function loadFeed()' in feed_script
assert 'function renderPagination(page, totalPages)' in feed_script
assert 'if (item.is_owner && !showIdentity)' in feed_script assert 'if (item.is_owner && !showIdentity)' in feed_script
assert 'deleteEntry(item, deleteButton)' in feed_script assert 'deleteEntry(item, deleteButton)' in feed_script
assert 'postToMastodon(item, mastodonButton)' in feed_script assert 'postToMastodon(item, mastodonButton)' in feed_script
assert 'tag.toLowerCase() === activeTag.toLowerCase()' in feed_script assert "params.set('tag', pref.tag)" in feed_script
assert 'loadFeed(event.target.value)' in feed_script assert 'currentPage = 1' in feed_script
assert 'Promise.all([loadUsers(), loadTags()]).then(() => loadFeed())' in feed_script assert "Promise.all([loadUsers(), loadTags()])" in feed_script
assert "fetch('/api/tags', {" in feed_script assert "fetch('/api/tags', {" in feed_script
assert 'Authorization: `Bearer ${accessToken}`' in feed_script assert 'Authorization: `Bearer ${accessToken}`' in feed_script
assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script
@@ -885,6 +888,7 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
'title': 'A useful page', 'title': 'A useful page',
'url': 'https://example.com/useful', 'url': 'https://example.com/useful',
'comment': 'Worth sharing', 'comment': 'Worth sharing',
'timestamp': '2026-08-29T21:10:00Z',
'tags': ['#python', '#web'], 'tags': ['#python', '#web'],
}) })
@@ -892,8 +896,8 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
assert received['path'] == '/api/v1/statuses' assert received['path'] == '/api/v1/statuses'
assert received['authorization'] == 'Bearer test-token' assert received['authorization'] == 'Bearer test-token'
assert received['content_type'] == 'application/x-www-form-urlencoded' assert received['content_type'] == 'application/x-www-form-urlencoded'
assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']} assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\nLogged on 2026 August 29 - 21:10 UTC from: https://example.com/useful\n\n#python #web']}
posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json() if item['id'] == response.json()['id']) posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json()['items'] if item['id'] == response.json()['id'])
assert posted_item['mastodon_posted'] is True assert posted_item['mastodon_posted'] is True
finally: finally:
server.shutdown() server.shutdown()
+94 -22
View File
@@ -5,10 +5,15 @@ const feedEl = document.getElementById('feed');
const sortSelect = document.getElementById('sort-select'); const sortSelect = document.getElementById('sort-select');
const userFilter = document.getElementById('user-filter'); const userFilter = document.getElementById('user-filter');
const tagFilter = document.getElementById('tag-filter'); const tagFilter = document.getElementById('tag-filter');
const searchInput = document.getElementById('search-input');
const pageSizeSelect = document.getElementById('page-size-select');
const paginationEl = document.getElementById('pagination');
const cookieName = 'linklog-feed-preferences'; const cookieName = 'linklog-feed-preferences';
const accessToken = localStorage.getItem('linklogAccessToken'); const accessToken = localStorage.getItem('linklogAccessToken');
let availableTags = []; let availableTags = [];
let pageSizes = [25, 100, 250];
let currentPage = 1;
function createAvatar(user) { function createAvatar(user) {
const avatar = document.createElement('div'); const avatar = document.createElement('div');
@@ -63,6 +68,17 @@ function formatDate(value) {
return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`; return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`;
} }
async function loadConfig() {
const response = await fetch('/api/public/config');
if (!response.ok) throw new Error('Could not load config');
const config = await response.json();
pageSizes = config.feed_page_sizes?.length ? config.feed_page_sizes : pageSizes;
const pref = readPreferences();
const selected = pageSizes.includes(pref.pageSize) ? pref.pageSize : pageSizes[0];
pageSizeSelect.replaceChildren(...pageSizes.map((size) => new Option(`${size} per page`, String(size))));
pageSizeSelect.value = String(selected);
}
async function loadUsers() { async function loadUsers() {
const response = await fetch('/api/public/users'); const response = await fetch('/api/public/users');
if (!response.ok) throw new Error('Could not load users'); if (!response.ok) throw new Error('Could not load users');
@@ -172,6 +188,43 @@ function renderFeed(items, showIdentity = true) {
}); });
} }
function renderPagination(page, totalPages) {
paginationEl.innerHTML = '';
if (totalPages <= 1) return;
const goToPage = (target) => {
currentPage = Math.min(Math.max(target, 1), totalPages);
loadFeed();
};
const makeButton = (label, target, options = {}) => {
const button = document.createElement('button');
button.type = 'button';
button.textContent = label;
if (options.active) button.classList.add('active');
if (options.disabled) button.disabled = true;
button.addEventListener('click', () => goToPage(target));
return button;
};
paginationEl.appendChild(makeButton('Previous', page - 1, {disabled: page <= 1}));
const pageNumbers = new Set([1, totalPages, page, page - 1, page + 1]);
let previous = null;
[...pageNumbers].filter((num) => num >= 1 && num <= totalPages).sort((a, b) => a - b).forEach((num) => {
if (previous !== null && num - previous > 1) {
const ellipsis = document.createElement('span');
ellipsis.className = 'pagination-ellipsis';
ellipsis.textContent = '…';
paginationEl.appendChild(ellipsis);
}
paginationEl.appendChild(makeButton(String(num), num, {active: num === page}));
previous = num;
});
paginationEl.appendChild(makeButton('Next', page + 1, {disabled: page >= totalPages}));
}
async function postToMastodon(item, button) { async function postToMastodon(item, button) {
button.disabled = true; button.disabled = true;
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}/mastodon`, { const response = await fetch(`/api/links/${encodeURIComponent(item.id)}/mastodon`, {
@@ -256,33 +309,30 @@ function showEditForm(article, item) {
article.appendChild(form); article.appendChild(form);
} }
async function loadFeed(selectedTag = null) { async function loadFeed() {
const routeUser = document.body.dataset.userFilter; const routeUser = document.body.dataset.userFilter;
const endpoint = routeUser const pref = readPreferences();
const pageSize = pageSizes.includes(pref.pageSize) ? pref.pageSize : pageSizes[0];
const params = new URLSearchParams();
if (pref.tag) params.set('tag', pref.tag);
if (pref.search) params.set('search', pref.search);
params.set('sort', pref.sort || 'newest');
params.set('page', String(currentPage));
params.set('page_size', String(pageSize));
if (pref.user && !routeUser) params.set('username', pref.user);
const path = routeUser
? `/api/public/feed/${encodeURIComponent(routeUser)}` ? `/api/public/feed/${encodeURIComponent(routeUser)}`
: '/api/public/feed'; : '/api/public/feed';
const response = await fetch(endpoint, { const response = await fetch(`${path}?${params.toString()}`, {
headers: accessToken ? {Authorization: `Bearer ${accessToken}`} : {}, headers: accessToken ? {Authorization: `Bearer ${accessToken}`} : {},
}); });
const data = await response.json(); const data = await response.json();
let items = data || []; currentPage = data.page || 1;
const pref = readPreferences(); renderFeed(data.items || [], !routeUser);
const activeTag = selectedTag ?? pref.tag; renderPagination(currentPage, data.total_pages || 1);
if (pref.user && !routeUser) {
items = items.filter((item) => (item.user?.username || '').toLowerCase() === pref.user.toLowerCase());
}
if (activeTag) {
items = items.filter((item) => item.tags?.some((tag) => tag.toLowerCase() === activeTag.toLowerCase()));
}
if (pref.sort === 'oldest') {
items = [...items].reverse();
}
renderFeed(items, !routeUser);
} }
function syncPreferences() { function syncPreferences() {
@@ -290,10 +340,12 @@ function syncPreferences() {
sortSelect.value = pref.sort; sortSelect.value = pref.sort;
userFilter.value = pref.user; userFilter.value = pref.user;
tagFilter.value = pref.tag || ''; tagFilter.value = pref.tag || '';
searchInput.value = pref.search || '';
sortSelect.addEventListener('change', (event) => { sortSelect.addEventListener('change', (event) => {
const next = { ...readPreferences(), sort: event.target.value }; const next = { ...readPreferences(), sort: event.target.value };
writePreferences(next); writePreferences(next);
currentPage = 1;
loadFeed(); loadFeed();
}); });
@@ -307,9 +359,29 @@ function syncPreferences() {
tagFilter.addEventListener('change', (event) => { tagFilter.addEventListener('change', (event) => {
const next = { ...readPreferences(), tag: event.target.value }; const next = { ...readPreferences(), tag: event.target.value };
writePreferences(next); writePreferences(next);
loadFeed(event.target.value); currentPage = 1;
loadFeed();
});
let searchDebounce;
searchInput.addEventListener('input', (event) => {
const next = { ...readPreferences(), search: event.target.value };
writePreferences(next);
currentPage = 1;
clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => loadFeed(), 300);
});
pageSizeSelect.addEventListener('change', (event) => {
const next = { ...readPreferences(), pageSize: Number(event.target.value) };
writePreferences(next);
currentPage = 1;
loadFeed();
}); });
} }
syncPreferences(); syncPreferences();
Promise.all([loadUsers(), loadTags()]).then(() => loadFeed()).catch(() => loadFeed()); loadConfig()
.then(() => Promise.all([loadUsers(), loadTags()]))
.then(() => loadFeed())
.catch(() => loadFeed());
+69 -11
View File
@@ -16,11 +16,14 @@
const refetchTitleButton = document.getElementById('refetch-title-button'); const refetchTitleButton = document.getElementById('refetch-title-button');
const submitButton = document.getElementById('submit-button'); const submitButton = document.getElementById('submit-button');
const submitStatus = document.getElementById('submit-status'); const submitStatus = document.getElementById('submit-status');
const characterCount = document.getElementById('character-count');
const token = localStorage.getItem('linklogAccessToken'); const token = localStorage.getItem('linklogAccessToken');
let availableTags = []; let availableTags = [];
let selectedTags = new Set(); let selectedTags = new Set();
let currentUser = null; let currentUser = null;
let maxPostCharacters = 500;
let mastodonPostPrefix = 'From my #LinkLog: ';
// Utility function to add status messages; splits on \n into real <br> line breaks without using innerHTML. // Utility function to add status messages; splits on \n into real <br> line breaks without using innerHTML.
function setStatus(statusEl, message, isError = false) { function setStatus(statusEl, message, isError = false) {
@@ -53,7 +56,7 @@
.then((user) => { .then((user) => {
currentUser = user; currentUser = user;
entryForm.classList.remove('hidden'); entryForm.classList.remove('hidden');
Promise.all([loadTags(), loadMastodonPublishing()]); Promise.all([loadTags(), loadMastodonPublishing(), loadConfig()]).then(updateCharacterCount);
}) })
.catch(() => { .catch(() => {
localStorage.removeItem('linklogAccessToken'); localStorage.removeItem('linklogAccessToken');
@@ -61,6 +64,17 @@
entryForm.classList.add('hidden'); entryForm.classList.add('hidden');
}); });
async function loadConfig() {
try {
const response = await fetch('/api/public/config');
if (!response.ok) throw new Error('Could not load config');
const config = await response.json();
if (config.max_post_characters) maxPostCharacters = config.max_post_characters;
} catch (error) {
console.error('Could not load config:', error);
}
}
// Load available tags // Load available tags
async function loadTags() { async function loadTags() {
try { try {
@@ -82,11 +96,63 @@
const config = await response.json(); const config = await response.json();
mastodonEnabledCheckbox.checked = Boolean(config.configured); mastodonEnabledCheckbox.checked = Boolean(config.configured);
mastodonPublishing.classList.toggle('hidden', !config.configured); mastodonPublishing.classList.toggle('hidden', !config.configured);
if (config.post_prefix) {
mastodonPostPrefix = config.post_prefix;
} else if (config.hashtag) {
mastodonPostPrefix = `#${String(config.hashtag).trim().replace(/^#/, '')} `;
}
} catch (error) { } catch (error) {
console.error('Could not load Mastodon configuration:', error); console.error('Could not load Mastodon configuration:', error);
} }
} }
// Collect the selected checkbox tags plus any typed new tags, mirroring the submit-time logic.
function collectTags() {
const tags = Array.from(selectedTags);
const newTags = newTagsInput.value.trim();
if (newTags) {
tags.push(...newTags.split(',').map((t) => t.trim()).filter(Boolean));
}
return tags;
}
// Format a UTC timestamp the same way the Mastodon plugin does, so the estimated post length matches the server.
function formatMastodonTimestamp(date) {
const months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
const pad = (value) => String(value).padStart(2, '0');
return `${date.getUTCFullYear()} ${months[date.getUTCMonth()]} ${pad(date.getUTCDate())} - ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}`;
}
// Estimate the assembled Mastodon post length, mirroring backend/app/services/plugin_manager.py.
function estimatePostLength() {
const title = titleInput.value.trim();
const comment = commentInput.value.trim();
const url = removeKnownTrackingParams(urlInput.value.trim());
const parts = [mastodonPostPrefix.trim()];
if (title) parts.push(title);
if (comment) parts.push(comment);
if (title) parts.push(`Logged on ${formatMastodonTimestamp(new Date())} UTC from: ${url}`);
const tags = collectTags();
if (tags.length) parts.push(tags.join(' '));
return parts.join('\n\n').length;
}
function updateCharacterCount() {
const length = estimatePostLength();
const overLimit = length > maxPostCharacters;
characterCount.textContent = overLimit
? `${length}/${maxPostCharacters} characters - exceeds the Mastodon post limit by ${length - maxPostCharacters}`
: `${length}/${maxPostCharacters} characters`;
characterCount.classList.toggle('over-limit', overLimit);
}
[urlInput, titleInput, commentInput, newTagsInput].forEach((input) => {
input.addEventListener('input', updateCharacterCount);
});
// Render tag checkboxes // Render tag checkboxes
function renderTags() { function renderTags() {
existingTagsEl.innerHTML = ''; existingTagsEl.innerHTML = '';
@@ -104,6 +170,7 @@
} else { } else {
selectedTags.delete(tag); selectedTags.delete(tag);
} }
updateCharacterCount();
}); });
label.appendChild(checkbox); label.appendChild(checkbox);
@@ -224,22 +291,13 @@
const url = removeKnownTrackingParams(urlInput.value.trim()); const url = removeKnownTrackingParams(urlInput.value.trim());
const title = titleInput.value.trim(); const title = titleInput.value.trim();
const comment = commentInput.value.trim(); const comment = commentInput.value.trim();
const newTags = newTagsInput.value.trim();
if (!url || !title) { if (!url || !title) {
setStatus(submitStatus, 'URL and title are required', true); setStatus(submitStatus, 'URL and title are required', true);
return; return;
} }
// Combine selected tags and new tags const tags = collectTags();
const tags = Array.from(selectedTags);
if (newTags) {
const newTagsList = newTags
.split(',')
.map((t) => t.trim())
.filter((t) => t);
tags.push(...newTagsList);
}
submitButton.disabled = true; submitButton.disabled = true;
setStatus(submitStatus, 'Saving...', false); setStatus(submitStatus, 'Saving...', false);
+92
View File
@@ -154,6 +154,8 @@ body::selection {
border-radius: 50%; border-radius: 50%;
content: ''; content: '';
transform: rotate(-12deg); transform: rotate(-12deg);
/* decorative only: must not swallow clicks on the toolbar selects underneath */
pointer-events: none;
} }
.site-header h1, .site-header h1,
@@ -219,11 +221,21 @@ body::selection {
font-size: 0.68rem; font-size: 0.68rem;
} }
.header-tools .toolbar .search-control {
flex-basis: 180px;
}
.header-tools .toolbar select { .header-tools .toolbar select {
min-width: 0; min-width: 0;
padding: 6px 8px; padding: 6px 8px;
} }
.header-tools .toolbar input {
width: 100%;
min-width: 0;
padding: 6px 8px;
}
.header-actions { .header-actions {
display: flex; display: flex;
flex: 0 0 auto; flex: 0 0 auto;
@@ -835,6 +847,11 @@ button:disabled {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
} }
.edit-form textarea {
width: 100%;
}
.edit-tags { .edit-tags {
display: grid; display: grid;
gap: 8px; gap: 8px;
@@ -874,6 +891,53 @@ button:disabled {
padding-bottom: 40px; padding-bottom: 40px;
} }
.pagination {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 4px;
max-width: 100%;
margin: 0 0 40px;
overflow-x: auto;
}
.pagination button {
min-width: 28px;
padding: 3px 7px;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.4;
cursor: pointer;
}
.pagination button:hover:not(:disabled) {
border-color: var(--border);
color: var(--text);
}
.pagination button:disabled {
opacity: 0.4;
cursor: default;
}
.pagination button.active {
background: var(--surface-1);
color: var(--text);
border-color: var(--border);
font-weight: 600;
}
.pagination .pagination-ellipsis {
padding: 3px 2px;
color: var(--muted);
font-size: 0.82rem;
opacity: 0.6;
}
.link-item { .link-item {
padding: 11px; padding: 11px;
background: var(--surface-0); background: var(--surface-0);
@@ -882,6 +946,21 @@ button:disabled {
box-shadow: var(--shadow); box-shadow: var(--shadow);
} }
.profile-summary summary {
color: var(--subtext);
cursor: pointer;
font-size: 0.9rem;
font-weight: 600;
}
.profile-summary[open] summary {
margin-bottom: 8px;
}
.profile-summary-content {
font-size: 0.95rem;
}
.about-content { .about-content {
display: grid; display: grid;
gap: 14px; gap: 14px;
@@ -948,6 +1027,7 @@ button:disabled {
.profile-summary p { .profile-summary p {
margin: 12px 0 0; margin: 12px 0 0;
color: var(--subtext); color: var(--subtext);
font-size: 0.95rem;
line-height: 1.65; line-height: 1.65;
} }
@@ -1183,6 +1263,18 @@ button:disabled {
display: none; display: none;
} }
.char-count {
margin: -8px 0 0;
color: var(--muted);
font-size: 0.82rem;
text-align: right;
}
.char-count.over-limit {
color: var(--red);
font-weight: 600;
}
@media (max-width: 600px) { @media (max-width: 600px) {
.container { .container {
padding: 0 14px; padding: 0 14px;
+1 -1
View File
@@ -60,7 +60,7 @@
<section class="link-item"> <section class="link-item">
<h2>Plugin</h2> <h2>Plugin</h2>
<p>Install the Firefox plugin to save links directly from your browser. <a <p>Install the Firefox plugin to save links directly from your browser. <a
href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.2.0.xpi" href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.3.0.xpi"
download>Download and install the Plugin</a>.</p> download>Download and install the Plugin</a>.</p>
</section> </section>
</main> </main>
+19 -7
View File
@@ -38,6 +38,12 @@
</nav> </nav>
</div> </div>
<section class="toolbar"> <section class="toolbar">
<label>
Tag filter
<select id="tag-filter">
<option value="">All tags</option>
</select>
</label>
<label> <label>
Sort Sort
<select id="sort-select"> <select id="sort-select">
@@ -52,10 +58,12 @@
</select> </select>
</label> </label>
<label> <label>
Tag filter Per page
<select id="tag-filter"> <select id="page-size-select"></select>
<option value="">All tags</option> </label>
</select> <label class="search-control">
Search
<input id="search-input" type="search" placeholder="Search links" autocomplete="off" aria-label="Search links" />
</label> </label>
</section> </section>
</div> </div>
@@ -65,7 +73,9 @@
<main class="container"> <main class="container">
{% if profile %} {% if profile %}
<section class="link-item profile-summary"> <details class="link-item profile-summary">
<summary>Profile</summary>
<div class="profile-summary-content">
<div class="link-header"> <div class="link-header">
<div class="avatar"> <div class="avatar">
{% if profile.avatar_url %} {% if profile.avatar_url %}
@@ -77,15 +87,17 @@
<div class="user-name">{{ profile.username }}</div> <div class="user-name">{{ profile.username }}</div>
</div> </div>
<p>{{ profile.bio or 'No profile information provided.' }}</p> <p>{{ profile.bio or 'No profile information provided.' }}</p>
</section> </div>
</details>
{% endif %} {% endif %}
<section id="feed" class="feed" aria-live="polite"></section> <section id="feed" class="feed" aria-live="polite"></section>
<nav id="pagination" class="pagination" aria-label="Feed pages"></nav>
</main> </main>
<footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=3"></script> <script src="/static/logout.js?v=3"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/feed.js?v=12"></script> <script src="/static/feed.js?v=14"></script>
</body> </body>
</html> </html>
+3 -1
View File
@@ -71,6 +71,7 @@
<textarea id="comment-input" name="comment" rows="4" placeholder="Optional comment about this link"></textarea> <textarea id="comment-input" name="comment" rows="4" placeholder="Optional comment about this link"></textarea>
</label> </label>
</div> </div>
<div id="character-count" class="char-count" aria-live="polite">0/500 characters</div>
<fieldset class="form-section"> <fieldset class="form-section">
<legend>Tags</legend> <legend>Tags</legend>
@@ -89,6 +90,7 @@
</label> </label>
</fieldset> </fieldset>
<div class="form-actions"> <div class="form-actions">
<button id="submit-button" type="submit">Save Entry</button> <button id="submit-button" type="submit">Save Entry</button>
<a href="/" class="secondary button">Cancel</a> <a href="/" class="secondary button">Cancel</a>
@@ -103,6 +105,6 @@
</footer> </footer>
<script src="/static/auth-header.js"></script> <script src="/static/auth-header.js"></script>
<script src="/static/new-entry.js?v=8"></script> <script src="/static/new-entry.js?v=9"></script>
</body> </body>
</html> </html>
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"version": "0.2.0" "version": "0.3.0"
} }
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
"""One-off script: seed the running LinkLog API with random users and links.
Uses the HTTP API exclusively for user/link creation. The only direct
database access is flipping `email_verified` for freshly created accounts,
since there is no mailbox available in this environment to click the real
verification link that the API would otherwise send.
"""
import random
import string
import subprocess
import sys
from datetime import datetime, timedelta, timezone
import requests
BASE_URL = 'http://localhost:5469'
ADMIN_EMAIL = 'bootstrap_admin@example.invalid'
ADMIN_PASSWORD = 'Bootstrap-Admin-Pass1!'
CONTAINER_NAME = 'testlog-app'
NUM_USERS = 5
LINKS_PER_USER = 500
FIRST_NAMES = ['ava', 'liam', 'noah', 'emma', 'olivia', 'mia', 'ethan', 'sofia', 'lucas', 'zoe']
SITES = [
('https://news.ycombinator.com', 'Hacker News'),
('https://www.theguardian.com', 'The Guardian'),
('https://arstechnica.com', 'Ars Technica'),
('https://www.wired.com', 'Wired'),
('https://github.com', 'GitHub'),
('https://www.nature.com', 'Nature'),
('https://www.bbc.com', 'BBC'),
('https://techcrunch.com', 'TechCrunch'),
('https://www.nytimes.com', 'NY Times'),
('https://www.reddit.com', 'Reddit'),
('https://stackoverflow.com', 'Stack Overflow'),
('https://www.smithsonianmag.com', 'Smithsonian'),
('https://www.economist.com', 'The Economist'),
('https://www.nationalgeographic.com', 'Nat Geo'),
('https://www.theverge.com', 'The Verge'),
]
PATH_WORDS = ['article', 'story', 'post', 'thread', 'blog', 'notes', 'guide', 'review', 'update', 'deep-dive']
HASHTAG_POOL = ['#tech', '#science', '#news', '#opensource', '#ai', '#climate', '#music',
'#photography', '#food', '#travel', '#fediverse', '#security', '#culture', '#space']
COMMENT_TEMPLATES = [
"Interesting take on {topic}.",
"Worth a read if you're into {topic}.",
"Not sure I agree with this on {topic}, but good points.",
"Bookmarking this for later - {topic}.",
"Great deep dive into {topic}.",
"", # some links have no comment
]
session = requests.Session()
def rand_suffix(n=6):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=n))
def create_bootstrap_admin_if_needed():
resp = session.post(f'{BASE_URL}/api/auth/login', json={'email': ADMIN_EMAIL, 'password': ADMIN_PASSWORD})
if resp.status_code == 200:
return resp.json()['access_token']
raise RuntimeError(f'Bootstrap admin login failed: {resp.status_code} {resp.text}')
def mark_email_verified(user_id: str):
code = (
"from backend.app.database import get_connection\n"
f"with get_connection() as conn:\n"
f" conn.execute('UPDATE users SET email_verified = 1 WHERE id = ?', ('{user_id}',))\n"
" conn.commit()\n"
)
subprocess.run(
['docker', 'exec', '-w', '/app', CONTAINER_NAME, 'python3', '-c', code],
check=True, capture_output=True, text=True,
)
def create_user(admin_token: str, index: int) -> dict:
name = f'{random.choice(FIRST_NAMES)}{index}_{rand_suffix()}'
email = f'{name}@example-seed.invalid'
password = f'Passw0rd-{rand_suffix(8)}!'
resp = session.post(
f'{BASE_URL}/api/admin/users',
headers={'Authorization': f'Bearer {admin_token}'},
json={'username': name, 'email': email, 'password': password, 'is_admin': False},
)
if resp.status_code == 201:
user = resp.json()
elif resp.status_code == 503:
# User row was created but the verification email failed to send (no SMTP egress here).
list_resp = session.get(f'{BASE_URL}/api/admin/users', headers={'Authorization': f'Bearer {admin_token}'})
list_resp.raise_for_status()
user = next(u for u in list_resp.json() if u['username'] == name)
else:
raise RuntimeError(f'Failed to create user {name}: {resp.status_code} {resp.text}')
mark_email_verified(user['id'])
return {'id': user['id'], 'username': name, 'email': email, 'password': password}
def login_user(email: str, password: str) -> str:
resp = session.post(f'{BASE_URL}/api/auth/login', json={'email': email, 'password': password})
resp.raise_for_status()
return resp.json()['access_token']
def random_link_payload():
base_url, site_name = random.choice(SITES)
url = f'{base_url}/{random.choice(PATH_WORDS)}/{rand_suffix(8)}'
title = f'{site_name}: {random.choice(PATH_WORDS).replace("-", " ").title()} #{random.randint(1000, 9999)}'
topic = random.choice(HASHTAG_POOL).lstrip('#')
comment = random.choice(COMMENT_TEMPLATES).format(topic=topic)
tags = random.sample(HASHTAG_POOL, k=random.randint(1, 4))
timestamp = (datetime.now(timezone.utc) - timedelta(days=random.randint(0, 730),
seconds=random.randint(0, 86400))).isoformat()
return {
'title': title,
'url': url,
'comment': comment,
'tags': tags,
'timestamp': timestamp,
'post_to_mastodon': False,
}
def create_links_for_user(token: str, username: str, count: int):
headers = {'Authorization': f'Bearer {token}'}
created = 0
for i in range(count):
payload = random_link_payload()
resp = session.post(f'{BASE_URL}/api/links', headers=headers, json=payload)
if resp.status_code == 401:
# access token expired mid-run; caller handles refresh via re-login
raise PermissionError('token_expired')
if resp.status_code not in (200, 201):
print(f' ! link {i} failed for {username}: {resp.status_code} {resp.text[:200]}', file=sys.stderr)
continue
created += 1
if created % 100 == 0:
print(f' {username}: {created}/{count} links created')
return created
def main():
print('Logging in as bootstrap admin...')
admin_token = create_bootstrap_admin_if_needed()
users = []
print(f'Creating {NUM_USERS} users...')
for i in range(1, NUM_USERS + 1):
user = create_user(admin_token, i)
users.append(user)
print(f' created user: {user["username"]} <{user["email"]}>')
for user in users:
print(f'Seeding {LINKS_PER_USER} links for {user["username"]}...')
token = login_user(user['email'], user['password'])
try:
total = create_links_for_user(token, user['username'], LINKS_PER_USER)
except PermissionError:
print(f' token expired, re-logging in for {user["username"]}')
token = login_user(user['email'], user['password'])
total = create_links_for_user(token, user['username'], LINKS_PER_USER)
print(f' done: {total}/{LINKS_PER_USER} links created for {user["username"]}')
print('\nSummary:')
for user in users:
print(f' {user["username"]} / {user["email"]} / password: {user["password"]}')
if __name__ == '__main__':
main()
+3 -1
View File
@@ -53,5 +53,7 @@
"loginFailed": {"message": "Anmeldung fehlgeschlagen"}, "loginFailed": {"message": "Anmeldung fehlgeschlagen"},
"loggedInSuccessfully": {"message": "Erfolgreich angemeldet"}, "loggedInSuccessfully": {"message": "Erfolgreich angemeldet"},
"unableToLogIn": {"message": "Anmeldung nicht möglich. Überprüfe Backend-URL und Zugangsdaten."}, "unableToLogIn": {"message": "Anmeldung nicht möglich. Überprüfe Backend-URL und Zugangsdaten."},
"signedOut": {"message": "Abgemeldet"} "signedOut": {"message": "Abgemeldet"},
"characterCount": {"message": "$USED$/$LIMIT$ Zeichen", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ Zeichen - überschreitet das Mastodon-Beitragslimit um $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
} }
+25
View File
@@ -181,5 +181,30 @@
}, },
"signedOut": { "signedOut": {
"message": "Signed out" "message": "Signed out"
},
"characterCount": {
"message": "$USED$/$LIMIT$ characters",
"placeholders": {
"used": {
"content": "$1"
},
"limit": {
"content": "$2"
}
}
},
"characterCountOverLimit": {
"message": "$USED$/$LIMIT$ characters - exceeds the Mastodon post limit by $OVER$",
"placeholders": {
"used": {
"content": "$1"
},
"limit": {
"content": "$2"
},
"over": {
"content": "$3"
}
}
} }
} }
+3 -1
View File
@@ -53,5 +53,7 @@
"loginFailed": {"message": "Error de inicio de sesión"}, "loginFailed": {"message": "Error de inicio de sesión"},
"loggedInSuccessfully": {"message": "Sesión iniciada correctamente"}, "loggedInSuccessfully": {"message": "Sesión iniciada correctamente"},
"unableToLogIn": {"message": "No se pudo iniciar sesión. Comprueba la URL y las credenciales."}, "unableToLogIn": {"message": "No se pudo iniciar sesión. Comprueba la URL y las credenciales."},
"signedOut": {"message": "Sesión cerrada"} "signedOut": {"message": "Sesión cerrada"},
"characterCount": {"message": "$USED$/$LIMIT$ caracteres", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ caracteres: supera el límite de publicación de Mastodon en $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
} }
+3 -1
View File
@@ -53,5 +53,7 @@
"loginFailed": {"message": "Échec de la connexion"}, "loginFailed": {"message": "Échec de la connexion"},
"loggedInSuccessfully": {"message": "Connexion réussie"}, "loggedInSuccessfully": {"message": "Connexion réussie"},
"unableToLogIn": {"message": "Connexion impossible. Vérifiez lURL du serveur et vos identifiants."}, "unableToLogIn": {"message": "Connexion impossible. Vérifiez lURL du serveur et vos identifiants."},
"signedOut": {"message": "Déconnecté"} "signedOut": {"message": "Déconnecté"},
"characterCount": {"message": "$USED$/$LIMIT$ caractères", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ caractères : dépasse la limite de publication Mastodon de $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
} }
+3 -1
View File
@@ -53,5 +53,7 @@
"loginFailed": {"message": "Inloggen mislukt"}, "loginFailed": {"message": "Inloggen mislukt"},
"loggedInSuccessfully": {"message": "Succesvol ingelogd"}, "loggedInSuccessfully": {"message": "Succesvol ingelogd"},
"unableToLogIn": {"message": "Inloggen mislukt. Controleer de backend-URL en inloggegevens."}, "unableToLogIn": {"message": "Inloggen mislukt. Controleer de backend-URL en inloggegevens."},
"signedOut": {"message": "Uitgelogd"} "signedOut": {"message": "Uitgelogd"},
"characterCount": {"message": "$USED$/$LIMIT$ tekens", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ tekens - overschrijdt de Mastodon-postlimiet met $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
} }
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"name": "__MSG_extensionName__", "name": "__MSG_extensionName__",
"version": "0.2.0", "version": "0.3.0",
"description": "__MSG_extensionDescription__", "description": "__MSG_extensionDescription__",
"default_locale": "en-US", "default_locale": "en-US",
"permissions": [ "permissions": [
+12
View File
@@ -149,6 +149,18 @@ button {
color: #f38ba8; color: #f38ba8;
} }
.char-count {
margin: -6px 0 10px;
color: #a6adc8;
font-size: 0.75rem;
text-align: right;
}
.char-count.over-limit {
color: #f38ba8;
font-weight: 600;
}
.auth-session { .auth-session {
margin-bottom: 10px; margin-bottom: 10px;
border: 1px solid #585b70; border: 1px solid #585b70;
+1
View File
@@ -37,6 +37,7 @@
<span data-i18n="commentLabel">Comment</span> <span data-i18n="commentLabel">Comment</span>
<textarea id="comment" name="comment" rows="3" data-i18n-placeholder="commentPlaceholder" placeholder="Your comment"></textarea> <textarea id="comment" name="comment" rows="3" data-i18n-placeholder="commentPlaceholder" placeholder="Your comment"></textarea>
</label> </label>
<div id="character-count" class="char-count" aria-live="polite"></div>
<fieldset> <fieldset>
<legend data-i18n="tagsLabel">Tags</legend> <legend data-i18n="tagsLabel">Tags</legend>
+82 -1
View File
@@ -14,10 +14,14 @@ const authWarning = document.getElementById('auth-warning');
const warningSettingsButton = document.getElementById('warning-settings'); const warningSettingsButton = document.getElementById('warning-settings');
const authSession = document.getElementById('auth-session'); const authSession = document.getElementById('auth-session');
const refetchTitleButton = document.getElementById('refetch-title'); const refetchTitleButton = document.getElementById('refetch-title');
const characterCountEl = document.getElementById('character-count');
const sessionStore = browser.storage.session; const sessionStore = browser.storage.session;
const t = window.linklogI18n; const t = window.linklogI18n;
let maxPostCharacters = 500;
let mastodonPostPrefix = 'From my #LinkLog: ';
function normalizeBackendOrigin(backendUrl) { function normalizeBackendOrigin(backendUrl) {
try { try {
const url = new URL(backendUrl); const url = new URL(backendUrl);
@@ -192,9 +196,11 @@ async function loadExistingTags() {
const checkbox = document.createElement('input'); const checkbox = document.createElement('input');
checkbox.type = 'checkbox'; checkbox.type = 'checkbox';
checkbox.value = tag; checkbox.value = tag;
checkbox.addEventListener('change', updateCharacterCount);
label.append(checkbox, document.createTextNode(` ${tag}`)); label.append(checkbox, document.createTextNode(` ${tag}`));
return label; return label;
})); }));
updateCharacterCount();
} }
function getTags() { function getTags() {
@@ -203,6 +209,79 @@ function getTags() {
return [...new Set([...selected, ...newTags])].slice(0, 10); return [...new Set([...selected, ...newTags])].slice(0, 10);
} }
// Load public app settings (e.g. the Mastodon post length limit) once a backend is configured.
async function loadConfig() {
const settings = await getSettings();
if (!settings.backendUrl || !(await hasBackendPermission(settings.backendUrl))) return;
try {
const response = await fetch(`${settings.backendUrl}/api/public/config`);
if (!response.ok) return;
const config = await response.json();
if (config.max_post_characters) maxPostCharacters = config.max_post_characters;
} catch (error) {
// Character-count warning is advisory; ignore config load failures.
}
updateCharacterCount();
}
// Load the user's configured Mastodon post prefix, so the estimated post length matches the server.
async function loadMastodonPrefix() {
const settings = await getSettings();
if (!settings.backendUrl || !settings.accessToken || !(await hasBackendPermission(settings.backendUrl))) return;
try {
const response = await fetch(`${settings.backendUrl}/api/user/plugins/mastodon`, {
headers: {'Authorization': `Bearer ${settings.accessToken}`},
});
if (!response.ok) return;
const config = await response.json();
if (config.post_prefix) {
mastodonPostPrefix = config.post_prefix;
} else if (config.hashtag) {
mastodonPostPrefix = `#${String(config.hashtag).trim().replace(/^#/, '')} `;
}
} catch (error) {
// Character-count warning is advisory; ignore config load failures.
}
updateCharacterCount();
}
// Format a UTC timestamp the same way the Mastodon plugin does, so the estimated post length matches the server.
function formatMastodonTimestamp(date) {
const months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
const pad = (value) => String(value).padStart(2, '0');
return `${date.getUTCFullYear()} ${months[date.getUTCMonth()]} ${pad(date.getUTCDate())} - ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}`;
}
// Estimate the assembled Mastodon post length, mirroring backend/app/services/plugin_manager.py.
function estimatePostLength() {
const title = titleInput.value.trim();
const comment = commentInput.value.trim();
const url = removeKnownTrackingParams(urlInput.value.trim());
const parts = [mastodonPostPrefix.trim()];
if (title) parts.push(title);
if (comment) parts.push(comment);
if (title) parts.push(`Logged on ${formatMastodonTimestamp(new Date())} UTC from: ${url}`);
const tags = getTags();
if (tags.length) parts.push(tags.join(' '));
return parts.join('\n\n').length;
}
function updateCharacterCount() {
const length = estimatePostLength();
const overLimit = length > maxPostCharacters;
characterCountEl.textContent = overLimit
? t('characterCountOverLimit', [String(length), String(maxPostCharacters), String(length - maxPostCharacters)])
: t('characterCount', [String(length), String(maxPostCharacters)]);
characterCountEl.classList.toggle('over-limit', overLimit);
}
[titleInput, urlInput, commentInput, newTagsInput].forEach((input) => {
input.addEventListener('input', updateCharacterCount);
});
function removeKnownTrackingParams(urlString) { function removeKnownTrackingParams(urlString) {
try { try {
const url = new URL(urlString); const url = new URL(urlString);
@@ -361,6 +440,8 @@ refetchTitleButton.addEventListener('click', (e) => {
titleInput.value = ''; titleInput.value = '';
fetchTitle(url, { force: true }); fetchTitle(url, { force: true });
}); });
populateCurrentTab().then(checkExistingLink); populateCurrentTab().then(checkExistingLink).then(updateCharacterCount);
loadExistingTags(); loadExistingTags();
updateFeedLink(); updateFeedLink();
loadConfig();
loadMastodonPrefix();
+10
View File
@@ -2,6 +2,16 @@
"addons": { "addons": {
"linklog@kolkman.org": { "linklog@kolkman.org": {
"updates": [ "updates": [
{
"version": "0.3.0",
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.3.0.xpi",
"update_hash": "sha256:c4cc16a7e96885caa759c803dca90dd43fdf0befc43457655f6eeb6fd51a4e7f",
"applications": {
"gecko": {
"strict_min_version": "142.0"
}
}
},
{ {
"version": "0.2.0", "version": "0.2.0",
"update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.2.0.xpi", "update_link": "https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.2.0.xpi",