GitLab steht wegen Wartungsarbeiten am Montag, den 10. Mai, zwischen 17:00 und 19:00 Uhr nicht zur Verfügung.

home.component.ts 21.4 KB
Newer Older
1
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
2
import { Component, Inject, OnDestroy, OnInit, PLATFORM_ID, SecurityContext } from '@angular/core';
3 4 5
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
6
import { Subject } from 'rxjs';
7
import { distinctUntilChanged, takeUntil } from 'rxjs/operators';
8
import { environment } from '../../../environments/environment';
9 10 11 12 13 14
import { checkABCDOrdering } from '../../lib/checkABCDOrdering';
import { DefaultSettings } from '../../lib/default.settings';
import { AbstractAnswerEntity } from '../../lib/entities/answer/AbstractAnswerEntity';
import { DefaultAnswerEntity } from '../../lib/entities/answer/DefaultAnswerEntity';
import { ABCDSingleChoiceQuestionEntity } from '../../lib/entities/question/ABCDSingleChoiceQuestionEntity';
import { QuizEntity } from '../../lib/entities/QuizEntity';
15
import { Language, StorageKey } from '../../lib/enums/enums';
16 17 18 19
import { MessageProtocol, StatusProtocol } from '../../lib/enums/Message';
import { QuestionType } from '../../lib/enums/QuestionType';
import { QuizState } from '../../lib/enums/QuizState';
import { UserRole } from '../../lib/enums/UserRole';
20
import { ITrackClickEvent } from '../../lib/interfaces/tracking/ITrackClickEvent';
21
import { AvailableQuizzesComponent } from '../../modals/available-quizzes/available-quizzes.component';
22
import { MemberApiService } from '../../service/api/member/member-api.service';
23
import { QuizApiService } from '../../service/api/quiz/quiz-api.service';
24 25 26 27
import { AttendeeService } from '../../service/attendee/attendee.service';
import { ConnectionService } from '../../service/connection/connection.service';
import { FooterBarService } from '../../service/footer-bar/footer-bar.service';
import { HeaderLabelService } from '../../service/header-label/header-label.service';
28
import { I18nService } from '../../service/i18n/i18n.service';
29
import { CasLoginService } from '../../service/login/cas-login.service';
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
30
import { QuizService } from '../../service/quiz/quiz.service';
31 32
import { SettingsService } from '../../service/settings/settings.service';
import { SharedService } from '../../service/shared/shared.service';
33
import { StorageService } from '../../service/storage/storage.service';
34
import { ThemesService } from '../../service/themes/themes.service';
35
import { TrackingService } from '../../service/tracking/tracking.service';
36
import { UserService } from '../../service/user/user.service';
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
37 38 39 40

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
41
  styleUrls: ['./home.component.scss'],
42
})
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
43
export class HomeComponent implements OnInit, OnDestroy {
44
  public static TYPE = 'HomeComponent';
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
45 46 47
  public canJoinQuiz = false;
  public canAddQuiz = false;
  public canEditQuiz = false;
48
  public canStartQuiz = false;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
49 50 51 52
  public passwordRequired = false;
  public isAddingDemoQuiz = false;
  public isAddingABCDQuiz = false;
  public enteredSessionName = '';
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
53 54
  public publicQuizAmount: number;
  public ownPublicQuizAmount: number;
55 56
  public canModifyQuiz: boolean = !environment.requireLoginToCreateQuiz;
  public canUsePublicQuizzes: boolean = !environment.requireLoginToCreateQuiz;
57 58
  public showJoinableQuizzes: boolean = environment.showJoinableQuizzes;
  public isQueryingQuizState: boolean;
59
  public readonly claimSrc = environment.claimSrc;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
60 61

  private _serverPassword = '';
62 63 64 65 66

  get serverPassword(): string {
    return this._serverPassword;
  }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
67 68
  private _hasErrors = '';

69 70 71
  get hasErrors(): string {
    return this._hasErrors;
  }
72 73 74

  private _isShowingQuiznameDatalist = false;

75 76 77 78 79 80 81 82
  get isShowingQuiznameDatalist(): boolean {
    return this._isShowingQuiznameDatalist;
  }

  set isShowingQuiznameDatalist(value: boolean) {
    this._isShowingQuiznameDatalist = value;
  }

83 84 85 86 87 88
  private _ownQuizzes: Array<string> = [];

