-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
285 lines (255 loc) · 10.2 KB
/
app.js
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
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const _ = require('lodash');
const moment = require('moment');
const http = require('http');
const socketIO = require('socket.io');
const bodyParser = require('body-parser');
const cors = require('cors');
const { TikTokConnectionWrapper, getGlobalConnectionCount } = require('./connectionWrapper');
const { clientBlocked } = require('./limiter');
const db = require('./db');
const ailatrieuphuControl = require('./controllers/ailatrieuphuController');
const liveSession = require('./models/liveSession');
const User = require('./models/user');
const SessionGame = require('./models/sessionGame');
// const tiktokConnector = require('./tiktok-connector');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use(express.static('client'));
const server = http.createServer(app);
const init = async () => {
await Promise.all([
db.init(),
]);
}
const io = socketIO(server, {
cors: {
origin: 'https://www.tiktok.com',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}
});
io.on('connection', (socket) => {
let tiktokConnectionWrapper;
console.info('New connection from origin', socket.handshake.headers['origin'] || socket.handshake.headers['referer']);
socket.on('setUniqueId', (uniqueId, options) => {
console.log({options})
// return;
// Prohibit the client from specifying these options (for security reasons)
if (typeof options === 'object' && options) {
delete options.requestOptions;
delete options.websocketOptions;
} else {
options = {};
}
// Session ID in .env file is optional
if (process.env.SESSIONID) {
options.sessionId = process.env.SESSIONID;
console.info('Using SessionId');
}
// Check if rate limit exceeded
if (process.env.ENABLE_RATE_LIMIT && clientBlocked(io, socket)) {
socket.emit('tiktokDisconnected', 'You have opened too many connections or made too many connection requests. Please reduce the number of connections/requests or host your own server instance. The connections are limited to avoid that the server IP gets blocked by TokTok.');
return;
}
// Connect to the given username (uniqueId)
try {
tiktokConnectionWrapper = new TikTokConnectionWrapper(uniqueId, options, true);
tiktokConnectionWrapper.connect();
} catch (err) {
socket.emit('tiktokDisconnected', err.toString());
return;
}
// Redirect wrapper control events once
tiktokConnectionWrapper.once('connected', state => socket.emit('tiktokConnected', state));
tiktokConnectionWrapper.once('disconnected', reason => socket.emit('tiktokDisconnected', reason));
// Notify client when stream ends
tiktokConnectionWrapper.connection.on('streamEnd', () => socket.emit('streamEnd'));
// Redirect message events
tiktokConnectionWrapper.connection.on('roomUser', msg => socketReceiveMessage('roomUser', msg, options, socket));
tiktokConnectionWrapper.connection.on('member', msg => socketReceiveMessage('member', msg, options, socket));
tiktokConnectionWrapper.connection.on('chat', msg => socketReceiveMessage('chat', msg, options, socket));
tiktokConnectionWrapper.connection.on('gift', msg => socketReceiveMessage('gift', msg, options, socket));
tiktokConnectionWrapper.connection.on('social', msg => socketReceiveMessage('social', msg, options, socket));
tiktokConnectionWrapper.connection.on('like', msg => socketReceiveMessage('like', msg, options, socket));
tiktokConnectionWrapper.connection.on('questionNew', msg => socketReceiveMessage('questionNew', msg, options, socket));
tiktokConnectionWrapper.connection.on('linkMicBattle', msg => socketReceiveMessage('linkMicBattle', msg, options, socket));
tiktokConnectionWrapper.connection.on('linkMicArmies', msg => socketReceiveMessage('linkMicArmies', msg, options, socket));
tiktokConnectionWrapper.connection.on('liveIntro', msg => socketReceiveMessage('liveIntro', msg, options, socket));
tiktokConnectionWrapper.connection.on('emote', msg => socketReceiveMessage('emote', msg, options, socket));
tiktokConnectionWrapper.connection.on('envelope', msg => socketReceiveMessage('envelope', msg, options, socket));
tiktokConnectionWrapper.connection.on('subscribe', msg => socketReceiveMessage('subscribe', msg, options, socket));
});
socket.on('send_coin', async (data) => {
let sessionName = _.get(data, 'userData.liveSession');
let user = await User.findOne({ username: _.get(data, 'winner.username')});
let sessionGame = await SessionGame.findOne({
userId: (new mongoose.Types.ObjectId(_.get(user, '_id'))),
sessionName,
});
let dataSess = {
score: parseInt(_.get(data, 'coinReceived')) + _.get(sessionGame, 'score'),
}
await SessionGame.updateData({ _id: _.get(sessionGame, '_id'), sessionName }, dataSess, async (data) => {
const winner = await SessionGame.getLimitWinner({
sessionName,
}, 30);
socket.emit(`${_.get(data, 'userData.channel')}-ranking`, {
ranking: winner,
sessionWinner: null,
});
});
});
socket.on('disconnect', () => {
if (tiktokConnectionWrapper) {
tiktokConnectionWrapper.disconnect();
}
});
});
function socketReceiveMessage(type, data, options, socket) {
if (type === 'chat') {
socket.emit(`${_.get(options, 'channel')}-chat`, data);
} else if (type === 'like') {
socket.emit(`${_.get(options, 'channel')}-like`, data);
} else if (type === 'roomUser') {
socket.emit(`${_.get(options, 'channel')}-views`, data);
} else if (type === 'gift') {
socket.emit(`${_.get(options, 'channel')}-gift`, data);
}
switch (type) {
case 'like':
addScore({
username: _.get(data, 'uniqueId'),
name: _.get(data, 'nickname'),
avatar: _.get(data, 'profilePictureUrl')
}, { channel: _.get(options, 'channel'), sessionName: _.get(options, 'liveSession'), score: Math.round(data.likeCount / 100) }, 'like', socket)
break;
// case 'follow':
// addScore({
// username: _.get(data, 'uniqueId'),
// name: _.get(data, 'nickname'),
// avatar: _.get(data, 'profilePictureUrl')
// }, { channel: _.get(options, 'channel'), sessionName: _.get(options, 'liveSession'), score: 5 }, 'follow', socket);
// break;
// case 'share':
// addScore({
// username: _.get(data, 'uniqueId'),
// name: _.get(data, 'nickname'),
// avatar: _.get(data, 'profilePictureUrl')
// }, { channel: _.get(options, 'channel'), sessionName: _.get(options, 'liveSession'), score: 1 }, 'share', socket);
// break;
case 'member':
addScore({
username: _.get(data, 'uniqueId'),
name: _.get(data, 'nickname'),
avatar: _.get(data, 'profilePictureUrl')
}, { channel: _.get(options, 'channel'), sessionName: _.get(options, 'liveSession'), score: 1 }, 'member', socket);
break;
// case 'gift':
// addScore({
// username: _.get(data, 'uniqueId'),
// name: _.get(data, 'nickname'),
// avatar: _.get(data, 'profilePictureUrl')
// }, { channel: _.get(options, 'channel'), sessionName: _.get(options, 'liveSession'), score: data.diamondCount }, 'gift', socket)
// break;
default:
break;
}
}
async function addScore({ username, name, avatar }, { channel, sessionName, score }, type, socket) {
let user = await User.findOne({ username });
if (!user) {
user = await User.add({
name, username, avatar,
});
}
let sessionGame = await SessionGame.findOne({
userId: (new mongoose.Types.ObjectId(_.get(user, '_id'))),
sessionName,
});
if (!sessionGame) {
sessionGame = await SessionGame.add({
channel, userId: _.get(user, '_id'),
score,
sessionName,
});
} else {
let dataSess = {
score: score + _.get(sessionGame, 'score'),
}
if (type === 'follow') {
if (_.get(sessionGame, 'followed')) {
return;
}
dataSess['followed'] = true;
}
if (type === 'member') {
if (_.get(sessionGame, 'isMember')) {
return;
}
dataSess['isMember'] = true;
}
await SessionGame.updateData({ _id: _.get(sessionGame, '_id'), sessionName }, dataSess, async (data) => {});
}
console.log({username, type, score})
const winner = await SessionGame.getLimitWinner({
sessionName,
}, 30);
socket.emit(`${channel}-ranking`, {
ranking: winner,
sessionWinner: null,
});
}
// Emit global connection statistics
// setInterval(() => {
// io.emit('statistic', { globalConnectionCount: getGlobalConnectionCount() });
// }, 5000)
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client/livetream.html');
});
app.get('/to', (req, res) => {
res.sendFile(__dirname + '/client/to.html');
});
app.get('/chat', (req, res) => {
res.sendFile(__dirname + '/client/chat.html');
});
app.get('/setting', (req, res) => {
res.sendFile(__dirname + '/client/setting.html');
});
app.get('/ailatrieuphu', (req, res) => {
res.sendFile(__dirname + '/client/ailatrieuphu.html');
});
app.get('/api/get-ranking-altp', async (req, res) => {
const session = _.get(req, 'query.session');
try {
const winner = await SessionGame.getLimitWinner({ sessionName: session }, 18);
res.send(winner);
} catch (error) {
console.log({ error })
}
});
app.get('/api/get-ranking', async (req, res) => {
const session = _.get(req, 'query.session');
try {
const winner = await SessionGame.getLimitWinner({ sessionName: session }, 30);
res.send(winner);
} catch (error) {
console.log({ error })
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
init();
});