mirror of https://github.com/vitalif/phantomjs
Remove PyPhantomJS.
Since there is no future maintainer, the code should not be there anymore. http://code.google.com/p/phantomjs/issues/detail?id=3441.5
parent
1770a4fd33
commit
f6c29b16c1
|
@ -15,7 +15,5 @@ debian/files
|
|||
debian/*.log
|
||||
debian/*.substvars
|
||||
debian/*/
|
||||
python/build/
|
||||
python/*.egg-info/
|
||||
/deploy/qt-*.tar.gz
|
||||
/deploy/Qt-*
|
||||
|
|
|
@ -26,7 +26,7 @@ which show various PhantomJS scripts, covering:
|
|||
|
||||
Do not forget to consult the concise [API Reference](http://code.google.com/p/phantomjs/wiki/Interface).
|
||||
|
||||
PhantomJS is based on [Qt](http://qt.nokia.com). There are two implementations, using C++ and Python.
|
||||
PhantomJS is based on [Qt](http://qt.nokia.com).
|
||||
|
||||
The latest [stable release](http://code.google.com/p/phantomjs/wiki/ReleaseNotes) is version 1.4 ("Glory of the Snow").
|
||||
|
||||
|
|
|
@ -1,8 +0,0 @@
|
|||
Core Developers:
|
||||
|
||||
James Roe <roejames12@hotmail.com>
|
||||
|
||||
|
||||
Contributors:
|
||||
|
||||
Francisco Souza
|
|
@ -1,34 +0,0 @@
|
|||
### DEPENDENCIES
|
||||
---------------------------------
|
||||
|
||||
* Python >= 2.6 (< 3.x)
|
||||
* PyQt4 >= 4.8.0
|
||||
* Qt >= 4.7.0
|
||||
|
||||
* python-argparse >= 1.2.1 (Python 2.6 only)
|
||||
* PIL (python-imaging-library) >= 1.1.7 (optional; for rendering to GIF)
|
||||
|
||||
### INSTALLING
|
||||
-------------------------
|
||||
|
||||
Windows
|
||||
|
||||
> Download and install the required programs.
|
||||
>
|
||||
[Python](http://www.python.org/download/)
|
||||
[PyQt4](http://www.riverbankcomputing.co.uk/software/pyqt/download)
|
||||
> Qt4 - PyQt4 comes packaged with the Qt runtime library(s)
|
||||
>
|
||||
[python-argparse](http://pypi.python.org/pypi/argparse/)
|
||||
[PIL](http://www.pythonware.com/products/pil/)
|
||||
|
||||
Ubuntu
|
||||
|
||||
> Open a terminal window, and enter the command `sudo apt-get install python-qt4 python-imaging`
|
||||
>
|
||||
All the required packages should be automatically pulled in and installed.
|
||||
|
||||
PyPi
|
||||
|
||||
> You can also install the latest stable release from PyPi with `pip install pyphantomjs`
|
||||
Afterward, you can invoke the program with `pyphantomjs`
|
674
python/LICENSE
674
python/LICENSE
|
@ -1,674 +0,0 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, 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
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If 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 convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state 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 program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -1,2 +0,0 @@
|
|||
include *
|
||||
exclude *.swp
|
|
@ -1,58 +0,0 @@
|
|||
PyPhantomJS is a headless WebKit with JavaScript API, based on the [PhantomJS](http://www.phantomjs.org/) project.
|
||||
|
||||
It has **fast** and **native** support for DOM handling, CSS selector, JSON, Canvas, SVG, and of course JavaScript.
|
||||
|
||||
PyPhantomJS scripts can be written in JavaScript or [CoffeeScript](http://jashkenas.github.com/coffee-script/).
|
||||
|
||||
See the [quick start guide](http://code.google.com/p/phantomjs/wiki/QuickStart) and more [advanced examples](http://code.google.com/p/phantomjs/wiki/ServiceIntegration) which show various PhantomJS scripts, covering:
|
||||
|
||||
* running regression tests from command line
|
||||
* getting driving direction
|
||||
* showing weather forecast conditions
|
||||
* finding pizza in New York
|
||||
* looking up approximate location based on IP address
|
||||
* pulling the list of seasonal food
|
||||
* producing PDF version of a Wikipedia article
|
||||
* rasterizing SVG to image
|
||||
|
||||
PyPhantomJS is written in PyQt4 and Python. It runs on Linux, Windows, and Mac OS X.
|
||||
Refer to the INSTALL file or Wiki links<sup>1</sup> for more information.
|
||||
|
||||
Do not forget to consult the concise API Reference<sup>2</sup>
|
||||
|
||||
If you want to contribute, please read the Contribution Guides<sup>3</sup>
|
||||
|
||||
You can find a list of downloadable plugins [here](http://dev.umaclan.com/projects/pyphantomjs/wiki/Plugins).
|
||||
|
||||
If you would like to know how to make plugins, check out this [article](http://dev.umaclan.com/projects/pyphantomjs/wiki/Writing_plugins).
|
||||
|
||||
1: http://code.google.com/p/phantomjs/w/list
|
||||
1: http://dev.umaclan.com/projects/pyphantomjs/wiki
|
||||
2: http://dev.umaclan.com/projects/pyphantomjs/wiki/Api_reference
|
||||
2: http://code.google.com/p/phantomjs/wiki/Interface
|
||||
3: http://code.google.com/p/phantomjs/wiki/ContributionGuide
|
||||
3: http://dev.umaclan.com/projects/pyphantomjs/wiki/Giving_back
|
||||
|
||||
LICENSING
|
||||
------------------
|
||||
Copyright (C) 2011 James Roe <<roejames12@hotmail.com>>
|
||||
Copyright (C) 2011 PyPhantomJS authors (see AUTHORS file)
|
||||
|
||||
PyPhantomJS is licensed with the GNU GPL v3.
|
||||
See the included file LICENSE for the licensing terms.
|
||||
|
||||
ADDITIONAL INFO
|
||||
-----------------------------
|
||||
This program is a port of PhantomJS to Python/PyQt4 (thus, PyPhantomJS).
|
||||
|
||||
1. We try to make PyPhantomJS to be as compatible with PhantomJS as possible,
|
||||
this means having the exact same features as they do. It happens to be fully
|
||||
compatible, with the exception of some very small things.
|
||||
2. PyPhantomJS however, has a few differences as well:
|
||||
* Some of the features work a little differently than PhantomJS.
|
||||
In most of these cases, the features were only changed to improve their
|
||||
reliability and performance, so they work more often/better, and break less.
|
||||
* There may also be additional features present that aren't in PhantomJS.
|
||||
|
||||
PhantomJS was written by Ariya Hidayat, and I'd like to give him a BIG thanks
|
||||
for all his work on PhantomJS! :)
|
|
@ -1,22 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
__version_info__ = (1, 5, 0)
|
||||
|
||||
__version__ = '.'.join(map(str, __version_info__))
|
|
@ -1,264 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import argparse
|
||||
import codecs
|
||||
import os
|
||||
import sys
|
||||
|
||||
from PyQt4.QtCore import qInstallMsgHandler, QObject, qWarning
|
||||
from PyQt4.QtNetwork import QNetworkProxy
|
||||
from PyQt4.QtWebKit import QWebPage
|
||||
|
||||
from __init__ import __version__
|
||||
from plugincontroller import do_action
|
||||
from utils import debug, MessageHandler, QPyFile
|
||||
|
||||
|
||||
license = '''
|
||||
PyPhantomJS Version %s
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
''' % __version__
|
||||
|
||||
|
||||
defaults = {
|
||||
'cookiesFile': None,
|
||||
'debug': None,
|
||||
'diskCache': False,
|
||||
'ignoreSslErrors': False,
|
||||
'loadImages': True,
|
||||
'loadPlugins': False,
|
||||
'localToRemoteUrlAccessEnabled': False,
|
||||
'maxDiskCacheSize': -1,
|
||||
'outputEncoding': 'System',
|
||||
'proxy': None,
|
||||
'proxyType': QNetworkProxy.HttpProxy,
|
||||
'scriptEncoding': 'utf-8',
|
||||
'verbose': False
|
||||
}
|
||||
|
||||
|
||||
def argParser():
|
||||
class YesOrNoAction(argparse.Action):
|
||||
'''Converts yes or no arguments to True/False respectively'''
|
||||
def __call__(self, parser, namespace, value, option_string=None):
|
||||
answer = True if value == 'yes' else False
|
||||
setattr(namespace, self.dest, answer)
|
||||
|
||||
def proxyType(type_):
|
||||
if type_ == QNetworkProxy.HttpProxy:
|
||||
return 'http'
|
||||
elif type_ == QNetworkProxy.Socks5Proxy:
|
||||
return 'socks5'
|
||||
|
||||
yesOrNo = lambda d: 'yes' if d else 'no'
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Minimalistic headless WebKit-based JavaScript-driven tool',
|
||||
usage='%(prog)s [options] script.[js|coffee] [script argument [script argument ...]]',
|
||||
formatter_class=argparse.RawTextHelpFormatter
|
||||
)
|
||||
|
||||
parser.add_argument('script', metavar='script.[js|coffee]', nargs='?',
|
||||
help='The script to execute, and any args to pass to it'
|
||||
)
|
||||
parser.add_argument('-v', '--version',
|
||||
action='version', version=license,
|
||||
help="show this program's version and license"
|
||||
)
|
||||
|
||||
program = parser.add_argument_group('program options')
|
||||
script = parser.add_argument_group('script options')
|
||||
debug = parser.add_argument_group('debug options')
|
||||
|
||||
program.add_argument('--config', metavar='/path/to/config',
|
||||
help='Specifies path to a JSON-formatted config file'
|
||||
)
|
||||
program.add_argument('--disk-cache', default=defaults['diskCache'], action=YesOrNoAction,
|
||||
choices=['yes', 'no'],
|
||||
help='Enable disk cache (default: %s)' % yesOrNo(defaults['diskCache'])
|
||||
)
|
||||
program.add_argument('--ignore-ssl-errors', default=defaults['ignoreSslErrors'], action=YesOrNoAction,
|
||||
choices=['yes', 'no'],
|
||||
help='Ignore SSL errors (default: %s)' % yesOrNo(defaults['ignoreSslErrors'])
|
||||
)
|
||||
program.add_argument('--max-disk-cache-size', default=defaults['maxDiskCacheSize'], metavar='size', type=int,
|
||||
help='Limits the size of disk cache (in KB)'
|
||||
)
|
||||
program.add_argument('--output-encoding', default=defaults['outputEncoding'], metavar='encoding',
|
||||
help='Sets the encoding used for terminal output (default: %(default)s)'
|
||||
)
|
||||
program.add_argument('--proxy', metavar='address:port',
|
||||
help='Set the network proxy'
|
||||
)
|
||||
program.add_argument('--proxy-type', default=defaults['proxyType'], metavar='type',
|
||||
help='Set the network proxy type (default: %s)' % proxyType(defaults['proxyType'])
|
||||
)
|
||||
program.add_argument('--script-encoding', default=defaults['scriptEncoding'], metavar='encoding',
|
||||
help='Sets the encoding used for scripts (default: %(default)s)'
|
||||
)
|
||||
|
||||
script.add_argument('--cookies-file', metavar='/path/to/cookies.txt',
|
||||
help='Sets the file name to store the persistent cookies'
|
||||
)
|
||||
script.add_argument('--load-images', default=defaults['loadImages'], action=YesOrNoAction,
|
||||
choices=['yes', 'no'],
|
||||
help='Load all inlined images (default: %s)' % yesOrNo(defaults['loadImages'])
|
||||
)
|
||||
script.add_argument('--load-plugins', default=defaults['loadPlugins'], action=YesOrNoAction,
|
||||
choices=['yes', 'no'],
|
||||
help='Load all plugins (i.e. Flash, Silverlight, ...) (default: %s)' % yesOrNo(defaults['loadPlugins'])
|
||||
)
|
||||
script.add_argument('--local-to-remote-url-access', default=defaults['localToRemoteUrlAccessEnabled'], action=YesOrNoAction,
|
||||
choices=['yes', 'no'],
|
||||
help='Local content can access remote URL (default: %s)' % yesOrNo(defaults['localToRemoteUrlAccessEnabled'])
|
||||
)
|
||||
|
||||
debug.add_argument('--debug', choices=['exception', 'program'], metavar='option',
|
||||
help=('Debug the program with pdb\n'
|
||||
' exception : Start debugger when program hits exception\n'
|
||||
' program : Start the program with the debugger enabled')
|
||||
)
|
||||
debug.add_argument('--verbose', action='store_true',
|
||||
help='Show verbose debug messages'
|
||||
)
|
||||
|
||||
do_action('ArgParser')
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def parseArgs(app, args):
|
||||
# Handle all command-line options
|
||||
p = argParser()
|
||||
arg_data = p.parse_known_args(args)
|
||||
args = arg_data[0]
|
||||
args.script_args = arg_data[1]
|
||||
|
||||
# convert script args to unicode
|
||||
for i, arg in enumerate(args.script_args):
|
||||
args.script_args[i] = unicode(arg, 'utf-8')
|
||||
|
||||
# register an alternative Message Handler
|
||||
messageHandler = MessageHandler(args.verbose)
|
||||
qInstallMsgHandler(messageHandler.process)
|
||||
|
||||
file_check = (args.cookies_file, args.config)
|
||||
for file_ in file_check:
|
||||
if file_ is not None and not os.path.exists(file_):
|
||||
sys.exit("No such file or directory: '%s'" % file_)
|
||||
|
||||
if args.config:
|
||||
config = Config(app, args.config)
|
||||
# apply settings
|
||||
for setting in config.settings:
|
||||
setattr(args, config.settings[setting]['mapping'], config.property(setting))
|
||||
|
||||
split_check = (
|
||||
(args.proxy, 'proxy'),
|
||||
)
|
||||
for arg, name in split_check:
|
||||
if arg:
|
||||
item = arg.split(':')
|
||||
if len(item) < 2 or not len(item[1]):
|
||||
p.print_help()
|
||||
sys.exit(1)
|
||||
setattr(args, name, item)
|
||||
|
||||
if args.proxy is not None:
|
||||
if args.proxy_type == 'socks5':
|
||||
args.proxy_type = QNetworkProxy.Socks5Proxy
|
||||
|
||||
do_action('ParseArgs', args)
|
||||
|
||||
if args.debug:
|
||||
debug(args.debug)
|
||||
|
||||
# verbose flag got changed on us, so we reload the flag
|
||||
if messageHandler.verbose != args.verbose:
|
||||
messageHandler.verbose = args.verbose
|
||||
|
||||
if args.script is None:
|
||||
p.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
if not os.path.exists(args.script):
|
||||
sys.exit("No such file or directory: '%s'" % args.script)
|
||||
|
||||
return args
|
||||
|
||||
|
||||
class Config(QObject):
|
||||
def __init__(self, parent, jsonFile):
|
||||
super(Config, self).__init__(parent)
|
||||
|
||||
with codecs.open(jsonFile, encoding='utf-8') as f:
|
||||
json = f.read()
|
||||
|
||||
self.settings = {
|
||||
'cookiesFile': { 'mapping': 'cookies_file', 'default': defaults['cookiesFile'] },
|
||||
'debug': { 'mapping': 'debug', 'default': defaults['debug'] },
|
||||
'diskCache': { 'mapping': 'disk_cache', 'default': defaults['diskCache'] },
|
||||
'ignoreSslErrors': { 'mapping': 'ignore_ssl_errors', 'default': defaults['ignoreSslErrors'] },
|
||||
'loadImages': { 'mapping': 'load_images', 'default': defaults['loadImages'] },
|
||||
'loadPlugins': { 'mapping': 'load_plugins', 'default': defaults['loadPlugins'] },
|
||||
'localToRemoteUrlAccessEnabled': { 'mapping': 'local_to_remote_url_access', 'default': defaults['localToRemoteUrlAccessEnabled'] },
|
||||
'maxDiskCacheSize': { 'mapping': 'max_disk_cache_size', 'default': defaults['maxDiskCacheSize'] },
|
||||
'outputEncoding': { 'mapping': 'output_encoding', 'default': defaults['outputEncoding'] },
|
||||
'proxy': { 'mapping': 'proxy', 'default': defaults['proxy'] },
|
||||
'proxyType': { 'mapping': 'proxy_type', 'default': defaults['proxyType'] },
|
||||
'scriptEncoding': { 'mapping': 'script_encoding', 'default': defaults['scriptEncoding'] },
|
||||
'verbose': { 'mapping': 'verbose', 'default': defaults['verbose'] }
|
||||
}
|
||||
|
||||
do_action('ConfigInit', self.settings)
|
||||
|
||||
# generate dynamic properties
|
||||
for setting in self.settings:
|
||||
self.setProperty(setting, self.settings[setting]['default'])
|
||||
|
||||
# now it's time to parse our JSON file
|
||||
if not json.lstrip().startswith('{') or not json.rstrip().endswith('}'):
|
||||
qWarning('Config file MUST be in JSON format!')
|
||||
return
|
||||
|
||||
webPage = QWebPage(self)
|
||||
|
||||
with QPyFile(':/configurator.js') as f:
|
||||
# add config object
|
||||
webPage.mainFrame().addToJavaScriptWindowObject('config', self)
|
||||
# apply settings
|
||||
webPage.mainFrame().evaluateJavaScript(f.readAll().replace('%1', json))
|
||||
|
||||
do_action('Config')
|
|
@ -1,58 +0,0 @@
|
|||
/*jslint sloppy: true, nomen: true */
|
||||
/*global window:true,phantom:true */
|
||||
|
||||
/*
|
||||
This file is part of the PhantomJS project from Ofi Labs.
|
||||
|
||||
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
|
||||
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
Copyright (C) 2011 execjosh, http://execjosh.blogspot.com
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the <organization> nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
function require(name) {
|
||||
|
||||
var code, func, exports;
|
||||
|
||||
if (name === 'webpage' || name === 'fs' || name == 'webserver') {
|
||||
code = phantom.loadModuleSource(name);
|
||||
func = new Function("exports", "window", code);
|
||||
exports = {};
|
||||
if (name === 'fs') {
|
||||
exports = phantom.createFilesystem();
|
||||
}
|
||||
func.call({}, exports, {});
|
||||
return exports;
|
||||
}
|
||||
|
||||
if (typeof exports === 'undefined') {
|
||||
throw 'Unknown module ' + name + ' for require()';
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy way to use WebPage
|
||||
window.WebPage = require('webpage').create;
|
||||
window.WebServer = require('webserver').create;
|
|
@ -1,17 +0,0 @@
|
|||
(function (opts) {
|
||||
var i;
|
||||
|
||||
opts = opts || {};
|
||||
|
||||
if (typeof opts !== 'object') {
|
||||
return;
|
||||
}
|
||||
|
||||
for (i in opts) {
|
||||
if (opts.hasOwnProperty(i) && typeof opts[i] !== 'undefined') {
|
||||
config[i] = opts[i];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
})((%1));
|
|
@ -1,51 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
from PyQt4.QtCore import QSettings
|
||||
from PyQt4.QtNetwork import QNetworkCookie, QNetworkCookieJar
|
||||
|
||||
|
||||
class CookieJar(QNetworkCookieJar):
|
||||
def __init__(self, parent, cookiesFile):
|
||||
super(CookieJar, self).__init__(parent)
|
||||
|
||||
self.m_cookiesFile = cookiesFile
|
||||
|
||||
def setCookiesFromUrl(self, cookieList, url):
|
||||
settings = QSettings(self.m_cookiesFile, QSettings.IniFormat)
|
||||
|
||||
settings.beginGroup(url.host())
|
||||
|
||||
for cookie in cookieList:
|
||||
settings.setValue(str(cookie.name()), str(cookie.value()))
|
||||
|
||||
settings.sync()
|
||||
|
||||
return True
|
||||
|
||||
def cookiesForUrl(self, url):
|
||||
settings = QSettings(self.m_cookiesFile, QSettings.IniFormat)
|
||||
cookieList = []
|
||||
|
||||
settings.beginGroup(url.host())
|
||||
|
||||
for cname in settings.childKeys():
|
||||
cookieList.append(QNetworkCookie(cname, settings.value(cname)))
|
||||
|
||||
return cookieList
|
|
@ -1,51 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
from PyQt4.QtCore import QObject
|
||||
from PyQt4.QtGui import QApplication
|
||||
from PyQt4.QtWebKit import QWebPage
|
||||
|
||||
from utils import QPyFile
|
||||
|
||||
|
||||
class CSConverter(QObject):
|
||||
_instance = None
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(CSConverter, cls).__new__(cls, *args, **kwargs)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
super(CSConverter, self).__init__(QApplication.instance())
|
||||
|
||||
self.m_webPage = QWebPage(self)
|
||||
|
||||
with QPyFile(':/resources/coffee-script.js') as f:
|
||||
self.m_webPage.mainFrame().evaluateJavaScript(f.readAll())
|
||||
self.m_webPage.mainFrame().addToJavaScriptWindowObject('converter', self)
|
||||
|
||||
def convert(self, script):
|
||||
self.setProperty('source', script)
|
||||
result = self.m_webPage.mainFrame().evaluateJavaScript('''try {
|
||||
[true, this.CoffeeScript.compile(converter.source)];
|
||||
} catch (error) {
|
||||
[false, error.message];
|
||||
}
|
||||
''')
|
||||
return result
|
|
@ -1,35 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import codecs
|
||||
|
||||
|
||||
class Encode(object):
|
||||
def __init__(self, encoding, default):
|
||||
# check that encoding is valid
|
||||
try:
|
||||
codecs.lookup(encoding)
|
||||
self.encoding = encoding
|
||||
except LookupError:
|
||||
# fall back to default encoding
|
||||
self.encoding = default
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return codecs.lookup(self.encoding).name
|
|
@ -1,671 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import codecs
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
try:
|
||||
from grp import getgrgid, getgrnam
|
||||
from pwd import getpwuid, getpwnam
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from PyQt4.QtCore import (pyqtProperty, pyqtSlot, QDateTime, qDebug,
|
||||
QFileInfo, QObject)
|
||||
|
||||
from plugincontroller import do_action
|
||||
|
||||
|
||||
class File(QObject):
|
||||
def __init__(self, parent, openfile):
|
||||
super(File, self).__init__(parent)
|
||||
|
||||
self.m_file = openfile
|
||||
|
||||
do_action('FileInit')
|
||||
|
||||
def __del__(self):
|
||||
self.m_file.close()
|
||||
|
||||
@pyqtSlot(result=bool)
|
||||
def atEnd(self):
|
||||
# :WARNING: On Windows, tell() can return illegal values (after an fgets())
|
||||
# when reading files with Unix-style line-endings. Use binary mode ('rb')
|
||||
# to circumvent this problem.
|
||||
currentPos = self.m_file.tell()
|
||||
|
||||
try:
|
||||
line = self.m_file.readline()
|
||||
self.m_file.seek(currentPos)
|
||||
except IOError as e:
|
||||
qDebug("File.atEnd - %s: '%s'" % (e, self.m_file.name))
|
||||
return False
|
||||
|
||||
# test for EOF
|
||||
if line == '':
|
||||
return True
|
||||
return False
|
||||
|
||||
@pyqtSlot()
|
||||
def close(self):
|
||||
self.m_file.flush()
|
||||
self.m_file.close()
|
||||
self.deleteLater()
|
||||
|
||||
@pyqtSlot()
|
||||
def flush(self):
|
||||
self.m_file.flush()
|
||||
|
||||
@pyqtSlot(result=str)
|
||||
def read(self):
|
||||
try:
|
||||
return self.m_file.read()
|
||||
except IOError as e:
|
||||
qDebug("File.read - %s: '%s'" % (e, self.m_file.name))
|
||||
return ''
|
||||
|
||||
@pyqtSlot(result=str)
|
||||
def readLine(self):
|
||||
try:
|
||||
return self.m_file.readline()
|
||||
except IOError as e:
|
||||
qDebug("File.readLine - %s: '%s'" % (e, self.m_file.name))
|
||||
return ''
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def write(self, data):
|
||||
try:
|
||||
self.m_file.write(data)
|
||||
return True
|
||||
except IOError as e:
|
||||
qDebug("File.write - %s: '%s'" % (e, self.m_file.name))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def writeLine(self, data):
|
||||
try:
|
||||
self.m_file.write(data + '\n')
|
||||
return True
|
||||
except IOError as e:
|
||||
qDebug("File.writeLine - %s: '%s'" % (e, self.m_file.name))
|
||||
return False
|
||||
|
||||
do_action('File')
|
||||
|
||||
|
||||
class FileSystem(QObject):
|
||||
_instance = None
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(FileSystem, cls).__new__(cls, *args, **kwargs)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, parent):
|
||||
super(FileSystem, self).__init__(parent)
|
||||
|
||||
do_action('FileSystemInit')
|
||||
|
||||
##
|
||||
# Attributes
|
||||
##
|
||||
|
||||
@pyqtSlot(str, result=int)
|
||||
def _size(self, path):
|
||||
try:
|
||||
return os.path.getsize(path)
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.size - %s: '%s'" % (e, path))
|
||||
return -1
|
||||
|
||||
@pyqtSlot(str, result=QDateTime)
|
||||
def lastModified(self, path):
|
||||
fi = QFileInfo(path)
|
||||
if fi.exists():
|
||||
return fi.lastModified()
|
||||
else:
|
||||
err = 'No such file or directory'
|
||||
|
||||
qDebug("FileSystem.lastModified - %s: '%s'" % (err, path))
|
||||
return QDateTime()
|
||||
|
||||
##
|
||||
# Files / Directories
|
||||
##
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
def _copy(self, source, target):
|
||||
try:
|
||||
shutil.copy2(source, target)
|
||||
return True
|
||||
except IOError as (_, e):
|
||||
qDebug("FileSystem.copy - %s: '%s' -> '%s'" % (e, source, target))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
def rename(self, source, target):
|
||||
try:
|
||||
os.rename(source, target)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.rename - %s: '%s' -> '%s'" % (e, source, target))
|
||||
return False
|
||||
|
||||
##
|
||||
# Directories
|
||||
##
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
def _copyTree(self, source, target):
|
||||
try:
|
||||
shutil.copytree(source, target)
|
||||
return True
|
||||
except IOError as (_, e):
|
||||
qDebug("FileSystem.copyTree - %s: '%s' -> '%s'" % (e, source, target))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def _removeDirectory(self, path):
|
||||
try:
|
||||
os.rmdir(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.removeDirectory - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def _removeTree(self, path):
|
||||
try:
|
||||
shutil.rmtree(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.removeTree - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
def copyLinkTree(self, source, target):
|
||||
try:
|
||||
shutil.copytree(source, target, True)
|
||||
return True
|
||||
except IOError as (_, e):
|
||||
qDebug("FileSystem.copyLinkTree - %s: '%s' -> '%s'" % (e, source, target))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def makeDirectory(self, path):
|
||||
try:
|
||||
os.mkdir(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.makeDirectory - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def makeTree(self, path):
|
||||
try:
|
||||
os.makedirs(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.makeTree - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
##
|
||||
# Files
|
||||
##
|
||||
|
||||
@pyqtSlot(str, str, result=File)
|
||||
def _open(self, path, mode):
|
||||
try:
|
||||
f = codecs.open(path, mode, encoding='utf-8')
|
||||
return File(self, f)
|
||||
except (IOError, ValueError) as (_, e):
|
||||
qDebug("FileSystem.open - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def _remove(self, path):
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.remove - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
@pyqtProperty(str)
|
||||
def newline(self):
|
||||
return os.linesep
|
||||
|
||||
##
|
||||
# Listing
|
||||
##
|
||||
|
||||
@pyqtSlot(str, name='list', result='QStringList')
|
||||
def list_(self, path):
|
||||
try:
|
||||
p = os.listdir(path)
|
||||
p[0:2] = ('.', '..')
|
||||
return p
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.list - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QStringList')
|
||||
def listTree(self, path):
|
||||
try:
|
||||
listing = []
|
||||
for root, _, files in os.walk(path):
|
||||
for file_ in files:
|
||||
listing.append(os.path.join(root, file_))
|
||||
return listing
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.listTree - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QStringList')
|
||||
def listDirectoryTree(self, path):
|
||||
try:
|
||||
listing = []
|
||||
for root, dirs, _ in os.walk(path):
|
||||
for dir_ in dirs:
|
||||
listing.append(os.path.join(root, dir_))
|
||||
return listing
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.listDirectoryTree - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
##
|
||||
# Links
|
||||
##
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
def symbolicLink(self, source, target):
|
||||
try:
|
||||
os.symlink(source, target)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.symbolicLink - %s: '%s' -> '%s'" % (e, source, target))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
def hardLink(self, source, target):
|
||||
try:
|
||||
os.link(source, target)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.hardLink - %s: '%s' -> '%s'" % (e, source, target))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def readLink(self, path):
|
||||
try:
|
||||
return os.readlink(path)
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.readLink - %s: '%s'" % (e, path))
|
||||
return ''
|
||||
|
||||
##
|
||||
# Paths
|
||||
##
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def absolute(self, path):
|
||||
return os.path.abspath(path)
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
@pyqtSlot(str, str, result=str)
|
||||
def base(self, path, ext=None):
|
||||
if ext is None:
|
||||
return os.path.basename(path)
|
||||
else:
|
||||
base = os.path.splitext(os.path.basename(path))
|
||||
if ext == base[1][1:]:
|
||||
return base[0]
|
||||
return ''.join(base)
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def canonical(self, path):
|
||||
return os.path.realpath(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def changeWorkingDirectory(self, path):
|
||||
try:
|
||||
os.chdir(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
qDebug("FileSystem.changeWorkingDirectory - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def directory(self, path):
|
||||
return os.path.dirname(path)
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def extension(self, path):
|
||||
return os.path.splitext(os.path.basename(path))[1][1:]
|
||||
|
||||
@pyqtSlot('QStringList', result=str)
|
||||
def join(self, paths):
|
||||
return os.path.join(*paths)
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def normal(self, path):
|
||||
return os.path.normpath(path)
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def normalCase(self, path):
|
||||
return os.path.normcase(path)
|
||||
|
||||
@pyqtProperty(str)
|
||||
def workingDirectory(self):
|
||||
return os.getcwdu()
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
@pyqtSlot(str, str, result=str)
|
||||
def relative(self, source, target=None):
|
||||
if target is None:
|
||||
return os.path.relpath(source)
|
||||
else:
|
||||
return os.path.relpath(source, target)
|
||||
|
||||
@pyqtProperty(str)
|
||||
def separator(self):
|
||||
return os.sep
|
||||
|
||||
@pyqtSlot(str, result='QStringList')
|
||||
def split(self, path):
|
||||
if os.sep in path:
|
||||
return path.split(os.sep)
|
||||
else:
|
||||
return path.split(os.altsep)
|
||||
|
||||
##
|
||||
# Permissions
|
||||
##
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
@pyqtSlot(str, int, result=bool)
|
||||
def changeGroup(self, path, group):
|
||||
try:
|
||||
if isinstance(group, int):
|
||||
os.chown(path, -1, group)
|
||||
else:
|
||||
os.chown(path, -1, getgrnam(group).gr_gid)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.changeGroup - %s: '%s':'%s'" % (e, group, path))
|
||||
except KeyError as e:
|
||||
qDebug("FileSystem.changeGroup - %s: '%s'" % (e.args[0], path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
@pyqtSlot(str, int, result=bool)
|
||||
def changeLinkGroup(self, path, group):
|
||||
try:
|
||||
if isinstance(group, int):
|
||||
os.lchown(path, -1, group)
|
||||
else:
|
||||
os.lchown(path, -1, getgrnam(group).gr_gid)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.changeLinkGroup - %s: '%s':'%s'" % (e, group, path))
|
||||
except KeyError as e:
|
||||
qDebug("FileSystem.changeLinkGroup - %s: '%s'" % (e.args[0], path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
@pyqtSlot(str, int, result=bool)
|
||||
def changeLinkOwner(self, path, owner):
|
||||
try:
|
||||
if isinstance(owner, int):
|
||||
os.lchown(path, owner, -1)
|
||||
else:
|
||||
os.lchown(path, getpwnam(owner).pw_uid, -1)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.changeLinkOwner - %s: '%s':'%s'" % (e, owner, path))
|
||||
except KeyError as e:
|
||||
qDebug("FileSystem.changeLinkOwner - %s: '%s'" % (e.args[0], path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, str, result=bool)
|
||||
@pyqtSlot(str, int, result=bool)
|
||||
def changeOwner(self, path, owner):
|
||||
try:
|
||||
if isinstance(owner, int):
|
||||
os.chown(path, owner, -1)
|
||||
else:
|
||||
os.chown(path, getpwnam(owner).pw_uid, -1)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.changeOwner - %s: '%s':'%s'" % (e, owner, path))
|
||||
except KeyError as e:
|
||||
qDebug("FileSystem.changeOwner - %s: '%s'" % (e.args[0], path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, int, result=bool)
|
||||
@pyqtSlot(str, 'QVariantMap', result=bool)
|
||||
def changePermissions(self, path, permissions):
|
||||
# permissions uses an object in 4 types: owner, group, others, special
|
||||
# owner,group,others each has 3 types, read,write,executable, contained in an array
|
||||
# special uses setuid,setgid,sticky
|
||||
#
|
||||
# In order to turn values on or off, just use true or false values.
|
||||
#
|
||||
# Permissions can alternatively be a numeric mode to chmod too.
|
||||
|
||||
keys = {
|
||||
'owner': {'read': 'S_IRUSR', 'write': 'S_IWUSR', 'executable': 'S_IXUSR'},
|
||||
'group': {'read': 'S_IRGRP', 'write': 'S_IWGRP', 'executable': 'S_IXGRP'},
|
||||
'others': {'read': 'S_IROTH', 'write': 'S_IWOTH', 'executable': 'S_IXOTH'},
|
||||
'special': {'setuid': 'S_ISUID', 'setgid': 'S_ISGID', 'sticky': 'S_ISVTX'}
|
||||
}
|
||||
|
||||
try:
|
||||
if isinstance(permissions, int):
|
||||
os.chmod(path, permissions)
|
||||
else:
|
||||
bitnum = os.stat(path).st_mode
|
||||
for section in permissions:
|
||||
for key in permissions[section]:
|
||||
try:
|
||||
if permissions[section][key] is True:
|
||||
bitnum = bitnum | stat.__dict__[keys[section][key]]
|
||||
elif permissions[section][key] is False:
|
||||
bitnum = bitnum & ~stat.__dict__[keys[section][key]]
|
||||
except KeyError:
|
||||
pass
|
||||
os.chmod(path, bitnum)
|
||||
return True
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.changePermissions - %s: '%s'" % (e, path))
|
||||
return False
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def group(self, path):
|
||||
try:
|
||||
finfo = os.stat(path)
|
||||
return {
|
||||
'name': getgrgid(finfo.st_gid).gr_name,
|
||||
'uid': finfo.st_gid
|
||||
}
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.group - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def owner(self, path):
|
||||
try:
|
||||
finfo = os.stat(path)
|
||||
return {
|
||||
'name': getpwuid(finfo.st_uid).pw_name,
|
||||
'uid': finfo.st_uid
|
||||
}
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.owner - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def linkGroup(self, path):
|
||||
try:
|
||||
finfo = os.lstat(path)
|
||||
return {
|
||||
'name': getgrgid(finfo.st_gid).gr_name,
|
||||
'uid': finfo.st_gid
|
||||
}
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.linkGroup - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def linkOwner(self, path):
|
||||
try:
|
||||
finfo = os.lstat(path)
|
||||
return {
|
||||
'name': getpwuid(finfo.st_uid).pw_name,
|
||||
'uid': finfo.st_uid
|
||||
}
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.linkOwner - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def linkPermissions(self, path):
|
||||
# returns an object in 4 types: owner, group, others, special
|
||||
# owner,group,others each has 3 types, read,write,executable
|
||||
# special will return setuid,setgid,sticky
|
||||
|
||||
try:
|
||||
finfo = os.lstat(path).st_mode
|
||||
|
||||
# owner
|
||||
isOwnRd = bool(finfo & stat.S_IRUSR)
|
||||
isOwnWr = bool(finfo & stat.S_IWUSR)
|
||||
isOwnEx = bool(finfo & stat.S_IXUSR)
|
||||
# group
|
||||
isGrpRd = bool(finfo & stat.S_IRGRP)
|
||||
isGrpWr = bool(finfo & stat.S_IWGRP)
|
||||
isGrpEx = bool(finfo & stat.S_IXGRP)
|
||||
# others
|
||||
isOthRd = bool(finfo & stat.S_IROTH)
|
||||
isOthWr = bool(finfo & stat.S_IWOTH)
|
||||
isOthEx = bool(finfo & stat.S_IXOTH)
|
||||
# s*id
|
||||
isSUid = bool(finfo & stat.S_ISUID)
|
||||
isSGid = bool(finfo & stat.S_ISGID)
|
||||
# sticky
|
||||
isStick = bool(finfo & stat.S_ISVTX)
|
||||
|
||||
return {
|
||||
'mode': oct(finfo)[-4:],
|
||||
'owner': {'read': isOwnRd, 'write': isOwnWr, 'executable': isOwnEx},
|
||||
'group': {'read': isGrpRd, 'write': isGrpWr, 'executable': isGrpEx},
|
||||
'others': {'read': isOthRd, 'write': isOthWr, 'executable': isOthEx},
|
||||
'special': {'setuid': isSUid, 'setgid': isSGid, 'sticky': isStick}
|
||||
}
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.linkPermissions - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def permissions(self, path):
|
||||
# returns an object in 4 types: owner, group, others, special
|
||||
# owner,group,others each has 3 types, read,write,executable
|
||||
# special will return setuid,setgid,sticky
|
||||
|
||||
try:
|
||||
finfo = os.stat(path).st_mode
|
||||
|
||||
# owner
|
||||
isOwnRd = bool(finfo & stat.S_IRUSR)
|
||||
isOwnWr = bool(finfo & stat.S_IWUSR)
|
||||
isOwnEx = bool(finfo & stat.S_IXUSR)
|
||||
# group
|
||||
isGrpRd = bool(finfo & stat.S_IRGRP)
|
||||
isGrpWr = bool(finfo & stat.S_IWGRP)
|
||||
isGrpEx = bool(finfo & stat.S_IXGRP)
|
||||
# others
|
||||
isOthRd = bool(finfo & stat.S_IROTH)
|
||||
isOthWr = bool(finfo & stat.S_IWOTH)
|
||||
isOthEx = bool(finfo & stat.S_IXOTH)
|
||||
# s*id
|
||||
isSUid = bool(finfo & stat.S_ISUID)
|
||||
isSGid = bool(finfo & stat.S_ISGID)
|
||||
# sticky
|
||||
isStick = bool(finfo & stat.S_ISVTX)
|
||||
|
||||
return {
|
||||
'mode': oct(finfo)[-4:],
|
||||
'owner': {'read': isOwnRd, 'write': isOwnWr, 'executable': isOwnEx},
|
||||
'group': {'read': isGrpRd, 'write': isGrpWr, 'executable': isGrpEx},
|
||||
'others': {'read': isOthRd, 'write': isOthWr, 'executable': isOthEx},
|
||||
'special': {'setuid': isSUid, 'setgid': isSGid, 'sticky': isStick}
|
||||
}
|
||||
except OSError as (_, e):
|
||||
qDebug("FileSystem.permissions - %s: '%s'" % (e, path))
|
||||
return
|
||||
|
||||
##
|
||||
# Tests
|
||||
##
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def exists(self, path):
|
||||
return os.path.exists(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isAbsolute(self, path):
|
||||
return os.path.isabs(os.path.splitdrive(path)[1])
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isDirectory(self, path):
|
||||
return os.path.isdir(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isExecutable(self, path):
|
||||
return os.access(path, os.X_OK)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isFile(self, path):
|
||||
return os.path.isfile(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isLink(self, path):
|
||||
return os.path.islink(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isMount(self, path):
|
||||
return os.path.ismount(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isReadable(self, path):
|
||||
return os.access(path, os.R_OK)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def isWritable(self, path):
|
||||
return os.access(path, os.W_OK)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def linkExists(self, path):
|
||||
return os.path.lexists(path)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def same(self, pathA, pathB):
|
||||
return os.path.samefile(pathA, pathB)
|
||||
|
||||
do_action('FileSystem')
|
|
@ -1,162 +0,0 @@
|
|||
/*jslint sloppy: true, nomen: true */
|
||||
/*global exports:true */
|
||||
|
||||
/*
|
||||
This file is part of the PhantomJS project from Ofi Labs.
|
||||
|
||||
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the <organization> nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// JavaScript "shim" to throw exceptions in case a critical operation fails.
|
||||
|
||||
/** Open and return a "file" object.
|
||||
* It will throw exception if it fails.
|
||||
*
|
||||
* @param path Path of the file to open
|
||||
* @param mode Open Mode. A string made of 'r', 'w', 'a/+' characters.
|
||||
* @return "file" object
|
||||
*/
|
||||
exports.open = function (path, mode) {
|
||||
var file = exports._open(path, mode);
|
||||
if (file) {
|
||||
return file;
|
||||
}
|
||||
throw "Unable to open file '" + path + "'";
|
||||
};
|
||||
|
||||
/** Open, read and return content of a file.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param path Path of the file to read from
|
||||
* @return file content
|
||||
*/
|
||||
exports.read = function (path) {
|
||||
var f = exports.open(path, 'r'),
|
||||
content = f.read();
|
||||
|
||||
f.close();
|
||||
return content;
|
||||
};
|
||||
|
||||
/** Open and write content to a file
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param path Path of the file to read from
|
||||
* @param content Content to write to the file
|
||||
* @param mode Open Mode. A string made of 'w' or 'a / +' characters.
|
||||
*/
|
||||
exports.write = function (path, content, mode) {
|
||||
var f = exports.open(path, mode);
|
||||
|
||||
f.write(content);
|
||||
f.close();
|
||||
};
|
||||
|
||||
/** Return the size of a file, in bytes.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param path Path of the file to read the size of
|
||||
* @return File size in bytes
|
||||
*/
|
||||
exports.size = function (path) {
|
||||
var size = exports._size(path);
|
||||
if (size !== -1) {
|
||||
return size;
|
||||
}
|
||||
throw "Unable to read file '" + path + "' size";
|
||||
};
|
||||
|
||||
/** Copy a file.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param source Path of the source file
|
||||
* @param destination Path of the destination file
|
||||
*/
|
||||
exports.copy = function (source, destination) {
|
||||
if (!exports._copy(source, destination)) {
|
||||
throw "Unable to copy file '" + source + "' at '" + destination + "'";
|
||||
}
|
||||
};
|
||||
|
||||
/** Copy a directory tree.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param source Path of the source directory tree
|
||||
* @param destination Path of the destination directory tree
|
||||
*/
|
||||
exports.copyTree = function (source, destination) {
|
||||
if (!exports._copyTree(source, destination)) {
|
||||
throw "Unable to copy directory tree '" + source + "' at '" + destination + "'";
|
||||
}
|
||||
};
|
||||
|
||||
/** Move a file.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param source Path of the source file
|
||||
* @param destination Path of the destination file
|
||||
*/
|
||||
exports.move = function (source, destination) {
|
||||
exports.copy(source, destination);
|
||||
exports.remove(source);
|
||||
};
|
||||
|
||||
/** Removes a file.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param path Path of the file to remove
|
||||
*/
|
||||
exports.remove = function (path) {
|
||||
if (!exports._remove(path)) {
|
||||
throw "Unable to remove file '" + path + "'";
|
||||
}
|
||||
};
|
||||
|
||||
/** Removes a directory.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param path Path of the directory to remove
|
||||
*/
|
||||
exports.removeDirectory = function (path) {
|
||||
if (!exports._removeDirectory(path)) {
|
||||
throw "Unable to remove directory '" + path + "'";
|
||||
}
|
||||
};
|
||||
|
||||
/** Removes a directory tree.
|
||||
* It will throw an exception if it fails.
|
||||
*
|
||||
* @param path Path of the directory tree to remove
|
||||
*/
|
||||
exports.removeTree = function (path) {
|
||||
if (!exports._removeTree(path)) {
|
||||
throw "Unable to remove directory tree '" + path + "'";
|
||||
}
|
||||
};
|
||||
|
||||
exports.touch = function (path) {
|
||||
exports.write(path, "", 'a');
|
||||
};
|
|
@ -1,180 +0,0 @@
|
|||
/*jslint sloppy: true, nomen: true */
|
||||
/*global exports:true,phantom:true */
|
||||
|
||||
/*
|
||||
This file is part of the PhantomJS project from Ofi Labs.
|
||||
|
||||
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
|
||||
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
Copyright (C) 2011 execjosh, http://execjosh.blogspot.com
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the <organization> nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
exports.create = function (opts) {
|
||||
var page = phantom.createWebPage(),
|
||||
handlers = {};
|
||||
|
||||
function checkType(o, type) {
|
||||
return typeof o === type;
|
||||
}
|
||||
|
||||
function isObject(o) {
|
||||
return checkType(o, 'object');
|
||||
}
|
||||
|
||||
function isUndefined(o) {
|
||||
return checkType(o, 'undefined');
|
||||
}
|
||||
|
||||
function isUndefinedOrNull(o) {
|
||||
return isUndefined(o) || null === o;
|
||||
}
|
||||
|
||||
function copyInto(target, source) {
|
||||
if (target === source || isUndefinedOrNull(source)) {
|
||||
return target;
|
||||
}
|
||||
|
||||
target = target || {};
|
||||
|
||||
// Copy into objects only
|
||||
if (isObject(target)) {
|
||||
// Make sure source exists
|
||||
source = source || {};
|
||||
|
||||
if (isObject(source)) {
|
||||
var i, newTarget, newSource;
|
||||
for (i in source) {
|
||||
if (source.hasOwnProperty(i)) {
|
||||
newTarget = target[i];
|
||||
newSource = source[i];
|
||||
|
||||
if (newTarget && isObject(newSource)) {
|
||||
// Deep copy
|
||||
newTarget = copyInto(target[i], newSource);
|
||||
} else {
|
||||
newTarget = newSource;
|
||||
}
|
||||
|
||||
if (!isUndefined(newTarget)) {
|
||||
target[i] = newTarget;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
target = source;
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function defineSetter(handlerName, signalName) {
|
||||
page.__defineSetter__(handlerName, function (f) {
|
||||
if (handlers && typeof handlers[signalName] === 'function') {
|
||||
try {
|
||||
this[signalName].disconnect(handlers[signalName]);
|
||||
} catch (e) {}
|
||||
}
|
||||
handlers[signalName] = f;
|
||||
this[signalName].connect(handlers[signalName]);
|
||||
});
|
||||
}
|
||||
|
||||
// deep copy
|
||||
page.settings = JSON.parse(JSON.stringify(phantom.defaultPageSettings));
|
||||
|
||||
defineSetter("onInitialized", "initialized");
|
||||
|
||||
defineSetter("onLoadStarted", "loadStarted");
|
||||
|
||||
defineSetter("onLoadFinished", "loadFinished");
|
||||
|
||||
defineSetter("onResourceRequested", "resourceRequested");
|
||||
|
||||
defineSetter("onResourceReceived", "resourceReceived");
|
||||
|
||||
defineSetter("onAlert", "javaScriptAlertSent");
|
||||
|
||||
defineSetter("onConsoleMessage", "javaScriptConsoleMessageSent");
|
||||
|
||||
page.open = function (url, arg1, arg2, arg3, arg4) {
|
||||
if (arguments.length === 1) {
|
||||
this.openUrl(url, 'get', this.settings);
|
||||
return;
|
||||
}
|
||||
if (arguments.length === 2 && typeof arg1 === 'function') {
|
||||
this.onLoadFinished = arg1;
|
||||
this.openUrl(url, 'get', this.settings);
|
||||
return;
|
||||
} else if (arguments.length === 2) {
|
||||
this.openUrl(url, arg1, this.settings);
|
||||
return;
|
||||
} else if (arguments.length === 3 && typeof arg2 === 'function') {
|
||||
this.onLoadFinished = arg2;
|
||||
this.openUrl(url, arg1, this.settings);
|
||||
return;
|
||||
} else if (arguments.length === 3) {
|
||||
this.openUrl(url, {
|
||||
operation: arg1,
|
||||
data: arg2
|
||||
}, this.settings);
|
||||
return;
|
||||
} else if (arguments.length === 4) {
|
||||
this.onLoadFinished = arg3;
|
||||
this.openUrl(url, {
|
||||
operation: arg1,
|
||||
data: arg2
|
||||
}, this.settings);
|
||||
return;
|
||||
}
|
||||
throw "Wrong use of WebPage#open";
|
||||
};
|
||||
|
||||
page.includeJs = function (scriptUrl, onScriptLoaded) {
|
||||
// Register temporary signal handler for 'alert()'
|
||||
this.javaScriptAlertSent.connect(function (msgFromAlert) {
|
||||
if (msgFromAlert === scriptUrl) {
|
||||
// Resource loaded, time to fire the callback
|
||||
onScriptLoaded(scriptUrl);
|
||||
// And disconnect the signal handler
|
||||
try {
|
||||
this.javaScriptAlertSent.disconnect(arguments.callee);
|
||||
} catch (e) {}
|
||||
}
|
||||
});
|
||||
|
||||
// Append the script tag to the body
|
||||
this._appendScriptElement(scriptUrl);
|
||||
};
|
||||
|
||||
// Copy options into page
|
||||
if (opts) {
|
||||
page = copyInto(page, opts);
|
||||
}
|
||||
|
||||
return page;
|
||||
};
|
|
@ -1,130 +0,0 @@
|
|||
/*jslint sloppy: true, nomen: true */
|
||||
/*global exports:true,phantom:true */
|
||||
|
||||
/*
|
||||
This file is part of the PhantomJS project from Ofi Labs.
|
||||
|
||||
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
|
||||
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
Copyright (C) 2011 execjosh, http://execjosh.blogspot.com
|
||||
Copyright (C) 2011 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
|
||||
Author: Milian Wolff <milian.wolff@kdab.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the <organization> nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
exports.create = function (opts) {
|
||||
var server = phantom.createWebServer();
|
||||
var handlers = {};
|
||||
|
||||
function checkType(o, type) {
|
||||
return typeof o === type;
|
||||
}
|
||||
|
||||
function isObject(o) {
|
||||
return checkType(o, 'object');
|
||||
}
|
||||
|
||||
function isUndefined(o) {
|
||||
return checkType(o, 'undefined');
|
||||
}
|
||||
|
||||
function isUndefinedOrNull(o) {
|
||||
return isUndefined(o) || null === o;
|
||||
}
|
||||
|
||||
function copyInto(target, source) {
|
||||
if (target === source || isUndefinedOrNull(source)) {
|
||||
return target;
|
||||
}
|
||||
|
||||
target = target || {};
|
||||
|
||||
// Copy into objects only
|
||||
if (isObject(target)) {
|
||||
// Make sure source exists
|
||||
source = source || {};
|
||||
|
||||
if (isObject(source)) {
|
||||
var i, newTarget, newSource;
|
||||
for (i in source) {
|
||||
if (source.hasOwnProperty(i)) {
|
||||
newTarget = target[i];
|
||||
newSource = source[i];
|
||||
|
||||
if (newTarget && isObject(newSource)) {
|
||||
// Deep copy
|
||||
newTarget = copyInto(target[i], newSource);
|
||||
} else {
|
||||
newTarget = newSource;
|
||||
}
|
||||
|
||||
if (!isUndefined(newTarget)) {
|
||||
target[i] = newTarget;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
target = source;
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function defineSetter(handlerName, signalName) {
|
||||
server.__defineSetter__(handlerName, function (f) {
|
||||
if (handlers && typeof handlers[signalName] === 'function') {
|
||||
try {
|
||||
this[signalName].disconnect(handlers[signalName]);
|
||||
} catch (e) {}
|
||||
}
|
||||
handlers[signalName] = f;
|
||||
this[signalName].connect(handlers[signalName]);
|
||||
});
|
||||
}
|
||||
|
||||
// deep copy
|
||||
//TODO: use this?
|
||||
// server.settings = JSON.parse(JSON.stringify(phantom.defaultServerSettings));
|
||||
|
||||
defineSetter("onNewRequest", "newRequest");
|
||||
|
||||
server.listen = function (port, handler) {
|
||||
if (arguments.length === 2 && typeof handler === 'function') {
|
||||
this.onNewRequest = handler;
|
||||
//TODO: settings?
|
||||
return this.listenOnPort(port);
|
||||
}
|
||||
throw "Wrong use of WebServer#listen";
|
||||
};
|
||||
|
||||
// Copy options into server
|
||||
if (opts) {
|
||||
server = copyInto(server, opts);
|
||||
}
|
||||
|
||||
return server;
|
||||
};
|
|
@ -1,174 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
from PyQt4.QtCore import pyqtSignal, QDateTime
|
||||
from PyQt4.QtGui import QDesktopServices
|
||||
from PyQt4.QtNetwork import (QNetworkAccessManager, QNetworkDiskCache,
|
||||
QNetworkRequest)
|
||||
|
||||
from cookiejar import CookieJar
|
||||
from plugincontroller import do_action
|
||||
|
||||
|
||||
class NetworkAccessManager(QNetworkAccessManager):
|
||||
resourceReceived = pyqtSignal('QVariantMap')
|
||||
resourceRequested = pyqtSignal('QVariantMap')
|
||||
|
||||
def __init__(self, parent, args):
|
||||
super(NetworkAccessManager, self).__init__(parent)
|
||||
|
||||
self.m_userName = self.m_password = ''
|
||||
self.m_ignoreSslErrors = args.ignore_ssl_errors
|
||||
self.m_idCounter = 0
|
||||
self.m_ids = {}
|
||||
self.m_started = []
|
||||
|
||||
if args.cookies_file:
|
||||
self.setCookieJar(CookieJar(self, args.cookies_file))
|
||||
|
||||
if args.disk_cache:
|
||||
m_networkDiskCache = QNetworkDiskCache()
|
||||
m_networkDiskCache.setCacheDirectory(QDesktopServices.storageLocation(QDesktopServices.CacheLocation))
|
||||
if args.max_disk_cache_size > 0:
|
||||
m_networkDiskCache.setMaximumCacheSize(args.max_disk_cache_size * 1024)
|
||||
self.setCache(m_networkDiskCache)
|
||||
|
||||
self.authenticationRequired.connect(self.provideAuthentication)
|
||||
self.finished.connect(self.handleFinished)
|
||||
|
||||
do_action('NetworkAccessManagerInit')
|
||||
|
||||
def createRequest(self, op, req, outgoingData):
|
||||
do_action('NetworkAccessManagerCreateRequestPre')
|
||||
|
||||
reply = QNetworkAccessManager.createRequest(self, op, req, outgoingData)
|
||||
|
||||
if self.m_ignoreSslErrors:
|
||||
reply.ignoreSslErrors()
|
||||
|
||||
headers = []
|
||||
for header in req.rawHeaderList():
|
||||
header = {
|
||||
'name': str(header),
|
||||
'value': str(req.rawHeader(header))
|
||||
}
|
||||
headers.append(header)
|
||||
|
||||
self.m_idCounter += 1
|
||||
self.m_ids[reply] = self.m_idCounter
|
||||
|
||||
data = {
|
||||
'id': self.m_idCounter,
|
||||
'url': req.url().toString(),
|
||||
'method': self.operationToString(op),
|
||||
'headers': headers,
|
||||
'time': QDateTime.currentDateTime()
|
||||
}
|
||||
|
||||
reply.readyRead.connect(self.handleStarted)
|
||||
|
||||
do_action('NetworkAccessManagerCreateRequestPost')
|
||||
|
||||
self.resourceRequested.emit(data)
|
||||
return reply
|
||||
|
||||
def handleFinished(self, reply):
|
||||
headers = []
|
||||
for header in reply.rawHeaderList():
|
||||
header = {
|
||||
'name': str(header),
|
||||
'value': str(reply.rawHeader(header))
|
||||
}
|
||||
headers.append(header)
|
||||
|
||||
data = {
|
||||
'stage': 'end',
|
||||
'id': self.m_ids[reply],
|
||||
'url': reply.url().toString(),
|
||||
'status': reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
|
||||
'statusText': reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
|
||||
'contentType': reply.header(QNetworkRequest.ContentTypeHeader),
|
||||
'redirectURL': reply.header(QNetworkRequest.LocationHeader),
|
||||
'headers': headers,
|
||||
'time': QDateTime.currentDateTime()
|
||||
}
|
||||
|
||||
del self.m_ids[reply]
|
||||
if reply in self.m_started:
|
||||
del self.m_started[self.m_started.index(reply)]
|
||||
|
||||
do_action('NetworkAccessManagerHandleFinished')
|
||||
|
||||
self.resourceReceived.emit(data)
|
||||
|
||||
def handleStarted(self):
|
||||
reply = self.sender()
|
||||
if not reply:
|
||||
return
|
||||
if reply in self.m_started:
|
||||
return
|
||||
|
||||
self.m_started.append(reply)
|
||||
|
||||
headers = []
|
||||
for header in reply.rawHeaderList():
|
||||
header = {
|
||||
'name': str(header),
|
||||
'value': str(reply.rawHeader(header))
|
||||
}
|
||||
headers.append(header)
|
||||
|
||||
data = {
|
||||
'stage': 'start',
|
||||
'id': self.m_ids[reply],
|
||||
'url': reply.url().toString(),
|
||||
'status': reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
|
||||
'statusText': reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
|
||||
'contentType': reply.header(QNetworkRequest.ContentTypeHeader),
|
||||
'bodySize': reply.size(),
|
||||
'redirectURL': reply.header(QNetworkRequest.LocationHeader),
|
||||
'headers': headers,
|
||||
'time': QDateTime.currentDateTime()
|
||||
}
|
||||
|
||||
do_action('NetworkAccessManagerHandleStarted')
|
||||
|
||||
self.resourceReceived.emit(data)
|
||||
|
||||
def operationToString(self, op):
|
||||
verb = '?'
|
||||
|
||||
if op == QNetworkAccessManager.HeadOperation:
|
||||
verb = 'HEAD'
|
||||
elif op == QNetworkAccessManager.GetOperation:
|
||||
verb = 'GET'
|
||||
elif op == QNetworkAccessManager.PutOperation:
|
||||
verb = 'PUT'
|
||||
elif op == QNetworkAccessManager.PostOperation:
|
||||
verb = 'POST'
|
||||
elif op == QNetworkAccessManager.DeleteOperation:
|
||||
verb = 'DELETE'
|
||||
|
||||
return verb
|
||||
|
||||
def provideAuthentication(self, reply, authenticator):
|
||||
authenticator.setUser(self.m_userName)
|
||||
authenticator.setPassword(self.m_password)
|
||||
|
||||
do_action('NetworkAccessManager')
|
|
@ -1,195 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from PyQt4.QtCore import pyqtProperty, pyqtSlot, QObject
|
||||
from PyQt4.QtGui import QApplication
|
||||
from PyQt4.QtNetwork import QNetworkProxy, QNetworkProxyFactory
|
||||
|
||||
from __init__ import __version_info__
|
||||
from encoding import Encode
|
||||
from filesystem import FileSystem
|
||||
from plugincontroller import do_action
|
||||
from utils import QPyFile
|
||||
from webpage import injectJsInFrame, WebPage
|
||||
from webserver import WebServer
|
||||
|
||||
|
||||
class Phantom(QObject):
|
||||
def __init__(self, parent, args):
|
||||
super(Phantom, self).__init__(parent)
|
||||
|
||||
# variable declarations
|
||||
self.m_defaultPageSettings = {}
|
||||
self.m_pages = []
|
||||
self.m_servers = []
|
||||
self.m_verbose = args.verbose
|
||||
self.m_page = WebPage(self, args)
|
||||
self.m_returnValue = 0
|
||||
self.m_terminated = False
|
||||
# setup the values from args
|
||||
self.app_args = args
|
||||
self.m_scriptFile = args.script
|
||||
self.m_args = args.script_args
|
||||
self.m_scriptEncoding = Encode(args.script_encoding, 'utf-8')
|
||||
self.m_outputEncoding = Encode(args.output_encoding, sys.stdout.encoding_sys)
|
||||
|
||||
self.m_pages.append(self.m_page)
|
||||
|
||||
do_action('PhantomInitPre')
|
||||
|
||||
if args.proxy is None:
|
||||
QNetworkProxyFactory.setUseSystemConfiguration(True)
|
||||
else:
|
||||
proxy = QNetworkProxy(args.proxy_type, args.proxy[0], int(args.proxy[1]))
|
||||
QNetworkProxy.setApplicationProxy(proxy)
|
||||
|
||||
self.m_page.javaScriptConsoleMessageSent.connect(self.printConsoleMessage)
|
||||
|
||||
self.m_defaultPageSettings['loadImages'] = args.load_images
|
||||
self.m_defaultPageSettings['loadPlugins'] = args.load_plugins
|
||||
self.m_defaultPageSettings['javascriptEnabled'] = True
|
||||
self.m_defaultPageSettings['XSSAuditingEnabled'] = False
|
||||
self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent()
|
||||
self.m_defaultPageSettings['localToRemoteUrlAccessEnabled'] = args.local_to_remote_url_access
|
||||
self.m_page.applySettings(self.m_defaultPageSettings)
|
||||
|
||||
self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile))
|
||||
|
||||
# inject our properties and slots into javascript
|
||||
self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self)
|
||||
|
||||
with QPyFile(':/bootstrap.js') as f:
|
||||
self.m_page.mainFrame().evaluateJavaScript(f.readAll())
|
||||
|
||||
do_action('PhantomInitPost')
|
||||
|
||||
def execute(self):
|
||||
injectJsInFrame(self.m_scriptFile, self.m_scriptEncoding.encoding, os.path.dirname(os.path.abspath(__file__)), self.m_page.mainFrame(), True)
|
||||
return not self.m_terminated
|
||||
|
||||
def printConsoleMessage(self, message, lineNumber, source):
|
||||
if source:
|
||||
message = '%s:%d %s' % (source, lineNumber, message)
|
||||
print message
|
||||
|
||||
def returnValue(self):
|
||||
return self.m_returnValue
|
||||
|
||||
##
|
||||
# Properties and methods exposed to JavaScript
|
||||
##
|
||||
|
||||
@pyqtProperty('QStringList')
|
||||
def args(self):
|
||||
return self.m_args
|
||||
|
||||
@pyqtSlot(result=FileSystem)
|
||||
def createFilesystem(self):
|
||||
return FileSystem(self)
|
||||
|
||||
@pyqtSlot(result=WebPage)
|
||||
def createWebPage(self):
|
||||
page = WebPage(self, self.app_args)
|
||||
self.m_pages.append(page)
|
||||
page.applySettings(self.m_defaultPageSettings)
|
||||
page.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile))
|
||||
return page
|
||||
|
||||
@pyqtSlot(result=WebServer)
|
||||
def createWebServer(self):
|
||||
server = WebServer(self)
|
||||
self.m_servers.append(server)
|
||||
# :TODO:
|
||||
# page.applySettings(self.m_defaultPageSettings)
|
||||
# page.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)
|
||||
return server
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def defaultPageSettings(self):
|
||||
return self.m_defaultPageSettings
|
||||
|
||||
@pyqtSlot()
|
||||
@pyqtSlot(int)
|
||||
def exit(self, code=0):
|
||||
self.m_terminated = True
|
||||
self.m_returnValue = code
|
||||
|
||||
# stop javascript execution in start script;
|
||||
# release all pages, then clear
|
||||
# the page list, and empty the Phantom page
|
||||
for page in self.m_pages:
|
||||
page.release()
|
||||
del self.m_pages[:]
|
||||
self.m_page = None
|
||||
|
||||
for server in self.m_servers:
|
||||
server.release()
|
||||
del self.m_servers[:] # not needed, but I'd rather be thorough
|
||||
|
||||
QApplication.instance().exit(code)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def injectJs(self, filePath):
|
||||
return injectJsInFrame(filePath, self.m_scriptEncoding.encoding, self.libraryPath, self.m_page.mainFrame())
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def loadModuleSource(self, name):
|
||||
moduleSourceFilePath = ':/modules/%s.js' % name
|
||||
|
||||
with QPyFile(moduleSourceFilePath) as f:
|
||||
return f.readAll()
|
||||
|
||||
@pyqtProperty(str)
|
||||
def libraryPath(self):
|
||||
return self.m_page.libraryPath
|
||||
|
||||
@libraryPath.setter
|
||||
def libraryPath(self, dirPath):
|
||||
self.m_page.libraryPath = dirPath
|
||||
|
||||
@pyqtProperty(str)
|
||||
def outputEncoding(self):
|
||||
return self.m_outputEncoding.name
|
||||
|
||||
@outputEncoding.setter
|
||||
def outputEncoding(self, encoding):
|
||||
self.m_outputEncoding = Encode(encoding, self.m_outputEncoding.encoding)
|
||||
|
||||
sys.stdout.encoding = self.m_outputEncoding.encoding
|
||||
sys.stdout.encode_to = self.m_outputEncoding.encoding
|
||||
sys.stderr.encoding = self.m_outputEncoding.encoding
|
||||
sys.stdout.encode_to = self.m_outputEncoding.encoding
|
||||
|
||||
@pyqtProperty(str)
|
||||
def scriptName(self):
|
||||
return os.path.basename(self.m_scriptFile)
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def version(self):
|
||||
version = {
|
||||
'major': __version_info__[0],
|
||||
'minor': __version_info__[1],
|
||||
'patch': __version_info__[2]
|
||||
}
|
||||
return version
|
||||
|
||||
do_action('Phantom')
|
|
@ -1,201 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from glob import glob
|
||||
|
||||
|
||||
hooks = defaultdict(dict)
|
||||
|
||||
|
||||
def createHook(func):
|
||||
'''Decorator that will create a hook if the hook doesn't exist'''
|
||||
def innerWrap(*args, **kwargs):
|
||||
if args[0] not in hooks:
|
||||
hooks[args[0]]['count'] = 0
|
||||
hooks[args[0]]['plugins'] = []
|
||||
return func(*args, **kwargs)
|
||||
return innerWrap
|
||||
|
||||
|
||||
def checkHookExists(func):
|
||||
'''Decorator that will raise LookupError if the hook doesn't exist'''
|
||||
def innerWrap(*args, **kwargs):
|
||||
if args[0] not in hooks:
|
||||
raise LookupError("Hook '%s' was not found" % args[0])
|
||||
return func(*args, **kwargs)
|
||||
return innerWrap
|
||||
|
||||
|
||||
@createHook
|
||||
def add_action(hook, priority=10):
|
||||
'''Decorator to be used for registering a function to
|
||||
a specific hook. Functions with lower priority are
|
||||
executed first (priority of 1 for example).
|
||||
'''
|
||||
def register(func):
|
||||
hooks[hook]['plugins'].append((priority, func))
|
||||
return func
|
||||
return register
|
||||
|
||||
|
||||
@checkHookExists
|
||||
def did_action(hook):
|
||||
'''Find out how many times a hook was fired'''
|
||||
return hooks[hook]['count']
|
||||
|
||||
|
||||
@createHook
|
||||
def do_action(hook, *args, **kwargs):
|
||||
'''Trigger a hook. It will run any functions that have registered
|
||||
themselves to the hook. Any additional arguments or keyword
|
||||
arguments you pass in will be passed to the functions.
|
||||
'''
|
||||
# sort plugins by priority
|
||||
hooks[hook]['plugins'].sort()
|
||||
for plugin in hooks[hook]['plugins']:
|
||||
hooks[hook]['count'] += 1
|
||||
plugin[1](*args, **kwargs)
|
||||
|
||||
|
||||
def get(name, depth=4, scope='local'):
|
||||
'''Gets the value of a variable in the parents namespace
|
||||
|
||||
Args:
|
||||
depth controls how deep to go into the stack
|
||||
scope controls the namespace used; valid values are: local,global,builtin
|
||||
'''
|
||||
if scope == 'local':
|
||||
scope = 'f_locals'
|
||||
elif scope == 'global':
|
||||
scope = 'f_globals'
|
||||
elif scope == 'builtin':
|
||||
scope = 'f_builtins'
|
||||
|
||||
return getattr(sys._getframe(depth), scope)[name]
|
||||
|
||||
|
||||
def has_action(hook, func=None):
|
||||
'''Check if hook exists. If function is specified,
|
||||
check if function has been registered for hook.
|
||||
'''
|
||||
if func is None:
|
||||
if hook in hooks:
|
||||
return True
|
||||
else:
|
||||
if hook not in hooks:
|
||||
raise LookupError("Hook '%s' was not found" % hook)
|
||||
|
||||
for plugin in hooks[hook]['plugins']:
|
||||
if plugin[1] is func:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def remove_action(hook, func=None, priority=10):
|
||||
'''Remove hook if hook exists. If function is specified,
|
||||
remove function from hook. If priority is not same as
|
||||
functions priority, it will not remove the function.
|
||||
'''
|
||||
if func is None:
|
||||
if hook in hooks:
|
||||
del hooks[hook]
|
||||
return True
|
||||
else:
|
||||
if hook not in hooks:
|
||||
raise LookupError("Hook '%s' was not found" % hook)
|
||||
|
||||
for i, plugin in enumerate(hooks[hook]['plugins']):
|
||||
if plugin[1] is func and plugin[0] == priority:
|
||||
del hooks[hook]['plugins'][i]
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@checkHookExists
|
||||
def remove_all_actions(hook, priority=None):
|
||||
'''Remove all functions that have been registered to hook.
|
||||
If priority is used, remove all actions from that priority
|
||||
instead.
|
||||
'''
|
||||
if priority is None:
|
||||
del hooks[hook][:]
|
||||
else:
|
||||
indexes = []
|
||||
for i, plugin in enumerate(hooks[hook]['plugins']):
|
||||
if plugin[0] == priority:
|
||||
indexes.append(i)
|
||||
for index in indexes:
|
||||
del hooks[hook]['plugins'][index]
|
||||
|
||||
|
||||
def set_(name, value, depth=4, scope='local'):
|
||||
'''Sets the value of a variable in the parents namespace
|
||||
|
||||
Args:
|
||||
depth controls how deep to go into the stack
|
||||
scope controls the namespace used; valid values are: local,global,builtin
|
||||
'''
|
||||
if scope == 'local':
|
||||
scope = 'f_locals'
|
||||
elif scope == 'global':
|
||||
scope = 'f_globals'
|
||||
elif scope == 'builtin':
|
||||
scope = 'f_builtins'
|
||||
|
||||
getattr(sys._getframe(depth), scope)[name] = value
|
||||
|
||||
|
||||
def load_plugins():
|
||||
''' Loads the plugins.
|
||||
|
||||
Plugins must be in folders under plugins/ (or plugins_path),
|
||||
and must also be the same name as the plugin folder.
|
||||
|
||||
E.g. a plugin folder named my_plugin will
|
||||
have my_plugin.py inside the folder loaded.
|
||||
'''
|
||||
plugins_path = os.environ.get('PYPHANTOMJS_PLUGINS_PATH')
|
||||
|
||||
if plugins_path is None:
|
||||
# path is different when frozen
|
||||
if hasattr(sys, 'frozen'):
|
||||
plugins_path = os.path.dirname(os.path.abspath(sys.executable))
|
||||
else:
|
||||
plugins_path = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
plugins_path = os.path.join(plugins_path, 'plugins')
|
||||
else:
|
||||
# make sure it's an absolute path
|
||||
plugins_path = os.path.abspath(plugins_path)
|
||||
|
||||
sys.path.insert(1, plugins_path)
|
||||
|
||||
plugin_list = glob(os.path.join(plugins_path, '*/*.py'))
|
||||
|
||||
# now convert list to [('plugin_folder', 'file'), ...]
|
||||
plugin_list = [(os.path.split(os.path.dirname(f))[1], os.path.splitext(os.path.split(f)[1])[0]) for f in plugin_list]
|
||||
|
||||
# initialize plugins
|
||||
for plugin in plugin_list:
|
||||
if plugin[0] == plugin[1]:
|
||||
moduleName = '.'.join((plugin[0], plugin[1]))
|
||||
__import__(moduleName, globals(), locals(), [], -1)
|
|
@ -1 +0,0 @@
|
|||
|
|
@ -1,76 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
# automatically convert Qt types by using api 2
|
||||
import sip
|
||||
for item in ('QDate', 'QDateTime', 'QString', 'QTextStream', 'QTime'
|
||||
'QUrl', 'QVariant'):
|
||||
sip.setapi(item, 2)
|
||||
|
||||
import sys
|
||||
|
||||
from PyQt4.QtGui import QApplication, QIcon
|
||||
|
||||
from plugincontroller import do_action
|
||||
# load plugins if running script directly
|
||||
if __name__ == '__main__':
|
||||
from plugincontroller import load_plugins
|
||||
load_plugins()
|
||||
|
||||
import resources
|
||||
from __init__ import __version__
|
||||
from arguments import parseArgs
|
||||
from phantom import Phantom
|
||||
|
||||
# make keyboard interrupt quit program
|
||||
import signal
|
||||
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||
|
||||
# output unicode safe text
|
||||
from utils import SafeStreamFilter
|
||||
sys.stdout = SafeStreamFilter(sys.stdout)
|
||||
sys.stderr = SafeStreamFilter(sys.stderr)
|
||||
|
||||
|
||||
def main(arguments):
|
||||
app = QApplication([sys.argv[0]] + arguments)
|
||||
|
||||
app.setWindowIcon(QIcon(':/resources/pyphantomjs-icon.png'))
|
||||
app.setApplicationName('PyPhantomJS')
|
||||
app.setOrganizationName('Umaclan Development')
|
||||
app.setOrganizationDomain('www.umaclan.com')
|
||||
app.setApplicationVersion(__version__)
|
||||
|
||||
args = parseArgs(app, arguments)
|
||||
|
||||
phantom = Phantom(app, args)
|
||||
|
||||
do_action('Main')
|
||||
|
||||
if phantom.execute():
|
||||
app.exec_()
|
||||
return phantom.returnValue()
|
||||
|
||||
|
||||
do_action('PyPhantomJS')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main(sys.argv[1:]))
|
File diff suppressed because it is too large
Load Diff
|
@ -1,11 +0,0 @@
|
|||
<RCC>
|
||||
<qresource prefix="/">
|
||||
<file>bootstrap.js</file>
|
||||
<file>configurator.js</file>
|
||||
<file>modules/fs.js</file>
|
||||
<file>modules/webpage.js</file>
|
||||
<file>modules/webserver.js</file>
|
||||
<file>resources/coffee-script.js</file>
|
||||
<file>resources/pyphantomjs-icon.png</file>
|
||||
</qresource>
|
||||
</RCC>
|
File diff suppressed because one or more lines are too long
Binary file not shown.
Before Width: | Height: | Size: 345 KiB |
Binary file not shown.
Before Width: | Height: | Size: 22 KiB |
|
@ -1,93 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# hack to import parent module(s)
|
||||
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path = [parent_dir] + sys.path
|
||||
|
||||
from __init__ import __version__
|
||||
|
||||
try:
|
||||
from cx_Freeze import setup, Executable
|
||||
except ImportError:
|
||||
sys.exit('cx_Freeze must be installed to use this script')
|
||||
|
||||
if sys.platform.startswith('win'):
|
||||
try:
|
||||
from win32verstamp import stamp
|
||||
except ImportError:
|
||||
from time import sleep
|
||||
print '*** WARNING ***'
|
||||
print 'the script will be unable to create the version resource'
|
||||
print 'install pywin32 extensions if you want the file stamped'
|
||||
sleep(2)
|
||||
|
||||
|
||||
def qt4_plugins_dir():
|
||||
from PyQt4.QtCore import QCoreApplication
|
||||
app = QCoreApplication([])
|
||||
|
||||
qt4_plugin_dirs = map(unicode, app.libraryPaths())
|
||||
if not qt4_plugin_dirs:
|
||||
return
|
||||
for d in qt4_plugin_dirs:
|
||||
if os.path.isdir(d):
|
||||
return str(d) # must be 8-bit chars for one-file builds
|
||||
|
||||
qt4_plugin_dir = qt4_plugins_dir()
|
||||
if qt4_plugin_dir is None:
|
||||
sys.exit('Cannot find PyQt4 plugins directory')
|
||||
|
||||
|
||||
# modules to include
|
||||
includes = [
|
||||
# to make sure images are supported; jpeg, gif, svg, etc.
|
||||
'PyQt4.QtSvg',
|
||||
'PyQt4.QtXml'
|
||||
]
|
||||
|
||||
# files/directories to include
|
||||
include_files = [
|
||||
# to make sure images are supported; jpeg, gif, svg, etc.
|
||||
(os.path.join(qt4_plugin_dir, 'imageformats'), 'imageformats'),
|
||||
(os.path.join(parent_dir, 'plugins'), 'plugins'),
|
||||
(os.path.join(parent_dir, '../../examples'), 'examples'),
|
||||
(os.path.join(parent_dir, '../LICENSE'), 'LICENSE.txt'),
|
||||
(os.path.join(parent_dir, '../README.md'), 'README.txt'),
|
||||
(os.path.join(parent_dir, '../../ChangeLog'), 'ChangeLog.txt')
|
||||
]
|
||||
|
||||
|
||||
exe = Executable(
|
||||
script = os.path.join(parent_dir, 'pyphantomjs.py'),
|
||||
icon = os.path.join(parent_dir, 'resources/pyphantomjs-icon.ico')
|
||||
)
|
||||
|
||||
|
||||
setup(
|
||||
name = 'PyPhantomJS',
|
||||
version = __version__,
|
||||
description = 'Minimalistic, headless, WebKit-based, JavaScript-driven tool',
|
||||
options = {'build_exe': {'includes': includes, 'include_files': include_files}},
|
||||
executables = [exe]
|
||||
)
|
|
@ -1,14 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
#
|
||||
# This script will convert each qrc into a
|
||||
# Python resource file(s) which can be used
|
||||
#
|
||||
|
||||
# change to script directory
|
||||
cd `dirname "$0"`
|
||||
|
||||
# convert each filename.qrc to respective filename.py
|
||||
for f in ../*.qrc; do
|
||||
pyrcc4 -compress 2 -o "${f%.*}.py" "$f"
|
||||
done
|
|
@ -1,166 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import sys
|
||||
|
||||
from PyQt4.QtCore import (QByteArray, QDateTime, QFile, Qt,
|
||||
QtCriticalMsg, QtDebugMsg, QtFatalMsg,
|
||||
QtWarningMsg)
|
||||
|
||||
|
||||
def debug(debug_type):
|
||||
def excepthook(type_, value, tb):
|
||||
import traceback
|
||||
|
||||
# print the exception...
|
||||
traceback.print_exception(type_, value, tb)
|
||||
print
|
||||
# ...then start the debugger in post-mortem mode
|
||||
pdb.pm()
|
||||
|
||||
# we are NOT in interactive mode
|
||||
if not hasattr(sys, 'ps1') or sys.stderr.target.isatty():
|
||||
import pdb
|
||||
|
||||
from PyQt4.QtCore import pyqtRemoveInputHook
|
||||
pyqtRemoveInputHook()
|
||||
|
||||
if debug_type == 'exception':
|
||||
sys.excepthook = excepthook
|
||||
elif debug_type == 'program':
|
||||
pdb.set_trace()
|
||||
|
||||
|
||||
class CaseInsensitiveDict(dict):
|
||||
def __delitem__(self, key):
|
||||
for dictKey in self:
|
||||
if self.sameKey(key, dictKey):
|
||||
super(CaseInsensitiveDict, self).__delitem__(dictKey)
|
||||
return
|
||||
|
||||
raise KeyError(key)
|
||||
|
||||
def __contains__(self, key):
|
||||
for dictKey in self:
|
||||
if self.sameKey(key, dictKey):
|
||||
return True
|
||||
return False
|
||||
|
||||
def __getitem__(self, key):
|
||||
for dictKey, dictValue in self.items():
|
||||
if self.sameKey(key, dictKey):
|
||||
return dictValue
|
||||
|
||||
raise KeyError(key)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
for dictKey in self:
|
||||
if self.sameKey(key, dictKey):
|
||||
super(CaseInsensitiveDict, self).__setitem__(dictKey, value)
|
||||
return
|
||||
|
||||
super(CaseInsensitiveDict, self).__setitem__(key, value)
|
||||
|
||||
def sameKey(self, key, dictKey):
|
||||
if hasattr(key, 'lower'):
|
||||
key = key.lower()
|
||||
if hasattr(dictKey, 'lower'):
|
||||
dictKey = dictKey.lower()
|
||||
|
||||
if key == dictKey:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class MessageHandler(object):
|
||||
def __init__(self, verbose):
|
||||
self.verbose = verbose
|
||||
|
||||
def process(self, msgType, msg):
|
||||
now = QDateTime.currentDateTime().toString(Qt.ISODate)
|
||||
|
||||
if msgType == QtDebugMsg:
|
||||
if self.verbose:
|
||||
print '%s [DEBUG] %s' % (now, msg)
|
||||
elif msgType == QtWarningMsg:
|
||||
print >> sys.stderr, '%s [WARNING] %s' % (now, msg)
|
||||
elif msgType == QtCriticalMsg:
|
||||
print >> sys.stderr, '%s [CRITICAL] %s' % (now, msg)
|
||||
elif msgType == QtFatalMsg:
|
||||
print >> sys.stderr, '%s [FATAL] %s' % (now, msg)
|
||||
|
||||
|
||||
class SafeStreamFilter(object):
|
||||
'''Convert string to something safe'''
|
||||
def __init__(self, target):
|
||||
self.target = target
|
||||
self.encoding = self.encode_to = self.encoding_sys = self.target.encoding or 'utf-8'
|
||||
self.errors = 'replace'
|
||||
|
||||
def write(self, s):
|
||||
s = self.encode(s)
|
||||
self.target.write(s)
|
||||
|
||||
def flush(self):
|
||||
self.target.flush()
|
||||
|
||||
def encode(self, s):
|
||||
return s.encode(self.encode_to, self.errors)
|
||||
|
||||
|
||||
class QPyFile(QFile):
|
||||
'''Simple subclass of QFile which supports the context manager
|
||||
|
||||
It also wraps methods that require/return some foreign data type,
|
||||
such as QByteArray.
|
||||
'''
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.close()
|
||||
|
||||
def __init__(self, filename, mode='r'):
|
||||
super(QPyFile, self).__init__(filename)
|
||||
|
||||
modeMap = {
|
||||
'r': QFile.ReadOnly,
|
||||
'r+': QFile.ReadOnly | QFile.WriteOnly,
|
||||
'w': QFile.WriteOnly | QFile.Truncate,
|
||||
'w+': QFile.WriteOnly | QFile.ReadOnly | QFile.Truncate,
|
||||
'a': QFile.Append,
|
||||
'a+': QFile.Append | QFile.ReadOnly
|
||||
}
|
||||
|
||||
flags = QFile.NotOpen
|
||||
for key, flag in modeMap.items():
|
||||
if key in mode:
|
||||
flags = flags | flag
|
||||
|
||||
if not self.open(flags):
|
||||
raise IOError("Could not open file: '%s'" % self.fileName())
|
||||
|
||||
def peek(self, maxlen):
|
||||
return str(super(QPyFile, self).peek(maxlen))
|
||||
|
||||
def readAll(self):
|
||||
return str(super(QPyFile, self).readAll())
|
||||
|
||||
def write(self, data):
|
||||
return super(QPyFile, self).write(QByteArray(data))
|
|
@ -1,572 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import codecs
|
||||
import os
|
||||
import sys
|
||||
from cStringIO import StringIO
|
||||
from math import ceil, floor
|
||||
|
||||
import sip
|
||||
from PyQt4.QtCore import (pyqtProperty, pyqtSignal, pyqtSlot, QBuffer,
|
||||
QByteArray, QDir, QEvent, QEventLoop, QFileInfo,
|
||||
QObject, QPoint, QRect, QSize, QSizeF, Qt, QUrl,
|
||||
qDebug)
|
||||
from PyQt4.QtGui import (QApplication, QDesktopServices, QImage,
|
||||
QMouseEvent, QPainter, QPalette, QPrinter,
|
||||
QRegion, qRgba)
|
||||
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
|
||||
from PyQt4.QtWebKit import QWebPage, QWebSettings
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
qDebug('PIL not found! Saving to gif files will be disabled.')
|
||||
|
||||
from csconverter import CSConverter
|
||||
from networkaccessmanager import NetworkAccessManager
|
||||
from plugincontroller import do_action
|
||||
|
||||
|
||||
def injectJsInFrame(filePath, scriptEncoding, libraryPath, targetFrame, startingScript=False):
|
||||
try:
|
||||
# if file doesn't exist in the CWD, use the lookup
|
||||
if not os.path.exists(filePath):
|
||||
filePath = os.path.join(libraryPath, filePath)
|
||||
|
||||
try:
|
||||
with codecs.open(filePath, encoding=scriptEncoding) as f:
|
||||
script = f.read()
|
||||
except UnicodeError as e:
|
||||
sys.exit("%s in '%s'" % (e, filePath))
|
||||
|
||||
if script.startswith('#!') and not filePath.lower().endswith('.coffee'):
|
||||
script = '//' + script
|
||||
|
||||
if filePath.lower().endswith('.coffee'):
|
||||
result = CSConverter().convert(script)
|
||||
if not result[0]:
|
||||
if startingScript:
|
||||
sys.exit("%s: '%s'" % (result[1], filePath))
|
||||
else:
|
||||
qDebug("%s: '%s'" % (result[1], filePath))
|
||||
script = ''
|
||||
else:
|
||||
script = result[1]
|
||||
|
||||
targetFrame.evaluateJavaScript(script)
|
||||
return True
|
||||
except IOError as (_, e):
|
||||
qDebug("%s: '%s'" % (e, filePath))
|
||||
return False
|
||||
|
||||
|
||||
class CustomPage(QWebPage):
|
||||
def __init__(self, parent):
|
||||
super(CustomPage, self).__init__(parent)
|
||||
|
||||
self.m_userAgent = QWebPage.userAgentForUrl(self, QUrl())
|
||||
|
||||
self.m_uploadFile = ''
|
||||
|
||||
do_action('CustomPageInit')
|
||||
|
||||
def chooseFile(self, originatingFrame, oldFile):
|
||||
return self.m_uploadFile
|
||||
|
||||
def shouldInterruptJavaScript(self):
|
||||
QApplication.processEvents(QEventLoop.AllEvents, 42)
|
||||
return False
|
||||
|
||||
def javaScriptAlert(self, originatingFrame, msg):
|
||||
self.parent().javaScriptAlertSent.emit(msg)
|
||||
|
||||
def javaScriptConsoleMessage(self, message, lineNumber, sourceID):
|
||||
self.parent().javaScriptConsoleMessageSent.emit(message, lineNumber, sourceID)
|
||||
|
||||
def userAgentForUrl(self, url):
|
||||
return self.m_userAgent
|
||||
|
||||
do_action('CustomPage')
|
||||
|
||||
|
||||
class WebPage(QObject):
|
||||
initialized = pyqtSignal()
|
||||
javaScriptAlertSent = pyqtSignal(str)
|
||||
javaScriptConsoleMessageSent = pyqtSignal(str, int, str)
|
||||
loadFinished = pyqtSignal(str)
|
||||
loadStarted = pyqtSignal()
|
||||
resourceReceived = pyqtSignal('QVariantMap')
|
||||
resourceRequested = pyqtSignal('QVariantMap')
|
||||
|
||||
blankHtml = '<html><head></head><body></body></html>'
|
||||
|
||||
def __init__(self, parent, args):
|
||||
super(WebPage, self).__init__(parent)
|
||||
|
||||
# variable declarations
|
||||
self.m_paperSize = {}
|
||||
self.m_clipRect = QRect()
|
||||
self.m_libraryPath = ''
|
||||
self.m_scrollPosition = QPoint()
|
||||
|
||||
self.setObjectName('WebPage')
|
||||
self.m_webPage = CustomPage(self)
|
||||
self.m_mainFrame = self.m_webPage.mainFrame()
|
||||
self.m_webPage.mainFrame().setHtml(self.blankHtml)
|
||||
|
||||
self.m_mainFrame.javaScriptWindowObjectCleared.connect(self.initialized)
|
||||
self.m_webPage.loadStarted.connect(self.loadStarted, Qt.QueuedConnection)
|
||||
self.m_webPage.loadFinished.connect(self.finish, Qt.QueuedConnection)
|
||||
|
||||
# Start with transparent background
|
||||
palette = self.m_webPage.palette()
|
||||
palette.setBrush(QPalette.Base, Qt.transparent)
|
||||
self.m_webPage.setPalette(palette)
|
||||
|
||||
# Page size does not need to take scrollbars into account
|
||||
self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
|
||||
self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
|
||||
|
||||
self.m_webPage.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True)
|
||||
self.m_webPage.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation))
|
||||
self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True)
|
||||
self.m_webPage.settings().setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True)
|
||||
self.m_webPage.settings().setOfflineWebApplicationCachePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation))
|
||||
self.m_webPage.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True)
|
||||
self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageEnabled, True)
|
||||
self.m_webPage.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation))
|
||||
|
||||
# Custom network access manager to allow traffic monitoring
|
||||
self.m_networkAccessManager = NetworkAccessManager(self.parent(), args)
|
||||
self.m_webPage.setNetworkAccessManager(self.m_networkAccessManager)
|
||||
self.m_networkAccessManager.resourceRequested.connect(self.resourceRequested)
|
||||
self.m_networkAccessManager.resourceReceived.connect(self.resourceReceived)
|
||||
|
||||
self.m_webPage.setViewportSize(QSize(400, 300))
|
||||
|
||||
do_action('WebPageInit')
|
||||
|
||||
def applySettings(self, defaults):
|
||||
opt = self.m_webPage.settings()
|
||||
|
||||
opt.setAttribute(QWebSettings.AutoLoadImages, defaults['loadImages'])
|
||||
opt.setAttribute(QWebSettings.PluginsEnabled, defaults['loadPlugins'])
|
||||
opt.setAttribute(QWebSettings.JavascriptEnabled, defaults['javascriptEnabled'])
|
||||
opt.setAttribute(QWebSettings.XSSAuditingEnabled, defaults['XSSAuditingEnabled'])
|
||||
opt.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, defaults['localToRemoteUrlAccessEnabled'])
|
||||
|
||||
if 'userAgent' in defaults:
|
||||
self.m_webPage.m_userAgent = defaults['userAgent']
|
||||
|
||||
if 'userName' in defaults:
|
||||
self.m_networkAccessManager.m_userName = defaults['userName']
|
||||
|
||||
if 'password' in defaults:
|
||||
self.m_networkAccessManager.m_password = defaults['password']
|
||||
|
||||
def finish(self, ok):
|
||||
status = 'success' if ok else 'fail'
|
||||
self.loadFinished.emit(status)
|
||||
|
||||
def mainFrame(self):
|
||||
return self.m_mainFrame
|
||||
|
||||
def renderGif(self, image, fileName):
|
||||
try:
|
||||
Image
|
||||
except NameError:
|
||||
return False
|
||||
|
||||
buffer_ = QBuffer()
|
||||
buffer_.open(QBuffer.ReadWrite)
|
||||
image.save(buffer_, 'PNG')
|
||||
|
||||
stream = StringIO()
|
||||
stream.write(buffer_.data())
|
||||
buffer_.close()
|
||||
stream.seek(0)
|
||||
pilimg = Image.open(stream)
|
||||
|
||||
# use the adaptive quantizer instead of the web quantizer; eases off of grainy images
|
||||
pilimg = pilimg.convert('RGB').convert('P', palette=Image.ADAPTIVE)
|
||||
|
||||
try:
|
||||
pilimg.save(fileName)
|
||||
return True
|
||||
except IOError as (_, e):
|
||||
qDebug("WebPage.renderGif - %s: '%s'" % (e, fileName))
|
||||
return False
|
||||
|
||||
def renderImage(self):
|
||||
contentsSize = self.m_mainFrame.contentsSize()
|
||||
contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y())
|
||||
frameRect = QRect(QPoint(0, 0), contentsSize)
|
||||
if not self.m_clipRect.isEmpty():
|
||||
frameRect = self.m_clipRect
|
||||
|
||||
viewportSize = self.m_webPage.viewportSize()
|
||||
self.m_webPage.setViewportSize(contentsSize)
|
||||
|
||||
image = QImage(frameRect.size(), QImage.Format_ARGB32)
|
||||
image.fill(qRgba(255, 255, 255, 0))
|
||||
|
||||
painter = QPainter()
|
||||
|
||||
# We use tiling approach to work-around Qt software rasterizer bug
|
||||
# when dealing with very large paint device.
|
||||
# See http://code.google.com/p/phantomjs/issues/detail?id=54.
|
||||
tileSize = 4096
|
||||
htiles = (image.width() + tileSize - 1) / tileSize
|
||||
vtiles = (image.height() + tileSize - 1) / tileSize
|
||||
for x in range(htiles):
|
||||
for y in range(vtiles):
|
||||
tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32)
|
||||
tileBuffer.fill(qRgba(255, 255, 255, 0))
|
||||
|
||||
# Render the web page onto the small tile first
|
||||
painter.begin(tileBuffer)
|
||||
painter.setRenderHint(QPainter.Antialiasing, True)
|
||||
painter.setRenderHint(QPainter.TextAntialiasing, True)
|
||||
painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
|
||||
painter.translate(-frameRect.left(), -frameRect.top())
|
||||
painter.translate(-x * tileSize, -y * tileSize)
|
||||
self.m_mainFrame.render(painter, QRegion(frameRect))
|
||||
painter.end()
|
||||
|
||||
# Copy the tile to the main buffer
|
||||
painter.begin(image)
|
||||
painter.setCompositionMode(QPainter.CompositionMode_Source)
|
||||
painter.drawImage(x * tileSize, y * tileSize, tileBuffer)
|
||||
painter.end()
|
||||
|
||||
self.m_webPage.setViewportSize(viewportSize)
|
||||
return image
|
||||
|
||||
# Different defaults.
|
||||
# OSX: 72, X11: 75(?), Windows: 96
|
||||
pdf_dpi = 72
|
||||
def renderPdf(self, fileName):
|
||||
p = QPrinter()
|
||||
p.setOutputFormat(QPrinter.PdfFormat)
|
||||
p.setOutputFileName(fileName)
|
||||
p.setResolution(self.pdf_dpi)
|
||||
paperSize = self.m_paperSize
|
||||
|
||||
if not len(paperSize):
|
||||
pageSize = QSize(self.m_webPage.mainFrame().contentsSize())
|
||||
paperSize['width'] = str(pageSize.width()) + 'px'
|
||||
paperSize['height'] = str(pageSize.height()) + 'px'
|
||||
paperSize['border'] = '0px'
|
||||
|
||||
if paperSize.get('width') and paperSize.get('height'):
|
||||
sizePt = QSizeF(ceil(self.stringToPointSize(paperSize['width'])),
|
||||
ceil(self.stringToPointSize(paperSize['height'])))
|
||||
p.setPaperSize(sizePt, QPrinter.Point)
|
||||
elif 'format' in paperSize:
|
||||
orientation = QPrinter.Landscape if paperSize.get('orientation') and paperSize['orientation'].lower() == 'landscape' else QPrinter.Portrait
|
||||
orientation = QPrinter.Orientation(orientation)
|
||||
p.setOrientation(orientation)
|
||||
|
||||
formats = {
|
||||
'A0': QPrinter.A0,
|
||||
'A1': QPrinter.A1,
|
||||
'A2': QPrinter.A2,
|
||||
'A3': QPrinter.A3,
|
||||
'A4': QPrinter.A4,
|
||||
'A5': QPrinter.A5,
|
||||
'A6': QPrinter.A6,
|
||||
'A7': QPrinter.A7,
|
||||
'A8': QPrinter.A8,
|
||||
'A9': QPrinter.A9,
|
||||
'B0': QPrinter.B0,
|
||||
'B1': QPrinter.B1,
|
||||
'B2': QPrinter.B2,
|
||||
'B3': QPrinter.B3,
|
||||
'B4': QPrinter.B4,
|
||||
'B5': QPrinter.B5,
|
||||
'B6': QPrinter.B6,
|
||||
'B7': QPrinter.B7,
|
||||
'B8': QPrinter.B8,
|
||||
'B9': QPrinter.B9,
|
||||
'B10': QPrinter.B10,
|
||||
'C5E': QPrinter.C5E,
|
||||
'Comm10E': QPrinter.Comm10E,
|
||||
'DLE': QPrinter.DLE,
|
||||
'Executive': QPrinter.Executive,
|
||||
'Folio': QPrinter.Folio,
|
||||
'Ledger': QPrinter.Ledger,
|
||||
'Legal': QPrinter.Legal,
|
||||
'Letter': QPrinter.Letter,
|
||||
'Tabloid': QPrinter.Tabloid
|
||||
}
|
||||
|
||||
p.setPaperSize(QPrinter.A4) # fallback
|
||||
for format_, size in formats.items():
|
||||
if format_.lower() == paperSize['format'].lower():
|
||||
p.setPaperSize(size)
|
||||
break
|
||||
else:
|
||||
return False
|
||||
|
||||
border = floor(self.stringToPointSize(paperSize['border'])) if paperSize.get('border') else 0
|
||||
p.setPageMargins(border, border, border, border, QPrinter.Point)
|
||||
|
||||
self.m_webPage.mainFrame().print_(p)
|
||||
return True
|
||||
|
||||
def stringToPointSize(self, string):
|
||||
units = (
|
||||
('mm', 72 / 25.4),
|
||||
('cm', 72 / 2.54),
|
||||
('in', 72.0),
|
||||
('px', 72.0 / self.pdf_dpi / 2.54),
|
||||
('', 72.0 / self.pdf_dpi / 2.54)
|
||||
)
|
||||
|
||||
for unit, format_ in units:
|
||||
if string.endswith(unit):
|
||||
value = string.rstrip(unit)
|
||||
return float(value) * format_
|
||||
return 0
|
||||
|
||||
def userAgent(self):
|
||||
return self.m_webPage.m_userAgent
|
||||
|
||||
##
|
||||
# Properties and methods exposed to JavaScript
|
||||
##
|
||||
|
||||
@pyqtSlot(str)
|
||||
def _appendScriptElement(self, scriptUrl):
|
||||
self.m_mainFrame.evaluateJavaScript('''
|
||||
var el = document.createElement('script');
|
||||
el.onload = function() { alert('%(scriptUrl)s'); };
|
||||
el.src = '%(scriptUrl)s';
|
||||
document.body.appendChild(el);
|
||||
''' % {'scriptUrl': scriptUrl})
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def clipRect(self):
|
||||
clipRect = self.m_clipRect
|
||||
result = {
|
||||
'width': clipRect.width(),
|
||||
'height': clipRect.height(),
|
||||
'top': clipRect.top(),
|
||||
'left': clipRect.left()
|
||||
}
|
||||
return result
|
||||
|
||||
@clipRect.setter
|
||||
def clipRect(self, size):
|
||||
sizes = {'width': 0, 'height': 0, 'top': 0, 'left': 0}
|
||||
for item in sizes:
|
||||
try:
|
||||
sizes[item] = int(size[item])
|
||||
if sizes[item] < 0:
|
||||
if item not in ('top', 'left'):
|
||||
sizes[item] = 0
|
||||
except (KeyError, ValueError):
|
||||
sizes[item] = self.clipRect[item]
|
||||
|
||||
self.m_clipRect = QRect(sizes['left'], sizes['top'], sizes['width'], sizes['height'])
|
||||
|
||||
@pyqtProperty(str)
|
||||
def content(self):
|
||||
return self.m_mainFrame.toHtml()
|
||||
|
||||
@content.setter
|
||||
def content(self, content):
|
||||
self.m_mainFrame.setHtml(content)
|
||||
|
||||
@pyqtSlot(str, result='QVariant')
|
||||
def evaluate(self, code):
|
||||
function = '(%s)()' % code
|
||||
return self.m_mainFrame.evaluateJavaScript(function)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def injectJs(self, filePath):
|
||||
return injectJsInFrame(filePath, self.parent().m_scriptEncoding.encoding, self.m_libraryPath, self.m_mainFrame)
|
||||
|
||||
@pyqtProperty(str)
|
||||
def libraryPath(self):
|
||||
return self.m_libraryPath
|
||||
|
||||
@libraryPath.setter
|
||||
def libraryPath(self, dirPath):
|
||||
self.m_libraryPath = dirPath
|
||||
|
||||
@pyqtSlot(str, str, 'QVariantMap')
|
||||
@pyqtSlot(str, 'QVariantMap', 'QVariantMap')
|
||||
def openUrl(self, address, op, settings):
|
||||
operation = op
|
||||
body = QByteArray()
|
||||
|
||||
self.applySettings(settings)
|
||||
self.m_webPage.triggerAction(QWebPage.Stop)
|
||||
|
||||
if type(op) is dict:
|
||||
operation = op.get('operation')
|
||||
body = QByteArray(op.get('data', ''))
|
||||
|
||||
if operation == '':
|
||||
operation = 'get'
|
||||
|
||||
networkOp = QNetworkAccessManager.CustomOperation
|
||||
operation = operation.lower()
|
||||
if operation == 'get':
|
||||
networkOp = QNetworkAccessManager.GetOperation
|
||||
elif operation == 'head':
|
||||
networkOp = QNetworkAccessManager.HeadOperation
|
||||
elif operation == 'put':
|
||||
networkOp = QNetworkAccessManager.PutOperation
|
||||
elif operation == 'post':
|
||||
networkOp = QNetworkAccessManager.PostOperation
|
||||
elif operation == 'delete':
|
||||
networkOp = QNetworkAccessManager.DeleteOperation
|
||||
|
||||
if networkOp == QNetworkAccessManager.CustomOperation:
|
||||
self.m_mainFrame.evaluateJavaScript('console.error("Unknown network operation: %s");' % operation)
|
||||
return
|
||||
|
||||
if address.lower() == 'about:blank':
|
||||
self.m_mainFrame.setHtml(self.blankHtml)
|
||||
else:
|
||||
self.m_mainFrame.load(QNetworkRequest(QUrl(address)), networkOp, body)
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def paperSize(self):
|
||||
return self.m_paperSize
|
||||
|
||||
@paperSize.setter
|
||||
def paperSize(self, size):
|
||||
self.m_paperSize = size
|
||||
|
||||
@pyqtSlot()
|
||||
def release(self):
|
||||
self.parent().m_pages.remove(self)
|
||||
sip.delete(self)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def render(self, fileName):
|
||||
if self.m_mainFrame.contentsSize() == '':
|
||||
return False
|
||||
|
||||
fileInfo = QFileInfo(fileName)
|
||||
path = QDir()
|
||||
path.mkpath(fileInfo.absolutePath())
|
||||
|
||||
if fileName.lower().endswith('.pdf'):
|
||||
return self.renderPdf(fileName)
|
||||
|
||||
image = self.renderImage()
|
||||
if fileName.lower().endswith('.gif'):
|
||||
return self.renderGif(image, fileName)
|
||||
|
||||
return image.save(fileName)
|
||||
|
||||
@pyqtSlot(str, 'QVariant', 'QVariant')
|
||||
def sendEvent(self, type_, arg1, arg2):
|
||||
type_ = type_.lower()
|
||||
|
||||
if type_ in ('mousedown', 'mouseup', 'mousemove'):
|
||||
eventType = QMouseEvent.Type(QEvent.None)
|
||||
button = Qt.MouseButton(Qt.LeftButton)
|
||||
buttons = Qt.MouseButtons(Qt.LeftButton)
|
||||
|
||||
if type_ == 'mousedown':
|
||||
eventType = QEvent.MouseButtonPress
|
||||
elif type_ == 'mouseup':
|
||||
eventType = QEvent.MouseButtonRelease
|
||||
elif type_ == 'mousemove':
|
||||
eventType = QEvent.MouseMove
|
||||
button = buttons = Qt.NoButton
|
||||
|
||||
assert eventType != QEvent.None
|
||||
|
||||
event = QMouseEvent(eventType, QPoint(arg1, arg2), button, buttons, Qt.NoModifier)
|
||||
QApplication.postEvent(self.m_webPage, event)
|
||||
QApplication.processEvents()
|
||||
|
||||
return
|
||||
|
||||
if type_ == 'click':
|
||||
self.sendEvent('mousedown', arg1, arg2)
|
||||
self.sendEvent('mouseup', arg1, arg2)
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def scrollPosition(self):
|
||||
scroll = self.m_scrollPosition
|
||||
result = {
|
||||
'left': scroll.x(),
|
||||
'top': scroll.y()
|
||||
}
|
||||
return result
|
||||
|
||||
@scrollPosition.setter
|
||||
def scrollPosition(self, size):
|
||||
positions = {'left': 0, 'top': 0}
|
||||
for item in positions:
|
||||
try:
|
||||
positions[item] = int(size[item])
|
||||
if positions[item] < 0:
|
||||
positions[item] = 0
|
||||
except (KeyError, ValueError):
|
||||
positions[item] = self.scrollPosition[item]
|
||||
self.m_scrollPosition = QPoint(positions['left'], positions['top'])
|
||||
self.m_mainFrame.setScrollPosition(self.m_scrollPosition)
|
||||
|
||||
@pyqtSlot(str, str)
|
||||
def uploadFile(self, selector, fileName):
|
||||
el = self.m_mainFrame.findFirstElement(selector)
|
||||
if el.isNull():
|
||||
return
|
||||
|
||||
self.m_webPage.m_uploadFile = fileName
|
||||
el.evaluateJavaScript('''
|
||||
(function (el) {
|
||||
var ev = document.createEvent('MouseEvents');
|
||||
ev.initEvent('click', true, true);
|
||||
el.dispatchEvent(ev);
|
||||
})(this)
|
||||
''')
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def viewportSize(self):
|
||||
size = self.m_webPage.viewportSize()
|
||||
result = {
|
||||
'width': size.width(),
|
||||
'height': size.height()
|
||||
}
|
||||
return result
|
||||
|
||||
@viewportSize.setter
|
||||
def viewportSize(self, size):
|
||||
sizes = {'width': 0, 'height': 0}
|
||||
for item in sizes:
|
||||
try:
|
||||
sizes[item] = int(size[item])
|
||||
if sizes[item] < 0:
|
||||
sizes[item] = 0
|
||||
except (KeyError, ValueError):
|
||||
sizes[item] = self.viewportSize[item]
|
||||
|
||||
self.m_webPage.setViewportSize(QSize(sizes['width'], sizes['height']))
|
||||
|
||||
do_action('WebPage')
|
|
@ -1,312 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import socket
|
||||
from BaseHTTPServer import (__version__ as __server_version__,
|
||||
BaseHTTPRequestHandler, HTTPServer)
|
||||
from cStringIO import StringIO
|
||||
from threading import Thread
|
||||
from SocketServer import ThreadingMixIn
|
||||
from urlparse import urlparse
|
||||
|
||||
import sip
|
||||
from PyQt4.QtCore import (pyqtProperty, pyqtSignal, pyqtSlot, Q_ARG,
|
||||
qDebug, QMetaObject, QObject, Qt, QThread)
|
||||
|
||||
from __init__ import __version__
|
||||
from plugincontroller import do_action
|
||||
from utils import CaseInsensitiveDict
|
||||
|
||||
|
||||
servers = []
|
||||
|
||||
|
||||
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
|
||||
pass
|
||||
|
||||
|
||||
class WebServer(QObject):
|
||||
newRequest = pyqtSignal(QObject, QObject)
|
||||
|
||||
def __init__(self, parent):
|
||||
super(WebServer, self).__init__(parent)
|
||||
|
||||
self.setObjectName('WebServer')
|
||||
|
||||
self.m_port = 0
|
||||
self.httpd = None
|
||||
|
||||
servers.append(self)
|
||||
|
||||
do_action('WebServerInit')
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
|
||||
@pyqtSlot()
|
||||
def close(self):
|
||||
if self.httpd is not None:
|
||||
self.httpd.shutdown()
|
||||
self.m_port = 0
|
||||
|
||||
@pyqtSlot(int, result=bool)
|
||||
def listenOnPort(self, port):
|
||||
try:
|
||||
self.httpd = ThreadingHTTPServer(('localhost', port), WebServerHandler)
|
||||
Thread(target=self.httpd.serve_forever).start()
|
||||
except socket.error as (_, e):
|
||||
qDebug('WebServer.listenOnPort - %s' % e)
|
||||
self.m_port = 0
|
||||
return False
|
||||
else:
|
||||
self.m_port = port
|
||||
return True
|
||||
|
||||
@pyqtProperty(int)
|
||||
def port(self):
|
||||
return self.m_port
|
||||
|
||||
@pyqtSlot()
|
||||
def release(self):
|
||||
self.close()
|
||||
servers.remove(self)
|
||||
self.parent().m_servers.remove(self)
|
||||
sip.delete(self)
|
||||
|
||||
do_action('WebServer')
|
||||
|
||||
|
||||
class WebServerHandler(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
server_version = 'BaseHTTP/%s PyPhantomJS/%s' % (__server_version__, __version__)
|
||||
|
||||
def handle_one_request(self):
|
||||
'''Handle a single HTTP request.
|
||||
|
||||
A patch to the request handling:
|
||||
|
||||
* This removes the functionality which calls do_X(),
|
||||
and simply calls our handleRequest() directly.
|
||||
* If do_X() didn't exist, a 501 unsupported
|
||||
method error would be returned. Since we patched
|
||||
that out as well, the user can actually handle when
|
||||
a request is or isn't valid through the code.
|
||||
* Then we handle the request and response.
|
||||
'''
|
||||
try:
|
||||
self.raw_requestline = self.rfile.readline(65537)
|
||||
if len(self.raw_requestline) > 65536:
|
||||
self.requestline = ''
|
||||
self.request_version = ''
|
||||
self.command = ''
|
||||
self.send_error(414)
|
||||
return
|
||||
if not self.raw_requestline:
|
||||
self.close_connection = 1
|
||||
return
|
||||
if not self.parse_request():
|
||||
# An error code has been sent, just exit
|
||||
return
|
||||
|
||||
# these variables must get (re)set on every request
|
||||
# for handleRequest(), due to the HTTP/1.1 nature of
|
||||
# keepalive, which seems to keep a constant running
|
||||
# instance of this class
|
||||
self.m_handleResponse = True
|
||||
self.m_headers = CaseInsensitiveDict()
|
||||
self.m_statusCode = 200
|
||||
self.m_wfile = StringIO()
|
||||
|
||||
self.handleRequest()
|
||||
|
||||
# some methods handle the response on their own instead
|
||||
if self.m_handleResponse:
|
||||
self.handleResponse()
|
||||
|
||||
self.wfile.flush() #actually send the response if not already done.
|
||||
except socket.timeout, e:
|
||||
#a read or a write timed out. Discard this connection
|
||||
self.log_error("Request timed out: %r", e)
|
||||
self.close_connection = 1
|
||||
return
|
||||
|
||||
def handleResponse(self):
|
||||
# send response code with response text (ex. 200 OK)
|
||||
self.send_response(self.m_statusCode, self.responses[self.m_statusCode][0])
|
||||
|
||||
# send all headers
|
||||
for name, value in self.m_headers.items():
|
||||
self.send_header(name, value)
|
||||
|
||||
# send content-length if not already sent
|
||||
if self.protocol_version == 'HTTP/1.1':
|
||||
if 'content-length' not in self.m_headers:
|
||||
if self.m_statusCode >= 200 and self.m_statusCode not in (204, 304):
|
||||
self.send_header('Content-Length', self.m_wfile.tell())
|
||||
|
||||
self.end_headers() #finish sending the headers
|
||||
|
||||
# check if body should be written to response
|
||||
if self.command != 'HEAD' and self.m_statusCode >= 200 and self.m_statusCode not in (204, 304):
|
||||
self.wfile.write(self.m_wfile.getvalue()) #write body to page
|
||||
|
||||
def handleRequest(self):
|
||||
request = WebServerRequest(self)
|
||||
response = WebServerResponse(self)
|
||||
|
||||
for server in servers:
|
||||
# verify which server this request is for
|
||||
if self.server == server.httpd:
|
||||
connectionType = Qt.BlockingQueuedConnection
|
||||
if QThread.currentThread() == server.thread():
|
||||
connectionType = Qt.DirectConnection
|
||||
|
||||
QMetaObject.invokeMethod(server, 'newRequest', connectionType,
|
||||
Q_ARG(WebServerRequest, request),
|
||||
Q_ARG(WebServerResponse, response))
|
||||
break
|
||||
|
||||
def log_message(self, format, *args):
|
||||
qDebug("%s - - %s" % (self.address_string(),
|
||||
format % args))
|
||||
|
||||
do_action('WebServerHandler')
|
||||
|
||||
|
||||
class WebServerResponse(QObject):
|
||||
def __init__(self, conn):
|
||||
super(WebServerResponse, self).__init__()
|
||||
|
||||
self.setObjectName('WebServerResponse')
|
||||
|
||||
self.m_conn = conn
|
||||
|
||||
do_action('WebServerResponseInit')
|
||||
|
||||
@pyqtSlot(str, result=str)
|
||||
def header(self, name):
|
||||
return self.m_conn.m_headers.get(name, '')
|
||||
|
||||
@pyqtProperty('QVariantMap')
|
||||
def headers(self):
|
||||
return self.m_conn.m_headers
|
||||
|
||||
@headers.setter
|
||||
def headers(self, headers):
|
||||
self.m_conn.m_headers = CaseInsensitiveDict(headers)
|
||||
|
||||
@pyqtSlot(int)
|
||||
@pyqtSlot(int, str)
|
||||
def sendError(self, code, message=None):
|
||||
self.m_conn.send_error(code, message)
|
||||
self.m_conn.m_handleResponse = False
|
||||
|
||||
@pyqtSlot(str, str)
|
||||
def setHeader(self, name, value):
|
||||
self.m_conn.m_headers[name] = value
|
||||
|
||||
@pyqtProperty(int)
|
||||
def statusCode(self):
|
||||
return self.m_conn.m_statusCode
|
||||
|
||||
@statusCode.setter
|
||||
def statusCode(self, code):
|
||||
self.m_conn.m_statusCode = code
|
||||
|
||||
@pyqtSlot(str)
|
||||
def write(self, body):
|
||||
self.m_conn.m_wfile.write(body)
|
||||
|
||||
@pyqtSlot(int, 'QVariantMap')
|
||||
def writeHead(self, code, headers):
|
||||
self.m_conn.m_statusCode = code
|
||||
self.m_conn.m_headers = CaseInsensitiveDict(headers)
|
||||
|
||||
do_action('WebServerResponse')
|
||||
|
||||
|
||||
class WebServerRequest(QObject):
|
||||
def __init__(self, request):
|
||||
super(WebServerRequest, self).__init__()
|
||||
|
||||
self.setObjectName('WebServerRequest')
|
||||
|
||||
self.m_request = request
|
||||
self.m_headerNames = list(request.headers)
|
||||
self.m_headers = CaseInsensitiveDict(request.headers)
|
||||
self.m_numHeaders = len(request.headers)
|
||||
|
||||
do_action('WebServerRequestInit')
|
||||
|
||||
@pyqtSlot(int, result=str)
|
||||
def headerName(self, header):
|
||||
if header <= self.m_numHeaders:
|
||||
return self.m_headerNames[header]
|
||||
return ''
|
||||
|
||||
@pyqtProperty(int)
|
||||
def headers(self):
|
||||
return self.m_numHeaders
|
||||
|
||||
@pyqtSlot(int, result=str)
|
||||
def headerValue(self, header):
|
||||
if header <= self.m_numHeaders:
|
||||
return self.m_request.headers[self.m_headerNames[header]]
|
||||
return ''
|
||||
|
||||
@pyqtProperty(str)
|
||||
def httpVersion(self):
|
||||
return self.m_request.request_version[-3:]
|
||||
|
||||
@pyqtProperty(int)
|
||||
def isSSL(self):
|
||||
return 0
|
||||
|
||||
@pyqtProperty(str)
|
||||
def method(self):
|
||||
return self.m_request.command
|
||||
|
||||
@pyqtProperty(str)
|
||||
def remoteIP(self):
|
||||
return self.m_request.client_address[0]
|
||||
|
||||
@pyqtProperty(int)
|
||||
def remotePort(self):
|
||||
return self.m_request.client_address[1]
|
||||
|
||||
@pyqtProperty(str)
|
||||
def remoteUser(self):
|
||||
try:
|
||||
return self.m_headers['REMOTE_USER']
|
||||
except KeyError:
|
||||
return ''
|
||||
|
||||
#@pyqtProperty(int)
|
||||
#def statusCode(self):
|
||||
# return self.m_request.status_code
|
||||
|
||||
@pyqtProperty(str)
|
||||
def url(self):
|
||||
return self.m_request.path
|
||||
|
||||
@pyqtProperty(str)
|
||||
def queryString(self):
|
||||
return urlparse(self.m_request.path).query
|
||||
|
||||
do_action('WebServerRequest')
|
|
@ -1,30 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
from runpy import run_module
|
||||
|
||||
# automatically convert Qt types by using api 2
|
||||
import sip
|
||||
for item in ('QDate', 'QDateTime', 'QString', 'QTextStream', 'QTime'
|
||||
'QUrl', 'QVariant'):
|
||||
sip.setapi(item, 2)
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_module('pyphantomjs.pyphantomjs', run_name='__main__')
|
|
@ -1,75 +0,0 @@
|
|||
'''
|
||||
This file is part of the PyPhantomJS project.
|
||||
|
||||
Copyright (C) 2011 James Roe <roejames12@hotmail.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
'''
|
||||
|
||||
import os
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
from pyphantomjs import __version__
|
||||
|
||||
|
||||
def read(fname):
|
||||
return open(os.path.join(os.path.dirname(__file__), fname)).read()
|
||||
|
||||
|
||||
README = read('README.md')
|
||||
INSTALL = read('INSTALL.md')
|
||||
|
||||
index = README.find('LICENSING')
|
||||
if index > -1:
|
||||
README = README[:index] + INSTALL + '\n\n' + README[index:]
|
||||
else:
|
||||
README += INSTALL
|
||||
|
||||
mainWarningPrinted = False
|
||||
mainWarning = ('\nWARNING: PyPhantomJS requires additional libraries, which were not found!\n'
|
||||
' Refer to the README or INSTALL file for installation information.\n')
|
||||
for module in ('PyQt4', 'PIL'):
|
||||
try:
|
||||
__import__(module)
|
||||
except ImportError:
|
||||
if not mainWarningPrinted:
|
||||
print mainWarning
|
||||
mainWarningPrinted = True
|
||||
print "* '%s' library not found" % module
|
||||
|
||||
|
||||
setup(
|
||||
name='PyPhantomJS',
|
||||
version=__version__,
|
||||
description='Minimalistic, headless, WebKit-based, JavaScript-driven tool',
|
||||
long_description=README,
|
||||
url = 'https://github.com/Roejames12/phantomjs',
|
||||
license = 'GNU General Public License (GPL)',
|
||||
author='James Roe',
|
||||
author_email='roejames12@hotmail.com',
|
||||
packages=find_packages(),
|
||||
include_package_data=True,
|
||||
install_requires=['argparse'],
|
||||
scripts = ['scripts/pyphantomjs'],
|
||||
classifiers = [
|
||||
'Development Status :: 5 - Production/Stable',
|
||||
'Environment :: Console',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: GNU General Public License (GPL)',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python',
|
||||
'Topic :: Internet :: WWW/HTTP :: Browsers'
|
||||
],
|
||||
zip_safe=False
|
||||
)
|
Loading…
Reference in New Issue