  get ownQuizzes(): Array<string> {
    return this._ownQuizzes;
  }

89
  private readonly _destroy = new Subject();
90
  private _isPerformingClick: Array<string> = [];
91 92 93 94 95 96

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private footerBarService: FooterBarService,
    private headerLabelService: HeaderLabelService,
    private modalService: NgbModal,
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
97
    private quizService: QuizService,
98 99
    private router: Router,
    private themesService: ThemesService,
100
    private activatedRoute: ActivatedRoute,
101 102 103 104 105 106 107
    private i18nService: I18nService,
    private attendeeService: AttendeeService,
    private sanitizer: DomSanitizer,
    private casService: CasLoginService,
    private settingsService: SettingsService,
    private trackingService: TrackingService,
    private quizApiService: QuizApiService,
108 109
    private storageService: StorageService,
    private userService: UserService,
110 111 112
    public connectionService: ConnectionService,
    public sharedService: SharedService,
    public memberApiService: MemberApiService,
113 114
  ) {

115
    sessionStorage.removeItem(StorageKey.CurrentQuestionIndex);
116 117
    this.footerBarService.TYPE_REFERENCE = HomeComponent.TYPE;

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
118
    headerLabelService.headerLabel = 'default';
119

120
    this.updateFooterElements(this.userService.isLoggedIn);
121
    this.canModifyQuiz = !environment.requireLoginToCreateQuiz || this.userService.isAuthorizedFor(UserRole.QuizAdmin);
122 123
    this.canUsePublicQuizzes = (environment.showPublicQuizzes || this.userService.isAuthorizedFor(UserRole.QuizAdmin))
                               && !environment.requireLoginToCreateQuiz || this.userService.isAuthorizedFor(UserRole.CreateQuiz);
124

125
    this.quizService.stopEditMode();
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
126 127
  }

128
  public sanitizeHTML(value: string): SafeHtml {
129
    return this.sanitizer.sanitize(SecurityContext.HTML, `${value}`);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
130 131
  }

132
  public ngOnInit(): void {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
133 134 135
    if (isPlatformServer(this.platformId)) {
      return;
    }
136

137
    this.userService.loginNotifier.pipe(takeUntil(this._destroy), distinctUntilChanged()).subscribe(isLoggedIn => {
138 139 140 141 142
      this.updateFooterElements(isLoggedIn);
      this.canModifyQuiz = !environment.requireLoginToCreateQuiz || (isLoggedIn && this.userService.isAuthorizedFor(UserRole.QuizAdmin));
      this.canUsePublicQuizzes = !environment.requireLoginToCreateQuiz || (isLoggedIn && this.userService.isAuthorizedFor(UserRole.CreateQuiz));
    });

143
    this.activatedRoute.paramMap.pipe(distinctUntilChanged(), takeUntil(this._destroy)).subscribe(async params => {
144
      this.cleanUpSessionStorage();
145

146 147
      this.storageService.db.getAllQuiznames().then(quizNames => {
        this._ownQuizzes = quizNames;
148

149 150 151
        if (this._ownQuizzes.length && //
            environment.showJoinableQuizzes && //
            (!environment.requireLoginToCreateQuiz || this.userService.isAuthorizedFor(UserRole.CreateQuiz))) {
152 153
          const ref = this.modalService.open(AvailableQuizzesComponent);
          this._destroy.subscribe(() => ref.close());
154 155
        }
      });
156

157 158 159 160 161 162
      if (environment.showPublicQuizzes || this.userService.isAuthorizedFor(UserRole.QuizAdmin)) {
        this.quizApiService.getPublicQuizAmount().subscribe(val => {
          this.publicQuizAmount = val;
        });
        this.quizApiService.getOwnPublicQuizAmount().subscribe(val => {
          this.ownPublicQuizAmount = val;
163 164
        });
      }
165

166
      if (!Object.keys(params).length || !params.get('themeId') || !params.get('languageId')) {
167
        const theme = this.storageService.db.Config.get(StorageKey.DefaultTheme);
168
        if (!theme) {
169 170 171 172
          await this.storageService.db.Config.put({
            value: this.themesService.defaultTheme,
            type: StorageKey.DefaultTheme,
          });
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
173
        }
174
      } else {
175
        await this.storageService.db.Config.put({
176 177
          value: params.get('themeId'),
          type: StorageKey.DefaultTheme,
178 179
        });
        await this.themesService.updateCurrentlyUsedTheme();
180
        this.i18nService.setLanguage(<Language>params.get('languageId').toUpperCase());
181
      }
182
    });
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
183 184
  }

