Better handling when server is not avaible, retry connection

This commit is contained in:
MrFry 2020-01-26 10:04:43 +01:00
parent b5d83f0bde
commit f3f1cb5598

View file

@ -21,7 +21,7 @@
// ==UserScript== // ==UserScript==
// @name Moodle/Elearning/KMOOC test help // @name Moodle/Elearning/KMOOC test help
// @version 1.7.0.0 // @version 2.0.0.0
// @description Online Moodle/Elearning/KMOOC test help // @description Online Moodle/Elearning/KMOOC test help
// @author MrFry // @author MrFry
// @match https://elearning.uni-obuda.hu/main/* // @match https://elearning.uni-obuda.hu/main/*
@ -62,7 +62,7 @@
// forcing pages for testing. unless you test, do not set these to true! // forcing pages for testing. unless you test, do not set these to true!
// only one of these should be true for testing // only one of these should be true for testing
const forceTestPage = false const forceTestPage = true
const forceResultPage = false const forceResultPage = false
const forceDefaultPage = false const forceDefaultPage = false
const logElementGetting = false const logElementGetting = false
@ -77,8 +77,8 @@
lastChangeLog: '- "Húzza a megfelelő helyre ..." kérdés lekezelése\n- Kód refactor\n- Ha valami elszállt: <a href="https://qmining.frylabs.net">feedback</a> pls', lastChangeLog: '- "Húzza a megfelelő helyre ..." kérdés lekezelése\n- Kód refactor\n- Ha valami elszállt: <a href="https://qmining.frylabs.net">feedback</a> pls',
fatalError: 'Fatál error. Check console (f12). Kattints az üzenetre az összes kérdés/válaszért manuális kereséshez!', fatalError: 'Fatál error. Check console (f12). Kattints az üzenetre az összes kérdés/válaszért manuális kereséshez!',
consoleErrorInfo: 'Itteni hibák 100% a moodle hiba. Kivéve, ha oda van írva hogy script error ;) Ha ilyesmi szerepel itt, akkor olvasd el a segítség szekciót!', consoleErrorInfo: 'Itteni hibák 100% a moodle hiba. Kivéve, ha oda van írva hogy script error ;) Ha ilyesmi szerepel itt, akkor olvasd el a segítség szekciót!',
freshStartWarning: '<h1>Moodle teszt userscript:<h1><h3>1.5.0 verzió: a script mostantól XMLHTTP kéréseket küld szerver fele! Erre a userscript futtató kiegészitőd is figyelmeztetni fog! Ha ez történik, a script rendes működése érdekében engedélyezd (Always allow domain)! Ha nem akarod, hogy ez történjen, akkor ne engedélyezd, vagy a menüben válaszd ki a "helyi fájl használata" opciót!</h3> <h3>Elküldött adatok: minden teszt után a kérdés-válasz páros. Fogadott adatok: Az összes eddig ismert kérdés. Érdemes help-et elolvasni!!!</h3><h5>Ez az ablak frissités után eltűnik. Ha nem, akkor a visza gombbal próbálkozz.</h5>', freshStartWarning: '<h1>Moodle teszt userscript:<h1><h3>1.5.0 verzió: a script mostantól XMLHTTP kéréseket küld szerver fele! Erre a userscript futtató kiegészítőd is figyelmeztetni fog! Ha ez történik, a script rendes működése érdekében engedélyezd (Always allow domain)! Ha nem akarod, hogy ez történjen, akkor ne engedélyezd, vagy a menüben válaszd ki a "helyi fájl használata" opciót!</h3> <h3>Elküldött adatok: minden teszt után a kérdés-válasz páros. Fogadott adatok: Az összes eddig ismert kérdés. Érdemes help-et elolvasni!!!</h3><h5>Ez az ablak frissités után eltűnik. Ha nem, akkor a visza gombbal próbálkozz.</h5>',
noResult: 'Nincs találat :( Kattints az üzenetre az összes kérdés/válaszért manuális kereséshez! Előfordulhat, hogy a tárgyat nem válsztottad ki a menüben.', noResult: 'Nincs találat :( Kattints az üzenetre az összes kérdés/válaszért manuális kereséshez! Előfordulhat, hogy a tárgyat nem választottad ki a menüben.',
videoHelp: 'Miután elindítottad: Play/pause: space. Seek: Bal/jobb nyíl.', videoHelp: 'Miután elindítottad: Play/pause: space. Seek: Bal/jobb nyíl.',
menuButtonText: 'Kérdések Menu', menuButtonText: 'Kérdések Menu',
couldntLoadDataPopupMenuText: 'A kérdéseket nem lehetett beolvasni, ellenőrizd hogy elérhető-e a szerver', couldntLoadDataPopupMenuText: 'A kérdéseket nem lehetett beolvasni, ellenőrizd hogy elérhető-e a szerver',
@ -87,13 +87,15 @@
help: 'Help', help: 'Help',
websiteBugreport: 'Weboldal / Bug report', websiteBugreport: 'Weboldal / Bug report',
donate: 'Donate', donate: 'Donate',
retry: 'Újrapróbálás',
search: 'Keresés ...', search: 'Keresés ...',
loading: 'Betöltés ...', loading: 'Betöltés ...',
noServer: 'Nem elérhető a szerver!', noServer: 'Nem elérhető a szerver!',
passiveModeActivated: 'Passzív mód bekapcsolva, nem lesz mostantól a szerver piszkálva', passiveModeActivated: 'Passzív mód bekapcsolva, nem lesz mostantól a szerver piszkálva',
passiveModeDeactivated: 'Passzív mód kikapcsolva, frissíts az érvénybe lépéshez!', passiveModeDeactivated: 'Passzív mód kikapcsolva, frissíts az érvénybe lépéshez!',
passiveMode: 'Passzív mód', passiveMode: 'Passzív mód',
passiveModeMenuBoxText: 'Passzív mód aktív' passiveModeMenuBoxText: 'Passzív mód aktív',
noServerConsoleMessage: `Nem elérhető a szerver, vagy kis eséllyel kezeletlen hiba történt! Ha elérhető a weboldal, akkor ott meg bírod nézni a kérdéseket itt: ${serverAdress}legacy`
} }
var texts = huTexts var texts = huTexts
@ -117,6 +119,7 @@
if (!val) { throw new Error('Assertion failed') } if (!val) { throw new Error('Assertion failed') }
} }
// TODO: check if someting is not used
class StringUtils { class StringUtils {
RemoveStuff (value, removableStrings, toReplace) { RemoveStuff (value, removableStrings, toReplace) {
removableStrings.forEach((x) => { removableStrings.forEach((x) => {
@ -688,11 +691,7 @@
console.time('main') console.time('main')
timerStarted = true timerStarted = true
Init(AfterLoad) Init()
if (forceTestPage || forceResultPage || forceDefaultPage) {
if (document.getElementById('scriptMessage')) { document.getElementById('scriptMessage').style.background = 'green' }
}
} }
function AfterLoad () { function AfterLoad () {
@ -725,6 +724,12 @@
console.timeEnd('main') console.timeEnd('main')
timerStarted = false timerStarted = false
} }
if (forceTestPage || forceResultPage || forceDefaultPage) {
if (document.getElementById('scriptMessage')) {
document.getElementById('scriptMessage').style.background = 'green'
}
}
} }
// : }}} // : }}}
@ -732,7 +737,7 @@
// : Loading {{{ // : Loading {{{
function Init (cwith) { function Init () {
if (false) { // eslint-disable-line if (false) { // eslint-disable-line
setVal('version16', undefined) setVal('version16', undefined)
setVal('version15', undefined) setVal('version15', undefined)
@ -763,11 +768,12 @@
VersionActions() VersionActions()
if (!url.includes('.pdf')) { ShowMenu() } if (!url.includes('.pdf')) { ShowMenu() }
if (!getVal('skipLoad')) { if (!getVal('skipLoad')) {
ConnectToServer(cwith) ConnectToServer(AfterLoad)
} }
} }
function ConnectToServer (cwith) { function ConnectToServer (cwith) {
ClearAllMessages()
GetXHRInfos().then((inf) => { GetXHRInfos().then((inf) => {
lastestVersion = inf.version lastestVersion = inf.version
motd = inf.motd motd = inf.motd
@ -776,11 +782,23 @@
// FIXME: if cwith() throws an unhandled error it sais server is not avaible // FIXME: if cwith() throws an unhandled error it sais server is not avaible
cwith() cwith()
}).catch(() => { }).catch(() => {
document.getElementById('menuButtonDiv').style.backgroundColor = 'red' NoServerAction()
document.getElementById('infoMainDiv').innerText = texts.noServer
}) })
} }
function NoServerAction () {
SafeGetElementById('menuButtonDiv', (elem) => {
elem.style.backgroundColor = 'red'
})
SafeGetElementById('infoMainDiv', (elem) => {
elem.innerText = texts.noServer
})
SafeGetElementById('retryButton', (elem) => {
elem.style.display = ''
})
Log(texts.noServerConsoleMessage)
}
function VersionActions () { function VersionActions () {
// FOR TESTING ONLY // FOR TESTING ONLY
// setVal("version15", true); // setVal("version15", true);
@ -1205,6 +1223,10 @@
// : }}} // : }}}
// : Minor UI stuff {{{ // : Minor UI stuff {{{
function ClearAllMessages () {
// TODO
// mainDiv.setAttribute('id', 'messageMainDiv')
}
// shows a message with "msg" text, "matchPercent" tip and transp, and "timeout" time // shows a message with "msg" text, "matchPercent" tip and transp, and "timeout" time
function ShowMessage (msgItem, timeout, funct) { function ShowMessage (msgItem, timeout, funct) {
@ -1453,9 +1475,7 @@
let buttonStyle = { let buttonStyle = {
position: '', position: '',
left: 10 + 'px',
margin: '5px 5px 5px 5px', margin: '5px 5px 5px 5px',
top: 10 + 'px',
border: 'none', border: 'none',
backgroundColor: '#222d32', backgroundColor: '#222d32',
color: '#ffffff', color: '#ffffff',
@ -1479,7 +1499,6 @@
}) })
// donate link ---------------------------------------------------------------------------------------------------------------- // donate link ----------------------------------------------------------------------------------------------------------------
let donateLink = CreateNodeWithText(buttonCell, texts.donate, 'button') let donateLink = CreateNodeWithText(buttonCell, texts.donate, 'button')
SetStyle(donateLink, buttonStyle) SetStyle(donateLink, buttonStyle)
@ -1493,14 +1512,41 @@
menuButtonDiv.style.top = (window.innerHeight - 70) + 'px' menuButtonDiv.style.top = (window.innerHeight - 70) + 'px'
}) })
// INFO TABEL --------------------------------------------------------------------
var itbl = document.createElement('table')
SetStyle(itbl, {
margin: '5px 5px 5px 5px',
textAlign: 'left',
width: '98%'
})
menuButtonDiv.appendChild(itbl)
var ibuttonRow = tbl.insertRow()
var ibuttonCell = ibuttonRow.insertCell()
ibuttonCell.style.textAlign = 'center'
// INFO DIV --------------------------------------------------------------------------------- // INFO DIV ---------------------------------------------------------------------------------
let infoDiv = CreateNodeWithText(menuButtonDiv, texts.loading, 'div') let infoDiv = CreateNodeWithText(ibuttonCell, texts.loading, 'span')
infoDiv.setAttribute('id', 'infoMainDiv') infoDiv.setAttribute('id', 'infoMainDiv')
SetStyle(infoDiv, { SetStyle(infoDiv, {
color: '#ffffff', color: '#ffffff',
margin: '5px' margin: '5px'
}) })
// retry button ----------------------------------------------------------------------------------------------------------------
let retryButton = CreateNodeWithText(ibuttonCell, texts.retry, 'button')
SetStyle(retryButton, buttonStyle)
retryButton.style.display = 'none'
retryButton.setAttribute('id', 'retryButton')
retryButton.addEventListener('click', function () {
ConnectToServer(AfterLoad)
})
// window resize event listener ---------------------------------------
addEventListener(window, 'resize', function () {
menuButtonDiv.style.top = (window.innerHeight - 70) + 'px'
})
// passive button ---------------------------------------------------------------------------------------------------------------- // passive button ----------------------------------------------------------------------------------------------------------------
let passiveButton = CreateNodeWithText(buttonCell, texts.passiveMode, 'button') let passiveButton = CreateNodeWithText(buttonCell, texts.passiveMode, 'button')
SetStyle(passiveButton, buttonStyle) SetStyle(passiveButton, buttonStyle)
@ -1552,6 +1598,15 @@
} }
} }
function SafeGetElementById (id, todo) {
let element = document.getElementById(id)
if (element) {
todo(element)
} else {
Log(`Unable to safe get element by id: ${id}`)
}
}
function SetStyle (target, style) { function SetStyle (target, style) {
Object.keys(style).sort().forEach((key) => { Object.keys(style).sort().forEach((key) => {
target.style[key] = style[key] target.style[key] = style[key]