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

Migrate apikeys to React #6390

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
27 changes: 27 additions & 0 deletions src/apps/dashboard/features/keys/api/useApiKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Api } from '@jellyfin/sdk';
import { getApiKeyApi } from '@jellyfin/sdk/lib/utils/api/api-key-api';
import { useQuery } from '@tanstack/react-query';
import { useApi } from 'hooks/useApi';

export const QUERY_KEY = 'ApiKeys';

const fetchApiKeys = async (api?: Api) => {
if (!api) {
console.error('[useApiKeys] Failed to create Api instance');
return;
}

const response = await getApiKeyApi(api).getKeys();

return response.data;
};

export const useApiKeys = () => {
const { api } = useApi();

return useQuery({
queryKey: [ QUERY_KEY ],
queryFn: () => fetchApiKeys(api),
enabled: !!api
});
};
23 changes: 23 additions & 0 deletions src/apps/dashboard/features/keys/api/useCreateKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ApiKeyApiCreateKeyRequest } from '@jellyfin/sdk/lib/generated-client/api/api-key-api';
import { getApiKeyApi } from '@jellyfin/sdk/lib/utils/api/api-key-api';
import { useMutation } from '@tanstack/react-query';
import { useApi } from 'hooks/useApi';
import { queryClient } from 'utils/query/queryClient';
import { QUERY_KEY } from './useApiKeys';

export const useCreateKey = () => {
const { api } = useApi();

return useMutation({
mutationFn: (params: ApiKeyApiCreateKeyRequest) => (
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
getApiKeyApi(api!)
.createKey(params)
),
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: [ QUERY_KEY ]
});
}
});
};
23 changes: 23 additions & 0 deletions src/apps/dashboard/features/keys/api/useRevokeKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ApiKeyApiRevokeKeyRequest } from '@jellyfin/sdk/lib/generated-client';
import { getApiKeyApi } from '@jellyfin/sdk/lib/utils/api/api-key-api';
import { useMutation } from '@tanstack/react-query';
import { useApi } from 'hooks/useApi';
import { queryClient } from 'utils/query/queryClient';
import { QUERY_KEY } from './useApiKeys';

