speedtest_worker.js 27 KB

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