refactor: zones => topics

This commit is contained in:
Andy Burke 2025-09-10 12:51:27 -07:00
parent 20a5d1bc88
commit fac8f409f4
26 changed files with 470 additions and 469 deletions

View file

@ -7,7 +7,7 @@ Bringing the BBS back.
These are in no particular order. Pull requests updating this section welcome for These are in no particular order. Pull requests updating this section welcome for
feature discussions. feature discussions.
- [ ] should everything be an event in a zone? - [ ] should everything be an event in a topic?
- [X] get a first-pass podman/docker setup up - [X] get a first-pass podman/docker setup up
- [X] sign up - [X] sign up
- [X] check for logged in user session - [X] check for logged in user session
@ -21,7 +21,7 @@ feature discussions.
- [X] logout button - [X] logout button
- [ ] profile editing - [ ] profile editing
- [X] avatar uploads - [X] avatar uploads
- [X] chat zones - [X] chat topics
- [X] chat messages - [X] chat messages
- [ ] chat message actions - [ ] chat message actions
- [X] '...' button to show actions - [X] '...' button to show actions
@ -76,7 +76,7 @@ feature discussions.
- [ ] if web notifications are enabled, emit on events - [ ] if web notifications are enabled, emit on events
- [ ] ability to mute - [ ] ability to mute
- [ ] users - [ ] users
- [ ] zones - [ ] topics
- [ ] tags (#tags?) - [ ] tags (#tags?)
- [ ] admin panel - [ ] admin panel
- [ ] add invite code generation - [ ] add invite code generation

View file

@ -32,16 +32,16 @@ export type EVENT = {
}; };
}; };
type ZONE_EVENT_CACHE_ENTRY = { type TOPIC_EVENT_CACHE_ENTRY = {
collection: FSDB_COLLECTION<EVENT>; collection: FSDB_COLLECTION<EVENT>;
eviction_timeout: number; eviction_timeout: number;
}; };
const ZONE_EVENTS: Record<string, ZONE_EVENT_CACHE_ENTRY> = {}; const TOPIC_EVENTS: Record<string, TOPIC_EVENT_CACHE_ENTRY> = {};
export function get_events_collection_for_zone(zone_id: string): FSDB_COLLECTION<EVENT> { export function get_events_collection_for_topic(topic_id: string): FSDB_COLLECTION<EVENT> {
ZONE_EVENTS[zone_id] = ZONE_EVENTS[zone_id] ?? { TOPIC_EVENTS[topic_id] = TOPIC_EVENTS[topic_id] ?? {
collection: new FSDB_COLLECTION<EVENT>({ collection: new FSDB_COLLECTION<EVENT>({
name: `zones/${zone_id.slice(0, 14)}/${zone_id.slice(0, 34)}/${zone_id}/events`, name: `topics/${topic_id.slice(0, 14)}/${topic_id.slice(0, 34)}/${topic_id}/events`,
id_field: 'id', id_field: 'id',
organize: by_lurid, organize: by_lurid,
indexers: { indexers: {
@ -65,22 +65,22 @@ export function get_events_collection_for_zone(zone_id: string): FSDB_COLLECTION
eviction_timeout: 0 eviction_timeout: 0
}; };
if (ZONE_EVENTS[zone_id].eviction_timeout) { if (TOPIC_EVENTS[topic_id].eviction_timeout) {
clearTimeout(ZONE_EVENTS[zone_id].eviction_timeout); clearTimeout(TOPIC_EVENTS[topic_id].eviction_timeout);
} }
ZONE_EVENTS[zone_id].eviction_timeout = setTimeout(() => { TOPIC_EVENTS[topic_id].eviction_timeout = setTimeout(() => {
delete ZONE_EVENTS[zone_id]; delete TOPIC_EVENTS[topic_id];
}, 60_000 * 5); }, 60_000 * 5);
return ZONE_EVENTS[zone_id].collection; return TOPIC_EVENTS[topic_id].collection;
} }
export function clear_zone_events_cache() { export function clear_topic_events_cache() {
for (const [zone_id, cached] of Object.entries(ZONE_EVENTS)) { for (const [topic_id, cached] of Object.entries(TOPIC_EVENTS)) {
if (cached.eviction_timeout) { if (cached.eviction_timeout) {
clearTimeout(cached.eviction_timeout); clearTimeout(cached.eviction_timeout);
} }
delete ZONE_EVENTS[zone_id]; delete TOPIC_EVENTS[topic_id];
} }
} }

View file

@ -3,29 +3,29 @@ import { FSDB_COLLECTION } from '@andyburke/fsdb';
import { FSDB_INDEXER_SYMLINKS } from '@andyburke/fsdb/indexers'; import { FSDB_INDEXER_SYMLINKS } from '@andyburke/fsdb/indexers';
/** /**
* @typedef {object} ZONE_PERMISSIONS * @typedef {object} TOPIC_PERMISSIONS
* @property {string[]} read a list of user_ids with read permission for the zone * @property {string[]} read a list of user_ids with read permission for the topic
* @property {string[]} write a list of user_ids with write permission for the zone * @property {string[]} write a list of user_ids with write permission for the topic
* @property {string[]} read_events a list of user_ids with read_events permission for this zone * @property {string[]} read_events a list of user_ids with read_events permission for this topic
* @property {string[]} write_events a list of user_ids with write_events permission for this zone * @property {string[]} write_events a list of user_ids with write_events permission for this topic
*/ */
/** /**
* ZONE * TOPIC
* *
* @property {string} id - lurid (stable) * @property {string} id - lurid (stable)
* @property {string} name - channel name (max 64 characters, unique, unstable) * @property {string} name - channel name (max 64 characters, unique, unstable)
* @property {string} creator_id - user id of the zone creator * @property {string} creator_id - user id of the topic creator
* @property {ZONE_PERMISSIONS} permissions - permissions setup for the zone * @property {TOPIC_PERMISSIONS} permissions - permissions setup for the topic
* @property {string} [icon_url] - optional url for zone icon * @property {string} [icon_url] - optional url for topic icon
* @property {string} [topic] - optional topic for the zone * @property {string} [topic] - optional topic for the topic
* @property {string} [rules] - optional zone rules (Markdown/text) * @property {string} [rules] - optional topic rules (Markdown/text)
* @property {string[]} [tags] - optional tags for the zone * @property {string[]} [tags] - optional tags for the topic
* @property {Record<string,any>} [meta] - optional metadata about the zone * @property {Record<string,any>} [meta] - optional metadata about the topic
* @property {Record<string,string>} [emojis] - optional emojis table, eg: { 'rofl': 🤣, 'blap': 'https://somewhere.someplace/image.jpg' } * @property {Record<string,string>} [emojis] - optional emojis table, eg: { 'rofl': 🤣, 'blap': 'https://somewhere.someplace/image.jpg' }
*/ */
export type ZONE = { export type TOPIC = {
id: string; id: string;
name: string; name: string;
creator_id: string; creator_id: string;
@ -48,37 +48,37 @@ export type ZONE = {
}; };
}; };
export const ZONES = new FSDB_COLLECTION<ZONE>({ export const TOPICS = new FSDB_COLLECTION<TOPIC>({
name: 'zones', name: 'topics',
id_field: 'id', id_field: 'id',
organize: by_lurid, organize: by_lurid,
indexers: { indexers: {
creator_id: new FSDB_INDEXER_SYMLINKS<ZONE>({ creator_id: new FSDB_INDEXER_SYMLINKS<TOPIC>({
name: 'creator_id', name: 'creator_id',
field: 'creator_id', field: 'creator_id',
to_many: true, to_many: true,
organize: by_lurid organize: by_lurid
}), }),
name: new FSDB_INDEXER_SYMLINKS<ZONE>({ name: new FSDB_INDEXER_SYMLINKS<TOPIC>({
name: 'name', name: 'name',
get_values_to_index: (zone) => [zone.name.toLowerCase()], get_values_to_index: (topic) => [topic.name.toLowerCase()],
organize: by_character organize: by_character
}), }),
tags: new FSDB_INDEXER_SYMLINKS<ZONE>({ tags: new FSDB_INDEXER_SYMLINKS<TOPIC>({
name: 'tags', name: 'tags',
get_values_to_index: (zone): string[] => { get_values_to_index: (topic): string[] => {
return (zone.tags ?? []).map((tag) => tag.toLowerCase()); return (topic.tags ?? []).map((tag) => tag.toLowerCase());
}, },
to_many: true, to_many: true,
organize: by_character organize: by_character
}), }),
topic: new FSDB_INDEXER_SYMLINKS<ZONE>({ topic: new FSDB_INDEXER_SYMLINKS<TOPIC>({
name: 'topic', name: 'topic',
get_values_to_index: (zone): string[] => { get_values_to_index: (topic): string[] => {
return (zone.topic ?? '').split(/\W/); return (topic.topic ?? '').split(/\W/);
}, },
to_many: true, to_many: true,
organize: by_character organize: by_character

View file

@ -0,0 +1,23 @@
# /api/topics/:topic_id
Interact with a specific topic.
## GET /api/topics/:topic_id
Get the topic specified by `:topic_id`.
## PUT /api/topics/:topic_id
Update the topics specified by `:topic_id`.
Eg:
```
{
name?: string;
}
```
## DELETE /api/topics/:topic_id
Delete the topic specified by `:topic_id`.

View file

@ -1,36 +1,36 @@
import { FSDB_COLLECTION } from '@andyburke/fsdb'; import { FSDB_COLLECTION } from '@andyburke/fsdb';
import { EVENT, get_events_collection_for_zone } from '../../../../../../models/event.ts'; import { EVENT, get_events_collection_for_topic } from '../../../../../../models/event.ts';
import { ZONE, ZONES } from '../../../../../../models/zone.ts'; import { TOPIC, TOPICS } from '../../../../../../models/topic.ts';
import parse_body from '../../../../../../utils/bodyparser.ts'; import parse_body from '../../../../../../utils/bodyparser.ts';
import * as CANNED_RESPONSES from '../../../../../../utils/canned_responses.ts'; import * as CANNED_RESPONSES from '../../../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../../utils/prechecks.ts'; import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../../utils/prechecks.ts';
export const PRECHECKS: PRECHECK_TABLE = {}; export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/zones/:zone_id/events/:id - Get an event // GET /api/topics/:topic_id/events/:id - Get an event
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const zone_is_public = zone.permissions.read.length === 0; const topic_is_public = topic.permissions.read.length === 0;
const user_has_read_for_zone = zone_is_public || zone.permissions.read.includes(meta.user.id); const user_has_read_for_topic = topic_is_public || topic.permissions.read.includes(meta.user.id);
const zone_has_public_events = user_has_read_for_zone && (zone.permissions.read_events.length === 0); const topic_has_public_events = user_has_read_for_topic && (topic.permissions.read_events.length === 0);
const user_has_read_events_for_zone = user_has_read_for_zone && const user_has_read_events_for_topic = user_has_read_for_topic &&
(zone_has_public_events || zone.permissions.read_events.includes(meta.user.id)); (topic_has_public_events || topic.permissions.read_events.includes(meta.user.id));
if (!user_has_read_events_for_zone) { if (!user_has_read_events_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> { export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_zone(meta.zone.id); const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const event: EVENT | null = await events.get(meta.params.event_id); const event: EVENT | null = await events.get(meta.params.event_id);
if (!event) { if (!event) {
@ -42,7 +42,7 @@ export async function GET(_req: Request, meta: Record<string, any>): Promise<Res
}); });
} }
// PUT /api/zones/:zone_id/events/:event_id - Update event // PUT /api/topics/:topic_id/events/:event_id - Update event
PRECHECKS.PUT = [ PRECHECKS.PUT = [
get_session, get_session,
get_user, get_user,
@ -53,23 +53,23 @@ PRECHECKS.PUT = [
} }
}, },
async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const zone_is_public: boolean = meta.zone.permissions.read.length === 0; const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_zone = zone_is_public || meta.zone.permissions.read.includes(meta.user.id); const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const zone_events_are_publicly_writable = meta.zone.permissions.write_events.length === 0; const topic_events_are_publicly_writable = meta.topic.permissions.write_events.length === 0;
const user_has_write_events_for_zone = user_has_read_for_zone && const user_has_write_events_for_topic = user_has_read_for_topic &&
(zone_events_are_publicly_writable || meta.zone.permissions.write_events.includes(meta.user.id)); (topic_events_are_publicly_writable || meta.topic.permissions.write_events.includes(meta.user.id));
if (!user_has_write_events_for_zone) { if (!user_has_write_events_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
} }
@ -78,7 +78,7 @@ export async function PUT(req: Request, meta: Record<string, any>): Promise<Resp
const now = new Date().toISOString(); const now = new Date().toISOString();
try { try {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_zone(meta.zone.id); const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const event: EVENT | null = await events.get(meta.params.event_id); const event: EVENT | null = await events.get(meta.params.event_id);
if (!event) { if (!event) {
@ -117,7 +117,7 @@ export async function PUT(req: Request, meta: Record<string, any>): Promise<Resp
} }
} }
// DELETE /api/zones/:zone_id/events/:event_id - Delete event // DELETE /api/topics/:topic_id/events/:event_id - Delete event
PRECHECKS.DELETE = [ PRECHECKS.DELETE = [
get_session, get_session,
get_user, get_user,
@ -128,29 +128,29 @@ PRECHECKS.DELETE = [
} }
}, },
async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const zone_is_public: boolean = meta.zone.permissions.read.length === 0; const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_zone = zone_is_public || meta.zone.permissions.read.includes(meta.user.id); const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const zone_events_are_publicly_writable = meta.zone.permissions.write_events.length === 0; const topic_events_are_publicly_writable = meta.topic.permissions.write_events.length === 0;
const user_has_write_events_for_zone = user_has_read_for_zone && const user_has_write_events_for_topic = user_has_read_for_topic &&
(zone_events_are_publicly_writable || meta.zone.permissions.write_events.includes(meta.user.id)); (topic_events_are_publicly_writable || meta.topic.permissions.write_events.includes(meta.user.id));
if (!user_has_write_events_for_zone) { if (!user_has_write_events_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
} }
]; ];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> { export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_zone(meta.zone.id); const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const event: EVENT | null = await events.get(meta.params.event_id); const event: EVENT | null = await events.get(meta.params.event_id);
if (!event) { if (!event) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();

View file

@ -0,0 +1,15 @@
# /api/topics/:topic_id/events
Interact with a events for a topic.
## GET /api/topics/:topic_id/events
Get events for the given topic.
## PUT /api/topics/:topic_id/events/:event_id
Update an event.
## DELETE /api/topics/:topic_id/events/:event_id
Delete an event.

View file

@ -1,40 +1,40 @@
import lurid from '@andyburke/lurid'; import lurid from '@andyburke/lurid';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts'; import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts';
import { ZONE, ZONES } from '../../../../../models/zone.ts'; import { TOPIC, TOPICS } from '../../../../../models/topic.ts';
import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts'; import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts';
import { EVENT, get_events_collection_for_zone } from '../../../../../models/event.ts'; import { EVENT, get_events_collection_for_topic } from '../../../../../models/event.ts';
import parse_body from '../../../../../utils/bodyparser.ts'; import parse_body from '../../../../../utils/bodyparser.ts';
import { FSDB_COLLECTION, FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb'; import { FSDB_COLLECTION, FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';
import * as path from '@std/path'; import * as path from '@std/path';
export const PRECHECKS: PRECHECK_TABLE = {}; export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/zones/:zone_id/events - get zone events // GET /api/topics/:topic_id/events - get topic events
// query parameters: // query parameters:
// partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted) // partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted)
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const zone_is_public: boolean = meta.zone.permissions.read.length === 0; const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_zone = zone_is_public || meta.zone.permissions.read.includes(meta.user.id); const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const zone_events_are_public = meta.zone.permissions.read_events.length === 0; const topic_events_are_public = meta.topic.permissions.read_events.length === 0;
const user_has_read_events_for_zone = user_has_read_for_zone && const user_has_read_events_for_topic = user_has_read_for_topic &&
(zone_events_are_public || meta.zone.permissions.read_events.includes(meta.user.id)); (topic_events_are_public || meta.topic.permissions.read_events.includes(meta.user.id));
if (!user_has_read_events_for_zone) { if (!user_has_read_events_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
export async function GET(request: Request, meta: Record<string, any>): Promise<Response> { export async function GET(request: Request, meta: Record<string, any>): Promise<Response> {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_zone(meta.zone.id); const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const sorts = events.sorts; const sorts = events.sorts;
const sort_name: string = meta.query.sort ?? 'newest'; const sort_name: string = meta.query.sort ?? 'newest';
@ -126,31 +126,31 @@ export async function GET(request: Request, meta: Record<string, any>): Promise<
}); });
} }
// POST /api/zones/:zone_id/events - Create an event // POST /api/topics/:topic_id/events - Create an event
PRECHECKS.POST = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { PRECHECKS.POST = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const zone_is_public: boolean = meta.zone.permissions.read.length === 0; const topic_is_public: boolean = meta.topic.permissions.read.length === 0;
const user_has_read_for_zone = zone_is_public || meta.zone.permissions.read.includes(meta.user.id); const user_has_read_for_topic = topic_is_public || meta.topic.permissions.read.includes(meta.user.id);
const zone_events_are_publicly_writable = meta.zone.permissions.write_events.length === 0; const topic_events_are_publicly_writable = meta.topic.permissions.write_events.length === 0;
const user_has_write_events_for_zone = user_has_read_for_zone && const user_has_write_events_for_topic = user_has_read_for_topic &&
(zone_events_are_publicly_writable || meta.zone.permissions.write_events.includes(meta.user.id)); (topic_events_are_publicly_writable || meta.topic.permissions.write_events.includes(meta.user.id));
if (!user_has_write_events_for_zone) { if (!user_has_write_events_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
export async function POST(req: Request, meta: Record<string, any>): Promise<Response> { export async function POST(req: Request, meta: Record<string, any>): Promise<Response> {
try { try {
const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_zone(meta.zone.id); const events: FSDB_COLLECTION<EVENT> = get_events_collection_for_topic(meta.topic.id);
const now = new Date().toISOString(); const now = new Date().toISOString();

View file

@ -1,50 +1,50 @@
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts'; import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts';
import parse_body from '../../../../utils/bodyparser.ts'; import parse_body from '../../../../utils/bodyparser.ts';
import * as CANNED_RESPONSES from '../../../../utils/canned_responses.ts'; import * as CANNED_RESPONSES from '../../../../utils/canned_responses.ts';
import { ZONE, ZONES } from '../../../../models/zone.ts'; import { TOPIC, TOPICS } from '../../../../models/topic.ts';
export const PRECHECKS: PRECHECK_TABLE = {}; export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/zones/:id - Get a zone // GET /api/topics/:id - Get a topic
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const zone_is_public = zone.permissions.read.length === 0; const topic_is_public = topic.permissions.read.length === 0;
const user_has_read_for_zone = zone_is_public || zone.permissions.read.includes(meta.user.id); const user_has_read_for_topic = topic_is_public || topic.permissions.read.includes(meta.user.id);
if (!user_has_read_for_zone) { if (!user_has_read_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
export function GET(_req: Request, meta: Record<string, any>): Response { export function GET(_req: Request, meta: Record<string, any>): Response {
return Response.json(meta.zone, { return Response.json(meta.topic, {
status: 200 status: 200
}); });
} }
// PUT /api/zones/:id - Update zone // PUT /api/topics/:id - Update topic
PRECHECKS.PUT = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { PRECHECKS.PUT = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const user_has_write_for_zone = zone.permissions.write.includes(meta.user.id); const user_has_write_for_topic = topic.permissions.write.includes(meta.user.id);
if (!user_has_write_for_zone) { if (!user_has_write_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
@ -54,16 +54,16 @@ export async function PUT(req: Request, meta: Record<string, any>): Promise<Resp
try { try {
const body = await parse_body(req); const body = await parse_body(req);
const updated = { const updated = {
...meta.zone, ...meta.topic,
...body, ...body,
id: meta.zone.id, id: meta.topic.id,
timestamps: { timestamps: {
created: meta.zone.timestamps.created, created: meta.topic.timestamps.created,
updated: now updated: now
} }
}; };
await ZONES.update(updated); await TOPICS.update(updated);
return Response.json(updated, { return Response.json(updated, {
status: 200 status: 200
}); });
@ -79,31 +79,31 @@ export async function PUT(req: Request, meta: Record<string, any>): Promise<Resp
} }
} }
// DELETE /api/zones/:id - Delete zone // DELETE /api/topics/:id - Delete topic
PRECHECKS.DELETE = [ PRECHECKS.DELETE = [
get_session, get_session,
get_user, get_user,
require_user, require_user,
async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => { async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
const zone_id: string = meta.params?.zone_id?.toLowerCase().trim() ?? ''; const topic_id: string = meta.params?.topic_id?.toLowerCase().trim() ?? '';
// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same" // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
const zone: ZONE | null = zone_id.length === 49 ? await ZONES.get(zone_id) : null; const topic: TOPIC | null = topic_id.length === 49 ? await TOPICS.get(topic_id) : null;
if (!zone) { if (!topic) {
return CANNED_RESPONSES.not_found(); return CANNED_RESPONSES.not_found();
} }
meta.zone = zone; meta.topic = topic;
const user_has_write_for_zone = zone.permissions.write.includes(meta.user.id); const user_has_write_for_topic = topic.permissions.write.includes(meta.user.id);
if (!user_has_write_for_zone) { if (!user_has_write_for_topic) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
} }
]; ];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> { export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
await ZONES.delete(meta.zone); await TOPICS.delete(meta.topic);
return Response.json({ return Response.json({
deleted: true deleted: true

View file

@ -0,0 +1,28 @@
# /api/topics
Interact with topics.
## POST /api/topics
Create a new topic.
```
export type TOPIC = {
id: string; // unique id for this topic
name: string; // the name of the topic (max 128 characters)
icon_url?: string; // optional url for a topic icon
topic?: string; // optional topic topic
tags: string[]; // a list of tags for the topic
meta: Record<string, any>;
limits: {
users: number;
user_messages_per_minute: number;
};
creator_id: string; // user_id of the topic creator
emojis: Record<string, string>; // either: string: emoji eg: { 'rofl: 🤣, ... } or { 'rofl': 🤣, 'blap': 'https://somewhere.someplace/image.jpg' }
};
```
## GET /api/topics
Get topics.

View file

@ -3,40 +3,40 @@ import parse_body from '../../../utils/bodyparser.ts';
import { get_session, get_user, require_user } from '../../../utils/prechecks.ts'; import { get_session, get_user, require_user } from '../../../utils/prechecks.ts';
import * as CANNED_RESPONSES from '../../../utils/canned_responses.ts'; import * as CANNED_RESPONSES from '../../../utils/canned_responses.ts';
import { PRECHECK_TABLE } from '../../../utils/prechecks.ts'; import { PRECHECK_TABLE } from '../../../utils/prechecks.ts';
import { ZONE, ZONES } from '../../../models/zone.ts'; import { TOPIC, TOPICS } from '../../../models/topic.ts';
import { WALK_ENTRY } from '@andyburke/fsdb'; import { WALK_ENTRY } from '@andyburke/fsdb';
export const PRECHECKS: PRECHECK_TABLE = {}; export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/zones - get zones // GET /api/topics - get topics
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => { PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_read_zones = meta.user.permissions.includes('zones.read'); const can_read_topics = meta.user.permissions.includes('topics.read');
if (!can_read_zones) { if (!can_read_topics) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> { export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const limit = Math.min(parseInt(meta.query.limit ?? '100'), 100); const limit = Math.min(parseInt(meta.query.limit ?? '100'), 100);
const zones = (await ZONES.all({ const topics = (await TOPICS.all({
limit, limit,
filter: (entry: WALK_ENTRY<ZONE>) => { filter: (entry: WALK_ENTRY<TOPIC>) => {
// we push our event collections into the zones, and fsdb // we push our event collections into the topics, and fsdb
// doesn't yet filter that out in its all() logic // doesn't yet filter that out in its all() logic
return entry.path.indexOf('/events/') === -1; return entry.path.indexOf('/events/') === -1;
} }
})).map((zone_entry) => zone_entry.load()); })).map((topic_entry) => topic_entry.load());
return Response.json(zones, { return Response.json(topics, {
status: 200 status: 200
}); });
} }
// POST /api/zones - Create a zone // POST /api/topics - Create a topic
PRECHECKS.POST = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => { PRECHECKS.POST = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_create_zones = meta.user.permissions.includes('zones.create'); const can_create_topics = meta.user.permissions.includes('topics.create');
if (!can_create_zones) { if (!can_create_topics) {
return CANNED_RESPONSES.permission_denied(); return CANNED_RESPONSES.permission_denied();
} }
}]; }];
@ -49,8 +49,8 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
if (typeof body.name !== 'string' || body.name.length === 0) { if (typeof body.name !== 'string' || body.name.length === 0) {
return Response.json({ return Response.json({
error: { error: {
cause: 'missing_zone_name', cause: 'missing_topic_name',
message: 'You must specify a unique name for a zone.' message: 'You must specify a unique name for a topic.'
} }
}, { }, {
status: 400 status: 400
@ -60,8 +60,8 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
if (body.name.length > 64) { if (body.name.length > 64) {
return Response.json({ return Response.json({
error: { error: {
cause: 'invalid_zone_name', cause: 'invalid_topic_name',
message: 'zone names must be 64 characters or fewer.' message: 'topic names must be 64 characters or fewer.'
} }
}, { }, {
status: 400 status: 400
@ -70,21 +70,21 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
const normalized_name = body.name.toLowerCase(); const normalized_name = body.name.toLowerCase();
const existing_zone = (await ZONES.find({ const existing_topic = (await TOPICS.find({
name: normalized_name name: normalized_name
})).shift(); })).shift();
if (existing_zone) { if (existing_topic) {
return Response.json({ return Response.json({
error: { error: {
cause: 'zone_name_conflict', cause: 'topic_name_conflict',
message: 'There is already a zone with this name.' message: 'There is already a topic with this name.'
} }
}, { }, {
status: 400 status: 400
}); });
} }
const zone: ZONE = { const topic: TOPIC = {
...body, ...body,
id: lurid(), id: lurid(),
creator_id: meta.user.id, creator_id: meta.user.id,
@ -101,9 +101,9 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
} }
}; };
await ZONES.create(zone); await TOPICS.create(topic);
return Response.json(zone, { return Response.json(topic, {
status: 201 status: 201
}); });
} catch (error) { } catch (error) {

View file

@ -13,7 +13,7 @@ const DEFAULT_USER_PERMISSIONS: string[] = [
'files.write.own', 'files.write.own',
'self.read', 'self.read',
'self.write', 'self.write',
'zones.read', 'topics.read',
'users.read' 'users.read'
]; ];

View file

@ -1,23 +0,0 @@
# /api/zones/:zone_id
Interact with a specific zone.
## GET /api/zones/:zone_id
Get the zone specified by `:zone_id`.
## PUT /api/zones/:zone_id
Update the zones specified by `:zone_id`.
Eg:
```
{
name?: string;
}
```
## DELETE /api/zones/:zone_id
Delete the zone specified by `:zone_id`.

View file

@ -1,15 +0,0 @@
# /api/zones/:zone_id/events
Interact with a events for a zone.
## GET /api/zones/:zone_id/events
Get events for the given zone.
## PUT /api/zones/:zone_id/events/:event_id
Update an event.
## DELETE /api/zones/:zone_id/events/:event_id
Delete an event.

View file

@ -1,28 +0,0 @@
# /api/zones
Interact with zones.
## POST /api/zones
Create a new zone.
```
export type ZONE = {
id: string; // unique id for this zone
name: string; // the name of the zone (max 128 characters)
icon_url?: string; // optional url for a zone icon
topic?: string; // optional zone topic
tags: string[]; // a list of tags for the zone
meta: Record<string, any>;
limits: {
users: number;
user_messages_per_minute: number;
};
creator_id: string; // user_id of the zone creator
emojis: Record<string, string>; // either: string: emoji eg: { 'rofl: 🤣, ... } or { 'rofl': 🤣, 'blap': 'https://somewhere.someplace/image.jpg' }
};
```
## GET /api/zones
Get zones.

View file

@ -200,7 +200,7 @@ button.primary {
} }
body[data-perms*="users.write"] [data-requires-permission="users.write"], body[data-perms*="users.write"] [data-requires-permission="users.write"],
body[data-perms*="zones.create"] [data-requires-permission="zones.create"] { body[data-perms*="topics.create"] [data-requires-permission="topics.create"] {
visibility: visible; visibility: visible;
opacity: 1; opacity: 1;
height: unset; height: unset;

View file

@ -3,12 +3,12 @@
grid-template-columns: auto 1fr; grid-template-columns: auto 1fr;
} }
.zone-list { .topic-list {
margin: 1rem 0; margin: 1rem 0;
list-style-type: none; list-style-type: none;
} }
.zone-list > li.zone a:before { .topic-list > li.topic a:before {
position: absolute; position: absolute;
left: -1.75rem; left: -1.75rem;
top: 0; top: 0;
@ -18,7 +18,7 @@
color: var(--text); color: var(--text);
} }
.zone-list > li.zone a { .topic-list > li.topic a {
position: relative; position: relative;
display: block; display: block;
width: 100%; width: 100%;
@ -30,7 +30,7 @@
text-decoration: none; text-decoration: none;
} }
.zone-list > li.zone.active a { .topic-list > li.topic.active a {
color: var(--accent); color: var(--accent);
} }
@ -56,11 +56,11 @@
line-height: 2rem; line-height: 2rem;
} }
#chat #zone-chat-container { #chat #topic-chat-container {
position: relative; position: relative;
} }
#chat #zone-chat-content { #chat #topic-chat-content {
overflow-y: scroll; overflow-y: scroll;
position: absolute; position: absolute;
top: 0; top: 0;
@ -70,7 +70,7 @@
padding: 0.5rem; padding: 0.5rem;
} }
#chat #zone-chat-entry-container { #chat #topic-chat-entry-container {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
left: 0; left: 0;
@ -79,7 +79,7 @@
padding: 1rem; padding: 1rem;
} }
#chat #zone-chat-entry-container form { #chat #topic-chat-entry-container form {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
@ -90,13 +90,13 @@
padding: 0.75rem; padding: 0.75rem;
} }
#chat #zone-chat-entry-container form input[type="file"] { #chat #topic-chat-entry-container form input[type="file"] {
opacity: 0; opacity: 0;
display: none; display: none;
} }
#chat #zone-chat-entry-container form button, #chat #topic-chat-entry-container form button,
#chat #zone-chat-entry-container form label { #chat #topic-chat-entry-container form label {
position: relative; position: relative;
top: inherit; top: inherit;
font-size: inherit; font-size: inherit;
@ -110,7 +110,7 @@
border: 1px solid var(--text); border: 1px solid var(--text);
} }
#chat #zone-chat-entry-container form textarea { #chat #topic-chat-entry-container form textarea {
width: 100%; width: 100%;
flex-grow: 1; flex-grow: 1;
background: inherit; background: inherit;
@ -373,7 +373,7 @@
rotate: 180deg; rotate: 180deg;
} }
#chat #zone-chat-container { #chat #topic-chat-container {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
@ -381,13 +381,13 @@
bottom: 0; bottom: 0;
} }
#chat #zone-chat-container #zone-chat-entry-container, #chat #topic-chat-container #topic-chat-entry-container,
#chat #zone-chat-container #zone-chat-entry-container form { #chat #topic-chat-container #topic-chat-entry-container form {
padding: 0.25rem; padding: 0.25rem;
} }
#chat #zone-chat-container #zone-chat-entry-container form button, #chat #topic-chat-container #topic-chat-entry-container form button,
#chat #zone-chat-container #zone-chat-entry-container form label { #chat #topic-chat-container #topic-chat-entry-container form label {
margin: 0 0.5rem; margin: 0 0.5rem;
} }

View file

@ -22,21 +22,21 @@
<label id="sidebar-toggle-icon" for="sidebar-toggle"> <label id="sidebar-toggle-icon" for="sidebar-toggle">
<div class="icon right"></div> <div class="icon right"></div>
</label> </label>
<div id="zone-creation-container" data-requires-permission="zones.create"> <div id="topic-creation-container" data-requires-permission="topics.create">
<button <button
id="toggle-zone-creation-form-button" id="toggle-topic-creation-form-button"
onclick="((event) => { onclick="((event) => {
event.preventDefault(); event.preventDefault();
const zone_create_form = document.getElementById( 'zone-create' ); const topic_create_form = document.getElementById( 'topic-create' );
zone_create_form.style[ 'height' ] = zone_create_form.style[ 'height' ] === '5rem' ? '0' : '5rem'; topic_create_form.style[ 'height' ] = topic_create_form.style[ 'height' ] === '5rem' ? '0' : '5rem';
})(event)" })(event)"
> >
<div class="icon plus"></div> <div class="icon plus"></div>
</button> </button>
<form <form
id="zone-create" id="topic-create"
data-smart="true" data-smart="true"
action="/api/zones" action="/api/topics"
method="POST" method="POST"
style=" style="
margin-top: 1rem; margin-top: 1rem;
@ -48,11 +48,11 @@
" "
> >
<input <input
id="new-zone-name-input" id="new-topic-name-input"
type="text" type="text"
name="name" name="name"
value="" value=""
placeholder="new zone" placeholder="new topic"
/> />
<!-- <button class="primary" type="submit"> <!-- <button class="primary" type="submit">
<div class="icon plus"></div> <div class="icon plus"></div>
@ -61,34 +61,34 @@
<script> <script>
{ {
const form = document.currentScript.closest("form"); const form = document.currentScript.closest("form");
const zone_create_form = document.getElementById("zone-create"); const topic_create_form = document.getElementById("topic-create");
const new_zone_name_input = const new_topic_name_input =
document.getElementById("new-zone-name-input"); document.getElementById("new-topic-name-input");
form.on_reply = (new_zone) => { form.on_reply = (new_topic) => {
const zone_list = document.getElementById("zone-list"); const topic_list = document.getElementById("topic-list");
zone_list.insertAdjacentHTML( topic_list.insertAdjacentHTML(
"beforeend", "beforeend",
`<li id="zone-selector-${new_zone.id}" class="zone"><a href="#/zone/${new_zone.id}">${new_zone.name}</a></li>`, `<li id="topic-selector-${new_topic.id}" class="topic"><a href="#/topic/${new_topic.id}">${new_topic.name}</a></li>`,
); );
new_zone_name_input.value = ""; new_topic_name_input.value = "";
window.location.hash = `/chat/zone/${new_zone.id}`; window.location.hash = `/chat/topic/${new_topic.id}`;
zone_create_form.style["height"] = "0"; topic_create_form.style["height"] = "0";
}; };
} }
</script> </script>
</form> </form>
</div> </div>
<div> <div>
<span class="title">chat zones</span> <span class="title">chat topics</span>
</div> </div>
<ul id="zone-list" class="zone-list"></ul> <ul id="topic-list" class="topic-list"></ul>
</div> </div>
<div id="zone-chat-container"> <div id="topic-chat-container">
<div id="zone-chat-content"></div> <div id="topic-chat-content"></div>
<div id="zone-chat-entry-container"> <div id="topic-chat-entry-container">
<form id="zone-chat-entry" action="" data-smart="true" data-method="POST"> <form id="topic-chat-entry" action="" data-smart="true" data-method="POST">
<input id="parent-id" type="hidden" name="parent_id" value="" /> <input id="parent-id" type="hidden" name="parent_id" value="" />
<input <input
id="file-upload-and-share-input" id="file-upload-and-share-input"
@ -101,12 +101,12 @@
<div class="icon attachment"></div> <div class="icon attachment"></div>
</label> </label>
<textarea <textarea
id="zone-chat-input" id="topic-chat-input"
class="zone-chat-input" class="topic-chat-input"
rows="1" rows="1"
name="data.message" name="data.message"
></textarea> ></textarea>
<button id="zone-chat-send" class="primary" aria-label="Send a message"> <button id="topic-chat-send" class="primary" aria-label="Send a message">
<i class="icon send"></i> <i class="icon send"></i>
</button> </button>
<script> <script>
@ -115,11 +115,12 @@
const file_input = document.querySelector( const file_input = document.querySelector(
'input[name="file-upload-and-share"]', 'input[name="file-upload-and-share"]',
); );
const chat_input = document.getElementById("zone-chat-input"); const chat_input = document.getElementById("topic-chat-input");
const parent_id_input = document.getElementById("parent-id"); const parent_id_input = document.getElementById("parent-id");
const zone_chat_container = const topic_chat_container =
document.getElementById("zone-chat-container"); document.getElementById("topic-chat-container");
const zone_chat_content = document.getElementById("zone-chat-content"); const topic_chat_content =
document.getElementById("topic-chat-content");
let messages_in_flight = {}; let messages_in_flight = {};
@ -131,9 +132,9 @@
form.on_submit = async (event) => { form.on_submit = async (event) => {
const user = JSON.parse(document.body.dataset.user); const user = JSON.parse(document.body.dataset.user);
const zone_id = zone_chat_container.dataset.zone_id; const topic_id = topic_chat_container.dataset.topic_id;
if (!zone_id) { if (!topic_id) {
alert("Failed to get zone_id!"); alert("Failed to get topic_id!");
return false; return false;
} }
@ -171,7 +172,7 @@
return false; return false;
} }
form.action = `/api/zones/${zone_id}/events`; form.action = `/api/topics/${topic_id}/events`;
}; };
form.on_parsed = (json) => { form.on_parsed = (json) => {
@ -198,7 +199,7 @@
} }
const user = JSON.parse(document.body.dataset.user); const user = JSON.parse(document.body.dataset.user);
render_text_event(zone_chat_content, json, user); render_text_event(topic_chat_content, json, user);
document document
.getElementById(`chat-${temp_id}`) .getElementById(`chat-${temp_id}`)
?.classList.add("sending"); ?.classList.add("sending");
@ -215,7 +216,7 @@
.getElementById(`chat-${sent_message.meta?.temp_id ?? ""}`) .getElementById(`chat-${sent_message.meta?.temp_id ?? ""}`)
?.classList.remove("sending"); ?.classList.remove("sending");
append_zone_events([sent_message]); append_topic_events([sent_message]);
parent_id_input.value = ""; parent_id_input.value = "";
chat_input.value = ""; chat_input.value = "";
chat_input.focus(); chat_input.focus();

View file

@ -257,7 +257,7 @@ let time_tick_tock_class = "time-tock";
let last_creator_id = null; let last_creator_id = null;
let user_tick_tock_class = "user-tock"; let user_tick_tock_class = "user-tock";
function render_text_event(zone_chat_content, event, creator, existing_element) { function render_text_event(topic_chat_content, event, creator, existing_element) {
const event_datetime = datetime_to_local(event.timestamps.created); const event_datetime = datetime_to_local(event.timestamps.created);
if (event_datetime.value - last_event_datetime_value > time_tick_tock_timeout) { if (event_datetime.value - last_event_datetime_value > time_tick_tock_timeout) {
@ -307,31 +307,31 @@ function render_text_event(zone_chat_content, event, creator, existing_element)
template.innerHTML = html_content; template.innerHTML = html_content;
existing_element.replaceWith(template.content.firstChild); existing_element.replaceWith(template.content.firstChild);
} else { } else {
zone_chat_content.insertAdjacentHTML("beforeend", html_content); topic_chat_content.insertAdjacentHTML("beforeend", html_content);
} }
} }
async function get_new_zone_element() { async function get_new_topic_element() {
const existing_new_zone_element = document.getElementById("new-zone"); const existing_new_topic_element = document.getElementById("new-topic");
if (existing_new_zone_element) { if (existing_new_topic_element) {
return existing_new_zone_element; return existing_new_topic_element;
} }
const zone_list = document.getElementById("zone-list"); const topic_list = document.getElementById("topic-list");
zone_list.insertAdjacentHTML( topic_list.insertAdjacentHTML(
"beforeend", "beforeend",
`<li id="new-zone" class="zone"><a href="" contenteditable="true">new zone</a></li>`, `<li id="new-topic" class="topic"><a href="" contenteditable="true">new topic</a></li>`,
); );
await new Promise((resolve) => setTimeout(resolve, 1)); await new Promise((resolve) => setTimeout(resolve, 1));
const new_zone_element = document.getElementById("new-zone"); const new_topic_element = document.getElementById("new-topic");
return new_zone_element; return new_topic_element;
} }
const users = {}; const users = {};
async function append_zone_events(events) { async function append_topic_events(events) {
const zone_chat_content = document.getElementById("zone-chat-content"); const topic_chat_content = document.getElementById("topic-chat-content");
let last_message_id = zone_chat_content.dataset.last_message_id ?? ""; let last_message_id = topic_chat_content.dataset.last_message_id ?? "";
for (const event of events) { for (const event of events) {
// if the last message is undefined, it becomes this event, otherwise, if this event's id is newer, // if the last message is undefined, it becomes this event, otherwise, if this event's id is newer,
// it becomes the latest message // it becomes the latest message
@ -341,8 +341,8 @@ async function append_zone_events(events) {
: last_message_id; : last_message_id;
// if the last message has been updated, update the content's dataset to reflect that // if the last message has been updated, update the content's dataset to reflect that
if (last_message_id !== zone_chat_content.dataset.last_message_id) { if (last_message_id !== topic_chat_content.dataset.last_message_id) {
zone_chat_content.dataset.last_message_id = last_message_id; topic_chat_content.dataset.last_message_id = last_message_id;
} }
users[event.creator_id] = users[event.creator_id] =
@ -354,37 +354,37 @@ async function append_zone_events(events) {
(event.meta?.temp_id (event.meta?.temp_id
? document.getElementById(`chat-${event.meta.temp_id}`) ? document.getElementById(`chat-${event.meta.temp_id}`)
: undefined); : undefined);
render_text_event(zone_chat_content, event, users[event.creator_id], existing_element); render_text_event(topic_chat_content, event, users[event.creator_id], existing_element);
} }
zone_chat_content.scrollTop = zone_chat_content.scrollHeight; topic_chat_content.scrollTop = topic_chat_content.scrollHeight;
} }
// TODO: we need some abortcontroller handling here or something // TODO: we need some abortcontroller handling here or something
// similar for when we change zones, this is the most basic // similar for when we change topics, this is the most basic
// first pass outline // first pass outline
let zone_polling_request_abort_controller = null; let topic_polling_request_abort_controller = null;
async function poll_for_new_events() { async function poll_for_new_events() {
const zone_chat_content = document.getElementById("zone-chat-content"); const topic_chat_content = document.getElementById("topic-chat-content");
const zone_id = zone_chat_content.dataset.zone_id; const topic_id = topic_chat_content.dataset.topic_id;
const last_message_id = zone_chat_content.dataset.last_message_id; const last_message_id = topic_chat_content.dataset.last_message_id;
if (!zone_id) { if (!topic_id) {
return; return;
} }
const message_polling_url = `/api/zones/${zone_id}/events?type=chat&limit=100&sort=newest&wait=true${last_message_id ? `&after_id=${last_message_id}` : ""}`; const message_polling_url = `/api/topics/${topic_id}/events?type=chat&limit=100&sort=newest&wait=true${last_message_id ? `&after_id=${last_message_id}` : ""}`;
zone_polling_request_abort_controller = topic_polling_request_abort_controller =
zone_polling_request_abort_controller || new AbortController(); topic_polling_request_abort_controller || new AbortController();
api.fetch(message_polling_url, { api.fetch(message_polling_url, {
signal: zone_polling_request_abort_controller.signal, signal: topic_polling_request_abort_controller.signal,
}) })
.then(async (new_events_response) => { .then(async (new_events_response) => {
const new_events = ((await new_events_response.json()) ?? []).reverse(); const new_events = ((await new_events_response.json()) ?? []).reverse();
await append_zone_events(new_events.toReversed()); await append_topic_events(new_events.toReversed());
poll_for_new_events(zone_id); poll_for_new_events(topic_id);
}) })
.catch((error) => { .catch((error) => {
// TODO: poll again? back off? // TODO: poll again? back off?
@ -392,37 +392,37 @@ async function poll_for_new_events() {
}); });
} }
async function load_zone(zone_id) { async function load_topic(topic_id) {
const zone_chat_content = document.getElementById("zone-chat-content"); const topic_chat_content = document.getElementById("topic-chat-content");
if (zone_polling_request_abort_controller) { if (topic_polling_request_abort_controller) {
zone_polling_request_abort_controller.abort(); topic_polling_request_abort_controller.abort();
zone_polling_request_abort_controller = null; topic_polling_request_abort_controller = null;
delete zone_chat_content.dataset.last_message_id; delete topic_chat_content.dataset.last_message_id;
} }
const zone_response = await api.fetch(`/api/zones/${zone_id}`); const topic_response = await api.fetch(`/api/topics/${topic_id}`);
if (!zone_response.ok) { if (!topic_response.ok) {
const error = await zone_response.json(); const error = await topic_response.json();
alert(error.message ?? JSON.stringify(error)); alert(error.message ?? JSON.stringify(error));
return; return;
} }
const zone = await zone_response.json(); const topic = await topic_response.json();
zone_chat_content.dataset.zone_id = zone.id; topic_chat_content.dataset.topic_id = topic.id;
zone_chat_content.innerHTML = ""; topic_chat_content.innerHTML = "";
const zone_selectors = document.querySelectorAll("li.zone"); const topic_selectors = document.querySelectorAll("li.topic");
for (const zone_selector of zone_selectors) { for (const topic_selector of topic_selectors) {
zone_selector.classList.remove("active"); topic_selector.classList.remove("active");
if (zone_selector.id === `zone-selector-${zone_id}`) { if (topic_selector.id === `topic-selector-${topic_id}`) {
zone_selector.classList.add("active"); topic_selector.classList.add("active");
} }
} }
const events_response = await api.fetch( const events_response = await api.fetch(
`/api/zones/${zone_id}/events?type=chat&limit=100&sort=newest`, `/api/topics/${topic_id}/events?type=chat&limit=100&sort=newest`,
); );
if (!events_response.ok) { if (!events_response.ok) {
const error = await events_response.json(); const error = await events_response.json();
@ -432,36 +432,36 @@ async function load_zone(zone_id) {
const events = (await events_response.json()).reverse(); const events = (await events_response.json()).reverse();
await append_zone_events(events); await append_topic_events(events);
poll_for_new_events(zone_id); poll_for_new_events(topic_id);
} }
let last_zone_update = undefined; let last_topic_update = undefined;
async function update_chat_zones() { async function update_chat_topics() {
const now = new Date(); const now = new Date();
const time_since_last_update = now - (last_zone_update ?? 0); const time_since_last_update = now - (last_topic_update ?? 0);
if (time_since_last_update < 5_000) { if (time_since_last_update < 5_000) {
return; return;
} }
const zones_response = await api.fetch("/api/zones"); const topics_response = await api.fetch("/api/topics");
if (zones_response.ok) { if (topics_response.ok) {
const zone_list = document.getElementById("zone-list"); const topic_list = document.getElementById("topic-list");
zone_list.innerHTML = ""; topic_list.innerHTML = "";
const zones = await zones_response.json(); const topics = await topics_response.json();
for (const zone of zones) { for (const topic of topics) {
zone_list.insertAdjacentHTML( topic_list.insertAdjacentHTML(
"beforeend", "beforeend",
`<li id="zone-selector-${zone.id}" class="zone"><a href="#/chat/zone/${zone.id}">${zone.name}</a></li>`, `<li id="topic-selector-${topic.id}" class="topic"><a href="#/chat/topic/${topic.id}">${topic.name}</a></li>`,
); );
} }
last_zone_update = now; last_topic_update = now;
} }
} }
window.addEventListener("locationchange", update_chat_zones); window.addEventListener("locationchange", update_chat_topics);
function check_for_zone_in_url() { function check_for_topic_in_url() {
const user_json = document.body.dataset.user; const user_json = document.body.dataset.user;
if (!user_json) { if (!user_json) {
return; return;
@ -473,28 +473,28 @@ function check_for_zone_in_url() {
return; return;
} }
const first_zone_id = document.querySelector("li.zone")?.id.substring(14); const first_topic_id = document.querySelector("li.topic")?.id.substring(14);
// #/chat/zone/{zone_id} // #/chat/topic/{topic_id}
// ^ 12 // ^ 12
const zone_id = hash.substring(12) || first_zone_id; const topic_id = hash.substring(12) || first_topic_id;
if (!zone_id) { if (!topic_id) {
setTimeout(check_for_zone_in_url, 100); setTimeout(check_for_topic_in_url, 100);
return; return;
} }
const zone_chat_container = document.getElementById("zone-chat-container"); const topic_chat_container = document.getElementById("topic-chat-container");
if (zone_chat_container.dataset.zone_id !== zone_id) { if (topic_chat_container.dataset.topic_id !== topic_id) {
window.location.hash = `/chat/zone/${zone_id}`; window.location.hash = `/chat/topic/${topic_id}`;
zone_chat_container.dataset.zone_id = zone_id; topic_chat_container.dataset.topic_id = topic_id;
load_zone(zone_id); load_topic(topic_id);
} }
} }
window.addEventListener("locationchange", check_for_zone_in_url); window.addEventListener("locationchange", check_for_topic_in_url);
document.addEventListener("DOMContentLoaded", async () => { document.addEventListener("DOMContentLoaded", async () => {
await update_chat_zones(); await update_chat_topics();
check_for_zone_in_url(); check_for_topic_in_url();
}); });

View file

@ -2,10 +2,10 @@ import { api, API_CLIENT } from '../../../utils/api.ts';
import * as asserts from '@std/assert'; import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../helpers.ts';
import { generateTotp } from '../../../utils/totp.ts'; import { generateTotp } from '../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../models/event.ts'; import { clear_topic_events_cache } from '../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - Create', name: 'API - TOPICS - Create',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -25,7 +25,7 @@ Deno.test({
const user_info = await get_new_user(client); const user_info = await get_new_user(client);
try { try {
const _permission_denied_zone = await client.fetch('/zones', { const _permission_denied_topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
@ -36,15 +36,15 @@ Deno.test({
} }
}); });
asserts.fail('allowed creation of a zone without zone creation permissions'); asserts.fail('allowed creation of a topic without topic creation permissions');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'permission_denied'); asserts.assertEquals((error as Error).cause, 'permission_denied');
} }
await set_user_permissions(client, user_info.user, user_info.session, [...user_info.user.permissions, 'zones.create']); await set_user_permissions(client, user_info.user, user_info.session, [...user_info.user.permissions, 'topics.create']);
try { try {
const _too_long_name_zone = await client.fetch('/zones', { const _too_long_name_topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
@ -55,25 +55,25 @@ Deno.test({
} }
}); });
asserts.fail('allowed creation of a zone with an excessively long name'); asserts.fail('allowed creation of a topic with an excessively long name');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'invalid_zone_name'); asserts.assertEquals((error as Error).cause, 'invalid_topic_name');
} }
const new_zone = await client.fetch('/zones', { const new_topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
'x-totp': await generateTotp(user_info.session.secret) 'x-totp': await generateTotp(user_info.session.secret)
}, },
json: { json: {
name: 'test zone' name: 'test topic'
} }
}); });
asserts.assert(new_zone); asserts.assert(new_topic);
} finally { } finally {
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info?.server?.stop(); await test_server_info?.server?.stop();
} }

View file

@ -2,10 +2,10 @@ import { api, API_CLIENT } from '../../../utils/api.ts';
import * as asserts from '@std/assert'; import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../helpers.ts';
import { generateTotp } from '../../../utils/totp.ts'; import { generateTotp } from '../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../models/event.ts'; import { clear_topic_events_cache } from '../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - Delete', name: 'API - TOPICS - Delete',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -24,22 +24,22 @@ Deno.test({
const user_info = await get_new_user(client); const user_info = await get_new_user(client);
await set_user_permissions(client, user_info.user, user_info.session, [...user_info.user.permissions, 'zones.create']); await set_user_permissions(client, user_info.user, user_info.session, [...user_info.user.permissions, 'topics.create']);
const new_zone = await client.fetch('/zones', { const new_topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
'x-totp': await generateTotp(user_info.session.secret) 'x-totp': await generateTotp(user_info.session.secret)
}, },
json: { json: {
name: 'test delete zone' name: 'test delete topic'
} }
}); });
asserts.assert(new_zone); asserts.assert(new_topic);
const deleted_zone = await client.fetch(`/zones/${new_zone.id}`, { const deleted_topic = await client.fetch(`/topics/${new_topic.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
@ -47,9 +47,9 @@ Deno.test({
} }
}); });
asserts.assert(deleted_zone); asserts.assert(deleted_topic);
} finally { } finally {
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info?.server?.stop(); await test_server_info?.server?.stop();
} }

View file

@ -2,10 +2,10 @@ import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts';
import { api, API_CLIENT } from '../../../../utils/api.ts'; import { api, API_CLIENT } from '../../../../utils/api.ts';
import { generateTotp } from '../../../../utils/totp.ts'; import { generateTotp } from '../../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../../models/event.ts'; import { clear_topic_events_cache } from '../../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - EVENTS - Create', name: 'API - TOPICS - EVENTS - Create',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -24,25 +24,25 @@ Deno.test({
const owner_info = await get_new_user(client); const owner_info = await get_new_user(client);
await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'zones.create']); await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'topics.create']);
const zone = await client.fetch('/zones', { const topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret) 'x-totp': await generateTotp(owner_info.session.secret)
}, },
json: { json: {
name: 'test events zone', name: 'test events topic',
permissions: { permissions: {
write_events: [owner_info.user.id] write_events: [owner_info.user.id]
} }
} }
}); });
asserts.assert(zone); asserts.assert(topic);
const event_from_owner = await client.fetch(`/zones/${zone.id}/events`, { const event_from_owner = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -61,7 +61,7 @@ Deno.test({
const other_user_info = await get_new_user(client); const other_user_info = await get_new_user(client);
try { try {
const _permission_denied_zone = await client.fetch(`/zones/${zone.id}/events`, { const _permission_denied_topic = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -75,13 +75,13 @@ Deno.test({
} }
}); });
asserts.fail('allowed adding an event to a zone without permission'); asserts.fail('allowed adding an event to a topic without permission');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'permission_denied'); asserts.assertEquals((error as Error).cause, 'permission_denied');
} }
// make the zone public write // make the topic public write
const updated_by_owner_zone = await client.fetch(`/zones/${zone.id}`, { const updated_by_owner_topic = await client.fetch(`/topics/${topic.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -89,16 +89,16 @@ Deno.test({
}, },
json: { json: {
permissions: { permissions: {
...zone.permissions, ...topic.permissions,
write_events: [] write_events: []
} }
} }
}); });
asserts.assert(updated_by_owner_zone); asserts.assert(updated_by_owner_topic);
asserts.assertEquals(updated_by_owner_zone.permissions.write_events, []); asserts.assertEquals(updated_by_owner_topic.permissions.write_events, []);
const event_from_other_user = await client.fetch(`/zones/${zone.id}/events`, { const event_from_other_user = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -114,7 +114,7 @@ Deno.test({
asserts.assert(event_from_other_user); asserts.assert(event_from_other_user);
} finally { } finally {
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info?.server?.stop(); await test_server_info?.server?.stop();
} }

View file

@ -2,10 +2,10 @@ import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts';
import { api, API_CLIENT } from '../../../../utils/api.ts'; import { api, API_CLIENT } from '../../../../utils/api.ts';
import { generateTotp } from '../../../../utils/totp.ts'; import { generateTotp } from '../../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../../models/event.ts'; import { clear_topic_events_cache } from '../../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - EVENTS - Get', name: 'API - TOPICS - EVENTS - Get',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -29,25 +29,25 @@ Deno.test({
const owner_info = await get_new_user(client); const owner_info = await get_new_user(client);
await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'zones.create']); await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'topics.create']);
const zone = await client.fetch('/zones', { const topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret) 'x-totp': await generateTotp(owner_info.session.secret)
}, },
json: { json: {
name: 'test get events zone' name: 'test get events topic'
} }
}); });
asserts.assert(zone); asserts.assert(topic);
const NUM_INITIAL_EVENTS = 5; const NUM_INITIAL_EVENTS = 5;
const events_initial_batch: any[] = []; const events_initial_batch: any[] = [];
for (let i = 0; i < NUM_INITIAL_EVENTS; ++i) { for (let i = 0; i < NUM_INITIAL_EVENTS; ++i) {
const event = await client.fetch(`/zones/${zone.id}/events`, { const event = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -69,7 +69,7 @@ Deno.test({
const other_user_info = await get_new_user(client); const other_user_info = await get_new_user(client);
const events_from_server = await client.fetch(`/zones/${zone.id}/events`, { const events_from_server = await client.fetch(`/topics/${topic.id}/events`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -82,7 +82,7 @@ Deno.test({
const newest_event = events_from_server[0]; const newest_event = events_from_server[0];
asserts.assert(newest_event); asserts.assert(newest_event);
const long_poll_request_promise = client.fetch(`/zones/${zone.id}/events?wait=true&after_id=${newest_event.id}`, { const long_poll_request_promise = client.fetch(`/topics/${topic.id}/events?wait=true&after_id=${newest_event.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -92,7 +92,7 @@ Deno.test({
const wait_and_then_create_an_event = new Promise((resolve) => { const wait_and_then_create_an_event = new Promise((resolve) => {
setTimeout(async () => { setTimeout(async () => {
await client.fetch(`/zones/${zone.id}/events`, { await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -117,7 +117,7 @@ Deno.test({
asserts.assertEquals(long_polled_events[0].data?.i, 12345); asserts.assertEquals(long_polled_events[0].data?.i, 12345);
}); });
} finally { } finally {
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info.server.stop(); await test_server_info.server.stop();
} }

View file

@ -2,10 +2,10 @@ import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts';
import { api, API_CLIENT } from '../../../../utils/api.ts'; import { api, API_CLIENT } from '../../../../utils/api.ts';
import { generateTotp } from '../../../../utils/totp.ts'; import { generateTotp } from '../../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../../models/event.ts'; import { clear_topic_events_cache } from '../../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - EVENTS - Update', name: 'API - TOPICS - EVENTS - Update',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -24,22 +24,22 @@ Deno.test({
const owner_info = await get_new_user(client); const owner_info = await get_new_user(client);
await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'zones.create']); await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'topics.create']);
const zone = await client.fetch('/zones', { const topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret) 'x-totp': await generateTotp(owner_info.session.secret)
}, },
json: { json: {
name: 'test update events zone' name: 'test update events topic'
} }
}); });
asserts.assert(zone); asserts.assert(topic);
const event_from_owner = await client.fetch(`/zones/${zone.id}/events`, { const event_from_owner = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -55,7 +55,7 @@ Deno.test({
asserts.assert(event_from_owner); asserts.assert(event_from_owner);
const fetched_event_from_owner = await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { const fetched_event_from_owner = await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -65,7 +65,7 @@ Deno.test({
asserts.assertEquals(fetched_event_from_owner, event_from_owner); asserts.assertEquals(fetched_event_from_owner, event_from_owner);
const updated_event_from_owner = await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { const updated_event_from_owner = await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -83,7 +83,7 @@ Deno.test({
asserts.assertEquals(updated_event_from_owner.type, 'other'); asserts.assertEquals(updated_event_from_owner.type, 'other');
asserts.assertEquals(updated_event_from_owner.data.foo, 'baz'); asserts.assertEquals(updated_event_from_owner.data.foo, 'baz');
const fetched_updated_event_from_owner = await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { const fetched_updated_event_from_owner = await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -97,7 +97,7 @@ Deno.test({
const other_user_info = await get_new_user(client); const other_user_info = await get_new_user(client);
const event_from_other_user = await client.fetch(`/zones/${zone.id}/events`, { const event_from_other_user = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -113,7 +113,7 @@ Deno.test({
asserts.assert(event_from_other_user); asserts.assert(event_from_other_user);
const fetched_event_from_other_user = await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { const fetched_event_from_other_user = await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -123,7 +123,7 @@ Deno.test({
asserts.assertEquals(fetched_event_from_other_user, event_from_other_user); asserts.assertEquals(fetched_event_from_other_user, event_from_other_user);
const updated_event_from_other_user = await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { const updated_event_from_other_user = await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -141,7 +141,7 @@ Deno.test({
asserts.assertEquals(updated_event_from_other_user.type, 'other'); asserts.assertEquals(updated_event_from_other_user.type, 'other');
asserts.assertEquals(updated_event_from_other_user.data.other_user, 'bloop'); asserts.assertEquals(updated_event_from_other_user.data.other_user, 'bloop');
const fetched_updated_event_from_other_user = await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { const fetched_updated_event_from_other_user = await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -153,7 +153,7 @@ Deno.test({
asserts.assertNotEquals(fetched_updated_event_from_other_user, fetched_event_from_other_user); asserts.assertNotEquals(fetched_updated_event_from_other_user, fetched_event_from_other_user);
asserts.assertEquals(fetched_updated_event_from_other_user, updated_event_from_other_user); asserts.assertEquals(fetched_updated_event_from_other_user, updated_event_from_other_user);
const updated_by_owner_zone = await client.fetch(`/zones/${zone.id}`, { const updated_by_owner_topic = await client.fetch(`/topics/${topic.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -161,16 +161,16 @@ Deno.test({
}, },
json: { json: {
permissions: { permissions: {
...zone.permissions, ...topic.permissions,
write_events: [owner_info.user.id] write_events: [owner_info.user.id]
} }
} }
}); });
asserts.assertEquals(updated_by_owner_zone.permissions.write_events, [owner_info.user.id]); asserts.assertEquals(updated_by_owner_topic.permissions.write_events, [owner_info.user.id]);
try { try {
await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -181,13 +181,13 @@ Deno.test({
} }
}); });
asserts.fail('allowed updating an event in a zone with a write_events allowed only by owner'); asserts.fail('allowed updating an event in a topic with a write_events allowed only by owner');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'permission_denied'); asserts.assertEquals((error as Error).cause, 'permission_denied');
} }
try { try {
await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -195,12 +195,12 @@ Deno.test({
} }
}); });
asserts.fail('allowed deleting an event in a zone with a write_events allowed only by owner'); asserts.fail('allowed deleting an event in a topic with a write_events allowed only by owner');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'permission_denied'); asserts.assertEquals((error as Error).cause, 'permission_denied');
} }
const publicly_writable_zone = await client.fetch(`/zones/${zone.id}`, { const publicly_writable_topic = await client.fetch(`/topics/${topic.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -208,15 +208,15 @@ Deno.test({
}, },
json: { json: {
permissions: { permissions: {
...zone.permissions, ...topic.permissions,
write_events: [] write_events: []
} }
} }
}); });
asserts.assertEquals(publicly_writable_zone.permissions.write_events, []); asserts.assertEquals(publicly_writable_topic.permissions.write_events, []);
const delete_other_user_event_response = await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { const delete_other_user_event_response = await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -226,7 +226,7 @@ Deno.test({
asserts.assertEquals(delete_other_user_event_response.deleted, true); asserts.assertEquals(delete_other_user_event_response.deleted, true);
const delete_owner_event_response = await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { const delete_owner_event_response = await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -236,7 +236,7 @@ Deno.test({
asserts.assertEquals(delete_owner_event_response.deleted, true); asserts.assertEquals(delete_owner_event_response.deleted, true);
} finally { } finally {
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info?.server?.stop(); await test_server_info?.server?.stop();
} }

View file

@ -2,10 +2,10 @@ import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts';
import { api, API_CLIENT } from '../../../../utils/api.ts'; import { api, API_CLIENT } from '../../../../utils/api.ts';
import { generateTotp } from '../../../../utils/totp.ts'; import { generateTotp } from '../../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../../models/event.ts'; import { clear_topic_events_cache } from '../../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - EVENTS - Update (APPEND_ONLY_EVENTS)', name: 'API - TOPICS - EVENTS - Update (APPEND_ONLY_EVENTS)',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -27,22 +27,22 @@ Deno.test({
const owner_info = await get_new_user(client); const owner_info = await get_new_user(client);
await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'zones.create']); await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'topics.create']);
const zone = await client.fetch('/zones', { const topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret) 'x-totp': await generateTotp(owner_info.session.secret)
}, },
json: { json: {
name: 'test update events zone in append only mode' name: 'test update events topic in append only mode'
} }
}); });
asserts.assert(zone); asserts.assert(topic);
const event_from_owner = await client.fetch(`/zones/${zone.id}/events`, { const event_from_owner = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -58,7 +58,7 @@ Deno.test({
asserts.assert(event_from_owner); asserts.assert(event_from_owner);
const fetched_event_from_owner = await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { const fetched_event_from_owner = await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -69,7 +69,7 @@ Deno.test({
asserts.assertEquals(fetched_event_from_owner, event_from_owner); asserts.assertEquals(fetched_event_from_owner, event_from_owner);
try { try {
await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -80,13 +80,13 @@ Deno.test({
} }
}); });
asserts.fail('allowed updating an event in a zone with APPEND_ONLY_EVENTS on'); asserts.fail('allowed updating an event in a topic with APPEND_ONLY_EVENTS on');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'append_only_events'); asserts.assertEquals((error as Error).cause, 'append_only_events');
} }
try { try {
await client.fetch(`/zones/${zone.id}/events/${event_from_owner.id}`, { await client.fetch(`/topics/${topic.id}/events/${event_from_owner.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'x-session_id': owner_info.session.id, 'x-session_id': owner_info.session.id,
@ -94,14 +94,14 @@ Deno.test({
} }
}); });
asserts.fail('allowed deleting an event in a zone with APPEND_ONLY_EVENTS on'); asserts.fail('allowed deleting an event in a topic with APPEND_ONLY_EVENTS on');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'append_only_events'); asserts.assertEquals((error as Error).cause, 'append_only_events');
} }
const other_user_info = await get_new_user(client); const other_user_info = await get_new_user(client);
const event_from_other_user = await client.fetch(`/zones/${zone.id}/events`, { const event_from_other_user = await client.fetch(`/topics/${topic.id}/events`, {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -117,7 +117,7 @@ Deno.test({
asserts.assert(event_from_other_user); asserts.assert(event_from_other_user);
const fetched_event_from_other_user = await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { const fetched_event_from_other_user = await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -128,7 +128,7 @@ Deno.test({
asserts.assertEquals(fetched_event_from_other_user, event_from_other_user); asserts.assertEquals(fetched_event_from_other_user, event_from_other_user);
try { try {
await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -139,13 +139,13 @@ Deno.test({
} }
}); });
asserts.fail('allowed updating an event in a zone with APPEND_ONLY_EVENTS on'); asserts.fail('allowed updating an event in a topic with APPEND_ONLY_EVENTS on');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'append_only_events'); asserts.assertEquals((error as Error).cause, 'append_only_events');
} }
try { try {
await client.fetch(`/zones/${zone.id}/events/${event_from_other_user.id}`, { await client.fetch(`/topics/${topic.id}/events/${event_from_other_user.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -153,14 +153,14 @@ Deno.test({
} }
}); });
asserts.fail('allowed deleting an event in a zone with APPEND_ONLY_EVENTS on'); asserts.fail('allowed deleting an event in a topic with APPEND_ONLY_EVENTS on');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'append_only_events'); asserts.assertEquals((error as Error).cause, 'append_only_events');
} }
} finally { } finally {
Deno.env.delete('APPEND_ONLY_EVENTS'); Deno.env.delete('APPEND_ONLY_EVENTS');
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info?.server?.stop(); await test_server_info?.server?.stop();
} }

View file

@ -2,10 +2,10 @@ import { api, API_CLIENT } from '../../../utils/api.ts';
import * as asserts from '@std/assert'; import * as asserts from '@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../helpers.ts'; import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../helpers.ts';
import { generateTotp } from '../../../utils/totp.ts'; import { generateTotp } from '../../../utils/totp.ts';
import { clear_zone_events_cache } from '../../../models/event.ts'; import { clear_topic_events_cache } from '../../../models/event.ts';
Deno.test({ Deno.test({
name: 'API - ZONES - Update', name: 'API - TOPICS - Update',
permissions: { permissions: {
env: true, env: true,
read: true, read: true,
@ -24,25 +24,25 @@ Deno.test({
const user_info = await get_new_user(client); const user_info = await get_new_user(client);
await set_user_permissions(client, user_info.user, user_info.session, [...user_info.user.permissions, 'zones.create']); await set_user_permissions(client, user_info.user, user_info.session, [...user_info.user.permissions, 'topics.create']);
const new_zone = await client.fetch('/zones', { const new_topic = await client.fetch('/topics', {
method: 'POST', method: 'POST',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
'x-totp': await generateTotp(user_info.session.secret) 'x-totp': await generateTotp(user_info.session.secret)
}, },
json: { json: {
name: 'test update zone' name: 'test update topic'
} }
}); });
asserts.assert(new_zone); asserts.assert(new_topic);
const other_user_info = await get_new_user(client); const other_user_info = await get_new_user(client);
try { try {
const _permission_denied_zone = await client.fetch(`/zones/${new_zone.id}`, { const _permission_denied_topic = await client.fetch(`/topics/${new_topic.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -53,12 +53,12 @@ Deno.test({
} }
}); });
asserts.fail('allowed updating a zone owned by someone else'); asserts.fail('allowed updating a topic owned by someone else');
} catch (error) { } catch (error) {
asserts.assertEquals((error as Error).cause, 'permission_denied'); asserts.assertEquals((error as Error).cause, 'permission_denied');
} }
const updated_by_owner_zone = await client.fetch(`/zones/${new_zone.id}`, { const updated_by_owner_topic = await client.fetch(`/topics/${new_topic.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': user_info.session.id, 'x-session_id': user_info.session.id,
@ -67,17 +67,17 @@ Deno.test({
json: { json: {
topic: 'this is a new topic', topic: 'this is a new topic',
permissions: { permissions: {
...new_zone.permissions, ...new_topic.permissions,
write: [...new_zone.permissions.write, other_user_info.user.id] write: [...new_topic.permissions.write, other_user_info.user.id]
} }
} }
}); });
asserts.assert(updated_by_owner_zone); asserts.assert(updated_by_owner_topic);
asserts.assertEquals(updated_by_owner_zone.topic, 'this is a new topic'); asserts.assertEquals(updated_by_owner_topic.topic, 'this is a new topic');
asserts.assertEquals(updated_by_owner_zone.permissions.write, [user_info.user.id, other_user_info.user.id]); asserts.assertEquals(updated_by_owner_topic.permissions.write, [user_info.user.id, other_user_info.user.id]);
const updated_by_other_user_zone = await client.fetch(`/zones/${new_zone.id}`, { const updated_by_other_user_topic = await client.fetch(`/topics/${new_topic.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'x-session_id': other_user_info.session.id, 'x-session_id': other_user_info.session.id,
@ -88,11 +88,11 @@ Deno.test({
} }
}); });
asserts.assert(updated_by_other_user_zone); asserts.assert(updated_by_other_user_topic);
asserts.assertEquals(updated_by_other_user_zone.topic, 'this is a newer topic'); asserts.assertEquals(updated_by_other_user_topic.topic, 'this is a newer topic');
asserts.assertEquals(updated_by_other_user_zone.permissions.write, [user_info.user.id, other_user_info.user.id]); asserts.assertEquals(updated_by_other_user_topic.permissions.write, [user_info.user.id, other_user_info.user.id]);
} finally { } finally {
clear_zone_events_cache(); clear_topic_events_cache();
if (test_server_info) { if (test_server_info) {
await test_server_info?.server?.stop(); await test_server_info?.server?.stop();
} }