Merge branch '19153-sharing-links-inline' into main. Closes #19153
[arvados-workbench2.git] / src / views-components / context-menu / actions / helpers.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { REDIRECT_TO_DOWNLOAD_KEY, REDIRECT_TO_PREVIEW_KEY } from "common/redirect-to";
6 import { extractUuidKind, ResourceKind } from "models/resource";
7
8 export const sanitizeToken = (href: string, tokenAsQueryParam = true): string => {
9     const [prefix, suffix] = href.split('/t=');
10     const [token1, token2, token3, ...rest] = suffix.split('/');
11     const token = `${token1}/${token2}/${token3}`;
12     const sep = href.indexOf("?") > -1 ? "&" : "?";
13
14     return `${[prefix, ...rest].join('/')}${tokenAsQueryParam ? `${sep}api_token=${token}` : ''}`;
15 };
16
17 export const getClipboardUrl = (href: string, shouldSanitizeToken = true, inline = false): string => {
18     const { origin } = window.location;
19     const url = shouldSanitizeToken ? sanitizeToken(href, false) : href;
20     const redirectKey = inline ? REDIRECT_TO_PREVIEW_KEY : REDIRECT_TO_DOWNLOAD_KEY;
21
22     return shouldSanitizeToken ? `${origin}?${redirectKey}=${url}` : `${origin}${url}`;
23 };
24
25 export const getInlineFileUrl = (url: string, keepWebSvcUrl: string, keepWebInlineSvcUrl: string): string => {
26     const collMatch = url.match(/\/c=([a-z0-9-+]+)\//);
27     if (collMatch === null) { return ''; }
28     if (extractUuidKind(collMatch[1]) !== ResourceKind.COLLECTION) { return ''; }
29     const collId = collMatch[1].replace('+', '-');
30     let inlineUrl = keepWebInlineSvcUrl !== ""
31         ? url.replace(keepWebSvcUrl, keepWebInlineSvcUrl)
32         : url;
33     let uuidOnHostname = false;
34     // Inline URLs as 'https://*.collections.example.com' or
35     // 'https://*--collections.example.com' should get the uuid on their hostnames
36     // See: https://doc.arvados.org/v2.1/api/keep-web-urls.html
37     if (inlineUrl.indexOf('*.') > -1) {
38         inlineUrl = inlineUrl.replace('*.', `${collId}.`);
39         uuidOnHostname = true;
40     } else if (inlineUrl.indexOf('*--') > -1) {
41         inlineUrl = inlineUrl.replace('*--', `${collId}--`);
42         uuidOnHostname = true;
43     }
44     if (uuidOnHostname) {
45         inlineUrl = inlineUrl.replace(`/c=${collMatch[1]}`, '');
46     }
47     return inlineUrl;
48 };
49
50 export const isInlineFileUrlSafe = (url: string, keepWebSvcUrl: string, keepWebInlineSvcUrl: string): boolean => {
51   let inlineUrl = keepWebInlineSvcUrl !== ""
52       ? url.replace(keepWebSvcUrl, keepWebInlineSvcUrl)
53       : url;
54   return inlineUrl.indexOf('*.') > -1;
55 }