speedtest_worker.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /*
  2. LibreSpeed - Worker
  3. by Federico Dossena
  4. https://github.com/librespeed/speedtest/
  5. GNU LGPLv3 License
  6. */
  7. // data reported to main thread
  8. var testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
  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. mpot: false, //set to true when in MPOT mode
  38. 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
  39. time_ul_max: 15, // max duration of upload test in seconds
  40. time_dl_max: 15, // max duration of download test in seconds
  41. time_auto: true, // if set to true, tests will take less time on faster connections
  42. time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
  43. time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
  44. count_ping: 10, // number of pings to perform in ping test
  45. url_dl: "backend/garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
  46. url_ul: "backend/empty.php", // path to an empty file, used for upload test. must be relative to this js file
  47. url_ping: "backend/empty.php", // path to an empty file, used for ping test. must be relative to this js file
  48. url_getIp: "backend/getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
  49. getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
  50. 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
  51. xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
  52. xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
  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: 50, // 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: "results/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 testState, 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: testState,
  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" && testState === -1) {
  103. // start new test
  104. testState = 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. var ua = navigator.userAgent;
  120. // quirks for specific browsers. apply only if not overridden. more may be added in future releases
  121. if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
  122. if (/Firefox.(\d+\.\d+)/i.test(ua)) {
  123. if (typeof s.ping_allowPerformanceApi === "undefined") {
  124. // ff performance API sucks
  125. settings.ping_allowPerformanceApi = false;
  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 (testState == 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. testState = 4;
  179. if (id != null) testId = id;
  180. });
  181. else testState = 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. testState = 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. testState = 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. testState = 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. if (testState >= 4) return;
  243. tlog("manually aborted");
  244. clearRequests(); // stop all xhr activity
  245. runNextTest = null;
  246. if (interval) clearInterval(interval); // clear timer if present
  247. if (settings.telemetry_level > 1) sendTelemetry(function() {});
  248. testState = 5; //set test as aborted
  249. dlStatus = "";
  250. ulStatus = "";
  251. pingStatus = "";
  252. jitterStatus = "";
  253. clientIp = "";
  254. dlProgress = 0;
  255. ulProgress = 0;
  256. pingProgress = 0;
  257. }
  258. });
  259. // stops all XHR activity, aggressively
  260. function clearRequests() {
  261. tverb("stopping pending XHRs");
  262. if (xhr) {
  263. for (var i = 0; i < xhr.length; i++) {
  264. try {
  265. xhr[i].onprogress = null;
  266. xhr[i].onload = null;
  267. xhr[i].onerror = null;
  268. } catch (e) {}
  269. try {
  270. xhr[i].upload.onprogress = null;
  271. xhr[i].upload.onload = null;
  272. xhr[i].upload.onerror = null;
  273. } catch (e) {}
  274. try {
  275. xhr[i].abort();
  276. } catch (e) {}
  277. try {
  278. delete xhr[i];
  279. } catch (e) {}
  280. }
  281. xhr = null;
  282. }
  283. }
  284. // gets client's IP using url_getIp, then calls the done function
  285. var ipCalled = false; // used to prevent multiple accidental calls to getIp
  286. var ispInfo = ""; //used for telemetry
  287. function getIp(done) {
  288. tverb("getIp");
  289. if (ipCalled) return;
  290. else ipCalled = true; // getIp already called?
  291. var startT = new Date().getTime();
  292. xhr = new XMLHttpRequest();
  293. xhr.onload = function() {
  294. tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
  295. try {
  296. var data = JSON.parse(xhr.responseText);
  297. clientIp = data.processedString;
  298. ispInfo = data.rawIspInfo;
  299. } catch (e) {
  300. clientIp = xhr.responseText;
  301. ispInfo = "";
  302. }
  303. done();
  304. };
  305. xhr.onerror = function() {
  306. tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
  307. done();
  308. };
  309. xhr.open("GET", settings.url_getIp + url_sep(settings.url_getIp) + (settings.mpot ? "cors=true&" : "") + (settings.getIp_ispInfo ? "isp=true" + (settings.getIp_ispInfo_distance ? "&distance=" + settings.getIp_ispInfo_distance + "&" : "&") : "&") + "r=" + Math.random(), true);
  310. xhr.send();
  311. }
  312. // download test, calls done function when it's over
  313. var dlCalled = false; // used to prevent multiple accidental calls to dlTest
  314. function dlTest(done) {
  315. tverb("dlTest");
  316. if (dlCalled) return;
  317. else dlCalled = true; // dlTest already called?
  318. var totLoaded = 0.0, // total number of loaded bytes
  319. startT = new Date().getTime(), // timestamp when test was started
  320. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  321. graceTimeDone = false, //set to true after the grace time is past
  322. failed = false; // set to true if a stream fails
  323. xhr = [];
  324. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  325. var testStream = function(i, delay) {
  326. setTimeout(
  327. function() {
  328. if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
  329. tverb("dl test stream started " + i + " " + delay);
  330. var prevLoaded = 0; // number of bytes loaded last time onprogress was called
  331. var x = new XMLHttpRequest();
  332. xhr[i] = x;
  333. xhr[i].onprogress = function(event) {
  334. tverb("dl stream progress event " + i + " " + event.loaded);
  335. if (testState !== 1) {
  336. try {
  337. x.abort();
  338. } catch (e) {}
  339. } // just in case this XHR is still running after the download test
  340. // progress event, add number of new loaded bytes to totLoaded
  341. var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  342. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  343. totLoaded += loadDiff;
  344. prevLoaded = event.loaded;
  345. }.bind(this);
  346. xhr[i].onload = function() {
  347. // the large file has been loaded entirely, start again
  348. tverb("dl stream finished " + i);
  349. try {
  350. xhr[i].abort();
  351. } catch (e) {} // reset the stream data to empty ram
  352. testStream(i, 0);
  353. }.bind(this);
  354. xhr[i].onerror = function() {
  355. // error
  356. tverb("dl stream failed " + i);
  357. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  358. try {
  359. xhr[i].abort();
  360. } catch (e) {}
  361. delete xhr[i];
  362. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  363. }.bind(this);
  364. // send xhr
  365. try {
  366. if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
  367. else xhr[i].responseType = "arraybuffer";
  368. } catch (e) {}
  369. xhr[i].open("GET", settings.url_dl + url_sep(settings.url_dl) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random() + "&ckSize=" + settings.garbagePhp_chunkSize, true); // random string to prevent caching
  370. xhr[i].send();
  371. }.bind(this),
  372. 1 + delay
  373. );
  374. }.bind(this);
  375. // open streams
  376. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  377. testStream(i, settings.xhr_multistreamDelay * i);
  378. }
  379. // every 200ms, update dlStatus
  380. interval = setInterval(
  381. function() {
  382. tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
  383. var t = new Date().getTime() - startT;
  384. if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
  385. if (t < 200) return;
  386. if (!graceTimeDone) {
  387. if (t > 1000 * settings.time_dlGraceTime) {
  388. if (totLoaded > 0) {
  389. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  390. startT = new Date().getTime();
  391. bonusT = 0;
  392. totLoaded = 0.0;
  393. }
  394. graceTimeDone = true;
  395. }
  396. } else {
  397. var speed = totLoaded / (t / 1000.0);
  398. if (settings.time_auto) {
  399. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  400. var bonus = (5.0 * speed) / 100000;
  401. bonusT += bonus > 400 ? 400 : bonus;
  402. }
  403. //update status
  404. 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
  405. if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
  406. // test is over, stop streams and timer
  407. if (failed || isNaN(dlStatus)) dlStatus = "Fail";
  408. clearRequests();
  409. clearInterval(interval);
  410. dlProgress = 1;
  411. tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
  412. done();
  413. }
  414. }
  415. }.bind(this),
  416. 200
  417. );
  418. }
  419. // upload test, calls done function whent it's over
  420. var ulCalled = false; // used to prevent multiple accidental calls to ulTest
  421. function ulTest(done) {
  422. tverb("ulTest");
  423. if (ulCalled) return;
  424. else ulCalled = true; // ulTest already called?
  425. // garbage data for upload test
  426. var r = new ArrayBuffer(1048576);
  427. var maxInt = Math.pow(2, 32) - 1;
  428. try {
  429. r = new Uint32Array(r);
  430. for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  431. } catch (e) {}
  432. var req = [];
  433. var reqsmall = [];
  434. for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
  435. req = new Blob(req);
  436. r = new ArrayBuffer(262144);
  437. try {
  438. r = new Uint32Array(r);
  439. for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  440. } catch (e) {}
  441. reqsmall.push(r);
  442. reqsmall = new Blob(reqsmall);
  443. var testFunction = function() {
  444. var totLoaded = 0.0, // total number of transmitted bytes
  445. startT = new Date().getTime(), // timestamp when test was started
  446. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  447. graceTimeDone = false, //set to true after the grace time is past
  448. failed = false; // set to true if a stream fails
  449. xhr = [];
  450. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  451. var testStream = function(i, delay) {
  452. setTimeout(
  453. function() {
  454. if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
  455. tverb("ul test stream started " + i + " " + delay);
  456. var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
  457. var x = new XMLHttpRequest();
  458. xhr[i] = x;
  459. var ie11workaround;
  460. if (settings.forceIE11Workaround) ie11workaround = true;
  461. else {
  462. try {
  463. xhr[i].upload.onprogress;
  464. ie11workaround = false;
  465. } catch (e) {
  466. ie11workaround = true;
  467. }
  468. }
  469. if (ie11workaround) {
  470. // 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
  471. xhr[i].onload = xhr[i].onerror = function() {
  472. tverb("ul stream progress event (ie11wa)");
  473. totLoaded += reqsmall.size;
  474. testStream(i, 0);
  475. };
  476. xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
  477. try {
  478. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  479. } catch (e) {}
  480. //No Content-Type header in MPOT branch because it triggers bugs in some browsers
  481. xhr[i].send(reqsmall);
  482. } else {
  483. // REGULAR version, no workaround
  484. xhr[i].upload.onprogress = function(event) {
  485. tverb("ul stream progress event " + i + " " + event.loaded);
  486. if (testState !== 3) {
  487. try {
  488. x.abort();
  489. } catch (e) {}
  490. } // just in case this XHR is still running after the upload test
  491. // progress event, add number of new loaded bytes to totLoaded
  492. var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  493. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  494. totLoaded += loadDiff;
  495. prevLoaded = event.loaded;
  496. }.bind(this);
  497. xhr[i].upload.onload = function() {
  498. // this stream sent all the garbage data, start again
  499. tverb("ul stream finished " + i);
  500. testStream(i, 0);
  501. }.bind(this);
  502. xhr[i].upload.onerror = function() {
  503. tverb("ul stream failed " + i);
  504. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  505. try {
  506. xhr[i].abort();
  507. } catch (e) {}
  508. delete xhr[i];
  509. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  510. }.bind(this);
  511. // send xhr
  512. xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
  513. try {
  514. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  515. } catch (e) {}
  516. //No Content-Type header in MPOT branch because it triggers bugs in some browsers
  517. xhr[i].send(req);
  518. }
  519. }.bind(this),
  520. delay
  521. );
  522. }.bind(this);
  523. // open streams
  524. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  525. testStream(i, settings.xhr_multistreamDelay * i);
  526. }
  527. // every 200ms, update ulStatus
  528. interval = setInterval(
  529. function() {
  530. tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
  531. var t = new Date().getTime() - startT;
  532. if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
  533. if (t < 200) return;
  534. if (!graceTimeDone) {
  535. if (t > 1000 * settings.time_ulGraceTime) {
  536. if (totLoaded > 0) {
  537. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  538. startT = new Date().getTime();
  539. bonusT = 0;
  540. totLoaded = 0.0;
  541. }
  542. graceTimeDone = true;
  543. }
  544. } else {
  545. var speed = totLoaded / (t / 1000.0);
  546. if (settings.time_auto) {
  547. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  548. var bonus = (5.0 * speed) / 100000;
  549. bonusT += bonus > 400 ? 400 : bonus;
  550. }
  551. //update status
  552. 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
  553. if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
  554. // test is over, stop streams and timer
  555. if (failed || isNaN(ulStatus)) ulStatus = "Fail";
  556. clearRequests();
  557. clearInterval(interval);
  558. ulProgress = 1;
  559. tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
  560. done();
  561. }
  562. }
  563. }.bind(this),
  564. 200
  565. );
  566. }.bind(this);
  567. if (settings.mpot) {
  568. tverb("Sending POST request before performing upload test");
  569. xhr = [];
  570. xhr[0] = new XMLHttpRequest();
  571. xhr[0].onload = xhr[0].onerror = function() {
  572. tverb("POST request sent, starting upload test");
  573. testFunction();
  574. }.bind(this);
  575. xhr[0].open("POST", settings.url_ul);
  576. xhr[0].send();
  577. } else testFunction();
  578. }
  579. // ping+jitter test, function done is called when it's over
  580. var ptCalled = false; // used to prevent multiple accidental calls to pingTest
  581. function pingTest(done) {
  582. tverb("pingTest");
  583. if (ptCalled) return;
  584. else ptCalled = true; // pingTest already called?
  585. var startT = new Date().getTime(); //when the test was started
  586. var prevT = null; // last time a pong was received
  587. var ping = 0.0; // current ping value
  588. var jitter = 0.0; // current jitter value
  589. var i = 0; // counter of pongs received
  590. var prevInstspd = 0; // last ping time, used for jitter calculation
  591. xhr = [];
  592. // ping function
  593. var doPing = function() {
  594. tverb("ping");
  595. pingProgress = i / settings.count_ping;
  596. prevT = new Date().getTime();
  597. xhr[0] = new XMLHttpRequest();
  598. xhr[0].onload = function() {
  599. // pong
  600. tverb("pong");
  601. if (i === 0) {
  602. prevT = new Date().getTime(); // first pong
  603. } else {
  604. var instspd = new Date().getTime() - prevT;
  605. if (settings.ping_allowPerformanceApi) {
  606. try {
  607. //try to get accurate performance timing using performance api
  608. var p = performance.getEntries();
  609. p = p[p.length - 1];
  610. var d = p.responseStart - p.requestStart;
  611. if (d <= 0) d = p.duration;
  612. if (d > 0 && d < instspd) instspd = d;
  613. } catch (e) {
  614. //if not possible, keep the estimate
  615. tverb("Performance API not supported, using estimate");
  616. }
  617. }
  618. //noticed that some browsers randomly have 0ms ping
  619. if (instspd < 1) instspd = prevInstspd;
  620. if (instspd < 1) instspd = 1;
  621. var instjitter = Math.abs(instspd - prevInstspd);
  622. if (i === 1) ping = instspd;
  623. /* first ping, can't tell jitter yet*/ else {
  624. if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
  625. if (i === 2) jitter = instjitter;
  626. //discard the first jitter measurement because it might be much higher than it should be
  627. 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.
  628. }
  629. prevInstspd = instspd;
  630. }
  631. pingStatus = ping.toFixed(2);
  632. jitterStatus = jitter.toFixed(2);
  633. i++;
  634. tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
  635. if (i < settings.count_ping) doPing();
  636. else {
  637. // more pings to do?
  638. pingProgress = 1;
  639. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  640. done();
  641. }
  642. }.bind(this);
  643. xhr[0].onerror = function() {
  644. // a ping failed, cancel test
  645. tverb("ping failed");
  646. if (settings.xhr_ignoreErrors === 0) {
  647. //abort
  648. pingStatus = "Fail";
  649. jitterStatus = "Fail";
  650. clearRequests();
  651. tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
  652. pingProgress = 1;
  653. done();
  654. }
  655. if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
  656. if (settings.xhr_ignoreErrors === 2) {
  657. //ignore failed ping
  658. i++;
  659. if (i < settings.count_ping) doPing();
  660. else {
  661. // more pings to do?
  662. pingProgress = 1;
  663. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  664. done();
  665. }
  666. }
  667. }.bind(this);
  668. // send xhr
  669. xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
  670. xhr[0].send();
  671. }.bind(this);
  672. doPing(); // start first ping
  673. }
  674. // telemetry
  675. function sendTelemetry(done) {
  676. if (settings.telemetry_level < 1) return;
  677. xhr = new XMLHttpRequest();
  678. xhr.onload = function() {
  679. try {
  680. var parts = xhr.responseText.split(" ");
  681. if (parts[0] == "id") {
  682. try {
  683. var id = parts[1];
  684. done(id);
  685. } catch (e) {
  686. done(null);
  687. }
  688. } else done(null);
  689. } catch (e) {
  690. done(null);
  691. }
  692. };
  693. xhr.onerror = function() {
  694. console.log("TELEMETRY ERROR " + xhr.status);
  695. done(null);
  696. };
  697. xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
  698. var telemetryIspInfo = {
  699. processedString: clientIp,
  700. rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
  701. };
  702. try {
  703. var fd = new FormData();
  704. fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
  705. fd.append("dl", dlStatus);
  706. fd.append("ul", ulStatus);
  707. fd.append("ping", pingStatus);
  708. fd.append("jitter", jitterStatus);
  709. fd.append("log", settings.telemetry_level > 1 ? log : "");
  710. fd.append("extra", settings.telemetry_extra);
  711. xhr.send(fd);
  712. } catch (ex) {
  713. 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 : "");
  714. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  715. xhr.send(postData);
  716. }
  717. }