convex-mux-component 0.1.6
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 +268 -0
- package/_generated/api.ts +16 -0
- package/_generated/dataModel.ts +60 -0
- package/_generated/server.ts +156 -0
- package/catalog.ts +78 -0
- package/convex.config.ts +5 -0
- package/package.json +55 -0
- package/schema.ts +106 -0
- package/sync.ts +430 -0
- package/videos.ts +111 -0
package/README.md
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
# Convex Mux Component
|
|
2
|
+
|
|
3
|
+
Yo!
|
|
4
|
+
|
|
5
|
+
We made a reusable Convex component for apps that use Mux for video and Convex for backend data. We hear from devs and want to make it easier for you to build video apps with a database. Think about it, if you want to build the next TikTok, Instagram, or YouTube, you can use this component to get you started or even migrate your existing data from Mux to Convex and go from there!
|
|
6
|
+
|
|
7
|
+
Here's what this component provides:
|
|
8
|
+
|
|
9
|
+
- Convex tables for Mux `assets`, `uploads`, `liveStreams`, and `events`
|
|
10
|
+
- Upsert/delete mutations to keep those tables in sync
|
|
11
|
+
- App-level `videoMetadata` storage (`userId`, title, visibility, tags, custom fields)
|
|
12
|
+
- Query helpers for catalog and user-facing video data
|
|
13
|
+
|
|
14
|
+
## Runtime Model (important info!)
|
|
15
|
+
|
|
16
|
+
This package follows Convex component best practices:
|
|
17
|
+
|
|
18
|
+
- The component package contains only component code (`convex.config.ts`, schema, queries, mutations)
|
|
19
|
+
- Node runtime integration code (Mux SDK calls, webhook verification, backfills) lives in the consuming app
|
|
20
|
+
- No CLI `bin` is shipped in the component package itself
|
|
21
|
+
|
|
22
|
+
This is intentional and avoids bundling/runtime friction in consumer projects.
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
## End-to-End Setup (From Scratch)
|
|
26
|
+
|
|
27
|
+
## 1) Create a Convex app
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npx create-convex@latest my-video-app
|
|
31
|
+
cd my-video-app
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
If you use Bun:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
bun install
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Then start Convex once to provision/select your deployment:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
npx convex dev
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
(You can use `bunx convex dev` if you prefer.)
|
|
47
|
+
|
|
48
|
+
## 2) Install this component
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
npm i convex-mux-component
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## 3) Mount the component
|
|
55
|
+
|
|
56
|
+
Create or update `convex/convex.config.ts`:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { defineApp } from "convex/server";
|
|
60
|
+
import mux from "convex-mux-component/convex.config.js";
|
|
61
|
+
|
|
62
|
+
const app = defineApp();
|
|
63
|
+
app.use(mux, { name: "mux" });
|
|
64
|
+
|
|
65
|
+
export default app;
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`mux` is your mounted component name. If you use a different name, update all `components.mux...` calls accordingly. So basically if you want your table to be named `muxVideos`, you should mount it as `mux` and use `components.muxVideos` in your code.
|
|
69
|
+
|
|
70
|
+
## 4) Add app-level wrappers (backfill + webhook)
|
|
71
|
+
|
|
72
|
+
Use the scaffolder package we provided for you.This is a really fast way to migrate your data from Mux to Convex:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
npx convex-mux-init --component-name mux
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
If `convex-mux-init` is not published yet, use the local tarball flow in
|
|
79
|
+
`Optional: Scaffold Package In This Repo`.
|
|
80
|
+
|
|
81
|
+
This creates:
|
|
82
|
+
|
|
83
|
+
- `convex/migrations.ts`
|
|
84
|
+
- `convex/muxWebhook.node.ts`
|
|
85
|
+
|
|
86
|
+
Install Mux SDK in your app (required by generated files):
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
npm i @mux/mux-node
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## 5) Add HTTP route for Mux webhook
|
|
93
|
+
|
|
94
|
+
Create or update `convex/http.ts`:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import { httpRouter } from "convex/server";
|
|
98
|
+
import { httpAction } from "./_generated/server";
|
|
99
|
+
import { internal } from "./_generated/api";
|
|
100
|
+
|
|
101
|
+
const http = httpRouter();
|
|
102
|
+
|
|
103
|
+
http.route({
|
|
104
|
+
path: "/mux/webhook",
|
|
105
|
+
method: "POST",
|
|
106
|
+
handler: httpAction(async (ctx, request) => {
|
|
107
|
+
const rawBody = await request.text();
|
|
108
|
+
const headers = Object.fromEntries(request.headers.entries());
|
|
109
|
+
const result = await ctx.runAction(internal.muxWebhook.ingestMuxWebhook, {
|
|
110
|
+
rawBody,
|
|
111
|
+
headers,
|
|
112
|
+
});
|
|
113
|
+
return new Response(JSON.stringify(result), {
|
|
114
|
+
headers: { "content-type": "application/json" },
|
|
115
|
+
});
|
|
116
|
+
}),
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
export default http;
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## 6) Add Mux credentials to Convex env
|
|
123
|
+
|
|
124
|
+
You can set env vars from the Convex dashboard or CLI.
|
|
125
|
+
|
|
126
|
+
Dashboard:
|
|
127
|
+
|
|
128
|
+
- Open your project in Convex dashboard
|
|
129
|
+
- Go to project/deployment settings for environment variables
|
|
130
|
+
- Add:
|
|
131
|
+
- `MUX_TOKEN_ID`
|
|
132
|
+
- `MUX_TOKEN_SECRET`
|
|
133
|
+
|
|
134
|
+
CLI equivalent:
|
|
135
|
+
|
|
136
|
+
```sh
|
|
137
|
+
npx convex env set MUX_TOKEN_ID <your_mux_token_id>
|
|
138
|
+
npx convex env set MUX_TOKEN_SECRET <your_mux_token_secret>
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## 7) Generate/apply schema and functions
|
|
142
|
+
|
|
143
|
+
```sh
|
|
144
|
+
npx convex dev
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
This applies component schema and generates `convex/_generated/*`.
|
|
148
|
+
|
|
149
|
+
## 8) Backfill Mux assets into Convex
|
|
150
|
+
|
|
151
|
+
Run the generated migration action:
|
|
152
|
+
|
|
153
|
+
```sh
|
|
154
|
+
npx convex run migrations:backfillMux '{}'
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
With options:
|
|
158
|
+
|
|
159
|
+
```sh
|
|
160
|
+
npx convex run migrations:backfillMux '{"maxAssets":500,"defaultUserId":"dev-user-1","includeVideoMetadata":true}'
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
For production deployment:
|
|
164
|
+
|
|
165
|
+
```sh
|
|
166
|
+
npx convex run --prod migrations:backfillMux '{"maxAssets":500}'
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Why Webhook URL Is Required
|
|
170
|
+
|
|
171
|
+
Backfill is a one-time catch-up. It does not keep data fresh.
|
|
172
|
+
|
|
173
|
+
Mux webhooks are how your app receives ongoing changes in near real time, such as:
|
|
174
|
+
|
|
175
|
+
- asset status updates (for example `preparing` to `ready`)
|
|
176
|
+
- deletions
|
|
177
|
+
- upload and live stream lifecycle events
|
|
178
|
+
|
|
179
|
+
Without the webhook URL:
|
|
180
|
+
|
|
181
|
+
- component tables only update when you run backfill/manual sync
|
|
182
|
+
- video state in Convex will drift from Mux over time
|
|
183
|
+
|
|
184
|
+
## 9) Configure Mux webhook endpoint
|
|
185
|
+
|
|
186
|
+
In Mux dashboard:
|
|
187
|
+
|
|
188
|
+
- Create webhook endpoint
|
|
189
|
+
- URL:
|
|
190
|
+
- Local testing (with tunnel): `https://<your-tunnel-domain>/mux/webhook`
|
|
191
|
+
- Deployed Convex app: `https://<your-deployment>.convex.site/mux/webhook`
|
|
192
|
+
- Select desired video events (asset, upload, live stream)
|
|
193
|
+
- Copy signing secret into `MUX_WEBHOOK_SECRET`
|
|
194
|
+
Add through Convex dashboard:
|
|
195
|
+
- Open your project in Convex dashboard
|
|
196
|
+
- Go to project/deployment settings for environment variables
|
|
197
|
+
- Add:
|
|
198
|
+
- `MUX_WEBHOOK_SECRET`
|
|
199
|
+
|
|
200
|
+
Set it via CLI(equivalent):
|
|
201
|
+
|
|
202
|
+
```sh
|
|
203
|
+
npx convex env set MUX_WEBHOOK_SECRET <your_mux_webhook_secret>
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
Note:
|
|
208
|
+
|
|
209
|
+
- If you use deployed Convex URL, you do not need ngrok or any other tunneling services.
|
|
210
|
+
- If your app is only local and not publicly reachable, use ngrok/cloudflare.
|
|
211
|
+
|
|
212
|
+
## 10) Verify data
|
|
213
|
+
|
|
214
|
+
In Convex dashboard data tables, you should see:
|
|
215
|
+
|
|
216
|
+
- `assets`
|
|
217
|
+
- `uploads`
|
|
218
|
+
- `liveStreams`
|
|
219
|
+
- `events`
|
|
220
|
+
- `videoMetadata`
|
|
221
|
+
|
|
222
|
+
## Local Testing This Package Before Publish
|
|
223
|
+
|
|
224
|
+
From this component repo:
|
|
225
|
+
|
|
226
|
+
```sh
|
|
227
|
+
npm pack --cache /tmp/npm-cache
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
In a separate consumer app:
|
|
231
|
+
|
|
232
|
+
```sh
|
|
233
|
+
npm i /absolute/path/to/convex-mux-component-0.1.6.tgz
|
|
234
|
+
npx convex dev
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
## Optional: Scaffold Package In This Repo
|
|
238
|
+
|
|
239
|
+
The separate scaffolder lives in `scaffold/` and should be published as its own package (`convex-mux-init`).
|
|
240
|
+
|
|
241
|
+
Build/test locally:
|
|
242
|
+
|
|
243
|
+
```sh
|
|
244
|
+
cd scaffold
|
|
245
|
+
npm pack --cache /tmp/npm-cache
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Then run in consumer app:
|
|
249
|
+
|
|
250
|
+
```sh
|
|
251
|
+
npm exec --yes --package /absolute/path/to/convex-mux-init-<version>.tgz convex-mux-init -- --component-name mux
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Troubleshooting
|
|
255
|
+
|
|
256
|
+
- `Could not find function for 'migrations:backfillMux'`
|
|
257
|
+
- Ensure `convex/migrations.ts` exists and exports `backfillMux`
|
|
258
|
+
- Run `npx convex dev` again
|
|
259
|
+
|
|
260
|
+
- `InvalidReference ... does not export [mux_node.backfillAssets]`
|
|
261
|
+
- Do not call `components.<name>.mux_node.*`
|
|
262
|
+
- Use app-level Node actions (`convex/migrations.ts`, `convex/muxWebhook.node.ts`) and call `components.<name>.sync.*Public`
|
|
263
|
+
|
|
264
|
+
- `TypeScript ... webhooks.unwrap ... Record<string, unknown>`
|
|
265
|
+
- Use `const event = mux.webhooks.unwrap(...) as unknown as Record<string, unknown>;`
|
|
266
|
+
|
|
267
|
+
- `It looks like you are using Node APIs from a file without the "use node" directive`
|
|
268
|
+
- Add `"use node";` at the top of files that use Mux SDK/Node APIs
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated `api` utility.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { AnyApi, AnyComponents } from "convex/server";
|
|
12
|
+
import { anyApi, componentsGeneric } from "convex/server";
|
|
13
|
+
|
|
14
|
+
export const api: AnyApi = anyApi;
|
|
15
|
+
export const internal: AnyApi = anyApi;
|
|
16
|
+
export const components: AnyComponents = componentsGeneric();
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated data model types.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
DataModelFromSchemaDefinition,
|
|
13
|
+
DocumentByName,
|
|
14
|
+
TableNamesInDataModel,
|
|
15
|
+
SystemTableNames,
|
|
16
|
+
} from "convex/server";
|
|
17
|
+
import type { GenericId } from "convex/values";
|
|
18
|
+
import schema from "../schema.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The names of all of your Convex tables.
|
|
22
|
+
*/
|
|
23
|
+
export type TableNames = TableNamesInDataModel<DataModel>;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The type of a document stored in Convex.
|
|
27
|
+
*
|
|
28
|
+
* @typeParam TableName - A string literal type of the table name (like "users").
|
|
29
|
+
*/
|
|
30
|
+
export type Doc<TableName extends TableNames> = DocumentByName<
|
|
31
|
+
DataModel,
|
|
32
|
+
TableName
|
|
33
|
+
>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An identifier for a document in Convex.
|
|
37
|
+
*
|
|
38
|
+
* Convex documents are uniquely identified by their `Id`, which is accessible
|
|
39
|
+
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
|
|
40
|
+
*
|
|
41
|
+
* Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
|
|
42
|
+
*
|
|
43
|
+
* IDs are just strings at runtime, but this type can be used to distinguish them from other
|
|
44
|
+
* strings when type checking.
|
|
45
|
+
*
|
|
46
|
+
* @typeParam TableName - A string literal type of the table name (like "users").
|
|
47
|
+
*/
|
|
48
|
+
export type Id<TableName extends TableNames | SystemTableNames> =
|
|
49
|
+
GenericId<TableName>;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A type describing your Convex data model.
|
|
53
|
+
*
|
|
54
|
+
* This type includes information about what tables you have, the type of
|
|
55
|
+
* documents stored in those tables, and the indexes defined on them.
|
|
56
|
+
*
|
|
57
|
+
* This type is used to parameterize methods like `queryGeneric` and
|
|
58
|
+
* `mutationGeneric` to make them type-safe.
|
|
59
|
+
*/
|
|
60
|
+
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated utilities for implementing server-side Convex query and mutation functions.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
ActionBuilder,
|
|
13
|
+
HttpActionBuilder,
|
|
14
|
+
MutationBuilder,
|
|
15
|
+
QueryBuilder,
|
|
16
|
+
GenericActionCtx,
|
|
17
|
+
GenericMutationCtx,
|
|
18
|
+
GenericQueryCtx,
|
|
19
|
+
GenericDatabaseReader,
|
|
20
|
+
GenericDatabaseWriter,
|
|
21
|
+
} from "convex/server";
|
|
22
|
+
import {
|
|
23
|
+
actionGeneric,
|
|
24
|
+
httpActionGeneric,
|
|
25
|
+
queryGeneric,
|
|
26
|
+
mutationGeneric,
|
|
27
|
+
internalActionGeneric,
|
|
28
|
+
internalMutationGeneric,
|
|
29
|
+
internalQueryGeneric,
|
|
30
|
+
} from "convex/server";
|
|
31
|
+
import type { DataModel } from "./dataModel.js";
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Define a query in this Convex app's public API.
|
|
35
|
+
*
|
|
36
|
+
* This function will be allowed to read your Convex database and will be accessible from the client.
|
|
37
|
+
*
|
|
38
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
39
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
40
|
+
*/
|
|
41
|
+
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Define a query that is only accessible from other Convex functions (but not from the client).
|
|
45
|
+
*
|
|
46
|
+
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
|
|
47
|
+
*
|
|
48
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
49
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
50
|
+
*/
|
|
51
|
+
export const internalQuery: QueryBuilder<DataModel, "internal"> =
|
|
52
|
+
internalQueryGeneric;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Define a mutation in this Convex app's public API.
|
|
56
|
+
*
|
|
57
|
+
* This function will be allowed to modify your Convex database and will be accessible from the client.
|
|
58
|
+
*
|
|
59
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
60
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
61
|
+
*/
|
|
62
|
+
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Define a mutation that is only accessible from other Convex functions (but not from the client).
|
|
66
|
+
*
|
|
67
|
+
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
|
|
68
|
+
*
|
|
69
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
70
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
71
|
+
*/
|
|
72
|
+
export const internalMutation: MutationBuilder<DataModel, "internal"> =
|
|
73
|
+
internalMutationGeneric;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Define an action in this Convex app's public API.
|
|
77
|
+
*
|
|
78
|
+
* An action is a function which can execute any JavaScript code, including non-deterministic
|
|
79
|
+
* code and code with side-effects, like calling third-party services.
|
|
80
|
+
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
|
|
81
|
+
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
|
|
82
|
+
*
|
|
83
|
+
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
|
|
84
|
+
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
|
|
85
|
+
*/
|
|
86
|
+
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Define an action that is only accessible from other Convex functions (but not from the client).
|
|
90
|
+
*
|
|
91
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
|
|
92
|
+
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
|
|
93
|
+
*/
|
|
94
|
+
export const internalAction: ActionBuilder<DataModel, "internal"> =
|
|
95
|
+
internalActionGeneric;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Define an HTTP action.
|
|
99
|
+
*
|
|
100
|
+
* The wrapped function will be used to respond to HTTP requests received
|
|
101
|
+
* by a Convex deployment if the requests matches the path and method where
|
|
102
|
+
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
|
|
103
|
+
*
|
|
104
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument
|
|
105
|
+
* and a Fetch API `Request` object as its second.
|
|
106
|
+
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
|
|
107
|
+
*/
|
|
108
|
+
export const httpAction: HttpActionBuilder = httpActionGeneric;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A set of services for use within Convex query functions.
|
|
112
|
+
*
|
|
113
|
+
* The query context is passed as the first argument to any Convex query
|
|
114
|
+
* function run on the server.
|
|
115
|
+
*
|
|
116
|
+
* If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
|
|
117
|
+
*/
|
|
118
|
+
export type QueryCtx = GenericQueryCtx<DataModel>;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A set of services for use within Convex mutation functions.
|
|
122
|
+
*
|
|
123
|
+
* The mutation context is passed as the first argument to any Convex mutation
|
|
124
|
+
* function run on the server.
|
|
125
|
+
*
|
|
126
|
+
* If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
|
|
127
|
+
*/
|
|
128
|
+
export type MutationCtx = GenericMutationCtx<DataModel>;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* A set of services for use within Convex action functions.
|
|
132
|
+
*
|
|
133
|
+
* The action context is passed as the first argument to any Convex action
|
|
134
|
+
* function run on the server.
|
|
135
|
+
*/
|
|
136
|
+
export type ActionCtx = GenericActionCtx<DataModel>;
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* An interface to read from the database within Convex query functions.
|
|
140
|
+
*
|
|
141
|
+
* The two entry points are {@link DatabaseReader.get}, which fetches a single
|
|
142
|
+
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
|
|
143
|
+
* building a query.
|
|
144
|
+
*/
|
|
145
|
+
export type DatabaseReader = GenericDatabaseReader<DataModel>;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* An interface to read from and write to the database within Convex mutation
|
|
149
|
+
* functions.
|
|
150
|
+
*
|
|
151
|
+
* Convex guarantees that all writes within a single mutation are
|
|
152
|
+
* executed atomically, so you never have to worry about partial writes leaving
|
|
153
|
+
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
|
|
154
|
+
* for the guarantees Convex provides your functions.
|
|
155
|
+
*/
|
|
156
|
+
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
|
package/catalog.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { query } from "./_generated/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
|
|
4
|
+
export const getAssetByMuxId = query({
|
|
5
|
+
args: { muxAssetId: v.string() },
|
|
6
|
+
handler: async (ctx, args) => {
|
|
7
|
+
return await ctx.db
|
|
8
|
+
.query("assets")
|
|
9
|
+
.withIndex("by_mux_asset_id", (q) => q.eq("muxAssetId", args.muxAssetId))
|
|
10
|
+
.unique();
|
|
11
|
+
},
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export const getLiveStreamByMuxId = query({
|
|
15
|
+
args: { muxLiveStreamId: v.string() },
|
|
16
|
+
handler: async (ctx, args) => {
|
|
17
|
+
return await ctx.db
|
|
18
|
+
.query("liveStreams")
|
|
19
|
+
.withIndex("by_mux_live_stream_id", (q) =>
|
|
20
|
+
q.eq("muxLiveStreamId", args.muxLiveStreamId)
|
|
21
|
+
)
|
|
22
|
+
.unique();
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export const getUploadByMuxId = query({
|
|
27
|
+
args: { muxUploadId: v.string() },
|
|
28
|
+
handler: async (ctx, args) => {
|
|
29
|
+
return await ctx.db
|
|
30
|
+
.query("uploads")
|
|
31
|
+
.withIndex("by_mux_upload_id", (q) => q.eq("muxUploadId", args.muxUploadId))
|
|
32
|
+
.unique();
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export const listAssets = query({
|
|
37
|
+
args: { limit: v.optional(v.number()) },
|
|
38
|
+
handler: async (ctx, args) => {
|
|
39
|
+
return await ctx.db
|
|
40
|
+
.query("assets")
|
|
41
|
+
.withIndex("by_updated_at")
|
|
42
|
+
.order("desc")
|
|
43
|
+
.take(args.limit ?? 50);
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export const listLiveStreams = query({
|
|
48
|
+
args: { limit: v.optional(v.number()) },
|
|
49
|
+
handler: async (ctx, args) => {
|
|
50
|
+
return await ctx.db
|
|
51
|
+
.query("liveStreams")
|
|
52
|
+
.withIndex("by_updated_at")
|
|
53
|
+
.order("desc")
|
|
54
|
+
.take(args.limit ?? 50);
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
export const listUploads = query({
|
|
59
|
+
args: { limit: v.optional(v.number()) },
|
|
60
|
+
handler: async (ctx, args) => {
|
|
61
|
+
return await ctx.db
|
|
62
|
+
.query("uploads")
|
|
63
|
+
.withIndex("by_updated_at")
|
|
64
|
+
.order("desc")
|
|
65
|
+
.take(args.limit ?? 50);
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
export const listRecentEvents = query({
|
|
70
|
+
args: { limit: v.optional(v.number()) },
|
|
71
|
+
handler: async (ctx, args) => {
|
|
72
|
+
return await ctx.db
|
|
73
|
+
.query("events")
|
|
74
|
+
.withIndex("by_received_at")
|
|
75
|
+
.order("desc")
|
|
76
|
+
.take(args.limit ?? 50);
|
|
77
|
+
},
|
|
78
|
+
});
|
package/convex.config.ts
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "convex-mux-component",
|
|
3
|
+
"version": "0.1.6",
|
|
4
|
+
"description": "Convex Component for syncing Mux video data and app metadata.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"convex",
|
|
8
|
+
"mux",
|
|
9
|
+
"component",
|
|
10
|
+
"video"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
"README.md",
|
|
14
|
+
"convex.config.ts",
|
|
15
|
+
"schema.ts",
|
|
16
|
+
"sync.ts",
|
|
17
|
+
"videos.ts",
|
|
18
|
+
"catalog.ts",
|
|
19
|
+
"_generated/api.ts",
|
|
20
|
+
"_generated/server.ts",
|
|
21
|
+
"_generated/dataModel.ts"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
"./convex.config": "./convex.config.ts",
|
|
25
|
+
"./convex.config.js": "./convex.config.ts",
|
|
26
|
+
"./schema": "./schema.ts",
|
|
27
|
+
"./schema.js": "./schema.ts",
|
|
28
|
+
"./sync": "./sync.ts",
|
|
29
|
+
"./sync.js": "./sync.ts",
|
|
30
|
+
"./videos": "./videos.ts",
|
|
31
|
+
"./videos.js": "./videos.ts",
|
|
32
|
+
"./catalog": "./catalog.ts",
|
|
33
|
+
"./catalog.js": "./catalog.ts",
|
|
34
|
+
"./_generated/api": "./_generated/api.ts",
|
|
35
|
+
"./_generated/api.js": "./_generated/api.ts",
|
|
36
|
+
"./_generated/server": "./_generated/server.ts",
|
|
37
|
+
"./_generated/server.js": "./_generated/server.ts",
|
|
38
|
+
"./_generated/dataModel": "./_generated/dataModel.ts",
|
|
39
|
+
"./_generated/dataModel.js": "./_generated/dataModel.ts"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"codegen": "convex codegen --component-dir .",
|
|
43
|
+
"typecheck": "convex codegen --component-dir . && tsc --noEmit"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@mux/mux-node": "^9.0.0",
|
|
50
|
+
"convex": "^1.20.0"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"typescript": "^5.7.0"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/schema.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { defineSchema, defineTable } from "convex/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
|
|
4
|
+
const playbackId = v.object({
|
|
5
|
+
id: v.string(),
|
|
6
|
+
policy: v.optional(v.string()),
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
const videoTrack = v.object({
|
|
10
|
+
id: v.optional(v.string()),
|
|
11
|
+
type: v.optional(v.string()),
|
|
12
|
+
textType: v.optional(v.string()),
|
|
13
|
+
languageCode: v.optional(v.string()),
|
|
14
|
+
status: v.optional(v.string()),
|
|
15
|
+
name: v.optional(v.string()),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const genericObject = v.record(v.string(), v.any());
|
|
19
|
+
|
|
20
|
+
export default defineSchema({
|
|
21
|
+
assets: defineTable({
|
|
22
|
+
muxAssetId: v.string(),
|
|
23
|
+
status: v.optional(v.string()),
|
|
24
|
+
playbackIds: v.optional(v.array(playbackId)),
|
|
25
|
+
durationSeconds: v.optional(v.number()),
|
|
26
|
+
aspectRatio: v.optional(v.string()),
|
|
27
|
+
maxStoredResolution: v.optional(v.string()),
|
|
28
|
+
maxStoredFrameRate: v.optional(v.number()),
|
|
29
|
+
passthrough: v.optional(v.string()),
|
|
30
|
+
uploadId: v.optional(v.string()),
|
|
31
|
+
liveStreamId: v.optional(v.string()),
|
|
32
|
+
tracks: v.optional(v.array(videoTrack)),
|
|
33
|
+
createdAtMs: v.number(),
|
|
34
|
+
updatedAtMs: v.number(),
|
|
35
|
+
deletedAtMs: v.optional(v.number()),
|
|
36
|
+
raw: genericObject,
|
|
37
|
+
})
|
|
38
|
+
.index("by_mux_asset_id", ["muxAssetId"])
|
|
39
|
+
.index("by_status", ["status"])
|
|
40
|
+
.index("by_updated_at", ["updatedAtMs"]),
|
|
41
|
+
|
|
42
|
+
liveStreams: defineTable({
|
|
43
|
+
muxLiveStreamId: v.string(),
|
|
44
|
+
status: v.optional(v.string()),
|
|
45
|
+
playbackIds: v.optional(v.array(playbackId)),
|
|
46
|
+
reconnectWindowSeconds: v.optional(v.number()),
|
|
47
|
+
recentAssetIds: v.optional(v.array(v.string())),
|
|
48
|
+
createdAtMs: v.number(),
|
|
49
|
+
updatedAtMs: v.number(),
|
|
50
|
+
deletedAtMs: v.optional(v.number()),
|
|
51
|
+
raw: genericObject,
|
|
52
|
+
})
|
|
53
|
+
.index("by_mux_live_stream_id", ["muxLiveStreamId"])
|
|
54
|
+
.index("by_status", ["status"])
|
|
55
|
+
.index("by_updated_at", ["updatedAtMs"]),
|
|
56
|
+
|
|
57
|
+
uploads: defineTable({
|
|
58
|
+
muxUploadId: v.string(),
|
|
59
|
+
status: v.optional(v.string()),
|
|
60
|
+
uploadUrl: v.optional(v.string()),
|
|
61
|
+
timeoutSeconds: v.optional(v.number()),
|
|
62
|
+
corsOrigin: v.optional(v.string()),
|
|
63
|
+
assetId: v.optional(v.string()),
|
|
64
|
+
error: v.optional(genericObject),
|
|
65
|
+
createdAtMs: v.number(),
|
|
66
|
+
updatedAtMs: v.number(),
|
|
67
|
+
deletedAtMs: v.optional(v.number()),
|
|
68
|
+
raw: genericObject,
|
|
69
|
+
})
|
|
70
|
+
.index("by_mux_upload_id", ["muxUploadId"])
|
|
71
|
+
.index("by_status", ["status"])
|
|
72
|
+
.index("by_updated_at", ["updatedAtMs"]),
|
|
73
|
+
|
|
74
|
+
events: defineTable({
|
|
75
|
+
muxEventId: v.optional(v.string()),
|
|
76
|
+
type: v.string(),
|
|
77
|
+
objectType: v.optional(v.string()),
|
|
78
|
+
objectId: v.optional(v.string()),
|
|
79
|
+
occurredAtMs: v.optional(v.number()),
|
|
80
|
+
receivedAtMs: v.number(),
|
|
81
|
+
verified: v.boolean(),
|
|
82
|
+
raw: genericObject,
|
|
83
|
+
})
|
|
84
|
+
.index("by_mux_event_id", ["muxEventId"])
|
|
85
|
+
.index("by_type", ["type"])
|
|
86
|
+
.index("by_object", ["objectType", "objectId"])
|
|
87
|
+
.index("by_received_at", ["receivedAtMs"]),
|
|
88
|
+
|
|
89
|
+
videoMetadata: defineTable({
|
|
90
|
+
muxAssetId: v.string(),
|
|
91
|
+
userId: v.string(),
|
|
92
|
+
title: v.optional(v.string()),
|
|
93
|
+
description: v.optional(v.string()),
|
|
94
|
+
tags: v.optional(v.array(v.string())),
|
|
95
|
+
visibility: v.optional(
|
|
96
|
+
v.union(v.literal("private"), v.literal("unlisted"), v.literal("public"))
|
|
97
|
+
),
|
|
98
|
+
custom: v.optional(genericObject),
|
|
99
|
+
createdAtMs: v.number(),
|
|
100
|
+
updatedAtMs: v.number(),
|
|
101
|
+
})
|
|
102
|
+
.index("by_mux_asset_id", ["muxAssetId"])
|
|
103
|
+
.index("by_user_id", ["userId"])
|
|
104
|
+
.index("by_asset_and_user", ["muxAssetId", "userId"])
|
|
105
|
+
.index("by_updated_at", ["updatedAtMs"]),
|
|
106
|
+
});
|
package/sync.ts
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import { internalMutation, mutation, type MutationCtx } from "./_generated/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
|
|
4
|
+
function omitUndefined<T extends Record<string, unknown>>(doc: T): Partial<T> {
|
|
5
|
+
return Object.fromEntries(
|
|
6
|
+
Object.entries(doc).filter(([, value]) => value !== undefined)
|
|
7
|
+
) as Partial<T>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function asString(value: unknown): string | undefined {
|
|
11
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
15
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
16
|
+
return value as Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function asNumber(value: unknown): number | undefined {
|
|
22
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function asTimestamp(value: unknown): number | undefined {
|
|
26
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "string") {
|
|
30
|
+
const parsed = Date.parse(value);
|
|
31
|
+
if (!Number.isNaN(parsed)) {
|
|
32
|
+
return parsed;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function asPlaybackIds(value: unknown): Array<{ id: string; policy?: string }> | undefined {
|
|
39
|
+
if (!Array.isArray(value)) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
const mapped = value
|
|
43
|
+
.map((entry) => {
|
|
44
|
+
const id = asString((entry as { id?: unknown }).id);
|
|
45
|
+
if (!id) return null;
|
|
46
|
+
const policy = asString((entry as { policy?: unknown }).policy);
|
|
47
|
+
return policy ? { id, policy } : { id };
|
|
48
|
+
})
|
|
49
|
+
.filter((entry): entry is { id: string; policy?: string } => entry !== null);
|
|
50
|
+
return mapped.length > 0 ? mapped : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function asTracks(
|
|
54
|
+
value: unknown
|
|
55
|
+
):
|
|
56
|
+
| Array<{
|
|
57
|
+
id?: string;
|
|
58
|
+
type?: string;
|
|
59
|
+
textType?: string;
|
|
60
|
+
languageCode?: string;
|
|
61
|
+
status?: string;
|
|
62
|
+
name?: string;
|
|
63
|
+
}>
|
|
64
|
+
| undefined {
|
|
65
|
+
if (!Array.isArray(value)) {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
const tracks = value.map((entry) => {
|
|
69
|
+
const track = entry as {
|
|
70
|
+
id?: unknown;
|
|
71
|
+
type?: unknown;
|
|
72
|
+
text_type?: unknown;
|
|
73
|
+
language_code?: unknown;
|
|
74
|
+
status?: unknown;
|
|
75
|
+
name?: unknown;
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
id: asString(track.id),
|
|
79
|
+
type: asString(track.type),
|
|
80
|
+
textType: asString(track.text_type),
|
|
81
|
+
languageCode: asString(track.language_code),
|
|
82
|
+
status: asString(track.status),
|
|
83
|
+
name: asString(track.name),
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
return tracks.length > 0 ? tracks : undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function asStringArray(value: unknown): string[] | undefined {
|
|
90
|
+
if (!Array.isArray(value)) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
const items = value.filter((item): item is string => typeof item === "string");
|
|
94
|
+
return items.length > 0 ? items : undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const upsertAssetFromPayloadHandler = async (
|
|
98
|
+
ctx: MutationCtx,
|
|
99
|
+
args: { asset: Record<string, unknown> }
|
|
100
|
+
) => {
|
|
101
|
+
const now = Date.now();
|
|
102
|
+
const asset = args.asset as {
|
|
103
|
+
id?: unknown;
|
|
104
|
+
status?: unknown;
|
|
105
|
+
playback_ids?: unknown;
|
|
106
|
+
duration?: unknown;
|
|
107
|
+
aspect_ratio?: unknown;
|
|
108
|
+
max_stored_resolution?: unknown;
|
|
109
|
+
max_stored_frame_rate?: unknown;
|
|
110
|
+
passthrough?: unknown;
|
|
111
|
+
upload_id?: unknown;
|
|
112
|
+
live_stream_id?: unknown;
|
|
113
|
+
tracks?: unknown;
|
|
114
|
+
};
|
|
115
|
+
const muxAssetId = asString(asset.id);
|
|
116
|
+
if (!muxAssetId) {
|
|
117
|
+
throw new Error("Mux asset payload is missing an id.");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const existing = await ctx.db
|
|
121
|
+
.query("assets")
|
|
122
|
+
.withIndex("by_mux_asset_id", (q) => q.eq("muxAssetId", muxAssetId))
|
|
123
|
+
.unique();
|
|
124
|
+
|
|
125
|
+
const patchDoc = omitUndefined({
|
|
126
|
+
status: asString(asset.status),
|
|
127
|
+
playbackIds: asPlaybackIds(asset.playback_ids),
|
|
128
|
+
durationSeconds: asNumber(asset.duration),
|
|
129
|
+
aspectRatio: asString(asset.aspect_ratio),
|
|
130
|
+
maxStoredResolution: asString(asset.max_stored_resolution),
|
|
131
|
+
maxStoredFrameRate: asNumber(asset.max_stored_frame_rate),
|
|
132
|
+
passthrough: asString(asset.passthrough),
|
|
133
|
+
uploadId: asString(asset.upload_id),
|
|
134
|
+
liveStreamId: asString(asset.live_stream_id),
|
|
135
|
+
tracks: asTracks(asset.tracks),
|
|
136
|
+
updatedAtMs: now,
|
|
137
|
+
deletedAtMs: asString(asset.status) === "deleted" ? now : undefined,
|
|
138
|
+
raw: args.asset,
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
if (existing) {
|
|
142
|
+
await ctx.db.patch(existing._id, patchDoc);
|
|
143
|
+
return existing._id;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return await ctx.db.insert("assets", {
|
|
147
|
+
muxAssetId,
|
|
148
|
+
createdAtMs: now,
|
|
149
|
+
...patchDoc,
|
|
150
|
+
updatedAtMs: now,
|
|
151
|
+
raw: args.asset,
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
export const upsertAssetFromPayload = internalMutation({
|
|
156
|
+
args: { asset: v.record(v.string(), v.any()) },
|
|
157
|
+
handler: upsertAssetFromPayloadHandler,
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
export const upsertAssetFromPayloadPublic = mutation({
|
|
161
|
+
args: { asset: v.record(v.string(), v.any()) },
|
|
162
|
+
handler: upsertAssetFromPayloadHandler,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const markAssetDeletedHandler = async (
|
|
166
|
+
ctx: MutationCtx,
|
|
167
|
+
args: { muxAssetId: string }
|
|
168
|
+
) => {
|
|
169
|
+
const existing = await ctx.db
|
|
170
|
+
.query("assets")
|
|
171
|
+
.withIndex("by_mux_asset_id", (q) => q.eq("muxAssetId", args.muxAssetId))
|
|
172
|
+
.unique();
|
|
173
|
+
if (!existing) return null;
|
|
174
|
+
await ctx.db.patch(existing._id, {
|
|
175
|
+
status: "deleted",
|
|
176
|
+
deletedAtMs: Date.now(),
|
|
177
|
+
updatedAtMs: Date.now(),
|
|
178
|
+
});
|
|
179
|
+
return existing._id;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
export const markAssetDeleted = internalMutation({
|
|
183
|
+
args: { muxAssetId: v.string() },
|
|
184
|
+
handler: markAssetDeletedHandler,
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
export const markAssetDeletedPublic = mutation({
|
|
188
|
+
args: { muxAssetId: v.string() },
|
|
189
|
+
handler: markAssetDeletedHandler,
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
const upsertLiveStreamFromPayloadHandler = async (
|
|
193
|
+
ctx: MutationCtx,
|
|
194
|
+
args: { liveStream: Record<string, unknown> }
|
|
195
|
+
) => {
|
|
196
|
+
const now = Date.now();
|
|
197
|
+
const liveStream = args.liveStream as {
|
|
198
|
+
id?: unknown;
|
|
199
|
+
status?: unknown;
|
|
200
|
+
playback_ids?: unknown;
|
|
201
|
+
reconnect_window?: unknown;
|
|
202
|
+
recent_asset_ids?: unknown;
|
|
203
|
+
};
|
|
204
|
+
const muxLiveStreamId = asString(liveStream.id);
|
|
205
|
+
if (!muxLiveStreamId) {
|
|
206
|
+
throw new Error("Mux live stream payload is missing an id.");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const existing = await ctx.db
|
|
210
|
+
.query("liveStreams")
|
|
211
|
+
.withIndex("by_mux_live_stream_id", (q) =>
|
|
212
|
+
q.eq("muxLiveStreamId", muxLiveStreamId)
|
|
213
|
+
)
|
|
214
|
+
.unique();
|
|
215
|
+
|
|
216
|
+
const patchDoc = omitUndefined({
|
|
217
|
+
status: asString(liveStream.status),
|
|
218
|
+
playbackIds: asPlaybackIds(liveStream.playback_ids),
|
|
219
|
+
reconnectWindowSeconds: asNumber(liveStream.reconnect_window),
|
|
220
|
+
recentAssetIds: asStringArray(liveStream.recent_asset_ids),
|
|
221
|
+
updatedAtMs: now,
|
|
222
|
+
raw: args.liveStream,
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
if (existing) {
|
|
226
|
+
await ctx.db.patch(existing._id, patchDoc);
|
|
227
|
+
return existing._id;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return await ctx.db.insert("liveStreams", {
|
|
231
|
+
muxLiveStreamId,
|
|
232
|
+
createdAtMs: now,
|
|
233
|
+
...patchDoc,
|
|
234
|
+
updatedAtMs: now,
|
|
235
|
+
raw: args.liveStream,
|
|
236
|
+
});
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
export const upsertLiveStreamFromPayload = internalMutation({
|
|
240
|
+
args: { liveStream: v.record(v.string(), v.any()) },
|
|
241
|
+
handler: upsertLiveStreamFromPayloadHandler,
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
export const upsertLiveStreamFromPayloadPublic = mutation({
|
|
245
|
+
args: { liveStream: v.record(v.string(), v.any()) },
|
|
246
|
+
handler: upsertLiveStreamFromPayloadHandler,
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
const markLiveStreamDeletedHandler = async (
|
|
250
|
+
ctx: MutationCtx,
|
|
251
|
+
args: { muxLiveStreamId: string }
|
|
252
|
+
) => {
|
|
253
|
+
const existing = await ctx.db
|
|
254
|
+
.query("liveStreams")
|
|
255
|
+
.withIndex("by_mux_live_stream_id", (q) =>
|
|
256
|
+
q.eq("muxLiveStreamId", args.muxLiveStreamId)
|
|
257
|
+
)
|
|
258
|
+
.unique();
|
|
259
|
+
if (!existing) return null;
|
|
260
|
+
await ctx.db.patch(existing._id, {
|
|
261
|
+
status: "deleted",
|
|
262
|
+
deletedAtMs: Date.now(),
|
|
263
|
+
updatedAtMs: Date.now(),
|
|
264
|
+
});
|
|
265
|
+
return existing._id;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
export const markLiveStreamDeleted = internalMutation({
|
|
269
|
+
args: { muxLiveStreamId: v.string() },
|
|
270
|
+
handler: markLiveStreamDeletedHandler,
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
export const markLiveStreamDeletedPublic = mutation({
|
|
274
|
+
args: { muxLiveStreamId: v.string() },
|
|
275
|
+
handler: markLiveStreamDeletedHandler,
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
const upsertUploadFromPayloadHandler = async (
|
|
279
|
+
ctx: MutationCtx,
|
|
280
|
+
args: { upload: Record<string, unknown> }
|
|
281
|
+
) => {
|
|
282
|
+
const now = Date.now();
|
|
283
|
+
const upload = args.upload as {
|
|
284
|
+
id?: unknown;
|
|
285
|
+
status?: unknown;
|
|
286
|
+
url?: unknown;
|
|
287
|
+
timeout?: unknown;
|
|
288
|
+
cors_origin?: unknown;
|
|
289
|
+
asset_id?: unknown;
|
|
290
|
+
error?: unknown;
|
|
291
|
+
};
|
|
292
|
+
const muxUploadId = asString(upload.id);
|
|
293
|
+
if (!muxUploadId) {
|
|
294
|
+
throw new Error("Mux upload payload is missing an id.");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const existing = await ctx.db
|
|
298
|
+
.query("uploads")
|
|
299
|
+
.withIndex("by_mux_upload_id", (q) => q.eq("muxUploadId", muxUploadId))
|
|
300
|
+
.unique();
|
|
301
|
+
|
|
302
|
+
const patchDoc = omitUndefined({
|
|
303
|
+
status: asString(upload.status),
|
|
304
|
+
uploadUrl: asString(upload.url),
|
|
305
|
+
timeoutSeconds: asNumber(upload.timeout),
|
|
306
|
+
corsOrigin: asString(upload.cors_origin),
|
|
307
|
+
assetId: asString(upload.asset_id),
|
|
308
|
+
error: asObject(upload.error),
|
|
309
|
+
updatedAtMs: now,
|
|
310
|
+
raw: args.upload,
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
if (existing) {
|
|
314
|
+
await ctx.db.patch(existing._id, patchDoc);
|
|
315
|
+
return existing._id;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
return await ctx.db.insert("uploads", {
|
|
319
|
+
muxUploadId,
|
|
320
|
+
createdAtMs: now,
|
|
321
|
+
...patchDoc,
|
|
322
|
+
updatedAtMs: now,
|
|
323
|
+
raw: args.upload,
|
|
324
|
+
});
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
export const upsertUploadFromPayload = internalMutation({
|
|
328
|
+
args: { upload: v.record(v.string(), v.any()) },
|
|
329
|
+
handler: upsertUploadFromPayloadHandler,
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
export const upsertUploadFromPayloadPublic = mutation({
|
|
333
|
+
args: { upload: v.record(v.string(), v.any()) },
|
|
334
|
+
handler: upsertUploadFromPayloadHandler,
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
const markUploadDeletedHandler = async (
|
|
338
|
+
ctx: MutationCtx,
|
|
339
|
+
args: { muxUploadId: string }
|
|
340
|
+
) => {
|
|
341
|
+
const existing = await ctx.db
|
|
342
|
+
.query("uploads")
|
|
343
|
+
.withIndex("by_mux_upload_id", (q) => q.eq("muxUploadId", args.muxUploadId))
|
|
344
|
+
.unique();
|
|
345
|
+
if (!existing) return null;
|
|
346
|
+
await ctx.db.patch(existing._id, {
|
|
347
|
+
status: "deleted",
|
|
348
|
+
deletedAtMs: Date.now(),
|
|
349
|
+
updatedAtMs: Date.now(),
|
|
350
|
+
});
|
|
351
|
+
return existing._id;
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
export const markUploadDeleted = internalMutation({
|
|
355
|
+
args: { muxUploadId: v.string() },
|
|
356
|
+
handler: markUploadDeletedHandler,
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
export const markUploadDeletedPublic = mutation({
|
|
360
|
+
args: { muxUploadId: v.string() },
|
|
361
|
+
handler: markUploadDeletedHandler,
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
function inferObjectTypeFromEventType(eventType: string): string | undefined {
|
|
365
|
+
if (eventType.startsWith("video.asset.")) return "asset";
|
|
366
|
+
if (eventType.startsWith("video.live_stream.")) return "live_stream";
|
|
367
|
+
if (eventType.startsWith("video.upload.")) return "upload";
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const recordWebhookEventHandler = async (
|
|
372
|
+
ctx: MutationCtx,
|
|
373
|
+
args: {
|
|
374
|
+
event: Record<string, unknown>;
|
|
375
|
+
verified: boolean;
|
|
376
|
+
}
|
|
377
|
+
) => {
|
|
378
|
+
const now = Date.now();
|
|
379
|
+
const event = args.event as {
|
|
380
|
+
id?: unknown;
|
|
381
|
+
type?: unknown;
|
|
382
|
+
data?: { id?: unknown };
|
|
383
|
+
created_at?: unknown;
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
const eventType = asString(event.type) ?? "unknown";
|
|
387
|
+
const muxEventId = asString(event.id);
|
|
388
|
+
const objectId = asString(event.data?.id);
|
|
389
|
+
const objectType = inferObjectTypeFromEventType(eventType);
|
|
390
|
+
const occurredAtMs = asTimestamp(event.created_at);
|
|
391
|
+
|
|
392
|
+
if (muxEventId) {
|
|
393
|
+
const existing = await ctx.db
|
|
394
|
+
.query("events")
|
|
395
|
+
.withIndex("by_mux_event_id", (q) => q.eq("muxEventId", muxEventId))
|
|
396
|
+
.unique();
|
|
397
|
+
if (existing) {
|
|
398
|
+
return { eventDocId: existing._id, alreadyProcessed: true };
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const eventDocId = await ctx.db.insert("events", {
|
|
403
|
+
type: eventType,
|
|
404
|
+
receivedAtMs: now,
|
|
405
|
+
verified: args.verified,
|
|
406
|
+
raw: args.event,
|
|
407
|
+
...(muxEventId ? { muxEventId } : {}),
|
|
408
|
+
...(objectType ? { objectType } : {}),
|
|
409
|
+
...(objectId ? { objectId } : {}),
|
|
410
|
+
...(occurredAtMs !== undefined ? { occurredAtMs } : {}),
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
return { eventDocId, alreadyProcessed: false };
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
export const recordWebhookEvent = internalMutation({
|
|
417
|
+
args: {
|
|
418
|
+
event: v.record(v.string(), v.any()),
|
|
419
|
+
verified: v.boolean(),
|
|
420
|
+
},
|
|
421
|
+
handler: recordWebhookEventHandler,
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
export const recordWebhookEventPublic = mutation({
|
|
425
|
+
args: {
|
|
426
|
+
event: v.record(v.string(), v.any()),
|
|
427
|
+
verified: v.boolean(),
|
|
428
|
+
},
|
|
429
|
+
handler: recordWebhookEventHandler,
|
|
430
|
+
});
|
package/videos.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { mutation, query } from "./_generated/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
|
|
4
|
+
function omitUndefined<T extends Record<string, unknown>>(doc: T): Partial<T> {
|
|
5
|
+
return Object.fromEntries(
|
|
6
|
+
Object.entries(doc).filter(([, value]) => value !== undefined)
|
|
7
|
+
) as Partial<T>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const upsertVideoMetadata = mutation({
|
|
11
|
+
args: {
|
|
12
|
+
muxAssetId: v.string(),
|
|
13
|
+
userId: v.string(),
|
|
14
|
+
title: v.optional(v.string()),
|
|
15
|
+
description: v.optional(v.string()),
|
|
16
|
+
tags: v.optional(v.array(v.string())),
|
|
17
|
+
visibility: v.optional(
|
|
18
|
+
v.union(v.literal("private"), v.literal("unlisted"), v.literal("public"))
|
|
19
|
+
),
|
|
20
|
+
custom: v.optional(v.record(v.string(), v.any())),
|
|
21
|
+
},
|
|
22
|
+
handler: async (ctx, args) => {
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
const existing = await ctx.db
|
|
25
|
+
.query("videoMetadata")
|
|
26
|
+
.withIndex("by_asset_and_user", (q) =>
|
|
27
|
+
q.eq("muxAssetId", args.muxAssetId).eq("userId", args.userId)
|
|
28
|
+
)
|
|
29
|
+
.unique();
|
|
30
|
+
|
|
31
|
+
const patchDoc = omitUndefined({
|
|
32
|
+
title: args.title,
|
|
33
|
+
description: args.description,
|
|
34
|
+
tags: args.tags,
|
|
35
|
+
visibility: args.visibility,
|
|
36
|
+
custom: args.custom,
|
|
37
|
+
updatedAtMs: now,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
if (existing) {
|
|
41
|
+
await ctx.db.patch(existing._id, patchDoc);
|
|
42
|
+
return existing._id;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return await ctx.db.insert("videoMetadata", {
|
|
46
|
+
muxAssetId: args.muxAssetId,
|
|
47
|
+
userId: args.userId,
|
|
48
|
+
createdAtMs: now,
|
|
49
|
+
...patchDoc,
|
|
50
|
+
updatedAtMs: now,
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export const getVideoByMuxAssetId = query({
|
|
56
|
+
args: {
|
|
57
|
+
muxAssetId: v.string(),
|
|
58
|
+
userId: v.optional(v.string()),
|
|
59
|
+
},
|
|
60
|
+
handler: async (ctx, args) => {
|
|
61
|
+
const asset = await ctx.db
|
|
62
|
+
.query("assets")
|
|
63
|
+
.withIndex("by_mux_asset_id", (q) => q.eq("muxAssetId", args.muxAssetId))
|
|
64
|
+
.unique();
|
|
65
|
+
|
|
66
|
+
if (!asset) return null;
|
|
67
|
+
|
|
68
|
+
if (args.userId) {
|
|
69
|
+
const userId = args.userId;
|
|
70
|
+
const metadata = await ctx.db
|
|
71
|
+
.query("videoMetadata")
|
|
72
|
+
.withIndex("by_asset_and_user", (q) =>
|
|
73
|
+
q.eq("muxAssetId", args.muxAssetId).eq("userId", userId)
|
|
74
|
+
)
|
|
75
|
+
.unique();
|
|
76
|
+
return { asset, metadata };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const metadata = await ctx.db
|
|
80
|
+
.query("videoMetadata")
|
|
81
|
+
.withIndex("by_mux_asset_id", (q) => q.eq("muxAssetId", args.muxAssetId))
|
|
82
|
+
.collect();
|
|
83
|
+
return { asset, metadata };
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
export const listVideosForUser = query({
|
|
88
|
+
args: {
|
|
89
|
+
userId: v.string(),
|
|
90
|
+
limit: v.optional(v.number()),
|
|
91
|
+
},
|
|
92
|
+
handler: async (ctx, args) => {
|
|
93
|
+
const metadataRows = await ctx.db
|
|
94
|
+
.query("videoMetadata")
|
|
95
|
+
.withIndex("by_user_id", (q) => q.eq("userId", args.userId))
|
|
96
|
+
.order("desc")
|
|
97
|
+
.take(args.limit ?? 25);
|
|
98
|
+
|
|
99
|
+
const joinedRows = await Promise.all(
|
|
100
|
+
metadataRows.map(async (metadata) => {
|
|
101
|
+
const asset = await ctx.db
|
|
102
|
+
.query("assets")
|
|
103
|
+
.withIndex("by_mux_asset_id", (q) => q.eq("muxAssetId", metadata.muxAssetId))
|
|
104
|
+
.unique();
|
|
105
|
+
return { metadata, asset };
|
|
106
|
+
})
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
return joinedRows;
|
|
110
|
+
},
|
|
111
|
+
});
|