Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add skeleton Plex webhook impl #213

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"bundle": "tsx scripts/bundle.ts",
"clean": "rimraf build",
"debug": "tsx watch --tsconfig ./tsconfig.build.json --ignore 'src/streams' --inspect-brk src",
"dev": "NODE_ENV=development tsx watch --tsconfig ./tsconfig.build.json --ignore 'build' --ignore 'src/streams' src",
"dev": "NODE_ENV=development TUNARR_BIND_ADDR='0.0.0.0' tsx watch --tsconfig ./tsconfig.build.json --ignore 'build' --ignore 'src/streams' src",
"make-exec": "tsx scripts/makeExecutable.ts",
"generate-db-cache": "mikro-orm-esm cache:generate --combined --ts",
"mikro-orm": "mikro-orm-esm",
Expand Down
4 changes: 3 additions & 1 deletion server/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { customShowsApiV2 } from './customShowsApi.js';
import { debugApi } from './debugApi.js';
import { fillerListsApi } from './fillerListsApi.js';
import { metadataApiRouter } from './metadataApi.js';
import { plexWebhookRouter } from './plexWebhookApi.js';
import { programmingApi } from './programmingApi.js';
import { tasksApiRouter } from './tasksApi.js';

Expand All @@ -40,7 +41,8 @@ export const apiRouter: RouterPluginAsyncCallback = async (fastify) => {
.register(fillerListsApi)
.register(programmingApi)
.register(debugApi)
.register(metadataApiRouter);
.register(metadataApiRouter)
.register(plexWebhookRouter);

fastify.get(
'/version',
Expand Down
36 changes: 36 additions & 0 deletions server/src/api/plexWebhookApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { PlexWebhookPayloadSchema } from '@tunarr/types/plex';
import createLogger from '../logger';
import { RouterPluginAsyncCallback } from '../types/serverType';

const logger = createLogger(import.meta);

// eslint-disable-next-line @typescript-eslint/require-await
export const plexWebhookRouter: RouterPluginAsyncCallback = async (f) => {
f.post(
'/plex/webhook',
{
schema: {
consumes: ['multipart/form-data'],
},
},
async (req, res) => {
for await (const part of req.parts()) {
if (part.type === 'field' && part.mimetype === 'application/json') {
const parseResult = await PlexWebhookPayloadSchema.safeParseAsync(
part.value,
);
logger.info('Payload: %O', part.value);
if (!parseResult.success) {
logger.error(
'Unable to parse Plex webhook payload: %O',
parseResult.error,
);
return res.status(400).send();
}
}
}

return res.send();
},
);
};
30 changes: 30 additions & 0 deletions types/src/plex/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './dvr.js';
import z from 'zod';
import { PlexWebhookBasePayloadSchema } from './webhooks.js';

type Alias<t> = t & { _?: never };

Expand Down Expand Up @@ -589,6 +590,29 @@ export type PlexCollectionContents =
| PlexMovieCollectionContents
| PlexTvShowCollectionContents;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
// const PlexMediaSchema = z.discriminatedUnion('type', [
// PlexMovieSchema,
// PlexTvShowSchema,
// PlexTvSeasonSchema,
// PlexEpisodeSchema,
// PlexLibraryCollectionSchema,
// PlexMusicArtistSchema,
// PlexMusicAlbumSchema,
// PlexMusicTrackSchema,
// ]);

const PartialPlexMediaSchema = z.discriminatedUnion('type', [
PlexMovieSchema.partial().required({ type: true }),
PlexTvShowSchema.partial().required({ type: true }),
PlexTvSeasonSchema.partial().required({ type: true }),
PlexEpisodeSchema.partial().required({ type: true }),
PlexLibraryCollectionSchema.partial().required({ type: true }),
PlexMusicArtistSchema.partial().required({ type: true }),
PlexMusicAlbumSchema.partial().required({ type: true }),
PlexMusicTrackSchema.partial().required({ type: true }),
]);

export type PlexMedia = Alias<
| PlexMovie
| PlexTvShow
Expand Down Expand Up @@ -703,3 +727,9 @@ export const PlexResourcesResponseSchema = z.array(PlexResourceSchema);
export type PlexResourcesResponse = Alias<
z.infer<typeof PlexResourcesResponseSchema>
>;

export * from './webhooks.js';

export const PlexWebhookPayloadSchema = PlexWebhookBasePayloadSchema.extend({
Metadata: PartialPlexMediaSchema,
});
36 changes: 36 additions & 0 deletions types/src/plex/webhooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { z } from 'zod';

// Extend with Metadata value in the main file... once we better organize
// the schemas here we can split files
export const PlexWebhookBasePayloadSchema = z.object({
event: z.union([
z.literal('library.on.deck'),
z.literal('library.new'),
z.literal('media.pause'),
z.literal('media.play'),
z.literal('media.rate'),
z.literal('media.resume'),
z.literal('media.scrobble'),
z.literal('media.stop'),
// We don't care about the server owner events, at the momen
]),
user: z.boolean(),
owner: z.boolean(),
Account: z.object({
id: z.number(),
thumb: z.string(),
title: z.string(),
}),
Server: z.object({
title: z.string(), // Name
uuid: z.string(), // 'client_identifier'
}),
Player: z
.object({
local: z.boolean(),
publicAddress: z.string(),
title: z.string(),
uuid: z.string(),
})
.optional(), // Only defined on play events
});
Loading