Merge branch '19899-webdav-cache-control' into main. Closes #19899
[arvados.git] / src / common / redirect-to.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { getInlineFileUrl } from 'views-components/context-menu/actions/helpers';
6 import { Config } from './config';
7
8 export const REDIRECT_TO_DOWNLOAD_KEY = 'redirectToDownload';
9 export const REDIRECT_TO_PREVIEW_KEY = 'redirectToPreview';
10 export const REDIRECT_TO_KEY = 'redirectTo';
11
12 const getRedirectKeyFromUrl = (href: string): string | null => {
13     switch (true) {
14         case href.indexOf(REDIRECT_TO_DOWNLOAD_KEY) > -1:
15             return REDIRECT_TO_DOWNLOAD_KEY;
16         case href.indexOf(REDIRECT_TO_PREVIEW_KEY) > -1:
17             return REDIRECT_TO_PREVIEW_KEY;
18         case href.indexOf(`${REDIRECT_TO_KEY}=`) > -1:
19             return REDIRECT_TO_KEY;
20         default:
21             return null;
22     }
23 }
24
25 const getRedirectKeyFromStorage = (localStorage: Storage): string | null => {
26     if (localStorage.getItem(REDIRECT_TO_DOWNLOAD_KEY)) {
27         return REDIRECT_TO_DOWNLOAD_KEY;
28     } else if (localStorage.getItem(REDIRECT_TO_PREVIEW_KEY)) {
29         return REDIRECT_TO_PREVIEW_KEY;
30     }
31     return null;
32 }
33
34 export const storeRedirects = () => {
35     const { location: { href }, localStorage } = window;
36     const redirectKey = getRedirectKeyFromUrl(href);
37
38     // Change old redirectTo -> redirectToPreview when storing redirect
39     const redirectStoreKey = redirectKey === REDIRECT_TO_KEY ? REDIRECT_TO_PREVIEW_KEY : redirectKey;
40
41     if (localStorage && redirectKey && redirectStoreKey) {
42         localStorage.setItem(redirectStoreKey, href.split(`${redirectKey}=`)[1]);
43     }
44 };
45
46 export const handleRedirects = (token: string, config: Config) => {
47     const { localStorage } = window;
48     const { keepWebServiceUrl, keepWebInlineServiceUrl } = config;
49
50     if (localStorage) {
51         const redirectKey = getRedirectKeyFromStorage(localStorage);
52         const redirectPath = redirectKey ? localStorage.getItem(redirectKey) : '';
53         redirectKey && localStorage.removeItem(redirectKey);
54
55         if (redirectKey && redirectPath) {
56             const sep = redirectPath.indexOf("?") > -1 ? "&" : "?";
57             let redirectUrl = `${keepWebServiceUrl}${redirectPath}${sep}api_token=${token}`;
58             if (redirectKey === REDIRECT_TO_PREVIEW_KEY) {
59                 redirectUrl = getInlineFileUrl(redirectUrl, keepWebServiceUrl, keepWebInlineServiceUrl);
60             }
61             window.location.href = redirectUrl;
62         }
63     }
64 };