QuizEntity.ts 12.2 KB
Newer Older
1
import { ObjectId } from 'bson';
2 3
import * as http from 'http';
import * as https from 'https';
4
import { DeleteWriteOpResultObject } from 'mongodb';
5
import AMQPConnector from '../../db/AMQPConnector';
6 7
import DbDAO from '../../db/DbDAO';
import MemberDAO from '../../db/MemberDAO';
8
import { DbCollection } from '../../enums/DbOperation';
9 10 11 12 13 14
import { MessageProtocol, StatusProtocol } from '../../enums/Message';
import { QuestionType } from '../../enums/QuestionType';
import { QuizState } from '../../enums/QuizState';
import { QuizVisibility } from '../../enums/QuizVisibility';
import { IQuizEntity, IQuizSerialized } from '../../interfaces/quizzes/IQuizEntity';
import { ISessionConfigurationEntity } from '../../interfaces/session_configuration/ISessionConfigurationEntity';
15
import { settings } from '../../statistics';
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
import { AbstractEntity } from '../AbstractEntity';
import { MemberEntity } from '../member/MemberEntity';
import { MemberGroupEntity } from '../member/MemberGroupEntity';
import { AbstractQuestionEntity } from '../question/AbstractQuestionEntity';
import { getQuestionForType } from '../question/QuizValidator';
import { SessionConfigurationEntity } from '../session-configuration/SessionConfigurationEntity';

export class QuizEntity extends AbstractEntity implements IQuizEntity {
  private _readingConfirmationRequested: boolean;

  get readingConfirmationRequested(): boolean {
    return this._readingConfirmationRequested;
  }

  set readingConfirmationRequested(value: boolean) {
    this._readingConfirmationRequested = value;
  }

  private _name: string;

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

  private _currentQuestionIndex: number;

  get currentQuestionIndex(): number {
    return this._currentQuestionIndex;
  }

  set currentQuestionIndex(value: number) {
    this._currentQuestionIndex = value;
  }

  private _questionList: Array<AbstractQuestionEntity>;

  get questionList(): Array<AbstractQuestionEntity> {
    return this._questionList;
  }

  set questionList(value: Array<AbstractQuestionEntity>) {
    this._questionList = value;
  }

  private _sessionConfig: ISessionConfigurationEntity;

  get sessionConfig(): ISessionConfigurationEntity {
    return this._sessionConfig;
  }

  set sessionConfig(value: ISessionConfigurationEntity) {
    this._sessionConfig = value;
  }

  private _state: QuizState;

  get state(): QuizState {
    return this._state;
  }

  set state(value: QuizState) {
81
    if (this._state !== value && value !== QuizState.Inactive) {
82 83 84 85 86 87
      clearInterval(this._dropEmptyQuizSettings.intervalInstance);
      this._dropEmptyQuizSettings.intervalInstance = setInterval(() => {
        this.checkExistingConnection();
      }, this._dropEmptyQuizSettings.interval);
    }

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
    this._state = value;
  }

  private _expiry: Date;

  get expiry(): Date {
    return this._expiry;
  }

  set expiry(value: Date) {
    this._expiry = value;
  }

  private _currentStartTimestamp: number;

  get currentStartTimestamp(): number {
    return this._currentStartTimestamp;
  }

  set currentStartTimestamp(value: number) {
    this._currentStartTimestamp = value;
  }

  private _memberGroups: Array<MemberGroupEntity>;

  get memberGroups(): Array<MemberGroupEntity> {
    return this._memberGroups;
  }

  set memberGroups(value: Array<MemberGroupEntity>) {
    this._memberGroups = value;
  }

  private _privateKey: string;

  get privateKey(): string {
    return this._privateKey;
  }

  set privateKey(value: string) {
    this._privateKey = value;
  }

  private _visibility: QuizVisibility;

  get visibility(): QuizVisibility {
    return this._visibility;
  }

  set visibility(value: QuizVisibility) {
    this._visibility = value;
  }

  private _description: string;

  get description(): string {
    return this._description;
  }

  set description(value: string) {
    this._description = value;
  }

151 152 153 154 155
  private _dropEmptyQuizSettings = {
    interval: 30000,
    intervalInstance: null,
    isEmpty: false,
  };
156 157
  private _quizTimerInterval: any;
  private _quizTimer: number;
158 159