185
  public ngOnDestroy(): void {
186 187
    this._destroy.next();
    this._destroy.complete();
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
188 189
  }

190 191 192 193
  public autoJoinToSession(quizname): void {
    if (isPlatformServer(this.platformId)) {
      return;
    }
194

195
    this.selectQuizByList(quizname);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
196
    this.joinQuiz();
197

198
    this.router.navigate(['/quiz', quizname]);
199 200
  }

201
  public showQuiznameDatalist(): void {
202 203 204
    if (environment.showJoinableQuizzes) {
      this.isShowingQuiznameDatalist = true;
    }
205 206
  }

207
  public hideQuiznameDatalist(): void {
208 209 210
    this.isShowingQuiznameDatalist = false;
  }

211 212
  public selectQuizByList(quizName: string): void {
    this.hideQuiznameDatalist();
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
213 214
    this.enteredSessionName = quizName;
    this.selectQuizByName(this.enteredSessionName.trim());
215 216
  }

217
  public parseQuiznameInput(quizname: string): void {
218
    this.isQueryingQuizState = true;
219
    this.selectQuizByName(quizname.trim());
220 221
  }

222
  public setPassword(event: Event): void {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
223
    this._serverPassword = (<HTMLInputElement>event.target).value;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
224 225
  }

226
  public handleClick(id: string): boolean {
227 228 229 230 231
    const trackingParams: ITrackClickEvent = {
      action: HomeComponent.TYPE,
      label: '',
      customDimensions: {
        dimension1: this.hasErrors,
232 233
        dimension2: this.passwordRequired,
      },
234 235
    };

236 237 238 239
    if (!this._isPerformingClick.includes(id)) {
      this._isPerformingClick.push(id);
    }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    switch (id) {
      case 'joinSession':
        trackingParams.label = 'join-session';
        break;
      case 'addSession':
        trackingParams.label = 'add-session';
        break;
      case 'editSession':
        trackingParams.label = 'edit-session';
        break;
      case 'add-demo-quiz':
        trackingParams.label = 'add-demo-quiz';
        break;
      case 'add-abcd-quiz':
        trackingParams.label = 'add-abcd-quiz';
        break;
    }

    this.trackingService.trackClickEvent(trackingParams);

    return true;
  }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
263 264 265
  public editQuiz(): void {
    if (isPlatformServer(this.platformId)) {
      return null;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
266
    }
267

268
    sessionStorage.setItem(StorageKey.CurrentQuizName, this.enteredSessionName);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
269 270 271 272 273 274
    this.router.navigate(['/quiz', 'manager', 'overview']);
  }

  public addQuiz(): void {
    if (isPlatformServer(this.platformId)) {
      return null;
275 276
    }

277
    sessionStorage.setItem(StorageKey.CurrentQuizName, this.enteredSessionName);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
278 279 280 281
    this.runQuiz(['/quiz', 'manager', 'overview']);
  }

  public joinQuiz(): void {
282
    sessionStorage.setItem(StorageKey.CurrentQuizName, this.enteredSessionName);
283 284
  }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
285
  public async runQuiz(routingTarget: Array<string>): Promise<void> {
286 287 288
    if (isPlatformServer(this.platformId)) {
      return null;
    }
289

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
290
    if (this.passwordRequired && !(this._serverPassword && this._serverPassword.length)) {
291 292
      return;
    }
293

294
    const questionGroupSerialized = await this.storageService.db.Quiz.get(this.enteredSessionName);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
295
    const questionGroup = await new Promise<QuizEntity>((resolve) => {
296
      if (this.isAddingDemoQuiz) {
297
        this.addDemoQuiz().then(value => resolve(value));
298
      } else if (this.isAddingABCDQuiz) {
299
        this.addAbcdQuiz().then(value => resolve(value));
300
      } else if (questionGroupSerialized) {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
301
        resolve(new QuizEntity(questionGroupSerialized));
302
      } else {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
303 304 305
        resolve(new QuizEntity({
          name: this.enteredSessionName,
          sessionConfig: DefaultSettings.defaultQuizSettings.sessionConfig,
306
        }));
307
      }
308 309
    });

310
    this.reserveQuiz(questionGroup, routingTarget);
311
  }
