From: Andrew Lorimer Date: Fri, 7 May 2021 13:24:37 +0000 (+1000) Subject: restructure project, add setuptools files X-Git-Tag: v0.0.1~1 X-Git-Url: https://git.lorimer.id.au/ppt-control.git/diff_plain/7cb045a41bc2a2cff810b5176cac78ddf6fbc27b?hp=ee4eafe3cd5e26aaf93702af45cd58eee1b90d03 restructure project, add setuptools files --- diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0fa4b27 --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +# ppt-control + +An interface for controlling PowerPoint slideshows over the network using WebSocket. With the included HTTP frontend, this package can essentially replicate PowerPoint's presenter view on any computer on the local network, with very low processing latency for commands. + +This was originally designed for controlling a PowerPoint slideshow from an instance of OBS (Open Broadcaster Software) running on the same computer (removing the need for an extra monitor to show presenter view). + +This package includes three main components: +1. The daemon, which runs in the background, independently of PowerPoint, and listens for WebSocket commands and hosts an HTTP server for the frontend +2. The HTTP frontend, written in JavaScript, which displays status information and sends commands to the daemon through WebSocket (this can be docked in one of OBS's "custom browser docks") +3. The OBS script, which allows a mapping of keyboard shortcuts to commands within OBS in order to control the slideshow from anywhere in OBS (keyboard shortcuts are implemented in the HTTP interface but only work when this is focused in OBS) + +Due to the implementation's use of `pywin32` for COM communication, this daemon only works on Windows (but the HTTP and WebSocket interfaces can be accessed from any device). + +## Installation + +`pip install ppt-control` +will install all three components. You can then start the daemon by running +`py -m ppt_control` +from a command prompt (note the underscore). There are a few steps to set the package up fully: + +### Starting the daemon at bootup + +To start the daemon automatically at login, run +`pip show ppt-control` +and get the location of the package. Create a shortcut to `ppt_control.py` in Explorer and put it in `%AppData%\Microsoft\Windows\Start Menu\Programs\Startup`. + +### Using the HTTP interface in OBS + +To view the HTTP interface from within OBS, you can add a "custom browser dock" (View -> Docks -> Custom Browser Docks). The location should be the hostname and port number of the daemon (`http://localhost` by default). You can refresh the custom browser dock with Ctrl+R. + +### Global keyboard shortcuts in OBS + +Keyboard shortcuts in OBS browser docks only work when the browser dock is focused by clicking in it (there is actually no indication of focus in the interface, but if you click away from the browser dock the shortcuts will not work). To resolve this, there is another Python script called `ppt_control_obs.py` which can be added as a custom script in OBS. This script will listen for specific keys (configured in OBS's Hotkeys settings) and send commands to the daemon directly over WebSocket (no HTTP involved). To add the custom script, go to Tools -> Scripts, then click the + and choose the script. This will be located in the package directory which can be found with +`pip show ppt-control` +as above. It is a good idea to turn off the keyboard shortcuts in the HTTP interface after loading the OBS hotkey script, otherwise commands will be sent to the daemon twice when the browser dock is focused. + +## Configuration + +Various settings can be changed in `%AppData%\ppt-control\ppt-control.ini`. This file is populated with the defaults for all possible settings at installation. diff --git a/ppt-control.ini b/ppt-control.ini new file mode 100644 index 0000000..a9b9bdd --- /dev/null +++ b/ppt-control.ini @@ -0,0 +1,14 @@ +[Main] +logging = debug +cache = C:\Windows\Temp\ppt-cache +cache_format = JPG +cache_timeout = 300 +blackwhite = both + +[HTTP] +interface = +port = 80 + +[WebSocket] +interface = 0.0.0.0 +port = 5678 diff --git a/ppt_control/__init__.py b/ppt_control/__init__.py new file mode 100644 index 0000000..8115f6b --- /dev/null +++ b/ppt_control/__init__.py @@ -0,0 +1,5 @@ +from os import getenv + +__version__ = "0.0.1" +__name__ = "ppt-control" +__configdir__ = getenv("APPDATA") + "\\" + __name__ diff --git a/ppt_control/__main__.py b/ppt_control/__main__.py new file mode 100644 index 0000000..588f74c --- /dev/null +++ b/ppt_control/__main__.py @@ -0,0 +1,6 @@ +""" +Executed when ppt_control is executed as a script +""" + +from .ppt_control import start_interface +start_interface() diff --git a/ppt_control/config.py b/ppt_control/config.py new file mode 100644 index 0000000..7964cc9 --- /dev/null +++ b/ppt_control/config.py @@ -0,0 +1,43 @@ +from configparser import ConfigParser +from pkg_resources import Requirement, resource_filename + +global prefs +prefs = None + +defaults = { + 'Main': { + 'logging': 'info', + 'cache': r'''C:\Windows\Temp\ppt-cache''', + 'cache_format': 'JPG', + 'cache_timeout': 5*60, + 'blackwhite': 'both' + }, + 'HTTP': { + 'interface': '', + 'port': 80 + }, + 'WebSocket': { + 'interface': '0.0.0.0', + 'port': 5678 + } +} + + +def loadconf(configpaths): + """ + Initial setup for a ConfigParser object. `configpaths` should be a list of + configuration files to load (typically only one). To use the generated + ConfigParser, use `import logparse.config` and then `config.prefs.get(..)`. + The prefs object is returned after creation as a convenience but this method + should only be called once per runtime. + """ + prefs = ConfigParser() + prefs.read_dict(defaults) + try: + success = prefs.read(configpaths) + print("Loaded {0} config file(s): {1}".format( + str(len(success)), str(success))) + except Exception as e: + print("Error processing config: " + str(e)) + return prefs + diff --git a/ppt_control/http_server_39.py b/ppt_control/http_server_39.py new file mode 100755 index 0000000..def05f4 --- /dev/null +++ b/ppt_control/http_server_39.py @@ -0,0 +1,1294 @@ +"""HTTP server classes. + +Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see +SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, +and CGIHTTPRequestHandler for CGI scripts. + +It does, however, optionally implement HTTP/1.1 persistent connections, +as of version 0.3. + +Notes on CGIHTTPRequestHandler +------------------------------ + +This class implements GET and POST requests to cgi-bin scripts. + +If the os.fork() function is not present (e.g. on Windows), +subprocess.Popen() is used as a fallback, with slightly altered semantics. + +In all cases, the implementation is intentionally naive -- all +requests are executed synchronously. + +SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL +-- it may execute arbitrary Python code or external programs. + +Note that status code 200 is sent prior to execution of a CGI script, so +scripts cannot send other status codes such as 302 (redirect). + +XXX To do: + +- log requests even later (to capture byte count) +- log user-agent header and other interesting goodies +- send error log to separate file +""" + + +# See also: +# +# HTTP Working Group T. Berners-Lee +# INTERNET-DRAFT R. T. Fielding +# H. Frystyk Nielsen +# Expires September 8, 1995 March 8, 1995 +# +# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt +# +# and +# +# Network Working Group R. Fielding +# Request for Comments: 2616 et al +# Obsoletes: 2068 June 1999 +# Category: Standards Track +# +# URL: http://www.faqs.org/rfcs/rfc2616.html + +# Log files +# --------- +# +# Here's a quote from the NCSA httpd docs about log file format. +# +# | The logfile format is as follows. Each line consists of: +# | +# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb +# | +# | host: Either the DNS name or the IP number of the remote client +# | rfc931: Any information returned by identd for this person, +# | - otherwise. +# | authuser: If user sent a userid for authentication, the user name, +# | - otherwise. +# | DD: Day +# | Mon: Month (calendar name) +# | YYYY: Year +# | hh: hour (24-hour format, the machine's timezone) +# | mm: minutes +# | ss: seconds +# | request: The first line of the HTTP request as sent by the client. +# | ddd: the status code returned by the server, - if not available. +# | bbbb: the total number of bytes sent, +# | *not including the HTTP/1.0 header*, - if not available +# | +# | You can determine the name of the file accessed through request. +# +# (Actually, the latter is only true if you know the server configuration +# at the time the request was made!) + +__version__ = "0.6" + +__all__ = [ + "HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", + "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler", +] + +import copy +import datetime +import email.utils +import html +import http.client +import io +import mimetypes +import os +import posixpath +import select +import shutil +import socket # For gethostbyaddr() +import socketserver +import sys +import time +import urllib.parse +import contextlib +from functools import partial + +from http import HTTPStatus + + +# Default error message template +DEFAULT_ERROR_MESSAGE = """\ + + + + + Error response + + +

Error response

+

Error code: %(code)d

+

Message: %(message)s.

+

Error code explanation: %(code)s - %(explain)s.

