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 8 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 ]
});
}
});
};
46 changes: 46 additions & 0 deletions src/apps/dashboard/features/keys/components/ApiKeyCell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React, { FunctionComponent, useCallback } from 'react';
import type { AuthenticationInfo } from '@jellyfin/sdk/lib/generated-client/models/authentication-info';
import ButtonElement from 'elements/ButtonElement';
import datetime from 'scripts/datetime';
import globalize from 'lib/globalize';

type ApiKeyCellProps = {
apiKey: AuthenticationInfo;
revokeKey?: (accessToken: string) => void;
};

const ApiKeyCell: FunctionComponent<ApiKeyCellProps> = ({ apiKey, revokeKey }: ApiKeyCellProps) => {
const getDate = (dateCreated: string | undefined) => {
const date = datetime.parseISO8601Date(dateCreated, true);
return datetime.toLocaleDateString(date) + ' ' + datetime.getDisplayTime(date);
};

const onClick = useCallback(() => {
if (apiKey?.AccessToken && revokeKey !== undefined) {
revokeKey(apiKey.AccessToken);
}
}, [apiKey, revokeKey]);

return (
<tr className='detailTableBodyRow detailTableBodyRow-shaded apiKey'>
<td className='detailTableBodyCell'>
<ButtonElement
className='raised raised-mini btnRevoke'
title={globalize.translate('ButtonRevoke')}
onClick={onClick}
/>
</td>
<td className='detailTableBodyCell' style={{ verticalAlign: 'middle' }}>
{apiKey.AccessToken}
</td>
<td className='detailTableBodyCell' style={{ verticalAlign: 'middle' }}>
{apiKey.AppName}
</td>
<td className='detailTableBodyCell' style={{ verticalAlign: 'middle' }}>
{getDate(apiKey.DateCreated)}
</td>
</tr>
);
};

export default ApiKeyCell;
3 changes: 2 additions & 1 deletion src/apps/dashboard/routes/_asyncRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ export const ASYNC_ADMIN_ROUTES: AsyncRoute[] = [
{ path: 'users/add', type: AsyncRouteType.Dashboard },
{ path: 'users/parentalcontrol', type: AsyncRouteType.Dashboard },
{ path: 'users/password', type: AsyncRouteType.Dashboard },
{ path: 'users/profile', type: AsyncRouteType.Dashboard }
{ path: 'users/profile', type: AsyncRouteType.Dashboard },
{ path: 'keys', type: AsyncRouteType.Dashboard }
];
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
95 changes: 95 additions & 0 deletions src/apps/dashboard/routes/keys/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import Page from 'components/Page';
import SectionTitleContainer from 'elements/SectionTitleContainer';
import { useApi } from 'hooks/useApi';
import globalize from 'lib/globalize';
import React, { useCallback } from 'react';
import type { AuthenticationInfo } from '@jellyfin/sdk/lib/generated-client/models/authentication-info';
import Loading from 'components/loading/LoadingComponent';
import confirm from 'components/confirm/confirm';
import ApiKeyCell from 'apps/dashboard/features/keys/components/ApiKeyCell';
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';

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

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]);

if (isLoading) {
return <Loading />;
}

return (
<Page
id='apiKeysPage'
title={globalize.translate('HeaderApiKeys')}
className='mainAnimatedPage type-interior'
>
<div className='content-primary'>
<SectionTitleContainer
title={globalize.translate('HeaderApiKeys')}
isBtnVisible={true}
btnId='btnAddSchedule'
btnClassName='fab submit sectionTitleButton btnNewKey'
btnTitle={globalize.translate('Add')}
btnIcon='add'
onClick={showNewKeyPopup}
/>
<p>{globalize.translate('HeaderApiKeysHelp')}</p>
<br />
<table className='tblApiKeys detailTable'>
<caption className='clipForScreenReader'>{globalize.translate('ApiKeysCaption')}</caption>
<thead>
<tr>
<th scope='col' className='detailTableHeaderCell'></th>
<th scope='col' className='detailTableHeaderCell'>{globalize.translate('HeaderApiKey')}</th>
<th scope='col' className='detailTableHeaderCell'>{globalize.translate('HeaderApp')}</th>
<th scope='col' className='detailTableHeaderCell'>{globalize.translate('HeaderDateIssued')}</th>
</tr>
</thead>
<tbody className='resultBody'>
{keys?.Items?.map((key: AuthenticationInfo) => {
return <ApiKeyCell key={key.AccessToken} apiKey={key} revokeKey={onRevokeKey} />;
})}
</tbody>
</table>
</div>
</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.

31 changes: 22 additions & 9 deletions src/elements/ButtonElement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,32 @@ type IProps = {
title?: string;
leftIcon?: string;
rightIcon?: string;
onClick?: () => void;
};

const ButtonElement: FunctionComponent<IProps> = ({ type, id, className, title, leftIcon, rightIcon }: IProps) => {
const ButtonElement: FunctionComponent<IProps> = ({ type, id, className, title, leftIcon, rightIcon, onClick }: IProps) => {
const button = createButtonElement({
type: type,
id: id ? `id="${id}"` : '',
className: className,
title: globalize.translate(title),
leftIcon: leftIcon ? `<span class="material-icons ${leftIcon}" aria-hidden="true"></span>` : '',
rightIcon: rightIcon ? `<span class="material-icons ${rightIcon}" aria-hidden="true"></span>` : ''
});

if (onClick !== undefined) {
return (
<button
style={{ all: 'unset' }}
dangerouslySetInnerHTML={button}
onClick={onClick}
/>
);
}

return (
<div
dangerouslySetInnerHTML={createButtonElement({
type: type,
id: id ? `id="${id}"` : '',
className: className,
title: globalize.translate(title),
leftIcon: leftIcon ? `<span class="material-icons ${leftIcon}" aria-hidden="true"></span>` : '',
rightIcon: rightIcon ? `<span class="material-icons ${rightIcon}" aria-hidden="true"></span>` : ''
})}
dangerouslySetInnerHTML={button}
/>
);
};
Expand Down
Loading
Loading