-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrooms.js
More file actions
102 lines (83 loc) · 2.53 KB
/
rooms.js
File metadata and controls
102 lines (83 loc) · 2.53 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
const Kodik = require("./controllers/kodik");
const throttle = require("lodash/throttle");
const constants = require("./constants");
class Room {
constructor() {
this._rooms = {};
this.cleanUnusedRooms = throttle(this._cleanUnusedRooms, constants.CONFIG.ROOM.CLEAN_UNUSED_TIMEOUT);
}
_cleanUnusedRooms() {
Object.keys(this._rooms).forEach((key) => {
const room = this.getRoomInfo(key);
if (room) {
// When created time more than 1 minutes, but still have 0 users
// Can be useful when users finish to watch a movie and left from room
const shouldBeDeleted =
room.link === null ||
(room.users <= 0 && new Date() - room.timestamp > constants.CONFIG.ROOM.PROTECT_FROM_DELETING);
if (shouldBeDeleted) {
delete this._rooms[key];
}
}
});
}
_getNewRoomIndex() {
const roomsId = Object.keys(this._rooms);
if (roomsId.length === 0) {
return 1;
}
const lastRoomId = parseInt(roomsId[roomsId.length - 1]);
return lastRoomId + 1;
}
async addRoom(roomId, kinopoiskId) {
this.cleanUnusedRooms();
const response = await Kodik.search(kinopoiskId);
const item = response.results[0];
this._rooms[roomId] = {
link: item ? item.link : null,
users: 0,
timestamp: new Date(),
};
return {
roomId,
};
}
async createRoom(kinopoiskID) {
if (kinopoiskID) {
this.cleanUnusedRooms();
const roomId = this._getNewRoomIndex();
return await this.addRoom(roomId, kinopoiskID);
}
return null;
}
getRooms() {
this.cleanUnusedRooms();
return this._rooms;
}
getRoomInfo(roomId) {
this.cleanUnusedRooms();
return this._rooms[roomId];
}
addUserToRoom(roomId) {
const room = this.getRoomInfo(roomId);
if (room) {
room.users++;
}
}
removeUserFromRoom(roomId) {
const room = this.getRoomInfo(roomId);
if (room) {
if (room.users > 0) {
room.users--;
}
}
}
setRoomEpisode(roomId, season, episode) {
const room = this.getRoomInfo(roomId);
if (room) {
room.season = season;
room.episode = episode;
}
}
}
module.exports = new Room();