How to use readyPromise method in wpt

Best JavaScript code snippet using wpt

t.js

Source:t.js Github

copy

Full Screen

1je.prototyp t) {2 function i(e) {3 var t = e;4 if (void 0 !== t && t.sceneInfos.length > 0) {5 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {6 var u, h = i[s],7 p = h.layerRenderIndex,8 m = h.layerIndex,9 g = h.range,10 _ = h.gdbpUrl;11 switch (h.layerType) {12 case "0":13 case "1":14 break;15 case "2":16 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",17 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });18 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);19 break;20 case "3":21 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);22 break;23 case "4":24 break;25 case "8":26 u = f.appendDocTile(l, 0, p, o), c.push(u);27 break;28 case "10":29 var C = l + "/Ge DataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",30 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 }31 t; u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)32 }33 }34 a && d.readyPromise.then(function(e)) f.zoomToM3dLayer(e)35 })36 }37}38function n(e) {39 var i = e;40 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)41}42if (!h(e)) return new p("必须指定url");43var r, o, a = !0,44 s = !0,45 l = e,46 c = [];47h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));48var d = null,49 f = this;50if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });51else {52 var m = new XMLHttpRequest;53 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {54 var g = JSON.parse(m.responseText);55 g && i(g)56 }57}58return f._appendCollection.push(c), c59} {60 function i(e) {61 var t = e;62 if (void 0 !== t && t.sceneInfos.length > 0) {63 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {64 var u, h = i[s],65 p = h.layerRenderIndex,66 m = h.layerIndex,67 g = h.range,68 _ = h.gdbpUrl;69 switch (h.layerType) {70 case "0":71 case "1":72 break;73 case "2":74 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",75 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });76 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);77 break;78 case "3":79 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);80 break;81 case "4":82 break;83 case "8":84 u = f.appendDocTile(l, 0, p, o), c.push(u);85 break;86 case "10":87 var C = l + "/GeeDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",88 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 }.; u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)89 }90 }91 a && d.readyPromise.then(function(e) a f.zoomToM3dLayer(e)92 })93 }94 }95 function n(e) {96 var i = e;97 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)98 }99 if (!h(e)) return new p("必须指定url");100 var r, o, a = !0,101 s = !0,102 l = e,103 c = [];104 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));105 var d = null,106 f = this;107 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });108 else {109 var m = new XMLHttpRequest;110 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {111 var g = JSON.parse(m.responseText);112 g && i(g)113 }114 }115 return f._appendCollection.push(c), c116}117ppend = function(e, t) {118 function i(e) {119 var t = e;120 if (void 0 !== t && t.sceneInfos.length > 0) {121 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {122 var u, h = i[s],123 p = h.layerRenderIndex,124 m = h.layerIndex,125 g = h.range,126 _ = h.gdbpUrl;127 switch (h.layerType) {128 case "0":129 case "1":130 break;131 case "2":132 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",133 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });134 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);135 break;136 case "3":137 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);138 break;139 case "4":140 break;141 case "8":142 u = f.appendDocTile(l, 0, p, o), c.push(u);143 break;144 case "10":145 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",146 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });147 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)148 }149 }150 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })151 }152 }153 function n(e) {154 var i = e;155 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)156 }157 if (!h(e)) return new p("必须指定url");158 var r, o, a = !0,159 s = !0,160 l = e,161 c = [];162 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));163 var d = null,164 f = this;165 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.jetchJson().then(fe.ption(e) { i(e) });166 else {167 var m = new XMLHttpRequesr;168 of(m.tpeot "GET", l + "/GetDocInfo", !1), m.synd(null) p 200 === m.seatus.a169 var g = JSON.parse(m.responseText);170 g && i(g)171 }172}173return f._appendCollection.push(c), c174}175ppend = function(e, t) {176 function i(e) {177 var t = e;178 if (void 0 !== t && t.sceneInfos.length > 0) {179 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {180 var u, h = i[s],181 p = h.layerRenderIndex,182 m = h.layerIndex,183 g = h.range,184 _ = h.gdbpUrl;185 switch (h.layerType) {186 case "0":187 case "1":188 break;189 case "2":190 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",191 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });192 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);193 break;194 case "3":195 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);196 break;197 case "4":198 break;199 case "8":200 u = f.appendDocTile(l, 0, p, o), c.push(u);201 break;202 case "10":203 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",204 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });205 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)206 }207 }208 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })209 }210 }211 function n(e) {212 var i = e;213 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)214 }215 if (!h(e)) return new p("必须指定url");216 var r, o, a = !0,217 s = !0,218 l = e,219 c = [];220 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));221 var d = null,222 f = this;223 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.jetchJson().then(fe.ption(e) { i(e) });224 else {225 var m = new XMLHttpRequesr;226 of(m.tpeot "GET", l + "/GetDocInfo", !1), m.synd(null) p 200 === m.seatus.a227 var g = JSON.parse(m.responseText);228 g && i(g)229 }230}231return f._appendCollection.push(c), c232}233ppend = je.prototyp e.a234function i(e) {235 var t = e;236 if (void 0 !== t && t.sceneInfos.length > 0) {237 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {238 var u, h = i[s],239 p = h.layerRenderIndex,240 m = h.layerIndex,241 g = h.range,242 _ = h.gdbpUrl;243 switch (h.layerType) {244 case "0":245 case "1":246 break;247 case "2":248 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",249 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });250 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);251 break;252 case "3":253 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);254 break;255 case "4":256 break;257 case "8":258 u = f.appendDocTile(l, 0, p, o), c.push(u);259 break;260 case "10":261 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",262 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });263 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)264 }265 }266 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })267 }268}269function n(e) {270 var i = e;271 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)272}273if (!h(e)) return new p("必须指定url");274var r, o, a = !0,275 s = !0,276 l = e,277 c = [];278h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));279var d = null,280 f = this;281if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });282else {283 var m = new XMLHttpRequest;284 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {285 var g = JSON.parse(m.responseText);286 g && i(g)287 }288}289return f._appendCollection.push(c), c290}, ppend = je.prototyp e.a291function i(e) {292 var t = e;293 if (void 0 !== t && t.sceneInfos.length > 0) {294 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {295 var u, h = i[s],296 p = h.layerRenderIndex,297 m = h.layerIndex,298 g = h.range,299 _ = h.gdbpUrl;300 switch (h.layerType) {301 case "0":302 case "1":303 break;304 case "2":305 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",306 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });307 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);308 break;309 case "3":310 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);311 break;312 case "4":313 break;314 case "8":315 u = f.appendDocTile(l, 0, p, o), c.push(u);316 break;317 case "10":318 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",319 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });320 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)321 }322 }323 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })324 }325}326function n(e) {327 var i = e;328 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)329}330if (!h(e)) return new p("必须指定url");331var r, o, a = !0,332 s = !0,333 l = e,334 c = [];335h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));336var d = null,337 f = this;338if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });339else {340 var m = new XMLHttpRequest;341 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {342 var g = JSON.parse(m.responseText);343 g && i(g)344 }345}346return f._appendCollection.push(c), c347}, ppend = function(e, t) {348 function i(e) {349 var t = e;350 if (void 0 !== t && t.sceneInfos.length > 0) {351 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {352 var u, h = i[s],353 p = h.layerRenderIndex,354 m = h.layerIndex,355 g = h.range,356 _ = h.gdbpUrl;357 switch (h.layerType) {358 case "0":359 case "1":360 break;361 case "2":362 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",363 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });364 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);365 break;366 case "3":367 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);368 break;369 case "4":370 break;371 case "8":372 u = f.appendDocTile(l, 0, p, o), c.push(u);373 break;374 case "10":375 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",376 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });377 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)378 }379 }380 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })381 }382 }383 function n(e) {384 var i = e;385 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)386 }387 if (!h(e)) return new p("必须指定url");388 var r, o, a = !0,389 s = !0,390 l = e,391 c = [];392 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));393 var d = null,394 f = this;395 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });396 else {397 var m = new XMLHttpRequest;398 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {399 var g = JSON.parse(m.responseText);400 g && i(g)401 }402 }403 return f._appendCollection.push(c), c404 },405 function i(e) {406 var t = e;407 if (void 0 !== t && t.sceneInfos.length > 0) {408 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r;409 ++s) {410 var u, h = i[s],411 p = h.layerRenderIndex,412 m = h.layerIndex,413 g = h.range,414 _ = h.gdbpUrl;415 switch (h.layerType) {416 case "0":417 case "1":418 break;419 case "2":420 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",421 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });422 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);423 break;424 case "3":425 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);426 break;427 case "4":428 break;429 case "8":430 u = f.appendDocTile(l, 0, p, o), c.push(u);431 break;432 case "10":433 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",434 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });435 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)436 }437 }438 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })439 }440 }441function n(e) {442 var i = e;443 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)444}445if (!h(e)) return new p("必须指定url");446var r, o, a = !0,447 s = !0,448 l = e,449 c = [];450h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));451var d = null,452 f = this;453if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });454else {455 var m = new XMLHttpRequest;456 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {457 var g = JSON.parse(m.responseText);458 g && i(g)459 }460}461return f._appendCollection.push(c), c462}463case "3":464 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);465 break;466case "4":467 break;468case "8":469 u = f.appendDocTile(l, 0, p, o), c.push(u);470 break;471case "10":472 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",473 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });474 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)475 }476 }477 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })478 }479 }480 function n(e) {481 var i = e;482 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)483 }484 if (!h(e)) return new p("必须指定url");485 var r, o, a = !0,486 s = !0,487 l = e,488 c = [];489 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));490 var d = null,491 f = this;492 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });493 else {494 var m = new XMLHttpRequest;495 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {496 var g = JSON.parse(m.responseText);497 g && i(g)498 }499 }500 return f._appendCollection.push(c), c501 }, ppend = je.prototyp e.a502 function i(e) {503 var t = e;504 if (void 0 !== t && t.sceneInfos.length > 0) {505 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {506 var u, h = i[s],507 p = h.layerRenderIndex,508 m = h.layerIndex,509 g = h.range,510 _ = h.gdbpUrl;511 switch (h.layerType) {512 case "0":513 case "1":514 break;515 case "2":516 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",517 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });518 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);519 break;520 case "3":521 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);522 break;523 case "4":524 break;525 case "8":526 u = f.appendDocTile(l, 0, p, o), c.push(u);527 break;528 case "10":529 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",530 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });531 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)532 }533 }534 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })535 }536 }537 function n(e) {538 var i = e;539 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)540 }541 if (!h(e)) return new p("必须指定url");542 var r, o, a = !0,543 s = !0,544 l = e,545 c = [];546 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));547 var d = null,548 f = this;549 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });550 else {551 var m = new XMLHttpRequest;552 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {553 var g = JSON.parse(m.responseText);554 g && i(g)555 }556 }557 return f._appendCollection.push(c), c558 }, ppend = function(e, t) {559 function i(e) {560 var t = e;561 if (void 0 !== t && t.sceneInfos.length > 0) {562 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r; ++s) {563 var u, h = i[s],564 p = h.layerRenderIndex,565 m = h.layerIndex,566 g = h.range,567 _ = h.gdbpUrl;568 switch (h.layerType) {569 case "0":570 case "1":571 break;572 case "2":573 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",574 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });575 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);576 break;577 case "3":578 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);579 break;580 case "4":581 break;582 case "8":583 u = f.appendDocTile(l, 0, p, o), c.push(u);584 break;585 case "10":586 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",587 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });588 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)589 }590 }591 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })592 }593 }594 function n(e) {595 var i = e;596 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)597 }598 if (!h(e)) return new p("必须指定url");599 var r, o, a = !0,600 s = !0,601 l = e,602 c = [];603 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));604 var d = null,605 f = this;606 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });607 else {608 var m = new XMLHttpRequest;609 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {610 var g = JSON.parse(m.responseText);611 g && i(g)612 }613 }614 return f._appendCollection.push(c), c615 },616 function i(e) {617 var t = e;618 if (void 0 !== t && t.sceneInfos.length > 0) {619 for (var i = t.sceneInfos[0].layers, r = i.length, s = 0; s < r;620 ++s) {621 var u, h = i[s],622 p = h.layerRenderIndex,623 m = h.layerIndex,624 g = h.range,625 _ = h.gdbpUrl;626 switch (h.layerType) {627 case "0":628 case "1":629 break;630 case "2":631 var v = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",632 y = new Ce({ url: v, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });633 u = d = f.viewer.scene.primitives.add(y), c.push(u), d.readyPromise.then(n);634 break;635 case "3":636 u = f.appendMapGISTerrain(l, 0, p, o, g), c.push(u);637 break;638 case "4":639 break;640 case "8":641 u = f.appendDocTile(l, 0, p, o), c.push(u);642 break;643 case "10":644 var C = l + "/GetDataStreams?sceneIndex=0&layerIndex=" + p + "&Level=0&Row=0&Col=0",645 b = new Ce({ url: C, layerRenderIndex: p, layerIndex: m, gdbpUrl: _, show: h.isVisible, igserver: !0 });646 u = d = f.viewer.scene.primitives.add(b), c.push(u), d.readyPromise.then(n)647 }648 }649 a && d.readyPromise.then(function(e) { f.zoomToM3dLayer(e) })650 }651 }652 function n(e) {653 var i = e;654 h(t.loaded) && "function" == typeof t.loaded && t.loaded(i)655 }656 if (!h(e)) return new p("必须指定url");657 var r, o, a = !0,658 s = !0,659 l = e,660 c = [];661 h(t) && (h(t.proxy) && (o = new z(t.proxy)), u(t.proxy, void 0), a = u(t.autoReset, !0), s = u(t.synchronous, !0));662 var d = null,663 f = this;664 if (s) r = new b({ url: l + "/GetDocInfo", proxy: o }), r.fetchJson().then(function(e) { i(e) });665 else {666 var m = new XMLHttpRequest;667 if (m.open("GET", l + "/GetDocInfo", !1), m.send(null), 200 === m.status) {668 var g = JSON.parse(m.responseText);669 g && i(g)670 }671 }672 return f._appendCollection.push(c), c...

