├── .gitignore ├── AUTHORS ├── INSTALL.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── pyphantomjs ├── __init__.py ├── arguments.py ├── bootstrap.js ├── configurator.js ├── cookiejar.py ├── csconverter.py ├── encoding.py ├── filesystem.py ├── modules │ ├── fs.js │ ├── webpage.js │ └── webserver.js ├── networkaccessmanager.py ├── phantom.py ├── plugincontroller.py ├── plugins │ └── __init__.py ├── pyphantomjs.py ├── resources.py ├── resources.qrc ├── resources │ ├── coffee-script.js │ ├── pyphantomjs-icon.ico │ └── pyphantomjs-icon.png ├── tools │ ├── build_binary.py │ └── build_resources.sh ├── utils.py ├── webpage.py └── webserver.py ├── scripts └── pyphantomjs └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.pro.user* 3 | *.xcodeproj 4 | Makefile* 5 | bin/phantomjs 6 | *~ 7 | *.moc 8 | moc_* 9 | qrc_* 10 | *.o 11 | *.swp 12 | *.pyc 13 | debian/*.debhelper 14 | debian/files 15 | debian/*.log 16 | debian/*.substvars 17 | debian/*/ 18 | /deploy/qt-*.tar.gz 19 | /deploy/Qt-* 20 | 21 | # ignore ctags 22 | /tags 23 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Core Developers: 2 | 3 | James Roe 4 | 5 | Contributors: 6 | 7 | Francisco Souza 8 | Bryan Bishop 9 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | ### DEPENDENCIES 2 | --------------------------------- 3 | 4 | * Python >= 2.6 (< 3.x) 5 | * PyQt4 >= 4.8.0 6 | * Qt >= 4.7.0 7 | 8 | * python-argparse >= 1.2.1 (Python 2.6 only) 9 | * PIL (python-imaging-library) >= 1.1.7 (optional; for rendering to GIF) 10 | 11 | ### INSTALLING 12 | ------------------------- 13 | 14 | Windows 15 | 16 | > Download and install the required programs. 17 | > 18 | [Python](http://www.python.org/download/) 19 | [PyQt4](http://www.riverbankcomputing.co.uk/software/pyqt/download) 20 | > Qt4 - PyQt4 comes packaged with the Qt runtime library(s) 21 | > 22 | [python-argparse](http://pypi.python.org/pypi/argparse/) 23 | [PIL](http://www.pythonware.com/products/pil/) 24 | 25 | Ubuntu 26 | 27 | > Open a terminal window, and enter the command `sudo apt-get install python-qt4 python-imaging` 28 | > 29 | All the required packages should be automatically pulled in and installed. 30 | 31 | PyPi 32 | 33 | > You can also install the latest stable release from PyPi with `pip install pyphantomjs` 34 | Afterward, you can invoke the program with `pyphantomjs` 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include * 2 | exclude *.swp 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PyPhantomJS is a headless WebKit with JavaScript API, based on the [PhantomJS](http://www.phantomjs.org/) project. 2 | 3 | It has **fast** and **native** support for DOM handling, CSS selector, JSON, Canvas, SVG, and of course JavaScript. 4 | 5 | PyPhantomJS scripts can be written in JavaScript or [CoffeeScript](http://jashkenas.github.com/coffee-script/). 6 | 7 | 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: 8 | 9 | * running regression tests from command line 10 | * getting driving direction 11 | * showing weather forecast conditions 12 | * finding pizza in New York 13 | * looking up approximate location based on IP address 14 | * pulling the list of seasonal food 15 | * producing PDF version of a Wikipedia article 16 | * rasterizing SVG to image 17 | 18 | PyPhantomJS is written in PyQt4 and Python. It runs on Linux, Windows, and Mac OS X. 19 | Refer to the INSTALL file or Wiki links1 for more information. 20 | 21 | Do not forget to consult the concise API Reference2 22 | 23 | If you want to contribute, please read the Contribution Guides3 24 | 25 | You can find a list of downloadable plugins [here](http://dev.umaclan.com/projects/pyphantomjs/wiki/Plugins). 26 | 27 | If you would like to know how to make plugins, check out this [article](http://dev.umaclan.com/projects/pyphantomjs/wiki/Writing_plugins). 28 | 29 | 1: http://code.google.com/p/phantomjs/w/list 30 | 1: http://dev.umaclan.com/projects/pyphantomjs/wiki 31 | 2: http://dev.umaclan.com/projects/pyphantomjs/wiki/Api_reference 32 | 2: http://code.google.com/p/phantomjs/wiki/Interface 33 | 3: http://code.google.com/p/phantomjs/wiki/ContributionGuide 34 | 3: http://dev.umaclan.com/projects/pyphantomjs/wiki/Giving_back 35 | 36 | LICENSING 37 | ----------------------------- 38 | Copyright (C) 2011 James Roe <> 39 | Copyright (C) 2011-2012 PyPhantomJS authors (see AUTHORS file) 40 | 41 | PyPhantomJS is licensed with the GNU GPL v3. See the included file LICENSE for the licensing terms. 42 | 43 | ADDITIONAL INFO 44 | ----------------------------- 45 | This program is a port of PhantomJS to Python/PyQt4 (thus, PyPhantomJS). 46 | 47 | 1. We try to make PyPhantomJS to be as compatible with PhantomJS as possible, 48 | this means having the exact same features as they do. It happens to be fully 49 | compatible, with the exception of some very small things. 50 | 2. PyPhantomJS however, has a few differences as well: 51 | * Some of the features work a little differently than PhantomJS. 52 | In most of these cases, the features were only changed to improve their 53 | reliability and performance, so they work more often/better, and break less. 54 | * There may also be additional features present that aren't in PhantomJS. 55 | 3. For whatever reason, PyPhantomJS was deleted from the upstream PhantomJS library, 56 | so this separate repository was created. The old commit ids have been kept 57 | in tact to facilitate referencing back to the upstream versions. 58 | 59 | PhantomJS was written by Ariya Hidayat, and I'd like to give him a BIG thanks 60 | for all his work on PhantomJS! :) 61 | -------------------------------------------------------------------------------- /pyphantomjs/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | __version_info__ = (1, 5, 0) 21 | 22 | __version__ = '.'.join(map(str, __version_info__)) 23 | -------------------------------------------------------------------------------- /pyphantomjs/arguments.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import argparse 21 | import codecs 22 | import os 23 | import sys 24 | 25 | from PyQt4.QtCore import qInstallMsgHandler, QObject, qWarning 26 | from PyQt4.QtNetwork import QNetworkProxy 27 | from PyQt4.QtWebKit import QWebPage 28 | 29 | from __init__ import __version__ 30 | from plugincontroller import do_action 31 | from utils import debug, MessageHandler, QPyFile 32 | 33 | 34 | license = ''' 35 | PyPhantomJS Version %s 36 | 37 | Copyright (C) 2011 James Roe 38 | 39 | This program is free software: you can redistribute it and/or modify 40 | it under the terms of the GNU General Public License as published by 41 | the Free Software Foundation, either version 3 of the License, or 42 | (at your option) any later version. 43 | 44 | This program is distributed in the hope that it will be useful, 45 | but WITHOUT ANY WARRANTY; without even the implied warranty of 46 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 47 | GNU General Public License for more details. 48 | 49 | You should have received a copy of the GNU General Public License 50 | along with this program. If not, see . 51 | ''' % __version__ 52 | 53 | 54 | defaults = { 55 | 'cookiesFile': None, 56 | 'debug': None, 57 | 'diskCache': False, 58 | 'ignoreSslErrors': False, 59 | 'loadImages': True, 60 | 'loadPlugins': False, 61 | 'localToRemoteUrlAccessEnabled': False, 62 | 'maxDiskCacheSize': -1, 63 | 'outputEncoding': 'System', 64 | 'proxy': None, 65 | 'proxyType': QNetworkProxy.HttpProxy, 66 | 'scriptEncoding': 'utf-8', 67 | 'verbose': False 68 | } 69 | 70 | 71 | def argParser(): 72 | class YesOrNoAction(argparse.Action): 73 | '''Converts yes or no arguments to True/False respectively''' 74 | def __call__(self, parser, namespace, value, option_string=None): 75 | answer = True if value == 'yes' else False 76 | setattr(namespace, self.dest, answer) 77 | 78 | def proxyType(type_): 79 | if type_ == QNetworkProxy.HttpProxy: 80 | return 'http' 81 | elif type_ == QNetworkProxy.Socks5Proxy: 82 | return 'socks5' 83 | 84 | yesOrNo = lambda d: 'yes' if d else 'no' 85 | 86 | 87 | parser = argparse.ArgumentParser( 88 | description='Minimalistic headless WebKit-based JavaScript-driven tool', 89 | usage='%(prog)s [options] script.[js|coffee] [script argument [script argument ...]]', 90 | formatter_class=argparse.RawTextHelpFormatter 91 | ) 92 | 93 | parser.add_argument('script', metavar='script.[js|coffee]', nargs='?', 94 | help='The script to execute, and any args to pass to it' 95 | ) 96 | parser.add_argument('-v', '--version', 97 | action='version', version=license, 98 | help="show this program's version and license" 99 | ) 100 | 101 | program = parser.add_argument_group('program options') 102 | script = parser.add_argument_group('script options') 103 | debug = parser.add_argument_group('debug options') 104 | 105 | program.add_argument('--config', metavar='/path/to/config', 106 | help='Specifies path to a JSON-formatted config file' 107 | ) 108 | program.add_argument('--disk-cache', default=defaults['diskCache'], action=YesOrNoAction, 109 | choices=['yes', 'no'], 110 | help='Enable disk cache (default: %s)' % yesOrNo(defaults['diskCache']) 111 | ) 112 | program.add_argument('--ignore-ssl-errors', default=defaults['ignoreSslErrors'], action=YesOrNoAction, 113 | choices=['yes', 'no'], 114 | help='Ignore SSL errors (default: %s)' % yesOrNo(defaults['ignoreSslErrors']) 115 | ) 116 | program.add_argument('--max-disk-cache-size', default=defaults['maxDiskCacheSize'], metavar='size', type=int, 117 | help='Limits the size of disk cache (in KB)' 118 | ) 119 | program.add_argument('--output-encoding', default=defaults['outputEncoding'], metavar='encoding', 120 | help='Sets the encoding used for terminal output (default: %(default)s)' 121 | ) 122 | program.add_argument('--proxy', metavar='address:port', 123 | help='Set the network proxy' 124 | ) 125 | program.add_argument('--proxy-type', default=defaults['proxyType'], metavar='type', 126 | help='Set the network proxy type (default: %s)' % proxyType(defaults['proxyType']) 127 | ) 128 | program.add_argument('--script-encoding', default=defaults['scriptEncoding'], metavar='encoding', 129 | help='Sets the encoding used for scripts (default: %(default)s)' 130 | ) 131 | 132 | script.add_argument('--cookies-file', metavar='/path/to/cookies.txt', 133 | help='Sets the file name to store the persistent cookies' 134 | ) 135 | script.add_argument('--load-images', default=defaults['loadImages'], action=YesOrNoAction, 136 | choices=['yes', 'no'], 137 | help='Load all inlined images (default: %s)' % yesOrNo(defaults['loadImages']) 138 | ) 139 | script.add_argument('--load-plugins', default=defaults['loadPlugins'], action=YesOrNoAction, 140 | choices=['yes', 'no'], 141 | help='Load all plugins (i.e. Flash, Silverlight, ...) (default: %s)' % yesOrNo(defaults['loadPlugins']) 142 | ) 143 | script.add_argument('--local-to-remote-url-access', default=defaults['localToRemoteUrlAccessEnabled'], action=YesOrNoAction, 144 | choices=['yes', 'no'], 145 | help='Local content can access remote URL (default: %s)' % yesOrNo(defaults['localToRemoteUrlAccessEnabled']) 146 | ) 147 | 148 | debug.add_argument('--debug', choices=['exception', 'program'], metavar='option', 149 | help=('Debug the program with pdb\n' 150 | ' exception : Start debugger when program hits exception\n' 151 | ' program : Start the program with the debugger enabled') 152 | ) 153 | debug.add_argument('--verbose', action='store_true', 154 | help='Show verbose debug messages' 155 | ) 156 | 157 | do_action('ArgParser') 158 | 159 | return parser 160 | 161 | 162 | def parseArgs(app, args): 163 | # Handle all command-line options 164 | p = argParser() 165 | arg_data = p.parse_known_args(args) 166 | args = arg_data[0] 167 | args.script_args = arg_data[1] 168 | 169 | # convert script args to unicode 170 | for i, arg in enumerate(args.script_args): 171 | args.script_args[i] = unicode(arg, 'utf-8') 172 | 173 | # register an alternative Message Handler 174 | messageHandler = MessageHandler(args.verbose) 175 | qInstallMsgHandler(messageHandler.process) 176 | 177 | file_check = (args.cookies_file, args.config) 178 | for file_ in file_check: 179 | if file_ is not None and not os.path.exists(file_): 180 | sys.exit("No such file or directory: '%s'" % file_) 181 | 182 | if args.config: 183 | config = Config(app, args.config) 184 | # apply settings 185 | for setting in config.settings: 186 | setattr(args, config.settings[setting]['mapping'], config.property(setting)) 187 | 188 | split_check = ( 189 | (args.proxy, 'proxy'), 190 | ) 191 | for arg, name in split_check: 192 | if arg: 193 | item = arg.split(':') 194 | if len(item) < 2 or not len(item[1]): 195 | p.print_help() 196 | sys.exit(1) 197 | setattr(args, name, item) 198 | 199 | if args.proxy is not None: 200 | if args.proxy_type == 'socks5': 201 | args.proxy_type = QNetworkProxy.Socks5Proxy 202 | 203 | do_action('ParseArgs', args) 204 | 205 | if args.debug: 206 | debug(args.debug) 207 | 208 | # verbose flag got changed on us, so we reload the flag 209 | if messageHandler.verbose != args.verbose: 210 | messageHandler.verbose = args.verbose 211 | 212 | if args.script is None: 213 | p.print_help() 214 | sys.exit(1) 215 | 216 | if not os.path.exists(args.script): 217 | sys.exit("No such file or directory: '%s'" % args.script) 218 | 219 | return args 220 | 221 | 222 | class Config(QObject): 223 | def __init__(self, parent, jsonFile): 224 | super(Config, self).__init__(parent) 225 | 226 | with codecs.open(jsonFile, encoding='utf-8') as f: 227 | json = f.read() 228 | 229 | self.settings = { 230 | 'cookiesFile': { 'mapping': 'cookies_file', 'default': defaults['cookiesFile'] }, 231 | 'debug': { 'mapping': 'debug', 'default': defaults['debug'] }, 232 | 'diskCache': { 'mapping': 'disk_cache', 'default': defaults['diskCache'] }, 233 | 'ignoreSslErrors': { 'mapping': 'ignore_ssl_errors', 'default': defaults['ignoreSslErrors'] }, 234 | 'loadImages': { 'mapping': 'load_images', 'default': defaults['loadImages'] }, 235 | 'loadPlugins': { 'mapping': 'load_plugins', 'default': defaults['loadPlugins'] }, 236 | 'localToRemoteUrlAccessEnabled': { 'mapping': 'local_to_remote_url_access', 'default': defaults['localToRemoteUrlAccessEnabled'] }, 237 | 'maxDiskCacheSize': { 'mapping': 'max_disk_cache_size', 'default': defaults['maxDiskCacheSize'] }, 238 | 'outputEncoding': { 'mapping': 'output_encoding', 'default': defaults['outputEncoding'] }, 239 | 'proxy': { 'mapping': 'proxy', 'default': defaults['proxy'] }, 240 | 'proxyType': { 'mapping': 'proxy_type', 'default': defaults['proxyType'] }, 241 | 'scriptEncoding': { 'mapping': 'script_encoding', 'default': defaults['scriptEncoding'] }, 242 | 'verbose': { 'mapping': 'verbose', 'default': defaults['verbose'] } 243 | } 244 | 245 | do_action('ConfigInit', self.settings) 246 | 247 | # generate dynamic properties 248 | for setting in self.settings: 249 | self.setProperty(setting, self.settings[setting]['default']) 250 | 251 | # now it's time to parse our JSON file 252 | if not json.lstrip().startswith('{') or not json.rstrip().endswith('}'): 253 | qWarning('Config file MUST be in JSON format!') 254 | return 255 | 256 | webPage = QWebPage(self) 257 | 258 | with QPyFile(':/configurator.js') as f: 259 | # add config object 260 | webPage.mainFrame().addToJavaScriptWindowObject('config', self) 261 | # apply settings 262 | webPage.mainFrame().evaluateJavaScript(f.readAll().replace('%1', json)) 263 | 264 | do_action('Config') 265 | -------------------------------------------------------------------------------- /pyphantomjs/bootstrap.js: -------------------------------------------------------------------------------- 1 | /*jslint sloppy: true, nomen: true */ 2 | /*global window:true,phantom:true */ 3 | 4 | /* 5 | This file is part of the PhantomJS project from Ofi Labs. 6 | 7 | Copyright (C) 2011 Ariya Hidayat 8 | Copyright (C) 2011 Ivan De Marino 9 | Copyright (C) 2011 James Roe 10 | Copyright (C) 2011 execjosh, http://execjosh.blogspot.com 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | 15 | * Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | * Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | * Neither the name of the nor the 21 | names of its contributors may be used to endorse or promote products 22 | derived from this software without specific prior written permission. 23 | 24 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 25 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 | ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 28 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 31 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 33 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | 36 | function require(name) { 37 | 38 | var code, func, exports; 39 | 40 | if (name === 'webpage' || name === 'fs' || name == 'webserver') { 41 | code = phantom.loadModuleSource(name); 42 | func = new Function("exports", "window", code); 43 | exports = {}; 44 | if (name === 'fs') { 45 | exports = phantom.createFilesystem(); 46 | } 47 | func.call({}, exports, {}); 48 | return exports; 49 | } 50 | 51 | if (typeof exports === 'undefined') { 52 | throw 'Unknown module ' + name + ' for require()'; 53 | } 54 | } 55 | 56 | // Legacy way to use WebPage 57 | window.WebPage = require('webpage').create; 58 | window.WebServer = require('webserver').create; 59 | -------------------------------------------------------------------------------- /pyphantomjs/configurator.js: -------------------------------------------------------------------------------- 1 | (function (opts) { 2 | var i; 3 | 4 | opts = opts || {}; 5 | 6 | if (typeof opts !== 'object') { 7 | return; 8 | } 9 | 10 | for (i in opts) { 11 | if (opts.hasOwnProperty(i) && typeof opts[i] !== 'undefined') { 12 | config[i] = opts[i]; 13 | } 14 | } 15 | 16 | return null; 17 | })((%1)); 18 | -------------------------------------------------------------------------------- /pyphantomjs/cookiejar.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | from PyQt4.QtCore import QSettings 21 | from PyQt4.QtNetwork import QNetworkCookie, QNetworkCookieJar 22 | 23 | 24 | class CookieJar(QNetworkCookieJar): 25 | def __init__(self, parent, cookiesFile): 26 | super(CookieJar, self).__init__(parent) 27 | 28 | self.m_cookiesFile = cookiesFile 29 | 30 | def setCookiesFromUrl(self, cookieList, url): 31 | settings = QSettings(self.m_cookiesFile, QSettings.IniFormat) 32 | 33 | settings.beginGroup(url.host()) 34 | 35 | for cookie in cookieList: 36 | settings.setValue(str(cookie.name()), str(cookie.value())) 37 | 38 | settings.sync() 39 | 40 | return True 41 | 42 | def cookiesForUrl(self, url): 43 | settings = QSettings(self.m_cookiesFile, QSettings.IniFormat) 44 | cookieList = [] 45 | 46 | settings.beginGroup(url.host()) 47 | 48 | for cname in settings.childKeys(): 49 | cookieList.append(QNetworkCookie(cname, settings.value(cname))) 50 | 51 | return cookieList 52 | -------------------------------------------------------------------------------- /pyphantomjs/csconverter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | from PyQt4.QtCore import QObject 21 | from PyQt4.QtGui import QApplication 22 | from PyQt4.QtWebKit import QWebPage 23 | 24 | from utils import QPyFile 25 | 26 | 27 | class CSConverter(QObject): 28 | _instance = None 29 | def __new__(cls, *args, **kwargs): 30 | if cls._instance is None: 31 | cls._instance = super(CSConverter, cls).__new__(cls, *args, **kwargs) 32 | return cls._instance 33 | 34 | def __init__(self): 35 | super(CSConverter, self).__init__(QApplication.instance()) 36 | 37 | self.m_webPage = QWebPage(self) 38 | 39 | with QPyFile(':/resources/coffee-script.js') as f: 40 | self.m_webPage.mainFrame().evaluateJavaScript(f.readAll()) 41 | self.m_webPage.mainFrame().addToJavaScriptWindowObject('converter', self) 42 | 43 | def convert(self, script): 44 | self.setProperty('source', script) 45 | result = self.m_webPage.mainFrame().evaluateJavaScript('''try { 46 | [true, this.CoffeeScript.compile(converter.source)]; 47 | } catch (error) { 48 | [false, error.message]; 49 | } 50 | ''') 51 | return result 52 | -------------------------------------------------------------------------------- /pyphantomjs/encoding.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import codecs 21 | 22 | 23 | class Encode(object): 24 | def __init__(self, encoding, default): 25 | # check that encoding is valid 26 | try: 27 | codecs.lookup(encoding) 28 | self.encoding = encoding 29 | except LookupError: 30 | # fall back to default encoding 31 | self.encoding = default 32 | 33 | @property 34 | def name(self): 35 | return codecs.lookup(self.encoding).name 36 | -------------------------------------------------------------------------------- /pyphantomjs/filesystem.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import codecs 21 | import os 22 | import shutil 23 | import stat 24 | try: 25 | from grp import getgrgid, getgrnam 26 | from pwd import getpwuid, getpwnam 27 | except ImportError: 28 | pass 29 | 30 | from PyQt4.QtCore import (pyqtProperty, pyqtSlot, QDateTime, qDebug, 31 | QFileInfo, QObject) 32 | 33 | from plugincontroller import do_action 34 | 35 | 36 | class File(QObject): 37 | def __init__(self, parent, openfile): 38 | super(File, self).__init__(parent) 39 | 40 | self.m_file = openfile 41 | 42 | do_action('FileInit') 43 | 44 | def __del__(self): 45 | self.m_file.close() 46 | 47 | @pyqtSlot(result=bool) 48 | def atEnd(self): 49 | # :WARNING: On Windows, tell() can return illegal values (after an fgets()) 50 | # when reading files with Unix-style line-endings. Use binary mode ('rb') 51 | # to circumvent this problem. 52 | currentPos = self.m_file.tell() 53 | 54 | try: 55 | line = self.m_file.readline() 56 | self.m_file.seek(currentPos) 57 | except IOError as e: 58 | qDebug("File.atEnd - %s: '%s'" % (e, self.m_file.name)) 59 | return False 60 | 61 | # test for EOF 62 | if line == '': 63 | return True 64 | return False 65 | 66 | @pyqtSlot() 67 | def close(self): 68 | self.m_file.flush() 69 | self.m_file.close() 70 | self.deleteLater() 71 | 72 | @pyqtSlot() 73 | def flush(self): 74 | self.m_file.flush() 75 | 76 | @pyqtSlot(result=str) 77 | def read(self): 78 | try: 79 | return self.m_file.read() 80 | except IOError as e: 81 | qDebug("File.read - %s: '%s'" % (e, self.m_file.name)) 82 | return '' 83 | 84 | @pyqtSlot(result=str) 85 | def readLine(self): 86 | try: 87 | return self.m_file.readline() 88 | except IOError as e: 89 | qDebug("File.readLine - %s: '%s'" % (e, self.m_file.name)) 90 | return '' 91 | 92 | @pyqtSlot(str, result=bool) 93 | def write(self, data): 94 | try: 95 | self.m_file.write(data) 96 | return True 97 | except IOError as e: 98 | qDebug("File.write - %s: '%s'" % (e, self.m_file.name)) 99 | return False 100 | 101 | @pyqtSlot(str, result=bool) 102 | def writeLine(self, data): 103 | try: 104 | self.m_file.write(data + '\n') 105 | return True 106 | except IOError as e: 107 | qDebug("File.writeLine - %s: '%s'" % (e, self.m_file.name)) 108 | return False 109 | 110 | do_action('File') 111 | 112 | 113 | class FileSystem(QObject): 114 | _instance = None 115 | def __new__(cls, *args, **kwargs): 116 | if cls._instance is None: 117 | cls._instance = super(FileSystem, cls).__new__(cls, *args, **kwargs) 118 | return cls._instance 119 | 120 | def __init__(self, parent): 121 | super(FileSystem, self).__init__(parent) 122 | 123 | do_action('FileSystemInit') 124 | 125 | ## 126 | # Attributes 127 | ## 128 | 129 | @pyqtSlot(str, result=int) 130 | def _size(self, path): 131 | try: 132 | return os.path.getsize(path) 133 | except OSError as (_, e): 134 | qDebug("FileSystem.size - %s: '%s'" % (e, path)) 135 | return -1 136 | 137 | @pyqtSlot(str, result=QDateTime) 138 | def lastModified(self, path): 139 | fi = QFileInfo(path) 140 | if fi.exists(): 141 | return fi.lastModified() 142 | else: 143 | err = 'No such file or directory' 144 | 145 | qDebug("FileSystem.lastModified - %s: '%s'" % (err, path)) 146 | return QDateTime() 147 | 148 | ## 149 | # Files / Directories 150 | ## 151 | 152 | @pyqtSlot(str, str, result=bool) 153 | def _copy(self, source, target): 154 | try: 155 | shutil.copy2(source, target) 156 | return True 157 | except IOError as (_, e): 158 | qDebug("FileSystem.copy - %s: '%s' -> '%s'" % (e, source, target)) 159 | return False 160 | 161 | @pyqtSlot(str, str, result=bool) 162 | def rename(self, source, target): 163 | try: 164 | os.rename(source, target) 165 | return True 166 | except OSError as (_, e): 167 | qDebug("FileSystem.rename - %s: '%s' -> '%s'" % (e, source, target)) 168 | return False 169 | 170 | ## 171 | # Directories 172 | ## 173 | 174 | @pyqtSlot(str, str, result=bool) 175 | def _copyTree(self, source, target): 176 | try: 177 | shutil.copytree(source, target) 178 | return True 179 | except IOError as (_, e): 180 | qDebug("FileSystem.copyTree - %s: '%s' -> '%s'" % (e, source, target)) 181 | return False 182 | 183 | @pyqtSlot(str, result=bool) 184 | def _removeDirectory(self, path): 185 | try: 186 | os.rmdir(path) 187 | return True 188 | except OSError as e: 189 | qDebug("FileSystem.removeDirectory - %s: '%s'" % (e, path)) 190 | return False 191 | 192 | @pyqtSlot(str, result=bool) 193 | def _removeTree(self, path): 194 | try: 195 | shutil.rmtree(path) 196 | return True 197 | except OSError as e: 198 | qDebug("FileSystem.removeTree - %s: '%s'" % (e, path)) 199 | return False 200 | 201 | @pyqtSlot(str, str, result=bool) 202 | def copyLinkTree(self, source, target): 203 | try: 204 | shutil.copytree(source, target, True) 205 | return True 206 | except IOError as (_, e): 207 | qDebug("FileSystem.copyLinkTree - %s: '%s' -> '%s'" % (e, source, target)) 208 | return False 209 | 210 | @pyqtSlot(str, result=bool) 211 | def makeDirectory(self, path): 212 | try: 213 | os.mkdir(path) 214 | return True 215 | except OSError as e: 216 | qDebug("FileSystem.makeDirectory - %s: '%s'" % (e, path)) 217 | return False 218 | 219 | @pyqtSlot(str, result=bool) 220 | def makeTree(self, path): 221 | try: 222 | os.makedirs(path) 223 | return True 224 | except OSError as e: 225 | qDebug("FileSystem.makeTree - %s: '%s'" % (e, path)) 226 | return False 227 | 228 | ## 229 | # Files 230 | ## 231 | 232 | @pyqtSlot(str, str, result=File) 233 | def _open(self, path, mode): 234 | try: 235 | f = codecs.open(path, mode, encoding='utf-8') 236 | return File(self, f) 237 | except (IOError, ValueError) as (_, e): 238 | qDebug("FileSystem.open - %s: '%s'" % (e, path)) 239 | return 240 | 241 | @pyqtSlot(str, result=bool) 242 | def _remove(self, path): 243 | try: 244 | os.remove(path) 245 | return True 246 | except OSError as e: 247 | qDebug("FileSystem.remove - %s: '%s'" % (e, path)) 248 | return False 249 | 250 | @pyqtProperty(str) 251 | def newline(self): 252 | return os.linesep 253 | 254 | ## 255 | # Listing 256 | ## 257 | 258 | @pyqtSlot(str, name='list', result='QStringList') 259 | def list_(self, path): 260 | try: 261 | p = os.listdir(path) 262 | p[0:2] = ('.', '..') 263 | return p 264 | except OSError as e: 265 | qDebug("FileSystem.list - %s: '%s'" % (e, path)) 266 | return 267 | 268 | @pyqtSlot(str, result='QStringList') 269 | def listTree(self, path): 270 | try: 271 | listing = [] 272 | for root, _, files in os.walk(path): 273 | for file_ in files: 274 | listing.append(os.path.join(root, file_)) 275 | return listing 276 | except OSError as (_, e): 277 | qDebug("FileSystem.listTree - %s: '%s'" % (e, path)) 278 | return 279 | 280 | @pyqtSlot(str, result='QStringList') 281 | def listDirectoryTree(self, path): 282 | try: 283 | listing = [] 284 | for root, dirs, _ in os.walk(path): 285 | for dir_ in dirs: 286 | listing.append(os.path.join(root, dir_)) 287 | return listing 288 | except OSError as (_, e): 289 | qDebug("FileSystem.listDirectoryTree - %s: '%s'" % (e, path)) 290 | return 291 | 292 | ## 293 | # Links 294 | ## 295 | 296 | @pyqtSlot(str, str, result=bool) 297 | def symbolicLink(self, source, target): 298 | try: 299 | os.symlink(source, target) 300 | return True 301 | except OSError as (_, e): 302 | qDebug("FileSystem.symbolicLink - %s: '%s' -> '%s'" % (e, source, target)) 303 | return False 304 | 305 | @pyqtSlot(str, str, result=bool) 306 | def hardLink(self, source, target): 307 | try: 308 | os.link(source, target) 309 | return True 310 | except OSError as (_, e): 311 | qDebug("FileSystem.hardLink - %s: '%s' -> '%s'" % (e, source, target)) 312 | return False 313 | 314 | @pyqtSlot(str, result=str) 315 | def readLink(self, path): 316 | try: 317 | return os.readlink(path) 318 | except OSError as (_, e): 319 | qDebug("FileSystem.readLink - %s: '%s'" % (e, path)) 320 | return '' 321 | 322 | ## 323 | # Paths 324 | ## 325 | 326 | @pyqtSlot(str, result=str) 327 | def absolute(self, path): 328 | return os.path.abspath(path) 329 | 330 | @pyqtSlot(str, result=str) 331 | @pyqtSlot(str, str, result=str) 332 | def base(self, path, ext=None): 333 | if ext is None: 334 | return os.path.basename(path) 335 | else: 336 | base = os.path.splitext(os.path.basename(path)) 337 | if ext == base[1][1:]: 338 | return base[0] 339 | return ''.join(base) 340 | 341 | @pyqtSlot(str, result=str) 342 | def canonical(self, path): 343 | return os.path.realpath(path) 344 | 345 | @pyqtSlot(str, result=bool) 346 | def changeWorkingDirectory(self, path): 347 | try: 348 | os.chdir(path) 349 | return True 350 | except OSError as e: 351 | qDebug("FileSystem.changeWorkingDirectory - %s: '%s'" % (e, path)) 352 | return False 353 | 354 | @pyqtSlot(str, result=str) 355 | def directory(self, path): 356 | return os.path.dirname(path) 357 | 358 | @pyqtSlot(str, result=str) 359 | def extension(self, path): 360 | return os.path.splitext(os.path.basename(path))[1][1:] 361 | 362 | @pyqtSlot('QStringList', result=str) 363 | def join(self, paths): 364 | return os.path.join(*paths) 365 | 366 | @pyqtSlot(str, result=str) 367 | def normal(self, path): 368 | return os.path.normpath(path) 369 | 370 | @pyqtSlot(str, result=str) 371 | def normalCase(self, path): 372 | return os.path.normcase(path) 373 | 374 | @pyqtProperty(str) 375 | def workingDirectory(self): 376 | return os.getcwdu() 377 | 378 | @pyqtSlot(str, result=str) 379 | @pyqtSlot(str, str, result=str) 380 | def relative(self, source, target=None): 381 | if target is None: 382 | return os.path.relpath(source) 383 | else: 384 | return os.path.relpath(source, target) 385 | 386 | @pyqtProperty(str) 387 | def separator(self): 388 | return os.sep 389 | 390 | @pyqtSlot(str, result='QStringList') 391 | def split(self, path): 392 | if os.sep in path: 393 | return path.split(os.sep) 394 | else: 395 | return path.split(os.altsep) 396 | 397 | ## 398 | # Permissions 399 | ## 400 | 401 | @pyqtSlot(str, str, result=bool) 402 | @pyqtSlot(str, int, result=bool) 403 | def changeGroup(self, path, group): 404 | try: 405 | if isinstance(group, int): 406 | os.chown(path, -1, group) 407 | else: 408 | os.chown(path, -1, getgrnam(group).gr_gid) 409 | return True 410 | except OSError as (_, e): 411 | qDebug("FileSystem.changeGroup - %s: '%s':'%s'" % (e, group, path)) 412 | except KeyError as e: 413 | qDebug("FileSystem.changeGroup - %s: '%s'" % (e.args[0], path)) 414 | return False 415 | 416 | @pyqtSlot(str, str, result=bool) 417 | @pyqtSlot(str, int, result=bool) 418 | def changeLinkGroup(self, path, group): 419 | try: 420 | if isinstance(group, int): 421 | os.lchown(path, -1, group) 422 | else: 423 | os.lchown(path, -1, getgrnam(group).gr_gid) 424 | return True 425 | except OSError as (_, e): 426 | qDebug("FileSystem.changeLinkGroup - %s: '%s':'%s'" % (e, group, path)) 427 | except KeyError as e: 428 | qDebug("FileSystem.changeLinkGroup - %s: '%s'" % (e.args[0], path)) 429 | return False 430 | 431 | @pyqtSlot(str, str, result=bool) 432 | @pyqtSlot(str, int, result=bool) 433 | def changeLinkOwner(self, path, owner): 434 | try: 435 | if isinstance(owner, int): 436 | os.lchown(path, owner, -1) 437 | else: 438 | os.lchown(path, getpwnam(owner).pw_uid, -1) 439 | return True 440 | except OSError as (_, e): 441 | qDebug("FileSystem.changeLinkOwner - %s: '%s':'%s'" % (e, owner, path)) 442 | except KeyError as e: 443 | qDebug("FileSystem.changeLinkOwner - %s: '%s'" % (e.args[0], path)) 444 | return False 445 | 446 | @pyqtSlot(str, str, result=bool) 447 | @pyqtSlot(str, int, result=bool) 448 | def changeOwner(self, path, owner): 449 | try: 450 | if isinstance(owner, int): 451 | os.chown(path, owner, -1) 452 | else: 453 | os.chown(path, getpwnam(owner).pw_uid, -1) 454 | return True 455 | except OSError as (_, e): 456 | qDebug("FileSystem.changeOwner - %s: '%s':'%s'" % (e, owner, path)) 457 | except KeyError as e: 458 | qDebug("FileSystem.changeOwner - %s: '%s'" % (e.args[0], path)) 459 | return False 460 | 461 | @pyqtSlot(str, int, result=bool) 462 | @pyqtSlot(str, 'QVariantMap', result=bool) 463 | def changePermissions(self, path, permissions): 464 | # permissions uses an object in 4 types: owner, group, others, special 465 | # owner,group,others each has 3 types, read,write,executable, contained in an array 466 | # special uses setuid,setgid,sticky 467 | # 468 | # In order to turn values on or off, just use true or false values. 469 | # 470 | # Permissions can alternatively be a numeric mode to chmod too. 471 | 472 | keys = { 473 | 'owner': {'read': 'S_IRUSR', 'write': 'S_IWUSR', 'executable': 'S_IXUSR'}, 474 | 'group': {'read': 'S_IRGRP', 'write': 'S_IWGRP', 'executable': 'S_IXGRP'}, 475 | 'others': {'read': 'S_IROTH', 'write': 'S_IWOTH', 'executable': 'S_IXOTH'}, 476 | 'special': {'setuid': 'S_ISUID', 'setgid': 'S_ISGID', 'sticky': 'S_ISVTX'} 477 | } 478 | 479 | try: 480 | if isinstance(permissions, int): 481 | os.chmod(path, permissions) 482 | else: 483 | bitnum = os.stat(path).st_mode 484 | for section in permissions: 485 | for key in permissions[section]: 486 | try: 487 | if permissions[section][key] is True: 488 | bitnum = bitnum | stat.__dict__[keys[section][key]] 489 | elif permissions[section][key] is False: 490 | bitnum = bitnum & ~stat.__dict__[keys[section][key]] 491 | except KeyError: 492 | pass 493 | os.chmod(path, bitnum) 494 | return True 495 | except OSError as (_, e): 496 | qDebug("FileSystem.changePermissions - %s: '%s'" % (e, path)) 497 | return False 498 | 499 | @pyqtSlot(str, result='QVariant') 500 | def group(self, path): 501 | try: 502 | finfo = os.stat(path) 503 | return { 504 | 'name': getgrgid(finfo.st_gid).gr_name, 505 | 'uid': finfo.st_gid 506 | } 507 | except OSError as (_, e): 508 | qDebug("FileSystem.group - %s: '%s'" % (e, path)) 509 | return 510 | 511 | @pyqtSlot(str, result='QVariant') 512 | def owner(self, path): 513 | try: 514 | finfo = os.stat(path) 515 | return { 516 | 'name': getpwuid(finfo.st_uid).pw_name, 517 | 'uid': finfo.st_uid 518 | } 519 | except OSError as (_, e): 520 | qDebug("FileSystem.owner - %s: '%s'" % (e, path)) 521 | return 522 | 523 | @pyqtSlot(str, result='QVariant') 524 | def linkGroup(self, path): 525 | try: 526 | finfo = os.lstat(path) 527 | return { 528 | 'name': getgrgid(finfo.st_gid).gr_name, 529 | 'uid': finfo.st_gid 530 | } 531 | except OSError as (_, e): 532 | qDebug("FileSystem.linkGroup - %s: '%s'" % (e, path)) 533 | return 534 | 535 | @pyqtSlot(str, result='QVariant') 536 | def linkOwner(self, path): 537 | try: 538 | finfo = os.lstat(path) 539 | return { 540 | 'name': getpwuid(finfo.st_uid).pw_name, 541 | 'uid': finfo.st_uid 542 | } 543 | except OSError as (_, e): 544 | qDebug("FileSystem.linkOwner - %s: '%s'" % (e, path)) 545 | return 546 | 547 | @pyqtSlot(str, result='QVariant') 548 | def linkPermissions(self, path): 549 | # returns an object in 4 types: owner, group, others, special 550 | # owner,group,others each has 3 types, read,write,executable 551 | # special will return setuid,setgid,sticky 552 | 553 | try: 554 | finfo = os.lstat(path).st_mode 555 | 556 | # owner 557 | isOwnRd = bool(finfo & stat.S_IRUSR) 558 | isOwnWr = bool(finfo & stat.S_IWUSR) 559 | isOwnEx = bool(finfo & stat.S_IXUSR) 560 | # group 561 | isGrpRd = bool(finfo & stat.S_IRGRP) 562 | isGrpWr = bool(finfo & stat.S_IWGRP) 563 | isGrpEx = bool(finfo & stat.S_IXGRP) 564 | # others 565 | isOthRd = bool(finfo & stat.S_IROTH) 566 | isOthWr = bool(finfo & stat.S_IWOTH) 567 | isOthEx = bool(finfo & stat.S_IXOTH) 568 | # s*id 569 | isSUid = bool(finfo & stat.S_ISUID) 570 | isSGid = bool(finfo & stat.S_ISGID) 571 | # sticky 572 | isStick = bool(finfo & stat.S_ISVTX) 573 | 574 | return { 575 | 'mode': oct(finfo)[-4:], 576 | 'owner': {'read': isOwnRd, 'write': isOwnWr, 'executable': isOwnEx}, 577 | 'group': {'read': isGrpRd, 'write': isGrpWr, 'executable': isGrpEx}, 578 | 'others': {'read': isOthRd, 'write': isOthWr, 'executable': isOthEx}, 579 | 'special': {'setuid': isSUid, 'setgid': isSGid, 'sticky': isStick} 580 | } 581 | except OSError as (_, e): 582 | qDebug("FileSystem.linkPermissions - %s: '%s'" % (e, path)) 583 | return 584 | 585 | @pyqtSlot(str, result='QVariant') 586 | def permissions(self, path): 587 | # returns an object in 4 types: owner, group, others, special 588 | # owner,group,others each has 3 types, read,write,executable 589 | # special will return setuid,setgid,sticky 590 | 591 | try: 592 | finfo = os.stat(path).st_mode 593 | 594 | # owner 595 | isOwnRd = bool(finfo & stat.S_IRUSR) 596 | isOwnWr = bool(finfo & stat.S_IWUSR) 597 | isOwnEx = bool(finfo & stat.S_IXUSR) 598 | # group 599 | isGrpRd = bool(finfo & stat.S_IRGRP) 600 | isGrpWr = bool(finfo & stat.S_IWGRP) 601 | isGrpEx = bool(finfo & stat.S_IXGRP) 602 | # others 603 | isOthRd = bool(finfo & stat.S_IROTH) 604 | isOthWr = bool(finfo & stat.S_IWOTH) 605 | isOthEx = bool(finfo & stat.S_IXOTH) 606 | # s*id 607 | isSUid = bool(finfo & stat.S_ISUID) 608 | isSGid = bool(finfo & stat.S_ISGID) 609 | # sticky 610 | isStick = bool(finfo & stat.S_ISVTX) 611 | 612 | return { 613 | 'mode': oct(finfo)[-4:], 614 | 'owner': {'read': isOwnRd, 'write': isOwnWr, 'executable': isOwnEx}, 615 | 'group': {'read': isGrpRd, 'write': isGrpWr, 'executable': isGrpEx}, 616 | 'others': {'read': isOthRd, 'write': isOthWr, 'executable': isOthEx}, 617 | 'special': {'setuid': isSUid, 'setgid': isSGid, 'sticky': isStick} 618 | } 619 | except OSError as (_, e): 620 | qDebug("FileSystem.permissions - %s: '%s'" % (e, path)) 621 | return 622 | 623 | ## 624 | # Tests 625 | ## 626 | 627 | @pyqtSlot(str, result=bool) 628 | def exists(self, path): 629 | return os.path.exists(path) 630 | 631 | @pyqtSlot(str, result=bool) 632 | def isAbsolute(self, path): 633 | return os.path.isabs(os.path.splitdrive(path)[1]) 634 | 635 | @pyqtSlot(str, result=bool) 636 | def isDirectory(self, path): 637 | return os.path.isdir(path) 638 | 639 | @pyqtSlot(str, result=bool) 640 | def isExecutable(self, path): 641 | return os.access(path, os.X_OK) 642 | 643 | @pyqtSlot(str, result=bool) 644 | def isFile(self, path): 645 | return os.path.isfile(path) 646 | 647 | @pyqtSlot(str, result=bool) 648 | def isLink(self, path): 649 | return os.path.islink(path) 650 | 651 | @pyqtSlot(str, result=bool) 652 | def isMount(self, path): 653 | return os.path.ismount(path) 654 | 655 | @pyqtSlot(str, result=bool) 656 | def isReadable(self, path): 657 | return os.access(path, os.R_OK) 658 | 659 | @pyqtSlot(str, result=bool) 660 | def isWritable(self, path): 661 | return os.access(path, os.W_OK) 662 | 663 | @pyqtSlot(str, result=bool) 664 | def linkExists(self, path): 665 | return os.path.lexists(path) 666 | 667 | @pyqtSlot(str, result=bool) 668 | def same(self, pathA, pathB): 669 | return os.path.samefile(pathA, pathB) 670 | 671 | do_action('FileSystem') 672 | -------------------------------------------------------------------------------- /pyphantomjs/modules/fs.js: -------------------------------------------------------------------------------- 1 | /*jslint sloppy: true, nomen: true */ 2 | /*global exports:true */ 3 | 4 | /* 5 | This file is part of the PhantomJS project from Ofi Labs. 6 | 7 | Copyright (C) 2011 Ivan De Marino 8 | 9 | Redistribution and use in source and binary forms, with or without 10 | modification, are permitted provided that the following conditions are met: 11 | 12 | * Redistributions of source code must retain the above copyright 13 | notice, this list of conditions and the following disclaimer. 14 | * Redistributions in binary form must reproduce the above copyright 15 | notice, this list of conditions and the following disclaimer in the 16 | documentation and/or other materials provided with the distribution. 17 | * Neither the name of the nor the 18 | names of its contributors may be used to endorse or promote products 19 | derived from this software without specific prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 22 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 25 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 26 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 27 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 28 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 30 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | // JavaScript "shim" to throw exceptions in case a critical operation fails. 34 | 35 | /** Open and return a "file" object. 36 | * It will throw exception if it fails. 37 | * 38 | * @param path Path of the file to open 39 | * @param mode Open Mode. A string made of 'r', 'w', 'a/+' characters. 40 | * @return "file" object 41 | */ 42 | exports.open = function (path, mode) { 43 | var file = exports._open(path, mode); 44 | if (file) { 45 | return file; 46 | } 47 | throw "Unable to open file '" + path + "'"; 48 | }; 49 | 50 | /** Open, read and return content of a file. 51 | * It will throw an exception if it fails. 52 | * 53 | * @param path Path of the file to read from 54 | * @return file content 55 | */ 56 | exports.read = function (path) { 57 | var f = exports.open(path, 'r'), 58 | content = f.read(); 59 | 60 | f.close(); 61 | return content; 62 | }; 63 | 64 | /** Open and write content to a file 65 | * It will throw an exception if it fails. 66 | * 67 | * @param path Path of the file to read from 68 | * @param content Content to write to the file 69 | * @param mode Open Mode. A string made of 'w' or 'a / +' characters. 70 | */ 71 | exports.write = function (path, content, mode) { 72 | var f = exports.open(path, mode); 73 | 74 | f.write(content); 75 | f.close(); 76 | }; 77 | 78 | /** Return the size of a file, in bytes. 79 | * It will throw an exception if it fails. 80 | * 81 | * @param path Path of the file to read the size of 82 | * @return File size in bytes 83 | */ 84 | exports.size = function (path) { 85 | var size = exports._size(path); 86 | if (size !== -1) { 87 | return size; 88 | } 89 | throw "Unable to read file '" + path + "' size"; 90 | }; 91 | 92 | /** Copy a file. 93 | * It will throw an exception if it fails. 94 | * 95 | * @param source Path of the source file 96 | * @param destination Path of the destination file 97 | */ 98 | exports.copy = function (source, destination) { 99 | if (!exports._copy(source, destination)) { 100 | throw "Unable to copy file '" + source + "' at '" + destination + "'"; 101 | } 102 | }; 103 | 104 | /** Copy a directory tree. 105 | * It will throw an exception if it fails. 106 | * 107 | * @param source Path of the source directory tree 108 | * @param destination Path of the destination directory tree 109 | */ 110 | exports.copyTree = function (source, destination) { 111 | if (!exports._copyTree(source, destination)) { 112 | throw "Unable to copy directory tree '" + source + "' at '" + destination + "'"; 113 | } 114 | }; 115 | 116 | /** Move a file. 117 | * It will throw an exception if it fails. 118 | * 119 | * @param source Path of the source file 120 | * @param destination Path of the destination file 121 | */ 122 | exports.move = function (source, destination) { 123 | exports.copy(source, destination); 124 | exports.remove(source); 125 | }; 126 | 127 | /** Removes a file. 128 | * It will throw an exception if it fails. 129 | * 130 | * @param path Path of the file to remove 131 | */ 132 | exports.remove = function (path) { 133 | if (!exports._remove(path)) { 134 | throw "Unable to remove file '" + path + "'"; 135 | } 136 | }; 137 | 138 | /** Removes a directory. 139 | * It will throw an exception if it fails. 140 | * 141 | * @param path Path of the directory to remove 142 | */ 143 | exports.removeDirectory = function (path) { 144 | if (!exports._removeDirectory(path)) { 145 | throw "Unable to remove directory '" + path + "'"; 146 | } 147 | }; 148 | 149 | /** Removes a directory tree. 150 | * It will throw an exception if it fails. 151 | * 152 | * @param path Path of the directory tree to remove 153 | */ 154 | exports.removeTree = function (path) { 155 | if (!exports._removeTree(path)) { 156 | throw "Unable to remove directory tree '" + path + "'"; 157 | } 158 | }; 159 | 160 | exports.touch = function (path) { 161 | exports.write(path, "", 'a'); 162 | }; 163 | -------------------------------------------------------------------------------- /pyphantomjs/modules/webpage.js: -------------------------------------------------------------------------------- 1 | /*jslint sloppy: true, nomen: true */ 2 | /*global exports:true,phantom:true */ 3 | 4 | /* 5 | This file is part of the PhantomJS project from Ofi Labs. 6 | 7 | Copyright (C) 2011 Ariya Hidayat 8 | Copyright (C) 2011 Ivan De Marino 9 | Copyright (C) 2011 James Roe 10 | Copyright (C) 2011 execjosh, http://execjosh.blogspot.com 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | 15 | * Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | * Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | * Neither the name of the nor the 21 | names of its contributors may be used to endorse or promote products 22 | derived from this software without specific prior written permission. 23 | 24 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 25 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 | ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 28 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 31 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 33 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | 36 | exports.create = function (opts) { 37 | var page = phantom.createWebPage(), 38 | handlers = {}; 39 | 40 | function checkType(o, type) { 41 | return typeof o === type; 42 | } 43 | 44 | function isObject(o) { 45 | return checkType(o, 'object'); 46 | } 47 | 48 | function isUndefined(o) { 49 | return checkType(o, 'undefined'); 50 | } 51 | 52 | function isUndefinedOrNull(o) { 53 | return isUndefined(o) || null === o; 54 | } 55 | 56 | function copyInto(target, source) { 57 | if (target === source || isUndefinedOrNull(source)) { 58 | return target; 59 | } 60 | 61 | target = target || {}; 62 | 63 | // Copy into objects only 64 | if (isObject(target)) { 65 | // Make sure source exists 66 | source = source || {}; 67 | 68 | if (isObject(source)) { 69 | var i, newTarget, newSource; 70 | for (i in source) { 71 | if (source.hasOwnProperty(i)) { 72 | newTarget = target[i]; 73 | newSource = source[i]; 74 | 75 | if (newTarget && isObject(newSource)) { 76 | // Deep copy 77 | newTarget = copyInto(target[i], newSource); 78 | } else { 79 | newTarget = newSource; 80 | } 81 | 82 | if (!isUndefined(newTarget)) { 83 | target[i] = newTarget; 84 | } 85 | } 86 | } 87 | } else { 88 | target = source; 89 | } 90 | } 91 | 92 | return target; 93 | } 94 | 95 | function defineSetter(handlerName, signalName) { 96 | page.__defineSetter__(handlerName, function (f) { 97 | if (handlers && typeof handlers[signalName] === 'function') { 98 | try { 99 | this[signalName].disconnect(handlers[signalName]); 100 | } catch (e) {} 101 | } 102 | handlers[signalName] = f; 103 | this[signalName].connect(handlers[signalName]); 104 | }); 105 | } 106 | 107 | // deep copy 108 | page.settings = JSON.parse(JSON.stringify(phantom.defaultPageSettings)); 109 | 110 | defineSetter("onInitialized", "initialized"); 111 | 112 | defineSetter("onLoadStarted", "loadStarted"); 113 | 114 | defineSetter("onLoadFinished", "loadFinished"); 115 | 116 | defineSetter("onResourceRequested", "resourceRequested"); 117 | 118 | defineSetter("onResourceReceived", "resourceReceived"); 119 | 120 | defineSetter("onAlert", "javaScriptAlertSent"); 121 | 122 | defineSetter("onConsoleMessage", "javaScriptConsoleMessageSent"); 123 | 124 | page.open = function (url, arg1, arg2, arg3, arg4) { 125 | if (arguments.length === 1) { 126 | this.openUrl(url, 'get', this.settings); 127 | return; 128 | } 129 | if (arguments.length === 2 && typeof arg1 === 'function') { 130 | this.onLoadFinished = arg1; 131 | this.openUrl(url, 'get', this.settings); 132 | return; 133 | } else if (arguments.length === 2) { 134 | this.openUrl(url, arg1, this.settings); 135 | return; 136 | } else if (arguments.length === 3 && typeof arg2 === 'function') { 137 | this.onLoadFinished = arg2; 138 | this.openUrl(url, arg1, this.settings); 139 | return; 140 | } else if (arguments.length === 3) { 141 | this.openUrl(url, { 142 | operation: arg1, 143 | data: arg2 144 | }, this.settings); 145 | return; 146 | } else if (arguments.length === 4) { 147 | this.onLoadFinished = arg3; 148 | this.openUrl(url, { 149 | operation: arg1, 150 | data: arg2 151 | }, this.settings); 152 | return; 153 | } 154 | throw "Wrong use of WebPage#open"; 155 | }; 156 | 157 | page.includeJs = function (scriptUrl, onScriptLoaded) { 158 | // Register temporary signal handler for 'alert()' 159 | this.javaScriptAlertSent.connect(function (msgFromAlert) { 160 | if (msgFromAlert === scriptUrl) { 161 | // Resource loaded, time to fire the callback 162 | onScriptLoaded(scriptUrl); 163 | // And disconnect the signal handler 164 | try { 165 | this.javaScriptAlertSent.disconnect(arguments.callee); 166 | } catch (e) {} 167 | } 168 | }); 169 | 170 | // Append the script tag to the body 171 | this._appendScriptElement(scriptUrl); 172 | }; 173 | 174 | // Copy options into page 175 | if (opts) { 176 | page = copyInto(page, opts); 177 | } 178 | 179 | return page; 180 | }; 181 | -------------------------------------------------------------------------------- /pyphantomjs/modules/webserver.js: -------------------------------------------------------------------------------- 1 | /*jslint sloppy: true, nomen: true */ 2 | /*global exports:true,phantom:true */ 3 | 4 | /* 5 | This file is part of the PhantomJS project from Ofi Labs. 6 | 7 | Copyright (C) 2011 Ariya Hidayat 8 | Copyright (C) 2011 Ivan De Marino 9 | Copyright (C) 2011 James Roe 10 | Copyright (C) 2011 execjosh, http://execjosh.blogspot.com 11 | Copyright (C) 2011 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com 12 | Author: Milian Wolff 13 | 14 | Redistribution and use in source and binary forms, with or without 15 | modification, are permitted provided that the following conditions are met: 16 | 17 | * Redistributions of source code must retain the above copyright 18 | notice, this list of conditions and the following disclaimer. 19 | * Redistributions in binary form must reproduce the above copyright 20 | notice, this list of conditions and the following disclaimer in the 21 | documentation and/or other materials provided with the distribution. 22 | * Neither the name of the nor the 23 | names of its contributors may be used to endorse or promote products 24 | derived from this software without specific prior written permission. 25 | 26 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 27 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 | ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 30 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 31 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 32 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 33 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 35 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 36 | */ 37 | 38 | exports.create = function (opts) { 39 | var server = phantom.createWebServer(); 40 | var handlers = {}; 41 | 42 | function checkType(o, type) { 43 | return typeof o === type; 44 | } 45 | 46 | function isObject(o) { 47 | return checkType(o, 'object'); 48 | } 49 | 50 | function isUndefined(o) { 51 | return checkType(o, 'undefined'); 52 | } 53 | 54 | function isUndefinedOrNull(o) { 55 | return isUndefined(o) || null === o; 56 | } 57 | 58 | function copyInto(target, source) { 59 | if (target === source || isUndefinedOrNull(source)) { 60 | return target; 61 | } 62 | 63 | target = target || {}; 64 | 65 | // Copy into objects only 66 | if (isObject(target)) { 67 | // Make sure source exists 68 | source = source || {}; 69 | 70 | if (isObject(source)) { 71 | var i, newTarget, newSource; 72 | for (i in source) { 73 | if (source.hasOwnProperty(i)) { 74 | newTarget = target[i]; 75 | newSource = source[i]; 76 | 77 | if (newTarget && isObject(newSource)) { 78 | // Deep copy 79 | newTarget = copyInto(target[i], newSource); 80 | } else { 81 | newTarget = newSource; 82 | } 83 | 84 | if (!isUndefined(newTarget)) { 85 | target[i] = newTarget; 86 | } 87 | } 88 | } 89 | } else { 90 | target = source; 91 | } 92 | } 93 | 94 | return target; 95 | } 96 | 97 | function defineSetter(handlerName, signalName) { 98 | server.__defineSetter__(handlerName, function (f) { 99 | if (handlers && typeof handlers[signalName] === 'function') { 100 | try { 101 | this[signalName].disconnect(handlers[signalName]); 102 | } catch (e) {} 103 | } 104 | handlers[signalName] = f; 105 | this[signalName].connect(handlers[signalName]); 106 | }); 107 | } 108 | 109 | // deep copy 110 | //TODO: use this? 111 | // server.settings = JSON.parse(JSON.stringify(phantom.defaultServerSettings)); 112 | 113 | defineSetter("onNewRequest", "newRequest"); 114 | 115 | server.listen = function (port, handler) { 116 | if (arguments.length === 2 && typeof handler === 'function') { 117 | this.onNewRequest = handler; 118 | //TODO: settings? 119 | return this.listenOnPort(port); 120 | } 121 | throw "Wrong use of WebServer#listen"; 122 | }; 123 | 124 | // Copy options into server 125 | if (opts) { 126 | server = copyInto(server, opts); 127 | } 128 | 129 | return server; 130 | }; 131 | -------------------------------------------------------------------------------- /pyphantomjs/networkaccessmanager.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | from PyQt4.QtCore import pyqtSignal, QDateTime 21 | from PyQt4.QtGui import QDesktopServices 22 | from PyQt4.QtNetwork import (QNetworkAccessManager, QNetworkDiskCache, 23 | QNetworkRequest) 24 | 25 | from cookiejar import CookieJar 26 | from plugincontroller import do_action 27 | 28 | 29 | class NetworkAccessManager(QNetworkAccessManager): 30 | resourceReceived = pyqtSignal('QVariantMap') 31 | resourceRequested = pyqtSignal('QVariantMap') 32 | 33 | def __init__(self, parent, args): 34 | super(NetworkAccessManager, self).__init__(parent) 35 | 36 | self.m_userName = self.m_password = '' 37 | self.m_ignoreSslErrors = args.ignore_ssl_errors 38 | self.m_idCounter = 0 39 | self.m_ids = {} 40 | self.m_started = [] 41 | 42 | if args.cookies_file: 43 | self.setCookieJar(CookieJar(self, args.cookies_file)) 44 | 45 | if args.disk_cache: 46 | m_networkDiskCache = QNetworkDiskCache() 47 | m_networkDiskCache.setCacheDirectory(QDesktopServices.storageLocation(QDesktopServices.CacheLocation)) 48 | if args.max_disk_cache_size > 0: 49 | m_networkDiskCache.setMaximumCacheSize(args.max_disk_cache_size * 1024) 50 | self.setCache(m_networkDiskCache) 51 | 52 | self.authenticationRequired.connect(self.provideAuthentication) 53 | self.finished.connect(self.handleFinished) 54 | 55 | do_action('NetworkAccessManagerInit') 56 | 57 | def createRequest(self, op, req, outgoingData): 58 | do_action('NetworkAccessManagerCreateRequestPre') 59 | 60 | reply = QNetworkAccessManager.createRequest(self, op, req, outgoingData) 61 | 62 | if self.m_ignoreSslErrors: 63 | reply.ignoreSslErrors() 64 | 65 | headers = [] 66 | for header in req.rawHeaderList(): 67 | header = { 68 | 'name': str(header), 69 | 'value': str(req.rawHeader(header)) 70 | } 71 | headers.append(header) 72 | 73 | self.m_idCounter += 1 74 | self.m_ids[reply] = self.m_idCounter 75 | 76 | data = { 77 | 'id': self.m_idCounter, 78 | 'url': req.url().toString(), 79 | 'method': self.operationToString(op), 80 | 'headers': headers, 81 | 'time': QDateTime.currentDateTime() 82 | } 83 | 84 | reply.readyRead.connect(self.handleStarted) 85 | 86 | do_action('NetworkAccessManagerCreateRequestPost') 87 | 88 | self.resourceRequested.emit(data) 89 | return reply 90 | 91 | def handleFinished(self, reply): 92 | headers = [] 93 | for header in reply.rawHeaderList(): 94 | header = { 95 | 'name': str(header), 96 | 'value': str(reply.rawHeader(header)) 97 | } 98 | headers.append(header) 99 | 100 | data = { 101 | 'stage': 'end', 102 | 'id': self.m_ids[reply], 103 | 'url': reply.url().toString(), 104 | 'status': reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), 105 | 'statusText': reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute), 106 | 'contentType': reply.header(QNetworkRequest.ContentTypeHeader), 107 | 'redirectURL': reply.header(QNetworkRequest.LocationHeader), 108 | 'headers': headers, 109 | 'time': QDateTime.currentDateTime() 110 | } 111 | 112 | del self.m_ids[reply] 113 | if reply in self.m_started: 114 | del self.m_started[self.m_started.index(reply)] 115 | 116 | do_action('NetworkAccessManagerHandleFinished') 117 | 118 | self.resourceReceived.emit(data) 119 | 120 | def handleStarted(self): 121 | reply = self.sender() 122 | if not reply: 123 | return 124 | if reply in self.m_started: 125 | return 126 | 127 | self.m_started.append(reply) 128 | 129 | headers = [] 130 | for header in reply.rawHeaderList(): 131 | header = { 132 | 'name': str(header), 133 | 'value': str(reply.rawHeader(header)) 134 | } 135 | headers.append(header) 136 | 137 | data = { 138 | 'stage': 'start', 139 | 'id': self.m_ids[reply], 140 | 'url': reply.url().toString(), 141 | 'status': reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), 142 | 'statusText': reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute), 143 | 'contentType': reply.header(QNetworkRequest.ContentTypeHeader), 144 | 'bodySize': reply.size(), 145 | 'redirectURL': reply.header(QNetworkRequest.LocationHeader), 146 | 'headers': headers, 147 | 'time': QDateTime.currentDateTime() 148 | } 149 | 150 | do_action('NetworkAccessManagerHandleStarted') 151 | 152 | self.resourceReceived.emit(data) 153 | 154 | def operationToString(self, op): 155 | verb = '?' 156 | 157 | if op == QNetworkAccessManager.HeadOperation: 158 | verb = 'HEAD' 159 | elif op == QNetworkAccessManager.GetOperation: 160 | verb = 'GET' 161 | elif op == QNetworkAccessManager.PutOperation: 162 | verb = 'PUT' 163 | elif op == QNetworkAccessManager.PostOperation: 164 | verb = 'POST' 165 | elif op == QNetworkAccessManager.DeleteOperation: 166 | verb = 'DELETE' 167 | 168 | return verb 169 | 170 | def provideAuthentication(self, reply, authenticator): 171 | authenticator.setUser(self.m_userName) 172 | authenticator.setPassword(self.m_password) 173 | 174 | do_action('NetworkAccessManager') 175 | -------------------------------------------------------------------------------- /pyphantomjs/phantom.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import os 21 | import sys 22 | 23 | from PyQt4.QtCore import pyqtProperty, pyqtSlot, QObject 24 | from PyQt4.QtGui import QApplication 25 | from PyQt4.QtNetwork import QNetworkProxy, QNetworkProxyFactory 26 | 27 | from __init__ import __version_info__ 28 | from encoding import Encode 29 | from filesystem import FileSystem 30 | from plugincontroller import do_action 31 | from utils import QPyFile 32 | from webpage import injectJsInFrame, WebPage 33 | from webserver import WebServer 34 | 35 | 36 | class Phantom(QObject): 37 | def __init__(self, parent, args): 38 | super(Phantom, self).__init__(parent) 39 | 40 | # variable declarations 41 | self.m_defaultPageSettings = {} 42 | self.m_pages = [] 43 | self.m_servers = [] 44 | self.m_verbose = args.verbose 45 | self.m_page = WebPage(self, args) 46 | self.m_returnValue = 0 47 | self.m_terminated = False 48 | # setup the values from args 49 | self.app_args = args 50 | self.m_scriptFile = args.script 51 | self.m_args = args.script_args 52 | self.m_scriptEncoding = Encode(args.script_encoding, 'utf-8') 53 | self.m_outputEncoding = Encode(args.output_encoding, sys.stdout.encoding_sys) 54 | 55 | self.m_pages.append(self.m_page) 56 | 57 | do_action('PhantomInitPre') 58 | 59 | if args.proxy is None: 60 | QNetworkProxyFactory.setUseSystemConfiguration(True) 61 | else: 62 | proxy = QNetworkProxy(args.proxy_type, args.proxy[0], int(args.proxy[1])) 63 | QNetworkProxy.setApplicationProxy(proxy) 64 | 65 | self.m_page.javaScriptConsoleMessageSent.connect(self.printConsoleMessage) 66 | 67 | self.m_defaultPageSettings['loadImages'] = args.load_images 68 | self.m_defaultPageSettings['loadPlugins'] = args.load_plugins 69 | self.m_defaultPageSettings['javascriptEnabled'] = True 70 | self.m_defaultPageSettings['XSSAuditingEnabled'] = False 71 | self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() 72 | self.m_defaultPageSettings['localToRemoteUrlAccessEnabled'] = args.local_to_remote_url_access 73 | self.m_page.applySettings(self.m_defaultPageSettings) 74 | 75 | self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) 76 | 77 | # inject our properties and slots into javascript 78 | self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) 79 | 80 | with QPyFile(':/bootstrap.js') as f: 81 | self.m_page.mainFrame().evaluateJavaScript(f.readAll()) 82 | 83 | do_action('PhantomInitPost') 84 | 85 | def execute(self): 86 | injectJsInFrame(self.m_scriptFile, self.m_scriptEncoding.encoding, os.path.dirname(os.path.abspath(__file__)), self.m_page.mainFrame(), True) 87 | return not self.m_terminated 88 | 89 | def printConsoleMessage(self, message, lineNumber, source): 90 | if source: 91 | message = '%s:%d %s' % (source, lineNumber, message) 92 | print message 93 | 94 | def returnValue(self): 95 | return self.m_returnValue 96 | 97 | ## 98 | # Properties and methods exposed to JavaScript 99 | ## 100 | 101 | @pyqtProperty('QStringList') 102 | def args(self): 103 | return self.m_args 104 | 105 | @pyqtSlot(result=FileSystem) 106 | def createFilesystem(self): 107 | return FileSystem(self) 108 | 109 | @pyqtSlot(result=WebPage) 110 | def createWebPage(self): 111 | page = WebPage(self, self.app_args) 112 | self.m_pages.append(page) 113 | page.applySettings(self.m_defaultPageSettings) 114 | page.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) 115 | return page 116 | 117 | @pyqtSlot(result=WebServer) 118 | def createWebServer(self): 119 | server = WebServer(self) 120 | self.m_servers.append(server) 121 | # :TODO: 122 | # page.applySettings(self.m_defaultPageSettings) 123 | # page.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile) 124 | return server 125 | 126 | @pyqtProperty('QVariantMap') 127 | def defaultPageSettings(self): 128 | return self.m_defaultPageSettings 129 | 130 | @pyqtSlot() 131 | @pyqtSlot(int) 132 | def exit(self, code=0): 133 | self.m_terminated = True 134 | self.m_returnValue = code 135 | 136 | # stop javascript execution in start script; 137 | # release all pages, then clear 138 | # the page list, and empty the Phantom page 139 | for page in self.m_pages: 140 | page.release() 141 | del self.m_pages[:] 142 | self.m_page = None 143 | 144 | for server in self.m_servers: 145 | server.release() 146 | del self.m_servers[:] # not needed, but I'd rather be thorough 147 | 148 | QApplication.instance().exit(code) 149 | 150 | @pyqtSlot(str, result=bool) 151 | def injectJs(self, filePath): 152 | return injectJsInFrame(filePath, self.m_scriptEncoding.encoding, self.libraryPath, self.m_page.mainFrame()) 153 | 154 | @pyqtSlot(str, result=str) 155 | def loadModuleSource(self, name): 156 | moduleSourceFilePath = ':/modules/%s.js' % name 157 | 158 | with QPyFile(moduleSourceFilePath) as f: 159 | return f.readAll() 160 | 161 | @pyqtProperty(str) 162 | def libraryPath(self): 163 | return self.m_page.libraryPath 164 | 165 | @libraryPath.setter 166 | def libraryPath(self, dirPath): 167 | self.m_page.libraryPath = dirPath 168 | 169 | @pyqtProperty(str) 170 | def outputEncoding(self): 171 | return self.m_outputEncoding.name 172 | 173 | @outputEncoding.setter 174 | def outputEncoding(self, encoding): 175 | self.m_outputEncoding = Encode(encoding, self.m_outputEncoding.encoding) 176 | 177 | sys.stdout.encoding = self.m_outputEncoding.encoding 178 | sys.stdout.encode_to = self.m_outputEncoding.encoding 179 | sys.stderr.encoding = self.m_outputEncoding.encoding 180 | sys.stdout.encode_to = self.m_outputEncoding.encoding 181 | 182 | @pyqtProperty(str) 183 | def scriptName(self): 184 | return os.path.basename(self.m_scriptFile) 185 | 186 | @pyqtProperty('QVariantMap') 187 | def version(self): 188 | version = { 189 | 'major': __version_info__[0], 190 | 'minor': __version_info__[1], 191 | 'patch': __version_info__[2] 192 | } 193 | return version 194 | 195 | do_action('Phantom') 196 | -------------------------------------------------------------------------------- /pyphantomjs/plugincontroller.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import os 21 | import sys 22 | from collections import defaultdict 23 | from glob import glob 24 | 25 | 26 | hooks = defaultdict(dict) 27 | 28 | 29 | def createHook(func): 30 | '''Decorator that will create a hook if the hook doesn't exist''' 31 | def innerWrap(*args, **kwargs): 32 | if args[0] not in hooks: 33 | hooks[args[0]]['count'] = 0 34 | hooks[args[0]]['plugins'] = [] 35 | return func(*args, **kwargs) 36 | return innerWrap 37 | 38 | 39 | def checkHookExists(func): 40 | '''Decorator that will raise LookupError if the hook doesn't exist''' 41 | def innerWrap(*args, **kwargs): 42 | if args[0] not in hooks: 43 | raise LookupError("Hook '%s' was not found" % args[0]) 44 | return func(*args, **kwargs) 45 | return innerWrap 46 | 47 | 48 | @createHook 49 | def add_action(hook, priority=10): 50 | '''Decorator to be used for registering a function to 51 | a specific hook. Functions with lower priority are 52 | executed first (priority of 1 for example). 53 | ''' 54 | def register(func): 55 | hooks[hook]['plugins'].append((priority, func)) 56 | return func 57 | return register 58 | 59 | 60 | @checkHookExists 61 | def did_action(hook): 62 | '''Find out how many times a hook was fired''' 63 | return hooks[hook]['count'] 64 | 65 | 66 | @createHook 67 | def do_action(hook, *args, **kwargs): 68 | '''Trigger a hook. It will run any functions that have registered 69 | themselves to the hook. Any additional arguments or keyword 70 | arguments you pass in will be passed to the functions. 71 | ''' 72 | # sort plugins by priority 73 | hooks[hook]['plugins'].sort() 74 | for plugin in hooks[hook]['plugins']: 75 | hooks[hook]['count'] += 1 76 | plugin[1](*args, **kwargs) 77 | 78 | 79 | def get(name, depth=4, scope='local'): 80 | '''Gets the value of a variable in the parents namespace 81 | 82 | Args: 83 | depth controls how deep to go into the stack 84 | scope controls the namespace used; valid values are: local,global,builtin 85 | ''' 86 | if scope == 'local': 87 | scope = 'f_locals' 88 | elif scope == 'global': 89 | scope = 'f_globals' 90 | elif scope == 'builtin': 91 | scope = 'f_builtins' 92 | 93 | return getattr(sys._getframe(depth), scope)[name] 94 | 95 | 96 | def has_action(hook, func=None): 97 | '''Check if hook exists. If function is specified, 98 | check if function has been registered for hook. 99 | ''' 100 | if func is None: 101 | if hook in hooks: 102 | return True 103 | else: 104 | if hook not in hooks: 105 | raise LookupError("Hook '%s' was not found" % hook) 106 | 107 | for plugin in hooks[hook]['plugins']: 108 | if plugin[1] is func: 109 | return True 110 | return False 111 | 112 | 113 | def remove_action(hook, func=None, priority=10): 114 | '''Remove hook if hook exists. If function is specified, 115 | remove function from hook. If priority is not same as 116 | functions priority, it will not remove the function. 117 | ''' 118 | if func is None: 119 | if hook in hooks: 120 | del hooks[hook] 121 | return True 122 | else: 123 | if hook not in hooks: 124 | raise LookupError("Hook '%s' was not found" % hook) 125 | 126 | for i, plugin in enumerate(hooks[hook]['plugins']): 127 | if plugin[1] is func and plugin[0] == priority: 128 | del hooks[hook]['plugins'][i] 129 | return True 130 | return False 131 | 132 | 133 | @checkHookExists 134 | def remove_all_actions(hook, priority=None): 135 | '''Remove all functions that have been registered to hook. 136 | If priority is used, remove all actions from that priority 137 | instead. 138 | ''' 139 | if priority is None: 140 | del hooks[hook][:] 141 | else: 142 | indexes = [] 143 | for i, plugin in enumerate(hooks[hook]['plugins']): 144 | if plugin[0] == priority: 145 | indexes.append(i) 146 | for index in indexes: 147 | del hooks[hook]['plugins'][index] 148 | 149 | 150 | def set_(name, value, depth=4, scope='local'): 151 | '''Sets the value of a variable in the parents namespace 152 | 153 | Args: 154 | depth controls how deep to go into the stack 155 | scope controls the namespace used; valid values are: local,global,builtin 156 | ''' 157 | if scope == 'local': 158 | scope = 'f_locals' 159 | elif scope == 'global': 160 | scope = 'f_globals' 161 | elif scope == 'builtin': 162 | scope = 'f_builtins' 163 | 164 | getattr(sys._getframe(depth), scope)[name] = value 165 | 166 | 167 | def load_plugins(): 168 | ''' Loads the plugins. 169 | 170 | Plugins must be in folders under plugins/ (or plugins_path), 171 | and must also be the same name as the plugin folder. 172 | 173 | E.g. a plugin folder named my_plugin will 174 | have my_plugin.py inside the folder loaded. 175 | ''' 176 | plugins_path = os.environ.get('PYPHANTOMJS_PLUGINS_PATH') 177 | 178 | if plugins_path is None: 179 | # path is different when frozen 180 | if hasattr(sys, 'frozen'): 181 | plugins_path = os.path.dirname(os.path.abspath(sys.executable)) 182 | else: 183 | plugins_path = os.path.dirname(os.path.abspath(__file__)) 184 | 185 | plugins_path = os.path.join(plugins_path, 'plugins') 186 | else: 187 | # make sure it's an absolute path 188 | plugins_path = os.path.abspath(plugins_path) 189 | 190 | sys.path.insert(1, plugins_path) 191 | 192 | plugin_list = glob(os.path.join(plugins_path, '*/*.py')) 193 | 194 | # now convert list to [('plugin_folder', 'file'), ...] 195 | plugin_list = [(os.path.split(os.path.dirname(f))[1], os.path.splitext(os.path.split(f)[1])[0]) for f in plugin_list] 196 | 197 | # initialize plugins 198 | for plugin in plugin_list: 199 | if plugin[0] == plugin[1]: 200 | moduleName = '.'.join((plugin[0], plugin[1])) 201 | __import__(moduleName, globals(), locals(), [], -1) 202 | -------------------------------------------------------------------------------- /pyphantomjs/plugins/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /pyphantomjs/pyphantomjs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | This file is part of the PyPhantomJS project. 4 | 5 | Copyright (C) 2011 James Roe 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | ''' 20 | 21 | # automatically convert Qt types by using api 2 22 | import sip 23 | for item in ('QDate', 'QDateTime', 'QString', 'QTextStream', 'QTime' 24 | 'QUrl', 'QVariant'): 25 | sip.setapi(item, 2) 26 | 27 | import sys 28 | 29 | from PyQt4.QtGui import QApplication, QIcon 30 | 31 | from plugincontroller import do_action 32 | # load plugins if running script directly 33 | if __name__ == '__main__': 34 | from plugincontroller import load_plugins 35 | load_plugins() 36 | 37 | import resources 38 | from __init__ import __version__ 39 | from arguments import parseArgs 40 | from phantom import Phantom 41 | 42 | # make keyboard interrupt quit program 43 | import signal 44 | signal.signal(signal.SIGINT, signal.SIG_DFL) 45 | 46 | # output unicode safe text 47 | from utils import SafeStreamFilter 48 | sys.stdout = SafeStreamFilter(sys.stdout) 49 | sys.stderr = SafeStreamFilter(sys.stderr) 50 | 51 | 52 | def main(arguments): 53 | app = QApplication([sys.argv[0]] + arguments) 54 | 55 | app.setWindowIcon(QIcon(':/resources/pyphantomjs-icon.png')) 56 | app.setApplicationName('PyPhantomJS') 57 | app.setOrganizationName('Umaclan Development') 58 | app.setOrganizationDomain('www.umaclan.com') 59 | app.setApplicationVersion(__version__) 60 | 61 | args = parseArgs(app, arguments) 62 | 63 | phantom = Phantom(app, args) 64 | 65 | do_action('Main') 66 | 67 | if phantom.execute(): 68 | app.exec_() 69 | return phantom.returnValue() 70 | 71 | 72 | do_action('PyPhantomJS') 73 | 74 | 75 | if __name__ == '__main__': 76 | sys.exit(main(sys.argv[1:])) 77 | -------------------------------------------------------------------------------- /pyphantomjs/resources.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | bootstrap.js 4 | configurator.js 5 | modules/fs.js 6 | modules/webpage.js 7 | modules/webserver.js 8 | resources/coffee-script.js 9 | resources/pyphantomjs-icon.png 10 | 11 | 12 | -------------------------------------------------------------------------------- /pyphantomjs/resources/pyphantomjs-icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kanzure/pyphantomjs/e878516bb10f6ce27302aabb5a5f30247ea261b8/pyphantomjs/resources/pyphantomjs-icon.ico -------------------------------------------------------------------------------- /pyphantomjs/resources/pyphantomjs-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kanzure/pyphantomjs/e878516bb10f6ce27302aabb5a5f30247ea261b8/pyphantomjs/resources/pyphantomjs-icon.png -------------------------------------------------------------------------------- /pyphantomjs/tools/build_binary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | This file is part of the PyPhantomJS project. 4 | 5 | Copyright (C) 2011 James Roe 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | ''' 20 | 21 | import os 22 | import sys 23 | 24 | # hack to import parent module(s) 25 | parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 26 | sys.path = [parent_dir] + sys.path 27 | 28 | from __init__ import __version__ 29 | 30 | try: 31 | from cx_Freeze import setup, Executable 32 | except ImportError: 33 | sys.exit('cx_Freeze must be installed to use this script') 34 | 35 | if sys.platform.startswith('win'): 36 | try: 37 | from win32verstamp import stamp 38 | except ImportError: 39 | from time import sleep 40 | print '*** WARNING ***' 41 | print 'the script will be unable to create the version resource' 42 | print 'install pywin32 extensions if you want the file stamped' 43 | sleep(2) 44 | 45 | 46 | def qt4_plugins_dir(): 47 | from PyQt4.QtCore import QCoreApplication 48 | app = QCoreApplication([]) 49 | 50 | qt4_plugin_dirs = map(unicode, app.libraryPaths()) 51 | if not qt4_plugin_dirs: 52 | return 53 | for d in qt4_plugin_dirs: 54 | if os.path.isdir(d): 55 | return str(d) # must be 8-bit chars for one-file builds 56 | 57 | qt4_plugin_dir = qt4_plugins_dir() 58 | if qt4_plugin_dir is None: 59 | sys.exit('Cannot find PyQt4 plugins directory') 60 | 61 | 62 | # modules to include 63 | includes = [ 64 | # to make sure images are supported; jpeg, gif, svg, etc. 65 | 'PyQt4.QtSvg', 66 | 'PyQt4.QtXml' 67 | ] 68 | 69 | # files/directories to include 70 | include_files = [ 71 | # to make sure images are supported; jpeg, gif, svg, etc. 72 | (os.path.join(qt4_plugin_dir, 'imageformats'), 'imageformats'), 73 | (os.path.join(parent_dir, 'plugins'), 'plugins'), 74 | (os.path.join(parent_dir, '../../examples'), 'examples'), 75 | (os.path.join(parent_dir, '../LICENSE'), 'LICENSE.txt'), 76 | (os.path.join(parent_dir, '../README.md'), 'README.txt'), 77 | (os.path.join(parent_dir, '../../ChangeLog'), 'ChangeLog.txt') 78 | ] 79 | 80 | 81 | exe = Executable( 82 | script = os.path.join(parent_dir, 'pyphantomjs.py'), 83 | icon = os.path.join(parent_dir, 'resources/pyphantomjs-icon.ico') 84 | ) 85 | 86 | 87 | setup( 88 | name = 'PyPhantomJS', 89 | version = __version__, 90 | description = 'Minimalistic, headless, WebKit-based, JavaScript-driven tool', 91 | options = {'build_exe': {'includes': includes, 'include_files': include_files}}, 92 | executables = [exe] 93 | ) 94 | -------------------------------------------------------------------------------- /pyphantomjs/tools/build_resources.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # This script will convert each qrc into a 5 | # Python resource file(s) which can be used 6 | # 7 | 8 | # change to script directory 9 | cd `dirname "$0"` 10 | 11 | # convert each filename.qrc to respective filename.py 12 | for f in ../*.qrc; do 13 | pyrcc4 -compress 2 -o "${f%.*}.py" "$f" 14 | done 15 | -------------------------------------------------------------------------------- /pyphantomjs/utils.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import sys 21 | 22 | from PyQt4.QtCore import (QByteArray, QDateTime, QFile, Qt, 23 | QtCriticalMsg, QtDebugMsg, QtFatalMsg, 24 | QtWarningMsg) 25 | 26 | 27 | def debug(debug_type): 28 | def excepthook(type_, value, tb): 29 | import traceback 30 | 31 | # print the exception... 32 | traceback.print_exception(type_, value, tb) 33 | print 34 | # ...then start the debugger in post-mortem mode 35 | pdb.pm() 36 | 37 | # we are NOT in interactive mode 38 | if not hasattr(sys, 'ps1') or sys.stderr.target.isatty(): 39 | import pdb 40 | 41 | from PyQt4.QtCore import pyqtRemoveInputHook 42 | pyqtRemoveInputHook() 43 | 44 | if debug_type == 'exception': 45 | sys.excepthook = excepthook 46 | elif debug_type == 'program': 47 | pdb.set_trace() 48 | 49 | 50 | class CaseInsensitiveDict(dict): 51 | def __delitem__(self, key): 52 | for dictKey in self: 53 | if self.sameKey(key, dictKey): 54 | super(CaseInsensitiveDict, self).__delitem__(dictKey) 55 | return 56 | 57 | raise KeyError(key) 58 | 59 | def __contains__(self, key): 60 | for dictKey in self: 61 | if self.sameKey(key, dictKey): 62 | return True 63 | return False 64 | 65 | def __getitem__(self, key): 66 | for dictKey, dictValue in self.items(): 67 | if self.sameKey(key, dictKey): 68 | return dictValue 69 | 70 | raise KeyError(key) 71 | 72 | def __setitem__(self, key, value): 73 | for dictKey in self: 74 | if self.sameKey(key, dictKey): 75 | super(CaseInsensitiveDict, self).__setitem__(dictKey, value) 76 | return 77 | 78 | super(CaseInsensitiveDict, self).__setitem__(key, value) 79 | 80 | def sameKey(self, key, dictKey): 81 | if hasattr(key, 'lower'): 82 | key = key.lower() 83 | if hasattr(dictKey, 'lower'): 84 | dictKey = dictKey.lower() 85 | 86 | if key == dictKey: 87 | return True 88 | return False 89 | 90 | 91 | class MessageHandler(object): 92 | def __init__(self, verbose): 93 | self.verbose = verbose 94 | 95 | def process(self, msgType, msg): 96 | now = QDateTime.currentDateTime().toString(Qt.ISODate) 97 | 98 | if msgType == QtDebugMsg: 99 | if self.verbose: 100 | print '%s [DEBUG] %s' % (now, msg) 101 | elif msgType == QtWarningMsg: 102 | print >> sys.stderr, '%s [WARNING] %s' % (now, msg) 103 | elif msgType == QtCriticalMsg: 104 | print >> sys.stderr, '%s [CRITICAL] %s' % (now, msg) 105 | elif msgType == QtFatalMsg: 106 | print >> sys.stderr, '%s [FATAL] %s' % (now, msg) 107 | 108 | 109 | class SafeStreamFilter(object): 110 | '''Convert string to something safe''' 111 | def __init__(self, target): 112 | self.target = target 113 | self.encoding = self.encode_to = self.encoding_sys = self.target.encoding or 'utf-8' 114 | self.errors = 'replace' 115 | 116 | def write(self, s): 117 | s = self.encode(s) 118 | self.target.write(s) 119 | 120 | def flush(self): 121 | self.target.flush() 122 | 123 | def encode(self, s): 124 | return s.encode(self.encode_to, self.errors) 125 | 126 | 127 | class QPyFile(QFile): 128 | '''Simple subclass of QFile which supports the context manager 129 | 130 | It also wraps methods that require/return some foreign data type, 131 | such as QByteArray. 132 | ''' 133 | def __enter__(self): 134 | return self 135 | 136 | def __exit__(self, exc_type, exc_value, traceback): 137 | self.close() 138 | 139 | def __init__(self, filename, mode='r'): 140 | super(QPyFile, self).__init__(filename) 141 | 142 | modeMap = { 143 | 'r': QFile.ReadOnly, 144 | 'r+': QFile.ReadOnly | QFile.WriteOnly, 145 | 'w': QFile.WriteOnly | QFile.Truncate, 146 | 'w+': QFile.WriteOnly | QFile.ReadOnly | QFile.Truncate, 147 | 'a': QFile.Append, 148 | 'a+': QFile.Append | QFile.ReadOnly 149 | } 150 | 151 | flags = QFile.NotOpen 152 | for key, flag in modeMap.items(): 153 | if key in mode: 154 | flags = flags | flag 155 | 156 | if not self.open(flags): 157 | raise IOError("Could not open file: '%s'" % self.fileName()) 158 | 159 | def peek(self, maxlen): 160 | return str(super(QPyFile, self).peek(maxlen)) 161 | 162 | def readAll(self): 163 | return str(super(QPyFile, self).readAll()) 164 | 165 | def write(self, data): 166 | return super(QPyFile, self).write(QByteArray(data)) 167 | -------------------------------------------------------------------------------- /pyphantomjs/webpage.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import codecs 21 | import os 22 | import sys 23 | from cStringIO import StringIO 24 | from math import ceil, floor 25 | 26 | import sip 27 | from PyQt4.QtCore import (pyqtProperty, pyqtSignal, pyqtSlot, QBuffer, 28 | QByteArray, QDir, QEvent, QEventLoop, QFileInfo, 29 | QObject, QPoint, QRect, QSize, QSizeF, Qt, QUrl, 30 | qDebug) 31 | from PyQt4.QtGui import (QApplication, QDesktopServices, QImage, 32 | QMouseEvent, QPainter, QPalette, QPrinter, 33 | QRegion, qRgba) 34 | from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest 35 | from PyQt4.QtWebKit import QWebPage, QWebSettings 36 | 37 | try: 38 | from PIL import Image 39 | except ImportError: 40 | qDebug('PIL not found! Saving to gif files will be disabled.') 41 | 42 | from csconverter import CSConverter 43 | from networkaccessmanager import NetworkAccessManager 44 | from plugincontroller import do_action 45 | 46 | 47 | def injectJsInFrame(filePath, scriptEncoding, libraryPath, targetFrame, startingScript=False): 48 | try: 49 | # if file doesn't exist in the CWD, use the lookup 50 | if not os.path.exists(filePath): 51 | filePath = os.path.join(libraryPath, filePath) 52 | 53 | try: 54 | with codecs.open(filePath, encoding=scriptEncoding) as f: 55 | script = f.read() 56 | except UnicodeError as e: 57 | sys.exit("%s in '%s'" % (e, filePath)) 58 | 59 | if script.startswith('#!') and not filePath.lower().endswith('.coffee'): 60 | script = '//' + script 61 | 62 | if filePath.lower().endswith('.coffee'): 63 | result = CSConverter().convert(script) 64 | if not result[0]: 65 | if startingScript: 66 | sys.exit("%s: '%s'" % (result[1], filePath)) 67 | else: 68 | qDebug("%s: '%s'" % (result[1], filePath)) 69 | script = '' 70 | else: 71 | script = result[1] 72 | 73 | targetFrame.evaluateJavaScript(script) 74 | return True 75 | except IOError as (_, e): 76 | qDebug("%s: '%s'" % (e, filePath)) 77 | return False 78 | 79 | 80 | class CustomPage(QWebPage): 81 | def __init__(self, parent): 82 | super(CustomPage, self).__init__(parent) 83 | 84 | self.m_userAgent = QWebPage.userAgentForUrl(self, QUrl()) 85 | 86 | self.m_uploadFile = '' 87 | 88 | do_action('CustomPageInit') 89 | 90 | def chooseFile(self, originatingFrame, oldFile): 91 | return self.m_uploadFile 92 | 93 | def shouldInterruptJavaScript(self): 94 | QApplication.processEvents(QEventLoop.AllEvents, 42) 95 | return False 96 | 97 | def javaScriptAlert(self, originatingFrame, msg): 98 | self.parent().javaScriptAlertSent.emit(msg) 99 | 100 | def javaScriptConsoleMessage(self, message, lineNumber, sourceID): 101 | self.parent().javaScriptConsoleMessageSent.emit(message, lineNumber, sourceID) 102 | 103 | def userAgentForUrl(self, url): 104 | return self.m_userAgent 105 | 106 | do_action('CustomPage') 107 | 108 | 109 | class WebPage(QObject): 110 | initialized = pyqtSignal() 111 | javaScriptAlertSent = pyqtSignal(str) 112 | javaScriptConsoleMessageSent = pyqtSignal(str, int, str) 113 | loadFinished = pyqtSignal(str) 114 | loadStarted = pyqtSignal() 115 | resourceReceived = pyqtSignal('QVariantMap') 116 | resourceRequested = pyqtSignal('QVariantMap') 117 | 118 | blankHtml = '' 119 | 120 | def __init__(self, parent, args): 121 | super(WebPage, self).__init__(parent) 122 | 123 | # variable declarations 124 | self.m_paperSize = {} 125 | self.m_clipRect = QRect() 126 | self.m_libraryPath = '' 127 | self.m_scrollPosition = QPoint() 128 | 129 | self.setObjectName('WebPage') 130 | self.m_webPage = CustomPage(self) 131 | self.m_mainFrame = self.m_webPage.mainFrame() 132 | self.m_webPage.mainFrame().setHtml(self.blankHtml) 133 | 134 | self.m_mainFrame.javaScriptWindowObjectCleared.connect(self.initialized) 135 | self.m_webPage.loadStarted.connect(self.loadStarted, Qt.QueuedConnection) 136 | self.m_webPage.loadFinished.connect(self.finish, Qt.QueuedConnection) 137 | 138 | # Start with transparent background 139 | palette = self.m_webPage.palette() 140 | palette.setBrush(QPalette.Base, Qt.transparent) 141 | self.m_webPage.setPalette(palette) 142 | 143 | # Page size does not need to take scrollbars into account 144 | self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) 145 | self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) 146 | 147 | self.m_webPage.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) 148 | self.m_webPage.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) 149 | self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True) 150 | self.m_webPage.settings().setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True) 151 | self.m_webPage.settings().setOfflineWebApplicationCachePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) 152 | self.m_webPage.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) 153 | self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) 154 | self.m_webPage.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) 155 | 156 | # Custom network access manager to allow traffic monitoring 157 | self.m_networkAccessManager = NetworkAccessManager(self.parent(), args) 158 | self.m_webPage.setNetworkAccessManager(self.m_networkAccessManager) 159 | self.m_networkAccessManager.resourceRequested.connect(self.resourceRequested) 160 | self.m_networkAccessManager.resourceReceived.connect(self.resourceReceived) 161 | 162 | self.m_webPage.setViewportSize(QSize(400, 300)) 163 | 164 | do_action('WebPageInit') 165 | 166 | def applySettings(self, defaults): 167 | opt = self.m_webPage.settings() 168 | 169 | opt.setAttribute(QWebSettings.AutoLoadImages, defaults['loadImages']) 170 | opt.setAttribute(QWebSettings.PluginsEnabled, defaults['loadPlugins']) 171 | opt.setAttribute(QWebSettings.JavascriptEnabled, defaults['javascriptEnabled']) 172 | opt.setAttribute(QWebSettings.XSSAuditingEnabled, defaults['XSSAuditingEnabled']) 173 | opt.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, defaults['localToRemoteUrlAccessEnabled']) 174 | 175 | if 'userAgent' in defaults: 176 | self.m_webPage.m_userAgent = defaults['userAgent'] 177 | 178 | if 'userName' in defaults: 179 | self.m_networkAccessManager.m_userName = defaults['userName'] 180 | 181 | if 'password' in defaults: 182 | self.m_networkAccessManager.m_password = defaults['password'] 183 | 184 | def finish(self, ok): 185 | status = 'success' if ok else 'fail' 186 | self.loadFinished.emit(status) 187 | 188 | def mainFrame(self): 189 | return self.m_mainFrame 190 | 191 | def renderGif(self, image, fileName): 192 | try: 193 | Image 194 | except NameError: 195 | return False 196 | 197 | buffer_ = QBuffer() 198 | buffer_.open(QBuffer.ReadWrite) 199 | image.save(buffer_, 'PNG') 200 | 201 | stream = StringIO() 202 | stream.write(buffer_.data()) 203 | buffer_.close() 204 | stream.seek(0) 205 | pilimg = Image.open(stream) 206 | 207 | # use the adaptive quantizer instead of the web quantizer; eases off of grainy images 208 | pilimg = pilimg.convert('RGB').convert('P', palette=Image.ADAPTIVE) 209 | 210 | try: 211 | pilimg.save(fileName) 212 | return True 213 | except IOError as (_, e): 214 | qDebug("WebPage.renderGif - %s: '%s'" % (e, fileName)) 215 | return False 216 | 217 | def renderImage(self): 218 | contentsSize = self.m_mainFrame.contentsSize() 219 | contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y()) 220 | frameRect = QRect(QPoint(0, 0), contentsSize) 221 | if not self.m_clipRect.isEmpty(): 222 | frameRect = self.m_clipRect 223 | 224 | viewportSize = self.m_webPage.viewportSize() 225 | self.m_webPage.setViewportSize(contentsSize) 226 | 227 | image = QImage(frameRect.size(), QImage.Format_ARGB32) 228 | image.fill(qRgba(255, 255, 255, 0)) 229 | 230 | painter = QPainter() 231 | 232 | # We use tiling approach to work-around Qt software rasterizer bug 233 | # when dealing with very large paint device. 234 | # See http://code.google.com/p/phantomjs/issues/detail?id=54. 235 | tileSize = 4096 236 | htiles = (image.width() + tileSize - 1) / tileSize 237 | vtiles = (image.height() + tileSize - 1) / tileSize 238 | for x in range(htiles): 239 | for y in range(vtiles): 240 | tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32) 241 | tileBuffer.fill(qRgba(255, 255, 255, 0)) 242 | 243 | # Render the web page onto the small tile first 244 | painter.begin(tileBuffer) 245 | painter.setRenderHint(QPainter.Antialiasing, True) 246 | painter.setRenderHint(QPainter.TextAntialiasing, True) 247 | painter.setRenderHint(QPainter.SmoothPixmapTransform, True) 248 | painter.translate(-frameRect.left(), -frameRect.top()) 249 | painter.translate(-x * tileSize, -y * tileSize) 250 | self.m_mainFrame.render(painter, QRegion(frameRect)) 251 | painter.end() 252 | 253 | # Copy the tile to the main buffer 254 | painter.begin(image) 255 | painter.setCompositionMode(QPainter.CompositionMode_Source) 256 | painter.drawImage(x * tileSize, y * tileSize, tileBuffer) 257 | painter.end() 258 | 259 | self.m_webPage.setViewportSize(viewportSize) 260 | return image 261 | 262 | # Different defaults. 263 | # OSX: 72, X11: 75(?), Windows: 96 264 | pdf_dpi = 72 265 | def renderPdf(self, fileName): 266 | p = QPrinter() 267 | p.setOutputFormat(QPrinter.PdfFormat) 268 | p.setOutputFileName(fileName) 269 | p.setResolution(self.pdf_dpi) 270 | paperSize = self.m_paperSize 271 | 272 | if not len(paperSize): 273 | pageSize = QSize(self.m_webPage.mainFrame().contentsSize()) 274 | paperSize['width'] = str(pageSize.width()) + 'px' 275 | paperSize['height'] = str(pageSize.height()) + 'px' 276 | paperSize['border'] = '0px' 277 | 278 | if paperSize.get('width') and paperSize.get('height'): 279 | sizePt = QSizeF(ceil(self.stringToPointSize(paperSize['width'])), 280 | ceil(self.stringToPointSize(paperSize['height']))) 281 | p.setPaperSize(sizePt, QPrinter.Point) 282 | elif 'format' in paperSize: 283 | orientation = QPrinter.Landscape if paperSize.get('orientation') and paperSize['orientation'].lower() == 'landscape' else QPrinter.Portrait 284 | orientation = QPrinter.Orientation(orientation) 285 | p.setOrientation(orientation) 286 | 287 | formats = { 288 | 'A0': QPrinter.A0, 289 | 'A1': QPrinter.A1, 290 | 'A2': QPrinter.A2, 291 | 'A3': QPrinter.A3, 292 | 'A4': QPrinter.A4, 293 | 'A5': QPrinter.A5, 294 | 'A6': QPrinter.A6, 295 | 'A7': QPrinter.A7, 296 | 'A8': QPrinter.A8, 297 | 'A9': QPrinter.A9, 298 | 'B0': QPrinter.B0, 299 | 'B1': QPrinter.B1, 300 | 'B2': QPrinter.B2, 301 | 'B3': QPrinter.B3, 302 | 'B4': QPrinter.B4, 303 | 'B5': QPrinter.B5, 304 | 'B6': QPrinter.B6, 305 | 'B7': QPrinter.B7, 306 | 'B8': QPrinter.B8, 307 | 'B9': QPrinter.B9, 308 | 'B10': QPrinter.B10, 309 | 'C5E': QPrinter.C5E, 310 | 'Comm10E': QPrinter.Comm10E, 311 | 'DLE': QPrinter.DLE, 312 | 'Executive': QPrinter.Executive, 313 | 'Folio': QPrinter.Folio, 314 | 'Ledger': QPrinter.Ledger, 315 | 'Legal': QPrinter.Legal, 316 | 'Letter': QPrinter.Letter, 317 | 'Tabloid': QPrinter.Tabloid 318 | } 319 | 320 | p.setPaperSize(QPrinter.A4) # fallback 321 | for format_, size in formats.items(): 322 | if format_.lower() == paperSize['format'].lower(): 323 | p.setPaperSize(size) 324 | break 325 | else: 326 | return False 327 | 328 | border = floor(self.stringToPointSize(paperSize['border'])) if paperSize.get('border') else 0 329 | p.setPageMargins(border, border, border, border, QPrinter.Point) 330 | 331 | self.m_webPage.mainFrame().print_(p) 332 | return True 333 | 334 | def stringToPointSize(self, string): 335 | units = ( 336 | ('mm', 72 / 25.4), 337 | ('cm', 72 / 2.54), 338 | ('in', 72.0), 339 | ('px', 72.0 / self.pdf_dpi / 2.54), 340 | ('', 72.0 / self.pdf_dpi / 2.54) 341 | ) 342 | 343 | for unit, format_ in units: 344 | if string.endswith(unit): 345 | value = string.rstrip(unit) 346 | return float(value) * format_ 347 | return 0 348 | 349 | def userAgent(self): 350 | return self.m_webPage.m_userAgent 351 | 352 | ## 353 | # Properties and methods exposed to JavaScript 354 | ## 355 | 356 | @pyqtSlot(str) 357 | def _appendScriptElement(self, scriptUrl): 358 | self.m_mainFrame.evaluateJavaScript(''' 359 | var el = document.createElement('script'); 360 | el.onload = function() { alert('%(scriptUrl)s'); }; 361 | el.src = '%(scriptUrl)s'; 362 | document.body.appendChild(el); 363 | ''' % {'scriptUrl': scriptUrl}) 364 | 365 | @pyqtProperty('QVariantMap') 366 | def clipRect(self): 367 | clipRect = self.m_clipRect 368 | result = { 369 | 'width': clipRect.width(), 370 | 'height': clipRect.height(), 371 | 'top': clipRect.top(), 372 | 'left': clipRect.left() 373 | } 374 | return result 375 | 376 | @clipRect.setter 377 | def clipRect(self, size): 378 | sizes = {'width': 0, 'height': 0, 'top': 0, 'left': 0} 379 | for item in sizes: 380 | try: 381 | sizes[item] = int(size[item]) 382 | if sizes[item] < 0: 383 | if item not in ('top', 'left'): 384 | sizes[item] = 0 385 | except (KeyError, ValueError): 386 | sizes[item] = self.clipRect[item] 387 | 388 | self.m_clipRect = QRect(sizes['left'], sizes['top'], sizes['width'], sizes['height']) 389 | 390 | @pyqtProperty(str) 391 | def content(self): 392 | return self.m_mainFrame.toHtml() 393 | 394 | @content.setter 395 | def content(self, content): 396 | self.m_mainFrame.setHtml(content) 397 | 398 | @pyqtSlot(str, result='QVariant') 399 | def evaluate(self, code): 400 | function = '(%s)()' % code 401 | return self.m_mainFrame.evaluateJavaScript(function) 402 | 403 | @pyqtSlot(str, result=bool) 404 | def injectJs(self, filePath): 405 | return injectJsInFrame(filePath, self.parent().m_scriptEncoding.encoding, self.m_libraryPath, self.m_mainFrame) 406 | 407 | @pyqtProperty(str) 408 | def libraryPath(self): 409 | return self.m_libraryPath 410 | 411 | @libraryPath.setter 412 | def libraryPath(self, dirPath): 413 | self.m_libraryPath = dirPath 414 | 415 | @pyqtSlot(str, str, 'QVariantMap') 416 | @pyqtSlot(str, 'QVariantMap', 'QVariantMap') 417 | def openUrl(self, address, op, settings): 418 | operation = op 419 | body = QByteArray() 420 | 421 | self.applySettings(settings) 422 | self.m_webPage.triggerAction(QWebPage.Stop) 423 | 424 | if type(op) is dict: 425 | operation = op.get('operation') 426 | body = QByteArray(op.get('data', '')) 427 | 428 | if operation == '': 429 | operation = 'get' 430 | 431 | networkOp = QNetworkAccessManager.CustomOperation 432 | operation = operation.lower() 433 | if operation == 'get': 434 | networkOp = QNetworkAccessManager.GetOperation 435 | elif operation == 'head': 436 | networkOp = QNetworkAccessManager.HeadOperation 437 | elif operation == 'put': 438 | networkOp = QNetworkAccessManager.PutOperation 439 | elif operation == 'post': 440 | networkOp = QNetworkAccessManager.PostOperation 441 | elif operation == 'delete': 442 | networkOp = QNetworkAccessManager.DeleteOperation 443 | 444 | if networkOp == QNetworkAccessManager.CustomOperation: 445 | self.m_mainFrame.evaluateJavaScript('console.error("Unknown network operation: %s");' % operation) 446 | return 447 | 448 | if address.lower() == 'about:blank': 449 | self.m_mainFrame.setHtml(self.blankHtml) 450 | else: 451 | self.m_mainFrame.load(QNetworkRequest(QUrl(address)), networkOp, body) 452 | 453 | @pyqtProperty('QVariantMap') 454 | def paperSize(self): 455 | return self.m_paperSize 456 | 457 | @paperSize.setter 458 | def paperSize(self, size): 459 | self.m_paperSize = size 460 | 461 | @pyqtSlot() 462 | def release(self): 463 | self.parent().m_pages.remove(self) 464 | sip.delete(self) 465 | 466 | @pyqtSlot(str, result=bool) 467 | def render(self, fileName): 468 | if self.m_mainFrame.contentsSize() == '': 469 | return False 470 | 471 | fileInfo = QFileInfo(fileName) 472 | path = QDir() 473 | path.mkpath(fileInfo.absolutePath()) 474 | 475 | if fileName.lower().endswith('.pdf'): 476 | return self.renderPdf(fileName) 477 | 478 | image = self.renderImage() 479 | if fileName.lower().endswith('.gif'): 480 | return self.renderGif(image, fileName) 481 | 482 | return image.save(fileName) 483 | 484 | @pyqtSlot(str, 'QVariant', 'QVariant') 485 | def sendEvent(self, type_, arg1, arg2): 486 | type_ = type_.lower() 487 | 488 | if type_ in ('mousedown', 'mouseup', 'mousemove'): 489 | eventType = QMouseEvent.Type(QEvent.None) 490 | button = Qt.MouseButton(Qt.LeftButton) 491 | buttons = Qt.MouseButtons(Qt.LeftButton) 492 | 493 | if type_ == 'mousedown': 494 | eventType = QEvent.MouseButtonPress 495 | elif type_ == 'mouseup': 496 | eventType = QEvent.MouseButtonRelease 497 | elif type_ == 'mousemove': 498 | eventType = QEvent.MouseMove 499 | button = buttons = Qt.NoButton 500 | 501 | assert eventType != QEvent.None 502 | 503 | event = QMouseEvent(eventType, QPoint(arg1, arg2), button, buttons, Qt.NoModifier) 504 | QApplication.postEvent(self.m_webPage, event) 505 | QApplication.processEvents() 506 | 507 | return 508 | 509 | if type_ == 'click': 510 | self.sendEvent('mousedown', arg1, arg2) 511 | self.sendEvent('mouseup', arg1, arg2) 512 | 513 | @pyqtProperty('QVariantMap') 514 | def scrollPosition(self): 515 | scroll = self.m_scrollPosition 516 | result = { 517 | 'left': scroll.x(), 518 | 'top': scroll.y() 519 | } 520 | return result 521 | 522 | @scrollPosition.setter 523 | def scrollPosition(self, size): 524 | positions = {'left': 0, 'top': 0} 525 | for item in positions: 526 | try: 527 | positions[item] = int(size[item]) 528 | if positions[item] < 0: 529 | positions[item] = 0 530 | except (KeyError, ValueError): 531 | positions[item] = self.scrollPosition[item] 532 | self.m_scrollPosition = QPoint(positions['left'], positions['top']) 533 | self.m_mainFrame.setScrollPosition(self.m_scrollPosition) 534 | 535 | @pyqtSlot(str, str) 536 | def uploadFile(self, selector, fileName): 537 | el = self.m_mainFrame.findFirstElement(selector) 538 | if el.isNull(): 539 | return 540 | 541 | self.m_webPage.m_uploadFile = fileName 542 | el.evaluateJavaScript(''' 543 | (function (el) { 544 | var ev = document.createEvent('MouseEvents'); 545 | ev.initEvent('click', true, true); 546 | el.dispatchEvent(ev); 547 | })(this) 548 | ''') 549 | 550 | @pyqtProperty('QVariantMap') 551 | def viewportSize(self): 552 | size = self.m_webPage.viewportSize() 553 | result = { 554 | 'width': size.width(), 555 | 'height': size.height() 556 | } 557 | return result 558 | 559 | @viewportSize.setter 560 | def viewportSize(self, size): 561 | sizes = {'width': 0, 'height': 0} 562 | for item in sizes: 563 | try: 564 | sizes[item] = int(size[item]) 565 | if sizes[item] < 0: 566 | sizes[item] = 0 567 | except (KeyError, ValueError): 568 | sizes[item] = self.viewportSize[item] 569 | 570 | self.m_webPage.setViewportSize(QSize(sizes['width'], sizes['height'])) 571 | 572 | do_action('WebPage') 573 | -------------------------------------------------------------------------------- /pyphantomjs/webserver.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import socket 21 | from BaseHTTPServer import (__version__ as __server_version__, 22 | BaseHTTPRequestHandler, HTTPServer) 23 | from cStringIO import StringIO 24 | from threading import Thread 25 | from SocketServer import ThreadingMixIn 26 | from urlparse import urlparse 27 | 28 | import sip 29 | from PyQt4.QtCore import (pyqtProperty, pyqtSignal, pyqtSlot, Q_ARG, 30 | qDebug, QMetaObject, QObject, Qt, QThread) 31 | 32 | from __init__ import __version__ 33 | from plugincontroller import do_action 34 | from utils import CaseInsensitiveDict 35 | 36 | 37 | servers = [] 38 | 39 | 40 | class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): 41 | pass 42 | 43 | 44 | class WebServer(QObject): 45 | newRequest = pyqtSignal(QObject, QObject) 46 | 47 | def __init__(self, parent): 48 | super(WebServer, self).__init__(parent) 49 | 50 | self.setObjectName('WebServer') 51 | 52 | self.m_port = 0 53 | self.httpd = None 54 | 55 | servers.append(self) 56 | 57 | do_action('WebServerInit') 58 | 59 | def __del__(self): 60 | self.close() 61 | 62 | @pyqtSlot() 63 | def close(self): 64 | if self.httpd is not None: 65 | self.httpd.shutdown() 66 | self.m_port = 0 67 | 68 | @pyqtSlot(int, result=bool) 69 | def listenOnPort(self, port): 70 | try: 71 | self.httpd = ThreadingHTTPServer(('localhost', port), WebServerHandler) 72 | Thread(target=self.httpd.serve_forever).start() 73 | except socket.error as (_, e): 74 | qDebug('WebServer.listenOnPort - %s' % e) 75 | self.m_port = 0 76 | return False 77 | else: 78 | self.m_port = port 79 | return True 80 | 81 | @pyqtProperty(int) 82 | def port(self): 83 | return self.m_port 84 | 85 | @pyqtSlot() 86 | def release(self): 87 | self.close() 88 | servers.remove(self) 89 | self.parent().m_servers.remove(self) 90 | sip.delete(self) 91 | 92 | do_action('WebServer') 93 | 94 | 95 | class WebServerHandler(BaseHTTPRequestHandler): 96 | protocol_version = 'HTTP/1.1' 97 | server_version = 'BaseHTTP/%s PyPhantomJS/%s' % (__server_version__, __version__) 98 | 99 | def handle_one_request(self): 100 | '''Handle a single HTTP request. 101 | 102 | A patch to the request handling: 103 | 104 | * This removes the functionality which calls do_X(), 105 | and simply calls our handleRequest() directly. 106 | * If do_X() didn't exist, a 501 unsupported 107 | method error would be returned. Since we patched 108 | that out as well, the user can actually handle when 109 | a request is or isn't valid through the code. 110 | * Then we handle the request and response. 111 | ''' 112 | try: 113 | self.raw_requestline = self.rfile.readline(65537) 114 | if len(self.raw_requestline) > 65536: 115 | self.requestline = '' 116 | self.request_version = '' 117 | self.command = '' 118 | self.send_error(414) 119 | return 120 | if not self.raw_requestline: 121 | self.close_connection = 1 122 | return 123 | if not self.parse_request(): 124 | # An error code has been sent, just exit 125 | return 126 | 127 | # these variables must get (re)set on every request 128 | # for handleRequest(), due to the HTTP/1.1 nature of 129 | # keepalive, which seems to keep a constant running 130 | # instance of this class 131 | self.m_handleResponse = True 132 | self.m_headers = CaseInsensitiveDict() 133 | self.m_statusCode = 200 134 | self.m_wfile = StringIO() 135 | 136 | self.handleRequest() 137 | 138 | # some methods handle the response on their own instead 139 | if self.m_handleResponse: 140 | self.handleResponse() 141 | 142 | self.wfile.flush() #actually send the response if not already done. 143 | except socket.timeout, e: 144 | #a read or a write timed out. Discard this connection 145 | self.log_error("Request timed out: %r", e) 146 | self.close_connection = 1 147 | return 148 | 149 | def handleResponse(self): 150 | # send response code with response text (ex. 200 OK) 151 | self.send_response(self.m_statusCode, self.responses[self.m_statusCode][0]) 152 | 153 | # send all headers 154 | for name, value in self.m_headers.items(): 155 | self.send_header(name, value) 156 | 157 | # send content-length if not already sent 158 | if self.protocol_version == 'HTTP/1.1': 159 | if 'content-length' not in self.m_headers: 160 | if self.m_statusCode >= 200 and self.m_statusCode not in (204, 304): 161 | self.send_header('Content-Length', self.m_wfile.tell()) 162 | 163 | self.end_headers() #finish sending the headers 164 | 165 | # check if body should be written to response 166 | if self.command != 'HEAD' and self.m_statusCode >= 200 and self.m_statusCode not in (204, 304): 167 | self.wfile.write(self.m_wfile.getvalue()) #write body to page 168 | 169 | def handleRequest(self): 170 | request = WebServerRequest(self) 171 | response = WebServerResponse(self) 172 | 173 | for server in servers: 174 | # verify which server this request is for 175 | if self.server == server.httpd: 176 | connectionType = Qt.BlockingQueuedConnection 177 | if QThread.currentThread() == server.thread(): 178 | connectionType = Qt.DirectConnection 179 | 180 | QMetaObject.invokeMethod(server, 'newRequest', connectionType, 181 | Q_ARG(WebServerRequest, request), 182 | Q_ARG(WebServerResponse, response)) 183 | break 184 | 185 | def log_message(self, format, *args): 186 | qDebug("%s - - %s" % (self.address_string(), 187 | format % args)) 188 | 189 | do_action('WebServerHandler') 190 | 191 | 192 | class WebServerResponse(QObject): 193 | def __init__(self, conn): 194 | super(WebServerResponse, self).__init__() 195 | 196 | self.setObjectName('WebServerResponse') 197 | 198 | self.m_conn = conn 199 | 200 | do_action('WebServerResponseInit') 201 | 202 | @pyqtSlot(str, result=str) 203 | def header(self, name): 204 | return self.m_conn.m_headers.get(name, '') 205 | 206 | @pyqtProperty('QVariantMap') 207 | def headers(self): 208 | return self.m_conn.m_headers 209 | 210 | @headers.setter 211 | def headers(self, headers): 212 | self.m_conn.m_headers = CaseInsensitiveDict(headers) 213 | 214 | @pyqtSlot(int) 215 | @pyqtSlot(int, str) 216 | def sendError(self, code, message=None): 217 | self.m_conn.send_error(code, message) 218 | self.m_conn.m_handleResponse = False 219 | 220 | @pyqtSlot(str, str) 221 | def setHeader(self, name, value): 222 | self.m_conn.m_headers[name] = value 223 | 224 | @pyqtProperty(int) 225 | def statusCode(self): 226 | return self.m_conn.m_statusCode 227 | 228 | @statusCode.setter 229 | def statusCode(self, code): 230 | self.m_conn.m_statusCode = code 231 | 232 | @pyqtSlot(str) 233 | def write(self, body): 234 | self.m_conn.m_wfile.write(body) 235 | 236 | @pyqtSlot(int, 'QVariantMap') 237 | def writeHead(self, code, headers): 238 | self.m_conn.m_statusCode = code 239 | self.m_conn.m_headers = CaseInsensitiveDict(headers) 240 | 241 | do_action('WebServerResponse') 242 | 243 | 244 | class WebServerRequest(QObject): 245 | def __init__(self, request): 246 | super(WebServerRequest, self).__init__() 247 | 248 | self.setObjectName('WebServerRequest') 249 | 250 | self.m_request = request 251 | self.m_headerNames = list(request.headers) 252 | self.m_headers = CaseInsensitiveDict(request.headers) 253 | self.m_numHeaders = len(request.headers) 254 | 255 | do_action('WebServerRequestInit') 256 | 257 | @pyqtSlot(int, result=str) 258 | def headerName(self, header): 259 | if header <= self.m_numHeaders: 260 | return self.m_headerNames[header] 261 | return '' 262 | 263 | @pyqtProperty(int) 264 | def headers(self): 265 | return self.m_numHeaders 266 | 267 | @pyqtSlot(int, result=str) 268 | def headerValue(self, header): 269 | if header <= self.m_numHeaders: 270 | return self.m_request.headers[self.m_headerNames[header]] 271 | return '' 272 | 273 | @pyqtProperty(str) 274 | def httpVersion(self): 275 | return self.m_request.request_version[-3:] 276 | 277 | @pyqtProperty(int) 278 | def isSSL(self): 279 | return 0 280 | 281 | @pyqtProperty(str) 282 | def method(self): 283 | return self.m_request.command 284 | 285 | @pyqtProperty(str) 286 | def remoteIP(self): 287 | return self.m_request.client_address[0] 288 | 289 | @pyqtProperty(int) 290 | def remotePort(self): 291 | return self.m_request.client_address[1] 292 | 293 | @pyqtProperty(str) 294 | def remoteUser(self): 295 | try: 296 | return self.m_headers['REMOTE_USER'] 297 | except KeyError: 298 | return '' 299 | 300 | #@pyqtProperty(int) 301 | #def statusCode(self): 302 | # return self.m_request.status_code 303 | 304 | @pyqtProperty(str) 305 | def url(self): 306 | return self.m_request.path 307 | 308 | @pyqtProperty(str) 309 | def queryString(self): 310 | return urlparse(self.m_request.path).query 311 | 312 | do_action('WebServerRequest') 313 | -------------------------------------------------------------------------------- /scripts/pyphantomjs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | This file is part of the PyPhantomJS project. 4 | 5 | Copyright (C) 2011 James Roe 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | ''' 20 | 21 | from runpy import run_module 22 | 23 | # automatically convert Qt types by using api 2 24 | import sip 25 | for item in ('QDate', 'QDateTime', 'QString', 'QTextStream', 'QTime' 26 | 'QUrl', 'QVariant'): 27 | sip.setapi(item, 2) 28 | 29 | if __name__ == '__main__': 30 | run_module('pyphantomjs.pyphantomjs', run_name='__main__') 31 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is part of the PyPhantomJS project. 3 | 4 | Copyright (C) 2011 James Roe 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | ''' 19 | 20 | import os 21 | from setuptools import setup, find_packages 22 | 23 | from pyphantomjs import __version__ 24 | 25 | 26 | def read(fname): 27 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 28 | 29 | 30 | README = read('README.md') 31 | INSTALL = read('INSTALL.md') 32 | 33 | index = README.find('LICENSING') 34 | if index > -1: 35 | README = README[:index] + INSTALL + '\n\n' + README[index:] 36 | else: 37 | README += INSTALL 38 | 39 | mainWarningPrinted = False 40 | mainWarning = ('\nWARNING: PyPhantomJS requires additional libraries, which were not found!\n' 41 | ' Refer to the README or INSTALL file for installation information.\n') 42 | for module in ('PyQt4', 'PIL'): 43 | try: 44 | __import__(module) 45 | except ImportError: 46 | if not mainWarningPrinted: 47 | print mainWarning 48 | mainWarningPrinted = True 49 | print "* '%s' library not found" % module 50 | 51 | 52 | setup( 53 | name='PyPhantomJS', 54 | version=__version__, 55 | description='Minimalistic, headless, WebKit-based, JavaScript-driven tool', 56 | long_description=README, 57 | url = 'https://github.com/Roejames12/phantomjs', 58 | license = 'GNU General Public License (GPL)', 59 | author='James Roe', 60 | author_email='roejames12@hotmail.com', 61 | packages=find_packages(), 62 | include_package_data=True, 63 | install_requires=['argparse'], 64 | scripts = ['scripts/pyphantomjs'], 65 | classifiers = [ 66 | 'Development Status :: 5 - Production/Stable', 67 | 'Environment :: Console', 68 | 'Intended Audience :: Developers', 69 | 'License :: OSI Approved :: GNU General Public License (GPL)', 70 | 'Operating System :: OS Independent', 71 | 'Programming Language :: Python', 72 | 'Topic :: Internet :: WWW/HTTP :: Browsers' 73 | ], 74 | zip_safe=False 75 | ) 76 | --------------------------------------------------------------------------------