312

313 314 315 316
  public isPerformingClick(id: string): boolean {
    return this._isPerformingClick.includes(id);
  }

317 318 319 320 321 322 323 324 325 326 327
  public resetSessionName(): void {
    this.enteredSessionName = '';
    this.canJoinQuiz = false;
    this.canAddQuiz = false;
    this.canEditQuiz = false;
    this.canStartQuiz = false;
    this.passwordRequired = false;
    this.isAddingDemoQuiz = false;
    this.isAddingABCDQuiz = false;
  }

328 329 330 331 332 333 334 335
  private updateFooterElements(isLoggedIn: boolean): void {
    const footerElements = [
      this.footerBarService.footerElemAbout,
      this.footerBarService.footerElemTranslation,
      this.footerBarService.footerElemTheme,
      this.footerBarService.footerElemFullscreen,
    ];

336
    if (!environment.requireLoginToCreateQuiz && (environment.showPublicQuizzes || this.userService.isAuthorizedFor(UserRole.QuizAdmin))) {
337 338 339 340
      footerElements.push(this.footerBarService.footerElemHashtagManagement);
      footerElements.push(this.footerBarService.footerElemImport);
    }

341
    if (isLoggedIn) {
342
      if (environment.requireLoginToCreateQuiz && (environment.showPublicQuizzes || this.userService.isAuthorizedFor(UserRole.QuizAdmin))) {
343 344 345 346 347 348 349 350 351
        if (this.userService.isAuthorizedFor(UserRole.CreateQuiz)) {
          footerElements.push(this.footerBarService.footerElemHashtagManagement);
        }

        if (this.userService.isAuthorizedFor(UserRole.QuizAdmin)) {
          footerElements.push(this.footerBarService.footerElemImport);
        }
      }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
352
      if (this.userService.isAuthorizedFor(UserRole.EditI18n)) {
353 354
        footerElements.push(this.footerBarService.footerElemEditI18n);
      }
355

356
      if (this.userService.isAuthorizedFor([UserRole.SuperAdmin])) {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
357 358
        footerElements.push(this.footerBarService.footerElemAdmin);
      }
359

360 361 362
      footerElements.push(this.footerBarService.footerElemLogout);

    } else {
363 364 365
      if (environment.loginMechanism && environment.loginMechanism.length) {
        footerElements.push(this.footerBarService.footerElemLogin);
      }
366 367 368 369 370
    }

    this.footerBarService.replaceFooterElements(footerElements);
  }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
371 372
  private async reserveQuiz(questionGroup: QuizEntity, routingTarget: Array<string>): Promise<void> {
    this.quizApiService.setQuiz(questionGroup).subscribe(modifiedQuestionGroup => {
373
      this.quizService.persistQuiz(new QuizEntity(questionGroup));
374

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
375 376 377 378 379 380 381 382 383 384 385 386 387
      this.quizService.quiz = new QuizEntity(modifiedQuestionGroup);
      this.quizService.isOwner = true;

      if (this.isAddingABCDQuiz) {
        this.trackingService.trackConversionEvent({
          action: HomeComponent.TYPE,
          label: 'ABCD Quiz created',
        });
      } else if (this.isAddingDemoQuiz) {
        this.trackingService.trackConversionEvent({
          action: HomeComponent.TYPE,
          label: 'Demo Quiz created',
        });
388 389 390 391 392
      } else {
        this.trackingService.trackConversionEvent({
          action: HomeComponent.TYPE,
          label: 'Custom Quiz created',
        });
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
393
      }
394

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
395 396 397 398 399 400 401 402
      this.router.navigate(routingTarget);
    }, error => {
      if (error === MessageProtocol.TooMuchActiveQuizzes) {
        this._hasErrors = 'plugins.splashscreen.error.error_messages.too_much_active_quizzes';
      } else if (error === MessageProtocol.ServerPasswordRequired) {
        this._hasErrors = 'plugins.splashscreen.error.error_messages.server_password_required';
      } else if (error === MessageProtocol.InsufficientPermissions) {
        this._hasErrors = 'plugins.splashscreen.error.error_messages.server_password_invalid';
403
      } else {
404
        console.log('HomeComponent: SetQuiz failed', error);
405
      }
406 407 408
    });
  }

