speedtest_worker.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. HTML5 Speedtest v4.7 MPOT
  3. by Federico Dossena
  4. https://github.com/adolfintel/speedtest/
  5. GNU LGPLv3 License
  6. */
  7. // data reported to main thread
  8. var testStatus = -1 // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort/error
  9. var dlStatus = '' // download speed in megabit/s with 2 decimal digits
  10. var ulStatus = '' // upload speed in megabit/s with 2 decimal digits
  11. var pingStatus = '' // ping in milliseconds with 2 decimal digits
  12. var jitterStatus = '' // jitter in milliseconds with 2 decimal digits
  13. var clientIp = '' // client's IP address as reported by getIP.php
  14. var dlProgress = 0 //progress of download test 0-1
  15. var ulProgress = 0 //progress of upload test 0-1
  16. var pingProgress = 0 //progress of ping+jitter test 0-1
  17. var testId = 'noID' //test ID (sent back by telemetry if used, the string 'noID' otherwise)
  18. var log='' //telemetry log
  19. function tlog(s){if(settings.telemetry_level>=2){log+=Date.now()+': '+s+'\n'}}
  20. function tverb(s){if(settings.telemetry_level>=3){log+=Date.now()+': '+s+'\n'}}
  21. function twarn(s){if(settings.telemetry_level>=2){log+=Date.now()+' WARN: '+s+'\n';} console.warn(s)}
  22. // test settings. can be overridden by sending specific values with the start command
  23. var settings = {
  24. test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
  25. time_ul_max: 15, // max duration of upload test in seconds
  26. time_dl_max: 15, // max duration of download test in seconds
  27. time_auto: true, // if set to true, tests will take less time on faster connections
  28. time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
  29. time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
  30. count_ping: 10, // number of pings to perform in ping test
  31. url_dl: 'garbage.php', // path to a large file or garbage.php, used for download test. must be relative to this js file
  32. url_ul: 'empty.php', // path to an empty file, used for upload test. must be relative to this js file
  33. url_ping: 'empty.php', // path to an empty file, used for ping test. must be relative to this js file
  34. url_getIp: 'getIP.php', // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
  35. getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
  36. getIp_ispInfo_distance: 'km', //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
  37. xhr_dlMultistream: 10, // number of download streams to use (can be different if enable_quirks is active)
  38. xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
  39. xhr_ul_sendPostRequestBeforeStartingTest: true, //if set to true, a single empty POST request will be sent to the upload test URL. This bypasses bugs with CORS headers in some browsers.
  40. xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
  41. xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
  42. xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
  43. xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
  44. garbagePhp_chunkSize: 20, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
  45. enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
  46. ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
  47. overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
  48. useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
  49. telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
  50. url_telemetry: 'telemetry/telemetry.php', // path to the script that adds telemetry data to the database
  51. telemetry_extra: '' //extra data that can be passed to the telemetry through the settings
  52. }
  53. var xhr = null // array of currently active xhr requests
  54. var interval = null // timer used in tests
  55. var test_pointer = 0 //pointer to the next test to run inside settings.test_order
  56. /*
  57. this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
  58. */
  59. function url_sep (url) { return url.match(/\?/) ? '&' : '?'; }
  60. /*
  61. listener for commands from main thread to this worker.
  62. commands:
  63. -status: returns the current status as a JSON string containing testStatus, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
  64. -abort: aborts the current test
  65. -start: starts the test. optionally, settings can be passed as JSON.
  66. example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
  67. */
  68. this.addEventListener('message', function (e) {
  69. var params = e.data.split(' ')
  70. if (params[0] === 'status') { // return status
  71. postMessage(JSON.stringify({
  72. testState:testStatus,
  73. dlStatus:dlStatus,
  74. ulStatus:ulStatus,
  75. pingStatus:pingStatus,
  76. clientIp:clientIp,
  77. jitterStatus:jitterStatus,
  78. dlProgress:dlProgress,
  79. ulProgress:ulProgress,
  80. pingProgress:pingProgress,
  81. testId:testId
  82. }))
  83. }
  84. if (params[0] === 'start' && testStatus === -1) { // start new test
  85. testStatus = 0
  86. try {
  87. // parse settings, if present
  88. var s = {}
  89. try{
  90. var ss = e.data.substring(5)
  91. if (ss) s = JSON.parse(ss)
  92. }catch(e){ twarn('Error parsing custom settings JSON. Please check your syntax') }
  93. //copy custom settings
  94. for(var key in s){
  95. if(typeof settings[key] !== 'undefined') settings[key]=s[key]; else twarn("Unknown setting ignored: "+key);
  96. }
  97. // quirks for specific browsers. apply only if not overridden. more may be added in future releases
  98. if (settings.enable_quirks||(typeof s.enable_quirks !== 'undefined' && s.enable_quirks)) {
  99. var ua = navigator.userAgent
  100. if (/Firefox.(\d+\.\d+)/i.test(ua)) {
  101. if(typeof s.xhr_ulMultistream === 'undefined'){
  102. // ff more precise with 1 upload stream
  103. settings.xhr_ulMultistream = 1
  104. }
  105. }
  106. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  107. if(typeof s.xhr_dlMultistream === 'undefined'){
  108. // edge more precise with 3 download streams
  109. settings.xhr_dlMultistream = 3
  110. }
  111. }
  112. if (/Chrome.(\d+)/i.test(ua) && (!!self.fetch)) {
  113. if(typeof s.xhr_dlMultistream === 'undefined'){
  114. // chrome more precise with 5 streams
  115. settings.xhr_dlMultistream = 5
  116. }
  117. }
  118. }
  119. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  120. //Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
  121. settings.forceIE11Workaround = true
  122. }
  123. if (/Chrome.(\d+)/i.test(ua)&&/Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)){ //cheap af
  124. //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
  125. settings.xhr_ul_blob_megabytes=4;
  126. }
  127. if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
  128. //Safari also needs the IE11 workaround but only for the MPOT version
  129. settings.forceIE11Workaround = true
  130. }
  131. //telemetry_level has to be parsed and not just copied
  132. if(typeof s.telemetry_level !== 'undefined') settings.telemetry_level = s.telemetry_level === 'basic' ? 1 : s.telemetry_level === 'full' ? 2 : s.telemetry_level === 'debug' ? 3 : 0; // telemetry level
  133. //transform test_order to uppercase, just in case
  134. settings.test_order=settings.test_order.toUpperCase();
  135. } catch (e) { twarn('Possible error in custom test settings. Some settings might not have been applied. Exception: '+e) }
  136. // run the tests
  137. tverb(JSON.stringify(settings))
  138. test_pointer=0;
  139. var iRun=false,dRun=false,uRun=false,pRun=false;
  140. var runNextTest=function(){
  141. if(testStatus==5) return;
  142. if(test_pointer>=settings.test_order.length){ //test is finished
  143. if(settings.telemetry_level>0)
  144. sendTelemetry(function(id){testStatus=4; if(id!=-1)testId=id})
  145. else testStatus=4
  146. return;
  147. }
  148. switch(settings.test_order.charAt(test_pointer)){
  149. case 'I':{test_pointer++; if(iRun) {runNextTest(); return;} else iRun=true; getIp(runNextTest);} break;
  150. case 'D':{test_pointer++; if(dRun) {runNextTest(); return;} else dRun=true; testStatus=1; dlTest(runNextTest);} break;
  151. case 'U':{test_pointer++; if(uRun) {runNextTest(); return;} else uRun=true; testStatus=3; ulTest(runNextTest);} break;
  152. case 'P':{test_pointer++; if(pRun) {runNextTest(); return;} else pRun=true; testStatus=2; pingTest(runNextTest);} break;
  153. case '_':{test_pointer++; setTimeout(runNextTest,1000);} break;
  154. default: test_pointer++;
  155. }
  156. }
  157. runNextTest()
  158. }
  159. if (params[0] === 'abort') { // abort command
  160. tlog('manually aborted')
  161. clearRequests() // stop all xhr activity
  162. runNextTest=null;
  163. if (interval) clearInterval(interval) // clear timer if present
  164. if (settings.telemetry_level > 1) sendTelemetry(function(){})
  165. testStatus = 5; dlStatus = ''; ulStatus = ''; pingStatus = ''; jitterStatus = '' // set test as aborted
  166. }
  167. })
  168. // stops all XHR activity, aggressively
  169. function clearRequests () {
  170. tverb('stopping pending XHRs')
  171. if (xhr) {
  172. for (var i = 0; i < xhr.length; i++) {
  173. try { xhr[i].onprogress = null; xhr[i].onload = null; xhr[i].onerror = null } catch (e) { }
  174. try { xhr[i].upload.onprogress = null; xhr[i].upload.onload = null; xhr[i].upload.onerror = null } catch (e) { }
  175. try { xhr[i].abort() } catch (e) { }
  176. try { delete (xhr[i]) } catch (e) { }
  177. }
  178. xhr = null
  179. }
  180. }
  181. // gets client's IP using url_getIp, then calls the done function
  182. var ipCalled = false // used to prevent multiple accidental calls to getIp
  183. var ispInfo=""; //used for telemetry
  184. function getIp (done) {
  185. tverb('getIp')
  186. if (ipCalled) return; else ipCalled = true // getIp already called?
  187. var startT=new Date().getTime();
  188. xhr = new XMLHttpRequest()
  189. xhr.onload = function () {
  190. tlog('IP: '+xhr.responseText+', took '+(new Date().getTime()-startT)+'ms')
  191. try{
  192. var data=JSON.parse(xhr.responseText)
  193. clientIp=data.processedString
  194. ispInfo=data.rawIspInfo
  195. }catch(e){
  196. clientIp = xhr.responseText
  197. ispInfo=''
  198. }
  199. done()
  200. }
  201. xhr.onerror = function () {
  202. tlog('getIp failed, took '+(new Date().getTime()-startT)+'ms')
  203. done()
  204. }
  205. xhr.open('GET', settings.url_getIp + url_sep(settings.url_getIp) + (settings.getIp_ispInfo?("isp=true"+(settings.getIp_ispInfo_distance?("&distance="+settings.getIp_ispInfo_distance+"&"):"&")):"&") + 'r=' + Math.random(), true)
  206. xhr.send()
  207. }
  208. // download test, calls done function when it's over
  209. var dlCalled = false // used to prevent multiple accidental calls to dlTest
  210. function dlTest (done) {
  211. tverb('dlTest')
  212. if (dlCalled) return; else dlCalled = true // dlTest already called?
  213. var totLoaded = 0.0, // total number of loaded bytes
  214. startT = new Date().getTime(), // timestamp when test was started
  215. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  216. graceTimeDone = false, //set to true after the grace time is past
  217. failed = false // set to true if a stream fails
  218. xhr = []
  219. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  220. var testStream = function (i, delay) {
  221. setTimeout(function () {
  222. if (testStatus !== 1) return // delayed stream ended up starting after the end of the download test
  223. tverb('dl test stream started '+i+' '+delay)
  224. var prevLoaded = 0 // number of bytes loaded last time onprogress was called
  225. var x = new XMLHttpRequest()
  226. xhr[i] = x
  227. xhr[i].onprogress = function (event) {
  228. tverb('dl stream progress event '+i+' '+event.loaded)
  229. if (testStatus !== 1) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the download test
  230. // progress event, add number of new loaded bytes to totLoaded
  231. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  232. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  233. totLoaded += loadDiff
  234. prevLoaded = event.loaded
  235. }.bind(this)
  236. xhr[i].onload = function () {
  237. // the large file has been loaded entirely, start again
  238. tverb('dl stream finished '+i)
  239. try { xhr[i].abort() } catch (e) { } // reset the stream data to empty ram
  240. testStream(i, 0)
  241. }.bind(this)
  242. xhr[i].onerror = function () {
  243. // error
  244. tverb('dl stream failed '+i)
  245. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  246. try { xhr[i].abort() } catch (e) { }
  247. delete (xhr[i])
  248. if (settings.xhr_ignoreErrors === 1) testStream(i, 0) //restart stream
  249. }.bind(this)
  250. // send xhr
  251. try { if (settings.xhr_dlUseBlob) xhr[i].responseType = 'blob'; else xhr[i].responseType = 'arraybuffer' } catch (e) { }
  252. xhr[i].open('GET', settings.url_dl + url_sep(settings.url_dl) + 'r=' + Math.random() + '&ckSize=' + settings.garbagePhp_chunkSize, true) // random string to prevent caching
  253. xhr[i].send()
  254. }.bind(this), 1 + delay)
  255. }.bind(this)
  256. // open streams
  257. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  258. testStream(i, settings.xhr_multistreamDelay * i)
  259. }
  260. // every 200ms, update dlStatus
  261. interval = setInterval(function () {
  262. tverb('DL: '+dlStatus+(graceTimeDone?'':' (in grace time)'))
  263. var t = new Date().getTime() - startT
  264. if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000)
  265. if (t < 200) return
  266. if (!graceTimeDone){
  267. if (t > 1000 * settings.time_dlGraceTime){
  268. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  269. startT = new Date().getTime()
  270. bonusT = 0
  271. totLoaded = 0.0
  272. }
  273. graceTimeDone = true;
  274. }
  275. }else{
  276. var speed = totLoaded / (t / 1000.0)
  277. if(settings.time_auto){
  278. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  279. var bonus=6.4*speed/100000
  280. bonusT+=bonus>800?800:bonus
  281. }
  282. //update status
  283. dlStatus = ((speed * 8 * settings.overheadCompensationFactor)/(settings.useMebibits?1048576:1000000)).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
  284. if ((((t+ bonusT) / 1000.0) > settings.time_dl_max) || failed) { // test is over, stop streams and timer
  285. if (failed || isNaN(dlStatus)) dlStatus = 'Fail'
  286. clearRequests()
  287. clearInterval(interval)
  288. dlProgress = 1
  289. tlog('dlTest: '+dlStatus+', took '+(new Date().getTime() - startT)+'ms')
  290. done()
  291. }
  292. }
  293. }.bind(this), 200)
  294. }
  295. // upload test, calls done function whent it's over
  296. var ulCalled = false // used to prevent multiple accidental calls to ulTest
  297. function ulTest (done) {
  298. tverb('ulTest')
  299. if (ulCalled) return; else ulCalled = true // ulTest already called?
  300. // garbage data for upload test
  301. var r = new ArrayBuffer(1048576)
  302. var maxInt=Math.pow(2,32)-1;
  303. try { r = new Uint32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random()*maxInt } catch (e) { }
  304. var req = []
  305. var reqsmall = []
  306. for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r)
  307. req = new Blob(req)
  308. r = new ArrayBuffer(262144)
  309. try { r = new Uint32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random()*maxInt } catch (e) { }
  310. reqsmall.push(r)
  311. reqsmall = new Blob(reqsmall)
  312. var testFunction=function(){
  313. var totLoaded = 0.0, // total number of transmitted bytes
  314. startT = new Date().getTime(), // timestamp when test was started
  315. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  316. graceTimeDone = false, //set to true after the grace time is past
  317. failed = false // set to true if a stream fails
  318. xhr = []
  319. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  320. var testStream = function (i, delay) {
  321. setTimeout(function () {
  322. if (testStatus !== 3) return // delayed stream ended up starting after the end of the upload test
  323. tverb('ul test stream started '+i+' '+delay)
  324. var prevLoaded = 0 // number of bytes transmitted last time onprogress was called
  325. var x = new XMLHttpRequest()
  326. xhr[i] = x
  327. var ie11workaround
  328. if (settings.forceIE11Workaround) ie11workaround = true; else {
  329. try {
  330. xhr[i].upload.onprogress
  331. ie11workaround = false
  332. } catch (e) {
  333. ie11workaround = true
  334. }
  335. }
  336. if (ie11workaround) {
  337. // IE11 workarond: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
  338. xhr[i].onload = function () {
  339. tverb('ul stream progress event (ie11wa)')
  340. totLoaded += reqsmall.size;
  341. testStream(i, 0)
  342. }
  343. xhr[i].onerror = function () {
  344. // error, abort
  345. tverb('ul stream failed (ie11wa)')
  346. if (settings.xhr_ignoreErrors === 0) failed = true //abort
  347. try { xhr[i].abort() } catch (e) { }
  348. delete (xhr[i])
  349. if (settings.xhr_ignoreErrors === 1) testStream(i,0); //restart stream
  350. }
  351. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  352. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  353. xhr[i].send(reqsmall)
  354. } else {
  355. // REGULAR version, no workaround
  356. xhr[i].upload.onprogress = function (event) {
  357. tverb('ul stream progress event '+i+' '+event.loaded)
  358. if (testStatus !== 3) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the upload test
  359. // progress event, add number of new loaded bytes to totLoaded
  360. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  361. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  362. totLoaded += loadDiff
  363. prevLoaded = event.loaded
  364. }.bind(this)
  365. xhr[i].upload.onload = function () {
  366. // this stream sent all the garbage data, start again
  367. tverb('ul stream finished '+i)
  368. testStream(i, 0)
  369. }.bind(this)
  370. xhr[i].upload.onerror = function () {
  371. tverb('ul stream failed '+i)
  372. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  373. try { xhr[i].abort() } catch (e) { }
  374. delete (xhr[i])
  375. if (settings.xhr_ignoreErrors === 1) testStream(i, 0) //restart stream
  376. }.bind(this)
  377. // send xhr
  378. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  379. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  380. xhr[i].send(req)
  381. }
  382. }.bind(this), 1)
  383. }.bind(this)
  384. // open streams
  385. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  386. testStream(i, settings.xhr_multistreamDelay * i)
  387. }
  388. // every 200ms, update ulStatus
  389. interval = setInterval(function () {
  390. tverb('UL: '+ulStatus+(graceTimeDone?'':' (in grace time)'))
  391. var t = new Date().getTime() - startT
  392. if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000)
  393. if (t < 200) return
  394. if (!graceTimeDone){
  395. if (t > 1000 * settings.time_ulGraceTime){
  396. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  397. startT = new Date().getTime()
  398. bonusT=0
  399. totLoaded = 0.0
  400. }
  401. graceTimeDone = true;
  402. }
  403. }else{
  404. var speed = totLoaded / (t / 1000.0)
  405. if(settings.time_auto){
  406. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  407. var bonus=6.4*speed/100000
  408. bonusT+=bonus>800?800:bonus
  409. }
  410. //update status
  411. ulStatus = ((speed * 8 * settings.overheadCompensationFactor)/(settings.useMebibits?1048576:1000000)).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
  412. if ((((t + bonusT) / 1000.0) > settings.time_ul_max) || failed) { // test is over, stop streams and timer
  413. if (failed || isNaN(ulStatus)) ulStatus = 'Fail'
  414. clearRequests()
  415. clearInterval(interval)
  416. ulProgress = 1
  417. tlog('ulTest: '+ulStatus+', took '+(new Date().getTime() - startT)+'ms')
  418. done()
  419. }
  420. }
  421. }.bind(this), 200)
  422. }.bind(this);
  423. if(settings.xhr_ul_sendPostRequestBeforeStartingTest){
  424. tverb('Sending POST request before performing upload test');
  425. xhr=[];
  426. xhr[0]=new XMLHttpRequest();
  427. xhr[0].onload=xhr[0].onerror=function(){
  428. tverb('POST request sent, starting upload test');
  429. testFunction();
  430. }.bind(this);
  431. xhr[0].open('POST',settings.url_ul);
  432. xhr[0].send();
  433. }else testFunction();
  434. }
  435. // ping+jitter test, function done is called when it's over
  436. var ptCalled = false // used to prevent multiple accidental calls to pingTest
  437. function pingTest (done) {
  438. tverb('pingTest')
  439. if (ptCalled) return; else ptCalled = true // pingTest already called?
  440. var startT=new Date().getTime(); //when the test was started
  441. var prevT = null // last time a pong was received
  442. var ping = 0.0 // current ping value
  443. var jitter = 0.0 // current jitter value
  444. var i = 0 // counter of pongs received
  445. var prevInstspd = 0 // last ping time, used for jitter calculation
  446. xhr = []
  447. // ping function
  448. var doPing = function () {
  449. tverb('ping')
  450. pingProgress = i / settings.count_ping
  451. prevT = new Date().getTime()
  452. xhr[0] = new XMLHttpRequest()
  453. xhr[0].onload = function () {
  454. // pong
  455. tverb('pong')
  456. if (i === 0) {
  457. prevT = new Date().getTime() // first pong
  458. } else {
  459. var instspd = new Date().getTime() - prevT
  460. if(settings.ping_allowPerformanceApi){
  461. try{
  462. //try to get accurate performance timing using performance api
  463. var p=performance.getEntries()
  464. p=p[p.length-1]
  465. var d = p.responseStart - p.requestStart //best precision: chromium-based
  466. if (d<=0) d=p.duration //edge: not so good precision because it also considers the overhead and there is no way to avoid it
  467. if (d>0&&d<instspd) instspd=d
  468. }catch(e){
  469. //if not possible, keep the estimate
  470. //firefox can't access performance api from worker: worst precision
  471. tverb('Performance API not supported, using estimate')
  472. }
  473. }
  474. var instjitter = Math.abs(instspd - prevInstspd)
  475. if (i === 1) ping = instspd; /* first ping, can't tell jitter yet*/ else {
  476. ping = instspd < ping ? instspd : ping * 0.8 + instspd * 0.2 // update ping, weighted average. if the instant ping is lower than the current average, it is set to that value instead of averaging
  477. if(i === 2) jitter=instjitter //discard the first jitter measurement because it might be much higher than it should be
  478. else
  479. jitter = instjitter > jitter ? (jitter * 0.3 + instjitter * 0.7) : (jitter * 0.8 + instjitter * 0.2) // update jitter, weighted average. spikes in ping values are given more weight.
  480. }
  481. prevInstspd = instspd
  482. }
  483. pingStatus = ping.toFixed(2)
  484. jitterStatus = jitter.toFixed(2)
  485. i++
  486. tverb('ping: '+pingStatus+' jitter: '+jitterStatus)
  487. if (i < settings.count_ping) doPing(); else { // more pings to do?
  488. pingProgress = 1
  489. tlog('ping: '+pingStatus+' jitter: '+jitterStatus+', took '+(new Date().getTime()-startT)+'ms')
  490. done()
  491. }
  492. }.bind(this)
  493. xhr[0].onerror = function () {
  494. // a ping failed, cancel test
  495. tverb('ping failed')
  496. if (settings.xhr_ignoreErrors === 0) { //abort
  497. pingStatus = 'Fail'
  498. jitterStatus = 'Fail'
  499. clearRequests()
  500. tlog('ping test failed, took '+(new Date().getTime()-startT)+'ms')
  501. pingProgress = 1
  502. done()
  503. }
  504. if (settings.xhr_ignoreErrors === 1) doPing() //retry ping
  505. if (settings.xhr_ignoreErrors === 2){ //ignore failed ping
  506. i++
  507. if (i < settings.count_ping) doPing(); else { // more pings to do?
  508. pingProgress = 1
  509. tlog('ping: '+pingStatus+' jitter: '+jitterStatus+', took '+(new Date().getTime()-startT)+'ms')
  510. done()
  511. }
  512. }
  513. }.bind(this)
  514. // send xhr
  515. xhr[0].open('GET', settings.url_ping + url_sep(settings.url_ping) + 'r=' + Math.random(), true) // random string to prevent caching
  516. xhr[0].send()
  517. }.bind(this)
  518. doPing() // start first ping
  519. }
  520. // telemetry
  521. function sendTelemetry(done){
  522. if (settings.telemetry_level < 1) return
  523. xhr = new XMLHttpRequest()
  524. xhr.onload = function () {
  525. try{
  526. var parts=xhr.responseText.split(' ')
  527. if(parts[0]=='id'){
  528. try{
  529. var id=Number(parts[1])
  530. if(!isNaN(id)) done(id); else done(-1);
  531. }catch(e){done(-1)}
  532. } else done(-1);
  533. }catch(e){
  534. done(-1)
  535. }
  536. }
  537. xhr.onerror = function () { console.log('TELEMETRY ERROR '+xhr.status); done(-1) }
  538. xhr.open('POST', settings.url_telemetry+url_sep(settings.url_telemetry)+"r="+Math.random(), true);
  539. var telemetryIspInfo={
  540. processedString: clientIp,
  541. rawIspInfo: (typeof ispInfo === "object")?ispInfo:""
  542. }
  543. try{
  544. var fd = new FormData()
  545. fd.append('ispinfo', JSON.stringify(telemetryIspInfo));
  546. fd.append('dl', dlStatus)
  547. fd.append('ul', ulStatus)
  548. fd.append('ping', pingStatus)
  549. fd.append('jitter', jitterStatus)
  550. fd.append('log', settings.telemetry_level>1?log:"")
  551. fd.append('extra', settings.telemetry_extra);
  552. xhr.send(fd)
  553. }catch(ex){
  554. var postData = 'extra='+encodeURIComponent(settings.telemetry_extra)+'&ispinfo='+encodeURIComponent(JSON.stringify(telemetryIspInfo))+'&dl='+encodeURIComponent(dlStatus)+'&ul='+encodeURIComponent(ulStatus)+'&ping='+encodeURIComponent(pingStatus)+'&jitter='+encodeURIComponent(jitterStatus)+'&log='+encodeURIComponent(settings.telemetry_level>1?log:'')
  555. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  556. xhr.send(postData)
  557. }
  558. }