Create speedtest-x

This commit is contained in:
Stille 2021-06-14 13:31:09 +08:00
parent 2812347933
commit 51a3b03bfd
39 changed files with 4297 additions and 0 deletions

42
.github/workflows/speedtest-x.yml vendored Normal file
View File

@ -0,0 +1,42 @@
name: "speedtest-x docker build"
env:
PROJECT: speedtest-x
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set tag
id: tag
run: |
TAG=$(cat ${{ env.PROJECT }}/Dockerfile | awk 'NR==4 {print $3}')
echo "::set-env name=TAG::$TAG"
- name: Docker Hub login
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
run: |
echo "${DOCKER_PASSWORD}" | docker login --username ${DOCKER_USERNAME} --password-stdin
- name: Set up Docker Buildx
id: buildx
uses: crazy-max/ghaction-docker-buildx@v1
with:
buildx-version: latest
- name: Build Dockerfile
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
run: |
docker buildx build \
--platform=linux/amd64,linux/arm64 \
--output "type=image,push=true" \
--file ${{ env.PROJECT }}/Dockerfile ./${{ env.PROJECT }} \
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:latest \
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:${TAG}

2
speedtest-x/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
speedlogs
.idea

44
speedtest-x/Dockerfile Normal file
View File

@ -0,0 +1,44 @@
FROM php:7.4-apache
ENV VERSION 2021-06-14
# Install extensions
RUN apt-get update && apt-get install -y \
libfreetype6-dev \
libjpeg62-turbo-dev \
libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv \
&& docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ \
&& docker-php-ext-install -j$(nproc) gd
# Prepare files and folders
RUN mkdir -p /speedtest/
# Copy sources
COPY backend/ /speedtest/backend
COPY chartjs/ /speedtest/chartjs
COPY *.js /speedtest/
COPY *.html /speedtest/
COPY docker/entrypoint.sh /
ENV TIME_ZONE=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TIME_ZONE /etc/localtime && echo $TIME_ZONE > /etc/timezone
RUN printf '[PHP]\ndate.timezone = "Asia/Shanghai"\n' > /usr/local/etc/php/conf.d/tzone.ini
# Prepare environment variabiles defaults
ENV WEBPORT=80
ENV MAX_LOG_COUNT=100
ENV IP_SERVICE="ip.sb"
ENV SAME_IP_MULTI_LOGS="false"
VOLUME ["/speedlogs"]
# Final touches
EXPOSE 80
CMD ["bash", "/entrypoint.sh"]

504
speedtest-x/LICENSE Normal file
View File

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

27
speedtest-x/README.md Normal file
View File

