-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
1860 lines (1757 loc) · 96.5 KB
/
background.js
File metadata and controls
1860 lines (1757 loc) · 96.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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { openDB } from '/libs/idb.js'
import { default as objectHash } from '/libs/object-hash.js'
import '/utils.js'
import '/normalize-text.js'
let db
let runningTab
let rejectWait
let stopRunning = false
let controller = new AbortController()
let reloadTabTimer
let lastResetReloadTabTimer
let collectAnswers = 0
let reloaded = 0
let started = 0
let startFunc
let settings
// let tempCabinet
let lastScore
class TopicError extends Error {}
const dbVersion = 19
const initializeFunc = init()
waitUntil(initializeFunc)
initializeFunc.finally(() => initializeFunc.done = true)
async function init() {
// noinspection JSUnusedGlobalSymbols
db = await openDB('nmo', dbVersion, {upgrade})
self.db = db
async function upgrade(db, oldVersion, newVersion, transaction) {
if (oldVersion !== newVersion) {
console.log('Обновление базы данных с версии ' + oldVersion + ' на ' + newVersion)
}
if (oldVersion === 0) {
const questions = db.createObjectStore('questions', {autoIncrement: true, keyPath: '_id'})
questions.createIndex('question', 'question', {unique: true})
questions.createIndex('topics', 'topics', {multiEntry: true})
const topics = db.createObjectStore('topics', {autoIncrement: true, keyPath: '_id'})
topics.createIndex('name', 'name')
// 0 - не выполнено, 1 - выполнено, 2 - есть ошибки
topics.createIndex('completed', 'completed')
// 1 - эта тема внесена вручную пользователем
topics.createIndex('dirty', 'dirty')
topics.createIndex('inputIndex', 'inputIndex')
topics.createIndex('completed, inputIndex', ['completed', 'inputIndex'])
topics.createIndex('code', 'code', {unique: true})
topics.createIndex('id', 'id', {unique: true})
const other = db.createObjectStore('other')
await other.put({
mode: 'manual',
clickWaitMin: 500,
clickWaitMax: 2000,
answerWaitMin: 3000,
answerWaitMax: 10000,
maxAttemptsNext: 16,
maxReloadTab: 7,
maxReloadTest: 30,
goodScore: false,
selectionMethod: true,
timeoutReloadTabMin: 15000,
timeoutReloadTabMax: 90000,
offlineMode: false,
sendResults: true,
positionStatus: 'bottom-left'
}, 'settings')
return
}
if (oldVersion <= 12) {
console.log('Этап обновления с версии 12 на 13')
settings = await transaction.objectStore('other').get('settings')
settings.timeoutReloadTabMin = 15000
settings.timeoutReloadTabMax = 90000
await transaction.objectStore('other').put(settings, 'settings')
}
if (oldVersion <= 14) {
console.log('Этап обновления с версии 14 на 15')
await db.deleteObjectStore('questions')
await db.deleteObjectStore('topics')
const questions = db.createObjectStore('questions', {autoIncrement: true, keyPath: '_id'})
questions.createIndex('question', 'question', {unique: true})
questions.createIndex('topics', 'topics', {multiEntry: true})
const topics = db.createObjectStore('topics', {autoIncrement: true, keyPath: '_id'})
topics.createIndex('name', 'name')
topics.createIndex('completed', 'completed')
topics.createIndex('code', 'code', {unique: true})
topics.createIndex('id', 'id', {unique: true})
}
if (oldVersion <= 15) {
console.log('Этап обновления с версии 15 на 16')
transaction.objectStore('topics').createIndex('dirty', 'dirty')
transaction.objectStore('topics').createIndex('inputIndex', 'inputIndex')
transaction.objectStore('topics').createIndex('completed, inputIndex', ['completed', 'inputIndex'])
settings = await transaction.objectStore('other').get('settings')
settings.selectionMethod = true
settings.offlineMode = false
settings.goodScore = false
await transaction.objectStore('other').put(settings, 'settings')
}
if (oldVersion <= 16) {
console.log('Этап обновления с версии 16 на 17')
settings = await transaction.objectStore('other').get('settings')
settings.sendResults = true
await transaction.objectStore('other').put(settings, 'settings')
}
if (oldVersion <= 17) {
console.log('Этап обновления с версии 17 на 18')
console.log('очистка topics')
await transaction.objectStore('topics').clear()
console.log('очистка questions')
await transaction.objectStore('questions').clear()
}
if (oldVersion <= 18) {
console.log('Этап обновления с версии 18 на 19')
settings = await transaction.objectStore('other').get('settings')
settings.positionStatus = 'bottom-left'
await transaction.objectStore('other').put(settings, 'settings')
}
console.log('Обновление базы данных завершено')
}
settings = await db.get('other', 'settings')
self.settings = settings
await toggleContentScript()
await toggleVisibleScript()
await toggleRuleSet()
await toggleDynamicsRuleSet()
console.log('started background!')
}
// chrome.runtime.onInstalled.addListener(function(details) {
// if (details.reason === 'install') {
// chrome.runtime.openOptionsPage()
// }
// })
self.resetOptionalVariables = resetOptionalVariables
async function resetOptionalVariables() {
const transaction = db.transaction(['questions', 'topics'], 'readwrite')
for await (const cursor of transaction.objectStore('questions')) {
const question = cursor.value
let changed
if (question.lastOrder) {
changed = true
delete question.lastOrder
}
for (const answersHash in question.answers) {
// if (question.answers[answersHash].fakeCorrectAnswers) {
// changed = true
// delete question.answers[answersHash].fakeCorrectAnswers
// }
if (question.answers[answersHash].tryedAI) {
changed = true
delete question.answers[answersHash].tryedAI
}
if (question.answers[answersHash].lastUsedAnswers) {
changed = true
delete question.answers[answersHash].lastUsedAnswers
}
// if (question.answers[answersHash].combinations) {
// changed = true
// delete question.answers[answersHash].combinations
// }
}
if (changed) {
await cursor.update(question)
}
}
for await (const cursor of transaction.objectStore('topics')) {
const topic = cursor.value
let changed
if (topic.inputName) {
changed = true
delete topic.inputName
}
if (topic.inputIndex != null) {
changed = true
delete topic.inputIndex
}
if (topic.completed != null) {
changed = true
delete topic.completed
}
if (topic.status != null) {
changed = true
delete topic.status
}
if (topic.needSearchAnswers != null) {
changed = true
delete topic.needSearchAnswers
}
if (topic.dirty != null) {
changed = true
delete topic.dirty
}
if (topic.error) {
changed = true
delete topic.error
}
if (changed) {
await cursor.update(topic)
}
}
}
self.fixDupQuestions = fixDupQuestions
async function fixDupQuestions() {
let transaction
try {
transaction = db.transaction('questions', 'readwrite')
{
console.log('этап 1')
let cursor = await transaction.store.openCursor()
while (cursor) {
const question = cursor.value
let changed = false
const newQuestion = normalizeText(question.question)
if (question.question !== newQuestion) {
console.log('Исправлено название', question)
question.question = newQuestion
changed = true
}
for (const answerHash in question.answers) {
const newAnswers = []
for (const answer of question.answers[answerHash].answers) {
newAnswers.push(normalizeText(answer))
}
newAnswers.sort()
const newAnswer = question.answers[answerHash]
const newAnswerHash = objectHash(newAnswers)
const oldQuestion = JSON.stringify(question)
delete question.answers[answerHash]
if (question.answers[newAnswerHash]) {
console.warn('Найдены дублирующиеся ответы', oldQuestion, question)
delete newAnswer.combinations
changed = true
} else if (answerHash !== newAnswerHash || JSON.stringify(newAnswer.answers) !== JSON.stringify(newAnswers)) {
console.warn('Вариации ответов не соответствовали', JSON.stringify(newAnswer.answers), newAnswers, newAnswerHash)
delete newAnswer.combinations
changed = true
}
newAnswer.answers = newAnswers
question.answers[newAnswerHash] = newAnswer
if (question.correctAnswers[answerHash]) {
const newCorrectAnswers = []
for (const answer of question.correctAnswers[answerHash]) {
newCorrectAnswers.push(normalizeText(answer))
}
newCorrectAnswers.sort()
if (!changed && JSON.stringify(question.correctAnswers[answerHash]) !== JSON.stringify(newCorrectAnswers)) {
console.warn('Правильны ответы не соответствовали', JSON.stringify(question.correctAnswers[answerHash]), newCorrectAnswers, newAnswerHash)
changed = true
}
delete question.correctAnswers[answerHash]
question.correctAnswers[newAnswerHash] = newCorrectAnswers
}
}
if (changed) {
await cursor.update(question)
}
// noinspection JSVoidFunctionReturnValueUsed
cursor = await cursor.continue()
}
}
{
console.log('этап 2')
let cursor = await transaction.store.openCursor()
while (cursor) {
const count = await transaction.store.index('question').count(cursor.value.question)
if (count > 1) {
console.warn('Найден дубликат', cursor.value)
let cursor2 = await transaction.store.index('question').openCursor(cursor.value.question)
const question = cursor2.value
// noinspection JSVoidFunctionReturnValueUsed
cursor2 = await cursor2.continue()
let changed = false
while (cursor2) {
for (const answersHash in cursor2.value.answers) {
if (!question.answers[answersHash] || (!question.answers[answersHash].type && cursor2.value.answers[answersHash].type)) {
changed = true
question.answers[answersHash] = cursor2.value.answers[answersHash]
}
if (!question.correctAnswers[answersHash] && cursor2.value.correctAnswers[answersHash]) {
changed = true
question.correctAnswers[answersHash] = cursor2.value.correctAnswers[answersHash]
}
}
if (cursor2.value.answers['unknown']) {
if (question.answers['unknown'] == null) question.answers['unknown'] = []
for (const answer of cursor2.value.answers['unknown']) {
if (!question.answers['unknown'].includes(answer)) {
changed = true
question.answers['unknown'].push(answer)
}
}
}
if (cursor2.value.correctAnswers['unknown']) {
if (question.correctAnswers['unknown'] == null) question.correctAnswers['unknown'] = []
for (const answer of cursor2.value.correctAnswers['unknown']) {
if (!question.correctAnswers['unknown'].includes(answer)) {
changed = true
question.correctAnswers['unknown'].push(answer)
}
}
}
for (const topic of cursor2.value.topics) {
if (!question.topics.includes(topic)) {
changed = true
question.topics.push(topic)
}
}
// console.warn('Удалено', cursor2.value)
await cursor2.delete()
// noinspection JSVoidFunctionReturnValueUsed
cursor2 = await cursor2.continue()
}
if (changed) {
console.warn('Дубликат объединён в', question)
await cursor.update(question)
}
}
// noinspection JSVoidFunctionReturnValueUsed
cursor = await cursor.continue()
}
}
} catch (error) {
transaction.abort()
console.error(error)
}
}
self.fixDupTopics = fixDupTopics
async function fixDupTopics() {
let transaction
try {
transaction = db.transaction(['questions', 'topics'], 'readwrite')
let cursor = await transaction.objectStore('topics').openCursor()
while (cursor) {
const topic = cursor.value
if (!topic.name) {
console.warn('нет имени!', topic)
// noinspection JSVoidFunctionReturnValueUsed
cursor = await cursor.continue()
continue
}
const newName = normalizeText(topic.name, true)
const found = await transaction.objectStore('topics').index('name').get(newName)
if (found && found._id !== topic._id) {
console.warn('Найден дублирующий topic, он был удалён и объединён', found)
await transaction.objectStore('topics').delete(found._id)
if (topic.id !== found.id) {
topic.id = found.id
}
if (topic.name !== found.name) {
topic.name = normalizeText(found.name, true)
} else if (topic.name) {
topic.name = normalizeText(topic.name, true)
}
if (topic.code !== found.number) {
topic.code = found.number
}
await cursor.update(topic)
let cursor2 = await transaction.objectStore('questions').index('topics').openCursor(found._id)
while (cursor2) {
const question = cursor2.value
question.topics.splice(question.topics.indexOf(found._id), 1)
if (!question.topics.includes(topic._id)) question.topics.push(topic._id)
await cursor2.update(question)
// noinspection JSVoidFunctionReturnValueUsed
cursor2 = await cursor2.continue()
}
} else if (topic.name !== newName) {
console.warn('Исправлено название', topic)
topic.name = newName
await cursor.update(topic)
}
// noinspection JSVoidFunctionReturnValueUsed
cursor = await cursor.continue()
}
} catch (error) {
transaction.abort()
console.error(error)
}
}
self.getCorrectAnswers = getCorrectAnswers
async function getCorrectAnswers(topic, index) {
topic = topic.toLowerCase()
let searchCursor = await db.transaction('topics').store.index('name').openCursor(IDBKeyRange.bound(topic, topic + '\uffff'))
if (!searchCursor) throw Error('Не найдено')
let currIndex = 0
let result
while (searchCursor) {
result = searchCursor
currIndex++
if (index == null || currIndex === index) {
console.log(currIndex, searchCursor.value.name)
}
if (currIndex === index) break
// noinspection JSVoidFunctionReturnValueUsed
searchCursor = await searchCursor.continue()
}
if (currIndex > 1 && index == null) {
console.log('По заданному названию найдено несколько тем, в качестве второго аргумента данной функции укажите номер из предложенных вариантов')
return
}
if (!result) throw Error('Не найдено по заданному номеру')
// console.log('Поиск...')
let text = result.value.name + ':\n\n'
let cursor = await db.transaction('questions').store.index('topics').openCursor(result.value._id)
while(cursor) {
const question = cursor.value
for (const answerHash in question.answers) {
if (question.correctAnswers[answerHash]) {
text += question.question + ':\n'
for (const answer of question.correctAnswers[answerHash]) {
text += '+ ' + answer + '\n'
}
for (const answer of question.answers[answerHash].answers) {
if (!question.correctAnswers[answerHash].includes(answer)) {
text += '- ' + answer + '\n'
}
}
text += '\n'
}
}
// noinspection JSVoidFunctionReturnValueUsed
cursor = await cursor.continue()
}
return text
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.authData) {
(async () => {
await initializeFunc
await db.put('other', message.authData, 'authData')
if (!message.cabinet) message.cabinet = 'vo'
message.cabinet = 'nmfo-' + message.cabinet
await db.put('other', message.cabinet, 'cabinet')
await toggleDynamicsRuleSet(message.cabinet)
})()
}
if (message.status) {
(async () => {
await initializeFunc
sendResponse({running: runningTab === sender.tab.id, collectAnswers, settings, lastScore})
})()
return true
} else if (message.reloadPage) {
if (runningTab !== sender.tab.id) {
console.warn('От вкладки пришёл запрос на перезагрузку но id не соответствует с runningTab', runningTab, sender.tab.id, sender, message)
return
}
if (message.error) {
(async () => {
await initializeFunc
console.warn('Похоже на вкладке где решается тест что-то зависло', message.error)
reloaded++
if (reloaded > settings.maxReloadTab) {
showNotification('Предупреждение', 'Слишком много попыток перезагрузить страницу')
startFunc = start(sender.tab, {hasTest: true, hasError: true})
startFunc.finally(() => startFunc.done = true)
} else {
if (!await checkThrottleTab(sender.tab.id)) {
showNotification('Ошибка', 'Похоже браузер ограничил или приостановил работу вкладки из-за ограничений фонового режима')
stop(sender.tab.id)
return
}
await chrome.tabs.reload(sender.tab.id)
}
})()
} else {
chrome.tabs.reload(sender.tab.id)
}
setReloadTabTimer()
} else if (message.reloadSettings) {
(async () => {
await initializeFunc
settings = await db.get('other', 'settings')
self.settings = settings
})()
} else if (message.stopError) {
if (runningTab !== sender.tab.id) {
console.warn('От вкладки пришёл запрос на перезагрузку но id не соответствует с runningTab', runningTab, sender.tab.id, sender, message)
}
showNotification('Ошибка', message.stopError)
stop(sender.tab.id)
} else if (message.needPassChallenge) {
passChallenge(sender.tab.id)
} else if (!message.authData) {
console.warn('Неизвестное сообщение от вкладки', message, sender)
}
})
chrome.action.onClicked.addListener(async (tab) => {
chrome.action.setTitle({title: chrome.runtime.getManifest().action.default_title})
chrome.action.setBadgeText({text: ''})
await initializeFunc
if (settings.mode === 'manual' || settings.mode === 'disabled') {
chrome.runtime.openOptionsPage()
return
}
if (runningTab || (startFunc && !startFunc.done)) {
console.warn('Работа расширения остановлена по запросу пользователя')
stop(runningTab, true)
} else {
let response
try {
response = await chrome.tabs.sendMessage(tab.id, {hasTest: true})
if (!response) throw Error('Receiving end does not exist')
} catch (error) {
if (error.message.includes('Receiving end does not exist') || error.message.includes('message port closed before a response was received')) {
showNotification('Ошибка', 'Похоже на данной вкладке открыт НЕ портал НМО (или что-то не относящееся к тестам ОИМ), если это не так - попробуйте обновить страницу')
} else {
showNotification('Непредвиденная ошибка', error.message)
}
return
}
startFunc = start(tab, {hasTest: response.hasTest})
startFunc.finally(() => startFunc.done = true)
}
})
async function start(tab, {hasTest, done, hasError, forceReload}) {
reloaded = 0
lastScore = null
lastResetReloadTabTimer = null
runningTab = null
clearTimeout(reloadTabTimer)
if (done) {
started = 0
} else {
started++
}
if (started > (settings.maxReloadTest + 1)) {
showNotification('Ошибка', 'Слишком много попыток запустить тест')
stop(tab.id)
return
}
if (hasOpenedChallenge) {
showNotification('Ошибка', 'Пройдите проверку на робота')
stop(tab.id)
return
}
waitUntilState(true)
controller = new AbortController()
stopRunning = false
if (!chrome.tabs.onRemoved.hasListeners()) chrome.tabs.onRemoved.addListener(onRemovedTabsListener)
if (hasError && !await checkThrottleTab(tab.id)) {
showNotification('Ошибка', 'Похоже браузер ограничил или приостановил работу вкладки из-за ограничений фонового режима')
stop(tab.id)
return
}
let url = await checkOrGetTopic()
if (url === 'error') {
waitUntilState(false)
started = 0
if (stopRunning) return
stop(tab.id)
return
}
if (url === 'null') {
if (done) {
showNotification('Готово', 'Расширение окончил работу')
chrome.action.setTitle({title: chrome.runtime.getManifest().action.default_title})
chrome.action.setBadgeText({text: 'DONE'})
stop(tab.id)
return
} else if (!hasTest) {
chrome.action.setTitle({title: chrome.runtime.getManifest().action.default_title})
showNotification('Ошибка', 'На данной странице нет теста' + (settings.mode === 'auto' ? ' или не назначены тесты в настройках' : ''))
stop(tab.id)
return
} else if (hasError) {
runningTab = tab.id
if (tab.autoDiscardable) {
await chrome.tabs.update(tab.id, {autoDiscardable: false})
}
if (forceReload) {
tab = await chrome.tabs.discard(tab.id)
runningTab = tab.id
}
chrome.tabs.reload(tab.id)
} else {
runningTab = tab.id
if (tab.autoDiscardable) {
await chrome.tabs.update(tab.id, {autoDiscardable: false})
}
chrome.tabs.sendMessage(tab.id, {start: true})
}
} else {
runningTab = tab.id
if (forceReload) {
tab = await chrome.tabs.discard(tab.id)
runningTab = tab.id
}
await chrome.tabs.update(tab.id, {url, autoDiscardable: false})
}
chrome.action.setTitle({title: 'Расширение решает тест' + (started > 1 ? ' (попытка № ' + started + ')' : '')})
chrome.action.setBadgeText({text: 'ON'})
setReloadTabTimer()
}
async function checkOrGetTopic() {
if (settings.mode !== 'auto') return 'null'
const countEE = await db.countFromIndex('topics', 'completed, inputIndex', IDBKeyRange.bound([0, 0], [0, Infinity]))
if (countEE) {
chrome.action.setTitle({title: 'Ищем тему (тест) на портале и пытаемся открыть'})
chrome.action.setBadgeText({text: 'SRCH'})
if (!(await db.get('other', 'authData'))?.access_token) {
showNotification('Ошибка', 'Нет данных об авторизации')
return 'error'
}
let url
let count = 0
while (true) {
count++
if (count > 1) {
chrome.action.setTitle({title: `Ищем тему (тест) на портале и пытаемся открыть (попытка № ${count})`})
}
if (count >= 100) {
showNotification('Ошибка', 'Слишком много попыток поиска темы')
return 'error'
}
const educationalElement = await db.getFromIndex('topics', 'completed, inputIndex', IDBKeyRange.bound([0, 0], [0, Infinity]))
if (!educationalElement) return 'null'
try {
url = await searchEducationalElement(educationalElement)
break
} catch (error) {
if (stopRunning) return 'error'
console.warn(error)
if (error instanceof TopicError) {
if (error.message === 'Уже пройдено') {
educationalElement.completed = 1
delete educationalElement.dirty
} else {
educationalElement.error = error.message
educationalElement.completed = 2
}
await db.put('topics', educationalElement)
if (educationalElement.inputIndex != null) {
chrome.runtime.sendMessage({updatedTopic: educationalElement}, function () {
const lastError = chrome.runtime.lastError?.message
if (!lastError.includes('Receiving end does not exist') && !lastError.includes('message port closed before a response was received')) {
console.error(lastError)
}
})
}
continue
} else if (
!error.message.startsWith('bad code 5') &&
!error.message.startsWith('Не была получена ссылка по теме ') &&
error.message !== 'Updated token' &&
error.message !== 'signal timed out' &&
error.message !== 'Failed to fetch' &&
error.message !== 'notFound'
) {
showNotification('Непредвиденная ошибка', error.message)
return 'error'
}
await wait(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin)
}
}
return url
}
return 'null'
}
async function searchEducationalElement(educationalElement, cut, inputName) {
if (settings.clickWaitMax) await wait(Math.random() * (settings.clickWaitMax - settings.clickWaitMin) + settings.clickWaitMin)
let searchQuery = educationalElement.name
console.log('ищем', educationalElement)
if (inputName) {
searchQuery = educationalElement.inputName
console.log('ищем (по пользовательскому названию)', searchQuery)
} else if (cut) {
searchQuery = searchQuery.slice(0, -10)
console.log('ищем (урезанное название)', searchQuery)
}
if (searchQuery.length > 255) {
searchQuery = searchQuery.slice(0, 255)
console.warn('название темы слишком длинное, урезано до 255 символов', searchQuery)
}
if (educationalElement.dirty && educationalElement.name) {
const result = await getAnswersByTopicFromServer(educationalElement.name)
if (result?.topic) {
educationalElement = result.topic
}
}
const authData = await db.get('other', 'authData')
let cabinet = await db.get('other', 'cabinet')
// if (tempCabinet) cabinet = tempCabinet
let foundEE
if (educationalElement.id && educationalElement.status) {
foundEE = {id: educationalElement.id, number: educationalElement.number, name: educationalElement.name, status: educationalElement.status}
} else if (educationalElement.id) {
let response = await fetch(`https://${cabinet}.edu.rosminzdrav.ru/api/api/educational-elements/iom/${educationalElement.id}/`, {
headers: {authorization: 'Bearer ' + authData.access_token},
method: 'GET',
signal: anySignal([AbortSignal.timeout(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin), controller.signal])
})
if (!response.ok && String(response.status).startsWith('5')) throw Error('bad code ' + response.status)
let json = await response.json()
if ((educationalElement.id || educationalElement.code) && json.globalErrors?.[0]?.code === 'notFound') {
// TODO у нас проблема с id, в разных кабинетах разные id тем с одинаковым названием
console.warn('Не удалось найти элемент по id, возможно тут конфликт с id')
delete educationalElement.id
delete educationalElement.code
await db.put('topics', educationalElement)
return await searchEducationalElement(educationalElement, cut, inputName)
}
await checkErrors(json)
foundEE = json
} else if (searchQuery) {
let response = await fetch(`https://${cabinet}.edu.rosminzdrav.ru/api/api/educational-elements/search`, {
headers: {authorization: 'Bearer ' + authData.access_token, 'content-type': 'application/json'},
body: JSON.stringify({
topicId: null,
cycleId: null,
limit: 10,
programId: null,
educationalOrganizationIds: [],
freeTextQuery: searchQuery.trim(),
elementType: "iom",
offset: 0,
startDate: null,
endDate: null,
iomTypeIds: [],
mainSpecialityNameList: []
}),
method: 'POST',
signal: anySignal([AbortSignal.timeout(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin), controller.signal])
})
if (!response.ok && String(response.status).startsWith('5')) throw Error('bad code ' + response.status)
let json = await response.json()
await checkErrors(json)
if (!json.elements.length) {
if (!cut && educationalElement.code) {
cut = true
return await searchEducationalElement(educationalElement, cut, inputName)
} else if (!inputName && educationalElement.inputName && educationalElement.name !== educationalElement.inputName) {
inputName = true
return await searchEducationalElement(educationalElement, cut, inputName)
} else {
console.log(json)
throw new TopicError('По заданному названию ничего не найдено')
}
}
for (const element of json.elements) {
if (settings.clickWaitMax) await wait(Math.random() * (settings.clickWaitMax - settings.clickWaitMin) + settings.clickWaitMin)
response = await fetch(`https://${cabinet}.edu.rosminzdrav.ru/api/api/educational-elements/iom/${element.elementId}/`, {
headers: {authorization: 'Bearer ' + authData.access_token},
method: 'GET',
signal: anySignal([AbortSignal.timeout(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin), controller.signal])
})
if (!response.ok && String(response.status).startsWith('5')) throw Error('bad code ' + response.status)
let json2 = await response.json()
await checkErrors(json2)
if (educationalElement.code) {
if (educationalElement.code === json2.number) {
foundEE = json2
break
}
} else if (educationalElement.name === normalizeText(json2.name, true)) {
foundEE = json2
break
} else if (cut && normalizeText(json2.name, true).includes(educationalElement.name)) {
foundEE = json2
break
}
}
} else {
throw new TopicError('Нет параметров для поиска (ошибка с id или не найдено по id)')
}
if (!foundEE) {
throw new TopicError('Не найдено')
}
if (settings.clickWaitMax) await wait(Math.random() * (settings.clickWaitMax - settings.clickWaitMin) + settings.clickWaitMin)
foundEE.name = normalizeText(foundEE.name, true)
if (educationalElement.name !== foundEE.name) {
if (educationalElement.name) {
console.warn('Названия не соответствуют:')
console.warn(educationalElement.name)
console.warn(foundEE.name)
educationalElement.error = 'Есть не соответствие в названии, название было изменено'
}
const newTopic = await db.getFromIndex('topics', 'name', foundEE.name)
if (newTopic) {
console.warn('Найден дублирующий topic, для исправления он был удалён', JSON.stringify(educationalElement))
await db.delete('topics', educationalElement._id)
educationalElement._id = newTopic._id
if (newTopic.inputName && !educationalElement.inputName) {
educationalElement.inputName = newTopic.inputName
}
if (newTopic.inputIndex != null && educationalElement.inputIndex == null) {
educationalElement.inputIndex = newTopic.inputIndex
}
}
}
// на случай если поиск был по id
if (!(educationalElement.dirty && educationalElement.id && !educationalElement.name)) {
delete educationalElement.dirty
}
if (educationalElement.id !== foundEE.id) {
educationalElement.id = foundEE.id
}
if (educationalElement.name !== foundEE.name) {
educationalElement.name = foundEE.name
}
if (educationalElement.code !== foundEE.number) {
educationalElement.code = foundEE.number
}
// educationalElement.completed = foundEE.completed
educationalElement.status = foundEE.status
await db.put('topics', educationalElement)
if (foundEE.iomHost?.name) {
if (!foundEE.iomHost.name.includes('Платформа онлайн-обучения Портала')) {
throw new TopicError('Данный элемент не возможно пройти так как платформа обучения не поддерживается расширением (' + foundEE.iomHost.name + ')')
}
}
if (!foundEE.completed && !foundEE.status) {
let response = await fetch(`https://${cabinet}.edu.rosminzdrav.ru/api/api/educational-elements/iom/${foundEE.id}/plan`, {
headers: {authorization: 'Bearer ' + authData.access_token},
method: 'PUT',
signal: anySignal([AbortSignal.timeout(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin), controller.signal])
})
if (!response.ok && String(response.status).startsWith('5')) throw Error('bad code ' + response.status)
if (!response.ok) {
let json = await response.json()
await checkErrors(json)
if (json.globalErrors?.[0]?.code === 'ELEMENT_CANNOT_BE_ADDED_TO_PLAN_EXCEPTION') {
throw new TopicError(JSON.stringify(json))
}
}
if (settings.clickWaitMax && settings.clickWaitMax > 500) {
await wait(Math.random() * (settings.clickWaitMax - settings.clickWaitMin) + settings.clickWaitMin)
} else {
await wait(Math.random() * (10000 - 5000) + 5000)
}
} else {
if (foundEE.completed) {
console.warn('данный элемент уже пройден пользователем', foundEE)
// TODO мы не можем пропустить открытие теста не смотря на то что оно уже пройдено
// так как иногда бывает зависание теста (с пропажей кнопок получения варианта, вперёд и назад)
// throw new TopicError('Уже пройдено')
}
}
let response = await fetch(`https://${cabinet}.edu.rosminzdrav.ru/api/api/educational-elements/iom/${foundEE.id}/open-link?backUrl=https%3A%2F%2F${cabinet}.edu.rosminzdrav.ru%2F%23%2Fuser-account%2Fmy-plan`, {
headers: {authorization: 'Bearer ' + authData.access_token},
method: 'GET',
signal: anySignal([AbortSignal.timeout(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin), controller.signal])
})
if (!response.ok && String(response.status).startsWith('5')) throw Error('bad code ' + response.status)
let json = await response.json()
if ((educationalElement.id || educationalElement.code) && json.globalErrors?.[0]?.code === 'notFound') {
// TODO у нас проблема с id, в разных кабинетах разные id тем с одинаковым названием
console.warn('Не удалось найти элемент по id, возможно тут конфликт с id')
delete educationalElement.id
delete educationalElement.code
await db.put('topics', educationalElement)
return await searchEducationalElement(educationalElement, cut, inputName)
}
await checkErrors(json)
console.log('открываем', educationalElement.name)
if (!json.url) {
console.log(json)
console.log(educationalElement)
if (educationalElement.status === 'included') {
delete educationalElement.status
await db.put('topics', educationalElement)
}
throw Error('Не была получена ссылка по теме ' + educationalElement.name)
}
if (!new URL(json.url).host.includes('edu.rosminzdrav.ru')) {
throw new TopicError('Данный элемент не возможно пройти так как платформа обучения не поддерживается расширением (' + new URL(json.url).host + ')')
}
// tempCabinet = null
return json.url
}
async function checkErrors(json) {
if (json.error) {
if (json.error_description?.includes('token expired') || json.error_description?.includes('access token')) {
const authData = await db.get('other', 'authData')
const cabinet = await db.get('other', 'cabinet')
if (authData?.refresh_token) {
const response = await fetch(`https://${cabinet}.edu.rosminzdrav.ru/api/api/v2/oauth/token?grant_type=refresh_token&refresh_token=${authData.refresh_token}`, {
headers: {"Content-Type": "application/x-www-form-urlencoded", Authorization: 'Basic ' + btoa(`client:secret`)},
method: 'POST',
signal: anySignal([AbortSignal.timeout(Math.random() * (settings.timeoutReloadTabMax - settings.timeoutReloadTabMin) + settings.timeoutReloadTabMin), controller.signal])
})
if (!response.ok && String(response.status).startsWith('5')) throw Error('bad code ' + response.status)
const json2 = await response.json()
console.log(json2)
if (json2?.access_token) {
await db.put('other', json2, 'authData')
} else {
console.error('Не удалось обновить access_token')
throw Error('Не удалось обновить access_token ' + JSON.stringify(json2).slice(0, 150))
}
throw Error('Updated token')
}
}
console.error(json)
throw Error('НМО выдал ошибку при попытке поиска ' + JSON.stringify(json).slice(0, 150))
} else if (json.globalErrors?.[0]?.code === 'notFound') {
throw new TopicError(JSON.stringify(json.globalErrors))
} /* else if (json.globalErrors?.[0]?.code === 'notFound') {
// TODO кривой костыль если у нас этот ИОМ можно пройти только в другом кабинете (по образованию)
if (!tempCabinet) {
tempCabinet = 'nmfo-spo'
throw Error('notFound')
} else {
tempCabinet = null
throw new TopicError('Не найдено')
}
}*/
}
function onRemovedTabsListener(tabId) {
if (runningTab === tabId) {
console.warn('Работа расширения остановлена, пользователь закрыл вкладку')
stop(null, true)
}
}
chrome.runtime.onConnect.addListener((port) => {
port.onMessage.addListener(async (message) => {
await initializeFunc
setReloadTabTimer()
if (message.question) {
let error
lastScore = null
let searchedOnServer
let topic
if (message.question.topics[0]) {
topic = await db.getFromIndex('topics', 'name', message.question.topics[0])
if (!topic || topic.dirty) {
searchedOnServer = true
const result = await getAnswersByTopicFromServer(message.question.topics[0])
if (result?.error) error = result.error
if (result?.topic) {
topic = result.topic
} else if (!topic) {
topic = {name: message.question.topics[0]}
topic._id = await db.put('topics', topic)
console.log('Внесена новая тема в базу', message.question.topics[0])
} else if (topic.dirty && result && !result.error) {
delete topic.dirty
await db.put('topics', topic)
}
}
}
let question = await db.getFromIndex('questions', 'question', message.question.question)
if (!question) {
searchedOnServer = true
const result = await getAnswersByQuestionFromServer(message.question.question)
if (result?.error) error = result.error