export const useRevokeKey = () => {
const { api } = useApi();

return useMutation({
mutationFn: (params: ApiKeyApiRevokeKeyRequest) => (
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
getApiKeyApi(api!)
.revokeKey(params)
),
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: [ QUERY_KEY ]
});
}
});
};
1 change: 1 addition & 0 deletions src/apps/dashboard/routes/_asyncRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { AsyncRouteType, type AsyncRoute } from 'components/router/AsyncRoute';
export const ASYNC_ADMIN_ROUTES: AsyncRoute[] = [
{ path: 'activity', type: AsyncRouteType.Dashboard },
{ path: 'branding', type: AsyncRouteType.Dashboard },
{ path: 'keys', type: AsyncRouteType.Dashboard },
{ path: 'playback/trickplay', type: AsyncRouteType.Dashboard },
{ path: 'plugins/:pluginId', page: 'plugins/plugin', type: AsyncRouteType.Dashboard },
{ path: 'users', type: AsyncRouteType.Dashboard },
Expand Down
6 changes: 0 additions & 6 deletions src/apps/dashboard/routes/_legacyRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,6 @@ export const LEGACY_ADMIN_ROUTES: LegacyRoute[] = [
controller: 'dashboard/scheduledtasks/scheduledtasks',
view: 'dashboard/scheduledtasks/scheduledtasks.html'
}
}, {
path: 'keys',
pageProps: {
controller: 'dashboard/apikeys',
view: 'dashboard/apikeys.html'
}
}, {
path: 'playback/streaming',
pageProps: {
Expand Down
157 changes: 157 additions & 0 deletions src/apps/dashboard/routes/keys/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import Page from 'components/Page';
import { useApi } from 'hooks/useApi';
import globalize from 'lib/globalize';
import React, { useCallback, useMemo } from 'react';
import type { AuthenticationInfo } from '@jellyfin/sdk/lib/generated-client/models/authentication-info';
import confirm from 'components/confirm/confirm';
import { useApiKeys } from 'apps/dashboard/features/keys/api/useApiKeys';
import { useRevokeKey } from 'apps/dashboard/features/keys/api/useRevokeKey';
import { useCreateKey } from 'apps/dashboard/features/keys/api/useCreateKey';
import { Box, Button, IconButton, Stack, Tooltip, Typography } from '@mui/material';
import { MaterialReactTable, MRT_ColumnDef, useMaterialReactTable } from 'material-react-table';
import { getDisplayTime, parseISO8601Date, toLocaleDateString } from 'scripts/datetime';
import DeleteIcon from '@mui/icons-material/Delete';

const ApiKeys = () => {
const { api } = useApi();
const { data: keys, isLoading } = useApiKeys();
const revokeKey = useRevokeKey();
const createKey = useCreateKey();

const columns = useMemo<MRT_ColumnDef<AuthenticationInfo>[]>(() => [
{
id: 'ApiKey',
accessorKey: 'AccessToken',
header: globalize.translate('HeaderApiKey'),
size: 300
},
{
id: 'AppName',
accessorKey: 'AppName',
header: globalize.translate('HeaderApp')
},
{
id: 'DateIssued',
accessorFn: item => parseISO8601Date(item.DateCreated),
Cell: ({ cell }) => toLocaleDateString(cell.getValue<Date>()) + ' ' + getDisplayTime(cell.getValue<Date>()),
header: globalize.translate('HeaderDateIssued'),
filterVariant: 'datetime-range'
}
], []);

const table = useMaterialReactTable({
columns,
data: keys?.Items || [],

state: {
isLoading
},

rowCount: keys?.TotalRecordCount || 0,

enableColumnPinning: true,
enableColumnResizing: true,

enableStickyFooter: true,
enableStickyHeader: true,
muiTableContainerProps: {
sx: {
maxHeight: 'calc(100% - 7rem)' // 2 x 3.5rem for header and footer
}
},

// Enable (delete) row actions
enableRowActions: true,
displayColumnDefOptions: {
'mrt-row-actions': {
header: '',
size: 25
}
},

renderTopToolbarCustomActions: () => (
<Button onClick={showNewKeyPopup}>{globalize.translate('HeaderNewApiKey')}</Button>
),

renderRowActions: ({ row }) => {
return (
<Box sx={{ display: 'flex' }}>
<Tooltip title={globalize.translate('ButtonRevoke')}>
<IconButton
color='error'
// eslint-disable-next-line react/jsx-no-bind
onClick={() => row.original?.AccessToken && onRevokeKey(row.original.AccessToken)}
>
<DeleteIcon />
</IconButton>
</Tooltip>
</Box>
);
}
});

const onRevokeKey = useCallback((accessToken: string) => {
if (!api) return;

confirm(globalize.translate('MessageConfirmRevokeApiKey'), globalize.translate('HeaderConfirmRevokeApiKey')).then(function () {
revokeKey.mutate({
key: accessToken
});
}).catch(err => {
console.error('[apikeys] failed to show confirmation dialog', err);
});
}, [api, revokeKey]);

const showNewKeyPopup = useCallback(() => {
if (!api) return;

import('../../../../components/prompt/prompt').then(({ default: prompt }) => {
prompt({
title: globalize.translate('HeaderNewApiKey'),
label: globalize.translate('LabelAppName'),
description: globalize.translate('LabelAppNameExample')
}).then((value) => {
createKey.mutate({
app: value
});
}).catch(() => {
// popup closed
});
}).catch(err => {
console.error('[apikeys] failed to load api key popup', err);
});
}, [api, createKey]);

return (
<Page
id='apiKeysPage'
title={globalize.translate('HeaderApiKeys')}
className='mainAnimatedPage type-interior'
>
<Box
className='content-primary'
sx={{
display: 'flex',
flexDirection: 'column',
height: '100%'
}}
>
<Box
sx={{
marginBottom: 1
}}
>
<Stack spacing={2}>
<Typography variant='h2'>
{globalize.translate('HeaderApiKeys')}
</Typography>
<Typography>{globalize.translate('HeaderApiKeysHelp')}</Typography>
</Stack>
</Box>
<MaterialReactTable table={table} />
</Box>
</Page>
);
};

export default ApiKeys;
26 changes: 0 additions & 26 deletions src/controllers/dashboard/apikeys.html

This file was deleted.

89 changes: 0 additions & 89 deletions src/controllers/dashboard/apikeys.js

This file was deleted.

Loading
Loading