  private readonly _exchangeName: string;
160 161 162 163 164 165 166 167 168

  constructor(quiz: IQuizSerialized) {
    super();

    this._id = new ObjectId(quiz._id || quiz.id);
    this._name = quiz.name;
    this._questionList = (quiz.questionList || []).map(val => getQuestionForType(val.TYPE, val));
    this._sessionConfig = quiz.sessionConfig ? new SessionConfigurationEntity(quiz.sessionConfig) : null;
    this._expiry = quiz.expiry;
169
    this.state = quiz.state || QuizState.Inactive;
170 171 172 173 174 175
    this._currentStartTimestamp = quiz.currentStartTimestamp || -1;
    this._currentQuestionIndex = typeof quiz.currentQuestionIndex !== 'undefined' ? quiz.currentQuestionIndex : -1;
    this._privateKey = quiz.privateKey;
    this._readingConfirmationRequested = !!quiz.readingConfirmationRequested;
    this._visibility = quiz.visibility;
    this._description = quiz.description;
176
    this._exchangeName = encodeURI(`quiz_${quiz.name}`);
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  }

  public setInactive(): void {
    clearInterval(this._dropEmptyQuizSettings.intervalInstance);

    DbDAO.updateOne(DbCollection.Quizzes, { _id: this.id }, { state: QuizState.Inactive });
    DbDAO.deleteMany(DbCollection.Members, { currentQuizName: this.name });

    AMQPConnector.channel.publish('global', '.*', Buffer.from(JSON.stringify({
      status: StatusProtocol.Success,
      step: MessageProtocol.SetInactive,
      payload: {
        quizName: this.name,
      },
    })));
192
  }
193

194 195
  public async onMemberAdded(member: MemberEntity): Promise<void> {
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
196 197 198
      status: StatusProtocol.Success,
      step: MessageProtocol.Added,
      payload: { member: member.serialize() },
199
    })));
200 201
  }

202 203
  public async onMemberRemoved(member: MemberEntity): Promise<void> {
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
204 205 206
      status: StatusProtocol.Success,
      step: MessageProtocol.Removed,
      payload: { name: member.name },
207
    })));
208 209 210
  }

  public onRemove(): void {
211
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
212 213
      status: StatusProtocol.Success,
      step: MessageProtocol.Closed,
214
    })));
215
    AMQPConnector.channel.deleteExchange(this._exchangeName);
216 217 218
  }

  public reset(): void {
219
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
220 221
      status: StatusProtocol.Success,
      step: MessageProtocol.Reset,
222
    })));
223
    clearTimeout(this._quizTimerInterval);
224 225
  }

226
  public stop(): void {
227
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
228 229
      status: StatusProtocol.Success,
      step: MessageProtocol.Stop,
230
    })));
231 232
    this.currentStartTimestamp = -1;
    clearTimeout(this._quizTimerInterval);
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
  public addQuestion(question: AbstractQuestionEntity, index: number = -1): void {
    if (index === -1 || index >= this.questionList.length) {
      this.questionList.push(question);
    } else {
      this.questionList.splice(index, 0, question);
    }
  }

  public removeQuestion(index: number): void {
    if (index < 0 || index > this.questionList.length) {
      throw new Error('Invalid argument list for QuestionGroup.removeQuestion');
    }
    this._questionList.splice(index, 1);
  }

  public serialize(): IQuizSerialized {
    return {
      id: this.id.toHexString(),
      name: this.name,
      questionList: this.questionList.map((question: AbstractQuestionEntity) => question.serialize()),
      sessionConfig: this.sessionConfig.serialize(),
      expiry: this.expiry,
      state: this.state,
      currentStartTimestamp: this.currentStartTimestamp,
      currentQuestionIndex: this.currentQuestionIndex,
      privateKey: this.privateKey,
      readingConfirmationRequested: this.readingConfirmationRequested,
      visibility: this.visibility,
      description: this.description,
    };
  }

  public isValid(): boolean {
    let questionListValid = this.questionList.length > 0;
    this.questionList.forEach((question: AbstractQuestionEntity) => {
      if (questionListValid && !question.isValid()) {
        questionListValid = false;
      }
    });
    return questionListValid;
  }

  public addDefaultQuestion(index: number = -1, type: QuestionType.SingleChoiceQuestion): void {
    if (typeof index === 'undefined' || index === -1 || index >= this.questionList.length) {
      index = this.questionList.length;
    }
    const questionItem = getQuestionForType(type, {
      hashtag: this.name,
      questionText: '',
      questionIndex: index,
      timer: 40,
      startTime: 0,
      answerOptionList: [],
    });
    this.addQuestion(questionItem, index);
  }

  public nextQuestion(): number {
    const nextIndex = this._currentQuestionIndex + 1;
    if (nextIndex > this.questionList.length) {
      return -1;
    }
    this._currentQuestionIndex = nextIndex;

299
    DbDAO.updateOne(DbCollection.Quizzes, { _id: this.id }, { currentQuestionIndex: nextIndex });
300

301
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
302 303 304 305 306
      status: StatusProtocol.Success,
      step: MessageProtocol.NextQuestion,
      payload: {
        nextQuestionIndex: nextIndex,
      },
307
    })));