@ -0,0 +1,27 @@
# speedtest-x
GitHub [stilleshan/dockerfiles](https://github.com/stilleshan/dockerfiles)
Docker [stilleshan/speedtest-x](https://hub.docker.com/r/stilleshan/speedtest-x)
> *docker image support for X86 and ARM*
## 简介
基于 [BadApple9/speedtest-x](https://github.com/BadApple9/speedtest-x) 项目的 docker 镜像.
## 更新
**2021-06-14** 更新 docker 镜像,新增同时支持 X86 和 ARM 架构.
## 部署
### docker
```shell
docker run -d --name=speedtest-x --restart=always -p 12345:80 stilleshan/speedtest-x
```
### docker compose
下载 [docker-compose.yml](https://raw.githubusercontent.com/stilleshan/dockerfiles/main/speedtest-x/docker-compose.yml) 执行以下命令启动:
```shell
docker-compose up -d
```
## 参考
GitHub [BadApple9/speedtest-x](https://github.com/BadApple9/speedtest-x)

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class ConditionNotAllowedException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class EmptyConditionException extends \Exception {}

View File

@ -0,0 +1,7 @@
<?php
namespace SleekDB\Exceptions;
class EmptyFieldNameException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class EmptyStoreDataException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class EmptyStoreNameException extends \Exception {}

View File

@ -0,0 +1,7 @@
<?php
namespace SleekDB\Exceptions;
class IOException extends \Exception {}

View File

@ -0,0 +1,7 @@
<?php
namespace SleekDB\Exceptions;
class IdNotAllowedException extends \Exception {}

View File

@ -0,0 +1,7 @@
<?php
namespace SleekDB\Exceptions;
class IndexNotFoundException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class InvalidArgumentException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class InvalidConfigurationException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class InvalidDataException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class InvalidOrderException extends \Exception {}

View File

@ -0,0 +1,6 @@
<?php
namespace SleekDB\Exceptions;
class InvalidStoreDataException extends \Exception {}

View File

@ -0,0 +1,9 @@
<?php
namespace SleekDB\Exceptions;
if(!class_exists('JsonException')){
class JsonException extends \Exception {}
}

View File

@ -0,0 +1,262 @@
<?php
namespace SleekDB;
use SleekDB\Exceptions\ConditionNotAllowedException;
use SleekDB\Exceptions\EmptyFieldNameException;
use SleekDB\Exceptions\EmptyStoreDataException;
use SleekDB\Exceptions\EmptyStoreNameException;
use SleekDB\Exceptions\IdNotAllowedException;
use SleekDB\Exceptions\IndexNotFoundException;
use SleekDB\Exceptions\InvalidConfigurationException;
use SleekDB\Exceptions\InvalidDataException;
use SleekDB\Exceptions\InvalidStoreDataException;
use SleekDB\Exceptions\IOException;
use SleekDB\Exceptions\JsonException;
use SleekDB\Traits\HelperTrait;
use SleekDB\Traits\CacheTrait;
use SleekDB\Traits\ConditionTrait;
// to provide usage without composer, we need to require the files
require_once __DIR__ . "/Exceptions/ConditionNotAllowedException.php";
require_once __DIR__ . "/Exceptions/EmptyFieldNameException.php";
require_once __DIR__ . "/Exceptions/EmptyStoreNameException.php";
require_once __DIR__ . "/Exceptions/IdNotAllowedException.php";
require_once __DIR__ . "/Exceptions/IndexNotFoundException.php";
require_once __DIR__ . "/Exceptions/InvalidConfigurationException.php";
require_once __DIR__ . "/Exceptions/InvalidDataException.php";
require_once __DIR__ . "/Exceptions/InvalidStoreDataException.php";
require_once __DIR__ . "/Exceptions/IOException.php";
require_once __DIR__ . "/Exceptions/JsonException.php";
require_once __DIR__ . "/Traits/HelperTrait.php";
require_once __DIR__ . "/Traits/CacheTrait.php";
require_once __DIR__ . "/Traits/ConditionTrait.php";
class SleekDB{
use HelperTrait;
use ConditionTrait;
use CacheTrait;
private $root = __DIR__;
private $storeName;
private $makeCache;
private $useCache;
private $deleteCacheOnCreate;
private $storePath;
private $dataDirectory;
private $shouldKeepConditions;
private $results;
private $limit;
private $skip;
private $conditions;
private $orConditions;
private $in;
private $notIn;
private $orderBy;
private $searchKeyword;
private $fieldsToSelect = [];
private $fieldsToExclude = [];
private $orConditionsWithAnd = [];
/**
* SleekDB constructor.
* Initialize the database.
* @param string $dataDir
* @param array $configurations
* @throws IOException
* @throws InvalidConfigurationException
*/
function __construct( $dataDir = '', $configurations = [] ) {
// Add data dir.
$configurations[ 'data_directory' ] = $dataDir;
// Initialize SleekDB
$this->init( $configurations );
}
/**
* Initialize the store.
* @param string $storeName
* @param string $dataDir
* @param array $options
* @return SleekDB
* @throws EmptyStoreNameException
* @throws IOException
* @throws InvalidConfigurationException
*/
public static function store( $storeName, $dataDir, $options = [] ) {
if ( empty( $storeName ) ) throw new EmptyStoreNameException( 'Store name was not valid' );
$_dbInstance = new SleekDB( $dataDir, $options );
$_dbInstance->storeName = $storeName;
// Boot store.
$_dbInstance->bootStore();
// Initialize variables for the store.
$_dbInstance->initVariables();
return $_dbInstance;
}
/**
* Read store objects.
* @return array
* @throws ConditionNotAllowedException
* @throws IndexNotFoundException
* @throws EmptyFieldNameException
* @throws InvalidDataException
*/
public function fetch() {
$fetchedData = null;
// Check if data should be provided from the cache.
if ( $this->makeCache === true ) {
$fetchedData = $this->reGenerateCache(); // Re-generate cache.
}
else if ( $this->useCache === true ) {
$fetchedData = $this->useExistingCache(); // Use existing cache else re-generate.
}
else {
$fetchedData = $this->findStoreDocuments(); // Returns data without looking for cached data.
}
$this->initVariables(); // Reset state.
return $fetchedData;
}
/**
* Creates a new object in the store.
* The object is a plaintext JSON document.
* @param array $storeData
* @return array
* @throws EmptyStoreDataException
* @throws IOException
* @throws InvalidStoreDataException
* @throws JsonException
* @throws IdNotAllowedException
*/
public function insert( $storeData ) {
// Handle invalid data
if ( empty( $storeData ) ) throw new EmptyStoreDataException( 'No data found to store' );
// Make sure that the data is an array
if ( ! is_array( $storeData ) ) throw new InvalidStoreDataException( 'Storable data must an array' );
$storeData = $this->writeInStore( $storeData );
// Check do we need to wipe the cache for this store.
if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache();
return $storeData;
}
/**
* Creates multiple objects in the store.
* @param $storeData
* @return array
* @throws EmptyStoreDataException
* @throws IOException
* @throws InvalidStoreDataException
* @throws JsonException
* @throws IdNotAllowedException
*/
public function insertMany( $storeData ) {
// Handle invalid data
if ( empty( $storeData ) ) throw new EmptyStoreDataException( 'No data found to insert in the store' );
// Make sure that the data is an array
if ( ! is_array( $storeData ) ) throw new InvalidStoreDataException( 'Data must be an array in order to insert in the store' );
// All results.
$results = [];
foreach ( $storeData as $key => $node ) {
$results[] = $this->writeInStore( $node );
}
// Check do we need to wipe the cache for this store.
if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache();
return $results;
}
/**
* @param $updatable
* @return bool
* @throws IndexNotFoundException
* @throws ConditionNotAllowedException
* @throws EmptyFieldNameException
* @throws InvalidDataException
*/
public function update($updatable ) {
// Find all store objects.
$storeObjects = $this->findStoreDocuments();
// If no store object found then return an empty array.
if ( empty( $storeObjects ) ) {
$this->initVariables(); // Reset state.
return false;
}
foreach ( $storeObjects as $data ) {
foreach ($updatable as $key => $value ) {
// Do not update the _id reserved index of a store.
if( $key != '_id' ) {
$data[ $key ] = $value;
}
}
$storePath = $this->storePath . 'data/' . $data[ '_id' ] . '.json';
if ( file_exists( $storePath ) ) {
// Wait until it's unlocked, then update data.
file_put_contents( $storePath, json_encode( $data ), LOCK_EX );
}
}
// Check do we need to wipe the cache for this store.
if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache();
$this->initVariables(); // Reset state.
return true;
}
/**
* Deletes matched store objects.
* @return bool
* @throws IOException
* @throws IndexNotFoundException
* @throws ConditionNotAllowedException
* @throws EmptyFieldNameException
* @throws InvalidDataException
*/
public function delete() {
// Find all store objects.
$storeObjects = $this->findStoreDocuments();
if ( ! empty( $storeObjects ) ) {
foreach ( $storeObjects as $data ) {
if ( ! unlink( $this->storePath . 'data/' . $data[ '_id' ] . '.json' ) ) {
$this->initVariables(); // Reset state.
throw new IOException(
'Unable to delete storage file!
Location: "'.$this->storePath . 'data/' . $data[ '_id' ] . '.json'.'"'
);
}
}
// Check do we need to wipe the cache for this store.
if ( $this->deleteCacheOnCreate === true ) $this->_emptyAllCache();
$this->initVariables(); // Reset state.
return true;
} else {
// Nothing found to delete
$this->initVariables(); // Reset state.
return true;
// throw new \Exception( 'Invalid store object found, nothing to delete.' );
}
}
/**
* Deletes a store and wipes all the data and cache it contains.
* @return bool
*/
public function deleteStore() {
$it = new \RecursiveDirectoryIterator( $this->storePath, \RecursiveDirectoryIterator::SKIP_DOTS );
$files = new \RecursiveIteratorIterator( $it, \RecursiveIteratorIterator::CHILD_FIRST );
foreach( $files as $file ) {
if ( $file->isDir() ) rmdir( $file->getRealPath() );
else unlink( $file->getRealPath() );
}
return rmdir( $this->storePath );
}
}

View File

@ -0,0 +1,101 @@
<?php
namespace SleekDB\Traits;
/**
* Methods required to perform the cache mechanishm.
*/
trait CacheTrait {
/**
* Make cache deletes the old cache if exists then creates a new cache file.
* returns the data.
* @return array
*/
private function reGenerateCache() {
$token = $this->getCacheToken();
$result = $this->findStoreDocuments();
// Write the cache file.
file_put_contents( $this->getCachePath( $token ), json_encode( $result ) );
// Reset cache flags to avoid future queries on the same object of the store.
$this->resetCacheFlags();
// Return the data.
return $result;
}
/**
* Use cache will first check if the cache exists, then re-use it.
* If cache dosent exists then call makeCache and return the data.
* @return array
*/
private function useExistingCache() {
$token = $this->getCacheToken();
// Check if cache file exists.
if ( file_exists( $this->getCachePath( $token ) ) ) {
// Reset cache flags to avoid future queries on the same object of the store.
$this->resetCacheFlags();
// Return data from the found cache file.
return json_decode( file_get_contents( $this->getCachePath( $token ) ), true );
} else {
// Cache file was not found, re-generate the cache and return the data.
return $this->reGenerateCache();
}
}
/**
* This method would make a unique token for the current query.
* We would use this hash token as the id/name of the cache file.
* @return string
*/
private function getCacheToken() {
$query = json_encode( [
'store' => $this->storePath,
'limit' => $this->limit,
'skip' => $this->skip,
'conditions' => $this->conditions,
'orConditions' => $this->orConditions,
'in' => $this->in,
'notIn' => $this->notIn,
'order' => $this->orderBy,
'search' => $this->searchKeyword,
'fieldsToSelect' => $this->fieldsToSelect,
'fieldsToExclude' => $this->fieldsToExclude,
'orConditionsWithAnd' => $this->orConditionsWithAnd,
] );
return md5( $query );
}
/**
* Reset the cache flags so the next database query dosent messedup.
*/
private function resetCacheFlags() {
$this->makeCache = false;
$this->useCache = false;
}
/**
* Returns the cache directory absolute path for the current store.
* @param string $token
* @return string
*/
private function getCachePath( $token ) {
return $this->storePath . 'cache/' . $token . '.json';
}
/**
* Delete a single cache file for current query.
*/
private function _deleteCache() {
$token = $this->getCacheToken();
unlink( $this->getCachePath( $token ) );
}
/**
* Delete all cache for current store.
*/
private function _emptyAllCache() {
array_map( 'unlink', glob( $this->storePath . "cache/*" ) );
}
}

View File

@ -0,0 +1,311 @@
<?php
namespace SleekDB\Traits;
use SleekDB\Exceptions\EmptyConditionException;
use SleekDB\Exceptions\EmptyFieldNameException;
use SleekDB\Exceptions\InvalidArgumentException;
use SleekDB\Exceptions\InvalidOrderException;
/**
* Coditions trait.
*/
trait ConditionTrait {
/**
* Select specific fields or exclude fields with - (minus) prepended
* @param string[] $fieldNames
* @return $this
* @throws InvalidArgumentException
*/
public function select($fieldNames){
$errorMsg = "if select is used an array containing strings with fieldNames has to be given";
if(!is_array($fieldNames)) throw new InvalidArgumentException($errorMsg);
foreach ($fieldNames as $fieldName){
if(empty($fieldName)) continue;
if(!is_string($fieldName)) throw new InvalidArgumentException($errorMsg);
$this->fieldsToSelect[] = $fieldName;
}
return $this;
}
/**
* @param string[] $fieldNames
* @return $this
* @throws InvalidArgumentException
*/
public function except($fieldNames){
$errorMsg = "if except is used an array containing strings with fieldNames has to be given";
if(!is_array($fieldNames)) throw new InvalidArgumentException($errorMsg);
foreach ($fieldNames as $fieldName){
if(empty($fieldName)) continue;
if(!is_string($fieldName)) throw new InvalidArgumentException($errorMsg);
$this->fieldsToExclude[] = $fieldName;
}
return $this;
}
/**
* Add conditions to filter data.
* @param string $fieldName
* @param string $condition
* @param mixed $value
* @return $this
* @throws EmptyConditionException
* @throws EmptyFieldNameException
*/
public function where( $fieldName, $condition, $value ) {
if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name in where condition can not be empty.' );
if ( empty( $condition ) ) throw new EmptyConditionException( 'The comparison operator can not be empty.' );
// Append the condition into the conditions variable.
$this->conditions[] = [
'fieldName' => $fieldName,
'condition' => trim( $condition ),
'value' => $value
];
return $this;
}
/**
* @param string $fieldName
* @param array $values
* @return $this
* @throws EmptyFieldNameException
*/
public function in ( $fieldName, $values = [] ) {
if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name for in clause can not be empty.' );
$values = (array) $values;
$this->in[] = [
'fieldName' => $fieldName,
'value' => $values
];
return $this;
}
/**
* @param string $fieldName
* @param array $values
* @return $this
* @throws EmptyFieldNameException
*/
public function notIn ( $fieldName, $values = [] ) {
if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name for notIn clause can not be empty.' );
$values = (array) $values;
$this->notIn[] = [
'fieldName' => $fieldName,
'value' => $values
];
return $this;
}
/**
* Add or-where conditions to filter data.
* @param string|array|mixed $condition,... (string fieldName, string condition, mixed value) OR ([string fieldName, string condition, mixed value],...)
* @return $this
* @throws EmptyConditionException
* @throws EmptyFieldNameException
* @throws InvalidArgumentException
*/
public function orWhere( $condition ) {
$args = func_get_args();
foreach ($args as $key => $arg){
if($key > 0) throw new InvalidArgumentException("Allowed: (string fieldName, string condition, mixed value) OR ([string fieldName, string condition, mixed value],...)");
if(is_array($arg)){
// parameters given as arrays for an "or where" with "and" between each condition
$this->orWhereWithAnd($args);
break;
}
if(count($args) === 3 && is_string($arg) && is_string($args[1])){
// parameters given as (string fieldName, string condition, mixed value) for a single "or where"
$this->singleOrWhere($arg, $args[1], $args[2]);
break;
}
}
return $this;
}
/**
* Add or-where conditions to filter data.
* @param string $fieldName
* @param string $condition
* @param mixed $value
* @return $this
* @throws EmptyConditionException
* @throws EmptyFieldNameException
*/
private function singleOrWhere( $fieldName, $condition, $value ) {
if ( empty( $fieldName ) ) throw new EmptyFieldNameException( 'Field name in orWhere condition can not be empty.' );
if ( empty( $condition ) ) throw new EmptyConditionException( 'The comparison operator can not be empty.' );
// Append the condition into the orConditions variable.
$this->orConditions[] = [
'fieldName' => $fieldName,
'condition' => trim( $condition ),
'value' => $value
];
return $this;
}
/**
* @param array $conditions
* @return $this
* @throws EmptyConditionException
* @throws InvalidArgumentException
*/
private function orWhereWithAnd($conditions){
if(!(count($conditions) > 0)){
throw new EmptyConditionException("You need to specify a where clause");
}
foreach ($conditions as $key => $condition){
if(!is_array($condition)){
throw new InvalidArgumentException("The where clause has to be an array");
}
// the user can pass the conditions as an array or a map
if(count($condition) === 3 && array_key_exists(0, $condition) && array_key_exists(1, $condition)
&& array_key_exists(2, $condition)){
// user passed the condition as an array
$this->orConditionsWithAnd[] = [
"fieldName" => $condition[0],
"condition" => trim($condition[1]),
"value" => $condition[2]
];
} else {
// user passed the condition as a map
if(!array_key_exists("fieldName", $condition) || empty($condition["fieldName"])){
throw new InvalidArgumentException("fieldName is required in where clause");
}
if(!array_key_exists("condition", $condition) || empty($condition["condition"])){
throw new InvalidArgumentException("condition is required in where clause");
}
if(!array_key_exists("value", $condition)){
throw new InvalidArgumentException("value is required in where clause");
}
$this->orConditionsWithAnd[] = [
"fieldName" => $condition["fieldName"],
"condition" => trim($condition["condition"]),
"value" => $condition["value"]
];
}
}
return $this;
}
/**
* Set the amount of data record to skip.
* @param int $skip
* @return $this
*/
public function skip( $skip = 0 ) {
if ( $skip === false ) $skip = 0;
$this->skip = (int) $skip;
return $this;
}
/**
* Set the amount of data record to limit.
* @param int $limit
* @return $this
*/
public function limit( $limit = 0 ) {
if ( $limit === false ) $limit = 0;
$this->limit = (int) $limit;
return $this;
}
/**
* Set the sort order.
* @param string $order "asc" or "desc"
* @param string $orderBy
* @return $this
* @throws InvalidOrderException
*/
public function orderBy( $order, $orderBy = '_id' ) {
// Validate order.
$order = strtolower( $order );
if ( ! in_array( $order, [ 'asc', 'desc' ] ) ) throw new InvalidOrderException( 'Invalid order found, please use "asc" or "desc" only.' );
$this->orderBy = [
'order' => $order,
'field' => $orderBy
];
return $this;
}
/**
* Do a fulltext like search against more than one field.
* @param string|array $field one fieldName or multiple fieldNames as an array
* @param string $keyword
* @return $this
* @throws EmptyFieldNameException
*/
public function search( $field, $keyword) {
if ( empty( $field ) ) throw new EmptyFieldNameException( 'Cant perform search due to no field name was provided' );
if ( ! empty( $keyword ) ) $this->searchKeyword = [
'field' => (array) $field,
'keyword' => $keyword
];
return $this;
}
/**
* Re-generate the cache for the query.
* @return $this
*/
public function makeCache() {
$this->makeCache = true;
$this->useCache = false;
return $this;
}
/**
* Re-use existing cache of the query, if doesnt exists
* then would make new cache.
* @return $this
*/
public function useCache() {
$this->useCache = true;
$this->makeCache = false;
return $this;
}
/**
* Delete cache for the current query.
* @return $this
*/
public function deleteCache() {
$this->_deleteCache();
return $this;
}
/**
* Delete all cache of the current store.
* @return $this
*/
public function deleteAllCache() {
$this->_emptyAllCache();
return $this;
}
/**
* Keep the active query conditions.
* @return $this
*/
public function keepConditions () {
$this->shouldKeepConditions = true;
return $this;
}
}

View File

@ -0,0 +1,590 @@
<?php
namespace SleekDB\Traits;
use SleekDB\Exceptions\ConditionNotAllowedException;
use SleekDB\Exceptions\IdNotAllowedException;
use SleekDB\Exceptions\IOException;
use SleekDB\Exceptions\InvalidConfigurationException;
use SleekDB\Exceptions\EmptyStoreNameException;
use SleekDB\Exceptions\IndexNotFoundException;
use SleekDB\Exceptions\JsonException;
use SleekDB\Exceptions\EmptyFieldNameException;
use SleekDB\Exceptions\InvalidDataException;
/**
* Collections of method that helps to manage the data.
* All methods in this trait should be private.
*
*/
trait HelperTrait {
/**
* @param array $conf
* @throws IOException
* @throws InvalidConfigurationException
*/
private function init( $conf ) {
// Check for valid configurations.
if( empty( $conf ) OR !is_array( $conf ) ) throw new InvalidConfigurationException( 'Invalid configurations was found.' );
// Check if the 'data_directory' was provided.
if ( !isset( $conf[ 'data_directory' ] ) ) throw new InvalidConfigurationException( '"data_directory" was not provided in the configurations.' );
// Check if data_directory is empty.
if ( empty( $conf[ 'data_directory' ] ) ) throw new InvalidConfigurationException( '"data_directory" cant be empty in the configurations.' );
// Prepare the data directory.
$dataDir = trim( $conf[ 'data_directory' ] );
// Handle directory path ending.
if ( substr( $dataDir, -1 ) !== '/' ) $dataDir = $dataDir . '/';
// Check if the data_directory exists.
if ( !file_exists( $dataDir ) ) {
// The directory was not found, create one.
if ( !mkdir( $dataDir, 0777, true ) ) throw new IOException( 'Unable to create the data directory at ' . $dataDir );
}
// Check if PHP has write permission in that directory.
if ( !is_writable( $dataDir ) ) throw new IOException( 'Data directory is not writable at "' . $dataDir . '." Please change data directory permission.' );
// Finally check if the directory is readable by PHP.
if ( !is_readable( $dataDir ) ) throw new IOException( 'Data directory is not readable at "' . $dataDir . '." Please change data directory permission.' );
// Set the data directory.
$this->dataDirectory = $dataDir;
// Set auto cache settings.
$autoCache = true;
if ( isset( $conf[ 'auto_cache' ] ) ) $autoCache = $conf[ 'auto_cache' ];
$this->initAutoCache( $autoCache );
// Set timeout.
$timeout = 120;
if ( isset( $conf[ 'timeout' ] ) ) {
if ( !empty( $conf[ 'timeout' ] ) ) $timeout = (int) $conf[ 'timeout' ];
}
set_time_limit( $timeout );
// Control when to keep or delete the active query conditions. Delete conditions by default.
$this->shouldKeepConditions = false;
} // End of init()
/**
* Init data that SleekDB required to operate.
*/
private function initVariables() {
if(!$this->shouldKeepConditions) {
// Set empty results
$this->results = [];
// Set a default limit
$this->limit = 0;
// Set a default skip
$this->skip = 0;
// Set default conditions
$this->conditions = [];
// Or conditions
$this->orConditions = [];
// In clause conditions
$this->in = [];
// notIn clause conditions
$this->notIn = [];
// Set default group by value
$this->orderBy = [
'order' => false,
'field' => '_id'
];
// Set the default search keyword as an empty string.
$this->searchKeyword = '';
// Disable make cache by default.
$this->makeCache = false;
// Control when to keep or delete the active query conditions. Delete conditions by default.
$this->shouldKeepConditions = false;
// specific fields to select
$this->fieldsToSelect = [];
$this->fieldsToExclude = [];
$this->orConditionsWithAnd = [];
}
} // End of initVariables()
/**
* Initialize the auto cache settings.
* @param bool $autoCache
*/
private function initAutoCache ( $autoCache = true ) {
// Decide the cache status.
if ( $autoCache === true ) {
$this->useCache = true;
// A flag that is used to check if cache should be empty
// while create a new object in a store.
$this->deleteCacheOnCreate = true;
} else {
$this->useCache = false;
// A flag that is used to check if cache should be empty
// while create a new object in a store.
$this->deleteCacheOnCreate = false;
}
}
/**
* Method to boot a store.
* @throws EmptyStoreNameException
* @throws IOException
*/
private function bootStore() {
$store = trim( $this->storeName );
// Validate the store name.
if ( !$store || empty( $store ) ) throw new EmptyStoreNameException( 'Invalid store name was found' );
// Prepare store name.
if ( substr( $store, -1 ) !== '/' ) $store = $store . '/';
// Store directory path.
$this->storePath = $this->dataDirectory . $store;
// Check if the store exists.
if ( !file_exists( $this->storePath ) ) {
// The directory was not found, create one with cache directory.
if ( !mkdir( $this->storePath, 0777, true ) ) throw new IOException( 'Unable to create the store path at ' . $this->storePath );
// Create the cache directory.
if ( !mkdir( $this->storePath . 'cache', 0777, true ) ) throw new IOException( 'Unable to create the store\'s cache directory at ' . $this->storePath . 'cache' );
// Create the data directory.
if ( !mkdir( $this->storePath . 'data', 0777, true ) ) throw new IOException( 'Unable to create the store\'s data directory at ' . $this->storePath . 'data' );
// Create the store counter file.
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' );
}
// Check if PHP has write permission in that directory.
if ( !is_writable( $this->storePath ) ) throw new IOException( 'Store path is not writable at "' . $this->storePath . '." Please change store path permission.' );
// Finally check if the directory is readable by PHP.
if ( !is_readable( $this->storePath ) ) throw new IOException( 'Store path is not readable at "' . $this->storePath . '." Please change store path permission.' );
}
// Returns a new and unique store object ID, by calling this method it would also
// increment the ID system-wide only for the store.
private function getStoreId() {
$counter = 1; // default (first) id
$counterPath = $this->storePath . '_cnt.sdb';
if ( file_exists( $counterPath ) ) {
$fp = fopen($counterPath, 'r+');
for($retries = 10; $retries > 0; $retries--) {
flock($fp, LOCK_UN);
if (flock($fp, LOCK_EX) === false) {
sleep(1);
} else {
$counter = (int) fgets($fp);
$counter++;
rewind($fp);
fwrite($fp, (string) $counter);
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
}
return $counter;
}
/**
* Return the last created store object ID.
* @return int
*/
private function getLastStoreId() {
$counterPath = $this->storePath . '_cnt.sdb';
if ( file_exists( $counterPath ) ) {
return (int) file_get_contents( $counterPath );
}
return 0;
}
/**
* Get a store by its system id. "_id"
* @param $id
* @return array|mixed
*/
private function getStoreDocumentById( $id ) {
$store = $this->storePath . 'data/' . $id . '.json';
if ( file_exists( $store ) ) {
$data = json_decode( file_get_contents( $store ), true );
if ( $data !== false ) return $data;
}
return [];
}
/**
* @param string $file
* @return mixed
*/
private function getDocumentByPath ( $file ) {
return @json_decode( @file_get_contents( $file ), true );
}
/**
* @param string $condition
* @param mixed $fieldValue value of current field
* @param mixed $value value to check
* @throws ConditionNotAllowedException
* @return bool
*/
private function verifyWhereConditions ( $condition, $fieldValue, $value ) {
// Check the type of rule.
if ( $condition === '=' ) {
// Check equal.
return ( $fieldValue == $value );
} else if ( $condition === '!=' ) {
// Check not equal.
return ( $fieldValue != $value );
} else if ( $condition === '>' ) {
// Check greater than.
return ( $fieldValue > $value );
} else if ( $condition === '>=' ) {
// Check greater equal.
return ( $fieldValue >= $value );
} else if ( $condition === '<' ) {
// Check less than.
return ( $fieldValue < $value );
} else if ( $condition === '<=' ) {
// Check less equal.
return ( $fieldValue <= $value );
} else if (strtolower($condition) === 'like'){
$value = str_replace('%', '(.)*', $value);
$pattern = "/^".$value."$/i";
return (preg_match($pattern, $fieldValue) === 1);
}
throw new ConditionNotAllowedException('condition '.$condition.' is not allowed');
}
/**
* @return array
* @throws IndexNotFoundException
* @throws ConditionNotAllowedException
* @throws EmptyFieldNameException
* @throws InvalidDataException
*/
private function findStoreDocuments() {
$found = [];
// Start collecting and filtering data.
$storeDataPath = $this->storePath . 'data/';
if( $handle = opendir($storeDataPath) ) {
while ( false !== ($entry = readdir($handle)) ) {
if ($entry != "." && $entry != "..") {
$file = $storeDataPath . $entry;
$data = $this->getDocumentByPath( $file );
$document = false;
if ( ! empty( $data ) ) {
// Filter data found.
if ( empty( $this->conditions ) ) {
// Append all data of this store.
$document = $data;
} else {
// Append only passed data from this store.
$storePassed = true;
// Iterate each conditions.
foreach ( $this->conditions as $condition ) {
if ( $storePassed === true ) {
// Check for valid data from data source.
$validData = true;
$fieldValue = '';
try {
$fieldValue = $this->getNestedProperty( $condition[ 'fieldName' ], $data );
} catch( \Exception $e ) {
$validData = false;
$storePassed = false;
}
if( $validData === true ) {
$storePassed = $this->verifyWhereConditions( $condition[ 'condition' ], $fieldValue, $condition[ 'value' ] );
}
}
}
// Check if current store is updatable or not.
if ( $storePassed === true ) {
// Append data to the found array.
$document = $data;
} else {
// Check if a or-where condition will allow this document.
foreach ( $this->orConditions as $condition ) {
// Check for valid data from data source.
$validData = true;
$fieldValue = '';
try {
$fieldValue = $this->getNestedProperty( $condition[ 'fieldName' ], $data );
} catch( \Exception $e ) {
$validData = false;
$storePassed = false;
}
if( $validData === true ) {
$storePassed = $this->verifyWhereConditions( $condition[ 'condition' ], $fieldValue, $condition[ 'value' ] );
if( $storePassed ) {
// Append data to the found array.
$document = $data;
break;
}
}
}
}
// Check if current store is updatable or not.
if ( $storePassed === true ) {
// Append data to the found array.
$document = $data;
} else if(count($this->orConditionsWithAnd) > 0) {
// Check if a all conditions will allow this document.
$allConditionMatched = true;
foreach ( $this->orConditionsWithAnd as $condition ) {
// Check for valid data from data source.
$validData = true;
$fieldValue = '';
try {
$fieldValue = $this->getNestedProperty( $condition[ 'fieldName' ], $data );
} catch( \Exception $e ) {
$validData = false;
}
if( $validData === true ) {
$storePassed = $this->verifyWhereConditions( $condition[ 'condition' ], $fieldValue, $condition[ 'value' ] );
if($storePassed) continue;
}
// if data was invalid or store did not pass
$allConditionMatched = false;
break;
}
if( $allConditionMatched === true ) {
// Append data to the found array.
$document = $data;
}
}
} // Completed condition checks.
// IN clause.
if( $document && !empty($this->in) ) {
foreach ( $this->in as $inClause) {
$validData = true;
$fieldValue = '';
try {
$fieldValue = $this->getNestedProperty( $inClause[ 'fieldName' ], $data );
} catch( \Exception $e ) {
$validData = false;
$document = false;
break;
}
if( $validData === true ) {
if( !in_array( $fieldValue, $inClause[ 'value' ] ) ) {
$document = false;
break;
}
}
}
}
// notIn clause.
if ( $document && !empty($this->notIn) ) {
foreach ( $this->notIn as $notInClause) {
$validData = true;
$fieldValue = '';
try {
$fieldValue = $this->getNestedProperty( $notInClause[ 'fieldName' ], $data );
} catch( \Exception $e ) {
$validData = false;
break;
}
if( $validData === true ) {
if( in_array( $fieldValue, $notInClause[ 'value' ] ) ) {
$document = false;
break;
}
}
}
}
// Check if there is any document appendable.
if( $document ) {
$found[] = $document;
}
}
}
}
closedir( $handle );
}
if ( count( $found ) > 0 ) {
// Check do we need to sort the data.
if ( $this->orderBy[ 'order' ] !== false ) {
// Start sorting on all data.
$found = $this->sortArray( $this->orderBy[ 'field' ], $found, $this->orderBy[ 'order' ] );
}
// If there was text search then we would also sort the result by search ranking.
if ( ! empty( $this->searchKeyword ) ) {
$found = $this->performSearch( $found );
}
// Skip data
if ( $this->skip > 0 ) $found = array_slice( $found, $this->skip );
// Limit data.
if ( $this->limit > 0 ) $found = array_slice( $found, 0, $this->limit );
}
if(count($found) > 0){
if(count($this->fieldsToSelect) > 0){
$found = $this->applyFieldsToSelect($found);
}
if(count($this->fieldsToExclude) > 0){
$found = $this->applyFieldsToExclude($found);
}
}
return $found;
}
/**
* @param array $found
* @return array
*/
private function applyFieldsToSelect($found){
if(!(count($found) > 0) || !(count($this->fieldsToSelect) > 0)){
return $found;
}
foreach ($found as $key => $item){
$newItem = [];
$newItem['_id'] = $item['_id'];
foreach ($this->fieldsToSelect as $fieldToSelect){
if(array_key_exists($fieldToSelect, $item)){
$newItem[$fieldToSelect] = $item[$fieldToSelect];
}
}
$found[$key] = $newItem;
}
return $found;
}
/**
* @param array $found
* @return array
*/
private function applyFieldsToExclude($found){
if(!(count($found) > 0) || !(count($this->fieldsToExclude) > 0)){
return $found;
}
foreach ($found as $key => $item){
foreach ($this->fieldsToExclude as $fieldToExclude){
if(array_key_exists($fieldToExclude, $item)){
unset($item[$fieldToExclude]);
}
}
$found[$key] = $item;
}
return $found;
}
/**
* Writes an object in a store.
* @param $storeData
* @return array
* @throws IOException
* @throws JsonException
* @throws IdNotAllowedException
*/
private function writeInStore( $storeData ) {
// Cast to array
$storeData = (array) $storeData;
// Check if it has _id key
if ( isset( $storeData[ '_id' ] ) ) throw new IdNotAllowedException( 'The _id index is reserved by SleekDB, please delete the _id key and try again' );
$id = $this->getStoreId();
// Add the system ID with the store data array.
$storeData[ '_id' ] = $id;
// Prepare storable data
$storableJSON = json_encode( $storeData );
if ( $storableJSON === false ) throw new JsonException( 'Unable to encode the data array,
please provide a valid PHP associative array' );
// Define the store path
$storePath = $this->storePath . 'data/' . $id . '.json';
if ( ! file_put_contents( $storePath, $storableJSON ) ) {
throw new IOException( "Unable to write the object file! Please check if PHP has write permission." );
}
return $storeData;
}
/**
* Sort store objects.
* @param $field
* @param $data
* @param string $order
* @return array
* @throws IndexNotFoundException
* @throws EmptyFieldNameException
* @throws InvalidDataException
*/
private function sortArray( $field, $data, $order = 'ASC' ) {
$dryData = [];
// Check if data is an array.
if( is_array( $data ) ) {
// Get value of the target field.
foreach ( $data as $value ) {
$dryData[] = $this->getNestedProperty( $field, $value );
}
}
// Descide the order direction.
if ( strtolower( $order ) === 'asc' ) asort( $dryData );
else if ( strtolower( $order ) === 'desc' ) arsort( $dryData );
// Re arrange the array.
$finalArray = [];
foreach ( $dryData as $key => $value) {
$finalArray[] = $data[ $key ];
}
return $finalArray;
}
/**
* Get nested properties of a store object.
* @param string $fieldName
* @param array $data
* @return array|mixed
* @throws EmptyFieldNameException
* @throws IndexNotFoundException
* @throws InvalidDataException
*/
private function getNestedProperty($fieldName, $data ) {
if( !is_array( $data ) ) throw new InvalidDataException('data has to be an array');
if(empty( $fieldName )) throw new EmptyFieldNameException('fieldName is not allowed to be empty');
// Dive deep step by step.
foreach(explode( '.', $fieldName ) as $i ) {
// If the field do not exists then insert an empty string.
if ( ! isset( $data[ $i ] ) ) {
$data = '';
throw new IndexNotFoundException( '"'.$i.'" index was not found in the provided data array' );
}
// The index is valid, collect the data.
$data = $data[ $i ];
}
return $data;
}
/**
* Do a search in store objects. This is like a doing a full-text search.
* @param array $data
* @return array
*/
private function performSearch($data = [] ) {
if ( empty( $data ) ) return $data;
$nodesRank = [];
// Looping on each store data.
foreach ($data as $key => $value) {
// Looping on each field name of search-able fields.
foreach ($this->searchKeyword[ 'field' ] as $field) {
try {
$nodeValue = $this->getNestedProperty( $field, $value );
// The searchable field was found, do comparison against search keyword.
similar_text( strtolower($nodeValue), strtolower($this->searchKeyword['keyword']), $perc );
if ( $perc > 50 ) {
// Check if current store object already has a value, if so then add the new value.
if ( isset( $nodesRank[ $key ] ) ) $nodesRank[ $key ] += $perc;
else $nodesRank[ $key ] = $perc;
}
} catch ( \Exception $e ) {
continue;
}
}
}
if ( empty( $nodesRank ) ) {
// No matched store was found against the search keyword.
return [];
}
// Sort nodes in descending order by the rank.
arsort( $nodesRank );
// Map original nodes by the rank.
$nodes = [];
foreach ( $nodesRank as $key => $value ) {
$nodes[] = $data[ $key ];
}
return $nodes;
}
}

View File

@ -0,0 +1,16 @@
<?php
/**
* 最多保存多少条测试记录
*/
const MAX_LOG_COUNT = 100;
/**
* IP运营商解析服务(1) ip.sb | (2) ipinfo.io 如果1解析ip异常请切换成2
*/
const IP_SERVICE = 'ip.sb';
/**
* 是否允许同一IP记录多条测速结果
*/
const SAME_IP_MULTI_LOGS = false;

View File

@ -0,0 +1,14 @@
<?php
header('HTTP/1.1 200 OK');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Encoding, Content-Type');
}
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Connection: keep-alive');

View File

@ -0,0 +1,63 @@
<?php
// Disable Compression
@ini_set('zlib.output_compression', 'Off');
@ini_set('output_buffering', 'Off');
@ini_set('output_handler', '');
/**
* @return int
*/
function getChunkCount()
{
if (
!array_key_exists('ckSize', $_GET)
|| !ctype_digit($_GET['ckSize'])
|| (int) $_GET['ckSize'] <= 0
) {
return 4;
}
if ((int) $_GET['ckSize'] > 50) {
return 50;
}
return (int) $_GET['ckSize'];
}
/**
* @return void
*/
function sendHeaders()
{
header('HTTP/1.1 200 OK');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
// Indicate a file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=random.dat');
header('Content-Transfer-Encoding: binary');
// Cache settings: never cache this request
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
// Determine how much data we should send
$chunks = getChunkCount();
// Generate data
$data = openssl_random_pseudo_bytes(1048576);
// Deliver chunks of 1048576 bytes
sendHeaders();
for ($i = 0; $i < $chunks; $i++) {
echo $data;
flush();
}

View File

@ -0,0 +1,353 @@
<?php
/*
* This script detects the client's IP address and fetches ISP info from ipinfo.io/
* Output from this script is a JSON string composed of 2 objects: a string called processedString which contains the combined IP, ISP, Contry and distance as it can be presented to the user; and an object called rawIspInfo which contains the raw data from ipinfo.io (will be empty if isp detection is disabled).
* Client side, the output of this script can be treated as JSON or as regular text. If the output is regular text, it will be shown to the user as is.
*/
require_once "./config.php";
error_reporting(0);
define('API_KEY_FILE', 'getIP_ipInfo_apikey.php');
define('SERVER_LOCATION_CACHE_FILE', 'getIP_serverLocation.php');
/**
* @return string
*/
function getClientIp()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
$ip = $_SERVER['HTTP_X_REAL_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = preg_replace('/,.*/', '', $ip); # hosts are comma-separated, client is first
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return preg_replace('/^::ffff:/', '', $ip);
}
/**
* @param string $ip
*
* @return string|null
*/
function getLocalOrPrivateIpInfo($ip)
{
// ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
if ('::1' === $ip) {
return 'localhost IPv6 access';
}
// simplified IPv6 link-local address (should match fe80::/10)
if (stripos($ip, 'fe80:') === 0) {
return 'link-local IPv6 access';
}
// anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
if (strpos($ip, '127.') === 0) {
return 'localhost IPv4 access';
}
// 10/8 private IPv4
if (strpos($ip, '10.') === 0) {
return 'private IPv4 access';
}
// 172.16/12 private IPv4
if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) {
return 'private IPv4 access';
}
// 192.168/16 private IPv4
if (strpos($ip, '192.168.') === 0) {
return 'private IPv4 access';
}
// IPv4 link-local
if (strpos($ip, '169.254.') === 0) {
return 'link-local IPv4 access';
}
return null;
}
/**
* @return string
*/
function getIpInfoTokenString()
{
if (!file_exists(API_KEY_FILE)) {
return '';
}
require API_KEY_FILE;
if (empty($IPINFO_APIKEY)) {
return '';
}
return '?token='.$IPINFO_APIKEY;
}
/**
* @param string $ip
*
* @return array|null
*/
function getIspInfo($ip, $ipService)
{
$json = '';
if ($ipService == 'ip.sb') {
$json = file_get_contents('https://api.ip.sb/geoip/' . $ip);
} elseif ($ipService == 'ipinfo.io') {
$json = file_get_contents('https://ipinfo.io/'.$ip.'/json'.getIpInfoTokenString());
}
if (!is_string($json)) {
return null;
}
$data = json_decode($json, true);
if (!is_array($data)) {
return null;
}
return $data;
}
/**
* @param array|null $rawIspInfo
*
* @return string
*/
function getIsp($rawIspInfo, $ipService)
{
if ($ipService == 'ip.sb') {
if (
!is_array($rawIspInfo)
|| !array_key_exists('organization', $rawIspInfo)
|| !is_string($rawIspInfo['organization'])
|| empty($rawIspInfo['organization'])
) {
return 'Unknown';
}
return $rawIspInfo['organization'];
} elseif ($ipService == 'ipinfo.io') {
if (
!is_array($rawIspInfo)
|| !array_key_exists('org', $rawIspInfo)
|| !is_string($rawIspInfo['org'])
|| empty($rawIspInfo['org'])
) {
return 'Unknown';
}
return preg_replace('/AS\\d+\\s/', '', $rawIspInfo['org']);
}
return 'Unknown';
}
/**
* @return string|null
*/
function getServerLocation()
{
$serverLoc = null;
if (file_exists(SERVER_LOCATION_CACHE_FILE)) {
require SERVER_LOCATION_CACHE_FILE;
}
if (is_string($serverLoc) && !empty($serverLoc)) {
return $serverLoc;
}
$json = file_get_contents('https://ipinfo.io/json'.getIpInfoTokenString());
if (!is_string($json)) {
return null;
}
$details = json_decode($json, true);
if (
!is_array($details)
|| !array_key_exists('loc', $details)
|| !is_string($details['loc'])
|| empty($details['loc'])
) {
return null;
}
$serverLoc = $details['loc'];
$cacheData = "<?php\n\n\$serverLoc = '".addslashes($serverLoc)."';\n";
file_put_contents(SERVER_LOCATION_CACHE_FILE, $cacheData);
return $serverLoc;
}
/**
* Optimized algorithm from http://www.codexworld.com
*
* @param float $latitudeFrom
* @param float $longitudeFrom
* @param float $latitudeTo
* @param float $longitudeTo
*
* @return float [km]
*/
function distance(
$latitudeFrom,
$longitudeFrom,
$latitudeTo,
$longitudeTo
) {
$rad = M_PI / 180;
$theta = $longitudeFrom - $longitudeTo;
$dist = sin($latitudeFrom * $rad)
* sin($latitudeTo * $rad)
+ cos($latitudeFrom * $rad)
* cos($latitudeTo * $rad)
* cos($theta * $rad);
return acos($dist) / $rad * 60 * 1.853;
}
/**
* @param array|null $rawIspInfo
*
* @return string|null
*/
function getDistance($rawIspInfo)
{
if (
!is_array($rawIspInfo)
|| !array_key_exists('loc', $rawIspInfo)
|| !isset($_GET['distance'])
|| !in_array($_GET['distance'], ['mi', 'km'], true)
) {
return null;
}
$unit = $_GET['distance'];
$clientLocation = $rawIspInfo['loc'];
$serverLocation = getServerLocation();
if (!is_string($serverLocation)) {
return null;
}
return calculateDistance(
$serverLocation,
$clientLocation,
$unit
);
}
/**
* @param string $clientLocation
* @param string $serverLocation
* @param string $unit
*
* @return string
*/
function calculateDistance($clientLocation, $serverLocation, $unit)
{
list($clientLatitude, $clientLongitude) = explode(',', $clientLocation);
list($serverLatitude, $serverLongitude) = explode(',', $serverLocation);
$dist = distance(
$clientLatitude,
$clientLongitude,
$serverLatitude,
$serverLongitude
);
if ('mi' === $unit) {
$dist /= 1.609344;
$dist = round($dist, -1);
if ($dist < 15) {
$dist = '<15';
}
return $dist.' mi';
}
if ('km' === $unit) {
$dist = round($dist, -1);
if ($dist < 20) {
$dist = '<20';
}
return $dist.' km';
}
return null;
}
/**
* @return void
*/
function sendHeaders()
{
header('Content-Type: application/json; charset=utf-8');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
/**
* @param string $ip
* @param string|null $ipInfo
* @param string|null $distance
* @param array|null $rawIspInfo
*
* @return void
*/
function sendResponse(
$ip,
$ipInfo = null,
$rawIspInfo = null
) {
$processedString = $ip;
if (is_string($ipInfo)) {
$processedString .= ' - '.$ipInfo;
}
if (
is_array($rawIspInfo)
&& array_key_exists('country', $rawIspInfo)
) {
$processedString .= ' - '.$rawIspInfo['country'] . ',' . $rawIspInfo['region'] . ',' . $rawIspInfo['city'];
}
sendHeaders();
echo json_encode([
'processedString' => $processedString,
'rawIspInfo' => $rawIspInfo ?: '',
]);
}
$ip = getClientIp();
$localIpInfo = getLocalOrPrivateIpInfo($ip);
// local ip, no need to fetch further information
if (is_string($localIpInfo)) {
sendResponse($ip, $localIpInfo);
exit;
}
if (!isset($_GET['isp'])) {
sendResponse($ip);
exit;
}
$rawIspInfo = getIspInfo($ip, IP_SERVICE);
$isp = getIsp($rawIspInfo, IP_SERVICE);
//$distance = getDistance($rawIspInfo);
sendResponse($ip, $isp, $rawIspInfo);

View File

@ -0,0 +1,4 @@
<?php
// put your token between the quotes if you have one
$IPINFO_APIKEY = '';

View File

@ -0,0 +1,60 @@
<?php
require_once "./SleekDB/SleekDB.php";
require_once "./config.php";
function maskLastSegment($ip) {
$ipaddr = inet_pton($ip);
if (strlen($ipaddr) == 4) {
$ipaddr[3] = chr(0);
} elseif (strlen($ipaddr) == 16) {
$ipaddr[14] = chr(0);
$ipaddr[15] = chr(0);
} else {
return "";
}
return rtrim(inet_ntop($ipaddr),"0")."*";
}
$store = \SleekDB\SleekDB::store('speedlogs', './',[
'auto_cache' => false,
'timeout' => 120
]);
$reportData = [
"key" => sha1(filter_var($_POST['key'], FILTER_SANITIZE_STRING)),
"ip" => maskLastSegment(filter_var($_POST['ip'], FILTER_SANITIZE_STRING)),
"isp" => filter_var($_POST['isp'], FILTER_SANITIZE_STRING),
"addr" => filter_var($_POST['addr'], FILTER_SANITIZE_STRING),
"dspeed" => (double) filter_var($_POST['dspeed'], FILTER_SANITIZE_STRING),
"uspeed" => (double) filter_var($_POST['uspeed'], FILTER_SANITIZE_STRING),
"ping" => (double) filter_var($_POST['ping'], FILTER_SANITIZE_STRING),
"jitter" => (double) filter_var($_POST['jitter'], FILTER_SANITIZE_STRING),
"created" => date('Y-m-d H:i:s', time()),
];
if (empty($reportData['ip'])) exit;
if (SAME_IP_MULTI_LOGS) {
$oldLog = $store->where('key', '=', $reportData['key'])->fetch();
} else {
$oldLog = $store->where('ip', '=', $reportData['ip'])->orderBy( 'desc', '_id' )->fetch();
}
if (is_array($oldLog) && empty($oldLog)) {
$results = $store->insert($reportData);
if ($results['_id'] > MAX_LOG_COUNT) {
$store->where('_id', '=', $results['_id'] - MAX_LOG_COUNT)->delete();
}
} else {
$id = $oldLog[0]['_id'];
if (SAME_IP_MULTI_LOGS) {
$key = $reportData['key'];
unset($reportData['key']);
$store->where('_id', '=', $id)->update($reportData);
} else {
$ip = $reportData['ip'];
unset($reportData['ip']);
$store->where('_id', '=', $id)->update($reportData);
}
}

View File

@ -0,0 +1,21 @@
<?php
require_once "./SleekDB/SleekDB.php";
require_once "./config.php";
$store = \SleekDB\SleekDB::store('speedlogs', './',[
'auto_cache' => false,
'timeout' => 120
]);
$logs = $store
->orderBy( 'desc', 'created' )
->limit( MAX_LOG_COUNT )
->fetch();
$data = [
'code' => 0,
'data' => $logs,
];
echo json_encode($data);

188
speedtest-x/chart.html Normal file
View File

@ -0,0 +1,188 @@
<!doctype html>
<html>
<head>
<title>ISP Speed Chart</title>
<script src="chartjs/Chart.min.js"></script>
<script src="chartjs/utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
position: relative;
flex-grow: 1;
min-height: 0;
width: 100%;
height:100%;
}
div {
width:100%;
height:100%;
}
</style>
</head>
<body>
<div>
<canvas id="canvas"></canvas>
</div>
<script>
var color = Chart.helpers.color;
async function mainfunc() {
var color = Chart.helpers.color;
//console.log(color)
var datareq = await fetch('backend/results-api.php');
//console.log(datareq)
var dataraw = await datareq.text();
//console.log(dataraw)
try {
dataraw = JSON.parse(dataraw);
} catch {
alert("Can't get data");
return 0;
}
data_sorted = {};
for (const data of dataraw["data"]) {
let data_isp = data["isp"].split(" ").length > 1 ? data["isp"].split(" ")[0] + " " + data["isp"].split(" ")[1] : data["isp"];
if (data_isp in data_sorted) {
data_sorted[data_isp] = data_sorted[data_isp].concat([data])
} else {
data_sorted[data_isp] = [data]
}
}
let datasets = []
for (const isp of Object.keys(data_sorted)) {
let ispdata_chart = {
label: isp,
data: []
}
for (const ispdata of data_sorted[isp]) {
let [t_h, t_m, t_s] = ispdata["created"].split(" ")[1].split(":");
ispdata_chart["data"] = ispdata_chart["data"].concat([{
x: t_h * 1.0 + t_m / 60 + t_s / 3600,
y: ispdata["dspeed"],
label: ispdata
}]);
}
datasets = datasets.concat([ispdata_chart])
}
datasets = datasets.sort((a, b) => a["data"].length < b["data"].length ? 1 : -1);
for (const [i, data] of datasets.entries()) {
if (i === 0) {
datasets[i]["borderColor"] = window.chartColors["red"];
datasets[i]["backgroundColor"] = color(datasets[i]["borderColor"]).alpha(0.9).rgbString()
} else if (i === 1) {
datasets[i]["borderColor"] = "rgb(12, 176, 42)";
datasets[i]["backgroundColor"] = color(datasets[i]["borderColor"]).alpha(0.9).rgbString()
} else if (i === 2) {
datasets[i]["borderColor"] = "rgb(2, 104, 219)";
datasets[i]["backgroundColor"] = color(datasets[i]["borderColor"]).alpha(0.9).rgbString()
}
else{
datasets[i]["borderColor"] = window.chartColors["gray"];;
datasets[i]["backgroundColor"] = color(window.chartColors["gray"]).alpha(0.1).rgbString()
}
}
console.log(datasets);
scatterChartData = {
datasets: datasets
}
var ctx = document.getElementById('canvas').getContext('2d');
window.myScatter = Chart.Scatter(ctx, {
data: scatterChartData,
options: {
title: {
display: true,
text: 'ISP Speed Chart'
},
tooltips: {
mode: 'nearest',
callbacks: {
title: function(TooltipItem, data){
// console.log(TooltipItem);
// console.log(data);
// console.log(data["datasets"][TooltipItem[0]["datasetIndex"]]["label"])
return data["datasets"][TooltipItem[0]["datasetIndex"]]["label"]
},
label:function(TooltipItem, data){
return data["datasets"][TooltipItem["datasetIndex"]]["data"][TooltipItem["index"]]["label"]["isp"];
},
footer: function(TooltipItem, data){
// console.log(TooltipItem);
// console.log(data);
displaydata = data["datasets"][TooltipItem[0]["datasetIndex"]]["data"][TooltipItem[0]["index"]]["label"];
showdict = {
location: displaydata["addr"],
Download: displaydata["dspeed"],
Upload: displaydata["uspeed"],
Ping: displaydata["ping"],
Jitter: displaydata["jitter"],
IP: displaydata["ip"],
Time: displaydata["created"],
// ISP: displaydata["isp"],
};
let showtext = ""
for (const k of Object.keys(showdict)){
showtext += k + ": " + showdict[k] + "\n";
}
return showtext
},
},
footerFontStyle: 'normal'
},
scales: {
yAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
userCallback: function(tick) {
return tick.toString() + 'Mbps';
},
},
scaleLabel: {
labelString: 'Speed',
display: true,
}
}],
xAxes: [{
type: 'linear',
ticks: {
userCallback: function(tick) {
return tick.toString() + ':00';
},
beginAtZero: true,
stepSize: 3,
max: 24
},
scaleLabel: {
labelString: 'Time',
display: true
}
}]
},
responsive: true,
maintainAspectRatio: false
}
});
}
window.onload = function() {
mainfunc();
};
</script>
</body>
</html>

7
speedtest-x/chartjs/Chart.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,147 @@
'use strict';
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
(function(global) {
var MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
var COLORS = [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
'#166a8f',
'#00a950',
'#58595b',
'#8549ba'
];
var Samples = global.Samples || (global.Samples = {});
var Color = global.Color;
Samples.utils = {
// Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
srand: function(seed) {
this._seed = seed;
},
rand: function(min, max) {
var seed = this._seed;
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
this._seed = (seed * 9301 + 49297) % 233280;
return min + (this._seed / 233280) * (max - min);
},
numbers: function(config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 1;
var from = cfg.from || [];
var count = cfg.count || 8;
var decimals = cfg.decimals || 8;
var continuity = cfg.continuity || 1;
var dfactor = Math.pow(10, decimals) || 0;
var data = [];
var i, value;
for (i = 0; i < count; ++i) {
value = (from[i] || 0) + this.rand(min, max);
if (this.rand() <= continuity) {
data.push(Math.round(dfactor * value) / dfactor);
} else {
data.push(null);
}
}
return data;
},
labels: function(config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 100;
var count = cfg.count || 8;
var step = (max - min) / count;
var decimals = cfg.decimals || 8;
var dfactor = Math.pow(10, decimals) || 0;
var prefix = cfg.prefix || '';
var values = [];
var i;
for (i = min; i < max; i += step) {
values.push(prefix + Math.round(dfactor * i) / dfactor);
}
return values;
},
months: function(config) {
var cfg = config || {};
var count = cfg.count || 12;
var section = cfg.section;
var values = [];
var i, value;
for (i = 0; i < count; ++i) {
value = MONTHS[Math.ceil(i) % 12];
values.push(value.substring(0, section));
}
return values;
},
color: function(index) {
return COLORS[index % COLORS.length];
},
transparentize: function(color, opacity) {
var alpha = opacity === undefined ? 0.5 : 1 - opacity;
return Color(color).alpha(alpha).rgbString();
}
};
// DEPRECATED
window.randomScalingFactor = function() {
return Math.round(Samples.utils.rand(-100, 100));
};
// INITIALIZATION
Samples.utils.srand(Date.now());
// Google Analytics
/* eslint-disable */
if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-28909194-3', 'auto');
ga('send', 'pageview');
}
/* eslint-enable */
}(this));

View File

@ -0,0 +1,9 @@
version: "3"
services:
speedtest-x:
image: stilleshan/speedtest-x
container_name: speedtest-x
ports:
- 12345:80
restart: always

View File

@ -0,0 +1,41 @@
#!/bin/bash
set -e
set -x
# Cleanup
#rm -rf /var/www/html/*
# Copy frontend files
cp /speedtest/*.js /var/www/html/
cp /speedtest/*.html /var/www/html/
cp -r /speedtest/backend/ /var/www/html/backend
cp -r /speedtest/chartjs/ /var/www/html/chartjs
ln -snf /var/www/html/backend/speedlogs /speedlogs
chown -R www-data /var/www/html/*
# Allow selection of Apache port for network_mode: host
if [ "$WEBPORT" != "80" ]; then
sed -i "s/^Listen 80\$/Listen $WEBPORT/g" /etc/apache2/ports.conf
sed -i "s/*:80>/*:$WEBPORT>/g" /etc/apache2/sites-available/000-default.conf
fi
if [ "$MAX_LOG_COUNT" != "100" ]; then
sed -i "s/^const MAX_LOG_COUNT = 100/const MAX_LOG_COUNT = $MAX_LOG_COUNT/g" /var/www/html/backend/config.php
fi
if [ "$IP_SERVICE" != "ip.sb" ]; then
sed -i "s/^const IP_SERVICE = 'ip.sb'/const IP_SERVICE = '$IP_SERVICE'/g" /var/www/html/backend/config.php
fi
if [ "$SAME_IP_MULTI_LOGS" != "false" ]; then
sed -i "s/^const SAME_IP_MULTI_LOGS = false/const SAME_IP_MULTI_LOGS = $SAME_IP_MULTI_LOGS/g" /var/www/html/backend/config.php
fi
echo "Done, Starting APACHE"
# This runs apache
apache2-foreground

236
speedtest-x/index.html Normal file
View File

@ -0,0 +1,236 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no" />
<title>speedtest-x</title>
<link rel="shortcut icon" href="favicon.ico">
<script type="text/javascript" src="speedtest.js"></script>
<script type="text/javascript">
//INITIALIZE SPEEDTEST
var s=new Speedtest(); //create speedtest object
var xhr=new XMLHttpRequest();
var url_report='./backend/report.php';
var milestone=0;
var key_prefix=Date.parse(new Date());
s.onupdate=function(data){ //callback to update data in UI
I("ip").textContent=data.clientIp;
I("dlText").textContent=(data.testState==1&&data.dlStatus==0)?"...":data.dlStatus;
I("ulText").textContent=(data.testState==3&&data.ulStatus==0)?"...":data.ulStatus;
I("pingText").textContent=data.pingStatus;
I("jitText").textContent=data.jitterStatus;
var prog=(Number(data.dlProgress)*2+Number(data.ulProgress)*2+Number(data.pingProgress))/5;
I("progress").style.width=(100*prog)+"%";
var ipIspArr = I("ip").textContent.split(' - ', 3);
var ip = ipIspArr[0];
var isp = ipIspArr[1];
var addr = ipIspArr[2] === undefined? '' :ipIspArr[2];
var progress = Math.floor(100*prog);
var key = key_prefix + "_" + ip;
if (progress > 20 && (progress % 10 == 0) && progress != milestone) {
console.log(progress);
var params = 'key='+key+'&ip='+ip+'&isp='+isp+'&addr='+addr+'&dspeed='+I("dlText").textContent+'&uspeed='+I("ulText").textContent+'&ping='+I("pingText").textContent
+'&jitter='+I("jitText").textContent;
xhr.timeout = 3000;
xhr.ontimeout = function (e) {
console.log('上报超时');
};
xhr.open('POST', url_report, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
milestone = progress;
}
}
s.onend=function(aborted){ //callback for test ended/aborted
I("startStopBtn").className=""; //show start button again
if(aborted){ //if the test was aborted, clear the UI and prepare for new test
initUI();
}
}
function startStop(){ //start/stop button pressed
if(s.getState()==3){
//speedtest is running, abort
s.abort();
}else{
//test is not running, begin
s.start();
I("startStopBtn").className="running";
}
}
//function to (re)initialize UI
function initUI(){
I("dlText").textContent="";
I("ulText").textContent="";
I("pingText").textContent="";
I("jitText").textContent="";
I("ip").textContent="";
}
function I(id){return document.getElementById(id);}
</script>
<style type="text/css">
html,body{
border:none; padding:0; margin:0;
background:#FFFFFF;
color:#202020;
}
body{
text-align:center;
font-family:"Roboto",sans-serif;
}
h1{
color:#404040;
}
#startStopBtn{
display:inline-block;
margin:0 auto;
color:#6060AA;
background-color:rgba(0,0,0,0);
border:0.15em solid #6060FF;
border-radius:0.3em;
transition:all 0.3s;
box-sizing:border-box;
width:8em; height:3em;
line-height:2.7em;
cursor:pointer;
box-shadow: 0 0 0 rgba(0,0,0,0.1), inset 0 0 0 rgba(0,0,0,0.1);
}
#startStopBtn:hover{
box-shadow: 0 0 2em rgba(0,0,0,0.1), inset 0 0 1em rgba(0,0,0,0.1);
}
#startStopBtn.running{
background-color:#FF3030;
border-color:#FF6060;
color:#FFFFFF;
}
#startStopBtn:before{
content:"Start";
}
#startStopBtn.running:before{
content:"Abort";
}
#test{
margin-top:2em;
margin-bottom:12em;
}
div.testArea{
display:inline-block;
width:14em;
height:9em;
position:relative;
box-sizing:border-box;
}
div.testName{
position:absolute;
top:0.1em; left:0;
width:100%;
font-size:1.4em;
z-index:9;
}
div.meterText{
position:absolute;
bottom:1.5em; left:0;
width:100%;
font-size:2.5em;
z-index:9;
}
#dlText{
color:#6060AA;
}
#ulText{
color:#309030;
}
#pingText,#jitText{
color:#AA6060;
}
div.meterText:empty:before{
color:#505050 !important;
content:"0.00";
}
div.unit{
position:absolute;
bottom:2em; left:0;
width:100%;
z-index:9;
}
div.testGroup{
display:inline-block;
}
@media all and (max-width:65em){
body{
font-size:1.5vw;
}
}
@media all and (max-width:40em){
body{
font-size:0.8em;
}
div.testGroup{
display:block;
margin: 0 auto;
}
}
#progressBar{
width:90%;
height:0.3em;
background-color:#EEEEEE;
position:relative;
display:block;
margin:0 auto;
margin-bottom:2em;
}
#progress{
position:absolute;
top:0; left:0;
height:100%;
width:0%;
transition: width 2s;
background-color:#90BBFF;
}
</style>
</head>
<body>
<h1>Speedtest-X</h1>
<div id="startStopBtn" onclick="startStop()"></div>
<div id="test">
<div id="progressBar"><div id="progress"></div></div>
<div class="testGroup">
<div class="testArea">
<div class="testName">下载速度</div>
<div id="dlText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
<div class="testArea">
<div class="testName">上传速度</div>
<div id="ulText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
</div>
<div class="testGroup">
<div class="testArea">
<div class="testName">延迟</div>
<div id="pingText" class="meterText"></div>
<div class="unit">ms</div>
</div>
<div class="testArea">
<div class="testName">抖动</div>
<div id="jitText" class="meterText"></div>
<div class="unit">ms</div>
</div>
</div>
<div id="ipArea">
IP地址: <span id="ip"></span>
</div>
</div>
<p><a href="./results.html" target="_blank">查看测速记录</a></p>
<p><a href="https://github.com/BadApple9/speedtest-x" target="_blank">speedtest-x 项目地址</a></p>
<script type="text/javascript">
initUI();
</script>
</body>
</html>

59
speedtest-x/results.html Normal file
View File

@ -0,0 +1,59 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测速结果 | speedtest-x</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-src@2.5.7/dist/css/layui.css" media="all">
<style>
.footer {line-height: 30px; text-align: center;}
.footer a{padding:0 6px; font-weight: 300;}
.footer a:hover{color: green;}
.header {line-height: 30px; text-align: center;height:50px;padding-top:50px;margin-bottom: 10px;}
.header span>a {color:white;}
</style>
</head>
<body>
<div class="header">
<h1>speedtest-x 测速结果</h1>
<span class="layui-badge layui-bg-green"><a href="./chart.html" target="_blank">查看线性图表</a></span>
<a href="javascript:layer.tips('线性图表用于展示不同运营商在不同时段的速度表现程序默认保留100条测速结果可调大此数值以获得更准确的图表分析', '#tips', {
tips: [3, '#3595CC'],
time: 6000
});"><span id="tips" class="layui-badge layui-bg-black">?</span></a>
</div>
<table class="layui-hide" id="test"></table>
<div class="footer">
<a href="https://github.com/BadApple9/speedtest-x" target="_blank">speedtest-x 项目地址</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/layui-src@2.5.7/dist/layui.js" charset="utf-8"></script>
<script>
layui.use('table', function(){
var table = layui.table;
table.render({
elem: '#test'
,url:'./backend/results-api.php'
,cellMinWidth: 80
,cols: [[
{field:'ip', title: 'IP地址'}
,{field:'isp', title: '运营商'}
,{field:'addr', title: '城市'}
,{field:'dspeed', title: '下载速度 (Mbps)', sort: true, align: 'right'}
,{field:'uspeed', title: '上传速度 (Mbps)', sort: true, align: 'right'}
,{field:'ping', title: 'Ping (ms)', sort: true, align: 'right'}
,{field:'jitter', title: '抖动 (ms)', sort: true, align: 'right'}
,{field:'created', title: '测试时间', sort: true}
]]
});
});
</script>
</body>
</html>

382
speedtest-x/speedtest.js Normal file
View File

@ -0,0 +1,382 @@
/*
LibreSpeed - Main
by Federico Dossena
https://github.com/librespeed/speedtest/
GNU LGPLv3 License
*/
/*
This is the main interface between your webpage and the speedtest.
It hides the speedtest web worker to the page, and provides many convenient functions to control the test.
The best way to learn how to use this is to look at the basic example, but here's some documentation.
To initialize the test, create a new Speedtest object:
var s=new Speedtest();
Now you can think of this as a finite state machine. These are the states (use getState() to see them):
- 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.
- 1: here you can add test points. You only need to do this if you want to use multiple test points.
A server is defined as an object like this:
{
name: "User friendly name",
server:"http://yourBackend.com/", <---- URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
dlURL:"garbage.php" <----- path to garbage.php or its replacement on the server
ulURL:"empty.php" <----- path to empty.php or its replacement on the server
pingURL:"empty.php" <----- path to empty.php or its replacement on the server. This is used to ping the server by this selector
getIpURL:"getIP.php" <----- path to getIP.php or its replacement on the server
}
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.
- 2: test point selected, ready to start the test. Use start() to begin, this will move to state 3
- 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:
- dlStatus: download speed in mbps
- ulStatus: upload speed in mbps
- pingStatus: ping in ms
- jitterStatus: jitter in ms
- dlProgress: progress of the download test as a float 0-1
- ulProgress: progress of the upload test as a float 0-1
- pingProgress: progress of the ping/jitter test as a float 0-1
- testState: state of the test (-1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=aborted)
- clientIp: IP address of the client performing the test (and optionally ISP and distance)
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.
The test can be aborted at any time with abort().
At the end of the test, it will move to state 4
- 4: test finished. You can run it again by calling start() if you want.
*/
function Speedtest() {
this._serverList = []; //when using multiple points of test, this is a list of test points
this._selectedServer = null; //when using multiple points of test, this is the selected server
this._settings = {}; //settings for the speedtest worker
this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
console.log(
"LibreSpeed by Federico Dossena v5.2.2 - https://github.com/librespeed/speedtest"
);
console.log(
"speedtest-x - https://github.com/BadApple9/speedtest-x"
);
}
Speedtest.prototype = {
constructor: Speedtest,
/**
* Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
*/
getState: function() {
return this._state;
},
/**
* Change one of the test settings from their defaults.
* - parameter: string with the name of the parameter that you want to set
* - value: new value for the parameter
*
* Invalid values or nonexistant parameters will be ignored by the speedtest worker.
*/
setParameter: function(parameter, value) {
if (this._state != 0)
throw "You cannot change the test settings after adding server or starting the test";
this._settings[parameter] = value;
if(parameter === "telemetry_extra"){
this._originalExtra=this._settings.telemetry_extra;
}
},
/**
* Used internally to check if a server object contains all the required elements.
* Also fixes the server URL if needed.
*/
_checkServerDefinition: function(server) {
try {
if (typeof server.name !== "string")
throw "Name string missing from server definition (name)";
if (typeof server.server !== "string")
throw "Server address string missing from server definition (server)";
if (server.server.charAt(server.server.length - 1) != "/")
server.server += "/";
if (server.server.indexOf("//") == 0)
server.server = location.protocol + server.server;
if (typeof server.dlURL !== "string")
throw "Download URL string missing from server definition (dlURL)";
if (typeof server.ulURL !== "string")
throw "Upload URL string missing from server definition (ulURL)";
if (typeof server.pingURL !== "string")
throw "Ping URL string missing from server definition (pingURL)";
if (typeof server.getIpURL !== "string")
throw "GetIP URL string missing from server definition (getIpURL)";
} catch (e) {
throw "Invalid server definition";
}
},
/**
* Add a test point (multiple points of test)
* server: the server to be added as an object. Must contain the following elements:
* {
* name: "User friendly name",
* server:"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
* dlURL:"garbage.php" path to garbage.php or its replacement on the server
* ulURL:"empty.php" path to empty.php or its replacement on the server
* pingURL:"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
* getIpURL:"getIP.php" path to getIP.php or its replacement on the server
* }
*/
addTestPoint: function(server) {
this._checkServerDefinition(server);
if (this._state == 0) this._state = 1;
if (this._state != 1) throw "You can't add a server after server selection";
this._settings.mpot = true;
this._serverList.push(server);
},
/**
* Same as addTestPoint, but you can pass an array of servers
*/
addTestPoints: function(list) {
for (var i = 0; i < list.length; i++) this.addTestPoint(list[i]);
},
/**
* Load a JSON server list from URL (multiple points of test)
* url: the url where the server list can be fetched. Must be an array with objects containing the following elements:
* {
* "name": "User friendly name",
* "server":"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
* "dlURL":"garbage.php" path to garbage.php or its replacement on the server
* "ulURL":"empty.php" path to empty.php or its replacement on the server
* "pingURL":"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
* "getIpURL":"getIP.php" path to getIP.php or its replacement on the server
* }
* 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
*/
loadServerList: function(url,result) {
if (this._state == 0) this._state = 1;
if (this._state != 1) throw "You can't add a server after server selection";
this._settings.mpot = true;
var xhr = new XMLHttpRequest();
xhr.onload = function(){
try{
var servers=JSON.parse(xhr.responseText);
for(var i=0;i<servers.length;i++){
this._checkServerDefinition(servers[i]);
}
this.addTestPoints(servers);
result(servers);
}catch(e){
result(null);
}
}.bind(this);
xhr.onerror = function(){result(null);}
xhr.open("GET",url);
xhr.send();
},
/**
* Returns the selected server (multiple points of test)
*/
getSelectedServer: function() {
if (this._state < 2 || this._selectedServer == null)
throw "No server is selected";
return this._selectedServer;
},
/**
* Manually selects one of the test points (multiple points of test)
*/
setSelectedServer: function(server) {
this._checkServerDefinition(server);
if (this._state == 3)
throw "You can't select a server while the test is running";
this._selectedServer = server;
this._state = 2;
},
/**
* Automatically selects a server from the list of added test points. The server with the lowest ping will be chosen. (multiple points of test)
* The process is asynchronous and the passed result callback function will be called when it's done, then the test can be started.
*/
selectServer: function(result) {
if (this._state != 1) {
if (this._state == 0) throw "No test points added";
if (this._state == 2) throw "Server already selected";
if (this._state >= 3)
throw "You can't select a server while the test is running";
}
if (this._selectServerCalled) throw "selectServer already called"; else this._selectServerCalled=true;
/*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.
*/
var select = function(serverList, result) {
//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.
var PING_TIMEOUT = 2000;
var USE_PING_TIMEOUT = true; //will be disabled on unsupported browsers
if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) {
//IE11 doesn't support XHR timeout
USE_PING_TIMEOUT = false;
}
var ping = function(url, result) {
url += (url.match(/\?/) ? "&" : "?") + "cors=true";
var xhr = new XMLHttpRequest();
var t = new Date().getTime();
xhr.onload = function() {
if (xhr.responseText.length == 0) {
//we expect an empty response
var instspd = new Date().getTime() - t; //rough timing estimate
try {
//try to get more accurate timing using performance API
var p = performance.getEntriesByName(url);
p = p[p.length - 1];
var d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d;
} catch (e) {}
result(instspd);
} else result(-1);
}.bind(this);
xhr.onerror = function() {
result(-1);
}.bind(this);
xhr.open("GET", url);
if (USE_PING_TIMEOUT) {
try {
xhr.timeout = PING_TIMEOUT;
xhr.ontimeout = xhr.onerror;
} catch (e) {}
}
xhr.send();
}.bind(this);
//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.
var PINGS = 3, //up to 3 pings are performed, unless the server is down...
SLOW_THRESHOLD = 500; //...or one of the pings is above this threshold
var checkServer = function(server, done) {
var i = 0;
server.pingT = -1;
if (server.server.indexOf(location.protocol) == -1) done();
else {
var nextPing = function() {
if (i++ == PINGS) {
done();
return;
}
ping(
server.server + server.pingURL,
function(t) {
if (t >= 0) {
if (t < server.pingT || server.pingT == -1) server.pingT = t;
if (t < SLOW_THRESHOLD) nextPing();
else done();
} else done();
}.bind(this)
);
}.bind(this);
nextPing();
}
}.bind(this);
//check servers in list, one by one
var i = 0;
var done = function() {
var bestServer = null;
for (var i = 0; i < serverList.length; i++) {
if (
serverList[i].pingT != -1 &&
(bestServer == null || serverList[i].pingT < bestServer.pingT)
)
bestServer = serverList[i];
}
result(bestServer);
}.bind(this);
var nextServer = function() {
if (i == serverList.length) {
done();
return;
}
checkServer(serverList[i++], nextServer);
}.bind(this);
nextServer();
}.bind(this);
//parallel server selection
var CONCURRENCY = 6;
var serverLists = [];
for (var i = 0; i < CONCURRENCY; i++) {
serverLists[i] = [];
}
for (var i = 0; i < this._serverList.length; i++) {
serverLists[i % CONCURRENCY].push(this._serverList[i]);
}
var completed = 0;
var bestServer = null;
for (var i = 0; i < CONCURRENCY; i++) {
select(
serverLists[i],
function(server) {
if (server != null) {
if (bestServer == null || server.pingT < bestServer.pingT)
bestServer = server;
}
completed++;
if (completed == CONCURRENCY) {
this._selectedServer = bestServer;
this._state = 2;
if (result) result(bestServer);
}
}.bind(this)
);
}
},
/**
* Starts the test.
* During the test, the onupdate(data) callback function will be called periodically with data from the worker.
* 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.
*/
start: function() {
if (this._state == 3) throw "Test already running";
this.worker = new Worker("speedtest_worker.js?r=" + Math.random());
this.worker.onmessage = function(e) {
if (e.data === this._prevData) return;
else this._prevData = e.data;
var data = JSON.parse(e.data);
try {
if (this.onupdate) this.onupdate(data);
} catch (e) {
console.error("Speedtest onupdate event threw exception: " + e);
}
if (data.testState >= 4) {
clearInterval(this.updater);
this._state = 4;
try {
if (this.onend) this.onend(data.testState == 5);
} catch (e) {
console.error("Speedtest onend event threw exception: " + e);
}
}
}.bind(this);
this.updater = setInterval(
function() {
this.worker.postMessage("status");
}.bind(this),
200
);
if (this._state == 1)
throw "When using multiple points of test, you must call selectServer before starting the test";
if (this._state == 2) {
this._settings.url_dl =
this._selectedServer.server + this._selectedServer.dlURL;
this._settings.url_ul =
this._selectedServer.server + this._selectedServer.ulURL;
this._settings.url_ping =
this._selectedServer.server + this._selectedServer.pingURL;
this._settings.url_getIp =
this._selectedServer.server + this._selectedServer.getIpURL;
if (typeof this._originalExtra !== "undefined") {
this._settings.telemetry_extra = JSON.stringify({
server: this._selectedServer.name,
extra: this._originalExtra
});
} else
this._settings.telemetry_extra = JSON.stringify({
server: this._selectedServer.name
});
}
this._state = 3;
this.worker.postMessage("start " + JSON.stringify(this._settings));
},
/**
* Aborts the test while it's running.
*/
abort: function() {
if (this._state < 3) throw "You cannot abort a test that's not started yet";
if (this._state < 4) this.worker.postMessage("abort");
}
};

View File

@ -0,0 +1,723 @@
/*
LibreSpeed - Worker
by Federico Dossena
https://github.com/librespeed/speedtest/
GNU LGPLv3 License
*/
// data reported to main thread
var testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
var dlStatus = ""; // download speed in megabit/s with 2 decimal digits
var ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
var pingStatus = ""; // ping in milliseconds with 2 decimal digits
var jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
var clientIp = ""; // client's IP address as reported by getIP.php
var dlProgress = 0; //progress of download test 0-1
var ulProgress = 0; //progress of upload test 0-1
var pingProgress = 0; //progress of ping+jitter test 0-1
var testId = null; //test ID (sent back by telemetry if used, null otherwise)
var log = ""; //telemetry log
function tlog(s) {
if (settings.telemetry_level >= 2) {
log += Date.now() + ": " + s + "\n";
}
}
function tverb(s) {
if (settings.telemetry_level >= 3) {
log += Date.now() + ": " + s + "\n";
}
}
function twarn(s) {
if (settings.telemetry_level >= 2) {
log += Date.now() + " WARN: " + s + "\n";
}
console.warn(s);
}
// test settings. can be overridden by sending specific values with the start command
var settings = {
mpot: false, //set to true when in MPOT mode
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
time_ul_max: 15, // max duration of upload test in seconds
time_dl_max: 15, // max duration of download test in seconds
time_auto: true, // if set to true, tests will take less time on faster connections
time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
count_ping: 10, // number of pings to perform in ping test
url_dl: "backend/garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
url_ul: "backend/empty.php", // path to an empty file, used for upload test. must be relative to this js file
url_ping: "backend/empty.php", // path to an empty file, used for ping test. must be relative to this js file
url_getIp: "backend/getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
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
xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
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)
xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
garbagePhp_chunkSize: 50, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
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
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.
overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
url_telemetry: "results/telemetry.php", // path to the script that adds telemetry data to the database
telemetry_extra: "" //extra data that can be passed to the telemetry through the settings
};
var xhr = null; // array of currently active xhr requests
var interval = null; // timer used in tests
var test_pointer = 0; //pointer to the next test to run inside settings.test_order
/*
this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
*/
function url_sep(url) {
return url.match(/\?/) ? "&" : "?";
}
/*
listener for commands from main thread to this worker.
commands:
-status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
-abort: aborts the current test
-start: starts the test. optionally, settings can be passed as JSON.
example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
*/
this.addEventListener("message", function(e) {
var params = e.data.split(" ");
if (params[0] === "status") {
// return status
postMessage(
JSON.stringify({
testState: testState,
dlStatus: dlStatus,
ulStatus: ulStatus,
pingStatus: pingStatus,
clientIp: clientIp,
jitterStatus: jitterStatus,
dlProgress: dlProgress,
ulProgress: ulProgress,
pingProgress: pingProgress,
testId: testId
})
);
}
if (params[0] === "start" && testState === -1) {
// start new test
testState = 0;
try {
// parse settings, if present
var s = {};
try {
var ss = e.data.substring(5);
if (ss) s = JSON.parse(ss);
} catch (e) {
twarn("Error parsing custom settings JSON. Please check your syntax");
}
//copy custom settings
for (var key in s) {
if (typeof settings[key] !== "undefined") settings[key] = s[key];
else twarn("Unknown setting ignored: " + key);
}
var ua = navigator.userAgent;
// quirks for specific browsers. apply only if not overridden. more may be added in future releases
if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
if (/Firefox.(\d+\.\d+)/i.test(ua)) {
if (typeof s.ping_allowPerformanceApi === "undefined") {
// ff performance API sucks
settings.ping_allowPerformanceApi = false;
}
}
if (/Edge.(\d+\.\d+)/i.test(ua)) {
if (typeof s.xhr_dlMultistream === "undefined") {
// edge more precise with 3 download streams
settings.xhr_dlMultistream = 3;
}
}
if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
if (typeof s.xhr_dlMultistream === "undefined") {
// chrome more precise with 5 streams
settings.xhr_dlMultistream = 5;
}
}
}
if (/Edge.(\d+\.\d+)/i.test(ua)) {
//Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
settings.forceIE11Workaround = true;
}
if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
//PS4 browser has the same bug as IE11/Edge
settings.forceIE11Workaround = true;
}
if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
//cheap af
//Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
settings.xhr_ul_blob_megabytes = 4;
}
if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
//Safari also needs the IE11 workaround but only for the MPOT version
settings.forceIE11Workaround = true;
}
//telemetry_level has to be parsed and not just copied
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
//transform test_order to uppercase, just in case
settings.test_order = settings.test_order.toUpperCase();
} catch (e) {
twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
}
// run the tests
tverb(JSON.stringify(settings));
test_pointer = 0;
var iRun = false,
dRun = false,
uRun = false,
pRun = false;
var runNextTest = function() {
if (testState == 5) return;
if (test_pointer >= settings.test_order.length) {
//test is finished
if (settings.telemetry_level > 0)
sendTelemetry(function(id) {
testState = 4;
if (id != null) testId = id;
});
else testState = 4;
return;
}
switch (settings.test_order.charAt(test_pointer)) {
case "I":
{
test_pointer++;
if (iRun) {
runNextTest();
return;
} else iRun = true;
getIp(runNextTest);
}
break;
case "D":
{
test_pointer++;
if (dRun) {
runNextTest();
return;
} else dRun = true;
testState = 1;
dlTest(runNextTest);
}
break;
case "U":
{
test_pointer++;
if (uRun) {
runNextTest();
return;
} else uRun = true;
testState = 3;
ulTest(runNextTest);
}
break;
case "P":
{
test_pointer++;
if (pRun) {
runNextTest();
return;
} else pRun = true;
testState = 2;
pingTest(runNextTest);
}
break;
case "_":
{
test_pointer++;
setTimeout(runNextTest, 1000);
}
break;
default:
test_pointer++;
}
};
runNextTest();
}
if (params[0] === "abort") {
// abort command
if (testState >= 4) return;
tlog("manually aborted");
clearRequests(); // stop all xhr activity
runNextTest = null;
if (interval) clearInterval(interval); // clear timer if present
if (settings.telemetry_level > 1) sendTelemetry(function() {});
testState = 5; //set test as aborted
dlStatus = "";
ulStatus = "";
pingStatus = "";
jitterStatus = "";
clientIp = "";
dlProgress = 0;
ulProgress = 0;
pingProgress = 0;
}
});
// stops all XHR activity, aggressively
function clearRequests() {
tverb("stopping pending XHRs");
if (xhr) {
for (var i = 0; i < xhr.length; i++) {
try {
xhr[i].onprogress = null;
xhr[i].onload = null;
xhr[i].onerror = null;
} catch (e) {}
try {
xhr[i].upload.onprogress = null;
xhr[i].upload.onload = null;
xhr[i].upload.onerror = null;
} catch (e) {}
try {
xhr[i].abort();
} catch (e) {}
try {
delete xhr[i];
} catch (e) {}
}
xhr = null;
}
}
// gets client's IP using url_getIp, then calls the done function
var ipCalled = false; // used to prevent multiple accidental calls to getIp
var ispInfo = ""; //used for telemetry
function getIp(done) {
tverb("getIp");
if (ipCalled) return;
else ipCalled = true; // getIp already called?
var startT = new Date().getTime();
xhr = new XMLHttpRequest();
xhr.onload = function() {
tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
try {
var data = JSON.parse(xhr.responseText);
clientIp = data.processedString;
ispInfo = data.rawIspInfo;
} catch (e) {
clientIp = xhr.responseText;
ispInfo = "";
}
done();
};
xhr.onerror = function() {
tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
done();
};
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);
xhr.send();
}
// download test, calls done function when it's over
var dlCalled = false; // used to prevent multiple accidental calls to dlTest
function dlTest(done) {
tverb("dlTest");
if (dlCalled) return;
else dlCalled = true; // dlTest already called?
var totLoaded = 0.0, // total number of loaded bytes
startT = new Date().getTime(), // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past
failed = false; // set to true if a stream fails
xhr = [];
// function to create a download stream. streams are slightly delayed so that they will not end at the same time
var testStream = function(i, delay) {
setTimeout(
function() {
if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
tverb("dl test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes loaded last time onprogress was called
var x = new XMLHttpRequest();
xhr[i] = x;
xhr[i].onprogress = function(event) {
tverb("dl stream progress event " + i + " " + event.loaded);
if (testState !== 1) {
try {
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the download test
// progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff;
prevLoaded = event.loaded;
}.bind(this);
xhr[i].onload = function() {
// the large file has been loaded entirely, start again
tverb("dl stream finished " + i);
try {
xhr[i].abort();
} catch (e) {} // reset the stream data to empty ram
testStream(i, 0);
}.bind(this);
xhr[i].onerror = function() {
// error
tverb("dl stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
try {
xhr[i].abort();
} catch (e) {}
delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
}.bind(this);
// send xhr
try {
if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
else xhr[i].responseType = "arraybuffer";
} catch (e) {}
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
xhr[i].send();
}.bind(this),
1 + delay
);
}.bind(this);
// open streams
for (var i = 0; i < settings.xhr_dlMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i);
}
// every 200ms, update dlStatus
interval = setInterval(
function() {
tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT;
if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
if (t < 200) return;
if (!graceTimeDone) {
if (t > 1000 * settings.time_dlGraceTime) {
if (totLoaded > 0) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date().getTime();
bonusT = 0;
totLoaded = 0.0;
}
graceTimeDone = true;
}
} else {
var speed = totLoaded / (t / 1000.0);
if (settings.time_auto) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (5.0 * speed) / 100000;
bonusT += bonus > 400 ? 400 : bonus;
}
//update status
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
if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
// test is over, stop streams and timer
if (failed || isNaN(dlStatus)) dlStatus = "Fail";
clearRequests();
clearInterval(interval);
dlProgress = 1;
tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this),
200
);
}
// upload test, calls done function whent it's over
var ulCalled = false; // used to prevent multiple accidental calls to ulTest
function ulTest(done) {
tverb("ulTest");
if (ulCalled) return;
else ulCalled = true; // ulTest already called?
// garbage data for upload test
var r = new ArrayBuffer(1048576);
var maxInt = Math.pow(2, 32) - 1;
try {
r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
} catch (e) {}
var req = [];
var reqsmall = [];
for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
req = new Blob(req);
r = new ArrayBuffer(262144);
try {
r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
} catch (e) {}
reqsmall.push(r);
reqsmall = new Blob(reqsmall);
var testFunction = function() {
var totLoaded = 0.0, // total number of transmitted bytes
startT = new Date().getTime(), // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past
failed = false; // set to true if a stream fails
xhr = [];
// function to create an upload stream. streams are slightly delayed so that they will not end at the same time
var testStream = function(i, delay) {
setTimeout(
function() {
if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
tverb("ul test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
var x = new XMLHttpRequest();
xhr[i] = x;
var ie11workaround;
if (settings.forceIE11Workaround) ie11workaround = true;
else {
try {
xhr[i].upload.onprogress;
ie11workaround = false;
} catch (e) {
ie11workaround = true;
}
}
if (ie11workaround) {
// 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
xhr[i].onload = xhr[i].onerror = function() {
tverb("ul stream progress event (ie11wa)");
totLoaded += reqsmall.size;
testStream(i, 0);
};
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
try {
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch (e) {}
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr[i].send(reqsmall);
} else {
// REGULAR version, no workaround
xhr[i].upload.onprogress = function(event) {
tverb("ul stream progress event " + i + " " + event.loaded);
if (testState !== 3) {
try {
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the upload test
// progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff;
prevLoaded = event.loaded;
}.bind(this);
xhr[i].upload.onload = function() {
// this stream sent all the garbage data, start again
tverb("ul stream finished " + i);
testStream(i, 0);
}.bind(this);
xhr[i].upload.onerror = function() {
tverb("ul stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
try {
xhr[i].abort();
} catch (e) {}
delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
}.bind(this);
// send xhr
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
try {
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch (e) {}
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr[i].send(req);
}
}.bind(this),
delay
);
}.bind(this);
// open streams
for (var i = 0; i < settings.xhr_ulMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i);
}
// every 200ms, update ulStatus
interval = setInterval(
function() {
tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT;
if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
if (t < 200) return;
if (!graceTimeDone) {
if (t > 1000 * settings.time_ulGraceTime) {
if (totLoaded > 0) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date().getTime();
bonusT = 0;
totLoaded = 0.0;
}
graceTimeDone = true;
}
} else {
var speed = totLoaded / (t / 1000.0);
if (settings.time_auto) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (5.0 * speed) / 100000;
bonusT += bonus > 400 ? 400 : bonus;
}
//update status
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
if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
// test is over, stop streams and timer
if (failed || isNaN(ulStatus)) ulStatus = "Fail";
clearRequests();
clearInterval(interval);
ulProgress = 1;
tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this),
200
);
}.bind(this);
if (settings.mpot) {
tverb("Sending POST request before performing upload test");
xhr = [];
xhr[0] = new XMLHttpRequest();
xhr[0].onload = xhr[0].onerror = function() {
tverb("POST request sent, starting upload test");
testFunction();
}.bind(this);
xhr[0].open("POST", settings.url_ul);
xhr[0].send();
} else testFunction();
}
// ping+jitter test, function done is called when it's over
var ptCalled = false; // used to prevent multiple accidental calls to pingTest
function pingTest(done) {
tverb("pingTest");
if (ptCalled) return;
else ptCalled = true; // pingTest already called?
var startT = new Date().getTime(); //when the test was started
var prevT = null; // last time a pong was received
var ping = 0.0; // current ping value
var jitter = 0.0; // current jitter value
var i = 0; // counter of pongs received
var prevInstspd = 0; // last ping time, used for jitter calculation
xhr = [];
// ping function
var doPing = function() {
tverb("ping");
pingProgress = i / settings.count_ping;
prevT = new Date().getTime();
xhr[0] = new XMLHttpRequest();
xhr[0].onload = function() {
// pong
tverb("pong");
if (i === 0) {
prevT = new Date().getTime(); // first pong
} else {
var instspd = new Date().getTime() - prevT;
if (settings.ping_allowPerformanceApi) {
try {
//try to get accurate performance timing using performance api
var p = performance.getEntries();
p = p[p.length - 1];
var d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d;
} catch (e) {
//if not possible, keep the estimate
tverb("Performance API not supported, using estimate");
}
}
//noticed that some browsers randomly have 0ms ping
if (instspd < 1) instspd = prevInstspd;
if (instspd < 1) instspd = 1;
var instjitter = Math.abs(instspd - prevInstspd);
if (i === 1) ping = instspd;
/* first ping, can't tell jitter yet*/ else {
if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
if (i === 2) jitter = instjitter;
//discard the first jitter measurement because it might be much higher than it should be
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.
}
prevInstspd = instspd;
}
pingStatus = ping.toFixed(2);
jitterStatus = jitter.toFixed(2);
i++;
tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
if (i < settings.count_ping) doPing();
else {
// more pings to do?
pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}.bind(this);
xhr[0].onerror = function() {
// a ping failed, cancel test
tverb("ping failed");
if (settings.xhr_ignoreErrors === 0) {
//abort
pingStatus = "Fail";
jitterStatus = "Fail";
clearRequests();
tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
pingProgress = 1;
done();
}
if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
if (settings.xhr_ignoreErrors === 2) {
//ignore failed ping
i++;
if (i < settings.count_ping) doPing();
else {
// more pings to do?
pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this);
// send xhr
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
xhr[0].send();
}.bind(this);
doPing(); // start first ping
}
// telemetry
function sendTelemetry(done) {
if (settings.telemetry_level < 1) return;
xhr = new XMLHttpRequest();
xhr.onload = function() {
try {
var parts = xhr.responseText.split(" ");
if (parts[0] == "id") {
try {
var id = parts[1];
done(id);
} catch (e) {
done(null);
}
} else done(null);
} catch (e) {
done(null);
}
};
xhr.onerror = function() {
console.log("TELEMETRY ERROR " + xhr.status);
done(null);
};
xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
var telemetryIspInfo = {
processedString: clientIp,
rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
};
try {
var fd = new FormData();
fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
fd.append("dl", dlStatus);
fd.append("ul", ulStatus);
fd.append("ping", pingStatus);
fd.append("jitter", jitterStatus);
fd.append("log", settings.telemetry_level > 1 ? log : "");
fd.append("extra", settings.telemetry_extra);
xhr.send(fd);
} catch (ex) {
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 : "");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postData);
}
}