mirror of
https://github.com/rommapp/romm.git
synced 2026-12-06 07:54:18 +01:00
Merge pull request #4748 from rommapp/claude/audit-log
feat(audit): record what users do and show it in Logs › Events
This commit is contained in:
105 files changed
+7897
-628
No files matched your search
@@ -0,0 +1,93 @@
|
||||
"""Add the audit_events table
|
||||
|
||||
One row per thing a user, or RomM itself, did: plays, downloads, library and
|
||||
collection changes, scans, tasks, sign-ins and account changes. Admins read it
|
||||
as the audit log.
|
||||
|
||||
Revision ID: 0132_audit_events
|
||||
Revises: 0131_notification_channels
|
||||
Create Date: 2026-09-24 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op # type: ignore[attr-defined]
|
||||
|
||||
from utils.database import CustomJSON
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0132_audit_events"
|
||||
down_revision = "0131_notification_channels"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"audit_events",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column(
|
||||
"occurred_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.text("now()"),
|
||||
),
|
||||
sa.Column("actor_kind", sa.String(length=16), nullable=False),
|
||||
sa.Column("actor_id", sa.Integer(), nullable=True),
|
||||
sa.Column("actor_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("action", sa.String(length=64), nullable=False),
|
||||
sa.Column("target_type", sa.String(length=32), nullable=True),
|
||||
sa.Column("target_id", sa.String(length=255), nullable=True),
|
||||
sa.Column("target_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("ip_address", sa.String(length=45), nullable=True),
|
||||
sa.Column("device_id", sa.String(length=255), nullable=True),
|
||||
sa.Column("data", CustomJSON(), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.text("now()"),
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.text("now()"),
|
||||
),
|
||||
sa.ForeignKeyConstraint(["actor_id"], ["users.id"], ondelete="SET NULL"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
if_not_exists=True,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_audit_events_occurred_at",
|
||||
"audit_events",
|
||||
["occurred_at"],
|
||||
unique=False,
|
||||
if_not_exists=True,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_audit_events_actor_occurred",
|
||||
"audit_events",
|
||||
["actor_id", "occurred_at"],
|
||||
unique=False,
|
||||
if_not_exists=True,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_audit_events_target",
|
||||
"audit_events",
|
||||
["target_type", "target_id", "occurred_at"],
|
||||
unique=False,
|
||||
if_not_exists=True,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_audit_events_action_occurred",
|
||||
"audit_events",
|
||||
["action", "occurred_at"],
|
||||
unique=False,
|
||||
if_not_exists=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# The indexes back the foreign key, so they go with the table.
|
||||
op.drop_table("audit_events", if_exists=True)
|
||||
@@ -310,6 +310,12 @@ SCHEDULED_BUILD_RECOMMENDATIONS_CRON: Final[str] = _get_env(
|
||||
"30 5 * * *", # At 5:30 AM every day, after the nightly scan and metadata tasks
|
||||
)
|
||||
|
||||
# AUDIT LOG
|
||||
# Days an audit event is kept; 0 keeps every event.
|
||||
AUDIT_LOG_RETENTION_DAYS: Final[int] = safe_int(
|
||||
_get_env("AUDIT_LOG_RETENTION_DAYS"), 90
|
||||
)
|
||||
|
||||
# SYNC
|
||||
SYNC_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/sync"
|
||||
ENABLE_SYNC_FOLDER_WATCHER: Final[bool] = safe_str_to_bool(
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Query, Request
|
||||
from fastapi_pagination import resolve_params
|
||||
from fastapi_pagination.limit_offset import LimitOffsetParams
|
||||
from pydantic import BaseModel
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.audit_event import AuditEventSchema
|
||||
from endpoints.responses.base import TypedLimitOffsetPage
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_audit_event_handler
|
||||
from handler.database.audit_events_handler import AuditEventFilters
|
||||
from models.audit_event import AuditCategory
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(prefix="/audit-events", tags=["audit"])
|
||||
|
||||
|
||||
class AuditLimitOffsetParams(LimitOffsetParams):
|
||||
limit: int = Query(50, ge=1, le=200, description="Page size limit")
|
||||
offset: int = Query(0, ge=0, description="Page offset")
|
||||
|
||||
|
||||
class AuditPage[T: BaseModel](TypedLimitOffsetPage[T]):
|
||||
__params_type__ = AuditLimitOffsetParams
|
||||
|
||||
# Rows are ordered by when they happened, not by id, so later pages pin to
|
||||
# the highest id rather than to the first row's.
|
||||
max_id: int | None = None
|
||||
|
||||
|
||||
@protected_route(router.get, "", [Scope.ME_READ])
|
||||
def get_audit_events(
|
||||
request: Request,
|
||||
actor_id: Annotated[
|
||||
list[int] | None,
|
||||
Query(
|
||||
description="Only these users' events; ignored unless the caller is an admin."
|
||||
),
|
||||
] = None,
|
||||
action: Annotated[
|
||||
list[str] | None, Query(description="Only these actions.")
|
||||
] = None,
|
||||
category: Annotated[
|
||||
list[AuditCategory] | None, Query(description="Only actions in these groups.")
|
||||
] = None,
|
||||
target_type: Annotated[str | None, Query()] = None,
|
||||
target_id: Annotated[str | None, Query()] = None,
|
||||
since: Annotated[datetime | None, Query(description="Inclusive.")] = None,
|
||||
until: Annotated[datetime | None, Query(description="Exclusive.")] = None,
|
||||
search: Annotated[
|
||||
str | None,
|
||||
Query(description="Substring match on the actor, target name or IP address."),
|
||||
] = None,
|
||||
max_id: Annotated[
|
||||
int | None,
|
||||
Query(description="Pins later pages to the events the first one saw."),
|
||||
] = None,
|
||||
) -> AuditPage[AuditEventSchema]:
|
||||
"""The audit log, newest first: everyone's for an admin, the caller's own otherwise."""
|
||||
perms = get_permissions(request)
|
||||
params: AuditLimitOffsetParams = resolve_params()
|
||||
|
||||
# An admin's token scoped below users.read must not read other users' history.
|
||||
sees_everyone = perms.is_admin and Scope.USERS_READ in request.auth.scopes
|
||||
|
||||
rows, total, highest_id = db_audit_event_handler.get_events(
|
||||
AuditEventFilters(
|
||||
actor_ids=(actor_id or None) if sees_everyone else [request.user.id],
|
||||
actions=action or None,
|
||||
categories=category,
|
||||
target_type=target_type,
|
||||
target_id=target_id,
|
||||
since=since,
|
||||
until=until,
|
||||
max_id=max_id,
|
||||
search=search,
|
||||
hidden_rom_ids=frozenset() if perms.is_admin else perms.hidden_rom_ids,
|
||||
hidden_platform_ids=(
|
||||
frozenset() if perms.is_admin else perms.hidden_platform_ids
|
||||
),
|
||||
),
|
||||
limit=params.limit,
|
||||
offset=params.offset,
|
||||
)
|
||||
return AuditPage.create(
|
||||
[AuditEventSchema.from_row(event, device_name) for event, device_name in rows],
|
||||
params,
|
||||
total=total,
|
||||
max_id=highest_id,
|
||||
)
|
||||
+102
-3
@@ -1,5 +1,5 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated, Optional
|
||||
from typing import Annotated, Final, Literal, Optional
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import BackgroundTasks, Body, Depends, HTTPException, Request, status
|
||||
@@ -23,11 +23,22 @@ from exceptions.auth_exceptions import (
|
||||
OIDCNotConfiguredException,
|
||||
UserDisabledException,
|
||||
)
|
||||
from handler.audit_handler import (
|
||||
AuditActor,
|
||||
AuditTarget,
|
||||
claim_once,
|
||||
client_ip,
|
||||
record,
|
||||
release_claim,
|
||||
within_budget,
|
||||
)
|
||||
from handler.auth import auth_handler, oauth_handler, oidc_handler
|
||||
from handler.database import db_user_handler
|
||||
from logger.formatter import CYAN
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.user import User
|
||||
from utils.auth import create_or_find_web_device
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -36,6 +47,71 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
# Failed sign-ins from one address for one username within this window are one attempt.
|
||||
LOGIN_FAILURE_WINDOW_SECONDS: Final = 60
|
||||
# At most this many failed sign-ins are recorded per address each window, so a
|
||||
# client cycling usernames can't flood the log.
|
||||
LOGIN_FAILURES_PER_ADDRESS: Final = 20
|
||||
LOGIN_FAILURE_ADDRESS_WINDOW_SECONDS: Final = 10 * 60
|
||||
# Repeated reset requests for one user from one address are one request.
|
||||
PASSWORD_RESET_REQUEST_WINDOW_SECONDS: Final = 10 * 60
|
||||
|
||||
LoginMethod = Literal["password", "token", "oidc"]
|
||||
|
||||
|
||||
def _record_login(
|
||||
request: Request, user: User, method: LoginMethod, device_id: str | None = None
|
||||
) -> None:
|
||||
record(
|
||||
AuditAction.AUTH_LOGIN,
|
||||
AuditActor.for_user(user, ip_address=client_ip(request), device_id=device_id),
|
||||
data={"method": method},
|
||||
)
|
||||
|
||||
|
||||
def _record_login_failure(
|
||||
request: Request,
|
||||
username: str | None,
|
||||
method: LoginMethod,
|
||||
reason: Literal["credentials", "disabled"],
|
||||
) -> None:
|
||||
ip_address = client_ip(request)
|
||||
key = f"login_failed:{ip_address}:{username}"
|
||||
if not claim_once(key, LOGIN_FAILURE_WINDOW_SECONDS) or not within_budget(
|
||||
f"login_failed:{ip_address}",
|
||||
LOGIN_FAILURES_PER_ADDRESS,
|
||||
LOGIN_FAILURE_ADDRESS_WINDOW_SECONDS,
|
||||
):
|
||||
return
|
||||
user = db_user_handler.get_user_by_username(username) if username else None
|
||||
# A name that matches no account may be a password typed in the wrong box,
|
||||
# so only an account's own name is kept.
|
||||
if not record(
|
||||
AuditAction.AUTH_LOGIN_FAILED,
|
||||
(
|
||||
AuditActor.for_user(user, ip_address=ip_address)
|
||||
if user
|
||||
else AuditActor.anonymous(ip_address)
|
||||
),
|
||||
data={
|
||||
"username": user.username if user else None,
|
||||
"method": method,
|
||||
"reason": reason,
|
||||
},
|
||||
):
|
||||
release_claim(key)
|
||||
|
||||
|
||||
def _record_password_reset_request(ip_address: str | None, user: User) -> None:
|
||||
key = f"password_reset:{ip_address}:{user.id}"
|
||||
if claim_once(key, PASSWORD_RESET_REQUEST_WINDOW_SECONDS) and not record(
|
||||
AuditAction.AUTH_PASSWORD_RESET_REQUEST,
|
||||
AuditActor.anonymous(ip_address),
|
||||
AuditTarget.of_user(user),
|
||||
):
|
||||
release_claim(key)
|
||||
|
||||
|
||||
# Session authentication endpoints
|
||||
@router.post("/login")
|
||||
def login(
|
||||
@@ -55,9 +131,11 @@ def login(
|
||||
|
||||
user = auth_handler.authenticate_user(credentials.username, credentials.password)
|
||||
if not user:
|
||||
_record_login_failure(request, credentials.username, "password", "credentials")
|
||||
raise AuthCredentialsException
|
||||
|
||||
if not user.enabled:
|
||||
_record_login_failure(request, credentials.username, "password", "disabled")
|
||||
raise UserDisabledException
|
||||
|
||||
request.session["iss"] = "romm:auth"
|
||||
@@ -70,6 +148,7 @@ def login(
|
||||
# Update last login and active times
|
||||
now = datetime.now(timezone.utc)
|
||||
db_user_handler.update_user(user.id, {"last_login": now, "last_active": now})
|
||||
_record_login(request, user, "password", device.id)
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_200_OK)
|
||||
@@ -107,7 +186,9 @@ async def logout(request: Request) -> Optional[OIDCLogoutResponse]:
|
||||
|
||||
|
||||
@router.post("/token")
|
||||
async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResponse:
|
||||
async def token(
|
||||
request: Request, form_data: Annotated[OAuth2RequestForm, Depends()]
|
||||
) -> TokenResponse:
|
||||
"""OAuth2 token endpoint
|
||||
|
||||
Args:
|
||||
@@ -181,12 +262,14 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp
|
||||
|
||||
user = auth_handler.authenticate_user(form_data.username, form_data.password)
|
||||
if not user:
|
||||
_record_login_failure(request, form_data.username, "token", "credentials")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password",
|
||||
)
|
||||
|
||||
if not user.enabled:
|
||||
_record_login_failure(request, form_data.username, "token", "disabled")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="User account is disabled"
|
||||
)
|
||||
@@ -229,6 +312,7 @@ async def token(form_data: Annotated[OAuth2RequestForm, Depends()]) -> TokenResp
|
||||
},
|
||||
expires_delta=timedelta(seconds=OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS),
|
||||
)
|
||||
_record_login(request, user, "token")
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
@@ -293,9 +377,11 @@ async def auth_openid(request: Request):
|
||||
)
|
||||
|
||||
if not potential_user:
|
||||
_record_login_failure(request, None, "oidc", "credentials")
|
||||
raise AuthCredentialsException
|
||||
|
||||
if not potential_user.enabled:
|
||||
_record_login_failure(request, potential_user.username, "oidc", "disabled")
|
||||
raise UserDisabledException
|
||||
|
||||
request.session["iss"] = "romm:auth"
|
||||
@@ -312,13 +398,16 @@ async def auth_openid(request: Request):
|
||||
db_user_handler.update_user(
|
||||
potential_user.id, {"last_login": now, "last_active": now}
|
||||
)
|
||||
_record_login(request, potential_user, "oidc", device.id)
|
||||
|
||||
return RedirectResponse(url="/")
|
||||
|
||||
|
||||
@router.post("/forgot-password", status_code=status.HTTP_200_OK)
|
||||
def request_password_reset(
|
||||
background_tasks: BackgroundTasks, username: str = Body(..., embed=True)
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
username: str = Body(..., embed=True),
|
||||
) -> None:
|
||||
"""Request a password reset link for the user.
|
||||
|
||||
@@ -331,6 +420,10 @@ def request_password_reset(
|
||||
|
||||
if user:
|
||||
# After the response, so its timing can't tell whether the user exists.
|
||||
# The record goes first: a link that fails to send stops the tasks after it.
|
||||
background_tasks.add_task(
|
||||
_record_password_reset_request, client_ip(request), user
|
||||
)
|
||||
background_tasks.add_task(auth_handler.send_password_reset_link, user)
|
||||
else:
|
||||
log.warning(
|
||||
@@ -340,6 +433,7 @@ def request_password_reset(
|
||||
|
||||
@router.post("/reset-password", status_code=status.HTTP_200_OK)
|
||||
async def reset_password(
|
||||
request: Request,
|
||||
token: str = Body(..., embed=True),
|
||||
new_password: str = Body(..., embed=True),
|
||||
) -> None:
|
||||
@@ -355,6 +449,11 @@ async def reset_password(
|
||||
user = auth_handler.verify_password_reset_token(token)
|
||||
|
||||
await auth_handler.set_user_new_password(user, new_password)
|
||||
record(
|
||||
AuditAction.AUTH_PASSWORD_RESET,
|
||||
AuditActor.for_user(user, ip_address=client_ip(request)),
|
||||
AuditTarget.of_user(user),
|
||||
)
|
||||
|
||||
log.info(
|
||||
f"Password was successfully reset for user {hl(user.username, color=CYAN)}."
|
||||
|
||||
@@ -10,10 +10,12 @@ from endpoints.responses.client_token import (
|
||||
ClientTokenPairSchema,
|
||||
ClientTokenSchema,
|
||||
)
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_client_token_handler
|
||||
from handler.redis_handler import sync_cache
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from models.client_token import ClientToken
|
||||
from utils.client_tokens import (
|
||||
PAIR_CODE_TTL_SECONDS,
|
||||
@@ -45,6 +47,15 @@ class ClientTokenExchangePayload(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
def _record_token(request: Request, action: AuditAction, token: ClientToken) -> None:
|
||||
record(
|
||||
action,
|
||||
request,
|
||||
AuditTarget(AuditTargetType.CLIENT_TOKEN, token.id, token.name),
|
||||
{"owner_id": token.user_id, "scopes": token.scopes.split()},
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.ME_WRITE], status_code=status.HTTP_201_CREATED)
|
||||
def create_token(
|
||||
request: Request,
|
||||
@@ -72,6 +83,7 @@ def create_token(
|
||||
expires_at=expires_at,
|
||||
)
|
||||
token = db_client_token_handler.add_token(token)
|
||||
_record_token(request, AuditAction.CLIENT_TOKEN_CREATE, token)
|
||||
return build_create_schema(token, raw_token)
|
||||
|
||||
|
||||
@@ -83,14 +95,18 @@ def list_tokens(request: Request) -> list[ClientTokenSchema]:
|
||||
|
||||
@protected_route(router.delete, "/{token_id}", [Scope.ME_WRITE])
|
||||
def delete_token(request: Request, token_id: int) -> None:
|
||||
token = db_client_token_handler.get_token(
|
||||
token_id=token_id, user_id=request.user.id
|
||||
)
|
||||
rows = db_client_token_handler.delete_token(
|
||||
token_id=token_id, user_id=request.user.id
|
||||
)
|
||||
if rows == 0:
|
||||
if rows == 0 or token is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Token not found",
|
||||
)
|
||||
_record_token(request, AuditAction.CLIENT_TOKEN_REVOKE, token)
|
||||
|
||||
|
||||
@protected_route(router.put, "/{token_id}/regenerate", [Scope.ME_WRITE])
|
||||
@@ -108,6 +124,7 @@ def regenerate_token(request: Request, token_id: int) -> ClientTokenCreateSchema
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Token not found",
|
||||
)
|
||||
_record_token(request, AuditAction.CLIENT_TOKEN_REGENERATE, token)
|
||||
return build_create_schema(token, raw_token)
|
||||
|
||||
|
||||
@@ -159,9 +176,11 @@ def list_all_tokens(request: Request) -> list[ClientTokenAdminSchema]:
|
||||
|
||||
@protected_route(router.delete, "/{token_id}/admin", [Scope.USERS_WRITE])
|
||||
def admin_delete_token(request: Request, token_id: int) -> None:
|
||||
token = db_client_token_handler.get_token(token_id=token_id)
|
||||
rows = db_client_token_handler.delete_token(token_id=token_id)
|
||||
if rows == 0:
|
||||
if rows == 0 or token is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Token not found",
|
||||
)
|
||||
_record_token(request, AuditAction.CLIENT_TOKEN_REVOKE, token)
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from typing import Annotated, TypeVar
|
||||
from typing import Annotated, Any, TypeVar
|
||||
|
||||
from fastapi import File, Form, HTTPException
|
||||
from fastapi import Path as PathVar
|
||||
@@ -20,6 +20,7 @@ from exceptions.endpoint_exceptions import (
|
||||
CollectionNotFoundInDatabaseException,
|
||||
CollectionPermissionError,
|
||||
)
|
||||
from handler.audit_handler import AuditTarget, changed_fields, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_collection_handler, db_rom_handler
|
||||
@@ -29,6 +30,7 @@ from handler.filesystem.base_handler import CoverSize
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.collection import (
|
||||
Collection,
|
||||
SmartCollection,
|
||||
@@ -82,6 +84,18 @@ def _hide_collection_roms(
|
||||
return schemas
|
||||
|
||||
|
||||
def _record_collection(
|
||||
request: Request,
|
||||
action: AuditAction,
|
||||
collection: Collection | SmartCollection,
|
||||
data: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
# Every heart toggle goes through the favourites collection; that's not news.
|
||||
if getattr(collection, "is_favorite", False):
|
||||
return
|
||||
record(action, request, AuditTarget.of_collection(collection), data)
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.COLLECTIONS_WRITE])
|
||||
async def add_collection(
|
||||
request: Request,
|
||||
@@ -152,6 +166,7 @@ async def add_collection(
|
||||
},
|
||||
)
|
||||
|
||||
_record_collection(request, AuditAction.COLLECTION_CREATE, created_collection)
|
||||
return CollectionSchema.model_validate(created_collection)
|
||||
|
||||
|
||||
@@ -206,6 +221,7 @@ async def add_smart_collection(
|
||||
db_collection_handler.refresh_smart_collection(created_smart_collection.id)
|
||||
or created_smart_collection
|
||||
)
|
||||
_record_collection(request, AuditAction.SMART_COLLECTION_CREATE, smart_collection)
|
||||
|
||||
return SmartCollectionSchema.model_validate(smart_collection)
|
||||
|
||||
@@ -514,6 +530,28 @@ async def update_collection(
|
||||
updated_collection = db_collection_handler.update_collection(
|
||||
id, cleaned_data, parsed_rom_ids
|
||||
)
|
||||
changed = changed_fields(
|
||||
collection, cleaned_data, ("name", "description", "is_public")
|
||||
)
|
||||
new_artwork = artwork is not None and artwork.filename is not None
|
||||
if (
|
||||
remove_cover
|
||||
or new_artwork
|
||||
or changed_fields(collection, cleaned_data, ["url_cover"])
|
||||
):
|
||||
changed.append("cover")
|
||||
before_ids, after_ids = set(collection.rom_ids), set(updated_collection.rom_ids)
|
||||
if changed or before_ids != after_ids:
|
||||
_record_collection(
|
||||
request,
|
||||
AuditAction.COLLECTION_EDIT,
|
||||
updated_collection,
|
||||
{
|
||||
"changed": changed,
|
||||
"added": len(after_ids - before_ids),
|
||||
"removed": len(before_ids - after_ids),
|
||||
},
|
||||
)
|
||||
|
||||
return CollectionSchema.model_validate(updated_collection)
|
||||
|
||||
@@ -545,10 +583,18 @@ async def add_roms_to_collection(
|
||||
if collection.user_id != request.user.id:
|
||||
raise CollectionPermissionError(id)
|
||||
|
||||
before = set(collection.rom_ids)
|
||||
updated_collection = db_collection_handler.add_roms_to_collection(
|
||||
id, payload.rom_ids
|
||||
)
|
||||
refresh_affected_smart_collections(payload.rom_ids, membership_only=True)
|
||||
if added := sorted(set(updated_collection.rom_ids) - before):
|
||||
_record_collection(
|
||||
request,
|
||||
AuditAction.COLLECTION_ADD_ROMS,
|
||||
collection,
|
||||
{"count": len(added), "rom_ids": added},
|
||||
)
|
||||
return CollectionSchema.model_validate(updated_collection)
|
||||
|
||||
|
||||
@@ -575,10 +621,18 @@ async def remove_roms_from_collection(
|
||||
if collection.user_id != request.user.id:
|
||||
raise CollectionPermissionError(id)
|
||||
|
||||
before = set(collection.rom_ids)
|
||||
updated_collection = db_collection_handler.remove_roms_from_collection(
|
||||
id, payload.rom_ids
|
||||
)
|
||||
refresh_affected_smart_collections(payload.rom_ids, membership_only=True)
|
||||
if removed := sorted(before - set(updated_collection.rom_ids)):
|
||||
_record_collection(
|
||||
request,
|
||||
AuditAction.COLLECTION_REMOVE_ROMS,
|
||||
collection,
|
||||
{"count": len(removed), "rom_ids": removed},
|
||||
)
|
||||
return CollectionSchema.model_validate(updated_collection)
|
||||
|
||||
|
||||
@@ -638,6 +692,7 @@ async def update_smart_collection(
|
||||
smart_collection = (
|
||||
db_collection_handler.refresh_smart_collection(id) or updated_smart_collection
|
||||
)
|
||||
_record_collection(request, AuditAction.SMART_COLLECTION_EDIT, smart_collection)
|
||||
|
||||
return SmartCollectionSchema.model_validate(smart_collection)
|
||||
|
||||
@@ -662,6 +717,7 @@ async def delete_collection(
|
||||
|
||||
log.info(f"Deleting {hl(collection.name, color=BLUE)} from database")
|
||||
db_collection_handler.delete_collection(id)
|
||||
_record_collection(request, AuditAction.COLLECTION_DELETE, collection)
|
||||
|
||||
try:
|
||||
await fs_resource_handler.remove_directory(collection.fs_resources_path)
|
||||
@@ -691,3 +747,4 @@ async def delete_smart_collection(
|
||||
|
||||
log.info(f"Deleting {hl(smart_collection.name, color=BLUE)} from database")
|
||||
db_collection_handler.delete_smart_collection(id)
|
||||
_record_collection(request, AuditAction.SMART_COLLECTION_DELETE, smart_collection)
|
||||
@@ -16,10 +16,12 @@ from config.config_manager import config_manager as cm
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.config import ConfigResponse
|
||||
from exceptions.config_exceptions import ConfigNotWritableException
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -183,6 +185,15 @@ async def _reject_ambiguous_folder(fs_slug: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _record_config(request: Request, setting: str, op: str, **values: str) -> None:
|
||||
record(
|
||||
AuditAction.CONFIG_UPDATE,
|
||||
request,
|
||||
AuditTarget(AuditTargetType.CONFIG, setting, None),
|
||||
{"setting": setting, "op": op, **values},
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE])
|
||||
async def add_platform_binding(
|
||||
request: Request, payload: PlatformBindingPayload
|
||||
@@ -200,6 +211,7 @@ async def add_platform_binding(
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(request, "platform_binding", "add", fs_slug=fs_slug, slug=slug)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/system/platforms/{fs_slug}", [Scope.PLATFORMS_WRITE])
|
||||
@@ -213,6 +225,7 @@ async def delete_platform_binding(request: Request, fs_slug: str) -> None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(request, "platform_binding", "remove", fs_slug=fs_slug)
|
||||
|
||||
|
||||
@protected_route(router.post, "/system/versions", [Scope.PLATFORMS_WRITE])
|
||||
@@ -232,6 +245,7 @@ async def add_platform_version(
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(request, "platform_version", "add", fs_slug=fs_slug, slug=slug)
|
||||
|
||||
|
||||
@protected_route(router.delete, "/system/versions/{fs_slug}", [Scope.PLATFORMS_WRITE])
|
||||
@@ -245,6 +259,7 @@ async def delete_platform_version(request: Request, fs_slug: str) -> None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(request, "platform_version", "remove", fs_slug=fs_slug)
|
||||
|
||||
|
||||
@protected_route(router.post, "/exclude", [Scope.PLATFORMS_WRITE])
|
||||
@@ -260,6 +275,9 @@ async def add_exclusion(request: Request, payload: ExclusionPayload) -> None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(
|
||||
request, "exclusion", "add", type=exclusion_type, value=exclusion_value
|
||||
)
|
||||
|
||||
|
||||
@protected_route(
|
||||
@@ -279,6 +297,9 @@ async def delete_exclusion(
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(
|
||||
request, "exclusion", "remove", type=exclusion_type, value=exclusion_value
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.put, "/scan", [Scope.PLATFORMS_WRITE])
|
||||
@@ -311,6 +332,7 @@ async def update_scan_settings(request: Request, payload: ScanSettingsPayload) -
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(request, "scan_settings", "update")
|
||||
|
||||
# Region priority picks the primary rom of each sibling group, so every
|
||||
# cached gallery sidecar is stale the moment the order changes.
|
||||
|
||||
@@ -27,11 +27,13 @@ from endpoints.responses.device_auth import (
|
||||
DeviceAuthTokenPayload,
|
||||
DeviceAuthTokenResponse,
|
||||
)
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_client_token_handler, db_device_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from models.client_token import ClientToken
|
||||
from models.device import Device, SyncMode
|
||||
from utils.client_tokens import parse_expiry
|
||||
@@ -254,6 +256,17 @@ def approve(
|
||||
f"scopes={' '.join(sorted(approved_set))}"
|
||||
)
|
||||
|
||||
record(
|
||||
AuditAction.DEVICE_APPROVE,
|
||||
request,
|
||||
AuditTarget(AuditTargetType.DEVICE, device.id, device_name),
|
||||
{
|
||||
"client": data.get("client"),
|
||||
"platform": data.get("platform"),
|
||||
"scopes": sorted(approved_set),
|
||||
},
|
||||
)
|
||||
|
||||
return DeviceAuthApproveResponse(device_id=device.id, device_name=device_name)
|
||||
|
||||
|
||||
|
||||
@@ -8,6 +8,13 @@ from config import DISABLE_DOWNLOAD_ENDPOINT_AUTH
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import BulkOperationResponse
|
||||
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
|
||||
from handler.audit_handler import (
|
||||
AuditActor,
|
||||
AuditDraft,
|
||||
AuditTarget,
|
||||
record,
|
||||
record_many,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import (
|
||||
assert_can,
|
||||
@@ -21,6 +28,7 @@ from handler.scan_handler import scan_firmware
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.firmware import Firmware
|
||||
from models.permission import PermAction, PermEntity
|
||||
from utils.router import APIRouter
|
||||
@@ -112,6 +120,13 @@ async def add_firmware(
|
||||
db_firmware_handler.add_firmware(scanned_firmware)
|
||||
uploaded_firmware.append(scanned_firmware)
|
||||
|
||||
record(
|
||||
AuditAction.FIRMWARE_UPLOAD,
|
||||
request,
|
||||
AuditTarget.of_platform(db_platform),
|
||||
{"file_names": [file.filename for file in files if file.filename]},
|
||||
)
|
||||
|
||||
return {
|
||||
"uploaded": len(files),
|
||||
"firmware": [
|
||||
@@ -306,6 +321,8 @@ async def delete_firmware(
|
||||
successful_items = 0
|
||||
failed_ids = []
|
||||
errors = []
|
||||
actor = AuditActor.from_request(request)
|
||||
audit_drafts: list[AuditDraft] = []
|
||||
|
||||
for id in firmware:
|
||||
fw = db_firmware_handler.get_firmware(id)
|
||||
@@ -315,15 +332,18 @@ async def delete_firmware(
|
||||
errors.append(f"Firmware with ID {id} not found")
|
||||
continue
|
||||
|
||||
deleted = removed = False
|
||||
try:
|
||||
log.info(f"Deleting {hl(fw.file_name)} from database")
|
||||
db_firmware_handler.delete_firmware(id)
|
||||
deleted = True
|
||||
|
||||
if id in delete_from_fs:
|
||||
log.info(f"Deleting {hl(fw.file_name)} from filesystem")
|
||||
try:
|
||||
file_path = f"{fw.file_path}/{fw.file_name}"
|
||||
await fs_firmware_handler.remove_file(file_path=file_path)
|
||||
removed = True
|
||||
except FileNotFoundError:
|
||||
error = f"Firmware file {hl(fw.file_name)} not found for platform {hl(fw.platform.slug)}"
|
||||
log.error(error)
|
||||
@@ -335,7 +355,19 @@ async def delete_firmware(
|
||||
except Exception as e:
|
||||
failed_ids.append(id)
|
||||
errors.append(f"Failed to delete firmware {id}: {str(e)}")
|
||||
finally:
|
||||
# The row is gone whatever became of its file.
|
||||
if deleted:
|
||||
audit_drafts.append(
|
||||
AuditDraft(
|
||||
AuditAction.FIRMWARE_DELETE,
|
||||
actor,
|
||||
AuditTarget.of_firmware(fw),
|
||||
{"deleted_from_fs": removed},
|
||||
)
|
||||
)
|
||||
|
||||
record_many(audit_drafts)
|
||||
return {
|
||||
"successful_items": successful_items,
|
||||
"failed_ids": failed_ids,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import Body, HTTPException, Request, status
|
||||
|
||||
@@ -16,11 +16,18 @@ from endpoints.responses.permission import (
|
||||
UserPermissionsSchema,
|
||||
UserPermissionsUpdate,
|
||||
)
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_admin, get_permissions
|
||||
from handler.database import db_permission_handler, db_user_handler
|
||||
from handler.database import (
|
||||
db_permission_handler,
|
||||
db_platform_handler,
|
||||
db_rom_handler,
|
||||
db_user_handler,
|
||||
)
|
||||
from handler.socket_handler import socket_handler
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from models.permission import PermAction, PermEntity, PermissionGroup
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -88,6 +95,41 @@ def _group_schema(group: PermissionGroup) -> PermissionGroupSchema:
|
||||
)
|
||||
|
||||
|
||||
def _group_target(group: PermissionGroup) -> AuditTarget:
|
||||
return AuditTarget(AuditTargetType.PERMISSION_GROUP, group.id, group.name)
|
||||
|
||||
|
||||
def _hidden_target(entity: PermEntity, entity_id: int) -> AuditTarget | None:
|
||||
if entity == PermEntity.ROMS:
|
||||
rom = db_rom_handler.get_rom_visibility_label(entity_id)
|
||||
return (
|
||||
AuditTarget.of_rom(rom)
|
||||
if rom
|
||||
else AuditTarget(AuditTargetType.ROM, entity_id, None)
|
||||
)
|
||||
if entity == PermEntity.PLATFORMS:
|
||||
platform = db_platform_handler.get_platform(entity_id)
|
||||
return (
|
||||
AuditTarget.of_platform(platform)
|
||||
if platform
|
||||
else AuditTarget(AuditTargetType.PLATFORM, entity_id, None)
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _group_name(group_id: int | None) -> str | None:
|
||||
group = db_permission_handler.get_group(group_id) if group_id is not None else None
|
||||
return group.name if group else None
|
||||
|
||||
|
||||
def _principal(user_id: int | None, group_id: int | None) -> dict[str, Any]:
|
||||
"""Who something was hidden from, named for the audit log."""
|
||||
if user_id is not None:
|
||||
user = db_user_handler.get_user(user_id)
|
||||
return {"type": "user", "id": user_id, "name": user.username if user else None}
|
||||
return {"type": "group", "id": group_id, "name": _group_name(group_id)}
|
||||
|
||||
|
||||
@protected_route(router.get, "/groups", [Scope.USERS_READ])
|
||||
def list_permission_groups(request: Request) -> list[PermissionGroupSchema]:
|
||||
"""List all permission groups with their grants."""
|
||||
@@ -115,6 +157,12 @@ def create_permission_group(
|
||||
color=body.color,
|
||||
grants=[(g.entity, g.action, g.own_only) for g in body.grants],
|
||||
)
|
||||
record(
|
||||
AuditAction.PERMISSION_GROUP_CREATE,
|
||||
request,
|
||||
_group_target(group),
|
||||
{"grants": len(body.grants), "is_default": body.is_default},
|
||||
)
|
||||
return _group_schema(group)
|
||||
|
||||
|
||||
@@ -164,6 +212,12 @@ async def update_permission_group(
|
||||
# Grant changes alter every member's effective permissions.
|
||||
for member_id in db_permission_handler.get_group_member_ids(id):
|
||||
await emit_permissions_changed(member_id)
|
||||
record(
|
||||
AuditAction.PERMISSION_GROUP_EDIT,
|
||||
request,
|
||||
_group_target(updated),
|
||||
{"changed": sorted(body.model_dump(exclude_none=True))},
|
||||
)
|
||||
return _group_schema(updated)
|
||||
|
||||
|
||||
@@ -187,6 +241,12 @@ async def delete_permission_group(request: Request, id: int) -> None:
|
||||
|
||||
member_ids = db_permission_handler.get_group_member_ids(id)
|
||||
db_permission_handler.delete_group(id)
|
||||
record(
|
||||
AuditAction.PERMISSION_GROUP_DELETE,
|
||||
request,
|
||||
_group_target(group),
|
||||
{"members": len(member_ids)},
|
||||
)
|
||||
for member_id in member_ids:
|
||||
await emit_permissions_changed(member_id)
|
||||
|
||||
@@ -258,6 +318,16 @@ async def update_user_permissions(
|
||||
)
|
||||
|
||||
await emit_permissions_changed(user_id)
|
||||
record(
|
||||
AuditAction.USER_PERMISSIONS_EDIT,
|
||||
request,
|
||||
AuditTarget.of_user(user),
|
||||
lambda: {
|
||||
"group": _group_name(group_id),
|
||||
"group_changed": body.set_group and group_id != user.permission_group_id,
|
||||
"overrides": len(body.overrides) if body.overrides is not None else None,
|
||||
},
|
||||
)
|
||||
return _user_permissions(user_id, group_id)
|
||||
|
||||
|
||||
@@ -289,6 +359,16 @@ async def add_hidden_entity(
|
||||
db_permission_handler.add_hidden_entity(
|
||||
body.entity, body.entity_id, user_id=body.user_id, group_id=body.group_id
|
||||
)
|
||||
record(
|
||||
AuditAction.VISIBILITY_HIDE,
|
||||
request,
|
||||
lambda: _hidden_target(body.entity, body.entity_id),
|
||||
lambda: {
|
||||
"from": _principal(body.user_id, body.group_id),
|
||||
"entity": body.entity,
|
||||
"entity_id": body.entity_id,
|
||||
},
|
||||
)
|
||||
await _emit_for_principal(body.user_id, body.group_id)
|
||||
return HiddenEntitySchema(entity=body.entity, entity_id=body.entity_id)
|
||||
|
||||
@@ -316,6 +396,16 @@ async def remove_hidden_entity(
|
||||
db_permission_handler.remove_hidden_entity(
|
||||
entity, entity_id, user_id=user_id, group_id=group_id
|
||||
)
|
||||
record(
|
||||
AuditAction.VISIBILITY_UNHIDE,
|
||||
request,
|
||||
lambda: _hidden_target(entity, entity_id),
|
||||
lambda: {
|
||||
"from": _principal(user_id, group_id),
|
||||
"entity": entity,
|
||||
"entity_id": entity_id,
|
||||
},
|
||||
)
|
||||
await _emit_for_principal(user_id, group_id)
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses.platform import PlatformSchema
|
||||
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
||||
from handler.audit_handler import AuditTarget, changed_fields, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import (
|
||||
assert_can,
|
||||
@@ -21,6 +22,7 @@ from handler.scan_handler import scan_platform
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.platform import (
|
||||
CUSTOM_NAME_MAX_LENGTH,
|
||||
@@ -53,9 +55,14 @@ async def add_platform(
|
||||
log.info(f"Detected platform: {hl(fs_slug)}")
|
||||
|
||||
scanned_platform = await scan_platform(fs_slug, [fs_slug])
|
||||
return PlatformSchema.model_validate(
|
||||
db_platform_handler.add_platform(scanned_platform)
|
||||
platform = db_platform_handler.add_platform(scanned_platform)
|
||||
record(
|
||||
AuditAction.PLATFORM_CREATE,
|
||||
request,
|
||||
AuditTarget.of_platform(platform),
|
||||
{"fs_slug": fs_slug},
|
||||
)
|
||||
return PlatformSchema.model_validate(platform)
|
||||
|
||||
|
||||
@protected_route(router.get, "", [Scope.PLATFORMS_READ])
|
||||
@@ -158,11 +165,22 @@ async def update_platform(
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
assert_platform_visible(request, platform_db)
|
||||
|
||||
submitted = {"custom_name": custom_name, "description": description}
|
||||
changed = changed_fields(
|
||||
platform_db, {k: v for k, v in submitted.items() if v is not None}, submitted
|
||||
)
|
||||
if custom_name is not None:
|
||||
platform_db.custom_name = custom_name
|
||||
if description is not None:
|
||||
platform_db.description = description
|
||||
platform_db = db_platform_handler.add_platform(platform_db)
|
||||
if changed:
|
||||
record(
|
||||
AuditAction.PLATFORM_EDIT,
|
||||
request,
|
||||
AuditTarget.of_platform(platform_db),
|
||||
{"changed": changed},
|
||||
)
|
||||
|
||||
return PlatformSchema.model_validate(platform_db)
|
||||
|
||||
@@ -190,3 +208,9 @@ async def delete_platform(
|
||||
f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database"
|
||||
)
|
||||
db_platform_handler.delete_platform(id)
|
||||
record(
|
||||
AuditAction.PLATFORM_DELETE,
|
||||
request,
|
||||
AuditTarget.of_platform(platform),
|
||||
{"fs_slug": platform.fs_slug},
|
||||
)
|
||||
@@ -10,6 +10,7 @@ from endpoints.responses.play_session import (
|
||||
PlaySessionSchema,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_play_session_handler
|
||||
from handler.play_session_handler import ingest_play_sessions as _ingest
|
||||
from logger.logger import log
|
||||
@@ -67,6 +68,7 @@ def ingest_play_sessions(
|
||||
summary = _ingest(
|
||||
user_id=request.user.id,
|
||||
username=request.user.username,
|
||||
perms=get_permissions(request),
|
||||
entries=[
|
||||
{
|
||||
"rom_id": s.rom_id,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
from typing import Any
|
||||
|
||||
from models.audit_event import (
|
||||
AuditAction,
|
||||
AuditActorKind,
|
||||
AuditCategory,
|
||||
AuditEvent,
|
||||
category_of,
|
||||
)
|
||||
|
||||
from .base import BaseModel, UTCDatetime
|
||||
from .notification import NotificationActorSchema
|
||||
|
||||
|
||||
class AuditEventSchema(BaseModel):
|
||||
id: int
|
||||
# A row written under an action a later version dropped must still list.
|
||||
action: AuditAction | str
|
||||
category: AuditCategory | None
|
||||
occurred_at: UTCDatetime
|
||||
actor_kind: AuditActorKind | str
|
||||
# The account as it is now; null once it's deleted, when `actor_name` remains.
|
||||
actor: NotificationActorSchema | None
|
||||
actor_name: str | None
|
||||
target_type: str | None
|
||||
target_id: str | None
|
||||
target_name: str | None
|
||||
ip_address: str | None
|
||||
device_id: str | None
|
||||
device_name: str | None
|
||||
data: dict[str, Any]
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, event: AuditEvent, device_name: str | None) -> "AuditEventSchema":
|
||||
return cls(
|
||||
id=event.id,
|
||||
action=event.action,
|
||||
category=category_of(event.action),
|
||||
occurred_at=event.occurred_at,
|
||||
actor_kind=event.actor_kind,
|
||||
actor=(
|
||||
NotificationActorSchema.model_validate(event.actor)
|
||||
if event.actor
|
||||
else None
|
||||
),
|
||||
actor_name=event.actor_name,
|
||||
target_type=event.target_type,
|
||||
target_id=event.target_id,
|
||||
target_name=event.target_name,
|
||||
ip_address=event.ip_address,
|
||||
device_id=event.device_id,
|
||||
device_name=device_name,
|
||||
data=event.data,
|
||||
)
|
||||
@@ -5,6 +5,7 @@ from starlette.requests import Request
|
||||
|
||||
from handler.metadata.ra_handler import RAUserProgression
|
||||
from models.user import Role, User
|
||||
from utils.auth import current_device_id
|
||||
from utils.urls import get_public_base_url
|
||||
|
||||
from .base import BaseModel, UTCDatetime
|
||||
@@ -45,9 +46,7 @@ class UserSchema(BaseModel):
|
||||
return None
|
||||
|
||||
schema = cls.model_validate(db_user)
|
||||
schema.current_device_id = getattr(
|
||||
request.state, "device_id", None
|
||||
) or request.session.get("device_id")
|
||||
schema.current_device_id = current_device_id(request)
|
||||
return schema
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from dataclasses import replace
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
from stat import S_IFREG
|
||||
from typing import Annotated, Any, Sequence
|
||||
from typing import Annotated, Any, Final, Literal, Sequence
|
||||
from urllib.parse import quote
|
||||
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo
|
||||
|
||||
@@ -51,6 +51,16 @@ from endpoints.responses.rom import (
|
||||
)
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from handler.audit_handler import (
|
||||
AuditActor,
|
||||
AuditDraft,
|
||||
AuditTarget,
|
||||
change,
|
||||
changed_fields,
|
||||
record,
|
||||
record_download,
|
||||
record_many,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import (
|
||||
assert_can,
|
||||
@@ -109,6 +119,8 @@ from handler.scan_handler import (
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from models.collection import VirtualCollection
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.rom import (
|
||||
HAS_FILE_ON_DISK_FILTERS,
|
||||
@@ -282,6 +294,47 @@ class RomUpdateForm(BaseModel):
|
||||
url_manual: str | None = None
|
||||
|
||||
|
||||
# The provider ids the edit form sets; changing one rematches the rom.
|
||||
MATCH_ID_FIELDS: Final = tuple(
|
||||
f for f in RomUpdateForm.model_fields if f.endswith("_id")
|
||||
)
|
||||
# What an edit reports as changed, each read off one or more columns.
|
||||
_EDIT_AUDIT_FIELDS: Final[dict[str, tuple[str, ...]]] = {
|
||||
"name": ("name",),
|
||||
"fs_name": ("fs_name",),
|
||||
"summary": ("summary",),
|
||||
"cover": ("url_cover", "path_cover_l"),
|
||||
"manual": ("url_manual",),
|
||||
}
|
||||
|
||||
|
||||
def _record_rom_update(request: Request, before: Rom, after: Rom) -> None:
|
||||
"""Record an edit as a rematch when a provider id moved, else as the fields it changed."""
|
||||
providers = {
|
||||
f: getattr(after, f) for f in changed_fields(before, after, MATCH_ID_FIELDS)
|
||||
}
|
||||
changed = [
|
||||
label
|
||||
for label, columns in _EDIT_AUDIT_FIELDS.items()
|
||||
if changed_fields(before, after, columns)
|
||||
]
|
||||
if not providers and not changed:
|
||||
return
|
||||
|
||||
data: dict[str, Any] = {"changed": changed}
|
||||
for field in ("name", "fs_name"):
|
||||
if field in changed:
|
||||
data[field] = change(before, after, field)
|
||||
if providers:
|
||||
data["providers"] = providers
|
||||
record(
|
||||
AuditAction.ROM_MATCH if providers else AuditAction.ROM_EDIT,
|
||||
request,
|
||||
AuditTarget.of_rom(after),
|
||||
data,
|
||||
)
|
||||
|
||||
|
||||
class RomUserData(BaseModel):
|
||||
is_main_sibling: bool | None = Field(
|
||||
default=None, description="Whether this rom is the main sibling."
|
||||
@@ -814,6 +867,37 @@ def get_random_rom(
|
||||
return SimpleRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
def _bulk_download_target(
|
||||
user_id: int,
|
||||
platform_id: int | None,
|
||||
collection_id: int | None,
|
||||
smart_collection_id: int | None,
|
||||
virtual_collection_id: str | None,
|
||||
) -> AuditTarget | None:
|
||||
"""What a bulk download took whole, or None for a hand-picked list of roms."""
|
||||
if platform_id:
|
||||
platform = db_platform_handler.get_platform(platform_id)
|
||||
return AuditTarget.of_platform(platform) if platform else None
|
||||
if virtual_collection_id:
|
||||
name, _ = VirtualCollection.from_id(virtual_collection_id)
|
||||
return AuditTarget(
|
||||
AuditTargetType.VIRTUAL_COLLECTION, virtual_collection_id, name
|
||||
)
|
||||
if collection_id:
|
||||
collection = db_collection_handler.get_collection(collection_id)
|
||||
elif smart_collection_id:
|
||||
collection = db_collection_handler.get_smart_collection(smart_collection_id)
|
||||
else:
|
||||
return None
|
||||
if collection is None:
|
||||
return None
|
||||
target = AuditTarget.of_collection(collection)
|
||||
if collection.is_public or collection.user_id == user_id:
|
||||
return target
|
||||
# Someone else's private collection is kept by id; its name stays theirs.
|
||||
return AuditTarget(target.type, target.id, None)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/download",
|
||||
@@ -919,6 +1003,23 @@ async def download_roms(
|
||||
f"User {hl(current_username, color=BLUE)} is downloading {len(rom_objects)} ROMs as zip"
|
||||
)
|
||||
|
||||
def served(response: Response) -> Response:
|
||||
# Recorded once there's a response, so a download that failed isn't logged.
|
||||
record_download(
|
||||
request,
|
||||
lambda: _bulk_download_target(
|
||||
request.user.id,
|
||||
platform_id,
|
||||
collection_id,
|
||||
smart_collection_id,
|
||||
virtual_collection_id,
|
||||
),
|
||||
f"bulk:{binascii.crc32(','.join(map(str, sorted(found_ids))).encode())}",
|
||||
{"count": len(rom_objects), "rom_ids": sorted(found_ids)},
|
||||
action=AuditAction.ROM_BULK_DOWNLOAD,
|
||||
)
|
||||
return response
|
||||
|
||||
all_entries = []
|
||||
for rom in rom_objects:
|
||||
rom_files = sorted(rom.files, key=lambda x: x.file_name)
|
||||
@@ -948,9 +1049,11 @@ async def download_roms(
|
||||
log_label=f"bulk download ({len(rom_objects)} ROMs)",
|
||||
)
|
||||
if redirect_path:
|
||||
return FileRedirectResponse(
|
||||
download_path=redirect_path,
|
||||
filename=file_name,
|
||||
return served(
|
||||
FileRedirectResponse(
|
||||
download_path=redirect_path,
|
||||
filename=file_name,
|
||||
)
|
||||
)
|
||||
|
||||
content_lines = [
|
||||
@@ -963,9 +1066,11 @@ async def download_roms(
|
||||
for e in all_entries
|
||||
]
|
||||
|
||||
return ZipResponse(
|
||||
content_lines=content_lines,
|
||||
filename=quote(file_name),
|
||||
return served(
|
||||
ZipResponse(
|
||||
content_lines=content_lines,
|
||||
filename=quote(file_name),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -1287,6 +1392,13 @@ async def get_rom_content(
|
||||
description="Comma-separated list of file ids to download for multi-part roms."
|
||||
),
|
||||
] = None,
|
||||
purpose: Annotated[
|
||||
Literal["download", "play"],
|
||||
Query(
|
||||
description="`play` when a player fetches the rom to run it, which is "
|
||||
"recorded as a player load rather than a download."
|
||||
),
|
||||
] = "download",
|
||||
):
|
||||
"""Download a rom.
|
||||
|
||||
@@ -1330,6 +1442,28 @@ async def get_rom_content(
|
||||
f"User {hl(current_username, color=BLUE)} is downloading {hl(rom.fs_name)}"
|
||||
)
|
||||
|
||||
def served(response: Response) -> Response:
|
||||
# Recorded once there's a response, so a fetch that failed isn't logged.
|
||||
# The marker is the client's word, so a player's fetch is still recorded.
|
||||
record_download(
|
||||
request,
|
||||
AuditTarget.of_rom(rom),
|
||||
f"rom:{purpose}:{rom.id}:{file_ids or ''}",
|
||||
{
|
||||
"file_name": (
|
||||
files[0].file_name if len(files) == 1 else f"{file_name}.zip"
|
||||
),
|
||||
"file_ids": [f.id for f in files] if file_ids else None,
|
||||
"size_bytes": sum(f.file_size_bytes for f in files),
|
||||
},
|
||||
action=(
|
||||
AuditAction.ROM_PLAYER_LOAD
|
||||
if purpose == "play"
|
||||
else AuditAction.ROM_DOWNLOAD
|
||||
),
|
||||
)
|
||||
return response
|
||||
|
||||
m3u_files = playlist_files(files)
|
||||
|
||||
# Serve the file directly in development mode for emulatorjs
|
||||
@@ -1342,14 +1476,16 @@ async def get_rom_content(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"File {file.file_name} not found on disk for ROM {id}",
|
||||
)
|
||||
return FileResponse(
|
||||
path=rom_path,
|
||||
filename=file.file_name,
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(file.file_name)}; filename=\"{quote(file.file_name)}\"",
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Content-Length": str(file.file_size_bytes),
|
||||
},
|
||||
return served(
|
||||
FileResponse(
|
||||
path=rom_path,
|
||||
filename=file.file_name,
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(file.file_name)}; filename=\"{quote(file.file_name)}\"",
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Content-Length": str(file.file_size_bytes),
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
async def build_zip_in_memory() -> bytes:
|
||||
@@ -1404,18 +1540,22 @@ async def get_rom_content(
|
||||
zip_data = await build_zip_in_memory()
|
||||
|
||||
# Streams the zip file to the client
|
||||
return Response(
|
||||
content=zip_data,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(file_name)}.zip; filename=\"{quote(file_name)}.zip\"",
|
||||
},
|
||||
return served(
|
||||
Response(
|
||||
content=zip_data,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{quote(file_name)}.zip; filename=\"{quote(file_name)}.zip\"",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
# Otherwise proxy through nginx
|
||||
if len(files) == 1:
|
||||
return FileRedirectResponse(
|
||||
download_path=Path(f"/library/{files[0].full_path}"),
|
||||
return served(
|
||||
FileRedirectResponse(
|
||||
download_path=Path(f"/library/{files[0].full_path}"),
|
||||
)
|
||||
)
|
||||
|
||||
# Multi-file path: serve cached ZIP for Range requests (resumable),
|
||||
@@ -1432,9 +1572,11 @@ async def get_rom_content(
|
||||
log_label=f"ROM {rom.id}",
|
||||
)
|
||||
if redirect_path:
|
||||
return FileRedirectResponse(
|
||||
download_path=redirect_path,
|
||||
filename=f"{file_name}.zip",
|
||||
return served(
|
||||
FileRedirectResponse(
|
||||
download_path=redirect_path,
|
||||
filename=f"{file_name}.zip",
|
||||
)
|
||||
)
|
||||
|
||||
content_lines = [
|
||||
@@ -1458,9 +1600,11 @@ async def get_rom_content(
|
||||
)
|
||||
content_lines.append(m3u_line)
|
||||
|
||||
return ZipResponse(
|
||||
content_lines=content_lines,
|
||||
filename=f"{quote(file_name)}.zip",
|
||||
return served(
|
||||
ZipResponse(
|
||||
content_lines=content_lines,
|
||||
filename=f"{quote(file_name)}.zip",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -1575,6 +1719,12 @@ async def create_physical_rom(
|
||||
|
||||
db_rom_handler.invalidate_filter_values_cache()
|
||||
refresh_affected_smart_collections([added_rom.id])
|
||||
record(
|
||||
AuditAction.ROM_CREATE,
|
||||
request,
|
||||
AuditTarget.of_rom(added_rom),
|
||||
{"physical": True},
|
||||
)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(added_rom, request)
|
||||
|
||||
@@ -1611,6 +1761,8 @@ async def update_rom(
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
if unmatch_metadata:
|
||||
unmatched = {f: getattr(rom, f) for f in MATCH_ID_FIELDS if getattr(rom, f)}
|
||||
unmatch_target = AuditTarget.of_rom(rom)
|
||||
db_rom_handler.update_rom(
|
||||
id,
|
||||
{
|
||||
@@ -1662,6 +1814,12 @@ async def update_rom(
|
||||
|
||||
db_rom_handler.invalidate_filter_values_cache()
|
||||
refresh_affected_smart_collections([id])
|
||||
record(
|
||||
AuditAction.ROM_UNMATCH,
|
||||
request,
|
||||
unmatch_target,
|
||||
{"providers": unmatched},
|
||||
)
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
provided_fields = form_data.model_fields_set
|
||||
@@ -2130,9 +2288,11 @@ async def update_rom(
|
||||
)
|
||||
|
||||
# Refetch the rom from the database
|
||||
before = rom
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
_record_rom_update(request, before, rom)
|
||||
|
||||
if meta_playmatch_handler.is_manual_match(form_data.model_fields_set):
|
||||
fire_and_forget(meta_playmatch_handler.submit_manual_match_suggestion(rom))
|
||||
@@ -2208,6 +2368,8 @@ async def delete_roms(
|
||||
deleted_ids: list[int] = []
|
||||
failed_ids = []
|
||||
errors = []
|
||||
actor = AuditActor.from_request(request)
|
||||
audit_drafts: list[AuditDraft] = []
|
||||
|
||||
for id in roms:
|
||||
rom = db_rom_handler.get_rom_deletion_target(id)
|
||||
@@ -2218,6 +2380,7 @@ async def delete_roms(
|
||||
errors.append(f"ROM with ID {id} not found")
|
||||
continue
|
||||
|
||||
removed = False
|
||||
try:
|
||||
if id in delete_from_fs:
|
||||
log.info(f"Deleting {hl(rom.fs_name)} from filesystem")
|
||||
@@ -2226,8 +2389,10 @@ async def delete_roms(
|
||||
full_path = fs_rom_handler.validate_path(rom_path)
|
||||
if full_path.is_dir():
|
||||
await fs_rom_handler.remove_directory(rom_path)
|
||||
removed = True
|
||||
else:
|
||||
await fs_rom_handler.remove_file(rom_path)
|
||||
removed = True
|
||||
# Clean up empty parent directory if it becomes empty
|
||||
parent = full_path.parent
|
||||
if (
|
||||
@@ -2252,6 +2417,18 @@ async def delete_roms(
|
||||
f"Deleting {hl(str(rom.name or 'ROM'), color=BLUE)} [{hl(rom.fs_name)}] from database"
|
||||
)
|
||||
db_rom_handler.delete_rom(id)
|
||||
# Recorded as soon as the row is gone, whatever becomes of its resources.
|
||||
audit_drafts.append(
|
||||
AuditDraft(
|
||||
AuditAction.ROM_DELETE,
|
||||
actor,
|
||||
AuditTarget.of_rom(rom),
|
||||
{
|
||||
"deleted_from_fs": removed,
|
||||
"platform": rom.platform_display_name,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
await fs_resource_handler.remove_directory(rom.fs_resources_path)
|
||||
@@ -2265,6 +2442,7 @@ async def delete_roms(
|
||||
failed_ids.append(id)
|
||||
errors.append(f"Failed to delete ROM {id}: {str(e)}")
|
||||
|
||||
record_many(audit_drafts)
|
||||
if deleted_ids:
|
||||
db_rom_handler.invalidate_filter_values_cache()
|
||||
# Deleted ROMs would otherwise linger in the cached smart collection
|
||||
|
||||
@@ -12,6 +12,7 @@ from config import DEV_MODE, DISABLE_DOWNLOAD_ENDPOINT_AUTH
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.rom import RomFileSchema, RomFileUserSchema
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from handler.audit_handler import AuditTarget, record, record_download
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_can, assert_rom_visible, get_permissions
|
||||
from handler.database import db_rom_handler
|
||||
@@ -19,6 +20,7 @@ from handler.filesystem import fs_rom_handler
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.rom import DOCUMENT_CATEGORIES, RomFileCategory
|
||||
from utils.audio_tags import guess_audio_media_type
|
||||
@@ -69,6 +71,11 @@ async def get_romfile(
|
||||
return RomFileSchema.model_validate(file)
|
||||
|
||||
|
||||
def _rom_target(rom_id: int) -> AuditTarget | None:
|
||||
rom = db_rom_handler.get_rom_visibility_label(rom_id)
|
||||
return AuditTarget.of_rom(rom) if rom else None
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/{id}/files/content/{file_name}",
|
||||
@@ -131,6 +138,20 @@ async def get_romfile_content(
|
||||
media_type = "application/octet-stream"
|
||||
disposition = "attachment"
|
||||
|
||||
# Inline files feed the in-page viewers and players; only an attachment is
|
||||
# someone taking the file away.
|
||||
if disposition == "attachment":
|
||||
record_download(
|
||||
request,
|
||||
lambda: _rom_target(file.rom_id),
|
||||
f"file:{file.id}",
|
||||
{
|
||||
"file_name": file.file_name,
|
||||
"file_ids": [file.id],
|
||||
"size_bytes": file.file_size_bytes,
|
||||
},
|
||||
)
|
||||
|
||||
# Inline files are served under an explicit, trusted Content-Type; nosniff
|
||||
# keeps the browser from sniffing them into anything script-capable (e.g. a
|
||||
# Markdown manual into HTML).
|
||||
@@ -216,6 +237,12 @@ async def delete_rom_file(
|
||||
f"Deleted file {hl(rom_file.file_name)} from "
|
||||
f"{hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]"
|
||||
)
|
||||
record(
|
||||
AuditAction.ROM_FILE_DELETE,
|
||||
request,
|
||||
AuditTarget.of_rom(rom),
|
||||
{"file_id": file_id, "file_name": rom_file.file_name},
|
||||
)
|
||||
|
||||
return Response()
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from config import ROM_UPLOAD_TMP_BASE, ROM_UPLOAD_TTL
|
||||
from decorators.auth import protected_route
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_rom_visible, get_permissions
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
@@ -35,6 +36,7 @@ from handler.rom_upload import (
|
||||
staging_path,
|
||||
)
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.rom import Rom, RomFile
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -162,6 +164,27 @@ async def _commit(
|
||||
) from exc
|
||||
|
||||
|
||||
def _upload_target(rom: Rom | None, platform_id: int) -> AuditTarget | None:
|
||||
if rom is not None:
|
||||
return AuditTarget.of_rom(rom)
|
||||
# A platform folder upload has no rom until the next scan finds it.
|
||||
platform = db_platform_handler.get_platform(platform_id)
|
||||
return AuditTarget.of_platform(platform) if platform else None
|
||||
|
||||
|
||||
def _record_upload(request: Request, rom: Rom | None, session: dict) -> None:
|
||||
record(
|
||||
AuditAction.ROM_UPLOAD,
|
||||
request,
|
||||
lambda: _upload_target(rom, session["platform_id"]),
|
||||
{
|
||||
"file_name": session["filename"],
|
||||
"size_bytes": session["total_size"],
|
||||
"overwrite": session["overwrite"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def receive_rom_file(
|
||||
request: Request, rom: Rom, folder: str, filename: str
|
||||
) -> RomFile | None:
|
||||
@@ -527,6 +550,7 @@ async def complete_chunked_upload(
|
||||
finally:
|
||||
await _cleanup_upload_state(upload_id)
|
||||
|
||||
_record_upload(request, destination.rom, session)
|
||||
return Response(status_code=status.HTTP_201_CREATED)
|
||||
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ from exceptions.fs_exceptions import (
|
||||
RomsNotFoundException,
|
||||
)
|
||||
from exceptions.socket_exceptions import ScanStoppedException
|
||||
from handler.audit_handler import AuditActor, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import (
|
||||
db_collection_handler,
|
||||
@@ -82,6 +83,7 @@ from handler.socket_handler import socket_handler
|
||||
from logger.formatter import BLUE, LIGHTYELLOW
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.firmware import Firmware
|
||||
from models.notification import NotificationKind, NotificationLevel
|
||||
from models.platform import Platform
|
||||
@@ -146,6 +148,12 @@ def report_scan_failure(
|
||||
await _get_socket_manager().emit("scan:done_ko", reason)
|
||||
await notify_scan_end(job.kwargs.get("started_by_user_id"), reason)
|
||||
|
||||
record(
|
||||
AuditAction.SCAN_FINISH,
|
||||
AuditActor.for_user_id(job.kwargs.get("started_by_user_id")),
|
||||
data={"status": "failed", "error": reason},
|
||||
)
|
||||
|
||||
try:
|
||||
asyncio.run(report())
|
||||
except Exception:
|
||||
@@ -1169,6 +1177,19 @@ async def scan_platforms(
|
||||
if not platform_fs_slugs:
|
||||
platform_fs_slugs = []
|
||||
|
||||
audit_actor = AuditActor.for_user_id(started_by_user_id)
|
||||
record(
|
||||
AuditAction.SCAN_START,
|
||||
audit_actor,
|
||||
data={
|
||||
"type": scan_type.value,
|
||||
"platform_ids": platform_ids,
|
||||
"platform_fs_slugs": platform_fs_slugs,
|
||||
"rom_ids": roms_ids,
|
||||
"sources": metadata_sources,
|
||||
},
|
||||
)
|
||||
|
||||
socket_manager = _get_socket_manager()
|
||||
scan_stats = ScanStats()
|
||||
|
||||
@@ -1181,6 +1202,17 @@ async def scan_platforms(
|
||||
update_job_meta({SCAN_REPORTED_META_KEY: True})
|
||||
await scan_stats.flush(socket_manager)
|
||||
await socket_manager.emit(event, payload)
|
||||
failed = event == "scan:done_ko"
|
||||
record(
|
||||
AuditAction.SCAN_FINISH,
|
||||
audit_actor,
|
||||
data={
|
||||
"status": "failed" if failed else "stopped" if stopped else "completed",
|
||||
"error": payload if failed else None,
|
||||
"rom_ids": roms_ids,
|
||||
**scan_stats.to_dict(),
|
||||
},
|
||||
)
|
||||
if event == "scan:done_ko":
|
||||
await notify_scan_end(started_by_user_id, payload)
|
||||
# A stop is the user's own doing, and a rescan of named roms answers a
|
||||
@@ -1546,7 +1578,8 @@ async def scan_handler(sid: str, options: dict[str, Any]):
|
||||
async def stop_scan_handler(sid: str):
|
||||
"""Stop scan socket endpoint"""
|
||||
|
||||
if await authorize_scan(sid) is None:
|
||||
user = await authorize_scan(sid)
|
||||
if user is None:
|
||||
return
|
||||
|
||||
log.info(f"{emoji.EMOJI_STOP_BUTTON} Stop scan requested...")
|
||||
@@ -1574,3 +1607,11 @@ async def stop_scan_handler(sid: str):
|
||||
f"({int(running_job is not None)} running, {len(queued_jobs)} queued, "
|
||||
f"{len(scheduled_jobs)} scheduled)"
|
||||
)
|
||||
record(
|
||||
AuditAction.SCAN_STOP,
|
||||
AuditActor.for_user(user),
|
||||
data={
|
||||
"running": running_job is not None,
|
||||
"cancelled": len(queued_jobs) + len(scheduled_jobs),
|
||||
},
|
||||
)
|
||||
@@ -17,6 +17,7 @@ from endpoints.responses.sync import (
|
||||
SyncSessionSchema,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import (
|
||||
db_device_handler,
|
||||
db_device_save_sync_handler,
|
||||
@@ -389,6 +390,7 @@ def complete_sync_session(
|
||||
summary = ingest_play_sessions(
|
||||
user_id=request.user.id,
|
||||
username=request.user.username,
|
||||
perms=get_permissions(request),
|
||||
entries=[
|
||||
{
|
||||
"rom_id": s.rom_id,
|
||||
|
||||
@@ -24,6 +24,7 @@ from endpoints.responses import (
|
||||
WatcherTaskStatusResponse,
|
||||
)
|
||||
from endpoints.responses.tasks import GroupedTasksDict, TaskInfo
|
||||
from handler.audit_handler import AuditTarget, record
|
||||
from handler.auth.constants import Scope
|
||||
from handler.redis_handler import (
|
||||
ALL_QUEUES,
|
||||
@@ -33,6 +34,7 @@ from handler.redis_handler import (
|
||||
low_prio_queue,
|
||||
redis_client,
|
||||
)
|
||||
from models.audit_event import AuditAction, AuditTargetType
|
||||
from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task
|
||||
from tasks.tasks import Task, TaskType
|
||||
from utils.router import APIRouter
|
||||
@@ -335,6 +337,12 @@ async def run_single_task(
|
||||
task_kwargs=task_kwargs or {},
|
||||
run_by_user_id=request.user.id,
|
||||
)
|
||||
record(
|
||||
AuditAction.TASK_RUN,
|
||||
request,
|
||||
AuditTarget(AuditTargetType.TASK, task_name, task_instance.title),
|
||||
{"job_id": job.id, "kwargs": task_kwargs or {}},
|
||||
)
|
||||
|
||||
return {
|
||||
"task_key": task_name,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import json
|
||||
from typing import Annotated, Any, cast
|
||||
from typing import Annotated, Any, Final, cast
|
||||
|
||||
from fastapi import Body, Form, HTTPException
|
||||
from fastapi import Path as PathVar
|
||||
@@ -10,6 +10,14 @@ from decorators.auth import protected_route
|
||||
from endpoints.forms.identity import UserForm
|
||||
from endpoints.permissions import emit_permissions_changed
|
||||
from endpoints.responses.identity import InviteLinkSchema, UserSchema
|
||||
from handler.audit_handler import (
|
||||
AuditActor,
|
||||
AuditTarget,
|
||||
change,
|
||||
changed_fields,
|
||||
client_ip,
|
||||
record,
|
||||
)
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_user_handler
|
||||
@@ -22,6 +30,7 @@ from handler.metadata import meta_ra_handler
|
||||
from handler.metadata.ra_handler import RAUserProgression
|
||||
from handler.notification_handler import notify
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction
|
||||
from models.notification import NotificationKind, NotificationLevel
|
||||
from models.user import Role, User
|
||||
from utils.router import APIRouter
|
||||
@@ -38,6 +47,33 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
# What a user edit reports; ui_settings and avatars change too often to be news.
|
||||
_USER_EDIT_AUDIT_FIELDS: Final = (
|
||||
"username",
|
||||
"email",
|
||||
"hashed_password",
|
||||
"role",
|
||||
"enabled",
|
||||
)
|
||||
|
||||
|
||||
def _record_user_edit(
|
||||
request: Request, before: User, after: User, cleaned_data: dict[str, Any]
|
||||
) -> None:
|
||||
changed = changed_fields(
|
||||
before, after, [f for f in _USER_EDIT_AUDIT_FIELDS if f in cleaned_data]
|
||||
)
|
||||
if not changed:
|
||||
return
|
||||
data: dict[str, Any] = {
|
||||
"changed": ["password" if f == "hashed_password" else f for f in changed]
|
||||
}
|
||||
for field in ("username", "role", "enabled"):
|
||||
if field in changed:
|
||||
data[field] = change(before, after, field)
|
||||
record(AuditAction.USER_EDIT, request, AuditTarget.of_user(after), data)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.post,
|
||||
"",
|
||||
@@ -119,7 +155,15 @@ def add_user(
|
||||
role=coerced_role,
|
||||
)
|
||||
|
||||
return UserSchema.model_validate(db_user_handler.add_user(user))
|
||||
created_user = db_user_handler.add_user(user)
|
||||
record(
|
||||
AuditAction.USER_CREATE,
|
||||
request,
|
||||
AuditTarget.of_user(created_user),
|
||||
{"role": created_user.role},
|
||||
)
|
||||
|
||||
return UserSchema.model_validate(created_user)
|
||||
|
||||
|
||||
@protected_route(
|
||||
@@ -186,6 +230,7 @@ def create_invite_link(
|
||||
|
||||
@router.post("/register", status_code=status.HTTP_201_CREATED)
|
||||
def create_user_from_invite(
|
||||
request: Request,
|
||||
username: str = Body(..., embed=True),
|
||||
email: str = Body(..., embed=True),
|
||||
password: str = Body(..., embed=True),
|
||||
@@ -242,6 +287,12 @@ def create_user_from_invite(
|
||||
)
|
||||
|
||||
created_user = db_user_handler.add_user(user)
|
||||
record(
|
||||
AuditAction.USER_REGISTER,
|
||||
AuditActor.for_user(created_user, ip_address=client_ip(request)),
|
||||
AuditTarget.of_user(created_user),
|
||||
{"role": created_user.role, "via": "invite"},
|
||||
)
|
||||
|
||||
return UserSchema.model_validate(created_user)
|
||||
|
||||
@@ -505,11 +556,13 @@ async def update_user(
|
||||
actor_id=request.user.id,
|
||||
)
|
||||
|
||||
before = db_user
|
||||
db_user = db_user_handler.get_user(id)
|
||||
if not db_user:
|
||||
msg = f"Username with id {id} not found"
|
||||
log.error(msg)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=msg)
|
||||
_record_user_edit(request, before, db_user, cleaned_data)
|
||||
|
||||
return UserSchema.model_validate(db_user)
|
||||
|
||||
@@ -550,6 +603,12 @@ async def delete_user(
|
||||
)
|
||||
|
||||
db_user_handler.delete_user(id)
|
||||
record(
|
||||
AuditAction.USER_DELETE,
|
||||
request,
|
||||
AuditTarget.of_user(user),
|
||||
{"role": user.role},
|
||||
)
|
||||
|
||||
# Remove the user's folder
|
||||
user_avatar_path = fs_asset_handler.build_avatar_path(user=user)
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
"""The audit log: what users and background jobs did, recorded best effort."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from starlette.requests import HTTPConnection
|
||||
|
||||
from config import AUDIT_LOG_RETENTION_DAYS
|
||||
from handler.database import db_audit_event_handler, db_user_handler
|
||||
from handler.redis_handler import sync_cache
|
||||
from logger.logger import log
|
||||
from models.audit_event import (
|
||||
AUDIT_DATA_MAX_LENGTH,
|
||||
AUDIT_NAME_MAX_LENGTH,
|
||||
AuditAction,
|
||||
AuditActorKind,
|
||||
AuditEvent,
|
||||
AuditTargetType,
|
||||
)
|
||||
from models.collection import Collection, SmartCollection
|
||||
from utils.auth import current_device_id
|
||||
from utils.datetime import to_utc
|
||||
from utils.rate_limit import count_in_window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.firmware import Firmware
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomDeletionTarget, RomVisibilityLabel
|
||||
from models.user import User
|
||||
|
||||
# Lists in `data` (rom ids, changed fields) keep this many entries.
|
||||
MAX_DATA_LIST_LENGTH: Final = 50
|
||||
# A download repeated within this window, by the same caller, is the same download.
|
||||
DOWNLOAD_DEDUPE_SECONDS: Final = 10 * 60
|
||||
_CLAIM_KEY_PREFIX: Final = "romm:audit:once"
|
||||
_RANGE_START = re.compile(r"^\s*bytes\s*=\s*(\d*)\s*-")
|
||||
|
||||
|
||||
def _clip_name(name: str | None) -> str | None:
|
||||
if name is None:
|
||||
return None
|
||||
return name.replace("\x00", "")[:AUDIT_NAME_MAX_LENGTH]
|
||||
|
||||
|
||||
def client_ip(conn: HTTPConnection) -> str | None:
|
||||
return conn.client.host if conn.client else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuditActor:
|
||||
kind: AuditActorKind
|
||||
user_id: int | None = None
|
||||
name: str | None = None
|
||||
ip_address: str | None = None
|
||||
device_id: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_request(cls, conn: HTTPConnection) -> AuditActor:
|
||||
"""Whoever made the request, anonymous when no account is behind it."""
|
||||
user = conn.scope.get("user")
|
||||
if (
|
||||
user is None
|
||||
or not user.is_authenticated
|
||||
or getattr(user, "is_kiosk_guest", False)
|
||||
):
|
||||
return cls.anonymous(client_ip(conn))
|
||||
return cls.for_user(
|
||||
user, ip_address=client_ip(conn), device_id=current_device_id(conn)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def anonymous(cls, ip_address: str | None) -> AuditActor:
|
||||
return cls(AuditActorKind.ANONYMOUS, ip_address=ip_address)
|
||||
|
||||
@classmethod
|
||||
def for_user(
|
||||
cls,
|
||||
user: User,
|
||||
*,
|
||||
ip_address: str | None = None,
|
||||
device_id: str | None = None,
|
||||
) -> AuditActor:
|
||||
return cls(
|
||||
AuditActorKind.USER,
|
||||
user_id=user.id,
|
||||
name=user.username,
|
||||
ip_address=ip_address,
|
||||
device_id=device_id,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def for_user_id(cls, user_id: int | None) -> AuditActor:
|
||||
"""The user a background job ran for, or the system when nobody started it."""
|
||||
if user_id is None:
|
||||
return SYSTEM_ACTOR
|
||||
try:
|
||||
user = db_user_handler.get_user(user_id)
|
||||
except Exception: # noqa: BLE001 - the name is a nicety
|
||||
user = None
|
||||
if user is None:
|
||||
return cls(AuditActorKind.USER)
|
||||
return cls.for_user(user)
|
||||
|
||||
|
||||
SYSTEM_ACTOR: Final = AuditActor(AuditActorKind.SYSTEM)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuditTarget:
|
||||
type: AuditTargetType
|
||||
id: int | str | None
|
||||
name: str | None
|
||||
|
||||
@classmethod
|
||||
def of_rom(cls, rom: Rom | RomVisibilityLabel | RomDeletionTarget) -> AuditTarget:
|
||||
return cls(AuditTargetType.ROM, rom.id, rom.name or rom.fs_name)
|
||||
|
||||
@classmethod
|
||||
def of_platform(cls, platform: Platform) -> AuditTarget:
|
||||
return cls(
|
||||
AuditTargetType.PLATFORM,
|
||||
platform.id,
|
||||
platform.custom_name or platform.name,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def of_collection(cls, collection: Collection | SmartCollection) -> AuditTarget:
|
||||
kind = (
|
||||
AuditTargetType.SMART_COLLECTION
|
||||
if isinstance(collection, SmartCollection)
|
||||
else AuditTargetType.COLLECTION
|
||||
)
|
||||
return cls(kind, collection.id, collection.name)
|
||||
|
||||
@classmethod
|
||||
def of_firmware(cls, firmware: Firmware) -> AuditTarget:
|
||||
return cls(AuditTargetType.FIRMWARE, firmware.id, firmware.file_name)
|
||||
|
||||
@classmethod
|
||||
def of_user(cls, user: User) -> AuditTarget:
|
||||
return cls(AuditTargetType.USER, user.id, user.username)
|
||||
|
||||
|
||||
# A target or data that takes a lookup can be passed as a function, so the
|
||||
# lookup runs inside the recorder's error handling, and only if it records.
|
||||
TargetSource = AuditTarget | Callable[[], AuditTarget | None] | None
|
||||
DataSource = dict[str, Any] | Callable[[], dict[str, Any]] | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuditDraft:
|
||||
action: AuditAction
|
||||
actor: AuditActor
|
||||
target: TargetSource = None
|
||||
data: DataSource = None
|
||||
occurred_at: datetime | None = None
|
||||
|
||||
|
||||
def _unset(value: Any) -> Any:
|
||||
# A save writes "" over a column that was null, which is no change.
|
||||
return None if value == "" else value
|
||||
|
||||
|
||||
def _value(source: object, field: str) -> Any:
|
||||
if isinstance(source, Mapping):
|
||||
return _unset(source.get(field))
|
||||
return _unset(getattr(source, field, None))
|
||||
|
||||
|
||||
def changed_fields(before: object, after: object, fields: Iterable[str]) -> list[str]:
|
||||
"""The fields whose value differs; `after` may be a mapping of the fields given."""
|
||||
return [
|
||||
field
|
||||
for field in fields
|
||||
if (not isinstance(after, Mapping) or field in after)
|
||||
and _value(before, field) != _value(after, field)
|
||||
]
|
||||
|
||||
|
||||
def change(before: object, after: object, field: str) -> dict[str, Any]:
|
||||
"""One field's change, in the shape the event log reads it."""
|
||||
return {"from": _value(before, field), "to": _value(after, field)}
|
||||
|
||||
|
||||
def _encode(data: dict[str, Any]) -> str:
|
||||
# PostgreSQL refuses NUL in JSON text.
|
||||
return json.dumps(data, default=str).replace("\\u0000", "")
|
||||
|
||||
|
||||
def _normalize_data(data: dict[str, Any] | None) -> dict[str, Any]:
|
||||
if not data:
|
||||
return {}
|
||||
clipped: dict[str, Any] = {}
|
||||
for key, value in data.items():
|
||||
if isinstance(value, (list, tuple, set, frozenset)):
|
||||
value = list(value)
|
||||
if len(value) > MAX_DATA_LIST_LENGTH:
|
||||
clipped["truncated"] = True
|
||||
value = value[:MAX_DATA_LIST_LENGTH]
|
||||
clipped[key] = value
|
||||
encoded = _encode(clipped)
|
||||
if len(encoded) > AUDIT_DATA_MAX_LENGTH:
|
||||
scalars = {k: v for k, v in clipped.items() if not isinstance(v, (list, dict))}
|
||||
encoded = _encode({**scalars, "truncated": True})
|
||||
if len(encoded) > AUDIT_DATA_MAX_LENGTH:
|
||||
return {"truncated": True}
|
||||
return json.loads(encoded)
|
||||
|
||||
|
||||
def _to_row(draft: AuditDraft) -> AuditEvent:
|
||||
actor = draft.actor
|
||||
target = draft.target() if callable(draft.target) else draft.target
|
||||
data = draft.data() if callable(draft.data) else draft.data
|
||||
return AuditEvent(
|
||||
occurred_at=to_utc(draft.occurred_at or datetime.now(timezone.utc)),
|
||||
actor_kind=actor.kind,
|
||||
actor_id=actor.user_id,
|
||||
actor_name=_clip_name(actor.name),
|
||||
action=draft.action,
|
||||
target_type=target.type if target else None,
|
||||
target_id=str(target.id) if target and target.id is not None else None,
|
||||
target_name=_clip_name(target.name) if target else None,
|
||||
ip_address=actor.ip_address[:45] if actor.ip_address else None,
|
||||
device_id=_clip_name(actor.device_id),
|
||||
data=_normalize_data(data),
|
||||
)
|
||||
|
||||
|
||||
def record_many(drafts: Sequence[AuditDraft]) -> bool:
|
||||
"""Store events, logging rather than raising when they can't; False then."""
|
||||
try:
|
||||
cutoff = (
|
||||
datetime.now(timezone.utc) - timedelta(days=AUDIT_LOG_RETENTION_DAYS)
|
||||
if AUDIT_LOG_RETENTION_DAYS > 0
|
||||
else None
|
||||
)
|
||||
rows = [
|
||||
_to_row(draft)
|
||||
for draft in drafts
|
||||
if cutoff is None
|
||||
or draft.occurred_at is None
|
||||
or to_utc(draft.occurred_at) >= cutoff
|
||||
]
|
||||
if rows:
|
||||
db_audit_event_handler.add_events(rows)
|
||||
except Exception: # noqa: BLE001 - never fail the action being recorded
|
||||
log.exception(
|
||||
f"Failed to record audit events {[draft.action for draft in drafts]}"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def record(
|
||||
action: AuditAction,
|
||||
actor: AuditActor | HTTPConnection,
|
||||
target: TargetSource = None,
|
||||
data: DataSource = None,
|
||||
*,
|
||||
occurred_at: datetime | None = None,
|
||||
) -> bool:
|
||||
"""Record one event; `actor` may be the request, whose caller then acts."""
|
||||
if isinstance(actor, HTTPConnection):
|
||||
actor = AuditActor.from_request(actor)
|
||||
return record_many([AuditDraft(action, actor, target, data, occurred_at)])
|
||||
|
||||
|
||||
def _claim_key(key: str) -> str:
|
||||
# Keys carry caller-supplied text (usernames, file ids), so they're hashed to
|
||||
# a fixed size.
|
||||
return f"{_CLAIM_KEY_PREFIX}:{hashlib.sha256(key.encode()).hexdigest()}"
|
||||
|
||||
|
||||
def claim_once(key: str, window_seconds: int) -> bool:
|
||||
"""Whether this is the first claim on `key` within the window; True if Redis fails."""
|
||||
try:
|
||||
return bool(sync_cache.set(_claim_key(key), 1, nx=True, ex=window_seconds))
|
||||
except Exception: # noqa: BLE001 - better a duplicate than a gap
|
||||
# The key may hold a failed sign-in's text, so only its kind is logged.
|
||||
log.exception(f"Failed to claim a {key.split(':', 1)[0]} audit key")
|
||||
return True
|
||||
|
||||
|
||||
def release_claim(key: str) -> None:
|
||||
"""Give up a claim whose event couldn't be stored, so a retry records it."""
|
||||
try:
|
||||
sync_cache.delete(_claim_key(key))
|
||||
except Exception: # noqa: BLE001 - the claim expires with its window anyway
|
||||
log.exception(f"Failed to release a {key.split(':', 1)[0]} audit key")
|
||||
|
||||
|
||||
def within_budget(key: str, limit: int, window_seconds: int) -> bool:
|
||||
"""Whether `key` has been counted at most `limit` times this window; True if Redis fails."""
|
||||
try:
|
||||
return count_in_window(_claim_key(key), window_seconds) <= limit
|
||||
except Exception: # noqa: BLE001 - better a duplicate than a gap
|
||||
log.exception(f"Failed to count a {key.split(':', 1)[0]} audit key")
|
||||
return True
|
||||
|
||||
|
||||
def _starts_a_transfer(range_header: str | None) -> bool:
|
||||
"""Whether a request fetches a file from its first byte, rather than resuming it."""
|
||||
if range_header is None:
|
||||
return True
|
||||
match = _RANGE_START.match(range_header)
|
||||
# An unparseable Range is ignored by the server, which sends the whole file.
|
||||
if match is None:
|
||||
return True
|
||||
# `bytes=-500` asks for the last 500 bytes, which is no start either.
|
||||
start = match.group(1)
|
||||
return start != "" and start.strip("0") == ""
|
||||
|
||||
|
||||
def record_download(
|
||||
conn: HTTPConnection,
|
||||
target: TargetSource,
|
||||
dedupe_key: str,
|
||||
data: dict[str, Any] | None = None,
|
||||
*,
|
||||
action: AuditAction = AuditAction.ROM_DOWNLOAD,
|
||||
) -> None:
|
||||
"""Record a download once, however many range requests and retries it takes."""
|
||||
if conn.scope.get("method") != "GET" or not _starts_a_transfer(
|
||||
conn.headers.get("range")
|
||||
):
|
||||
return
|
||||
actor = AuditActor.from_request(conn)
|
||||
caller = actor.user_id if actor.user_id is not None else actor.ip_address
|
||||
key = f"download:{caller}:{dedupe_key}"
|
||||
if not claim_once(key, DOWNLOAD_DEDUPE_SECONDS):
|
||||
return
|
||||
user_agent = conn.headers.get("user-agent")
|
||||
if not record(
|
||||
action,
|
||||
actor,
|
||||
target,
|
||||
{**(data or {}), "user_agent": user_agent[:255] if user_agent else None},
|
||||
):
|
||||
release_claim(key)
|
||||
@@ -528,7 +528,9 @@ class OAuthHandler:
|
||||
|
||||
class OpenIDHandler:
|
||||
async def get_current_active_user_from_openid_token(self, token: Any):
|
||||
from handler.audit_handler import SYSTEM_ACTOR, AuditActor, AuditTarget, record
|
||||
from handler.database import db_user_handler
|
||||
from models.audit_event import AuditAction
|
||||
from models.user import Role, User
|
||||
|
||||
if not OIDC_ENABLED:
|
||||
@@ -620,8 +622,25 @@ class OpenIDHandler:
|
||||
role=role,
|
||||
)
|
||||
user = db_user_handler.add_user(new_user)
|
||||
record(
|
||||
AuditAction.USER_REGISTER,
|
||||
AuditActor.for_user(user),
|
||||
AuditTarget.of_user(user),
|
||||
{"role": user.role, "via": "oidc"},
|
||||
)
|
||||
elif claims_provided and user.role != role:
|
||||
previous_role = user.role
|
||||
user = db_user_handler.update_user(user.id, {"role": role})
|
||||
record(
|
||||
AuditAction.USER_EDIT,
|
||||
SYSTEM_ACTOR,
|
||||
AuditTarget.of_user(user),
|
||||
{
|
||||
"changed": ["role"],
|
||||
"role": {"from": previous_role, "to": role},
|
||||
"via": "oidc",
|
||||
},
|
||||
)
|
||||
|
||||
if not user.enabled:
|
||||
raise UserDisabledException
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from .audit_events_handler import DBAuditEventsHandler
|
||||
from .client_tokens_handler import DBClientTokensHandler
|
||||
from .collections_handler import DBCollectionsHandler
|
||||
from .container_adoptions_handler import DBContainerAdoptionsHandler
|
||||
@@ -20,6 +21,7 @@ from .stats_handler import DBStatsHandler
|
||||
from .sync_sessions_handler import DBSyncSessionsHandler
|
||||
from .users_handler import DBUsersHandler
|
||||
|
||||
db_audit_event_handler = DBAuditEventsHandler()
|
||||
db_client_token_handler = DBClientTokensHandler()
|
||||
db_collection_handler = DBCollectionsHandler()
|
||||
db_container_adoption_handler = DBContainerAdoptionsHandler()
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
from collections.abc import Collection, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ColumnElement, Select, String, cast, delete, func, or_, select
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.audit_event import AuditCategory, AuditEvent, actions_in
|
||||
from models.device import Device
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
from utils.database import LIKE_ESCAPE_CHAR, escape_like
|
||||
|
||||
from .base_handler import DBBaseHandler, affected_rows
|
||||
|
||||
|
||||
def _with_actor():
|
||||
# Name and avatar only, the rest of a user row is large JSON.
|
||||
return joinedload(AuditEvent.actor).load_only(
|
||||
User.id, User.username, User.avatar_path, User.updated_at
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuditEventFilters:
|
||||
actor_ids: Collection[int] | None = None
|
||||
actions: Collection[str] | None = None
|
||||
# Narrows `actions`, or stands for them when none are given.
|
||||
categories: Collection[AuditCategory] | None = None
|
||||
target_type: str | None = None
|
||||
target_id: str | None = None
|
||||
since: datetime | None = None
|
||||
until: datetime | None = None
|
||||
# Pins a paged read to the rows that existed when its first page was fetched.
|
||||
max_id: int | None = None
|
||||
search: str | None = None
|
||||
hidden_rom_ids: Collection[int] = field(default_factory=frozenset)
|
||||
hidden_platform_ids: Collection[int] = field(default_factory=frozenset)
|
||||
|
||||
|
||||
def _not_targeting(
|
||||
target_type: str, ids: Collection[int] | Select
|
||||
) -> ColumnElement[bool]:
|
||||
"""Events other than those on the given targets of one type."""
|
||||
excluded = ids if isinstance(ids, Select) else [str(i) for i in ids]
|
||||
return or_(
|
||||
AuditEvent.target_type.is_(None),
|
||||
AuditEvent.target_type != target_type,
|
||||
AuditEvent.target_id.is_(None),
|
||||
AuditEvent.target_id.not_in(excluded),
|
||||
)
|
||||
|
||||
|
||||
class DBAuditEventsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def add_events(
|
||||
self,
|
||||
events: Sequence[AuditEvent],
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.add_all(events)
|
||||
|
||||
@begin_session
|
||||
def get_events(
|
||||
self,
|
||||
filters: AuditEventFilters,
|
||||
limit: int,
|
||||
offset: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> tuple[list[tuple[AuditEvent, str | None]], int, int | None]:
|
||||
"""A page of events, newest first, each with its device's name, the total,
|
||||
and the highest id among the matches for later pages to be pinned to."""
|
||||
clauses: list[ColumnElement[bool]] = []
|
||||
if filters.actor_ids is not None:
|
||||
clauses.append(AuditEvent.actor_id.in_(filters.actor_ids))
|
||||
actions = set(filters.actions) if filters.actions is not None else None
|
||||
if filters.categories:
|
||||
in_categories: set[str] = {
|
||||
a for c in filters.categories for a in actions_in(c)
|
||||
}
|
||||
actions = in_categories if actions is None else actions & in_categories
|
||||
if actions is not None:
|
||||
clauses.append(AuditEvent.action.in_(actions))
|
||||
if filters.target_type is not None:
|
||||
clauses.append(AuditEvent.target_type == filters.target_type)
|
||||
if filters.target_id is not None:
|
||||
clauses.append(AuditEvent.target_id == filters.target_id)
|
||||
if filters.since is not None:
|
||||
clauses.append(AuditEvent.occurred_at >= filters.since)
|
||||
if filters.until is not None:
|
||||
clauses.append(AuditEvent.occurred_at < filters.until)
|
||||
if filters.max_id is not None:
|
||||
clauses.append(AuditEvent.id <= filters.max_id)
|
||||
if filters.search:
|
||||
like = f"%{escape_like(filters.search.lower())}%"
|
||||
clauses.append(
|
||||
or_(
|
||||
*(
|
||||
func.lower(column).like(like, escape=LIKE_ESCAPE_CHAR)
|
||||
for column in (
|
||||
AuditEvent.actor_name,
|
||||
AuditEvent.target_name,
|
||||
AuditEvent.ip_address,
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
if filters.hidden_rom_ids:
|
||||
clauses.append(_not_targeting("rom", filters.hidden_rom_ids))
|
||||
if filters.hidden_platform_ids:
|
||||
clauses.append(_not_targeting("platform", filters.hidden_platform_ids))
|
||||
# A platform's hide covers its roms too.
|
||||
clauses.append(
|
||||
_not_targeting(
|
||||
"rom",
|
||||
select(cast(Rom.id, String)).where(
|
||||
Rom.platform_id.in_(filters.hidden_platform_ids)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
total, highest_id = session.execute(
|
||||
select(func.count(), func.max(AuditEvent.id)).where(*clauses)
|
||||
).one()
|
||||
rows = session.execute(
|
||||
select(AuditEvent, Device.name)
|
||||
.options(_with_actor())
|
||||
.outerjoin(Device, Device.id == AuditEvent.device_id)
|
||||
.where(*clauses)
|
||||
.order_by(AuditEvent.occurred_at.desc(), AuditEvent.id.desc())
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
).all()
|
||||
return (
|
||||
[(event, device_name) for event, device_name in rows],
|
||||
total or 0,
|
||||
highest_id,
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def delete_batch_before(
|
||||
self,
|
||||
cutoff: datetime,
|
||||
batch_size: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> int:
|
||||
"""Delete up to `batch_size` of the oldest events from before `cutoff`."""
|
||||
# Ids first: MySQL refuses a LIMIT inside an IN subquery.
|
||||
ids = session.scalars(
|
||||
select(AuditEvent.id)
|
||||
.where(AuditEvent.occurred_at < cutoff)
|
||||
.order_by(AuditEvent.occurred_at)
|
||||
.limit(batch_size)
|
||||
).all()
|
||||
if not ids:
|
||||
return 0
|
||||
result = session.execute(
|
||||
delete(AuditEvent)
|
||||
.where(AuditEvent.id.in_(ids))
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
return affected_rows(result)
|
||||
@@ -3,8 +3,11 @@ from typing import Literal, NotRequired, TypedDict
|
||||
|
||||
from pydash import compact
|
||||
|
||||
from handler.audit_handler import AuditActor, AuditDraft, AuditTarget, record_many
|
||||
from handler.auth.permissions import ResolvedPermissions
|
||||
from handler.database import db_device_handler, db_play_session_handler, db_rom_handler
|
||||
from logger.logger import log
|
||||
from models.audit_event import AuditAction, AuditActorKind
|
||||
from models.play_session import PlaySession
|
||||
from models.rom import RomUserStatus
|
||||
from utils.datetime import to_utc
|
||||
@@ -69,17 +72,29 @@ def ingest_play_sessions(
|
||||
device_id: str | None = None,
|
||||
sync_session_id: int | None = None,
|
||||
max_future_minutes: int = 5,
|
||||
perms: ResolvedPermissions | None,
|
||||
) -> PlaySessionIngestSummary:
|
||||
"""Core play session ingestion logic shared by the standalone endpoint and sync complete."""
|
||||
"""Core play session ingestion logic shared by the standalone endpoint and sync complete.
|
||||
|
||||
Args:
|
||||
perms: The caller's permissions, a rom hidden from them counting as
|
||||
unknown; None when its roms were already checked.
|
||||
"""
|
||||
max_future = datetime.now(timezone.utc) + timedelta(minutes=max_future_minutes)
|
||||
resolved_device_id = _resolve_device(device_id, user_id)
|
||||
|
||||
# Bulk-resolve all referenced rom IDs in one query
|
||||
candidate_rom_ids = {e["rom_id"] for e in entries}
|
||||
valid_rom_ids: set[int] = set()
|
||||
if candidate_rom_ids:
|
||||
found_roms = db_rom_handler.get_roms_by_ids(compact(candidate_rom_ids))
|
||||
valid_rom_ids = {r.id for r in found_roms}
|
||||
found_roms = (
|
||||
{
|
||||
r.id: r
|
||||
for r in db_rom_handler.get_roms_by_ids(compact(candidate_rom_ids))
|
||||
if perms is None or perms.can_see_rom(r.id, r.platform_id)
|
||||
}
|
||||
if candidate_rom_ids
|
||||
else {}
|
||||
)
|
||||
valid_rom_ids = set(found_roms)
|
||||
|
||||
# Phase 1: Validate and resolve each entry
|
||||
results: list[PlaySessionIngestResult] = []
|
||||
@@ -149,6 +164,26 @@ def ingest_play_sessions(
|
||||
# Phase 4: Side effects
|
||||
_apply_play_to_rom_user(rom_user_updates, user_id)
|
||||
|
||||
actor = AuditActor(
|
||||
AuditActorKind.USER,
|
||||
user_id=user_id,
|
||||
name=username,
|
||||
device_id=resolved_device_id,
|
||||
)
|
||||
record_many(
|
||||
[
|
||||
AuditDraft(
|
||||
AuditAction.ROM_PLAY,
|
||||
actor,
|
||||
AuditTarget.of_rom(found_roms[ps.rom_id]),
|
||||
{"duration_ms": ps.duration_ms, "save_slot": ps.save_slot},
|
||||
occurred_at=to_utc(ps.start_time),
|
||||
)
|
||||
for _, _, ps in to_insert
|
||||
if ps.rom_id is not None
|
||||
]
|
||||
)
|
||||
|
||||
if resolved_device_id is not None:
|
||||
db_device_handler.update_last_seen(
|
||||
device_id=resolved_device_id, user_id=user_id
|
||||
|
||||
@@ -290,6 +290,8 @@ async def record_play_session(session: dict[str, Any]) -> None:
|
||||
"duration_ms": duration_ms,
|
||||
}
|
||||
],
|
||||
# The rom was checked against the user when the stream was claimed.
|
||||
perms=None,
|
||||
)
|
||||
except Exception:
|
||||
log.exception("failed to record play session")
|
||||
|
||||
@@ -31,6 +31,7 @@ from config import (
|
||||
SENTRY_DSN,
|
||||
)
|
||||
from endpoints.activity import router as activity_router
|
||||
from endpoints.audit_events import router as audit_events_router
|
||||
from endpoints.auth import router as auth_router
|
||||
from endpoints.client_tokens import router as client_tokens_router
|
||||
from endpoints.collections import router as collections_router
|
||||
@@ -184,6 +185,7 @@ app.middleware("http")(set_context_middleware)
|
||||
app.include_router(heartbeat_router, prefix="/api")
|
||||
app.include_router(auth_router, prefix="/api")
|
||||
app.include_router(activity_router, prefix="/api")
|
||||
app.include_router(audit_events_router, prefix="/api")
|
||||
app.include_router(user_router, prefix="/api")
|
||||
app.include_router(client_tokens_router, prefix="/api")
|
||||
app.include_router(notifications_router, prefix="/api")
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from sqlalchemy import TIMESTAMP, ForeignKey, Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import BaseModel, utc_now
|
||||
from utils.database import CustomJSON
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.user import User
|
||||
|
||||
|
||||
class AuditAction(enum.StrEnum):
|
||||
"""What someone, or a background job, did; the client builds its sentence from `data`."""
|
||||
|
||||
ROM_DOWNLOAD = "rom.download"
|
||||
ROM_BULK_DOWNLOAD = "rom.bulk_download"
|
||||
ROM_PLAYER_LOAD = "rom.player_load"
|
||||
ROM_PLAY = "rom.play"
|
||||
|
||||
ROM_UPLOAD = "rom.upload"
|
||||
ROM_CREATE = "rom.create"
|
||||
ROM_EDIT = "rom.edit"
|
||||
ROM_MATCH = "rom.match"
|
||||
ROM_UNMATCH = "rom.unmatch"
|
||||
ROM_DELETE = "rom.delete"
|
||||
ROM_FILE_DELETE = "rom.file_delete"
|
||||
PLATFORM_CREATE = "platform.create"
|
||||
PLATFORM_EDIT = "platform.edit"
|
||||
PLATFORM_DELETE = "platform.delete"
|
||||
FIRMWARE_UPLOAD = "firmware.upload"
|
||||
FIRMWARE_DELETE = "firmware.delete"
|
||||
CONFIG_UPDATE = "config.update"
|
||||
|
||||
COLLECTION_CREATE = "collection.create"
|
||||
COLLECTION_EDIT = "collection.edit"
|
||||
COLLECTION_DELETE = "collection.delete"
|
||||
COLLECTION_ADD_ROMS = "collection.add_roms"
|
||||
COLLECTION_REMOVE_ROMS = "collection.remove_roms"
|
||||
SMART_COLLECTION_CREATE = "smart_collection.create"
|
||||
SMART_COLLECTION_EDIT = "smart_collection.edit"
|
||||
SMART_COLLECTION_DELETE = "smart_collection.delete"
|
||||
|
||||
SCAN_START = "scan.start"
|
||||
SCAN_FINISH = "scan.finish"
|
||||
SCAN_STOP = "scan.stop"
|
||||
TASK_RUN = "task.run"
|
||||
|
||||
AUTH_LOGIN = "auth.login"
|
||||
AUTH_LOGIN_FAILED = "auth.login_failed"
|
||||
AUTH_PASSWORD_RESET_REQUEST = "auth.password_reset_request" # nosec B105
|
||||
AUTH_PASSWORD_RESET = "auth.password_reset" # nosec B105
|
||||
USER_CREATE = "user.create"
|
||||
USER_REGISTER = "user.register"
|
||||
USER_EDIT = "user.edit"
|
||||
USER_DELETE = "user.delete"
|
||||
USER_PERMISSIONS_EDIT = "user.permissions_edit"
|
||||
PERMISSION_GROUP_CREATE = "permission_group.create"
|
||||
PERMISSION_GROUP_EDIT = "permission_group.edit"
|
||||
PERMISSION_GROUP_DELETE = "permission_group.delete"
|
||||
VISIBILITY_HIDE = "visibility.hide"
|
||||
VISIBILITY_UNHIDE = "visibility.unhide"
|
||||
CLIENT_TOKEN_CREATE = "client_token.create" # nosec B105
|
||||
CLIENT_TOKEN_REGENERATE = "client_token.regenerate" # nosec B105
|
||||
CLIENT_TOKEN_REVOKE = "client_token.revoke" # nosec B105
|
||||
DEVICE_APPROVE = "device.approve"
|
||||
|
||||
|
||||
class AuditCategory(enum.StrEnum):
|
||||
CONSUMPTION = "consumption"
|
||||
LIBRARY = "library"
|
||||
COLLECTIONS = "collections"
|
||||
OPERATIONS = "operations"
|
||||
SECURITY = "security"
|
||||
|
||||
|
||||
class AuditActorKind(enum.StrEnum):
|
||||
USER = "user"
|
||||
# Someone with no account behind them: a kiosk visitor, an unauthenticated
|
||||
# download, a login attempt for a username that doesn't exist.
|
||||
ANONYMOUS = "anonymous"
|
||||
# A scheduled job or the filesystem watcher.
|
||||
SYSTEM = "system"
|
||||
|
||||
|
||||
class AuditTargetType(enum.StrEnum):
|
||||
ROM = "rom"
|
||||
PLATFORM = "platform"
|
||||
FIRMWARE = "firmware"
|
||||
COLLECTION = "collection"
|
||||
SMART_COLLECTION = "smart_collection"
|
||||
VIRTUAL_COLLECTION = "virtual_collection"
|
||||
USER = "user"
|
||||
PERMISSION_GROUP = "permission_group"
|
||||
CLIENT_TOKEN = "client_token" # nosec B105
|
||||
DEVICE = "device"
|
||||
TASK = "task"
|
||||
CONFIG = "config"
|
||||
|
||||
|
||||
_CATEGORY_PREFIXES: Final[dict[str, AuditCategory]] = {
|
||||
"rom": AuditCategory.LIBRARY,
|
||||
"platform": AuditCategory.LIBRARY,
|
||||
"firmware": AuditCategory.LIBRARY,
|
||||
"config": AuditCategory.LIBRARY,
|
||||
"collection": AuditCategory.COLLECTIONS,
|
||||
"smart_collection": AuditCategory.COLLECTIONS,
|
||||
"scan": AuditCategory.OPERATIONS,
|
||||
"task": AuditCategory.OPERATIONS,
|
||||
"auth": AuditCategory.SECURITY,
|
||||
"user": AuditCategory.SECURITY,
|
||||
"permission_group": AuditCategory.SECURITY,
|
||||
"visibility": AuditCategory.SECURITY,
|
||||
"client_token": AuditCategory.SECURITY,
|
||||
"device": AuditCategory.SECURITY,
|
||||
}
|
||||
|
||||
_CONSUMPTION_ACTIONS: Final = frozenset(
|
||||
{
|
||||
AuditAction.ROM_DOWNLOAD,
|
||||
AuditAction.ROM_BULK_DOWNLOAD,
|
||||
AuditAction.ROM_PLAYER_LOAD,
|
||||
AuditAction.ROM_PLAY,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def category_of(action: str) -> AuditCategory | None:
|
||||
"""The group an action is filtered under; None for an action no longer defined."""
|
||||
if action in _CONSUMPTION_ACTIONS:
|
||||
return AuditCategory.CONSUMPTION
|
||||
return _CATEGORY_PREFIXES.get(action.partition(".")[0])
|
||||
|
||||
|
||||
def actions_in(category: AuditCategory) -> list[AuditAction]:
|
||||
return [action for action in AuditAction if category_of(action) == category]
|
||||
|
||||
|
||||
AUDIT_NAME_MAX_LENGTH: Final = 255
|
||||
AUDIT_ACTION_MAX_LENGTH: Final = 64
|
||||
# Cap on `data` as serialized JSON; longer lists are clipped before this applies.
|
||||
AUDIT_DATA_MAX_LENGTH: Final = 4096
|
||||
|
||||
|
||||
class AuditEvent(BaseModel):
|
||||
__tablename__ = "audit_events"
|
||||
__table_args__ = (
|
||||
Index("ix_audit_events_occurred_at", "occurred_at"),
|
||||
# Leads with `actor_id`, so it also backs that foreign key.
|
||||
Index("ix_audit_events_actor_occurred", "actor_id", "occurred_at"),
|
||||
Index("ix_audit_events_target", "target_type", "target_id", "occurred_at"),
|
||||
Index("ix_audit_events_action_occurred", "action", "occurred_at"),
|
||||
{"extend_existing": True},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
# When it happened, which for a play session reported later is its start.
|
||||
occurred_at: Mapped[datetime] = mapped_column(
|
||||
TIMESTAMP(timezone=True), default=utc_now
|
||||
)
|
||||
actor_kind: Mapped[str] = mapped_column(String(16))
|
||||
actor_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
# Names are copied in so an event still reads after its user or target is gone.
|
||||
actor_name: Mapped[str | None] = mapped_column(
|
||||
String(AUDIT_NAME_MAX_LENGTH), nullable=True
|
||||
)
|
||||
action: Mapped[str] = mapped_column(String(AUDIT_ACTION_MAX_LENGTH))
|
||||
target_type: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
# A string with no foreign key: device and task ids aren't integers, and
|
||||
# targets get deleted.
|
||||
target_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
target_name: Mapped[str | None] = mapped_column(
|
||||
String(AUDIT_NAME_MAX_LENGTH), nullable=True
|
||||
)
|
||||
ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True)
|
||||
device_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
data: Mapped[dict[str, Any]] = mapped_column(CustomJSON(), default=dict)
|
||||
|
||||
actor: Mapped[User | None] = relationship(lazy="raise", foreign_keys=[actor_id])
|
||||
@@ -15,6 +15,7 @@ from tasks.manual.recompute_save_content_hashes import (
|
||||
)
|
||||
from tasks.manual.sync_folder_scan import sync_folder_scan_task
|
||||
from tasks.scheduled.build_recommendations import build_recommendations_task
|
||||
from tasks.scheduled.cleanup_audit_log import cleanup_audit_log_task
|
||||
from tasks.scheduled.cleanup_netplay import cleanup_netplay_task
|
||||
from tasks.scheduled.cleanup_orphaned_resources import cleanup_orphaned_resources_task
|
||||
from tasks.scheduled.cleanup_upload_tmp import cleanup_upload_tmp_task
|
||||
@@ -43,6 +44,7 @@ SCHEDULED_TASKS: Final[dict[str, PeriodicTask]] = {
|
||||
"cleanup_orphaned_resources": cleanup_orphaned_resources_task,
|
||||
"cleanup_netplay": cleanup_netplay_task,
|
||||
"cleanup_upload_tmp": cleanup_upload_tmp_task,
|
||||
"cleanup_audit_log": cleanup_audit_log_task,
|
||||
"sync_retroachievements_progress": sync_retroachievements_progress_task,
|
||||
"sync_push_pull": sync_push_pull_task,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Final
|
||||
|
||||
from config import AUDIT_LOG_RETENTION_DAYS
|
||||
from handler.database import db_audit_event_handler
|
||||
from logger.logger import log
|
||||
from tasks.tasks import PeriodicTask, TaskType
|
||||
|
||||
# Each batch is its own short transaction, so the table stays writable meanwhile.
|
||||
DELETE_BATCH_SIZE: Final = 5000
|
||||
|
||||
|
||||
class CleanupAuditLogTask(PeriodicTask):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
title="Scheduled audit log cleanup",
|
||||
description=f"Removes audit log events older than {AUDIT_LOG_RETENTION_DAYS} days",
|
||||
task_type=TaskType.CLEANUP,
|
||||
enabled=AUDIT_LOG_RETENTION_DAYS > 0,
|
||||
manual_run=False,
|
||||
cron_string="30 4 * * *",
|
||||
)
|
||||
|
||||
async def run(self) -> int:
|
||||
if not self.enabled:
|
||||
return 0
|
||||
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=AUDIT_LOG_RETENTION_DAYS)
|
||||
deleted = 0
|
||||
while True:
|
||||
batch = db_audit_event_handler.delete_batch_before(
|
||||
cutoff, DELETE_BATCH_SIZE
|
||||
)
|
||||
deleted += batch
|
||||
if batch < DELETE_BATCH_SIZE:
|
||||
break
|
||||
if deleted:
|
||||
log.info(f"Removed {deleted} audit log events older than {cutoff}")
|
||||
return deleted
|
||||
|
||||
|
||||
cleanup_audit_log_task = CleanupAuditLogTask()
|
||||
@@ -0,0 +1,11 @@
|
||||
from handler.database import db_audit_event_handler
|
||||
from handler.database.audit_events_handler import AuditEventFilters
|
||||
from models.audit_event import AuditEvent
|
||||
|
||||
|
||||
def recorded_events() -> list[AuditEvent]:
|
||||
"""Every audit event recorded so far, newest first."""
|
||||
rows, _, _ = db_audit_event_handler.get_events(
|
||||
AuditEventFilters(), limit=200, offset=0
|
||||
)
|
||||
return [event for event, _ in rows]
|
||||
@@ -31,6 +31,7 @@ from handler.database import (
|
||||
)
|
||||
from handler.database.base_handler import sync_engine
|
||||
from models.assets import MemoryCard, MemoryCardVersion, Save, Screenshot, State
|
||||
from models.audit_event import AuditEvent
|
||||
from models.client_token import ClientToken
|
||||
from models.container_adoption import StreamingContainerAdoption
|
||||
from models.device import Device
|
||||
@@ -133,6 +134,7 @@ def setup_database():
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_database():
|
||||
with session.begin() as s:
|
||||
s.query(AuditEvent).delete(synchronize_session="evaluate")
|
||||
s.query(Notification).delete(synchronize_session="evaluate")
|
||||
s.query(NotificationChannel).delete(synchronize_session="evaluate")
|
||||
s.query(PlaySession).delete(synchronize_session="evaluate")
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
from tests.audit_events import recorded_events
|
||||
|
||||
from endpoints import roms as rom_endpoints
|
||||
from handler.database import (
|
||||
db_audit_event_handler,
|
||||
db_collection_handler,
|
||||
db_rom_handler,
|
||||
)
|
||||
from models.collection import Collection
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from models.user import User
|
||||
|
||||
|
||||
def _auth(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
class TestRomContent:
|
||||
def test_a_download_is_recorded_once(
|
||||
self, client: TestClient, access_token: str, rom: Rom, rom_file: RomFile
|
||||
):
|
||||
for _ in range(2):
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers=_auth(access_token),
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.download"
|
||||
assert event.actor_name == "test_admin"
|
||||
assert (event.target_type, event.target_id) == ("rom", str(rom.id))
|
||||
assert event.data["file_name"] == "test_rom.zip"
|
||||
|
||||
def test_a_players_fetch_is_a_player_load(
|
||||
self, client: TestClient, access_token: str, rom: Rom, rom_file: RomFile
|
||||
):
|
||||
for purpose in ("play", "download"):
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
params={"purpose": purpose},
|
||||
headers=_auth(access_token),
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
assert sorted(event.action for event in recorded_events()) == [
|
||||
"rom.download",
|
||||
"rom.player_load",
|
||||
]
|
||||
|
||||
def test_a_file_missing_from_disk_is_not_a_download(
|
||||
self,
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
rom_file: RomFile,
|
||||
mocker,
|
||||
):
|
||||
mocker.patch.object(rom_endpoints, "DEV_MODE", True)
|
||||
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers=_auth(access_token),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_a_resumed_transfer_is_not_a_new_download(
|
||||
self, client: TestClient, access_token: str, rom: Rom, rom_file: RomFile
|
||||
):
|
||||
client.get(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers={**_auth(access_token), "Range": "bytes=1024-"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_a_head_request_is_not_a_download(
|
||||
self, client: TestClient, access_token: str, rom: Rom, rom_file: RomFile
|
||||
):
|
||||
client.head(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers=_auth(access_token),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_a_failing_recorder_still_serves_the_file(
|
||||
self,
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
rom_file: RomFile,
|
||||
mocker,
|
||||
):
|
||||
mocker.patch.object(
|
||||
db_audit_event_handler, "add_events", side_effect=RuntimeError("down")
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers=_auth(access_token),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
|
||||
class TestRomFileContent:
|
||||
def _add_file(self, rom: Rom, name: str, category: RomFileCategory) -> RomFile:
|
||||
return db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
rom_id=rom.id,
|
||||
file_name=name,
|
||||
file_path=f"{rom.fs_path}/{rom.fs_name}",
|
||||
file_size_bytes=10,
|
||||
category=category,
|
||||
)
|
||||
)
|
||||
|
||||
def test_a_game_file_is_a_download(
|
||||
self, client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
file = self._add_file(rom, "game.bin", RomFileCategory.GAME)
|
||||
|
||||
client.get(
|
||||
f"/api/roms/{file.id}/files/content/game.bin",
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.download"
|
||||
assert event.data["file_ids"] == [file.id]
|
||||
|
||||
def test_a_manual_read_in_the_viewer_is_not(
|
||||
self, client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
file = self._add_file(rom, "manual.pdf", RomFileCategory.MANUAL)
|
||||
|
||||
client.get(
|
||||
f"/api/roms/{file.id}/files/content/manual.pdf",
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
|
||||
def test_a_bulk_download_is_one_event_on_its_platform(
|
||||
client: TestClient, access_token: str, platform: Platform, rom_file: RomFile
|
||||
):
|
||||
response = client.get(
|
||||
"/api/roms/download",
|
||||
params={"platform_id": platform.id},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.bulk_download"
|
||||
assert (event.target_type, event.target_id) == ("platform", str(platform.id))
|
||||
assert event.data["count"] == 1
|
||||
|
||||
|
||||
def test_someone_elses_private_collection_is_kept_by_id_only(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
editor_user: User,
|
||||
rom: Rom,
|
||||
rom_file: RomFile,
|
||||
):
|
||||
private = db_collection_handler.add_collection(
|
||||
Collection(
|
||||
name="Secret shelf",
|
||||
description="",
|
||||
is_public=False,
|
||||
is_favorite=False,
|
||||
user_id=editor_user.id,
|
||||
)
|
||||
)
|
||||
db_collection_handler.add_roms_to_collection(private.id, [rom.id])
|
||||
|
||||
client.get(
|
||||
"/api/roms/download",
|
||||
params={"collection_id": private.id},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert (event.target_id, event.target_name) == (str(private.id), None)
|
||||
@@ -32,6 +32,7 @@ from endpoints.sockets.scan import (
|
||||
from exceptions.fs_exceptions import FolderStructureNotMatchException
|
||||
from exceptions.socket_exceptions import ScanStoppedException
|
||||
from handler import notification_handler
|
||||
from handler.audit_handler import SYSTEM_ACTOR
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database.roms_handler import SyncedRomFiles
|
||||
from handler.filesystem.roms_handler import (
|
||||
@@ -43,6 +44,7 @@ from handler.filesystem.roms_handler import (
|
||||
from handler.rom_files import RomFilesRefresh
|
||||
from handler.scan_handler import MetadataSource, ScanType
|
||||
from handler.scan_jobs import SCAN_PLATFORMS_FUNC
|
||||
from models.audit_event import AuditAction
|
||||
from models.firmware import Firmware
|
||||
from models.notification import NotificationKind, NotificationLevel
|
||||
from models.platform import Platform
|
||||
@@ -289,6 +291,45 @@ class TestScanEndNotification:
|
||||
notify_scan_end.assert_not_awaited()
|
||||
|
||||
|
||||
class TestScanAudit:
|
||||
"""A scan leaves a start and an end in the audit log, however it ends."""
|
||||
|
||||
@pytest.fixture
|
||||
def record(self, mocker):
|
||||
mocker.patch.object(scan_module, "notify_scan_end", AsyncMock())
|
||||
return mocker.patch.object(scan_module, "record")
|
||||
|
||||
async def test_a_finished_scan_records_its_start_and_stats(self, patched, record):
|
||||
await scan_platforms(platform_ids=[], metadata_sources=[])
|
||||
|
||||
start, finish = record.call_args_list
|
||||
assert start.args[:2] == (AuditAction.SCAN_START, SYSTEM_ACTOR)
|
||||
assert finish.args[0] == AuditAction.SCAN_FINISH
|
||||
assert finish.kwargs["data"]["status"] == "completed"
|
||||
assert "new_roms" in finish.kwargs["data"]
|
||||
|
||||
async def test_a_failed_scan_records_the_error(self, patched, record, mocker):
|
||||
mocker.patch.object(
|
||||
scan_module, "_identify_platform", side_effect=RuntimeError("boom")
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
await scan_platforms(platform_ids=[], metadata_sources=[])
|
||||
|
||||
data = record.call_args.kwargs["data"]
|
||||
assert (data["status"], data["error"]) == ("failed", "boom")
|
||||
|
||||
async def test_a_stopped_scan_says_so(self, patched, record, mocker):
|
||||
mocker.patch.object(
|
||||
scan_module, "_identify_platform", side_effect=ScanStoppedException()
|
||||
)
|
||||
mocker.patch.object(scan_module, "redis_client")
|
||||
|
||||
await scan_platforms(platform_ids=[], metadata_sources=[])
|
||||
|
||||
assert record.call_args.kwargs["data"]["status"] == "stopped"
|
||||
|
||||
|
||||
class TestNotifyScanEnd:
|
||||
"""Who hears about a scan's end depends on who started it."""
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import status
|
||||
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_audit_event_handler, db_user_handler
|
||||
from models.audit_event import AuditAction, AuditActorKind, AuditEvent
|
||||
from models.user import User
|
||||
|
||||
|
||||
def _add(
|
||||
actor: User | None,
|
||||
action: AuditAction = AuditAction.ROM_DOWNLOAD,
|
||||
minutes_ago: int = 0,
|
||||
**overrides: Any,
|
||||
) -> AuditEvent:
|
||||
fields: dict[str, Any] = {
|
||||
"occurred_at": datetime.now(timezone.utc) - timedelta(minutes=minutes_ago),
|
||||
"actor_kind": AuditActorKind.USER if actor else AuditActorKind.SYSTEM,
|
||||
"actor_id": actor.id if actor else None,
|
||||
"actor_name": actor.username if actor else None,
|
||||
"action": action,
|
||||
"target_type": "rom",
|
||||
"target_id": "1",
|
||||
"target_name": "Super Mario Bros.",
|
||||
"data": {},
|
||||
}
|
||||
event = AuditEvent(**{**fields, **overrides})
|
||||
db_audit_event_handler.add_events([event])
|
||||
return event
|
||||
|
||||
|
||||
def _auth(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _ids(response) -> list[int]:
|
||||
return [event["id"] for event in response.json()["items"]]
|
||||
|
||||
|
||||
class TestAdminReadsEveryone:
|
||||
def test_lists_every_users_events_newest_first(
|
||||
self, client, access_token, admin_user, viewer_user
|
||||
):
|
||||
older = _add(viewer_user, minutes_ago=5)
|
||||
newer = _add(admin_user, AuditAction.ROM_EDIT, minutes_ago=1)
|
||||
system = _add(None, AuditAction.SCAN_START, minutes_ago=3)
|
||||
|
||||
response = client.get("/api/audit-events", headers=_auth(access_token))
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
body = response.json()
|
||||
assert body["total"] == 3
|
||||
assert _ids(response) == [newer.id, system.id, older.id]
|
||||
first = body["items"][0]
|
||||
assert first["action"] == "rom.edit"
|
||||
assert first["category"] == "library"
|
||||
assert first["actor"]["username"] == admin_user.username
|
||||
assert first["target_name"] == "Super Mario Bros."
|
||||
assert body["items"][1]["actor_kind"] == "system"
|
||||
assert body["items"][1]["actor"] is None
|
||||
|
||||
def test_filters_by_actor(self, client, access_token, admin_user, viewer_user):
|
||||
_add(admin_user)
|
||||
theirs = _add(viewer_user)
|
||||
|
||||
response = client.get(
|
||||
"/api/audit-events",
|
||||
params={"actor_id": viewer_user.id},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(response) == [theirs.id]
|
||||
|
||||
def test_an_admin_token_without_users_read_sees_only_its_own(
|
||||
self, client, admin_user, viewer_user
|
||||
):
|
||||
own = _add(admin_user)
|
||||
_add(viewer_user)
|
||||
token = oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": admin_user.username,
|
||||
"iss": "romm:oauth",
|
||||
"scopes": " ".join(
|
||||
s for s in admin_user.oauth_scopes if s != "users.read"
|
||||
),
|
||||
},
|
||||
expires_delta=timedelta(minutes=5),
|
||||
)
|
||||
|
||||
response = client.get("/api/audit-events", headers=_auth(token))
|
||||
|
||||
assert _ids(response) == [own.id]
|
||||
|
||||
|
||||
class TestNonAdminReadsOwn:
|
||||
def test_is_held_to_their_own_events_whatever_they_ask_for(
|
||||
self, client, viewer_access_token, admin_user, viewer_user
|
||||
):
|
||||
_add(admin_user)
|
||||
own = _add(viewer_user)
|
||||
|
||||
response = client.get(
|
||||
"/api/audit-events",
|
||||
params={"actor_id": admin_user.id},
|
||||
headers=_auth(viewer_access_token),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert _ids(response) == [own.id]
|
||||
|
||||
def test_needs_a_login(self, client):
|
||||
response = client.get("/api/audit-events")
|
||||
|
||||
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
|
||||
|
||||
class TestFilters:
|
||||
def test_category_narrows_to_its_actions(self, client, access_token, admin_user):
|
||||
play = _add(admin_user, AuditAction.ROM_PLAY)
|
||||
_add(admin_user, AuditAction.ROM_EDIT)
|
||||
_add(admin_user, AuditAction.AUTH_LOGIN)
|
||||
|
||||
response = client.get(
|
||||
"/api/audit-events",
|
||||
params={"category": "consumption"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(response) == [play.id]
|
||||
|
||||
def test_category_and_action_intersect(self, client, access_token, admin_user):
|
||||
_add(admin_user, AuditAction.ROM_PLAY)
|
||||
_add(admin_user, AuditAction.ROM_EDIT)
|
||||
|
||||
response = client.get(
|
||||
"/api/audit-events",
|
||||
params={"category": "consumption", "action": "rom.edit"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(response) == []
|
||||
|
||||
def test_date_range_is_inclusive_then_exclusive(
|
||||
self, client, access_token, admin_user
|
||||
):
|
||||
now = datetime.now(timezone.utc)
|
||||
_add(admin_user, minutes_ago=120)
|
||||
inside = _add(admin_user, minutes_ago=60)
|
||||
_add(admin_user, minutes_ago=0)
|
||||
|
||||
response = client.get(
|
||||
"/api/audit-events",
|
||||
params={
|
||||
"since": (now - timedelta(minutes=90)).isoformat(),
|
||||
"until": (now - timedelta(minutes=30)).isoformat(),
|
||||
},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(response) == [inside.id]
|
||||
|
||||
def test_search_matches_names_and_addresses(
|
||||
self, client, access_token, admin_user, viewer_user
|
||||
):
|
||||
by_viewer = _add(viewer_user, target_name="Tetris")
|
||||
zelda = _add(admin_user, target_name="The Legend of Zelda")
|
||||
from_lan = _add(None, target_name="Doom", ip_address="192.168.1.20")
|
||||
|
||||
viewer = client.get(
|
||||
"/api/audit-events",
|
||||
params={"search": "VIEWER"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
target = client.get(
|
||||
"/api/audit-events",
|
||||
params={"search": "zelda"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
address = client.get(
|
||||
"/api/audit-events",
|
||||
params={"search": "192.168.1"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(viewer) == [by_viewer.id]
|
||||
assert _ids(target) == [zelda.id]
|
||||
assert _ids(address) == [from_lan.id]
|
||||
|
||||
def test_pages_stay_pinned_to_max_id(self, client, access_token, admin_user):
|
||||
newest = _add(admin_user, minutes_ago=1)
|
||||
# Recorded after `newest` but happened before it, like a synced play.
|
||||
synced = _add(admin_user, AuditAction.ROM_PLAY, minutes_ago=30)
|
||||
|
||||
first = client.get(
|
||||
"/api/audit-events",
|
||||
params={"limit": 1},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
_add(admin_user)
|
||||
second = client.get(
|
||||
"/api/audit-events",
|
||||
params={"limit": 1, "offset": 1, "max_id": first.json()["max_id"]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert _ids(first) == [newest.id]
|
||||
assert first.json()["max_id"] == synced.id
|
||||
assert _ids(second) == [synced.id]
|
||||
assert second.json()["total"] == 2
|
||||
|
||||
|
||||
def test_an_event_outlives_its_actor(client, access_token, viewer_user):
|
||||
event = _add(viewer_user)
|
||||
db_user_handler.delete_user(viewer_user.id)
|
||||
|
||||
response = client.get("/api/audit-events", headers=_auth(access_token))
|
||||
|
||||
[item] = response.json()["items"]
|
||||
assert item["id"] == event.id
|
||||
assert item["actor"] is None
|
||||
assert item["actor_name"] == "test_viewer"
|
||||
@@ -0,0 +1,247 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
from tests.audit_events import recorded_events
|
||||
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.database import (
|
||||
db_collection_handler,
|
||||
db_rom_handler,
|
||||
)
|
||||
from handler.filesystem import fs_firmware_handler, fs_resource_handler
|
||||
from models.collection import Collection
|
||||
from models.firmware import Firmware
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
|
||||
|
||||
def _auth(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _collection(user: User, *, favorite: bool = False) -> Collection:
|
||||
return db_collection_handler.add_collection(
|
||||
Collection(
|
||||
name="Favorites" if favorite else "Shelf",
|
||||
description="",
|
||||
is_public=False,
|
||||
is_favorite=favorite,
|
||||
user_id=user.id,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestRomUpdate:
|
||||
def test_an_edit_records_what_changed(
|
||||
self, client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
response = client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
headers=_auth(access_token),
|
||||
data={"name": "Metroid"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.edit"
|
||||
assert event.target_name == "Metroid"
|
||||
assert event.data["changed"] == ["name"]
|
||||
assert event.data["name"] == {"from": "test_rom", "to": "Metroid"}
|
||||
|
||||
def test_a_new_provider_id_is_a_manual_match(
|
||||
self, client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
headers=_auth(access_token),
|
||||
data={"sgdb_id": "4242"},
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.match"
|
||||
assert event.data["providers"] == {"sgdb_id": 4242}
|
||||
|
||||
def test_saving_without_changes_records_nothing(
|
||||
self, client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
headers=_auth(access_token),
|
||||
data={"name": "test_rom"},
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_an_unmatch_records_the_ids_it_dropped(
|
||||
self, client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
db_rom_handler.update_rom(rom.id, {"sgdb_id": 4242})
|
||||
|
||||
client.put(
|
||||
f"/api/roms/{rom.id}",
|
||||
params={"unmatch_metadata": True},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.unmatch"
|
||||
assert event.data["providers"] == {"sgdb_id": 4242}
|
||||
|
||||
|
||||
def test_a_deleted_rom_keeps_its_name(client: TestClient, access_token: str, rom: Rom):
|
||||
response = client.post(
|
||||
"/api/roms/delete",
|
||||
headers=_auth(access_token),
|
||||
json={"roms": [rom.id]},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.delete"
|
||||
assert (event.target_id, event.target_name) == (str(rom.id), "test_rom")
|
||||
assert event.data["deleted_from_fs"] is False
|
||||
|
||||
|
||||
def test_a_rom_whose_resources_stay_behind_is_still_deleted(
|
||||
client: TestClient, access_token: str, rom: Rom, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
fs_resource_handler, "remove_directory", side_effect=PermissionError("busy")
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"/api/roms/delete",
|
||||
headers=_auth(access_token),
|
||||
json={"roms": [rom.id]},
|
||||
)
|
||||
|
||||
assert response.json()["failed_ids"] == [rom.id]
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.delete"
|
||||
|
||||
|
||||
def test_a_firmware_file_left_on_disk_is_not_deleted_from_it(
|
||||
client: TestClient, access_token: str, firmware: Firmware, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
fs_firmware_handler, "remove_file", side_effect=PermissionError("read-only")
|
||||
)
|
||||
|
||||
client.post(
|
||||
"/api/firmware/delete",
|
||||
headers=_auth(access_token),
|
||||
json={"firmware": [firmware.id], "delete_from_fs": [firmware.id]},
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "firmware.delete"
|
||||
assert event.data["deleted_from_fs"] is False
|
||||
|
||||
|
||||
def test_a_platform_rename_is_an_edit(
|
||||
client: TestClient, access_token: str, platform: Platform
|
||||
):
|
||||
client.put(
|
||||
f"/api/platforms/{platform.id}",
|
||||
headers=_auth(access_token),
|
||||
json={"custom_name": "Famicom"},
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "platform.edit"
|
||||
assert event.target_name == "Famicom"
|
||||
assert event.data["changed"] == ["custom_name"]
|
||||
|
||||
|
||||
def test_a_config_change_names_its_setting(client: TestClient, access_token: str):
|
||||
with patch.object(cm, "add_exclusion"):
|
||||
client.post(
|
||||
"/api/config/exclude",
|
||||
headers=_auth(access_token),
|
||||
json={
|
||||
"exclusion_type": "EXCLUDED_SINGLE_FILES",
|
||||
"exclusion_value": "README.txt",
|
||||
},
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "config.update"
|
||||
assert event.data == {
|
||||
"setting": "exclusion",
|
||||
"op": "add",
|
||||
"type": "EXCLUDED_SINGLE_FILES",
|
||||
"value": "README.txt",
|
||||
}
|
||||
|
||||
|
||||
class TestCollections:
|
||||
def test_creating_one_is_recorded(self, client: TestClient, access_token: str):
|
||||
client.post(
|
||||
"/api/collections",
|
||||
data={"name": "Shelf"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "collection.create"
|
||||
assert event.target_name == "Shelf"
|
||||
|
||||
def test_adding_roms_counts_them(
|
||||
self, client: TestClient, access_token: str, admin_user: User, rom: Rom
|
||||
):
|
||||
collection = _collection(admin_user)
|
||||
|
||||
client.post(
|
||||
f"/api/collections/{collection.id}/roms",
|
||||
json={"rom_ids": [rom.id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "collection.add_roms"
|
||||
assert event.data == {"count": 1, "rom_ids": [rom.id]}
|
||||
|
||||
@pytest.mark.parametrize("method", ["post", "delete"])
|
||||
def test_games_that_change_nothing_are_not_recorded(
|
||||
self,
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
admin_user: User,
|
||||
rom: Rom,
|
||||
method: str,
|
||||
):
|
||||
collection = _collection(admin_user)
|
||||
if method == "post":
|
||||
db_collection_handler.add_roms_to_collection(collection.id, [rom.id])
|
||||
|
||||
client.request(
|
||||
method.upper(),
|
||||
f"/api/collections/{collection.id}/roms",
|
||||
json={"rom_ids": [rom.id] if method == "post" else [999999]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
@pytest.mark.parametrize("method", ["post", "delete"])
|
||||
def test_a_favourite_toggle_is_not(
|
||||
self,
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
admin_user: User,
|
||||
rom: Rom,
|
||||
method: str,
|
||||
):
|
||||
favorites = _collection(admin_user, favorite=True)
|
||||
|
||||
client.request(
|
||||
method.upper(),
|
||||
f"/api/collections/{favorites.id}/roms",
|
||||
json={"rom_ids": [rom.id]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
@@ -5,11 +5,20 @@ import pytest
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
from tests.audit_events import recorded_events
|
||||
|
||||
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_device_handler, db_play_session_handler, db_rom_handler
|
||||
from handler.database import (
|
||||
db_audit_event_handler,
|
||||
db_device_handler,
|
||||
db_play_session_handler,
|
||||
db_rom_handler,
|
||||
)
|
||||
from handler.database.audit_events_handler import AuditEventFilters
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.device import Device
|
||||
from models.permission import HiddenEntity, PermEntity
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomUserStatus
|
||||
from models.user import User
|
||||
@@ -213,6 +222,59 @@ class TestPlaySessionIngest:
|
||||
assert response.json()["created_count"] == 1
|
||||
|
||||
|
||||
class TestPlaySessionAudit:
|
||||
def test_each_new_session_of_a_known_rom_is_a_play(
|
||||
self, client, access_token: str, device: Device, rom: Rom
|
||||
):
|
||||
played = _session(rom_id=rom.id, duration_minutes=45)
|
||||
payload = _ingest(
|
||||
device_id=device.id,
|
||||
sessions=[played, _session(rom_id=None, start_offset_hours=-2)],
|
||||
)
|
||||
|
||||
for _ in range(2):
|
||||
client.post(
|
||||
"/api/play-sessions",
|
||||
json=payload,
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
|
||||
rows, total, _ = db_audit_event_handler.get_events(
|
||||
AuditEventFilters(), limit=10, offset=0
|
||||
)
|
||||
assert total == 1
|
||||
[(event, device_name)] = rows
|
||||
assert event.action == "rom.play"
|
||||
assert event.target_id == str(rom.id)
|
||||
assert event.device_id == device.id
|
||||
assert device_name == "Test Device"
|
||||
assert event.data["duration_ms"] == 45 * 60 * 1000
|
||||
started = datetime.fromisoformat(played["start_time"])
|
||||
# The column keeps whole seconds.
|
||||
assert abs(to_utc(event.occurred_at) - started) < timedelta(seconds=1)
|
||||
|
||||
def test_a_rom_hidden_from_the_player_is_not_theirs_to_log(
|
||||
self, client, editor_user: User, editor_access_token: str, rom: Rom
|
||||
):
|
||||
with sync_session.begin() as session:
|
||||
session.add(
|
||||
HiddenEntity(
|
||||
entity=PermEntity.ROMS, entity_id=rom.id, user_id=editor_user.id
|
||||
)
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"/api/play-sessions",
|
||||
json=_ingest(sessions=[_session(rom_id=rom.id)]),
|
||||
headers={"Authorization": f"Bearer {editor_access_token}"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
[played] = db_play_session_handler.get_sessions(user_id=editor_user.id)
|
||||
assert played.rom_id is None
|
||||
assert recorded_events() == []
|
||||
|
||||
|
||||
class TestPlaySessionDedup:
|
||||
def test_duplicate_batch(self, client, access_token: str, device: Device, rom: Rom):
|
||||
payload = _ingest(device_id=device.id, sessions=[_session(rom_id=rom.id)])
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import base64
|
||||
import uuid
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
from tests.audit_events import recorded_events
|
||||
|
||||
from endpoints import auth as auth_endpoints
|
||||
from endpoints import permissions as permission_endpoints
|
||||
from handler.auth import auth_handler
|
||||
from models.user import User
|
||||
from tasks.tasks import Task, TaskType
|
||||
|
||||
|
||||
def _auth(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _basic(username: str, password: str) -> dict[str, str]:
|
||||
encoded = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {encoded}"}
|
||||
|
||||
|
||||
class TestLogin:
|
||||
def test_a_session_login_names_its_device(
|
||||
self, client: TestClient, admin_user: User
|
||||
):
|
||||
response = client.post(
|
||||
"/api/login", headers=_basic("test_admin", "test_admin_password")
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
[event] = recorded_events()
|
||||
assert event.action == "auth.login"
|
||||
assert event.actor_id == admin_user.id
|
||||
assert event.device_id is not None
|
||||
assert event.data == {"method": "password"}
|
||||
|
||||
def test_repeated_failures_from_one_address_are_one_attempt(
|
||||
self, client: TestClient, admin_user: User
|
||||
):
|
||||
for _ in range(3):
|
||||
response = client.post("/api/login", headers=_basic("test_admin", "wrong"))
|
||||
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "auth.login_failed"
|
||||
assert event.actor_id == admin_user.id
|
||||
assert event.data["reason"] == "credentials"
|
||||
|
||||
def test_a_failure_for_an_unknown_name_keeps_no_name(self, client: TestClient):
|
||||
client.post("/api/login", headers=_basic("hunter2", "wrong"))
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.actor_kind == "anonymous"
|
||||
assert event.data["username"] is None
|
||||
|
||||
def test_one_address_cycling_usernames_is_capped(self, client: TestClient, mocker):
|
||||
mocker.patch.object(auth_endpoints, "LOGIN_FAILURES_PER_ADDRESS", 3)
|
||||
|
||||
for i in range(6):
|
||||
client.post("/api/login", headers=_basic(f"guess{i}", "wrong"))
|
||||
|
||||
assert len(recorded_events()) == 3
|
||||
|
||||
def test_repeated_reset_requests_are_one(
|
||||
self, client: TestClient, admin_user: User, mocker
|
||||
):
|
||||
mocker.patch.object(auth_handler, "send_password_reset_link")
|
||||
|
||||
for _ in range(2):
|
||||
client.post("/api/forgot-password", json={"username": "test_admin"})
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "auth.password_reset_request"
|
||||
assert (event.actor_kind, event.target_name) == ("anonymous", "test_admin")
|
||||
|
||||
def test_a_reset_request_is_recorded_when_its_link_fails(
|
||||
self, client: TestClient, admin_user: User, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
auth_handler, "send_password_reset_link", side_effect=RuntimeError("smtp")
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
client.post("/api/forgot-password", json={"username": "test_admin"})
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "auth.password_reset_request"
|
||||
|
||||
def test_a_token_grant_is_a_login(self, client: TestClient, admin_user: User):
|
||||
response = client.post(
|
||||
"/api/token",
|
||||
data={
|
||||
"grant_type": "password",
|
||||
"username": "test_admin",
|
||||
"password": "test_admin_password",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
[event] = recorded_events()
|
||||
assert (event.action, event.data["method"]) == ("auth.login", "token")
|
||||
|
||||
|
||||
class TestUsers:
|
||||
def test_a_role_change_records_both_roles(
|
||||
self, client: TestClient, access_token: str, viewer_user: User
|
||||
):
|
||||
client.put(
|
||||
f"/api/users/{viewer_user.id}",
|
||||
data={"role": "admin"},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "user.edit"
|
||||
assert event.target_name == "test_viewer"
|
||||
assert event.data["changed"] == ["role"]
|
||||
assert event.data["role"] == {"from": "user", "to": "admin"}
|
||||
|
||||
def test_saving_ui_settings_is_not_an_edit(
|
||||
self, client: TestClient, access_token: str, admin_user: User
|
||||
):
|
||||
client.put(
|
||||
f"/api/users/{admin_user.id}",
|
||||
data={"ui_settings": '{"theme": "dark"}'},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_a_deleted_user_keeps_their_name(
|
||||
self, client: TestClient, access_token: str, viewer_user: User
|
||||
):
|
||||
client.delete(f"/api/users/{viewer_user.id}", headers=_auth(access_token))
|
||||
|
||||
[event] = recorded_events()
|
||||
assert (event.action, event.target_name) == ("user.delete", "test_viewer")
|
||||
|
||||
|
||||
@patch("endpoints.tasks.has_live_worker", return_value=True)
|
||||
@patch(
|
||||
"endpoints.tasks.enqueue_task",
|
||||
return_value=Mock(
|
||||
id="job-1",
|
||||
created_at=None,
|
||||
enqueued_at=None,
|
||||
**{"get_status.return_value": "queued"},
|
||||
),
|
||||
)
|
||||
def test_a_manual_task_run_is_recorded(
|
||||
_enqueue, _worker, client: TestClient, access_token: str
|
||||
):
|
||||
task = Mock(spec=Task)
|
||||
task.title = "Cleanup"
|
||||
task.task_type = TaskType.CLEANUP
|
||||
task.can_run_manually = True
|
||||
with patch("endpoints.tasks.RUNNABLE_TASKS", {"cleanup": task}):
|
||||
client.post("/api/tasks/run/cleanup", headers=_auth(access_token))
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "task.run"
|
||||
assert (event.target_id, event.target_name) == ("cleanup", "Cleanup")
|
||||
assert event.data["job_id"] == "job-1"
|
||||
|
||||
|
||||
class TestClientTokens:
|
||||
@pytest.fixture
|
||||
def token_id(self, client: TestClient, access_token: str) -> int:
|
||||
response = client.post(
|
||||
"/api/client-tokens",
|
||||
json={"name": "Argosy", "scopes": ["roms.read"]},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
return response.json()["id"]
|
||||
|
||||
def test_creating_and_revoking_are_recorded(
|
||||
self, client: TestClient, access_token: str, token_id: int
|
||||
):
|
||||
client.delete(f"/api/client-tokens/{token_id}", headers=_auth(access_token))
|
||||
|
||||
revoke, create = recorded_events()
|
||||
assert create.action == "client_token.create"
|
||||
assert revoke.action == "client_token.revoke"
|
||||
assert revoke.target_name == "Argosy"
|
||||
assert revoke.data["scopes"] == ["roms.read"]
|
||||
|
||||
|
||||
def test_a_hide_succeeds_when_naming_it_for_the_log_fails(
|
||||
client: TestClient, access_token: str, viewer_user: User, rom, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
permission_endpoints, "_principal", side_effect=RuntimeError("db gone")
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_auth(access_token),
|
||||
json={"entity": "roms", "entity_id": rom.id, "user_id": viewer_user.id},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert recorded_events() == []
|
||||
|
||||
|
||||
def test_a_new_permission_group_is_recorded(client: TestClient, access_token: str):
|
||||
# Groups outlive a test, so the name has to be one no earlier run left behind.
|
||||
name = f"Kids {uuid.uuid4().hex[:8]}"
|
||||
client.post(
|
||||
"/api/permissions/groups",
|
||||
json={"name": name, "grants": []},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert (event.action, event.target_name) == ("permission_group.create", name)
|
||||
@@ -0,0 +1,98 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from handler.database import db_audit_event_handler, db_device_handler
|
||||
from handler.database.audit_events_handler import AuditEventFilters
|
||||
from models.audit_event import AuditAction, AuditActorKind, AuditCategory, AuditEvent
|
||||
from models.device import Device
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
|
||||
|
||||
def _add(minutes_ago: int = 0, **overrides) -> AuditEvent:
|
||||
event = AuditEvent(
|
||||
**{
|
||||
"occurred_at": datetime.now(timezone.utc) - timedelta(minutes=minutes_ago),
|
||||
"actor_kind": AuditActorKind.SYSTEM,
|
||||
"action": AuditAction.ROM_EDIT,
|
||||
"data": {},
|
||||
**overrides,
|
||||
}
|
||||
)
|
||||
db_audit_event_handler.add_events([event])
|
||||
return event
|
||||
|
||||
|
||||
def _ids(filters: AuditEventFilters) -> list[int]:
|
||||
rows, _, _ = db_audit_event_handler.get_events(filters, limit=50, offset=0)
|
||||
return [event.id for event, _ in rows]
|
||||
|
||||
|
||||
class TestHiddenTargets:
|
||||
def test_drops_events_on_roms_of_a_hidden_platform(self, rom: Rom):
|
||||
on_hidden = _add(target_type="rom", target_id=str(rom.id))
|
||||
elsewhere = _add(target_type="rom", target_id="999999")
|
||||
|
||||
ids = _ids(AuditEventFilters(hidden_platform_ids={rom.platform_id}))
|
||||
|
||||
assert on_hidden.id not in ids
|
||||
assert elsewhere.id in ids
|
||||
|
||||
def test_drops_events_on_hidden_roms_and_platforms_only(self):
|
||||
hidden_rom = _add(target_type="rom", target_id="7")
|
||||
visible_rom = _add(target_type="rom", target_id="8")
|
||||
hidden_platform = _add(target_type="platform", target_id="7")
|
||||
no_target = _add()
|
||||
|
||||
ids = _ids(AuditEventFilters(hidden_rom_ids={7}, hidden_platform_ids={7}))
|
||||
|
||||
assert hidden_rom.id not in ids
|
||||
assert hidden_platform.id not in ids
|
||||
assert set(ids) == {visible_rom.id, no_target.id}
|
||||
|
||||
|
||||
class TestCategories:
|
||||
def test_a_category_stands_for_its_actions(self):
|
||||
login = _add(action=AuditAction.AUTH_LOGIN)
|
||||
_add(action=AuditAction.ROM_EDIT)
|
||||
|
||||
assert _ids(AuditEventFilters(categories=[AuditCategory.SECURITY])) == [
|
||||
login.id
|
||||
]
|
||||
|
||||
def test_actions_outside_the_category_match_nothing(self):
|
||||
_add(action=AuditAction.ROM_EDIT)
|
||||
|
||||
filters = AuditEventFilters(
|
||||
actions=[AuditAction.ROM_EDIT], categories=[AuditCategory.SECURITY]
|
||||
)
|
||||
assert _ids(filters) == []
|
||||
|
||||
|
||||
def test_joins_the_device_name(admin_user: User):
|
||||
db_device_handler.add_device(
|
||||
Device(id="dev-1", user_id=admin_user.id, name="Steam Deck")
|
||||
)
|
||||
_add(device_id="dev-1")
|
||||
_add(device_id="gone")
|
||||
|
||||
rows, total, _ = db_audit_event_handler.get_events(
|
||||
AuditEventFilters(), limit=50, offset=0
|
||||
)
|
||||
|
||||
assert total == 2
|
||||
assert sorted(name or "" for _, name in rows) == ["", "Steam Deck"]
|
||||
|
||||
|
||||
class TestDeleteBatchBefore:
|
||||
def test_deletes_only_older_events_up_to_the_batch_size(self):
|
||||
old = [_add(minutes_ago=60 * 24 * 100) for _ in range(3)]
|
||||
recent = _add(minutes_ago=5)
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=90)
|
||||
|
||||
first = db_audit_event_handler.delete_batch_before(cutoff, batch_size=2)
|
||||
second = db_audit_event_handler.delete_batch_before(cutoff, batch_size=2)
|
||||
third = db_audit_event_handler.delete_batch_before(cutoff, batch_size=2)
|
||||
|
||||
assert (first, second, third) == (2, 1, 0)
|
||||
assert _ids(AuditEventFilters()) == [recent.id]
|
||||
assert all(event.id not in _ids(AuditEventFilters()) for event in old)
|
||||
@@ -0,0 +1,231 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from starlette.authentication import UnauthenticatedUser
|
||||
from starlette.requests import Request
|
||||
from tests.audit_events import recorded_events
|
||||
|
||||
from handler import audit_handler
|
||||
from handler.audit_handler import (
|
||||
AuditActor,
|
||||
AuditDraft,
|
||||
AuditTarget,
|
||||
claim_once,
|
||||
record,
|
||||
record_download,
|
||||
record_many,
|
||||
)
|
||||
from handler.database import db_audit_event_handler
|
||||
from handler.redis_handler import sync_cache
|
||||
from models.audit_event import AuditAction, AuditActorKind, AuditTargetType
|
||||
from models.user import User
|
||||
from utils.datetime import to_utc
|
||||
|
||||
ROM = AuditTarget(AuditTargetType.ROM, 12, "Metroid")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cache():
|
||||
sync_cache.flushall()
|
||||
yield
|
||||
sync_cache.flushall()
|
||||
|
||||
|
||||
def _request(
|
||||
user: Any = None,
|
||||
*,
|
||||
method: str = "GET",
|
||||
headers: dict[str, str] | None = None,
|
||||
state: dict[str, Any] | None = None,
|
||||
session: dict[str, Any] | None = None,
|
||||
) -> Request:
|
||||
return Request(
|
||||
{
|
||||
"type": "http",
|
||||
"method": method,
|
||||
"path": "/",
|
||||
"headers": [
|
||||
(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()
|
||||
],
|
||||
"client": ("203.0.113.9", 4242),
|
||||
"user": user if user is not None else UnauthenticatedUser(),
|
||||
"state": state or {},
|
||||
"session": session or {},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class TestActorFromRequest:
|
||||
def test_a_signed_in_user_with_their_session_device(self, admin_user: User):
|
||||
actor = AuditActor.from_request(
|
||||
_request(admin_user, session={"device_id": "web-1"})
|
||||
)
|
||||
|
||||
assert actor == AuditActor(
|
||||
AuditActorKind.USER,
|
||||
user_id=admin_user.id,
|
||||
name="test_admin",
|
||||
ip_address="203.0.113.9",
|
||||
device_id="web-1",
|
||||
)
|
||||
|
||||
def test_a_client_tokens_device_wins_over_the_session(self, admin_user: User):
|
||||
actor = AuditActor.from_request(
|
||||
_request(
|
||||
admin_user,
|
||||
state={"device_id": "deck"},
|
||||
session={"device_id": "web-1"},
|
||||
)
|
||||
)
|
||||
|
||||
assert actor.device_id == "deck"
|
||||
|
||||
def test_nobody_signed_in_is_anonymous(self):
|
||||
actor = AuditActor.from_request(_request())
|
||||
|
||||
assert actor == AuditActor(AuditActorKind.ANONYMOUS, ip_address="203.0.113.9")
|
||||
|
||||
def test_a_kiosk_visitor_is_anonymous(self):
|
||||
actor = AuditActor.from_request(_request(User.kiosk_mode_user()))
|
||||
|
||||
assert actor.kind == AuditActorKind.ANONYMOUS
|
||||
assert actor.user_id is None
|
||||
|
||||
|
||||
class TestRecord:
|
||||
def test_stores_the_actor_and_target_snapshots(self, admin_user: User):
|
||||
record(
|
||||
AuditAction.ROM_EDIT,
|
||||
AuditActor.for_user(admin_user),
|
||||
ROM,
|
||||
{"changed": ["name"]},
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.action == "rom.edit"
|
||||
assert event.actor_id == admin_user.id
|
||||
assert event.actor_name == "test_admin"
|
||||
assert (event.target_type, event.target_id, event.target_name) == (
|
||||
"rom",
|
||||
"12",
|
||||
"Metroid",
|
||||
)
|
||||
assert event.data == {"changed": ["name"]}
|
||||
|
||||
def test_a_storage_failure_never_reaches_the_caller(self, mocker):
|
||||
mocker.patch.object(
|
||||
db_audit_event_handler, "add_events", side_effect=RuntimeError("down")
|
||||
)
|
||||
|
||||
assert record(AuditAction.SCAN_START, audit_handler.SYSTEM_ACTOR) is False
|
||||
|
||||
def test_a_lookup_for_the_data_fails_inside_the_recorder(self):
|
||||
def lookup() -> dict[str, Any]:
|
||||
raise RuntimeError("db gone")
|
||||
|
||||
assert (
|
||||
record(AuditAction.SCAN_START, audit_handler.SYSTEM_ACTOR, data=lookup)
|
||||
is False
|
||||
)
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_clips_long_lists_and_drops_nul(self):
|
||||
record(
|
||||
AuditAction.COLLECTION_ADD_ROMS,
|
||||
audit_handler.SYSTEM_ACTOR,
|
||||
data={"rom_ids": list(range(80)), "name": "a\x00b"},
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.data["rom_ids"] == list(range(50))
|
||||
assert event.data["truncated"] is True
|
||||
assert event.data["name"] == "ab"
|
||||
|
||||
def test_drops_events_older_than_the_retention(self, mocker):
|
||||
mocker.patch.object(audit_handler, "AUDIT_LOG_RETENTION_DAYS", 90)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
record_many(
|
||||
[
|
||||
AuditDraft(
|
||||
AuditAction.ROM_PLAY,
|
||||
audit_handler.SYSTEM_ACTOR,
|
||||
occurred_at=now - timedelta(days=91),
|
||||
),
|
||||
AuditDraft(
|
||||
AuditAction.ROM_PLAY,
|
||||
audit_handler.SYSTEM_ACTOR,
|
||||
occurred_at=now - timedelta(days=1),
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
[event] = recorded_events()
|
||||
assert to_utc(event.occurred_at) > now - timedelta(days=2)
|
||||
|
||||
def test_for_user_id_without_a_user_is_the_system(self):
|
||||
assert AuditActor.for_user_id(None) == audit_handler.SYSTEM_ACTOR
|
||||
|
||||
|
||||
def test_claim_once_holds_within_its_window():
|
||||
assert claim_once("k", 60) is True
|
||||
assert claim_once("k", 60) is False
|
||||
assert claim_once("other", 60) is True
|
||||
|
||||
|
||||
class TestRecordDownload:
|
||||
@pytest.mark.parametrize(
|
||||
"range_header,counted",
|
||||
[
|
||||
(None, True),
|
||||
("bytes=0-", True),
|
||||
("bytes=0-1023", True),
|
||||
("bytes=100-", False),
|
||||
("bytes=-500", False),
|
||||
("not a range", True),
|
||||
("bytes=" + "9" * 5000 + "-", False),
|
||||
],
|
||||
)
|
||||
def test_only_a_transfer_from_the_first_byte_counts(
|
||||
self, admin_user: User, range_header: str | None, counted: bool
|
||||
):
|
||||
headers = {"range": range_header} if range_header else {}
|
||||
|
||||
record_download(_request(admin_user, headers=headers), ROM, "12")
|
||||
|
||||
assert len(recorded_events()) == (1 if counted else 0)
|
||||
|
||||
def test_a_head_request_never_counts(self, admin_user: User):
|
||||
record_download(_request(admin_user, method="HEAD"), ROM, "12")
|
||||
|
||||
assert recorded_events() == []
|
||||
|
||||
def test_a_repeat_within_the_window_counts_once(self, admin_user: User):
|
||||
record_download(_request(admin_user), ROM, "12")
|
||||
record_download(_request(admin_user), ROM, "12")
|
||||
record_download(_request(admin_user), ROM, "13")
|
||||
|
||||
assert len(recorded_events()) == 2
|
||||
|
||||
def test_a_download_that_failed_to_store_is_recorded_on_retry(
|
||||
self, admin_user: User, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
db_audit_event_handler, "add_events", side_effect=RuntimeError("down")
|
||||
)
|
||||
record_download(_request(admin_user), ROM, "12")
|
||||
mocker.stopall()
|
||||
|
||||
record_download(_request(admin_user), ROM, "12")
|
||||
|
||||
assert len(recorded_events()) == 1
|
||||
|
||||
def test_an_anonymous_download_is_kept_by_ip(self):
|
||||
record_download(_request(headers={"user-agent": "Tinfoil/19.0"}), ROM, "12")
|
||||
|
||||
[event] = recorded_events()
|
||||
assert event.actor_kind == "anonymous"
|
||||
assert event.actor_id is None
|
||||
assert event.ip_address == "203.0.113.9"
|
||||
assert event.data["user_agent"] == "Tinfoil/19.0"
|
||||
@@ -0,0 +1,46 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from tasks.scheduled import cleanup_audit_log
|
||||
from tasks.scheduled.cleanup_audit_log import CleanupAuditLogTask
|
||||
|
||||
|
||||
class TestCleanupAuditLogTask:
|
||||
def test_runs_daily_when_events_expire(self, mocker):
|
||||
mocker.patch.object(cleanup_audit_log, "AUDIT_LOG_RETENTION_DAYS", 90)
|
||||
task = CleanupAuditLogTask()
|
||||
|
||||
assert task.enabled is True
|
||||
assert task.cron_string == "30 4 * * *"
|
||||
|
||||
def test_is_off_when_events_are_kept_forever(self, mocker):
|
||||
mocker.patch.object(cleanup_audit_log, "AUDIT_LOG_RETENTION_DAYS", 0)
|
||||
|
||||
assert CleanupAuditLogTask().enabled is False
|
||||
|
||||
async def test_deletes_batches_until_one_comes_back_short(self, mocker):
|
||||
mocker.patch.object(cleanup_audit_log, "AUDIT_LOG_RETENTION_DAYS", 90)
|
||||
mocker.patch.object(cleanup_audit_log, "DELETE_BATCH_SIZE", 2)
|
||||
delete = mocker.patch.object(
|
||||
cleanup_audit_log.db_audit_event_handler,
|
||||
"delete_batch_before",
|
||||
side_effect=[2, 2, 1],
|
||||
)
|
||||
task = CleanupAuditLogTask()
|
||||
|
||||
deleted = await task.run()
|
||||
|
||||
assert deleted == 5
|
||||
assert delete.call_count == 3
|
||||
cutoff = delete.call_args.args[0]
|
||||
expected = datetime.now(timezone.utc) - timedelta(days=90)
|
||||
assert abs(cutoff - expected) < timedelta(minutes=1)
|
||||
|
||||
async def test_run_disabled_skips_the_cleanup(self, mocker):
|
||||
delete = mocker.patch.object(
|
||||
cleanup_audit_log.db_audit_event_handler, "delete_batch_before"
|
||||
)
|
||||
task = CleanupAuditLogTask()
|
||||
task.enabled = False
|
||||
|
||||
assert await task.run() == 0
|
||||
delete.assert_not_called()
|
||||
@@ -174,6 +174,7 @@ def _replay(connection: sa.Connection, filename: str) -> None:
|
||||
("0128_hltb_main_story_column.py", "roms"),
|
||||
("0130_notifications.py", "notifications"),
|
||||
("0131_notification_channels.py", "notification_channels"),
|
||||
("0132_audit_events.py", "audit_events"),
|
||||
],
|
||||
)
|
||||
def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op(
|
||||
|
||||
@@ -90,3 +90,27 @@ def test_env_template_documents_the_same_keepalive_default() -> None:
|
||||
|
||||
def test_init_script_records_the_rq_worker_pid_at_launch() -> None:
|
||||
assert 'echo "$!" >"/tmp/${name}.pid"' in INIT_SCRIPT.read_text()
|
||||
|
||||
|
||||
def _init_script_trusted_proxies() -> str:
|
||||
match = re.search(
|
||||
r'--forwarded-allow-ips="\$\{FORWARDED_ALLOW_IPS:-([^}]+)\}"',
|
||||
INIT_SCRIPT.read_text(),
|
||||
)
|
||||
assert match, "could not read the gunicorn --forwarded-allow-ips default"
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def test_client_addresses_are_trusted_only_from_private_proxies() -> None:
|
||||
"""A client can't choose its own address by sending X-Forwarded-For."""
|
||||
trusted = _init_script_trusted_proxies().split(",")
|
||||
|
||||
assert "*" not in trusted
|
||||
assert "127.0.0.1" in trusted
|
||||
|
||||
|
||||
def test_env_template_documents_the_same_trusted_proxies() -> None:
|
||||
assert (
|
||||
f"FORWARDED_ALLOW_IPS={_init_script_trusted_proxies()} "
|
||||
in ENV_TEMPLATE.read_text()
|
||||
)
|
||||
@@ -4,6 +4,7 @@ from http.cookies import SimpleCookie
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.requests import HTTPConnection
|
||||
from ua_parser import Result as UAResult
|
||||
from ua_parser import parse as parse_ua
|
||||
|
||||
@@ -18,6 +19,13 @@ from models.user import User
|
||||
from utils import json_module
|
||||
|
||||
|
||||
def current_device_id(conn: HTTPConnection) -> str | None:
|
||||
"""The device a request comes from: its client token's, else its web session's."""
|
||||
return getattr(conn.state, "device_id", None) or (
|
||||
conn.scope.get("session") or {}
|
||||
).get("device_id")
|
||||
|
||||
|
||||
async def get_session_from_environ(environ: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Resolve the auth session for a socket handshake.
|
||||
|
||||
|
||||
@@ -9,6 +9,17 @@ def get_client_ip(request: Request) -> str:
|
||||
return request.client.host if request.client else "unknown"
|
||||
|
||||
|
||||
def count_in_window(key: str, window_seconds: int) -> int:
|
||||
"""Count one call against a fixed window and return the window's count so far."""
|
||||
pipe = sync_cache.pipeline()
|
||||
pipe.incr(key)
|
||||
# NX in the same transaction as the INCR: only the call that starts a window
|
||||
# sets its TTL, and no counter can be left without one.
|
||||
pipe.expire(key, window_seconds, nx=True)
|
||||
count, _ = pipe.execute()
|
||||
return int(count)
|
||||
|
||||
|
||||
def enforce_rate_limit(
|
||||
key: str, *, max_requests: int, window_seconds: int, detail: str
|
||||
) -> None:
|
||||
@@ -21,14 +32,7 @@ def enforce_rate_limit(
|
||||
window_seconds: Window length.
|
||||
detail: Message returned with the 429.
|
||||
"""
|
||||
pipe = sync_cache.pipeline()
|
||||
pipe.incr(key)
|
||||
# NX in the same transaction as the INCR: only the call that starts a window
|
||||
# sets its TTL, and no counter can be left without one.
|
||||
pipe.expire(key, window_seconds, nx=True)
|
||||
count, _ = pipe.execute()
|
||||
|
||||
if count > max_requests:
|
||||
if count_in_window(key, window_seconds) > max_requests:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=detail,
|
||||
|
||||
@@ -138,7 +138,7 @@ start_bin_gunicorn() {
|
||||
"${wrap[@]}" gunicorn \
|
||||
--bind=0.0.0.0:"${DEV_PORT:-5000}" \
|
||||
--pid=/tmp/gunicorn.pid \
|
||||
--forwarded-allow-ips="*" \
|
||||
--forwarded-allow-ips="${FORWARDED_ALLOW_IPS:-127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,100.64.0.0/10,fc00::/7}" \
|
||||
--worker-class uvicorn_worker.UvicornWorker \
|
||||
--workers "${WEB_SERVER_CONCURRENCY:-4}" \
|
||||
--timeout "${WEB_SERVER_TIMEOUT:-300}" \
|
||||
|
||||
@@ -760,6 +760,23 @@ Token format: `rmm_` + 64 hex chars (32-byte random)
|
||||
|
||||
---
|
||||
|
||||
#### Audit Events
|
||||
|
||||
**Table:** `audit_events` (what users and background jobs did, kept `AUDIT_LOG_RETENTION_DAYS`)
|
||||
|
||||
| Column | Type | Notes |
|
||||
| ------------------------------------------------------- | ---------- | --------------------------------------------- |
|
||||
| `id` | Integer | PK |
|
||||
| `occurred_at` | Timestamp | For a synced play, when it started |
|
||||
| `actor_kind` | String(16) | `user`, `anonymous` or `system` |
|
||||
| `actor_id` | FK → users | `SET NULL` on delete |
|
||||
| `action` | String(64) | `AuditAction`, e.g. `rom.download` |
|
||||
| `actor_name`, `target_type`, `target_id`, `target_name` | String | Snapshots, so an event outlives what it names |
|
||||
| `ip_address`, `device_id` | String | No FK |
|
||||
| `data` | JSON | What the client builds the sentence from |
|
||||
|
||||
---
|
||||
|
||||
#### Firmware
|
||||
|
||||
**Table:** `firmware`
|
||||
@@ -1061,7 +1078,17 @@ A webhook's `format` is `json` (RomM's payload below), `discord` (an embed that
|
||||
|
||||
With a secret, the JSON format adds `X-RomM-Signature: sha256=<hex HMAC-SHA256 of the body>`. Email needs `SMTP_HOST` and `SMTP_FROM` (see `env.template`); the heartbeat's `NOTIFICATIONS.EMAIL_ENABLED` says whether it's set up. Channel configs are sealed with a key derived from `ROMM_AUTH_SECRET_KEY`, so rotating it means entering their URLs again.
|
||||
|
||||
### 6.17 Other Endpoints
|
||||
### 6.17 Audit Events (`/api/audit-events`)
|
||||
|
||||
| Method | Path | Scope | Description |
|
||||
| ------ | ---- | ------- | --------------------------------------------------------------- |
|
||||
| GET | `/` | ME_READ | Events newest first: everyone's for an admin, else the caller's |
|
||||
|
||||
Filters: `actor_id`, `action`, `category`, `target_type`/`target_id`, `since`/`until`, `search` (names and IP). Pages carry `max_id`; pass it back so later pages skip events recorded meanwhile. An admin reads everyone's only with `users.read` in the token.
|
||||
|
||||
Events are written by `handler/audit_handler.record()` after an action succeeds, and a failure to write never fails the action. A ROM content fetch is a `rom.download`, or a `rom.player_load` when the in-browser player marks it `purpose=play`; a fetch whose Range starts past byte 0, or that the same caller made in the last 10 minutes, isn't recorded. A failed login keeps the attempted name only when an account has it. The client address comes from `X-Forwarded-For` only when the connection is from a proxy in `FORWARDED_ALLOW_IPS`.
|
||||
|
||||
### 6.18 Other Endpoints
|
||||
|
||||
| Router | Path | Description |
|
||||
| ------------- | -------------------------------------- | -------------------------------------- |
|
||||
@@ -1490,6 +1517,7 @@ Toggled via environment variables:
|
||||
| `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress |
|
||||
| `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork |
|
||||
| `cleanup_netplay` | Always enabled | Periodic | Clean stale rooms |
|
||||
| `cleanup_audit_log` | `AUDIT_LOG_RETENTION_DAYS` above 0 (default 90) | `30 4 * * *` | Prune old audit events |
|
||||
|
||||
### Manual Tasks
|
||||
|
||||
@@ -1623,13 +1651,14 @@ Falls back to `FakeRedis` in test mode.
|
||||
|
||||
#### Core
|
||||
|
||||
| Variable | Default | Description |
|
||||
| ---------------- | ---------------- | -------------------- |
|
||||
| `ROMM_BASE_PATH` | `/romm` | Base data directory |
|
||||
| `ROMM_BASE_URL` | `http://0.0.0.0` | Application base URL |
|
||||
| `ROMM_PORT` | `8080` | Server port |
|
||||
| `DEV_MODE` | `false` | Development mode |
|
||||
| `LOGLEVEL` | `INFO` | Log level |
|
||||
| Variable | Default | Description |
|
||||
| --------------------- | ---------------- | ---------------------------------------------------------- |
|
||||
| `ROMM_BASE_PATH` | `/romm` | Base data directory |
|
||||
| `ROMM_BASE_URL` | `http://0.0.0.0` | Application base URL |
|
||||
| `ROMM_PORT` | `8080` | Server port |
|
||||
| `DEV_MODE` | `false` | Development mode |
|
||||
| `LOGLEVEL` | `INFO` | Log level |
|
||||
| `FORWARDED_ALLOW_IPS` | private ranges | Proxies trusted to report the client address (`*` for any) |
|
||||
|
||||
#### Database
|
||||
|
||||
|
||||
@@ -119,6 +119,9 @@ SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON=0 4 * * * # Cron expression for
|
||||
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS=true # Enable the scheduled rebuild of the recommendations index
|
||||
SCHEDULED_BUILD_RECOMMENDATIONS_CRON=30 5 * * * # Cron expression for the recommendations index rebuild
|
||||
|
||||
# Audit log
|
||||
AUDIT_LOG_RETENTION_DAYS=90 # Days to keep audit log events (plays, downloads, library and account changes); 0 keeps them forever
|
||||
|
||||
# Sync
|
||||
ENABLE_SYNC_FOLDER_WATCHER=false # Watch the sync folder and trigger scans on change
|
||||
SYNC_FOLDER_SCAN_DELAY=2 # Delay in minutes before scanning after a sync folder change
|
||||
@@ -155,6 +158,7 @@ WEB_SERVER_MAX_REQUESTS=1000 # Maximum requests a worker processes before resta
|
||||
WEB_SERVER_MAX_REQUESTS_JITTER=100 # Random jitter added to max requests value
|
||||
WEB_SERVER_WORKER_CONNECTIONS=1000 # Maximum simultaneous clients per worker process
|
||||
WEB_SERVER_GUNICORN_WAIT_SECONDS=30 # Seconds to wait for Gunicorn to start before giving up
|
||||
FORWARDED_ALLOW_IPS=127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,100.64.0.0/10,fc00::/7 # Proxies trusted to report the client's address (X-Forwarded-For); add a reverse proxy's public IP here, or * to trust any
|
||||
IPV4_ONLY=false # Bind only to IPv4
|
||||
|
||||
# Proxy
|
||||
|
||||
Generated
+5
@@ -10,6 +10,11 @@ export type { AdminContainerSchema } from './models/AdminContainerSchema';
|
||||
export type { AdminContainersResponse } from './models/AdminContainersResponse';
|
||||
export type { AdminSessionSchema } from './models/AdminSessionSchema';
|
||||
export type { AdminSessionsResponse } from './models/AdminSessionsResponse';
|
||||
export type { AuditAction } from './models/AuditAction';
|
||||
export type { AuditActorKind } from './models/AuditActorKind';
|
||||
export type { AuditCategory } from './models/AuditCategory';
|
||||
export type { AuditEventSchema } from './models/AuditEventSchema';
|
||||
export type { AuditPage_AuditEventSchema_ } from './models/AuditPage_AuditEventSchema_';
|
||||
export type { Body_add_collection_api_collections_post } from './models/Body_add_collection_api_collections_post';
|
||||
export type { Body_add_firmware_api_firmware_post } from './models/Body_add_firmware_api_firmware_post';
|
||||
export type { Body_add_platform_api_platforms_post } from './models/Body_add_platform_api_platforms_post';
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* What someone, or a background job, did; the client builds its sentence from `data`.
|
||||
*/
|
||||
export type AuditAction = 'rom.download' | 'rom.bulk_download' | 'rom.player_load' | 'rom.play' | 'rom.upload' | 'rom.create' | 'rom.edit' | 'rom.match' | 'rom.unmatch' | 'rom.delete' | 'rom.file_delete' | 'platform.create' | 'platform.edit' | 'platform.delete' | 'firmware.upload' | 'firmware.delete' | 'config.update' | 'collection.create' | 'collection.edit' | 'collection.delete' | 'collection.add_roms' | 'collection.remove_roms' | 'smart_collection.create' | 'smart_collection.edit' | 'smart_collection.delete' | 'scan.start' | 'scan.finish' | 'scan.stop' | 'task.run' | 'auth.login' | 'auth.login_failed' | 'auth.password_reset_request' | 'auth.password_reset' | 'user.create' | 'user.register' | 'user.edit' | 'user.delete' | 'user.permissions_edit' | 'permission_group.create' | 'permission_group.edit' | 'permission_group.delete' | 'visibility.hide' | 'visibility.unhide' | 'client_token.create' | 'client_token.regenerate' | 'client_token.revoke' | 'device.approve';
|
||||
@@ -0,0 +1,5 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type AuditActorKind = 'user' | 'anonymous' | 'system';
|
||||
@@ -0,0 +1,5 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type AuditCategory = 'consumption' | 'library' | 'collections' | 'operations' | 'security';
|
||||
@@ -0,0 +1,25 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { AuditAction } from './AuditAction';
|
||||
import type { AuditActorKind } from './AuditActorKind';
|
||||
import type { AuditCategory } from './AuditCategory';
|
||||
import type { NotificationActorSchema } from './NotificationActorSchema';
|
||||
export type AuditEventSchema = {
|
||||
id: number;
|
||||
action: (AuditAction | string);
|
||||
category: (AuditCategory | null);
|
||||
occurred_at: string;
|
||||
actor_kind: (AuditActorKind | string);
|
||||
actor: (NotificationActorSchema | null);
|
||||
actor_name: (string | null);
|
||||
target_type: (string | null);
|
||||
target_id: (string | null);
|
||||
target_name: (string | null);
|
||||
ip_address: (string | null);
|
||||
device_id: (string | null);
|
||||
device_name: (string | null);
|
||||
data: Record<string, any>;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { AuditEventSchema } from './AuditEventSchema';
|
||||
export type AuditPage_AuditEventSchema_ = {
|
||||
items: Array<AuditEventSchema>;
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
max_id?: (number | null);
|
||||
};
|
||||
|
||||
@@ -450,6 +450,7 @@ async function boot() {
|
||||
window.EJS_gameUrl = getDownloadPath({
|
||||
rom: rom,
|
||||
fileIDs: validDiscId ? [validDiscId] : [],
|
||||
purpose: "play",
|
||||
});
|
||||
|
||||
// BIOS selection persistence
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Вход",
|
||||
"action-auth-login-failed": "Неуспешен вход като {username}",
|
||||
"action-auth-login-failed-unknown": "Неуспешен вход с непознато потребителско име",
|
||||
"action-auth-password-reset": "Възстановяване на паролата на {target}",
|
||||
"action-auth-password-reset-request": "Заявка за възстановяване на паролата на {target}",
|
||||
"action-client-token-create": "Създаване на API токен {target}",
|
||||
"action-client-token-regenerate": "Регенериране на API токен {target}",
|
||||
"action-client-token-revoke": "Отмяна на API токен {target}",
|
||||
"action-collection-add-roms": "Добавяне на {n} игра към {target} | Добавяне на {n} игри към {target}",
|
||||
"action-collection-create": "Създаване на колекция {target}",
|
||||
"action-collection-delete": "Изтриване на колекция {target}",
|
||||
"action-collection-edit": "Редактиране на колекция {target}",
|
||||
"action-collection-remove-roms": "Премахване на {n} игра от {target} | Премахване на {n} игри от {target}",
|
||||
"action-config-update": "Промяна на {setting}",
|
||||
"action-device-approve": "Сдвояване на устройство {target}",
|
||||
"action-firmware-delete": "Изтриване на фърмуер {target}",
|
||||
"action-firmware-upload": "Качване на фърмуер за {target}",
|
||||
"action-permission-group-create": "Създаване на група с разрешения {target}",
|
||||
"action-permission-group-delete": "Изтриване на група с разрешения {target}",
|
||||
"action-permission-group-edit": "Редактиране на група с разрешения {target}",
|
||||
"action-platform-create": "Добавяне на платформа {target}",
|
||||
"action-platform-delete": "Изтриване на платформа {target}",
|
||||
"action-platform-edit": "Редактиране на платформа {target}",
|
||||
"action-rom-bulk-download": "Сваляне на {n} игра от {target} | Сваляне на {n} игри от {target}",
|
||||
"action-rom-bulk-download-selection": "Сваляне на {n} игра | Сваляне на {n} игри",
|
||||
"action-rom-create": "Добавяне на {target}",
|
||||
"action-rom-delete": "Изтриване на {target}",
|
||||
"action-rom-download": "Сваляне на {target}",
|
||||
"action-rom-edit": "Редактиране на {target}",
|
||||
"action-rom-file-delete": "Изтриване на файл от {target}",
|
||||
"action-rom-match": "Разпознаване на {target}",
|
||||
"action-rom-play": "Игра на {target}",
|
||||
"action-rom-player-load": "Зареждане на {target} за игра",
|
||||
"action-rom-unmatch": "Премахване на разпознаването на {target}",
|
||||
"action-rom-upload": "Качване на {file} в {target}",
|
||||
"action-scan-failed": "Неуспешно сканиране",
|
||||
"action-scan-finish": "Завършено сканиране",
|
||||
"action-scan-start": "Стартиране на сканиране",
|
||||
"action-scan-stop": "Спиране на сканирането",
|
||||
"action-scan-stopped": "Сканирането беше спряно",
|
||||
"action-smart-collection-create": "Създаване на умна колекция {target}",
|
||||
"action-smart-collection-delete": "Изтриване на умна колекция {target}",
|
||||
"action-smart-collection-edit": "Редактиране на умна колекция {target}",
|
||||
"action-task-run": "Изпълнение на задача {target}",
|
||||
"action-user-create": "Създаване на потребител {target}",
|
||||
"action-user-delete": "Изтриване на потребител {target}",
|
||||
"action-user-edit": "Редактиране на потребител {target}",
|
||||
"action-user-permissions-edit": "Промяна на разрешенията на {target}",
|
||||
"action-user-register": "Регистрация",
|
||||
"action-visibility-hide": "Скриване на {target} от {principal}",
|
||||
"action-visibility-unhide": "Повторно показване на {target} за {principal}",
|
||||
"all-categories": "Всички категории",
|
||||
"all-users": "Всички потребители",
|
||||
"anonymous": "Анонимен",
|
||||
"category-collections": "Колекции",
|
||||
"category-consumption": "Игра и сваляния",
|
||||
"category-library": "Библиотека",
|
||||
"category-operations": "Сканирания и задачи",
|
||||
"category-security": "Акаунти и сигурност",
|
||||
"config-exclusion": "изключенията при сканиране",
|
||||
"config-platform-binding": "свързванията на папки на платформите",
|
||||
"config-platform-version": "версиите на платформите",
|
||||
"config-scan-settings": "настройките за сканиране",
|
||||
"deleted-user": "Изтрит потребител",
|
||||
"detail-changed": "Промени: {fields}",
|
||||
"detail-deleted-from-disk": "Изтрито и от диска",
|
||||
"detail-games-added": "{n} добавена игра | {n} добавени игри",
|
||||
"detail-games-removed": "{n} премахната игра | {n} премахнати игри",
|
||||
"detail-login-credentials": "Грешно потребителско име или парола",
|
||||
"detail-login-disabled": "Акаунтът е деактивиран",
|
||||
"detail-new-games": "Няма нови игри | {n} нова игра | {n} нови игри",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Роля: {from} → {to}",
|
||||
"empty": "Все още няма записани събития",
|
||||
"events": "Събития",
|
||||
"field-cover": "корица",
|
||||
"field-custom-name": "име",
|
||||
"field-description": "описание",
|
||||
"field-email": "имейл",
|
||||
"field-enabled": "активиран",
|
||||
"field-fs-name": "име на файл",
|
||||
"field-is-public": "видимост",
|
||||
"field-manual": "ръководство",
|
||||
"field-name": "име",
|
||||
"field-password": "парола",
|
||||
"field-role": "роля",
|
||||
"field-summary": "резюме",
|
||||
"field-username": "потребителско име",
|
||||
"filter-category": "Категория",
|
||||
"filter-user": "Потребител",
|
||||
"load-error": "Одитният дневник не можа да бъде зареден",
|
||||
"no-matches": "Няма събития, отговарящи на тези филтри",
|
||||
"search-placeholder": "Търси събития",
|
||||
"since": "От",
|
||||
"system": "RomM",
|
||||
"until": "До",
|
||||
"yesterday": "Вчера"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Přihlášení",
|
||||
"action-auth-login-failed": "Neúspěšné přihlášení jako {username}",
|
||||
"action-auth-login-failed-unknown": "Neúspěšné přihlášení s neznámým uživatelským jménem",
|
||||
"action-auth-password-reset": "Resetováno heslo uživatele {target}",
|
||||
"action-auth-password-reset-request": "Vyžádán reset hesla uživatele {target}",
|
||||
"action-client-token-create": "Vytvořen API token {target}",
|
||||
"action-client-token-regenerate": "Znovu vygenerován API token {target}",
|
||||
"action-client-token-revoke": "Zrušen API token {target}",
|
||||
"action-collection-add-roms": "Přidáno {n} her do kolekce {target} | Přidána {n} hra do kolekce {target} | Přidány {n} hry do kolekce {target} | Přidáno {n} her do kolekce {target}",
|
||||
"action-collection-create": "Vytvořena kolekce {target}",
|
||||
"action-collection-delete": "Smazána kolekce {target}",
|
||||
"action-collection-edit": "Upravena kolekce {target}",
|
||||
"action-collection-remove-roms": "Odebráno {n} her z kolekce {target} | Odebrána {n} hra z kolekce {target} | Odebrány {n} hry z kolekce {target} | Odebráno {n} her z kolekce {target}",
|
||||
"action-config-update": "Změněno: {setting}",
|
||||
"action-device-approve": "Spárováno zařízení {target}",
|
||||
"action-firmware-delete": "Smazán firmware {target}",
|
||||
"action-firmware-upload": "Nahrán firmware pro {target}",
|
||||
"action-permission-group-create": "Vytvořena skupina oprávnění {target}",
|
||||
"action-permission-group-delete": "Smazána skupina oprávnění {target}",
|
||||
"action-permission-group-edit": "Upravena skupina oprávnění {target}",
|
||||
"action-platform-create": "Přidána platforma {target}",
|
||||
"action-platform-delete": "Smazána platforma {target}",
|
||||
"action-platform-edit": "Upravena platforma {target}",
|
||||
"action-rom-bulk-download": "Staženo {n} her z {target} | Stažena {n} hra z {target} | Staženy {n} hry z {target} | Staženo {n} her z {target}",
|
||||
"action-rom-bulk-download-selection": "Staženo {n} her | Stažena {n} hra | Staženy {n} hry | Staženo {n} her",
|
||||
"action-rom-create": "Přidána hra {target}",
|
||||
"action-rom-delete": "Smazána hra {target}",
|
||||
"action-rom-download": "Stažena hra {target}",
|
||||
"action-rom-edit": "Upravena hra {target}",
|
||||
"action-rom-file-delete": "Smazán soubor hry {target}",
|
||||
"action-rom-match": "Spárována hra {target}",
|
||||
"action-rom-play": "Hraní hry {target}",
|
||||
"action-rom-player-load": "Hra {target} načtena k hraní",
|
||||
"action-rom-unmatch": "Zrušeno spárování hry {target}",
|
||||
"action-rom-upload": "Nahrán soubor {file} do {target}",
|
||||
"action-scan-failed": "Skenování selhalo",
|
||||
"action-scan-finish": "Skenování dokončeno",
|
||||
"action-scan-start": "Skenování spuštěno",
|
||||
"action-scan-stop": "Skenování zastaveno",
|
||||
"action-scan-stopped": "Skenování bylo přerušeno",
|
||||
"action-smart-collection-create": "Vytvořena chytrá kolekce {target}",
|
||||
"action-smart-collection-delete": "Smazána chytrá kolekce {target}",
|
||||
"action-smart-collection-edit": "Upravena chytrá kolekce {target}",
|
||||
"action-task-run": "Spuštěna úloha {target}",
|
||||
"action-user-create": "Vytvořen uživatel {target}",
|
||||
"action-user-delete": "Smazán uživatel {target}",
|
||||
"action-user-edit": "Upraven uživatel {target}",
|
||||
"action-user-permissions-edit": "Změněna oprávnění uživatele {target}",
|
||||
"action-user-register": "Registrace",
|
||||
"action-visibility-hide": "Skryto {target} pro {principal}",
|
||||
"action-visibility-unhide": "Znovu zobrazeno {target} pro {principal}",
|
||||
"all-categories": "Všechny kategorie",
|
||||
"all-users": "Všichni uživatelé",
|
||||
"anonymous": "Anonymní",
|
||||
"category-collections": "Kolekce",
|
||||
"category-consumption": "Hraní a stahování",
|
||||
"category-library": "Knihovna",
|
||||
"category-operations": "Skenování a úlohy",
|
||||
"category-security": "Účty a zabezpečení",
|
||||
"config-exclusion": "výjimky skenování",
|
||||
"config-platform-binding": "mapování složek platforem",
|
||||
"config-platform-version": "verze platforem",
|
||||
"config-scan-settings": "nastavení skenování",
|
||||
"deleted-user": "Smazaný uživatel",
|
||||
"detail-changed": "Změněno: {fields}",
|
||||
"detail-deleted-from-disk": "Smazáno i z disku",
|
||||
"detail-games-added": "Přidáno {n} her | Přidána {n} hra | Přidány {n} hry | Přidáno {n} her",
|
||||
"detail-games-removed": "Odebráno {n} her | Odebrána {n} hra | Odebrány {n} hry | Odebráno {n} her",
|
||||
"detail-login-credentials": "Nesprávné uživatelské jméno nebo heslo",
|
||||
"detail-login-disabled": "Účet zakázán",
|
||||
"detail-new-games": "Žádné nové hry | {n} nová hra | {n} nové hry | {n} nových her",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Role: {from} → {to}",
|
||||
"empty": "Zatím nebylo nic zaznamenáno",
|
||||
"events": "Události",
|
||||
"field-cover": "obal",
|
||||
"field-custom-name": "název",
|
||||
"field-description": "popis",
|
||||
"field-email": "e-mail",
|
||||
"field-enabled": "povoleno",
|
||||
"field-fs-name": "název souboru",
|
||||
"field-is-public": "viditelnost",
|
||||
"field-manual": "manuál",
|
||||
"field-name": "název",
|
||||
"field-password": "heslo",
|
||||
"field-role": "role",
|
||||
"field-summary": "souhrn",
|
||||
"field-username": "uživatelské jméno",
|
||||
"filter-category": "Kategorie",
|
||||
"filter-user": "Uživatel",
|
||||
"load-error": "Protokol auditu se nepodařilo načíst",
|
||||
"no-matches": "Těmto filtrům neodpovídají žádné události",
|
||||
"search-placeholder": "Hledat události",
|
||||
"since": "Od",
|
||||
"system": "RomM",
|
||||
"until": "Do",
|
||||
"yesterday": "Včera"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Angemeldet",
|
||||
"action-auth-login-failed": "Anmeldung als {username} fehlgeschlagen",
|
||||
"action-auth-login-failed-unknown": "Anmeldung mit unbekanntem Benutzernamen fehlgeschlagen",
|
||||
"action-auth-password-reset": "Passwort von {target} zurückgesetzt",
|
||||
"action-auth-password-reset-request": "Zurücksetzen des Passworts von {target} angefordert",
|
||||
"action-client-token-create": "API-Token {target} erstellt",
|
||||
"action-client-token-regenerate": "API-Token {target} regeneriert",
|
||||
"action-client-token-revoke": "API-Token {target} widerrufen",
|
||||
"action-collection-add-roms": "{n} Spiel zu {target} hinzugefügt | {n} Spiele zu {target} hinzugefügt",
|
||||
"action-collection-create": "Sammlung {target} erstellt",
|
||||
"action-collection-delete": "Sammlung {target} gelöscht",
|
||||
"action-collection-edit": "Sammlung {target} bearbeitet",
|
||||
"action-collection-remove-roms": "{n} Spiel aus {target} entfernt | {n} Spiele aus {target} entfernt",
|
||||
"action-config-update": "{setting} geändert",
|
||||
"action-device-approve": "Gerät {target} gekoppelt",
|
||||
"action-firmware-delete": "Firmware {target} gelöscht",
|
||||
"action-firmware-upload": "Firmware für {target} hochgeladen",
|
||||
"action-permission-group-create": "Berechtigungsgruppe {target} erstellt",
|
||||
"action-permission-group-delete": "Berechtigungsgruppe {target} gelöscht",
|
||||
"action-permission-group-edit": "Berechtigungsgruppe {target} bearbeitet",
|
||||
"action-platform-create": "Plattform {target} hinzugefügt",
|
||||
"action-platform-delete": "Plattform {target} gelöscht",
|
||||
"action-platform-edit": "Plattform {target} bearbeitet",
|
||||
"action-rom-bulk-download": "{n} Spiel aus {target} heruntergeladen | {n} Spiele aus {target} heruntergeladen",
|
||||
"action-rom-bulk-download-selection": "{n} Spiel heruntergeladen | {n} Spiele heruntergeladen",
|
||||
"action-rom-create": "{target} hinzugefügt",
|
||||
"action-rom-delete": "{target} gelöscht",
|
||||
"action-rom-download": "{target} heruntergeladen",
|
||||
"action-rom-edit": "{target} bearbeitet",
|
||||
"action-rom-file-delete": "Eine Datei von {target} gelöscht",
|
||||
"action-rom-match": "{target} zugeordnet",
|
||||
"action-rom-play": "{target} gespielt",
|
||||
"action-rom-player-load": "{target} zum Spielen geladen",
|
||||
"action-rom-unmatch": "Zuordnung von {target} aufgehoben",
|
||||
"action-rom-upload": "{file} zu {target} hochgeladen",
|
||||
"action-scan-failed": "Ein Scan ist fehlgeschlagen",
|
||||
"action-scan-finish": "Scan abgeschlossen",
|
||||
"action-scan-start": "Scan gestartet",
|
||||
"action-scan-stop": "Scan abgebrochen",
|
||||
"action-scan-stopped": "Ein Scan wurde abgebrochen",
|
||||
"action-smart-collection-create": "Intelligente Sammlung {target} erstellt",
|
||||
"action-smart-collection-delete": "Intelligente Sammlung {target} gelöscht",
|
||||
"action-smart-collection-edit": "Intelligente Sammlung {target} bearbeitet",
|
||||
"action-task-run": "Aufgabe {target} ausgeführt",
|
||||
"action-user-create": "Benutzer {target} erstellt",
|
||||
"action-user-delete": "Benutzer {target} gelöscht",
|
||||
"action-user-edit": "Benutzer {target} bearbeitet",
|
||||
"action-user-permissions-edit": "Berechtigungen von {target} geändert",
|
||||
"action-user-register": "Registriert",
|
||||
"action-visibility-hide": "{target} vor {principal} versteckt",
|
||||
"action-visibility-unhide": "{target} für {principal} wieder sichtbar gemacht",
|
||||
"all-categories": "Alle Kategorien",
|
||||
"all-users": "Alle Benutzer",
|
||||
"anonymous": "Anonym",
|
||||
"category-collections": "Sammlungen",
|
||||
"category-consumption": "Spielsitzungen und Downloads",
|
||||
"category-library": "Bibliothek",
|
||||
"category-operations": "Scans und Aufgaben",
|
||||
"category-security": "Konten und Sicherheit",
|
||||
"config-exclusion": "Scan-Ausschlüsse",
|
||||
"config-platform-binding": "Ordnerzuordnungen der Plattformen",
|
||||
"config-platform-version": "Plattformversionen",
|
||||
"config-scan-settings": "Scan-Einstellungen",
|
||||
"deleted-user": "Gelöschter Benutzer",
|
||||
"detail-changed": "Geändert: {fields}",
|
||||
"detail-deleted-from-disk": "Auch vom Datenträger gelöscht",
|
||||
"detail-games-added": "{n} Spiel hinzugefügt | {n} Spiele hinzugefügt",
|
||||
"detail-games-removed": "{n} Spiel entfernt | {n} Spiele entfernt",
|
||||
"detail-login-credentials": "Falscher Benutzername oder falsches Passwort",
|
||||
"detail-login-disabled": "Konto deaktiviert",
|
||||
"detail-new-games": "Keine neuen Spiele | {n} neues Spiel | {n} neue Spiele",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Rolle: {from} → {to}",
|
||||
"empty": "Bisher wurde nichts aufgezeichnet",
|
||||
"events": "Ereignisse",
|
||||
"field-cover": "Coverbild",
|
||||
"field-custom-name": "Name",
|
||||
"field-description": "Beschreibung",
|
||||
"field-email": "E-Mail",
|
||||
"field-enabled": "aktiviert",
|
||||
"field-fs-name": "Dateiname",
|
||||
"field-is-public": "Sichtbarkeit",
|
||||
"field-manual": "Handbuch",
|
||||
"field-name": "Name",
|
||||
"field-password": "Passwort",
|
||||
"field-role": "Rolle",
|
||||
"field-summary": "Zusammenfassung",
|
||||
"field-username": "Benutzername",
|
||||
"filter-category": "Kategorie",
|
||||
"filter-user": "Benutzer",
|
||||
"load-error": "Das Audit-Protokoll konnte nicht geladen werden",
|
||||
"no-matches": "Keine Ereignisse entsprechen diesen Filtern",
|
||||
"search-placeholder": "Ereignisse suchen",
|
||||
"since": "Von",
|
||||
"system": "RomM",
|
||||
"until": "Bis",
|
||||
"yesterday": "Gestern"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Signed in",
|
||||
"action-auth-login-failed": "Failed to sign in as {username}",
|
||||
"action-auth-login-failed-unknown": "Failed to sign in with an unknown username",
|
||||
"action-auth-password-reset": "Reset the password of {target}",
|
||||
"action-auth-password-reset-request": "Requested a password reset for {target}",
|
||||
"action-client-token-create": "Created the API token {target}",
|
||||
"action-client-token-regenerate": "Regenerated the API token {target}",
|
||||
"action-client-token-revoke": "Revoked the API token {target}",
|
||||
"action-collection-add-roms": "Added {n} game to {target} | Added {n} games to {target}",
|
||||
"action-collection-create": "Created the collection {target}",
|
||||
"action-collection-delete": "Deleted the collection {target}",
|
||||
"action-collection-edit": "Edited the collection {target}",
|
||||
"action-collection-remove-roms": "Removed {n} game from {target} | Removed {n} games from {target}",
|
||||
"action-config-update": "Changed the {setting}",
|
||||
"action-device-approve": "Paired the device {target}",
|
||||
"action-firmware-delete": "Deleted the firmware {target}",
|
||||
"action-firmware-upload": "Uploaded firmware for {target}",
|
||||
"action-permission-group-create": "Created the permission group {target}",
|
||||
"action-permission-group-delete": "Deleted the permission group {target}",
|
||||
"action-permission-group-edit": "Edited the permission group {target}",
|
||||
"action-platform-create": "Added the platform {target}",
|
||||
"action-platform-delete": "Deleted the platform {target}",
|
||||
"action-platform-edit": "Edited the platform {target}",
|
||||
"action-rom-bulk-download": "Downloaded {n} game from {target} | Downloaded {n} games from {target}",
|
||||
"action-rom-bulk-download-selection": "Downloaded {n} game | Downloaded {n} games",
|
||||
"action-rom-create": "Added {target}",
|
||||
"action-rom-delete": "Deleted {target}",
|
||||
"action-rom-download": "Downloaded {target}",
|
||||
"action-rom-edit": "Edited {target}",
|
||||
"action-rom-file-delete": "Deleted a file of {target}",
|
||||
"action-rom-match": "Matched {target}",
|
||||
"action-rom-play": "Played {target}",
|
||||
"action-rom-player-load": "Loaded {target} into a player",
|
||||
"action-rom-unmatch": "Unmatched {target}",
|
||||
"action-rom-upload": "Uploaded {file} to {target}",
|
||||
"action-scan-failed": "A scan failed",
|
||||
"action-scan-finish": "Finished a scan",
|
||||
"action-scan-start": "Started a scan",
|
||||
"action-scan-stop": "Stopped the scan",
|
||||
"action-scan-stopped": "A scan was stopped",
|
||||
"action-smart-collection-create": "Created the smart collection {target}",
|
||||
"action-smart-collection-delete": "Deleted the smart collection {target}",
|
||||
"action-smart-collection-edit": "Edited the smart collection {target}",
|
||||
"action-task-run": "Ran the task {target}",
|
||||
"action-user-create": "Created the user {target}",
|
||||
"action-user-delete": "Deleted the user {target}",
|
||||
"action-user-edit": "Edited the user {target}",
|
||||
"action-user-permissions-edit": "Changed the permissions of {target}",
|
||||
"action-user-register": "Signed up",
|
||||
"action-visibility-hide": "Hid {target} from {principal}",
|
||||
"action-visibility-unhide": "Showed {target} to {principal} again",
|
||||
"all-categories": "All categories",
|
||||
"all-users": "All users",
|
||||
"anonymous": "Anonymous",
|
||||
"category-collections": "Collections",
|
||||
"category-consumption": "Plays and downloads",
|
||||
"category-library": "Library",
|
||||
"category-operations": "Scans and tasks",
|
||||
"category-security": "Accounts and security",
|
||||
"config-exclusion": "scan exclusions",
|
||||
"config-platform-binding": "platform folder mappings",
|
||||
"config-platform-version": "platform versions",
|
||||
"config-scan-settings": "scan settings",
|
||||
"deleted-user": "Deleted user",
|
||||
"detail-changed": "Changed: {fields}",
|
||||
"detail-deleted-from-disk": "Also deleted from disk",
|
||||
"detail-games-added": "{n} game added | {n} games added",
|
||||
"detail-games-removed": "{n} game removed | {n} games removed",
|
||||
"detail-login-credentials": "Wrong username or password",
|
||||
"detail-login-disabled": "Account disabled",
|
||||
"detail-new-games": "No new games | {n} new game | {n} new games",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Role: {from} → {to}",
|
||||
"empty": "Nothing has been recorded yet",
|
||||
"events": "Events",
|
||||
"field-cover": "cover",
|
||||
"field-custom-name": "name",
|
||||
"field-description": "description",
|
||||
"field-email": "email",
|
||||
"field-enabled": "enabled",
|
||||
"field-fs-name": "file name",
|
||||
"field-is-public": "visibility",
|
||||
"field-manual": "manual",
|
||||
"field-name": "name",
|
||||
"field-password": "password",
|
||||
"field-role": "role",
|
||||
"field-summary": "summary",
|
||||
"field-username": "username",
|
||||
"filter-category": "Category",
|
||||
"filter-user": "User",
|
||||
"load-error": "Couldn't load the audit log",
|
||||
"no-matches": "No events match these filters",
|
||||
"search-placeholder": "Search events",
|
||||
"since": "From",
|
||||
"system": "RomM",
|
||||
"until": "To",
|
||||
"yesterday": "Yesterday"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Signed in",
|
||||
"action-auth-login-failed": "Failed to sign in as {username}",
|
||||
"action-auth-login-failed-unknown": "Failed to sign in with an unknown username",
|
||||
"action-auth-password-reset": "Reset the password of {target}",
|
||||
"action-auth-password-reset-request": "Requested a password reset for {target}",
|
||||
"action-client-token-create": "Created the API token {target}",
|
||||
"action-client-token-regenerate": "Regenerated the API token {target}",
|
||||
"action-client-token-revoke": "Revoked the API token {target}",
|
||||
"action-collection-add-roms": "Added {n} game to {target} | Added {n} games to {target}",
|
||||
"action-collection-create": "Created the collection {target}",
|
||||
"action-collection-delete": "Deleted the collection {target}",
|
||||
"action-collection-edit": "Edited the collection {target}",
|
||||
"action-collection-remove-roms": "Removed {n} game from {target} | Removed {n} games from {target}",
|
||||
"action-config-update": "Changed the {setting}",
|
||||
"action-device-approve": "Paired the device {target}",
|
||||
"action-firmware-delete": "Deleted the firmware {target}",
|
||||
"action-firmware-upload": "Uploaded firmware for {target}",
|
||||
"action-permission-group-create": "Created the permission group {target}",
|
||||
"action-permission-group-delete": "Deleted the permission group {target}",
|
||||
"action-permission-group-edit": "Edited the permission group {target}",
|
||||
"action-platform-create": "Added the platform {target}",
|
||||
"action-platform-delete": "Deleted the platform {target}",
|
||||
"action-platform-edit": "Edited the platform {target}",
|
||||
"action-rom-bulk-download": "Downloaded {n} game from {target} | Downloaded {n} games from {target}",
|
||||
"action-rom-bulk-download-selection": "Downloaded {n} game | Downloaded {n} games",
|
||||
"action-rom-create": "Added {target}",
|
||||
"action-rom-delete": "Deleted {target}",
|
||||
"action-rom-download": "Downloaded {target}",
|
||||
"action-rom-edit": "Edited {target}",
|
||||
"action-rom-file-delete": "Deleted a file of {target}",
|
||||
"action-rom-match": "Matched {target}",
|
||||
"action-rom-play": "Played {target}",
|
||||
"action-rom-player-load": "Loaded {target} into a player",
|
||||
"action-rom-unmatch": "Unmatched {target}",
|
||||
"action-rom-upload": "Uploaded {file} to {target}",
|
||||
"action-scan-failed": "A scan failed",
|
||||
"action-scan-finish": "Finished a scan",
|
||||
"action-scan-start": "Started a scan",
|
||||
"action-scan-stop": "Stopped the scan",
|
||||
"action-scan-stopped": "A scan was stopped",
|
||||
"action-smart-collection-create": "Created the smart collection {target}",
|
||||
"action-smart-collection-delete": "Deleted the smart collection {target}",
|
||||
"action-smart-collection-edit": "Edited the smart collection {target}",
|
||||
"action-task-run": "Ran the task {target}",
|
||||
"action-user-create": "Created the user {target}",
|
||||
"action-user-delete": "Deleted the user {target}",
|
||||
"action-user-edit": "Edited the user {target}",
|
||||
"action-user-permissions-edit": "Changed the permissions of {target}",
|
||||
"action-user-register": "Signed up",
|
||||
"action-visibility-hide": "Hid {target} from {principal}",
|
||||
"action-visibility-unhide": "Showed {target} to {principal} again",
|
||||
"all-categories": "All categories",
|
||||
"all-users": "All users",
|
||||
"anonymous": "Anonymous",
|
||||
"category-collections": "Collections",
|
||||
"category-consumption": "Plays and downloads",
|
||||
"category-library": "Library",
|
||||
"category-operations": "Scans and tasks",
|
||||
"category-security": "Accounts and security",
|
||||
"config-exclusion": "scan exclusions",
|
||||
"config-platform-binding": "platform folder mappings",
|
||||
"config-platform-version": "platform versions",
|
||||
"config-scan-settings": "scan settings",
|
||||
"deleted-user": "Deleted user",
|
||||
"detail-changed": "Changed: {fields}",
|
||||
"detail-deleted-from-disk": "Also deleted from disk",
|
||||
"detail-games-added": "{n} game added | {n} games added",
|
||||
"detail-games-removed": "{n} game removed | {n} games removed",
|
||||
"detail-login-credentials": "Wrong username or password",
|
||||
"detail-login-disabled": "Account disabled",
|
||||
"detail-new-games": "No new games | {n} new game | {n} new games",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Role: {from} → {to}",
|
||||
"empty": "Nothing has been recorded yet",
|
||||
"events": "Events",
|
||||
"field-cover": "cover",
|
||||
"field-custom-name": "name",
|
||||
"field-description": "description",
|
||||
"field-email": "email",
|
||||
"field-enabled": "enabled",
|
||||
"field-fs-name": "file name",
|
||||
"field-is-public": "visibility",
|
||||
"field-manual": "manual",
|
||||
"field-name": "name",
|
||||
"field-password": "password",
|
||||
"field-role": "role",
|
||||
"field-summary": "summary",
|
||||
"field-username": "username",
|
||||
"filter-category": "Category",
|
||||
"filter-user": "User",
|
||||
"load-error": "Couldn't load the audit log",
|
||||
"no-matches": "No events match these filters",
|
||||
"search-placeholder": "Search events",
|
||||
"since": "From",
|
||||
"system": "RomM",
|
||||
"until": "To",
|
||||
"yesterday": "Yesterday"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Inició sesión",
|
||||
"action-auth-login-failed": "Error al iniciar sesión como {username}",
|
||||
"action-auth-login-failed-unknown": "Error al iniciar sesión con un usuario desconocido",
|
||||
"action-auth-password-reset": "Restableció la contraseña de {target}",
|
||||
"action-auth-password-reset-request": "Solicitó restablecer la contraseña de {target}",
|
||||
"action-client-token-create": "Creó el token API {target}",
|
||||
"action-client-token-regenerate": "Regeneró el token API {target}",
|
||||
"action-client-token-revoke": "Revocó el token API {target}",
|
||||
"action-collection-add-roms": "Añadió {n} juego a {target} | Añadió {n} juegos a {target}",
|
||||
"action-collection-create": "Creó la colección {target}",
|
||||
"action-collection-delete": "Eliminó la colección {target}",
|
||||
"action-collection-edit": "Editó la colección {target}",
|
||||
"action-collection-remove-roms": "Quitó {n} juego de {target} | Quitó {n} juegos de {target}",
|
||||
"action-config-update": "Cambió {setting}",
|
||||
"action-device-approve": "Emparejó el dispositivo {target}",
|
||||
"action-firmware-delete": "Eliminó el firmware {target}",
|
||||
"action-firmware-upload": "Subió firmware para {target}",
|
||||
"action-permission-group-create": "Creó el grupo de permisos {target}",
|
||||
"action-permission-group-delete": "Eliminó el grupo de permisos {target}",
|
||||
"action-permission-group-edit": "Editó el grupo de permisos {target}",
|
||||
"action-platform-create": "Añadió la plataforma {target}",
|
||||
"action-platform-delete": "Eliminó la plataforma {target}",
|
||||
"action-platform-edit": "Editó la plataforma {target}",
|
||||
"action-rom-bulk-download": "Descargó {n} juego de {target} | Descargó {n} juegos de {target}",
|
||||
"action-rom-bulk-download-selection": "Descargó {n} juego | Descargó {n} juegos",
|
||||
"action-rom-create": "Añadió {target}",
|
||||
"action-rom-delete": "Eliminó {target}",
|
||||
"action-rom-download": "Descargó {target}",
|
||||
"action-rom-edit": "Editó {target}",
|
||||
"action-rom-file-delete": "Eliminó un archivo de {target}",
|
||||
"action-rom-match": "Identificó {target}",
|
||||
"action-rom-play": "Jugó a {target}",
|
||||
"action-rom-player-load": "Cargó {target} para jugar",
|
||||
"action-rom-unmatch": "Desvinculó {target}",
|
||||
"action-rom-upload": "Subió {file} a {target}",
|
||||
"action-scan-failed": "Un escaneo falló",
|
||||
"action-scan-finish": "Terminó un escaneo",
|
||||
"action-scan-start": "Inició un escaneo",
|
||||
"action-scan-stop": "Detuvo el escaneo",
|
||||
"action-scan-stopped": "Se detuvo un escaneo",
|
||||
"action-smart-collection-create": "Creó la colección inteligente {target}",
|
||||
"action-smart-collection-delete": "Eliminó la colección inteligente {target}",
|
||||
"action-smart-collection-edit": "Editó la colección inteligente {target}",
|
||||
"action-task-run": "Ejecutó la tarea {target}",
|
||||
"action-user-create": "Creó el usuario {target}",
|
||||
"action-user-delete": "Eliminó el usuario {target}",
|
||||
"action-user-edit": "Editó el usuario {target}",
|
||||
"action-user-permissions-edit": "Cambió los permisos de {target}",
|
||||
"action-user-register": "Se registró",
|
||||
"action-visibility-hide": "Ocultó {target} a {principal}",
|
||||
"action-visibility-unhide": "Volvió a mostrar {target} a {principal}",
|
||||
"all-categories": "Todas las categorías",
|
||||
"all-users": "Todos los usuarios",
|
||||
"anonymous": "Anónimo",
|
||||
"category-collections": "Colecciones",
|
||||
"category-consumption": "Partidas y descargas",
|
||||
"category-library": "Biblioteca",
|
||||
"category-operations": "Escaneos y tareas",
|
||||
"category-security": "Cuentas y seguridad",
|
||||
"config-exclusion": "las exclusiones de escaneo",
|
||||
"config-platform-binding": "las asignaciones de carpetas de plataforma",
|
||||
"config-platform-version": "las versiones de plataforma",
|
||||
"config-scan-settings": "los ajustes de escaneo",
|
||||
"deleted-user": "Usuario eliminado",
|
||||
"detail-changed": "Cambios: {fields}",
|
||||
"detail-deleted-from-disk": "También eliminado del disco",
|
||||
"detail-games-added": "{n} juego añadido | {n} juegos añadidos",
|
||||
"detail-games-removed": "{n} juego quitado | {n} juegos quitados",
|
||||
"detail-login-credentials": "Usuario o contraseña incorrectos",
|
||||
"detail-login-disabled": "Cuenta desactivada",
|
||||
"detail-new-games": "Ningún juego nuevo | {n} juego nuevo | {n} juegos nuevos",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Rol: {from} → {to}",
|
||||
"empty": "Todavía no se ha registrado nada",
|
||||
"events": "Eventos",
|
||||
"field-cover": "portada",
|
||||
"field-custom-name": "nombre",
|
||||
"field-description": "descripción",
|
||||
"field-email": "correo electrónico",
|
||||
"field-enabled": "habilitado",
|
||||
"field-fs-name": "nombre del archivo",
|
||||
"field-is-public": "visibilidad",
|
||||
"field-manual": "manual",
|
||||
"field-name": "nombre",
|
||||
"field-password": "contraseña",
|
||||
"field-role": "rol",
|
||||
"field-summary": "resumen",
|
||||
"field-username": "nombre de usuario",
|
||||
"filter-category": "Categoría",
|
||||
"filter-user": "Usuario",
|
||||
"load-error": "No se pudo cargar el registro de auditoría",
|
||||
"no-matches": "Ningún evento coincide con estos filtros",
|
||||
"search-placeholder": "Buscar eventos",
|
||||
"since": "Desde",
|
||||
"system": "RomM",
|
||||
"until": "Hasta",
|
||||
"yesterday": "Ayer"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Connexion",
|
||||
"action-auth-login-failed": "Échec de la connexion en tant que {username}",
|
||||
"action-auth-login-failed-unknown": "Échec de la connexion avec un nom d'utilisateur inconnu",
|
||||
"action-auth-password-reset": "Réinitialisation du mot de passe de {target}",
|
||||
"action-auth-password-reset-request": "Demande de réinitialisation du mot de passe de {target}",
|
||||
"action-client-token-create": "Création du token d'API {target}",
|
||||
"action-client-token-regenerate": "Régénération du token d'API {target}",
|
||||
"action-client-token-revoke": "Révocation du token d'API {target}",
|
||||
"action-collection-add-roms": "Ajout de {n} jeu à {target} | Ajout de {n} jeux à {target}",
|
||||
"action-collection-create": "Création de la collection {target}",
|
||||
"action-collection-delete": "Suppression de la collection {target}",
|
||||
"action-collection-edit": "Modification de la collection {target}",
|
||||
"action-collection-remove-roms": "Retrait de {n} jeu de {target} | Retrait de {n} jeux de {target}",
|
||||
"action-config-update": "Modification des {setting}",
|
||||
"action-device-approve": "Association de l'appareil {target}",
|
||||
"action-firmware-delete": "Suppression du firmware {target}",
|
||||
"action-firmware-upload": "Téléversement de firmware pour {target}",
|
||||
"action-permission-group-create": "Création du groupe d'autorisations {target}",
|
||||
"action-permission-group-delete": "Suppression du groupe d'autorisations {target}",
|
||||
"action-permission-group-edit": "Modification du groupe d'autorisations {target}",
|
||||
"action-platform-create": "Ajout de la plateforme {target}",
|
||||
"action-platform-delete": "Suppression de la plateforme {target}",
|
||||
"action-platform-edit": "Modification de la plateforme {target}",
|
||||
"action-rom-bulk-download": "Téléchargement de {n} jeu depuis {target} | Téléchargement de {n} jeux depuis {target}",
|
||||
"action-rom-bulk-download-selection": "Téléchargement de {n} jeu | Téléchargement de {n} jeux",
|
||||
"action-rom-create": "Ajout de {target}",
|
||||
"action-rom-delete": "Suppression de {target}",
|
||||
"action-rom-download": "Téléchargement de {target}",
|
||||
"action-rom-edit": "Modification de {target}",
|
||||
"action-rom-file-delete": "Suppression d'un fichier de {target}",
|
||||
"action-rom-match": "Association de {target}",
|
||||
"action-rom-play": "Partie de {target}",
|
||||
"action-rom-player-load": "Chargement de {target} pour jouer",
|
||||
"action-rom-unmatch": "Dissociation de {target}",
|
||||
"action-rom-upload": "Téléversement de {file} dans {target}",
|
||||
"action-scan-failed": "Échec d'un scan",
|
||||
"action-scan-finish": "Fin d'un scan",
|
||||
"action-scan-start": "Lancement d'un scan",
|
||||
"action-scan-stop": "Arrêt du scan",
|
||||
"action-scan-stopped": "Scan interrompu",
|
||||
"action-smart-collection-create": "Création de la collection intelligente {target}",
|
||||
"action-smart-collection-delete": "Suppression de la collection intelligente {target}",
|
||||
"action-smart-collection-edit": "Modification de la collection intelligente {target}",
|
||||
"action-task-run": "Exécution de la tâche {target}",
|
||||
"action-user-create": "Création de l'utilisateur {target}",
|
||||
"action-user-delete": "Suppression de l'utilisateur {target}",
|
||||
"action-user-edit": "Modification de l'utilisateur {target}",
|
||||
"action-user-permissions-edit": "Modification des autorisations de {target}",
|
||||
"action-user-register": "Inscription",
|
||||
"action-visibility-hide": "Masquage de {target} pour {principal}",
|
||||
"action-visibility-unhide": "Réaffichage de {target} pour {principal}",
|
||||
"all-categories": "Toutes les catégories",
|
||||
"all-users": "Tous les utilisateurs",
|
||||
"anonymous": "Anonyme",
|
||||
"category-collections": "Collections",
|
||||
"category-consumption": "Parties et téléchargements",
|
||||
"category-library": "Bibliothèque",
|
||||
"category-operations": "Scans et tâches",
|
||||
"category-security": "Comptes et sécurité",
|
||||
"config-exclusion": "exclusions de scan",
|
||||
"config-platform-binding": "mappages de dossiers des plateformes",
|
||||
"config-platform-version": "versions des plateformes",
|
||||
"config-scan-settings": "paramètres de scan",
|
||||
"deleted-user": "Utilisateur supprimé",
|
||||
"detail-changed": "Modifié : {fields}",
|
||||
"detail-deleted-from-disk": "Également supprimé du disque",
|
||||
"detail-games-added": "{n} jeu ajouté | {n} jeux ajoutés",
|
||||
"detail-games-removed": "{n} jeu retiré | {n} jeux retirés",
|
||||
"detail-login-credentials": "Nom d'utilisateur ou mot de passe incorrect",
|
||||
"detail-login-disabled": "Compte désactivé",
|
||||
"detail-new-games": "Aucun nouveau jeu | {n} nouveau jeu | {n} nouveaux jeux",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Rôle : {from} → {to}",
|
||||
"empty": "Rien n'a encore été enregistré",
|
||||
"events": "Événements",
|
||||
"field-cover": "jaquette",
|
||||
"field-custom-name": "nom",
|
||||
"field-description": "description",
|
||||
"field-email": "e-mail",
|
||||
"field-enabled": "activé",
|
||||
"field-fs-name": "nom du fichier",
|
||||
"field-is-public": "visibilité",
|
||||
"field-manual": "manuel",
|
||||
"field-name": "nom",
|
||||
"field-password": "mot de passe",
|
||||
"field-role": "rôle",
|
||||
"field-summary": "résumé",
|
||||
"field-username": "nom d'utilisateur",
|
||||
"filter-category": "Catégorie",
|
||||
"filter-user": "Utilisateur",
|
||||
"load-error": "Impossible de charger le journal d'audit",
|
||||
"no-matches": "Aucun événement ne correspond à ces filtres",
|
||||
"search-placeholder": "Rechercher des événements",
|
||||
"since": "Du",
|
||||
"system": "RomM",
|
||||
"until": "Au",
|
||||
"yesterday": "Hier"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Bejelentkezett",
|
||||
"action-auth-login-failed": "Sikertelen bejelentkezés {username} néven",
|
||||
"action-auth-login-failed-unknown": "Sikertelen bejelentkezés ismeretlen felhasználónévvel",
|
||||
"action-auth-password-reset": "Visszaállította {target} jelszavát",
|
||||
"action-auth-password-reset-request": "Jelszó-visszaállítást kért {target} számára",
|
||||
"action-client-token-create": "Létrehozta a(z) {target} API tokent",
|
||||
"action-client-token-regenerate": "Újragenerálta a(z) {target} API tokent",
|
||||
"action-client-token-revoke": "Visszavonta a(z) {target} API tokent",
|
||||
"action-collection-add-roms": "Hozzáadott {n} játékot a(z) {target} gyűjteményhez | Hozzáadott {n} játékot a(z) {target} gyűjteményhez",
|
||||
"action-collection-create": "Létrehozta a(z) {target} gyűjteményt",
|
||||
"action-collection-delete": "Törölte a(z) {target} gyűjteményt",
|
||||
"action-collection-edit": "Szerkesztette a(z) {target} gyűjteményt",
|
||||
"action-collection-remove-roms": "Eltávolított {n} játékot a(z) {target} gyűjteményből | Eltávolított {n} játékot a(z) {target} gyűjteményből",
|
||||
"action-config-update": "Módosította {setting}",
|
||||
"action-device-approve": "Párosította a(z) {target} eszközt",
|
||||
"action-firmware-delete": "Törölte a(z) {target} firmware-t",
|
||||
"action-firmware-upload": "Firmware-t töltött fel a(z) {target} platformhoz",
|
||||
"action-permission-group-create": "Létrehozta a(z) {target} jogosultsági csoportot",
|
||||
"action-permission-group-delete": "Törölte a(z) {target} jogosultsági csoportot",
|
||||
"action-permission-group-edit": "Szerkesztette a(z) {target} jogosultsági csoportot",
|
||||
"action-platform-create": "Hozzáadta a(z) {target} platformot",
|
||||
"action-platform-delete": "Törölte a(z) {target} platformot",
|
||||
"action-platform-edit": "Szerkesztette a(z) {target} platformot",
|
||||
"action-rom-bulk-download": "Letöltött {n} játékot innen: {target} | Letöltött {n} játékot innen: {target}",
|
||||
"action-rom-bulk-download-selection": "Letöltött {n} játékot | Letöltött {n} játékot",
|
||||
"action-rom-create": "Hozzáadta a(z) {target} játékot",
|
||||
"action-rom-delete": "Törölte a(z) {target} játékot",
|
||||
"action-rom-download": "Letöltötte a(z) {target} játékot",
|
||||
"action-rom-edit": "Szerkesztette a(z) {target} játékot",
|
||||
"action-rom-file-delete": "Törölt egy fájlt a(z) {target} játékból",
|
||||
"action-rom-match": "Egyeztette a(z) {target} játékot",
|
||||
"action-rom-play": "Játszott a(z) {target} játékkal",
|
||||
"action-rom-player-load": "Játékra betöltötte a(z) {target} játékot",
|
||||
"action-rom-unmatch": "Megszüntette a(z) {target} játék egyeztetését",
|
||||
"action-rom-upload": "Feltöltötte a(z) {file} fájlt ide: {target}",
|
||||
"action-scan-failed": "Egy szkennelés sikertelen volt",
|
||||
"action-scan-finish": "Befejezett egy szkennelést",
|
||||
"action-scan-start": "Elindított egy szkennelést",
|
||||
"action-scan-stop": "Leállította a szkennelést",
|
||||
"action-scan-stopped": "Egy szkennelés le lett állítva",
|
||||
"action-smart-collection-create": "Létrehozta a(z) {target} intelligens gyűjteményt",
|
||||
"action-smart-collection-delete": "Törölte a(z) {target} intelligens gyűjteményt",
|
||||
"action-smart-collection-edit": "Szerkesztette a(z) {target} intelligens gyűjteményt",
|
||||
"action-task-run": "Lefuttatta a(z) {target} feladatot",
|
||||
"action-user-create": "Létrehozta a(z) {target} felhasználót",
|
||||
"action-user-delete": "Törölte a(z) {target} felhasználót",
|
||||
"action-user-edit": "Szerkesztette a(z) {target} felhasználót",
|
||||
"action-user-permissions-edit": "Módosította {target} jogosultságait",
|
||||
"action-user-register": "Regisztrált",
|
||||
"action-visibility-hide": "Elrejtette a(z) {target} elemet {principal} elől",
|
||||
"action-visibility-unhide": "Újra megjelenítette a(z) {target} elemet {principal} számára",
|
||||
"all-categories": "Minden kategória",
|
||||
"all-users": "Minden felhasználó",
|
||||
"anonymous": "Névtelen",
|
||||
"category-collections": "Gyűjtemények",
|
||||
"category-consumption": "Játékmenetek és letöltések",
|
||||
"category-library": "Könyvtár",
|
||||
"category-operations": "Szkennelések és feladatok",
|
||||
"category-security": "Fiókok és biztonság",
|
||||
"config-exclusion": "a szkennelési kizárásokat",
|
||||
"config-platform-binding": "a platformok mappaleképezéseit",
|
||||
"config-platform-version": "a platformverziókat",
|
||||
"config-scan-settings": "a szkennelési beállításokat",
|
||||
"deleted-user": "Törölt felhasználó",
|
||||
"detail-changed": "Módosítva: {fields}",
|
||||
"detail-deleted-from-disk": "A lemezről is törölve",
|
||||
"detail-games-added": "{n} játék hozzáadva | {n} játék hozzáadva",
|
||||
"detail-games-removed": "{n} játék eltávolítva | {n} játék eltávolítva",
|
||||
"detail-login-credentials": "Hibás felhasználónév vagy jelszó",
|
||||
"detail-login-disabled": "Fiók letiltva",
|
||||
"detail-new-games": "Nincs új játék | {n} új játék | {n} új játék",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Szerepkör: {from} → {to}",
|
||||
"empty": "Még nincs rögzített esemény",
|
||||
"events": "Események",
|
||||
"field-cover": "borítókép",
|
||||
"field-custom-name": "név",
|
||||
"field-description": "leírás",
|
||||
"field-email": "e-mail",
|
||||
"field-enabled": "engedélyezve",
|
||||
"field-fs-name": "fájlnév",
|
||||
"field-is-public": "láthatóság",
|
||||
"field-manual": "kézikönyv",
|
||||
"field-name": "név",
|
||||
"field-password": "jelszó",
|
||||
"field-role": "szerepkör",
|
||||
"field-summary": "összefoglaló",
|
||||
"field-username": "felhasználónév",
|
||||
"filter-category": "Kategória",
|
||||
"filter-user": "Felhasználó",
|
||||
"load-error": "Nem sikerült betölteni az auditnaplót",
|
||||
"no-matches": "Egy esemény sem felel meg ezeknek a szűrőknek",
|
||||
"search-placeholder": "Események keresése",
|
||||
"since": "Ettől",
|
||||
"system": "RomM",
|
||||
"until": "Eddig",
|
||||
"yesterday": "Tegnap"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Ha effettuato l'accesso",
|
||||
"action-auth-login-failed": "Accesso come {username} non riuscito",
|
||||
"action-auth-login-failed-unknown": "Accesso con un nome utente sconosciuto non riuscito",
|
||||
"action-auth-password-reset": "Ha reimpostato la password di {target}",
|
||||
"action-auth-password-reset-request": "Ha richiesto la reimpostazione della password di {target}",
|
||||
"action-client-token-create": "Ha creato il token API {target}",
|
||||
"action-client-token-regenerate": "Ha rigenerato il token API {target}",
|
||||
"action-client-token-revoke": "Ha revocato il token API {target}",
|
||||
"action-collection-add-roms": "Ha aggiunto {n} gioco a {target} | Ha aggiunto {n} giochi a {target}",
|
||||
"action-collection-create": "Ha creato la collezione {target}",
|
||||
"action-collection-delete": "Ha eliminato la collezione {target}",
|
||||
"action-collection-edit": "Ha modificato la collezione {target}",
|
||||
"action-collection-remove-roms": "Ha rimosso {n} gioco da {target} | Ha rimosso {n} giochi da {target}",
|
||||
"action-config-update": "Ha modificato {setting}",
|
||||
"action-device-approve": "Ha associato il dispositivo {target}",
|
||||
"action-firmware-delete": "Ha eliminato il firmware {target}",
|
||||
"action-firmware-upload": "Ha caricato il firmware per {target}",
|
||||
"action-permission-group-create": "Ha creato il gruppo di permessi {target}",
|
||||
"action-permission-group-delete": "Ha eliminato il gruppo di permessi {target}",
|
||||
"action-permission-group-edit": "Ha modificato il gruppo di permessi {target}",
|
||||
"action-platform-create": "Ha aggiunto la piattaforma {target}",
|
||||
"action-platform-delete": "Ha eliminato la piattaforma {target}",
|
||||
"action-platform-edit": "Ha modificato la piattaforma {target}",
|
||||
"action-rom-bulk-download": "Ha scaricato {n} gioco da {target} | Ha scaricato {n} giochi da {target}",
|
||||
"action-rom-bulk-download-selection": "Ha scaricato {n} gioco | Ha scaricato {n} giochi",
|
||||
"action-rom-create": "Ha aggiunto {target}",
|
||||
"action-rom-delete": "Ha eliminato {target}",
|
||||
"action-rom-download": "Ha scaricato {target}",
|
||||
"action-rom-edit": "Ha modificato {target}",
|
||||
"action-rom-file-delete": "Ha eliminato un file di {target}",
|
||||
"action-rom-match": "Ha associato {target}",
|
||||
"action-rom-play": "Ha giocato a {target}",
|
||||
"action-rom-player-load": "Ha caricato {target} per giocare",
|
||||
"action-rom-unmatch": "Ha rimosso l'associazione di {target}",
|
||||
"action-rom-upload": "Ha caricato {file} in {target}",
|
||||
"action-scan-failed": "Una scansione non è riuscita",
|
||||
"action-scan-finish": "Ha completato una scansione",
|
||||
"action-scan-start": "Ha avviato una scansione",
|
||||
"action-scan-stop": "Ha interrotto la scansione",
|
||||
"action-scan-stopped": "Una scansione è stata interrotta",
|
||||
"action-smart-collection-create": "Ha creato la collezione intelligente {target}",
|
||||
"action-smart-collection-delete": "Ha eliminato la collezione intelligente {target}",
|
||||
"action-smart-collection-edit": "Ha modificato la collezione intelligente {target}",
|
||||
"action-task-run": "Ha eseguito l'attività {target}",
|
||||
"action-user-create": "Ha creato l'utente {target}",
|
||||
"action-user-delete": "Ha eliminato l'utente {target}",
|
||||
"action-user-edit": "Ha modificato l'utente {target}",
|
||||
"action-user-permissions-edit": "Ha modificato i permessi di {target}",
|
||||
"action-user-register": "Ha effettuato la registrazione",
|
||||
"action-visibility-hide": "Ha nascosto {target} a {principal}",
|
||||
"action-visibility-unhide": "Ha mostrato di nuovo {target} a {principal}",
|
||||
"all-categories": "Tutte le categorie",
|
||||
"all-users": "Tutti gli utenti",
|
||||
"anonymous": "Anonimo",
|
||||
"category-collections": "Collezioni",
|
||||
"category-consumption": "Partite e download",
|
||||
"category-library": "Libreria",
|
||||
"category-operations": "Scansioni e attività",
|
||||
"category-security": "Account e sicurezza",
|
||||
"config-exclusion": "le esclusioni della scansione",
|
||||
"config-platform-binding": "le mappature delle cartelle delle piattaforme",
|
||||
"config-platform-version": "le versioni delle piattaforme",
|
||||
"config-scan-settings": "le impostazioni di scansione",
|
||||
"deleted-user": "Utente eliminato",
|
||||
"detail-changed": "Modificato: {fields}",
|
||||
"detail-deleted-from-disk": "Eliminato anche dal disco",
|
||||
"detail-games-added": "{n} gioco aggiunto | {n} giochi aggiunti",
|
||||
"detail-games-removed": "{n} gioco rimosso | {n} giochi rimossi",
|
||||
"detail-login-credentials": "Nome utente o password errati",
|
||||
"detail-login-disabled": "Account disabilitato",
|
||||
"detail-new-games": "Nessun nuovo gioco | {n} nuovo gioco | {n} nuovi giochi",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Ruolo: {from} → {to}",
|
||||
"empty": "Non è stato ancora registrato nulla",
|
||||
"events": "Eventi",
|
||||
"field-cover": "copertina",
|
||||
"field-custom-name": "nome",
|
||||
"field-description": "descrizione",
|
||||
"field-email": "email",
|
||||
"field-enabled": "abilitato",
|
||||
"field-fs-name": "nome file",
|
||||
"field-is-public": "visibilità",
|
||||
"field-manual": "manuale",
|
||||
"field-name": "nome",
|
||||
"field-password": "password",
|
||||
"field-role": "ruolo",
|
||||
"field-summary": "riepilogo",
|
||||
"field-username": "nome utente",
|
||||
"filter-category": "Categoria",
|
||||
"filter-user": "Utente",
|
||||
"load-error": "Impossibile caricare il registro di audit",
|
||||
"no-matches": "Nessun evento corrisponde a questi filtri",
|
||||
"search-placeholder": "Cerca eventi",
|
||||
"since": "Dal",
|
||||
"system": "RomM",
|
||||
"until": "Al",
|
||||
"yesterday": "Ieri"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "ログインしました",
|
||||
"action-auth-login-failed": "{username}としてのログインに失敗しました",
|
||||
"action-auth-login-failed-unknown": "不明なユーザ名でのログインに失敗しました",
|
||||
"action-auth-password-reset": "「{target}」のパスワードをリセットしました",
|
||||
"action-auth-password-reset-request": "「{target}」のパスワードリセットをリクエストしました",
|
||||
"action-client-token-create": "APIトークン「{target}」を作成しました",
|
||||
"action-client-token-regenerate": "APIトークン「{target}」を再生成しました",
|
||||
"action-client-token-revoke": "APIトークン「{target}」を取り消しました",
|
||||
"action-collection-add-roms": "「{target}」にゲームを{n}件追加しました | 「{target}」にゲームを{n}件追加しました",
|
||||
"action-collection-create": "コレクション「{target}」を作成しました",
|
||||
"action-collection-delete": "コレクション「{target}」を削除しました",
|
||||
"action-collection-edit": "コレクション「{target}」を編集しました",
|
||||
"action-collection-remove-roms": "「{target}」からゲームを{n}件削除しました | 「{target}」からゲームを{n}件削除しました",
|
||||
"action-config-update": "{setting}を変更しました",
|
||||
"action-device-approve": "デバイス「{target}」をペアリングしました",
|
||||
"action-firmware-delete": "ファームウェア「{target}」を削除しました",
|
||||
"action-firmware-upload": "「{target}」のファームウェアをアップロードしました",
|
||||
"action-permission-group-create": "権限グループ「{target}」を作成しました",
|
||||
"action-permission-group-delete": "権限グループ「{target}」を削除しました",
|
||||
"action-permission-group-edit": "権限グループ「{target}」を編集しました",
|
||||
"action-platform-create": "プラットフォーム「{target}」を追加しました",
|
||||
"action-platform-delete": "プラットフォーム「{target}」を削除しました",
|
||||
"action-platform-edit": "プラットフォーム「{target}」を編集しました",
|
||||
"action-rom-bulk-download": "「{target}」からゲームを{n}件ダウンロードしました | 「{target}」からゲームを{n}件ダウンロードしました",
|
||||
"action-rom-bulk-download-selection": "ゲームを{n}件ダウンロードしました | ゲームを{n}件ダウンロードしました",
|
||||
"action-rom-create": "「{target}」を追加しました",
|
||||
"action-rom-delete": "「{target}」を削除しました",
|
||||
"action-rom-download": "「{target}」をダウンロードしました",
|
||||
"action-rom-edit": "「{target}」を編集しました",
|
||||
"action-rom-file-delete": "「{target}」のファイルを削除しました",
|
||||
"action-rom-match": "「{target}」をマッチしました",
|
||||
"action-rom-play": "「{target}」をプレイしました",
|
||||
"action-rom-player-load": "「{target}」をプレイ用に読み込みました",
|
||||
"action-rom-unmatch": "「{target}」のマッチを解除しました",
|
||||
"action-rom-upload": "{file}を「{target}」にアップロードしました",
|
||||
"action-scan-failed": "スキャンが失敗しました",
|
||||
"action-scan-finish": "スキャンを完了しました",
|
||||
"action-scan-start": "スキャンを開始しました",
|
||||
"action-scan-stop": "スキャンを停止しました",
|
||||
"action-scan-stopped": "スキャンが停止されました",
|
||||
"action-smart-collection-create": "スマートコレクション「{target}」を作成しました",
|
||||
"action-smart-collection-delete": "スマートコレクション「{target}」を削除しました",
|
||||
"action-smart-collection-edit": "スマートコレクション「{target}」を編集しました",
|
||||
"action-task-run": "タスク「{target}」を実行しました",
|
||||
"action-user-create": "ユーザー「{target}」を作成しました",
|
||||
"action-user-delete": "ユーザー「{target}」を削除しました",
|
||||
"action-user-edit": "ユーザー「{target}」を編集しました",
|
||||
"action-user-permissions-edit": "「{target}」の権限を変更しました",
|
||||
"action-user-register": "アカウントを登録しました",
|
||||
"action-visibility-hide": "「{target}」を{principal}に対して非表示にしました",
|
||||
"action-visibility-unhide": "「{target}」を{principal}に再表示しました",
|
||||
"all-categories": "すべてのカテゴリ",
|
||||
"all-users": "すべてのユーザー",
|
||||
"anonymous": "匿名",
|
||||
"category-collections": "コレクション",
|
||||
"category-consumption": "プレイとダウンロード",
|
||||
"category-library": "ライブラリ",
|
||||
"category-operations": "スキャンとタスク",
|
||||
"category-security": "アカウントとセキュリティ",
|
||||
"config-exclusion": "スキャンの除外設定",
|
||||
"config-platform-binding": "プラットフォームのフォルダマッピング",
|
||||
"config-platform-version": "プラットフォームバージョン",
|
||||
"config-scan-settings": "スキャン設定",
|
||||
"deleted-user": "削除されたユーザー",
|
||||
"detail-changed": "変更: {fields}",
|
||||
"detail-deleted-from-disk": "ディスクからも削除",
|
||||
"detail-games-added": "ゲーム{n}件を追加 | ゲーム{n}件を追加",
|
||||
"detail-games-removed": "ゲーム{n}件を削除 | ゲーム{n}件を削除",
|
||||
"detail-login-credentials": "ユーザ名またはパスワードが正しくありません",
|
||||
"detail-login-disabled": "アカウントが無効です",
|
||||
"detail-new-games": "新しいゲームはありません | 新しいゲーム{n}件 | 新しいゲーム{n}件",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "役割: {from} → {to}",
|
||||
"empty": "まだ何も記録されていません",
|
||||
"events": "イベント",
|
||||
"field-cover": "カバーアート",
|
||||
"field-custom-name": "名前",
|
||||
"field-description": "説明",
|
||||
"field-email": "メール",
|
||||
"field-enabled": "有効",
|
||||
"field-fs-name": "ファイル名",
|
||||
"field-is-public": "公開設定",
|
||||
"field-manual": "マニュアル",
|
||||
"field-name": "名前",
|
||||
"field-password": "パスワード",
|
||||
"field-role": "役割",
|
||||
"field-summary": "概要",
|
||||
"field-username": "ユーザ名",
|
||||
"filter-category": "カテゴリ",
|
||||
"filter-user": "ユーザー",
|
||||
"load-error": "監査ログを読み込めませんでした",
|
||||
"no-matches": "条件に一致するイベントはありません",
|
||||
"search-placeholder": "イベントを検索",
|
||||
"since": "開始",
|
||||
"system": "RomM",
|
||||
"until": "終了",
|
||||
"yesterday": "昨日"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "로그인했습니다",
|
||||
"action-auth-login-failed": "{username}(으)로 로그인하지 못했습니다",
|
||||
"action-auth-login-failed-unknown": "알 수 없는 아이디로 로그인하지 못했습니다",
|
||||
"action-auth-password-reset": "{target}의 비밀번호를 재설정했습니다",
|
||||
"action-auth-password-reset-request": "{target}의 비밀번호 재설정을 요청했습니다",
|
||||
"action-client-token-create": "API 토큰 {target}을(를) 생성했습니다",
|
||||
"action-client-token-regenerate": "API 토큰 {target}을(를) 재생성했습니다",
|
||||
"action-client-token-revoke": "API 토큰 {target}을(를) 폐기했습니다",
|
||||
"action-collection-add-roms": "{target}에 게임 {n}개를 추가했습니다 | {target}에 게임 {n}개를 추가했습니다",
|
||||
"action-collection-create": "모음집 {target}을(를) 생성했습니다",
|
||||
"action-collection-delete": "모음집 {target}을(를) 삭제했습니다",
|
||||
"action-collection-edit": "모음집 {target}을(를) 수정했습니다",
|
||||
"action-collection-remove-roms": "{target}에서 게임 {n}개를 제거했습니다 | {target}에서 게임 {n}개를 제거했습니다",
|
||||
"action-config-update": "{setting}을(를) 변경했습니다",
|
||||
"action-device-approve": "장치 {target}을(를) 페어링했습니다",
|
||||
"action-firmware-delete": "펌웨어 {target}을(를) 삭제했습니다",
|
||||
"action-firmware-upload": "{target}용 펌웨어를 업로드했습니다",
|
||||
"action-permission-group-create": "권한 그룹 {target}을(를) 생성했습니다",
|
||||
"action-permission-group-delete": "권한 그룹 {target}을(를) 삭제했습니다",
|
||||
"action-permission-group-edit": "권한 그룹 {target}을(를) 수정했습니다",
|
||||
"action-platform-create": "플랫폼 {target}을(를) 추가했습니다",
|
||||
"action-platform-delete": "플랫폼 {target}을(를) 삭제했습니다",
|
||||
"action-platform-edit": "플랫폼 {target}을(를) 수정했습니다",
|
||||
"action-rom-bulk-download": "{target}에서 게임 {n}개를 다운로드했습니다 | {target}에서 게임 {n}개를 다운로드했습니다",
|
||||
"action-rom-bulk-download-selection": "게임 {n}개를 다운로드했습니다 | 게임 {n}개를 다운로드했습니다",
|
||||
"action-rom-create": "{target}을(를) 추가했습니다",
|
||||
"action-rom-delete": "{target}을(를) 삭제했습니다",
|
||||
"action-rom-download": "{target}을(를) 다운로드했습니다",
|
||||
"action-rom-edit": "{target}을(를) 수정했습니다",
|
||||
"action-rom-file-delete": "{target}의 파일을 삭제했습니다",
|
||||
"action-rom-match": "{target}을(를) DB에 대응했습니다",
|
||||
"action-rom-play": "{target}을(를) 플레이했습니다",
|
||||
"action-rom-player-load": "플레이하려고 {target}을(를) 불러왔습니다",
|
||||
"action-rom-unmatch": "{target}의 DB 대응을 해제했습니다",
|
||||
"action-rom-upload": "{file}을(를) {target}에 업로드했습니다",
|
||||
"action-scan-failed": "스캔이 실패했습니다",
|
||||
"action-scan-finish": "스캔을 완료했습니다",
|
||||
"action-scan-start": "스캔을 시작했습니다",
|
||||
"action-scan-stop": "스캔을 중지했습니다",
|
||||
"action-scan-stopped": "스캔이 중지되었습니다",
|
||||
"action-smart-collection-create": "스마트 모음집 {target}을(를) 생성했습니다",
|
||||
"action-smart-collection-delete": "스마트 모음집 {target}을(를) 삭제했습니다",
|
||||
"action-smart-collection-edit": "스마트 모음집 {target}을(를) 수정했습니다",
|
||||
"action-task-run": "작업 {target}을(를) 실행했습니다",
|
||||
"action-user-create": "사용자 {target}을(를) 생성했습니다",
|
||||
"action-user-delete": "사용자 {target}을(를) 삭제했습니다",
|
||||
"action-user-edit": "사용자 {target}을(를) 수정했습니다",
|
||||
"action-user-permissions-edit": "{target}의 권한을 변경했습니다",
|
||||
"action-user-register": "가입했습니다",
|
||||
"action-visibility-hide": "{principal}에게 {target}을(를) 숨겼습니다",
|
||||
"action-visibility-unhide": "{principal}에게 {target}을(를) 다시 표시했습니다",
|
||||
"all-categories": "모든 분류",
|
||||
"all-users": "모든 사용자",
|
||||
"anonymous": "익명",
|
||||
"category-collections": "모음집",
|
||||
"category-consumption": "플레이 및 다운로드",
|
||||
"category-library": "라이브러리",
|
||||
"category-operations": "스캔 및 작업",
|
||||
"category-security": "계정 및 보안",
|
||||
"config-exclusion": "스캔 제외 항목",
|
||||
"config-platform-binding": "플랫폼 폴더 매핑",
|
||||
"config-platform-version": "플랫폼 버전",
|
||||
"config-scan-settings": "스캔 설정",
|
||||
"deleted-user": "삭제된 사용자",
|
||||
"detail-changed": "변경됨: {fields}",
|
||||
"detail-deleted-from-disk": "디스크에서도 삭제됨",
|
||||
"detail-games-added": "게임 {n}개 추가됨 | 게임 {n}개 추가됨",
|
||||
"detail-games-removed": "게임 {n}개 제거됨 | 게임 {n}개 제거됨",
|
||||
"detail-login-credentials": "아이디 또는 패스워드가 올바르지 않습니다",
|
||||
"detail-login-disabled": "비활성화된 계정",
|
||||
"detail-new-games": "새 게임 없음 | 새 게임 {n}개 | 새 게임 {n}개",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "역할: {from} → {to}",
|
||||
"empty": "아직 기록된 항목이 없습니다",
|
||||
"events": "이벤트",
|
||||
"field-cover": "커버",
|
||||
"field-custom-name": "이름",
|
||||
"field-description": "설명",
|
||||
"field-email": "이메일",
|
||||
"field-enabled": "활성화됨",
|
||||
"field-fs-name": "파일 이름",
|
||||
"field-is-public": "공개 여부",
|
||||
"field-manual": "매뉴얼",
|
||||
"field-name": "이름",
|
||||
"field-password": "패스워드",
|
||||
"field-role": "역할",
|
||||
"field-summary": "요약",
|
||||
"field-username": "아이디",
|
||||
"filter-category": "분류",
|
||||
"filter-user": "사용자",
|
||||
"load-error": "감사 로그를 불러올 수 없습니다",
|
||||
"no-matches": "이 필터와 일치하는 이벤트가 없습니다",
|
||||
"search-placeholder": "이벤트 검색",
|
||||
"since": "시작",
|
||||
"system": "RomM",
|
||||
"until": "종료",
|
||||
"yesterday": "어제"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Zalogowano",
|
||||
"action-auth-login-failed": "Nieudane logowanie jako {username}",
|
||||
"action-auth-login-failed-unknown": "Nieudane logowanie z nieznaną nazwą użytkownika",
|
||||
"action-auth-password-reset": "Zresetowano hasło użytkownika {target}",
|
||||
"action-auth-password-reset-request": "Poproszono o reset hasła użytkownika {target}",
|
||||
"action-client-token-create": "Utworzono token API {target}",
|
||||
"action-client-token-regenerate": "Wygenerowano ponownie token API {target}",
|
||||
"action-client-token-revoke": "Unieważniono token API {target}",
|
||||
"action-collection-add-roms": "Dodano {n} gier do kolekcji {target} | Dodano {n} grę do kolekcji {target} | Dodano gry do kolekcji {target}: {n}",
|
||||
"action-collection-create": "Utworzono kolekcję {target}",
|
||||
"action-collection-delete": "Usunięto kolekcję {target}",
|
||||
"action-collection-edit": "Edytowano kolekcję {target}",
|
||||
"action-collection-remove-roms": "Usunięto {n} gier z kolekcji {target} | Usunięto {n} grę z kolekcji {target} | Usunięto gry z kolekcji {target}: {n}",
|
||||
"action-config-update": "Zmieniono {setting}",
|
||||
"action-device-approve": "Sparowano urządzenie {target}",
|
||||
"action-firmware-delete": "Usunięto firmware {target}",
|
||||
"action-firmware-upload": "Przesłano firmware dla {target}",
|
||||
"action-permission-group-create": "Utworzono grupę uprawnień {target}",
|
||||
"action-permission-group-delete": "Usunięto grupę uprawnień {target}",
|
||||
"action-permission-group-edit": "Edytowano grupę uprawnień {target}",
|
||||
"action-platform-create": "Dodano platformę {target}",
|
||||
"action-platform-delete": "Usunięto platformę {target}",
|
||||
"action-platform-edit": "Edytowano platformę {target}",
|
||||
"action-rom-bulk-download": "Pobrano {n} gier z {target} | Pobrano {n} grę z {target} | Pobrano gry z {target}: {n}",
|
||||
"action-rom-bulk-download-selection": "Pobrano {n} gier | Pobrano {n} grę | Pobrano gry: {n}",
|
||||
"action-rom-create": "Dodano {target}",
|
||||
"action-rom-delete": "Usunięto {target}",
|
||||
"action-rom-download": "Pobrano {target}",
|
||||
"action-rom-edit": "Edytowano {target}",
|
||||
"action-rom-file-delete": "Usunięto plik gry {target}",
|
||||
"action-rom-match": "Dopasowano {target}",
|
||||
"action-rom-play": "Zagrano w {target}",
|
||||
"action-rom-player-load": "Wczytano {target} do gry",
|
||||
"action-rom-unmatch": "Usunięto dopasowanie {target}",
|
||||
"action-rom-upload": "Przesłano {file} do {target}",
|
||||
"action-scan-failed": "Skanowanie nie powiodło się",
|
||||
"action-scan-finish": "Zakończono skanowanie",
|
||||
"action-scan-start": "Rozpoczęto skanowanie",
|
||||
"action-scan-stop": "Zatrzymano skanowanie",
|
||||
"action-scan-stopped": "Skanowanie zostało zatrzymane",
|
||||
"action-smart-collection-create": "Utworzono inteligentną kolekcję {target}",
|
||||
"action-smart-collection-delete": "Usunięto inteligentną kolekcję {target}",
|
||||
"action-smart-collection-edit": "Edytowano inteligentną kolekcję {target}",
|
||||
"action-task-run": "Uruchomiono zadanie {target}",
|
||||
"action-user-create": "Utworzono użytkownika {target}",
|
||||
"action-user-delete": "Usunięto użytkownika {target}",
|
||||
"action-user-edit": "Edytowano użytkownika {target}",
|
||||
"action-user-permissions-edit": "Zmieniono uprawnienia użytkownika {target}",
|
||||
"action-user-register": "Zarejestrowano konto",
|
||||
"action-visibility-hide": "Ukryto {target} przed {principal}",
|
||||
"action-visibility-unhide": "Przywrócono widoczność {target} dla {principal}",
|
||||
"all-categories": "Wszystkie kategorie",
|
||||
"all-users": "Wszyscy użytkownicy",
|
||||
"anonymous": "Anonim",
|
||||
"category-collections": "Kolekcje",
|
||||
"category-consumption": "Granie i pobieranie",
|
||||
"category-library": "Biblioteka",
|
||||
"category-operations": "Skanowania i zadania",
|
||||
"category-security": "Konta i bezpieczeństwo",
|
||||
"config-exclusion": "wykluczenia skanowania",
|
||||
"config-platform-binding": "mapowania folderów platform",
|
||||
"config-platform-version": "wersje platform",
|
||||
"config-scan-settings": "ustawienia skanowania",
|
||||
"deleted-user": "Usunięty użytkownik",
|
||||
"detail-changed": "Zmieniono: {fields}",
|
||||
"detail-deleted-from-disk": "Usunięto również z dysku",
|
||||
"detail-games-added": "Dodano {n} gier | Dodano {n} grę | Dodane gry: {n}",
|
||||
"detail-games-removed": "Usunięto {n} gier | Usunięto {n} grę | Usunięte gry: {n}",
|
||||
"detail-login-credentials": "Nieprawidłowa nazwa użytkownika lub hasło",
|
||||
"detail-login-disabled": "Konto wyłączone",
|
||||
"detail-new-games": "Brak nowych gier | {n} nowa gra | Nowe gry: {n}",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Rola: {from} → {to}",
|
||||
"empty": "Nic jeszcze nie zarejestrowano",
|
||||
"events": "Zdarzenia",
|
||||
"field-cover": "okładka",
|
||||
"field-custom-name": "nazwa",
|
||||
"field-description": "opis",
|
||||
"field-email": "e-mail",
|
||||
"field-enabled": "włączone",
|
||||
"field-fs-name": "nazwa pliku",
|
||||
"field-is-public": "widoczność",
|
||||
"field-manual": "instrukcja",
|
||||
"field-name": "nazwa",
|
||||
"field-password": "hasło",
|
||||
"field-role": "rola",
|
||||
"field-summary": "podsumowanie",
|
||||
"field-username": "nazwa użytkownika",
|
||||
"filter-category": "Kategoria",
|
||||
"filter-user": "Użytkownik",
|
||||
"load-error": "Nie udało się wczytać dziennika audytu",
|
||||
"no-matches": "Żadne zdarzenia nie pasują do tych filtrów",
|
||||
"search-placeholder": "Szukaj zdarzeń",
|
||||
"since": "Od",
|
||||
"system": "RomM",
|
||||
"until": "Do",
|
||||
"yesterday": "Wczoraj"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Fez login",
|
||||
"action-auth-login-failed": "Falha ao fazer login como {username}",
|
||||
"action-auth-login-failed-unknown": "Falha ao fazer login com um nome de usuário desconhecido",
|
||||
"action-auth-password-reset": "Redefiniu a senha de {target}",
|
||||
"action-auth-password-reset-request": "Solicitou a redefinição da senha de {target}",
|
||||
"action-client-token-create": "Criou o token de API {target}",
|
||||
"action-client-token-regenerate": "Regenerou o token de API {target}",
|
||||
"action-client-token-revoke": "Revogou o token de API {target}",
|
||||
"action-collection-add-roms": "Adicionou {n} jogo a {target} | Adicionou {n} jogos a {target}",
|
||||
"action-collection-create": "Criou a coleção {target}",
|
||||
"action-collection-delete": "Excluiu a coleção {target}",
|
||||
"action-collection-edit": "Editou a coleção {target}",
|
||||
"action-collection-remove-roms": "Removeu {n} jogo de {target} | Removeu {n} jogos de {target}",
|
||||
"action-config-update": "Alterou {setting}",
|
||||
"action-device-approve": "Pareou o dispositivo {target}",
|
||||
"action-firmware-delete": "Excluiu o firmware {target}",
|
||||
"action-firmware-upload": "Enviou firmware para {target}",
|
||||
"action-permission-group-create": "Criou o grupo de permissões {target}",
|
||||
"action-permission-group-delete": "Excluiu o grupo de permissões {target}",
|
||||
"action-permission-group-edit": "Editou o grupo de permissões {target}",
|
||||
"action-platform-create": "Adicionou a plataforma {target}",
|
||||
"action-platform-delete": "Excluiu a plataforma {target}",
|
||||
"action-platform-edit": "Editou a plataforma {target}",
|
||||
"action-rom-bulk-download": "Baixou {n} jogo de {target} | Baixou {n} jogos de {target}",
|
||||
"action-rom-bulk-download-selection": "Baixou {n} jogo | Baixou {n} jogos",
|
||||
"action-rom-create": "Adicionou {target}",
|
||||
"action-rom-delete": "Excluiu {target}",
|
||||
"action-rom-download": "Baixou {target}",
|
||||
"action-rom-edit": "Editou {target}",
|
||||
"action-rom-file-delete": "Excluiu um arquivo de {target}",
|
||||
"action-rom-match": "Vinculou {target}",
|
||||
"action-rom-play": "Jogou {target}",
|
||||
"action-rom-player-load": "Carregou {target} para jogar",
|
||||
"action-rom-unmatch": "Desvinculou {target}",
|
||||
"action-rom-upload": "Enviou {file} para {target}",
|
||||
"action-scan-failed": "Um escaneamento falhou",
|
||||
"action-scan-finish": "Concluiu um escaneamento",
|
||||
"action-scan-start": "Iniciou um escaneamento",
|
||||
"action-scan-stop": "Interrompeu o escaneamento",
|
||||
"action-scan-stopped": "Um escaneamento foi interrompido",
|
||||
"action-smart-collection-create": "Criou a coleção inteligente {target}",
|
||||
"action-smart-collection-delete": "Excluiu a coleção inteligente {target}",
|
||||
"action-smart-collection-edit": "Editou a coleção inteligente {target}",
|
||||
"action-task-run": "Executou a tarefa {target}",
|
||||
"action-user-create": "Criou o usuário {target}",
|
||||
"action-user-delete": "Excluiu o usuário {target}",
|
||||
"action-user-edit": "Editou o usuário {target}",
|
||||
"action-user-permissions-edit": "Alterou as permissões de {target}",
|
||||
"action-user-register": "Criou uma conta",
|
||||
"action-visibility-hide": "Ocultou {target} de {principal}",
|
||||
"action-visibility-unhide": "Voltou a mostrar {target} para {principal}",
|
||||
"all-categories": "Todas as categorias",
|
||||
"all-users": "Todos os usuários",
|
||||
"anonymous": "Anônimo",
|
||||
"category-collections": "Coleções",
|
||||
"category-consumption": "Partidas e downloads",
|
||||
"category-library": "Biblioteca",
|
||||
"category-operations": "Escaneamentos e tarefas",
|
||||
"category-security": "Contas e segurança",
|
||||
"config-exclusion": "as exclusões do escaneamento",
|
||||
"config-platform-binding": "os mapeamentos de pastas das plataformas",
|
||||
"config-platform-version": "as versões das plataformas",
|
||||
"config-scan-settings": "as configurações de escaneamento",
|
||||
"deleted-user": "Usuário excluído",
|
||||
"detail-changed": "Alterado: {fields}",
|
||||
"detail-deleted-from-disk": "Também excluído do disco",
|
||||
"detail-games-added": "{n} jogo adicionado | {n} jogos adicionados",
|
||||
"detail-games-removed": "{n} jogo removido | {n} jogos removidos",
|
||||
"detail-login-credentials": "Nome de usuário ou senha incorretos",
|
||||
"detail-login-disabled": "Conta desativada",
|
||||
"detail-new-games": "Nenhum jogo novo | {n} jogo novo | {n} jogos novos",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Papel: {from} → {to}",
|
||||
"empty": "Nada foi registrado ainda",
|
||||
"events": "Eventos",
|
||||
"field-cover": "capa",
|
||||
"field-custom-name": "nome",
|
||||
"field-description": "descrição",
|
||||
"field-email": "e-mail",
|
||||
"field-enabled": "habilitado",
|
||||
"field-fs-name": "nome do arquivo",
|
||||
"field-is-public": "visibilidade",
|
||||
"field-manual": "manual",
|
||||
"field-name": "nome",
|
||||
"field-password": "senha",
|
||||
"field-role": "papel",
|
||||
"field-summary": "resumo",
|
||||
"field-username": "nome de usuário",
|
||||
"filter-category": "Categoria",
|
||||
"filter-user": "Usuário",
|
||||
"load-error": "Não foi possível carregar o registro de auditoria",
|
||||
"no-matches": "Nenhum evento corresponde a estes filtros",
|
||||
"search-placeholder": "Buscar eventos",
|
||||
"since": "De",
|
||||
"system": "RomM",
|
||||
"until": "Até",
|
||||
"yesterday": "Ontem"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "S-a autentificat",
|
||||
"action-auth-login-failed": "Autentificare eșuată ca {username}",
|
||||
"action-auth-login-failed-unknown": "Autentificare eșuată cu un nume de utilizator necunoscut",
|
||||
"action-auth-password-reset": "A resetat parola utilizatorului {target}",
|
||||
"action-auth-password-reset-request": "A solicitat resetarea parolei pentru {target}",
|
||||
"action-client-token-create": "A creat token-ul API {target}",
|
||||
"action-client-token-regenerate": "A regenerat token-ul API {target}",
|
||||
"action-client-token-revoke": "A revocat token-ul API {target}",
|
||||
"action-collection-add-roms": "A adăugat {n} joc în {target} | A adăugat {n} jocuri în {target}",
|
||||
"action-collection-create": "A creat colecția {target}",
|
||||
"action-collection-delete": "A șters colecția {target}",
|
||||
"action-collection-edit": "A editat colecția {target}",
|
||||
"action-collection-remove-roms": "A eliminat {n} joc din {target} | A eliminat {n} jocuri din {target}",
|
||||
"action-config-update": "A modificat {setting}",
|
||||
"action-device-approve": "A asociat dispozitivul {target}",
|
||||
"action-firmware-delete": "A șters firmware-ul {target}",
|
||||
"action-firmware-upload": "A încărcat firmware pentru {target}",
|
||||
"action-permission-group-create": "A creat grupul de permisiuni {target}",
|
||||
"action-permission-group-delete": "A șters grupul de permisiuni {target}",
|
||||
"action-permission-group-edit": "A editat grupul de permisiuni {target}",
|
||||
"action-platform-create": "A adăugat platforma {target}",
|
||||
"action-platform-delete": "A șters platforma {target}",
|
||||
"action-platform-edit": "A editat platforma {target}",
|
||||
"action-rom-bulk-download": "A descărcat {n} joc din {target} | A descărcat {n} jocuri din {target}",
|
||||
"action-rom-bulk-download-selection": "A descărcat {n} joc | A descărcat {n} jocuri",
|
||||
"action-rom-create": "A adăugat {target}",
|
||||
"action-rom-delete": "A șters {target}",
|
||||
"action-rom-download": "A descărcat {target}",
|
||||
"action-rom-edit": "A editat {target}",
|
||||
"action-rom-file-delete": "A șters un fișier din {target}",
|
||||
"action-rom-match": "A asociat {target}",
|
||||
"action-rom-play": "A jucat {target}",
|
||||
"action-rom-player-load": "A încărcat {target} pentru a juca",
|
||||
"action-rom-unmatch": "A disociat {target}",
|
||||
"action-rom-upload": "A încărcat {file} în {target}",
|
||||
"action-scan-failed": "O scanare a eșuat",
|
||||
"action-scan-finish": "A finalizat o scanare",
|
||||
"action-scan-start": "A pornit o scanare",
|
||||
"action-scan-stop": "A oprit scanarea",
|
||||
"action-scan-stopped": "O scanare a fost oprită",
|
||||
"action-smart-collection-create": "A creat colecția inteligentă {target}",
|
||||
"action-smart-collection-delete": "A șters colecția inteligentă {target}",
|
||||
"action-smart-collection-edit": "A editat colecția inteligentă {target}",
|
||||
"action-task-run": "A rulat sarcina {target}",
|
||||
"action-user-create": "A creat utilizatorul {target}",
|
||||
"action-user-delete": "A șters utilizatorul {target}",
|
||||
"action-user-edit": "A editat utilizatorul {target}",
|
||||
"action-user-permissions-edit": "A modificat permisiunile utilizatorului {target}",
|
||||
"action-user-register": "S-a înregistrat",
|
||||
"action-visibility-hide": "A ascuns {target} pentru {principal}",
|
||||
"action-visibility-unhide": "A afișat din nou {target} pentru {principal}",
|
||||
"all-categories": "Toate categoriile",
|
||||
"all-users": "Toți utilizatorii",
|
||||
"anonymous": "Anonim",
|
||||
"category-collections": "Colecții",
|
||||
"category-consumption": "Sesiuni de joc și descărcări",
|
||||
"category-library": "Bibliotecă",
|
||||
"category-operations": "Scanări și sarcini",
|
||||
"category-security": "Conturi și securitate",
|
||||
"config-exclusion": "excluderile de la scanare",
|
||||
"config-platform-binding": "mapările dosarelor platformelor",
|
||||
"config-platform-version": "versiunile platformelor",
|
||||
"config-scan-settings": "setările de scanare",
|
||||
"deleted-user": "Utilizator șters",
|
||||
"detail-changed": "Modificat: {fields}",
|
||||
"detail-deleted-from-disk": "Șters și de pe disc",
|
||||
"detail-games-added": "{n} joc adăugat | {n} jocuri adăugate",
|
||||
"detail-games-removed": "{n} joc eliminat | {n} jocuri eliminate",
|
||||
"detail-login-credentials": "Nume de utilizator sau parolă greșită",
|
||||
"detail-login-disabled": "Cont dezactivat",
|
||||
"detail-new-games": "Niciun joc nou | {n} joc nou | {n} jocuri noi",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Rol: {from} → {to}",
|
||||
"empty": "Nu s-a înregistrat încă nimic",
|
||||
"events": "Evenimente",
|
||||
"field-cover": "copertă",
|
||||
"field-custom-name": "nume",
|
||||
"field-description": "descriere",
|
||||
"field-email": "email",
|
||||
"field-enabled": "activat",
|
||||
"field-fs-name": "nume fișier",
|
||||
"field-is-public": "vizibilitate",
|
||||
"field-manual": "manual",
|
||||
"field-name": "nume",
|
||||
"field-password": "parolă",
|
||||
"field-role": "rol",
|
||||
"field-summary": "rezumat",
|
||||
"field-username": "nume de utilizator",
|
||||
"filter-category": "Categorie",
|
||||
"filter-user": "Utilizator",
|
||||
"load-error": "Jurnalul de audit nu a putut fi încărcat",
|
||||
"no-matches": "Niciun eveniment nu corespunde acestor filtre",
|
||||
"search-placeholder": "Caută evenimente",
|
||||
"since": "De la",
|
||||
"system": "RomM",
|
||||
"until": "Până la",
|
||||
"yesterday": "Ieri"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Выполнен вход",
|
||||
"action-auth-login-failed": "Не удалось войти как {username}",
|
||||
"action-auth-login-failed-unknown": "Не удалось войти с неизвестным именем пользователя",
|
||||
"action-auth-password-reset": "Сброшен пароль пользователя {target}",
|
||||
"action-auth-password-reset-request": "Запрошен сброс пароля пользователя {target}",
|
||||
"action-client-token-create": "Создан API-токен {target}",
|
||||
"action-client-token-regenerate": "Перегенерирован API-токен {target}",
|
||||
"action-client-token-revoke": "Отозван API-токен {target}",
|
||||
"action-collection-add-roms": "Добавлено игр в коллекцию {target}: {n} | Добавлено игр в коллекцию {target}: {n}",
|
||||
"action-collection-create": "Создана коллекция {target}",
|
||||
"action-collection-delete": "Удалена коллекция {target}",
|
||||
"action-collection-edit": "Изменена коллекция {target}",
|
||||
"action-collection-remove-roms": "Удалено игр из коллекции {target}: {n} | Удалено игр из коллекции {target}: {n}",
|
||||
"action-config-update": "Изменены {setting}",
|
||||
"action-device-approve": "Привязано устройство {target}",
|
||||
"action-firmware-delete": "Удалена прошивка {target}",
|
||||
"action-firmware-upload": "Загружена прошивка для {target}",
|
||||
"action-permission-group-create": "Создана группа разрешений {target}",
|
||||
"action-permission-group-delete": "Удалена группа разрешений {target}",
|
||||
"action-permission-group-edit": "Изменена группа разрешений {target}",
|
||||
"action-platform-create": "Добавлена платформа {target}",
|
||||
"action-platform-delete": "Удалена платформа {target}",
|
||||
"action-platform-edit": "Изменена платформа {target}",
|
||||
"action-rom-bulk-download": "Скачано игр из {target}: {n} | Скачано игр из {target}: {n}",
|
||||
"action-rom-bulk-download-selection": "Скачано игр: {n} | Скачано игр: {n}",
|
||||
"action-rom-create": "Добавлена игра {target}",
|
||||
"action-rom-delete": "Удалена игра {target}",
|
||||
"action-rom-download": "Скачана игра {target}",
|
||||
"action-rom-edit": "Изменена игра {target}",
|
||||
"action-rom-file-delete": "Удалён файл игры {target}",
|
||||
"action-rom-match": "Сопоставлена игра {target}",
|
||||
"action-rom-play": "Игровая сессия: {target}",
|
||||
"action-rom-player-load": "Игра {target} загружена для запуска",
|
||||
"action-rom-unmatch": "Отменено сопоставление игры {target}",
|
||||
"action-rom-upload": "Загружен файл {file} в {target}",
|
||||
"action-scan-failed": "Сканирование не удалось",
|
||||
"action-scan-finish": "Сканирование завершено",
|
||||
"action-scan-start": "Сканирование запущено",
|
||||
"action-scan-stop": "Сканирование остановлено",
|
||||
"action-scan-stopped": "Сканирование прервано",
|
||||
"action-smart-collection-create": "Создана умная коллекция {target}",
|
||||
"action-smart-collection-delete": "Удалена умная коллекция {target}",
|
||||
"action-smart-collection-edit": "Изменена умная коллекция {target}",
|
||||
"action-task-run": "Запущена задача {target}",
|
||||
"action-user-create": "Создан пользователь {target}",
|
||||
"action-user-delete": "Удалён пользователь {target}",
|
||||
"action-user-edit": "Изменён пользователь {target}",
|
||||
"action-user-permissions-edit": "Изменены права пользователя {target}",
|
||||
"action-user-register": "Зарегистрирован аккаунт",
|
||||
"action-visibility-hide": "Скрыто от {principal}: {target}",
|
||||
"action-visibility-unhide": "Снова показано для {principal}: {target}",
|
||||
"all-categories": "Все категории",
|
||||
"all-users": "Все пользователи",
|
||||
"anonymous": "Аноним",
|
||||
"category-collections": "Коллекции",
|
||||
"category-consumption": "Игровые сессии и скачивания",
|
||||
"category-library": "Библиотека",
|
||||
"category-operations": "Сканирования и задачи",
|
||||
"category-security": "Аккаунты и безопасность",
|
||||
"config-exclusion": "исключения сканирования",
|
||||
"config-platform-binding": "сопоставления папок платформ",
|
||||
"config-platform-version": "версии платформ",
|
||||
"config-scan-settings": "настройки сканирования",
|
||||
"deleted-user": "Удалённый пользователь",
|
||||
"detail-changed": "Изменено: {fields}",
|
||||
"detail-deleted-from-disk": "Также удалено с диска",
|
||||
"detail-games-added": "Добавлено игр: {n} | Добавлено игр: {n}",
|
||||
"detail-games-removed": "Удалено игр: {n} | Удалено игр: {n}",
|
||||
"detail-login-credentials": "Неверное имя пользователя или пароль",
|
||||
"detail-login-disabled": "Аккаунт отключён",
|
||||
"detail-new-games": "Новых игр нет | Новых игр: {n} | Новых игр: {n}",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Роль: {from} → {to}",
|
||||
"empty": "Пока ничего не записано",
|
||||
"events": "События",
|
||||
"field-cover": "обложка",
|
||||
"field-custom-name": "название",
|
||||
"field-description": "описание",
|
||||
"field-email": "электронная почта",
|
||||
"field-enabled": "включён",
|
||||
"field-fs-name": "имя файла",
|
||||
"field-is-public": "видимость",
|
||||
"field-manual": "руководство",
|
||||
"field-name": "название",
|
||||
"field-password": "пароль",
|
||||
"field-role": "роль",
|
||||
"field-summary": "резюме",
|
||||
"field-username": "имя пользователя",
|
||||
"filter-category": "Категория",
|
||||
"filter-user": "Пользователь",
|
||||
"load-error": "Не удалось загрузить журнал аудита",
|
||||
"no-matches": "Нет событий, соответствующих этим фильтрам",
|
||||
"search-placeholder": "Поиск событий",
|
||||
"since": "С",
|
||||
"system": "RomM",
|
||||
"until": "По",
|
||||
"yesterday": "Вчера"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "Giriş yaptı",
|
||||
"action-auth-login-failed": "{username} olarak giriş yapılamadı",
|
||||
"action-auth-login-failed-unknown": "Bilinmeyen bir kullanıcı adıyla giriş yapılamadı",
|
||||
"action-auth-password-reset": "{target} kullanıcısının şifresini sıfırladı",
|
||||
"action-auth-password-reset-request": "{target} için şifre sıfırlama istedi",
|
||||
"action-client-token-create": "{target} API tokenını oluşturdu",
|
||||
"action-client-token-regenerate": "{target} API tokenını yeniden oluşturdu",
|
||||
"action-client-token-revoke": "{target} API tokenını iptal etti",
|
||||
"action-collection-add-roms": "{target} koleksiyonuna {n} oyun ekledi | {target} koleksiyonuna {n} oyun ekledi",
|
||||
"action-collection-create": "{target} koleksiyonunu oluşturdu",
|
||||
"action-collection-delete": "{target} koleksiyonunu sildi",
|
||||
"action-collection-edit": "{target} koleksiyonunu düzenledi",
|
||||
"action-collection-remove-roms": "{target} koleksiyonundan {n} oyun kaldırdı | {target} koleksiyonundan {n} oyun kaldırdı",
|
||||
"action-config-update": "{setting} değiştirdi",
|
||||
"action-device-approve": "{target} cihazını eşleştirdi",
|
||||
"action-firmware-delete": "{target} firmware dosyasını sildi",
|
||||
"action-firmware-upload": "{target} için firmware yükledi",
|
||||
"action-permission-group-create": "{target} izin grubunu oluşturdu",
|
||||
"action-permission-group-delete": "{target} izin grubunu sildi",
|
||||
"action-permission-group-edit": "{target} izin grubunu düzenledi",
|
||||
"action-platform-create": "{target} platformunu ekledi",
|
||||
"action-platform-delete": "{target} platformunu sildi",
|
||||
"action-platform-edit": "{target} platformunu düzenledi",
|
||||
"action-rom-bulk-download": "{target} içinden {n} oyun indirdi | {target} içinden {n} oyun indirdi",
|
||||
"action-rom-bulk-download-selection": "{n} oyun indirdi | {n} oyun indirdi",
|
||||
"action-rom-create": "{target} oyununu ekledi",
|
||||
"action-rom-delete": "{target} oyununu sildi",
|
||||
"action-rom-download": "{target} oyununu indirdi",
|
||||
"action-rom-edit": "{target} oyununu düzenledi",
|
||||
"action-rom-file-delete": "{target} oyununun bir dosyasını sildi",
|
||||
"action-rom-match": "{target} oyununu eşleştirdi",
|
||||
"action-rom-play": "{target} oyununu oynadı",
|
||||
"action-rom-player-load": "{target} oyununu oynamak için yükledi",
|
||||
"action-rom-unmatch": "{target} oyununun eşleşmesini kaldırdı",
|
||||
"action-rom-upload": "{file} dosyasını şuraya yükledi: {target}",
|
||||
"action-scan-failed": "Bir tarama başarısız oldu",
|
||||
"action-scan-finish": "Bir taramayı tamamladı",
|
||||
"action-scan-start": "Bir tarama başlattı",
|
||||
"action-scan-stop": "Taramayı durdurdu",
|
||||
"action-scan-stopped": "Bir tarama durduruldu",
|
||||
"action-smart-collection-create": "{target} akıllı koleksiyonunu oluşturdu",
|
||||
"action-smart-collection-delete": "{target} akıllı koleksiyonunu sildi",
|
||||
"action-smart-collection-edit": "{target} akıllı koleksiyonunu düzenledi",
|
||||
"action-task-run": "{target} görevini çalıştırdı",
|
||||
"action-user-create": "{target} kullanıcısını oluşturdu",
|
||||
"action-user-delete": "{target} kullanıcısını sildi",
|
||||
"action-user-edit": "{target} kullanıcısını düzenledi",
|
||||
"action-user-permissions-edit": "{target} kullanıcısının izinlerini değiştirdi",
|
||||
"action-user-register": "Kaydoldu",
|
||||
"action-visibility-hide": "{target} öğesini {principal} için gizledi",
|
||||
"action-visibility-unhide": "{target} öğesini {principal} için yeniden gösterdi",
|
||||
"all-categories": "Tüm kategoriler",
|
||||
"all-users": "Tüm kullanıcılar",
|
||||
"anonymous": "Anonim",
|
||||
"category-collections": "Koleksiyonlar",
|
||||
"category-consumption": "Oyun oturumları ve indirmeler",
|
||||
"category-library": "Kütüphane",
|
||||
"category-operations": "Taramalar ve görevler",
|
||||
"category-security": "Hesaplar ve güvenlik",
|
||||
"config-exclusion": "Tarama dışlamalarını",
|
||||
"config-platform-binding": "Platform klasör eşlemelerini",
|
||||
"config-platform-version": "Platform sürümlerini",
|
||||
"config-scan-settings": "Tarama ayarlarını",
|
||||
"deleted-user": "Silinmiş kullanıcı",
|
||||
"detail-changed": "Değişenler: {fields}",
|
||||
"detail-deleted-from-disk": "Diskten de silindi",
|
||||
"detail-games-added": "{n} oyun eklendi | {n} oyun eklendi",
|
||||
"detail-games-removed": "{n} oyun kaldırıldı | {n} oyun kaldırıldı",
|
||||
"detail-login-credentials": "Kullanıcı adı veya şifre yanlış",
|
||||
"detail-login-disabled": "Hesap devre dışı",
|
||||
"detail-new-games": "Yeni oyun yok | {n} yeni oyun | {n} yeni oyun",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "Rol: {from} → {to}",
|
||||
"empty": "Henüz hiçbir şey kaydedilmedi",
|
||||
"events": "Olaylar",
|
||||
"field-cover": "kapak",
|
||||
"field-custom-name": "ad",
|
||||
"field-description": "açıklama",
|
||||
"field-email": "e-posta",
|
||||
"field-enabled": "etkin",
|
||||
"field-fs-name": "dosya adı",
|
||||
"field-is-public": "görünürlük",
|
||||
"field-manual": "kılavuz",
|
||||
"field-name": "ad",
|
||||
"field-password": "şifre",
|
||||
"field-role": "rol",
|
||||
"field-summary": "özet",
|
||||
"field-username": "kullanıcı adı",
|
||||
"filter-category": "Kategori",
|
||||
"filter-user": "Kullanıcı",
|
||||
"load-error": "Denetim günlüğü yüklenemedi",
|
||||
"no-matches": "Bu filtrelerle eşleşen olay yok",
|
||||
"search-placeholder": "Olaylarda ara",
|
||||
"since": "Başlangıç",
|
||||
"system": "RomM",
|
||||
"until": "Bitiş",
|
||||
"yesterday": "Dün"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "登录",
|
||||
"action-auth-login-failed": "以 {username} 身份登录失败",
|
||||
"action-auth-login-failed-unknown": "使用未知用户名登录失败",
|
||||
"action-auth-password-reset": "重置了 {target} 的密码",
|
||||
"action-auth-password-reset-request": "请求重置 {target} 的密码",
|
||||
"action-client-token-create": "创建了 API 令牌 {target}",
|
||||
"action-client-token-regenerate": "重新生成了 API 令牌 {target}",
|
||||
"action-client-token-revoke": "吊销了 API 令牌 {target}",
|
||||
"action-collection-add-roms": "向 {target} 添加了 {n} 个游戏 | 向 {target} 添加了 {n} 个游戏",
|
||||
"action-collection-create": "创建了收藏 {target}",
|
||||
"action-collection-delete": "删除了收藏 {target}",
|
||||
"action-collection-edit": "编辑了收藏 {target}",
|
||||
"action-collection-remove-roms": "从 {target} 移除了 {n} 个游戏 | 从 {target} 移除了 {n} 个游戏",
|
||||
"action-config-update": "更改了{setting}",
|
||||
"action-device-approve": "配对了设备 {target}",
|
||||
"action-firmware-delete": "删除了固件 {target}",
|
||||
"action-firmware-upload": "为 {target} 上传了固件",
|
||||
"action-permission-group-create": "创建了权限分组 {target}",
|
||||
"action-permission-group-delete": "删除了权限分组 {target}",
|
||||
"action-permission-group-edit": "编辑了权限分组 {target}",
|
||||
"action-platform-create": "添加了平台 {target}",
|
||||
"action-platform-delete": "删除了平台 {target}",
|
||||
"action-platform-edit": "编辑了平台 {target}",
|
||||
"action-rom-bulk-download": "从 {target} 下载了 {n} 个游戏 | 从 {target} 下载了 {n} 个游戏",
|
||||
"action-rom-bulk-download-selection": "下载了 {n} 个游戏 | 下载了 {n} 个游戏",
|
||||
"action-rom-create": "添加了 {target}",
|
||||
"action-rom-delete": "删除了 {target}",
|
||||
"action-rom-download": "下载了 {target}",
|
||||
"action-rom-edit": "编辑了 {target}",
|
||||
"action-rom-file-delete": "删除了 {target} 的一个文件",
|
||||
"action-rom-match": "匹配了 {target}",
|
||||
"action-rom-play": "游玩了 {target}",
|
||||
"action-rom-player-load": "加载了 {target} 以游玩",
|
||||
"action-rom-unmatch": "取消了 {target} 的匹配",
|
||||
"action-rom-upload": "将 {file} 上传到 {target}",
|
||||
"action-scan-failed": "扫描失败",
|
||||
"action-scan-finish": "完成了一次扫描",
|
||||
"action-scan-start": "开始了一次扫描",
|
||||
"action-scan-stop": "停止了扫描",
|
||||
"action-scan-stopped": "扫描已被停止",
|
||||
"action-smart-collection-create": "创建了智能收藏 {target}",
|
||||
"action-smart-collection-delete": "删除了智能收藏 {target}",
|
||||
"action-smart-collection-edit": "编辑了智能收藏 {target}",
|
||||
"action-task-run": "运行了任务 {target}",
|
||||
"action-user-create": "创建了用户 {target}",
|
||||
"action-user-delete": "删除了用户 {target}",
|
||||
"action-user-edit": "编辑了用户 {target}",
|
||||
"action-user-permissions-edit": "更改了 {target} 的权限",
|
||||
"action-user-register": "注册了账户",
|
||||
"action-visibility-hide": "对 {principal} 隐藏了 {target}",
|
||||
"action-visibility-unhide": "重新对 {principal} 显示了 {target}",
|
||||
"all-categories": "所有分类",
|
||||
"all-users": "所有用户",
|
||||
"anonymous": "匿名",
|
||||
"category-collections": "收藏",
|
||||
"category-consumption": "游玩与下载",
|
||||
"category-library": "游戏库",
|
||||
"category-operations": "扫描与任务",
|
||||
"category-security": "账户与安全",
|
||||
"config-exclusion": "扫描排除项",
|
||||
"config-platform-binding": "平台文件夹映射",
|
||||
"config-platform-version": "平台版本",
|
||||
"config-scan-settings": "扫描设置",
|
||||
"deleted-user": "已删除的用户",
|
||||
"detail-changed": "已更改:{fields}",
|
||||
"detail-deleted-from-disk": "同时已从磁盘删除",
|
||||
"detail-games-added": "添加了 {n} 个游戏 | 添加了 {n} 个游戏",
|
||||
"detail-games-removed": "移除了 {n} 个游戏 | 移除了 {n} 个游戏",
|
||||
"detail-login-credentials": "用户名或密码错误",
|
||||
"detail-login-disabled": "账户已禁用",
|
||||
"detail-new-games": "没有新游戏 | {n} 个新游戏 | {n} 个新游戏",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "角色:{from} → {to}",
|
||||
"empty": "暂无任何记录",
|
||||
"events": "事件",
|
||||
"field-cover": "封面",
|
||||
"field-custom-name": "名称",
|
||||
"field-description": "描述",
|
||||
"field-email": "电子邮件",
|
||||
"field-enabled": "已启用",
|
||||
"field-fs-name": "文件名称",
|
||||
"field-is-public": "可见性",
|
||||
"field-manual": "手册",
|
||||
"field-name": "名称",
|
||||
"field-password": "密码",
|
||||
"field-role": "角色",
|
||||
"field-summary": "概要",
|
||||
"field-username": "用户名",
|
||||
"filter-category": "分类",
|
||||
"filter-user": "用户",
|
||||
"load-error": "无法加载审计日志",
|
||||
"no-matches": "没有符合这些筛选条件的事件",
|
||||
"search-placeholder": "搜索事件",
|
||||
"since": "从",
|
||||
"system": "RomM",
|
||||
"until": "至",
|
||||
"yesterday": "昨天"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"action-auth-login": "登入",
|
||||
"action-auth-login-failed": "以 {username} 身分登入失敗",
|
||||
"action-auth-login-failed-unknown": "使用未知用戶名登入失敗",
|
||||
"action-auth-password-reset": "重置了 {target} 的密碼",
|
||||
"action-auth-password-reset-request": "請求重置 {target} 的密碼",
|
||||
"action-client-token-create": "建立了 API 權杖 {target}",
|
||||
"action-client-token-regenerate": "重新產生了 API 權杖 {target}",
|
||||
"action-client-token-revoke": "撤銷了 API 權杖 {target}",
|
||||
"action-collection-add-roms": "將 {n} 個遊戲加入 {target} | 將 {n} 個遊戲加入 {target}",
|
||||
"action-collection-create": "建立了收藏庫 {target}",
|
||||
"action-collection-delete": "刪除了收藏庫 {target}",
|
||||
"action-collection-edit": "編輯了收藏庫 {target}",
|
||||
"action-collection-remove-roms": "從 {target} 移除了 {n} 個遊戲 | 從 {target} 移除了 {n} 個遊戲",
|
||||
"action-config-update": "變更了{setting}",
|
||||
"action-device-approve": "配對了裝置 {target}",
|
||||
"action-firmware-delete": "刪除了韌體 {target}",
|
||||
"action-firmware-upload": "為 {target} 上傳了韌體",
|
||||
"action-permission-group-create": "建立了權限群組 {target}",
|
||||
"action-permission-group-delete": "刪除了權限群組 {target}",
|
||||
"action-permission-group-edit": "編輯了權限群組 {target}",
|
||||
"action-platform-create": "新增了平台 {target}",
|
||||
"action-platform-delete": "刪除了平台 {target}",
|
||||
"action-platform-edit": "編輯了平台 {target}",
|
||||
"action-rom-bulk-download": "從 {target} 下載了 {n} 個遊戲 | 從 {target} 下載了 {n} 個遊戲",
|
||||
"action-rom-bulk-download-selection": "下載了 {n} 個遊戲 | 下載了 {n} 個遊戲",
|
||||
"action-rom-create": "新增了 {target}",
|
||||
"action-rom-delete": "刪除了 {target}",
|
||||
"action-rom-download": "下載了 {target}",
|
||||
"action-rom-edit": "編輯了 {target}",
|
||||
"action-rom-file-delete": "刪除了 {target} 的一個檔案",
|
||||
"action-rom-match": "匹配了 {target}",
|
||||
"action-rom-play": "遊玩了 {target}",
|
||||
"action-rom-player-load": "載入了 {target} 以遊玩",
|
||||
"action-rom-unmatch": "清除了 {target} 的匹配資料",
|
||||
"action-rom-upload": "將 {file} 上傳到 {target}",
|
||||
"action-scan-failed": "掃描失敗",
|
||||
"action-scan-finish": "完成了一次掃描",
|
||||
"action-scan-start": "開始了一次掃描",
|
||||
"action-scan-stop": "停止了掃描",
|
||||
"action-scan-stopped": "掃描已被停止",
|
||||
"action-smart-collection-create": "建立了智能收藏庫 {target}",
|
||||
"action-smart-collection-delete": "刪除了智能收藏庫 {target}",
|
||||
"action-smart-collection-edit": "編輯了智能收藏庫 {target}",
|
||||
"action-task-run": "執行了任務 {target}",
|
||||
"action-user-create": "建立了使用者 {target}",
|
||||
"action-user-delete": "刪除了使用者 {target}",
|
||||
"action-user-edit": "編輯了使用者 {target}",
|
||||
"action-user-permissions-edit": "變更了 {target} 的權限",
|
||||
"action-user-register": "註冊了帳號",
|
||||
"action-visibility-hide": "對 {principal} 隱藏了 {target}",
|
||||
"action-visibility-unhide": "重新對 {principal} 顯示了 {target}",
|
||||
"all-categories": "所有分類",
|
||||
"all-users": "所有使用者",
|
||||
"anonymous": "匿名",
|
||||
"category-collections": "收藏庫",
|
||||
"category-consumption": "遊玩與下載",
|
||||
"category-library": "遊戲庫",
|
||||
"category-operations": "掃描與任務",
|
||||
"category-security": "帳號與安全性",
|
||||
"config-exclusion": "掃描排除項",
|
||||
"config-platform-binding": "平台資料夾對應",
|
||||
"config-platform-version": "平台版本",
|
||||
"config-scan-settings": "掃描設定",
|
||||
"deleted-user": "已刪除的使用者",
|
||||
"detail-changed": "已變更:{fields}",
|
||||
"detail-deleted-from-disk": "也已從磁碟刪除",
|
||||
"detail-games-added": "新增了 {n} 個遊戲 | 新增了 {n} 個遊戲",
|
||||
"detail-games-removed": "移除了 {n} 個遊戲 | 移除了 {n} 個遊戲",
|
||||
"detail-login-credentials": "用戶名或密碼錯誤",
|
||||
"detail-login-disabled": "帳號已停用",
|
||||
"detail-new-games": "沒有新遊戲 | {n} 個新遊戲 | {n} 個新遊戲",
|
||||
"detail-renamed": "{from} → {to}",
|
||||
"detail-role": "角色:{from} → {to}",
|
||||
"empty": "尚未記錄任何內容",
|
||||
"events": "事件",
|
||||
"field-cover": "封面",
|
||||
"field-custom-name": "名稱",
|
||||
"field-description": "描述",
|
||||
"field-email": "電子郵件",
|
||||
"field-enabled": "已啟用",
|
||||
"field-fs-name": "檔案名稱",
|
||||
"field-is-public": "可見性",
|
||||
"field-manual": "手冊",
|
||||
"field-name": "名稱",
|
||||
"field-password": "密碼",
|
||||
"field-role": "角色",
|
||||
"field-summary": "摘要",
|
||||
"field-username": "用戶名",
|
||||
"filter-category": "分類",
|
||||
"filter-user": "使用者",
|
||||
"load-error": "無法載入稽核日誌",
|
||||
"no-matches": "沒有符合這些篩選條件的事件",
|
||||
"search-placeholder": "搜尋事件",
|
||||
"since": "從",
|
||||
"system": "RomM",
|
||||
"until": "至",
|
||||
"yesterday": "昨天"
|
||||
}
|
||||
@@ -672,11 +672,12 @@ router.beforeEach(async (to, from, next) => {
|
||||
return next({ name: ROUTES.NOT_FOUND });
|
||||
}
|
||||
|
||||
// The logs viewer can be turned off entirely via DISABLE_LOGS_VIEWER; the
|
||||
// backend endpoint/stream are then gone, so direct navigation must 404 too.
|
||||
// DISABLE_LOGS_VIEWER takes the log tab away; an admin still has the
|
||||
// event log there, anyone else has nothing left on the page.
|
||||
if (
|
||||
currentRoute === ROUTES.LOGS &&
|
||||
heartbeat.value.FRONTEND.DISABLE_LOGS_VIEWER
|
||||
heartbeat.value.FRONTEND.DISABLE_LOGS_VIEWER &&
|
||||
user.value?.role !== "admin"
|
||||
) {
|
||||
return next({ name: ROUTES.NOT_FOUND });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type {
|
||||
AuditCategory,
|
||||
AuditPage_AuditEventSchema_,
|
||||
} from "@/__generated__";
|
||||
import api from "@/services/api";
|
||||
|
||||
export interface AuditEventsQuery {
|
||||
actorIds?: number[];
|
||||
categories?: AuditCategory[];
|
||||
since?: string;
|
||||
until?: string;
|
||||
search?: string;
|
||||
/** Pins later pages to the events the first page saw. */
|
||||
maxId?: number;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
async function getAuditEvents(query: AuditEventsQuery = {}) {
|
||||
return api.get<AuditPage_AuditEventSchema_>("/audit-events", {
|
||||
params: {
|
||||
actor_id: query.actorIds,
|
||||
category: query.categories,
|
||||
since: query.since,
|
||||
until: query.until,
|
||||
search: query.search || undefined,
|
||||
max_id: query.maxId,
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export default {
|
||||
getAuditEvents,
|
||||
};
|
||||
@@ -301,7 +301,7 @@ export const useNativeStore = defineStore("native", () => {
|
||||
try {
|
||||
await launchNative({
|
||||
romId: rom.id,
|
||||
downloadPath: getDownloadPath({ rom: detailed }),
|
||||
downloadPath: getDownloadPath({ rom: detailed, purpose: "play" }),
|
||||
// What the endpoint will actually serve, which for a folder rom is
|
||||
// neither `fs_name` nor `fs_name` with an extension.
|
||||
fileName: getDownloadFileName(detailed),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from "pinia";
|
||||
import type { UserSchema } from "@/__generated__";
|
||||
import i18n from "@/locales";
|
||||
import userApi from "@/services/api/user";
|
||||
|
||||
export type User = UserSchema;
|
||||
|
||||
@@ -47,6 +48,12 @@ export default defineStore("users", {
|
||||
set(users: User[]) {
|
||||
this.allUsers = users;
|
||||
},
|
||||
/** Fetches the users unless some are already here. */
|
||||
async ensureLoaded() {
|
||||
if (this.allUsers.length > 0) return;
|
||||
const { data } = await userApi.fetchUsers();
|
||||
this.allUsers = data;
|
||||
},
|
||||
add(user: User) {
|
||||
this.allUsers = this.allUsers.concat(user);
|
||||
},
|
||||
|
||||
@@ -87,6 +87,20 @@ describe("getDownloadPath", () => {
|
||||
"/api/roms/24/content/B.A.T.?file_ids=999",
|
||||
);
|
||||
});
|
||||
|
||||
it("marks a player's fetch after the file selection", () => {
|
||||
const rom = makeRom({
|
||||
id: 24,
|
||||
fs_name: "B.A.T.",
|
||||
files: [
|
||||
{ id: 29, file_name: "B.A.T. Disk1.adf" },
|
||||
{ id: 30, file_name: "B.A.T. Disk2.adf" },
|
||||
] as SimpleRom["files"],
|
||||
});
|
||||
expect(getDownloadPath({ rom, fileIDs: [29], purpose: "play" })).toBe(
|
||||
"/api/roms/24/content/B.A.T.%20Disk1.adf?file_ids=29&purpose=play",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("download URL encoding", () => {
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
import type { RomFileSchema } from "@/__generated__";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
|
||||
/** Build the `/api` path that serves a ROM's content. */
|
||||
/** Build the `/api` path that serves a ROM's content.
|
||||
* `purpose: "play"` marks a player's fetch, which is logged as a player load. */
|
||||
export function getDownloadPath({
|
||||
rom,
|
||||
fileIDs = [],
|
||||
purpose,
|
||||
}: {
|
||||
rom: SimpleRom;
|
||||
fileIDs?: number[];
|
||||
purpose?: "play";
|
||||
}) {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (fileIDs.length > 0) {
|
||||
queryParams.append("file_ids", fileIDs.join(","));
|
||||
}
|
||||
if (purpose) {
|
||||
queryParams.append("purpose", purpose);
|
||||
}
|
||||
const queryString = queryParams.toString();
|
||||
|
||||
const selectedFile =
|
||||
|
||||
@@ -34,7 +34,6 @@ import { refetchCSRFToken } from "@/services/api";
|
||||
import identityApi from "@/services/api/identity";
|
||||
import socket from "@/services/socket";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storeHeartbeat from "@/stores/heartbeat";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { useCan } from "@/v2/composables/useCan";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
@@ -66,11 +65,6 @@ const isAdmin = useCan("app.admin");
|
||||
// "editor or admin" without an inline role check (see CLAUDE.md §VI.G).
|
||||
const canSeeChangelog = useCan("library.scan");
|
||||
|
||||
const heartbeatStore = storeHeartbeat();
|
||||
const logsViewerEnabled = computed(
|
||||
() => !heartbeatStore.value.FRONTEND.DISABLE_LOGS_VIEWER,
|
||||
);
|
||||
|
||||
const canSeeProfile = computed(
|
||||
() => !!user.value?.id && scopes.value.includes("me.write"),
|
||||
);
|
||||
@@ -286,7 +280,7 @@ async function onLogout() {
|
||||
@click="open = false"
|
||||
/>
|
||||
<RMenuItem
|
||||
v-if="isAdmin && logsViewerEnabled"
|
||||
v-if="isAdmin"
|
||||
:to="{ name: ROUTES.LOGS }"
|
||||
icon="mdi-text-box-search-outline"
|
||||
:label="t('common.logs')"
|
||||
|
||||
@@ -7,7 +7,6 @@ import { computed, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { NotificationLevel } from "@/__generated__";
|
||||
import notificationApi from "@/services/api/notification";
|
||||
import userApi from "@/services/api/user";
|
||||
import storeUsers from "@/stores/users";
|
||||
import SettingsSection from "@/v2/components/Settings/SettingsSection.vue";
|
||||
import { TONE_ICONS, useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
@@ -71,10 +70,8 @@ const linkRules = [
|
||||
];
|
||||
|
||||
onMounted(async () => {
|
||||
if (allUsers.value.length > 0) return;
|
||||
try {
|
||||
const { data } = await userApi.fetchUsers();
|
||||
usersStore.set(data);
|
||||
await usersStore.ensureLoaded();
|
||||
} catch (error) {
|
||||
console.error("Could not load users:", error);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent, reactive } from "vue";
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
import i18n, { loadLocale } from "@/locales";
|
||||
import auditApi from "@/services/api/audit";
|
||||
import { makeAuditEvent } from "@/v2/utils/auditEvents.fixtures";
|
||||
import EventLog from "./EventLog.vue";
|
||||
|
||||
const route = reactive<{ query: Record<string, string> }>({ query: {} });
|
||||
|
||||
vi.mock("vue-router", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("vue-router")>()),
|
||||
useRoute: () => route,
|
||||
useRouter: () => ({ replace: vi.fn(), currentRoute: { value: route } }),
|
||||
}));
|
||||
vi.mock("@/services/api/audit", () => ({
|
||||
default: { getAuditEvents: vi.fn() },
|
||||
}));
|
||||
vi.mock("@/services/api/user", () => ({
|
||||
default: { fetchUsers: vi.fn(async () => ({ data: [] })) },
|
||||
}));
|
||||
|
||||
const getAuditEvents = vi.mocked(auditApi.getAuditEvents);
|
||||
|
||||
function event(
|
||||
id: number,
|
||||
action: string,
|
||||
data: AuditEventSchema["data"],
|
||||
): AuditEventSchema {
|
||||
return makeAuditEvent({
|
||||
id,
|
||||
action,
|
||||
actor_name: "maria",
|
||||
target_id: "33",
|
||||
target_name: "Hollow Knight",
|
||||
ip_address: "192.168.1.20",
|
||||
device_name: "Steam Deck",
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
const EVENTS = [
|
||||
event(3, "rom.play", { duration_ms: 7_633_360 }),
|
||||
event(2, "rom.download", { file_name: "hk.zip", size_bytes: 1024 }),
|
||||
event(1, "rom.teleport", {}),
|
||||
];
|
||||
|
||||
// happy-dom lays nothing out, so a windowed list would render no rows.
|
||||
const WholeList = defineComponent({
|
||||
props: { items: { type: Array, default: () => [] } },
|
||||
template: `<div><slot name="prepend" /><div v-for="(item, index) in items" :key="index"><slot :item="item" :index="index" /></div></div>`,
|
||||
});
|
||||
|
||||
function render() {
|
||||
return mount(EventLog, {
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
RouterLink: { template: "<a><slot /></a>" },
|
||||
RVirtualScroller: WholeList,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await loadLocale("en_US");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
route.query = {};
|
||||
getAuditEvents.mockReset();
|
||||
getAuditEvents.mockResolvedValue({
|
||||
data: { items: EVENTS, total: 3, limit: 50, offset: 0 },
|
||||
} as Awaited<ReturnType<typeof auditApi.getAuditEvents>>);
|
||||
});
|
||||
|
||||
describe("EventLog", () => {
|
||||
it("lists every event, a long play and an unknown action included", async () => {
|
||||
const wrapper = render();
|
||||
await flushPromises();
|
||||
|
||||
const text = wrapper.text();
|
||||
expect(text).toContain("Played Hollow Knight");
|
||||
expect(text).toContain("Downloaded Hollow Knight");
|
||||
expect(text).toContain("rom.teleport Hollow Knight");
|
||||
expect(text).toContain("Steam Deck");
|
||||
});
|
||||
|
||||
it("follows a link that changes its query while it stays open", async () => {
|
||||
const wrapper = render();
|
||||
await flushPromises();
|
||||
getAuditEvents.mockClear();
|
||||
|
||||
route.query = { q: "steam", category: "security" };
|
||||
await flushPromises();
|
||||
|
||||
expect(getAuditEvents).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ search: "steam", categories: ["security"] }),
|
||||
);
|
||||
expect(
|
||||
(
|
||||
wrapper.find('input[placeholder="Search events"]')
|
||||
.element as HTMLInputElement
|
||||
).value,
|
||||
).toBe("steam");
|
||||
});
|
||||
|
||||
it("searches once typing pauses, or straight away on Enter", async () => {
|
||||
// lodash's debounce reads the clock; setImmediate stays real for flushPromises.
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
|
||||
try {
|
||||
const wrapper = render();
|
||||
await flushPromises();
|
||||
getAuditEvents.mockClear();
|
||||
const input = wrapper.find('input[placeholder="Search events"]');
|
||||
|
||||
await input.setValue("192");
|
||||
await input.setValue("192.168");
|
||||
await flushPromises();
|
||||
expect(getAuditEvents).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
await flushPromises();
|
||||
expect(getAuditEvents).toHaveBeenCalledOnce();
|
||||
expect(getAuditEvents).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ search: "192.168" }),
|
||||
);
|
||||
|
||||
getAuditEvents.mockClear();
|
||||
await input.setValue("steam");
|
||||
await input.trigger("keyup", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(getAuditEvents).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ search: "steam" }),
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,641 @@
|
||||
<script setup lang="ts">
|
||||
// EventLog: the audit log grouped by day, its filters in the URL. The list is
|
||||
// windowed and pulls the next page in as its end scrolls into view.
|
||||
import {
|
||||
RBtn,
|
||||
RDateField,
|
||||
REmptyState,
|
||||
RSelect,
|
||||
RSkeletonBlock,
|
||||
RSpinner,
|
||||
RTextField,
|
||||
RVirtualScroller,
|
||||
} from "@v2/lib";
|
||||
import { useEventListener, useResizeObserver } from "@vueuse/core";
|
||||
import { isToday, isYesterday } from "date-fns";
|
||||
import { debounce } from "lodash";
|
||||
import { storeToRefs } from "pinia";
|
||||
import {
|
||||
computed,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
ref,
|
||||
shallowRef,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import type { AuditCategory, AuditEventSchema } from "@/__generated__";
|
||||
import storeUsers from "@/stores/users";
|
||||
import { toBrowserLocale } from "@/utils";
|
||||
import EventLogRow from "@/v2/components/Settings/EventLogRow.vue";
|
||||
import {
|
||||
EVENT_ROW,
|
||||
EVENT_ROW_HEIGHT,
|
||||
EVENT_ROW_VARS,
|
||||
phoneEventRowHeight,
|
||||
} from "@/v2/components/Settings/eventLogLayout";
|
||||
import { useAuditLog } from "@/v2/composables/useAuditLog";
|
||||
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
|
||||
import { useGridNav } from "@/v2/composables/useGridNav";
|
||||
import { useIsAlive } from "@/v2/composables/useIsAlive";
|
||||
import { useLoadingPhase } from "@/v2/composables/useLoadingPhase";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import {
|
||||
AUDIT_CATEGORIES,
|
||||
describeAuditEvent,
|
||||
type AuditEventView,
|
||||
} from "@/v2/utils/auditEvents";
|
||||
import { syncQueryParam } from "@/v2/utils/routeQuery";
|
||||
import { canvasMeasure, wrappedLineCount } from "@/v2/utils/textLines";
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const snackbar = useSnackbar();
|
||||
const usersStore = storeUsers();
|
||||
const { allUsers } = storeToRefs(usersStore);
|
||||
const { events, loading, hasMore, reset, loadMore } = useAuditLog(200);
|
||||
|
||||
const ALL = "all";
|
||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
function queryString(key: string): string | undefined {
|
||||
const value = route.query[key];
|
||||
return typeof value === "string" && value ? value : undefined;
|
||||
}
|
||||
|
||||
function queryDay(key: string): string | undefined {
|
||||
const value = queryString(key);
|
||||
return value && DAY.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
const userFilter = ref<string>(queryString("user") ?? ALL);
|
||||
const categoryFilter = ref<string>(queryString("category") ?? ALL);
|
||||
const search = ref(queryString("q") ?? "");
|
||||
const appliedSearch = ref(search.value);
|
||||
const since = ref<string | undefined>(queryDay("from"));
|
||||
const until = ref<string | undefined>(queryDay("to"));
|
||||
|
||||
const userItems = computed(() => [
|
||||
{ title: t("audit.all-users"), value: ALL },
|
||||
...allUsers.value.map((user) => ({
|
||||
title: user.username,
|
||||
value: String(user.id),
|
||||
})),
|
||||
]);
|
||||
|
||||
const categoryItems = computed(() => [
|
||||
{ title: t("audit.all-categories"), value: ALL },
|
||||
...AUDIT_CATEGORIES.map((category) => ({
|
||||
title: t(`audit.category-${category}`),
|
||||
value: category,
|
||||
})),
|
||||
]);
|
||||
|
||||
// The date fields hold a calendar day; the log is read from its local midnight.
|
||||
function dayToDate(day: string | undefined): Date | null {
|
||||
return day ? new Date(`${day}T00:00:00Z`) : null;
|
||||
}
|
||||
|
||||
function dateToDay(date: Date | null): string | undefined {
|
||||
return date ? date.toISOString().slice(0, 10) : undefined;
|
||||
}
|
||||
|
||||
function localMidnight(day: string, addDays = 0): string {
|
||||
const [year, month, date] = day.split("-").map(Number);
|
||||
return new Date(year, month - 1, date + addDays).toISOString();
|
||||
}
|
||||
|
||||
const sinceDate = computed({
|
||||
get: () => dayToDate(since.value),
|
||||
set: (date) => (since.value = dateToDay(date)),
|
||||
});
|
||||
const untilDate = computed({
|
||||
get: () => dayToDate(until.value),
|
||||
set: (date) => (until.value = dateToDay(date)),
|
||||
});
|
||||
|
||||
// Typing searches once it pauses.
|
||||
const applySearch = debounce(() => {
|
||||
appliedSearch.value = search.value.trim();
|
||||
}, 300);
|
||||
watch(search, applySearch);
|
||||
onBeforeUnmount(() => applySearch.cancel());
|
||||
|
||||
const hasFilters = computed(
|
||||
() =>
|
||||
userFilter.value !== ALL ||
|
||||
categoryFilter.value !== ALL ||
|
||||
!!appliedSearch.value ||
|
||||
!!since.value ||
|
||||
!!until.value,
|
||||
);
|
||||
|
||||
// Set when a page fails to load, so scrolling doesn't retry it on every frame.
|
||||
const moreFailed = ref(false);
|
||||
const alive = useIsAlive();
|
||||
|
||||
async function refresh() {
|
||||
moreFailed.value = false;
|
||||
try {
|
||||
await reset({
|
||||
actorIds:
|
||||
userFilter.value === ALL ? undefined : [Number(userFilter.value)],
|
||||
categories:
|
||||
categoryFilter.value === ALL
|
||||
? undefined
|
||||
: [categoryFilter.value as AuditCategory],
|
||||
search: appliedSearch.value,
|
||||
since: since.value ? localMidnight(since.value) : undefined,
|
||||
// Inclusive of the whole day picked.
|
||||
until: until.value ? localMidnight(until.value, 1) : undefined,
|
||||
});
|
||||
} catch {
|
||||
if (alive.value) snackbar.error(t("audit.load-error"));
|
||||
}
|
||||
}
|
||||
|
||||
function searchNow() {
|
||||
applySearch.cancel();
|
||||
const next = search.value.trim();
|
||||
// Searching the same text again reloads, picking up newer events.
|
||||
if (next === appliedSearch.value) void refresh();
|
||||
else appliedSearch.value = next;
|
||||
}
|
||||
|
||||
async function showMore() {
|
||||
moreFailed.value = false;
|
||||
try {
|
||||
await loadMore();
|
||||
} catch {
|
||||
moreFailed.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
// A link to this page, such as the sidebar's, can change the query while the
|
||||
// tab stays mounted.
|
||||
watch(
|
||||
() => route.query,
|
||||
() => {
|
||||
userFilter.value = queryString("user") ?? ALL;
|
||||
categoryFilter.value = queryString("category") ?? ALL;
|
||||
since.value = queryDay("from");
|
||||
until.value = queryDay("to");
|
||||
const q = queryString("q") ?? "";
|
||||
if (q !== appliedSearch.value) {
|
||||
applySearch.cancel();
|
||||
search.value = q;
|
||||
appliedSearch.value = q;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
[userFilter, categoryFilter, appliedSearch, since, until],
|
||||
([user, category, q, from, to]) => {
|
||||
syncQueryParam(router, "user", user === ALL ? undefined : user);
|
||||
syncQueryParam(router, "category", category === ALL ? undefined : category);
|
||||
syncQueryParam(router, "q", q || undefined);
|
||||
syncQueryParam(router, "from", from);
|
||||
syncQueryParam(router, "to", to);
|
||||
void refresh();
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(async () => {
|
||||
void refresh();
|
||||
try {
|
||||
await usersStore.ensureLoaded();
|
||||
} catch (error) {
|
||||
console.error("Could not load users:", error);
|
||||
}
|
||||
});
|
||||
|
||||
const phase = useLoadingPhase(
|
||||
() => loading.value,
|
||||
() => events.value.length === 0,
|
||||
);
|
||||
|
||||
const timeFormat = computed(
|
||||
() =>
|
||||
new Intl.DateTimeFormat(toBrowserLocale(locale.value), {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}),
|
||||
);
|
||||
|
||||
const dayFormats = computed(() => {
|
||||
const intlLocale = toBrowserLocale(locale.value);
|
||||
const format = { weekday: "long", day: "numeric", month: "long" } as const;
|
||||
return {
|
||||
thisYear: new Intl.DateTimeFormat(intlLocale, format),
|
||||
otherYear: new Intl.DateTimeFormat(intlLocale, {
|
||||
...format,
|
||||
year: "numeric",
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
function dayLabel(date: Date, year: number): string {
|
||||
if (isToday(date)) return t("common.today");
|
||||
if (isYesterday(date)) return t("audit.yesterday");
|
||||
const { thisYear, otherYear } = dayFormats.value;
|
||||
return (date.getFullYear() === year ? thisYear : otherYear).format(date);
|
||||
}
|
||||
|
||||
// Each page brings the earlier ones along, so their sentences are kept rather
|
||||
// than rebuilt; the cache starts over with the language.
|
||||
const described = computed(() => {
|
||||
void locale.value;
|
||||
return new WeakMap<AuditEventSchema, AuditEventView>();
|
||||
});
|
||||
|
||||
function describe(event: AuditEventSchema): AuditEventView {
|
||||
let view = described.value.get(event);
|
||||
if (!view) {
|
||||
view = describeAuditEvent(event);
|
||||
described.value.set(event, view);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
interface EventItem {
|
||||
kind: "event";
|
||||
key: number;
|
||||
event: AuditEventSchema;
|
||||
view: AuditEventView;
|
||||
first: boolean;
|
||||
last: boolean;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface DayItem {
|
||||
kind: "day";
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
type Item = DayItem | EventItem | { kind: "more"; key: "more" };
|
||||
|
||||
// Kept in step with the day and "more" rows below.
|
||||
const ROW_HEIGHTS = { day: 44, more: 56 } as const;
|
||||
|
||||
// A phone wraps each event's title and detail, so its row's height depends on
|
||||
// how they wrap in the fonts and width of a row already on screen.
|
||||
interface TextMetrics {
|
||||
width: number;
|
||||
fonts: string;
|
||||
title: (run: string) => number;
|
||||
detail: (run: string) => number;
|
||||
}
|
||||
|
||||
const listRoot = ref<HTMLElement | null>(null);
|
||||
const scroller = ref<InstanceType<typeof RVirtualScroller> | null>(null);
|
||||
const { xs } = useBreakpoint();
|
||||
const textMetrics = shallowRef<TextMetrics | null>(null);
|
||||
|
||||
function readTextMetrics(force = false) {
|
||||
if (!xs.value) return;
|
||||
const body = listRoot.value?.querySelector<HTMLElement>(
|
||||
".r-v2-audit-event__body",
|
||||
);
|
||||
const title = body?.querySelector<HTMLElement>(".r-v2-audit-event__title");
|
||||
const meta = body?.querySelector<HTMLElement>(".r-v2-audit-event__meta");
|
||||
if (!body || !title || !meta) return;
|
||||
const width = body.clientWidth;
|
||||
const current = textMetrics.value;
|
||||
if (!force && current?.width === width) return;
|
||||
const titleFont = getComputedStyle(title).font;
|
||||
const metaFont = getComputedStyle(meta).font;
|
||||
const fonts = `${titleFont}|${metaFont}`;
|
||||
// Measurers remember word widths, so they're kept while the fonts are.
|
||||
if (!force && current?.fonts === fonts) {
|
||||
textMetrics.value = { ...current, width };
|
||||
return;
|
||||
}
|
||||
const measureTitle = canvasMeasure(titleFont);
|
||||
const measureDetail = canvasMeasure(metaFont);
|
||||
if (!measureTitle || !measureDetail) return;
|
||||
textMetrics.value = {
|
||||
width,
|
||||
fonts,
|
||||
title: measureTitle,
|
||||
detail: measureDetail,
|
||||
};
|
||||
}
|
||||
|
||||
function phoneLines(text: string, font: "title" | "detail"): number {
|
||||
const metrics = textMetrics.value;
|
||||
if (!metrics) return 1;
|
||||
// Measured a little short, so a line that only just fits counts as wrapped:
|
||||
// a spare line is better than one cut off.
|
||||
return wrappedLineCount(
|
||||
text,
|
||||
metrics.width - 2,
|
||||
metrics[font],
|
||||
EVENT_ROW.maxLines,
|
||||
);
|
||||
}
|
||||
|
||||
// Like the sentences, heights are kept until the fonts or the width change.
|
||||
const heights = computed(() => {
|
||||
void textMetrics.value;
|
||||
return new WeakMap<AuditEventView, number>();
|
||||
});
|
||||
|
||||
function eventHeight(event: AuditEventSchema, view: AuditEventView): number {
|
||||
if (!xs.value) return EVENT_ROW_HEIGHT;
|
||||
let height = heights.value.get(view);
|
||||
if (height === undefined) {
|
||||
height = phoneEventRowHeight({
|
||||
title: phoneLines(view.title, "title"),
|
||||
detail: view.detail ? phoneLines(view.detail, "detail") : 0,
|
||||
where: !!(event.device_name || event.ip_address),
|
||||
});
|
||||
heights.value.set(view, height);
|
||||
}
|
||||
return height;
|
||||
}
|
||||
|
||||
// Events arrive newest first, so each local day is one run of them. Nothing is
|
||||
// handed to the scroller until the list is shown.
|
||||
const items = computed<Item[]>(() => {
|
||||
if (phase.value !== "content") return [];
|
||||
const year = new Date().getFullYear();
|
||||
const out: Item[] = [];
|
||||
let dayKey: string | null = null;
|
||||
let previous: EventItem | null = null;
|
||||
for (const event of events.value) {
|
||||
const date = new Date(event.occurred_at);
|
||||
const key = date.toDateString();
|
||||
const startsDay = key !== dayKey;
|
||||
if (startsDay) {
|
||||
if (previous) previous.last = true;
|
||||
dayKey = key;
|
||||
out.push({ kind: "day", key: `day-${key}`, label: dayLabel(date, year) });
|
||||
}
|
||||
const view = describe(event);
|
||||
previous = {
|
||||
kind: "event",
|
||||
key: event.id,
|
||||
event,
|
||||
view,
|
||||
first: startsDay,
|
||||
last: false,
|
||||
height: eventHeight(event, view),
|
||||
};
|
||||
out.push(previous);
|
||||
}
|
||||
if (previous) previous.last = true;
|
||||
if (hasMore.value) out.push({ kind: "more", key: "more" });
|
||||
return out;
|
||||
});
|
||||
|
||||
function itemHeight(item: unknown): number {
|
||||
const row = item as Item;
|
||||
return row.kind === "event" ? row.height : ROW_HEIGHTS[row.kind];
|
||||
}
|
||||
|
||||
function itemKey(item: unknown): string | number {
|
||||
return (item as Item).key;
|
||||
}
|
||||
|
||||
function onViewportRange({ last }: { first: number; last: number }) {
|
||||
if (hasMore.value && !moreFailed.value && last >= items.value.length - 20) {
|
||||
void showMore();
|
||||
}
|
||||
}
|
||||
|
||||
useGridNav(listRoot, {
|
||||
rowSelector: ".r-v2-audit-event",
|
||||
getCells: (row) => Array.from(row.querySelectorAll<HTMLElement>("a")),
|
||||
});
|
||||
|
||||
watch(items, () => readTextMetrics(), { flush: "post" });
|
||||
// The scroller's content box leaves out its scrollbar, so it narrows with one.
|
||||
useResizeObserver(
|
||||
() => scroller.value?.containerEl,
|
||||
() => readTextMetrics(),
|
||||
);
|
||||
// A web font loaded after a measure changes the widths under the same name.
|
||||
useEventListener(document.fonts, "loadingdone", (event) => {
|
||||
const fonts = textMetrics.value?.fonts;
|
||||
const loaded = (event as FontFaceSetLoadEvent).fontfaces;
|
||||
if (
|
||||
fonts &&
|
||||
loaded.some((f) => fonts.includes(f.family.replace(/["']/g, "")))
|
||||
) {
|
||||
readTextMetrics(true);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="listRoot" class="r-v2-audit" :style="EVENT_ROW_VARS">
|
||||
<RVirtualScroller
|
||||
ref="scroller"
|
||||
class="r-v2-audit__scroller"
|
||||
:items="items"
|
||||
:get-item-height="itemHeight"
|
||||
:get-item-key="itemKey"
|
||||
@update:viewport-range="onViewportRange"
|
||||
>
|
||||
<template #prepend>
|
||||
<div class="r-v2-audit__toolbar">
|
||||
<RSelect
|
||||
v-model="userFilter"
|
||||
class="r-v2-audit__select"
|
||||
:items="userItems"
|
||||
item-title="title"
|
||||
item-value="value"
|
||||
density="compact"
|
||||
hide-details
|
||||
searchable
|
||||
prepend-inner-icon="mdi-account-outline"
|
||||
:aria-label="t('audit.filter-user')"
|
||||
/>
|
||||
<RSelect
|
||||
v-model="categoryFilter"
|
||||
class="r-v2-audit__select"
|
||||
:items="categoryItems"
|
||||
item-title="title"
|
||||
item-value="value"
|
||||
density="compact"
|
||||
hide-details
|
||||
prepend-inner-icon="mdi-filter-variant"
|
||||
:aria-label="t('audit.filter-category')"
|
||||
/>
|
||||
<div class="r-v2-audit__range">
|
||||
<div class="r-v2-audit__date">
|
||||
<RDateField
|
||||
v-model="sinceDate"
|
||||
density="compact"
|
||||
hide-details
|
||||
clearable
|
||||
:max="untilDate"
|
||||
:placeholder="t('audit.since')"
|
||||
:aria-label="t('audit.since')"
|
||||
/>
|
||||
</div>
|
||||
<div class="r-v2-audit__date">
|
||||
<RDateField
|
||||
v-model="untilDate"
|
||||
density="compact"
|
||||
hide-details
|
||||
clearable
|
||||
:min="sinceDate"
|
||||
:placeholder="t('audit.until')"
|
||||
:aria-label="t('audit.until')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<RTextField
|
||||
v-model="search"
|
||||
class="r-v2-audit__search"
|
||||
density="compact"
|
||||
clearable
|
||||
hide-details
|
||||
prepend-inner-icon="mdi-magnify"
|
||||
:placeholder="t('audit.search-placeholder')"
|
||||
:aria-label="t('audit.search-placeholder')"
|
||||
@keyup.enter="searchNow"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="phase === 'skeleton'" class="r-v2-audit__skeleton">
|
||||
<RSkeletonBlock
|
||||
v-for="n in 8"
|
||||
:key="`sk-${n}`"
|
||||
width="100%"
|
||||
height="54px"
|
||||
rounded="lg"
|
||||
/>
|
||||
</div>
|
||||
<REmptyState
|
||||
v-else-if="phase === 'empty'"
|
||||
icon="mdi-timeline-clock-outline"
|
||||
:title="hasFilters ? t('audit.no-matches') : t('audit.empty')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #default="{ item }">
|
||||
<h3 v-if="(item as Item).kind === 'day'" class="r-v2-audit-day">
|
||||
{{ (item as DayItem).label }}
|
||||
</h3>
|
||||
<div
|
||||
v-else-if="(item as Item).kind === 'more'"
|
||||
class="r-v2-audit__more"
|
||||
>
|
||||
<RSpinner v-if="!moreFailed" :size="22" />
|
||||
<RBtn
|
||||
v-else
|
||||
variant="text"
|
||||
prepend-icon="mdi-refresh"
|
||||
@click="showMore"
|
||||
>
|
||||
{{ t("audit.load-error") }}
|
||||
</RBtn>
|
||||
</div>
|
||||
<EventLogRow
|
||||
v-else-if="(item as Item).kind === 'event'"
|
||||
:event="(item as EventItem).event"
|
||||
:view="(item as EventItem).view"
|
||||
:first="(item as EventItem).first"
|
||||
:last="(item as EventItem).last"
|
||||
:height="(item as EventItem).height"
|
||||
:time="
|
||||
timeFormat.format(new Date((item as EventItem).event.occurred_at))
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
</RVirtualScroller>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* The Logs page pins to the viewport, so the event log scrolls inside it:
|
||||
the toolbar scrolls away with the events, the page's tabs stay. */
|
||||
.r-v2-audit {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.r-v2-audit__scroller {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.r-v2-audit__toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: var(--r-space-2);
|
||||
}
|
||||
|
||||
.r-v2-audit__select {
|
||||
width: 190px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.r-v2-audit__range {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex: 0 0 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.r-v2-audit__date {
|
||||
width: 160px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.r-v2-audit__search {
|
||||
flex: 1 1 200px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
html[data-bp~="sm-and-down"] .r-v2-audit__select {
|
||||
width: auto;
|
||||
flex: 1 1 calc(50% - 5px);
|
||||
min-width: 0;
|
||||
}
|
||||
/* The range keeps both ends on one row, sharing the full width. */
|
||||
html[data-bp~="sm-and-down"] .r-v2-audit__range {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
html[data-bp~="sm-and-down"] .r-v2-audit__date {
|
||||
width: auto;
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.r-v2-audit__skeleton {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--r-space-2);
|
||||
}
|
||||
|
||||
.r-v2-audit-day {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
box-sizing: border-box;
|
||||
height: 44px;
|
||||
margin: 0;
|
||||
padding: 0 var(--r-space-1) var(--r-space-2);
|
||||
font-size: var(--r-font-size-sm);
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
|
||||
/* Weekday names are lowercase in many languages. */
|
||||
.r-v2-audit-day::first-letter {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.r-v2-audit__more {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 56px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,278 @@
|
||||
<script setup lang="ts">
|
||||
// EventLogRow: one event on the event log's timeline, at the height the list
|
||||
// windows it at and in the geometry the list sets (EVENT_ROW_VARS).
|
||||
import { RAvatar, RIcon } from "@v2/lib";
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { RouterLink } from "vue-router";
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
import { formatTimestamp } from "@/utils";
|
||||
import type { AuditEventView } from "@/v2/utils/auditEvents";
|
||||
import { userAvatarUrl } from "@/v2/utils/userAvatar";
|
||||
|
||||
const props = defineProps<{
|
||||
event: AuditEventSchema;
|
||||
view: AuditEventView;
|
||||
/** The day's first and last events close its panel and its rail. */
|
||||
first: boolean;
|
||||
last: boolean;
|
||||
/** The time of day it happened, formatted by the list for all its rows. */
|
||||
time: string;
|
||||
height: number;
|
||||
}>();
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
const actorName = computed(() => {
|
||||
const { actor_kind, actor, actor_name } = props.event;
|
||||
if (actor_kind === "system") return t("audit.system");
|
||||
if (actor_kind === "anonymous") return t("audit.anonymous");
|
||||
return actor?.username ?? actor_name ?? t("audit.deleted-user");
|
||||
});
|
||||
|
||||
const actorIcon = computed(() => {
|
||||
const { actor_kind, actor } = props.event;
|
||||
if (actor_kind === "system") return "mdi-robot-outline";
|
||||
if (actor_kind === "anonymous") return "mdi-incognito";
|
||||
return actor ? undefined : "mdi-account-off-outline";
|
||||
});
|
||||
|
||||
const actorAvatar = computed(() => {
|
||||
const { actor } = props.event;
|
||||
if (!actor) return undefined;
|
||||
return userAvatarUrl({
|
||||
userId: actor.id,
|
||||
avatarPath: actor.avatar_path,
|
||||
updatedAt: actor.updated_at,
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="r-v2-audit-event"
|
||||
:class="{
|
||||
'r-v2-audit-event--first': first,
|
||||
'r-v2-audit-event--last': last,
|
||||
}"
|
||||
:style="{ height: `${height}px` }"
|
||||
>
|
||||
<time
|
||||
class="r-v2-audit-event__time"
|
||||
:datetime="event.occurred_at"
|
||||
:title="formatTimestamp(event.occurred_at, locale)"
|
||||
>
|
||||
{{ time }}
|
||||
</time>
|
||||
<span class="r-v2-audit-event__rail">
|
||||
<span
|
||||
class="r-v2-audit-event__dot"
|
||||
:style="{ '--r-audit-tone': view.tone }"
|
||||
>
|
||||
<RIcon :icon="view.icon" size="16" />
|
||||
</span>
|
||||
</span>
|
||||
<span class="r-v2-audit-event__body">
|
||||
<component
|
||||
:is="view.to ? RouterLink : 'span'"
|
||||
:to="view.to ?? undefined"
|
||||
class="r-v2-audit-event__title"
|
||||
>
|
||||
{{ view.title }}
|
||||
</component>
|
||||
<span class="r-v2-audit-event__meta">
|
||||
<span class="r-v2-audit-event__item r-v2-audit-event__actor">
|
||||
<RAvatar
|
||||
:image="actorAvatar"
|
||||
:icon="actorIcon"
|
||||
variant="translucent"
|
||||
size="16"
|
||||
/>
|
||||
<span class="r-v2-audit-event__text">{{ actorName }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="view.detail"
|
||||
class="r-v2-audit-event__item r-v2-audit-event__detail"
|
||||
>
|
||||
<span class="r-v2-audit-event__text">{{ view.detail }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="event.device_name"
|
||||
class="r-v2-audit-event__item r-v2-audit-event__device"
|
||||
>
|
||||
<RIcon icon="mdi-devices" size="14" />
|
||||
<span class="r-v2-audit-event__text">{{ event.device_name }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="event.ip_address"
|
||||
class="r-v2-audit-event__item r-v2-audit-event__ip"
|
||||
>
|
||||
<RIcon icon="mdi-ip-network-outline" size="14" />
|
||||
{{ event.ip_address }}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Each day reads as one panel: its first and last rows round the corners. */
|
||||
.r-v2-audit-event {
|
||||
--r-audit-dot: 28px;
|
||||
display: grid;
|
||||
grid-template-columns: 3.25rem var(--r-audit-dot) minmax(0, 1fr);
|
||||
column-gap: var(--r-space-3);
|
||||
box-sizing: border-box;
|
||||
padding: var(--r-audit-pad-block) var(--r-space-4);
|
||||
background: var(--r-color-surface);
|
||||
border-inline: 1px solid var(--r-color-border);
|
||||
}
|
||||
.r-v2-audit-event--first {
|
||||
border-top: 1px solid var(--r-color-border);
|
||||
border-start-start-radius: var(--r-radius-card);
|
||||
border-start-end-radius: var(--r-radius-card);
|
||||
}
|
||||
.r-v2-audit-event--last {
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
border-end-start-radius: var(--r-radius-card);
|
||||
border-end-end-radius: var(--r-radius-card);
|
||||
}
|
||||
|
||||
.r-v2-audit-event__time {
|
||||
padding-top: 5px;
|
||||
font-size: var(--r-font-size-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: end;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
|
||||
/* One rail joins the day's events through the middle of their icons. */
|
||||
.r-v2-audit-event__rail {
|
||||
position: relative;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
.r-v2-audit-event__rail::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: calc(-1 * var(--r-audit-pad-block));
|
||||
bottom: calc(-1 * var(--r-audit-pad-block));
|
||||
left: 50%;
|
||||
width: 2px;
|
||||
transform: translateX(-50%);
|
||||
background: var(--r-color-border);
|
||||
}
|
||||
.r-v2-audit-event--first .r-v2-audit-event__rail::before {
|
||||
top: calc(var(--r-audit-dot) / 2);
|
||||
}
|
||||
.r-v2-audit-event--last .r-v2-audit-event__rail::before {
|
||||
bottom: calc(100% - var(--r-audit-dot) / 2);
|
||||
}
|
||||
|
||||
/* The page's own background is the one color that reads on every tone. */
|
||||
.r-v2-audit-event__dot {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--r-audit-dot);
|
||||
height: var(--r-audit-dot);
|
||||
border-radius: 50%;
|
||||
background: var(--r-audit-tone);
|
||||
color: var(--r-color-bg);
|
||||
}
|
||||
|
||||
.r-v2-audit-event__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--r-audit-gap);
|
||||
min-width: 0;
|
||||
padding-top: 3px;
|
||||
}
|
||||
|
||||
.r-v2-audit-event__title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--r-font-size-md);
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
color: var(--r-color-fg);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a.r-v2-audit-event__title:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Who, what, and where from, on one line; long names shorten rather than
|
||||
push what follows off the end. */
|
||||
.r-v2-audit-event__meta {
|
||||
display: flex;
|
||||
gap: var(--r-space-3);
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
font-size: var(--r-font-size-sm);
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
|
||||
.r-v2-audit-event__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
.r-v2-audit-event__actor,
|
||||
.r-v2-audit-event__ip {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.r-v2-audit-event__text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.r-v2-audit-event__ip {
|
||||
font-family: var(--r-font-family-mono);
|
||||
}
|
||||
|
||||
html[data-bp~="xs"] .r-v2-audit-event {
|
||||
grid-template-columns: 2.75rem var(--r-audit-dot) minmax(0, 1fr);
|
||||
column-gap: var(--r-space-2);
|
||||
padding-inline: var(--r-space-3);
|
||||
}
|
||||
/* A phone stacks the title, the detail, who, and where from, in that order
|
||||
on every row; the list sizes each row for how its title and detail wrap. */
|
||||
html[data-bp~="xs"] .r-v2-audit-event__body {
|
||||
padding-top: var(--r-audit-title-offset);
|
||||
}
|
||||
html[data-bp~="xs"] .r-v2-audit-event__title,
|
||||
html[data-bp~="xs"] .r-v2-audit-event__detail .r-v2-audit-event__text {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: var(--r-audit-max-lines);
|
||||
line-clamp: var(--r-audit-max-lines);
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
html[data-bp~="xs"] .r-v2-audit-event__title {
|
||||
line-height: var(--r-audit-title-line);
|
||||
}
|
||||
html[data-bp~="xs"] .r-v2-audit-event__meta {
|
||||
flex-wrap: wrap;
|
||||
gap: var(--r-audit-gap) var(--r-space-3);
|
||||
line-height: var(--r-audit-meta-line);
|
||||
}
|
||||
html[data-bp~="xs"] .r-v2-audit-event__actor,
|
||||
html[data-bp~="xs"] .r-v2-audit-event__detail {
|
||||
flex: 0 0 100%;
|
||||
}
|
||||
html[data-bp~="xs"] .r-v2-audit-event__detail {
|
||||
order: -1;
|
||||
}
|
||||
/* No basis, so a long device name shortens beside the address instead of
|
||||
wrapping it onto a line of its own. */
|
||||
html[data-bp~="xs"] .r-v2-audit-event__device {
|
||||
flex: 1 1 0;
|
||||
max-width: max-content;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,560 @@
|
||||
<script setup lang="ts">
|
||||
// LogViewer: the backend log, backfilled from `GET /logs` then streamed over
|
||||
// Socket.IO (`logs:entry`) into a capped in-memory buffer, newest line on top.
|
||||
import { RBtn, RSelect, RTextField, RTooltip, RVirtualScroller } from "@v2/lib";
|
||||
import { computed, nextTick, onBeforeMount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import api from "@/services/api";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { useSocketEvent } from "@/v2/composables/useSocketEvent";
|
||||
|
||||
const { t } = useI18n();
|
||||
const snackbar = useSnackbar();
|
||||
|
||||
interface LogEntry {
|
||||
ts: number;
|
||||
level: string;
|
||||
module: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface LogRow extends LogEntry {
|
||||
// Client-side monotonic key: the backend payload has no id, and a
|
||||
// stable key keeps virtual-scroller rows from re-patching on front
|
||||
// eviction.
|
||||
seq: number;
|
||||
// The message as emitted, before newline folding. What the tooltip,
|
||||
// the clipboard and the downloaded file use.
|
||||
raw: string;
|
||||
}
|
||||
|
||||
// Cap the in-memory buffer so a long-lived view holds memory flat.
|
||||
const MAX_ENTRIES = 2000;
|
||||
// Fixed row height: single-line rows keep windowing math exact.
|
||||
const ROW_HEIGHT = 24;
|
||||
|
||||
const LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] as const;
|
||||
|
||||
const entries = ref<LogRow[]>([]);
|
||||
const pending = ref<LogRow[]>([]);
|
||||
const paused = ref(false);
|
||||
const autoTail = ref(true);
|
||||
const loading = ref(true);
|
||||
|
||||
const levelFilter = ref<string>("ALL");
|
||||
const moduleFilter = ref<string>("ALL");
|
||||
const search = ref("");
|
||||
|
||||
// ANSI SGR escapes are stripped server-side now, but lines buffered before
|
||||
// that fix (or any future stray escape) get cleaned here too.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ANSI_RE = /\x1b\[[0-9;]*m/g;
|
||||
|
||||
// A record can carry embedded newlines: a provider logging a formatted JSON
|
||||
// body, a traceback. Rows are one line tall, so a message rendered with
|
||||
// `white-space: pre` painted over the rows the scroller placed after it.
|
||||
const NEWLINE_RE = /\r?\n\s*/g;
|
||||
|
||||
let seqCounter = 0;
|
||||
function toRow(entry: LogEntry): LogRow {
|
||||
const raw = entry.message.replace(ANSI_RE, "");
|
||||
return {
|
||||
...entry,
|
||||
message: raw.trim().replace(NEWLINE_RE, " ⏎ "),
|
||||
raw,
|
||||
seq: seqCounter++,
|
||||
};
|
||||
}
|
||||
|
||||
const levelItems = computed(() => [
|
||||
{ title: t("logs.level-all"), value: "ALL" },
|
||||
...LEVELS.map((l) => ({ title: l, value: l })),
|
||||
]);
|
||||
|
||||
// Module options are data-driven: the backend has no fixed catalogue, so
|
||||
// they're derived from whatever modules the buffered entries carry. The
|
||||
// active selection is always kept in the list (even if its module has
|
||||
// scrolled out of the ring buffer) so the select never goes blank.
|
||||
const moduleItems = computed(() => {
|
||||
const mods = new Set<string>();
|
||||
for (const e of entries.value) {
|
||||
if (e.module) mods.add(e.module);
|
||||
}
|
||||
if (moduleFilter.value !== "ALL") mods.add(moduleFilter.value);
|
||||
return [
|
||||
{ title: t("logs.module-all"), value: "ALL" },
|
||||
...[...mods].sort().map((m) => ({ title: m, value: m })),
|
||||
];
|
||||
});
|
||||
|
||||
// Rank levels so "minimum severity" filtering shows the selected level
|
||||
// and everything above it.
|
||||
const LEVEL_RANK: Record<string, number> = {
|
||||
DEBUG: 10,
|
||||
INFO: 20,
|
||||
WARNING: 30,
|
||||
ERROR: 40,
|
||||
CRITICAL: 50,
|
||||
};
|
||||
|
||||
const matchesFilters = computed(() => {
|
||||
const minRank =
|
||||
levelFilter.value === "ALL" ? 0 : (LEVEL_RANK[levelFilter.value] ?? 0);
|
||||
const mod = moduleFilter.value;
|
||||
const q = search.value.trim().toLowerCase();
|
||||
return (e: LogRow) => {
|
||||
if ((LEVEL_RANK[e.level] ?? 0) < minRank) return false;
|
||||
if (mod !== "ALL" && e.module !== mod) return false;
|
||||
return (
|
||||
!q ||
|
||||
e.raw.toLowerCase().includes(q) ||
|
||||
e.module.toLowerCase().includes(q)
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
// Oldest first, the order copies and downloads keep.
|
||||
const filtered = computed<LogRow[]>(() =>
|
||||
entries.value.filter(matchesFilters.value),
|
||||
);
|
||||
// Newest first, so the latest line sits under the toolbar.
|
||||
const shown = computed<LogRow[]>(() => [...filtered.value].reverse());
|
||||
|
||||
// Wide enough for the longest line, counted in `ch` of the rows' monospace
|
||||
// font; the px cover the row's padding, its gaps and the level column.
|
||||
const contentWidth = computed(() => {
|
||||
const timeChars = formatTime(Date.now()).length;
|
||||
let chars = 0;
|
||||
for (const e of shown.value) {
|
||||
chars = Math.max(chars, e.module.length + e.message.length);
|
||||
}
|
||||
return `calc(${timeChars + chars + 2}ch + 134px)`;
|
||||
});
|
||||
|
||||
const scrollerRef = ref<InstanceType<typeof RVirtualScroller> | null>(null);
|
||||
|
||||
function getItemHeight() {
|
||||
return ROW_HEIGHT;
|
||||
}
|
||||
function getItemKey(item: unknown) {
|
||||
return (item as LogRow).seq;
|
||||
}
|
||||
|
||||
function pushEntries(rows: LogRow[]) {
|
||||
if (rows.length === 0) return;
|
||||
const added = rows.filter(matchesFilters.value).length;
|
||||
const next = entries.value.concat(rows);
|
||||
// Trim the oldest once we exceed the cap; they're at the bottom.
|
||||
entries.value =
|
||||
next.length > MAX_ENTRIES ? next.slice(next.length - MAX_ENTRIES) : next;
|
||||
// New lines land above the one being read, so push the view down by as much.
|
||||
if (!autoTail.value && added > 0) {
|
||||
void nextTick(() => {
|
||||
const el = scrollerRef.value?.containerEl;
|
||||
if (el) el.scrollTop += added * ROW_HEIGHT;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
useSocketEvent<LogEntry>("logs:entry", (entry) => {
|
||||
const row = toRow(entry);
|
||||
if (paused.value) {
|
||||
pending.value.push(row);
|
||||
// Bound the paused queue too so a long pause can't grow unbounded.
|
||||
if (pending.value.length > MAX_ENTRIES) {
|
||||
pending.value = pending.value.slice(pending.value.length - MAX_ENTRIES);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pushEntries([row]);
|
||||
});
|
||||
|
||||
onBeforeMount(async () => {
|
||||
try {
|
||||
const { data } = await api.get<LogEntry[]>("/logs", {
|
||||
params: { limit: 1000 },
|
||||
});
|
||||
entries.value = data.map(toRow);
|
||||
} catch {
|
||||
snackbar.error(t("logs.load-error"));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
function onViewportRange(range: { first: number; last: number }) {
|
||||
// Following while the newest line is in view; scrolling down off it stops.
|
||||
autoTail.value = range.first === 0;
|
||||
}
|
||||
|
||||
function jumpToLatest() {
|
||||
autoTail.value = true;
|
||||
scrollerRef.value?.containerEl?.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
|
||||
function togglePause() {
|
||||
paused.value = !paused.value;
|
||||
if (!paused.value && pending.value.length > 0) {
|
||||
const queued = pending.value;
|
||||
pending.value = [];
|
||||
pushEntries(queued);
|
||||
}
|
||||
}
|
||||
|
||||
function clearLogs() {
|
||||
entries.value = [];
|
||||
pending.value = [];
|
||||
}
|
||||
|
||||
function levelClass(level: string) {
|
||||
return `r-v2-logs__level--${level.toLowerCase()}`;
|
||||
}
|
||||
|
||||
function formatTime(ts: number) {
|
||||
return new Date(ts).toLocaleTimeString();
|
||||
}
|
||||
|
||||
function asLine(e: LogRow) {
|
||||
return `[${new Date(e.ts).toISOString()}] ${e.level} [${e.module}] ${e.raw}`;
|
||||
}
|
||||
|
||||
async function copyLogs() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(filtered.value.map(asLine).join("\n"));
|
||||
snackbar.success(t("logs.copied"));
|
||||
} catch {
|
||||
snackbar.error(t("logs.copy-error"));
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRow(row: LogRow) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(asLine(row));
|
||||
snackbar.success(t("logs.line-copied"));
|
||||
} catch {
|
||||
snackbar.error(t("logs.copy-error"));
|
||||
}
|
||||
}
|
||||
|
||||
function downloadLogs() {
|
||||
const blob = new Blob([filtered.value.map(asLine).join("\n")], {
|
||||
type: "text/plain",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `romm-logs-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-logs">
|
||||
<RVirtualScroller
|
||||
ref="scrollerRef"
|
||||
class="r-v2-logs__scroller"
|
||||
:items="shown"
|
||||
:get-item-height="getItemHeight"
|
||||
:get-item-key="getItemKey"
|
||||
:min-content-width="contentWidth"
|
||||
@update:viewport-range="onViewportRange"
|
||||
>
|
||||
<template #prepend>
|
||||
<div class="r-v2-logs__toolbar">
|
||||
<RSelect
|
||||
v-model="levelFilter"
|
||||
class="r-v2-logs__level-select"
|
||||
:items="levelItems"
|
||||
item-title="title"
|
||||
item-value="value"
|
||||
density="compact"
|
||||
hide-details
|
||||
prepend-inner-icon="mdi-filter-variant"
|
||||
:aria-label="t('logs.level-filter')"
|
||||
/>
|
||||
<RSelect
|
||||
v-model="moduleFilter"
|
||||
class="r-v2-logs__module-select"
|
||||
:items="moduleItems"
|
||||
item-title="title"
|
||||
item-value="value"
|
||||
density="compact"
|
||||
hide-details
|
||||
prepend-inner-icon="mdi-cube-outline"
|
||||
:aria-label="t('logs.module-filter')"
|
||||
/>
|
||||
<RTextField
|
||||
v-model="search"
|
||||
class="r-v2-logs__search"
|
||||
density="compact"
|
||||
clearable
|
||||
hide-details
|
||||
prepend-inner-icon="mdi-magnify"
|
||||
:placeholder="t('logs.search-placeholder')"
|
||||
:aria-label="t('logs.search-placeholder')"
|
||||
/>
|
||||
<div class="r-v2-logs__spacer" />
|
||||
<div class="r-v2-logs__actions">
|
||||
<RBtn
|
||||
:icon="paused ? 'mdi-play' : 'mdi-pause'"
|
||||
variant="text"
|
||||
density="compact"
|
||||
:color="paused ? 'primary' : undefined"
|
||||
:tooltip="paused ? t('logs.resume') : t('logs.pause')"
|
||||
:aria-label="paused ? t('logs.resume') : t('logs.pause')"
|
||||
@click="togglePause"
|
||||
/>
|
||||
<RBtn
|
||||
icon="mdi-content-copy"
|
||||
variant="text"
|
||||
density="compact"
|
||||
:disabled="filtered.length === 0"
|
||||
:tooltip="t('logs.copy')"
|
||||
:aria-label="t('logs.copy')"
|
||||
@click="copyLogs"
|
||||
/>
|
||||
<RBtn
|
||||
icon="mdi-download"
|
||||
variant="text"
|
||||
density="compact"
|
||||
:disabled="filtered.length === 0"
|
||||
:tooltip="t('logs.download')"
|
||||
:aria-label="t('logs.download')"
|
||||
@click="downloadLogs"
|
||||
/>
|
||||
<RBtn
|
||||
icon="mdi-notification-clear-all"
|
||||
variant="text"
|
||||
density="compact"
|
||||
:disabled="entries.length === 0"
|
||||
:tooltip="t('logs.clear')"
|
||||
:aria-label="t('logs.clear')"
|
||||
@click="clearLogs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!loading && filtered.length === 0" class="r-v2-logs__empty">
|
||||
{{ entries.length === 0 ? t("logs.empty") : t("logs.no-matches") }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #default="{ item, index }">
|
||||
<!-- eslint-disable-next-line vuejs-accessibility/click-events-have-key-events, vuejs-accessibility/no-static-element-interactions -- row click is a pointer convenience for copying a single line; keyboard/AT users have the toolbar's Copy-all and Download actions -->
|
||||
<div
|
||||
class="r-v2-logs__row"
|
||||
:class="{
|
||||
'r-v2-logs__row--first': index === 0,
|
||||
'r-v2-logs__row--last': index === shown.length - 1,
|
||||
}"
|
||||
@click="copyRow(item as LogRow)"
|
||||
>
|
||||
<RTooltip
|
||||
activator="parent"
|
||||
location="top start"
|
||||
max-width="min(80vw, 900px)"
|
||||
hint-icon="mdi-content-copy"
|
||||
:text="(item as LogRow).raw"
|
||||
:hint="t('logs.click-to-copy')"
|
||||
/>
|
||||
<span class="r-v2-logs__time">{{
|
||||
formatTime((item as LogRow).ts)
|
||||
}}</span>
|
||||
<span
|
||||
class="r-v2-logs__level"
|
||||
:class="levelClass((item as LogRow).level)"
|
||||
>{{ (item as LogRow).level }}</span
|
||||
>
|
||||
<span class="r-v2-logs__module">[{{ (item as LogRow).module }}]</span>
|
||||
<span class="r-v2-logs__message">{{ (item as LogRow).message }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</RVirtualScroller>
|
||||
|
||||
<RBtn
|
||||
v-if="!autoTail"
|
||||
class="r-v2-logs__jump"
|
||||
variant="flat"
|
||||
color="primary"
|
||||
size="small"
|
||||
prepend-icon="mdi-arrow-up"
|
||||
@click="jumpToLatest"
|
||||
>
|
||||
{{ t("logs.jump-to-latest") }}
|
||||
</RBtn>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Fills the Logs page's tab body; the scroller below is its only scroll, so the
|
||||
toolbar scrolls away with the lines while the page's tabs stay. */
|
||||
.r-v2-logs {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Pinned to the left edge while the lines scroll sideways under it. */
|
||||
.r-v2-logs__toolbar,
|
||||
.r-v2-logs__empty {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.r-v2-logs__toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.r-v2-logs__level-select {
|
||||
width: 160px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.r-v2-logs__module-select {
|
||||
width: 160px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.r-v2-logs__search {
|
||||
width: 260px;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.r-v2-logs__spacer {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.r-v2-logs__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
/* Phones: the single control row overflows off the right edge. Wrap it into
|
||||
two: the level + module selectors share the first row; the search field and
|
||||
the action buttons share the second. */
|
||||
html[data-bp~="sm-and-down"] .r-v2-logs__toolbar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
html[data-bp~="sm-and-down"] .r-v2-logs__level-select,
|
||||
html[data-bp~="sm-and-down"] .r-v2-logs__module-select {
|
||||
width: auto;
|
||||
flex: 1 1 calc(50% - 5px);
|
||||
min-width: 0;
|
||||
}
|
||||
html[data-bp~="sm-and-down"] .r-v2-logs__search {
|
||||
width: auto;
|
||||
/* Small, non-zero basis: >0 so it wraps off the (full) first row, small
|
||||
enough that it + the action cluster still share the second row on a 320px
|
||||
screen. It grows to fill the leftover width. */
|
||||
flex: 1 1 110px;
|
||||
min-width: 0;
|
||||
}
|
||||
/* Search grows to fill the second row; the action cluster sits to its right. */
|
||||
html[data-bp~="sm-and-down"] .r-v2-logs__spacer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.r-v2-logs__scroller {
|
||||
height: 100%;
|
||||
}
|
||||
/* The rows' font, set here so the `ch` in the content width measures them. */
|
||||
.r-v2-logs__scroller :deep(.r-virtual-scroller__inner) {
|
||||
font-family: var(--r-font-family-mono);
|
||||
font-size: var(--r-font-size-sm);
|
||||
}
|
||||
|
||||
/* The lines read as one panel: the first and last round its corners. */
|
||||
.r-v2-logs__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
box-sizing: border-box;
|
||||
height: 24px;
|
||||
padding: 0 16px;
|
||||
line-height: 22px;
|
||||
white-space: nowrap;
|
||||
/* Structural guard: the row is one line tall, so anything taller would
|
||||
paint over the rows the scroller placed after it. */
|
||||
overflow: hidden;
|
||||
color: var(--r-color-fg-secondary);
|
||||
background: var(--r-color-bg-elevated);
|
||||
border-inline: 1px solid var(--r-color-border);
|
||||
cursor: pointer;
|
||||
}
|
||||
.r-v2-logs__row--first {
|
||||
border-top: 1px solid var(--r-color-border);
|
||||
border-start-start-radius: var(--r-radius-card);
|
||||
border-start-end-radius: var(--r-radius-card);
|
||||
}
|
||||
.r-v2-logs__row--last {
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
border-end-start-radius: var(--r-radius-card);
|
||||
border-end-end-radius: var(--r-radius-card);
|
||||
}
|
||||
|
||||
.r-v2-logs__row:hover {
|
||||
background: var(--r-color-surface-hover);
|
||||
}
|
||||
|
||||
.r-v2-logs__time {
|
||||
flex: 0 0 auto;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
|
||||
.r-v2-logs__level {
|
||||
flex: 0 0 72px;
|
||||
font-weight: var(--r-font-weight-bold);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.r-v2-logs__level--debug {
|
||||
color: var(--r-color-brand-primary);
|
||||
}
|
||||
.r-v2-logs__level--info {
|
||||
color: var(--r-color-status-base-success);
|
||||
}
|
||||
.r-v2-logs__level--warning {
|
||||
color: var(--r-color-status-base-warning);
|
||||
}
|
||||
.r-v2-logs__level--error,
|
||||
.r-v2-logs__level--critical {
|
||||
color: var(--r-color-status-base-danger);
|
||||
}
|
||||
|
||||
.r-v2-logs__module {
|
||||
flex: 0 0 auto;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
|
||||
.r-v2-logs__message {
|
||||
flex: 0 0 auto;
|
||||
white-space: pre;
|
||||
color: var(--r-color-fg);
|
||||
}
|
||||
|
||||
.r-v2-logs__empty {
|
||||
padding: 48px 16px;
|
||||
border: 1px solid var(--r-color-border);
|
||||
border-radius: var(--r-radius-card);
|
||||
background: var(--r-color-bg-elevated);
|
||||
text-align: center;
|
||||
color: var(--r-color-fg-muted);
|
||||
font-size: var(--r-font-size-md);
|
||||
}
|
||||
|
||||
.r-v2-logs__jump {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
box-shadow: 0 4px 16px color-mix(in srgb, black 30%, transparent);
|
||||
}
|
||||
</style>
|
||||
@@ -23,7 +23,6 @@ import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ROUTES } from "@/plugins/router";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storeHeartbeat from "@/stores/heartbeat";
|
||||
import { useCan } from "@/v2/composables/useCan";
|
||||
import storeNotificationInbox from "@/v2/stores/notificationInbox";
|
||||
|
||||
@@ -34,11 +33,6 @@ const auth = storeAuth();
|
||||
const { user, scopes } = storeToRefs(auth);
|
||||
const isAdmin = useCan("app.admin");
|
||||
const { unreadCount } = storeToRefs(storeNotificationInbox());
|
||||
const heartbeat = storeHeartbeat();
|
||||
const logsViewerEnabled = computed(
|
||||
() => !heartbeat.value.FRONTEND.DISABLE_LOGS_VIEWER,
|
||||
);
|
||||
|
||||
interface Entry {
|
||||
icon: string;
|
||||
label: string;
|
||||
@@ -154,7 +148,7 @@ const groups = computed<Group[]>(() => {
|
||||
icon: "mdi-text-box-search-outline",
|
||||
label: t("common.logs"),
|
||||
to: { name: ROUTES.LOGS },
|
||||
visible: isAdmin.value && logsViewerEnabled.value,
|
||||
visible: isAdmin.value,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// The event log row's geometry, shared by EventLogRow's styles and the list's
|
||||
// windowing, which has to know every row's height before it renders.
|
||||
|
||||
/** A row with its title and details each on one line. */
|
||||
export const EVENT_ROW_HEIGHT = 62;
|
||||
|
||||
/** A row's spacing; on a phone it also stacks title, detail, author and where. */
|
||||
export const EVENT_ROW = {
|
||||
paddingBlock: 8,
|
||||
gap: 2,
|
||||
/** Drops the title's first line to the middle of the event's icon. */
|
||||
titleOffset: 4,
|
||||
titleLine: 19,
|
||||
metaLine: 17,
|
||||
/** The title and the detail each wrap to at most this many lines. */
|
||||
maxLines: 2,
|
||||
} as const;
|
||||
|
||||
/** The geometry as the custom properties EventLogRow's styles read. */
|
||||
export const EVENT_ROW_VARS = {
|
||||
"--r-audit-pad-block": `${EVENT_ROW.paddingBlock}px`,
|
||||
"--r-audit-gap": `${EVENT_ROW.gap}px`,
|
||||
"--r-audit-title-offset": `${EVENT_ROW.titleOffset}px`,
|
||||
"--r-audit-title-line": `${EVENT_ROW.titleLine}px`,
|
||||
"--r-audit-meta-line": `${EVENT_ROW.metaLine}px`,
|
||||
"--r-audit-max-lines": EVENT_ROW.maxLines,
|
||||
};
|
||||
|
||||
export function phoneEventRowHeight({
|
||||
title,
|
||||
detail,
|
||||
where,
|
||||
}: {
|
||||
title: number;
|
||||
/** 0 when the event has no detail. */
|
||||
detail: number;
|
||||
/** Whether it names a device or an address. */
|
||||
where: boolean;
|
||||
}): number {
|
||||
const { paddingBlock, gap, titleOffset, titleLine, metaLine } = EVENT_ROW;
|
||||
const line = metaLine + gap;
|
||||
return (
|
||||
2 * paddingBlock +
|
||||
titleOffset +
|
||||
title * titleLine +
|
||||
line +
|
||||
(detail ? detail * metaLine + gap : 0) +
|
||||
(where ? line : 0)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
import auditApi from "@/services/api/audit";
|
||||
import { useAuditLog } from "@/v2/composables/useAuditLog";
|
||||
|
||||
vi.mock("@/services/api/audit", () => ({
|
||||
default: { getAuditEvents: vi.fn() },
|
||||
}));
|
||||
|
||||
const getAuditEvents = vi.mocked(auditApi.getAuditEvents);
|
||||
|
||||
function page(ids: number[], total: number, maxId: number | null = null) {
|
||||
return {
|
||||
data: {
|
||||
items: ids.map((id) => ({ id }) as AuditEventSchema),
|
||||
total,
|
||||
limit: 2,
|
||||
offset: 0,
|
||||
max_id: maxId,
|
||||
},
|
||||
} as Awaited<ReturnType<typeof auditApi.getAuditEvents>>;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
getAuditEvents.mockReset();
|
||||
});
|
||||
|
||||
describe("useAuditLog", () => {
|
||||
it("pins later pages to the highest id the first one saw", async () => {
|
||||
getAuditEvents
|
||||
.mockResolvedValueOnce(page([9, 8], 3, 12))
|
||||
.mockResolvedValueOnce(page([7], 3));
|
||||
const log = useAuditLog(2);
|
||||
|
||||
await log.reset({ categories: ["consumption"] });
|
||||
await log.loadMore();
|
||||
|
||||
expect(getAuditEvents).toHaveBeenLastCalledWith({
|
||||
categories: ["consumption"],
|
||||
maxId: 12,
|
||||
limit: 2,
|
||||
offset: 2,
|
||||
});
|
||||
expect(log.events.value.map((e) => e.id)).toEqual([9, 8, 7]);
|
||||
expect(log.hasMore.value).toBe(false);
|
||||
});
|
||||
|
||||
it("clears what the old filters matched when a reload fails", async () => {
|
||||
getAuditEvents
|
||||
.mockResolvedValueOnce(page([9, 8], 2))
|
||||
.mockRejectedValueOnce(new Error("down"));
|
||||
const log = useAuditLog(2);
|
||||
|
||||
await log.reset({});
|
||||
await expect(log.reset({ search: "new" })).rejects.toThrow("down");
|
||||
|
||||
expect(log.events.value).toEqual([]);
|
||||
expect(log.hasMore.value).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a page that a newer reset overtook", async () => {
|
||||
let resolveFirst: (value: ReturnType<typeof page>) => void = () => {};
|
||||
getAuditEvents
|
||||
.mockReturnValueOnce(new Promise((resolve) => (resolveFirst = resolve)))
|
||||
.mockResolvedValueOnce(page([5], 1));
|
||||
const log = useAuditLog(2);
|
||||
|
||||
const stale = log.reset({ search: "old" });
|
||||
await log.reset({ search: "new" });
|
||||
resolveFirst(page([1, 2], 2));
|
||||
await stale;
|
||||
|
||||
expect(log.events.value.map((e) => e.id)).toEqual([5]);
|
||||
expect(log.loading.value).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
import auditApi, { type AuditEventsQuery } from "@/services/api/audit";
|
||||
|
||||
type AuditLogFilters = Omit<AuditEventsQuery, "maxId" | "limit" | "offset">;
|
||||
|
||||
/** Pages through the audit log, newest first, pinned to what the first page saw. */
|
||||
export function useAuditLog(pageSize = 50) {
|
||||
const events = shallowRef<AuditEventSchema[]>([]);
|
||||
const total = ref(0);
|
||||
const loading = ref(false);
|
||||
const loadingMore = ref(false);
|
||||
|
||||
let filters: AuditLogFilters = {};
|
||||
// Events recorded after the first page would shift every later offset.
|
||||
let maxId: number | undefined;
|
||||
// A reset while a page is in flight makes that page stale.
|
||||
let generation = 0;
|
||||
|
||||
const hasMore = computed(() => events.value.length < total.value);
|
||||
|
||||
async function reset(next: AuditLogFilters): Promise<void> {
|
||||
const current = ++generation;
|
||||
filters = next;
|
||||
maxId = undefined;
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await auditApi.getAuditEvents({
|
||||
...filters,
|
||||
limit: pageSize,
|
||||
offset: 0,
|
||||
});
|
||||
if (current !== generation) return;
|
||||
events.value = data.items;
|
||||
total.value = data.total;
|
||||
maxId = data.max_id ?? undefined;
|
||||
} catch (error) {
|
||||
// What's on screen was matched by the old filters, so it can't stay.
|
||||
if (current === generation) {
|
||||
events.value = [];
|
||||
total.value = 0;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (current === generation) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore(): Promise<void> {
|
||||
if (loading.value || loadingMore.value || !hasMore.value) return;
|
||||
const current = generation;
|
||||
loadingMore.value = true;
|
||||
try {
|
||||
const { data } = await auditApi.getAuditEvents({
|
||||
...filters,
|
||||
maxId,
|
||||
limit: pageSize,
|
||||
offset: events.value.length,
|
||||
});
|
||||
if (current !== generation) return;
|
||||
events.value = [...events.value, ...data.items];
|
||||
total.value = data.total;
|
||||
} finally {
|
||||
loadingMore.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return { events, loading, hasMore, reset, loadMore };
|
||||
}
|
||||
@@ -149,9 +149,9 @@ html[data-bp~="sm-and-down"] .r-v2-settings--fill {
|
||||
|
||||
/* On sm-and-down the sidebar is unmounted (see script), so the content
|
||||
column fills the row on its own — just tighten the gutters to the
|
||||
responsive page padding. */
|
||||
responsive page padding. The nav bar right above already separates it. */
|
||||
html[data-bp~="sm-and-down"] .r-v2-settings__content {
|
||||
padding: 24px var(--r-row-pad) 48px;
|
||||
padding: var(--r-space-2) var(--r-row-pad) 48px;
|
||||
}
|
||||
/* Fill views own their height and reserve the bottom bar separately, so the
|
||||
generous 48px scroll gutter above just leaves a big empty band under the
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
|
||||
export function makeAuditEvent(
|
||||
overrides: Partial<AuditEventSchema> = {},
|
||||
): AuditEventSchema {
|
||||
return {
|
||||
id: 1,
|
||||
action: "rom.download",
|
||||
category: null,
|
||||
occurred_at: "2026-09-24T10:00:00Z",
|
||||
actor_kind: "user",
|
||||
actor: null,
|
||||
actor_name: "zurdi",
|
||||
target_type: "rom",
|
||||
target_id: "12",
|
||||
target_name: "Metroid",
|
||||
ip_address: null,
|
||||
device_id: null,
|
||||
device_name: null,
|
||||
data: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
import { loadLocale } from "@/locales";
|
||||
import { ROUTES } from "@/plugins/routeNames";
|
||||
import { describeAuditEvent } from "@/v2/utils/auditEvents";
|
||||
import { makeAuditEvent } from "@/v2/utils/auditEvents.fixtures";
|
||||
|
||||
function event(
|
||||
action: string,
|
||||
overrides: Partial<AuditEventSchema> = {},
|
||||
): AuditEventSchema {
|
||||
return makeAuditEvent({ action, ...overrides });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await loadLocale("en_US");
|
||||
});
|
||||
|
||||
describe("describeAuditEvent", () => {
|
||||
it("names a downloaded game and links to it", () => {
|
||||
const view = describeAuditEvent(
|
||||
event("rom.download", {
|
||||
data: { file_name: "Metroid (USA).nes", size_bytes: 2048 },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view.title).toBe("Downloaded Metroid");
|
||||
expect(view.detail).toMatch(/^Metroid \(USA\)\.nes · 2(\.0+)? KB$/);
|
||||
expect(view.to).toEqual({ name: ROUTES.ROM, params: { rom: "12" } });
|
||||
});
|
||||
|
||||
it("gives how long a game was played", () => {
|
||||
const short = describeAuditEvent(
|
||||
event("rom.play", { data: { duration_ms: 45 * 60 * 1000 } }),
|
||||
);
|
||||
const long = describeAuditEvent(
|
||||
event("rom.play", { data: { duration_ms: 150 * 60 * 1000 } }),
|
||||
);
|
||||
|
||||
expect(short.title).toBe("Played Metroid");
|
||||
expect(short.detail).toBe("45m");
|
||||
expect(long.detail).toBe("2.5h");
|
||||
});
|
||||
|
||||
it("lists what an edit changed and the rename", () => {
|
||||
const view = describeAuditEvent(
|
||||
event("rom.edit", {
|
||||
data: {
|
||||
changed: ["name", "fs_name"],
|
||||
name: { from: "metroid", to: "Metroid" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view.detail).toBe("Changed: name and file name · metroid → Metroid");
|
||||
});
|
||||
|
||||
it("names the providers of a manual match", () => {
|
||||
const view = describeAuditEvent(
|
||||
event("rom.match", { data: { providers: { igdb_id: 1, sgdb_id: 2 } } }),
|
||||
);
|
||||
|
||||
expect(view.title).toBe("Matched Metroid");
|
||||
expect(view.detail).toBe("IGDB and SGDB");
|
||||
});
|
||||
|
||||
it("doesn't link to what was deleted", () => {
|
||||
const view = describeAuditEvent(
|
||||
event("rom.delete", { data: { deleted_from_fs: true } }),
|
||||
);
|
||||
|
||||
expect(view.detail).toBe("Also deleted from disk");
|
||||
expect(view.to).toBeNull();
|
||||
});
|
||||
|
||||
it("counts the games a bulk download took from a platform", () => {
|
||||
const view = describeAuditEvent(
|
||||
event("rom.bulk_download", {
|
||||
target_type: "platform",
|
||||
target_id: "3",
|
||||
target_name: "NES",
|
||||
data: { count: 4 },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view.title).toBe("Downloaded 4 games from NES");
|
||||
expect(view.to).toEqual({
|
||||
name: ROUTES.PLATFORM,
|
||||
params: { platform: "3" },
|
||||
});
|
||||
});
|
||||
|
||||
it("reports how a scan ended", () => {
|
||||
expect(
|
||||
describeAuditEvent(
|
||||
event("scan.finish", { data: { status: "completed", new_roms: 1 } }),
|
||||
).detail,
|
||||
).toBe("1 new game");
|
||||
expect(
|
||||
describeAuditEvent(
|
||||
event("scan.finish", { data: { status: "failed", error: "boom" } }),
|
||||
),
|
||||
).toMatchObject({ title: "A scan failed", detail: "boom" });
|
||||
});
|
||||
|
||||
it("shows a role change in words", () => {
|
||||
const view = describeAuditEvent(
|
||||
event("user.edit", {
|
||||
target_type: "user",
|
||||
target_name: "kid",
|
||||
data: { changed: ["role"], role: { from: "user", to: "admin" } },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view.title).toBe("Edited the user kid");
|
||||
expect(view.detail).toContain("Role:");
|
||||
});
|
||||
|
||||
it("falls back to an id when the target has no name", () => {
|
||||
const view = describeAuditEvent(event("rom.create", { target_name: null }));
|
||||
|
||||
expect(view.title).toBe("Added #12");
|
||||
});
|
||||
|
||||
it("colors a failure apart from its category", () => {
|
||||
expect(
|
||||
describeAuditEvent(event("rom.play", { category: "consumption" })).tone,
|
||||
).toBe("var(--r-color-brand-primary)");
|
||||
expect(
|
||||
describeAuditEvent(
|
||||
event("auth.login_failed", { category: "security", data: {} }),
|
||||
).tone,
|
||||
).toBe("var(--r-color-danger)");
|
||||
});
|
||||
|
||||
it("names a failed sign-in only by an account's own name", () => {
|
||||
expect(
|
||||
describeAuditEvent(
|
||||
event("auth.login_failed", { data: { username: "maria" } }),
|
||||
).title,
|
||||
).toBe("Failed to sign in as maria");
|
||||
expect(
|
||||
describeAuditEvent(
|
||||
event("auth.login_failed", { data: { username: null } }),
|
||||
).title,
|
||||
).toBe("Failed to sign in with an unknown username");
|
||||
});
|
||||
|
||||
it("tells a player's load from a download", () => {
|
||||
expect(describeAuditEvent(event("rom.player_load")).title).toBe(
|
||||
"Loaded Metroid into a player",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows an action it doesn't know as it came", () => {
|
||||
const view = describeAuditEvent(event("rom.teleport"));
|
||||
|
||||
expect(view.title).toBe("rom.teleport Metroid");
|
||||
expect(view.to).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,445 @@
|
||||
// Each audit event reads as a sentence built from its action and `data`, so it
|
||||
// is written in the language of whoever opens the log.
|
||||
import type { RouteLocationRaw } from "vue-router";
|
||||
import type {
|
||||
AuditAction,
|
||||
AuditCategory,
|
||||
AuditEventSchema,
|
||||
} from "@/__generated__";
|
||||
import i18n from "@/locales";
|
||||
import { ROUTES } from "@/plugins/routeNames";
|
||||
import { formatBytes, toBrowserLocale } from "@/utils";
|
||||
import { count, list, text } from "@/v2/utils/eventData";
|
||||
import { joinNames } from "@/v2/utils/lists";
|
||||
import { METADATA_PROVIDERS } from "@/v2/utils/metadataProviders";
|
||||
import { formatPlaytime } from "@/v2/utils/time";
|
||||
|
||||
export interface AuditEventView {
|
||||
icon: string;
|
||||
/** A color token: the category's, or danger for something that failed. */
|
||||
tone: string;
|
||||
title: string;
|
||||
detail: string | null;
|
||||
/** Where the target lives, or null once it's gone. */
|
||||
to: RouteLocationRaw | null;
|
||||
}
|
||||
|
||||
type AuditData = AuditEventSchema["data"];
|
||||
type Describer = (
|
||||
event: AuditEventSchema,
|
||||
target: string,
|
||||
) => Omit<AuditEventView, "to" | "tone">;
|
||||
|
||||
const t = i18n.global.t;
|
||||
|
||||
export const AUDIT_CATEGORIES: readonly AuditCategory[] = [
|
||||
"consumption",
|
||||
"library",
|
||||
"collections",
|
||||
"operations",
|
||||
"security",
|
||||
];
|
||||
|
||||
function kebab(value: string): string {
|
||||
return value.replaceAll("_", "-");
|
||||
}
|
||||
|
||||
function names(values: string[]): string | null {
|
||||
return values.length ? joinNames(values, i18n.global.locale.value) : null;
|
||||
}
|
||||
|
||||
function fields(value: unknown): string | null {
|
||||
const labels = names(list(value).map((f) => t(`audit.field-${kebab(f)}`)));
|
||||
return labels ? t("audit.detail-changed", { fields: labels }) : null;
|
||||
}
|
||||
|
||||
function change(value: unknown): { from: string; to: string } | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const { from, to } = value as Record<string, unknown>;
|
||||
return { from: String(from ?? ""), to: String(to ?? "") };
|
||||
}
|
||||
|
||||
function providers(data: AuditData): string | null {
|
||||
const ids = data.providers;
|
||||
if (!ids || typeof ids !== "object") return null;
|
||||
return names(
|
||||
Object.keys(ids).map(
|
||||
(key) =>
|
||||
METADATA_PROVIDERS.find((p) => p.key === key)?.name ??
|
||||
key.replace(/_id$/, "").toUpperCase(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function size(data: AuditData): string | null {
|
||||
const bytes = count(data.size_bytes);
|
||||
return bytes ? formatBytes(bytes) : null;
|
||||
}
|
||||
|
||||
function joinDetails(...parts: (string | null)[]): string | null {
|
||||
const present = parts.filter((p): p is string => !!p);
|
||||
return present.length ? present.join(" · ") : null;
|
||||
}
|
||||
|
||||
function principal(data: AuditData): string {
|
||||
const from = data.from;
|
||||
if (!from || typeof from !== "object") return "";
|
||||
const { name, id } = from as Record<string, unknown>;
|
||||
return text(name) ?? `#${String(id ?? "")}`;
|
||||
}
|
||||
|
||||
// The sentence names the target; `detail` adds a muted second line.
|
||||
function simple(
|
||||
icon: string,
|
||||
key: string,
|
||||
detail: (event: AuditEventSchema) => string | null = () => null,
|
||||
): Describer {
|
||||
return (event, target) => ({
|
||||
icon,
|
||||
title: t(key, { target }),
|
||||
detail: detail(event),
|
||||
});
|
||||
}
|
||||
|
||||
// A sentence about a number of games, such as roms added to a collection.
|
||||
function counted(icon: string, key: string): Describer {
|
||||
return (event, target) => {
|
||||
const n = count(event.data.count);
|
||||
return { icon, title: t(key, n, { named: { n, target } }), detail: null };
|
||||
};
|
||||
}
|
||||
|
||||
function visibility(icon: string, key: string): Describer {
|
||||
return (event, target) => ({
|
||||
icon,
|
||||
title: t(key, { target, principal: principal(event.data) }),
|
||||
detail: null,
|
||||
});
|
||||
}
|
||||
|
||||
function edited(icon: string, key: string): Describer {
|
||||
return simple(icon, key, (event) => {
|
||||
const renamed = change(event.data.name);
|
||||
return joinDetails(
|
||||
fields(event.data.changed),
|
||||
renamed ? t("audit.detail-renamed", renamed) : null,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const deletedFromDisk = (event: AuditEventSchema) =>
|
||||
event.data.deleted_from_fs ? t("audit.detail-deleted-from-disk") : null;
|
||||
|
||||
const fileAndSize = (event: AuditEventSchema) =>
|
||||
joinDetails(text(event.data.file_name), size(event.data));
|
||||
|
||||
const DESCRIBERS: Record<AuditAction, Describer> = {
|
||||
"rom.download": simple(
|
||||
"mdi-download",
|
||||
"audit.action-rom-download",
|
||||
fileAndSize,
|
||||
),
|
||||
"rom.bulk_download": (event, target) => {
|
||||
const n = count(event.data.count);
|
||||
return {
|
||||
icon: "mdi-download-multiple",
|
||||
title: event.target_type
|
||||
? t("audit.action-rom-bulk-download", n, { named: { n, target } })
|
||||
: t("audit.action-rom-bulk-download-selection", n, { named: { n } }),
|
||||
detail: null,
|
||||
};
|
||||
},
|
||||
"rom.player_load": simple(
|
||||
"mdi-controller",
|
||||
"audit.action-rom-player-load",
|
||||
fileAndSize,
|
||||
),
|
||||
"rom.play": simple("mdi-play-circle-outline", "audit.action-rom-play", (e) =>
|
||||
formatPlaytime(
|
||||
count(e.data.duration_ms) / 1000,
|
||||
toBrowserLocale(i18n.global.locale.value),
|
||||
),
|
||||
),
|
||||
|
||||
"rom.upload": (event, target) => ({
|
||||
icon: "mdi-cloud-upload-outline",
|
||||
title: t("audit.action-rom-upload", {
|
||||
target,
|
||||
file: text(event.data.file_name) ?? "",
|
||||
}),
|
||||
detail: size(event.data),
|
||||
}),
|
||||
"rom.create": simple("mdi-plus-box-outline", "audit.action-rom-create"),
|
||||
"rom.edit": edited("mdi-pencil-outline", "audit.action-rom-edit"),
|
||||
"rom.match": simple("mdi-link-variant", "audit.action-rom-match", (e) =>
|
||||
providers(e.data),
|
||||
),
|
||||
"rom.unmatch": simple(
|
||||
"mdi-link-variant-off",
|
||||
"audit.action-rom-unmatch",
|
||||
(e) => providers(e.data),
|
||||
),
|
||||
"rom.delete": simple(
|
||||
"mdi-trash-can-outline",
|
||||
"audit.action-rom-delete",
|
||||
(e) => joinDetails(text(e.data.platform), deletedFromDisk(e)),
|
||||
),
|
||||
"rom.file_delete": simple(
|
||||
"mdi-file-remove-outline",
|
||||
"audit.action-rom-file-delete",
|
||||
(e) => text(e.data.file_name),
|
||||
),
|
||||
"platform.create": simple(
|
||||
"mdi-gamepad-variant-outline",
|
||||
"audit.action-platform-create",
|
||||
),
|
||||
"platform.edit": edited("mdi-pencil-outline", "audit.action-platform-edit"),
|
||||
"platform.delete": simple(
|
||||
"mdi-trash-can-outline",
|
||||
"audit.action-platform-delete",
|
||||
),
|
||||
"firmware.upload": simple("mdi-chip", "audit.action-firmware-upload", (e) =>
|
||||
names(list(e.data.file_names)),
|
||||
),
|
||||
"firmware.delete": simple(
|
||||
"mdi-trash-can-outline",
|
||||
"audit.action-firmware-delete",
|
||||
deletedFromDisk,
|
||||
),
|
||||
"config.update": (event) => {
|
||||
const setting = text(event.data.setting);
|
||||
const values = [event.data.fs_slug, event.data.slug, event.data.value]
|
||||
.map(text)
|
||||
.filter((v): v is string => !!v);
|
||||
return {
|
||||
icon: "mdi-cog-outline",
|
||||
title: t("audit.action-config-update", {
|
||||
setting: setting ? t(`audit.config-${kebab(setting)}`) : "",
|
||||
}),
|
||||
detail: values.join(" → ") || null,
|
||||
};
|
||||
},
|
||||
|
||||
"collection.create": simple(
|
||||
"mdi-bookmark-plus-outline",
|
||||
"audit.action-collection-create",
|
||||
),
|
||||
"collection.edit": simple(
|
||||
"mdi-bookmark-outline",
|
||||
"audit.action-collection-edit",
|
||||
(e) => {
|
||||
const added = count(e.data.added);
|
||||
const removed = count(e.data.removed);
|
||||
return joinDetails(
|
||||
fields(e.data.changed),
|
||||
added
|
||||
? t("audit.detail-games-added", added, { named: { n: added } })
|
||||
: null,
|
||||
removed
|
||||
? t("audit.detail-games-removed", removed, { named: { n: removed } })
|
||||
: null,
|
||||
);
|
||||
},
|
||||
),
|
||||
"collection.delete": simple(
|
||||
"mdi-bookmark-remove-outline",
|
||||
"audit.action-collection-delete",
|
||||
),
|
||||
"collection.add_roms": counted(
|
||||
"mdi-bookmark-plus-outline",
|
||||
"audit.action-collection-add-roms",
|
||||
),
|
||||
"collection.remove_roms": counted(
|
||||
"mdi-bookmark-minus-outline",
|
||||
"audit.action-collection-remove-roms",
|
||||
),
|
||||
"smart_collection.create": simple(
|
||||
"mdi-bookmark-plus-outline",
|
||||
"audit.action-smart-collection-create",
|
||||
),
|
||||
"smart_collection.edit": simple(
|
||||
"mdi-bookmark-outline",
|
||||
"audit.action-smart-collection-edit",
|
||||
),
|
||||
"smart_collection.delete": simple(
|
||||
"mdi-bookmark-remove-outline",
|
||||
"audit.action-smart-collection-delete",
|
||||
),
|
||||
|
||||
"scan.start": simple("mdi-radar", "audit.action-scan-start"),
|
||||
"scan.finish": (event) => {
|
||||
const status = text(event.data.status);
|
||||
if (status === "failed") {
|
||||
return {
|
||||
icon: "mdi-radar",
|
||||
title: t("audit.action-scan-failed"),
|
||||
detail: text(event.data.error),
|
||||
};
|
||||
}
|
||||
const n = count(event.data.new_roms);
|
||||
return {
|
||||
icon: "mdi-radar",
|
||||
title:
|
||||
status === "stopped"
|
||||
? t("audit.action-scan-stopped")
|
||||
: t("audit.action-scan-finish"),
|
||||
detail: t("audit.detail-new-games", n, { named: { n } }),
|
||||
};
|
||||
},
|
||||
"scan.stop": simple("mdi-stop-circle-outline", "audit.action-scan-stop"),
|
||||
"task.run": simple("mdi-pulse", "audit.action-task-run"),
|
||||
|
||||
"auth.login": simple("mdi-login", "audit.action-auth-login"),
|
||||
"auth.login_failed": (event) => {
|
||||
const reason = text(event.data.reason);
|
||||
const username = text(event.data.username);
|
||||
return {
|
||||
icon: "mdi-account-alert-outline",
|
||||
title: username
|
||||
? t("audit.action-auth-login-failed", { username })
|
||||
: t("audit.action-auth-login-failed-unknown"),
|
||||
detail: reason ? t(`audit.detail-login-${reason}`) : null,
|
||||
};
|
||||
},
|
||||
"auth.password_reset_request": simple(
|
||||
"mdi-lock-question",
|
||||
"audit.action-auth-password-reset-request",
|
||||
),
|
||||
"auth.password_reset": simple(
|
||||
"mdi-lock-reset",
|
||||
"audit.action-auth-password-reset",
|
||||
),
|
||||
"user.create": simple("mdi-account-plus-outline", "audit.action-user-create"),
|
||||
"user.register": simple(
|
||||
"mdi-account-plus-outline",
|
||||
"audit.action-user-register",
|
||||
),
|
||||
"user.edit": simple(
|
||||
"mdi-account-edit-outline",
|
||||
"audit.action-user-edit",
|
||||
(e) => {
|
||||
const role = change(e.data.role);
|
||||
return joinDetails(
|
||||
fields(e.data.changed),
|
||||
role
|
||||
? t("audit.detail-role", {
|
||||
from: t(`settings.role-${role.from}`),
|
||||
to: t(`settings.role-${role.to}`),
|
||||
})
|
||||
: null,
|
||||
);
|
||||
},
|
||||
),
|
||||
"user.delete": simple(
|
||||
"mdi-account-remove-outline",
|
||||
"audit.action-user-delete",
|
||||
),
|
||||
"user.permissions_edit": simple(
|
||||
"mdi-shield-account-outline",
|
||||
"audit.action-user-permissions-edit",
|
||||
(e) => text(e.data.group),
|
||||
),
|
||||
"permission_group.create": simple(
|
||||
"mdi-shield-plus-outline",
|
||||
"audit.action-permission-group-create",
|
||||
),
|
||||
"permission_group.edit": simple(
|
||||
"mdi-shield-edit-outline",
|
||||
"audit.action-permission-group-edit",
|
||||
),
|
||||
"permission_group.delete": simple(
|
||||
"mdi-shield-remove-outline",
|
||||
"audit.action-permission-group-delete",
|
||||
),
|
||||
"visibility.hide": visibility(
|
||||
"mdi-eye-off-outline",
|
||||
"audit.action-visibility-hide",
|
||||
),
|
||||
"visibility.unhide": visibility(
|
||||
"mdi-eye-outline",
|
||||
"audit.action-visibility-unhide",
|
||||
),
|
||||
"client_token.create": simple(
|
||||
"mdi-key-plus",
|
||||
"audit.action-client-token-create",
|
||||
),
|
||||
"client_token.regenerate": simple(
|
||||
"mdi-key-change",
|
||||
"audit.action-client-token-regenerate",
|
||||
),
|
||||
"client_token.revoke": simple(
|
||||
"mdi-key-remove",
|
||||
"audit.action-client-token-revoke",
|
||||
),
|
||||
"device.approve": simple(
|
||||
"mdi-cellphone-link",
|
||||
"audit.action-device-approve",
|
||||
(e) => text(e.data.client),
|
||||
),
|
||||
};
|
||||
|
||||
const CATEGORY_TONES: Record<AuditCategory, string> = {
|
||||
consumption: "var(--r-color-brand-primary)",
|
||||
library: "var(--r-color-info)",
|
||||
collections: "var(--r-color-brand-accent)",
|
||||
operations: "var(--r-color-brand-secondary)",
|
||||
security: "var(--r-color-warning)",
|
||||
};
|
||||
|
||||
function toneOf(event: AuditEventSchema): string {
|
||||
if (event.action === "auth.login_failed" || event.data.status === "failed") {
|
||||
return "var(--r-color-danger)";
|
||||
}
|
||||
return CATEGORY_TONES[event.category ?? "operations"];
|
||||
}
|
||||
|
||||
function targetRoute(event: AuditEventSchema): RouteLocationRaw | null {
|
||||
const id = event.target_id;
|
||||
// What was deleted has nowhere left to link to.
|
||||
if (!id || event.action.endsWith(".delete")) return null;
|
||||
switch (event.target_type) {
|
||||
case "rom":
|
||||
return { name: ROUTES.ROM, params: { rom: id } };
|
||||
case "platform":
|
||||
return { name: ROUTES.PLATFORM, params: { platform: id } };
|
||||
case "collection":
|
||||
return { name: ROUTES.COLLECTION, params: { collection: id } };
|
||||
case "smart_collection":
|
||||
return { name: ROUTES.SMART_COLLECTION, params: { collection: id } };
|
||||
case "virtual_collection":
|
||||
return { name: ROUTES.VIRTUAL_COLLECTION, params: { collection: id } };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function fallback(event: AuditEventSchema, target: string): AuditEventView {
|
||||
return {
|
||||
icon: "mdi-help-circle-outline",
|
||||
tone: CATEGORY_TONES.operations,
|
||||
title: [event.action, target].filter(Boolean).join(" "),
|
||||
detail: null,
|
||||
to: null,
|
||||
};
|
||||
}
|
||||
|
||||
function isKnownAction(action: string): action is AuditAction {
|
||||
return Object.hasOwn(DESCRIBERS, action);
|
||||
}
|
||||
|
||||
export function describeAuditEvent(event: AuditEventSchema): AuditEventView {
|
||||
const target =
|
||||
event.target_name ?? (event.target_id ? `#${event.target_id}` : "");
|
||||
if (!isKnownAction(event.action)) return fallback(event, target);
|
||||
try {
|
||||
return {
|
||||
...DESCRIBERS[event.action](event, target),
|
||||
tone: toneOf(event),
|
||||
to: targetRoute(event),
|
||||
};
|
||||
} catch (error) {
|
||||
// `data` is free-form JSON, so one odd row must not blank the whole log.
|
||||
console.error(`Could not describe audit event ${event.id}:`, error);
|
||||
return fallback(event, target);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Readers for the free-form `data` JSON of notifications and audit events, so a
|
||||
// value of the wrong type renders as absent instead of breaking the row.
|
||||
|
||||
export function text(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value : null;
|
||||
}
|
||||
|
||||
export function count(value: unknown): number {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
export function list(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((v): v is string => typeof v === "string")
|
||||
: [];
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type { NotificationKind, NotificationSchema } from "@/__generated__";
|
||||
import i18n from "@/locales";
|
||||
import { ROUTES } from "@/plugins/routeNames";
|
||||
import { TONE_ICONS } from "@/v2/composables/useSnackbar";
|
||||
import { count, text } from "@/v2/utils/eventData";
|
||||
|
||||
interface NotificationView {
|
||||
icon: string;
|
||||
@@ -19,14 +20,6 @@ type NotificationData = NotificationSchema["data"];
|
||||
|
||||
const t = i18n.global.t;
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value : null;
|
||||
}
|
||||
|
||||
function count(value: unknown): number {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
// Mirror the columns in backend/models/notification.py.
|
||||
export const NOTIFICATION_TITLE_MAX_LENGTH = 255;
|
||||
export const NOTIFICATION_BODY_MAX_LENGTH = 1000;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { wrappedLineCount } from "@/v2/utils/textLines";
|
||||
|
||||
// Every character is 10px wide.
|
||||
const measure = (run: string) => run.length * 10;
|
||||
|
||||
describe("wrappedLineCount", () => {
|
||||
it("keeps text that fits on one line", () => {
|
||||
expect(wrappedLineCount("Signed in", 100, measure)).toBe(1);
|
||||
});
|
||||
|
||||
it("moves the word that doesn't fit to the next line", () => {
|
||||
expect(wrappedLineCount("Played Metroid today", 140, measure)).toBe(2);
|
||||
expect(wrappedLineCount("aaaa bbbb cccc dddd", 90, measure)).toBe(2);
|
||||
expect(wrappedLineCount("aaaa bbbb cccc dddd", 80, measure)).toBe(4);
|
||||
});
|
||||
|
||||
it("breaks a word longer than a line wherever it must", () => {
|
||||
expect(
|
||||
wrappedLineCount("不明なユーザ名でのログインに失敗しました", 50, measure),
|
||||
).toBe(4);
|
||||
expect(wrappedLineCount("go aaaaaaaaaaaa", 50, measure)).toBe(4);
|
||||
});
|
||||
|
||||
it("stops counting at the most lines shown", () => {
|
||||
expect(wrappedLineCount("aaaa bbbb cccc dddd", 80, measure, 2)).toBe(2);
|
||||
expect(wrappedLineCount("go aaaaaaaaaaaa", 50, measure, 3)).toBe(3);
|
||||
});
|
||||
|
||||
it("counts one line for no text or no room", () => {
|
||||
expect(wrappedLineCount("", 100, measure)).toBe(1);
|
||||
expect(wrappedLineCount("Signed in", 0, measure)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* How many lines `text` wraps to in `width` pixels, breaking between words the
|
||||
* way the browser does, and inside a word only when it can't fit a line alone.
|
||||
*
|
||||
* Args:
|
||||
* measure: The width of a run of text in the font it's set in.
|
||||
* maxLines: Stops counting here, as a line clamp stops showing.
|
||||
*/
|
||||
export function wrappedLineCount(
|
||||
text: string,
|
||||
width: number,
|
||||
measure: (run: string) => number,
|
||||
maxLines = Infinity,
|
||||
): number {
|
||||
if (width <= 0) return 1;
|
||||
const space = measure(" ");
|
||||
let lines = 1;
|
||||
let line = 0;
|
||||
for (const word of text.split(/\s+/).filter(Boolean)) {
|
||||
const w = measure(word);
|
||||
const next = line === 0 ? w : line + space + w;
|
||||
if (next <= width) {
|
||||
line = next;
|
||||
continue;
|
||||
}
|
||||
if (line > 0) lines += 1;
|
||||
const extra = Math.max(0, Math.ceil(w / width) - 1);
|
||||
lines += extra;
|
||||
if (lines >= maxLines) return maxLines;
|
||||
line = w - extra * width;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
let context: CanvasRenderingContext2D | null | undefined;
|
||||
|
||||
/** Measures text in a CSS `font`, each run only once, or null without a canvas. */
|
||||
export function canvasMeasure(font: string): ((run: string) => number) | null {
|
||||
context ??= document.createElement("canvas").getContext("2d");
|
||||
const shared = context;
|
||||
if (!shared) return null;
|
||||
const widths = new Map<string, number>();
|
||||
return (run) => {
|
||||
let width = widths.get(run);
|
||||
if (width === undefined) {
|
||||
shared.font = font;
|
||||
width = shared.measureText(run).width;
|
||||
widths.set(run, width);
|
||||
}
|
||||
return width;
|
||||
};
|
||||
}
|
||||
@@ -94,7 +94,7 @@ async function onPlay() {
|
||||
// DOSBox-X provides Windows support.
|
||||
runtimeBound = true;
|
||||
dos = dosFactory(stage.value, {
|
||||
url: getDownloadPath({ rom: currentRom }),
|
||||
url: getDownloadPath({ rom: currentRom, purpose: "play" }),
|
||||
backend: "dosboxX",
|
||||
backendLocked: true,
|
||||
pathPrefix: `${assetBase}/emulators/`,
|
||||
|
||||
@@ -198,7 +198,9 @@ function showPlayError(error: unknown) {
|
||||
}
|
||||
|
||||
async function fetchCartBytes(target: DetailedRom) {
|
||||
const response = await fetch(getDownloadPath({ rom: target }));
|
||||
const response = await fetch(
|
||||
getDownloadPath({ rom: target, purpose: "play" }),
|
||||
);
|
||||
if (!response.ok) throw new Error(`ROM request failed: ${response.status}`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user