18123: Add test for resources shared with group.
[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 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 { Resource, ResourceKind, TrashableResource } from 'models/resource';
9 import { ProjectIcon, FilterGroupIcon, CollectionIcon, ProcessIcon, DefaultIcon, ShareIcon, CollectionOldVersionIcon, WorkflowIcon, RemoveIcon, RenameIcon } 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, filterResources } 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 { getUserFullname, getUserDisplayName, User, UserResource } from 'models/user';
24 import { toggleIsActive, toggleIsAdmin } from 'store/users/users-actions';
25 import { LinkClass, LinkResource } from 'models/link';
26 import { navigateTo, navigateToGroupDetails } 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 import { loadResource } from 'store/resources/resources-actions';
31 import { GroupClass, GroupResource } from 'models/group';
32 import { openRemoveGroupMemberDialog } from 'store/group-details-panel/group-details-panel-actions';
33 import { setMemberIsHidden } from 'store/group-details-panel/group-details-panel-actions';
34 import { formatPermissionLevel } from 'views-components/sharing-dialog/permission-select';
35 import { PermissionLevel } from 'models/permission';
36 import { openPermissionEditContextMenu } from 'store/context-menu/context-menu-actions';
37 import { getUserUuid } from 'common/getuser';
38
39 const renderName = (dispatch: Dispatch, item: GroupContentsResource) => {
40
41     const navFunc = ("groupClass" in item && item.groupClass === GroupClass.ROLE ? navigateToGroupDetails : navigateTo);
42     return <Grid container alignItems="center" wrap="nowrap" spacing={16}>
43         <Grid item>
44             {renderIcon(item)}
45         </Grid>
46         <Grid item>
47             <Typography color="primary" style={{ width: 'auto', cursor: 'pointer' }} onClick={() => dispatch<any>(navFunc(item.uuid))}>
48                 {item.kind === ResourceKind.PROJECT || item.kind === ResourceKind.COLLECTION
49                     ? <IllegalNamingWarning name={item.name} />
50                     : null}
51                 {item.name}
52             </Typography>
53         </Grid>
54         <Grid item>
55             <Typography variant="caption">
56                 <FavoriteStar resourceUuid={item.uuid} />
57                 <PublicFavoriteStar resourceUuid={item.uuid} />
58             </Typography>
59         </Grid>
60     </Grid>;
61 };
62
63 export const ResourceName = connect(
64     (state: RootState, props: { uuid: string }) => {
65         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
66         return resource;
67     })((resource: GroupContentsResource & DispatchProp<any>) => renderName(resource.dispatch, resource));
68
69 const renderIcon = (item: GroupContentsResource) => {
70     switch (item.kind) {
71         case ResourceKind.PROJECT:
72             if (item.groupClass === GroupClass.FILTER) {
73                 return <FilterGroupIcon />;
74             }
75             return <ProjectIcon />;
76         case ResourceKind.COLLECTION:
77             if (item.uuid === item.currentVersionUuid) {
78                 return <CollectionIcon />;
79             }
80             return <CollectionOldVersionIcon />;
81         case ResourceKind.PROCESS:
82             return <ProcessIcon />;
83         case ResourceKind.WORKFLOW:
84             return <WorkflowIcon />;
85         default:
86             return <DefaultIcon />;
87     }
88 };
89
90 const renderDate = (date?: string) => {
91     return <Typography noWrap style={{ minWidth: '100px' }}>{formatDate(date)}</Typography>;
92 };
93
94 const renderWorkflowName = (item: WorkflowResource) =>
95     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
96         <Grid item>
97             {renderIcon(item)}
98         </Grid>
99         <Grid item>
100             <Typography color="primary" style={{ width: '100px' }}>
101                 {item.name}
102             </Typography>
103         </Grid>
104     </Grid>;
105
106 export const ResourceWorkflowName = connect(
107     (state: RootState, props: { uuid: string }) => {
108         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
109         return resource;
110     })(renderWorkflowName);
111
112 const getPublicUuid = (uuidPrefix: string) => {
113     return `${uuidPrefix}-tpzed-anonymouspublic`;
114 };
115
116 const resourceShare = (dispatch: Dispatch, uuidPrefix: string, ownerUuid?: string, uuid?: string) => {
117     const isPublic = ownerUuid === getPublicUuid(uuidPrefix);
118     return (
119         <div>
120             {!isPublic && uuid &&
121                 <Tooltip title="Share">
122                     <IconButton onClick={() => dispatch<any>(openSharingDialog(uuid))}>
123                         <ShareIcon />
124                     </IconButton>
125                 </Tooltip>
126             }
127         </div>
128     );
129 };
130
131 export const ResourceShare = connect(
132     (state: RootState, props: { uuid: string }) => {
133         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
134         const uuidPrefix = getUuidPrefix(state);
135         return {
136             uuid: resource ? resource.uuid : '',
137             ownerUuid: resource ? resource.ownerUuid : '',
138             uuidPrefix
139         };
140     })((props: { ownerUuid?: string, uuidPrefix: string, uuid?: string } & DispatchProp<any>) =>
141         resourceShare(props.dispatch, props.uuidPrefix, props.ownerUuid, props.uuid));
142
143 // User Resources
144 const renderFirstName = (item: { firstName: string }) => {
145     return <Typography noWrap>{item.firstName}</Typography>;
146 };
147
148 export const ResourceFirstName = connect(
149     (state: RootState, props: { uuid: string }) => {
150         const resource = getResource<UserResource>(props.uuid)(state.resources);
151         return resource || { firstName: '' };
152     })(renderFirstName);
153
154 const renderLastName = (item: { lastName: string }) =>
155     <Typography noWrap>{item.lastName}</Typography>;
156
157 export const ResourceLastName = connect(
158     (state: RootState, props: { uuid: string }) => {
159         const resource = getResource<UserResource>(props.uuid)(state.resources);
160         return resource || { lastName: '' };
161     })(renderLastName);
162
163 const renderFullName = (item: { firstName: string, lastName: string }) =>
164     <Typography noWrap>{(item.firstName + " " + item.lastName).trim()}</Typography>;
165
166 export const ResourceFullName = connect(
167     (state: RootState, props: { uuid: string }) => {
168         const resource = getResource<UserResource>(props.uuid)(state.resources);
169         return resource || { firstName: '', lastName: '' };
170     })(renderFullName);
171
172
173 const renderUuid = (item: { uuid: string }) =>
174     <Typography data-cy="uuid" noWrap>{item.uuid}</Typography>;
175
176 export const ResourceUuid = connect(
177     (state: RootState, props: { uuid: string }) => {
178         const resource = getResource<UserResource>(props.uuid)(state.resources);
179         return resource || { uuid: '' };
180     })(renderUuid);
181
182 const renderEmail = (item: { email: string }) =>
183     <Typography noWrap>{item.email}</Typography>;
184
185 export const ResourceEmail = connect(
186     (state: RootState, props: { uuid: string }) => {
187         const resource = getResource<UserResource>(props.uuid)(state.resources);
188         return resource || { email: '' };
189     })(renderEmail);
190
191 const renderIsActive = (props: { uuid: string, kind: ResourceKind, isActive: boolean, toggleIsActive: (uuid: string) => void }) => {
192     if (props.kind === ResourceKind.USER) {
193         return <Checkbox
194             color="primary"
195             checked={props.isActive}
196             onClick={() => props.toggleIsActive(props.uuid)} />;
197     } else {
198         return <Typography />;
199     }
200 }
201
202 export const ResourceIsActive = connect(
203     (state: RootState, props: { uuid: string }) => {
204         const resource = getResource<UserResource>(props.uuid)(state.resources);
205         return resource || { isActive: false, kind: ResourceKind.NONE };
206     }, { toggleIsActive }
207 )(renderIsActive);
208
209 export const ResourceLinkTailIsActive = connect(
210     (state: RootState, props: { uuid: string }) => {
211         const link = getResource<LinkResource>(props.uuid)(state.resources);
212         const tailResource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
213
214         return tailResource || { isActive: false, kind: ResourceKind.NONE };
215     }, { toggleIsActive }
216 )(renderIsActive);
217
218 const renderIsHidden = (props: { memberLinkUuid: string, permissionLinkUuid: string, hidden: boolean, setMemberIsHidden: (memberLinkUuid: string, permissionLinkUuid: string, hide: boolean) => void }) => {
219     if (props.memberLinkUuid) {
220         return <Checkbox
221                 data-cy="user-hidden-checkbox"
222                 color="primary"
223                 checked={props.hidden}
224                 onClick={() => props.setMemberIsHidden(props.memberLinkUuid, props.permissionLinkUuid, !props.hidden)} />;
225     } else {
226         return <Typography />;
227     }
228 }
229
230 export const ResourceLinkTailIsHidden = connect(
231     (state: RootState, props: { uuid: string }) => {
232         const link = getResource<LinkResource>(props.uuid)(state.resources);
233         const member = getResource<Resource>(link?.tailUuid || '')(state.resources);
234         const group = getResource<GroupResource>(link?.headUuid || '')(state.resources);
235         const permissions = filterResources((resource: LinkResource) => {
236             return resource.linkClass === LinkClass.PERMISSION
237                 && resource.headUuid === link?.tailUuid
238                 && resource.tailUuid === group?.uuid
239                 && resource.name === PermissionLevel.CAN_READ;
240         })(state.resources);
241
242         const permissionLinkUuid = permissions.length > 0 ? permissions[0].uuid : '';
243         const isVisible = link && group && permissions.length > 0;
244
245         return member?.kind === ResourceKind.USER
246             ? { memberLinkUuid: link?.uuid, permissionLinkUuid, hidden: !isVisible }
247             : { memberLinkUuid: '', permissionLinkUuid: '', hidden: false};
248     }, { setMemberIsHidden }
249 )(renderIsHidden);
250
251 const renderIsAdmin = (props: { uuid: string, isAdmin: boolean, toggleIsAdmin: (uuid: string) => void }) =>
252     <Checkbox
253         color="primary"
254         checked={props.isAdmin}
255         onClick={() => props.toggleIsAdmin(props.uuid)} />;
256
257 export const ResourceIsAdmin = connect(
258     (state: RootState, props: { uuid: string }) => {
259         const resource = getResource<UserResource>(props.uuid)(state.resources);
260         return resource || { isAdmin: false };
261     }, { toggleIsAdmin }
262 )(renderIsAdmin);
263
264 const renderUsername = (item: { username: string }) =>
265     <Typography noWrap>{item.username}</Typography>;
266
267 export const ResourceUsername = connect(
268     (state: RootState, props: { uuid: string }) => {
269         const resource = getResource<UserResource>(props.uuid)(state.resources);
270         return resource || { username: '' };
271     })(renderUsername);
272
273 // Common methods
274 const renderCommonData = (data: string) =>
275     <Typography noWrap>{data}</Typography>;
276
277 const renderCommonDate = (date: string) =>
278     <Typography noWrap>{formatDate(date)}</Typography>;
279
280 export const CommonUuid = withResourceData('uuid', renderCommonData);
281
282 // Api Client Authorizations
283 export const TokenApiClientId = withResourceData('apiClientId', renderCommonData);
284
285 export const TokenApiToken = withResourceData('apiToken', renderCommonData);
286
287 export const TokenCreatedByIpAddress = withResourceData('createdByIpAddress', renderCommonDate);
288
289 export const TokenDefaultOwnerUuid = withResourceData('defaultOwnerUuid', renderCommonData);
290
291 export const TokenExpiresAt = withResourceData('expiresAt', renderCommonDate);
292
293 export const TokenLastUsedAt = withResourceData('lastUsedAt', renderCommonDate);
294
295 export const TokenLastUsedByIpAddress = withResourceData('lastUsedByIpAddress', renderCommonData);
296
297 export const TokenScopes = withResourceData('scopes', renderCommonData);
298
299 export const TokenUserId = withResourceData('userId', renderCommonData);
300
301 const clusterColors = [
302     ['#f44336', '#fff'],
303     ['#2196f3', '#fff'],
304     ['#009688', '#fff'],
305     ['#cddc39', '#fff'],
306     ['#ff9800', '#fff']
307 ];
308
309 export const ResourceCluster = (props: { uuid: string }) => {
310     const CLUSTER_ID_LENGTH = 5;
311     const pos = props.uuid.length > CLUSTER_ID_LENGTH ? props.uuid.indexOf('-') : 5;
312     const clusterId = pos >= CLUSTER_ID_LENGTH ? props.uuid.substr(0, pos) : '';
313     const ci = pos >= CLUSTER_ID_LENGTH ? (((((
314         (props.uuid.charCodeAt(0) * props.uuid.charCodeAt(1))
315         + props.uuid.charCodeAt(2))
316         * props.uuid.charCodeAt(3))
317         + props.uuid.charCodeAt(4))) % clusterColors.length) : 0;
318     return <span style={{
319         backgroundColor: clusterColors[ci][0],
320         color: clusterColors[ci][1],
321         padding: "2px 7px",
322         borderRadius: 3
323     }}>{clusterId}</span>;
324 };
325
326 // Links Resources
327 const renderLinkName = (item: { name: string }) =>
328     <Typography noWrap>{item.name || '(none)'}</Typography>;
329
330 export const ResourceLinkName = connect(
331     (state: RootState, props: { uuid: string }) => {
332         const resource = getResource<LinkResource>(props.uuid)(state.resources);
333         return resource || { name: '' };
334     })(renderLinkName);
335
336 const renderLinkClass = (item: { linkClass: string }) =>
337     <Typography noWrap>{item.linkClass}</Typography>;
338
339 export const ResourceLinkClass = connect(
340     (state: RootState, props: { uuid: string }) => {
341         const resource = getResource<LinkResource>(props.uuid)(state.resources);
342         return resource || { linkClass: '' };
343     })(renderLinkClass);
344
345 const getResourceDisplayName = (resource: Resource): string => {
346     if ((resource as UserResource).kind === ResourceKind.USER
347           && typeof (resource as UserResource).firstName !== 'undefined') {
348         // We can be sure the resource is UserResource
349         return getUserDisplayName(resource as UserResource);
350     } else {
351         return (resource as GroupContentsResource).name;
352     }
353 }
354
355 const renderResourceLink = (dispatch: Dispatch, item: Resource) => {
356     var displayName = getResourceDisplayName(item);
357
358     return <Typography noWrap color="primary" style={{ 'cursor': 'pointer' }} onClick={() => dispatch<any>(navigateTo(item.uuid))}>
359         {resourceLabel(item.kind)}: {displayName || item.uuid}
360     </Typography>;
361 };
362
363 export const ResourceLinkTail = connect(
364     (state: RootState, props: { uuid: string }) => {
365         const resource = getResource<LinkResource>(props.uuid)(state.resources);
366         const tailResource = getResource<Resource>(resource?.tailUuid || '')(state.resources);
367
368         return {
369             item: tailResource || { uuid: resource?.tailUuid || '', kind: resource?.tailKind || ResourceKind.NONE }
370         };
371     })((props: { item: Resource } & DispatchProp<any>) =>
372         renderResourceLink(props.dispatch, props.item));
373
374 export const ResourceLinkHead = connect(
375     (state: RootState, props: { uuid: string }) => {
376         const resource = getResource<LinkResource>(props.uuid)(state.resources);
377         const headResource = getResource<Resource>(resource?.headUuid || '')(state.resources);
378
379         return {
380             item: headResource || { uuid: resource?.headUuid || '', kind: resource?.headKind || ResourceKind.NONE }
381         };
382     })((props: { item: Resource } & DispatchProp<any>) =>
383         renderResourceLink(props.dispatch, props.item));
384
385 export const ResourceLinkUuid = connect(
386     (state: RootState, props: { uuid: string }) => {
387         const resource = getResource<LinkResource>(props.uuid)(state.resources);
388         return resource || { uuid: '' };
389     })(renderUuid);
390
391 export const ResourceLinkHeadUuid = connect(
392     (state: RootState, props: { uuid: string }) => {
393         const link = getResource<LinkResource>(props.uuid)(state.resources);
394         const headResource = getResource<Resource>(link?.headUuid || '')(state.resources);
395
396         return headResource || { uuid: '' };
397     })(renderUuid);
398
399 export const ResourceLinkTailUuid = connect(
400     (state: RootState, props: { uuid: string }) => {
401         const link = getResource<LinkResource>(props.uuid)(state.resources);
402         const tailResource = getResource<Resource>(link?.tailUuid || '')(state.resources);
403
404         return tailResource || { uuid: '' };
405     })(renderUuid);
406
407 const renderLinkDelete = (dispatch: Dispatch, item: LinkResource, canManage: boolean) => {
408     if (item.uuid) {
409         return canManage ?
410             <Typography noWrap>
411                 <IconButton data-cy="resource-delete-button" onClick={() => dispatch<any>(openRemoveGroupMemberDialog(item.uuid))}>
412                     <RemoveIcon />
413                 </IconButton>
414             </Typography> :
415             <Typography noWrap>
416                 <IconButton disabled data-cy="resource-delete-button">
417                     <RemoveIcon />
418                 </IconButton>
419             </Typography>;
420     } else {
421       return <Typography noWrap></Typography>;
422     }
423 }
424
425 export const ResourceLinkDelete = connect(
426     (state: RootState, props: { uuid: string }) => {
427         const link = getResource<LinkResource>(props.uuid)(state.resources);
428         return {
429             item: link || { uuid: '', kind: ResourceKind.NONE },
430             canManage: link && getResourceLinkCanManage(state, link),
431         };
432     })((props: { item: LinkResource, canManage: boolean } & DispatchProp<any>) =>
433       renderLinkDelete(props.dispatch, props.item, props.canManage));
434
435 export const ResourceLinkTailEmail = connect(
436     (state: RootState, props: { uuid: string }) => {
437         const link = getResource<LinkResource>(props.uuid)(state.resources);
438         const resource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
439
440         return resource || { email: '' };
441     })(renderEmail);
442
443 export const ResourceLinkTailUsername = connect(
444     (state: RootState, props: { uuid: string }) => {
445         const link = getResource<LinkResource>(props.uuid)(state.resources);
446         const resource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
447
448         return resource || { username: '' };
449     })(renderUsername);
450
451 const renderPermissionLevel = (dispatch: Dispatch, link: LinkResource, canManage: boolean) => {
452     return <Typography noWrap>
453         {formatPermissionLevel(link.name as PermissionLevel)}
454         {canManage ?
455             <IconButton onClick={(event) => dispatch<any>(openPermissionEditContextMenu(event, link))}>
456                 <RenameIcon />
457             </IconButton> :
458             ''
459         }
460     </Typography>;
461 }
462
463 export const ResourceLinkHeadPermissionLevel = connect(
464     (state: RootState, props: { uuid: string }) => {
465         const link = getResource<LinkResource>(props.uuid)(state.resources);
466
467         return {
468             link: link || { uuid: '', name: '', kind: ResourceKind.NONE },
469             canManage: link && getResourceLinkCanManage(state, link),
470         };
471     })((props: { link: LinkResource, canManage: boolean } & DispatchProp<any>) =>
472         renderPermissionLevel(props.dispatch, props.link, props.canManage));
473
474 export const ResourceLinkTailPermissionLevel = connect(
475     (state: RootState, props: { uuid: string }) => {
476         const link = getResource<LinkResource>(props.uuid)(state.resources);
477
478         return {
479             link: link || { uuid: '', name: '', kind: ResourceKind.NONE },
480             canManage: link && getResourceLinkCanManage(state, link),
481         };
482     })((props: { link: LinkResource, canManage: boolean } & DispatchProp<any>) =>
483         renderPermissionLevel(props.dispatch, props.link, props.canManage));
484
485 const getResourceLinkCanManage = (state: RootState, link: LinkResource) => {
486     const headResource = getResource<Resource>(link.headUuid)(state.resources);
487     // const tailResource = getResource<Resource>(link.tailUuid)(state.resources);
488     const userUuid = getUserUuid(state);
489
490     if (headResource && headResource.kind === ResourceKind.GROUP) {
491         return userUuid ? (headResource as GroupResource).writableBy?.includes(userUuid) : false;
492     } else {
493         // true for now
494         return true;
495     }
496 }
497
498 // Process Resources
499 const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
500     return (
501         <div>
502             {uuid &&
503                 <Tooltip title="Run process">
504                     <IconButton onClick={() => dispatch<any>(openRunProcess(uuid))}>
505                         <ProcessIcon />
506                     </IconButton>
507                 </Tooltip>}
508         </div>
509     );
510 };
511
512 export const ResourceRunProcess = connect(
513     (state: RootState, props: { uuid: string }) => {
514         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
515         return {
516             uuid: resource ? resource.uuid : ''
517         };
518     })((props: { uuid: string } & DispatchProp<any>) =>
519         resourceRunProcess(props.dispatch, props.uuid));
520
521 const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
522     if (ownerUuid === getPublicUuid(uuidPrefix)) {
523         return renderStatus(WorkflowStatus.PUBLIC);
524     } else {
525         return renderStatus(WorkflowStatus.PRIVATE);
526     }
527 };
528
529 const renderStatus = (status: string) =>
530     <Typography noWrap style={{ width: '60px' }}>{status}</Typography>;
531
532 export const ResourceWorkflowStatus = connect(
533     (state: RootState, props: { uuid: string }) => {
534         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
535         const uuidPrefix = getUuidPrefix(state);
536         return {
537             ownerUuid: resource ? resource.ownerUuid : '',
538             uuidPrefix
539         };
540     })((props: { ownerUuid?: string, uuidPrefix: string }) => renderWorkflowStatus(props.uuidPrefix, props.ownerUuid));
541
542 export const ResourceLastModifiedDate = connect(
543     (state: RootState, props: { uuid: string }) => {
544         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
545         return { date: resource ? resource.modifiedAt : '' };
546     })((props: { date: string }) => renderDate(props.date));
547
548 export const ResourceCreatedAtDate = connect(
549     (state: RootState, props: { uuid: string }) => {
550         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
551         return { date: resource ? resource.createdAt : '' };
552     })((props: { date: string }) => renderDate(props.date));
553
554 export const ResourceTrashDate = connect(
555     (state: RootState, props: { uuid: string }) => {
556         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
557         return { date: resource ? resource.trashAt : '' };
558     })((props: { date: string }) => renderDate(props.date));
559
560 export const ResourceDeleteDate = connect(
561     (state: RootState, props: { uuid: string }) => {
562         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
563         return { date: resource ? resource.deleteAt : '' };
564     })((props: { date: string }) => renderDate(props.date));
565
566 export const renderFileSize = (fileSize?: number) =>
567     <Typography noWrap style={{ minWidth: '45px' }}>
568         {formatFileSize(fileSize)}
569     </Typography>;
570
571 export const ResourceFileSize = connect(
572     (state: RootState, props: { uuid: string }) => {
573         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
574
575         if (resource && resource.kind !== ResourceKind.COLLECTION) {
576             return { fileSize: '' };
577         }
578
579         return { fileSize: resource ? resource.fileSizeTotal : 0 };
580     })((props: { fileSize?: number }) => renderFileSize(props.fileSize));
581
582 const renderOwner = (owner: string) =>
583     <Typography noWrap>
584         {owner}
585     </Typography>;
586
587 export const ResourceOwner = connect(
588     (state: RootState, props: { uuid: string }) => {
589         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
590         return { owner: resource ? resource.ownerUuid : '' };
591     })((props: { owner: string }) => renderOwner(props.owner));
592
593 export const ResourceOwnerName = connect(
594     (state: RootState, props: { uuid: string }) => {
595         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
596         const ownerNameState = state.ownerName;
597         const ownerName = ownerNameState.find(it => it.uuid === resource!.ownerUuid);
598         return { owner: ownerName ? ownerName!.name : resource!.ownerUuid };
599     })((props: { owner: string }) => renderOwner(props.owner));
600
601 const userFromID =
602     connect(
603         (state: RootState, props: { uuid: string }) => {
604             let userFullname = '';
605             const resource = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
606
607             if (resource) {
608                 userFullname = getUserFullname(resource as User) || (resource as GroupContentsResource).name;
609             }
610
611             return { uuid: props.uuid, userFullname };
612         });
613
614 export const ResourceOwnerWithName =
615     compose(
616         userFromID,
617         withStyles({}, { withTheme: true }))
618         ((props: { uuid: string, userFullname: string, dispatch: Dispatch, theme: ArvadosTheme }) => {
619             const { uuid, userFullname, dispatch, theme } = props;
620
621             if (userFullname === '') {
622                 dispatch<any>(loadResource(uuid, false));
623                 return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
624                     {uuid}
625                 </Typography>;
626             }
627
628             return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
629                 {userFullname} ({uuid})
630             </Typography>;
631         });
632
633 export const UserNameFromID =
634     compose(userFromID)(
635         (props: { uuid: string, userFullname: string, dispatch: Dispatch }) => {
636             const { uuid, userFullname, dispatch } = props;
637
638             if (userFullname === '') {
639                 dispatch<any>(loadResource(uuid, false));
640             }
641             return <span>
642                 {userFullname ? userFullname : uuid}
643             </span>;
644         });
645
646 export const ResponsiblePerson =
647     compose(
648         connect(
649             (state: RootState, props: { uuid: string, parentRef: HTMLElement | null }) => {
650                 let responsiblePersonName: string = '';
651                 let responsiblePersonUUID: string = '';
652                 let responsiblePersonProperty: string = '';
653
654                 if (state.auth.config.clusterConfig.Collections.ManagedProperties) {
655                     let index = 0;
656                     const keys = Object.keys(state.auth.config.clusterConfig.Collections.ManagedProperties);
657
658                     while (!responsiblePersonProperty && keys[index]) {
659                         const key = keys[index];
660                         if (state.auth.config.clusterConfig.Collections.ManagedProperties[key].Function === 'original_owner') {
661                             responsiblePersonProperty = key;
662                         }
663                         index++;
664                     }
665                 }
666
667                 let resource: Resource | undefined = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
668
669                 while (resource && resource.kind !== ResourceKind.USER && responsiblePersonProperty) {
670                     responsiblePersonUUID = (resource as CollectionResource).properties[responsiblePersonProperty];
671                     resource = getResource<GroupContentsResource & UserResource>(responsiblePersonUUID)(state.resources);
672                 }
673
674                 if (resource && resource.kind === ResourceKind.USER) {
675                     responsiblePersonName = getUserFullname(resource as UserResource) || (resource as GroupContentsResource).name;
676                 }
677
678                 return { uuid: responsiblePersonUUID, responsiblePersonName, parentRef: props.parentRef };
679             }),
680         withStyles({}, { withTheme: true }))
681         ((props: { uuid: string | null, responsiblePersonName: string, parentRef: HTMLElement | null, theme: ArvadosTheme }) => {
682             const { uuid, responsiblePersonName, parentRef, theme } = props;
683
684             if (!uuid && parentRef) {
685                 parentRef.style.display = 'none';
686                 return null;
687             } else if (parentRef) {
688                 parentRef.style.display = 'block';
689             }
690
691             if (!responsiblePersonName) {
692                 return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
693                     {uuid}
694                 </Typography>;
695             }
696
697             return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
698                 {responsiblePersonName} ({uuid})
699                 </Typography>;
700         });
701
702 const renderType = (type: string, subtype: string) =>
703     <Typography noWrap>
704         {resourceLabel(type, subtype)}
705     </Typography>;
706
707 export const ResourceType = connect(
708     (state: RootState, props: { uuid: string }) => {
709         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
710         return { type: resource ? resource.kind : '', subtype: resource && resource.kind === ResourceKind.GROUP ? resource.groupClass : '' };
711     })((props: { type: string, subtype: string }) => renderType(props.type, props.subtype));
712
713 export const ResourceStatus = connect((state: RootState, props: { uuid: string }) => {
714     return { resource: getResource<GroupContentsResource>(props.uuid)(state.resources) };
715 })((props: { resource: GroupContentsResource }) =>
716     (props.resource && props.resource.kind === ResourceKind.COLLECTION)
717         ? <CollectionStatus uuid={props.resource.uuid} />
718         : <ProcessStatus uuid={props.resource.uuid} />
719 );
720
721 export const CollectionStatus = connect((state: RootState, props: { uuid: string }) => {
722     return { collection: getResource<CollectionResource>(props.uuid)(state.resources) };
723 })((props: { collection: CollectionResource }) =>
724     (props.collection.uuid !== props.collection.currentVersionUuid)
725         ? <Typography>version {props.collection.version}</Typography>
726         : <Typography>head version</Typography>
727 );
728
729 export const ProcessStatus = compose(
730     connect((state: RootState, props: { uuid: string }) => {
731         return { process: getProcess(props.uuid)(state.resources) };
732     }),
733     withStyles({}, { withTheme: true }))
734     ((props: { process?: Process, theme: ArvadosTheme }) => {
735         const status = props.process ? getProcessStatus(props.process) : "-";
736         return <Typography
737             noWrap
738             style={{ color: getProcessStatusColor(status, props.theme) }} >
739             {status}
740         </Typography>;
741     });
742
743 export const ProcessStartDate = connect(
744     (state: RootState, props: { uuid: string }) => {
745         const process = getProcess(props.uuid)(state.resources);
746         return { date: (process && process.container) ? process.container.startedAt : '' };
747     })((props: { date: string }) => renderDate(props.date));
748
749 export const renderRunTime = (time: number) =>
750     <Typography noWrap style={{ minWidth: '45px' }}>
751         {formatTime(time, true)}
752     </Typography>;
753
754 interface ContainerRunTimeProps {
755     process: Process;
756 }
757
758 interface ContainerRunTimeState {
759     runtime: number;
760 }
761
762 export const ContainerRunTime = connect((state: RootState, props: { uuid: string }) => {
763     return { process: getProcess(props.uuid)(state.resources) };
764 })(class extends React.Component<ContainerRunTimeProps, ContainerRunTimeState> {
765     private timer: any;
766
767     constructor(props: ContainerRunTimeProps) {
768         super(props);
769         this.state = { runtime: this.getRuntime() };
770     }
771
772     getRuntime() {
773         return this.props.process ? getProcessRuntime(this.props.process) : 0;
774     }
775
776     updateRuntime() {
777         this.setState({ runtime: this.getRuntime() });
778     }
779
780     componentDidMount() {
781         this.timer = setInterval(this.updateRuntime.bind(this), 5000);
782     }
783
784     componentWillUnmount() {
785         clearInterval(this.timer);
786     }
787
788     render() {
789         return renderRunTime(this.state.runtime);
790     }
791 });