-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
707 lines (614 loc) · 19.5 KB
/
Copy pathapi.js
File metadata and controls
707 lines (614 loc) · 19.5 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
const axios = require('axios');
const config = require('./db').config; // config lida do TXT
const { requisitionHolyricsHTML } = require('./reqHTML');
const striptags = require('striptags');
const { response } = require('express');
// --------- Variáveis ---------
// Variáveis Global
global.list_media = '';
global.slide_atual = null;
global.presentation_active = false;
global.list_updated = false;
global.id_current = '0';
global.type_current = null;
global.pos_id = -1;
global.isPrevious = false;
global.ID_intervalChkPresent;
global.flag_verse_unico = false;
global.tipos_permitidos = ['song', 'text', 'image', 'announcement', 'verse', 'video'];
global.tipos_somente_exec = ['audio', 'api', 'script'];
if (!config) {
console.log("#########");
console.log("Arquivo config.txt não encontrado! Preencha-o com:\n\nIP={IP_HOLYRICS}\nport=8091\ntoken={TOKEN_HOLYRICS}\n");
console.log("#########");
throw new Error("Arquivo config.txt não encontrado!");
}
// criando um objeto de solicitação simulado
const req_local = {
params: {
ip: config.ip,
token: config.token
},
body: {
data: 'example'
}
};
// criando um objeto de resposta simulado
const res_local = {
data: null,
status: null,
send: function (response) {
this.data = response;
},
status: function (statusCode) {
this.status = statusCode;
return this;
}
};
// Gera a url de comunicação com o Holyrics
// Exemplo: http://192.168.100.5:8091/api/GetMediaPlaylist?token=MXdskASO1edgBsTG
function generate_url(content) {
return `http://${config.ip}:${config.port}/api/` + content + `?token=${config.token}`;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// GetMediaPlaylist
async function getMediaPlaylist() {
return new Promise((resolve, reject) => {
const url = generate_url('GetMediaPlaylist');
axios.post(url, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
list_media = response.data.data;
list_updated = true;
//console.log(list_media);
// Verificar a posição do id atual
// for (let i = 0; i < Object.keys(list_media).length; i++) {
// if (list_media[i].id == id_current) {
// pos_id = i;
// break;
// }
// }
pos_id = list_media.findIndex(item => item.id === id_current);
flag_verse_unico = false;
console.log("Playlist atualizada!");
resolve(response.data);
})
.catch(error => {
console.log(error);
reject(error);
});
});
}
async function changeSlide(req, res) {
const type = req.params.type;
const force_change = req.params.force_change;
console.log("Requisição " + type + " | Force Change: " + force_change);
// // ------- FORCE CHANGE -------
// if (force_change == 1) {
// await nextID();
// res.send({ status: "Chamando próxima presentation!", type: type_current });
// return;
// }
// else if (force_change == -1) {
// await previousID();
// res.send({ status: "Chamando presentation anterior!", type: type_current });
// return;
// }
// // -----------------------------
if (presentation_active) {
await SlideAtual();
//console.log(slide_atual);
if (slide_atual) { // TODO: VERSE retorna slide_atual Nulo
switch (type_current) {
case 'song':
case 'text':
// Próxima apresentação
if (slide_atual.slide_index == slide_atual.slide_total && type == 'next') {
await nextID();
res.send({ status: "Chamando próxima presentation!", type: type_current });
return;
}
// Apresentação anterior
else if (type == 'previous') {
if ((type_current == 'text' && slide_atual.slide_index == 1) ||
(type_current != 'text' && slide_atual.slide_index == 0)) {
console.log("previous aqui");
await previousID();
res.send({ status: "Chamando presentation anterior!", type: type_current });
return;
}
}
break;
case 'announcement':
case 'image':
if (slide_atual.slide_number == slide_atual.total_slides) {
if (slide_atual.total_slides > 1) { // p/ tratar Anúncio (TODOS) ou Anúncio (LISTA)
await closeCurrentPresentation();
res.send({ status: "Encerrando presentation!", type: type_current });
return;
}
if (type == 'next') {
await nextID();
res.send({ status: "Chamando próxima presentation!", type: type_current });
return;
} else if (type == 'previous') {
console.log("previous aqui");
await previousID();
res.send({ status: "Chamando presentation anterior!", type: type_current });
return;
}
}
break;
// case 'video':
// case 'audio':
// break;
case 'verse':
await waitForVerseChange(res, type);
return;
break;
case 'file':
if (list_media[pos_id].name.endsWith('.pptx')) {
if (slide_atual.slide_number == slide_atual.slide_total && type == 'next') {
await nextID();
res.send({ status: "Chamando próxima presentation!", type: type_current });
return;
}
if (slide_atual.slide_number == 1 && type == 'previous') {
console.log("previous aqui");
await previousID();
res.send({ status: "Chamando presentation anterior!", type: type_current });
return;
}
}
break;
default:
break;
}
}
}
res.send(await ActionNextorPrevious(type));
}
// Apagar res depois, usado em control_slide.js
async function ActionNextorPrevious(type) {
if (type == 'next')
url = generate_url('ActionNext');
else if (type == 'previous')
url = generate_url('ActionPrevious');
try {
const response = await axios.post(url, {
headers: {
'Content-Type': 'application/json'
}
});
response.data.type = type_current;
console.log(response.data);
return response.data;
} catch (error) {
console.log(error);
return error;
}
}
async function waitForVerseChange(res, type) {
dateHTML = await requisitionHolyricsHTML(true, 1); // Requisição para HTML do versiculo atual
verse = striptags(dateHTML.map.text);
resp = await ActionNextorPrevious(type);
tentativas = 0;
async function checkVerseChange() {
dateHTML_new = await requisitionHolyricsHTML(true, 1);
verse_new = striptags(dateHTML_new.map.text);
console.log(verse_new)
if (verse !== verse_new) {
console.log("Verse diferente");
res.send(resp);
} else if (tentativas > 6) {
console.log("Mais de 6 tentativas, mudando para a apresentação anterior/seguinte!");
if (type === 'next') {
await nextID();
res.send({ status: "Chamando próxima presentation!", type: type_current });
} else if (type === 'previous') {
console.log("previous aqui");
await previousID();
res.send({ status: "Chamando presentation anterior!", type: type_current });
}
return;
} else {
tentativas++;
setTimeout(checkVerseChange, 150);
}
}
checkVerseChange();
}
async function SlideAtual() {
url = generate_url('SlideAtual');
const data = {
isprevious: isPrevious,
type: type_current
};
return new Promise((resolve, reject) => {
axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
slide_atual = response.data.data;
isPrevious = false;
resolve();
})
.catch(error => {
console.log(error);
reject(error);
});
});
}
// Verificar próximo ID da list_media
async function nextID() {
//Fim da lista
if (pos_id + 1 == Object.keys(list_media).length) {
console.log("Chegou no final");
pos_id = -1;
presentation_active = false;
id_current = null;
type_current = null;
await closeCurrentPresentation();
}
else if (pos_id == -1) // Não iniciou nenhuma apresentação
{
console.log("Nenhuma apresentação armazenada");
}
else {
pos_id_ant = pos_id;
clearInterval(global.ID_intervalChkPresent);
do {
pos_id++;
id_current = list_media[pos_id].id;
type_current = list_media[pos_id].type;
console.log(type_current);
// Verifica se é um PowerPoint
if (type_current == 'file' && list_media[pos_id].name.endsWith('.pptx'))
break;
if (tipos_somente_exec.includes(type_current)) {
await MediaPlaylistAction(id_current);
await sleep(300);
}
}
while (!tipos_permitidos.includes(type_current) && (pos_id + 1) < Object.keys(list_media).length);
// Caso percorra toda a lista e não ache o próximo ID
if (!tipos_permitidos.includes(type_current) &&
!list_media[pos_id].name.endsWith('.pptx') &&
(pos_id + 1) >= Object.keys(list_media).length) {
console.log("Chegou ao FINAL da lista e não encontrou outra presentation!");
pos_id = -1;
presentation_active = false;
id_current = null;
type_current = null;
await closeCurrentPresentation();
return;
}
// Para fechar apresentação atual
if (type_current == 'video')
await closeCurrentPresentation();
// Iniciar apresentação do próximo id
console.log("Chamando próximo ID!");
console.log(id_current)
await MediaPlaylistAction(id_current);
//Cria novamente a chamada de checkPresentation
global.ID_intervalChkPresent =
setInterval(() => {
checkPresentationActive();
}, 1000);
}
}
// Verificar ID anterior da list_media
async function previousID() {
//Começo da lista
console.log(pos_id);
if (pos_id == 0) {
console.log("Começo da lista");
}
else if (pos_id == -1) // Não iniciou nenhuma apresentação
{
console.log("Nenhuma apresentação armazenada");
}
else {
clearInterval(global.ID_intervalChkPresent);
do {
pos_id--;
id_current = list_media[pos_id].id;
type_current = list_media[pos_id].type;
console.log(type_current);
// Verifica se é um PowerPoint
if (type_current == 'file' && list_media[pos_id].name.endsWith('.pptx'))
break;
if (tipos_somente_exec.includes(type_current)) {
await MediaPlaylistAction(id_current);
await sleep(300);
}
} while (!tipos_permitidos.includes(type_current) && pos_id > 0);
// Caso chegue ao começo da lista e não encontre outra presentation
if (!tipos_permitidos.includes(type_current) &&
!list_media[pos_id].name.endsWith('.pptx') &&
pos_id == 0) {
console.log("Chegou ao COMEÇO da lista e não encontrou outra presentation!");
return;
}
isPrevious = true;
// Para fechar apresentação atual
if (type_current == 'video')
await closeCurrentPresentation();
// Iniciar apresentação do id anterior
console.log("Chamando ID anterior!");
await MediaPlaylistAction(id_current);
//Cria novamente a chamada de checkPresentation
global.ID_intervalChkPresent =
setInterval(() => {
checkPresentationActive();
}, 1000);
}
}
//MediaPlaylistAction
async function MediaPlaylistAction(id) {
url = `http://${config.ip}:${config.port}/api/MediaPlaylistAction?id=${id}&token=${config.token}`;
console.log("Media Playlist Action - Chamando ID: " + id);
try {
const response = await axios.post(url, {
headers: {
'Content-Type': 'application/json'
}
});
// Se chamou uma apresentação anterior a atual
if (isPrevious) {
await SlideAtual();
}
} catch (error) {
console.log(error);
}
}
//GetCurrentPresentation
async function checkPresentationActive() {
try {
const url = generate_url('GetCurrentPresentation');
const response = await axios.post(url, {}, {
headers: {
'Content-Type': 'application/json'
}
});
if (response.data.data === null) {
presentation_active = false;
} else if (presentation_active) {
await SlideAtual();
type_current = response.data.data.type;
// Verifica se apresentação atual é do tipo VERSE
if (type_current == 'verse') {
//TODO: Refazer verificação verse a partir da atualização 2.21.0 do Holyrics
dateHTML = await requisitionHolyricsHTML();
header = striptags(dateHTML.map.header);
headerPrefix = header.substring(0, header.indexOf('.')); // Extrai o prefixo do cabeçalho
// Encontre o índice do item em list_media cujas referências do name correspondem ao prefixo do cabeçalho
pos_id = list_media.findIndex(item => {
const references = item.name.split(', '); // Divide as referências em uma lista
for (const reference of references) {
const itemPrefix = reference.substring(0, reference.indexOf('.')); // Extrai o prefixo de cada referência
if (itemPrefix === headerPrefix) {
return true; // Se encontrarmos uma correspondência, retorna verdadeiro
}
}
return false; // Se não encontrarmos correspondências, retorna falso
});
if (pos_id == -1) {
console.log("POS_ID não encontrado!")
nextID();
}
else {
// NÃO é uma lista de versículo
if ((list_media[pos_id].name.indexOf('-') == -1 || header.split('-').length - 1 >= 2 || flag_verse_unico) && list_media[pos_id].name.indexOf(', ') == -1) {
flag_verse_unico = true;
if (header.substring(0, header.indexOf(' - ')) == list_media[pos_id].name)
id_current = list_media[pos_id].id;
else {
console.log("Verse passou do especificado. Chamando prox ID da lista...");
flag_verse_unico = false;
nextID();
}
}
else {
id_current = list_media[pos_id].id;
}
}
} else if (type_current == 'announcement' && response.data.data.total_slides > 1) {
// Bug: não consigo tratar o tipo Anúncio(lista) ou Anúncio(todos)
id_current = null;
type_current = 'announcement';
}
else {
// Caso não entre nas outras condições faz esse tratamento
if (id_current !== response.data.data.id) {
id_current = response.data.data.id;
await getMediaPlaylist(req_local, res_local);
}
}
} else {
console.log("Apresentação iniciada!");
presentation_active = true;
type_current = response.data.data.type;
if (type_current == 'verse') {
await getMediaPlaylist(req_local, res_local);
dateHTML = await requisitionHolyricsHTML();
header = striptags(dateHTML.map.header);
pos_id = list_media.findIndex(item => item.name.substring(0, item.name.indexOf('.')) === header.substring(0, header.indexOf('.')));
console.log("POS_ID encontrado p/ VERSE: " + pos_id)
id_current = list_media[pos_id].id;
}
else if (type_current == 'announcement' && response.data.data.total_slides > 1) {
// Bug: não consigo tratar o tipo Anúncio(lista) ou Anúncio(todos)
console.log("Anúncio (TODOS) ou Anúncio (LISTA), não há tratamento disponível!");
id_current = null;
type_current = 'announcement';
}
else
id_current = response.data.data.id;
await SlideAtual();
getMediaPlaylist(req_local, res_local);
}
} catch (error) {
console.log(error.message);
}
}
//GetCurrentPresentation
async function getCurrentPresentation() {
try {
const url = generate_url('GetCurrentPresentation');
// const data = {
// include_slides: false,
// include_slide_preview: true,
// slide_preview_size: '320x180'
// };
const response = await axios.post(url, /*data,*/ {
headers: {
'Content-Type': 'application/json'
}
});
//console.log(response.data);
return response.data;
} catch (error) {
console.error('Erro na requisição:', error);
}
}
//GetCurrentPresentation
async function getCurrentPresentation(data) {
try {
const url = generate_url('GetCurrentPresentation');
const response = await axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
});
//console.log(response.data);
return response.data;
} catch (error) {
console.error('Erro na requisição:', error);
}
}
//CloseCurrentPresentation
async function closeCurrentPresentation() {
try {
const url = generate_url('CloseCurrentPresentation');
await axios.post(url, {}, {
headers: {
'Content-Type': 'application/json'
}
});
presentation_active = false;
console.log("Apresentação atual fechada!");
} catch (error) {
console.error(error);
}
}
//GetMediaPlayerInfo
async function GetMediaPlayerInfo() {
return new Promise((resolve, reject) => {
const url = generate_url('GetMediaPlayerInfo');
axios.post(url, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response.data)
resolve(response.data);
})
.catch(error => {
console.log(error);
reject(error);
});
});
}
//getPlaylistInfo
async function getPlaylistInfo() {
return new Promise((resolve, reject) => {
const url = generate_url('getPlaylistInfo');
axios.post(url, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response.data)
resolve(response.data);
})
.catch(error => {
console.log(error);
reject(error);
});
});
}
//GetCurrentSchedule
async function getCurrentSchedule() {
try {
const url = generate_url('GetCurrentSchedule');
const response = await axios.post(url, {
headers: {
'Content-Type': 'application/json'
}
});
return response.data;
} catch (error) {
console.error('Erro na requisição:', error);
}
}
async function getGlobal(variavel) {
try {
const url = generate_url('GetGlobal');
const data = {
variavel: variavel
};
const response = await axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
});
//console.log(response.data);
return response.data;
} catch (error) {
console.error('Erro na requisição:', error);
}
}
//actionGoToIndex
async function actionGoToIndex(index) {
try {
const url = generate_url('ActionGoToIndex');
const data = {
index: index
};
const response = await axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Erro na requisição:', error);
}
}
// Exportar funções
module.exports = {
getMediaPlaylist: getMediaPlaylist,
changeSlide: changeSlide,
checkPresentationActive: checkPresentationActive,
getCurrentPresentation: getCurrentPresentation,
MediaPlaylistAction: MediaPlaylistAction,
closeCurrentPresentation: closeCurrentPresentation,
getPlaylistInfo: getPlaylistInfo,
SlideAtual: SlideAtual,
ActionNextorPrevious: ActionNextorPrevious,
waitForVerseChange: waitForVerseChange,
getCurrentSchedule: getCurrentSchedule,
getGlobal: getGlobal,
actionGoToIndex: actionGoToIndex,
req_local: req_local,
res_local: res_local
};