409
  private selectQuizByName(quizName: string): void {
410 411 412 413 414 415 416 417 418 419 420 421
    this.canJoinQuiz = false;
    this.canAddQuiz = false;
    this.canEditQuiz = false;
    this.canStartQuiz = false;
    this.passwordRequired = false;
    this.isAddingDemoQuiz = false;
    this.isAddingABCDQuiz = false;

    if (isPlatformServer(this.platformId)) {
      return;
    }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
422
    if (this.ownQuizzes.find(quiz => quiz === quizName)) {
423 424 425
      this.selectQuizAsExisting(quizName);
    } else if (quizName.toLowerCase() === 'demo quiz') {
      this.selectQuizAsDemoQuiz();
426
    } else if (checkABCDOrdering(quizName)) {
427
      this.selectQuizAsAbcdQuiz();
428
    } else {
429 430
      if (quizName.length > 3) {
        this.selectQuizAsDefaultQuiz(quizName);
431 432
      } else {
        this.isQueryingQuizState = false;
433
      }
434
    }
435 436
  }

437
  private async selectQuizAsExisting(quizname): Promise<void> {
438
    const currentQuiz = new QuizEntity(await this.storageService.db.Quiz.get(quizname));
439 440
    this.canAddQuiz = false;
    this.canEditQuiz = true;
441 442 443
    this.canStartQuiz = this.connectionService.serverAvailable && //
                        (this.settingsService.serverSettings && !this.settingsService.serverSettings.createQuizPasswordRequired) && //
                        currentQuiz.isValid();
444
    this.passwordRequired = this.canStartQuiz && this.settingsService.serverSettings.createQuizPasswordRequired;
445
    this.isQueryingQuizState = false;
446 447 448 449 450 451
  }

  private selectQuizAsDemoQuiz(): void {
    this.isAddingDemoQuiz = true;
    this.canAddQuiz = false;
    this.canEditQuiz = false;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
452
    this.canStartQuiz = false;
453
    this.passwordRequired = this.settingsService.serverSettings.createQuizPasswordRequired;
454
    this.isQueryingQuizState = false;
455 456 457 458 459 460
  }

  private selectQuizAsAbcdQuiz(): void {
    this.isAddingABCDQuiz = true;
    this.canAddQuiz = false;
    this.canEditQuiz = false;
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
461
    this.canStartQuiz = false;
462
    this.passwordRequired = this.settingsService.serverSettings.createQuizPasswordRequired;
463
    this.isQueryingQuizState = false;
464 465
  }

466 467
  private selectQuizAsDefaultQuiz(quizName: string): void {
    this.quizApiService.getQuizStatus(quizName).subscribe(value => {
468 469
      this.isQueryingQuizState = false;

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
470
      if (value.status === StatusProtocol.Success) {
471
        if (value.step === MessageProtocol.AlreadyTaken || (value.payload.state && value.payload.state !== QuizState.Active)) {
472 473 474 475 476 477
          this.canAddQuiz = false;
          this.canJoinQuiz = false;
          this.passwordRequired = false;
          this.canStartQuiz = false;
        } else if (value.step === MessageProtocol.Available && value.payload.state === QuizState.Active) {
          this.canAddQuiz = false;
478
          this.canJoinQuiz = this.connectionService.serverAvailable;
479 480 481 482 483 484 485 486 487 488 489 490 491
          this.passwordRequired = false;
          this.canStartQuiz = false;
          this.casService.casLoginRequired = value.payload.authorizeViaCas;
          if (this.casService.casLoginRequired) {
            this.casService.quizName = quizName;
          }
        } else if (value.step === MessageProtocol.Unavailable) {
          this.canAddQuiz = true;
          this.canJoinQuiz = false;
          this.passwordRequired = this.settingsService.serverSettings.createQuizPasswordRequired;
          this.canStartQuiz = false;
        } else {
          console.error('Invalid quiz status response in home component', value);
492 493
        }
      }
494
    }, () => {});
495 496 497
  }

  private cleanUpSessionStorage(): void {
498 499 500
    if (this.quizService.quiz && this.attendeeService.ownNick) {
      this.memberApiService.deleteMember(this.quizService.quiz.name, this.attendeeService.ownNick).subscribe();
    }
501
    this.attendeeService.cleanUp();
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
502
    this.quizService.cleanUp();
503
    this.connectionService.cleanUp();
504 505
    sessionStorage.removeItem(StorageKey.CurrentQuizName);
    sessionStorage.removeItem(StorageKey.CurrentNickName);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
506
    if (isPlatformBrowser(this.platformId)) {
507
      this.storageService.db.Config.delete(StorageKey.QuizTheme);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
508
    }
509
    if (!environment.persistQuizzes && !this.userService.isAuthorizedFor(UserRole.QuizAdmin)) {
510 511 512 513 514
      this.storageService.db.Quiz.toCollection().each(quizData => {
        this.quizApiService.deleteQuiz(quizData).subscribe(() => {
          this.storageService.db.Quiz.delete(quizData.name);
        }, () => {
          this.storageService.db.Quiz.delete(quizData.name);
515 516 517
        });
      });
    }
518
  }