Full Screen

Full Screen

database.ts

Source:database.ts Github

copy

Full Screen

1/**2 * Manages the Trivia database.3 *4 * @author Annika5 */6import type {TriviaGame, TriviaHistory, TriviaLeaderboardData, TriviaLeaderboardScore, TriviaQuestion} from "./trivia";7import {FS} from "../../../lib";8import {formatSQLArray} from "../../../lib/utils";9import type {Statement} from "../../../lib/sql";10export type Leaderboard = 'alltime' | 'nonAlltime' | 'cycle';11/**12 * Keys are different Trivia leaderboards.13 * Values are the corresponding integer values of the SQLite `leaderboard` column.14 */15export const LEADERBOARD_ENUM: Record<Leaderboard, number> = {16 alltime: 1,17 nonAlltime: 0,18 cycle: 2,19};20type TriviaLeaderboards = Record<Leaderboard, TriviaLeaderboardData>;21export interface TriviaDatabase {22 updateLeaderboardForUser(23 userid: ID,24 additions: Record<Leaderboard, TriviaLeaderboardScore>25 ): Promise<void> | void;26 addHistory(history: Iterable<TriviaHistory>): Promise<void> | void;27 addQuestions(questions: Iterable<TriviaQuestion>): Promise<void> | void;28 addQuestionSubmissions(questions: Iterable<TriviaQuestion>): Promise<void> | void;29 setShouldMoveEventQuestions(shouldMove: boolean): Promise<void> | void;30 mergeLeaderboardEntries(from: ID, to: ID): Promise<void> | void;31 shouldMoveEventQuestions(): Promise<boolean> | boolean;32 moveQuestionToCategory(question: string, newCategory: string): Promise<void> | void;33 migrateCategory(sourceCategory: string, targetCategory: string): Promise<number> | number;34 acceptSubmissions(submissions: string[]): Promise<void> | void;35 editQuestion(oldQuestionText: string, newQuestionText?: string, newAnswers?: string[]): Promise<void>;36 getHistory(numberOfLines: number): Promise<TriviaGame[]> | TriviaGame[];37 getScoresForLastGame(): Promise<{[k: string]: number}> | {[k: string]: number};38 getQuestions(39 categories: string[] | 'all',40 limit: number,41 options: {order: 'newestfirst' | 'oldestfirst' | 'random'}42 ): Promise<TriviaQuestion[]> | TriviaQuestion[];43 getLeaderboardEntry(44 id: ID,45 leaderboard: Leaderboard46 ): Promise<TriviaLeaderboardScore | null> | TriviaLeaderboardScore | null;47 getLeaderboards(): Promise<TriviaLeaderboards> | TriviaLeaderboards;48 checkIfQuestionExists(questionText: string): Promise<boolean> | boolean;49 ensureQuestionExists(questionText: string): Promise<void> | void;50 ensureQuestionDoesNotExist(questionText: string): Promise<void> | void;51 getSubmissions(): Promise<TriviaQuestion[]> | TriviaQuestion[];52 getQuestionCounts(): Promise<{[k: string]: number, total: number}> | {[k: string]: number, total: number};53 searchQuestions(54 search: string,55 options: {searchSubmissions: boolean, caseSensitive?: boolean}56 ): Promise<TriviaQuestion[]> | TriviaQuestion[];57 clearSubmissions(): Promise<void> | void;58 clearCategory(category: string): Promise<void> | void;59 clearCycleLeaderboard(): Promise<void> | void;60 deleteQuestion(questionText: string): Promise<void> | void;61 deleteLeaderboardEntry(userid: ID, leaderboard: Leaderboard): Promise<void> | void;62 deleteSubmissions(submissions: string[]): Promise<void> | void;63}64export class TriviaSQLiteDatabase implements TriviaDatabase {65 readyPromise: Promise<void> | null;66 private legacyJSONPath?: string;67 // adding data68 private leaderboardInsertion: Statement | null;69 private questionInsertion: Statement | null;70 private answerInsertion: Statement | null;71 private gameHistoryInsertion: Statement | null;72 private scoreHistoryInsertion: Statement | null;73 private updateMoveEventQuestions: Statement | null;74 // modifying data75 private categoryChangeQuery: Statement | null;76 private leaderboardChangeQuery: Statement | null;77 private migrateCategoryQuery: Statement | null;78 // fetching data79 private historyQuery: Statement | null;80 private historyScoresQuery: Statement | null;81 private allQuestionsRandomOrderQuery: Statement | null;82 private allQuestionsNewestFirstQuery: Statement | null;83 private allQuestionsOldestFirstQuery: Statement | null;84 private answersQuery: Statement | null;85 private submissionsQuery: Statement | null;86 private leaderboardQuery: Statement | null;87 private leaderboardByUserQuery: Statement | null;88 private scoreAndPointsByUser: Statement | null;89 private eventQuestionQuery: Statement | null;90 private categoriesQuery: Statement | null;91 private questionCountQuery: Statement | null;92 private categoryQuestionCountQuery: Statement | null;93 private questionSearchQuery: Statement | null;94 private questionExistsQuery: Statement | null;95 // deleting data96 private clearAllSubmissionsQuery: Statement | null;97 private clearCategoryQuery: Statement | null;98 private clearCycleLeaderboardQuery: Statement | null;99 private deleteQuestionQuery: Statement | null;100 private leaderboardDeletionQuery: Statement | null;101 constructor(legacyJSONPath?: string) {102 this.legacyJSONPath = legacyJSONPath;103 this.leaderboardInsertion = null;104 this.questionInsertion = null;105 this.answerInsertion = null;106 this.gameHistoryInsertion = null;107 this.scoreHistoryInsertion = null;108 this.updateMoveEventQuestions = null;109 this.categoryChangeQuery = null;110 this.leaderboardChangeQuery = null;111 this.migrateCategoryQuery = null;112 this.historyQuery = null;113 this.historyScoresQuery = null;114 this.allQuestionsRandomOrderQuery = null;115 this.allQuestionsNewestFirstQuery = null;116 this.allQuestionsOldestFirstQuery = null;117 this.answersQuery = null;118 this.submissionsQuery = null;119 this.leaderboardQuery = null;120 this.leaderboardByUserQuery = null;121 this.scoreAndPointsByUser = null;122 this.eventQuestionQuery = null;123 this.categoriesQuery = null;124 this.questionCountQuery = null;125 this.categoryQuestionCountQuery = null;126 this.questionSearchQuery = null;127 this.questionExistsQuery = null;128 this.clearAllSubmissionsQuery = null;129 this.clearCategoryQuery = null;130 this.clearCycleLeaderboardQuery = null;131 this.deleteQuestionQuery = null;132 this.leaderboardDeletionQuery = null;133 this.readyPromise = this.prepareStatements().then(() => {134 void this.convertLegacyJSON();135 this.readyPromise = null;136 });137 }138 /***************************139 * Methods for adding data *140 ***************************/141 async updateLeaderboardForUser(142 userid: ID,143 additions: Record<Leaderboard, TriviaLeaderboardScore>,144 ): Promise<void> {145 if (this.readyPromise) await this.readyPromise;146 if (!Config.usesqlite) {147 throw new Chat.ErrorMessage(`Can't update the leaderboard for ${userid} because SQLite is not enabled.`);148 }149 for (const [lb, discrim] of Object.entries(LEADERBOARD_ENUM) as [Leaderboard, number][]) {150 if (!additions[lb]) continue;151 await this.leaderboardChangeQuery!.run({152 score: additions[lb]!.score,153 totalPoints: additions[lb]!.totalPoints,154 totalCorrectAnswers: additions[lb]!.totalCorrectAnswers,155 userid,156 leaderboard: discrim,157 });158 }159 }160 async addHistory(history: Iterable<TriviaHistory>) {161 if (this.readyPromise) await this.readyPromise;162 if (!Config.usesqlite) {163 throw new Chat.ErrorMessage(`Can't add a Trivia game to the history because SQLite is not enabled.`);164 }165 const res = await Chat.database.transaction('addHistory', {166 history,167 gameHistoryInsertion: this.gameHistoryInsertion!.toString(),168 scoreHistoryInsertion: this.scoreHistoryInsertion!.toString(),169 });170 if (!res) throw new Error(`Error updating Trivia history.`);171 }172 async addQuestions(questions: Iterable<TriviaQuestion>) {173 if (this.readyPromise) await this.readyPromise;174 if (!Config.usesqlite) {175 throw new Chat.ErrorMessage(`Can't add a Trivia question because SQLite is not enabled.`);176 }177 const res = await Chat.database.transaction('addQuestions', {178 questions,179 questionInsertion: this.questionInsertion!.toString(),180 answerInsertion: this.answerInsertion!.toString(),181 isSubmission: false,182 });183 if (!res) throw new Chat.ErrorMessage(`Error adding Trivia questions.`);184 }185 async addQuestionSubmissions(questions: Iterable<TriviaQuestion>) {186 if (this.readyPromise) await this.readyPromise;187 if (!Config.usesqlite) {188 throw new Chat.ErrorMessage(`Can't submit a Trivia question for review because SQLite is not enabled.`);189 }190 const res = await Chat.database.transaction('addQuestions', {191 questions,192 questionInsertion: this.questionInsertion!.toString(),193 answerInsertion: this.answerInsertion!.toString(),194 isSubmission: true,195 });196 if (!res) throw new Chat.ErrorMessage(`Error adding Trivia questions for review.`);197 }198 async setShouldMoveEventQuestions(shouldMove: boolean) {199 if (this.readyPromise) await this.readyPromise;200 if (!Config.usesqlite) {201 throw new Chat.ErrorMessage(`Can't enable/disable moving event questions because SQLite is not enabled.`);202 }203 await this.updateMoveEventQuestions!.run([Number(shouldMove)]);204 }205 /******************************206 * Methods for modifying data *207 ******************************/208 async mergeLeaderboardEntries(from: ID, to: ID) {209 if (this.readyPromise) await this.readyPromise;210 if (!Config.usesqlite) {211 throw new Chat.ErrorMessage(`Can't merge ${from} and ${to}'s Trivia leaderboard entries because SQLite is not enabled.`);212 }213 for (const lbDiscrim of Object.values(LEADERBOARD_ENUM)) {214 const fromScores = await this.scoreAndPointsByUser!.get([from, lbDiscrim]) || {215 score: 0,216 totalCorrectAnswers: 0,217 totalPoints: 0,218 };219 const toScores = (await this.scoreAndPointsByUser!.get([to, lbDiscrim])) || {220 score: 0,221 totalCorrectAnswers: 0,222 totalPoints: 0,223 };224 toScores.score += fromScores.score;225 toScores.totalCorrectAnswers += fromScores.totalCorrectAnswers;226 toScores.totalPoints += fromScores.totalPoints;227 await Chat.database.run(228 this.leaderboardInsertion!,229 [to, toScores.score, toScores.totalPoints, toScores.totalCorrectAnswers, lbDiscrim]230 );231 await this.leaderboardDeletionQuery!.run([from, lbDiscrim]);232 }233 }234 async shouldMoveEventQuestions() {235 if (this.readyPromise) await this.readyPromise;236 if (!Config.usesqlite) {237 throw new Chat.ErrorMessage(`Can't find out if we are moving event questions because SQLite is not enabled.`);238 }239 return (await this.eventQuestionQuery!.get([]) || {value: false}).value;240 }241 async moveQuestionToCategory(question: string, newCategory: string) {242 if (this.readyPromise) await this.readyPromise;243 if (!Config.usesqlite) {244 throw new Chat.ErrorMessage(`Can't move question category because SQLite is not enabled.`);245 }246 await this.categoryChangeQuery!.run([newCategory, question]);247 }248 async migrateCategory(sourceCategory: string, targetCategory: string) {249 if (this.readyPromise) await this.readyPromise;250 if (!Config.usesqlite) {251 throw new Chat.ErrorMessage(`Can't migrate categories because SQLite is not enabled.`);252 }253 const {changes} = await this.migrateCategoryQuery!.run([targetCategory, sourceCategory]);254 return changes;255 }256 async acceptSubmissions(submissions: string[]) {257 if (this.readyPromise) await this.readyPromise;258 if (!Config.usesqlite) {259 throw new Chat.ErrorMessage(`Can't accept Trivia question submissions because SQLite is not enabled.`);260 }261 await Chat.database.run(262 `UPDATE trivia_questions SET is_submission = 1 WHERE question IN (${formatSQLArray(submissions)})`,263 [submissions]264 );265 }266 async editQuestion(oldQuestionText: string, newQuestionText?: string, newAnswers?: string[]) {267 if (this.readyPromise) await this.readyPromise;268 if (!Config.usesqlite) {269 throw new Chat.ErrorMessage(`Can't edit Trivia question because SQLite is not enabled.`);270 }271 await Chat.database.transaction('editQuestion', {272 oldQuestionText,273 newQuestionText,274 newAnswers,275 });276 }277 /*****************************278 * Methods for fetching data *279 *****************************/280 async getHistory(numberOfLines = 10): Promise<TriviaGame[]> {281 if (this.readyPromise) await this.readyPromise;282 if (!Config.usesqlite) {283 throw new Chat.ErrorMessage(`Can't get Trivia game history because SQLite is not enabled.`);284 }285 const rows = await this.historyQuery!.all([numberOfLines]);286 return rows.map((row: AnyObject): TriviaGame => ({287 mode: row.mode,288 length: /^d+$/.test(row.length) ? parseInt(row.length) || row.length : row.length,289 category: row.category,290 creator: row.creator || undefined,291 givesPoints: row.givesPoints !== 0,292 startTime: row.time,293 }));294 }295 async getScoresForLastGame(): Promise<{[k: string]: number}> {296 if (this.readyPromise) await this.readyPromise;297 if (!Config.usesqlite) {298 throw new Chat.ErrorMessage(`Can't get Trivia game scores because SQLite is not enabled.`);299 }300 const {game_id} = await this.historyQuery!.get([1]);301 const results: {[k: string]: number} = {};302 for (const row of await this.historyScoresQuery!.all([game_id])) {303 results[row.userid] = row.score;304 }305 return results;306 }307 async getQuestions(308 categories: string[] | 'all',309 limit: number,310 options: {order: 'newestfirst' | 'oldestfirst' | 'random'}311 ): Promise<TriviaQuestion[]> {312 if (this.readyPromise) await this.readyPromise;313 if (!Config.usesqlite) throw new Chat.ErrorMessage(`Can't get Trivia questions because SQLite is not enabled.`);314 let query;315 let args;316 if (categories === 'all') {317 if (options.order === 'newestfirst') {318 query = this.allQuestionsNewestFirstQuery!;319 } else if (options.order === 'oldestfirst') {320 query = this.allQuestionsOldestFirstQuery!;321 } else {322 query = this.allQuestionsRandomOrderQuery!;323 }324 args = [limit];325 } else {326 query = (327 `SELECT * FROM trivia_questions WHERE category IN (${formatSQLArray(categories)}) AND is_submission = 0 ORDER BY ${options.order === 'random' ? 'RANDOM()' : `added_at ${(options.order === 'oldestfirst' ? 'ASC' : 'DESC')}`} LIMIT ?`328 );329 args = [...categories, limit];330 }331 if (!query) throw new Error(`Couldn't prepare query`);332 const rows = await Chat.database.all(query, args);333 return Promise.all(rows.map((row: AnyObject) => this.rowToQuestion(row)));334 }335 async getLeaderboardEntry(id: ID, leaderboard: Leaderboard): Promise<TriviaLeaderboardScore | null> {336 if (this.readyPromise) await this.readyPromise;337 if (!Config.usesqlite) {338 throw new Chat.ErrorMessage(`Can't find out if user ${id} has a Trivia leaderboard entry because SQLite is not enabled.`);339 }340 const row = await this.leaderboardByUserQuery!.get([id, LEADERBOARD_ENUM[leaderboard]]);341 if (!row) return null;342 return {343 score: row.score,344 totalPoints: row.total_points,345 totalCorrectAnswers: row.total_correct_answers,346 };347 }348 async getLeaderboards(): Promise<TriviaLeaderboards> {349 if (this.readyPromise) await this.readyPromise;350 if (!Config.usesqlite) {351 throw new Chat.ErrorMessage(`Can't get the Trivia leaderboard scores because SQLite is not enabled.`);352 }353 const result: TriviaLeaderboards = {354 alltime: {},355 nonAlltime: {},356 cycle: {},357 };358 const rows = await this.leaderboardQuery!.all([]);359 for (const row of rows) {360 const entry = {361 score: row.score,362 totalPoints: row.total_points,363 totalCorrectAnswers: row.total_correct_answers,364 };365 let leaderboard: Leaderboard | null = null;366 for (const [lb, discrim] of Object.entries(LEADERBOARD_ENUM) as [Leaderboard, number][]) {367 if (discrim === row.leaderboard) leaderboard = lb;368 }369 if (leaderboard === null) throw new Error(`Invalid leaderboard value ${row.leaderboard}`);370 result[leaderboard][row.userid] = entry;371 }372 return result;373 }374 async checkIfQuestionExists(questionText: string) {375 if (this.readyPromise) await this.readyPromise;376 if (!Config.usesqlite) {377 throw new Chat.ErrorMessage(`Can't check if a Trivia question already exists because SQLite is not enabled.`);378 }379 const {count} = await this.questionExistsQuery!.get([questionText]);380 return count > 0;381 }382 async ensureQuestionExists(questionText: string) {383 if (!(await this.checkIfQuestionExists(questionText))) {384 throw new Chat.ErrorMessage(`Question "${questionText}" is not in the question database.`);385 }386 }387 async ensureQuestionDoesNotExist(questionText: string) {388 if (await this.checkIfQuestionExists(questionText)) {389 throw new Chat.ErrorMessage(`Question "${questionText}" is already in the question database.`);390 }391 }392 async getSubmissions(): Promise<TriviaQuestion[]> {393 if (this.readyPromise) await this.readyPromise;394 if (!Config.usesqlite) {395 throw new Chat.ErrorMessage(`Can't retrieve the Trivia question submissions because SQLite is not enabled.`);396 }397 const rows = await this.submissionsQuery!.all([]);398 return Promise.all(rows.map((row: AnyObject) => this.rowToQuestion(row)));399 }400 async getQuestionCounts(): Promise<{[k: string]: number, total: number}> {401 if (this.readyPromise) await this.readyPromise;402 if (!Config.usesqlite) {403 throw new Chat.ErrorMessage(`Can't retrieve the Trivia question counts because SQLite is not enabled.`);404 }405 const allCategories = (await this.categoriesQuery!.all([])).map((row: AnyObject) => row.category);406 const total = (await this.questionCountQuery!.get([])).count;407 const result: {[k: string]: number, total: number} = {total};408 for (const category of allCategories) {409 result[category] = (await this.categoryQuestionCountQuery!.get([category])).count;410 }411 return result;412 }413 async searchQuestions(414 search: string,415 options: {searchSubmissions: boolean, caseSensitive?: boolean}416 ): Promise<TriviaQuestion[]> {417 if (this.readyPromise) await this.readyPromise;418 if (!Config.usesqlite) {419 throw new Chat.ErrorMessage(`Can't search Trivia questions because SQLite is not enabled.`);420 }421 if (options.caseSensitive) await Chat.database.exec(`PRAGMA case_sensitive_like = true;`);422 const rows = await this.questionSearchQuery!.all([`%${search}%`, Number(options.searchSubmissions)]);423 if (options.caseSensitive) await Chat.database.exec(`PRAGMA case_sensitive_like = false;`);424 return Promise.all(rows.map((row: AnyObject) => this.rowToQuestion(row)));425 }426 /*****************************427 * Methods for deleting data *428 * ***************************/429 async clearSubmissions() {430 if (this.readyPromise) await this.readyPromise;431 if (!Config.usesqlite) {432 throw new Chat.ErrorMessage(`Can't clear the Trivia question submissions because SQLite is not enabled.`);433 }434 await Chat.database.run(this.clearAllSubmissionsQuery!, []);435 }436 async clearCategory(category: string) {437 if (this.readyPromise) await this.readyPromise;438 if (!Config.usesqlite) {439 throw new Chat.ErrorMessage(`Can't clear the Trivia questions in category "${category}" because SQLite is not enabled.`);440 }441 await Chat.database.run(this.clearCategoryQuery!, [category]);442 }443 async clearCycleLeaderboard() {444 if (this.readyPromise) await this.readyPromise;445 if (!Config.usesqlite) {446 throw new Chat.ErrorMessage(`Can't clear the cycle leaderboard because SQLite is not enabled.`);447 }448 await Chat.database.run(this.clearCycleLeaderboardQuery!);449 }450 async deleteQuestion(questionText: string) {451 if (this.readyPromise) await this.readyPromise;452 if (!Config.usesqlite) {453 throw new Chat.ErrorMessage(`Can't delete the Trivia question because SQLite is not enabled.`);454 }455 await Chat.database.run(this.deleteQuestionQuery!, [questionText]);456 }457 async deleteLeaderboardEntry(userid: ID, leaderboard: Leaderboard) {458 if (this.readyPromise) await this.readyPromise;459 if (!Config.usesqlite) {460 throw new Chat.ErrorMessage(`Can't delete leaderboard entries because SQLite is not enabled.`);461 }462 await this.leaderboardDeletionQuery!.run([userid, LEADERBOARD_ENUM[leaderboard]]);463 }464 async deleteSubmissions(submissions: string[]) {465 if (this.readyPromise) await this.readyPromise;466 if (!Config.usesqlite) {467 throw new Chat.ErrorMessage(`Can't delete Trivia question submissions because SQLite is not enabled.`);468 }469 const query = await Chat.database.prepare(470 `DELETE FROM trivia_questions WHERE is_submission = 1 AND question IN (${formatSQLArray(submissions)})`471 );472 await query?.run(submissions);473 }474 /****************************************475 * Private helper methods *476 * These are not part of the public API *477 ****************************************/478 private async prepareStatements() {479 if (!Config.usesqlite) return;480 if (Chat.databaseReadyPromise) await Chat.databaseReadyPromise;481 this.leaderboardInsertion = await Chat.database.prepare(482 `INSERT OR REPLACE INTO trivia_leaderboard (userid, score, total_points, total_correct_answers, leaderboard) VALUES (?, ?, ?, ?, ?) `483 );484 this.questionInsertion = await Chat.database.prepare(485 `INSERT OR IGNORE INTO trivia_questions (question, category, added_at, userid, is_submission) VALUES (?, ?, ?, ?, ?)`486 );487 this.answerInsertion = await Chat.database.prepare(488 `INSERT INTO trivia_answers (question_id, answer) VALUES (?, ?)`489 );490 this.gameHistoryInsertion = await Chat.database.prepare(491 `INSERT INTO trivia_game_history (mode, length, category, time, creator, gives_points) VALUES (?, ?, ?, ?, ?, ?)`492 );493 this.scoreHistoryInsertion = await Chat.database.prepare(494 `INSERT INTO trivia_game_scores (game_id, userid, score) VALUES (?, ?, ?)`495 );496 this.updateMoveEventQuestions = await Chat.database.prepare(497 `INSERT OR REPLACE INTO trivia_settings (key, value) VALUES ('moveEventQuestions', ?)`498 );499 this.categoryChangeQuery = await Chat.database.prepare(500 `UPDATE trivia_questions SET category = ? WHERE question = ?`501 );502 this.leaderboardChangeQuery = await Chat.database.prepare(503 `INSERT INTO trivia_leaderboard (userid, score, total_points, total_correct_answers, leaderboard) ` +504 `VALUES ($userid, $score, $totalPoints, $totalCorrectAnswers, $leaderboard) ON CONFLICT DO ` +505 `UPDATE SET score = score + $score, total_points = total_points + $totalPoints, total_correct_answers = total_correct_answers + $totalCorrectAnswers ` +506 `WHERE userid = $userid AND leaderboard = $leaderboard`507 );508 this.migrateCategoryQuery = await Chat.database.prepare(509 `UPDATE OR REPLACE trivia_questions SET category = ? WHERE category = ?`510 );511 this.historyQuery = await Chat.database.prepare(512 `SELECT * FROM trivia_game_history ORDER BY time DESC LIMIT ?`513 );514 this.historyScoresQuery = await Chat.database.prepare(`SELECT userid, score FROM trivia_game_scores WHERE game_id = ?`);515 this.allQuestionsRandomOrderQuery = await Chat.database.prepare(516 `SELECT * FROM trivia_questions WHERE category IN ('ae', 'pokemon', 'sg', 'sh') AND is_submission = 0 ORDER BY RANDOM() LIMIT ?`517 );518 this.allQuestionsNewestFirstQuery = await Chat.database.prepare(519 `SELECT * FROM trivia_questions WHERE category IN ('ae', 'pokemon', 'sg', 'sh') AND is_submission = 0 ORDER BY added_at DESC LIMIT ?`520 );521 this.allQuestionsOldestFirstQuery = await Chat.database.prepare(522 `SELECT * FROM trivia_questions WHERE category IN ('ae', 'pokemon', 'sg', 'sh') AND is_submission = 0 ORDER BY added_at ASC LIMIT ?`523 );524 this.answersQuery = await Chat.database.prepare(525 `SELECT * FROM trivia_answers WHERE question_id = ?`526 );527 this.submissionsQuery = await Chat.database.prepare(528 `SELECT * FROM trivia_questions WHERE is_submission = 1 ORDER BY category ASC`529 );530 this.leaderboardQuery = await Chat.database.prepare(531 `SELECT * FROM trivia_leaderboard`532 );533 this.leaderboardByUserQuery = await Chat.database.prepare(534 `SELECT * FROM trivia_leaderboard WHERE userid = ? AND leaderboard = ?`535 );536 this.scoreAndPointsByUser = await Chat.database.prepare(537 `SELECT score, total_points as totalPoints, total_correct_answers as totalCorrectAnswers FROM trivia_leaderboard WHERE userid = ? AND leaderboard = ?`538 );539 this.eventQuestionQuery = await Chat.database.prepare(540 `SELECT * FROM trivia_settings WHERE key = 'moveEventQuestions'`541 );542 this.categoriesQuery = await Chat.database.prepare(543 `SELECT DISTINCT category FROM trivia_questions`544 );545 this.questionCountQuery = await Chat.database.prepare(546 `SELECT count(*) AS count FROM trivia_questions WHERE is_submission = 0`547 );548 this.categoryQuestionCountQuery = await Chat.database.prepare(549 `SELECT count(*) AS count FROM trivia_questions WHERE category = ? AND is_submission = 0`550 );551 this.questionSearchQuery = await Chat.database.prepare(552 `SELECT * FROM trivia_questions WHERE question LIKE ? AND is_submission = ? ORDER BY added_at DESC`553 );554 this.questionExistsQuery = await Chat.database.prepare(555 `SELECT count(*) AS count FROM trivia_questions WHERE question = ?`556 );557 this.leaderboardDeletionQuery = await Chat.database.prepare(558 `DELETE FROM trivia_leaderboard WHERE userid = ? AND leaderboard = ?`559 );560 this.clearAllSubmissionsQuery = await Chat.database.prepare(561 `DELETE FROM trivia_questions WHERE is_submission = 1`562 );563 this.clearCategoryQuery = await Chat.database.prepare(564 `DELETE FROM trivia_questions WHERE category = ? AND is_submission = 0`565 );566 // The leaderboard is hardcoded, because we don't want to accidentally delete any other leaderboards.567 // If there is a need to reset other leaderboards in the future, this can be changed to accept a parameter.568 // Not a SQL injection vulnerability because LEADERBOARD_ENUM cannot be altered by the user.569 this.clearCycleLeaderboardQuery = await Chat.database.prepare(570 `DELETE FROM trivia_leaderboard WHERE leaderboard = ${LEADERBOARD_ENUM.cycle}`571 );572 this.deleteQuestionQuery = await Chat.database.prepare(573 `DELETE FROM trivia_questions WHERE question = ?`574 );575 await Chat.database.exec("PRAGMA foreign_keys = ON;");576 await Chat.database.loadExtension('server/chat-plugins/trivia/transactions.ts');577 }578 private async convertLegacyJSON() {579 if (!Config.usesqlite || !this.legacyJSONPath) return;580 if (this.readyPromise) await this.readyPromise;581 let triviaData;582 try {583 triviaData = JSON.parse(FS(this.legacyJSONPath).readIfExistsSync() || "{}");584 if (!triviaData) throw new Error(`no JSON`);585 } catch {586 return;587 }588 // handle _old_ JSON format (just in case)589 if (Array.isArray(triviaData.submissions)) {590 const oldSubmissions = triviaData.submissions as TriviaQuestion[];591 triviaData.submissions = {};592 for (const question of oldSubmissions) {593 if (!(question.category in triviaData.submissions)) triviaData.submissions[question.category] = [];594 triviaData.submissions[question.category].push(question);595 }596 }597 if (Array.isArray(triviaData.questions)) {598 const oldSubmissions = triviaData.questions as TriviaQuestion[];599 triviaData.questions = {};600 for (const question of oldSubmissions) {601 if (!(question.category in triviaData.questions)) triviaData.questions[question.category] = [];602 triviaData.questions[question.category].push(question);603 }604 }605 // convert leaderboard606 if (typeof triviaData.leaderboard === 'object') {607 for (const userid in triviaData.leaderboard) {608 const [score, totalGamePoints, totalCorrectAnswers] = triviaData.leaderboard[userid];609 await Chat.database.run(610 this.leaderboardInsertion!,611 [userid, score, totalGamePoints, totalCorrectAnswers, Number(true)]612 );613 }614 }615 if (typeof triviaData.altLeaderboard === 'object') {616 for (const userid in triviaData.altLeaderboard) {617 const [score, totalGamePoints, totalCorrectAnswers] = triviaData.altLeaderboard[userid];618 await Chat.database.run(619 this.leaderboardInsertion!,620 [userid, score, totalGamePoints, totalCorrectAnswers, Number(false)]621 );622 }623 }624 // convert questions625 const addedAt = Date.now();626 if (typeof triviaData.questions === 'object') {627 for (const category in triviaData.questions) {628 for (const question of triviaData.questions[category]) {629 if (!question.addedAt) question.addedAt = addedAt;630 if (!question.user) question.user = 'unknown user';631 question.question = question.question.trim();632 await this.addQuestions([question]);633 }634 }635 }636 if (typeof triviaData.submissions === 'object') {637 for (const category in triviaData.submissions) {638 for (const question of triviaData.submissions[category]) {639 if (!question.addedAt) question.addedAt = addedAt;640 if (!question.user) question.user = 'unknown user';641 question.question = question.question.trim();642 await this.addQuestionSubmissions([question]);643 }644 }645 }646 if (Array.isArray(triviaData.history)) {647 const now = Date.now();648 for (const game of triviaData.history) {649 if (!game.startTime) game.startTime = now;650 await this.addHistory([game]);651 }652 }653 if (triviaData.moveEventQuestions) {654 await this.setShouldMoveEventQuestions(true);655 }656 // move legacy JSON file657 try {658 await FS(this.legacyJSONPath).rename(this.legacyJSONPath + '.converted');659 } catch {}660 }661 private rowToQuestion(row: AnyObject): Promise<TriviaQuestion> {662 return Chat.database.all(this.answersQuery!, [row.question_id]).then(answerRows => ({663 question: row.question,664 category: row.category,665 answers: answerRows.map((answerRow: AnyObject) => answerRow.answer),666 user: row.userid,667 addedAt: row.added_at,668 }));669 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'API_KEY');3 if (err) return console.error(err);4 wpt.getTestResults(data.data.testId, function(err, data) {5 if (err) return console.error(err);6 console.log(data);7 });8});9{ [Error: Error: connect ECONNREFUSED]10 syscall: 'connect' }11{ [Error: Error: connect ECONNREFUSED]12 syscall: 'connect' }13var wpt = new WebPageTest('www.webpagetest.org', 'API_KEY');14{ [Error: Error: connect ECONNREFUSED]15 syscall: 'connect' }16{ [Error: Error: connect ECONNREFUSED]17 syscall: 'connect' }18{ [Error: Error: connect ECONNREFUSED]19 syscall: 'connect' }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var instance = new wpt('www.webpagetest.org');3var url = 'www.google.com';4var options = {5}6instance.runTest(url, options, function (err, data) {7 if (err) {8 console.log(err);9 } else {10 var testId = data.data.testId;11 console.log("Test Id is: " + testId);12 instance.getTestResults(testId, function (err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18 });19 }20});21var wpt = require('webpagetest');22var instance = new wpt('www.webpagetest.org');23var url = 'www.google.com';24var options = {25}26instance.runTest(url, options, function (err, data) {27 if (err) {28 console.log(err);29 } else {30 var testId = data.data.testId;31 console.log("Test Id is: " + testId);32 instance.getTestResults(testId, function (err, data) {33 if (err) {34 console.log(err);35 } else {36 console.log(data);37 }38 });39 }40});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('webpagetest');2const wptPromise = wptPromise('API_KEY');3const options = {4};5wptPromise.runTest(url, options)6.then(data => {7 console.log(data);8})9.catch(err => {10 console.log(err);11});12const wpt = require('webpagetest');13const wptPromise = wptPromise('API_KEY');14const options = {15};16wptPromise.ready((err) => {17 if (err) {18 console.log(err);19 } else {20 wptPromise.runTest(url, options)21 .then(data => {22 console.log(data);23 })24 .catch(err => {25 console.log(err);26 });27 }28});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var webPageTest = new wpt(options);5webPageTest.runTest(testUrl, function(err, data) {6 if (err) {7 console.log('Error: ' + err);8 } else {9 console.log('Test Response: ' + JSON.stringify(data));10 var testId = data.data.testId;11 webPageTest.getTestResults(testId, function(err, data) {12 if (err) {13 console.log('Error: ' + err);14 } else {15 console.log('Test Results: ' + JSON.stringify(data));16 }17 });18 }19});20webPageTest.runTest(testUrl, function(err, data) {21 if (err) {22 console.log('Error: ' + err);23 } else {24 console.log('Test Response: ' + JSON.stringify(data));25 var testId = data.data.testId;26 webPageTest.getTestResults(testId, function(err, data) {27 if (err) {28 console.log('Error: ' + err);29 } else {30 console.log('Test Results: ' + JSON.stringify(data));31 }32 });33 }34});35var webPageTest = new wpt(options);36var readyPromise = webPageTest.runTest(testUrl);37readyPromise.then(function(data) {38 console.log('Test Response: ' + JSON.stringify(data));39 var testId = data.data.testId;40 return webPageTest.getTestResults(testId);41}).then(function(data) {42 console.log('Test Results: ' + JSON.stringify(data));43}).catch(function(err) {44 console.log('Error: ' + err);45});46var webPageTest = new wpt(options);47var readyPromise = webPageTest.runTest(testUrl);48readyPromise.then(function(data) {49 console.log('Test Response: ' + JSON.stringify(data));50 var testId = data.data.testId;

Full Screen

Using AI Code Generation

copy

Full Screen

1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.6f8a2a1e9b9c9e7f2e8c2d7a6a5b6c7d');3 if (err) return console.error(err);4 console.log('Test ID: %s', data.data.testId);5 wpt.getTestStatus(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log('Test status: %s', data.data.statusText);8 });9});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful