Merge branch '13494-collection-version-browser'
[arvados-workbench2.git] / src / views-components / data-explorer / renderers.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { Grid, Typography, withStyles, Tooltip, IconButton, Checkbox } from '@material-ui/core';
7 import { FavoriteStar, PublicFavoriteStar } from '../favorite-star/favorite-star';
8 import { ResourceKind, TrashableResource } from '~/models/resource';
9 import { ProjectIcon, CollectionIcon, ProcessIcon, DefaultIcon, ShareIcon, CollectionOldVersionIcon, WorkflowIcon } from '~/components/icon/icon';
10 import { formatDate, formatFileSize, formatTime } from '~/common/formatters';
11 import { resourceLabel } from '~/common/labels';
12 import { connect, DispatchProp } from 'react-redux';
13 import { RootState } from '~/store/store';
14 import { getResource } from '~/store/resources/resources';
15 import { GroupContentsResource } from '~/services/groups-service/groups-service';
16 import { getProcess, Process, getProcessStatus, getProcessStatusColor, getProcessRuntime } from '~/store/processes/process';
17 import { ArvadosTheme } from '~/common/custom-theme';
18 import { compose, Dispatch } from 'redux';
19 import { WorkflowResource } from '~/models/workflow';
20 import { ResourceStatus as WorkflowStatus } from '~/views/workflow-panel/workflow-panel-view';
21 import { getUuidPrefix, openRunProcess } from '~/store/workflow-panel/workflow-panel-actions';
22 import { openSharingDialog } from '~/store/sharing-dialog/sharing-dialog-actions';
23 import { UserResource } from '~/models/user';
24 import { toggleIsActive, toggleIsAdmin } from '~/store/users/users-actions';
25 import { LinkResource } from '~/models/link';
26 import { navigateTo } from '~/store/navigation/navigation-action';
27 import { withResourceData } from '~/views-components/data-explorer/with-resources';
28 import { CollectionResource } from '~/models/collection';
29 import { IllegalNamingWarning } from '~/components/warning/warning';
30
31 const renderName = (dispatch: Dispatch, item: GroupContentsResource) =>
32     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
33         <Grid item>
34             {renderIcon(item)}
35         </Grid>
36         <Grid item>
37             <Typography color="primary" style={{ width: 'auto', cursor: 'pointer' }} onClick={() => dispatch<any>(navigateTo(item.uuid))}>
38                 {item.kind === ResourceKind.PROJECT || item.kind === ResourceKind.COLLECTION
39                     ? <IllegalNamingWarning name={item.name} />
40                     : null}
41                 {item.name}
42             </Typography>
43         </Grid>
44         <Grid item>
45             <Typography variant="caption">
46                 <FavoriteStar resourceUuid={item.uuid} />
47                 <PublicFavoriteStar resourceUuid={item.uuid} />
48             </Typography>
49         </Grid>
50     </Grid>;
51
52 export const ResourceName = connect(
53     (state: RootState, props: { uuid: string }) => {
54         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
55         return resource;
56     })((resource: GroupContentsResource & DispatchProp<any>) => renderName(resource.dispatch, resource));
57
58 const renderIcon = (item: GroupContentsResource) => {
59     switch (item.kind) {
60         case ResourceKind.PROJECT:
61             return <ProjectIcon />;
62         case ResourceKind.COLLECTION:
63             if (item.uuid === item.currentVersionUuid) {
64                 return <CollectionIcon />;
65             }
66             return <CollectionOldVersionIcon />;
67         case ResourceKind.PROCESS:
68             return <ProcessIcon />;
69         case ResourceKind.WORKFLOW:
70             return <WorkflowIcon />;
71         default:
72             return <DefaultIcon />;
73     }
74 };
75
76 const renderDate = (date?: string) => {
77     return <Typography noWrap style={{ minWidth: '100px' }}>{formatDate(date)}</Typography>;
78 };
79
80 const renderWorkflowName = (item: WorkflowResource) =>
81     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
82         <Grid item>
83             {renderIcon(item)}
84         </Grid>
85         <Grid item>
86             <Typography color="primary" style={{ width: '100px' }}>
87                 {item.name}
88             </Typography>
89         </Grid>
90     </Grid>;
91
92 export const ResourceWorkflowName = connect(
93     (state: RootState, props: { uuid: string }) => {
94         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
95         return resource;
96     })(renderWorkflowName);
97
98 const getPublicUuid = (uuidPrefix: string) => {
99     return `${uuidPrefix}-tpzed-anonymouspublic`;
100 };
101
102 const resourceShare = (dispatch: Dispatch, uuidPrefix: string, ownerUuid?: string, uuid?: string) => {
103     const isPublic = ownerUuid === getPublicUuid(uuidPrefix);
104     return (
105         <div>
106             {!isPublic && uuid &&
107                 <Tooltip title="Share">
108                     <IconButton onClick={() => dispatch<any>(openSharingDialog(uuid))}>
109                         <ShareIcon />
110                     </IconButton>
111                 </Tooltip>
112             }
113         </div>
114     );
115 };
116
117 export const ResourceShare = connect(
118     (state: RootState, props: { uuid: string }) => {
119         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
120         const uuidPrefix = getUuidPrefix(state);
121         return {
122             uuid: resource ? resource.uuid : '',
123             ownerUuid: resource ? resource.ownerUuid : '',
124             uuidPrefix
125         };
126     })((props: { ownerUuid?: string, uuidPrefix: string, uuid?: string } & DispatchProp<any>) =>
127         resourceShare(props.dispatch, props.uuidPrefix, props.ownerUuid, props.uuid));
128
129 const renderFirstName = (item: { firstName: string }) => {
130     return <Typography noWrap>{item.firstName}</Typography>;
131 };
132
133 // User Resources
134 export const ResourceFirstName = connect(
135     (state: RootState, props: { uuid: string }) => {
136         const resource = getResource<UserResource>(props.uuid)(state.resources);
137         return resource || { firstName: '' };
138     })(renderFirstName);
139
140 const renderLastName = (item: { lastName: string }) =>
141     <Typography noWrap>{item.lastName}</Typography>;
142
143 export const ResourceLastName = connect(
144     (state: RootState, props: { uuid: string }) => {
145         const resource = getResource<UserResource>(props.uuid)(state.resources);
146         return resource || { lastName: '' };
147     })(renderLastName);
148
149 const renderUuid = (item: { uuid: string }) =>
150     <Typography noWrap>{item.uuid}</Typography>;
151
152 export const ResourceUuid = connect(
153     (state: RootState, props: { uuid: string }) => {
154         const resource = getResource<UserResource>(props.uuid)(state.resources);
155         return resource || { uuid: '' };
156     })(renderUuid);
157
158 const renderEmail = (item: { email: string }) =>
159     <Typography noWrap>{item.email}</Typography>;
160
161 export const ResourceEmail = connect(
162     (state: RootState, props: { uuid: string }) => {
163         const resource = getResource<UserResource>(props.uuid)(state.resources);
164         return resource || { email: '' };
165     })(renderEmail);
166
167 const renderIsActive = (props: { uuid: string, isActive: boolean, toggleIsActive: (uuid: string) => void }) =>
168     <Checkbox
169         color="primary"
170         checked={props.isActive}
171         onClick={() => props.toggleIsActive(props.uuid)} />;
172
173 export const ResourceIsActive = connect(
174     (state: RootState, props: { uuid: string }) => {
175         const resource = getResource<UserResource>(props.uuid)(state.resources);
176         return resource || { isActive: false };
177     }, { toggleIsActive }
178 )(renderIsActive);
179
180 const renderIsAdmin = (props: { uuid: string, isAdmin: boolean, toggleIsAdmin: (uuid: string) => void }) =>
181     <Checkbox
182         color="primary"
183         checked={props.isAdmin}
184         onClick={() => props.toggleIsAdmin(props.uuid)} />;
185
186 export const ResourceIsAdmin = connect(
187     (state: RootState, props: { uuid: string }) => {
188         const resource = getResource<UserResource>(props.uuid)(state.resources);
189         return resource || { isAdmin: false };
190     }, { toggleIsAdmin }
191 )(renderIsAdmin);
192
193 const renderUsername = (item: { username: string }) =>
194     <Typography noWrap>{item.username}</Typography>;
195
196 export const ResourceUsername = connect(
197     (state: RootState, props: { uuid: string }) => {
198         const resource = getResource<UserResource>(props.uuid)(state.resources);
199         return resource || { username: '' };
200     })(renderUsername);
201
202 // Common methods
203 const renderCommonData = (data: string) =>
204     <Typography noWrap>{data}</Typography>;
205
206 const renderCommonDate = (date: string) =>
207     <Typography noWrap>{formatDate(date)}</Typography>;
208
209 export const CommonUuid = withResourceData('uuid', renderCommonData);
210
211 // Api Client Authorizations
212 export const TokenApiClientId = withResourceData('apiClientId', renderCommonData);
213
214 export const TokenApiToken = withResourceData('apiToken', renderCommonData);
215
216 export const TokenCreatedByIpAddress = withResourceData('createdByIpAddress', renderCommonDate);
217
218 export const TokenDefaultOwnerUuid = withResourceData('defaultOwnerUuid', renderCommonData);
219
220 export const TokenExpiresAt = withResourceData('expiresAt', renderCommonDate);
221
222 export const TokenLastUsedAt = withResourceData('lastUsedAt', renderCommonDate);
223
224 export const TokenLastUsedByIpAddress = withResourceData('lastUsedByIpAddress', renderCommonData);
225
226 export const TokenScopes = withResourceData('scopes', renderCommonData);
227
228 export const TokenUserId = withResourceData('userId', renderCommonData);
229
230 // Compute Node Resources
231 const renderNodeInfo = (data: string) => {
232     return <Typography>{JSON.stringify(data, null, 4)}</Typography>;
233 };
234
235 const clusterColors = [
236     ['#f44336', '#fff'],
237     ['#2196f3', '#fff'],
238     ['#009688', '#fff'],
239     ['#cddc39', '#fff'],
240     ['#ff9800', '#fff']
241 ];
242
243 export const ResourceCluster = (props: { uuid: string }) => {
244     const CLUSTER_ID_LENGTH = 5;
245     const pos = props.uuid.length > CLUSTER_ID_LENGTH ? props.uuid.indexOf('-') : 5;
246     const clusterId = pos >= CLUSTER_ID_LENGTH ? props.uuid.substr(0, pos) : '';
247     const ci = pos >= CLUSTER_ID_LENGTH ? (((((
248         (props.uuid.charCodeAt(0) * props.uuid.charCodeAt(1))
249         + props.uuid.charCodeAt(2))
250         * props.uuid.charCodeAt(3))
251         + props.uuid.charCodeAt(4))) % clusterColors.length) : 0;
252     return <span style={{
253         backgroundColor: clusterColors[ci][0],
254         color: clusterColors[ci][1],
255         padding: "2px 7px",
256         borderRadius: 3
257     }}>{clusterId}</span>;
258 };
259
260 export const ComputeNodeInfo = withResourceData('info', renderNodeInfo);
261
262 export const ComputeNodeDomain = withResourceData('domain', renderCommonData);
263
264 export const ComputeNodeFirstPingAt = withResourceData('firstPingAt', renderCommonDate);
265
266 export const ComputeNodeHostname = withResourceData('hostname', renderCommonData);
267
268 export const ComputeNodeIpAddress = withResourceData('ipAddress', renderCommonData);
269
270 export const ComputeNodeJobUuid = withResourceData('jobUuid', renderCommonData);
271
272 export const ComputeNodeLastPingAt = withResourceData('lastPingAt', renderCommonDate);
273
274 // Links Resources
275 const renderLinkName = (item: { name: string }) =>
276     <Typography noWrap>{item.name || '(none)'}</Typography>;
277
278 export const ResourceLinkName = connect(
279     (state: RootState, props: { uuid: string }) => {
280         const resource = getResource<LinkResource>(props.uuid)(state.resources);
281         return resource || { name: '' };
282     })(renderLinkName);
283
284 const renderLinkClass = (item: { linkClass: string }) =>
285     <Typography noWrap>{item.linkClass}</Typography>;
286
287 export const ResourceLinkClass = connect(
288     (state: RootState, props: { uuid: string }) => {
289         const resource = getResource<LinkResource>(props.uuid)(state.resources);
290         return resource || { linkClass: '' };
291     })(renderLinkClass);
292
293 const renderLinkTail = (dispatch: Dispatch, item: { uuid: string, tailUuid: string, tailKind: string }) => {
294     const currentLabel = resourceLabel(item.tailKind);
295     const isUnknow = currentLabel === "Unknown";
296     return (<div>
297         {!isUnknow ? (
298             renderLink(dispatch, item.tailUuid, currentLabel)
299         ) : (
300                 <Typography noWrap color="default">
301                     {item.tailUuid}
302                 </Typography>
303             )}
304     </div>);
305 };
306
307 const renderLink = (dispatch: Dispatch, uuid: string, label: string) =>
308     <Typography noWrap color="primary" style={{ 'cursor': 'pointer' }} onClick={() => dispatch<any>(navigateTo(uuid))}>
309         {label}: {uuid}
310     </Typography>;
311
312 export const ResourceLinkTail = connect(
313     (state: RootState, props: { uuid: string }) => {
314         const resource = getResource<LinkResource>(props.uuid)(state.resources);
315         return {
316             item: resource || { uuid: '', tailUuid: '', tailKind: ResourceKind.NONE }
317         };
318     })((props: { item: any } & DispatchProp<any>) =>
319         renderLinkTail(props.dispatch, props.item));
320
321 const renderLinkHead = (dispatch: Dispatch, item: { uuid: string, headUuid: string, headKind: ResourceKind }) =>
322     renderLink(dispatch, item.headUuid, resourceLabel(item.headKind));
323
324 export const ResourceLinkHead = connect(
325     (state: RootState, props: { uuid: string }) => {
326         const resource = getResource<LinkResource>(props.uuid)(state.resources);
327         return {
328             item: resource || { uuid: '', headUuid: '', headKind: ResourceKind.NONE }
329         };
330     })((props: { item: any } & DispatchProp<any>) =>
331         renderLinkHead(props.dispatch, props.item));
332
333 export const ResourceLinkUuid = connect(
334     (state: RootState, props: { uuid: string }) => {
335         const resource = getResource<LinkResource>(props.uuid)(state.resources);
336         return resource || { uuid: '' };
337     })(renderUuid);
338
339 // Process Resources
340 const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
341     return (
342         <div>
343             {uuid &&
344                 <Tooltip title="Run process">
345                     <IconButton onClick={() => dispatch<any>(openRunProcess(uuid))}>
346                         <ProcessIcon />
347                     </IconButton>
348                 </Tooltip>}
349         </div>
350     );
351 };
352
353 export const ResourceRunProcess = connect(
354     (state: RootState, props: { uuid: string }) => {
355         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
356         return {
357             uuid: resource ? resource.uuid : ''
358         };
359     })((props: { uuid: string } & DispatchProp<any>) =>
360         resourceRunProcess(props.dispatch, props.uuid));
361
362 const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
363     if (ownerUuid === getPublicUuid(uuidPrefix)) {
364         return renderStatus(WorkflowStatus.PUBLIC);
365     } else {
366         return renderStatus(WorkflowStatus.PRIVATE);
367     }
368 };
369
370 const renderStatus = (status: string) =>
371     <Typography noWrap style={{ width: '60px' }}>{status}</Typography>;
372
373 export const ResourceWorkflowStatus = connect(
374     (state: RootState, props: { uuid: string }) => {
375         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
376         const uuidPrefix = getUuidPrefix(state);
377         return {
378             ownerUuid: resource ? resource.ownerUuid : '',
379             uuidPrefix
380         };
381     })((props: { ownerUuid?: string, uuidPrefix: string }) => renderWorkflowStatus(props.uuidPrefix, props.ownerUuid));
382
383 export const ResourceLastModifiedDate = connect(
384     (state: RootState, props: { uuid: string }) => {
385         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
386         return { date: resource ? resource.modifiedAt : '' };
387     })((props: { date: string }) => renderDate(props.date));
388
389 export const ResourceCreatedAtDate = connect(
390     (state: RootState, props: { uuid: string }) => {
391         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
392         return { date: resource ? resource.createdAt : '' };
393     })((props: { date: string }) => renderDate(props.date));
394
395 export const ResourceTrashDate = connect(
396     (state: RootState, props: { uuid: string }) => {
397         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
398         return { date: resource ? resource.trashAt : '' };
399     })((props: { date: string }) => renderDate(props.date));
400
401 export const ResourceDeleteDate = connect(
402     (state: RootState, props: { uuid: string }) => {
403         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
404         return { date: resource ? resource.deleteAt : '' };
405     })((props: { date: string }) => renderDate(props.date));
406
407 export const renderFileSize = (fileSize?: number) =>
408     <Typography noWrap style={{ minWidth: '45px' }}>
409         {formatFileSize(fileSize)}
410     </Typography>;
411
412 export const ResourceFileSize = connect(
413     (state: RootState, props: { uuid: string }) => {
414         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
415         return { fileSize: resource ? resource.fileSizeTotal : 0 };
416     })((props: { fileSize?: number }) => renderFileSize(props.fileSize));
417
418 const renderOwner = (owner: string) =>
419     <Typography noWrap>
420         {owner}
421     </Typography>;
422
423 export const ResourceOwner = connect(
424     (state: RootState, props: { uuid: string }) => {
425         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
426         return { owner: resource ? resource.ownerUuid : '' };
427     })((props: { owner: string }) => renderOwner(props.owner));
428
429 export const ResourceOwnerName = connect(
430     (state: RootState, props: { uuid: string }) => {
431         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
432         const ownerNameState = state.ownerName;
433         const ownerName = ownerNameState.find(it => it.uuid === resource!.ownerUuid);
434         return { owner: ownerName ? ownerName!.name : resource!.ownerUuid };
435     })((props: { owner: string }) => renderOwner(props.owner));
436
437 const renderType = (type: string) =>
438     <Typography noWrap>
439         {resourceLabel(type)}
440     </Typography>;
441
442 export const ResourceType = connect(
443     (state: RootState, props: { uuid: string }) => {
444         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
445         return { type: resource ? resource.kind : '' };
446     })((props: { type: string }) => renderType(props.type));
447
448 export const ResourceStatus = connect((state: RootState, props: { uuid: string }) => {
449         return { resource: getResource<GroupContentsResource>(props.uuid)(state.resources) };
450     })((props: { resource: GroupContentsResource }) =>
451         (props.resource && props.resource.kind === ResourceKind.COLLECTION)
452         ? <CollectionStatus uuid={props.resource.uuid} />
453         : <ProcessStatus uuid={props.resource.uuid} />
454     );
455
456 export const CollectionStatus = connect((state: RootState, props: { uuid: string }) => {
457         return { collection: getResource<CollectionResource>(props.uuid)(state.resources) };
458     })((props: { collection: CollectionResource }) =>
459         (props.collection.uuid !== props.collection.currentVersionUuid)
460         ? <Typography>version {props.collection.version}</Typography>
461         : <Typography>head version</Typography>
462     );
463
464 export const ProcessStatus = compose(
465     connect((state: RootState, props: { uuid: string }) => {
466         return { process: getProcess(props.uuid)(state.resources) };
467     }),
468     withStyles({}, { withTheme: true }))
469     ((props: { process?: Process, theme: ArvadosTheme }) => {
470         const status = props.process ? getProcessStatus(props.process) : "-";
471         return <Typography
472             noWrap
473             style={{ color: getProcessStatusColor(status, props.theme) }} >
474             {status}
475         </Typography>;
476     });
477
478 export const ProcessStartDate = connect(
479     (state: RootState, props: { uuid: string }) => {
480         const process = getProcess(props.uuid)(state.resources);
481         return { date: ( process && process.container ) ? process.container.startedAt : '' };
482     })((props: { date: string }) => renderDate(props.date));
483
484 export const renderRunTime = (time: number) =>
485     <Typography noWrap style={{ minWidth: '45px' }}>
486         {formatTime(time, true)}
487     </Typography>;
488
489 interface ContainerRunTimeProps {
490     process: Process;
491 }
492
493 interface ContainerRunTimeState {
494     runtime: number;
495 }
496
497 export const ContainerRunTime = connect((state: RootState, props: { uuid: string }) => {
498     return { process: getProcess(props.uuid)(state.resources) };
499 })(class extends React.Component<ContainerRunTimeProps, ContainerRunTimeState> {
500     private timer: any;
501
502     constructor(props: ContainerRunTimeProps) {
503         super(props);
504         this.state = { runtime: this.getRuntime() };
505     }
506
507     getRuntime() {
508         return this.props.process ? getProcessRuntime(this.props.process) : 0;
509     }
510
511     updateRuntime() {
512         this.setState({ runtime: this.getRuntime() });
513     }
514
515     componentDidMount() {
516         this.timer = setInterval(this.updateRuntime.bind(this), 5000);
517     }
518
519     componentWillUnmount() {
520         clearInterval(this.timer);
521     }
522
523     render() {
524         return renderRunTime(this.state.runtime);
525     }
526 });