@crombolo/data 0.34.0 → 0.36.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/cluster.ts +72 -8
- package/src/index.ts +6 -0
- package/src/repositories/documents.ts +91 -28
- package/src/repositories/media-access.ts +473 -0
- package/src/repositories/media-listing.ts +216 -0
- package/src/repositories/nodes.ts +13 -2
- package/src/schema/media-access.ts +106 -0
- package/src/schema/media-cache.ts +27 -0
- package/src/schema/media-member-grants.ts +23 -0
- package/src/schema/media-member-uploads.ts +26 -0
- package/src/schema/plan.ts +8 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/data",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.36.2",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -28,6 +28,6 @@
|
|
|
28
28
|
"access": "public"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@crombolo/core": "0.
|
|
31
|
+
"@crombolo/core": "0.36.2"
|
|
32
32
|
}
|
|
33
33
|
}
|
package/src/cluster.ts
CHANGED
|
@@ -22,6 +22,68 @@ export interface CacheInstruction {
|
|
|
22
22
|
checkpoint: number | null
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* What a media change touched (story 197), as a `content` instruction carries
|
|
27
|
+
* it: `{ media: [keys], moved?: [paths] }`. `moved` holds the old paths
|
|
28
|
+
* (`-1,1050`) of items that moved, so the items below them are dropped too.
|
|
29
|
+
*/
|
|
30
|
+
export interface MediaChangePayload {
|
|
31
|
+
media: string[]
|
|
32
|
+
moved?: string[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What an instruction changes: the page snapshot, and the media cache. */
|
|
36
|
+
export interface InstructionEffects {
|
|
37
|
+
pages: boolean
|
|
38
|
+
media: 'keep' | 'clear' | { keys: string[]; moved: string[] }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Payload fields that change only what the page snapshot holds. */
|
|
42
|
+
const PAGE_ONLY = new Set(['key', 'redirects', 'domains', 'dictionary', 'elements', 'urls'])
|
|
43
|
+
|
|
44
|
+
const strings = (value: unknown): string[] | undefined =>
|
|
45
|
+
Array.isArray(value) && value.every((v) => typeof v === 'string')
|
|
46
|
+
? (value as string[])
|
|
47
|
+
: undefined
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* What an instruction asks of a node's caches (story 197). A media change names
|
|
51
|
+
* its items and leaves the pages alone; a page change leaves media alone; a
|
|
52
|
+
* schema change, a bulk change such as an import, or anything not recognised
|
|
53
|
+
* empties both, which is never wrong, only slower. Pure.
|
|
54
|
+
*/
|
|
55
|
+
export function instructionEffects(
|
|
56
|
+
kind: CacheInstructionKind,
|
|
57
|
+
payload: Record<string, unknown>,
|
|
58
|
+
): InstructionEffects {
|
|
59
|
+
if (kind === 'components') return { pages: false, media: 'keep' }
|
|
60
|
+
if (kind === 'schema') return { pages: true, media: 'clear' }
|
|
61
|
+
const fields = Object.keys(payload)
|
|
62
|
+
const keys = strings(payload.media)
|
|
63
|
+
if (keys) {
|
|
64
|
+
const pages = fields.some((field) => field !== 'media' && field !== 'moved')
|
|
65
|
+
return { pages, media: { keys, moved: strings(payload.moved) ?? [] } }
|
|
66
|
+
}
|
|
67
|
+
if (payload.media === true)
|
|
68
|
+
return { pages: fields.some((field) => field !== 'media'), media: 'clear' }
|
|
69
|
+
const pagesOnly = fields.length > 0 && fields.every((field) => PAGE_ONLY.has(field))
|
|
70
|
+
return { pages: true, media: pagesOnly ? 'keep' : 'clear' }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The instructions numbered after `after` up to `upTo`, in checkpoint order: what a node missed. */
|
|
74
|
+
export async function instructionsBetween(
|
|
75
|
+
db: Db,
|
|
76
|
+
after: number,
|
|
77
|
+
upTo: number,
|
|
78
|
+
): Promise<CacheInstruction[]> {
|
|
79
|
+
const rows = await db.query(
|
|
80
|
+
`SELECT id, kind, payload, created_by, checkpoint FROM cache_instruction
|
|
81
|
+
WHERE checkpoint > ? AND checkpoint <= ? ORDER BY checkpoint`,
|
|
82
|
+
[after, upTo],
|
|
83
|
+
)
|
|
84
|
+
return rows.map(instructionOf)
|
|
85
|
+
}
|
|
86
|
+
|
|
25
87
|
/** Where Postgres says an instruction was written, so nodes poll now rather than on their timer. */
|
|
26
88
|
export const CACHE_INSTRUCTION_CHANNEL = 'crombolo_cache_instruction'
|
|
27
89
|
|
|
@@ -128,16 +190,18 @@ export async function cacheInstructionsAfter(db: Db, afterId: number): Promise<C
|
|
|
128
190
|
'SELECT id, kind, payload, created_by, checkpoint FROM cache_instruction WHERE id > ? ORDER BY id',
|
|
129
191
|
[afterId],
|
|
130
192
|
)
|
|
131
|
-
return rows.map(
|
|
132
|
-
id: Number(row.id),
|
|
133
|
-
kind: String(row.kind) as CacheInstructionKind,
|
|
134
|
-
payload: row.payload ? (JSON.parse(String(row.payload)) as Record<string, unknown>) : {},
|
|
135
|
-
createdBy: (row.created_by as string | null) ?? null,
|
|
136
|
-
checkpoint:
|
|
137
|
-
row.checkpoint === null || row.checkpoint === undefined ? null : Number(row.checkpoint),
|
|
138
|
-
}))
|
|
193
|
+
return rows.map(instructionOf)
|
|
139
194
|
}
|
|
140
195
|
|
|
196
|
+
const instructionOf = (row: Record<string, unknown>): CacheInstruction => ({
|
|
197
|
+
id: Number(row.id),
|
|
198
|
+
kind: String(row.kind) as CacheInstructionKind,
|
|
199
|
+
payload: row.payload ? (JSON.parse(String(row.payload)) as Record<string, unknown>) : {},
|
|
200
|
+
createdBy: (row.created_by as string | null) ?? null,
|
|
201
|
+
checkpoint:
|
|
202
|
+
row.checkpoint === null || row.checkpoint === undefined ? null : Number(row.checkpoint),
|
|
203
|
+
})
|
|
204
|
+
|
|
141
205
|
export interface ServerIdentity {
|
|
142
206
|
nodeId: string
|
|
143
207
|
version: string
|
package/src/index.ts
CHANGED
|
@@ -31,6 +31,8 @@ export * from './repositories/form-entries.ts'
|
|
|
31
31
|
export * from './repositories/form-workflows.ts'
|
|
32
32
|
export * from './repositories/languages.ts'
|
|
33
33
|
export * from './repositories/log-searches.ts'
|
|
34
|
+
export * from './repositories/media-access.ts'
|
|
35
|
+
export * from './repositories/media-listing.ts'
|
|
34
36
|
export * from './repositories/members.ts'
|
|
35
37
|
export * from './repositories/nodes.ts'
|
|
36
38
|
export * from './repositories/notifications.ts'
|
|
@@ -72,6 +74,10 @@ export * from './schema/form-permission-prefix.ts'
|
|
|
72
74
|
export * from './schema/group-permissions.ts'
|
|
73
75
|
export * from './schema/identity.ts'
|
|
74
76
|
export * from './schema/log-viewer.ts'
|
|
77
|
+
export * from './schema/media-access.ts'
|
|
78
|
+
export * from './schema/media-cache.ts'
|
|
79
|
+
export * from './schema/media-member-grants.ts'
|
|
80
|
+
export * from './schema/media-member-uploads.ts'
|
|
75
81
|
export * from './schema/media-permissions.ts'
|
|
76
82
|
export * from './schema/member-property-type.ts'
|
|
77
83
|
export * from './schema/members.ts'
|
|
@@ -15,9 +15,11 @@ import {
|
|
|
15
15
|
type DocumentVariant,
|
|
16
16
|
type DocumentVersionSummary,
|
|
17
17
|
variesByCulture as flagVariesByCulture,
|
|
18
|
+
type MediaItemAccess,
|
|
18
19
|
normaliseUuid,
|
|
19
20
|
ObjectTypes,
|
|
20
21
|
type Page,
|
|
22
|
+
parseMediaPolicy,
|
|
21
23
|
STORAGE_COLUMN,
|
|
22
24
|
SystemNodes,
|
|
23
25
|
toEditorValue,
|
|
@@ -37,6 +39,7 @@ import {
|
|
|
37
39
|
visibleStateIdFor,
|
|
38
40
|
} from '../schema-state.ts'
|
|
39
41
|
import { queueForSearch } from '../search.ts'
|
|
42
|
+
import { recordFiles } from './media-access.ts'
|
|
40
43
|
import { NodeRepository, type NodeRow } from './nodes.ts'
|
|
41
44
|
|
|
42
45
|
export type EventKind = 'save' | 'publish' | 'rollback' | 'migrate'
|
|
@@ -312,6 +315,28 @@ export function publishedValueRows<
|
|
|
312
315
|
return [...chosen.values()]
|
|
313
316
|
}
|
|
314
317
|
|
|
318
|
+
/** Which nodes `loadCurrent` reads: by key, by id, or by the file address a media item serves. */
|
|
319
|
+
export type CurrentFilter =
|
|
320
|
+
| { keys: readonly string[]; ids?: undefined; urls?: undefined }
|
|
321
|
+
| { ids: readonly number[]; keys?: undefined; urls?: undefined }
|
|
322
|
+
| { urls: readonly string[]; keys?: undefined; ids?: undefined }
|
|
323
|
+
|
|
324
|
+
/** A node as an editor sees it now. */
|
|
325
|
+
export interface CurrentNodeRow {
|
|
326
|
+
id: number
|
|
327
|
+
key: string
|
|
328
|
+
name: string
|
|
329
|
+
contentTypeAlias: string
|
|
330
|
+
values: DocumentValue[]
|
|
331
|
+
parentId: number
|
|
332
|
+
path: string
|
|
333
|
+
sortOrder: number
|
|
334
|
+
createDate: Date
|
|
335
|
+
updateDate: Date
|
|
336
|
+
/** A media item's own read and write settings (story 196); `inherit` for anything else. */
|
|
337
|
+
access: MediaItemAccess
|
|
338
|
+
}
|
|
339
|
+
|
|
315
340
|
/** Ids in slices small enough for either dialect's parameter limit. */
|
|
316
341
|
const slices = <T>(items: readonly T[], size = 500): T[][] =>
|
|
317
342
|
Array.from({ length: Math.ceil(items.length / size) }, (_, n) =>
|
|
@@ -524,40 +549,55 @@ export class DocumentRepository {
|
|
|
524
549
|
}
|
|
525
550
|
|
|
526
551
|
/**
|
|
527
|
-
*
|
|
528
|
-
*
|
|
529
|
-
*
|
|
552
|
+
* The nodes of this kind not in the bin, with the values an editor sees now:
|
|
553
|
+
* what media is read as, having no publish. Without a filter every one, read
|
|
554
|
+
* in slices like `loadPublished`; with one, only the nodes it names — by key,
|
|
555
|
+
* id or (media) file address — through indexed lookups, in the order asked.
|
|
530
556
|
*/
|
|
531
|
-
async loadCurrent(): Promise<
|
|
532
|
-
Array<{
|
|
533
|
-
id: number
|
|
534
|
-
key: string
|
|
535
|
-
name: string
|
|
536
|
-
contentTypeAlias: string
|
|
537
|
-
values: DocumentValue[]
|
|
538
|
-
parentId: number
|
|
539
|
-
sortOrder: number
|
|
540
|
-
createDate: Date
|
|
541
|
-
updateDate: Date
|
|
542
|
-
}>
|
|
543
|
-
> {
|
|
557
|
+
async loadCurrent(filter?: CurrentFilter): Promise<CurrentNodeRow[]> {
|
|
544
558
|
const t = this.#db.dialect.boolValue(true)
|
|
545
|
-
const
|
|
546
|
-
`SELECT n.id, n.unique_id, n.text, n.parent_id, n.sort_order, n.create_date,
|
|
559
|
+
const select = `SELECT n.id, n.unique_id, n.text, n.parent_id, n.path, n.sort_order, n.create_date,
|
|
547
560
|
head.text AS draft_name, head.version_date,
|
|
548
|
-
ct.alias AS content_type_alias, c.content_type_id
|
|
561
|
+
ct.alias AS content_type_alias, c.content_type_id,
|
|
562
|
+
c.read_policy, c.write_policy, c.creator_member_key, c.file_url
|
|
549
563
|
FROM node n
|
|
550
564
|
JOIN content c ON c.node_id = n.id
|
|
551
565
|
JOIN content_type ct ON ct.node_id = c.content_type_id
|
|
552
566
|
JOIN content_version head ON head.node_id = n.id AND head.current = ?
|
|
553
|
-
WHERE n.node_object_type = ? AND n.trashed =
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
)
|
|
567
|
+
WHERE n.node_object_type = ? AND n.trashed = ?`
|
|
568
|
+
const base = [t, this.objectType, this.#db.dialect.boolValue(false)]
|
|
569
|
+
let rows: Record<string, unknown>[]
|
|
570
|
+
if (!filter) rows = await this.#db.query(`${select} ORDER BY n.level, n.sort_order, n.id`, base)
|
|
571
|
+
else {
|
|
572
|
+
const [column, wanted] =
|
|
573
|
+
filter.keys !== undefined
|
|
574
|
+
? ['n.unique_id', [...new Set(filter.keys.map(normaliseUuid))]]
|
|
575
|
+
: filter.ids !== undefined
|
|
576
|
+
? ['n.id', [...new Set(filter.ids)]]
|
|
577
|
+
: ['c.file_url', [...new Set(filter.urls ?? [])]]
|
|
578
|
+
rows = []
|
|
579
|
+
for (const slice of slices<string | number>(wanted))
|
|
580
|
+
rows.push(
|
|
581
|
+
...(await this.#db.query(
|
|
582
|
+
`${select} AND ${column} IN (${slice.map(() => '?').join(', ')})`,
|
|
583
|
+
[...base, ...slice],
|
|
584
|
+
)),
|
|
585
|
+
)
|
|
586
|
+
const order = new Map(wanted.map((value, index) => [String(value), index]))
|
|
587
|
+
const at = (row: Record<string, unknown>) =>
|
|
588
|
+
order.get(
|
|
589
|
+
column === 'n.unique_id'
|
|
590
|
+
? normaliseUuid(String(row.unique_id))
|
|
591
|
+
: column === 'n.id'
|
|
592
|
+
? String(Number(row.id))
|
|
593
|
+
: String(row.file_url),
|
|
594
|
+
) ?? 0
|
|
595
|
+
rows.sort((a, b) => at(a) - at(b) || Number(a.id) - Number(b.id))
|
|
596
|
+
}
|
|
557
597
|
const languages = await this.#languages()
|
|
558
598
|
const typesById = new Map<number, PropertyTypeRow[]>()
|
|
559
599
|
const rowsById = await this.#currentValueRowsFor(rows.map((row) => Number(row.id)))
|
|
560
|
-
const out = []
|
|
600
|
+
const out: CurrentNodeRow[] = []
|
|
561
601
|
for (const row of rows) {
|
|
562
602
|
const typeId = Number(row.content_type_id)
|
|
563
603
|
if (!typesById.has(typeId)) typesById.set(typeId, await this.#propertyTypes(typeId))
|
|
@@ -568,10 +608,18 @@ export class DocumentRepository {
|
|
|
568
608
|
name: String(row.draft_name ?? row.text ?? ''),
|
|
569
609
|
contentTypeAlias: String(row.content_type_alias),
|
|
570
610
|
parentId: Number(row.parent_id),
|
|
611
|
+
path: String(row.path),
|
|
571
612
|
sortOrder: Number(row.sort_order),
|
|
572
613
|
createDate: DbDate.fromDb(row.create_date) ?? new Date(0),
|
|
573
614
|
updateDate:
|
|
574
615
|
DbDate.fromDb(row.version_date) ?? DbDate.fromDb(row.create_date) ?? new Date(0),
|
|
616
|
+
access: {
|
|
617
|
+
readPolicy: parseMediaPolicy(row.read_policy),
|
|
618
|
+
writePolicy: parseMediaPolicy(row.write_policy),
|
|
619
|
+
creatorMemberKey: row.creator_member_key
|
|
620
|
+
? normaliseUuid(String(row.creator_member_key))
|
|
621
|
+
: null,
|
|
622
|
+
},
|
|
575
623
|
values:
|
|
576
624
|
propertyTypes.length === 0
|
|
577
625
|
? []
|
|
@@ -740,6 +788,7 @@ export class DocumentRepository {
|
|
|
740
788
|
|
|
741
789
|
const created = await repo.#load({ ...node, text: name })
|
|
742
790
|
if (!created) throw new Error('Document could not be read back after creation.')
|
|
791
|
+
await recordFiles(tx, this.kind, node.id, created)
|
|
743
792
|
return created
|
|
744
793
|
}),
|
|
745
794
|
)
|
|
@@ -911,7 +960,9 @@ export class DocumentRepository {
|
|
|
911
960
|
await repo.#appendValues(node.id, eventId, state, contentTypeNodeId, input.values)
|
|
912
961
|
await repo.#writeCultureVariations(node.id, eventId, input.variants)
|
|
913
962
|
await repo.#recomputeEdited(node.id)
|
|
914
|
-
|
|
963
|
+
const saved = await repo.#load({ ...node, text: name })
|
|
964
|
+
if (saved) await recordFiles(tx, this.kind, node.id, saved)
|
|
965
|
+
return saved
|
|
915
966
|
})
|
|
916
967
|
}
|
|
917
968
|
|
|
@@ -1189,7 +1240,9 @@ export class DocumentRepository {
|
|
|
1189
1240
|
await repo.#copyCultureVariations(targetId, eventId)
|
|
1190
1241
|
await repo.nodes.rename(node.id, name)
|
|
1191
1242
|
await repo.#recomputeEdited(node.id)
|
|
1192
|
-
|
|
1243
|
+
const restored = await repo.#load({ ...node, text: name })
|
|
1244
|
+
if (restored) await recordFiles(tx, this.kind, node.id, restored)
|
|
1245
|
+
return restored
|
|
1193
1246
|
})
|
|
1194
1247
|
}
|
|
1195
1248
|
|
|
@@ -1277,6 +1330,12 @@ export class DocumentRepository {
|
|
|
1277
1330
|
await tx.exec('DELETE FROM content_schedule WHERE node_id = ?', [row])
|
|
1278
1331
|
await tx.exec('DELETE FROM user_notification WHERE node_id = ?', [row])
|
|
1279
1332
|
await tx.exec('DELETE FROM domain WHERE node_id = ?', [row])
|
|
1333
|
+
await tx.exec(
|
|
1334
|
+
'DELETE FROM media_access_rule WHERE media_access_id IN (SELECT id FROM media_access WHERE node_id = ?)',
|
|
1335
|
+
[row],
|
|
1336
|
+
)
|
|
1337
|
+
await tx.exec('DELETE FROM media_access WHERE node_id = ?', [row])
|
|
1338
|
+
await tx.exec('DELETE FROM node_file WHERE node_id = ?', [row])
|
|
1280
1339
|
await tx.exec(
|
|
1281
1340
|
'DELETE FROM content_version_culture_variation WHERE version_id IN (SELECT id FROM content_version WHERE node_id = ?)',
|
|
1282
1341
|
[row],
|
|
@@ -2554,9 +2613,13 @@ export class DocumentRepository {
|
|
|
2554
2613
|
return (await this.#nodes.byId(Number(parentId)))?.key ?? null
|
|
2555
2614
|
}
|
|
2556
2615
|
|
|
2557
|
-
/** Other nodes drop their published cache when they see this. */
|
|
2616
|
+
/** Other nodes drop their published cache when they see this; media, only that item (story 197). */
|
|
2558
2617
|
async #instructContent(key: string): Promise<void> {
|
|
2559
|
-
await appendCacheInstruction(this.#db, {
|
|
2618
|
+
await appendCacheInstruction(this.#db, {
|
|
2619
|
+
kind: 'content',
|
|
2620
|
+
payload: this.objectType === ObjectTypes.Media ? { media: [key] } : { key },
|
|
2621
|
+
by: this.#nodeId,
|
|
2622
|
+
})
|
|
2560
2623
|
}
|
|
2561
2624
|
|
|
2562
2625
|
async #insertEvent(
|
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may read and change media (story 196): a rule on a folder or item, and
|
|
3
|
+
* each item's own policies and creator. docs/media.md, "Protected media".
|
|
4
|
+
*
|
|
5
|
+
* Rules are few — one per folder given permissions — so the nearest one is
|
|
6
|
+
* found from `node.path`, as `PublicAccessRepository.entryFor` finds a page's.
|
|
7
|
+
* An item's settings are columns on its `content` row, so a library of
|
|
8
|
+
* millions of files holds no rule rows for them.
|
|
9
|
+
*/
|
|
10
|
+
import {
|
|
11
|
+
type DocumentAggregate,
|
|
12
|
+
type DocumentValue,
|
|
13
|
+
FILE_VALUE_EDITORS,
|
|
14
|
+
type MediaItemAccess,
|
|
15
|
+
type MediaPolicy,
|
|
16
|
+
type MediaRule,
|
|
17
|
+
mediaFileOf,
|
|
18
|
+
NEW_MEDIA_READ,
|
|
19
|
+
NEW_MEDIA_WRITE,
|
|
20
|
+
type NewMediaRead,
|
|
21
|
+
type NewMediaWrite,
|
|
22
|
+
normaliseUuid,
|
|
23
|
+
ObjectTypes,
|
|
24
|
+
parseMediaPolicy,
|
|
25
|
+
stampedPolicies,
|
|
26
|
+
} from '@crombolo/core'
|
|
27
|
+
import type { Db } from '../database.ts'
|
|
28
|
+
import { DbDate, fromDbBool } from '../dialect.ts'
|
|
29
|
+
import { NodeRepository, type NodeRow } from './nodes.ts'
|
|
30
|
+
|
|
31
|
+
export interface MediaAccessGroup {
|
|
32
|
+
name: string
|
|
33
|
+
read: boolean
|
|
34
|
+
write: boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface MediaAccessMember {
|
|
38
|
+
key: string
|
|
39
|
+
read: boolean
|
|
40
|
+
write: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A rule as it is set on one folder or item. */
|
|
44
|
+
export interface MediaAccessInput {
|
|
45
|
+
nodeKey: string
|
|
46
|
+
publicRead: boolean
|
|
47
|
+
groups: readonly MediaAccessGroup[]
|
|
48
|
+
members?: readonly MediaAccessMember[]
|
|
49
|
+
newRead: NewMediaRead | null
|
|
50
|
+
newWrite: NewMediaWrite | null
|
|
51
|
+
/** File types a member may upload below (story 198); none when absent. */
|
|
52
|
+
memberTypes?: readonly string[]
|
|
53
|
+
memberMaxBytes?: number | null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface MediaAccessEntry extends MediaAccessInput {
|
|
57
|
+
nodeId: number
|
|
58
|
+
groups: MediaAccessGroup[]
|
|
59
|
+
memberTypes: string[]
|
|
60
|
+
memberMaxBytes: number | null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The item a `/media/…` path names, with what decides who may read it. */
|
|
64
|
+
export interface MediaByUrl {
|
|
65
|
+
id: number
|
|
66
|
+
key: string
|
|
67
|
+
path: string
|
|
68
|
+
trashed: boolean
|
|
69
|
+
access: MediaItemAccess
|
|
70
|
+
rule: MediaRule | undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A rule in the shape `memberMay` reads. Pure. */
|
|
74
|
+
export const ruleOf = (entry: MediaAccessEntry): MediaRule => ({
|
|
75
|
+
nodeId: entry.nodeId,
|
|
76
|
+
publicRead: entry.publicRead,
|
|
77
|
+
readGroups: entry.groups.filter((g) => g.read).map((g) => g.name),
|
|
78
|
+
writeGroups: entry.groups.filter((g) => g.write).map((g) => g.name),
|
|
79
|
+
readMembers: entry.members?.filter((m) => m.read).map((m) => m.key),
|
|
80
|
+
writeMembers: entry.members?.filter((m) => m.write).map((m) => m.key),
|
|
81
|
+
newRead: entry.newRead,
|
|
82
|
+
newWrite: entry.newWrite,
|
|
83
|
+
memberTypes: entry.memberTypes,
|
|
84
|
+
memberMaxBytes: entry.memberMaxBytes,
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
/** A stored list of member file types: lowercase names, each once. Pure. */
|
|
88
|
+
export const memberTypesOf = (value: unknown): string[] =>
|
|
89
|
+
typeof value === 'string'
|
|
90
|
+
? [
|
|
91
|
+
...new Set(
|
|
92
|
+
value
|
|
93
|
+
.split(',')
|
|
94
|
+
.map((name) => name.trim().toLowerCase())
|
|
95
|
+
.filter(Boolean),
|
|
96
|
+
),
|
|
97
|
+
]
|
|
98
|
+
: []
|
|
99
|
+
|
|
100
|
+
const storedTypes = (types: readonly string[] | undefined): string | null => {
|
|
101
|
+
const list = memberTypesOf((types ?? []).join(','))
|
|
102
|
+
return list.length > 0 ? list.join(',') : null
|
|
103
|
+
}
|
|
104
|
+
const storedBytes = (bytes: number | null | undefined): number | null =>
|
|
105
|
+
typeof bytes === 'number' && Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : null
|
|
106
|
+
|
|
107
|
+
const newRead = (value: unknown): NewMediaRead | null =>
|
|
108
|
+
NEW_MEDIA_READ.includes(value as NewMediaRead) ? (value as NewMediaRead) : null
|
|
109
|
+
const newWrite = (value: unknown): NewMediaWrite | null =>
|
|
110
|
+
NEW_MEDIA_WRITE.includes(value as NewMediaWrite) ? (value as NewMediaWrite) : null
|
|
111
|
+
|
|
112
|
+
/** An item's own settings from its `content` columns; null policies are `inherit`. */
|
|
113
|
+
export const itemAccessOf = (row: Record<string, unknown>): MediaItemAccess => ({
|
|
114
|
+
readPolicy: parseMediaPolicy(row.read_policy),
|
|
115
|
+
writePolicy: parseMediaPolicy(row.write_policy),
|
|
116
|
+
creatorMemberKey: row.creator_member_key ? normaliseUuid(String(row.creator_member_key)) : null,
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
const stored = (policy: MediaPolicy): string | null => (policy === 'inherit' ? null : policy)
|
|
120
|
+
|
|
121
|
+
/** The `/media/…` paths a node's upload and image cropper values name. Pure. */
|
|
122
|
+
export function filesOf(values: readonly DocumentValue[]): string[] {
|
|
123
|
+
const urls = new Set<string>()
|
|
124
|
+
for (const value of values) {
|
|
125
|
+
if (!value.editorAlias || !FILE_VALUE_EDITORS.has(value.editorAlias)) continue
|
|
126
|
+
const file = mediaFileOf({ values: [{ ...value, alias: 'umbracoFile' }] })
|
|
127
|
+
if (file) urls.add(file)
|
|
128
|
+
}
|
|
129
|
+
return [...urls]
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Records where a node's files are served, so `/media/…` serves only files
|
|
134
|
+
* something owns: a media item's on its `content` row, anything else's — a
|
|
135
|
+
* page's upload field — in `node_file`.
|
|
136
|
+
*/
|
|
137
|
+
export async function recordFiles(
|
|
138
|
+
db: Db,
|
|
139
|
+
kind: string,
|
|
140
|
+
nodeId: number,
|
|
141
|
+
aggregate: Pick<DocumentAggregate, 'values'>,
|
|
142
|
+
): Promise<void> {
|
|
143
|
+
if (kind === 'media') {
|
|
144
|
+
await db.exec('UPDATE content SET file_url = ? WHERE node_id = ?', [
|
|
145
|
+
mediaFileOf(aggregate),
|
|
146
|
+
nodeId,
|
|
147
|
+
])
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
await db.exec('DELETE FROM node_file WHERE node_id = ?', [nodeId])
|
|
151
|
+
for (const url of filesOf(aggregate.values))
|
|
152
|
+
await db.exec('INSERT INTO node_file (node_id, url) VALUES (?, ?)', [nodeId, url])
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
interface EntryRow {
|
|
156
|
+
id: number
|
|
157
|
+
node_id: number
|
|
158
|
+
node_key: string
|
|
159
|
+
public_read: unknown
|
|
160
|
+
new_read: string | null
|
|
161
|
+
new_write: string | null
|
|
162
|
+
member_types: string | null
|
|
163
|
+
member_max_bytes: unknown
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const SELECT = `SELECT a.id, a.node_id, n.unique_id AS node_key, a.public_read, a.new_read, a.new_write,
|
|
167
|
+
a.member_types, a.member_max_bytes
|
|
168
|
+
FROM media_access a JOIN node n ON n.id = a.node_id`
|
|
169
|
+
|
|
170
|
+
export class MediaAccessRepository {
|
|
171
|
+
#db: Db
|
|
172
|
+
#nodes: NodeRepository
|
|
173
|
+
|
|
174
|
+
constructor(db: Db) {
|
|
175
|
+
this.#db = db
|
|
176
|
+
this.#nodes = new NodeRepository(db)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async #media(key: string): Promise<NodeRow | undefined> {
|
|
180
|
+
const node = await this.#nodes.byKey(key)
|
|
181
|
+
return node && node.objectType === ObjectTypes.Media ? node : undefined
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async #hydrate(rows: readonly EntryRow[]): Promise<MediaAccessEntry[]> {
|
|
185
|
+
if (rows.length === 0) return []
|
|
186
|
+
const ids = rows.map((row) => Number(row.id))
|
|
187
|
+
const groups = await this.#db.query<{
|
|
188
|
+
media_access_id: number
|
|
189
|
+
member_group: string
|
|
190
|
+
can_read: unknown
|
|
191
|
+
can_write: unknown
|
|
192
|
+
}>(
|
|
193
|
+
`SELECT media_access_id, member_group, can_read, can_write FROM media_access_rule
|
|
194
|
+
WHERE media_access_id IN (${ids.map(() => '?').join(', ')}) ORDER BY member_group`,
|
|
195
|
+
ids,
|
|
196
|
+
)
|
|
197
|
+
const members = await this.#db.query<{
|
|
198
|
+
media_access_id: number
|
|
199
|
+
member_key: string
|
|
200
|
+
can_read: unknown
|
|
201
|
+
can_write: unknown
|
|
202
|
+
}>(
|
|
203
|
+
`SELECT media_access_id, member_key, can_read, can_write FROM media_access_member WHERE media_access_id IN (${ids.map(() => '?').join(', ')}) ORDER BY member_key`,
|
|
204
|
+
ids,
|
|
205
|
+
)
|
|
206
|
+
return rows.map((row) => ({
|
|
207
|
+
...(members.some((m) => Number(m.media_access_id) === Number(row.id))
|
|
208
|
+
? {
|
|
209
|
+
members: members
|
|
210
|
+
.filter((m) => Number(m.media_access_id) === Number(row.id))
|
|
211
|
+
.map((m) => ({
|
|
212
|
+
key: normaliseUuid(m.member_key),
|
|
213
|
+
read: fromDbBool(m.can_read),
|
|
214
|
+
write: fromDbBool(m.can_write),
|
|
215
|
+
})),
|
|
216
|
+
}
|
|
217
|
+
: {}),
|
|
218
|
+
nodeId: Number(row.node_id),
|
|
219
|
+
nodeKey: normaliseUuid(String(row.node_key)),
|
|
220
|
+
publicRead: fromDbBool(row.public_read),
|
|
221
|
+
newRead: newRead(row.new_read),
|
|
222
|
+
newWrite: newWrite(row.new_write),
|
|
223
|
+
memberTypes: memberTypesOf(row.member_types),
|
|
224
|
+
memberMaxBytes: storedBytes(
|
|
225
|
+
row.member_max_bytes === null || row.member_max_bytes === undefined
|
|
226
|
+
? null
|
|
227
|
+
: Number(row.member_max_bytes),
|
|
228
|
+
),
|
|
229
|
+
groups: groups
|
|
230
|
+
.filter((g) => Number(g.media_access_id) === Number(row.id))
|
|
231
|
+
.map((g) => ({
|
|
232
|
+
name: String(g.member_group),
|
|
233
|
+
read: fromDbBool(g.can_read),
|
|
234
|
+
write: fromDbBool(g.can_write),
|
|
235
|
+
})),
|
|
236
|
+
}))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Every rule, in three queries: what a request deciding over many items reads. */
|
|
240
|
+
async allRules(): Promise<MediaRule[]> {
|
|
241
|
+
const rows = await this.#db.query<EntryRow>(SELECT)
|
|
242
|
+
return (await this.#hydrate(rows)).map(ruleOf)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** The rule set on this folder or item itself, if any. */
|
|
246
|
+
async byNodeKey(nodeKey: string): Promise<MediaAccessEntry | undefined> {
|
|
247
|
+
const rows = await this.#db.query<EntryRow>(`${SELECT} WHERE n.unique_id = ?`, [
|
|
248
|
+
normaliseUuid(nodeKey),
|
|
249
|
+
])
|
|
250
|
+
return (await this.#hydrate(rows))[0]
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The rule that governs a node: its own, else its nearest ancestor's;
|
|
255
|
+
* `above` skips its own, as for the defaults a new file is given.
|
|
256
|
+
*/
|
|
257
|
+
async ruleFor(
|
|
258
|
+
nodeKey: string,
|
|
259
|
+
options: { above?: boolean } = {},
|
|
260
|
+
): Promise<MediaAccessEntry | undefined> {
|
|
261
|
+
const node = await this.#nodes.byKey(nodeKey)
|
|
262
|
+
return node ? this.#nearest(node.path, options.above ? node.id : undefined) : undefined
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async #nearest(path: string, skip?: number): Promise<MediaAccessEntry | undefined> {
|
|
266
|
+
const ids = path
|
|
267
|
+
.split(',')
|
|
268
|
+
.map(Number)
|
|
269
|
+
.filter((id) => Number.isFinite(id) && id > 0 && id !== skip)
|
|
270
|
+
if (ids.length === 0) return undefined
|
|
271
|
+
const rows = await this.#db.query<EntryRow>(
|
|
272
|
+
`${SELECT} WHERE a.node_id IN (${ids.map(() => '?').join(', ')}) ORDER BY n.level DESC LIMIT 1`,
|
|
273
|
+
ids,
|
|
274
|
+
)
|
|
275
|
+
return (await this.#hydrate(rows))[0]
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Sets the rule on a media folder or item, replacing any; undefined when it is not media. */
|
|
279
|
+
async save(input: MediaAccessInput): Promise<MediaAccessEntry | undefined> {
|
|
280
|
+
const node = await this.#media(input.nodeKey)
|
|
281
|
+
if (!node) return undefined
|
|
282
|
+
const now = DbDate.toDb(new Date())
|
|
283
|
+
await this.#db.transaction(async (tx) => {
|
|
284
|
+
const existing = await tx.query<{ id: number }>(
|
|
285
|
+
'SELECT id FROM media_access WHERE node_id = ?',
|
|
286
|
+
[node.id],
|
|
287
|
+
)
|
|
288
|
+
let id = existing[0] ? Number(existing[0].id) : undefined
|
|
289
|
+
const values = [
|
|
290
|
+
tx.dialect.boolValue(input.publicRead),
|
|
291
|
+
input.newRead,
|
|
292
|
+
input.newWrite,
|
|
293
|
+
storedTypes(input.memberTypes),
|
|
294
|
+
storedBytes(input.memberMaxBytes),
|
|
295
|
+
]
|
|
296
|
+
if (id === undefined) {
|
|
297
|
+
await tx.exec(
|
|
298
|
+
`INSERT INTO media_access (node_id, public_read, new_read, new_write, member_types, member_max_bytes, create_date, update_date)
|
|
299
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
300
|
+
[node.id, ...values, now, now],
|
|
301
|
+
)
|
|
302
|
+
const created = await tx.query<{ id: number }>(
|
|
303
|
+
'SELECT id FROM media_access WHERE node_id = ?',
|
|
304
|
+
[node.id],
|
|
305
|
+
)
|
|
306
|
+
id = Number(created[0]?.id)
|
|
307
|
+
} else {
|
|
308
|
+
await tx.exec(
|
|
309
|
+
`UPDATE media_access SET public_read = ?, new_read = ?, new_write = ?, member_types = ?,
|
|
310
|
+
member_max_bytes = ?, update_date = ? WHERE id = ?`,
|
|
311
|
+
[...values, now, id],
|
|
312
|
+
)
|
|
313
|
+
await tx.exec('DELETE FROM media_access_rule WHERE media_access_id = ?', [id])
|
|
314
|
+
}
|
|
315
|
+
const seen = new Set<string>()
|
|
316
|
+
await tx.exec('DELETE FROM media_access_member WHERE media_access_id = ?', [id])
|
|
317
|
+
const memberKeys = new Set<string>()
|
|
318
|
+
for (const member of input.members ?? []) {
|
|
319
|
+
const key = normaliseUuid(member.key)
|
|
320
|
+
if (memberKeys.has(key) || (!member.read && !member.write)) continue
|
|
321
|
+
memberKeys.add(key)
|
|
322
|
+
await tx.exec(
|
|
323
|
+
'INSERT INTO media_access_member (media_access_id, member_key, can_read, can_write) VALUES (?, ?, ?, ?)',
|
|
324
|
+
[id, key, tx.dialect.boolValue(member.read), tx.dialect.boolValue(member.write)],
|
|
325
|
+
)
|
|
326
|
+
}
|
|
327
|
+
for (const group of input.groups) {
|
|
328
|
+
const name = group.name.trim()
|
|
329
|
+
if (name === '' || seen.has(name.toLowerCase()) || (!group.read && !group.write)) continue
|
|
330
|
+
seen.add(name.toLowerCase())
|
|
331
|
+
await tx.exec(
|
|
332
|
+
'INSERT INTO media_access_rule (media_access_id, member_group, can_read, can_write) VALUES (?, ?, ?, ?)',
|
|
333
|
+
[id, name, tx.dialect.boolValue(group.read), tx.dialect.boolValue(group.write)],
|
|
334
|
+
)
|
|
335
|
+
}
|
|
336
|
+
})
|
|
337
|
+
return this.byNodeKey(input.nodeKey)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Takes the rule off a folder or item, which then follows the one above it. */
|
|
341
|
+
async remove(nodeKey: string): Promise<boolean> {
|
|
342
|
+
const own = await this.byNodeKey(nodeKey)
|
|
343
|
+
if (!own) return false
|
|
344
|
+
await this.#db.transaction(async (tx) => {
|
|
345
|
+
await tx.exec(
|
|
346
|
+
'DELETE FROM media_access_rule WHERE media_access_id IN (SELECT id FROM media_access WHERE node_id = ?)',
|
|
347
|
+
[own.nodeId],
|
|
348
|
+
)
|
|
349
|
+
await tx.exec('DELETE FROM media_access WHERE node_id = ?', [own.nodeId])
|
|
350
|
+
})
|
|
351
|
+
return true
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** An item's own settings; undefined when it is not media. */
|
|
355
|
+
async itemAccess(nodeKey: string): Promise<MediaItemAccess | undefined> {
|
|
356
|
+
const rows = await this.#db.query(
|
|
357
|
+
`SELECT c.read_policy, c.write_policy, c.creator_member_key
|
|
358
|
+
FROM content c JOIN node n ON n.id = c.node_id
|
|
359
|
+
WHERE n.unique_id = ? AND n.node_object_type = ?`,
|
|
360
|
+
[normaliseUuid(nodeKey), ObjectTypes.Media],
|
|
361
|
+
)
|
|
362
|
+
return rows[0] ? itemAccessOf(rows[0]) : undefined
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Sets who may see and change an item itself; false when it is not media. */
|
|
366
|
+
async setItemAccess(
|
|
367
|
+
nodeKey: string,
|
|
368
|
+
policies: { readPolicy: MediaPolicy; writePolicy: MediaPolicy },
|
|
369
|
+
): Promise<boolean> {
|
|
370
|
+
const node = await this.#media(nodeKey)
|
|
371
|
+
if (!node) return false
|
|
372
|
+
await this.#db.exec('UPDATE content SET read_policy = ?, write_policy = ? WHERE node_id = ?', [
|
|
373
|
+
stored(policies.readPolicy),
|
|
374
|
+
stored(policies.writePolicy),
|
|
375
|
+
node.id,
|
|
376
|
+
])
|
|
377
|
+
return true
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Records the member who created an item; null clears it. */
|
|
381
|
+
async setCreator(nodeKey: string, memberKey: string | null): Promise<boolean> {
|
|
382
|
+
const node = await this.#media(nodeKey)
|
|
383
|
+
if (!node) return false
|
|
384
|
+
await this.#db.exec('UPDATE content SET creator_member_key = ? WHERE node_id = ?', [
|
|
385
|
+
memberKey ? normaliseUuid(memberKey) : null,
|
|
386
|
+
node.id,
|
|
387
|
+
])
|
|
388
|
+
return true
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Gives a new item the policies the nearest rule above it sets for new
|
|
393
|
+
* files, and records its creator when a member made it.
|
|
394
|
+
*/
|
|
395
|
+
async stampNew(
|
|
396
|
+
nodeKey: string,
|
|
397
|
+
creatorMemberKey: string | null = null,
|
|
398
|
+
): Promise<MediaItemAccess | undefined> {
|
|
399
|
+
const node = await this.#media(nodeKey)
|
|
400
|
+
if (!node) return undefined
|
|
401
|
+
const above = await this.#nearest(node.path, node.id)
|
|
402
|
+
const policies = stampedPolicies(above ? ruleOf(above) : undefined)
|
|
403
|
+
const creator = creatorMemberKey ? normaliseUuid(creatorMemberKey) : null
|
|
404
|
+
await this.#db.exec(
|
|
405
|
+
'UPDATE content SET read_policy = ?, write_policy = ?, creator_member_key = ? WHERE node_id = ?',
|
|
406
|
+
[stored(policies.readPolicy), stored(policies.writePolicy), creator, node.id],
|
|
407
|
+
)
|
|
408
|
+
return { ...policies, creatorMemberKey: creator }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* The item whose file is served at a `/media/…` path, its settings and the
|
|
413
|
+
* nearest rule, through the `file_url` index; undefined when none owns it.
|
|
414
|
+
* Two queries: the item with its rule's id, then that rule.
|
|
415
|
+
*/
|
|
416
|
+
async byUrl(urls: string | readonly string[]): Promise<MediaByUrl | undefined> {
|
|
417
|
+
const wanted = [...new Set(typeof urls === 'string' ? [urls] : urls)]
|
|
418
|
+
if (wanted.length === 0) return undefined
|
|
419
|
+
const rows = await this.#db.query(
|
|
420
|
+
`SELECT n.id, n.unique_id, n.path, n.trashed, c.read_policy, c.write_policy, c.creator_member_key,
|
|
421
|
+
(SELECT a.id FROM media_access a JOIN node an ON an.id = a.node_id
|
|
422
|
+
WHERE (',' || n.path || ',') LIKE ('%,' || CAST(a.node_id AS VARCHAR(20)) || ',%')
|
|
423
|
+
ORDER BY an.level DESC LIMIT 1) AS rule_id
|
|
424
|
+
FROM content c JOIN node n ON n.id = c.node_id
|
|
425
|
+
WHERE c.file_url IN (${wanted.map(() => '?').join(', ')}) AND n.node_object_type = ?
|
|
426
|
+
ORDER BY n.id LIMIT 1`,
|
|
427
|
+
[...wanted, ObjectTypes.Media],
|
|
428
|
+
)
|
|
429
|
+
const row = rows[0]
|
|
430
|
+
if (!row) return undefined
|
|
431
|
+
const ruleRows =
|
|
432
|
+
row.rule_id === null || row.rule_id === undefined
|
|
433
|
+
? []
|
|
434
|
+
: await this.#db.query<EntryRow>(`${SELECT} WHERE a.id = ?`, [Number(row.rule_id)])
|
|
435
|
+
const entry = (await this.#hydrate(ruleRows))[0]
|
|
436
|
+
return {
|
|
437
|
+
id: Number(row.id),
|
|
438
|
+
key: normaliseUuid(String(row.unique_id)),
|
|
439
|
+
path: String(row.path),
|
|
440
|
+
trashed: fromDbBool(row.trashed),
|
|
441
|
+
access: itemAccessOf(row),
|
|
442
|
+
rule: entry ? ruleOf(entry) : undefined,
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Whether something other than a media item owns this file — a page's,
|
|
448
|
+
* element's or member's upload value, or a back-office user's avatar — and
|
|
449
|
+
* so is served as before.
|
|
450
|
+
*/
|
|
451
|
+
async ownedElsewhere(urls: readonly string[]): Promise<boolean> {
|
|
452
|
+
if (urls.length === 0) return false
|
|
453
|
+
const holes = urls.map(() => '?').join(', ')
|
|
454
|
+
const rows = await this.#db.query(
|
|
455
|
+
`SELECT node_id FROM node_file WHERE url IN (${holes})
|
|
456
|
+
UNION ALL SELECT id FROM user_account WHERE avatar IN (${holes})`,
|
|
457
|
+
[...urls, ...urls],
|
|
458
|
+
)
|
|
459
|
+
return rows.length > 0
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Every media item that says something of its own, by node id: for the published cache. */
|
|
463
|
+
async itemSettings(): Promise<Map<number, MediaItemAccess>> {
|
|
464
|
+
const rows = await this.#db.query(
|
|
465
|
+
`SELECT c.node_id, c.read_policy, c.write_policy, c.creator_member_key
|
|
466
|
+
FROM content c JOIN node n ON n.id = c.node_id
|
|
467
|
+
WHERE n.node_object_type = ?
|
|
468
|
+
AND (c.read_policy IS NOT NULL OR c.write_policy IS NOT NULL OR c.creator_member_key IS NOT NULL)`,
|
|
469
|
+
[ObjectTypes.Media],
|
|
470
|
+
)
|
|
471
|
+
return new Map(rows.map((row) => [Number(row.node_id), itemAccessOf(row)]))
|
|
472
|
+
}
|
|
473
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The media tree read a page at a time (story 197): the Delivery API's media
|
|
3
|
+
* listing, an item by its path of names, and those paths, as indexed queries
|
|
4
|
+
* over `node`, so no request holds the library in memory. The order is
|
|
5
|
+
* Umbraco's: `sort_order`, then the node id. docs/delivery-api.md, "Media".
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
type MediaMember,
|
|
9
|
+
type MediaRule,
|
|
10
|
+
nearestMediaRule,
|
|
11
|
+
normaliseUuid,
|
|
12
|
+
ObjectTypes,
|
|
13
|
+
} from '@crombolo/core'
|
|
14
|
+
import type { Db } from '../database.ts'
|
|
15
|
+
|
|
16
|
+
export type MediaSortField = 'createDate' | 'updateDate' | 'name' | 'sortOrder'
|
|
17
|
+
|
|
18
|
+
export interface MediaListingQuery {
|
|
19
|
+
/** The parent's node id; -1 for the top level. */
|
|
20
|
+
parentId: number
|
|
21
|
+
/** Its path, for the rule the children inherit; `-1` for the top level. */
|
|
22
|
+
parentPath: string
|
|
23
|
+
/** Every one must match: a media type alias. */
|
|
24
|
+
mediaTypes?: readonly string[]
|
|
25
|
+
/** Every one must match: part of the name, in any case. */
|
|
26
|
+
names?: readonly string[]
|
|
27
|
+
sort?: { field: MediaSortField; ascending: boolean }
|
|
28
|
+
skip: number
|
|
29
|
+
take: number
|
|
30
|
+
/** Leaves out what this caller may not read; everything when absent. */
|
|
31
|
+
readable?: { rules: ReadonlyMap<number, MediaRule>; member: MediaMember | undefined }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const NAME = 'COALESCE(head.text, n.text)'
|
|
35
|
+
const FROM = `FROM node n
|
|
36
|
+
JOIN content c ON c.node_id = n.id
|
|
37
|
+
JOIN content_type ct ON ct.node_id = c.content_type_id
|
|
38
|
+
LEFT JOIN content_version head ON head.node_id = n.id AND head.current = ?`
|
|
39
|
+
|
|
40
|
+
const SORT_COLUMNS: Record<MediaSortField, string> = {
|
|
41
|
+
createDate: 'n.create_date',
|
|
42
|
+
updateDate: 'COALESCE(head.version_date, n.create_date)',
|
|
43
|
+
name: `LOWER(${NAME})`,
|
|
44
|
+
sortOrder: 'n.sort_order',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const likeEscape = (value: string) => value.replace(/[\\%_]/g, (c) => `\\${c}`)
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Who may read a child, as SQL, under one rule: `memberMay('read', …)` with
|
|
51
|
+
* everything but the item's own columns worked out here. Pure.
|
|
52
|
+
*/
|
|
53
|
+
function readableUnder(
|
|
54
|
+
rule: MediaRule | undefined,
|
|
55
|
+
member: MediaMember | undefined,
|
|
56
|
+
): { sql: string; params: unknown[] } {
|
|
57
|
+
const held = new Set(member?.groups.map((g) => g.toLowerCase()) ?? [])
|
|
58
|
+
const inGroups = (names: readonly string[]) => names.some((n) => held.has(n.toLowerCase()))
|
|
59
|
+
const groups =
|
|
60
|
+
inGroups(rule?.readGroups ?? []) ||
|
|
61
|
+
Boolean(
|
|
62
|
+
member && rule?.readMembers?.some((key) => key.toLowerCase() === member.key.toLowerCase()),
|
|
63
|
+
)
|
|
64
|
+
const inherited = !rule || rule.publicRead || groups
|
|
65
|
+
const parts = ["c.read_policy = 'public'"]
|
|
66
|
+
const params: unknown[] = []
|
|
67
|
+
if (groups) parts.push("c.read_policy = 'groups'")
|
|
68
|
+
if (member) {
|
|
69
|
+
parts.push("c.read_policy = 'members'")
|
|
70
|
+
parts.push("(c.read_policy = 'creator' AND c.creator_member_key = ?)")
|
|
71
|
+
params.push(normaliseUuid(member.key))
|
|
72
|
+
}
|
|
73
|
+
if (inherited) parts.push("(c.read_policy IS NULL OR c.read_policy = 'inherit')")
|
|
74
|
+
return { sql: `(${parts.join(' OR ')})`, params }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class MediaListingRepository {
|
|
78
|
+
#db: Db
|
|
79
|
+
|
|
80
|
+
constructor(db: Db) {
|
|
81
|
+
this.#db = db
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A page of a parent's children: their keys in order, and how many match in
|
|
86
|
+
* all. Only the tables a filter or sort reads are joined, so the count over a
|
|
87
|
+
* large folder reads the node index alone where it can.
|
|
88
|
+
*/
|
|
89
|
+
async children(query: MediaListingQuery): Promise<{ total: number; keys: string[] }> {
|
|
90
|
+
const mediaTypes = query.mediaTypes ?? []
|
|
91
|
+
const names = query.names ?? []
|
|
92
|
+
const sortsByHead = query.sort?.field === 'name' || query.sort?.field === 'updateDate'
|
|
93
|
+
const joins: string[] = []
|
|
94
|
+
const joinParams: unknown[] = []
|
|
95
|
+
if (query.readable || mediaTypes.length > 0) joins.push('JOIN content c ON c.node_id = n.id')
|
|
96
|
+
if (mediaTypes.length > 0) joins.push('JOIN content_type ct ON ct.node_id = c.content_type_id')
|
|
97
|
+
const head = 'LEFT JOIN content_version head ON head.node_id = n.id AND head.current = ?'
|
|
98
|
+
const where = ['n.parent_id = ?', 'n.node_object_type = ?', 'n.trashed = ?']
|
|
99
|
+
const params: unknown[] = [query.parentId, ObjectTypes.Media, this.#db.dialect.boolValue(false)]
|
|
100
|
+
for (const alias of mediaTypes) {
|
|
101
|
+
where.push('ct.alias = ?')
|
|
102
|
+
params.push(alias)
|
|
103
|
+
}
|
|
104
|
+
for (const part of names) {
|
|
105
|
+
where.push(`LOWER(${NAME}) LIKE ? ESCAPE '\\'`)
|
|
106
|
+
params.push(`%${likeEscape(part.toLowerCase())}%`)
|
|
107
|
+
}
|
|
108
|
+
if (query.readable) {
|
|
109
|
+
// The children share the rule above them, except one with a rule of its own.
|
|
110
|
+
const { rules, member } = query.readable
|
|
111
|
+
const own = [...rules.values()]
|
|
112
|
+
const above = readableUnder(nearestMediaRule(query.parentPath, rules), member)
|
|
113
|
+
const clauses: string[] = []
|
|
114
|
+
if (own.length === 0) clauses.push(above.sql)
|
|
115
|
+
else
|
|
116
|
+
clauses.push(
|
|
117
|
+
`(n.id NOT IN (${own.map(() => '?').join(', ')}) AND ${above.sql})`,
|
|
118
|
+
...own.map((rule) => `(n.id = ? AND ${readableUnder(rule, member).sql})`),
|
|
119
|
+
)
|
|
120
|
+
where.push(`(${clauses.join(' OR ')})`)
|
|
121
|
+
if (own.length > 0) params.push(...own.map((rule) => rule.nodeId))
|
|
122
|
+
params.push(...above.params)
|
|
123
|
+
for (const rule of own) params.push(rule.nodeId, ...readableUnder(rule, member).params)
|
|
124
|
+
}
|
|
125
|
+
const from = (withHead: boolean) =>
|
|
126
|
+
`FROM node n ${[...joins, ...(withHead ? [head] : [])].join(' ')} WHERE ${where.join(' AND ')}`
|
|
127
|
+
const headParams = (withHead: boolean) =>
|
|
128
|
+
withHead ? [...joinParams, this.#db.dialect.boolValue(true)] : joinParams
|
|
129
|
+
const countHead = names.length > 0
|
|
130
|
+
const counted = await this.#db.query<{ n: unknown }>(
|
|
131
|
+
`SELECT COUNT(*) AS n ${from(countHead)}`,
|
|
132
|
+
[...headParams(countHead), ...params],
|
|
133
|
+
)
|
|
134
|
+
const pageHead = countHead || sortsByHead
|
|
135
|
+
const order = query.sort
|
|
136
|
+
? `${SORT_COLUMNS[query.sort.field]} ${query.sort.ascending ? 'ASC' : 'DESC'}, n.sort_order, n.id`
|
|
137
|
+
: 'n.sort_order, n.id'
|
|
138
|
+
const rows =
|
|
139
|
+
query.take <= 0
|
|
140
|
+
? []
|
|
141
|
+
: await this.#db.query<{ unique_id: string }>(
|
|
142
|
+
`SELECT n.unique_id ${from(pageHead)} ORDER BY ${order} LIMIT ? OFFSET ?`,
|
|
143
|
+
[...headParams(pageHead), ...params, query.take, Math.max(0, query.skip)],
|
|
144
|
+
)
|
|
145
|
+
return {
|
|
146
|
+
total: Number(counted[0]?.n ?? 0),
|
|
147
|
+
keys: rows.map((row) => normaliseUuid(String(row.unique_id))),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The node at a path of names below the top level, in any case; the first by sort order. */
|
|
152
|
+
async byPath(path: string): Promise<{ id: number; key: string; path: string } | undefined> {
|
|
153
|
+
let parentId = -1
|
|
154
|
+
let found: { id: number; key: string; path: string } | undefined
|
|
155
|
+
for (const segment of path.split('/').filter(Boolean)) {
|
|
156
|
+
found = await this.#childNamed(parentId, segment)
|
|
157
|
+
if (!found) return undefined
|
|
158
|
+
parentId = found.id
|
|
159
|
+
}
|
|
160
|
+
return found
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** A node's id and path, by key; undefined for anything not media or in the bin. */
|
|
164
|
+
async byKey(key: string): Promise<{ id: number; key: string; path: string } | undefined> {
|
|
165
|
+
const rows = await this.#db.query<{ id: number; unique_id: string; path: string }>(
|
|
166
|
+
'SELECT id, unique_id, path FROM node WHERE unique_id = ? AND node_object_type = ? AND trashed = ?',
|
|
167
|
+
[normaliseUuid(key), ObjectTypes.Media, this.#db.dialect.boolValue(false)],
|
|
168
|
+
)
|
|
169
|
+
const row = rows[0]
|
|
170
|
+
return row
|
|
171
|
+
? { id: Number(row.id), key: normaliseUuid(String(row.unique_id)), path: String(row.path) }
|
|
172
|
+
: undefined
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async #childNamed(parentId: number, name: string) {
|
|
176
|
+
const lowered = name.toLowerCase()
|
|
177
|
+
const query = (extra: string, params: unknown[], limit = '') =>
|
|
178
|
+
this.#db.query<{ id: number; unique_id: string; path: string; name: string }>(
|
|
179
|
+
`SELECT n.id, n.unique_id, n.path, ${NAME} AS name ${FROM}
|
|
180
|
+
WHERE n.parent_id = ? AND n.node_object_type = ? AND n.trashed = ? ${extra}
|
|
181
|
+
ORDER BY n.sort_order, n.id ${limit}`,
|
|
182
|
+
[
|
|
183
|
+
this.#db.dialect.boolValue(true),
|
|
184
|
+
parentId,
|
|
185
|
+
ObjectTypes.Media,
|
|
186
|
+
this.#db.dialect.boolValue(false),
|
|
187
|
+
...params,
|
|
188
|
+
],
|
|
189
|
+
)
|
|
190
|
+
let rows = await query(`AND LOWER(${NAME}) = ?`, [lowered], 'LIMIT 1')
|
|
191
|
+
// SQLite lowers only ASCII, so a name with other letters is matched here.
|
|
192
|
+
if (rows.length === 0 && this.#db.dialect.name === 'sqlite' && /[^ -~]/.test(name))
|
|
193
|
+
rows = (await query('', [])).filter((row) => String(row.name).toLowerCase() === lowered)
|
|
194
|
+
const row = rows[0]
|
|
195
|
+
return row
|
|
196
|
+
? { id: Number(row.id), key: normaliseUuid(String(row.unique_id)), path: String(row.path) }
|
|
197
|
+
: undefined
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Each node's name, by id: for the paths of names an answer carries. */
|
|
201
|
+
async names(ids: readonly number[]): Promise<Map<number, string>> {
|
|
202
|
+
const wanted = [...new Set(ids.filter((id) => id > 0))]
|
|
203
|
+
const out = new Map<number, string>()
|
|
204
|
+
for (let at = 0; at < wanted.length; at += 500) {
|
|
205
|
+
const slice = wanted.slice(at, at + 500)
|
|
206
|
+
const rows = await this.#db.query<{ id: number; name: string }>(
|
|
207
|
+
`SELECT n.id, ${NAME} AS name FROM node n
|
|
208
|
+
LEFT JOIN content_version head ON head.node_id = n.id AND head.current = ?
|
|
209
|
+
WHERE n.id IN (${slice.map(() => '?').join(', ')})`,
|
|
210
|
+
[this.#db.dialect.boolValue(true), ...slice],
|
|
211
|
+
)
|
|
212
|
+
for (const row of rows) out.set(Number(row.id), String(row.name ?? ''))
|
|
213
|
+
}
|
|
214
|
+
return out
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -397,9 +397,20 @@ export class NodeRepository {
|
|
|
397
397
|
}
|
|
398
398
|
|
|
399
399
|
async #nextSortOrder(parentId: number, objectType: string): Promise<number> {
|
|
400
|
+
// One maximum per `trashed`, so each is read off the end of `ix_node_parent_sort`
|
|
401
|
+
// rather than across every child: a folder may hold a million files (story 197).
|
|
402
|
+
const max =
|
|
403
|
+
'SELECT MAX(sort_order) AS m FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ?'
|
|
400
404
|
const rows = await this.#db.query<{ next: number | null }>(
|
|
401
|
-
|
|
402
|
-
[
|
|
405
|
+
`SELECT MAX(m) AS next FROM (${max} UNION ALL ${max}) maxima`,
|
|
406
|
+
[
|
|
407
|
+
parentId,
|
|
408
|
+
objectType,
|
|
409
|
+
this.#db.dialect.boolValue(false),
|
|
410
|
+
parentId,
|
|
411
|
+
objectType,
|
|
412
|
+
this.#db.dialect.boolValue(true),
|
|
413
|
+
],
|
|
403
414
|
)
|
|
404
415
|
const current = rows[0]?.next
|
|
405
416
|
return current === null || current === undefined ? 0 : Number(current) + 1
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 050 — who may read and change media (story 196).
|
|
3
|
+
*
|
|
4
|
+
* `media_access` is a rule on a media folder or item, one per node, with the
|
|
5
|
+
* defaults a folder gives files created below it; `media_access_rule` names a
|
|
6
|
+
* member group and whether it may read and write. Each media item's own
|
|
7
|
+
* settings are columns on `content`, so millions of files cost no rule rows:
|
|
8
|
+
* the member who created it, its read and write policies, and `file_url`, the
|
|
9
|
+
* `/media/…` path its file is served at, indexed so a request finds its item.
|
|
10
|
+
* Existing items get their `file_url` here, and keep following the rules.
|
|
11
|
+
*
|
|
12
|
+
* `node_file` lists the files anything else's upload values name — a page's
|
|
13
|
+
* attachment — so that `/media/…` serves only files something owns.
|
|
14
|
+
*/
|
|
15
|
+
import { ObjectTypes } from '@crombolo/core'
|
|
16
|
+
import type { Db } from '../database.ts'
|
|
17
|
+
import type { Migration } from '../migrations.ts'
|
|
18
|
+
import { STATE_CONTENT_APPLIED } from './content-applied.ts'
|
|
19
|
+
|
|
20
|
+
export const STATE_MEDIA_ACCESS = '{2b7e9c41-0050-4d8a-a3f6-1e5c8b9d7a50}'
|
|
21
|
+
|
|
22
|
+
export const mediaAccessMigration: Migration = {
|
|
23
|
+
from: STATE_CONTENT_APPLIED,
|
|
24
|
+
to: STATE_MEDIA_ACCESS,
|
|
25
|
+
name: 'AddMediaAccess',
|
|
26
|
+
kind: 'expand',
|
|
27
|
+
release: '0.35.0',
|
|
28
|
+
async up(db: Db) {
|
|
29
|
+
const t = db.dialect.types
|
|
30
|
+
|
|
31
|
+
await db.exec(
|
|
32
|
+
`CREATE TABLE media_access (
|
|
33
|
+
id ${t.identity},
|
|
34
|
+
node_id ${t.integer} NOT NULL REFERENCES node (id),
|
|
35
|
+
public_read ${t.boolean} NOT NULL,
|
|
36
|
+
new_read ${t.varchar(10)},
|
|
37
|
+
new_write ${t.varchar(10)},
|
|
38
|
+
create_date ${t.timestamp} NOT NULL,
|
|
39
|
+
update_date ${t.timestamp} NOT NULL
|
|
40
|
+
)`,
|
|
41
|
+
)
|
|
42
|
+
await db.exec('CREATE UNIQUE INDEX ux_media_access_node ON media_access (node_id)')
|
|
43
|
+
await db.exec(
|
|
44
|
+
`CREATE TABLE media_access_rule (
|
|
45
|
+
id ${t.identity},
|
|
46
|
+
media_access_id ${t.integer} NOT NULL REFERENCES media_access (id),
|
|
47
|
+
member_group ${t.textCi} NOT NULL,
|
|
48
|
+
can_read ${t.boolean} NOT NULL,
|
|
49
|
+
can_write ${t.boolean} NOT NULL
|
|
50
|
+
)`,
|
|
51
|
+
)
|
|
52
|
+
await db.exec(
|
|
53
|
+
'CREATE UNIQUE INDEX ux_media_access_rule ON media_access_rule (media_access_id, member_group)',
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
await db.exec(`ALTER TABLE content ADD COLUMN file_url ${t.text}`)
|
|
57
|
+
await db.exec(`ALTER TABLE content ADD COLUMN creator_member_key ${t.uuid}`)
|
|
58
|
+
await db.exec(`ALTER TABLE content ADD COLUMN read_policy ${t.varchar(10)}`)
|
|
59
|
+
await db.exec(`ALTER TABLE content ADD COLUMN write_policy ${t.varchar(10)}`)
|
|
60
|
+
await db.exec('CREATE INDEX ix_content_file_url ON content (file_url)')
|
|
61
|
+
|
|
62
|
+
// Each item's file from its current `umbracoFile` value: a cropper's JSON
|
|
63
|
+
// `src`, or an upload's path. In SQL, so the step stays plannable.
|
|
64
|
+
const src =
|
|
65
|
+
db.dialect.name === 'postgres'
|
|
66
|
+
? `CASE WHEN v.text_value LIKE '{%'
|
|
67
|
+
THEN substring(v.text_value from '"src"\\s*:\\s*"([^"]*)"')
|
|
68
|
+
ELSE COALESCE(v.text_value, v.varchar_value) END`
|
|
69
|
+
: `CASE WHEN json_valid(v.text_value) AND json_type(v.text_value) = 'object'
|
|
70
|
+
THEN json_extract(v.text_value, '$.src')
|
|
71
|
+
ELSE COALESCE(v.text_value, v.varchar_value) END`
|
|
72
|
+
await db.exec(
|
|
73
|
+
`UPDATE content SET file_url = (
|
|
74
|
+
SELECT NULLIF(${src}, '')
|
|
75
|
+
FROM property_value v JOIN property_type p ON p.id = v.property_type_id
|
|
76
|
+
WHERE v.node_id = content.node_id AND p.alias = 'umbracoFile' AND v.is_current = ?
|
|
77
|
+
ORDER BY v.id DESC LIMIT 1)
|
|
78
|
+
WHERE node_id IN (SELECT id FROM node WHERE node_object_type = ?)`,
|
|
79
|
+
[db.dialect.boolValue(true), ObjectTypes.Media],
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
// The files anything else's upload values name — a page's attachment —
|
|
83
|
+
// which are served as before.
|
|
84
|
+
await db.exec(
|
|
85
|
+
`CREATE TABLE node_file (
|
|
86
|
+
node_id ${t.integer} NOT NULL REFERENCES node (id),
|
|
87
|
+
url ${t.text} NOT NULL
|
|
88
|
+
)`,
|
|
89
|
+
)
|
|
90
|
+
await db.exec('CREATE INDEX ix_node_file_url ON node_file (url)')
|
|
91
|
+
await db.exec('CREATE INDEX ix_node_file_node ON node_file (node_id)')
|
|
92
|
+
await db.exec(
|
|
93
|
+
`INSERT INTO node_file (node_id, url)
|
|
94
|
+
SELECT DISTINCT node_id, url FROM (
|
|
95
|
+
SELECT v.node_id, NULLIF(${src}, '') AS url
|
|
96
|
+
FROM property_value v
|
|
97
|
+
JOIN property_type p ON p.id = v.property_type_id
|
|
98
|
+
JOIN data_type d ON d.node_id = p.data_type_id
|
|
99
|
+
JOIN node n ON n.id = v.node_id
|
|
100
|
+
WHERE d.editor_alias IN ('Umbraco.UploadField', 'Umbraco.ImageCropper')
|
|
101
|
+
AND v.is_current = ? AND n.node_object_type <> ?) files
|
|
102
|
+
WHERE url IS NOT NULL`,
|
|
103
|
+
[db.dialect.boolValue(true), ObjectTypes.Media],
|
|
104
|
+
)
|
|
105
|
+
},
|
|
106
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 051 — indexes for media read a page at a time (story 197).
|
|
3
|
+
*
|
|
4
|
+
* The Delivery API's media listing pages a folder's children in the database,
|
|
5
|
+
* ordered by sort order then id, so a folder of a million files is read ten at
|
|
6
|
+
* a time rather than sorted in full. A server that missed changes reads the
|
|
7
|
+
* cache instructions after its checkpoint, by checkpoint.
|
|
8
|
+
*/
|
|
9
|
+
import type { Db } from '../database.ts'
|
|
10
|
+
import type { Migration } from '../migrations.ts'
|
|
11
|
+
import { STATE_MEDIA_ACCESS } from './media-access.ts'
|
|
12
|
+
|
|
13
|
+
export const STATE_MEDIA_CACHE = '{8d3f1a62-0051-4c7e-b9a4-2f6e1d8c5b51}'
|
|
14
|
+
|
|
15
|
+
export const mediaCacheMigration: Migration = {
|
|
16
|
+
from: STATE_MEDIA_ACCESS,
|
|
17
|
+
to: STATE_MEDIA_CACHE,
|
|
18
|
+
name: 'AddMediaPagingIndexes',
|
|
19
|
+
kind: 'expand',
|
|
20
|
+
release: '0.35.0',
|
|
21
|
+
async up(db: Db) {
|
|
22
|
+
await db.exec(
|
|
23
|
+
'CREATE INDEX ix_node_parent_sort ON node (parent_id, node_object_type, trashed, sort_order, id)',
|
|
24
|
+
)
|
|
25
|
+
await db.exec('CREATE INDEX ix_cache_instruction_checkpoint ON cache_instruction (checkpoint)')
|
|
26
|
+
},
|
|
27
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Db } from '../database.ts'
|
|
2
|
+
import type { Migration } from '../migrations.ts'
|
|
3
|
+
import { STATE_MEDIA_MEMBER_UPLOADS } from './media-member-uploads.ts'
|
|
4
|
+
|
|
5
|
+
export const STATE_MEDIA_MEMBER_GRANTS = '{4b198f00-0053-4ca8-bc39-97d92fca0053}'
|
|
6
|
+
|
|
7
|
+
export const mediaMemberGrantsMigration: Migration = {
|
|
8
|
+
from: STATE_MEDIA_MEMBER_UPLOADS,
|
|
9
|
+
to: STATE_MEDIA_MEMBER_GRANTS,
|
|
10
|
+
name: 'AddMediaMemberGrants',
|
|
11
|
+
kind: 'expand',
|
|
12
|
+
release: '0.36.0',
|
|
13
|
+
async up(db: Db) {
|
|
14
|
+
const t = db.dialect.types
|
|
15
|
+
await db.exec(`CREATE TABLE media_access_member (
|
|
16
|
+
media_access_id ${t.integer} NOT NULL REFERENCES media_access (id) ON DELETE CASCADE,
|
|
17
|
+
member_key ${t.uuid} NOT NULL,
|
|
18
|
+
can_read ${t.boolean} NOT NULL,
|
|
19
|
+
can_write ${t.boolean} NOT NULL,
|
|
20
|
+
PRIMARY KEY (media_access_id, member_key)
|
|
21
|
+
)`)
|
|
22
|
+
},
|
|
23
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 052 — what members may upload into a media folder (story 198).
|
|
3
|
+
*
|
|
4
|
+
* A rule on a folder names the file types a member may upload below it, as a
|
|
5
|
+
* comma-separated list of type names (`jpeg,png,webp`; null or empty is none),
|
|
6
|
+
* and an optional size limit in bytes. Both follow the rule: inherited
|
|
7
|
+
* downwards, and replaced by a nearer one.
|
|
8
|
+
*/
|
|
9
|
+
import type { Db } from '../database.ts'
|
|
10
|
+
import type { Migration } from '../migrations.ts'
|
|
11
|
+
import { STATE_MEDIA_CACHE } from './media-cache.ts'
|
|
12
|
+
|
|
13
|
+
export const STATE_MEDIA_MEMBER_UPLOADS = '{4e9a2c17-0052-4b6d-8f3e-7a1c5d9b2e52}'
|
|
14
|
+
|
|
15
|
+
export const mediaMemberUploadsMigration: Migration = {
|
|
16
|
+
from: STATE_MEDIA_CACHE,
|
|
17
|
+
to: STATE_MEDIA_MEMBER_UPLOADS,
|
|
18
|
+
name: 'AddMediaMemberUploads',
|
|
19
|
+
kind: 'expand',
|
|
20
|
+
release: '0.35.0',
|
|
21
|
+
async up(db: Db) {
|
|
22
|
+
const t = db.dialect.types
|
|
23
|
+
await db.exec(`ALTER TABLE media_access ADD COLUMN member_types ${t.text}`)
|
|
24
|
+
await db.exec(`ALTER TABLE media_access ADD COLUMN member_max_bytes ${t.bigint}`)
|
|
25
|
+
},
|
|
26
|
+
}
|
package/src/schema/plan.ts
CHANGED
|
@@ -40,6 +40,10 @@ import { formsMigration } from './forms.ts'
|
|
|
40
40
|
import { groupPermissionsMigration } from './group-permissions.ts'
|
|
41
41
|
import { identityMigration } from './identity.ts'
|
|
42
42
|
import { logViewerMigration } from './log-viewer.ts'
|
|
43
|
+
import { mediaAccessMigration } from './media-access.ts'
|
|
44
|
+
import { mediaCacheMigration } from './media-cache.ts'
|
|
45
|
+
import { mediaMemberGrantsMigration } from './media-member-grants.ts'
|
|
46
|
+
import { mediaMemberUploadsMigration } from './media-member-uploads.ts'
|
|
43
47
|
import { mediaPermissionsMigration } from './media-permissions.ts'
|
|
44
48
|
import { memberPropertyTypeMigration } from './member-property-type.ts'
|
|
45
49
|
import { membersMigration } from './members.ts'
|
|
@@ -113,4 +117,8 @@ export const cromboloPlan = new MigrationPlan([
|
|
|
113
117
|
contentCheckpointMigration,
|
|
114
118
|
dropAssistantMigration,
|
|
115
119
|
contentAppliedMigration,
|
|
120
|
+
mediaAccessMigration,
|
|
121
|
+
mediaCacheMigration,
|
|
122
|
+
mediaMemberUploadsMigration,
|
|
123
|
+
mediaMemberGrantsMigration,
|
|
116
124
|
])
|