-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathadmin-view-edit.component.ts
More file actions
778 lines (724 loc) · 21.4 KB
/
admin-view-edit.component.ts
File metadata and controls
778 lines (724 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
// Copyright 2023 Carnegie Mellon University. All Rights Reserved.
// Released under a MIT (SEI)-style license. See LICENSE.md in the project root for license information.
import {
Component,
OnInit,
EventEmitter,
Output,
NgZone,
ViewChild,
} from '@angular/core';
import { ErrorStateMatcher } from '@angular/material/core';
import { MatStepper } from '@angular/material/stepper';
import {
UntypedFormControl,
FormGroupDirective,
NgForm,
Validators,
} from '@angular/forms';
import {
View,
ViewStatus,
Team,
TeamService,
ViewService,
UserService,
FileService,
FileModel,
} from '../../../../generated/player-api';
import {
ApplicationTemplate,
ApplicationService,
Application,
} from '../../../../generated/player-api';
import { User } from '../../../../generated/player-api';
import { DialogService } from '../../../../services/dialog/dialog.service';
import { take } from 'rxjs/operators';
import { ViewApplicationsSelectComponent } from '../../view-applications-select/view-applications-select.component';
import { Clipboard } from '@angular/cdk/clipboard';
import { EditFileDialogComponent } from '../../../shared/edit-file-dialog/edit-file-dialog.component';
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { TeamPermissionsService } from '../../../../services/permissions/team-permissions.service';
import { TeamRolesService } from '../../../../services/roles/team-roles.service';
import { forkJoin } from 'rxjs';
/** Team node with related user and application information */
export class TeamUserApp {
constructor(
public name: string,
public team: Team,
public users: Array<User>,
) {}
}
@Component({
selector: 'app-admin-view-edit',
templateUrl: './admin-view-edit.component.html',
styleUrls: ['./admin-view-edit.component.scss'],
standalone: false,
})
export class AdminViewEditComponent implements OnInit {
@Output() editComplete = new EventEmitter<string>();
@ViewChild(ViewApplicationsSelectComponent)
viewApplicationsSelectComponent: ViewApplicationsSelectComponent;
@ViewChild(AdminViewEditComponent) child;
@ViewChild('stepper') stepper: MatStepper;
@ViewChild(EditFileDialogComponent)
editFileComponent: EditFileDialogComponent;
public viewNameFormControl = new UntypedFormControl('', [
Validators.required,
Validators.minLength(4),
]);
public teamNameFormControl = new UntypedFormControl('', [
Validators.required,
Validators.minLength(3),
]);
public descriptionFormControl = new UntypedFormControl('', [
Validators.required,
]);
public matcher = new UserErrorStateMatcher();
public viewStates = Object.values(ViewStatus);
public isLinear = false;
public view: View;
public teams: Array<TeamUserApp>;
public currentTeam: TeamUserApp;
public isLoadingTeams: boolean;
public applicationTemplates: Array<ApplicationTemplate>;
public BLANK_TEMPLATE = <ApplicationTemplate>{
name: 'New Application',
viewId: '',
};
public staged: PlayerFile[];
public teamsForFile: string[];
public selectAllTeamsForFile: boolean;
public uploadProgess: number;
public uploading: boolean;
public viewFiles: FileModel[];
public currentFile: FileModel;
public appNames: string[];
constructor(
public viewService: ViewService,
public teamService: TeamService,
public dialogService: DialogService,
public userService: UserService,
public fileService: FileService,
public applicationService: ApplicationService,
public zone: NgZone,
public clipboard: Clipboard,
public teamPermissionsService: TeamPermissionsService,
public teamRolesService: TeamRolesService,
) {}
/**
* Initialize component
*/
ngOnInit() {
this.isLoadingTeams = false;
this.view = undefined;
this.teams = new Array<TeamUserApp>();
this.staged = new Array<PlayerFile>();
this.teamsForFile = new Array<string>();
this.appNames = new Array<string>();
this.viewFiles = new Array<FileModel>();
forkJoin([
this.teamPermissionsService.load(),
this.teamRolesService.getRoles(),
]).subscribe();
}
/**
* Updates the list of available app templates
*/
updateApplicationTemplates() {
this.applicationService
.getApplicationTemplates()
.pipe(take(1))
.subscribe((templates) => {
this.applicationTemplates = templates;
});
}
/**
* Updates the contents of the current view
*/
updateViewTeams(): void {
if (this.view !== undefined && this.view.id !== undefined) {
// Update the teams arrays
this.isLoadingTeams = true;
this.teams = new Array<TeamUserApp>();
this.teamService
.getViewTeams(this.view.id)
.pipe(take(1))
.subscribe((tms) => {
tms.forEach((tm) => {
this.userService
.getTeamUsers(tm.id)
.pipe(take(1))
.subscribe((usrs) => {
this.teams.push(new TeamUserApp(tm.name, tm, usrs));
this.teams.sort((t1, t2) => {
if (t1.name === null || t2.name === null) {
return 0;
}
if (t1.name.toLowerCase() < t2.name.toLowerCase()) {
return -1;
}
if (t1.name.toLowerCase() > t2.name.toLowerCase()) {
return 1;
}
return 0;
});
if (this.teams.length === tms.length) {
this.isLoadingTeams = false;
}
});
});
});
}
}
/**
* Sets the contents of the current view
*/
setView(view: View): void {
if (view) {
this.view = view;
this.viewNameFormControl.setValue(view.name);
this.descriptionFormControl.setValue(view.description);
} else {
this.view = {};
this.viewNameFormControl.setValue('');
this.descriptionFormControl.setValue('');
}
}
/**
* Updates the contents of the current view
*/
updateView(): void {
if (this.view !== undefined && this.view.id !== undefined) {
this.viewApplicationsSelectComponent.view = this.view;
this.viewApplicationsSelectComponent.updateApplications();
this.viewApplicationsSelectComponent.currentApp = undefined;
}
}
/**
* Returns the stepper to zero index
*/
resetStepper() {
if (this.stepper) {
this.stepper.selectedIndex = 0;
this.view = undefined;
}
}
/**
* Closes the edit screen
*/
returnToViewSearch(): void {
this.currentTeam = undefined;
this.editComplete.emit(this.view.id);
}
addViewApplication(template: ApplicationTemplate) {
console.log(template);
let app = <Application>{};
if (template.id == null) {
app = <Application>{
name: template.name,
viewId: this.view.id,
};
} else {
app = <Application>{
viewId: this.view.id,
applicationTemplateId: template.id,
};
}
console.log(app);
this.applicationService
.createApplication(this.view.id, app)
.pipe(take(1))
.subscribe((rslt) => {
console.log('Application added');
this.viewApplicationsSelectComponent.updateApplications();
this.viewApplicationsSelectComponent.currentApp = rslt;
});
}
/**
* Delete an view after confirmation
*/
deleteView(): void {
this.dialogService
.confirm(
'Delete View',
'Are you sure that you want to delete view ' + this.view.name + '?',
)
.subscribe((result) => {
if (result['confirm']) {
this.viewService
.deleteView(this.view.id)
.pipe(take(1))
.subscribe(() => {
console.log('successfully deleted view');
this.returnToViewSearch();
});
}
});
}
/**
* Saves the current view
*/
saveView(): void {
if (
!this.viewNameFormControl.hasError('minlength') &&
!this.viewNameFormControl.hasError('required')
) {
if (this.view.name !== this.viewNameFormControl.value) {
this.view.name = this.viewNameFormControl.value;
this.viewService
.updateView(this.view.id, this.view)
.pipe(take(1))
.subscribe((updatedView) => {
this.view = updatedView;
});
}
}
if (!this.descriptionFormControl.hasError('required')) {
if (this.view.description !== this.descriptionFormControl.value) {
this.view.description = this.descriptionFormControl.value;
this.viewService
.updateView(this.view.id, this.view)
.pipe(take(1))
.subscribe((updatedView) => {
this.view = updatedView;
});
}
}
}
/**
* Updates the view status
*/
saveViewStatus(): void {
console.log(this.view.status);
this.viewService
.updateView(this.view.id, this.view)
.subscribe((updatedView) => {
this.view = updatedView;
});
}
setDefaultTeam(teamId: string) {
this.view.defaultTeamId = teamId;
this.viewService
.updateView(this.view.id, this.view)
.subscribe((updatedView) => {
this.view = updatedView;
});
}
/**
* Delete a team after confirmation
* @param tm The team to delete
*/
deleteTeam(tm: Team): void {
this.dialogService
.confirm(
'Delete View',
'Are you sure that you want to delete team ' + tm.name + '?',
)
.subscribe((result) => {
if (result['confirm']) {
this.teamService.deleteTeam(tm.id).subscribe(() => {
console.log('successfully deleted team');
this.updateViewTeams();
});
}
});
}
/**
* Saves the team name
* @param name New name of the team
* @param id team Guid
*/
saveTeamName(name: string, id: string): void {
this.teamService
.getTeam(id)
.pipe(take(1))
.subscribe((tm) => {
tm.name = name;
this.teamService.updateTeam(id, tm).subscribe((updatedTeam) => {
this.teams.find((t) => t.team.id === id).team = updatedTeam;
console.log('Team updated: ' + updatedTeam.name);
});
});
}
/**
* Opens the Add/Remove Users dialog for a specific team
* @param team The team to add/remove users to
*/
openUsersDialog(team: Team): void {
if (team !== undefined) {
this.dialogService
.addRemoveUsersToTeam(
'Add or Remove Users for team ' + team.name,
team,
{ maxWidth: '100vw', width: 'auto' },
)
.subscribe((result) => {
this.teams.find((t) => t.team.id === team.id).users =
result['teamUsers'];
});
}
}
/**
* Called when the mat-step index has changed to signal an update to the view
* @param event SelectionChange event
*/
onViewStepChange(event: any) {
// Index 3 is the files step. Grab the files already in the view.
if (event.selectedIndex === 3) {
this.staged = new Array<PlayerFile>();
this.getViewFiles();
this.getExistingApps();
this.updateViewTeams();
} else if (event.selectedIndex === 2) {
// index 2 is the Teams step. Refresh when selected to ensure latest information updated
this.currentTeam = undefined;
this.updateViewTeams();
} else if (event.selectedIndex === 1) {
// Clicked away from teams
this.updateApplicationTemplates();
this.viewApplicationsSelectComponent.updateApplications();
}
}
/**
* Adds a new Team to the view
*/
addNewTeam() {
this.teamService
.createTeam(this.view.id, { name: 'New Team' })
.pipe(take(1))
.subscribe((newTeam) => {
const team = new TeamUserApp('New Team', newTeam, new Array<User>());
this.teams.unshift(team);
this.currentTeam = team;
// This uses the rxjs take and ngZone to determine when the html is rendered
this.zone.onMicrotaskEmpty
.asObservable()
.pipe(take(1))
.subscribe(() => {
const nameElement = <HTMLInputElement>(
document.getElementById('teamName' + newTeam.id)
);
if (nameElement) {
nameElement.focus();
nameElement.select();
}
});
});
}
/**
* Selects the file(s) to be uploaded. Called when file selection is changed
*/
selectFile(files: FileList) {
const filesToUpload = Array.from(files);
this.uploading = false;
for (const fp of filesToUpload) {
this.staged.push(new PlayerFile(fp));
}
}
/**
* Uploads file(s) to specified team(s) in this view
*/
uploadFile() {
this.uploadProgess = 0;
this.uploading = true;
this.fileService
.uploadMultipleFiles(
this.view.id,
this.teamsForFile,
this.staged.map((f) => f.file),
'events',
true,
)
.subscribe((event) => {
if (event.type === HttpEventType.UploadProgress) {
this.uploadProgess = Math.round((100 * event.loaded) / event.total);
console.log(this.uploadProgess);
} else if (event instanceof HttpResponse) {
this.uploading = false;
if (event.status === 201) {
for (const elem of event.body) {
if (!this.viewFiles.some((f) => f.name === elem.name)) {
this.viewFiles.push(elem);
}
}
this.staged = new Array<PlayerFile>();
} else {
this.uploading = false;
console.log('Error uploading files: ' + event.status);
}
}
});
}
/**
* Removes a file from the list of file staged for upload
*
* @param file: The file to remove from the list
*/
removeFile(file: PlayerFile) {
console.log(file);
this.staged = this.staged.filter((f) => f.file.name !== file.file.name);
}
/**
* Toggles selection of all teams for file upload
*
* @param checked: Whether all teams should be selected
*/
toggleAllTeamsForFile(checked: boolean) {
if (checked) {
this.teamsForFile = this.teams.map(t => t.team.id);
} else {
this.teamsForFile = [];
}
}
/**
* Handles manual changes to team selection
* Unchecks "Select All" if not all teams are selected
*/
onTeamsForFileChange() {
const allTeamIds = this.teams.map(t => t.team.id);
const allSelected = allTeamIds.length === this.teamsForFile.length &&
allTeamIds.every(id => this.teamsForFile.includes(id));
this.selectAllTeamsForFile = allSelected;
}
/**
* Returns a link to the download endpoint for a particular file
*/
getDownloadLink(file: FileModel) {
this.clipboard.copy(this.getFileUri(file));
}
/**
* Get the files in this view that can be accessed by the user
*/
getViewFiles() {
this.fileService
.getViewFiles(this.view.id)
.pipe(take(1))
.subscribe(
(data) => {
for (const elem of data) {
if (!this.viewFiles.some((f) => f.name === elem.name)) {
this.viewFiles.push(elem);
}
}
},
(err) => {
console.log('Error getting files ' + err);
},
);
}
/**
* Trigger a download for a file. This will open the file in the broswer if it is an image or pdf
*
* @param id: The GUID of the file to download
* @param name: The name to use when triggering the download
*/
downloadFile(id: string, name: string) {
this.fileService
.download(id)
.pipe(take(1))
.subscribe({
next: (data) => {
const url = window.URL.createObjectURL(data);
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
if (!this.isImageOrPdf(name)) {
link.download = name;
}
link.click();
},
error: (err) => {
window.alert('Error downloading file');
console.log(err);
},
complete: () => {
console.log('Got a next value');
},
});
}
/**
* Delete the file with the specified id.
*
* @param id: The GUID of the file to delete
* @param name: The name of the file
*/
deleteFile(id: string, name: string) {
this.dialogService
.confirm('Delete File?', 'Are you sure you want to delete file ' + name)
.subscribe((result) => {
if (result['confirm']) {
this.fileService.deleteFile(id).subscribe((resp) => {
if (resp != null) {
window.alert('Error deleting file');
} else {
this.viewFiles = this.viewFiles.filter((f) => f.id !== id);
}
});
}
});
}
/**
* Rename or assign this file to different teams.
*
* @param id: The GUID of the file
* @param name: The current name of the file
*/
editFile(id: string, name: string, teams: string[]) {
this.dialogService
.editFile(id, this.view.id, name, teams)
.subscribe((val) => {
if (val !== undefined) {
const index = this.viewFiles.findIndex((f) => f.id === id);
this.viewFiles[index].name = val['name'];
}
});
}
/**
*
* @param file Creates a player application pointing to this file
*/
createApplication(file: FileModel) {
const payload: Application = {
name: file.name,
url: this.getFileUri(file),
embeddable: true,
loadInBackground: false,
viewId: this.view.id,
icon: '/assets/img/SP_Icon_Intel.png', // Default icon rather than no icon
};
this.applicationService
.createApplication(this.view.id, payload)
.pipe(take(1))
.subscribe(
(application) => {
this.appNames.push(application.name);
this.dialogService
.createApplication(application.id, file, this.view.name, this.teams)
.subscribe((val) => {
if (val !== undefined) {
console.log('Create app for teams: ', val);
}
});
},
(err) => {
console.log('Error creating application ' + err);
},
);
}
/**
* Gets the names of the apps already in this view so we don't duplicate an application
*/
getExistingApps() {
this.applicationService
.getViewApplications(this.view.id)
.pipe(take(1))
.subscribe({
next: (data) => {
this.appNames = new Array<string>();
for (const app of data) {
this.appNames.push(app.name);
}
},
error: (err) => {
console.log('Error fetching apps');
console.log(err);
},
});
}
/**
* Called when the Teams select box for a file is changed.
* @param event The event from the select box
* @param file The file to update the teams for
*/
teamsForFileUpdated(event: any, file: FileModel) {
const newTeamIds = event.value;
// Update local state to reflect selection
file.teamIds = newTeamIds || [];
// Only save to server if at least one team is selected
if (!newTeamIds || newTeamIds.length === 0) {
return;
}
this.fileService
.updateFile(file.id, file.name, file.teamIds, null)
.pipe(take(1))
.subscribe({
error: (err) => {
console.error('Error updating file teams:', err);
}
});
}
/**
* Checks if all teams are selected for a given file
* @param file The file to check
*/
isAllTeamsSelected(file: FileModel): boolean {
if (!file.teamIds || !this.teams) {
return false;
}
const allTeamIds = this.teams.map(t => t.team.id);
return allTeamIds.length === file.teamIds.length &&
allTeamIds.every(id => file.teamIds.includes(id));
}
/**
* Toggles selection of all teams for a specific file
* @param checked Whether all teams should be selected
* @param file The file to update
*/
toggleAllTeamsForViewFile(checked: boolean, file: FileModel) {
if (checked) {
file.teamIds = this.teams.map(t => t.team.id);
this.fileService
.updateFile(file.id, file.name, file.teamIds, null)
.pipe(take(1))
.subscribe({
error: (err) => {
console.error('Error updating file teams:', err);
}
});
} else {
// Allow clearing teams in UI, but don't save until at least one team is selected
file.teamIds = [];
}
}
/**
* Returns true if the file is an image or pdf. If we want to support more image type, will have to modify this function
*
* @param file: The file to consider
*/
private isImageOrPdf(file: string): boolean {
return (
file.endsWith('.pdf') ||
file.endsWith('.jpeg') ||
file.endsWith('.jpg') ||
file.endsWith('.png') ||
file.endsWith('.bmp') ||
file.endsWith('.heic') ||
file.endsWith('.gif')
);
}
private getFileUri(file: FileModel) {
let baseURI = document.baseURI;
if (baseURI.endsWith('/')) {
baseURI = baseURI.slice(0, baseURI.length - 1);
}
return `${baseURI}/file?id=${file.id}&name=${file.name}`;
}
} // End Class
/** Error when invalid control is dirty, touched, or submitted. */
export class UserErrorStateMatcher implements ErrorStateMatcher {
isErrorState(
control: UntypedFormControl | null,
form: FormGroupDirective | NgForm | null,
): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || isSubmitted));
}
}
class PlayerFile {
file: File;
id: string;
constructor(file: File) {
this.file = file;
}
}