├── .github └── workflows │ └── docker-build.yml ├── .gitignore ├── LICENSE ├── README.md ├── README_CN.md ├── backend ├── SleekDB │ ├── Exceptions │ │ ├── ConditionNotAllowedException.php │ │ ├── EmptyConditionException.php │ │ ├── EmptyFieldNameException.php │ │ ├── EmptyStoreDataException.php │ │ ├── EmptyStoreNameException.php │ │ ├── IOException.php │ │ ├── IdNotAllowedException.php │ │ ├── IndexNotFoundException.php │ │ ├── InvalidArgumentException.php │ │ ├── InvalidConfigurationException.php │ │ ├── InvalidDataException.php │ │ ├── InvalidOrderException.php │ │ ├── InvalidStoreDataException.php │ │ └── JsonException.php │ ├── SleekDB.php │ └── Traits │ │ ├── CacheTrait.php │ │ ├── ConditionTrait.php │ │ └── HelperTrait.php ├── config.php ├── empty.php ├── garbage.php ├── getIP.php ├── getIP_ipInfo_apikey.php ├── report.php └── results-api.php ├── chart.html ├── chartjs ├── Chart.min.js └── utils.js ├── favicon.ico ├── index.html ├── results.html ├── speedtest.js └── speedtest_worker.js /.github/workflows/docker-build.yml: -------------------------------------------------------------------------------- 1 | name: Build Docker Image 2 | 3 | on: 4 | push: 5 | branches: 6 | - 'docker' 7 | 8 | workflow_dispatch: 9 | 10 | env: 11 | APP_NAME: speedtest-x 12 | 13 | jobs: 14 | main: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v2.3.5 19 | 20 | - name: Set up QEMU 21 | uses: docker/setup-qemu-action@v1 22 | 23 | - name: Set up Docker Buildx 24 | uses: docker/setup-buildx-action@v1 25 | 26 | - name: Login to DockerHub 27 | uses: docker/login-action@v1 28 | with: 29 | username: ${{ secrets.DOCKERHUB_USERNAME }} 30 | password: ${{ secrets.DOCKERHUB_PASSWORD }} 31 | 32 | - name: Generate Image Tag 33 | run: echo "TAG=$(date +%Y)-$(date +%m)-$(date +%d)" >> $GITHUB_ENV 34 | 35 | - name: Build and push 36 | id: docker_build 37 | uses: docker/build-push-action@v2 38 | with: 39 | push: true 40 | platforms: | 41 | linux/amd64 42 | linux/arm64 43 | tags: | 44 | ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.APP_NAME }}:latest 45 | ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.APP_NAME }}:${{ env.TAG }} 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | speedlogs 2 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ![GitHub Actions Build Status](https://img.shields.io/github/actions/workflow/status/MortyFx/speedtest-x/docker-build.yml) ![GitHub last commit](https://img.shields.io/github/last-commit/MortyFx/speedtest-x) ![GitHub](https://img.shields.io/github/license/MortyFx/speedtest-x) 4 | 5 | This project is an extension of [LibreSpeed](https://github.com/librespeed/speedtest), LibreSpeed is a pretty lightweight speedtest tool. 6 | 7 | speedtest-x uses file datebase to save speedtest results from various users. Thus you can check out different results from various countries/regions. 8 | 9 | [中文文档](https://github.com/MortyFx/speedtest-x/blob/master/README_CN.md) 10 | 11 | [Join Telegram group](https://t.me/xiaozhu5) 12 | 13 | **❗ Warning**:Based on the principle of web speedtest, this program will generate garbage files for tester to download them to calculate the downstream network bandwidth from server to local. There may be abuses by malicious tester in a certain extent, after shared your speedtest website in public, please pay attention to the condition of your server traffic to avoid an traffic overload. 14 | 15 | ## Features and extensions 16 | - Self-hosted lightweight speedtest page 17 | - User speedtest result datasheet 18 | - No MySQL, but lightweight file database 19 | - Use [ip.sb](https://ip.sb) to get IP info by default 20 | 21 | ## Quick start 22 | 23 | #### Deploy by Docker (Supported platforms: AMD64/ARM64) 24 | > 1. Pull [Image](https://hub.docker.com/r/badapple9/speedtest-x) `docker pull badapple9/speedtest-x` 25 | > 2. Run container `docker run -d -p 9001:80 -it badapple9/speedtest-x` (💡 See more parameters [Here](https://github.com/MortyFx/speedtest-x/wiki/Docker-deploy)) 26 | >3. Open `{your_ip}:9001` 27 | 28 | ------- 29 | 30 | #### General deploy (Require: PHP5.6+) 31 | 32 | >1. Download repository files and unzip to website directory, open `{your_domain_name}/index.html`. 33 | >2. Open `{your_domain_name}/results.html` to check out speedtest result datasheet. 34 | 35 | ## Settings 36 | 37 | `backend/config.php`: 38 | > 39 | > `MAX_LOG_COUNT = 100`:Maximum results size, 100 by default 40 | > 41 | > `IP_SERVICE = 'ip.sb'`:IP info provider (Options: ip.sb / ipinfo.io), ip.sb by default 42 | > 43 | > `SAME_IP_MULTI_LOGS = false`:Whether to allow the same user IP to record multiple speedtest results, false by default. 44 | 45 | 46 | ## Screenshots 47 | 48 | ![index](https://raw.githubusercontent.com/BadApple9/images/main/indexdemo.png) 49 | ![results](https://raw.githubusercontent.com/BadApple9/images/main/resultsdemo.png) 50 | 51 | ## See also 52 | - [LibreSpeed](https://github.com/librespeed/speedtest) 53 | - [ip.sb](https://ip.sb) 54 | - [SleekDB](https://github.com/rakibtg/SleekDB) 55 | 56 | ## Contributors 57 | 58 | 59 | 60 | 61 | 62 | ## License 63 | 64 | See [License](https://github.com/MortyFx/speedtest-x/blob/master/LICENSE) 65 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ![GitHub Actions Build Status](https://img.shields.io/github/workflow/status/MortyFx/speedtest-x/Build%20Docker%20Image) ![GitHub last commit](https://img.shields.io/github/last-commit/MortyFx/speedtest-x) ![GitHub](https://img.shields.io/github/license/MortyFx/speedtest-x) 4 | 5 | 本仓库为 [LibreSpeed](https://github.com/librespeed/speedtest) 的延伸项目,LibreSpeed 是一个非常轻巧的网站测速工具。 6 | 7 | speedtest-x 使用文件数据库来保存来自不同用户的测速结果,方便您查看全国不同地域与运营商的测速效果。 8 | 9 | [English docs](https://github.com/MortyFx/MortyFx/blob/master/README.md) 10 | 11 | [加入交流 TG 群](https://t.me/xiaozhu5) 12 | 13 | **❗ 注意**:基于网页测速的原理,程序会生成无用文件供测速者下载来计算真实下行带宽,一定程度上存在被恶意刷流量的风险,在对外分享你的测速页面后,请注意观察服务器流量使用情况,避免流量使用异常。 14 | 15 | ## 扩展细节 16 | - 用户测速会上传测速记录并保存至网站服务器 17 | - 不依赖 MySQL,使用文件数据库 18 | - IP 库改用 [ip.sb](https://ip.sb),运营商记录更为精确 19 | 20 | ## 部署与使用 21 | 22 | #### 常规部署 (环境要求:PHP 5.6+) 23 | 24 | 1、下载本仓库并解压到网站目录,访问 `{域名}/index.html` 进行测速 25 | 26 | 2、打开 `{域名}/results.html` 查看测速记录 27 | 28 | > Tips:`backend/config.php` 中可定义一些自定义配置: 29 | > 30 | > `MAX_LOG_COUNT = 100`:最大可保存多少条测速记录 31 | > 32 | > `IP_SERVICE = 'ip.sb'`:使用的 IP 运营商解析服务(ip.sb 或 ipinfo.io) 33 | > 34 | > `SAME_IP_MULTI_LOGS = false`:是否允许同一IP记录多条测速结果 35 | 36 | #### Docker 部署 (支持平台: amd64 / arm64) 37 | 38 | 1、拉取 [Docker 镜像](https://hub.docker.com/r/badapple9/speedtest-x) `docker pull badapple9/speedtest-x` 39 | 40 | 2、运行容器 `docker run -d -p 9001:80 -it badapple9/speedtest-x` 41 | 42 | 参数解释: 43 | > **-d**:以常驻进程模式启动 44 | > 45 | > **9001**: 默认容器开放端口,可改为其他端口 46 | > 47 | > 启动时可指定的环境变量: 48 | > 49 | > **-e WEBPORT=80**: 容器内使用的端口 50 | > 51 | > **-e MAX_LOG_COUNT=100**: 最大可保存多少条测速记录 52 | > 53 | > **-e IP_SERVICE=ip.sb**: 使用的 IP 运营商解析服务(ip.sb 或 ipinfo.io) 54 | > 55 | > **-e SAME_IP_MULTI_LOGS=false**: 是否允许同一IP记录多条测速结果 56 | 57 | > 如果想让 Docker 容器支持 ipv6,可编辑 `/etc/docker/daemon.json` ,加上以下内容:(如果不存在这个文件则直接创建) 58 | > ``` 59 | > { 60 | > "ipv6": true, 61 | > "fixed-cidr-v6": "fd00::/80", 62 | > "experimental": true, 63 | > "ip6tables": true 64 | > } 65 | > ``` 66 | 67 | 3、访问 `{IP}:{端口}/index.html` 进行测速 68 | 69 | ## 截图 70 | 71 | ![index](https://raw.githubusercontent.com/BadApple9/images/main/indexdemo.png) 72 | ![results](https://raw.githubusercontent.com/BadApple9/images/main/resultsdemo.png) 73 | 74 | ## 更新记录 75 | 76 | **2022/07/25** 77 | 78 | > 静态资源 CDN 更换为 `cdn.baomitu.com` 79 | 80 | **2020/12/22** 81 | 82 | > 测速结果增加线性图表([@HuJK](https://github.com/HuJK)) 83 | 84 | **2020/12/10** 85 | 86 | > 增加可配置项 `SAME_IP_MULTI_LOGS`,可设置是否允许同一IP记录多条测速结果 87 | 88 | **2020/12/01** 89 | 90 | > 增加 ipv6 支持 91 | > 92 | > 增加可配置项 `IP_SERVICE`,可选择使用的 IP 运营商解析服务,`ip.sb` 或 `ipinfo.io` 93 | 94 | **2020/11/27** 95 | 96 | > 下行测速文件默认大小与最大大小限制为 50M(源项目默认 100M,最大 1024M) 97 | 98 | **2020/11/19** 99 | 100 | > Docker 镜像上线 [https://hub.docker.com/r/badapple9/speedtest-x](https://hub.docker.com/r/badapple9/speedtest-x) 101 | 102 | **2020/11/18** 103 | 104 | > 上报速度与延迟值强制使用浮点类型,修复结果页表格按照下载速度或 ping 值排序错误的问题 105 | 106 | **2020/11/16** 107 | 108 | > 优化测速结果上报频率 109 | > 110 | > 掩去测速结果 IP D 段 111 | 112 | **2020/11/13** 113 | 114 | > Release 115 | 116 | ## 鸣谢 117 | - [LibreSpeed](https://github.com/librespeed/speedtest) 118 | - [ip.sb](https://ip.sb) 119 | - [SleekDB](https://github.com/rakibtg/SleekDB) 120 | -------------------------------------------------------------------------------- /backend/SleekDB/Exceptions/ConditionNotAllowedException.php: -------------------------------------------------------------------------------- 1 | init( $configurations ); 85 | } 86 | 87 | /** 88 | * Initialize the store. 89 | * @param string $storeName 90 | * @param string $dataDir 91 | * @param array $options 92 | * @return SleekDB 93 | * @throws EmptyStoreNameException 94 | * @throws IOException 95 | * @throws InvalidConfigurationException 96 | */ 97 | public static function store( $storeName, $dataDir, $options = [] ) { 98 | if ( empty( $storeName ) ) throw new EmptyStoreNameException( 'Store name was not valid' ); 99 | $_dbInstance = new SleekDB( $dataDir, $options ); 100 | $_dbInstance->storeName = $storeName; 101 | // Boot store. 102 | $_dbInstance->bootStore(); 103 | // Initialize variables for the store. 104 | $_dbInstance->initVariables(); 105 | return $_dbInstance; 106 | } 107 | 108 | /** 109 | * Read store objects. 110 | * @return array 111 | * @throws ConditionNotAllowedException 112 | * @throws IndexNotFoundException 113 | * @throws EmptyFieldNameException 114 | * @throws InvalidDataException 115 | */ 116 | public function fetch() { 117 | $fetchedData = null; 118 | // Check if data should be provided from the cache. 119 | if ( $this->makeCache === true ) { 120 | $fetchedData = $this->reGenerateCache(); // Re-generate cache. 121 | } 122 | else if ( $this->useCache === true ) { 123 | $fetchedData = $this->useExistingCache(); // Use existing cache else re-generate. 124 | } 125 | else { 126 | $fetchedData = $this->findStoreDocuments(); // Returns data without looking for cached data. 127 | } 128 | $this->initVariables(); // Reset state. 129 | return $fetchedData; 130 | } 131 | 132 | /** 133 | * Creates a new object in the store. 134 | * The object is a plaintext JSON document. 135 | * @param array $storeData 136 | * @return array 137 | * @throws EmptyStoreDataException 138 | * @throws IOException 139 | * @throws InvalidStoreDataException 140 | * @throws JsonException 141 | * @throws IdNotAllowedException 142 | */ 143 | public function insert( $storeData ) { 144 | // Handle invalid data 145 | if ( empty( $storeData ) ) throw new EmptyStoreDataException( 'No data found to store' ); 146 | // Make sure that the data is an array 147 | if ( ! is_array( $storeData ) ) throw new InvalidStoreDataException( 'Storable data must an array' ); 148 | $storeData = $this->writeInStore( $storeData ); 149 | // Check do we need to wipe the cache for this store. 150 | if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache(); 151 | return $storeData; 152 | } 153 | 154 | /** 155 | * Creates multiple objects in the store. 156 | * @param $storeData 157 | * @return array 158 | * @throws EmptyStoreDataException 159 | * @throws IOException 160 | * @throws InvalidStoreDataException 161 | * @throws JsonException 162 | * @throws IdNotAllowedException 163 | */ 164 | public function insertMany( $storeData ) { 165 | // Handle invalid data 166 | if ( empty( $storeData ) ) throw new EmptyStoreDataException( 'No data found to insert in the store' ); 167 | // Make sure that the data is an array 168 | if ( ! is_array( $storeData ) ) throw new InvalidStoreDataException( 'Data must be an array in order to insert in the store' ); 169 | // All results. 170 | $results = []; 171 | foreach ( $storeData as $key => $node ) { 172 | $results[] = $this->writeInStore( $node ); 173 | } 174 | // Check do we need to wipe the cache for this store. 175 | if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache(); 176 | return $results; 177 | } 178 | 179 | /** 180 | * @param $updatable 181 | * @return bool 182 | * @throws IndexNotFoundException 183 | * @throws ConditionNotAllowedException 184 | * @throws EmptyFieldNameException 185 | * @throws InvalidDataException 186 | */ 187 | public function update($updatable ) { 188 | // Find all store objects. 189 | $storeObjects = $this->findStoreDocuments(); 190 | // If no store object found then return an empty array. 191 | if ( empty( $storeObjects ) ) { 192 | $this->initVariables(); // Reset state. 193 | return false; 194 | } 195 | foreach ( $storeObjects as $data ) { 196 | foreach ($updatable as $key => $value ) { 197 | // Do not update the _id reserved index of a store. 198 | if( $key != '_id' ) { 199 | $data[ $key ] = $value; 200 | } 201 | } 202 | $storePath = $this->storePath . 'data/' . $data[ '_id' ] . '.json'; 203 | if ( file_exists( $storePath ) ) { 204 | // Wait until it's unlocked, then update data. 205 | file_put_contents( $storePath, json_encode( $data ), LOCK_EX ); 206 | } 207 | } 208 | // Check do we need to wipe the cache for this store. 209 | if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache(); 210 | $this->initVariables(); // Reset state. 211 | return true; 212 | } 213 | 214 | /** 215 | * Deletes matched store objects. 216 | * @return bool 217 | * @throws IOException 218 | * @throws IndexNotFoundException 219 | * @throws ConditionNotAllowedException 220 | * @throws EmptyFieldNameException 221 | * @throws InvalidDataException 222 | */ 223 | public function delete() { 224 | // Find all store objects. 225 | $storeObjects = $this->findStoreDocuments(); 226 | if ( ! empty( $storeObjects ) ) { 227 | foreach ( $storeObjects as $data ) { 228 | if ( ! unlink( $this->storePath . 'data/' . $data[ '_id' ] . '.json' ) ) { 229 | $this->initVariables(); // Reset state. 230 | throw new IOException( 231 | 'Unable to delete storage file! 232 | Location: "'.$this->storePath . 'data/' . $data[ '_id' ] . '.json'.'"' 233 | ); 234 | } 235 | } 236 | // Check do we need to wipe the cache for this store. 237 | if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache(); 238 | $this->initVariables(); // Reset state. 239 | return true; 240 | } else { 241 | // Nothing found to delete 242 | $this->initVariables(); // Reset state. 243 | return true; 244 | // throw new \Exception( 'Invalid store object found, nothing to delete.' ); 245 | } 246 | } 247 | 248 | /** 249 | * Deletes a store and wipes all the data and cache it contains. 250 | * @return bool 251 | */ 252 | public function deleteStore() { 253 | $it = new \RecursiveDirectoryIterator( $this->storePath, \RecursiveDirectoryIterator::SKIP_DOTS ); 254 | $files = new \RecursiveIteratorIterator( $it, \RecursiveIteratorIterator::CHILD_FIRST ); 255 | foreach( $files as $file ) { 256 | if ( $file->isDir() ) rmdir( $file->getRealPath() ); 257 | else unlink( $file->getRealPath() ); 258 | } 259 | return rmdir( $this->storePath ); 260 | } 261 | 262 | } -------------------------------------------------------------------------------- /backend/SleekDB/Traits/CacheTrait.php: -------------------------------------------------------------------------------- 1 | getCacheToken(); 17 | $result = $this->findStoreDocuments(); 18 | // Write the cache file. 19 | file_put_contents( $this->getCachePath( $token ), json_encode( $result ) ); 20 | // Reset cache flags to avoid future queries on the same object of the store. 21 | $this->resetCacheFlags(); 22 | // Return the data. 23 | return $result; 24 | } 25 | 26 | /** 27 | * Use cache will first check if the cache exists, then re-use it. 28 | * If cache dosent exists then call makeCache and return the data. 29 | * @return array 30 | */ 31 | private function useExistingCache() { 32 | $token = $this->getCacheToken(); 33 | // Check if cache file exists. 34 | if ( file_exists( $this->getCachePath( $token ) ) ) { 35 | // Reset cache flags to avoid future queries on the same object of the store. 36 | $this->resetCacheFlags(); 37 | // Return data from the found cache file. 38 | return json_decode( file_get_contents( $this->getCachePath( $token ) ), true ); 39 | } else { 40 | // Cache file was not found, re-generate the cache and return the data. 41 | return $this->reGenerateCache(); 42 | } 43 | } 44 | 45 | /** 46 | * This method would make a unique token for the current query. 47 | * We would use this hash token as the id/name of the cache file. 48 | * @return string 49 | */ 50 | private function getCacheToken() { 51 | $query = json_encode( [ 52 | 'store' => $this->storePath, 53 | 'limit' => $this->limit, 54 | 'skip' => $this->skip, 55 | 'conditions' => $this->conditions, 56 | 'orConditions' => $this->orConditions, 57 | 'in' => $this->in, 58 | 'notIn' => $this->notIn, 59 | 'order' => $this->orderBy, 60 | 'search' => $this->searchKeyword, 61 | 'fieldsToSelect' => $this->fieldsToSelect, 62 | 'fieldsToExclude' => $this->fieldsToExclude, 63 | 'orConditionsWithAnd' => $this->orConditionsWithAnd, 64 | ] ); 65 | return md5( $query ); 66 | } 67 | 68 | /** 69 | * Reset the cache flags so the next database query dosent messedup. 70 | */ 71 | private function resetCacheFlags() { 72 | $this->makeCache = false; 73 | $this->useCache = false; 74 | } 75 | 76 | /** 77 | * Returns the cache directory absolute path for the current store. 78 | * @param string $token 79 | * @return string 80 | */ 81 | private function getCachePath( $token ) { 82 | return $this->storePath . 'cache/' . $token . '.json'; 83 | } 84 | 85 | /** 86 | * Delete a single cache file for current query. 87 | */ 88 | private function _deleteCache() { 89 | $token = $this->getCacheToken(); 90 | unlink( $this->getCachePath( $token ) ); 91 | } 92 | 93 | /** 94 | * Delete all cache for current store. 95 | */ 96 | private function _emptyAllCache() { 97 | array_map( 'unlink', glob( $this->storePath . "cache/*" ) ); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /backend/SleekDB/Traits/ConditionTrait.php: -------------------------------------------------------------------------------- 1 | fieldsToSelect[] = $fieldName; 28 | } 29 | return $this; 30 | } 31 | 32 | /** 33 | * @param string[] $fieldNames 34 | * @return $this 35 | * @throws InvalidArgumentException 36 | */ 37 | public function except($fieldNames){ 38 | $errorMsg = "if except is used an array containing strings with fieldNames has to be given"; 39 | if(!is_array($fieldNames)) throw new InvalidArgumentException($errorMsg); 40 | foreach ($fieldNames as $fieldName){ 41 | if(empty($fieldName)) continue; 42 | if(!is_string($fieldName)) throw new InvalidArgumentException($errorMsg); 43 | $this->fieldsToExclude[] = $fieldName; 44 | } 45 | return $this; 46 | } 47 | 48 | /** 49 | * Add conditions to filter data. 50 | * @param string $fieldName 51 | * @param string $condition 52 | * @param mixed $value 53 | * @return $this 54 | * @throws EmptyConditionException 55 | * @throws EmptyFieldNameException 56 | */ 57 | public function where( $fieldName, $condition, $value ) { 58 | if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name in where condition can not be empty.' ); 59 | if ( empty( $condition ) ) throw new EmptyConditionException( 'The comparison operator can not be empty.' ); 60 | // Append the condition into the conditions variable. 61 | $this->conditions[] = [ 62 | 'fieldName' => $fieldName, 63 | 'condition' => trim( $condition ), 64 | 'value' => $value 65 | ]; 66 | return $this; 67 | } 68 | 69 | 70 | /** 71 | * @param string $fieldName 72 | * @param array $values 73 | * @return $this 74 | * @throws EmptyFieldNameException 75 | */ 76 | public function in ( $fieldName, $values = [] ) { 77 | if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name for in clause can not be empty.' ); 78 | $values = (array) $values; 79 | $this->in[] = [ 80 | 'fieldName' => $fieldName, 81 | 'value' => $values 82 | ]; 83 | return $this; 84 | } 85 | 86 | /** 87 | * @param string $fieldName 88 | * @param array $values 89 | * @return $this 90 | * @throws EmptyFieldNameException 91 | */ 92 | public function notIn ( $fieldName, $values = [] ) { 93 | if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name for notIn clause can not be empty.' ); 94 | $values = (array) $values; 95 | $this->notIn[] = [ 96 | 'fieldName' => $fieldName, 97 | 'value' => $values 98 | ]; 99 | return $this; 100 | } 101 | 102 | /** 103 | * Add or-where conditions to filter data. 104 | * @param string|array|mixed $condition,... (string fieldName, string condition, mixed value) OR ([string fieldName, string condition, mixed value],...) 105 | * @return $this 106 | * @throws EmptyConditionException 107 | * @throws EmptyFieldNameException 108 | * @throws InvalidArgumentException 109 | */ 110 | public function orWhere( $condition ) { 111 | $args = func_get_args(); 112 | foreach ($args as $key => $arg){ 113 | if($key > 0) throw new InvalidArgumentException("Allowed: (string fieldName, string condition, mixed value) OR ([string fieldName, string condition, mixed value],...)"); 114 | if(is_array($arg)){ 115 | // parameters given as arrays for an "or where" with "and" between each condition 116 | $this->orWhereWithAnd($args); 117 | break; 118 | } 119 | if(count($args) === 3 && is_string($arg) && is_string($args[1])){ 120 | // parameters given as (string fieldName, string condition, mixed value) for a single "or where" 121 | $this->singleOrWhere($arg, $args[1], $args[2]); 122 | break; 123 | } 124 | } 125 | 126 | return $this; 127 | } 128 | 129 | /** 130 | * Add or-where conditions to filter data. 131 | * @param string $fieldName 132 | * @param string $condition 133 | * @param mixed $value 134 | * @return $this 135 | * @throws EmptyConditionException 136 | * @throws EmptyFieldNameException 137 | */ 138 | private function singleOrWhere( $fieldName, $condition, $value ) { 139 | if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name in orWhere condition can not be empty.' ); 140 | if ( empty( $condition ) ) throw new EmptyConditionException( 'The comparison operator can not be empty.' ); 141 | // Append the condition into the orConditions variable. 142 | $this->orConditions[] = [ 143 | 'fieldName' => $fieldName, 144 | 'condition' => trim( $condition ), 145 | 'value' => $value 146 | ]; 147 | return $this; 148 | } 149 | 150 | /** 151 | * @param array $conditions 152 | * @return $this 153 | * @throws EmptyConditionException 154 | * @throws InvalidArgumentException 155 | */ 156 | private function orWhereWithAnd($conditions){ 157 | 158 | if(!(count($conditions) > 0)){ 159 | throw new EmptyConditionException("You need to specify a where clause"); 160 | } 161 | 162 | foreach ($conditions as $key => $condition){ 163 | 164 | if(!is_array($condition)){ 165 | throw new InvalidArgumentException("The where clause has to be an array"); 166 | } 167 | 168 | // the user can pass the conditions as an array or a map 169 | if(count($condition) === 3 && array_key_exists(0, $condition) && array_key_exists(1, $condition) 170 | && array_key_exists(2, $condition)){ 171 | 172 | // user passed the condition as an array 173 | 174 | $this->orConditionsWithAnd[] = [ 175 | "fieldName" => $condition[0], 176 | "condition" => trim($condition[1]), 177 | "value" => $condition[2] 178 | ]; 179 | } else { 180 | 181 | // user passed the condition as a map 182 | 183 | if(!array_key_exists("fieldName", $condition) || empty($condition["fieldName"])){ 184 | throw new InvalidArgumentException("fieldName is required in where clause"); 185 | } 186 | if(!array_key_exists("condition", $condition) || empty($condition["condition"])){ 187 | throw new InvalidArgumentException("condition is required in where clause"); 188 | } 189 | if(!array_key_exists("value", $condition)){ 190 | throw new InvalidArgumentException("value is required in where clause"); 191 | } 192 | 193 | $this->orConditionsWithAnd[] = [ 194 | "fieldName" => $condition["fieldName"], 195 | "condition" => trim($condition["condition"]), 196 | "value" => $condition["value"] 197 | ]; 198 | 199 | } 200 | } 201 | 202 | return $this; 203 | 204 | } 205 | 206 | /** 207 | * Set the amount of data record to skip. 208 | * @param int $skip 209 | * @return $this 210 | */ 211 | public function skip( $skip = 0 ) { 212 | if ( $skip === false ) $skip = 0; 213 | $this->skip = (int) $skip; 214 | return $this; 215 | } 216 | 217 | /** 218 | * Set the amount of data record to limit. 219 | * @param int $limit 220 | * @return $this 221 | */ 222 | public function limit( $limit = 0 ) { 223 | if ( $limit === false ) $limit = 0; 224 | $this->limit = (int) $limit; 225 | return $this; 226 | } 227 | 228 | /** 229 | * Set the sort order. 230 | * @param string $order "asc" or "desc" 231 | * @param string $orderBy 232 | * @return $this 233 | * @throws InvalidOrderException 234 | */ 235 | public function orderBy( $order, $orderBy = '_id' ) { 236 | // Validate order. 237 | $order = strtolower( $order ); 238 | if ( ! in_array( $order, [ 'asc', 'desc' ] ) ) throw new InvalidOrderException( 'Invalid order found, please use "asc" or "desc" only.' ); 239 | $this->orderBy = [ 240 | 'order' => $order, 241 | 'field' => $orderBy 242 | ]; 243 | return $this; 244 | } 245 | 246 | /** 247 | * Do a fulltext like search against more than one field. 248 | * @param string|array $field one fieldName or multiple fieldNames as an array 249 | * @param string $keyword 250 | * @return $this 251 | * @throws EmptyFieldNameException 252 | */ 253 | public function search( $field, $keyword) { 254 | if ( empty( $field ) ) throw new EmptyFieldNameException( 'Cant perform search due to no field name was provided' ); 255 | if ( ! empty( $keyword ) ) $this->searchKeyword = [ 256 | 'field' => (array) $field, 257 | 'keyword' => $keyword 258 | ]; 259 | return $this; 260 | } 261 | 262 | /** 263 | * Re-generate the cache for the query. 264 | * @return $this 265 | */ 266 | public function makeCache() { 267 | $this->makeCache = true; 268 | $this->useCache = false; 269 | return $this; 270 | } 271 | 272 | /** 273 | * Re-use existing cache of the query, if doesnt exists 274 | * then would make new cache. 275 | * @return $this 276 | */ 277 | public function useCache() { 278 | $this->useCache = true; 279 | $this->makeCache = false; 280 | return $this; 281 | } 282 | 283 | /** 284 | * Delete cache for the current query. 285 | * @return $this 286 | */ 287 | public function deleteCache() { 288 | $this->_deleteCache(); 289 | return $this; 290 | } 291 | 292 | /** 293 | * Delete all cache of the current store. 294 | * @return $this 295 | */ 296 | public function deleteAllCache() { 297 | $this->_emptyAllCache(); 298 | return $this; 299 | } 300 | 301 | /** 302 | * Keep the active query conditions. 303 | * @return $this 304 | */ 305 | public function keepConditions () { 306 | $this->shouldKeepConditions = true; 307 | return $this; 308 | } 309 | 310 | } 311 | -------------------------------------------------------------------------------- /backend/SleekDB/Traits/HelperTrait.php: -------------------------------------------------------------------------------- 1 | dataDirectory = $dataDir; 50 | // Set auto cache settings. 51 | $autoCache = true; 52 | if ( isset( $conf[ 'auto_cache' ] ) ) $autoCache = $conf[ 'auto_cache' ]; 53 | $this->initAutoCache( $autoCache ); 54 | // Set timeout. 55 | $timeout = 120; 56 | if ( isset( $conf[ 'timeout' ] ) ) { 57 | if ( !empty( $conf[ 'timeout' ] ) ) $timeout = (int) $conf[ 'timeout' ]; 58 | } 59 | set_time_limit( $timeout ); 60 | // Control when to keep or delete the active query conditions. Delete conditions by default. 61 | $this->shouldKeepConditions = false; 62 | } // End of init() 63 | 64 | /** 65 | * Init data that SleekDB required to operate. 66 | */ 67 | private function initVariables() { 68 | if(!$this->shouldKeepConditions) { 69 | // Set empty results 70 | $this->results = []; 71 | // Set a default limit 72 | $this->limit = 0; 73 | // Set a default skip 74 | $this->skip = 0; 75 | // Set default conditions 76 | $this->conditions = []; 77 | // Or conditions 78 | $this->orConditions = []; 79 | // In clause conditions 80 | $this->in = []; 81 | // notIn clause conditions 82 | $this->notIn = []; 83 | // Set default group by value 84 | $this->orderBy = [ 85 | 'order' => false, 86 | 'field' => '_id' 87 | ]; 88 | // Set the default search keyword as an empty string. 89 | $this->searchKeyword = ''; 90 | // Disable make cache by default. 91 | $this->makeCache = false; 92 | // Control when to keep or delete the active query conditions. Delete conditions by default. 93 | $this->shouldKeepConditions = false; 94 | // specific fields to select 95 | $this->fieldsToSelect = []; 96 | $this->fieldsToExclude = []; 97 | 98 | $this->orConditionsWithAnd = []; 99 | } 100 | } // End of initVariables() 101 | 102 | /** 103 | * Initialize the auto cache settings. 104 | * @param bool $autoCache 105 | */ 106 | private function initAutoCache ( $autoCache = true ) { 107 | // Decide the cache status. 108 | if ( $autoCache === true ) { 109 | $this->useCache = true; 110 | // A flag that is used to check if cache should be empty 111 | // while create a new object in a store. 112 | $this->deleteCacheOnCreate = true; 113 | } else { 114 | $this->useCache = false; 115 | // A flag that is used to check if cache should be empty 116 | // while create a new object in a store. 117 | $this->deleteCacheOnCreate = false; 118 | } 119 | } 120 | 121 | /** 122 | * Method to boot a store. 123 | * @throws EmptyStoreNameException 124 | * @throws IOException 125 | */ 126 | private function bootStore() { 127 | $store = trim( $this->storeName ); 128 | // Validate the store name. 129 | if ( !$store || empty( $store ) ) throw new EmptyStoreNameException( 'Invalid store name was found' ); 130 | // Prepare store name. 131 | if ( substr( $store, -1 ) !== '/' ) $store = $store . '/'; 132 | // Store directory path. 133 | $this->storePath = $this->dataDirectory . $store; 134 | // Check if the store exists. 135 | if ( !file_exists( $this->storePath ) ) { 136 | // The directory was not found, create one with cache directory. 137 | if ( !mkdir( $this->storePath, 0777, true ) ) throw new IOException( 'Unable to create the store path at ' . $this->storePath ); 138 | // Create the cache directory. 139 | if ( !mkdir( $this->storePath . 'cache', 0777, true ) ) throw new IOException( 'Unable to create the store\'s cache directory at ' . $this->storePath . 'cache' ); 140 | // Create the data directory. 141 | if ( !mkdir( $this->storePath . 'data', 0777, true ) ) throw new IOException( 'Unable to create the store\'s data directory at ' . $this->storePath . 'data' ); 142 | // Create the store counter file. 143 | if ( !file_put_contents( $this->storePath . '_cnt.sdb', '0' ) ) throw new IOException( 'Unable to create the system counter for the store! Please check write permission' ); 144 | } 145 | // Check if PHP has write permission in that directory. 146 | if ( !is_writable( $this->storePath ) ) throw new IOException( 'Store path is not writable at "' . $this->storePath . '." Please change store path permission.' ); 147 | // Finally check if the directory is readable by PHP. 148 | if ( !is_readable( $this->storePath ) ) throw new IOException( 'Store path is not readable at "' . $this->storePath . '." Please change store path permission.' ); 149 | } 150 | 151 | // Returns a new and unique store object ID, by calling this method it would also 152 | // increment the ID system-wide only for the store. 153 | private function getStoreId() { 154 | $counter = 1; // default (first) id 155 | $counterPath = $this->storePath . '_cnt.sdb'; 156 | if ( file_exists( $counterPath ) ) { 157 | $fp = fopen($counterPath, 'r+'); 158 | for($retries = 10; $retries > 0; $retries--) { 159 | flock($fp, LOCK_UN); 160 | if (flock($fp, LOCK_EX) === false) { 161 | sleep(1); 162 | } else { 163 | $counter = (int) fgets($fp); 164 | $counter++; 165 | rewind($fp); 166 | fwrite($fp, (string) $counter); 167 | break; 168 | } 169 | } 170 | flock($fp, LOCK_UN); 171 | fclose($fp); 172 | } 173 | return $counter; 174 | } 175 | 176 | /** 177 | * Return the last created store object ID. 178 | * @return int 179 | */ 180 | private function getLastStoreId() { 181 | $counterPath = $this->storePath . '_cnt.sdb'; 182 | if ( file_exists( $counterPath ) ) { 183 | return (int) file_get_contents( $counterPath ); 184 | } 185 | return 0; 186 | } 187 | 188 | /** 189 | * Get a store by its system id. "_id" 190 | * @param $id 191 | * @return array|mixed 192 | */ 193 | private function getStoreDocumentById( $id ) { 194 | $store = $this->storePath . 'data/' . $id . '.json'; 195 | if ( file_exists( $store ) ) { 196 | $data = json_decode( file_get_contents( $store ), true ); 197 | if ( $data !== false ) return $data; 198 | } 199 | return []; 200 | } 201 | 202 | /** 203 | * @param string $file 204 | * @return mixed 205 | */ 206 | private function getDocumentByPath ( $file ) { 207 | return @json_decode( @file_get_contents( $file ), true ); 208 | } 209 | 210 | /** 211 | * @param string $condition 212 | * @param mixed $fieldValue value of current field 213 | * @param mixed $value value to check 214 | * @throws ConditionNotAllowedException 215 | * @return bool 216 | */ 217 | private function verifyWhereConditions ( $condition, $fieldValue, $value ) { 218 | // Check the type of rule. 219 | if ( $condition === '=' ) { 220 | // Check equal. 221 | return ( $fieldValue == $value ); 222 | } else if ( $condition === '!=' ) { 223 | // Check not equal. 224 | return ( $fieldValue != $value ); 225 | } else if ( $condition === '>' ) { 226 | // Check greater than. 227 | return ( $fieldValue > $value ); 228 | } else if ( $condition === '>=' ) { 229 | // Check greater equal. 230 | return ( $fieldValue >= $value ); 231 | } else if ( $condition === '<' ) { 232 | // Check less than. 233 | return ( $fieldValue < $value ); 234 | } else if ( $condition === '<=' ) { 235 | // Check less equal. 236 | return ( $fieldValue <= $value ); 237 | } else if (strtolower($condition) === 'like'){ 238 | $value = str_replace('%', '(.)*', $value); 239 | $pattern = "/^".$value."$/i"; 240 | return (preg_match($pattern, $fieldValue) === 1); 241 | } 242 | throw new ConditionNotAllowedException('condition '.$condition.' is not allowed'); 243 | } 244 | 245 | /** 246 | * @return array 247 | * @throws IndexNotFoundException 248 | * @throws ConditionNotAllowedException 249 | * @throws EmptyFieldNameException 250 | * @throws InvalidDataException 251 | */ 252 | private function findStoreDocuments() { 253 | $found = []; 254 | // Start collecting and filtering data. 255 | $storeDataPath = $this->storePath . 'data/'; 256 | if( $handle = opendir($storeDataPath) ) { 257 | while ( false !== ($entry = readdir($handle)) ) { 258 | if ($entry != "." && $entry != "..") { 259 | $file = $storeDataPath . $entry; 260 | $data = $this->getDocumentByPath( $file ); 261 | $document = false; 262 | if ( ! empty( $data ) ) { 263 | // Filter data found. 264 | if ( empty( $this->conditions ) ) { 265 | // Append all data of this store. 266 | $document = $data; 267 | } else { 268 | // Append only passed data from this store. 269 | $storePassed = true; 270 | // Iterate each conditions. 271 | foreach ( $this->conditions as $condition ) { 272 | if ( $storePassed === true ) { 273 | // Check for valid data from data source. 274 | $validData = true; 275 | $fieldValue = ''; 276 | try { 277 | $fieldValue = $this->getNestedProperty( $condition[ 'fieldName' ], $data ); 278 | } catch( \Exception $e ) { 279 | $validData = false; 280 | $storePassed = false; 281 | } 282 | if( $validData === true ) { 283 | $storePassed = $this->verifyWhereConditions( $condition[ 'condition' ], $fieldValue, $condition[ 'value' ] ); 284 | } 285 | } 286 | } 287 | // Check if current store is updatable or not. 288 | if ( $storePassed === true ) { 289 | // Append data to the found array. 290 | $document = $data; 291 | } else { 292 | // Check if a or-where condition will allow this document. 293 | foreach ( $this->orConditions as $condition ) { 294 | // Check for valid data from data source. 295 | $validData = true; 296 | $fieldValue = ''; 297 | try { 298 | $fieldValue = $this->getNestedProperty( $condition[ 'fieldName' ], $data ); 299 | } catch( \Exception $e ) { 300 | $validData = false; 301 | $storePassed = false; 302 | } 303 | if( $validData === true ) { 304 | $storePassed = $this->verifyWhereConditions( $condition[ 'condition' ], $fieldValue, $condition[ 'value' ] ); 305 | if( $storePassed ) { 306 | // Append data to the found array. 307 | $document = $data; 308 | break; 309 | } 310 | } 311 | } 312 | } 313 | // Check if current store is updatable or not. 314 | if ( $storePassed === true ) { 315 | // Append data to the found array. 316 | $document = $data; 317 | } else if(count($this->orConditionsWithAnd) > 0) { 318 | // Check if a all conditions will allow this document. 319 | $allConditionMatched = true; 320 | foreach ( $this->orConditionsWithAnd as $condition ) { 321 | // Check for valid data from data source. 322 | $validData = true; 323 | $fieldValue = ''; 324 | try { 325 | $fieldValue = $this->getNestedProperty( $condition[ 'fieldName' ], $data ); 326 | } catch( \Exception $e ) { 327 | $validData = false; 328 | } 329 | if( $validData === true ) { 330 | $storePassed = $this->verifyWhereConditions( $condition[ 'condition' ], $fieldValue, $condition[ 'value' ] ); 331 | if($storePassed) continue; 332 | } 333 | 334 | // if data was invalid or store did not pass 335 | $allConditionMatched = false; 336 | break; 337 | } 338 | if( $allConditionMatched === true ) { 339 | // Append data to the found array. 340 | $document = $data; 341 | } 342 | } 343 | } // Completed condition checks. 344 | 345 | // IN clause. 346 | if( $document && !empty($this->in) ) { 347 | foreach ( $this->in as $inClause) { 348 | $validData = true; 349 | $fieldValue = ''; 350 | try { 351 | $fieldValue = $this->getNestedProperty( $inClause[ 'fieldName' ], $data ); 352 | } catch( \Exception $e ) { 353 | $validData = false; 354 | $document = false; 355 | break; 356 | } 357 | if( $validData === true ) { 358 | if( !in_array( $fieldValue, $inClause[ 'value' ] ) ) { 359 | $document = false; 360 | break; 361 | } 362 | } 363 | } 364 | } 365 | 366 | // notIn clause. 367 | if ( $document && !empty($this->notIn) ) { 368 | foreach ( $this->notIn as $notInClause) { 369 | $validData = true; 370 | $fieldValue = ''; 371 | try { 372 | $fieldValue = $this->getNestedProperty( $notInClause[ 'fieldName' ], $data ); 373 | } catch( \Exception $e ) { 374 | $validData = false; 375 | break; 376 | } 377 | if( $validData === true ) { 378 | if( in_array( $fieldValue, $notInClause[ 'value' ] ) ) { 379 | $document = false; 380 | break; 381 | } 382 | } 383 | } 384 | } 385 | 386 | // Check if there is any document appendable. 387 | if( $document ) { 388 | $found[] = $document; 389 | } 390 | } 391 | } 392 | } 393 | closedir( $handle ); 394 | } 395 | 396 | if ( count( $found ) > 0 ) { 397 | // Check do we need to sort the data. 398 | if ( $this->orderBy[ 'order' ] !== false ) { 399 | // Start sorting on all data. 400 | $found = $this->sortArray( $this->orderBy[ 'field' ], $found, $this->orderBy[ 'order' ] ); 401 | } 402 | // If there was text search then we would also sort the result by search ranking. 403 | if ( ! empty( $this->searchKeyword ) ) { 404 | $found = $this->performSearch( $found ); 405 | } 406 | // Skip data 407 | if ( $this->skip > 0 ) $found = array_slice( $found, $this->skip ); 408 | // Limit data. 409 | if ( $this->limit > 0 ) $found = array_slice( $found, 0, $this->limit ); 410 | } 411 | 412 | if(count($found) > 0){ 413 | if(count($this->fieldsToSelect) > 0){ 414 | $found = $this->applyFieldsToSelect($found); 415 | } 416 | if(count($this->fieldsToExclude) > 0){ 417 | $found = $this->applyFieldsToExclude($found); 418 | } 419 | } 420 | 421 | return $found; 422 | } 423 | 424 | /** 425 | * @param array $found 426 | * @return array 427 | */ 428 | private function applyFieldsToSelect($found){ 429 | if(!(count($found) > 0) || !(count($this->fieldsToSelect) > 0)){ 430 | return $found; 431 | } 432 | foreach ($found as $key => $item){ 433 | $newItem = []; 434 | $newItem['_id'] = $item['_id']; 435 | foreach ($this->fieldsToSelect as $fieldToSelect){ 436 | if(array_key_exists($fieldToSelect, $item)){ 437 | $newItem[$fieldToSelect] = $item[$fieldToSelect]; 438 | } 439 | } 440 | $found[$key] = $newItem; 441 | } 442 | return $found; 443 | } 444 | 445 | /** 446 | * @param array $found 447 | * @return array 448 | */ 449 | private function applyFieldsToExclude($found){ 450 | if(!(count($found) > 0) || !(count($this->fieldsToExclude) > 0)){ 451 | return $found; 452 | } 453 | foreach ($found as $key => $item){ 454 | foreach ($this->fieldsToExclude as $fieldToExclude){ 455 | if(array_key_exists($fieldToExclude, $item)){ 456 | unset($item[$fieldToExclude]); 457 | } 458 | } 459 | $found[$key] = $item; 460 | } 461 | return $found; 462 | } 463 | 464 | 465 | /** 466 | * Writes an object in a store. 467 | * @param $storeData 468 | * @return array 469 | * @throws IOException 470 | * @throws JsonException 471 | * @throws IdNotAllowedException 472 | */ 473 | private function writeInStore( $storeData ) { 474 | // Cast to array 475 | $storeData = (array) $storeData; 476 | // Check if it has _id key 477 | if ( isset( $storeData[ '_id' ] ) ) throw new IdNotAllowedException( 'The _id index is reserved by SleekDB, please delete the _id key and try again' ); 478 | $id = $this->getStoreId(); 479 | // Add the system ID with the store data array. 480 | $storeData[ '_id' ] = $id; 481 | // Prepare storable data 482 | $storableJSON = json_encode( $storeData ); 483 | if ( $storableJSON === false ) throw new JsonException( 'Unable to encode the data array, 484 | please provide a valid PHP associative array' ); 485 | // Define the store path 486 | $storePath = $this->storePath . 'data/' . $id . '.json'; 487 | if ( ! file_put_contents( $storePath, $storableJSON ) ) { 488 | throw new IOException( "Unable to write the object file! Please check if PHP has write permission." ); 489 | } 490 | return $storeData; 491 | } 492 | 493 | /** 494 | * Sort store objects. 495 | * @param $field 496 | * @param $data 497 | * @param string $order 498 | * @return array 499 | * @throws IndexNotFoundException 500 | * @throws EmptyFieldNameException 501 | * @throws InvalidDataException 502 | */ 503 | private function sortArray( $field, $data, $order = 'ASC' ) { 504 | $dryData = []; 505 | // Check if data is an array. 506 | if( is_array( $data ) ) { 507 | // Get value of the target field. 508 | foreach ( $data as $value ) { 509 | $dryData[] = $this->getNestedProperty( $field, $value ); 510 | } 511 | } 512 | // Descide the order direction. 513 | if ( strtolower( $order ) === 'asc' ) asort( $dryData ); 514 | else if ( strtolower( $order ) === 'desc' ) arsort( $dryData ); 515 | // Re arrange the array. 516 | $finalArray = []; 517 | foreach ( $dryData as $key => $value) { 518 | $finalArray[] = $data[ $key ]; 519 | } 520 | return $finalArray; 521 | } 522 | 523 | /** 524 | * Get nested properties of a store object. 525 | * @param string $fieldName 526 | * @param array $data 527 | * @return array|mixed 528 | * @throws EmptyFieldNameException 529 | * @throws IndexNotFoundException 530 | * @throws InvalidDataException 531 | */ 532 | private function getNestedProperty($fieldName, $data ) { 533 | if( !is_array( $data ) ) throw new InvalidDataException('data has to be an array'); 534 | if(empty( $fieldName )) throw new EmptyFieldNameException('fieldName is not allowed to be empty'); 535 | 536 | // Dive deep step by step. 537 | foreach(explode( '.', $fieldName ) as $i ) { 538 | // If the field do not exists then insert an empty string. 539 | if ( ! isset( $data[ $i ] ) ) { 540 | $data = ''; 541 | throw new IndexNotFoundException( '"'.$i.'" index was not found in the provided data array' ); 542 | } 543 | // The index is valid, collect the data. 544 | $data = $data[ $i ]; 545 | } 546 | return $data; 547 | } 548 | 549 | /** 550 | * Do a search in store objects. This is like a doing a full-text search. 551 | * @param array $data 552 | * @return array 553 | */ 554 | private function performSearch($data = [] ) { 555 | if ( empty( $data ) ) return $data; 556 | $nodesRank = []; 557 | // Looping on each store data. 558 | foreach ($data as $key => $value) { 559 | // Looping on each field name of search-able fields. 560 | foreach ($this->searchKeyword[ 'field' ] as $field) { 561 | try { 562 | $nodeValue = $this->getNestedProperty( $field, $value ); 563 | // The searchable field was found, do comparison against search keyword. 564 | similar_text( strtolower($nodeValue), strtolower($this->searchKeyword['keyword']), $perc ); 565 | if ( $perc > 50 ) { 566 | // Check if current store object already has a value, if so then add the new value. 567 | if ( isset( $nodesRank[ $key ] ) ) $nodesRank[ $key ] += $perc; 568 | else $nodesRank[ $key ] = $perc; 569 | } 570 | } catch ( \Exception $e ) { 571 | continue; 572 | } 573 | } 574 | } 575 | if ( empty( $nodesRank ) ) { 576 | // No matched store was found against the search keyword. 577 | return []; 578 | } 579 | // Sort nodes in descending order by the rank. 580 | arsort( $nodesRank ); 581 | // Map original nodes by the rank. 582 | $nodes = []; 583 | foreach ( $nodesRank as $key => $value ) { 584 | $nodes[] = $data[ $key ]; 585 | } 586 | return $nodes; 587 | } 588 | 589 | } 590 | -------------------------------------------------------------------------------- /backend/config.php: -------------------------------------------------------------------------------- 1 | 50) { 22 | return 50; 23 | } 24 | 25 | return (int) $_GET['ckSize']; 26 | } 27 | 28 | /** 29 | * @return void 30 | */ 31 | function sendHeaders() 32 | { 33 | header('HTTP/1.1 200 OK'); 34 | 35 | if (isset($_GET['cors'])) { 36 | header('Access-Control-Allow-Origin: *'); 37 | header('Access-Control-Allow-Methods: GET, POST'); 38 | } 39 | 40 | // Indicate a file download 41 | header('Content-Description: File Transfer'); 42 | header('Content-Type: application/octet-stream'); 43 | header('Content-Disposition: attachment; filename=random.dat'); 44 | header('Content-Transfer-Encoding: binary'); 45 | 46 | // Cache settings: never cache this request 47 | header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0'); 48 | header('Cache-Control: post-check=0, pre-check=0', false); 49 | header('Pragma: no-cache'); 50 | } 51 | 52 | // Determine how much data we should send 53 | $chunks = getChunkCount(); 54 | 55 | // Generate data 56 | $data = openssl_random_pseudo_bytes(1048576); 57 | 58 | // Deliver chunks of 1048576 bytes 59 | sendHeaders(); 60 | for ($i = 0; $i < $chunks; $i++) { 61 | echo $data; 62 | flush(); 63 | } 64 | -------------------------------------------------------------------------------- /backend/getIP.php: -------------------------------------------------------------------------------- 1 | $processedString, 332 | 'rawIspInfo' => $rawIspInfo ?: '', 333 | ]); 334 | } 335 | 336 | $ip = getClientIp(); 337 | $localIpInfo = getLocalOrPrivateIpInfo($ip); 338 | // local ip, no need to fetch further information 339 | if (is_string($localIpInfo)) { 340 | sendResponse($ip, $localIpInfo); 341 | exit; 342 | } 343 | 344 | if (!isset($_GET['isp'])) { 345 | sendResponse($ip); 346 | exit; 347 | } 348 | 349 | $rawIspInfo = getIspInfo($ip, IP_SERVICE); 350 | $isp = getIsp($rawIspInfo, IP_SERVICE); 351 | //$distance = getDistance($rawIspInfo); 352 | 353 | sendResponse($ip, $isp, $rawIspInfo); 354 | -------------------------------------------------------------------------------- /backend/getIP_ipInfo_apikey.php: -------------------------------------------------------------------------------- 1 | false, 21 | 'timeout' => 120 22 | ]); 23 | 24 | $reportData = [ 25 | "key" => sha1(filter_var($_POST['key'], FILTER_SANITIZE_STRING)), 26 | "ip" => maskLastSegment(filter_var($_POST['ip'], FILTER_SANITIZE_STRING)), 27 | "isp" => filter_var($_POST['isp'], FILTER_SANITIZE_STRING), 28 | "addr" => filter_var($_POST['addr'], FILTER_SANITIZE_STRING), 29 | "dspeed" => (double) filter_var($_POST['dspeed'], FILTER_SANITIZE_STRING), 30 | "uspeed" => (double) filter_var($_POST['uspeed'], FILTER_SANITIZE_STRING), 31 | "ping" => (double) filter_var($_POST['ping'], FILTER_SANITIZE_STRING), 32 | "jitter" => (double) filter_var($_POST['jitter'], FILTER_SANITIZE_STRING), 33 | "created" => date('Y-m-d H:i:s', time()), 34 | ]; 35 | 36 | if (empty($reportData['ip'])) exit; 37 | 38 | if (SAME_IP_MULTI_LOGS) { 39 | $oldLog = $store->where('key', '=', $reportData['key'])->fetch(); 40 | } else { 41 | $oldLog = $store->where('ip', '=', $reportData['ip'])->orderBy( 'desc', '_id' )->fetch(); 42 | } 43 | 44 | if (is_array($oldLog) && empty($oldLog)) { 45 | $results = $store->insert($reportData); 46 | if ($results['_id'] > MAX_LOG_COUNT) { 47 | $store->where('_id', '=', $results['_id'] - MAX_LOG_COUNT)->delete(); 48 | } 49 | } else { 50 | $id = $oldLog[0]['_id']; 51 | if (SAME_IP_MULTI_LOGS) { 52 | $key = $reportData['key']; 53 | unset($reportData['key']); 54 | $store->where('_id', '=', $id)->update($reportData); 55 | } else { 56 | $ip = $reportData['ip']; 57 | unset($reportData['ip']); 58 | $store->where('_id', '=', $id)->update($reportData); 59 | } 60 | } -------------------------------------------------------------------------------- /backend/results-api.php: -------------------------------------------------------------------------------- 1 | false, 8 | 'timeout' => 120 9 | ]); 10 | 11 | $logs = $store 12 | ->orderBy( 'desc', 'created' ) 13 | ->limit( MAX_LOG_COUNT ) 14 | ->fetch(); 15 | 16 | $data = [ 17 | 'code' => 0, 18 | 'data' => $logs, 19 | ]; 20 | 21 | echo json_encode($data); -------------------------------------------------------------------------------- /chart.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ISP Speed Chart 6 | 7 | 8 | 9 | 41 | 42 | 43 | 44 |
45 | 46 |
47 | 202 | 203 | 204 | 205 | 206 | -------------------------------------------------------------------------------- /chartjs/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | window.chartColors = { 4 | red: 'rgb(255, 99, 132)', 5 | orange: 'rgb(255, 159, 64)', 6 | yellow: 'rgb(255, 205, 86)', 7 | green: 'rgb(75, 192, 192)', 8 | blue: 'rgb(54, 162, 235)', 9 | purple: 'rgb(153, 102, 255)', 10 | grey: 'rgb(201, 203, 207)' 11 | }; 12 | 13 | (function(global) { 14 | var MONTHS = [ 15 | 'January', 16 | 'February', 17 | 'March', 18 | 'April', 19 | 'May', 20 | 'June', 21 | 'July', 22 | 'August', 23 | 'September', 24 | 'October', 25 | 'November', 26 | 'December' 27 | ]; 28 | 29 | var COLORS = [ 30 | '#4dc9f6', 31 | '#f67019', 32 | '#f53794', 33 | '#537bc4', 34 | '#acc236', 35 | '#166a8f', 36 | '#00a950', 37 | '#58595b', 38 | '#8549ba' 39 | ]; 40 | 41 | var Samples = global.Samples || (global.Samples = {}); 42 | var Color = global.Color; 43 | 44 | Samples.utils = { 45 | // Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/ 46 | srand: function(seed) { 47 | this._seed = seed; 48 | }, 49 | 50 | rand: function(min, max) { 51 | var seed = this._seed; 52 | min = min === undefined ? 0 : min; 53 | max = max === undefined ? 1 : max; 54 | this._seed = (seed * 9301 + 49297) % 233280; 55 | return min + (this._seed / 233280) * (max - min); 56 | }, 57 | 58 | numbers: function(config) { 59 | var cfg = config || {}; 60 | var min = cfg.min || 0; 61 | var max = cfg.max || 1; 62 | var from = cfg.from || []; 63 | var count = cfg.count || 8; 64 | var decimals = cfg.decimals || 8; 65 | var continuity = cfg.continuity || 1; 66 | var dfactor = Math.pow(10, decimals) || 0; 67 | var data = []; 68 | var i, value; 69 | 70 | for (i = 0; i < count; ++i) { 71 | value = (from[i] || 0) + this.rand(min, max); 72 | if (this.rand() <= continuity) { 73 | data.push(Math.round(dfactor * value) / dfactor); 74 | } else { 75 | data.push(null); 76 | } 77 | } 78 | 79 | return data; 80 | }, 81 | 82 | labels: function(config) { 83 | var cfg = config || {}; 84 | var min = cfg.min || 0; 85 | var max = cfg.max || 100; 86 | var count = cfg.count || 8; 87 | var step = (max - min) / count; 88 | var decimals = cfg.decimals || 8; 89 | var dfactor = Math.pow(10, decimals) || 0; 90 | var prefix = cfg.prefix || ''; 91 | var values = []; 92 | var i; 93 | 94 | for (i = min; i < max; i += step) { 95 | values.push(prefix + Math.round(dfactor * i) / dfactor); 96 | } 97 | 98 | return values; 99 | }, 100 | 101 | months: function(config) { 102 | var cfg = config || {}; 103 | var count = cfg.count || 12; 104 | var section = cfg.section; 105 | var values = []; 106 | var i, value; 107 | 108 | for (i = 0; i < count; ++i) { 109 | value = MONTHS[Math.ceil(i) % 12]; 110 | values.push(value.substring(0, section)); 111 | } 112 | 113 | return values; 114 | }, 115 | 116 | color: function(index) { 117 | return COLORS[index % COLORS.length]; 118 | }, 119 | 120 | transparentize: function(color, opacity) { 121 | var alpha = opacity === undefined ? 0.5 : 1 - opacity; 122 | return Color(color).alpha(alpha).rgbString(); 123 | } 124 | }; 125 | 126 | // DEPRECATED 127 | window.randomScalingFactor = function() { 128 | return Math.round(Samples.utils.rand(-100, 100)); 129 | }; 130 | 131 | // INITIALIZATION 132 | 133 | Samples.utils.srand(Date.now()); 134 | 135 | // Google Analytics 136 | /* eslint-disable */ 137 | if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) { 138 | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 139 | (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 140 | m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 141 | })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 142 | ga('create', 'UA-28909194-3', 'auto'); 143 | ga('send', 'pageview'); 144 | } 145 | /* eslint-enable */ 146 | 147 | }(this)); 148 | -------------------------------------------------------------------------------- /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MortyFx/speedtest-x/dd8bbe1080cdfb960307540cff47e76080e4083e/favicon.ico -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | speedtest-x 7 | 8 | 9 | 74 | 75 | 233 | 234 | 235 |

Speedtest-X

236 |
237 |
238 |
239 |
240 |
241 |
下载速度
242 |
243 |
Mbps
244 |
245 |
246 |
上传速度
247 |
248 |
Mbps
249 |
250 |
251 |
252 |
253 |
延迟
254 |
255 |
ms
256 |
257 |
258 |
抖动
259 |
260 |
ms
261 |
262 |
263 |
264 | IP地址: 265 |
266 |
267 |

查看测速记录

268 |

speedtest-x 项目地址

269 | 272 | 273 | 274 | -------------------------------------------------------------------------------- /results.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 测速结果 | speedtest-x 6 | 7 | 8 | 9 | 10 | 11 | 31 | 32 | 33 |
34 |

speedtest-x 测速结果

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