519

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
520
  private async addDemoQuiz(): Promise<QuizEntity> {
521
    const value = await this.quizApiService.generateDemoQuiz(this.i18nService.currentLanguage.toString()).toPromise();
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
522 523 524
    value.sessionConfig = Object.assign({}, DefaultSettings.defaultQuizSettings.sessionConfig, value.sessionConfig);
    const questionGroup = new QuizEntity(value);
    this.enteredSessionName = questionGroup.name;
525 526

    return questionGroup;
527 528
  }

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
529
  private async addAbcdQuiz(): Promise<QuizEntity> {
530 531 532
    const language = this.i18nService.currentLanguage.toString();
    const answerList = this.enteredSessionName.split('');

533 534 535
    if (isPlatformServer(this.platformId)) {
      return;
    }
536

537
    const hasMatchedABCDQuiz = this.ownQuizzes.filter(quizName => {
538 539 540
      return quizName.split(' ')[0] === this.enteredSessionName;
    });
    if (hasMatchedABCDQuiz.length) {
541
      const questionGroup = await this.storageService.db.Quiz.get(hasMatchedABCDQuiz[0]);
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
542
      const answerOptionList = (<Array<AbstractAnswerEntity>>[]);
543 544

      answerList.forEach((character, index) => {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
545
        answerOptionList.push(new DefaultAnswerEntity({
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
546
          answerText: (String.fromCharCode(index + 65)),
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
547
          isCorrect: false,
548
        }));
549
      });
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
550 551
      this.enteredSessionName = questionGroup.name;
      const abcdQuestion: ABCDSingleChoiceQuestionEntity = new ABCDSingleChoiceQuestionEntity({
552 553 554 555 556
        questionText: '',
        timer: 60,
        displayAnswerText: false,
        answerOptionList,
        showOneAnswerPerRow: false,
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
557
      });
558
      questionGroup.questionList = [abcdQuestion];
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
559
      return new QuizEntity(questionGroup);
560 561 562 563

    } else {

      const value = await this.quizApiService.generateABCDQuiz(language, answerList.length).toPromise();
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
564
      Object.assign({}, DefaultSettings.defaultQuizSettings.sessionConfig, value.sessionConfig);
565

Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
566 567
      const questionGroup = value;
      const answerOptionList = (<Array<AbstractAnswerEntity>>[]);
568 569

      answerList.forEach((character, index) => {
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
570
        answerOptionList.push(new DefaultAnswerEntity({
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
571
          answerText: (String.fromCharCode(index + 65)),
572
        }));
573
      });
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
574 575 576
      this.enteredSessionName = questionGroup.name;
      const abcdQuestion: ABCDSingleChoiceQuestionEntity = new ABCDSingleChoiceQuestionEntity({
        TYPE: QuestionType.ABCDSingleChoiceQuestion,
577 578 579 580 581
        questionText: '',
        timer: 60,
        displayAnswerText: false,
        answerOptionList,
        showOneAnswerPerRow: false,
582 583
      });
      questionGroup.questionList = [abcdQuestion];
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
584
      return new QuizEntity(questionGroup);
585
    }
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
586 587
  }
}