speedtest_worker.js 26 KB

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