+ + +""" + +DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8" + +class HTTPServer(socketserver.TCPServer): + + allow_reuse_address = 1 # Seems to make sense in testing environment + + def server_bind(self): + """Override server_bind to store the server name.""" + socketserver.TCPServer.server_bind(self) + host, port = self.server_address[:2] + self.server_name = socket.getfqdn(host) + self.server_port = port + + +class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): + daemon_threads = True + + +class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): + + """HTTP request handler base class. + + The following explanation of HTTP serves to guide you through the + code as well as to expose any misunderstandings I may have about + HTTP (so you don't need to read the code to figure out I'm wrong + :-). + + HTTP (HyperText Transfer Protocol) is an extensible protocol on + top of a reliable stream transport (e.g. TCP/IP). The protocol + recognizes three parts to a request: + + 1. One line identifying the request type and path + 2. An optional set of RFC-822-style headers + 3. An optional data part + + The headers and data are separated by a blank line. + + The first line of the request has the form + + + + where is a (case-sensitive) keyword such as GET or POST, + is a string containing path information for the request, + and should be the string "HTTP/1.0" or "HTTP/1.1". + is encoded using the URL encoding scheme (using %xx to signify + the ASCII character with hex code xx). + + The specification specifies that lines are separated by CRLF but + for compatibility with the widest range of clients recommends + servers also handle LF. Similarly, whitespace in the request line + is treated sensibly (allowing multiple spaces between components + and allowing trailing whitespace). + + Similarly, for output, lines ought to be separated by CRLF pairs + but most clients grok LF characters just fine. + + If the first line of the request has the form + + + + (i.e. is left out) then this is assumed to be an HTTP + 0.9 request; this form has no optional headers and data part and + the reply consists of just the data. + + The reply form of the HTTP 1.x protocol again has three parts: + + 1. One line giving the response code + 2. An optional set of RFC-822-style headers + 3. The data + + Again, the headers and data are separated by a blank line. + + The response code line has the form + + + + where is the protocol version ("HTTP/1.0" or "HTTP/1.1"), + is a 3-digit response code indicating success or + failure of the request, and is an optional + human-readable string explaining what the response code means. + + This server parses the request and the headers, and then calls a + function specific to the request type (). Specifically, + a request SPAM will be handled by a method do_SPAM(). If no + such method exists the server sends an error response to the + client. If it exists, it is called with no arguments: + + do_SPAM() + + Note that the request name is case sensitive (i.e. SPAM and spam + are different requests). + + The various request details are stored in instance variables: + + - client_address is the client IP address in the form (host, + port); + + - command, path and version are the broken-down request line; + + - headers is an instance of email.message.Message (or a derived + class) containing the header information; + + - rfile is a file object open for reading positioned at the + start of the optional input data part; + + - wfile is a file object open for writing. + + IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! + + The first thing to be written must be the response line. Then + follow 0 or more header lines, then a blank line, and then the + actual data (if any). The meaning of the header lines depends on + the command executed by the server; in most cases, when data is + returned, there should be at least one header line of the form + + Content-type: / + + where and should be registered MIME types, + e.g. "text/html" or "text/plain". + + """ + + # The Python system version, truncated to its first component. + sys_version = "Python/" + sys.version.split()[0] + + # The server software version. You may want to override this. + # The format is multiple whitespace-separated strings, + # where each string is of the form name[/version]. + server_version = "BaseHTTP/" + __version__ + + error_message_format = DEFAULT_ERROR_MESSAGE + error_content_type = DEFAULT_ERROR_CONTENT_TYPE + + # The default request version. This only affects responses up until + # the point where the request line is parsed, so it mainly decides what + # the client gets back when sending a malformed request line. + # Most web servers default to HTTP 0.9, i.e. don't send a status line. + default_request_version = "HTTP/0.9" + + def parse_request(self): + """Parse a request (internal). + + The request should be stored in self.raw_requestline; the results + are in self.command, self.path, self.request_version and + self.headers. + + Return True for success, False for failure; on failure, any relevant + error response has already been sent back. + + """ + self.command = None # set in case of error on the first line + self.request_version = version = self.default_request_version + self.close_connection = True + requestline = str(self.raw_requestline, 'iso-8859-1') + requestline = requestline.rstrip('\r\n') + self.requestline = requestline + words = requestline.split() + if len(words) == 0: + return False + + if len(words) >= 3: # Enough to determine protocol version + version = words[-1] + try: + if not version.startswith('HTTP/'): + raise ValueError + base_version_number = version.split('/', 1)[1] + version_number = base_version_number.split(".") + # RFC 2145 section 3.1 says there can be only one "." and + # - major and minor numbers MUST be treated as + # separate integers; + # - HTTP/2.4 is a lower version than HTTP/2.13, which in + # turn is lower than HTTP/12.3; + # - Leading zeros MUST be ignored by recipients. + if len(version_number) != 2: + raise ValueError + version_number = int(version_number[0]), int(version_number[1]) + except (ValueError, IndexError): + self.send_error( + HTTPStatus.BAD_REQUEST, + "Bad request version (%r)" % version) + return False + if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": + self.close_connection = False + if version_number >= (2, 0): + self.send_error( + HTTPStatus.HTTP_VERSION_NOT_SUPPORTED, + "Invalid HTTP version (%s)" % base_version_number) + return False + self.request_version = version + + if not 2 <= len(words) <= 3: + self.send_error( + HTTPStatus.BAD_REQUEST, + "Bad request syntax (%r)" % requestline) + return False + command, path = words[:2] + if len(words) == 2: + self.close_connection = True + if command != 'GET': + self.send_error( + HTTPStatus.BAD_REQUEST, + "Bad HTTP/0.9 request type (%r)" % command) + return False + self.command, self.path = command, path + + # Examine the headers and look for a Connection directive. + try: + self.headers = http.client.parse_headers(self.rfile, + _class=self.MessageClass) + except http.client.LineTooLong as err: + self.send_error( + HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE, + "Line too long", + str(err)) + return False + except http.client.HTTPException as err: + self.send_error( + HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE, + "Too many headers", + str(err) + ) + return False + + conntype = self.headers.get('Connection', "") + if conntype.lower() == 'close': + self.close_connection = True + elif (conntype.lower() == 'keep-alive' and + self.protocol_version >= "HTTP/1.1"): + self.close_connection = False + # Examine the headers and look for an Expect directive + expect = self.headers.get('Expect', "") + if (expect.lower() == "100-continue" and + self.protocol_version >= "HTTP/1.1" and + self.request_version >= "HTTP/1.1"): + if not self.handle_expect_100(): + return False + return True + + def handle_expect_100(self): + """Decide what to do with an "Expect: 100-continue" header. + + If the client is expecting a 100 Continue response, we must + respond with either a 100 Continue or a final response before + waiting for the request body. The default is to always respond + with a 100 Continue. You can behave differently (for example, + reject unauthorized requests) by overriding this method. + + This method should either return True (possibly after sending + a 100 Continue response) or send an error response and return + False. + + """ + self.send_response_only(HTTPStatus.CONTINUE) + self.end_headers() + return True + + def handle_one_request(self): + """Handle a single HTTP request. + + You normally don't need to override this method; see the class + __doc__ string for information on how to handle specific HTTP + commands such as GET and POST. + + """ + try: + self.raw_requestline = self.rfile.readline(65537) + if len(self.raw_requestline) > 65536: + self.requestline = '' + self.request_version = '' + self.command = '' + self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG) + return + if not self.raw_requestline: + self.close_connection = True + return + if not self.parse_request(): + # An error code has been sent, just exit + return + mname = 'do_' + self.command + if not hasattr(self, mname): + self.send_error( + HTTPStatus.NOT_IMPLEMENTED, + "Unsupported method (%r)" % self.command) + return + method = getattr(self, mname) + method() + self.wfile.flush() #actually send the response if not already done. + except socket.timeout as e: + #a read or a write timed out. Discard this connection + self.log_error("Request timed out: %r", e) + self.close_connection = True + return + + def handle(self): + """Handle multiple requests if necessary.""" + self.close_connection = True + + self.handle_one_request() + while not self.close_connection: + self.handle_one_request() + + def send_error(self, code, message=None, explain=None): + """Send and log an error reply. + + Arguments are + * code: an HTTP error code + 3 digits + * message: a simple optional 1 line reason phrase. + *( HTAB / SP / VCHAR / %x80-FF ) + defaults to short entry matching the response code + * explain: a detailed message defaults to the long entry + matching the response code. + + This sends an error response (so it must be called before any + output has been generated), logs the error, and finally sends + a piece of HTML explaining the error to the user. + + """ + + try: + shortmsg, longmsg = self.responses[code] + except KeyError: + shortmsg, longmsg = '???', '???' + if message is None: + message = shortmsg + if explain is None: + explain = longmsg + self.log_error("code %d, message %s", code, message) + self.send_response(code, message) + self.send_header('Connection', 'close') + + # Message body is omitted for cases described in: + # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified) + # - RFC7231: 6.3.6. 205(Reset Content) + body = None + if (code >= 200 and + code not in (HTTPStatus.NO_CONTENT, + HTTPStatus.RESET_CONTENT, + HTTPStatus.NOT_MODIFIED)): + # HTML encode to prevent Cross Site Scripting attacks + # (see bug #1100201) + content = (self.error_message_format % { + 'code': code, + 'message': html.escape(message, quote=False), + 'explain': html.escape(explain, quote=False) + }) + body = content.encode('UTF-8', 'replace') + self.send_header("Content-Type", self.error_content_type) + self.send_header('Content-Length', str(len(body))) + self.end_headers() + + if self.command != 'HEAD' and body: + self.wfile.write(body) + + def send_response(self, code, message=None): + """Add the response header to the headers buffer and log the + response code. + + Also send two standard headers with the server software + version and the current date. + + """ + self.log_request(code) + self.send_response_only(code, message) + self.send_header('Server', self.version_string()) + self.send_header('Date', self.date_time_string()) + + def send_response_only(self, code, message=None): + """Send the response header only.""" + if self.request_version != 'HTTP/0.9': + if message is None: + if code in self.responses: + message = self.responses[code][0] + else: + message = '' + if not hasattr(self, '_headers_buffer'): + self._headers_buffer = [] + self._headers_buffer.append(("%s %d %s\r\n" % + (self.protocol_version, code, message)).encode( + 'latin-1', 'strict')) + + def send_header(self, keyword, value): + """Send a MIME header to the headers buffer.""" + if self.request_version != 'HTTP/0.9': + if not hasattr(self, '_headers_buffer'): + self._headers_buffer = [] + self._headers_buffer.append( + ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict')) + + if keyword.lower() == 'connection': + if value.lower() == 'close': + self.close_connection = True + elif value.lower() == 'keep-alive': + self.close_connection = False + + def end_headers(self): + """Send the blank line ending the MIME headers.""" + if self.request_version != 'HTTP/0.9': + self._headers_buffer.append(b"\r\n") + self.flush_headers() + + def flush_headers(self): + if hasattr(self, '_headers_buffer'): + self.wfile.write(b"".join(self._headers_buffer)) + self._headers_buffer = [] + + def log_request(self, code='-', size='-'): + """Log an accepted request. + + This is called by send_response(). + + """ + if isinstance(code, HTTPStatus): + code = code.value + self.log_message('"%s" %s %s', + self.requestline, str(code), str(size)) + + def log_error(self, format, *args): + """Log an error. + + This is called when a request cannot be fulfilled. By + default it passes the message on to log_message(). + + Arguments are the same as for log_message(). + + XXX This should go to the separate error log. + + """ + + self.log_message(format, *args) + + def log_message(self, format, *args): + """Log an arbitrary message. + + This is used by all other logging functions. Override + it if you have specific logging wishes. + + The first argument, FORMAT, is a format string for the + message to be logged. If the format string contains + any % escapes requiring parameters, they should be + specified as subsequent arguments (it's just like + printf!). + + The client ip and current date/time are prefixed to + every message. + + """ + + sys.stderr.write("%s - - [%s] %s\n" % + (self.address_string(), + self.log_date_time_string(), + format%args)) + + def version_string(self): + """Return the server software version string.""" + return self.server_version + ' ' + self.sys_version + + def date_time_string(self, timestamp=None): + """Return the current date and time formatted for a message header.""" + if timestamp is None: + timestamp = time.time() + return email.utils.formatdate(timestamp, usegmt=True) + + def log_date_time_string(self): + """Return the current time formatted for logging.""" + now = time.time() + year, month, day, hh, mm, ss, x, y, z = time.localtime(now) + s = "%02d/%3s/%04d %02d:%02d:%02d" % ( + day, self.monthname[month], year, hh, mm, ss) + return s + + weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + + monthname = [None, + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + + def address_string(self): + """Return the client address.""" + + return self.client_address[0] + + # Essentially static class variables + + # The version of the HTTP protocol we support. + # Set this to HTTP/1.1 to enable automatic keepalive + protocol_version = "HTTP/1.0" + + # MessageClass used to parse headers + MessageClass = http.client.HTTPMessage + + # hack to maintain backwards compatibility + responses = { + v: (v.phrase, v.description) + for v in HTTPStatus.__members__.values() + } + + +class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): + + """Simple HTTP request handler with GET and HEAD commands. + + This serves files from the current directory and any of its + subdirectories. The MIME type for files is determined by + calling the .guess_type() method. + + The GET and HEAD requests are identical except that the HEAD + request omits the actual contents of the file. + + """ + + server_version = "SimpleHTTP/" + __version__ + extensions_map = _encodings_map_default = { + '.gz': 'application/gzip', + '.Z': 'application/octet-stream', + '.bz2': 'application/x-bzip2', + '.xz': 'application/x-xz', + } + + def __init__(self, *args, directory=None, **kwargs): + if directory is None: + directory = os.getcwd() + self.directory = os.fspath(directory) + super().__init__(*args, **kwargs) + + def do_GET(self): + """Serve a GET request.""" + f = self.send_head() + if f: + try: + self.copyfile(f, self.wfile) + finally: + f.close() + + def do_HEAD(self): + """Serve a HEAD request.""" + f = self.send_head() + if f: + f.close() + + def send_head(self): + """Common code for GET and HEAD commands. + + This sends the response code and MIME headers. + + Return value is either a file object (which has to be copied + to the outputfile by the caller unless the command was HEAD, + and must be closed by the caller under all circumstances), or + None, in which case the caller has nothing further to do. + + """ + path = self.translate_path(self.path) + f = None + if os.path.isdir(path): + parts = urllib.parse.urlsplit(self.path) + if not parts.path.endswith('/'): + # redirect browser - doing basically what apache does + self.send_response(HTTPStatus.MOVED_PERMANENTLY) + new_parts = (parts[0], parts[1], parts[2] + '/', + parts[3], parts[4]) + new_url = urllib.parse.urlunsplit(new_parts) + self.send_header("Location", new_url) + self.end_headers() + return None + for index in "index.html", "index.htm": + index = os.path.join(path, index) + if os.path.exists(index): + path = index + break + else: + return self.list_directory(path) + ctype = self.guess_type(path) + # check for trailing "/" which should return 404. See Issue17324 + # The test for this was added in test_httpserver.py + # However, some OS platforms accept a trailingSlash as a filename + # See discussion on python-dev and Issue34711 regarding + # parseing and rejection of filenames with a trailing slash + if path.endswith("/"): + self.send_error(HTTPStatus.NOT_FOUND, "File not found") + return None + try: + f = open(path, 'rb') + except OSError: + self.send_error(HTTPStatus.NOT_FOUND, "File not found") + return None + + try: + fs = os.fstat(f.fileno()) + # Use browser cache if possible + if ("If-Modified-Since" in self.headers + and "If-None-Match" not in self.headers): + # compare If-Modified-Since and time of last file modification + try: + ims = email.utils.parsedate_to_datetime( + self.headers["If-Modified-Since"]) + except (TypeError, IndexError, OverflowError, ValueError): + # ignore ill-formed values + pass + else: + if ims.tzinfo is None: + # obsolete format with no timezone, cf. + # https://tools.ietf.org/html/rfc7231#section-7.1.1.1 + ims = ims.replace(tzinfo=datetime.timezone.utc) + if ims.tzinfo is datetime.timezone.utc: + # compare to UTC datetime of last modification + last_modif = datetime.datetime.fromtimestamp( + fs.st_mtime, datetime.timezone.utc) + # remove microseconds, like in If-Modified-Since + last_modif = last_modif.replace(microsecond=0) + + if last_modif <= ims: + self.send_response(HTTPStatus.NOT_MODIFIED) + self.end_headers() + f.close() + return None + + self.send_response(HTTPStatus.OK) + self.send_header("Content-type", ctype) + self.send_header("Content-Length", str(fs[6])) + self.send_header("Last-Modified", + self.date_time_string(fs.st_mtime)) + self.end_headers() + return f + except: + f.close() + raise + + def list_directory(self, path): + """Helper to produce a directory listing (absent index.html). + + Return value is either a file object, or None (indicating an + error). In either case, the headers are sent, making the + interface the same as for send_head(). + + """ + try: + list = os.listdir(path) + except OSError: + self.send_error( + HTTPStatus.NOT_FOUND, + "No permission to list directory") + return None + list.sort(key=lambda a: a.lower()) + r = [] + try: + displaypath = urllib.parse.unquote(self.path, + errors='surrogatepass') + except UnicodeDecodeError: + displaypath = urllib.parse.unquote(path) + displaypath = html.escape(displaypath, quote=False) + enc = sys.getfilesystemencoding() + title = 'Directory listing for %s' % displaypath + r.append('') + r.append('\n') + r.append('' % enc) + r.append('%s\n' % title) + r.append('\n

%s

' % title) + r.append('
\n
    ') + for name in list: + fullname = os.path.join(path, name) + displayname = linkname = name + # Append / for directories or @ for symbolic links + if os.path.isdir(fullname): + displayname = name + "/" + linkname = name + "/" + if os.path.islink(fullname): + displayname = name + "@" + # Note: a link to a directory displays with @ and links with / + r.append('
  • %s
  • ' + % (urllib.parse.quote(linkname, + errors='surrogatepass'), + html.escape(displayname, quote=False))) + r.append('
\n
\n\n\n') + encoded = '\n'.join(r).encode(enc, 'surrogateescape') + f = io.BytesIO() + f.write(encoded) + f.seek(0) + self.send_response(HTTPStatus.OK) + self.send_header("Content-type", "text/html; charset=%s" % enc) + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + return f + + def translate_path(self, path): + """Translate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + """ + # abandon query parameters + path = path.split('?',1)[0] + path = path.split('#',1)[0] + # Don't forget explicit trailing slash when normalizing. Issue17324 + trailing_slash = path.rstrip().endswith('/') + try: + path = urllib.parse.unquote(path, errors='surrogatepass') + except UnicodeDecodeError: + path = urllib.parse.unquote(path) + path = posixpath.normpath(path) + words = path.split('/') + words = filter(None, words) + path = self.directory + for word in words: + if os.path.dirname(word) or word in (os.curdir, os.pardir): + # Ignore components that are not a simple file/directory name + continue + path = os.path.join(path, word) + if trailing_slash: + path += '/' + return path + + def copyfile(self, source, outputfile): + """Copy all data between two file objects. + + The SOURCE argument is a file object open for reading + (or anything with a read() method) and the DESTINATION + argument is a file object open for writing (or + anything with a write() method). + + The only reason for overriding this would be to change + the block size or perhaps to replace newlines by CRLF + -- note however that this the default server uses this + to copy binary data as well. + + """ + shutil.copyfileobj(source, outputfile) + + def guess_type(self, path): + """Guess the type of a file. + + Argument is a PATH (a filename). + + Return value is a string of the form type/subtype, + usable for a MIME Content-type header. + + The default implementation looks the file's extension + up in the table self.extensions_map, using application/octet-stream + as a default; however it would be permissible (if + slow) to look inside the data to make a better guess. + + """ + base, ext = posixpath.splitext(path) + if ext in self.extensions_map: + return self.extensions_map[ext] + ext = ext.lower() + if ext in self.extensions_map: + return self.extensions_map[ext] + guess, _ = mimetypes.guess_type(path) + if guess: + return guess + return 'application/octet-stream' + + +# Utilities for CGIHTTPRequestHandler + +def _url_collapse_path(path): + """ + Given a URL path, remove extra '/'s and '.' path elements and collapse + any '..' references and returns a collapsed path. + + Implements something akin to RFC-2396 5.2 step 6 to parse relative paths. + The utility of this function is limited to is_cgi method and helps + preventing some security attacks. + + Returns: The reconstituted URL, which will always start with a '/'. + + Raises: IndexError if too many '..' occur within the path. + + """ + # Query component should not be involved. + path, _, query = path.partition('?') + path = urllib.parse.unquote(path) + + # Similar to os.path.split(os.path.normpath(path)) but specific to URL + # path semantics rather than local operating system semantics. + path_parts = path.split('/') + head_parts = [] + for part in path_parts[:-1]: + if part == '..': + head_parts.pop() # IndexError if more '..' than prior parts + elif part and part != '.': + head_parts.append( part ) + if path_parts: + tail_part = path_parts.pop() + if tail_part: + if tail_part == '..': + head_parts.pop() + tail_part = '' + elif tail_part == '.': + tail_part = '' + else: + tail_part = '' + + if query: + tail_part = '?'.join((tail_part, query)) + + splitpath = ('/' + '/'.join(head_parts), tail_part) + collapsed_path = "/".join(splitpath) + + return collapsed_path + + + +nobody = None + +def nobody_uid(): + """Internal routine to get nobody's uid""" + global nobody + if nobody: + return nobody + try: + import pwd + except ImportError: + return -1 + try: + nobody = pwd.getpwnam('nobody')[2] + except KeyError: + nobody = 1 + max(x[2] for x in pwd.getpwall()) + return nobody + + +def executable(path): + """Test for executable file.""" + return os.access(path, os.X_OK) + + +class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): + + """Complete HTTP server with GET, HEAD and POST commands. + + GET and HEAD also support running CGI scripts. + + The POST command is *only* implemented for CGI scripts. + + """ + + # Determine platform specifics + have_fork = hasattr(os, 'fork') + + # Make rfile unbuffered -- we need to read one line and then pass + # the rest to a subprocess, so we can't use buffered input. + rbufsize = 0 + + def do_POST(self): + """Serve a POST request. + + This is only implemented for CGI scripts. + + """ + + if self.is_cgi(): + self.run_cgi() + else: + self.send_error( + HTTPStatus.NOT_IMPLEMENTED, + "Can only POST to CGI scripts") + + def send_head(self): + """Version of send_head that support CGI scripts""" + if self.is_cgi(): + return self.run_cgi() + else: + return SimpleHTTPRequestHandler.send_head(self) + + def is_cgi(self): + """Test whether self.path corresponds to a CGI script. + + Returns True and updates the cgi_info attribute to the tuple + (dir, rest) if self.path requires running a CGI script. + Returns False otherwise. + + If any exception is raised, the caller should assume that + self.path was rejected as invalid and act accordingly. + + The default implementation tests whether the normalized url + path begins with one of the strings in self.cgi_directories + (and the next character is a '/' or the end of the string). + + """ + collapsed_path = _url_collapse_path(self.path) + dir_sep = collapsed_path.find('/', 1) + while dir_sep > 0 and not collapsed_path[:dir_sep] in self.cgi_directories: + dir_sep = collapsed_path.find('/', dir_sep+1) + if dir_sep > 0: + head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:] + self.cgi_info = head, tail + return True + return False + + + cgi_directories = ['/cgi-bin', '/htbin'] + + def is_executable(self, path): + """Test whether argument path is an executable file.""" + return executable(path) + + def is_python(self, path): + """Test whether argument path is a Python script.""" + head, tail = os.path.splitext(path) + return tail.lower() in (".py", ".pyw") + + def run_cgi(self): + """Execute a CGI script.""" + dir, rest = self.cgi_info + path = dir + '/' + rest + i = path.find('/', len(dir)+1) + while i >= 0: + nextdir = path[:i] + nextrest = path[i+1:] + + scriptdir = self.translate_path(nextdir) + if os.path.isdir(scriptdir): + dir, rest = nextdir, nextrest + i = path.find('/', len(dir)+1) + else: + break + + # find an explicit query string, if present. + rest, _, query = rest.partition('?') + + # dissect the part after the directory name into a script name & + # a possible additional path, to be stored in PATH_INFO. + i = rest.find('/') + if i >= 0: + script, rest = rest[:i], rest[i:] + else: + script, rest = rest, '' + + scriptname = dir + '/' + script + scriptfile = self.translate_path(scriptname) + if not os.path.exists(scriptfile): + self.send_error( + HTTPStatus.NOT_FOUND, + "No such CGI script (%r)" % scriptname) + return + if not os.path.isfile(scriptfile): + self.send_error( + HTTPStatus.FORBIDDEN, + "CGI script is not a plain file (%r)" % scriptname) + return + ispy = self.is_python(scriptname) + if self.have_fork or not ispy: + if not self.is_executable(scriptfile): + self.send_error( + HTTPStatus.FORBIDDEN, + "CGI script is not executable (%r)" % scriptname) + return + + # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html + # XXX Much of the following could be prepared ahead of time! + env = copy.deepcopy(os.environ) + env['SERVER_SOFTWARE'] = self.version_string() + env['SERVER_NAME'] = self.server.server_name + env['GATEWAY_INTERFACE'] = 'CGI/1.1' + env['SERVER_PROTOCOL'] = self.protocol_version + env['SERVER_PORT'] = str(self.server.server_port) + env['REQUEST_METHOD'] = self.command + uqrest = urllib.parse.unquote(rest) + env['PATH_INFO'] = uqrest + env['PATH_TRANSLATED'] = self.translate_path(uqrest) + env['SCRIPT_NAME'] = scriptname + if query: + env['QUERY_STRING'] = query + env['REMOTE_ADDR'] = self.client_address[0] + authorization = self.headers.get("authorization") + if authorization: + authorization = authorization.split() + if len(authorization) == 2: + import base64, binascii + env['AUTH_TYPE'] = authorization[0] + if authorization[0].lower() == "basic": + try: + authorization = authorization[1].encode('ascii') + authorization = base64.decodebytes(authorization).\ + decode('ascii') + except (binascii.Error, UnicodeError): + pass + else: + authorization = authorization.split(':') + if len(authorization) == 2: + env['REMOTE_USER'] = authorization[0] + # XXX REMOTE_IDENT + if self.headers.get('content-type') is None: + env['CONTENT_TYPE'] = self.headers.get_content_type() + else: + env['CONTENT_TYPE'] = self.headers['content-type'] + length = self.headers.get('content-length') + if length: + env['CONTENT_LENGTH'] = length + referer = self.headers.get('referer') + if referer: + env['HTTP_REFERER'] = referer + accept = self.headers.get_all('accept', ()) + env['HTTP_ACCEPT'] = ','.join(accept) + ua = self.headers.get('user-agent') + if ua: + env['HTTP_USER_AGENT'] = ua + co = filter(None, self.headers.get_all('cookie', [])) + cookie_str = ', '.join(co) + if cookie_str: + env['HTTP_COOKIE'] = cookie_str + # XXX Other HTTP_* headers + # Since we're setting the env in the parent, provide empty + # values to override previously set values + for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', + 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'): + env.setdefault(k, "") + + self.send_response(HTTPStatus.OK, "Script output follows") + self.flush_headers() + + decoded_query = query.replace('+', ' ') + + if self.have_fork: + # Unix -- fork as we should + args = [script] + if '=' not in decoded_query: + args.append(decoded_query) + nobody = nobody_uid() + self.wfile.flush() # Always flush before forking + pid = os.fork() + if pid != 0: + # Parent + pid, sts = os.waitpid(pid, 0) + # throw away additional data [see bug #427345] + while select.select([self.rfile], [], [], 0)[0]: + if not self.rfile.read(1): + break + exitcode = os.waitstatus_to_exitcode(sts) + if exitcode: + self.log_error(f"CGI script exit code {exitcode}") + return + # Child + try: + try: + os.setuid(nobody) + except OSError: + pass + os.dup2(self.rfile.fileno(), 0) + os.dup2(self.wfile.fileno(), 1) + os.execve(scriptfile, args, env) + except: + self.server.handle_error(self.request, self.client_address) + os._exit(127) + + else: + # Non-Unix -- use subprocess + import subprocess + cmdline = [scriptfile] + if self.is_python(scriptfile): + interp = sys.executable + if interp.lower().endswith("w.exe"): + # On Windows, use python.exe, not pythonw.exe + interp = interp[:-5] + interp[-4:] + cmdline = [interp, '-u'] + cmdline + if '=' not in query: + cmdline.append(query) + self.log_message("command: %s", subprocess.list2cmdline(cmdline)) + try: + nbytes = int(length) + except (TypeError, ValueError): + nbytes = 0 + p = subprocess.Popen(cmdline, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env = env + ) + if self.command.lower() == "post" and nbytes > 0: + data = self.rfile.read(nbytes) + else: + data = None + # throw away additional data [see bug #427345] + while select.select([self.rfile._sock], [], [], 0)[0]: + if not self.rfile._sock.recv(1): + break + stdout, stderr = p.communicate(data) + self.wfile.write(stdout) + if stderr: + self.log_error('%s', stderr) + p.stderr.close() + p.stdout.close() + status = p.returncode + if status: + self.log_error("CGI script exit status %#x", status) + else: + self.log_message("CGI script exited OK") + + +def _get_best_family(*address): + infos = socket.getaddrinfo( + *address, + type=socket.SOCK_STREAM, + flags=socket.AI_PASSIVE, + ) + family, type, proto, canonname, sockaddr = next(iter(infos)) + return family, sockaddr + + +def test(HandlerClass=BaseHTTPRequestHandler, + ServerClass=ThreadingHTTPServer, + protocol="HTTP/1.0", port=8000, bind=None): + """Test the HTTP request handler class. + + This runs an HTTP server on port 8000 (or the port argument). + + """ + ServerClass.address_family, addr = _get_best_family(bind, port) + + HandlerClass.protocol_version = protocol + with ServerClass(addr, HandlerClass) as httpd: + host, port = httpd.socket.getsockname()[:2] + url_host = f'[{host}]' if ':' in host else host + print( + f"Serving HTTP on {host} port {port} " + f"(http://{url_host}:{port}/) ..." + ) + try: + httpd.serve_forever() + except KeyboardInterrupt: + print("\nKeyboard interrupt received, exiting.") + sys.exit(0) + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument('--cgi', action='store_true', + help='Run as CGI Server') + parser.add_argument('--bind', '-b', metavar='ADDRESS', + help='Specify alternate bind address ' + '[default: all interfaces]') + parser.add_argument('--directory', '-d', default=os.getcwd(), + help='Specify alternative directory ' + '[default:current directory]') + parser.add_argument('port', action='store', + default=8000, type=int, + nargs='?', + help='Specify alternate port [default: 8000]') + args = parser.parse_args() + if args.cgi: + handler_class = CGIHTTPRequestHandler + else: + handler_class = partial(SimpleHTTPRequestHandler, + directory=args.directory) + + # ensure dual-stack is not disabled; ref #38907 + class DualStackServer(ThreadingHTTPServer): + def server_bind(self): + # suppress exception when protocol is IPv4 + with contextlib.suppress(Exception): + self.socket.setsockopt( + socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) + return super().server_bind() + + test( + HandlerClass=handler_class, + ServerClass=DualStackServer, + port=args.port, + bind=args.bind, + ) diff --git a/ppt_control/ppt_control.py b/ppt_control/ppt_control.py new file mode 100755 index 0000000..6b0f818 --- /dev/null +++ b/ppt_control/ppt_control.py @@ -0,0 +1,579 @@ +import sys +sys.coinit_flags= 0 +import win32com.client +import pywintypes +import os +import shutil +#import http.server as server +import socketserver +import threading +import asyncio +import websockets +import logging, logging.handlers +import json +import urllib +import posixpath +import time +import pythoncom +import pystray +import tkinter as tk +from tkinter import ttk +from PIL import Image +from copy import copy + +import ppt_control.http_server_39 as server +import ppt_control.config as config + +logging.basicConfig() + +global http_daemon +global ws_daemon +global STATE +global STATE_DEFAULT +global current_slideshow +global interface_root +global logger +global refresh_daemon +global status_label +global http_label +global ws_label +global http_server +scheduler = None +current_slideshow = None +CACHEDIR = r'''C:\Windows\Temp\ppt-cache''' +interface_root = None +CONFIG_FILE = r'''..\ppt-control.ini''' +LOGFILE = r'''..\ppt-control.log''' +logger = None +refresh_daemon = None +status_label = None +http_label = None +ws_label = None +ws_daemon = None +http_server = None + + +class Handler(server.SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=os.path.dirname(os.path.realpath(__file__)) + r'''\static''') + + def translate_path(self, path): + """Translate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + """ + # abandon query parameters + path = path.split('?',1)[0] + path = path.split('#',1)[0] + # Don't forget explicit trailing slash when normalizing. Issue17324 + trailing_slash = path.rstrip().endswith('/') + try: + path = urllib.parse.unquote(path, errors='surrogatepass') + except UnicodeDecodeError: + path = urllib.parse.unquote(path) + path = posixpath.normpath(path) + words = path.split('/') + words = list(filter(None, words)) + if len(words) > 0 and words[0] == "cache": + black = 0 + if current_slideshow: + try: + path = CACHEDIR + "\\" + current_slideshow.name() + except Exception as e: + path = os.path.join(os.path.dirname(os.path.realpath(__file__)), r'''\static\black.jpg''') + '/' + logger.warning("Failed to get current slideshow name: ", e) + else: + path = os.path.join(os.path.dirname(os.path.realpath(__file__)), r'''\static\black.jpg''') + '/' + return path + words.pop(0) + else: + path = self.directory + for word in words: + if os.path.dirname(word) or word in (os.curdir, os.pardir): + # Ignore components that are not a simple file/directory name + continue + path = os.path.join(path, word) + if trailing_slash: + path += '/' + return path + + +def run_http(): + global http_server + http_server = server.HTTPServer(("", 80), Handler) + http_server.serve_forever() + +STATE_DEFAULT = {"connected": 0, "current": 0, "total": 0, "visible": 0, "name": ""} +STATE = copy(STATE_DEFAULT) +USERS = set() + + +def state_event(): + return json.dumps({"type": "state", **STATE}) + + +def users_event(): + return json.dumps({"type": "users", "count": len(USERS)}) + + +async def notify_state(): + global STATE + if current_slideshow and STATE["connected"] == 1: + try: + STATE["current"] = current_slideshow.current_slide() + STATE["total"] = current_slideshow.total_slides() + STATE["visible"] = current_slideshow.visible() + STATE["name"] = current_slideshow.name() + except Exception as e: + logger.info("Failed to update state variables, presumably PPT instance doesn't exist anymore: {}".format(e)) + current_slideshow.unload() + else: + STATE = copy(STATE_DEFAULT) + if USERS: # asyncio.wait doesn't accept an empty list + message = state_event() + await asyncio.wait([user.send(message) for user in USERS]) + + +async def notify_users(): + if USERS: # asyncio.wait doesn't accept an empty list + message = users_event() + await asyncio.wait([user.send(message) for user in USERS]) + + +async def register(websocket): + USERS.add(websocket) + await notify_users() + + +async def unregister(websocket): + USERS.remove(websocket) + await notify_users() + + +async def ws_handle(websocket, path): + logger.debug("Received websocket request") + global current_slideshow + # register(websocket) sends user_event() to websocket + await register(websocket) + try: + await websocket.send(state_event()) + async for message in websocket: + data = json.loads(message) + if data["action"] == "prev": + if current_slideshow: + current_slideshow.prev() + await notify_state() + elif data["action"] == "next": + if current_slideshow: + current_slideshow.next() + await notify_state() + elif data["action"] == "first": + if current_slideshow: + current_slideshow.first() + await notify_state() + elif data["action"] == "last": + if current_slideshow: + current_slideshow.last() + await notify_state() + elif data["action"] == "black": + if current_slideshow: + if current_slideshow.visible() == 3: + current_slideshow.normal() + else: + current_slideshow.black() + await notify_state() + elif data["action"] == "white": + if current_slideshow: + if current_slideshow.visible() == 4: + current_slideshow.normal() + else: + current_slideshow.white() + await notify_state() + elif data["action"] == "goto": + if current_slideshow: + current_slideshow.goto(int(data["value"])) + await notify_state() + elif data["action"] == "refresh": + await notify_state() + if current_slideshow: + current_slideshow.export_current_next() + current_slideshow.refresh() + else: + logger.error("unsupported event: {}", data) + finally: + await unregister(websocket) + +def run_ws(): + # https://stackoverflow.com/questions/21141217/how-to-launch-win32-applications-in-separate-threads-in-python/22619084#22619084 + # https://www.reddit.com/r/learnpython/comments/mwt4qi/pywintypescom_error_2147417842_the_application/ + pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) + asyncio.set_event_loop(asyncio.new_event_loop()) + #start_server = websockets.serve(ws_handle, "0.0.0.0", 5678, ping_interval=None) + start_server = websockets.serve(ws_handle, "0.0.0.0", 5678) + asyncio.get_event_loop().run_until_complete(start_server) + asyncio.get_event_loop().run_forever() + +def start_http(): + http_daemon = threading.Thread(name="http_daemon", target=run_http) + http_daemon.setDaemon(True) + http_daemon.start() + logger.info("Started HTTP server") + +def restart_http(): + global http_server + if http_server: + http_server.shutdown() + http_server = None + refresh_status() + start_http() + refresh_status() + +def start_ws(): + global ws_daemon + ws_daemon = threading.Thread(name="ws_daemon", target=run_ws) + ws_daemon.setDaemon(True) + ws_daemon.start() + logger.info("Started websocket server") + +class Slideshow: + def __init__(self, instance): + self.instance = instance + if self.instance is None: + raise ValueError("PPT instance cannot be None") + + if self.instance.SlideShowWindows.Count == 0: + raise ValueError("PPT instance has no slideshow windows") + self.view = self.instance.SlideShowWindows[0].View + + if self.instance.ActivePresentation is None: + raise ValueError("PPT instance has no active presentation") + self.presentation = self.instance.ActivePresentation + + self.export_current_next() + + def unload(self): + connect_ppt() + + def refresh(self): + logger.debug("Refreshing") + try: + if self.instance is None: + raise ValueError("PPT instance cannot be None") + + if self.instance.SlideShowWindows.Count == 0: + raise ValueError("PPT instance has no slideshow windows") + self.view = self.instance.SlideShowWindows[0].View + + if self.instance.ActivePresentation is None: + raise ValueError("PPT instance has no active presentation") + except: + self.unload() + + def total_slides(self): + try: + self.refresh() + return len(self.presentation.Slides) + except (ValueError, pywintypes.com_error): + self.unload() + + def current_slide(self): + try: + self.refresh() + return self.view.CurrentShowPosition + except (ValueError, pywintypes.com_error): + self.unload() + + def visible(self): + try: + self.refresh() + return self.view.State + except (ValueError, pywintypes.com_error): + self.unload() + + def prev(self): + try: + self.refresh() + self.view.Previous() + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def next(self): + try: + self.refresh() + self.view.Next() + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def first(self): + try: + self.refresh() + self.view.First() + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def last(self): + try: + self.refresh() + self.view.Last() + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def goto(self, slide): + try: + self.refresh() + if slide <= self.total_slides(): + self.view.GotoSlide(slide) + else: + self.last() + self.next() + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def black(self): + try: + self.refresh() + self.view.State = 3 + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def white(self): + try: + self.refresh() + self.view.State = 4 + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def normal(self): + try: + self.refresh() + self.view.State = 1 + self.export_current_next() + except (ValueError, pywintypes.com_error): + self.unload() + + def name(self): + try: + self.refresh() + return self.presentation.Name + except (ValueError, pywintypes.com_error): + self.unload() + + + def export_current_next(self): + self.export(self.current_slide()) + self.export(self.current_slide() + 1) + self.export(self.current_slide() + 2) + + def export(self, slide): + destination = CACHEDIR + "\\" + self.name() + "\\" + str(slide) + ".jpg" + os.makedirs(os.path.dirname(destination), exist_ok=True) + if not os.path.exists(destination) or time.time() - os.path.getmtime(destination) > config.prefs.getint("Main", "cache_timeout"): + if slide <= self.total_slides(): + attempts = 0 + while attempts < 3: + try: + self.presentation.Slides(slide).Export(destination, "JPG") + break + except: + pass + attempts += 1 + elif slide == self.total_slides() + 1: + shutil.copyfileobj(open(os.path.dirname(os.path.realpath(__file__)), r'''\static\black.jpg''', 'rb'), open(destination, 'wb')) + else: + pass + + def export_all(self): + for i in range(1, self.total_slides()): + self.export(i) + +def get_ppt_instance(): + instance = win32com.client.Dispatch('Powerpoint.Application') + if instance is None or instance.SlideShowWindows.Count == 0: + return None + return instance + +def get_current_slideshow(): + return current_slideshow + +def refresh_interval(): + while getattr(refresh_daemon, "do_run", True): + logger.debug("Triggering server-side refresh") + current_slideshow.refresh() + refresh_status() + time.sleep(1) + +def refresh_status(): + if status_label is not None: + status_label.config(text="PowerPoint status: " + ("not " if not STATE["connected"] else "") + "connected") + http_label.config(text="HTTP server: " + ("not " if http_server is None else "") + "running") + #ws_label.config(text="WebSocket server: " + ("not " if ws_daemon is not None or not ws_daemon.is_alive() else "") + "running") + +def connect_ppt(): + global STATE + global refresh_daemon + if STATE["connected"] == 1: + logger.info("Disconnected from PowerPoint instance") + refresh_daemon.do_run = False + STATE = copy(STATE_DEFAULT) + refresh_status() + logger.debug("State is now " + str(STATE)) + while True: + try: + instance = get_ppt_instance() + global current_slideshow + current_slideshow = Slideshow(instance) + STATE["connected"] = 1 + STATE["current"] = current_slideshow.current_slide() + STATE["total"] = current_slideshow.total_slides() + refresh_status() + logger.info("Connected to PowerPoint instance") + refresh_daemon = threading.Thread(name="refresh_daemon", target=refresh_interval) + refresh_daemon.setDaemon(True) + refresh_daemon.start() + break + except ValueError as e: + current_slideshow = None + pass + time.sleep(1) + +def start(_=None): + start_http() + start_ws() + connect_ppt() + +def on_closing(): + global status_label + global http_label + global ws_label + status_label = None + http_label = None + ws_label = None + interface_root.destroy() + +def open_settings(_=None): + global interface_root + interface_root = tk.Tk() + interface_root.protocol("WM_DELETE_WINDOW", on_closing) + interface_root.iconphoto(False, tk.PhotoImage(file="static/icons/ppt.png")) + interface_root.geometry("600x300+300+300") + app = Interface(interface_root) + interface_thread = threading.Thread(target=interface_root.mainloop()) + interface_thread.setDaemon(True) + interface_thread.start() + +def null_action(): + pass + +def save_settings(): + pass + +class Interface(ttk.Frame): + + def __init__(self, parent): + ttk.Frame.__init__(self, parent) + + self.parent = parent + + self.initUI() + + def initUI(self): + global status_label + global http_label + global ws_label + self.parent.title("ppt-control") + self.style = ttk.Style() + #self.style.theme_use("default") + self.focus_force() + + self.pack(fill=tk.BOTH, expand=1) + + quitButton = ttk.Button(self, text="Cancel", command=interface_root.destroy) + quitButton.place(x=480, y=280) + + save_button = ttk.Button(self, text="OK", command=save_settings) + save_button.place(x=400, y=280) + + reset_ppt_button = ttk.Button(self, text="Reconnect", command=connect_ppt) + reset_ppt_button.place(x=300, y=10) + + reset_http_button = ttk.Button(self, text="Restart", command=restart_http) + reset_http_button.place(x=300, y=30) + + reset_ws_button = ttk.Button(self, text="Restart", command=null_action) + reset_ws_button.place(x=300, y=50) + + status_label = ttk.Label(self) + status_label.place(x=10,y=10) + + http_label = ttk.Label(self) + http_label.place(x=10,y=30) + + ws_label = ttk.Label(self) + ws_label.place(x=10,y=50) + + refresh_status() + + + +def show_icon(): + logger.debug("Starting system tray icon") + menu = (pystray.MenuItem("Status", lambda: null_action(), enabled=False), + pystray.MenuItem("Restart", lambda: start()), + pystray.MenuItem("Settings", lambda: open_settings())) + icon = pystray.Icon("ppt-control", Image.open(os.path.dirname(os.path.realpath(__file__)) + r'''\static\icons\ppt.ico'''), "ppt-control", menu) + icon.visible = True + icon.run(setup=start) + +def start_interface(): + global logger + + # Load config + config.prefs = config.loadconf(CONFIG_FILE) + + # Set up logging + if config.prefs["Main"]["logging"] == "debug": + log_level = logging.DEBUG + elif config.prefs["Main"]["logging"] == "info": + log_level = logging.CRITICAL + else: + log_level = logging.WARNING + log_level = logging.DEBUG + + log_formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-7.7s] %(message)s") + logger = logging.getLogger("ppt-control") + logger.setLevel(log_level) + logger.propagate = False + + file_handler = logging.FileHandler("{0}/{1}".format(os.getenv("APPDATA"), LOGFILE)) + file_handler.setFormatter(log_formatter) + file_handler.setLevel(log_level) + logger.addHandler(file_handler) + + console_handler = logging.StreamHandler() + console_handler.setFormatter(log_formatter) + console_handler.setLevel(log_level) + logger.addHandler(console_handler) + + logging.getLogger("asyncio").setLevel(logging.ERROR) + logging.getLogger("asyncio.coroutines").setLevel(logging.ERROR) + logging.getLogger("websockets.server").setLevel(logging.ERROR) + logging.getLogger("websockets.protocol").setLevel(logging.ERROR) + + + logger.debug("Finished setting up config and logging") + + # Start systray icon and server + show_icon() + +if __name__ == "__main__": + start_interface() diff --git a/ppt_control/ppt_control_obs.py b/ppt_control/ppt_control_obs.py new file mode 100755 index 0000000..e36957e --- /dev/null +++ b/ppt_control/ppt_control_obs.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- + +import obspython as obs +import asyncio +import websockets +import threading +from time import sleep + +PORT_DEFAULT = 5678 +HOSTNAME_DEFAULT = "localhost" + +hotkey_id_first = None +hotkey_id_prev = None +hotkey_id_next = None +hotkey_id_last = None +hotkey_id_black = None +hotkey_id_white = None + +HOTKEY_NAME_FIRST = 'powerpoint_slides.first' +HOTKEY_NAME_PREV = 'powerpoint_slides.previous' +HOTKEY_NAME_NEXT = 'powerpoint_slides.next' +HOTKEY_NAME_LAST = 'powerpoint_slides.last' +HOTKEY_NAME_BLACK = 'powerpoint_slides.black' +HOTKEY_NAME_WHITE = 'powerpoint_slides.white' + +HOTKEY_DESC_FIRST = 'First PowerPoint slide' +HOTKEY_DESC_PREV = 'Previous PowerPoint slide' +HOTKEY_DESC_NEXT = 'Next PowerPoint slide' +HOTKEY_DESC_LAST = 'Last PowerPoint slide' +HOTKEY_DESC_BLACK = 'Black PowerPoint slide' +HOTKEY_DESC_WHITE = 'White PowerPoint slide' + +global cmd +global attempts +cmd = "" +hostname = HOSTNAME_DEFAULT +port = PORT_DEFAULT +attempts = 0 + +async def communicate(): + async with websockets.connect("ws://%s:%s" % (hostname, port), ping_interval=None) as websocket: + global cmd + global attempts + while True: + if cmd: + try: + await websocket.send('{"action": "%s"}' % cmd) + cmd = "" + except websockets.ConnectionClosed as exc: + attempts += 1 + if attempts == 4: + print("Failed to send command after {} attempts - aborting connection".format(attempts)) + attempts = 0 + cmd = "" + raise websockets.exceptions.ConnectionClosedError(1006, "Sending command failed after {} attempts".format(attempts)) + await asyncio.sleep(0.05 + 0.5*attempts**2) + +def run_ws(): + while True: + try: + asyncio.set_event_loop(asyncio.new_event_loop()) + asyncio.get_event_loop().run_until_complete(communicate()) + except (OSError, websockets.exceptions.ConnectionClosedError): + # No server available - just keep trying + pass + except Exception as e: + print("Failed to connect to websocket: {} - {}".format(type(e), e)) + finally: + sleep(1) + +#------------------------------------------------------------ +# global functions for script plugins + +def script_load(settings): + global hotkey_id_first + global hotkey_id_prev + global hotkey_id_next + global hotkey_id_last + global hotkey_id_black + global hotkey_id_white + + hotkey_id_first = register_and_load_hotkey(settings, HOTKEY_NAME_FIRST, HOTKEY_DESC_FIRST, first_slide) + hotkey_id_prev = register_and_load_hotkey(settings, HOTKEY_NAME_PREV, HOTKEY_DESC_PREV, prev_slide) + hotkey_id_next = register_and_load_hotkey(settings, HOTKEY_NAME_NEXT, HOTKEY_DESC_NEXT, next_slide) + hotkey_id_last = register_and_load_hotkey(settings, HOTKEY_NAME_LAST, HOTKEY_DESC_LAST, last_slide) + hotkey_id_black = register_and_load_hotkey(settings, HOTKEY_NAME_BLACK, HOTKEY_DESC_BLACK, black) + hotkey_id_white = register_and_load_hotkey(settings, HOTKEY_NAME_WHITE, HOTKEY_DESC_WHITE, white) + + ws_daemon = threading.Thread(name="ws_daemon", target=run_ws) + ws_daemon.setDaemon(True) + ws_daemon.start() + print("Started websocket client") + +def script_unload(): + obs.obs_hotkey_unregister(first_slide) + obs.obs_hotkey_unregister(prev_slide) + obs.obs_hotkey_unregister(next_slide) + obs.obs_hotkey_unregister(last_slide) + obs.obs_hotkey_unregister(black) + obs.obs_hotkey_unregister(white) + +def script_save(settings): + save_hotkey(settings, HOTKEY_NAME_FIRST, hotkey_id_first) + save_hotkey(settings, HOTKEY_NAME_PREV, hotkey_id_prev) + save_hotkey(settings, HOTKEY_NAME_NEXT, hotkey_id_next) + save_hotkey(settings, HOTKEY_NAME_LAST, hotkey_id_last) + save_hotkey(settings, HOTKEY_NAME_BLACK, hotkey_id_black) + save_hotkey(settings, HOTKEY_NAME_WHITE, hotkey_id_white) + +def script_description(): + return """ppt-control client + + Provides hotkeys for controlling PowerPoint slides using websockets. + Go to OBS settings -> Hotkeys to change hotkeys (none set by default).""" + +def script_defaults(settings): + obs.obs_data_set_default_string(settings, 'hostname', HOSTNAME_DEFAULT) + obs.obs_data_set_default_int(settings, 'port', PORT_DEFAULT) + +def script_properties(): + props = obs.obs_properties_create() + + obs.obs_properties_add_text(props, "hostname", "Hostname: ", obs.OBS_TEXT_DEFAULT) + obs.obs_properties_add_int(props, "port", "Port: ", 0, 9999, 1) + return props + +def script_update(settings): + global port + port = obs.obs_data_get_int(settings, "port") + hostname = obs.obs_data_get_string(settings, "hostname") + +def register_and_load_hotkey(settings, name, description, callback): + hotkey_id = obs.obs_hotkey_register_frontend(name, description, callback) + hotkey_save_array = obs.obs_data_get_array(settings, name) + obs.obs_hotkey_load(hotkey_id, hotkey_save_array) + obs.obs_data_array_release(hotkey_save_array) + + return hotkey_id + +def save_hotkey(settings, name, hotkey_id): + hotkey_save_array = obs.obs_hotkey_save(hotkey_id) + obs.obs_data_set_array(settings, name, hotkey_save_array) + obs.obs_data_array_release(hotkey_save_array) + +#------------------------------------- + +def first_slide(pressed): + if pressed: + global cmd + cmd = "first" + +def prev_slide(pressed): + if pressed: + global cmd + cmd = "prev" + +def next_slide(pressed): + if pressed: + global cmd + cmd = "next" + +def last_slide(pressed): + if pressed: + global cmd + cmd = "last" + +def black(pressed): + if pressed: + global cmd + cmd = "black" + +def white(pressed): + if pressed: + global cmd + cmd = "white" diff --git a/ppt_control/static/black.jpg b/ppt_control/static/black.jpg new file mode 100755 index 0000000..7b05935 Binary files /dev/null and b/ppt_control/static/black.jpg differ diff --git a/ppt_control/static/icons/first.svg b/ppt_control/static/icons/first.svg new file mode 100644 index 0000000..8d0f155 --- /dev/null +++ b/ppt_control/static/icons/first.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ppt_control/static/icons/last.svg b/ppt_control/static/icons/last.svg new file mode 100644 index 0000000..7064515 --- /dev/null +++ b/ppt_control/static/icons/last.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ppt_control/static/icons/left.svg b/ppt_control/static/icons/left.svg new file mode 100644 index 0000000..acb94c1 --- /dev/null +++ b/ppt_control/static/icons/left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ppt_control/static/icons/ppt.ico b/ppt_control/static/icons/ppt.ico new file mode 100644 index 0000000..460c2ef Binary files /dev/null and b/ppt_control/static/icons/ppt.ico differ diff --git a/ppt_control/static/icons/ppt.png b/ppt_control/static/icons/ppt.png new file mode 100755 index 0000000..841b67b Binary files /dev/null and b/ppt_control/static/icons/ppt.png differ diff --git a/ppt_control/static/icons/right.svg b/ppt_control/static/icons/right.svg new file mode 100644 index 0000000..a9e5aa7 --- /dev/null +++ b/ppt_control/static/icons/right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ppt_control/static/index.html b/ppt_control/static/index.html new file mode 100755 index 0000000..b19415f --- /dev/null +++ b/ppt_control/static/index.html @@ -0,0 +1,49 @@ + + + + + + + ppt-control + + + +
+ +
+

Current slide

+ +
+ +
+

Next slide

+ +
+ +
+ +
+
+

+ + + + + Current: /? + + +

+ + Show current slide + Show next slide + Keyboard shortcuts + +

Not connected

+
+
+ + + + + + diff --git a/ppt_control/static/ppt-control.js b/ppt_control/static/ppt-control.js new file mode 100644 index 0000000..9bba171 --- /dev/null +++ b/ppt_control/static/ppt-control.js @@ -0,0 +1,240 @@ +var DEFAULT_TITLE = "ppt-control" +var preloaded = false; +var preload = []; + +function imageRefresh(id) { + img = document.getElementById(id); + var d = new Date; + var http = img.src; + if (http.indexOf("?t=") != -1) { http = http.split("?t=")[0]; } + img.src = http + '?t=' + d.getTime(); +} + +function startWebsocket() { + ws = new WebSocket("ws://" + window.location.host + ":5678/"); + ws.onclose = function(){ + //websocket = null; + setTimeout(function(){startWebsocket()}, 10000); + } + return ws; +} + +var websocket = startWebsocket(); + +var prev = document.querySelector('#prev'), + next = document.querySelector('#next'), + first = document.querySelector('#first'), + last = document.querySelector('#last'), + black = document.querySelector('#black'), + white = document.querySelector('#white'), + slide_label = document.querySelector('#slide_label'), + current = document.querySelector('#current'), + total = document.querySelector('#total'), + users = document.querySelector('.users'), + current_img = document.querySelector('#current_img'), + next_img = document.querySelector('#next_img'), + current_div = document.querySelector('#current_div'), + next_div = document.querySelector('#next_div'), + controls_container = document.querySelector('#controls_container'), + controls_container_inner = document.querySelector('#controls_container_inner'), + show_current = document.querySelector('#show_current'), + show_next = document.querySelector('#show_next'), + shortcuts = document.querySelector('#shortcuts'); + +prev.onclick = function (event) { + websocket.send(JSON.stringify({action: 'prev'})); +} + +next.onclick = function (event) { + websocket.send(JSON.stringify({action: 'next'})); +} + +first.onclick = function (event) { + websocket.send(JSON.stringify({action: 'first'})); +} + +last.onclick = function (event) { + websocket.send(JSON.stringify({action: 'last'})); +} + +black.onclick = function (event) { + websocket.send(JSON.stringify({action: 'black'})); +} + +white.onclick = function (event) { + websocket.send(JSON.stringify({action: 'white'})); +} + +current.onblur = function (event) { + websocket.send(JSON.stringify({action: 'goto', value: current.value})); +} + +current.addEventListener('keyup',function(e){ + if (e.which == 13) this.blur(); +}); + +current_img.onclick = function (event) { + next.click() +} + +next_img.onclick = function (event) { + next.click() +} + + +function sync_current() { + if (show_current.checked) { + current_div.style.display = "block"; + slide_label.style.display = "none"; + next_div.style.width = "25%"; + } else { + current_div.style.display = "none"; + slide_label.style.display = "inline"; + next_div.style.width = "calc(100% - 20px)"; + } + set_control_width(); + saveSettings(); +} +show_current.onclick = sync_current; + +function sync_next() { + if (show_next.checked) { + next_div.style.display = "block"; + current_div.style.width = "70%"; + } else { + next_div.style.display = "none"; + current_div.style.width = "calc(100% - 20px)"; + } + set_control_width(); + saveSettings(); +} +show_next.onclick = sync_next; + +function sync_shortcuts() { + saveSettings(); +} +shortcuts.onclick = sync_shortcuts; + +function set_control_width() { + var width = window.innerWidth + || document.documentElement.clientWidth + || document.body.clientWidth; + if (show_current.checked && show_next.checked && width > 800) { + controls_container_inner.style.width = "70%" + } else { + controls_container_inner.style.width = "100%" + } +} + + +document.addEventListener('keydown', function (e) { + if (shortcuts.checked) { + switch (e.key) { + case "Left": + case "ArrowLeft": + case "Up": + case "ArrowUp": + case "k": + case "K": + prev.click(); + break; + case " ": + case "Spacebar": + case "Enter": + case "Right": + case "ArrowRight": + case "Down": + case "ArrowDown": + case "j": + case "J": + next.click(); + break; + case "b": + case "B": + black.click(); + case "w": + case "W": + white.click(); + default: + return + } + } +}); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function disconnect() { + document.title = DEFAULT_TITLE; + current_img.src = "/black.jpg"; + next_img.src = "/black.jpg"; + users.textContent = "Connection to PowerPoint failed"; +} + +websocket.onmessage = function (event) { + console.log("Received data"); + data = JSON.parse(event.data); + switch (data.type) { + case 'state': + if (data.connected == "0" || data.connected == 0) { + console.log("Disconnected"); + disconnect(); + break; + } + var d = new Date; + switch (data.visible) { + case 3: + current_img.src = "/black.jpg"; + break; + case 4: + current_img.src = "/white.jpg"; + break; + default: + //current_img.src = "/cache/" + data.current + ".jpg?t=" + d.getTime(); + current_img.src = "/cache/" + data.current + ".jpg"; + break; + } + if (data.current == data.total + 1) { + //next_img.src = "/cache/" + (data.total + 1) + ".jpg?t=" + d.getTime(); + next_img.src = "/cache/" + (data.total + 1) + ".jpg"; + } else { + //next_img.src = "/cache/" + (data.current + 1) + ".jpg?t=" + d.getTime(); + next_img.src = "/cache/" + (data.current + 1) + ".jpg"; + } + + if (document.activeElement != current) { + current.value = data.current; + } + total.textContent = data.total; + document.title = data.name; + break; + case 'users': + users.textContent = ( + data.count.toString() + " client" + + (data.count == 1 ? "" : "s")); + break; + default: + console.error( + "unsupported event", data); + } + if (preloaded == false && ! isNaN(total.textContent)) { + image = document.getElementById("preload_img"); + for (let i=1; i<=Number(total.textContent); i++) { + image.src = "/cache/" + i + ".jpg"; + preload.push(image); + console.log("Preloaded " + total.textContent); + //sleep(0.5) + } + preloaded = true; + } + +}; + +var interval = setInterval(refresh, 1000); + +function refresh() { + console.log("Refreshing") + websocket.send(JSON.stringify({action: 'refresh'})); +} + diff --git a/ppt_control/static/settings.js b/ppt_control/static/settings.js new file mode 100644 index 0000000..901af0b --- /dev/null +++ b/ppt_control/static/settings.js @@ -0,0 +1,50 @@ +const COOKIENAME = "settings"; +const COOKIEEXP = 365; + +function setCookie(cname, cvalue, exdays) { + var d = new Date(); + d.setTime(d.getTime() + (exdays*24*60*60*1000)); + var expires = "expires="+ d.toUTCString(); + document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; +} + +function getCookie(cname) { + var name = cname + "="; + var decodedCookie = decodeURIComponent(document.cookie); + var ca = decodedCookie.split(';'); + for(var i = 0; i 3.6. + install_requires=['pywin32', 'websockets', 'pystray'], # https://packaging.python.org/en/latest/requirements.html + data_files=[(ppt_control.__configdir__, ['ppt-control.ini'])], + package_data={"": ["static/*", "static/icons/*"]} + #include_package_data=True +)