308 309 310 311 312 313 314 315

    return nextIndex;
  }

  public removeMember(name: string): Promise<DeleteWriteOpResultObject> {
    return DbDAO.deleteOne(DbCollection.Members, { name });
  }

316
  public startNextQuestion(): void {
317
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
318 319
      status: StatusProtocol.Success,
      step: MessageProtocol.Start,
320
      payload: {},
321
    })));
322 323

    this._quizTimer = this._questionList[this._currentQuestionIndex].timer;
324
    if (this._quizTimer <= 0) {
325 326
      return;
    }
327

328 329 330
    if (this._quizTimerInterval) {
      clearInterval(this._quizTimerInterval);
    }
331 332
    this._quizTimerInterval = setInterval(() => {
      this._quizTimer--;
333
      AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
334 335 336 337 338
        status: StatusProtocol.Success,
        step: MessageProtocol.Countdown,
        payload: {
          value: this._quizTimer,
        },
339
      })));
340 341 342

      if (this._quizTimer <= 0) {
        clearInterval(this._quizTimerInterval);
343
        DbDAO.updateOne(DbCollection.Quizzes, { _id: this.id }, { currentStartTimestamp: -1 });
344 345 346
      }

    }, 1000);
347 348 349 350
  }

  public requestReadingConfirmation(): void {
    this._readingConfirmationRequested = true;
351
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
352 353 354
      status: StatusProtocol.Success,
      step: MessageProtocol.ReadingConfirmationRequested,
      payload: {},
355
    })));
356 357 358
  }

  public updatedMemberResponse(payload: object): void {
359
    AMQPConnector.channel.publish(this._exchangeName, '.*', Buffer.from(JSON.stringify({
360 361 362
      status: StatusProtocol.Success,
      step: MessageProtocol.UpdatedResponse,
      payload,
363 364
    })));

365
    if (MemberDAO.getMembersOfQuiz(this.name).every(nick => {
366 367 368
      const val = nick.responses[this.currentQuestionIndex].value;
      return typeof val === 'number' ? val > -1 : val.length > 0;
    })) {
369 370 371 372 373
      if (this._quizTimer) {
        this._quizTimer = 1;
      } else {
        DbDAO.updateOne(DbCollection.Quizzes, { _id: this.id }, { currentStartTimestamp: -1 });
      }
374
    }
375
  }
376 377 378 379 380 381 382 383 384 385

  private checkExistingConnection(): void {
    const reqOptions: http.RequestOptions = {
      protocol: settings.amqp.managementApi.protocol,
      host: settings.amqp.managementApi.host,
      port: settings.amqp.managementApi.port,
      path: `/api/exchanges/${encodeURIComponent(settings.amqp.vhost)}/quiz_${encodeURIComponent(encodeURIComponent(this.name))}/bindings/source`,
      auth: `${settings.amqp.managementApi.user}:${settings.amqp.managementApi.password}`,
    };

386
    (settings.amqp.managementApi.protocol === 'https:' ? https : http).get(reqOptions, response => {
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
      let data = '';

      response.on('data', (chunk) => {
        data += chunk;
      });

      response.on('end', () => {
        const parsedData = JSON.parse(data);
        if (Array.isArray(parsedData) && parsedData.length) {
          this._dropEmptyQuizSettings.isEmpty = false;
          return;
        }

        if (this._dropEmptyQuizSettings.isEmpty) {
          this.setInactive();
          return;
        }

        this._dropEmptyQuizSettings.isEmpty = true;
      });
    });
  }
409
}