speedtest_worker.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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: 6, // 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: 100, // 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. if (typeof s.xhr_ulMultistream === "undefined") {
  128. // ff performance API sucks
  129. settings.ping_allowPerformanceApi = false;
  130. }
  131. }
  132. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  133. if (typeof s.xhr_dlMultistream === "undefined") {
  134. // edge more precise with 3 download streams
  135. settings.xhr_dlMultistream = 3;
  136. }
  137. }
  138. if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
  139. if (typeof s.xhr_dlMultistream === "undefined") {
  140. // chrome more precise with 5 streams
  141. settings.xhr_dlMultistream = 5;
  142. }
  143. }
  144. }
  145. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  146. //Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
  147. settings.forceIE11Workaround = true;
  148. }
  149. if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
  150. //PS4 browser has the same bug as IE11/Edge
  151. settings.forceIE11Workaround = true;
  152. }
  153. if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
  154. //cheap af
  155. //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
  156. settings.xhr_ul_blob_megabytes = 4;
  157. }
  158. if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
  159. //Safari also needs the IE11 workaround but only for the MPOT version
  160. settings.forceIE11Workaround = true;
  161. }
  162. //telemetry_level has to be parsed and not just copied
  163. 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
  164. //transform test_order to uppercase, just in case
  165. settings.test_order = settings.test_order.toUpperCase();
  166. } catch (e) {
  167. twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
  168. }
  169. // run the tests
  170. tverb(JSON.stringify(settings));
  171. test_pointer = 0;
  172. var iRun = false,
  173. dRun = false,
  174. uRun = false,
  175. pRun = false;
  176. var runNextTest = function() {
  177. if (testStatus == 5) return;
  178. if (test_pointer >= settings.test_order.length) {
  179. //test is finished
  180. if (settings.telemetry_level > 0)
  181. sendTelemetry(function(id) {
  182. testStatus = 4;
  183. if (id != null) testId = id;
  184. });
  185. else testStatus = 4;
  186. return;
  187. }
  188. switch (settings.test_order.charAt(test_pointer)) {
  189. case "I":
  190. {
  191. test_pointer++;
  192. if (iRun) {
  193. runNextTest();
  194. return;
  195. } else iRun = true;
  196. getIp(runNextTest);
  197. }
  198. break;
  199. case "D":
  200. {
  201. test_pointer++;
  202. if (dRun) {
  203. runNextTest();
  204. return;
  205. } else dRun = true;
  206. testStatus = 1;
  207. dlTest(runNextTest);
  208. }
  209. break;
  210. case "U":
  211. {
  212. test_pointer++;
  213. if (uRun) {
  214. runNextTest();
  215. return;
  216. } else uRun = true;
  217. testStatus = 3;
  218. ulTest(runNextTest);
  219. }
  220. break;
  221. case "P":
  222. {
  223. test_pointer++;
  224. if (pRun) {
  225. runNextTest();
  226. return;
  227. } else pRun = true;
  228. testStatus = 2;
  229. pingTest(runNextTest);
  230. }
  231. break;
  232. case "_":
  233. {
  234. test_pointer++;
  235. setTimeout(runNextTest, 1000);
  236. }
  237. break;
  238. default:
  239. test_pointer++;
  240. }
  241. };
  242. runNextTest();
  243. }
  244. if (params[0] === "abort") {
  245. // abort command
  246. tlog("manually aborted");
  247. clearRequests(); // stop all xhr activity
  248. runNextTest = null;
  249. if (interval) clearInterval(interval); // clear timer if present
  250. if (settings.telemetry_level > 1) sendTelemetry(function() {});
  251. testStatus = 5;
  252. dlStatus = "";
  253. ulStatus = "";
  254. pingStatus = "";
  255. jitterStatus = ""; // set test as aborted
  256. }
  257. });
  258. // stops all XHR activity, aggressively
  259. function clearRequests() {
  260. tverb("stopping pending XHRs");
  261. if (xhr) {
  262. for (var i = 0; i < xhr.length; i++) {
  263. try {
  264. xhr[i].onprogress = null;
  265. xhr[i].onload = null;
  266. xhr[i].onerror = null;
  267. } catch (e) {}
  268. try {
  269. xhr[i].upload.onprogress = null;
  270. xhr[i].upload.onload = null;
  271. xhr[i].upload.onerror = null;
  272. } catch (e) {}
  273. try {
  274. xhr[i].abort();
  275. } catch (e) {}
  276. try {
  277. delete xhr[i];
  278. } catch (e) {}
  279. }
  280. xhr = null;
  281. }
  282. }
  283. // gets client's IP using url_getIp, then calls the done function
  284. var ipCalled = false; // used to prevent multiple accidental calls to getIp
  285. var ispInfo = ""; //used for telemetry
  286. function getIp(done) {
  287. tverb("getIp");
  288. if (ipCalled) return;
  289. else ipCalled = true; // getIp already called?
  290. var startT = new Date().getTime();
  291. xhr = new XMLHttpRequest();
  292. xhr.onload = function() {
  293. tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
  294. try {
  295. var data = JSON.parse(xhr.responseText);
  296. clientIp = data.processedString;
  297. ispInfo = data.rawIspInfo;
  298. } catch (e) {
  299. clientIp = xhr.responseText;
  300. ispInfo = "";
  301. }
  302. done();
  303. };
  304. xhr.onerror = function() {
  305. tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
  306. done();
  307. };
  308. 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);
  309. xhr.send();
  310. }
  311. // download test, calls done function when it's over
  312. var dlCalled = false; // used to prevent multiple accidental calls to dlTest
  313. function dlTest(done) {
  314. tverb("dlTest");
  315. if (dlCalled) return;
  316. else dlCalled = true; // dlTest already called?
  317. var totLoaded = 0.0, // total number of loaded bytes
  318. startT = new Date().getTime(), // timestamp when test was started
  319. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  320. graceTimeDone = false, //set to true after the grace time is past
  321. failed = false; // set to true if a stream fails
  322. xhr = [];
  323. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  324. var testStream = function(i, delay) {
  325. setTimeout(
  326. function() {
  327. if (testStatus !== 1) return; // delayed stream ended up starting after the end of the download test
  328. tverb("dl test stream started " + i + " " + delay);
  329. var prevLoaded = 0; // number of bytes loaded last time onprogress was called
  330. var x = new XMLHttpRequest();
  331. xhr[i] = x;
  332. xhr[i].onprogress = function(event) {
  333. tverb("dl stream progress event " + i + " " + event.loaded);
  334. if (testStatus !== 1) {
  335. try {
  336. x.abort();
  337. } catch (e) {}
  338. } // just in case this XHR is still running after the download test
  339. // progress event, add number of new loaded bytes to totLoaded
  340. var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  341. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  342. totLoaded += loadDiff;
  343. prevLoaded = event.loaded;
  344. }.bind(this);
  345. xhr[i].onload = function() {
  346. // the large file has been loaded entirely, start again
  347. tverb("dl stream finished " + i);
  348. try {
  349. xhr[i].abort();
  350. } catch (e) {} // reset the stream data to empty ram
  351. testStream(i, 0);
  352. }.bind(this);
  353. xhr[i].onerror = function() {
  354. // error
  355. tverb("dl stream failed " + i);
  356. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  357. try {
  358. xhr[i].abort();
  359. } catch (e) {}
  360. delete xhr[i];
  361. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  362. }.bind(this);
  363. // send xhr
  364. try {
  365. if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
  366. else xhr[i].responseType = "arraybuffer";
  367. } catch (e) {}
  368. 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
  369. xhr[i].send();
  370. }.bind(this),
  371. 1 + delay
  372. );
  373. }.bind(this);
  374. // open streams
  375. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  376. testStream(i, settings.xhr_multistreamDelay * i);
  377. }
  378. // every 200ms, update dlStatus
  379. interval = setInterval(
  380. function() {
  381. tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
  382. var t = new Date().getTime() - startT;
  383. if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
  384. if (t < 200) return;
  385. if (!graceTimeDone) {
  386. if (t > 1000 * settings.time_dlGraceTime) {
  387. if (totLoaded > 0) {
  388. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  389. startT = new Date().getTime();
  390. bonusT = 0;
  391. totLoaded = 0.0;
  392. }
  393. graceTimeDone = true;
  394. }
  395. } else {
  396. var speed = totLoaded / (t / 1000.0);
  397. if (settings.time_auto) {
  398. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  399. var bonus = (6.4 * speed) / 100000;
  400. bonusT += bonus > 800 ? 800 : bonus;
  401. }
  402. //update status
  403. 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
  404. if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
  405. // test is over, stop streams and timer
  406. if (failed || isNaN(dlStatus)) dlStatus = "Fail";
  407. clearRequests();
  408. clearInterval(interval);
  409. dlProgress = 1;
  410. tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
  411. done();
  412. }
  413. }
  414. }.bind(this),
  415. 200
  416. );
  417. }
  418. // upload test, calls done function whent it's over
  419. var ulCalled = false; // used to prevent multiple accidental calls to ulTest
  420. function ulTest(done) {
  421. tverb("ulTest");
  422. if (ulCalled) return;
  423. else ulCalled = true; // ulTest already called?
  424. // garbage data for upload test
  425. var r = new ArrayBuffer(1048576);
  426. var maxInt = Math.pow(2, 32) - 1;
  427. try {
  428. r = new Uint32Array(r);
  429. for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  430. } catch (e) {}
  431. var req = [];
  432. var reqsmall = [];
  433. for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
  434. req = new Blob(req);
  435. r = new ArrayBuffer(262144);
  436. try {
  437. r = new Uint32Array(r);
  438. for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  439. } catch (e) {}
  440. reqsmall.push(r);
  441. reqsmall = new Blob(reqsmall);
  442. var testFunction = function() {
  443. var totLoaded = 0.0, // total number of transmitted bytes
  444. startT = new Date().getTime(), // timestamp when test was started
  445. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  446. graceTimeDone = false, //set to true after the grace time is past
  447. failed = false; // set to true if a stream fails
  448. xhr = [];
  449. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  450. var testStream = function(i, delay) {
  451. setTimeout(
  452. function() {
  453. if (testStatus !== 3) return; // delayed stream ended up starting after the end of the upload test
  454. tverb("ul test stream started " + i + " " + delay);
  455. var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
  456. var x = new XMLHttpRequest();
  457. xhr[i] = x;
  458. var ie11workaround;
  459. if (settings.forceIE11Workaround) ie11workaround = true;
  460. else {
  461. try {
  462. xhr[i].upload.onprogress;
  463. ie11workaround = false;
  464. } catch (e) {
  465. ie11workaround = true;
  466. }
  467. }
  468. if (ie11workaround) {
  469. // 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
  470. xhr[i].onload = xhr[i].onerror = function() {
  471. tverb("ul stream progress event (ie11wa)");
  472. totLoaded += reqsmall.size;
  473. testStream(i, 0);
  474. };
  475. xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + "r=" + Math.random(), true); // random string to prevent caching
  476. try{
  477. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  478. }catch(e){}
  479. //No Content-Type header in MPOT branch because it triggers bugs in some browsers
  480. xhr[i].send(reqsmall);
  481. } else {
  482. // REGULAR version, no workaround
  483. xhr[i].upload.onprogress = function(event) {
  484. tverb("ul stream progress event " + i + " " + event.loaded);
  485. if (testStatus !== 3) {
  486. try {
  487. x.abort();
  488. } catch (e) {}
  489. } // just in case this XHR is still running after the upload test
  490. // progress event, add number of new loaded bytes to totLoaded
  491. var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  492. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  493. totLoaded += loadDiff;
  494. prevLoaded = event.loaded;
  495. }.bind(this);
  496. xhr[i].upload.onload = function() {
  497. // this stream sent all the garbage data, start again
  498. tverb("ul stream finished " + i);
  499. testStream(i, 0);
  500. }.bind(this);
  501. xhr[i].upload.onerror = function() {
  502. tverb("ul stream failed " + i);
  503. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  504. try {
  505. xhr[i].abort();
  506. } catch (e) {}
  507. delete xhr[i];
  508. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  509. }.bind(this);
  510. // send xhr
  511. xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + "r=" + Math.random(), true); // random string to prevent caching
  512. try{
  513. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  514. }catch(e){}
  515. //No Content-Type header in MPOT branch because it triggers bugs in some browsers
  516. xhr[i].send(req);
  517. }
  518. }.bind(this),
  519. 1
  520. );
  521. }.bind(this);
  522. // open streams
  523. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  524. testStream(i, settings.xhr_multistreamDelay * i);
  525. }
  526. // every 200ms, update ulStatus
  527. interval = setInterval(
  528. function() {
  529. tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
  530. var t = new Date().getTime() - startT;
  531. if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
  532. if (t < 200) return;
  533. if (!graceTimeDone) {
  534. if (t > 1000 * settings.time_ulGraceTime) {
  535. if (totLoaded > 0) {
  536. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  537. startT = new Date().getTime();
  538. bonusT = 0;
  539. totLoaded = 0.0;
  540. }
  541. graceTimeDone = true;
  542. }
  543. } else {
  544. var speed = totLoaded / (t / 1000.0);
  545. if (settings.time_auto) {
  546. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  547. var bonus = (6.4 * speed) / 100000;
  548. bonusT += bonus > 800 ? 800 : bonus;
  549. }
  550. //update status
  551. 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
  552. if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
  553. // test is over, stop streams and timer
  554. if (failed || isNaN(ulStatus)) ulStatus = "Fail";
  555. clearRequests();
  556. clearInterval(interval);
  557. ulProgress = 1;
  558. tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
  559. done();
  560. }
  561. }
  562. }.bind(this),
  563. 200
  564. );
  565. }.bind(this);
  566. if (settings.xhr_ul_sendPostRequestBeforeStartingTest) {
  567. tverb("Sending POST request before performing upload test");
  568. xhr = [];
  569. xhr[0] = new XMLHttpRequest();
  570. xhr[0].onload = xhr[0].onerror = function() {
  571. tverb("POST request sent, starting upload test");
  572. testFunction();
  573. }.bind(this);
  574. xhr[0].open("POST", settings.url_ul);
  575. xhr[0].send();
  576. } else testFunction();
  577. }
  578. // ping+jitter test, function done is called when it's over
  579. var ptCalled = false; // used to prevent multiple accidental calls to pingTest
  580. function pingTest(done) {
  581. tverb("pingTest");
  582. if (ptCalled) return;
  583. else ptCalled = true; // pingTest already called?
  584. var startT = new Date().getTime(); //when the test was started
  585. var prevT = null; // last time a pong was received
  586. var ping = 0.0; // current ping value
  587. var jitter = 0.0; // current jitter value
  588. var i = 0; // counter of pongs received
  589. var prevInstspd = 0; // last ping time, used for jitter calculation
  590. xhr = [];
  591. // ping function
  592. var doPing = function() {
  593. tverb("ping");
  594. pingProgress = i / settings.count_ping;
  595. prevT = new Date().getTime();
  596. xhr[0] = new XMLHttpRequest();
  597. xhr[0].onload = function() {
  598. // pong
  599. tverb("pong");
  600. if (i === 0) {
  601. prevT = new Date().getTime(); // first pong
  602. } else {
  603. var instspd = new Date().getTime() - prevT;
  604. if (settings.ping_allowPerformanceApi) {
  605. try {
  606. //try to get accurate performance timing using performance api
  607. var p = performance.getEntries();
  608. p = p[p.length - 1];
  609. var d = p.responseStart - p.requestStart;
  610. if (d <= 0) d = p.duration;
  611. if (d > 0 && d < instspd) instspd = d;
  612. } catch (e) {
  613. //if not possible, keep the estimate
  614. tverb("Performance API not supported, using estimate");
  615. }
  616. }
  617. //noticed that some browsers randomly have 0ms ping
  618. if(instspd<1) instspd=prevInstspd;
  619. if(instspd<1) instspd=1;
  620. var instjitter = Math.abs(instspd - prevInstspd);
  621. if (i === 1) ping = instspd;
  622. /* first ping, can't tell jitter yet*/ else {
  623. 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
  624. if (i === 2) jitter = instjitter;
  625. //discard the first jitter measurement because it might be much higher than it should be
  626. 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.
  627. }
  628. prevInstspd = instspd;
  629. }
  630. pingStatus = ping.toFixed(2);
  631. jitterStatus = jitter.toFixed(2);
  632. i++;
  633. tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
  634. if (i < settings.count_ping) doPing();
  635. else {
  636. // more pings to do?
  637. pingProgress = 1;
  638. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  639. done();
  640. }
  641. }.bind(this);
  642. xhr[0].onerror = function() {
  643. // a ping failed, cancel test
  644. tverb("ping failed");
  645. if (settings.xhr_ignoreErrors === 0) {
  646. //abort
  647. pingStatus = "Fail";
  648. jitterStatus = "Fail";
  649. clearRequests();
  650. tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
  651. pingProgress = 1;
  652. done();
  653. }
  654. if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
  655. if (settings.xhr_ignoreErrors === 2) {
  656. //ignore failed ping
  657. i++;
  658. if (i < settings.count_ping) doPing();
  659. else {
  660. // more pings to do?
  661. pingProgress = 1;
  662. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  663. done();
  664. }
  665. }
  666. }.bind(this);
  667. // send xhr
  668. xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + "r=" + Math.random(), true); // random string to prevent caching
  669. xhr[0].send();
  670. }.bind(this);
  671. doPing(); // start first ping
  672. }
  673. // telemetry
  674. function sendTelemetry(done) {
  675. if (settings.telemetry_level < 1) return;
  676. xhr = new XMLHttpRequest();
  677. xhr.onload = function() {
  678. try {
  679. var parts = xhr.responseText.split(" ");
  680. if (parts[0] == "id") {
  681. try {
  682. var id = parts[1];
  683. done(id);
  684. } catch (e) {
  685. done(null);
  686. }
  687. } else done(null);
  688. } catch (e) {
  689. done(null);
  690. }
  691. };
  692. xhr.onerror = function() {
  693. console.log("TELEMETRY ERROR " + xhr.status);
  694. done(null);
  695. };
  696. xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + "r=" + Math.random(), true);
  697. var telemetryIspInfo = {
  698. processedString: clientIp,
  699. rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
  700. };
  701. try {
  702. var fd = new FormData();
  703. fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
  704. fd.append("dl", dlStatus);
  705. fd.append("ul", ulStatus);
  706. fd.append("ping", pingStatus);
  707. fd.append("jitter", jitterStatus);
  708. fd.append("log", settings.telemetry_level > 1 ? log : "");
  709. fd.append("extra", settings.telemetry_extra);
  710. xhr.send(fd);
  711. } catch (ex) {
  712. 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 : "");
  713. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  714. xhr.send(postData);
  715. }
  716. }