speedtest_worker.js 27 KB

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