-
Notifications
You must be signed in to change notification settings - Fork 16
/
entry-store.service.ts
385 lines (329 loc) · 10.9 KB
/
entry-store.service.ts
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
import {Host, Injectable, OnDestroy} from '@angular/core';
import {ActivatedRoute, NavigationEnd, NavigationStart, Router} from '@angular/router';
import {AppLocalization} from '@kaltura-ng/kaltura-common';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {ISubscription} from 'rxjs/Subscription';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/subscribeOn';
import 'rxjs/add/operator/switchMap';
import {KalturaClient} from 'kaltura-ngx-client';
import {KalturaMediaEntry} from 'kaltura-ngx-client/api/types/KalturaMediaEntry';
import {KalturaMultiRequest, KalturaTypesFactory} from 'kaltura-ngx-client';
import {BaseEntryGetAction} from 'kaltura-ngx-client/api/types/BaseEntryGetAction';
import {BaseEntryUpdateAction} from 'kaltura-ngx-client/api/types/BaseEntryUpdateAction';
import '@kaltura-ng/kaltura-common/rxjs/add/operators';
import { EntryWidgetsManager } from './entry-widgets-manager';
import { OnDataSavingReasons } from '@kaltura-ng/kaltura-ui';
import { BrowserService } from 'app-shared/kmc-shell/providers/browser.service';
import { EntriesStore } from 'app-shared/content-shared/entries/entries-store/entries-store.service';
import { PageExitVerificationService } from 'app-shared/kmc-shell/page-exit-verification';
export enum ActionTypes
{
EntryLoading,
EntryLoaded,
EntryLoadingFailed,
EntrySaving,
EntryPrepareSavingFailed,
EntrySavingFailed,
EntryDataIsInvalid,
ActiveSectionBusy
}
declare type StatusArgs =
{
action : ActionTypes;
error? : Error;
}
@Injectable()
export class EntryStore implements OnDestroy {
private _loadEntrySubscription : ISubscription;
private _sectionToRouteMapping : { [key : number] : string} = {};
private _state = new BehaviorSubject<StatusArgs>({ action : ActionTypes.EntryLoading, error : null});
private _pageExitVerificationToken: string;
public state$ = this._state.asObservable();
private _entryIsDirty : boolean;
public get entryIsDirty() : boolean{
return this._entryIsDirty;
}
private _saveEntryInvoked = false;
private _entry : BehaviorSubject<KalturaMediaEntry> = new BehaviorSubject<KalturaMediaEntry>(null);
public entry$ = this._entry.asObservable();
private _entryId : string;
public get entryId() : string{
return this._entryId;
}
public get entry() : KalturaMediaEntry
{
return this._entry.getValue();
}
constructor(private _kalturaServerClient: KalturaClient,
private _router: Router,
private _browserService : BrowserService,
private _entriesStore : EntriesStore,
@Host() private _widgetsManager: EntryWidgetsManager,
private _entryRoute: ActivatedRoute,
private _pageExitVerificationService: PageExitVerificationService,
private _appLocalization: AppLocalization) {
this._widgetsManager.entryStore = this;
this._mapSections();
this._onSectionsStateChanges();
this._onRouterEvents();
// hard reload the entries upon navigating back from entry (by adding 'reloadEntriesListOnNavigateOut' to the queryParams)
this._entryRoute.queryParams.cancelOnDestroy(this)
.first()
.subscribe(queryParams => {
const reloadEntriesListOnNavigateOut = !!queryParams['reloadEntriesListOnNavigateOut']; // convert string to boolean
if (reloadEntriesListOnNavigateOut) {
this._saveEntryInvoked = reloadEntriesListOnNavigateOut;
}
});
}
private _onSectionsStateChanges()
{
this._widgetsManager.widgetsState$
.cancelOnDestroy(this)
.debounce(() => Observable.timer(500))
.subscribe(
sectionsState =>
{
const newDirtyState = Object.keys(sectionsState).reduce((result, sectionName) => result || sectionsState[sectionName].isDirty,false);
if (this._entryIsDirty !== newDirtyState)
{
console.log(`entry store: update entry is dirty state to ${newDirtyState}`);
this._entryIsDirty = newDirtyState;
this._updatePageExitVerification();
}
}
);
}
private _updatePageExitVerification() {
if (this._entryIsDirty) {
this._pageExitVerificationToken = this._pageExitVerificationService.add();
} else {
if (this._pageExitVerificationToken) {
this._pageExitVerificationService.remove(this._pageExitVerificationToken);
}
this._pageExitVerificationToken = null;
}
}
ngOnDestroy() {
this._loadEntrySubscription && this._loadEntrySubscription.unsubscribe();
this._state.complete();
this._entry.complete();
if (this._pageExitVerificationToken) {
this._pageExitVerificationService.remove(this._pageExitVerificationToken);
}
if (this._saveEntryInvoked)
{
this._entriesStore.reload();
}
}
private _mapSections() : void{
if (!this._entryRoute || !this._entryRoute.snapshot.data.entryRoute)
{
throw new Error("this service can be injected from component that is associated to the entry route");
}
this._entryRoute.snapshot.routeConfig.children.forEach(childRoute =>
{
const routeSectionType = childRoute.data ? childRoute.data.sectionKey : null;
if (routeSectionType !== null)
{
this._sectionToRouteMapping[routeSectionType] = childRoute.path;
}
});
}
private _onRouterEvents() : void {
this._router.events
.cancelOnDestroy(this)
.subscribe(
event => {
if (event instanceof NavigationStart) {
} else if (event instanceof NavigationEnd) {
// we must defer the loadEntry to the next event cycle loop to allow components
// to init them-selves when entering this module directly.
setTimeout(() =>
{
const currentEntryId = this._entryRoute.snapshot.params.id;
const entry = this._entry.getValue();
if (!entry || (entry && entry.id !== currentEntryId)) {
this._loadEntry(currentEntryId);
}
});
}
}
)
}
private _transmitSaveRequest(newEntry : KalturaMediaEntry) {
this._state.next({action: ActionTypes.EntrySaving});
const request = new KalturaMultiRequest(
new BaseEntryUpdateAction({
entryId: this.entryId,
baseEntry: newEntry
})
);
this._widgetsManager.notifyDataSaving(newEntry, request, this.entry)
.cancelOnDestroy(this)
.tag('block-shell')
.monitor('entry store: prepare entry for save')
.flatMap(
(response) => {
if (response.ready) {
this._saveEntryInvoked = true;
return this._kalturaServerClient.multiRequest(request)
.monitor('entry store: save entry')
.tag('block-shell')
.map(
response => {
if (response.hasErrors()) {
this._state.next({action: ActionTypes.EntrySavingFailed});
} else {
this._loadEntry(this.entryId);
}
return Observable.empty();
}
)
}
else {
switch (response.reason) {
case OnDataSavingReasons.validationErrors:
this._state.next({action: ActionTypes.EntryDataIsInvalid});
break;
case OnDataSavingReasons.attachedWidgetBusy:
this._state.next({action: ActionTypes.ActiveSectionBusy});
break;
case OnDataSavingReasons.buildRequestFailure:
this._state.next({action: ActionTypes.EntryPrepareSavingFailed});
break;
}
return Observable.empty();
}
}
)
.subscribe(
response => {
// do nothing - the service state is modified inside the map functions.
},
error => {
// should not reach here, this is a fallback plan.
this._state.next({action: ActionTypes.EntrySavingFailed});
}
);
}
public saveEntry() : void {
const newEntry = KalturaTypesFactory.createObject(this.entry);
if (newEntry && newEntry instanceof KalturaMediaEntry) {
this._transmitSaveRequest(newEntry)
} else {
console.error(new Error(`Failed to create a new instance of the entry type '${this.entry ? typeof this.entry : 'n/a'}`));
this._state.next({action: ActionTypes.EntryPrepareSavingFailed});
}
}
public reloadEntry() : void
{
if (this.entryId)
{
this._loadEntry(this.entryId);
}
}
private _loadEntry(entryId : string) : void {
if (this._loadEntrySubscription) {
this._loadEntrySubscription.unsubscribe();
this._loadEntrySubscription = null;
}
this._entryId = entryId;
this._entryIsDirty = false;
this._updatePageExitVerification();
this._state.next({action: ActionTypes.EntryLoading});
this._widgetsManager.notifyDataLoading(entryId);
this._loadEntrySubscription = this._getEntry(entryId)
.cancelOnDestroy(this)
.subscribe(
response => {
this._entry.next(response);
this._entryId = response.id;
const dataLoadedResult = this._widgetsManager.notifyDataLoaded(response, { isNewData: false });
if (dataLoadedResult.errors.length)
{
this._state.next({action: ActionTypes.EntryLoadingFailed,
error: new Error(`one of the widgets failed while handling data loaded event`)});
}else {
this._state.next({action: ActionTypes.EntryLoaded});
}
},
error => {
this._state.next({action: ActionTypes.EntryLoadingFailed, error});
}
);
}
public openSection(sectionKey : string) : void{
const navigatePath = this._sectionToRouteMapping[sectionKey];
if (navigatePath) {
this._router.navigate([navigatePath], {relativeTo: this._entryRoute});
}
}
private _getEntry(entryId:string) : Observable<KalturaMediaEntry>
{
if (entryId)
{
return this._kalturaServerClient.request(
new BaseEntryGetAction({entryId})
).map(response =>
{
if (response instanceof KalturaMediaEntry)
{
return response;
}else {
throw new Error(`invalid type provided, expected KalturaMediaEntry, got ${typeof response}`);
}
});
}else
{
return Observable.throw(new Error('missing entryId'));
}
}
public openEntry(entryId : string)
{
this.canLeave()
.cancelOnDestroy(this)
.subscribe(
response =>
{
if (response.allowed)
{
this._router.navigate(["entry", entryId, "metadata"],{ relativeTo : this._entryRoute.parent});
}
}
);
}
public canLeave() : Observable<{ allowed : boolean}>
{
return Observable.create(observer =>
{
if (this._entryIsDirty) {
this._browserService.confirm(
{
header: this._appLocalization.get('applications.content.entryDetails.captions.cancelEdit'),
message: this._appLocalization.get('applications.content.entryDetails.captions.discard'),
accept: () => {
this._entryIsDirty = false;
observer.next({allowed: true});
observer.complete();
},
reject: () => {
observer.next({allowed: false});
observer.complete();
}
}
)
}else
{
observer.next({allowed: true});
observer.complete();
}
}).monitor('entry store: check if can leave section without saving');
}
public returnToEntries(params : {force? : boolean} = {})
{
this._router.navigate(['content/entries']);
}
}