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

Files 841 handle open with docs over size failures #404

Open
wants to merge 12 commits into
base: devel
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
6 changes: 6 additions & 0 deletions __mocks__/@zextras/carbonio-shell-ui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,9 @@ export const EMAIL_VALIDATION_REGEX =
export const registerActions: typeof shell.registerActions = () => undefined;
export const removeActions: typeof shell.removeActions = () => undefined;
export const Spinner: typeof shell.Spinner = () => <>Spinner component stub</>;
const noop = (): void => undefined;
export const useTracker: typeof shell.useTracker = () => ({
capture: noop,
enableTracker: noop,
reset: noop
});
3,472 changes: 1,873 additions & 1,599 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@
"jest-styled-components": "^7.2.0",
"msw": "^2.4.9",
"npm-check-updates": "^17.1.3",
"ts-node": "^10.9.2"
"ts-node": "^10.9.2",
"typescript": "^5.6.3"
},
"dependencies": {
"@apollo/client": "3.10.8",
Expand Down
7 changes: 6 additions & 1 deletion src/carbonio-files-ui-common/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ export const HTTP_STATUS_CODE = {
maxVersionReached: 405,
/** aborted or blocked request */
aborted: 0,
overQuota: 422
overQuota: 422,
docsFileSizeExceeded: 403
} as const;

export const ERROR_CODE = {
Expand Down Expand Up @@ -183,3 +184,7 @@ export const FILTER_TYPE = {

export const FILES_ROUTE = 'files';
export const FILES_APP_ID = 'carbonio-files-ui';

export const TRACKER_EVENT = {
openDocumentWithDocs: 'Open document with Docs'
} as const;
66 changes: 66 additions & 0 deletions src/carbonio-files-ui-common/hooks/useHeaderActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* SPDX-FileCopyrightText: 2024 Zextras <https://www.zextras.com>
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { useCallback } from 'react';

import { HeaderAction } from '@zextras/carbonio-ui-preview/lib/preview/Header';
import { useTranslation } from 'react-i18next';

import { useHealthInfo } from './useHealthInfo';
import { useOpenWithDocs } from './useOpenWithDocs';
import { useActiveNode } from '../../hooks/useActiveNode';
import { DISPLAYER_TABS } from '../constants';
import { File } from '../types/graphql/types';
import { canEdit, canOpenWithDocs } from '../utils/ActionsFactory';
import { downloadNode } from '../utils/utils';

export function useHeaderActions(): (
node: Pick<File, '__typename' | 'id' | 'permissions' | 'rootId' | 'mime_type'>
) => Array<HeaderAction> {
const [t] = useTranslation();
const openNodeWithDocs = useOpenWithDocs();
const { setActiveNode } = useActiveNode();
const { canUseDocs } = useHealthInfo();

return useCallback(
(node) => {
const actions: Array<HeaderAction> = [
{
icon: 'ShareOutline',
id: 'ShareOutline',
tooltipLabel: t('preview.actions.tooltip.manageShares', 'Manage shares'),
onClick: (): void => setActiveNode(node.id, DISPLAYER_TABS.sharing)
},
{
icon: 'DownloadOutline',
tooltipLabel: t('preview.actions.tooltip.download', 'Download'),
id: 'DownloadOutline',
onClick: (): void => downloadNode(node.id)
}
];
if (canEdit({ nodes: [node], canUseDocs })) {
actions.unshift({
icon: 'Edit2Outline',
id: 'Edit',
onClick: (): void => {
openNodeWithDocs(node.id);
},
tooltipLabel: t('preview.actions.tooltip.edit', 'Edit')
});
} else if (canOpenWithDocs({ nodes: [node], canUseDocs })) {
actions.unshift({
id: 'OpenWithDocs',
icon: 'BookOpenOutline',
tooltipLabel: t('actions.openWithDocs', 'Open document'),
onClick: (): void => {
openNodeWithDocs(node.id);
}
});
}
return actions;
},
[canUseDocs, openNodeWithDocs, setActiveNode, t]
);
}
119 changes: 119 additions & 0 deletions src/carbonio-files-ui-common/hooks/useOpenWithDocs.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* SPDX-FileCopyrightText: 2024 Zextras <https://www.zextras.com>
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import React from 'react';

import { faker } from '@faker-js/faker';
import { act } from '@testing-library/react';
import { CreateSnackbarFn, CreateSnackbarFnArgs, Text } from '@zextras/carbonio-design-system';
import { http, HttpResponse } from 'msw';

import { OpenWithDocsResponse, useOpenWithDocs } from './useOpenWithDocs';
import server from '../../mocks/server';
import { DOCS_ENDPOINT, HTTP_STATUS_CODE, OPEN_FILE_PATH } from '../constants';
import { setupHook } from '../tests/utils';

let mockCreateSnackbar: jest.MockedFn<CreateSnackbarFn>;

jest.mock('@zextras/carbonio-design-system', () => ({
...jest.requireActual('@zextras/carbonio-design-system'),
useSnackbar: (): CreateSnackbarFn => mockCreateSnackbar
}));

beforeEach(() => {
mockCreateSnackbar = jest.fn();
});

describe('useOpenWithDocs hook', () => {
it('should open the returned url if the document can be opened', async () => {
const fileOpenUrl = faker.internet.url();
server.use(
http.get<Record<string, string>, never, OpenWithDocsResponse>(
`${DOCS_ENDPOINT}${OPEN_FILE_PATH}/:id`,
() => HttpResponse.json({ fileOpenUrl })
)
);

const spyWindowOpen = jest.spyOn(window, 'open').mockImplementation();
const { result } = setupHook(() => useOpenWithDocs());
await result.current('id');
expect(spyWindowOpen).toHaveBeenCalledWith(fileOpenUrl, fileOpenUrl);
});

it('should show specific snackbar if document cannot be opened due to its size', async () => {
server.use(
http.get<Record<string, string>, never, OpenWithDocsResponse>(
`${DOCS_ENDPOINT}${OPEN_FILE_PATH}/:id`,
() => HttpResponse.json(null, { status: HTTP_STATUS_CODE.docsFileSizeExceeded })
)
);

const spyWindowOpen = jest.spyOn(window, 'open').mockImplementation();
const { result } = setupHook(() => useOpenWithDocs());

await act(async () => {
await result.current('id');
});

expect(spyWindowOpen).not.toHaveBeenCalled();
const label = (
<>
<Text color="gray6" size="medium" overflow={'break-word'}>
{'The item exceeds the size limit allowed and cannot be opened.'}
</Text>
<Text color="gray6" size="medium" overflow={'break-word'}>
{'To view the item, please download it on your device'}
</Text>
</>
);
expect(mockCreateSnackbar).toHaveBeenCalledWith(
expect.objectContaining<CreateSnackbarFnArgs>({
label,
actionLabel: 'Ok',
disableAutoHide: true,
severity: 'warning'
})
);
});

it('should show generic error snackbar if status code is unhandled', async () => {
server.use(
http.get<Record<string, string>, never, OpenWithDocsResponse>(
`${DOCS_ENDPOINT}${OPEN_FILE_PATH}/:id`,
() => HttpResponse.json(null, { status: 500 })
)
);

const spyWindowOpen = jest.spyOn(window, 'open').mockImplementation();
const { result } = setupHook(() => useOpenWithDocs());

await act(async () => {
await result.current('id');
});

expect(spyWindowOpen).not.toHaveBeenCalled();
const label = 'Something went wrong';
expect(mockCreateSnackbar).toHaveBeenCalledWith(
expect.objectContaining<CreateSnackbarFnArgs>({ label })
);
});

it('should show generic error snackbar if there is a network error', async () => {
server.use(http.get(`${DOCS_ENDPOINT}${OPEN_FILE_PATH}/:id`, () => HttpResponse.error()));

const spyWindowOpen = jest.spyOn(window, 'open').mockImplementation();
const { result } = setupHook(() => useOpenWithDocs());

await act(async () => {
await result.current('id');
});

expect(spyWindowOpen).not.toHaveBeenCalled();
const label = 'Something went wrong';
expect(mockCreateSnackbar).toHaveBeenCalledWith(
expect.objectContaining<CreateSnackbarFnArgs>({ label })
);
});
});
98 changes: 98 additions & 0 deletions src/carbonio-files-ui-common/hooks/useOpenWithDocs.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* SPDX-FileCopyrightText: 2024 Zextras <https://www.zextras.com>
*
* SPDX-License-Identifier: AGPL-3.0-only
*/

import React, { useCallback } from 'react';

import { useSnackbar, Text } from '@zextras/carbonio-design-system';
import { useTranslation } from 'react-i18next';

import { useTracker } from '../../hooks/useTracker';
import {
DOCS_ENDPOINT,
FILES_APP_ID,
HTTP_STATUS_CODE,
OPEN_FILE_PATH,
TRACKER_EVENT
} from '../constants';

export type OpenWithDocsResponse = { fileOpenUrl: string };

const docsTabMap: { [url: string]: Window } = {};

const openNodeWithDocs = (url: string): void => {
if (docsTabMap[url] == null || docsTabMap[url]?.closed) {
docsTabMap[url] = window.open(url, url) as Window;
} else {
docsTabMap[url].focus();
}
};

type OpenWithDocsFn = (id: string, version?: number) => Promise<void>;

export const useOpenWithDocs = (): OpenWithDocsFn => {
const createSnackbar = useSnackbar();
const [t] = useTranslation();
const { capture } = useTracker();
return useCallback(
async (id, version) => {
try {
const response = await fetch(
`${DOCS_ENDPOINT}${OPEN_FILE_PATH}/${encodeURIComponent(id)}${
version ? `?version=${version}` : ''
}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
);
capture(TRACKER_EVENT.openDocumentWithDocs, { app: FILES_APP_ID, success: response.ok });
if (!response.ok) {
if (response.status === HTTP_STATUS_CODE.docsFileSizeExceeded) {
createSnackbar({
key: new Date().toLocaleString(),
severity: 'warning',
label: (
<>
<Text color="gray6" size="medium" overflow={'break-word'}>
{t(
'snackbar.openWithDocs.error.exceedSizeLimit',
'The item exceeds the size limit allowed and cannot be opened.'
)}
</Text>
<Text color="gray6" size="medium" overflow={'break-word'}>
{t(
'snackbar.openWithDocs.error.pleaseDownload',
'To view the item, please download it on your device'
)}
</Text>
</>
),
replace: true,
actionLabel: t('snackbar.openWithDocs.error.exceedSizeLimit.actionLabel', 'Ok'),
disableAutoHide: true
});
} else {
throw new Error('Error code not handled');
}
} else {
const { fileOpenUrl } = (await response.json()) as OpenWithDocsResponse;
openNodeWithDocs(fileOpenUrl);
}
} catch (error) {
createSnackbar({
key: new Date().toLocaleString(),
severity: 'warning',
label: t('errorCode.code', 'Something went wrong', { context: 'Generic' }),
replace: true,
hideButton: true
});
}
},
[capture, createSnackbar, t]
);
};
4 changes: 2 additions & 2 deletions src/carbonio-files-ui-common/hooks/useUpload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import { useCallback, useMemo } from 'react';
import { forEach, map, filter, includes, reduce, noop, partition } from 'lodash';
import { v4 as uuidv4 } from 'uuid';

import buildClient from '../apollo';
import { useCreateFolderMutation } from './graphql/mutations/useCreateFolderMutation';
import { useUpdateFolderContent } from './graphql/useUpdateFolderContent';
import buildClient from '../apollo';
import { nodeSortVar } from '../apollo/nodeSortVar';
import { UploadFunctions, uploadFunctionsVar, uploadVar } from '../apollo/uploadVar';
import { UploadFolderItem } from '../types/common';
import { useCreateFolderMutation } from './graphql/mutations/useCreateFolderMutation';
import { UploadItem, UploadStatus } from '../types/graphql/client-types';
import { File as FilesFile } from '../types/graphql/types';
import { DeepPick } from '../types/utils';
Expand Down
20 changes: 0 additions & 20 deletions src/carbonio-files-ui-common/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,9 @@ import { DefaultTheme } from 'styled-components';
import { getUserAccount } from '../../utils/utils';
import {
DATE_FORMAT,
DOCS_ENDPOINT,
DOCS_EXTENSIONS,
DOWNLOAD_PATH,
INTERNAL_PATH,
OPEN_FILE_PATH,
REST_ENDPOINT,
ROOTS,
TIMERS,
Expand Down Expand Up @@ -330,24 +328,6 @@ export const downloadNode = (id: string, version?: number): void => {
}
};

const docsTabMap: { [url: string]: Window } = {};

/**
* Open with docs
*/
export const openNodeWithDocs = (id: string, version?: number): void => {
if (id) {
const url = `${DOCS_ENDPOINT}${OPEN_FILE_PATH}/${encodeURIComponent(id)}${
version ? `?version=${version}` : ''
}`;
if (docsTabMap[url] == null || docsTabMap[url]?.closed) {
docsTabMap[url] = window.open(url, url) as Window;
} else {
docsTabMap[url].focus();
}
}
};

export const inputElement = ((): HTMLInputElement => {
const input = document.createElement('input');
if (input) {
Expand Down
Loading