payload-video-streaming 0.2.0-beta.0 → 0.2.0-beta.1
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/README.md +174 -543
- package/dist/access.d.ts +35 -0
- package/dist/access.js +53 -0
- package/dist/access.js.map +1 -0
- package/dist/bin/args.d.ts +13 -0
- package/dist/bin/args.js +61 -0
- package/dist/bin/args.js.map +1 -1
- package/dist/bin/cli.js +9 -1
- package/dist/bin/cli.js.map +1 -1
- package/dist/bin/webhooks.d.ts +15 -0
- package/dist/bin/webhooks.js +149 -0
- package/dist/bin/webhooks.js.map +1 -0
- package/dist/collection.js +148 -1
- package/dist/collection.js.map +1 -1
- package/dist/components/BulkUploader.d.ts +16 -0
- package/dist/components/BulkUploader.js +226 -0
- package/dist/components/BulkUploader.js.map +1 -0
- package/dist/components/ListUploader.js +22 -0
- package/dist/components/ListUploader.js.map +1 -1
- package/dist/components/Uploader.d.ts +5 -0
- package/dist/components/Uploader.js +13 -4
- package/dist/components/Uploader.js.map +1 -1
- package/dist/components/VideoField.js +9 -5
- package/dist/components/VideoField.js.map +1 -1
- package/dist/components/VideoRelationshipField.d.ts +16 -0
- package/dist/components/VideoRelationshipField.js +106 -0
- package/dist/components/VideoRelationshipField.js.map +1 -0
- package/dist/components/WebhookStatusPanel.d.ts +6 -0
- package/dist/components/WebhookStatusPanel.js +143 -0
- package/dist/components/WebhookStatusPanel.js.map +1 -0
- package/dist/components/api.d.ts +7 -1
- package/dist/components/api.js +2 -0
- package/dist/components/api.js.map +1 -1
- package/dist/components/uploadFile.d.ts +30 -0
- package/dist/components/uploadFile.js +140 -0
- package/dist/components/uploadFile.js.map +1 -0
- package/dist/components/usePluginApi.d.ts +5 -0
- package/dist/components/useUploadQueue.d.ts +35 -0
- package/dist/components/useUploadQueue.js +135 -0
- package/dist/components/useUploadQueue.js.map +1 -0
- package/dist/components/useVideoUpload.d.ts +3 -7
- package/dist/components/useVideoUpload.js +29 -123
- package/dist/components/useVideoUpload.js.map +1 -1
- package/dist/core/provider.d.ts +16 -0
- package/dist/core/provider.js.map +1 -1
- package/dist/endpoints/index.js +38 -2
- package/dist/endpoints/index.js.map +1 -1
- package/dist/exports/client.d.ts +9 -0
- package/dist/exports/client.js +5 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/react.d.ts +12 -0
- package/dist/exports/react.js +7 -0
- package/dist/exports/react.js.map +1 -1
- package/dist/fields.d.ts +11 -2
- package/dist/fields.js +62 -2
- package/dist/fields.js.map +1 -1
- package/dist/frontend/VideoUploader.d.ts +65 -0
- package/dist/frontend/VideoUploader.js +260 -0
- package/dist/frontend/VideoUploader.js.map +1 -0
- package/dist/frontend/useVideoStatus.d.ts +26 -0
- package/dist/frontend/useVideoStatus.js +68 -0
- package/dist/frontend/useVideoStatus.js.map +1 -0
- package/dist/index.d.ts +5 -4
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +7 -2
- package/dist/options.js +65 -2
- package/dist/options.js.map +1 -1
- package/dist/plugin.js +80 -1
- package/dist/plugin.js.map +1 -1
- package/dist/providers/bunny/provider.d.ts +2 -1
- package/dist/providers/bunny/provider.js +8 -0
- package/dist/providers/bunny/provider.js.map +1 -1
- package/dist/providers/cloudflare/provider.d.ts +2 -1
- package/dist/providers/cloudflare/provider.js +11 -0
- package/dist/providers/cloudflare/provider.js.map +1 -1
- package/dist/providers/mux/provider.d.ts +2 -1
- package/dist/providers/mux/provider.js +9 -0
- package/dist/providers/mux/provider.js.map +1 -1
- package/dist/service.d.ts +28 -1
- package/dist/service.js +114 -4
- package/dist/service.js.map +1 -1
- package/dist/types.d.ts +155 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -1
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Access-control helpers for the videos collection, for sites where members upload their own videos.
|
|
3
|
+
* Nothing here is applied by default: the collection keeps whatever access you configure. Use them in
|
|
4
|
+
* `collection.access`, e.g. `{ read: approvedOrOwner(), update: ownerOr(isAdmin), delete: ownerOr(isAdmin) }`.
|
|
5
|
+
*/
|
|
6
|
+
import type { Access } from 'payload';
|
|
7
|
+
/**
|
|
8
|
+
* Allows what any of the given access functions allows: `true` if one returns `true`, otherwise the
|
|
9
|
+
* `or` of the query constraints they return, otherwise `false`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const anyOf: (...checks: Access[]) => Access;
|
|
12
|
+
/**
|
|
13
|
+
* Videos owned by the logged-in user (needs `ownership` in the plugin options). Users from other auth
|
|
14
|
+
* collections than `collection` (when given) own nothing.
|
|
15
|
+
*/
|
|
16
|
+
export declare const isVideoOwner: ({ collection, field }?: {
|
|
17
|
+
collection?: string;
|
|
18
|
+
field?: string;
|
|
19
|
+
}) => Access;
|
|
20
|
+
/** Videos a moderator approved (needs `moderation` in the plugin options). */
|
|
21
|
+
export declare const isApprovedVideo: ({ field }?: {
|
|
22
|
+
field?: string;
|
|
23
|
+
}) => Access;
|
|
24
|
+
/** `access` or ownership: e.g. `ownerOr(isAdmin)` lets admins edit every video and members their own. */
|
|
25
|
+
export declare const ownerOr: (access: Access, options?: Parameters<typeof isVideoOwner>[0]) => Access;
|
|
26
|
+
/**
|
|
27
|
+
* Read access for member uploads: approved videos for everyone, plus each user's own videos in any
|
|
28
|
+
* state. Pass `or` to let some users (e.g. moderators) read everything.
|
|
29
|
+
*/
|
|
30
|
+
export declare const approvedOrOwner: ({ moderationField, or, ownerCollection, ownerField, }?: {
|
|
31
|
+
moderationField?: string;
|
|
32
|
+
or?: Access;
|
|
33
|
+
ownerCollection?: string;
|
|
34
|
+
ownerField?: string;
|
|
35
|
+
}) => Access;
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Access-control helpers for the videos collection, for sites where members upload their own videos.
|
|
3
|
+
* Nothing here is applied by default: the collection keeps whatever access you configure. Use them in
|
|
4
|
+
* `collection.access`, e.g. `{ read: approvedOrOwner(), update: ownerOr(isAdmin), delete: ownerOr(isAdmin) }`.
|
|
5
|
+
*/ const combine = (results)=>{
|
|
6
|
+
if (results.some((r)=>r === true)) {
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
const wheres = results.filter((r)=>typeof r === 'object' && r !== null);
|
|
10
|
+
if (wheres.length === 0) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
return wheres.length === 1 ? wheres[0] : {
|
|
14
|
+
or: wheres
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Allows what any of the given access functions allows: `true` if one returns `true`, otherwise the
|
|
19
|
+
* `or` of the query constraints they return, otherwise `false`.
|
|
20
|
+
*/ export const anyOf = (...checks)=>async (args)=>combine(await Promise.all(checks.map((check)=>check(args))));
|
|
21
|
+
/**
|
|
22
|
+
* Videos owned by the logged-in user (needs `ownership` in the plugin options). Users from other auth
|
|
23
|
+
* collections than `collection` (when given) own nothing.
|
|
24
|
+
*/ export const isVideoOwner = ({ collection, field = 'owner' } = {})=>({ req })=>{
|
|
25
|
+
const user = req.user;
|
|
26
|
+
if (!user || collection && user.collection && user.collection !== collection) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
[field]: {
|
|
31
|
+
equals: user.id
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
/** Videos a moderator approved (needs `moderation` in the plugin options). */ export const isApprovedVideo = ({ field = 'moderation' } = {})=>()=>({
|
|
36
|
+
[field]: {
|
|
37
|
+
equals: 'approved'
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
/** `access` or ownership: e.g. `ownerOr(isAdmin)` lets admins edit every video and members their own. */ export const ownerOr = (access, options = {})=>anyOf(access, isVideoOwner(options));
|
|
41
|
+
/**
|
|
42
|
+
* Read access for member uploads: approved videos for everyone, plus each user's own videos in any
|
|
43
|
+
* state. Pass `or` to let some users (e.g. moderators) read everything.
|
|
44
|
+
*/ export const approvedOrOwner = ({ moderationField, or, ownerCollection, ownerField } = {})=>anyOf(...or ? [
|
|
45
|
+
or
|
|
46
|
+
] : [], isApprovedVideo({
|
|
47
|
+
field: moderationField
|
|
48
|
+
}), isVideoOwner({
|
|
49
|
+
collection: ownerCollection,
|
|
50
|
+
field: ownerField
|
|
51
|
+
}));
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=access.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/access.ts"],"sourcesContent":["/**\n * Access-control helpers for the videos collection, for sites where members upload their own videos.\n * Nothing here is applied by default: the collection keeps whatever access you configure. Use them in\n * `collection.access`, e.g. `{ read: approvedOrOwner(), update: ownerOr(isAdmin), delete: ownerOr(isAdmin) }`.\n */\nimport type { Access, AccessArgs, AccessResult, Where } from 'payload'\n\nconst combine = (results: AccessResult[]): AccessResult => {\n if (results.some((r) => r === true)) {\n return true\n }\n const wheres = results.filter((r): r is Where => typeof r === 'object' && r !== null)\n if (wheres.length === 0) {\n return false\n }\n return wheres.length === 1 ? wheres[0]! : { or: wheres }\n}\n\n/**\n * Allows what any of the given access functions allows: `true` if one returns `true`, otherwise the\n * `or` of the query constraints they return, otherwise `false`.\n */\nexport const anyOf =\n (...checks: Access[]): Access =>\n async (args: AccessArgs) =>\n combine(await Promise.all(checks.map((check) => check(args))))\n\n/**\n * Videos owned by the logged-in user (needs `ownership` in the plugin options). Users from other auth\n * collections than `collection` (when given) own nothing.\n */\nexport const isVideoOwner =\n ({ collection, field = 'owner' }: { collection?: string; field?: string } = {}): Access =>\n ({ req }) => {\n const user = req.user as null | undefined | { collection?: string; id: number | string }\n if (!user || (collection && user.collection && user.collection !== collection)) {\n return false\n }\n return { [field]: { equals: user.id } }\n }\n\n/** Videos a moderator approved (needs `moderation` in the plugin options). */\nexport const isApprovedVideo =\n ({ field = 'moderation' }: { field?: string } = {}): Access =>\n () => ({ [field]: { equals: 'approved' } })\n\n/** `access` or ownership: e.g. `ownerOr(isAdmin)` lets admins edit every video and members their own. */\nexport const ownerOr = (access: Access, options: Parameters<typeof isVideoOwner>[0] = {}): Access =>\n anyOf(access, isVideoOwner(options))\n\n/**\n * Read access for member uploads: approved videos for everyone, plus each user's own videos in any\n * state. Pass `or` to let some users (e.g. moderators) read everything.\n */\nexport const approvedOrOwner = ({\n moderationField,\n or,\n ownerCollection,\n ownerField,\n}: { moderationField?: string; or?: Access; ownerCollection?: string; ownerField?: string } = {}): Access =>\n anyOf(\n ...(or ? [or] : []),\n isApprovedVideo({ field: moderationField }),\n isVideoOwner({ collection: ownerCollection, field: ownerField }),\n )\n"],"names":["combine","results","some","r","wheres","filter","length","or","anyOf","checks","args","Promise","all","map","check","isVideoOwner","collection","field","req","user","equals","id","isApprovedVideo","ownerOr","access","options","approvedOrOwner","moderationField","ownerCollection","ownerField"],"mappings":"AAAA;;;;CAIC,GAGD,MAAMA,UAAU,CAACC;IACf,IAAIA,QAAQC,IAAI,CAAC,CAACC,IAAMA,MAAM,OAAO;QACnC,OAAO;IACT;IACA,MAAMC,SAASH,QAAQI,MAAM,CAAC,CAACF,IAAkB,OAAOA,MAAM,YAAYA,MAAM;IAChF,IAAIC,OAAOE,MAAM,KAAK,GAAG;QACvB,OAAO;IACT;IACA,OAAOF,OAAOE,MAAM,KAAK,IAAIF,MAAM,CAAC,EAAE,GAAI;QAAEG,IAAIH;IAAO;AACzD;AAEA;;;CAGC,GACD,OAAO,MAAMI,QACX,CAAC,GAAGC,SACJ,OAAOC,OACLV,QAAQ,MAAMW,QAAQC,GAAG,CAACH,OAAOI,GAAG,CAAC,CAACC,QAAUA,MAAMJ,SAAQ;AAElE;;;CAGC,GACD,OAAO,MAAMK,eACX,CAAC,EAAEC,UAAU,EAAEC,QAAQ,OAAO,EAA2C,GAAG,CAAC,CAAC,GAC9E,CAAC,EAAEC,GAAG,EAAE;QACN,MAAMC,OAAOD,IAAIC,IAAI;QACrB,IAAI,CAACA,QAASH,cAAcG,KAAKH,UAAU,IAAIG,KAAKH,UAAU,KAAKA,YAAa;YAC9E,OAAO;QACT;QACA,OAAO;YAAE,CAACC,MAAM,EAAE;gBAAEG,QAAQD,KAAKE,EAAE;YAAC;QAAE;IACxC,EAAC;AAEH,4EAA4E,GAC5E,OAAO,MAAMC,kBACX,CAAC,EAAEL,QAAQ,YAAY,EAAsB,GAAG,CAAC,CAAC,GAClD,IAAO,CAAA;YAAE,CAACA,MAAM,EAAE;gBAAEG,QAAQ;YAAW;QAAE,CAAA,EAAE;AAE7C,uGAAuG,GACvG,OAAO,MAAMG,UAAU,CAACC,QAAgBC,UAA8C,CAAC,CAAC,GACtFjB,MAAMgB,QAAQT,aAAaU,UAAS;AAEtC;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,CAAC,EAC9BC,eAAe,EACfpB,EAAE,EACFqB,eAAe,EACfC,UAAU,EAC+E,GAAG,CAAC,CAAC,GAC9FrB,SACMD,KAAK;QAACA;KAAG,GAAG,EAAE,EAClBe,gBAAgB;QAAEL,OAAOU;IAAgB,IACzCZ,aAAa;QAAEC,YAAYY;QAAiBX,OAAOY;IAAW,IAC/D"}
|
package/dist/bin/args.d.ts
CHANGED
|
@@ -21,4 +21,17 @@ export type MigrateCliOptions = {
|
|
|
21
21
|
};
|
|
22
22
|
/** Options for `payload-video-streaming migrate-cf-stream`. */
|
|
23
23
|
export declare const parseMigrateArgs: (argv: string[]) => MigrateCliOptions;
|
|
24
|
+
export type WebhooksCliOptions = {
|
|
25
|
+
apiRoute: string;
|
|
26
|
+
check: boolean;
|
|
27
|
+
collection: string;
|
|
28
|
+
force: boolean;
|
|
29
|
+
register?: string;
|
|
30
|
+
url?: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Options for `payload-video-streaming webhooks`. The site URL falls back to `VIDEO_SITE_URL`,
|
|
34
|
+
* `PAYLOAD_PUBLIC_SERVER_URL`, `NEXT_PUBLIC_SERVER_URL` and `SERVER_URL`.
|
|
35
|
+
*/
|
|
36
|
+
export declare const parseWebhooksArgs: (argv: string[], env?: Record<string, string | undefined>) => WebhooksCliOptions;
|
|
24
37
|
export declare const CLI_USAGE: string;
|
package/dist/bin/args.js
CHANGED
|
@@ -76,9 +76,70 @@ import { FAKE_PROVIDER_IDS, isFakeProviderId } from '../testing/index.js';
|
|
|
76
76
|
to: values.to
|
|
77
77
|
};
|
|
78
78
|
};
|
|
79
|
+
/**
|
|
80
|
+
* Options for `payload-video-streaming webhooks`. The site URL falls back to `VIDEO_SITE_URL`,
|
|
81
|
+
* `PAYLOAD_PUBLIC_SERVER_URL`, `NEXT_PUBLIC_SERVER_URL` and `SERVER_URL`.
|
|
82
|
+
*/ export const parseWebhooksArgs = (argv, env = {})=>{
|
|
83
|
+
const { values } = parseArgs({
|
|
84
|
+
args: argv,
|
|
85
|
+
options: {
|
|
86
|
+
'api-route': {
|
|
87
|
+
type: 'string'
|
|
88
|
+
},
|
|
89
|
+
check: {
|
|
90
|
+
type: 'boolean'
|
|
91
|
+
},
|
|
92
|
+
collection: {
|
|
93
|
+
type: 'string'
|
|
94
|
+
},
|
|
95
|
+
force: {
|
|
96
|
+
type: 'boolean'
|
|
97
|
+
},
|
|
98
|
+
register: {
|
|
99
|
+
type: 'string'
|
|
100
|
+
},
|
|
101
|
+
url: {
|
|
102
|
+
type: 'string'
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
strict: true
|
|
106
|
+
});
|
|
107
|
+
const url = values.url ?? env.VIDEO_SITE_URL ?? env.PAYLOAD_PUBLIC_SERVER_URL ?? env.NEXT_PUBLIC_SERVER_URL ?? env.SERVER_URL;
|
|
108
|
+
if (url !== undefined) {
|
|
109
|
+
let parsed;
|
|
110
|
+
try {
|
|
111
|
+
parsed = new URL(url);
|
|
112
|
+
} catch {
|
|
113
|
+
throw new Error(`--url must be your site's public URL, e.g. https://example.com (got "${url}")`);
|
|
114
|
+
}
|
|
115
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
116
|
+
throw new Error('--url must be an http(s) URL');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if ((values.register || values.check) && !url) {
|
|
120
|
+
throw new Error(`--${values.register ? 'register' : 'check'} needs your site's public URL: --url https://example.com`);
|
|
121
|
+
}
|
|
122
|
+
const apiRoute = `/${(values['api-route'] ?? '/api').replace(/^\/+|\/+$/g, '')}`;
|
|
123
|
+
return {
|
|
124
|
+
apiRoute,
|
|
125
|
+
check: Boolean(values.check),
|
|
126
|
+
collection: values.collection ?? 'videos',
|
|
127
|
+
force: Boolean(values.force),
|
|
128
|
+
register: values.register,
|
|
129
|
+
url: url?.replace(/\/+$/, '')
|
|
130
|
+
};
|
|
131
|
+
};
|
|
79
132
|
export const CLI_USAGE = `Usage: payload-video-streaming <command> [options]
|
|
80
133
|
|
|
81
134
|
Commands:
|
|
135
|
+
webhooks Show the webhook URL to register for each provider in the environment, and how
|
|
136
|
+
--url <url> Your site's public URL (default: VIDEO_SITE_URL, PAYLOAD_PUBLIC_SERVER_URL,
|
|
137
|
+
NEXT_PUBLIC_SERVER_URL or SERVER_URL)
|
|
138
|
+
--check Check that each webhook URL is reachable and has its secret configured
|
|
139
|
+
--register <id> Register the URL through the provider's API (cloudflare) and print the secret
|
|
140
|
+
--force With --register: replace a different URL that is already registered
|
|
141
|
+
--collection <slug> The videos collection (default: videos)
|
|
142
|
+
--api-route <path> Payload's API route (default: /api)
|
|
82
143
|
migrate-cf-stream Migrate payload-cf-stream documents to the payload-video-streaming schema
|
|
83
144
|
--from <slug> The old collection (default: cf-stream-videos)
|
|
84
145
|
--to <slug> The new collection (default: the plugin's; same as --from to migrate in place)
|
package/dist/bin/args.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/args.ts"],"sourcesContent":["/** Argument parsing for the CLIs, kept free of side effects so it can be unit tested. */\nimport { parseArgs } from 'node:util'\n\nimport { FAKE_PROVIDER_IDS, type FakeProviderId, isFakeProviderId } from '../testing/index.js'\n\nexport type FakeCliOptions = {\n delayMs: number\n hlsFixtureDir?: string\n port: number\n provider: FakeProviderId\n publicUrl?: string\n}\n\n/**\n * Options for `payload-video-streaming-fake` (and `payload-video-streaming fake`). Flags win over\n * environment variables: `VIDEO_PROVIDER`, `VIDEO_FAKE_PORT` (or `PORT`), `VIDEO_FAKE_DELAY_MS`,\n * `VIDEO_FAKE_PUBLIC_URL`, `VIDEO_FAKE_HLS_DIR`.\n */\nexport const parseFakeArgs = (argv: string[], env: Record<string, string | undefined> = {}): FakeCliOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n delay: { type: 'string' },\n 'hls-fixture': { type: 'string' },\n port: { type: 'string' },\n provider: { type: 'string' },\n 'public-url': { type: 'string' },\n },\n strict: true,\n })\n const provider = values.provider ?? env.VIDEO_PROVIDER ?? 'cloudflare'\n if (!isFakeProviderId(provider)) {\n throw new Error(`Unknown provider \"${provider}\". Available: ${FAKE_PROVIDER_IDS.join(', ')}`)\n }\n const port = Number(values.port ?? env.VIDEO_FAKE_PORT ?? env.PORT ?? 4870)\n const delayMs = Number(values.delay ?? env.VIDEO_FAKE_DELAY_MS ?? 1500)\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Invalid port \"${values.port ?? env.VIDEO_FAKE_PORT ?? env.PORT}\"`)\n }\n if (!(delayMs >= 0)) {\n throw new Error('--delay must be a number of milliseconds')\n }\n return {\n delayMs,\n hlsFixtureDir: values['hls-fixture'] ?? env.VIDEO_FAKE_HLS_DIR ?? undefined,\n port,\n provider,\n publicUrl: values['public-url'] ?? env.VIDEO_FAKE_PUBLIC_URL ?? undefined,\n }\n}\n\nexport type MigrateCliOptions = {\n config?: string\n dryRun: boolean\n from: string\n provider: string\n to?: string\n}\n\n/** Options for `payload-video-streaming migrate-cf-stream`. */\nexport const parseMigrateArgs = (argv: string[]): MigrateCliOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n config: { type: 'string' },\n 'dry-run': { type: 'boolean' },\n from: { type: 'string' },\n provider: { type: 'string' },\n to: { type: 'string' },\n },\n strict: true,\n })\n return {\n config: values.config,\n dryRun: Boolean(values['dry-run']),\n from: values.from ?? 'cf-stream-videos',\n provider: values.provider ?? 'cloudflare',\n to: values.to,\n }\n}\n\nexport const CLI_USAGE = `Usage: payload-video-streaming <command> [options]\n\nCommands:\n migrate-cf-stream Migrate payload-cf-stream documents to the payload-video-streaming schema\n --from <slug> The old collection (default: cf-stream-videos)\n --to <slug> The new collection (default: the plugin's; same as --from to migrate in place)\n --provider <id> Provider id written on each document (default: cloudflare)\n --config <path> Payload config (default: PAYLOAD_CONFIG_PATH or Payload's usual locations)\n --dry-run Count what would change without writing\n fake Run an in-memory fake provider for local development\n --provider <id> ${FAKE_PROVIDER_IDS.join(' | ')} (default: cloudflare)\n --port <n> Port (default: 4870; 0 picks a free one)\n --delay <ms> Processing time of uploaded videos (default: 1500)\n --hls-fixture <dir> Serve a real HLS rendition for ready videos\n --public-url <url> Public base URL, e.g. behind a local proxy\n`\n"],"names":["parseArgs","FAKE_PROVIDER_IDS","isFakeProviderId","parseFakeArgs","argv","env","values","args","options","delay","type","port","provider","strict","VIDEO_PROVIDER","Error","join","Number","VIDEO_FAKE_PORT","PORT","delayMs","VIDEO_FAKE_DELAY_MS","isInteger","hlsFixtureDir","VIDEO_FAKE_HLS_DIR","undefined","publicUrl","VIDEO_FAKE_PUBLIC_URL","parseMigrateArgs","config","from","to","dryRun","Boolean","CLI_USAGE"],"mappings":"AAAA,uFAAuF,GACvF,SAASA,SAAS,QAAQ,YAAW;AAErC,SAASC,iBAAiB,EAAuBC,gBAAgB,QAAQ,sBAAqB;AAU9F;;;;CAIC,GACD,OAAO,MAAMC,gBAAgB,CAACC,MAAgBC,MAA0C,CAAC,CAAC;IACxF,MAAM,EAAEC,MAAM,EAAE,GAAGN,UAAU;QAC3BO,MAAMH;QACNI,SAAS;YACPC,OAAO;gBAAEC,MAAM;YAAS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ErB,MAAM;YAAS;QACvB;QACAG,QAAQ;IACV;IACA,OAAO;QACLgB,QAAQvB,OAAOuB,MAAM;QACrBG,QAAQC,QAAQ3B,MAAM,CAAC,UAAU;QACjCwB,MAAMxB,OAAOwB,IAAI,IAAI;QACrBlB,UAAUN,OAAOM,QAAQ,IAAI;QAC7BmB,IAAIzB,OAAOyB,EAAE;IACf;AACF,EAAC;
|
|
1
|
+
{"version":3,"sources":["../../src/bin/args.ts"],"sourcesContent":["/** Argument parsing for the CLIs, kept free of side effects so it can be unit tested. */\nimport { parseArgs } from 'node:util'\n\nimport { FAKE_PROVIDER_IDS, type FakeProviderId, isFakeProviderId } from '../testing/index.js'\n\nexport type FakeCliOptions = {\n delayMs: number\n hlsFixtureDir?: string\n port: number\n provider: FakeProviderId\n publicUrl?: string\n}\n\n/**\n * Options for `payload-video-streaming-fake` (and `payload-video-streaming fake`). Flags win over\n * environment variables: `VIDEO_PROVIDER`, `VIDEO_FAKE_PORT` (or `PORT`), `VIDEO_FAKE_DELAY_MS`,\n * `VIDEO_FAKE_PUBLIC_URL`, `VIDEO_FAKE_HLS_DIR`.\n */\nexport const parseFakeArgs = (argv: string[], env: Record<string, string | undefined> = {}): FakeCliOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n delay: { type: 'string' },\n 'hls-fixture': { type: 'string' },\n port: { type: 'string' },\n provider: { type: 'string' },\n 'public-url': { type: 'string' },\n },\n strict: true,\n })\n const provider = values.provider ?? env.VIDEO_PROVIDER ?? 'cloudflare'\n if (!isFakeProviderId(provider)) {\n throw new Error(`Unknown provider \"${provider}\". Available: ${FAKE_PROVIDER_IDS.join(', ')}`)\n }\n const port = Number(values.port ?? env.VIDEO_FAKE_PORT ?? env.PORT ?? 4870)\n const delayMs = Number(values.delay ?? env.VIDEO_FAKE_DELAY_MS ?? 1500)\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Invalid port \"${values.port ?? env.VIDEO_FAKE_PORT ?? env.PORT}\"`)\n }\n if (!(delayMs >= 0)) {\n throw new Error('--delay must be a number of milliseconds')\n }\n return {\n delayMs,\n hlsFixtureDir: values['hls-fixture'] ?? env.VIDEO_FAKE_HLS_DIR ?? undefined,\n port,\n provider,\n publicUrl: values['public-url'] ?? env.VIDEO_FAKE_PUBLIC_URL ?? undefined,\n }\n}\n\nexport type MigrateCliOptions = {\n config?: string\n dryRun: boolean\n from: string\n provider: string\n to?: string\n}\n\n/** Options for `payload-video-streaming migrate-cf-stream`. */\nexport const parseMigrateArgs = (argv: string[]): MigrateCliOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n config: { type: 'string' },\n 'dry-run': { type: 'boolean' },\n from: { type: 'string' },\n provider: { type: 'string' },\n to: { type: 'string' },\n },\n strict: true,\n })\n return {\n config: values.config,\n dryRun: Boolean(values['dry-run']),\n from: values.from ?? 'cf-stream-videos',\n provider: values.provider ?? 'cloudflare',\n to: values.to,\n }\n}\n\nexport type WebhooksCliOptions = {\n apiRoute: string\n check: boolean\n collection: string\n force: boolean\n register?: string\n url?: string\n}\n\n/**\n * Options for `payload-video-streaming webhooks`. The site URL falls back to `VIDEO_SITE_URL`,\n * `PAYLOAD_PUBLIC_SERVER_URL`, `NEXT_PUBLIC_SERVER_URL` and `SERVER_URL`.\n */\nexport const parseWebhooksArgs = (argv: string[], env: Record<string, string | undefined> = {}): WebhooksCliOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n 'api-route': { type: 'string' },\n check: { type: 'boolean' },\n collection: { type: 'string' },\n force: { type: 'boolean' },\n register: { type: 'string' },\n url: { type: 'string' },\n },\n strict: true,\n })\n const url = values.url ?? env.VIDEO_SITE_URL ?? env.PAYLOAD_PUBLIC_SERVER_URL ?? env.NEXT_PUBLIC_SERVER_URL ?? env.SERVER_URL\n if (url !== undefined) {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n throw new Error(`--url must be your site's public URL, e.g. https://example.com (got \"${url}\")`)\n }\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n throw new Error('--url must be an http(s) URL')\n }\n }\n if ((values.register || values.check) && !url) {\n throw new Error(`--${values.register ? 'register' : 'check'} needs your site's public URL: --url https://example.com`)\n }\n const apiRoute = `/${(values['api-route'] ?? '/api').replace(/^\\/+|\\/+$/g, '')}`\n return {\n apiRoute,\n check: Boolean(values.check),\n collection: values.collection ?? 'videos',\n force: Boolean(values.force),\n register: values.register,\n url: url?.replace(/\\/+$/, ''),\n }\n}\n\nexport const CLI_USAGE = `Usage: payload-video-streaming <command> [options]\n\nCommands:\n webhooks Show the webhook URL to register for each provider in the environment, and how\n --url <url> Your site's public URL (default: VIDEO_SITE_URL, PAYLOAD_PUBLIC_SERVER_URL,\n NEXT_PUBLIC_SERVER_URL or SERVER_URL)\n --check Check that each webhook URL is reachable and has its secret configured\n --register <id> Register the URL through the provider's API (cloudflare) and print the secret\n --force With --register: replace a different URL that is already registered\n --collection <slug> The videos collection (default: videos)\n --api-route <path> Payload's API route (default: /api)\n migrate-cf-stream Migrate payload-cf-stream documents to the payload-video-streaming schema\n --from <slug> The old collection (default: cf-stream-videos)\n --to <slug> The new collection (default: the plugin's; same as --from to migrate in place)\n --provider <id> Provider id written on each document (default: cloudflare)\n --config <path> Payload config (default: PAYLOAD_CONFIG_PATH or Payload's usual locations)\n --dry-run Count what would change without writing\n fake Run an in-memory fake provider for local development\n --provider <id> ${FAKE_PROVIDER_IDS.join(' | ')} (default: cloudflare)\n --port <n> Port (default: 4870; 0 picks a free one)\n --delay <ms> Processing time of uploaded videos (default: 1500)\n --hls-fixture <dir> Serve a real HLS rendition for ready videos\n --public-url <url> Public base URL, e.g. behind a local proxy\n`\n"],"names":["parseArgs","FAKE_PROVIDER_IDS","isFakeProviderId","parseFakeArgs","argv","env","values","args","options","delay","type","port","provider","strict","VIDEO_PROVIDER","Error","join","Number","VIDEO_FAKE_PORT","PORT","delayMs","VIDEO_FAKE_DELAY_MS","isInteger","hlsFixtureDir","VIDEO_FAKE_HLS_DIR","undefined","publicUrl","VIDEO_FAKE_PUBLIC_URL","parseMigrateArgs","config","from","to","dryRun","Boolean","parseWebhooksArgs","check","collection","force","register","url","VIDEO_SITE_URL","PAYLOAD_PUBLIC_SERVER_URL","NEXT_PUBLIC_SERVER_URL","SERVER_URL","parsed","URL","protocol","apiRoute","replace","CLI_USAGE"],"mappings":"AAAA,uFAAuF,GACvF,SAASA,SAAS,QAAQ,YAAW;AAErC,SAASC,iBAAiB,EAAuBC,gBAAgB,QAAQ,sBAAqB;AAU9F;;;;CAIC,GACD,OAAO,MAAMC,gBAAgB,CAACC,MAAgBC,MAA0C,CAAC,CAAC;IACxF,MAAM,EAAEC,MAAM,EAAE,GAAGN,UAAU;QAC3BO,MAAMH;QACNI,SAAS;YACPC,OAAO;gBAAEC,MAAM;YAAS;YACxB,eAAe;gBAAEA,MAAM;YAAS;YAChCC,MAAM;gBAAED,MAAM;YAAS;YACvBE,UAAU;gBAAEF,MAAM;YAAS;YAC3B,cAAc;gBAAEA,MAAM;YAAS;QACjC;QACAG,QAAQ;IACV;IACA,MAAMD,WAAWN,OAAOM,QAAQ,IAAIP,IAAIS,cAAc,IAAI;IAC1D,IAAI,CAACZ,iBAAiBU,WAAW;QAC/B,MAAM,IAAIG,MAAM,CAAC,kBAAkB,EAAEH,SAAS,cAAc,EAAEX,kBAAkBe,IAAI,CAAC,OAAO;IAC9F;IACA,MAAML,OAAOM,OAAOX,OAAOK,IAAI,IAAIN,IAAIa,eAAe,IAAIb,IAAIc,IAAI,IAAI;IACtE,MAAMC,UAAUH,OAAOX,OAAOG,KAAK,IAAIJ,IAAIgB,mBAAmB,IAAI;IAClE,IAAI,CAACJ,OAAOK,SAAS,CAACX,SAASA,OAAO,KAAKA,OAAO,OAAO;QACvD,MAAM,IAAII,MAAM,CAAC,cAAc,EAAET,OAAOK,IAAI,IAAIN,IAAIa,eAAe,IAAIb,IAAIc,IAAI,CAAC,CAAC,CAAC;IACpF;IACA,IAAI,CAAEC,CAAAA,WAAW,CAAA,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IAAIrC,IAAIsC,UAAU;IAC7H,IAAIJ,QAAQd,WAAW;QACrB,IAAImB;QACJ,IAAI;YACFA,SAAS,IAAIC,IAAIN;QACnB,EAAE,OAAM;YACN,MAAM,IAAIxB,MAAM,CAAC,qEAAqE,EAAEwB,IAAI,EAAE,CAAC;QACjG;QACA,IAAIK,OAAOE,QAAQ,KAAK,YAAYF,OAAOE,QAAQ,KAAK,SAAS;YAC/D,MAAM,IAAI/B,MAAM;QAClB;IACF;IACA,IAAI,AAACT,CAAAA,OAAOgC,QAAQ,IAAIhC,OAAO6B,KAAK,AAAD,KAAM,CAACI,KAAK;QAC7C,MAAM,IAAIxB,MAAM,CAAC,EAAE,EAAET,OAAOgC,QAAQ,GAAG,aAAa,QAAQ,wDAAwD,CAAC;IACvH;IACA,MAAMS,WAAW,CAAC,CAAC,EAAE,AAACzC,CAAAA,MAAM,CAAC,YAAY,IAAI,MAAK,EAAG0C,OAAO,CAAC,cAAc,KAAK;IAChF,OAAO;QACLD;QACAZ,OAAOF,QAAQ3B,OAAO6B,KAAK;QAC3BC,YAAY9B,OAAO8B,UAAU,IAAI;QACjCC,OAAOJ,QAAQ3B,OAAO+B,KAAK;QAC3BC,UAAUhC,OAAOgC,QAAQ;QACzBC,KAAKA,KAAKS,QAAQ,QAAQ;IAC5B;AACF,EAAC;AAED,OAAO,MAAMC,YAAY,CAAC;;;;;;;;;;;;;;;;;;wBAkBF,EAAEhD,kBAAkBe,IAAI,CAAC,OAAO;;;;;AAKxD,CAAC,CAAA"}
|
package/dist/bin/cli.js
CHANGED
|
@@ -3,7 +3,15 @@
|
|
|
3
3
|
* `npx payload-video-streaming <command>`: see CLI_USAGE in ./args.ts.
|
|
4
4
|
*/ import { CLI_USAGE } from './args.js';
|
|
5
5
|
const [command, ...rest] = process.argv.slice(2);
|
|
6
|
-
if (command === '
|
|
6
|
+
if (command === 'webhooks') {
|
|
7
|
+
// Read the app's .env like Payload's own CLI does (variables already set win).
|
|
8
|
+
const { existsSync } = await import('node:fs');
|
|
9
|
+
if (existsSync('.env') && typeof process.loadEnvFile === 'function') {
|
|
10
|
+
process.loadEnvFile('.env');
|
|
11
|
+
}
|
|
12
|
+
const { runWebhooks } = await import('./webhooks.js');
|
|
13
|
+
process.exitCode = await runWebhooks(rest);
|
|
14
|
+
} else if (command === 'migrate-cf-stream') {
|
|
7
15
|
const { runMigrateCfStream } = await import('./migrate.js');
|
|
8
16
|
process.exitCode = await runMigrateCfStream(rest);
|
|
9
17
|
} else if (command === 'fake') {
|
package/dist/bin/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `npx payload-video-streaming <command>`: see CLI_USAGE in ./args.ts.\n */\nimport { CLI_USAGE } from './args.js'\n\nconst [command, ...rest] = process.argv.slice(2)\n\nif (command === 'migrate-cf-stream') {\n const { runMigrateCfStream } = await import('./migrate.js')\n process.exitCode = await runMigrateCfStream(rest)\n} else if (command === 'fake') {\n const { runFake } = await import('./runFake.js')\n await runFake(rest)\n} else {\n console.log(CLI_USAGE)\n process.exitCode = command && command !== 'help' && command !== '--help' ? 1 : 0\n}\n"],"names":["CLI_USAGE","command","rest","process","argv","slice","
|
|
1
|
+
{"version":3,"sources":["../../src/bin/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `npx payload-video-streaming <command>`: see CLI_USAGE in ./args.ts.\n */\nimport { CLI_USAGE } from './args.js'\n\nconst [command, ...rest] = process.argv.slice(2)\n\nif (command === 'webhooks') {\n // Read the app's .env like Payload's own CLI does (variables already set win).\n const { existsSync } = await import('node:fs')\n if (existsSync('.env') && typeof process.loadEnvFile === 'function') {\n process.loadEnvFile('.env')\n }\n const { runWebhooks } = await import('./webhooks.js')\n process.exitCode = await runWebhooks(rest)\n} else if (command === 'migrate-cf-stream') {\n const { runMigrateCfStream } = await import('./migrate.js')\n process.exitCode = await runMigrateCfStream(rest)\n} else if (command === 'fake') {\n const { runFake } = await import('./runFake.js')\n await runFake(rest)\n} else {\n console.log(CLI_USAGE)\n process.exitCode = command && command !== 'help' && command !== '--help' ? 1 : 0\n}\n"],"names":["CLI_USAGE","command","rest","process","argv","slice","existsSync","loadEnvFile","runWebhooks","exitCode","runMigrateCfStream","runFake","console","log"],"mappings":";AACA;;CAEC,GACD,SAASA,SAAS,QAAQ,YAAW;AAErC,MAAM,CAACC,SAAS,GAAGC,KAAK,GAAGC,QAAQC,IAAI,CAACC,KAAK,CAAC;AAE9C,IAAIJ,YAAY,YAAY;IAC1B,+EAA+E;IAC/E,MAAM,EAAEK,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC;IACpC,IAAIA,WAAW,WAAW,OAAOH,QAAQI,WAAW,KAAK,YAAY;QACnEJ,QAAQI,WAAW,CAAC;IACtB;IACA,MAAM,EAAEC,WAAW,EAAE,GAAG,MAAM,MAAM,CAAC;IACrCL,QAAQM,QAAQ,GAAG,MAAMD,YAAYN;AACvC,OAAO,IAAID,YAAY,qBAAqB;IAC1C,MAAM,EAAES,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC5CP,QAAQM,QAAQ,GAAG,MAAMC,mBAAmBR;AAC9C,OAAO,IAAID,YAAY,QAAQ;IAC7B,MAAM,EAAEU,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC;IACjC,MAAMA,QAAQT;AAChB,OAAO;IACLU,QAAQC,GAAG,CAACb;IACZG,QAAQM,QAAQ,GAAGR,WAAWA,YAAY,UAAUA,YAAY,WAAW,IAAI;AACjF"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Env = Record<string, string | undefined>;
|
|
2
|
+
export type WebhooksCliIO = {
|
|
3
|
+
env?: Env;
|
|
4
|
+
error?: (line: string) => void;
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
log?: (line: string) => void;
|
|
7
|
+
};
|
|
8
|
+
export type WebhookCheck = {
|
|
9
|
+
ok: boolean;
|
|
10
|
+
message: string;
|
|
11
|
+
};
|
|
12
|
+
/** What an unsigned POST to a webhook URL says about it. */
|
|
13
|
+
export declare const interpretWebhookCheck: (status: number, body: string) => WebhookCheck;
|
|
14
|
+
export declare const runWebhooks: (argv: string[], io?: WebhooksCliIO) => Promise<number>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `payload-video-streaming webhooks`: for every provider configured in the environment, shows the
|
|
3
|
+
* webhook URL to register and how; `--check` tests deployed URLs; `--register cloudflare` registers
|
|
4
|
+
* the URL through Cloudflare's API and prints the secret.
|
|
5
|
+
*/ import { videoOptionsFromEnv } from '../env.js';
|
|
6
|
+
import { StreamClient } from '../providers/cloudflare/client.js';
|
|
7
|
+
import { cloudflareOptionsFromEnv } from '../providers/cloudflare/env.js';
|
|
8
|
+
import { parseWebhooksArgs } from './args.js';
|
|
9
|
+
/** What an unsigned POST to a webhook URL says about it. */ export const interpretWebhookCheck = (status, body)=>{
|
|
10
|
+
let message = '';
|
|
11
|
+
try {
|
|
12
|
+
message = JSON.parse(body).errors?.[0]?.message ?? '';
|
|
13
|
+
} catch {
|
|
14
|
+
/* not JSON */ }
|
|
15
|
+
if (status === 401) {
|
|
16
|
+
return {
|
|
17
|
+
message: 'reachable, and the secret is configured (unsigned test request refused as expected)',
|
|
18
|
+
ok: true
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
if (status === 404 && /not configured/i.test(message)) {
|
|
22
|
+
return {
|
|
23
|
+
message: `reachable, but the server has no webhook secret: ${message}`,
|
|
24
|
+
ok: false
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
if (status === 404) {
|
|
28
|
+
return {
|
|
29
|
+
message: 'not found: check the URL, --collection and --api-route, and that the deployed site runs this plugin',
|
|
30
|
+
ok: false
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (status === 502 || status === 503 || status === 504) {
|
|
34
|
+
return {
|
|
35
|
+
message: `HTTP ${status}: the URL answers, but no app is serving behind it. Is the site (or the app behind your tunnel) running?`,
|
|
36
|
+
ok: false
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
if (status === 501) {
|
|
40
|
+
return {
|
|
41
|
+
message: `this provider doesn't support webhooks${message ? `: ${message}` : ''}`,
|
|
42
|
+
ok: false
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
message: `unexpected HTTP ${status}${message ? `: ${message}` : ''}`,
|
|
47
|
+
ok: false
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
export const runWebhooks = async (argv, io = {})=>{
|
|
51
|
+
const env = io.env ?? process.env;
|
|
52
|
+
const log = io.log ?? ((line)=>process.stdout.write(`${line}\n`));
|
|
53
|
+
const error = io.error ?? ((line)=>process.stderr.write(`${line}\n`));
|
|
54
|
+
const doFetch = io.fetch ?? fetch;
|
|
55
|
+
let options;
|
|
56
|
+
try {
|
|
57
|
+
options = parseWebhooksArgs(argv, env);
|
|
58
|
+
} catch (err) {
|
|
59
|
+
error(err.message);
|
|
60
|
+
return 1;
|
|
61
|
+
}
|
|
62
|
+
let providers;
|
|
63
|
+
try {
|
|
64
|
+
providers = videoOptionsFromEnv({}, env).providers;
|
|
65
|
+
} catch (err) {
|
|
66
|
+
error(err.message);
|
|
67
|
+
return 1;
|
|
68
|
+
}
|
|
69
|
+
if (providers.length === 0) {
|
|
70
|
+
error('No provider credentials in the environment (CLOUDFLARE_*, MUX_* or BUNNY_* variables). Run this where your app runs, or load its .env first.');
|
|
71
|
+
return 1;
|
|
72
|
+
}
|
|
73
|
+
const base = options.url ?? '<your site>';
|
|
74
|
+
const urlFor = (provider)=>`${base}${options.apiRoute}/${options.collection}/webhook/${provider.id}`;
|
|
75
|
+
if (options.register) {
|
|
76
|
+
const provider = providers.find((p)=>p.id === options.register);
|
|
77
|
+
if (!provider) {
|
|
78
|
+
error(`No provider "${options.register}" in the environment. Configured: ${providers.map((p)=>p.id).join(', ')}`);
|
|
79
|
+
return 1;
|
|
80
|
+
}
|
|
81
|
+
if (!provider.webhookSetup?.apiRegistration || provider.id !== 'cloudflare') {
|
|
82
|
+
error(`${provider.label} webhooks are registered in its dashboard, not through the API:`);
|
|
83
|
+
provider.webhookSetup?.steps.forEach((step, i)=>error(` ${i + 1}. ${step.replaceAll('{url}', urlFor(provider))}`));
|
|
84
|
+
return 1;
|
|
85
|
+
}
|
|
86
|
+
const cf = cloudflareOptionsFromEnv(env);
|
|
87
|
+
const client = new StreamClient({
|
|
88
|
+
accountId: cf.accountId,
|
|
89
|
+
apiBaseUrl: cf.apiBaseUrl,
|
|
90
|
+
apiToken: cf.apiToken,
|
|
91
|
+
fetch: doFetch
|
|
92
|
+
});
|
|
93
|
+
const url = urlFor(provider);
|
|
94
|
+
const existing = await client.getWebhook();
|
|
95
|
+
if (existing?.notificationUrl && existing.notificationUrl !== url && !options.force) {
|
|
96
|
+
error(`This Cloudflare account already sends its webhook to ${existing.notificationUrl}.`);
|
|
97
|
+
error('Each account has one webhook URL. Pass --force to replace it.');
|
|
98
|
+
return 1;
|
|
99
|
+
}
|
|
100
|
+
const webhook = await client.setWebhook(url);
|
|
101
|
+
log(`Registered ${url} as the Cloudflare Stream webhook.`);
|
|
102
|
+
log('Set this secret where your app runs (it replaces any previous one):');
|
|
103
|
+
log(`CLOUDFLARE_STREAM_WEBHOOK_SECRET=${webhook.secret}`);
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
let failed = false;
|
|
107
|
+
for (const provider of providers){
|
|
108
|
+
const url = urlFor(provider);
|
|
109
|
+
log(`${provider.label} (${provider.id})`);
|
|
110
|
+
if (!provider.capabilities.webhooks) {
|
|
111
|
+
log(" This provider doesn't send webhooks. Use syncPendingTask to keep videos up to date.");
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
log(` URL: ${url}`);
|
|
115
|
+
const setup = provider.webhookSetup;
|
|
116
|
+
if (setup) {
|
|
117
|
+
log(` Secret: ${setup.secret}, ${provider.webhook ? 'set in this environment' : 'NOT set in this environment'}`);
|
|
118
|
+
log(` Its value: ${setup.secretLocation}`);
|
|
119
|
+
setup.steps.forEach((step, i)=>log(` ${i + 1}. ${step.replaceAll('{url}', url)}`));
|
|
120
|
+
} else {
|
|
121
|
+
log(` Secret: ${provider.webhook ? 'configured' : 'not configured'}`);
|
|
122
|
+
}
|
|
123
|
+
if (options.check) {
|
|
124
|
+
try {
|
|
125
|
+
const res = await doFetch(url, {
|
|
126
|
+
body: '{}',
|
|
127
|
+
headers: {
|
|
128
|
+
'content-type': 'application/json'
|
|
129
|
+
},
|
|
130
|
+
method: 'POST'
|
|
131
|
+
});
|
|
132
|
+
const check = interpretWebhookCheck(res.status, await res.text());
|
|
133
|
+
log(` Check: ${check.ok ? 'OK' : 'PROBLEM'}: ${check.message}`);
|
|
134
|
+
failed ||= !check.ok;
|
|
135
|
+
} catch (err) {
|
|
136
|
+
log(` Check: PROBLEM: unreachable (${err.message})`);
|
|
137
|
+
failed = true;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
log('');
|
|
141
|
+
}
|
|
142
|
+
if (!options.url) {
|
|
143
|
+
log('Pass --url https://your-site.com (or set VIDEO_SITE_URL) to print complete URLs.');
|
|
144
|
+
}
|
|
145
|
+
log('Providers must reach your site: in development, expose it with a tunnel, e.g. `cloudflared tunnel --url http://localhost:3000`.');
|
|
146
|
+
return failed ? 1 : 0;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
//# sourceMappingURL=webhooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/bin/webhooks.ts"],"sourcesContent":["/**\n * `payload-video-streaming webhooks`: for every provider configured in the environment, shows the\n * webhook URL to register and how; `--check` tests deployed URLs; `--register cloudflare` registers\n * the URL through Cloudflare's API and prints the secret.\n */\nimport type { VideoProvider } from '../core/provider.js'\n\nimport { videoOptionsFromEnv } from '../env.js'\nimport { StreamClient } from '../providers/cloudflare/client.js'\nimport { cloudflareOptionsFromEnv } from '../providers/cloudflare/env.js'\nimport { parseWebhooksArgs } from './args.js'\n\ntype Env = Record<string, string | undefined>\n\nexport type WebhooksCliIO = {\n env?: Env\n error?: (line: string) => void\n fetch?: typeof fetch\n log?: (line: string) => void\n}\n\nexport type WebhookCheck = { ok: boolean; message: string }\n\n/** What an unsigned POST to a webhook URL says about it. */\nexport const interpretWebhookCheck = (status: number, body: string): WebhookCheck => {\n let message = ''\n try {\n message = (JSON.parse(body) as { errors?: { message?: string }[] }).errors?.[0]?.message ?? ''\n } catch {\n /* not JSON */\n }\n if (status === 401) {\n return { message: 'reachable, and the secret is configured (unsigned test request refused as expected)', ok: true }\n }\n if (status === 404 && /not configured/i.test(message)) {\n return { message: `reachable, but the server has no webhook secret: ${message}`, ok: false }\n }\n if (status === 404) {\n return {\n message: 'not found: check the URL, --collection and --api-route, and that the deployed site runs this plugin',\n ok: false,\n }\n }\n if (status === 502 || status === 503 || status === 504) {\n return { message: `HTTP ${status}: the URL answers, but no app is serving behind it. Is the site (or the app behind your tunnel) running?`, ok: false }\n }\n if (status === 501) {\n return { message: `this provider doesn't support webhooks${message ? `: ${message}` : ''}`, ok: false }\n }\n return { message: `unexpected HTTP ${status}${message ? `: ${message}` : ''}`, ok: false }\n}\n\nexport const runWebhooks = async (argv: string[], io: WebhooksCliIO = {}): Promise<number> => {\n const env = io.env ?? process.env\n const log = io.log ?? ((line: string) => process.stdout.write(`${line}\\n`))\n const error = io.error ?? ((line: string) => process.stderr.write(`${line}\\n`))\n const doFetch = io.fetch ?? fetch\n\n let options: ReturnType<typeof parseWebhooksArgs>\n try {\n options = parseWebhooksArgs(argv, env)\n } catch (err) {\n error((err as Error).message)\n return 1\n }\n\n let providers: VideoProvider[]\n try {\n providers = videoOptionsFromEnv({}, env).providers\n } catch (err) {\n error((err as Error).message)\n return 1\n }\n if (providers.length === 0) {\n error('No provider credentials in the environment (CLOUDFLARE_*, MUX_* or BUNNY_* variables). Run this where your app runs, or load its .env first.')\n return 1\n }\n\n const base = options.url ?? '<your site>'\n const urlFor = (provider: VideoProvider) => `${base}${options.apiRoute}/${options.collection}/webhook/${provider.id}`\n\n if (options.register) {\n const provider = providers.find((p) => p.id === options.register)\n if (!provider) {\n error(`No provider \"${options.register}\" in the environment. Configured: ${providers.map((p) => p.id).join(', ')}`)\n return 1\n }\n if (!provider.webhookSetup?.apiRegistration || provider.id !== 'cloudflare') {\n error(`${provider.label} webhooks are registered in its dashboard, not through the API:`)\n provider.webhookSetup?.steps.forEach((step, i) => error(` ${i + 1}. ${step.replaceAll('{url}', urlFor(provider))}`))\n return 1\n }\n const cf = cloudflareOptionsFromEnv(env)!\n const client = new StreamClient({ accountId: cf.accountId, apiBaseUrl: cf.apiBaseUrl, apiToken: cf.apiToken, fetch: doFetch })\n const url = urlFor(provider)\n const existing = await client.getWebhook()\n if (existing?.notificationUrl && existing.notificationUrl !== url && !options.force) {\n error(`This Cloudflare account already sends its webhook to ${existing.notificationUrl}.`)\n error('Each account has one webhook URL. Pass --force to replace it.')\n return 1\n }\n const webhook = await client.setWebhook(url)\n log(`Registered ${url} as the Cloudflare Stream webhook.`)\n log('Set this secret where your app runs (it replaces any previous one):')\n log(`CLOUDFLARE_STREAM_WEBHOOK_SECRET=${webhook.secret}`)\n return 0\n }\n\n let failed = false\n for (const provider of providers) {\n const url = urlFor(provider)\n log(`${provider.label} (${provider.id})`)\n if (!provider.capabilities.webhooks) {\n log(\" This provider doesn't send webhooks. Use syncPendingTask to keep videos up to date.\")\n continue\n }\n log(` URL: ${url}`)\n const setup = provider.webhookSetup\n if (setup) {\n log(` Secret: ${setup.secret}, ${provider.webhook ? 'set in this environment' : 'NOT set in this environment'}`)\n log(` Its value: ${setup.secretLocation}`)\n setup.steps.forEach((step, i) => log(` ${i + 1}. ${step.replaceAll('{url}', url)}`))\n } else {\n log(` Secret: ${provider.webhook ? 'configured' : 'not configured'}`)\n }\n if (options.check) {\n try {\n const res = await doFetch(url, { body: '{}', headers: { 'content-type': 'application/json' }, method: 'POST' })\n const check = interpretWebhookCheck(res.status, await res.text())\n log(` Check: ${check.ok ? 'OK' : 'PROBLEM'}: ${check.message}`)\n failed ||= !check.ok\n } catch (err) {\n log(` Check: PROBLEM: unreachable (${(err as Error).message})`)\n failed = true\n }\n }\n log('')\n }\n if (!options.url) {\n log('Pass --url https://your-site.com (or set VIDEO_SITE_URL) to print complete URLs.')\n }\n log('Providers must reach your site: in development, expose it with a tunnel, e.g. `cloudflared tunnel --url http://localhost:3000`.')\n return failed ? 1 : 0\n}\n"],"names":["videoOptionsFromEnv","StreamClient","cloudflareOptionsFromEnv","parseWebhooksArgs","interpretWebhookCheck","status","body","message","JSON","parse","errors","ok","test","runWebhooks","argv","io","env","process","log","line","stdout","write","error","stderr","doFetch","fetch","options","err","providers","length","base","url","urlFor","provider","apiRoute","collection","id","register","find","p","map","join","webhookSetup","apiRegistration","label","steps","forEach","step","i","replaceAll","cf","client","accountId","apiBaseUrl","apiToken","existing","getWebhook","notificationUrl","force","webhook","setWebhook","secret","failed","capabilities","webhooks","setup","secretLocation","check","res","headers","method","text"],"mappings":"AAAA;;;;CAIC,GAGD,SAASA,mBAAmB,QAAQ,YAAW;AAC/C,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,wBAAwB,QAAQ,iCAAgC;AACzE,SAASC,iBAAiB,QAAQ,YAAW;AAa7C,0DAA0D,GAC1D,OAAO,MAAMC,wBAAwB,CAACC,QAAgBC;IACpD,IAAIC,UAAU;IACd,IAAI;QACFA,UAAU,AAACC,KAAKC,KAAK,CAACH,MAA8CI,MAAM,EAAE,CAAC,EAAE,EAAEH,WAAW;IAC9F,EAAE,OAAM;IACN,YAAY,GACd;IACA,IAAIF,WAAW,KAAK;QAClB,OAAO;YAAEE,SAAS;YAAuFI,IAAI;QAAK;IACpH;IACA,IAAIN,WAAW,OAAO,kBAAkBO,IAAI,CAACL,UAAU;QACrD,OAAO;YAAEA,SAAS,CAAC,iDAAiD,EAAEA,SAAS;YAAEI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AO,EAAE;gBAChEuD,WAAW,CAACK,MAAMxD,EAAE;YACtB,EAAE,OAAOgB,KAAK;gBACZT,IAAI,CAAC,gCAAgC,EAAE,AAACS,IAAcpB,OAAO,CAAC,CAAC,CAAC;gBAChEuD,SAAS;YACX;QACF;QACA5C,IAAI;IACN;IACA,IAAI,CAACQ,QAAQK,GAAG,EAAE;QAChBb,IAAI;IACN;IACAA,IAAI;IACJ,OAAO4C,SAAS,IAAI;AACtB,EAAC"}
|
package/dist/collection.js
CHANGED
|
@@ -26,6 +26,98 @@ const readOnly = {
|
|
|
26
26
|
const id = doc?.provider ?? service.providers.defaultId;
|
|
27
27
|
return !id || !service.providers.has(id) || check(service.providers.get(id).capabilities);
|
|
28
28
|
};
|
|
29
|
+
const ownerField = (ownership)=>{
|
|
30
|
+
/** Set from the uploader on create; only `canAssign` users (or server code without a user) change it. */ const hook = async ({ operation, originalDoc, req, value })=>{
|
|
31
|
+
if (operation !== 'create' && operation !== 'update') {
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
const user = req.user;
|
|
35
|
+
if (!user) {
|
|
36
|
+
return value ?? (operation === 'update' ? originalDoc?.[ownership.field] : null) ?? null;
|
|
37
|
+
}
|
|
38
|
+
const canAssign = await ownership.canAssign({
|
|
39
|
+
req
|
|
40
|
+
});
|
|
41
|
+
if (operation === 'update') {
|
|
42
|
+
return canAssign ? value : originalDoc?.[ownership.field] ?? null;
|
|
43
|
+
}
|
|
44
|
+
if (canAssign && value !== undefined && value !== null && value !== '') {
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
return !user.collection || user.collection === ownership.relationTo ? user.id : null;
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
name: ownership.field,
|
|
51
|
+
type: 'relationship',
|
|
52
|
+
access: {
|
|
53
|
+
update: ({ req })=>!req.user || ownership.canAssign({
|
|
54
|
+
req
|
|
55
|
+
})
|
|
56
|
+
},
|
|
57
|
+
admin: {
|
|
58
|
+
description: 'Who uploaded the video',
|
|
59
|
+
position: 'sidebar'
|
|
60
|
+
},
|
|
61
|
+
hooks: {
|
|
62
|
+
beforeChange: [
|
|
63
|
+
hook
|
|
64
|
+
]
|
|
65
|
+
},
|
|
66
|
+
index: true,
|
|
67
|
+
relationTo: ownership.relationTo
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
const moderationField = (moderation)=>{
|
|
71
|
+
/** New videos get `defaultStatus`; only moderators (or server code without a user) change it. */ const hook = async ({ operation, originalDoc, req, value })=>{
|
|
72
|
+
if (operation !== 'create' && operation !== 'update') {
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
const canModerate = !req.user || await moderation.canModerate({
|
|
76
|
+
req
|
|
77
|
+
});
|
|
78
|
+
const previous = originalDoc?.[moderation.field];
|
|
79
|
+
if (operation === 'update') {
|
|
80
|
+
return canModerate ? value ?? previous ?? null : previous ?? null;
|
|
81
|
+
}
|
|
82
|
+
return canModerate && value ? value : await moderation.defaultStatus({
|
|
83
|
+
canModerate,
|
|
84
|
+
req
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
name: moderation.field,
|
|
89
|
+
type: 'select',
|
|
90
|
+
access: {
|
|
91
|
+
update: ({ req })=>!req.user || moderation.canModerate({
|
|
92
|
+
req
|
|
93
|
+
})
|
|
94
|
+
},
|
|
95
|
+
admin: {
|
|
96
|
+
description: 'Review state of the video',
|
|
97
|
+
position: 'sidebar'
|
|
98
|
+
},
|
|
99
|
+
hooks: {
|
|
100
|
+
beforeChange: [
|
|
101
|
+
hook
|
|
102
|
+
]
|
|
103
|
+
},
|
|
104
|
+
index: true,
|
|
105
|
+
options: [
|
|
106
|
+
{
|
|
107
|
+
label: 'Pending review',
|
|
108
|
+
value: 'pending'
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
label: 'Approved',
|
|
112
|
+
value: 'approved'
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
label: 'Rejected',
|
|
116
|
+
value: 'rejected'
|
|
117
|
+
}
|
|
118
|
+
]
|
|
119
|
+
};
|
|
120
|
+
};
|
|
29
121
|
/** Fields managed by the providers (kept in sync by the plugin). */ const buildFields = (service, enabled)=>{
|
|
30
122
|
const clientProps = adminClientProps(service);
|
|
31
123
|
const perVideoSigning = supports(service, (caps)=>caps.signedPlayback === 'video');
|
|
@@ -38,10 +130,18 @@ const readOnly = {
|
|
|
38
130
|
}
|
|
39
131
|
try {
|
|
40
132
|
const allowed = await service.checkExtraAccess(service.options.access.playback, req, doc);
|
|
41
|
-
|
|
133
|
+
const playback = await service.getPlayback(doc, {
|
|
42
134
|
localSigningOnly: true,
|
|
43
135
|
sign: allowed
|
|
44
136
|
});
|
|
137
|
+
// `access.playback` decides who receives playback URLs, signed or not.
|
|
138
|
+
return allowed ? playback : {
|
|
139
|
+
...playback,
|
|
140
|
+
expiresAt: undefined,
|
|
141
|
+
signed: false,
|
|
142
|
+
token: undefined,
|
|
143
|
+
urls: null
|
|
144
|
+
};
|
|
45
145
|
} catch (err) {
|
|
46
146
|
req.payload.logger.warn({
|
|
47
147
|
err,
|
|
@@ -95,6 +195,12 @@ const readOnly = {
|
|
|
95
195
|
} : {},
|
|
96
196
|
index: true
|
|
97
197
|
},
|
|
198
|
+
...service.options.ownership ? [
|
|
199
|
+
ownerField(service.options.ownership)
|
|
200
|
+
] : [],
|
|
201
|
+
...service.options.moderation ? [
|
|
202
|
+
moderationField(service.options.moderation)
|
|
203
|
+
] : [],
|
|
98
204
|
{
|
|
99
205
|
name: 'assetId',
|
|
100
206
|
type: 'text',
|
|
@@ -406,6 +512,44 @@ const readOnly = {
|
|
|
406
512
|
}
|
|
407
513
|
return data;
|
|
408
514
|
};
|
|
515
|
+
/** Runs the lifecycle hooks when `status` changes. Their errors are logged, never thrown. */ const afterChange = async ({ doc, operation, previousDoc, req })=>{
|
|
516
|
+
const { afterStatusChange, onError, onReady } = service.options.hooks;
|
|
517
|
+
if (!afterStatusChange && !onError && !onReady) {
|
|
518
|
+
return doc;
|
|
519
|
+
}
|
|
520
|
+
const video = doc;
|
|
521
|
+
const previous = operation === 'create' ? undefined : previousDoc;
|
|
522
|
+
const previousStatus = previous?.status ?? null;
|
|
523
|
+
if (!video.status || video.status === previousStatus) {
|
|
524
|
+
return doc;
|
|
525
|
+
}
|
|
526
|
+
const args = {
|
|
527
|
+
doc: video,
|
|
528
|
+
previousDoc: previous,
|
|
529
|
+
previousStatus,
|
|
530
|
+
req,
|
|
531
|
+
status: video.status
|
|
532
|
+
};
|
|
533
|
+
const hooks = [
|
|
534
|
+
afterStatusChange,
|
|
535
|
+
video.status === 'ready' ? onReady : undefined,
|
|
536
|
+
video.status === 'error' ? onError : undefined
|
|
537
|
+
];
|
|
538
|
+
for (const hook of hooks){
|
|
539
|
+
if (!hook) {
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
try {
|
|
543
|
+
await hook(args);
|
|
544
|
+
} catch (err) {
|
|
545
|
+
req.payload.logger.error({
|
|
546
|
+
err,
|
|
547
|
+
msg: `[${PKG}] a lifecycle hook failed for video ${String(video.id)}`
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return doc;
|
|
552
|
+
};
|
|
409
553
|
const afterDelete = async ({ doc, req })=>{
|
|
410
554
|
const video = doc;
|
|
411
555
|
if (!service.options.deleteFromProvider || !video.provider || !service.providers.has(video.provider)) {
|
|
@@ -498,6 +642,9 @@ const readOnly = {
|
|
|
498
642
|
endpoints: enabled ? buildEndpoints(service) : [],
|
|
499
643
|
fields: buildFields(service, enabled),
|
|
500
644
|
hooks: enabled ? {
|
|
645
|
+
afterChange: [
|
|
646
|
+
afterChange
|
|
647
|
+
],
|
|
501
648
|
afterDelete: [
|
|
502
649
|
afterDelete
|
|
503
650
|
],
|