Merge branch '17914-peer-federation-login-fix'. Closes #17914
[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, isBuiltinGroup } 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, disabled?: boolean }) => {
192     if (props.kind === ResourceKind.USER) {
193         return <Checkbox
194             color="primary"
195             checked={props.isActive}
196             disabled={!!props.disabled}
197             onClick={() => props.toggleIsActive(props.uuid)} />;
198     } else {
199         return <Typography />;
200     }
201 }
202
203 export const ResourceIsActive = connect(
204     (state: RootState, props: { uuid: string, disabled?: boolean }) => {
205         const resource = getResource<UserResource>(props.uuid)(state.resources);
206         return resource ? {...resource, disabled: !!props.disabled} : { isActive: false, kind: ResourceKind.NONE };
207     }, { toggleIsActive }
208 )(renderIsActive);
209
210 export const ResourceLinkTailIsActive = connect(
211     (state: RootState, props: { uuid: string, disabled?: boolean }) => {
212         const link = getResource<LinkResource>(props.uuid)(state.resources);
213         const tailResource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
214
215         return tailResource ? {...tailResource, disabled: !!props.disabled} : { isActive: false, kind: ResourceKind.NONE };
216     }, { toggleIsActive }
217 )(renderIsActive);
218
219 const renderIsHidden = (props: {
220                             memberLinkUuid: string,
221                             permissionLinkUuid: string,
222                             visible: boolean,
223                             canManage: boolean,
224                             setMemberIsHidden: (memberLinkUuid: string, permissionLinkUuid: string, hide: boolean) => void
225                         }) => {
226     if (props.memberLinkUuid) {
227         return <Checkbox
228                 data-cy="user-visible-checkbox"
229                 color="primary"
230                 checked={props.visible}
231                 disabled={!props.canManage}
232                 onClick={() => props.setMemberIsHidden(props.memberLinkUuid, props.permissionLinkUuid, !props.visible)} />;
233     } else {
234         return <Typography />;
235     }
236 }
237
238 export const ResourceLinkTailIsVisible = connect(
239     (state: RootState, props: { uuid: string }) => {
240         const link = getResource<LinkResource>(props.uuid)(state.resources);
241         const member = getResource<Resource>(link?.tailUuid || '')(state.resources);
242         const group = getResource<GroupResource>(link?.headUuid || '')(state.resources);
243         const permissions = filterResources((resource: LinkResource) => {
244             return resource.linkClass === LinkClass.PERMISSION
245                 && resource.headUuid === link?.tailUuid
246                 && resource.tailUuid === group?.uuid
247                 && resource.name === PermissionLevel.CAN_READ;
248         })(state.resources);
249
250         const permissionLinkUuid = permissions.length > 0 ? permissions[0].uuid : '';
251         const isVisible = link && group && permissions.length > 0;
252         // Consider whether the current user canManage this resurce in addition when it's possible
253         const isBuiltin = isBuiltinGroup(link?.headUuid || '');
254
255         return member?.kind === ResourceKind.USER
256             ? { memberLinkUuid: link?.uuid, permissionLinkUuid, visible: isVisible, canManage: !isBuiltin }
257             : { memberLinkUuid: '', permissionLinkUuid: '', visible: false, canManage: false };
258     }, { setMemberIsHidden }
259 )(renderIsHidden);
260
261 const renderIsAdmin = (props: { uuid: string, isAdmin: boolean, toggleIsAdmin: (uuid: string) => void }) =>
262     <Checkbox
263         color="primary"
264         checked={props.isAdmin}
265         onClick={() => props.toggleIsAdmin(props.uuid)} />;
266
267 export const ResourceIsAdmin = connect(
268     (state: RootState, props: { uuid: string }) => {
269         const resource = getResource<UserResource>(props.uuid)(state.resources);
270         return resource || { isAdmin: false };
271     }, { toggleIsAdmin }
272 )(renderIsAdmin);
273
274 const renderUsername = (item: { username: string }) =>
275     <Typography noWrap>{item.username}</Typography>;
276
277 export const ResourceUsername = connect(
278     (state: RootState, props: { uuid: string }) => {
279         const resource = getResource<UserResource>(props.uuid)(state.resources);
280         return resource || { username: '' };
281     })(renderUsername);
282
283 // Common methods
284 const renderCommonData = (data: string) =>
285     <Typography noWrap>{data}</Typography>;
286
287 const renderCommonDate = (date: string) =>
288     <Typography noWrap>{formatDate(date)}</Typography>;
289
290 export const CommonUuid = withResourceData('uuid', renderCommonData);
291
292 // Api Client Authorizations
293 export const TokenApiClientId = withResourceData('apiClientId', renderCommonData);
294
295 export const TokenApiToken = withResourceData('apiToken', renderCommonData);
296
297 export const TokenCreatedByIpAddress = withResourceData('createdByIpAddress', renderCommonDate);
298
299 export const TokenDefaultOwnerUuid = withResourceData('defaultOwnerUuid', renderCommonData);
300
301 export const TokenExpiresAt = withResourceData('expiresAt', renderCommonDate);
302
303 export const TokenLastUsedAt = withResourceData('lastUsedAt', renderCommonDate);
304
305 export const TokenLastUsedByIpAddress = withResourceData('lastUsedByIpAddress', renderCommonData);
306
307 export const TokenScopes = withResourceData('scopes', renderCommonData);
308
309 export const TokenUserId = withResourceData('userId', renderCommonData);
310
311 const clusterColors = [
312     ['#f44336', '#fff'],
313     ['#2196f3', '#fff'],
314     ['#009688', '#fff'],
315     ['#cddc39', '#fff'],
316     ['#ff9800', '#fff']
317 ];
318
319 export const ResourceCluster = (props: { uuid: string }) => {
320     const CLUSTER_ID_LENGTH = 5;
321     const pos = props.uuid.length > CLUSTER_ID_LENGTH ? props.uuid.indexOf('-') : 5;
322     const clusterId = pos >= CLUSTER_ID_LENGTH ? props.uuid.substring(0, pos) : '';
323     const ci = pos >= CLUSTER_ID_LENGTH ? (((((
324         (props.uuid.charCodeAt(0) * props.uuid.charCodeAt(1))
325         + props.uuid.charCodeAt(2))
326         * props.uuid.charCodeAt(3))
327         + props.uuid.charCodeAt(4))) % clusterColors.length) : 0;
328     return <span style={{
329         backgroundColor: clusterColors[ci][0],
330         color: clusterColors[ci][1],
331         padding: "2px 7px",
332         borderRadius: 3
333     }}>{clusterId}</span>;
334 };
335
336 // Links Resources
337 const renderLinkName = (item: { name: string }) =>
338     <Typography noWrap>{item.name || '(none)'}</Typography>;
339
340 export const ResourceLinkName = connect(
341     (state: RootState, props: { uuid: string }) => {
342         const resource = getResource<LinkResource>(props.uuid)(state.resources);
343         return resource || { name: '' };
344     })(renderLinkName);
345
346 const renderLinkClass = (item: { linkClass: string }) =>
347     <Typography noWrap>{item.linkClass}</Typography>;
348
349 export const ResourceLinkClass = connect(
350     (state: RootState, props: { uuid: string }) => {
351         const resource = getResource<LinkResource>(props.uuid)(state.resources);
352         return resource || { linkClass: '' };
353     })(renderLinkClass);
354
355 const getResourceDisplayName = (resource: Resource): string => {
356     if ((resource as UserResource).kind === ResourceKind.USER
357           && typeof (resource as UserResource).firstName !== 'undefined') {
358         // We can be sure the resource is UserResource
359         return getUserDisplayName(resource as UserResource);
360     } else {
361         return (resource as GroupContentsResource).name;
362     }
363 }
364
365 const renderResourceLink = (dispatch: Dispatch, item: Resource) => {
366     var displayName = getResourceDisplayName(item);
367
368     return <Typography noWrap color="primary" style={{ 'cursor': 'pointer' }} onClick={() => dispatch<any>(navigateTo(item.uuid))}>
369         {resourceLabel(item.kind, item && item.kind === ResourceKind.GROUP ? (item as GroupResource).groupClass || '' : '')}: {displayName || item.uuid}
370     </Typography>;
371 };
372
373 export const ResourceLinkTail = connect(
374     (state: RootState, props: { uuid: string }) => {
375         const resource = getResource<LinkResource>(props.uuid)(state.resources);
376         const tailResource = getResource<Resource>(resource?.tailUuid || '')(state.resources);
377
378         return {
379             item: tailResource || { uuid: resource?.tailUuid || '', kind: resource?.tailKind || ResourceKind.NONE }
380         };
381     })((props: { item: Resource } & DispatchProp<any>) =>
382         renderResourceLink(props.dispatch, props.item));
383
384 export const ResourceLinkHead = connect(
385     (state: RootState, props: { uuid: string }) => {
386         const resource = getResource<LinkResource>(props.uuid)(state.resources);
387         const headResource = getResource<Resource>(resource?.headUuid || '')(state.resources);
388
389         return {
390             item: headResource || { uuid: resource?.headUuid || '', kind: resource?.headKind || ResourceKind.NONE }
391         };
392     })((props: { item: Resource } & DispatchProp<any>) =>
393         renderResourceLink(props.dispatch, props.item));
394
395 export const ResourceLinkUuid = connect(
396     (state: RootState, props: { uuid: string }) => {
397         const resource = getResource<LinkResource>(props.uuid)(state.resources);
398         return resource || { uuid: '' };
399     })(renderUuid);
400
401 export const ResourceLinkHeadUuid = connect(
402     (state: RootState, props: { uuid: string }) => {
403         const link = getResource<LinkResource>(props.uuid)(state.resources);
404         const headResource = getResource<Resource>(link?.headUuid || '')(state.resources);
405
406         return headResource || { uuid: '' };
407     })(renderUuid);
408
409 export const ResourceLinkTailUuid = connect(
410     (state: RootState, props: { uuid: string }) => {
411         const link = getResource<LinkResource>(props.uuid)(state.resources);
412         const tailResource = getResource<Resource>(link?.tailUuid || '')(state.resources);
413
414         return tailResource || { uuid: '' };
415     })(renderUuid);
416
417 const renderLinkDelete = (dispatch: Dispatch, item: LinkResource, canManage: boolean) => {
418     if (item.uuid) {
419         return canManage ?
420             <Typography noWrap>
421                 <IconButton data-cy="resource-delete-button" onClick={() => dispatch<any>(openRemoveGroupMemberDialog(item.uuid))}>
422                     <RemoveIcon />
423                 </IconButton>
424             </Typography> :
425             <Typography noWrap>
426                 <IconButton disabled data-cy="resource-delete-button">
427                     <RemoveIcon />
428                 </IconButton>
429             </Typography>;
430     } else {
431       return <Typography noWrap></Typography>;
432     }
433 }
434
435 export const ResourceLinkDelete = connect(
436     (state: RootState, props: { uuid: string }) => {
437         const link = getResource<LinkResource>(props.uuid)(state.resources);
438         const isBuiltin = isBuiltinGroup(link?.headUuid || '') || isBuiltinGroup(link?.tailUuid || '');
439
440         return {
441             item: link || { uuid: '', kind: ResourceKind.NONE },
442             canManage: link && getResourceLinkCanManage(state, link) && !isBuiltin,
443         };
444     })((props: { item: LinkResource, canManage: boolean } & DispatchProp<any>) =>
445       renderLinkDelete(props.dispatch, props.item, props.canManage));
446
447 export const ResourceLinkTailEmail = connect(
448     (state: RootState, props: { uuid: string }) => {
449         const link = getResource<LinkResource>(props.uuid)(state.resources);
450         const resource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
451
452         return resource || { email: '' };
453     })(renderEmail);
454
455 export const ResourceLinkTailUsername = connect(
456     (state: RootState, props: { uuid: string }) => {
457         const link = getResource<LinkResource>(props.uuid)(state.resources);
458         const resource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
459
460         return resource || { username: '' };
461     })(renderUsername);
462
463 const renderPermissionLevel = (dispatch: Dispatch, link: LinkResource, canManage: boolean) => {
464     return <Typography noWrap>
465         {formatPermissionLevel(link.name as PermissionLevel)}
466         {canManage ?
467             <IconButton data-cy="edit-permission-button" onClick={(event) => dispatch<any>(openPermissionEditContextMenu(event, link))}>
468                 <RenameIcon />
469             </IconButton> :
470             ''
471         }
472     </Typography>;
473 }
474
475 export const ResourceLinkHeadPermissionLevel = connect(
476     (state: RootState, props: { uuid: string }) => {
477         const link = getResource<LinkResource>(props.uuid)(state.resources);
478         const isBuiltin = isBuiltinGroup(link?.headUuid || '') || isBuiltinGroup(link?.tailUuid || '');
479
480         return {
481             link: link || { uuid: '', name: '', kind: ResourceKind.NONE },
482             canManage: link && getResourceLinkCanManage(state, link) && !isBuiltin,
483         };
484     })((props: { link: LinkResource, canManage: boolean } & DispatchProp<any>) =>
485         renderPermissionLevel(props.dispatch, props.link, props.canManage));
486
487 export const ResourceLinkTailPermissionLevel = connect(
488     (state: RootState, props: { uuid: string }) => {
489         const link = getResource<LinkResource>(props.uuid)(state.resources);
490         const isBuiltin = isBuiltinGroup(link?.headUuid || '') || isBuiltinGroup(link?.tailUuid || '');
491
492         return {
493             link: link || { uuid: '', name: '', kind: ResourceKind.NONE },
494             canManage: link && getResourceLinkCanManage(state, link) && !isBuiltin,
495         };
496     })((props: { link: LinkResource, canManage: boolean } & DispatchProp<any>) =>
497         renderPermissionLevel(props.dispatch, props.link, props.canManage));
498
499 const getResourceLinkCanManage = (state: RootState, link: LinkResource) => {
500     const headResource = getResource<Resource>(link.headUuid)(state.resources);
501     // const tailResource = getResource<Resource>(link.tailUuid)(state.resources);
502     const userUuid = getUserUuid(state);
503
504     if (headResource && headResource.kind === ResourceKind.GROUP) {
505         return userUuid ? (headResource as GroupResource).writableBy?.includes(userUuid) : false;
506     } else {
507         // true for now
508         return true;
509     }
510 }
511
512 // Process Resources
513 const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
514     return (
515         <div>
516             {uuid &&
517                 <Tooltip title="Run process">
518                     <IconButton onClick={() => dispatch<any>(openRunProcess(uuid))}>
519                         <ProcessIcon />
520                     </IconButton>
521                 </Tooltip>}
522         </div>
523     );
524 };
525
526 export const ResourceRunProcess = connect(
527     (state: RootState, props: { uuid: string }) => {
528         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
529         return {
530             uuid: resource ? resource.uuid : ''
531         };
532     })((props: { uuid: string } & DispatchProp<any>) =>
533         resourceRunProcess(props.dispatch, props.uuid));
534
535 const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
536     if (ownerUuid === getPublicUuid(uuidPrefix)) {
537         return renderStatus(WorkflowStatus.PUBLIC);
538     } else {
539         return renderStatus(WorkflowStatus.PRIVATE);
540     }
541 };
542
543 const renderStatus = (status: string) =>
544     <Typography noWrap style={{ width: '60px' }}>{status}</Typography>;
545
546 export const ResourceWorkflowStatus = connect(
547     (state: RootState, props: { uuid: string }) => {
548         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
549         const uuidPrefix = getUuidPrefix(state);
550         return {
551             ownerUuid: resource ? resource.ownerUuid : '',
552             uuidPrefix
553         };
554     })((props: { ownerUuid?: string, uuidPrefix: string }) => renderWorkflowStatus(props.uuidPrefix, props.ownerUuid));
555
556 export const ResourceLastModifiedDate = connect(
557     (state: RootState, props: { uuid: string }) => {
558         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
559         return { date: resource ? resource.modifiedAt : '' };
560     })((props: { date: string }) => renderDate(props.date));
561
562 export const ResourceCreatedAtDate = connect(
563     (state: RootState, props: { uuid: string }) => {
564         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
565         return { date: resource ? resource.createdAt : '' };
566     })((props: { date: string }) => renderDate(props.date));
567
568 export const ResourceTrashDate = connect(
569     (state: RootState, props: { uuid: string }) => {
570         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
571         return { date: resource ? resource.trashAt : '' };
572     })((props: { date: string }) => renderDate(props.date));
573
574 export const ResourceDeleteDate = connect(
575     (state: RootState, props: { uuid: string }) => {
576         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
577         return { date: resource ? resource.deleteAt : '' };
578     })((props: { date: string }) => renderDate(props.date));
579
580 export const renderFileSize = (fileSize?: number) =>
581     <Typography noWrap style={{ minWidth: '45px' }}>
582         {formatFileSize(fileSize)}
583     </Typography>;
584
585 export const ResourceFileSize = connect(
586     (state: RootState, props: { uuid: string }) => {
587         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
588
589         if (resource && resource.kind !== ResourceKind.COLLECTION) {
590             return { fileSize: '' };
591         }
592
593         return { fileSize: resource ? resource.fileSizeTotal : 0 };
594     })((props: { fileSize?: number }) => renderFileSize(props.fileSize));
595
596 const renderOwner = (owner: string) =>
597     <Typography noWrap>
598         {owner}
599     </Typography>;
600
601 export const ResourceOwner = connect(
602     (state: RootState, props: { uuid: string }) => {
603         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
604         return { owner: resource ? resource.ownerUuid : '' };
605     })((props: { owner: string }) => renderOwner(props.owner));
606
607 export const ResourceOwnerName = connect(
608     (state: RootState, props: { uuid: string }) => {
609         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
610         const ownerNameState = state.ownerName;
611         const ownerName = ownerNameState.find(it => it.uuid === resource!.ownerUuid);
612         return { owner: ownerName ? ownerName!.name : resource!.ownerUuid };
613     })((props: { owner: string }) => renderOwner(props.owner));
614
615 const userFromID =
616     connect(
617         (state: RootState, props: { uuid: string }) => {
618             let userFullname = '';
619             const resource = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
620
621             if (resource) {
622                 userFullname = getUserFullname(resource as User) || (resource as GroupContentsResource).name;
623             }
624
625             return { uuid: props.uuid, userFullname };
626         });
627
628 export const ResourceOwnerWithName =
629     compose(
630         userFromID,
631         withStyles({}, { withTheme: true }))
632         ((props: { uuid: string, userFullname: string, dispatch: Dispatch, theme: ArvadosTheme }) => {
633             const { uuid, userFullname, dispatch, theme } = props;
634
635             if (userFullname === '') {
636                 dispatch<any>(loadResource(uuid, false));
637                 return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
638                     {uuid}
639                 </Typography>;
640             }
641
642             return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
643                 {userFullname} ({uuid})
644             </Typography>;
645         });
646
647 export const UserNameFromID =
648     compose(userFromID)(
649         (props: { uuid: string, userFullname: string, dispatch: Dispatch }) => {
650             const { uuid, userFullname, dispatch } = props;
651
652             if (userFullname === '') {
653                 dispatch<any>(loadResource(uuid, false));
654             }
655             return <span>
656                 {userFullname ? userFullname : uuid}
657             </span>;
658         });
659
660 export const ResponsiblePerson =
661     compose(
662         connect(
663             (state: RootState, props: { uuid: string, parentRef: HTMLElement | null }) => {
664                 let responsiblePersonName: string = '';
665                 let responsiblePersonUUID: string = '';
666                 let responsiblePersonProperty: string = '';
667
668                 if (state.auth.config.clusterConfig.Collections.ManagedProperties) {
669                     let index = 0;
670                     const keys = Object.keys(state.auth.config.clusterConfig.Collections.ManagedProperties);
671
672                     while (!responsiblePersonProperty && keys[index]) {
673                         const key = keys[index];
674                         if (state.auth.config.clusterConfig.Collections.ManagedProperties[key].Function === 'original_owner') {
675                             responsiblePersonProperty = key;
676                         }
677                         index++;
678                     }
679                 }
680
681                 let resource: Resource | undefined = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
682
683                 while (resource && resource.kind !== ResourceKind.USER && responsiblePersonProperty) {
684                     responsiblePersonUUID = (resource as CollectionResource).properties[responsiblePersonProperty];
685                     resource = getResource<GroupContentsResource & UserResource>(responsiblePersonUUID)(state.resources);
686                 }
687
688                 if (resource && resource.kind === ResourceKind.USER) {
689                     responsiblePersonName = getUserFullname(resource as UserResource) || (resource as GroupContentsResource).name;
690                 }
691
692                 return { uuid: responsiblePersonUUID, responsiblePersonName, parentRef: props.parentRef };
693             }),
694         withStyles({}, { withTheme: true }))
695         ((props: { uuid: string | null, responsiblePersonName: string, parentRef: HTMLElement | null, theme: ArvadosTheme }) => {
696             const { uuid, responsiblePersonName, parentRef, theme } = props;
697
698             if (!uuid && parentRef) {
699                 parentRef.style.display = 'none';
700                 return null;
701             } else if (parentRef) {
702                 parentRef.style.display = 'block';
703             }
704
705             if (!responsiblePersonName) {
706                 return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
707                     {uuid}
708                 </Typography>;
709             }
710
711             return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
712                 {responsiblePersonName} ({uuid})
713                 </Typography>;
714         });
715
716 const renderType = (type: string, subtype: string) =>
717     <Typography noWrap>
718         {resourceLabel(type, subtype)}
719     </Typography>;
720
721 export const ResourceType = connect(
722     (state: RootState, props: { uuid: string }) => {
723         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
724         return { type: resource ? resource.kind : '', subtype: resource && resource.kind === ResourceKind.GROUP ? resource.groupClass : '' };
725     })((props: { type: string, subtype: string }) => renderType(props.type, props.subtype));
726
727 export const ResourceStatus = connect((state: RootState, props: { uuid: string }) => {
728     return { resource: getResource<GroupContentsResource>(props.uuid)(state.resources) };
729 })((props: { resource: GroupContentsResource }) =>
730     (props.resource && props.resource.kind === ResourceKind.COLLECTION)
731         ? <CollectionStatus uuid={props.resource.uuid} />
732         : <ProcessStatus uuid={props.resource.uuid} />
733 );
734
735 export const CollectionStatus = connect((state: RootState, props: { uuid: string }) => {
736     return { collection: getResource<CollectionResource>(props.uuid)(state.resources) };
737 })((props: { collection: CollectionResource }) =>
738     (props.collection.uuid !== props.collection.currentVersionUuid)
739         ? <Typography>version {props.collection.version}</Typography>
740         : <Typography>head version</Typography>
741 );
742
743 export const ProcessStatus = compose(
744     connect((state: RootState, props: { uuid: string }) => {
745         return { process: getProcess(props.uuid)(state.resources) };
746     }),
747     withStyles({}, { withTheme: true }))
748     ((props: { process?: Process, theme: ArvadosTheme }) => {
749         const status = props.process ? getProcessStatus(props.process) : "-";
750         return <Typography
751             noWrap
752             style={{ color: getProcessStatusColor(status, props.theme) }} >
753             {status}
754         </Typography>;
755     });
756
757 export const ProcessStartDate = connect(
758     (state: RootState, props: { uuid: string }) => {
759         const process = getProcess(props.uuid)(state.resources);
760         return { date: (process && process.container) ? process.container.startedAt : '' };
761     })((props: { date: string }) => renderDate(props.date));
762
763 export const renderRunTime = (time: number) =>
764     <Typography noWrap style={{ minWidth: '45px' }}>
765         {formatTime(time, true)}
766     </Typography>;
767
768 interface ContainerRunTimeProps {
769     process: Process;
770 }
771
772 interface ContainerRunTimeState {
773     runtime: number;
774 }
775
776 export const ContainerRunTime = connect((state: RootState, props: { uuid: string }) => {
777     return { process: getProcess(props.uuid)(state.resources) };
778 })(class extends React.Component<ContainerRunTimeProps, ContainerRunTimeState> {
779     private timer: any;
780
781     constructor(props: ContainerRunTimeProps) {
782         super(props);
783         this.state = { runtime: this.getRuntime() };
784     }
785
786     getRuntime() {
787         return this.props.process ? getProcessRuntime(this.props.process) : 0;
788     }
789
790     updateRuntime() {
791         this.setState({ runtime: this.getRuntime() });
792     }
793
794     componentDidMount() {
795         this.timer = setInterval(this.updateRuntime.bind(this), 5000);
796     }
797
798     componentWillUnmount() {
799         clearInterval(this.timer);
800     }
801
802     render() {
803         return renderRunTime(this.state.runtime);
804     }
805 });