Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(api): add the operators' wall service, store and feed route

Hampus88d7bcf66498
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassInternalController.ts b/fluxer_api/src/api/operator_pass/OperatorPassInternalController.ts
new file mode 100644
index 000000000..f5b272325
--- /dev/null
+++ b/fluxer_api/src/api/operator_pass/OperatorPassInternalController.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Config} from '@app/api/Config';
+import {getOperatorPassWallService} from '@app/api/middleware/ServiceSingletons';
+import type {HonoApp} from '@app/api/types/HonoEnv';
+import {constantTimeEquals} from '@app/api/utils/SecretHash';
+import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
+
+const OPERATOR_PASS_WALL_SNAPSHOT_BUCKET = 'operator_pass:wall_snapshot';
+const INTERNAL_KEY_HEADER = 'x-fluxer-internal-key';
+
+function isOperatorPassWallSnapshotCaller(providedKey: string): boolean {
+ if (providedKey.length === 0) return false;
+ let trusted = false;
+ for (const caller of Config.internal.trustedCallers) {
+ if (!caller.buckets.includes(OPERATOR_PASS_WALL_SNAPSHOT_BUCKET)) continue;
+ if (constantTimeEquals(caller.key, providedKey)) trusted = true;
+ }
+ return trusted;
+}
+
+export function OperatorPassInternalController(app: HonoApp): void {
+ app.get('/internal/operator-pass/wall', async (ctx) => {
+ if (Config.instance.selfHosted || !isOperatorPassWallSnapshotCaller(ctx.req.header(INTERNAL_KEY_HEADER) ?? '')) {
+ throw new UnauthorizedError();
+ }
+ const snapshot = await getOperatorPassWallService().publication.snapshot();
+ ctx.header('Cache-Control', 'no-store');
+ return ctx.json(snapshot);
+ });
+}
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallEntryStore.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallEntryStore.ts
new file mode 100644
index 000000000..6cbeacb70
--- /dev/null
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallEntryStore.ts
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {randomUUID} from 'node:crypto';
+import type {UserID} from '@app/api/BrandedTypes';
+import {Db, type DbOp} from '@app/api/database/CassandraTypes';
+import type {
+ OperatorPassWallDecisionKind,
+ OperatorPassWallDecisionRow,
+ OperatorPassWallDeclineReason,
+ OperatorPassWallEntryRow,
+ OperatorPassWallEventKind,
+ OperatorPassWallRevisionRow,
+ OperatorPassWallTakeDownCause,
+} from '@app/api/database/types/OperatorPassTypes';
+import {getOperatorPassWallInfrastructure} from '@app/api/middleware/ServiceSingletons';
+import type {OperatorPassRepository, OperatorPassWallEntryPatch} from '@app/api/operator_pass/OperatorPassRepository';
+import {OPERATOR_PASS_WALL_UPDATE_ATTEMPTS} from '@app/api/operator_pass/OperatorPassWallConstants';
+import {UnknownOperatorPassWallEntryError} from '@fluxer/errors/src/domains/operator_pass/UnknownOperatorPassWallEntryError';
+
+const SCAN_PAGE_SIZE = 500;
+
+export interface WallEventDraft {
+ kind: OperatorPassWallEventKind;
+ name?: string | null;
+ reason?: string | null;
+ cause?: OperatorPassWallTakeDownCause | null;
+ purchaseId?: string | null;
+ releaseYear?: number | null;
+ releaseTag?: string | null;
+ passCount?: number | null;
+}
+
+interface WallMutation {
+ patch: OperatorPassWallEntryPatch;
+ events: Array<WallEventDraft>;
+}
+
+export function liveRevisionPatch(revision: OperatorPassWallRevisionRow | null): OperatorPassWallEntryPatch {
+ return {
+ live_revision_id: Db.set(revision?.revision_id ?? null),
+ live_name: Db.set(revision?.name ?? null),
+ live_avatar: Db.set(revision?.avatar ?? null),
+ live_business: Db.set(revision?.business ?? false),
+ };
+}
+
+function emptyEntry(userId: UserID, now: Date): OperatorPassWallEntryRow {
+ return {
+ user_id: userId,
+ name: null,
+ opted_out: true,
+ keep_as_is: false,
+ release_list_opt_in: false,
+ hidden: false,
+ legal_hold: false,
+ left_wall_at: null,
+ username_declined: false,
+ live_revision_id: null,
+ live_name: null,
+ live_avatar: null,
+ live_business: null,
+ pending_revision_id: null,
+ pending_name: null,
+ pending_avatar: null,
+ pending_source: null,
+ pending_since: null,
+ declined_revision_id: null,
+ declined_name: null,
+ declined_avatar: null,
+ decline_reason: null,
+ decline_note: null,
+ decline_statement_id: null,
+ reviewed_at: null,
+ reviewed_by: null,
+ listed_at: null,
+ delivered_at: null,
+ release_published_year: null,
+ release_published_at: null,
+ release_erased_at: null,
+ updated_at: now,
+ version: 0,
+ };
+}
+
+function applyWallPatch<K extends keyof OperatorPassWallEntryPatch>(
+ row: OperatorPassWallEntryRow,
+ patch: Partial<{[P in K]: DbOp<OperatorPassWallEntryRow[P]>}>,
+): OperatorPassWallEntryRow {
+ const next = {...row};
+ for (const key in patch) {
+ if (!Object.hasOwn(patch, key)) {
+ continue;
+ }
+ const op = patch[key];
+ if (op && typeof op === 'object' && 'value' in op) {
+ next[key] = op.value;
+ }
+ }
+ return next;
+}
+
+export class OperatorPassWallEntryStore {
+ constructor(
+ private readonly repository: OperatorPassRepository,
+ private readonly invalidate: () => void,
+ ) {}
+
+ async appendDecision(
+ userId: UserID,
+ params: {
+ kind: OperatorPassWallDecisionKind;
+ revisionId: bigint | null;
+ decidedBy: UserID | null;
+ decidedAt: Date;
+ reason?: OperatorPassWallDeclineReason | null;
+ note?: string | null;
+ statementId?: string | null;
+ usernameDeclined?: boolean;
+ },
+ ): Promise<OperatorPassWallDecisionRow> {
+ const decision: OperatorPassWallDecisionRow = {
+ user_id: userId,
+ decision_id: await getOperatorPassWallInfrastructure().nextId(),
+ revision_id: params.revisionId,
+ kind: params.kind,
+ decided_by: params.decidedBy,
+ decided_at: params.decidedAt,
+ reason: params.reason ?? null,
+ note: params.note ?? null,
+ statement_id: params.statementId ?? null,
+ username_declined: params.usernameDeclined ?? null,
+ };
+ await this.repository.appendWallDecision(decision);
+ return decision;
+ }
+
+ async mutateExisting(
+ userId: UserID,
+ now: Date,
+ actorId: UserID | null,
+ decide: (current: OperatorPassWallEntryRow) => WallMutation | null,
+ ): Promise<OperatorPassWallEntryRow> {
+ return this.mutate(userId, now, actorId, decide, 'reject');
+ }
+
+ async mutate(
+ userId: UserID,
+ now: Date,
+ actorId: UserID | null,
+ decide: (current: OperatorPassWallEntryRow) => WallMutation | null,
+ missingEntry: 'create' | 'reject' = 'create',
+ ): Promise<OperatorPassWallEntryRow> {
+ for (let attempt = 0; attempt < OPERATOR_PASS_WALL_UPDATE_ATTEMPTS; attempt++) {
+ const existing = await this.repository.findWallEntry(userId);
+ if (!existing && missingEntry === 'reject') {
+ throw new UnknownOperatorPassWallEntryError();
+ }
+ const current = existing ?? emptyEntry(userId, now);
+ const mutation = decide(current);
+ if (!mutation) {
+ return current;
+ }
+ let next: OperatorPassWallEntryRow | null;
+ if (existing) {
+ next = await this.repository.updateWallEntry(existing, mutation.patch);
+ } else {
+ const created = {...applyWallPatch(current, mutation.patch), version: 1};
+ next = (await this.repository.createWallEntry(created)) ? created : null;
+ }
+ if (!next) {
+ continue;
+ }
+ this.invalidate();
+ if ((existing?.pending_revision_id != null) !== (next.pending_revision_id != null)) {
+ await this.repository.setWallPending(userId, next.pending_revision_id != null);
+ }
+ for (const event of mutation.events) {
+ await this.appendEvent(userId, now, event, actorId);
+ }
+ return next;
+ }
+ throw new Error("Operators' wall entry changed too often to update");
+ }
+
+ async appendEvent(userId: UserID, now: Date, event: WallEventDraft, actorId: UserID | null): Promise<void> {
+ this.invalidate();
+ await this.repository.appendWallEvent({
+ user_id: userId,
+ occurred_at: now,
+ event_id: `${process.hrtime.bigint().toString().padStart(24, '0')}-${randomUUID()}`,
+ kind: event.kind,
+ name: event.name ?? null,
+ reason: event.reason ?? null,
+ cause: event.cause ?? null,
+ purchase_id: event.purchaseId ?? null,
+ release_year: event.releaseYear ?? null,
+ release_tag: event.releaseTag ?? null,
+ actor_id: actorId,
+ pass_count: event.passCount ?? null,
+ });
+ }
+
+ async scanAll(): Promise<Array<OperatorPassWallEntryRow>> {
+ const rows: Array<OperatorPassWallEntryRow> = [];
+ let pageState: string | null = null;
+ do {
+ const page = await this.repository.scanWallEntries(SCAN_PAGE_SIZE, pageState);
+ rows.push(...page.rows);
+ pageState = page.pageState;
+ } while (pageState);
+ return rows;
+ }
+}
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallPublisher.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallPublisher.ts
new file mode 100644
index 000000000..753660960
--- /dev/null
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallPublisher.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createHmac} from 'node:crypto';
+import type {UserID} from '@app/api/BrandedTypes';
+import {Logger} from '@app/api/Logger';
+import {deriveOperatorPassSecret} from '@app/api/operator_pass/OperatorPassSecrets';
+import type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';
+
+const OPERATOR_PASS_WALL_NATS_SUBJECT = 'operator_pass.wall.delta';
+const OPERATOR_PASS_WALL_PUBLIC_ID_LABEL = 'fluxer-operator-pass-wall-public-id-v1';
+
+export interface OperatorPassWallBlobEntry {
+ id: string;
+ name: string;
+ avatar: string | null;
+ tier: number;
+ count?: number;
+ business?: true;
+}
+
+export interface OperatorPassWallDelta {
+ type: 'operator_pass_wall_delta';
+ version: number;
+ previous_version: number;
+ published_at: string;
+ resync: boolean;
+ upserts: Array<OperatorPassWallBlobEntry>;
+ removals: Array<string>;
+}
+
+export interface IOperatorPassWallPublisher {
+ publish(delta: OperatorPassWallDelta): Promise<void>;
+}
+
+export function operatorPassWallPublicId(userId: UserID): string {
+ return createHmac('sha256', deriveOperatorPassSecret(OPERATOR_PASS_WALL_PUBLIC_ID_LABEL))
+ .update(userId.toString())
+ .digest('hex')
+ .slice(0, 16);
+}
+
+const textEncoder = new TextEncoder();
+
+export class NatsOperatorPassWallPublisher implements IOperatorPassWallPublisher {
+ constructor(private readonly connectionManager: INatsConnectionManager) {}
+
+ async publish(delta: OperatorPassWallDelta): Promise<void> {
+ try {
+ if (this.connectionManager.isClosed()) await this.connectionManager.connect();
+ const connection = this.connectionManager.getConnection();
+ connection.publish(OPERATOR_PASS_WALL_NATS_SUBJECT, textEncoder.encode(JSON.stringify(delta)));
+ await connection.flush();
+ } catch (error) {
+ Logger.warn({error, version: delta.version}, "Failed to publish an Operators' wall delta");
+ }
+ }
+}
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts
new file mode 100644
index 000000000..872bafe10
--- /dev/null
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts
@@ -0,0 +1,389 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {AdminRepository} from '@app/api/admin/AdminRepository';
+import type {UserID} from '@app/api/BrandedTypes';
+import {Db} from '@app/api/database/CassandraTypes';
+import type {
+ OperatorPassWallEntryRow,
+ OperatorPassWallRevisionRow,
+ OperatorPassWallRevisionSource,
+ OperatorPassWallTakeDownCause,
+} from '@app/api/database/types/OperatorPassTypes';
+import {getOperatorPassWallInfrastructure} from '@app/api/middleware/ServiceSingletons';
+import type {User} from '@app/api/models/User';
+import {validateOperatorPassBusinessLogo} from '@app/api/operator_pass/OperatorPassBusinessListing';
+import {OperatorPassReleaseService} from '@app/api/operator_pass/OperatorPassReleaseService';
+import type {OperatorPassRepository, OperatorPassWallEntryPatch} from '@app/api/operator_pass/OperatorPassRepository';
+import {operatorPassNow} from '@app/api/operator_pass/OperatorPassSchedule';
+import {
+ liveRevisionPatch,
+ OperatorPassWallEntryStore,
+ type WallEventDraft,
+} from '@app/api/operator_pass/OperatorPassWallEntryStore';
+import {OperatorPassWallHistoryService} from '@app/api/operator_pass/OperatorPassWallHistoryService';
+import {
+ type OperatorPassWallDecisionResult,
+ OperatorPassWallModerationService,
+} from '@app/api/operator_pass/OperatorPassWallModerationService';
+import {
+ hasOperatorPassWallChoice,
+ isOperatorPassWallListed,
+ type OperatorPassWallChoice,
+} from '@app/api/operator_pass/OperatorPassWallPresentation';
+import {
+ invalidateOperatorPassPublicWall,
+ OperatorPassWallPublicationService,
+} from '@app/api/operator_pass/OperatorPassWallPublicationService';
+import {OperatorPassWallRetentionService} from '@app/api/operator_pass/OperatorPassWallRetentionService';
+import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+
+export class OperatorPassWallService {
+ private readonly entries: OperatorPassWallEntryStore;
+ readonly releases: OperatorPassReleaseService;
+ readonly publication: OperatorPassWallPublicationService;
+ readonly retention: OperatorPassWallRetentionService;
+ readonly history: OperatorPassWallHistoryService;
+ readonly moderation: OperatorPassWallModerationService;
+
+ constructor(
+ private readonly repository: OperatorPassRepository,
+ private readonly userRepository: UserRepository,
+ ) {
+ this.entries = new OperatorPassWallEntryStore(repository, invalidateOperatorPassPublicWall);
+ this.releases = new OperatorPassReleaseService(repository, userRepository, this.entries);
+ this.publication = new OperatorPassWallPublicationService(repository, userRepository, this.entries);
+ this.retention = new OperatorPassWallRetentionService(repository, this.entries, this.publication, this.auditLogs);
+ this.history = new OperatorPassWallHistoryService(repository, userRepository, this.entries);
+ this.moderation = new OperatorPassWallModerationService(repository, userRepository, this.entries, this.publication);
+ }
+
+ private readonly auditLogs = new AdminRepository();
+
+ async getEntry(userId: UserID): Promise<OperatorPassWallEntryRow | null> {
+ return this.repository.findWallEntry(userId);
+ }
+
+ async hasChoice(userId: UserID): Promise<boolean> {
+ return hasOperatorPassWallChoice(await this.repository.findWallEntry(userId));
+ }
+
+ async deliver(params: {
+ userId: UserID;
+ purchaseId: string | null;
+ choice: OperatorPassWallChoice | null;
+ deliveredAt: Date;
+ }): Promise<void> {
+ let before: OperatorPassWallEntryRow | null = null;
+ const entry = await this.entries.mutate(params.userId, params.deliveredAt, params.userId, (current) => {
+ before = current;
+ const events: Array<WallEventDraft> = [{kind: 'delivered', purchaseId: params.purchaseId}];
+ const patch: OperatorPassWallEntryPatch = {
+ delivered_at: Db.set(current.delivered_at ?? params.deliveredAt),
+ updated_at: Db.set(params.deliveredAt),
+ };
+ if (!params.choice) {
+ if (!current.opted_out && current.listed_at == null) {
+ patch.listed_at = Db.set(params.deliveredAt);
+ patch.left_wall_at = Db.set(null);
+ events.push({kind: 'listed', name: current.name});
+ }
+ return {patch, events};
+ }
+ if (params.choice.optedOut) {
+ patch.opted_out = Db.set(true);
+ patch.listed_at = Db.set(null);
+ patch.left_wall_at = Db.set(current.left_wall_at ?? params.deliveredAt);
+ events.push({kind: 'opted_out'});
+ if (isOperatorPassWallListed(current)) {
+ events.push({kind: 'taken_down', name: current.live_name, cause: 'holder_request'});
+ }
+ } else {
+ patch.opted_out = Db.set(false);
+ patch.listed_at = Db.set(current.listed_at ?? params.deliveredAt);
+ patch.left_wall_at = Db.set(null);
+ events.push({kind: 'listed', name: params.choice.name});
+ }
+ return {patch, events};
+ });
+ if (params.choice && !params.choice.optedOut && params.choice.name) {
+ await this.submitRevision(params.userId, params.choice.name, 'checkout', params.userId, {useProfileAvatar: true});
+ }
+ await this.publication.publishChanges([params.userId]);
+ await this.syncListedAvatar(before, entry);
+ }
+
+ async setChoice(
+ userId: UserID,
+ choice: OperatorPassWallChoice,
+ actorId: UserID = userId,
+ {keepAsIs, releaseListOptIn}: {keepAsIs?: boolean; releaseListOptIn?: boolean} = {},
+ ): Promise<void> {
+ const now = operatorPassNow();
+ let before: OperatorPassWallEntryRow | null = null;
+ const entry = await this.entries.mutate(userId, now, actorId, (current) => {
+ before = current;
+ const patch: OperatorPassWallEntryPatch = {updated_at: Db.set(now)};
+ const events: Array<WallEventDraft> = [];
+ if (keepAsIs !== undefined && keepAsIs !== current.keep_as_is) {
+ patch.keep_as_is = Db.set(keepAsIs);
+ }
+ if (releaseListOptIn !== undefined && releaseListOptIn !== (current.release_list_opt_in ?? false)) {
+ patch.release_list_opt_in = Db.set(releaseListOptIn);
+ }
+ if (choice.optedOut) {
+ if (!current.opted_out) {
+ patch.opted_out = Db.set(true);
+ patch.listed_at = Db.set(null);
+ patch.left_wall_at = Db.set(now);
+ events.push({kind: 'opted_out'});
+ if (isOperatorPassWallListed(current)) {
+ events.push({kind: 'taken_down', name: current.live_name, cause: 'holder_request'});
+ }
+ }
+ } else if (!isOperatorPassWallListed(current)) {
+ patch.opted_out = Db.set(false);
+ patch.listed_at = Db.set(now);
+ patch.left_wall_at = Db.set(null);
+ events.push({kind: 'listed', name: choice.name});
+ }
+ return Object.keys(patch).length > 1 || events.length > 0 ? {patch, events} : null;
+ });
+ if (!choice.optedOut && choice.name) {
+ const latest = entry.pending_name ?? entry.live_name;
+ if (latest !== choice.name) {
+ await this.submitRevision(userId, choice.name, 'settings', actorId, {useProfileAvatar: true});
+ }
+ }
+ await this.publication.publishChanges([userId]);
+ await this.syncListedAvatar(before, entry);
+ }
+
+ private async syncListedAvatar(
+ before: OperatorPassWallEntryRow | null,
+ after: OperatorPassWallEntryRow,
+ ): Promise<void> {
+ const wasListed = before != null && isOperatorPassWallListed(before);
+ const isListed = isOperatorPassWallListed(after);
+ if (wasListed && !isListed && before.live_avatar) {
+ await this.publication.releaseAvatar(before.live_avatar);
+ } else if (!wasListed && isListed) {
+ await this.publication.publishAvatarIfServed(after);
+ }
+ }
+
+ async onProfileChanged(
+ user: User,
+ previous: {username: string; globalName: string | null; avatarHash: string | null},
+ ): Promise<void> {
+ const entry = await this.repository.findWallEntry(user.id);
+ if (!entry || !isOperatorPassWallListed(entry)) {
+ return;
+ }
+ const avatarChanged = (previous.avatarHash ?? null) !== (user.avatarHash ?? null);
+ const previousDisplay = previous.globalName ?? previous.username;
+ const currentDisplay = user.globalName ?? user.username;
+ const latestName = entry.pending_name ?? entry.live_name ?? entry.name ?? currentDisplay;
+ const followsName = latestName === previousDisplay && previousDisplay !== currentDisplay;
+ if (entry.live_revision_id == null && previous.username !== user.username) {
+ await this.publication.publishChanges([user.id], 'preserve');
+ }
+ if (entry.keep_as_is || entry.live_business || (!avatarChanged && !followsName)) {
+ return;
+ }
+ await this.submitRevision(user.id, followsName ? currentDisplay : latestName, 'profile', user.id, {
+ useProfileAvatar: true,
+ user,
+ });
+ }
+
+ async submitRevision(
+ userId: UserID,
+ name: string,
+ source: OperatorPassWallRevisionSource,
+ actorId: UserID | null,
+ options: {useProfileAvatar?: boolean; avatar?: string | null; user?: User; business?: boolean} = {},
+ ): Promise<OperatorPassWallRevisionRow> {
+ const now = operatorPassNow();
+ let avatar = options.avatar ?? null;
+ if (options.useProfileAvatar) {
+ const user = options.user ?? (await this.userRepository.findUnique(userId));
+ avatar = user ? await getOperatorPassWallInfrastructure().avatarStore.snapshotUserAvatar(user) : null;
+ }
+ const revision: OperatorPassWallRevisionRow = {
+ user_id: userId,
+ revision_id: await getOperatorPassWallInfrastructure().nextId(),
+ name,
+ avatar,
+ business: options.business ?? false,
+ source,
+ created_at: now,
+ created_by: actorId,
+ };
+ await this.repository.appendWallRevision(revision);
+ if (avatar) {
+ await this.repository.addWallAvatarRef(avatar, userId);
+ }
+ await this.entries.mutate(userId, now, actorId, () => ({
+ patch: {
+ name: Db.set(name),
+ pending_revision_id: Db.set(revision.revision_id),
+ pending_name: Db.set(name),
+ pending_avatar: Db.set(avatar),
+ pending_source: Db.set(source),
+ pending_since: Db.set(now),
+ updated_at: Db.set(now),
+ },
+ events: source === 'checkout' ? [] : [{kind: 'changed', name}],
+ }));
+ return revision;
+ }
+
+ async setBusinessListing(
+ userId: UserID,
+ adminId: UserID,
+ input: {name: string; logo: Uint8Array},
+ ): Promise<OperatorPassWallDecisionResult> {
+ await validateOperatorPassBusinessLogo(input.logo);
+ const avatar = await getOperatorPassWallInfrastructure().avatarStore.storePrivate(input.logo);
+ await this.submitRevision(userId, input.name, 'admin', adminId, {avatar, business: true});
+ await this.setChoice(userId, {name: input.name, optedOut: false}, adminId);
+ return this.moderation.approve(userId, adminId);
+ }
+
+ async endBusinessListing(userId: UserID): Promise<void> {
+ const entry = await this.repository.findWallEntry(userId);
+ if (!entry?.live_business) {
+ return;
+ }
+ const personal = await this.moderation.lastPersonalRevision(userId);
+ const now = operatorPassNow();
+ let ended = false;
+ const next = await this.entries.mutate(userId, now, null, (current) => {
+ if (!current.live_business || current.live_revision_id !== entry.live_revision_id) {
+ return null;
+ }
+ ended = true;
+ return {
+ patch: {...liveRevisionPatch(personal), updated_at: Db.set(now)},
+ events: [{kind: 'fallback', name: personal?.name ?? null}],
+ };
+ });
+ if (!ended) {
+ return;
+ }
+ await this.moderation.recordBusinessEnded(userId, entry.live_revision_id ?? null, personal, null, now);
+ await this.publication.publishAvatarIfServed(next);
+ await this.publication.publishChanges([userId], 'preserve');
+ if (entry.live_avatar && entry.live_avatar !== personal?.avatar) {
+ await this.publication.releaseAvatar(entry.live_avatar);
+ }
+ }
+
+ async takeDown(userId: UserID, cause: OperatorPassWallTakeDownCause, purchaseId: string | null): Promise<void> {
+ const now = operatorPassNow();
+ const existing = await this.repository.findWallEntry(userId);
+ const personal = existing?.live_business ? await this.moderation.lastPersonalRevision(userId) : null;
+ let endedBusiness: {revisionId: bigint | null; avatar: string | null} | null = null;
+ const entry = await this.entries.mutate(
+ userId,
+ now,
+ null,
+ (current) => {
+ if (current.delivered_at == null && current.listed_at == null) {
+ return null;
+ }
+ const events: Array<WallEventDraft> = isOperatorPassWallListed(current)
+ ? [{kind: 'taken_down', name: current.live_name, cause, purchaseId}]
+ : [];
+ const business = current.live_business === true && current.live_revision_id === existing?.live_revision_id;
+ endedBusiness = business
+ ? {revisionId: current.live_revision_id ?? null, avatar: current.live_avatar ?? null}
+ : null;
+ return {
+ patch: {
+ ...(business ? liveRevisionPatch(personal) : {}),
+ listed_at: Db.set(null),
+ delivered_at: Db.set(null),
+ left_wall_at: Db.set(current.left_wall_at ?? now),
+ updated_at: Db.set(now),
+ },
+ events,
+ };
+ },
+ 'create',
+ );
+ const business = endedBusiness as {revisionId: bigint | null; avatar: string | null} | null;
+ if (business) {
+ await this.moderation.recordBusinessEnded(userId, business.revisionId, personal, null, now);
+ }
+ await this.publication.publishChanges([userId]);
+ for (const avatar of new Set([entry.live_avatar, business?.avatar])) {
+ if (avatar) {
+ await this.publication.releaseAvatar(avatar);
+ }
+ }
+ }
+
+ async forgetForDeletion(userId: UserID): Promise<void> {
+ const now = operatorPassNow();
+ const existing = await this.repository.findWallEntry(userId);
+ if (!existing) {
+ return;
+ }
+ await this.entries.appendEvent(userId, now, {kind: 'taken_down', name: null, cause: 'deletion'}, null);
+ const entry = await this.entries.mutate(userId, now, null, (current) => {
+ if (current.name == null && current.listed_at == null && current.delivered_at == null) {
+ return null;
+ }
+ return {
+ patch: {
+ name: Db.set(null),
+ opted_out: Db.set(true),
+ listed_at: Db.set(null),
+ left_wall_at: Db.set(current.left_wall_at ?? now),
+ delivered_at: Db.set(null),
+ updated_at: Db.set(now),
+ },
+ events: [],
+ };
+ });
+ await this.publication.publishChanges([userId]);
+ if (entry.live_avatar) {
+ await this.publication.releaseAvatar(entry.live_avatar);
+ }
+ }
+
+ async recordHidden(userId: UserID, cause: OperatorPassWallTakeDownCause): Promise<void> {
+ const entry = await this.repository.findWallEntry(userId);
+ if (entry && isOperatorPassWallListed(entry)) {
+ await this.entries.appendEvent(
+ userId,
+ operatorPassNow(),
+ {kind: 'taken_down', name: entry.live_name, cause},
+ null,
+ );
+ }
+ await this.publication.publishChanges([userId]);
+ if (entry?.live_avatar) {
+ await this.publication.releaseAvatar(entry.live_avatar);
+ }
+ }
+
+ async recordCountChange(userId: UserID, passCount: number, at: Date = operatorPassNow()): Promise<void> {
+ await this.entries.appendEvent(userId, at, {kind: 'count_changed', passCount}, null);
+ await this.publication.publishChanges([userId]);
+ const entry = passCount > 0 ? await this.repository.findWallEntry(userId) : null;
+ if (entry) {
+ await this.publication.publishAvatarIfServed(entry);
+ }
+ }
+
+ async recordShownAgain(userId: UserID): Promise<void> {
+ const entry = await this.repository.findWallEntry(userId);
+ if (entry && isOperatorPassWallListed(entry)) {
+ await this.entries.appendEvent(userId, operatorPassNow(), {kind: 'shown_again', name: entry.live_name}, null);
+ await this.publication.publishAvatarIfServed(entry);
+ }
+ await this.publication.publishChanges([userId]);
+ }
+}
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallStanding.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallStanding.ts
new file mode 100644
index 000000000..4eb400f69
--- /dev/null
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallStanding.ts
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Config} from '@app/api/Config';
+import {Logger} from '@app/api/Logger';
+import {getOperatorPassWallService} from '@app/api/middleware/ServiceSingletons';
+import type {User} from '@app/api/models/User';
+import {isOperatorPassWallStanding} from '@app/api/operator_pass/OperatorPassWallPresentation';
+
+export async function followOperatorPassWallStanding(before: User, after: User): Promise<void> {
+ if (Config.instance.selfHosted) return;
+ if (isOperatorPassWallStanding(before) === isOperatorPassWallStanding(after)) return;
+ try {
+ const wall = getOperatorPassWallService();
+ if (!(await wall.getEntry(after.id))) return;
+ await wall.publication.publishChanges([after.id]);
+ } catch (error) {
+ Logger.error(
+ {error, userId: after.id.toString()},
+ "Failed to follow an account standing change on the Operators' wall",
+ );
+ }
+}