forked from zerodytrash/TikTok-Chat-Reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
581 lines (522 loc) · 22.2 KB
/
server.js
File metadata and controls
581 lines (522 loc) · 22.2 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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
require('dotenv').config();
// thinking about trying to bring some sort of framework in here..
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const { TikTokConnectionWrapper, getGlobalConnectionCount } = require('./connectionWrapper');
const { clientBlocked } = require('./limiter');
//const { updateUsernames, readUsernames } = require('./tt-usernames');
// https://www.atatus.com/blog/read-write-a-json-file-with-node-js/
// ^^ Possible alternative use for reading / writing files
const editJsonFile = require("edit-json-file");
const {google} = require('googleapis');
const fs = require('fs');
const path = require('path');
//! used for finding files in the sounds folder
//const {fs,writefile} = require('fs');
// setting up google apis
// https://medium.com/@shkim04/beginner-guide-on-google-sheet-api-for-node-js-4c0b533b071a
// https://github.com/googleworkspace/browser-samples/tree/main/sheets/snippets
const app = express();
const httpServer = createServer(app);
app.use(express.urlencoded({ extended: true }));
let file = editJsonFile(`${__dirname}/public/config.json`);
let toDoData = editJsonFile(`${__dirname}/toDoData.json`);
// Config güncelleme ayarını .env dosyasından oku
const enableConfigUpdate = process.env.ENABLE_CONFIG_UPDATE === 'true';
// Enable cross origin resource sharing
const io = new Server(httpServer, {
cors: {
origin: '*'
}
});
let isLoggedIn = false, loggedInRow = -1, userRow = {};
// Google Sheets bağlantısı için güvenlik kontrolü
let googleSheetsEnabled = false;
let auth = null;
// keys.json dosyasının varlığını ve geçerliliğini kontrol et
async function initializeGoogleSheets() {
try {
const keysPath = path.join(__dirname, 'keys.json');
// Önce dosyanın varlığını kontrol et
if (!fs.existsSync(keysPath)) {
console.log('keys.json dosyası bulunamadı. Google Sheets özellikleri devre dışı bırakıldı.');
console.log('Google Sheets kullanmak için keys.example.json dosyasını keys.json olarak kopyalayın ve gerekli bilgileri girin.');
return false;
}
// Dosya içeriğini kontrol et
const keysContent = fs.readFileSync(keysPath, 'utf8');
const keysData = JSON.parse(keysContent);
// Gerekli alanların varlığını kontrol et
if (!keysData.private_key || !keysData.client_email) {
console.log('keys.json dosyasında geçerli Google Cloud kimlik bilgileri bulunamadı.');
console.log('Lütfen keys.json dosyasının doğru yapılandırıldığından emin olun.');
return false;
}
// Google Sheets API bağlantısını dene
auth = new google.auth.GoogleAuth({
keyFile: "keys.json",
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
// Bağlantıyı test et
const authClient = await auth.getClient();
const testAuth = google.sheets({ version: "v4", auth: authClient });
console.log('Google Sheets API başarıyla etkinleştirildi ve bağlantı test edildi.');
return true;
} catch (error) {
console.error('Google Sheets API başlatılırken hata oluştu:', error.message);
console.log('Google Sheets özellikleri devre dışı bırakıldı, ancak sunucu çalışmaya devam edecek.');
console.log('Hata detayı:', error.stack);
return false;
}
}
// Başlangıçta Google Sheets'i başlat
initializeGoogleSheets().then(success => {
googleSheetsEnabled = success;
}).catch(error => {
console.error('Google Sheets başlatma sırasında beklenmedik hata:', error);
googleSheetsEnabled = false;
});
// Google Sheets API için güvenli çağrı fonksiyonu
async function safeGoogleSheetsCall(functionName, callback) {
if (!googleSheetsEnabled) {
console.log(`Google Sheets çağrısı atlandı (${functionName}): API etkin değil`);
return { success: false, error: 'Google Sheets API etkin değil' };
}
try {
const result = await callback();
return { success: true, data: result };
} catch (error) {
console.error(`Google Sheets çağrısı başarısız oldu (${functionName}):`, error.message);
// Hata durumunda error objesi döndürerek uygulamanın devam etmesini sağla
return { success: false, error: error.message };
}
}
io.on('connection', (socket) => {
let tiktokConnectionWrapper;
console.info('New connection from origin', socket.handshake.headers['origin'] || socket.handshake.headers['referer']);
// Client'tan gelen config güncelleme ayarı isteğini işle
socket.on('getConfigUpdateSetting', () => {
socket.emit('configUpdateSetting', {
enableConfigUpdate: enableConfigUpdate
});
});
socket.on('setUniqueId', (uniqueId, options) => {
// 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 => socket.emit('roomUser', msg));
tiktokConnectionWrapper.connection.on('member', msg => socket.emit('member', msg));
tiktokConnectionWrapper.connection.on('chat', (msg) => {
// lets tranalate before it even comes to the front end,
// instead of sending to front, to back, and again to the front.
// thats too many, come on now
socket.emit('chat', msg)
});
tiktokConnectionWrapper.connection.on('gift', msg => socket.emit('gift', msg));
tiktokConnectionWrapper.connection.on('social', msg => socket.emit('social', msg));
tiktokConnectionWrapper.connection.on('like', msg => socket.emit('like', msg));
tiktokConnectionWrapper.connection.on('questionNew', (msg) => {
socket.emit('questionNew', msg);
toDoData.append('toDoData.questionNew', data)
toDoData.save();
})
tiktokConnectionWrapper.connection.on('linkMicBattle', msg => socket.emit('linkMicBattle', msg));
tiktokConnectionWrapper.connection.on('linkMicArmies', msg => socket.emit('linkMicArmies', msg));
tiktokConnectionWrapper.connection.on('liveIntro', msg => socket.emit('liveIntro', msg));
//tiktokConnectionWrapper.connection.on('emote', msg => socket.emit('emote', msg));
tiktokConnectionWrapper.connection.on('envelope', (msg) => {
socket.emit('envelope', msg);
toDoData.append('toDoData.envelope', msg)
toDoData.save();
})
tiktokConnectionWrapper.connection.on('subscribe', (msg) => {
socket.emit('subscribe', msg);
toDoData.append('toDoData.subscribe', msg)
toDoData.save();
})
//tiktokConnectionWrapper.connection.on('rawData', (messageTypeName, binary) => socket.emit('rawData', messageTypeName));
//console.log(messageTypeName, binary);
});
//socket.on("upload", (file, callback) => {
// console.log(file); // <Buffer 25 50 44 ...>
// // save the content to the disk, for example
// writeFile("sounds/", file, (err) => {
// console.log({ message: err ? "failure" : "success" });
// });
//});
socket.on('disconnect', () => {
if (tiktokConnectionWrapper) {
tiktokConnectionWrapper.disconnect();
}
});
socket.on('userUpdateSavedHosts', async (data) => {
const result = await safeGoogleSheetsCall('userUpdateSavedHosts', async () => {
// Google Sheets işlemi burada yapılacak
if(typeof loggedInRow !== undefined){
console.log('based on when we logged in')
console.log('user row = '+loggedInRow)
console.log(data)
console.log('/ userUpdateSavedHosts')
}
return { status: 'processed' };
});
if (!result.success) {
socket.emit('error', `Google Sheets hatası: ${result.error}`);
}
/*
@ from async above
^ data.body = {
#? "mimeType": "application/json",
^ "text": "{\n\t\"values\": [\n\t\t[\"patchapi\"]\n\t]\n} ^ }
$ id = data.rowId
$ values = data.body
!googleSheets.spreadsheets.values.update({
! auth,
! spreadsheetId,
! range: `Sheet1!A${id}`, // {id} = the row # i believe?
! valueInputOption: "RAW",
! resource: {
! values: values
! }
!})
*/
})
// data.place, data.vals
// google sheets
socket.on('userSaveNote', async (dat)=>{
const result = await safeGoogleSheetsCall('userSaveNote', async () => {
//Auth client Object
const authClientObject = await auth.getClient();
//Google sheets instance
const googleSheetsInstance = google.sheets({ version: "v4", auth: authClientObject });
const spreadsheetId = process.env.GOOGLE_USER_SHEET_ID //process.env.GOOGLE_SHEET_ID;
const userNotes = await googleSheetsInstance.spreadsheets.values.get({
auth, //auth object
spreadsheetId, //spreadsheet id
range: "Notes" //!A1:B1:C1:D1:E1:F1:G1:H1:I1:J1:K1:L1", //sheet name and range of cells
});
let noteCount = userNotes.data.values.length, n, userNotesRow = {};
for(n=0;n<noteCount;n++){
if(userNotes.data.values[n][0] == userRow.email){
userNotesRow = {
i : n,
e : userRow.email,
rec : JSON.parse(userNotes.data.values[n][2])
}
break;
}
}
if(userNotesRow.length == 0){
// add it
} else {
// update it
let totalNotes = userNotesRow.rec.length, r
for(r=0;r<totalNotes;r++){
if(userNotesRow.rec[r].qId == dat.qId){
}
}
googleSheetsInstance.spreadsheets.values.update({
auth,
spreadsheetId,
range: `Notes!A${userNotesRow.i}`, // {id} = the row # i believe?
valueInputOption: "RAW",
resource: {
values: [[
userNotesRow.row[0],
Intl.DateTimeFormat(this.locale, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric"
}).format(data.timestamp),
updatedNotes
]]
}
})
}
return { status: 'note saved' };
});
if (!result.success) {
socket.emit('error', `Not kaydedilirken hata oluştu: ${result.error}`);
}
})
socket.on('userLogin', async (data) => {
const result = await safeGoogleSheetsCall('userLogin', async () => {
//Auth client Object
const authClientObject = await auth.getClient();
//Google sheets instance
const googleSheetsInstance = google.sheets({ version: "v4", auth: authClientObject });
const spreadsheetId = process.env.GOOGLE_USER_SHEET_ID //process.env.GOOGLE_SHEET_ID;
const userList = await googleSheetsInstance.spreadsheets.values.get({
auth, //auth object
spreadsheetId, //spreadsheet id
range: "Sheet1" //!A1:B1:C1:D1:E1:F1:G1:H1:I1:J1:K1:L1", //sheet name and range of cells
});
let allUsers = userList.data.values.length, b
, found = false
, userRowData = {}, newSettingsMenu = `
<li><h6 class="dropdown-header">User Settings</h6></li>
<li><a class="dropdown-item" href="#">Saved Hosts</a></li>
<li><a class="dropdown-item" href="#"></a></li>
`
for(b=1;b<allUsers;b++){
if(userList.data.values[b][0] == data.email){
found = true
if(userList.data.values[b][2] == data.pass){
isLoggedIn = true
userRow = userList.data.values[b]
loggedInRow = b
userRowData = {
email: userRow[0],
name: userRow[1],
//created: userRow[3],
//lastLogin: userRow[4],
sheetId: userRow[5],
pExpires: userRow[6],
userList : userRow[7],
sounds : userRow[8],
keyFile : userRow[9]
};
}
// check password
break;
}
}
let respond = found == true && isLoggedIn == true ? 'ok' : 'fail'
return {
respond,
userRowData,
newSettingsMenu
};
});
if (result.success) {
socket.emit('loginTry', {
r : result.data.respond,
info : result.data.userRowData,
replaceForm : result.data.newSettingsMenu
});
} else {
socket.emit('loginTry', {
r : 'fail',
info : {},
replaceForm : '<li><h6 class="dropdown-header">Google Sheets erişim hatası</h6></li>'
});
}
})
socket.on('addGift', async (data) => {
const result = await safeGoogleSheetsCall('addGift', async () => {
//console.log(data)
//Auth client Object
const authClientObject = await auth.getClient();
//Google sheets instance
const googleSheetsInstance = google.sheets({ version: "v4", auth: authClientObject });
// spreadsheet id
const spreadsheetId = process.env.GOOGLE_SHEET_ID //process.env.GOOGLE_SHEET_ID;
await googleSheetsInstance.spreadsheets.values.append({
auth, //auth object
spreadsheetId, //spreadsheet id
range: "Sheet1", //!A1:B1:C1:D1:E1:F1:G1:H1:I1:J1:K1:L1", //sheet name and range of cells
valueInputOption: "USER_ENTERED", // The information will be passed according to what the user passes in as date, number or text
resource: {
values: [[
//data.timestamp.toLocaleDateString("en-US"),
Intl.DateTimeFormat(this.locale, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric"
}).format(data.timestamp),
data.userId,
data.uniqueId,
data.nickname,
'=IMAGE("'+data.profilePictureUrl+'",2)',
data.giftId,
data.giftName,
'=IMAGE("'+data.giftPictureUrl+'",2)',
data.repeatCount,
data.diamondCount,
data.receiverUser,
data.receiverUserId
]] //[[dat, username, nickname, coinsSent, userId]]
},
});
return { status: 'gift saved' };
});
if (!result.success) {
socket.emit('error', `Hediye kaydedilirken hata oluştu: ${result.error}`);
}
})
var sounds = fs.readdirSync('public/sounds/');
socket.emit('soundDirectory', {
r : 'done',
files : sounds
});
socket.on('saveGiftSound', async (data) => {
let msg
if(data.gift == '' || data.sound == ''){
// error
msg = 'Gift or Sound not found.'
} else {
file.set('sounds.gift.'+data.gift, data.sound)
file.save();
msg = 'Sound had been saved for gift - '+data.gift+'.'
}
socket.emit('saveGiftSound', {
r : `<div class="alert alert-secondary mt-3" role="alert">${msg}</div>`
});
})
socket.on('removeGiftSound', async (data) => {
file.set('sounds.gift.'+data.gift, data.sound)
file.save();
msg = 'Gift sound had been removed for - '+data.gift+'.'
socket.emit('removeGiftSound', {
r : `<div class="alert alert-secondary mt-3" role="alert">${msg}</div>`
});
})
socket.on('toDoData', async (data) => {
toDoData.append('toDoData.'+data.socket, data.data)
toDoData.save();
socket.emit('toDoData', {
r : `Saved to-do Data!`
});
})
socket.on('deleteNote', async (data) => {
let find = data.name, list = file.get('notes'),
list_len = list.length, i, ob = []
file.unset('notes')
console.log('find -- '+find+' --- find')
console.log(list_len+' total notes')
for(i=0;i<list_len;i++){
if(list[i].name == find){
// do nothing to remove it
console.log(list[i].name+' = '+find)
} else {
ob.push(list[i])
console.log(list[i])
console.log('--- list['+i+'] ---')
file.append('notes', list[i])
}
}
//file.set('notes', ob)
file.save();
socket.emit('deleteNote', {
r : 'Note removed!'
});
})
socket.on('saveNote', async (data) => {
let msg = ''
if(data.id == 'new'){
//file.append('notes.'+data.name, data.note)
file.append('notes', {name : data.name, note : data.note})
msg = 'New Note Saved!'
} else {
let find = data.id, list = file.get('notes'),
list_len = list.length, i, ob = []
//console.log(list)
//file.set('notes', undefined)
//console.log(find)
//console.log('----find')
////console.log('remove - '+dname)
for(i=0;i<list_len;i++){
if(list[i].name == find){
ob.push({name : data.name, note : data.note})
} else {
ob.push(list[i])
}
}
console.log(ob)
file.set('notes', ob)
//file.append('notes.'+data.name, data.note)
msg = 'Note Updated!'
}
file.save();
socket.emit('saveNote', {
r : msg
});
})
socket.on('addToNames', async (data) => {
let dname = data.name, json = file.get('names')
// Sadece config güncellemesi etkinse config.json'a yaz
if (enableConfigUpdate) {
if(json.includes(dname) == false){
file.append('names', dname)
file.save();
}
}
// Her durumda client'a bildir
socket.emit('addToNames', {
r : 'done',
name : dname
});
})
socket.on('removeNames', async (data) => {
let dname = data.name, list = file.get('names'),
list_len = list.length, i, ob = []
// Sadece config güncellemesi etkinse config.json'dan sil
if (enableConfigUpdate) {
file.set('names', undefined)
for(i=0;i<list_len;i++){
if(ob.includes(dname) || list[i] == dname){
//console.log('found -- '+list[i])
} else {
//console.log('--'+list[i])
ob.push(list[i])
}
}
file.set('names', ob.sort().reverse())
file.save();
}
// Her durumda client'a bildir
socket.emit('removeNames', {
r : 'done',
name : dname
});
})
//socket.on('readUsernames', async (data) => {
// //response.send(readUsernames())
// socket.emit('readUsernames', {
// names : readUsernames()
// });
//})
});
// Emit global connection statistics
setInterval(() => {
io.emit('statistic', { globalConnectionCount: getGlobalConnectionCount() });
}, 5000)
// Serve frontend files
app.use(express.static('public'));
// Start http listener
const port = process.env.PORT || 8081;
httpServer.listen(port);
console.info(`Server running! Please visit http://localhost:${port}`);