pax_global_header00006660000000000000000000000064121574362320014517gustar00rootroot0000000000000052 comment=5b4a1f5e8788db8d41c52ec1cff6366acbf8d4c9 encuentro-1.0/000077500000000000000000000000001215743623200133615ustar00rootroot00000000000000encuentro-1.0/AUTHORS000066400000000000000000000001001215743623200144200ustar00rootroot00000000000000Copyright 2010-2013 Facundo Batista encuentro-1.0/AYUDA.txt000066400000000000000000000032531215743623200147700ustar00rootroot00000000000000¡Bienvenido al Visualizador de contenidos del Canal Encuentro y otros! Este es un simple programa que permite buscar, descargar y ver contenido del Canal Encuentro y otros. Para más información de cómo instalar el programa y licencias, leer el archivo LEEME.txt. Cómo ejecutar el programa ------------------------- Una vez que está instalado se puede ejecutar el programa escribiendo... encuentro ...desde la linea de comandos, aunque también se puede ejecutarlo de la siguiente manera estando parado en el directorio donde se descomprimió el tarball: bin/encuentro Para ver no solo la salida estándar sino también el log del programa, ejecutar: bin/encuentro -v Cómo usarlo ----------- Lo primero que hay que hacer es actualizar la metadata de los programas. Para ello está el botón Actualizar en la barra superior, hacé click ahí, y luego de bajar la info tendrás centenares de programas para elegir. Para descargar cualquiera de ellos, tenés que seleccionarlo y hacer click en el botón "Descargar". Pero antes, como cada descarga es personal, hay que configurar el programa con el usuario y clave que saques en el sitio web del Canal Encuentro o del backend que corresponda (no todos necesitan autenticación) Entonces, en el programa hacé click en el botón Configurar de la barra de arriba. Ahí vas a ver algunas pestañas, con configuración general y específica para los distintos backends, incluso con la URL para ir a registrarte y obtener las credenciales). Listo! Ahora puedes descargar cualquier programa de cualquier canal! Una vez descargado, para verlos sólo necesitás seleccionarlo y hacer click en el botón de Play. ¡Que los disfrutes! encuentro-1.0/COPYING000066400000000000000000001043741215743623200144250ustar00rootroot00000000000000 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 . encuentro-1.0/LEEME.txt000066400000000000000000000040221215743623200147470ustar00rootroot00000000000000¡Bienvenido al Visualizador de contenidos del Canal Encuentro! Este es un simple programa que permite buscar, descargar y ver contenido del Canal Encuentro y otros. Para más información de cómo usar el programa, leer el archivo AYUDA.txt. Si querés conocer más sobre el proyecto, el mismo se gestiona desde aquí: https://launchpad.net/encuentro *Nota importante*: Si tenés una versión anterior a la 0.7, el programa no te va a funcionar. Tenés que actualizar sí o sí la versión. Esto es porque Encuentro migró sus contenidos al portal Conectate, por lo que las versiones viejas no te van a funcionar correctamente. La buena noticia es que ahora podrás descargar no sólo contenido de Encuentro, sino también de Paka Paka, Educ.ar, y otros. Cómo ejecutarlo directamente ---------------------------- Tanto si hacés un branch del proyecto, como si abrís el tarball, el programa puede ejecutarse fácilmente sin instalarlo, haciendo: bin/encuentro Cómo instalarlo --------------- Es bastante sencillo, sólo tenés que hacer: sudo python setup.py install Para que funcione correctamente, tenés que tener Python 2 instalado, y las siguientes dependencias (paquete y número mínimo de versión): python 2.6.6 python-mechanize 0.1.11 python-twisted-bin 8.2.0 python-twisted-web 8.2.0 python-qt4 4.9.1 python-xdg 0.15 python-notify 0.1.1 (este último, python-notify, no es realmente necesario, pero si está el programa notificará las descargas finalizadas) Licencias --------- Este programa no distribuye contenido de Canal Encuentro, sino que permite un mejor uso personal de esos contenidos. Por favor, referirse al sitio web de Conectate (http://conectate.gov.ar/) para saber qué se puede y qué no se puede hacer con los contenidos de ese sitio. El código de este programa está licenciado bajo la GNU GPL v3, podés encontrar esta licencia en el archivo COPYING o acá: http://www.gnu.org/licenses/gpl.html encuentro-1.0/PKG-INFO000066400000000000000000000005601215743623200144570ustar00rootroot00000000000000Metadata-Version: 1.0 Name: encuentro Version: 1.0 Summary: Search, download and see the wonderful Encuentro content. Home-page: https://launchpad.net/encuentro Author: Facundo Batista Author-email: facundo@taniquetil.com.ar License: GPL-3 Description: Simple application that allows to search, download and see the content of the Encuentro channel. Platform: UNKNOWN encuentro-1.0/README.txt000066400000000000000000000015111215743623200150550ustar00rootroot00000000000000Welcome to the Canal Encuentro visualization program! This is a simple program to search, download and see the content of the Canal Encuentro and others. This program is strongly oriented to Spanish speaking people, as the content of Canal Encuentro and the other channels is only in Spanish... for further information please check the LEEME.txt file. Notes regarding licenses: - The content of the channels is not distributed at all, but downloaded personally by the user, please check here to see the licenses about that content in http://conectate.gov.ar/ - The code is licensed under the GNU GPL v3, see file COPYING here or... http://www.gnu.org/licenses/gpl.html - I included in the qtreactor directory code from https://github.com/ghtdak/qtreactor (last commit: 82ec1802f04fbe54527884a55dafc859cd997c49) encuentro-1.0/bin/000077500000000000000000000000001215743623200141315ustar00rootroot00000000000000encuentro-1.0/bin/encuentro000077500000000000000000000037431215743623200160700ustar00rootroot00000000000000#!/usr/bin/python # Copyright 2011-2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Script to run Encuentro.""" import logging import sys import os # this will be replaced at install time INSTALLED_BASE_DIR = "@ INSTALLED_BASE_DIR @" # get the replaced-at-install-time name if exists, or the project one if os.path.exists(INSTALLED_BASE_DIR): project_basedir = INSTALLED_BASE_DIR sys._INSTALLED_BASE_DIR = INSTALLED_BASE_DIR else: project_basedir = os.path.abspath(os.path.dirname(os.path.dirname( os.path.realpath(sys.argv[0])))) if project_basedir not in sys.path: sys.path.insert(0, project_basedir) sys.path.insert(1, os.path.join(project_basedir, 'qtreactor')) from encuentro import main, platform, logger # set up logging verbose = len(sys.argv) > 1 and sys.argv[1] == '-v' logger.set_up(verbose) log = logging.getLogger('encuentro.init') # first of all, show the versions print "Running Python %s on %r" % (sys.version_info, sys.platform) log.info("Running Python %s on %r", sys.version_info, sys.platform) version_file = platform.get_path('version.txt') if os.path.exists(version_file): version = open(version_file).read().strip() print "Encuentro: v. %s" % (version,) else: version = None print "Encuentro: sin revno info" log.info("Encuentro version: %r", version) main.start(version) encuentro-1.0/encuentro.desktop000066400000000000000000000006221215743623200167560ustar00rootroot00000000000000[Desktop Entry] Version=1.0 Encoding=UTF-8 Type=Application Name=Encuentro GenericName=Encuentro Comment=Simple program to download and see the content from Canal Encuentro y otros Comment[es]=Simple programa que permite buscar, descargar y ver contenido del Canal Encuentro and others Icon=@ INSTALLED_ICON @ Exec=encuentro Terminal=false StartupNotify=false Categories=Application;Education;Network; encuentro-1.0/encuentro/000077500000000000000000000000001215743623200153635ustar00rootroot00000000000000encuentro-1.0/encuentro/__init__.py000066400000000000000000000047071215743623200175040ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2011 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """The package.""" import sys # special import before any other imports to configure GUI to use API 2 import sip for name in "QDate QDateTime QString QTextStream QTime QUrl QVariant".split(): sip.setapi(name, 2) # API v2 FTW! IMPORT_MSG = u""" ERROR! Problema al importar %(module)r Probablemente falte instalar una dependencia. Se necesita tener instalado el paquete %(package)r versión %(version)s o superior. """ class NiceImporter(object): """Show nicely successful and errored imports.""" def __init__(self, module, package, version): self.module = module self.package = package self.version = version def __enter__(self): pass def _get_version(self): """Get the version of a module.""" mod = sys.modules[self.module] for attr in ('version', '__version__', 'ver', 'PYQT_VERSION_STR'): v = getattr(mod, attr, None) if v is not None: return v return "" def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: version = self._get_version() print "Modulo %r importado ok, version %r" % (self.module, version) else: print IMPORT_MSG % dict(module=self.module, package=self.package, version=self.version) # consume the exception! return True # test the packages # pylint: disable=W0611 with NiceImporter('xdg', 'python-xdg', '0.15'): import xdg with NiceImporter('mechanize', 'python-mechanize', '0.1.11'): import mechanize with NiceImporter('pynotify', 'python-notify', '0.1.1'): import pynotify with NiceImporter('PyQt4.QtCore', 'PyQt4', '4.9.1'): import PyQt4.QtCore encuentro-1.0/encuentro/config.py000066400000000000000000000041641215743623200172070ustar00rootroot00000000000000# -*- coding: UTF-8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """The system configuration.""" import os import pickle class _Config(dict): """The configuration.""" SYSTEM = 'system' def __init__(self): self._fname = None super(_Config, self).__init__() def init(self, fname): """Initialize and load config.""" self._fname = fname if not os.path.exists(fname): # default to an almost empty dict self[self.SYSTEM] = {} return with open(fname, 'rb') as fh: saved_dict = pickle.load(fh) self.update(saved_dict) # for compatibility, put the system container if not there if self.SYSTEM not in self: self[self.SYSTEM] = {} def save(self): """Save the config to disk.""" # we don't want to pickle this class, but the dict itself raw_dict = self.copy() with open(self._fname, 'wb') as fh: pickle.dump(raw_dict, fh) class _Signal(object): """Custom signals. Decorate a function to be called when signal is emitted. """ def __init__(self): self.store = {} def register(self, method): """Register a method.""" self.store.setdefault(method.__name__, []).append(method) def emit(self, name): """Call the registered methods.""" meths = self.store.get(name, []) for meth in meths: meth() config = _Config() signal = _Signal() encuentro-1.0/encuentro/data.py000066400000000000000000000207221215743623200166510ustar00rootroot00000000000000# Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Classes to interface to and persist the episodes data.""" import cgi import logging import os import pickle from unicodedata import normalize from encuentro.ui import dialogs logger = logging.getLogger('encuentro.data') class Status(object): """Status constants.""" none = 'none' waiting = 'waiting' downloading = 'downloading' downloaded = 'downloaded' _normalize_cache = {} def _search_normalizer(char): """Normalize always to one char length.""" try: return _normalize_cache[char] except KeyError: norm = normalize('NFKD', char).encode('ASCII', 'ignore').lower() if not norm: norm = '?' _normalize_cache[char] = norm return norm def prepare_to_filter(text): """Prepare a text to filter. It receives unicode, but return simple lowercase ascii. """ return ''.join(_search_normalizer(c) for c in text) class EpisodeData(object): """Episode data.""" # these is for the attributes to be here when unpickling old instances image_url = None downtype = None def __init__(self, channel, section, title, duration, description, episode_id, url, image_url, state=None, progress=None, filename=None, downtype=None): self.channel = channel self.section = section self.title = cgi.escape(title) self.duration = duration self.description = description self.episode_id = episode_id # urls are bytes! self.url = str(url) self.image_url = str(image_url) self.state = Status.none if state is None else state self.progress = progress self.filename = filename self.to_filter = None self.downtype = downtype # cache the processed title self._normalized_title = prepare_to_filter(self.title) @property def normalized_title(self): """Get the normalized title, if already have it, or calculate it. This attribute may not be present because old pickled instances didn't have it. """ if not hasattr(self, '_normalized_title'): self._normalized_title = prepare_to_filter(self.title) return self._normalized_title def update(self, channel, section, title, duration, description, episode_id, url, image_url, state=None, progress=None, filename=None, downtype=None): """Update the episode data.""" self.channel = channel self.section = section self.title = cgi.escape(title) self.duration = duration self.description = description self.episode_id = episode_id # urls are bytes! self.url = str(url) self.image_url = str(image_url) self.state = Status.none if state is None else state self.progress = progress self.filename = filename self.downtype = downtype def filter_params(self, text, only_downloaded): """Return the filtering params. If should filter, it will return (pos1, pos2) (both in None if it only filters by only_downloaded). If it should not filter, will return None. """ if only_downloaded and self.state != Status.downloaded: # need downloaded ones, sorry return t = self.normalized_title text = prepare_to_filter(text) pos1 = t.find(text) if pos1 == -1: # need to match text, sorry return # return boundaries pos2 = pos1 + len(text) return (pos1, pos2) def __str__(self): args = (self.episode_id, self.state, self.channel, self.section, self.title) return "" % args class ProgramsData(object): """Holder / interface for programs data.""" # more recent version of the in-disk data last_programs_version = 1 def __init__(self, main_window, filename): self.main_window = main_window self.filename = filename print "Using data file:", repr(filename) logger.info("Using data file: %r", filename) self.version = None self.data = None self.reset_config_from_migration = False self.load() self.migrate() logger.info("Episodes metadata loaded (total %d)", len(self.data)) def merge(self, new_data, episodes_widget): """Merge new data to current programs data.""" for d in new_data: # v2 of json file names = ['channel', 'section', 'title', 'duration', 'description', 'episode_id', 'url', 'image_url', 'downtype'] values = dict((name, d[name]) for name in names) episode_id = d['episode_id'] try: ed = self.data[episode_id] except KeyError: ed = EpisodeData(**values) episodes_widget.add_episode(ed) self.data[episode_id] = ed else: ed.update(**values) episodes_widget.update_episode(ed) self.save() def load(self): """Load the data from the file.""" # if not file, all empty if not os.path.exists(self.filename): self.data = {} self.version = self.last_programs_version return # get from the file with open(self.filename, 'rb') as fh: try: loaded_programs_data = pickle.load(fh) except Exception, err: logger.warning("ERROR while opening the pickled data: %s", err) self.data = {} self.version = self.last_programs_version return # check pre-versioned data if isinstance(loaded_programs_data, dict): # pre-versioned data self.version = 0 self.data = loaded_programs_data else: self.version, self.data = loaded_programs_data def migrate(self): """Migrate metadata if needed.""" if self.version == self.last_programs_version: # all updated, nothing to migrate return if self.version > self.last_programs_version: raise ValueError("Data is newer than code! %s" % (self.version,)) # migrate if self.version == 0: # actually, from 0, no migration is possible, we # need to tell the user the ugly truth dlg = dialogs.ForceUpgradeDialog() should_quit = dlg.exec_() if should_quit: self.main_window.shutdown() return # if user accessed to go on, don't really need to migrate # anything, as *all* the code is to support the new metadata # version only, so just remove it and mark the usr/pass config # to be removed self.version = self.last_programs_version self.reset_config_from_migration = True self.data = {} return raise ValueError("Don't know how to migrate from %r" % (self.version,)) def __str__(self): return "" % (self.version, len(self.data)) def __nonzero__(self): return bool(self.data) def __getitem__(self, pos): return self.data[pos] def __setitem__(self, pos, value): self.data[pos] = value def values(self): """Return the iter values of the data.""" return self.data.itervalues() def __len__(self): """The length.""" return len(self.data) def items(self): """Return the iter items of the data.""" return self.data.iteritems() def save(self): """Save to disk.""" to_save = (self.last_programs_version, self.data) with open(self.filename, 'wb') as fh: pickle.dump(to_save, fh) encuentro-1.0/encuentro/image.py000066400000000000000000000047131215743623200170240ustar00rootroot00000000000000# Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Get an image from web and cache it.""" import logging import md5 import os from twisted.web.client import getPage from encuentro import platform logger = logging.getLogger('encuentro.main') class ImageGetter(object): """Image downloader and cache object.""" def __init__(self, callback): self.callback = callback self.cache_dir = os.path.join(platform.cache_dir, 'encuentro.images') if not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir) def get_image(self, episode_id, url): """Get an image and show it using the callback.""" logger.info("Loading image for episode %s: %r", episode_id, url) file_name = md5.md5(url).hexdigest() + '.jpg' file_fullname = os.path.join(self.cache_dir, file_name) if os.path.exists(file_fullname): logger.debug("Image already available: %r", file_fullname) self.callback(episode_id, file_fullname) return def _d_callback(data, episode_id, file_fullname): """Cache the image and use the callback.""" logger.debug("Image downloaded for episode_id %s, saving to %r", episode_id, file_fullname) temp_file_name = file_fullname + '.tmp' with open(temp_file_name, 'wb') as fh: fh.write(data) os.rename(temp_file_name, file_fullname) self.callback(episode_id, file_fullname) def _d_errback(failure): """Log the problem.""" logger.error("Problem getting image: %s", failure.getErrorMessage()) logger.debug("Need to download the image") d = getPage(url) d.addCallback(_d_callback, episode_id, file_fullname) d.addErrback(_d_errback) encuentro-1.0/encuentro/logger.py000066400000000000000000000044761215743623200172270ustar00rootroot00000000000000# Copyright 2011-2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Logging set up.""" import logging import os import sys import traceback from logging.handlers import RotatingFileHandler import xdg.BaseDirectory class CustomRotatingFH(RotatingFileHandler): """Rotating handler that starts a new file for every run.""" def __init__(self, *args, **kwargs): RotatingFileHandler.__init__(self, *args, **kwargs) self.doRollover() def exception_handler(exc_type, exc_value, tb): """Handle an unhandled exception.""" exception = traceback.format_exception(exc_type, exc_value, tb) msg = "".join(exception) print >> sys.stderr, msg # log logger = logging.getLogger('encuentro') logger.error("Unhandled exception!\n%s", msg) def get_filename(): """Return the log file name.""" return os.path.join(xdg.BaseDirectory.xdg_cache_home, 'encuentro', 'encuentro.log') def set_up(verbose): """Set up the logging.""" logfile = get_filename() logfolder = os.path.dirname(logfile) if not os.path.exists(logfolder): os.makedirs(logfolder) logger = logging.getLogger('encuentro') handler = CustomRotatingFH(logfile, maxBytes=1e6, backupCount=10) logger.addHandler(handler) formatter = logging.Formatter("%(asctime)s %(name)-22s " "%(levelname)-8s %(message)s") handler.setFormatter(formatter) logger.setLevel(logging.DEBUG) if verbose: handler = logging.StreamHandler() logger.addHandler(handler) handler.setFormatter(formatter) logger.setLevel(logging.DEBUG) # hook the exception handler sys.excepthook = exception_handler encuentro-1.0/encuentro/logos/000077500000000000000000000000001215743623200165065ustar00rootroot00000000000000encuentro-1.0/encuentro/logos/icon-192.png000066400000000000000000000311541215743623200204610ustar00rootroot00000000000000PNG  IHDRRlsBIT|d pHYs!8!8E1`tEXtSoftwarewww.inkscape.org< IDATxyս:ݳϰ̰3, `QF.߫11Ƹܯ1јC.hK"&*^5Ѹ+*HQFa`atuWUWwW ~zԩꪳ|BJIpd:IP~ دQ @5 (`F(t B0n*,z)/ Lfˀ ^F @188"^ 2?g& ]ԡ ;vI)v_&p%X~a<,R)9$b!ppͿt2Q)c;"`|L7a$DJ]{wH)w/!Z`(P?UH-\XJٗ`8FV@Q2x{+, , !8Ngmۻ-!1b kinTPH2p$=+nd E%5DI nnm=FBDJ'KWQY9TVjUU#Aep"PFk>_?{vww/>_?jj7nO(-a|ssl@EjR7Rl !ϢGNp: RVVkit>_}*6lx;bԨL| xJ#;rC_StwO=tw不Gvw..qO ťߒRVz7Ph]JynLƒddBRoذL~ #lX>VO|ኊLIQQ1,Gr<{)$1%N>8pvر.fyvر3Aj4!8NX^-[R[52J!D(Ǝ=C!`'έ|џؼC7h&N\ȑф$"um{ooj_~au GUˎ՛l):#2MہkcgKufV$1ȠAcpKhgmW$t6%^z{7 h~^m Xsb2~Lt-4gjk'[FGύv^q>A^:C tƒ dԯF6FMo/Yiɡ' C9zzz7Y2M pbʈ3btjj&'hgsBԓ2H_: %KGgqpՔZd|>b:pjL0y>`Ə?q) 挆X8'0c'v5.\8.jjF3i 22e w]$^G.d:vܪeRa; !"|tVp:44fRQQa3bѱ/?kiڣrJGG vVJy>K)^E@& CjN8᧌}HJp}.]]0&L?dƌ:ºu꫏|xQ0Ͽ>m:ݏFJO?̍7~[Rʭ!M=fj]'s\ơ?laЂZčZ lr)|scر13 ./_l|y%DJԂIJpc0C1 pt_$~}ni^/l6-RZl8(R0 v;DXc„i\s]L2+LMRUo6Ԝ2ŕWlpc׳~/{^y>}uR%1?!nVuCPv0mʶG H?r6ߓRI)RʛWK)&}R7=OߏvL5H)iii6-8$$Fuhk,ӿ)iZJ'7P;5kJe>ohn6XIT@Ɛ/dZ0c"qx[eum|)_!~ _{kPUͺ_շQY$͛)qB 9p 쳷~6Q)M//K|UJ+2( _g`C&/+ryZ{b%Į]ر+NkLӃ%Z{{mֳN{LC ^Ct> C#0 jvmFxݯ>7ltx/,rX]gn,ܙe j'k:BYRBooO=eh'xUJiH; ݯEތ J5;:xۢ~$/7v2EEń90{ %9M|߱s疘tz6Bmq sG#LnI;: ؖHe 퍠CI⋏ygޖ B ЛoKp_s!@J!jTV|%KԮJC?r"+/XeW׮(Z߾7m˒r P?aZ{{&{/=j6V2u涘=q9 4;lVK =|P#/4|tNݱEE?R~ hڇG00oIW^Yw\DjۣVӁ|!Awtl%"#2ϐR>M;_=~1^;7t~cj;ud O?}vn@#fa~E?jY |>>s6^%ߴ24bR lBn3eݥ ~Rv !l}^]47o2F)flAjv^ynK7r_tB8Nw~G) j~&_WJ)9x1!GhjZV@1-F!lKH)C7fCOO!$4$˅~j˼d+B4xv>v,8`Nº.)]{MFW4496$~n͜E&kq@b5TE^@(~v~ ;(~,fBTT ryA`:=~!'šu_LП ZTݯ,H|B!`11iհ"_*+kqt+F P.oB#KLlZ? 9ES+dPN#_Ф9v74޹ i 5޽twk+8UV};m3c?kBTV\Ta П47Yf쏹rQZZ]aھ[H鳩. Wu˗?Ia u:D?DA7B&ŔR@"o iac.#C0w5[G{!fpgH);2Ԕ / cǡ#߫ %\#Ro?~%j)h/' Ӽ/Wa4/B\=؇rIvҍ|()bHTyCb<%B_660}\> ܹ7CcaKbB- B1Jr2Zɳ|_ʶՎ#Aq#&;v \9҈k -B4F%i !fOMuԴO3@q&pvrOG?c4&?7y@ !f4/^޾Q0I@n89,Yu O !BvP$in9s(H.0ڈܜBW;Cg~y,b-N=5J/A{%TFOJN !Nn[o}Z$00>$W7R~*x6ϳyeׇ.kEpY = ʪ9)ӳwR|}[A1j ye,ZtF,ͺ|@9!O$]tũ SnìY SjFI[!iB k!B! B !QthKSzG?UqB&L8p}%|rZB@ɠ!06kZ8.W͜9[RGn^ YB}GG{Їąo3O3skW8=xf͚]c/BIBջ[[D) B۵nxӏpIb!ꫵX_|ob576'>?/42sO\s z zYt! dXGQP^ ڶcXr18@ c{.?$0Smc޼3ۨNA=r%(`X1=oLH/-)e$-tb>RvBTPn7xO>y+5*RѬ*%TU  C<}Bi3B,͔>^.CV_'cq!)B|֡aI)nqqDz:://+nequO ڬZZjSr6_{hR[p~Zv>0PJy.)囱)()tlOJ[ %+^Ng_ȇٰuO \341@ @xt~#9dEDJPIJyΝ[y6zH)_]>O=uODݏ؟S\^zA|>CRJ^ َ|!@@7wtF)#;8A_3(`#?Id˖,Yr6{5ip7Z#_ȍ.޸eս!FhпcQJvq]ߧזb_pd͏%rW: :;7jXkieRܫoذO0>ֽσW|0eJ)?IcTt޾QtIDAT0h6{f1Y:>(˾}twwkNV|jS@ܹGP<Ф~c `~X H) ! k^ݐ.pQRC 2`ӦIzWSQaX!K.>B5|#~:|6n,o0GƆ#!\qW>TFSI=Rs6Ӽ@H PX ApCGgR>'{9W}۶m~u^t5C!I9R!* ~tr6JwᤀC>tļӖFhA5w !rjoFFjjMwﵫ:4+f@`D^!Z`A7w$BX gz E`d̘8Nxj A6dH 5@#'AW>FKJʸ?e`NHݕx ̂*9\>|]2D0eab6hZP0rA.'89[С#~Lns@tr a$ Н#KD"5 Yq89P9M ]s& +"Mc H2rRʿ(g{BJaX4pFN6Z#`@c㪈-8tDލ N:EǣjJkԲ/H)!_8`˖/S!8_B  2 x )m@T߁Y5I|ݼbBBB 4A}⠴. 55Ȝ$S#/w~ZzŭVZZqJhkHk&trbrmZG ֞H@5]rS^>$v;v| /ASmCW$T#_$P#Ö /et !ęB0e1\rɟ⿢Vy^[jc`)kijF`1\%pY3~ĉG7 )A>Y#.gHke!V_<먯ikE!q/(/7|  QC߰u : !&].{+.WI\_eh@8hPR?Tcr[+>0ED& !O9G 6# l+V Ǎk$[{ذa;vIWzbқjڙ3OaS#S7;w~a~9K3~$3ݔ:X x„#9ljȺ_so۶FGL>9K ,ޮNhU 7b!2蕝2e\p'EEu;9K!tvj5X}[~Ɲ5k>#SL@1\0h>D;V.VzA}$л9I!f c"@?C2LxGQBZn8|[?G >ק>7o^~BqgԼvDK...c3<#cF !B\*h!Db⇨At`e~öַ{5?WAjGV̔H^n 7y>E8o?~kWqz B?RFY( T~wS*{k9(TI䓯e >zGRhAVf3&;-d2ŋ/Y|`.|ƍ!>C )e?.E1],/%x]ݱآ=3LQoY~Bi:SNF1;R:YB56 /ʲ9Rʴo:5BL@! B⋯o'Cd^n5^{ma+H܍"ns5<>p0lf8sOc?.7b͚gA9[JD'&dnnvut}~8ь?̋v_~{9\˼yj|k^!5JQ^>cgP_?1cbȩ\)L'ҥذ~;p=剠C6gLtG#XȴiGG<;T$3~%Ven; g#$^>#Vzog׮V2+&3nLƍر3:>b̒9k>˛oީRʻpJr%71q4&M:<oa3:zaWٹ #rAsp8\QIo.ښioA{{3v><2x<_WYYCY٠ߚ$mq#޲9ī`'^[$^!/t,bG43H)HMs5ԩnysn8Gʼp{ , lcIEϬ9=t 0J)=P](F5 YA!D0Q;6Ȉ%|1A a63:!@Xw2I|5ydMx {TWa¸ƒdd03{0C"g'3?Cۚ2Rx _ÛB. >Isp4NeNq>ŠZ§B6X}MWm E{oEE涝8[=1399xFea45xkkc: }j>{C$u8ѭ)`bRloэ^A2 >'eYC_;M 8Gs=I=s2ZsW2Za/rI0^;I ^CgaT#P\{)ʜeN"KImӇh2Ċ0}˖ =i]e#5EFFwٺK6&t%Dڑ9vIKxZzR$7trknh56m4kxaL8-j1͙o7c/!9<~M“Hd&ټyi^f&cB/4ַJPwf^|\B[!~ፇޠu:uua)30%2+JI9[:ە9pd2E#pj{?OMOdY3)>&Ϡq )* N WJ3k--hiF[zzzz }sV~^\\Ÿ\.(r=<~=8n8n@ald]Kʾnz{;>I)!cq j^g^ԩ0P]=$W ?0㬳p-0}6sVZZFLkr6LOOwFn)"O"NGQtpp:8.r>, WNp'jpk>zz:ӳ޽u׷;})冴$ $ѨK6n=hjj{wttgO==륧tuClذLū)"&X8c}a~X0G qְ8UJF&iT#:_.`hRZ<='H$X{PsE-~z:Pih!Y3'@u6'p T&mvT?zPkZPcI^4lCsCh*P@5 P~ دN楊˧OIENDB`encuentro-1.0/encuentro/logos/icon-32.png000066400000000000000000000033651215743623200203750ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYsmhtEXtSoftwarewww.inkscape.org<rIDATXŗmlSs_a;!IRҮT "mMmDU4նMH M6iP@ij*]JmA$ 1I=޳ Ît$>%s?e$P:W33O}(ſY]M 6iۦNB$Irnbh\NIh.}wvv<w眕 !.ι6.IƘ^N% 7$LwW/k33'Ɔq\.V@y0ET֙sF!]/.ROojZ~D"R0 Z X`ll{: pV aϞ#k C[#I"Dԩ9aCn[2 Y D 8.bE Bʩ6 m& ÄiZ`_,R1>>juw7($_$LӆiZ&ײDQ@[MY|{|ۻ[,'vE.PJ gc%o4/!dϾ}?:l(C2ϝX-W˅Bf&< z&2\n̲ER$hk:Z[[UBBH nt@U#POg9S+YvhP㇝UuB!PR>(Q,`V͕CUw<맞O\o?PނY8s15u_ v^n lݪRg -wXTms돕!+ |>}}?ںL6U>dٵ͛ =AJEe0,;CF2ya0XAvCAuժMaU>ϩO?Fh;XL+Itݪ1W.ǙH&?DZc~NP˦nP*V%meW%[:=iX6veBT(,zN. # # For further info, check https://launchpad.net/encuentro """Main entry point, and initialization of everything we can.""" import logging import os import sys from encuentro import platform from encuentro.config import config # we put here EpisodeData only for legacy reasons: unpickle of old pickles # will try to load EpisodeData from this namespace # pylint: disable=W0611 from encuentro.data import EpisodeData logger = logging.getLogger('encuentro.init') try: import pynotify except ImportError: pynotify = None from PyQt4.QtGui import QApplication, QIcon def start(version): """Rock and roll.""" if pynotify is not None: pynotify.init("Encuentro") # set up config fname = os.path.join(platform.config_dir, 'encuentro.conf') print "Using configuration file:", repr(fname) logger.info("Using configuration file: %r", fname) config.init(fname) # the order of the lines hereafter are very precise, don't mess with them app = QApplication(sys.argv) icon = QIcon(platform.get_path("encuentro/logos/icon-192.png")) app.setWindowIcon(icon) # qt4reactor was path-mangled to be available; pylint: disable=F0401 import qt4reactor qt4reactor.install() from encuentro.ui.main import MainUI from twisted.internet import reactor def _quit(): """Quit.""" app.quit() if reactor.threadpool is not None: reactor.threadpool.stop() reactor.stop() reactor.callWhenRunning(MainUI, version, _quit) reactor.run() encuentro-1.0/encuentro/network.py000066400000000000000000000373121215743623200174340ustar00rootroot00000000000000# -*- coding: utf8 -*- # Copyright 2011-2012 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Some functions to deal with network and Encuentro site.""" import logging import os import re import sys import time import urllib import urlparse if sys.platform == 'win32': # multiprocessing path mangling is not useful for how we are # installing Encuentro, so let's use threading from threading import Thread as Process, Event from Queue import Queue, Empty else: from multiprocessing import Process, Event from multiprocessing.queues import Queue from Queue import Empty from mechanize import Browser # this must go before the reactor import from encuentro import platform from twisted.internet import defer, reactor from twisted.web.client import HTTPDownloader, PartialDownloadError from encuentro.config import config URL_BASE = "http://conectate.gov.ar" URL_AUTH = ("http://conectate.gov.ar/educar-portal-video-web/" "module/login/loginAjax.do") CHUNK = 16 * 1024 BAD_LOGIN_TEXT = "loginForm" DONE_TOKEN = "I positively assure that the download is finished (?)" logger = logging.getLogger('encuentro.network') class BadCredentialsError(Exception): """Problems with user and/or password.""" class EncuentroError(Exception): """Generic problem working with the Encuentro web site.""" class CancelledError(Exception): """The download was cancelled.""" class MiBrowser(Process): """Browser en otro proceso.""" # we *are* calling parent's init; pylint: disable=W0231 def __init__(self, authuser, authpass, url, input_queue, output_queue, must_quit): self.authinfo = authuser, authpass self.url = url self.input_queue = input_queue self.output_queue = output_queue self.must_quit = must_quit Process.__init__(self) def _get_download_content(self, browser): """Get the content handler to download.""" # open base url browser.open(self.url) logger.debug("Browser download, getting html") html = self._get_html(browser) logger.debug("Browser download, got html len %d", len(html)) # get the new url url_items = dict(base=URL_BASE) for token in "urlDescarga idRecurso fileId".split(): re_str = 'id="%s" value="([^"]*)"' % (token,) val = re.search(re_str, html).groups()[0] url_items[token] = val new_url = ("%(base)s%(urlDescarga)s&idRecurso=%(idRecurso)s&" "fileId=%(fileId)s" % url_items) # log in logger.debug("Sending user and pass") usr, psw = self.authinfo auth = urllib.urlencode(dict(usuario=usr, clave=psw)) browser.open(URL_AUTH, data=auth) logger.debug("Opening final url %s", new_url) content = browser.open(new_url) try: # pylint: disable=W0212 filesize = int(content._headers['content-length']) except KeyError: logger.debug("No content information") else: logger.debug("Got content! filesize: %d", filesize) return content, filesize # didn't get the download link, let's check if it is a password error # or something else with open("/tmp/roto.html", "wb") as fh: fh.write(html) if BAD_LOGIN_TEXT in html: logger.error("Wrong user or password sent") raise BadCredentialsError() # ok, we don't know what happened :( logger.error("Unknown error while browsing Encuentro: %r", html) raise EncuentroError("Unknown problem when getting download link") def _get_html(self, browser): """Return the viewing HTML.""" assert browser.viewing_html() fh = browser.response() return fh.read() def run(self): """Do the heavy work.""" # set up browser = Browser() browser.set_handle_robots(False) # open the url and send the content logger.debug("Browser opening url %s", self.url) # yes, browser.open *is* callable; pylint: disable=E1102 try: browser.open(self.url) except Exception, e: # mechanize error can not be pickled self.output_queue.put(EncuentroError(str(e))) return # get the filename and download fname = self.input_queue.get(browser) logger.debug("Browser download to %r", fname) try: content, filesize = self._get_download_content(browser) except Exception, e: # problem, can't continue self.output_queue.put(e) return aout = open(fname, "wb") tot = 0 size_mb = filesize / (1024.0 ** 2) while not self.must_quit.is_set(): r = content.read(CHUNK) if r == "": break aout.write(r) tot += len(r) m = "%.1f%% (de %d MB)" % (tot * 100.0 / filesize, size_mb) self.output_queue.put(m) content.close() self.output_queue.put(DONE_TOKEN) class DeferredQueue(Queue): """A Queue with a deferred get.""" _reactor_period = .5 def deferred_get(self): """Return a deferred that is triggered when data.""" d = defer.Deferred() attempts = [None] * 6 def check(): """Check if we have data and transmit it.""" try: data = self.get(block=False) except Empty: # no data, check again later, unless we had too many attempts attempts.pop() if attempts: reactor.callLater(self._reactor_period, check) else: # finish without data, for external loop to do checks d.callback(None) else: # have some data, let's check if there's more all_data = [data] try: while True: all_data.append(self.get(block=False)) except Empty: # we're done! d.callback(all_data) reactor.callLater(self._reactor_period, check) return d class BaseDownloader(object): """Base episode downloader.""" def shutdown(self): """Quit the download.""" return self._shutdown() def cancel(self): """Cancel a download.""" return self._cancel() def _setup_target(self, channel, section, title, extension): """Set up the target file to download.""" # build where to save it downloaddir = config.get('downloaddir', '') channel = platform.sanitize(channel) section = platform.sanitize(section) title = platform.sanitize(title) fname = os.path.join(downloaddir, channel, section, title + extension) # if the directory doesn't exist, create it dirsecc = os.path.dirname(fname) if not os.path.exists(dirsecc): os.makedirs(dirsecc) tempf = fname + str(time.time()) return fname, tempf def download(self, channel, section, title, url, cb_progress): """Download an episode.""" return self._download(channel, section, title, url, cb_progress) class ConectarDownloader(BaseDownloader): """Episode downloader for Conectar site.""" def __init__(self): super(ConectarDownloader, self).__init__() self._prev_progress = None self.browser_quit = set() self.cancelled = False logger.info("Conectar downloader inited") def _shutdown(self): """Quit the download.""" for bquit in self.browser_quit: bquit.set() logger.info("Conectar downloader shutdown finished") def _cancel(self): """Cancel a download.""" self.cancelled = True logger.info("Conectar downloader cancelled") @defer.inlineCallbacks def _download(self, canal, seccion, titulo, url, cb_progress): """Descarga una emisión a disco.""" self.cancelled = False # levantamos el browser qinput = DeferredQueue() qoutput = Queue() bquit = Event() self.browser_quit.add(bquit) authuser = config.get('user', '') authpass = config.get('password', '') logger.info("Download episode %r: browser started", url) brow = MiBrowser(authuser, authpass, url, qoutput, qinput, bquit) brow.start() # build where to save it fname, tempf = self._setup_target(canal, seccion, titulo, u".avi") logger.debug("Downloading to temporal file %r", tempf) qoutput.put(tempf) # loop reading until finished self._prev_progress = None logger.info("Downloader started receiving bytes") while True: # get all data and just use the last item payload = yield qinput.deferred_get() if self.cancelled: logger.debug("Cancelled! Quit browser, wait, and clean.") bquit.set() yield qinput.deferred_get() if os.path.exists(tempf): os.remove(tempf) logger.debug("Cancelled! Cleaned up.") raise CancelledError() # special situations if payload is None: # no data, let's try again continue data = payload[-1] if isinstance(data, Exception): raise data if data == DONE_TOKEN: break # actualizamos si hay algo nuevo if data != self._prev_progress: cb_progress(data) self._prev_progress = data # movemos al nombre correcto y terminamos logger.info("Downloading done, renaming temp to %r", fname) os.rename(tempf, fname) self.browser_quit.remove(bquit) defer.returnValue(fname) class GenericDownloader(BaseDownloader): """Episode downloader for a generic site that works with urllib2.""" headers = { 'User-Agent': 'Mozilla/5.0', 'Accept': '*/*', } def __init__(self): super(GenericDownloader, self).__init__() self._prev_progress = None self.downloader = None logger.info("Generic downloader inited") def _shutdown(self): """Quit the download.""" logger.info("Generic downloader shutdown finished") def _cancel(self): """Cancel a download.""" if self.downloader is not None: self.downloader.cancel() logger.info("Generic downloader cancelled") def _parse_url(self, url): """Return host and port from the URL.""" urlparts = urlparse.urlparse(url) if urlparts.port is None: if urlparts.scheme == 'http': port = 80 elif urlparts.scheme == 'http': port = 80 else: raise ValueError("Unknown schema when guessing port: " + repr(urlparts.scheme)) else: port = int(urlparts.port) return urlparts.hostname, port @defer.inlineCallbacks def _download(self, canal, seccion, titulo, url, cb_progress): """Download an episode to disk.""" url = str(url) logger.info("Download episode %r", url) def report(dloaded, total): """Report download.""" size_mb = total // 1024 ** 2 perc = dloaded * 100.0 / total m = "%.1f%% (de %d MB)" % (perc, size_mb) if m != self._prev_progress: cb_progress(m) self._prev_progress = m class ReportingDownloader(HTTPDownloader): """Customize HTTPDownloader to also report and can be cancelled.""" def __init__(self, *args, **kwrgs): self.content_length = None self.downloaded = 0 self.connected_client = None self.cancelled = False HTTPDownloader.__init__(self, *args, **kwrgs) def gotHeaders(self, headers): """Got headers.""" clength = headers.get("content-length", [None])[0] self.content_length = int(clength) HTTPDownloader.gotHeaders(self, headers) def pagePart(self, data): """Got part of content.""" self.downloaded += len(data) report(self.downloaded, self.content_length) HTTPDownloader.pagePart(self, data) def cancel(self): """Cancel.""" self.cancelled = True if self.connected_client is not None: self.connected_client.stopProducing() def buildProtocol(self, addr): """Store the protocol built.""" p = HTTPDownloader.buildProtocol(self, addr) self.connected_client = p if self.cancelled: p.stopProducing() return p # build where to save it fname, tempf = self._setup_target(canal, seccion, titulo, u".mp4") logger.debug("Downloading to temporal file %r", tempf) self.downloader = ReportingDownloader(url, tempf, headers=self.headers) host, port = self._parse_url(url) reactor.connectTCP(host, port, self.downloader) try: yield self.downloader.deferred except PartialDownloadError: if self.downloader.cancelled: raise CancelledError else: raise # rename to final name and end logger.info("Downloading done, renaming temp to %r", fname) os.rename(tempf, fname) defer.returnValue(fname) # this is the entry point to get the downloaders for each type all_downloaders = { None: ConectarDownloader, 'conectar': ConectarDownloader, 'generic': GenericDownloader, } if __name__ == "__main__": h = logging.StreamHandler() h.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) logger.addHandler(h) def show(avance): """Show progress.""" print "Avance:", avance # overwrite config for the test config = dict(user="lxpdvtnvrqdoa@mailinator.com", password="descargas", downloaddir='.') # url_episode = "http://conectate.gov.ar/educar-portal-video-web/module/"\ # "detalleRecurso/DetalleRecurso.do?modulo=masVotados&"\ # "recursoPadreId=50001&idRecurso=50004" url_episode = "http://backend.bacua.gob.ar/video.php?v=_173fb17c" @defer.inlineCallbacks def download(): """Download.""" # downloader = ConectarDownloader(config) downloader = GenericDownloader(config) # reactor.callLater(5, downloader.cancel) try: fname = yield downloader.download("test-ej-canal", "secc", "tit", url_episode, show) print "All done!", fname except CancelledError: print "--- cancelado!" finally: downloader.shutdown() reactor.stop() reactor.callWhenRunning(download) reactor.run() encuentro-1.0/encuentro/platform.py000066400000000000000000000054341215743623200175670ustar00rootroot00000000000000# -*- coding: utf8 -*- # Copyright 2011-2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Multiplatform code.""" import os import re import subprocess import sys import user _basedir = os.path.abspath(os.path.dirname(os.path.dirname( os.path.realpath(sys.argv[0])))) # if the base directory was determined by setup.py, fix it # pylint: disable=W0212 if hasattr(sys, '_INSTALLED_BASE_DIR'): _basedir = sys._INSTALLED_BASE_DIR # if the base directory was mangled by PyInstaller, fix it _frozen = False if hasattr(sys, 'frozen'): _basedir = sys._MEIPASS _frozen = True # pylint: enable=W0212 if sys.platform == 'win32': # won't find this in linux; pylint: disable=F0401 from win32com.shell import shell, shellcon config_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0) data_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_LOCAL_APPDATA, None, 0) cache_dir = data_dir del shell, shellcon else: from xdg import BaseDirectory config_dir = BaseDirectory.xdg_config_home data_dir = BaseDirectory.xdg_data_home cache_dir = BaseDirectory.xdg_cache_home del BaseDirectory def get_path(path): """Build an usable path for media.""" parts = path.split("/") # if frozen by PyInstaller, all stuff is in the same dir if _frozen: return os.path.join(_basedir, parts[-1]) # normal work return os.path.join(_basedir, *parts) def sanitize(name): """Sanitize the name according to the OS.""" if sys.platform == 'win32': sanit = re.sub(u'[<>:"/|?*]', '', name) else: sanit = re.sub(u'/', '', name) return sanit def get_download_dir(): """Get a the download dir for the system. I hope this someday will be included in the xdg library :| """ try: cmd = ["xdg-user-dir", 'DOWNLOAD'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) base = proc.communicate()[0].strip() except OSError: base = user.home return os.path.join(base, 'encuentro') def open_file(fullpath): """Open the file.""" if sys.platform == 'win32': os.startfile(fullpath) else: subprocess.call(["/usr/bin/xdg-open", fullpath]) encuentro-1.0/encuentro/ui/000077500000000000000000000000001215743623200160005ustar00rootroot00000000000000encuentro-1.0/encuentro/ui/__init__.py000066400000000000000000000013641215743623200201150ustar00rootroot00000000000000# Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """All classes to define the User Interface of the program.""" encuentro-1.0/encuentro/ui/central_panel.py000066400000000000000000000416641215743623200211740ustar00rootroot00000000000000# -*- coding: UTF-8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Central panels in the main window, the content part of all the interface.""" import logging import operator from PyQt4.QtGui import ( QAbstractItemView, QAbstractTextDocumentLayout, QApplication, QColor, QHBoxLayout, QLabel, QMenu, QPalette, QPixmap, QPushButton, QStyle, QStyleOptionViewItemV4, QStyledItemDelegate, QTextDocument, QTextEdit, QTreeWidgetItem, QVBoxLayout, QWidget, ) from PyQt4.QtCore import Qt, QSize from encuentro import data, image from encuentro.data import Status from encuentro.ui import remembering from encuentro.ui.throbber import Throbber logger = logging.getLogger("encuentro.centralpanel") class DownloadsWidget(remembering.RememberingTreeWidget): """The downloads queue.""" def __init__(self, episodes_widget): self.episodes_widget = episodes_widget super(DownloadsWidget, self).__init__('downloads') _headers = (u"Descargando...", u"Estado") self.setColumnCount(len(_headers)) self.setHeaderLabels(_headers) self.queue = [] self.current = -1 self.downloading = False # connect the signals self.clicked.connect(self.on_signal_clicked) def on_signal_clicked(self, _): """The view was clicked.""" item = self.currentItem() self.episodes_widget.show(item.episode_id) def append(self, episode): """Append an episode to the downloads list.""" # add to the list in the GUI item = QTreeWidgetItem((episode.title, u"Encolado")) item.episode_id = episode.episode_id self.queue.append((episode, item)) self.addTopLevelItem(item) self.setCurrentItem(item) # fix episode state episode.state = Status.downloading def prepare(self): """Set up everything for next download.""" self.downloading = True self.current += 1 episode, _ = self.queue[self.current] return episode def start(self): """Download started.""" episode, item = self.queue[self.current] item.setText(1, u"Comenzando") episode.state = Status.downloading def progress(self, progress): """Advance the progress indicator.""" _, item = self.queue[self.current] item.setText(1, u"Descargando: %s" % progress) def end(self, error=None): """Mark episode as downloaded.""" episode, item = self.queue[self.current] if error is None: # downloaded OK gui_msg = u"Terminado ok" end_state = Status.downloaded else: # something bad happened gui_msg = unicode(error) end_state = Status.none item.setText(1, gui_msg) item.setDisabled(True) episode.state = end_state self.episodes_widget.set_color(episode) self.downloading = False def cancel(self): """The download is being cancelled.""" _, item = self.queue[self.current] item.setText(1, u"Cancelado") def pending(self): """Return the pending downloads quantity (including current).""" # remaining after current one q = len(self.queue) - self.current - 1 # if we're still downloading current one, add it to the count if self.downloading: q += 1 return q class HTMLDelegate(QStyledItemDelegate): """Custom delegate so the QTreeWidget can do HTML. This is an adaptation of a post here: http://stackoverflow.com/questions/10924175/how-do-i-use-a- qstyleditemdelegate-to-paint-only-the-background-without-coverin We only need to do background highlighting, so probably this will be trimmed as much as possible for performance reasons. Also, we only do HTML for one column, the rest is delegated to parent. """ def __init__(self, parent, html_column): self._html_column = html_column QStyledItemDelegate.__init__(self, parent) def paint(self, painter, option, index): """Render the delegate for the item.""" if index.column() != self._html_column: return QStyledItemDelegate.paint(self, painter, option, index) options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) if options.widget is None: style = QApplication.style() else: style = options.widget.style() doc = QTextDocument() doc.setHtml(options.text) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore() def sizeHint(self, option, index): """Calculate the needed size.""" options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) doc = QTextDocument() doc.setHtml(options.text) doc.setTextWidth(options.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) class EpisodesWidget(remembering.RememberingTreeWidget): """The list of episodes info.""" _row_getter = operator.attrgetter('channel', 'section', 'title', 'duration') _title_column = 2 def __init__(self, main_window, episode_info): self.main_window = main_window self.episode_info = episode_info super(EpisodesWidget, self).__init__('episodes') self.setMinimumSize(600, 300) self.setItemDelegate(HTMLDelegate(self, self._title_column)) _headers = (u"Canal", u"Sección", u"Título", u"Duración [min]") self.setColumnCount(len(_headers)) self.setHeaderLabels(_headers) header = self.header() header.setStretchLastSection(False) header.setResizeMode(2, header.Stretch) episodes = list(self.main_window.programs_data.values()) self._item_map = {} for e in episodes: item = QTreeWidgetItem([unicode(v) for v in self._row_getter(e)]) item.episode_id = e.episode_id item.setTextAlignment(3, Qt.AlignRight) self._item_map[e.episode_id] = item self.addTopLevelItem(item) self.set_color(e) # enable sorting self.setSortingEnabled(True) self.setSelectionMode(QAbstractItemView.ExtendedSelection) # connect the signals self.clicked.connect(self.on_signal_clicked) self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.on_right_button) self.itemDoubleClicked.connect(self.on_double_click) def show(self, episode_id): """Show the row for the requested episode.""" item = self._item_map[episode_id] self.setCurrentItem(item) self._adjust_gui(episode_id) def on_signal_clicked(self, _): """The view was clicked.""" item = self.currentItem() self._adjust_gui(item.episode_id) def on_double_click(self, item, col): """Double click.""" episode = self.main_window.programs_data[item.episode_id] logger.debug("Double click in %s", episode) if episode.state == Status.downloaded: self.main_window.play_episode(episode) elif episode.state == Status.none: if self.main_window.have_config(): self.main_window.queue_download(episode) else: logger.debug("Not starting download because no config.") t = (u"No se puede arrancar una descarga porque la " u"configuración está incompleta.") self.main_window.show_message(u'Falta configuración', t) def _adjust_gui(self, episode_id): """Adjust the rest of the GUI for this episode.""" episode = self.main_window.programs_data[episode_id] self.episode_info.update(episode) self.main_window.check_download_play_buttons() def on_right_button(self, point): """Right button was pressed, build a menu.""" item = self.currentItem() self._adjust_gui(item.episode_id) episode = self.main_window.programs_data[item.episode_id] menu = QMenu() mw = self.main_window act_play = menu.addAction(u"&Reproducir", lambda: mw.play_episode(episode)) act_cancel = menu.addAction(u"&Cancelar descarga", lambda: mw.cancel_download(episode)) act_download = menu.addAction(u"&Descargar", lambda: mw.queue_download(episode)) # set menu options according status state = episode.state if state == Status.downloaded: act_play.setEnabled(True) act_cancel.setEnabled(False) act_download.setEnabled(False) elif state == Status.downloading or state == Status.waiting: act_play.setEnabled(False) act_cancel.setEnabled(True) act_download.setEnabled(False) elif state == Status.none: act_play.setEnabled(False) act_cancel.setEnabled(False) if self.main_window.have_config(): act_download.setEnabled(True) else: act_download.setEnabled(False) menu.exec_(self.viewport().mapToGlobal(point)) def update_episode(self, episode): """Update episode with new info""" item = self._item_map[episode.episode_id] for i, v in enumerate(self._row_getter(episode)): item.setText(i, unicode(v)) def add_episode(self, episode): """Update episode with new info""" item = QTreeWidgetItem([unicode(v) for v in self._row_getter(episode)]) item.episode_id = episode.episode_id item.setTextAlignment(3, Qt.AlignRight) self._item_map[episode.episode_id] = item self.set_color(episode) self.addTopLevelItem(item) def set_color(self, episode): """Set the background color for an episode (if needed).""" if episode.state == Status.downloaded: color = QColor("light green") else: palette = self.palette() color = palette.color(QPalette.AlternateBase) item = self._item_map[episode.episode_id] for i in xrange(item.columnCount()): item.setBackgroundColor(i, color) def set_filter(self, text, only_downloaded=False): """Apply a filter to the episodes list.""" for episode_id, item in self._item_map.iteritems(): episode = self.main_window.programs_data[episode_id] params = episode.filter_params(text, only_downloaded) if params is None: item.setHidden(True) else: item.setHidden(False) pos1, pos2 = params if pos1 is None: # no highlighting item.setText(self._title_column, episode.title) else: # filtering by text, so highlight t = episode.title ht = u''.join((t[:pos1], '', t[pos1:pos2], '', t[pos2:])) item.setText(self._title_column, ht) # clear the selection to get consistent behaviour (because otherwise # something will keep selected when widening the filter, or nothing # will be selected when the filter gets more restrict) self.clearSelection() # now nothing is selected, so clear the episode info self.episode_info.clear() class EpisodeInfo(QWidget): """Show the episode at the right.""" def __init__(self, main_window): self.main_window = main_window super(EpisodeInfo, self).__init__() self.current_episode = None layout = QVBoxLayout(self) # a throbber, that we don't initially show self.throbber = Throbber() layout.addWidget(self.throbber) self.throbber.hide() # the image and its getter self.image_episode = QLabel() self.image_episode.hide() layout.addWidget(self.image_episode, alignment=Qt.AlignCenter) self.get_image = image.ImageGetter(self.image_episode_loaded).get_image # text area self.text_edit = QTextEdit( u"Seleccionar un programa para ver aquí la info.") self.text_edit.setReadOnly(True) layout.addWidget(self.text_edit) # the button self.button = QPushButton() self.button.connected = False self.button.hide() layout.addWidget(self.button) def image_episode_loaded(self, episode_id, image_path): """An image has arrived, show it only if the path is correct.""" # only set the image if the user still have the same episode selected if self.current_episode != episode_id: return # load the image and show it pixmap = QPixmap(image_path) self.image_episode.setPixmap(pixmap) self.image_episode.show() # hide the throbber self.throbber.hide() def clear(self): """Clear the episode info panel.""" self.throbber.hide() self.image_episode.hide() msg = u"Seleccionar un programa para ver aquí la info." self.text_edit.setText(msg) self.button.hide() def update(self, episode): """Update all the episode info.""" self.current_episode = episode.episode_id # image if episode.image_url is not None: # this must be before the get_image call, as it may call # immediately to image_episode_loaded (showing the image and # hiding the throber) self.image_episode.hide() self.throbber.show() # now do call the get_image self.get_image(episode.episode_id, episode.image_url.encode('utf-8')) # all description msg = "

%s



%s" % ( episode.title, episode.description) self.text_edit.setHtml(msg) # action button self.button.show() if episode.state == data.Status.downloaded: label = "Reproducir" func = self.main_window.play_episode enable = True elif (episode.state == data.Status.downloading or episode.state == data.Status.waiting): label = u"Cancelar descarga" func = self.main_window.cancel_download enable = True else: label = u"Descargar" func = self.main_window.download_episode enable = bool(self.main_window.have_config()) def _exec(func, episode): """Execute a function on the episode and update its info.""" func(episode) self.update(episode) # set button text, disconnect if should, and connect new func self.button.setEnabled(enable) self.button.setText(label) if self.button.connected: self.button.clicked.disconnect() self.button.connected = True self.button.clicked.connect(lambda: _exec(func, episode)) class BigPanel(QWidget): """The big panel for the main interface with user.""" def __init__(self, main_window): super(BigPanel, self).__init__() self.main_window = main_window layout = QHBoxLayout(self) # get this before, as it be used when creating other sutff episode_info = EpisodeInfo(main_window) self.episodes = EpisodesWidget(main_window, episode_info) # split on the right right_split = remembering.RememberingSplitter(Qt.Vertical, 'right') right_split.addWidget(episode_info) self.downloads_widget = DownloadsWidget(self.episodes) right_split.addWidget(self.downloads_widget) # main split main_split = remembering.RememberingSplitter(Qt.Horizontal, 'main') main_split.addWidget(self.episodes) main_split.addWidget(right_split) layout.addWidget(main_split) encuentro-1.0/encuentro/ui/dialogs.py000066400000000000000000000056761215743623200200120ustar00rootroot00000000000000# -*- coding: utf8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Several dialogs.""" from PyQt4.QtGui import ( QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QPushButton, QVBoxLayout, ) UPGRADE_TEXT = u""" Esta nueva versión del programa Encuentro sólo funciona con contenido actualizado, lo cual le permitirá trabajar con programas del canal Encuentro y de otros nuevos canales, pero deberá configurarlo nuevamente y perderá la posibilidad de ver directactamente los videos ya descargados (los cuales permanecerán en su disco). Haga click en Continuar y podrá ver el Wizard que lo ayudará a configurar nuevamente el programa. """ class ForceUpgradeDialog(QDialog): """The dialog for a force upgrade.""" def __init__(self): super(ForceUpgradeDialog, self).__init__() vbox = QVBoxLayout(self) self.setWindowTitle(u"El contenido debe actualizarse") self.main_text = QLabel(UPGRADE_TEXT) vbox.addWidget(self.main_text) bbox = QDialogButtonBox() bbox.addButton(QPushButton(u"Salir del programa"), QDialogButtonBox.AcceptRole) bbox.accepted.connect(self.accept) bbox.addButton(QPushButton(u"Continuar"), QDialogButtonBox.RejectRole) bbox.rejected.connect(self.reject) vbox.addWidget(bbox) self.show() class UpdateDialog(QDialog): """The dialog for update.""" def __init__(self): super(UpdateDialog, self).__init__() vbox = QVBoxLayout(self) self.closed = False self.setModal(True) self.resize(500, 250) vbox.addWidget(QLabel(u"Actualización de la lista de episodios:")) self.text = QPlainTextEdit() self.text.setReadOnly(True) vbox.addWidget(self.text) bbox = QDialogButtonBox(QDialogButtonBox.Cancel) bbox.rejected.connect(self.reject) vbox.addWidget(bbox) def append(self, text): """Append some text in the dialog.""" self.text.appendPlainText(text.strip()) def closeEvent(self, event): """It was closed.""" self.closed = True if __name__ == '__main__': import sys from PyQt4.QtGui import QApplication app = QApplication(sys.argv) frame = UpdateDialog() frame.show() frame.exec_() encuentro-1.0/encuentro/ui/main.py000066400000000000000000000446411215743623200173070ustar00rootroot00000000000000# -*- coding: UTF-8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """The main window.""" import logging import os try: import pynotify except ImportError: pynotify = None from PyQt4.QtGui import ( QAction, QCheckBox, QLabel, QLineEdit, QMessageBox, QSizePolicy, QStyle, QWidget, ) from twisted.internet import defer from encuentro import platform, data, update from encuentro.config import config, signal from encuentro.data import Status from encuentro.network import ( BadCredentialsError, CancelledError, all_downloaders, ) from encuentro.ui import ( central_panel, preferences, remembering, systray, wizard, ) logger = logging.getLogger('encuentro.main') # tooltips for buttons enabled and disabled TTIP_PLAY_E = u'Reproducir el programa' TTIP_PLAY_D = ( u"Reproducir - El episodio debe estar descargado para poder verlo." ) TTIP_DOWNLOAD_E = u'Descargar el programa de la web' TTIP_DOWNLOAD_D = ( u"Descargar - No se puede descargar si ya está descargado o falta " u"alguna configuración en el programa." ) ABOUT_TEXT = u"""
Simple programa que permite buscar, descargar y ver
contenido del canal Encuentro y otros.

Versión %s

Copyright 2010-2013 Facundo Batista

http://encuentro.taniquetil.com.ar
""" class MainUI(remembering.RememberingMainWindow): """Main UI.""" _programs_file = os.path.join(platform.data_dir, 'encuentro.data') def __init__(self, version, app_quit): super(MainUI, self).__init__() self.app_quit = app_quit self.finished = False self.version = version self.setWindowTitle('Encuentro') self.programs_data = data.ProgramsData(self, self._programs_file) self._touch_config() self.downloaders = {} for downtype, dloader_class in all_downloaders.iteritems(): self.downloaders[downtype] = dloader_class() # finish all gui stuff self.big_panel = central_panel.BigPanel(self) self.episodes_list = self.big_panel.episodes self.episodes_download = self.big_panel.downloads_widget self.setCentralWidget(self.big_panel) # the setting of menubar should be almost in the end, because it may # trigger the wizard, which needs big_panel and etc. self.action_play = self.action_download = None self.filter_line = self.filter_cbox = self.needsomething_alert = None self._menubar() systray.show(self) if config.get('autorefresh'): ue = update.UpdateEpisodes(self) ue.background() self.show() logger.debug("Main UI started ok") def _sanitize_config(self): """Return a copied config, sanitized to log.""" safecfg = config.copy() if 'user' in safecfg: safecfg['user'] = '' if 'password' in safecfg: safecfg['password'] = '' return safecfg def _touch_config(self): """Do some config processing.""" # log the config, but without user and pass safecfg = self._sanitize_config() logger.debug("Configuration loaded: %s", safecfg) # we have a default for download dir if not config.get('downloaddir'): config['downloaddir'] = platform.get_download_dir() # maybe clean some config if self.programs_data.reset_config_from_migration: config['user'] = '' config['password'] = '' config.pop('cols_width', None) config.pop('cols_order', None) config.pop('selected_row', None) def have_config(self): """Return if some config is needed.""" return config.get('user') and config.get('password') def have_metadata(self): """Return if metadata is needed.""" return bool(self.programs_data) def _menubar(self): """Set up the menu bar.""" menubar = self.menuBar() # applications menu menu_appl = menubar.addMenu(u'&Aplicación') icon = self.style().standardIcon(QStyle.SP_BrowserReload) action_reload = QAction(icon, '&Refrescar', self) action_reload.setShortcut('Ctrl+R') action_reload.setToolTip(u'Recarga la lista de programas') action_reload.triggered.connect(self.refresh_episodes) menu_appl.addAction(action_reload) icon = self.style().standardIcon(QStyle.SP_FileDialogDetailedView) action_preferences = QAction(icon, u'&Preferencias', self) action_preferences.triggered.connect(self.open_preferences) action_preferences.setToolTip( u'Configurar distintos parámetros del programa') menu_appl.addAction(action_preferences) menu_appl.addSeparator() icon = self.style().standardIcon(QStyle.SP_MessageBoxInformation) _act = QAction(icon, '&Acerca de', self) _act.triggered.connect(self.open_about_dialog) _act.setToolTip(u'Muestra información de la aplicación') menu_appl.addAction(_act) icon = self.style().standardIcon(QStyle.SP_DialogCloseButton) _act = QAction(icon, '&Salir', self) _act.setShortcut('Ctrl+Q') _act.setToolTip(u'Sale de la aplicación') _act.triggered.connect(self.on_close) menu_appl.addAction(_act) # program menu menu_prog = menubar.addMenu(u'&Programa') icon = self.style().standardIcon(QStyle.SP_ArrowDown) self.action_download = QAction(icon, '&Descargar', self) self.action_download.setShortcut('Ctrl+D') self.action_download.setEnabled(False) self.action_download.setToolTip(TTIP_DOWNLOAD_D) self.action_download.triggered.connect(self.download_episode) menu_prog.addAction(self.action_download) icon = self.style().standardIcon(QStyle.SP_MediaPlay) self.action_play = QAction(icon, '&Reproducir', self) self.action_play.setEnabled(False) self.action_play.setToolTip(TTIP_PLAY_D) self.action_play.triggered.connect(self.on_play_action) menu_prog.addAction(self.action_play) # toolbar for buttons toolbar = self.addToolBar('main') toolbar.addAction(self.action_download) toolbar.addAction(self.action_play) toolbar.addSeparator() toolbar.addAction(action_reload) toolbar.addAction(action_preferences) # filter text and button, to the right spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) toolbar.addWidget(QLabel(u"Filtro: ")) self.filter_line = QLineEdit() self.filter_line.setMaximumWidth(150) self.filter_line.textChanged.connect(self.on_filter_changed) toolbar.addWidget(self.filter_line) self.filter_cbox = QCheckBox(u"Sólo descargados") self.filter_cbox.stateChanged.connect(self.on_filter_changed) toolbar.addWidget(self.filter_cbox) # if needed, a warning that stuff needs to be configured icon = self.style().standardIcon(QStyle.SP_MessageBoxWarning) m = u"Necesita configurar algo; haga click aquí para abrir el wizard" self.needsomething_alert = QAction(icon, m, self) self.needsomething_alert.triggered.connect(self._start_wizard) toolbar.addAction(self.needsomething_alert) if not config.get('nowizard'): self._start_wizard() self._review_need_something_indicator() def _start_wizard(self, _=None): """Start the wizard if needed.""" if not self.have_config() or not self.have_metadata(): dlg = wizard.WizardDialog(self) dlg.exec_() self._review_need_something_indicator() def on_filter_changed(self, _): """The filter text has changed, apply it in the episodes list.""" text = self.filter_line.text() cbox = self.filter_cbox.checkState() self.episodes_list.set_filter(text, cbox) # after applying filter, nothing is selected, so check buttons # (easiest way to clean them all) self.check_download_play_buttons() def _review_need_something_indicator(self): """Hide/show/enable/disable different indicators if need sth.""" needsomething = bool(not self.have_config() or not self.have_metadata()) self.needsomething_alert.setVisible(needsomething) def shutdown(self): """Stop everything and quit. This shutdown con be called at any time, even on init, so we have extra precautions about which attributes we have. """ signal.emit('save_state') config.save() self.finished = True programs_data = getattr(self, 'programs_data', None) if programs_data is not None: programs_data.save() downloaders = getattr(self, 'downloaders', {}) for downloader in downloaders.itervalues(): downloader.shutdown() # bye bye self.app_quit() def on_close(self, _): """Close signal.""" if self._should_close(): self.shutdown() def closeEvent(self, event): """All is being closed.""" if self._should_close(): self.shutdown() else: event.ignore() def _should_close(self): """Still time to decide if want to close or not.""" logger.info("Attempt to close the program") pending = self.episodes_download.pending() if not pending: # all fine, save all and quit logger.info("Saving states and quitting") return True logger.debug("Still %d active downloads when trying to quit", pending) # stuff pending m = (u"Hay programas todavía en proceso de descarga!\n" u"¿Seguro quiere salir del programa?") QMB = QMessageBox dlg = QMB(u"Guarda!", m, QMB.Question, QMB.Yes, QMB.No, QMB.NoButton) opt = dlg.exec_() if opt != QMB.Yes: logger.info("Quit cancelled") return False # quit anyway, put all downloading and pending episodes to none logger.info("Fixing episodes, saving state and exiting") for program in self.programs_data.values(): state = program.state if state == Status.waiting or state == Status.downloading: program.state = Status.none return True def show_message(self, err_type, text): """Show different messages to the user.""" if self.finished: logger.debug("Ignoring message: %r", text) return logger.debug("Showing a message: %r", text) # error text can be produced by windows, try to to sanitize it if isinstance(text, str): try: text = text.decode("utf8") except UnicodeDecodeError: try: text = text.decode("latin1") except UnicodeDecodeError: text = repr(text) QMB = QMessageBox dlg = QMB(u"Atención: " + err_type, text, QMB.Warning, QMB.Ok, QMB.NoButton, QMB.NoButton) dlg.exec_() def refresh_episodes(self, _=None): """Update and refresh episodes.""" ue = update.UpdateEpisodes(self) ue.interactive() def download_episode(self, _=None): """Download the episode(s).""" items = self.episodes_list.selectedItems() for item in items: episode = self.programs_data[item.episode_id] self.queue_download(episode) @defer.inlineCallbacks def queue_download(self, episode): """User indicated to download something.""" logger.debug("Download requested of %s", episode) if episode.state != Status.none: logger.debug("Download denied, episode %s is not in downloadeable " "state.", episode.episode_id) return # queue self.episodes_download.append(episode) self.adjust_episode_info(episode) self.check_download_play_buttons() if self.episodes_download.downloading: return logger.debug("Downloads: starting") while self.episodes_download.pending(): episode = self.episodes_download.prepare() try: filename, episode = yield self._episode_download(episode) except CancelledError: logger.debug("Got a CancelledError!") self.episodes_download.end(error=u"Cancelado") except BadCredentialsError: logger.debug("Bad credentials error!") msg = (u"Error con las credenciales: hay que configurar " u"usuario y clave correctos") self.show_message('BadCredentialsError', msg) self.episodes_download.end(error=msg) except Exception, e: logger.debug("Unknown download error: %s", e) err_type = e.__class__.__name__ self.show_message(err_type, str(e)) self.episodes_download.end(error=u"Error: " + str(e)) else: logger.debug("Episode downloaded: %s", episode) self.episodes_download.end() episode.filename = filename # check buttons self.adjust_episode_info(episode) self.check_download_play_buttons() logger.debug("Downloads: finished") @defer.inlineCallbacks def _episode_download(self, episode): """Effectively download an episode.""" logger.debug("Effectively downloading episode %s", episode.episode_id) self.episodes_download.start() # download! downloader = self.downloaders[episode.downtype] fname = yield downloader.download(episode.channel, episode.section, episode.title, episode.url, self.episodes_download.progress) episode_name = u"%s - %s - %s" % (episode.channel, episode.section, episode.title) if config.get('notification', True) and pynotify is not None: n = pynotify.Notification(u"Descarga finalizada", episode_name) n.show() defer.returnValue((fname, episode)) def open_preferences(self, _=None): """Open the preferences dialog.""" dlg = preferences.PreferencesDialog() dlg.exec_() # after dialog closes, config changed, so review indicators self._review_need_something_indicator() safecfg = self._sanitize_config() logger.debug("Configuration changed: %s", safecfg) def adjust_episode_info(self, episode): """Adjust the episode info.""" self.episodes_list.episode_info.update(episode) def check_download_play_buttons(self): """Set both buttons state according to the selected episodes.""" items = self.episodes_list.selectedItems() # 'play' button should be enabled if only one row is selected and # its state is 'downloaded' play_enabled = False if len(items) == 1: episode = self.programs_data[items[0].episode_id] if episode.state == Status.downloaded: play_enabled = True self.action_play.setEnabled(play_enabled) ttip = TTIP_PLAY_E if play_enabled else TTIP_PLAY_D self.action_play.setToolTip(ttip) # 'download' button should be enabled if at least one of the selected # rows is in 'none' state, and if config is ok download_enabled = False if self.have_config(): for item in items: episode = self.programs_data[item.episode_id] if episode.state == Status.none: download_enabled = True break ttip = TTIP_DOWNLOAD_E if download_enabled else TTIP_DOWNLOAD_D self.action_download.setEnabled(download_enabled) self.action_download.setToolTip(ttip) def on_play_action(self, _=None): """Play the selected episode.""" items = self.episodes_list.selectedItems() if len(items) != 1: raise ValueError("Wrong call to play_episode, with %d selections" % len(items)) item = items[0] episode = self.programs_data[item.episode_id] self.play_episode(episode) def play_episode(self, episode): """Play an episode.""" downloaddir = config.get('downloaddir', '') filename = os.path.join(downloaddir, episode.filename) logger.info("Play requested of %s", episode) if os.path.exists(filename): # pass file:// url with absolute path fullpath = 'file://' + os.path.abspath(filename) logger.info("Playing %r", fullpath) platform.open_file(fullpath) else: logger.warning("Aborted playing, file not found: %r", filename) msg = (u"No se encontró el archivo para reproducir: " + repr(filename)) self.show_message('Error al reproducir', msg) episode.state = Status.none self.episodes_list.set_color(episode) def cancel_download(self, episode): """Cancel the downloading of an episode.""" logger.info("Cancelling download of %s", episode) self.episodes_download.cancel() downloader = self.downloaders[episode.downtype] downloader.cancel() episode.state = Status.none def open_about_dialog(self): """Show the about dialog.""" version = self.version if self.version else u"(?)" title = "Encuentro v" + version text = ABOUT_TEXT % (version,) QMessageBox.about(self, title, text) encuentro-1.0/encuentro/ui/media/000077500000000000000000000000001215743623200170575ustar00rootroot00000000000000encuentro-1.0/encuentro/ui/media/throbber.gif000066400000000000000000000016461215743623200213640ustar00rootroot00000000000000GIF89a333LLLfff! NETSCAPE2.0!Created with GIMP! ,SI̵SHކ%:Vo s&F'7` Kjb-[+@x`1lF-G! ,SI/̵ H%:Vo 0s&F'G ` Kjb-[Px`1lF-G! ,SIO̵0H%:Vo As&F'W(`Kjb-[`x`1lF-G! ,SIo ̵AH%:Vo TQs&F'g0`Kjb-[px`1lF-G! ,SI̵SQH %:Vo as&F'w8`Kjb-[x`1lF-G! ,SI̵aH%:Vo qs&F'`Kjb-[#x`1lF-G! ,SI̵qH%:Vo s&F'`Kjb-[C x`1lF-G! ,SI̵H%:Vo Ts&F''`Kjb-[c0x`1lF-G;encuentro-1.0/encuentro/ui/preferences.py000066400000000000000000000121101215743623200206460ustar00rootroot00000000000000# -*- coding: utf8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """The preferences dialog.""" import os import sys import logging from PyQt4.QtGui import ( QCheckBox, QDialog, QDialogButtonBox, QGridLayout, QLabel, QLineEdit, QTabWidget, QVBoxLayout, QWidget, ) from PyQt4.QtCore import Qt from encuentro.config import config logger = logging.getLogger('encuentro.preferences') URL_CONECTATE = ( "http://registro.educ.ar/cuentas/registro/index?servicio=conectate" ) class GeneralPreferences(QWidget): """The general preferences input.""" def __init__(self): super(GeneralPreferences, self).__init__() grid = QGridLayout(self) grid.setSpacing(20) grid.setColumnStretch(1, 10) l = QLabel( u"Ingresá el directorio donde descargar los videos...") l.setTextFormat(Qt.RichText) grid.addWidget(l, 0, 0, 1, 2) grid.addWidget(QLabel(u"Descargar en:"), 1, 0, 2, 1) prv = config.get('downloaddir', '') self.downloaddir_entry = QLineEdit(prv) grid.addWidget(self.downloaddir_entry, 1, 1, 2, 2) self.autoreload_checkbox = QCheckBox( u"Recargar automáticamente la lista de episodios al iniciar") prv = config.get('autorefresh', False) self.autoreload_checkbox.setChecked(prv) grid.addWidget(self.autoreload_checkbox, 2, 0, 3, 2) self.shownotifs_checkbox = QCheckBox( u"Mostrar una notificación cuando termina cada descarga") prv = config.get('notification', True) self.shownotifs_checkbox.setChecked(prv) grid.addWidget(self.shownotifs_checkbox, 3, 0, 4, 2) def get_config(self): """Return the config for this tab.""" d = {} d['downloaddir'] = self.downloaddir_entry.text() d['autorefresh'] = self.autoreload_checkbox.isChecked() d['notification'] = self.shownotifs_checkbox.isChecked() return d class ConectatePreferences(QWidget): """The preferences for Conectate backend.""" def __init__(self): super(ConectatePreferences, self).__init__() grid = QGridLayout(self) grid.setSpacing(20) grid.setColumnStretch(1, 10) l = QLabel(u"Ingresá tus datos del portal Conectate:") l.setTextFormat(Qt.RichText) grid.addWidget(l, 0, 0, 1, 2) grid.addWidget(QLabel(u"Usuario:"), 1, 0, 2, 1) prv = config.get('user', '') self.user_entry = QLineEdit(prv) grid.addWidget(self.user_entry, 1, 1, 2, 2) grid.addWidget(QLabel(u"Contraseña:"), 2, 0, 3, 1) prv = config.get('password', '') self.password_entry = QLineEdit(prv) grid.addWidget(self.password_entry, 2, 1, 3, 2) l = QLabel(u'Si no tenés estos datos, registrate aquí' u'' % (URL_CONECTATE,)) l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) l.setTextFormat(Qt.RichText) l.setOpenExternalLinks(True) grid.addWidget(l, 3, 0, 4, 3) def get_config(self): """Return the config for this tab.""" d = {} d['user'] = self.user_entry.text() d['password'] = self.password_entry.text() return d class PreferencesDialog(QDialog): """The dialog for preferences.""" def __init__(self): super(PreferencesDialog, self).__init__() vbox = QVBoxLayout(self) tabbed = QTabWidget() self.gp = GeneralPreferences() tabbed.addTab(self.gp, u"General") self.cp = ConectatePreferences() tabbed.addTab(self.cp, u"Conectate") vbox.addWidget(tabbed) bbox = QDialogButtonBox(QDialogButtonBox.Ok) bbox.accepted.connect(self.accept) bbox.accepted.connect(self._save) vbox.addWidget(bbox) def closeEvent(self, event): """Save and close.""" self._save() super(PreferencesDialog, self).closeEvent(event) def _save(self): """Just save.""" # get it from tabs config.update(self.gp.get_config()) config.update(self.cp.get_config()) config.save() if __name__ == '__main__': project_basedir = os.path.abspath(os.path.dirname(os.path.dirname( os.path.realpath(sys.argv[0])))) sys.path.insert(0, project_basedir) from PyQt4.QtGui import QApplication app = QApplication(sys.argv) frame = PreferencesDialog() frame.show() frame.exec_() frame.save_config() encuentro-1.0/encuentro/ui/remembering.py000066400000000000000000000106601215743623200206510ustar00rootroot00000000000000# -*- coding: UTF-8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """The remembering widgets.""" from PyQt4.QtCore import Qt from PyQt4.QtGui import ( QMainWindow, QSplitter, QTreeWidget, ) from encuentro.config import config, signal SYSTEM = config.SYSTEM class RememberingMainWindow(QMainWindow): """A MainWindow that remembers size and position.""" def __init__(self): super(RememberingMainWindow, self).__init__() signal.register(self.save_state) self._name = self.__class__.__name__ self._initted = False def showEvent(self, event): """Know when it was shown, load config.""" if not self._initted: self._initted = True conf = config[SYSTEM].get(self._name, {}) prv_size = conf.get('size', (800, 600)) prv_pos = conf.get('pos', (300, 300)) self.resize(*prv_size) self.move(*prv_pos) super(RememberingMainWindow, self).showEvent(event) def save_state(self): """Save what to remember.""" qsize = self.size() size = qsize.width(), qsize.height() qpos = self.pos() pos = qpos.x(), qpos.y() to_save = dict(pos=pos, size=size) config[SYSTEM][self._name] = to_save class RememberingSplitter(QSplitter): """A Splitter that remembers position.""" def __init__(self, type_, name): super(RememberingSplitter, self).__init__(type_) signal.register(self.save_state) cname = self.__class__.__name__ self._name = '-'.join((cname, name)) self._initted = False def showEvent(self, event): """Know when it was shown, load config.""" if not self._initted: self._initted = True sizes = config[SYSTEM].get(self._name) if sizes is not None: self.setSizes(sizes) super(RememberingSplitter, self).showEvent(event) def save_state(self): """Save what to remember.""" sizes = self.sizes() config[SYSTEM][self._name] = sizes class RememberingTreeWidget(QTreeWidget): """A TreeWidget that remembers visual stuff.""" def __init__(self, name): super(RememberingTreeWidget, self).__init__() signal.register(self.save_state) cname = self.__class__.__name__ self._name = '-'.join((cname, name)) self._initted = False def showEvent(self, event): """Know when it was shown, load config.""" if not self._initted: self._initted = True info = config[SYSTEM].get(self._name) if info is not None: cols_w = info['cols_w'] for i, w in enumerate(cols_w): self.setColumnWidth(i, w) s_enabled = info['s_enabled'] self.setSortingEnabled(s_enabled) if s_enabled: s_column = info['s_column'] s_order = info['s_order'] ordr = Qt.AscendingOrder if s_order else Qt.DescendingOrder self.sortItems(s_column, ordr) super(RememberingTreeWidget, self).showEvent(event) def save_state(self): """Save what to remember.""" cols_w = [self.columnWidth(i) for i in xrange(self.columnCount())] s_enabled = self.isSortingEnabled() s_column = self.sortColumn() c = self.topLevelItemCount() if c < 2: # less than two records, no point in sorting s_order = True else: val_first = self.topLevelItem(0).text(s_column) val_last = self.topLevelItem(c - 1).text(s_column) s_order = val_first > val_last info = dict(cols_w=cols_w, s_enabled=s_enabled, s_column=s_column, s_order=s_order) config[SYSTEM][self._name] = info encuentro-1.0/encuentro/ui/systray.py000066400000000000000000000061051215743623200200720ustar00rootroot00000000000000# Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Show an icon in the systray.""" import json import logging import subprocess from encuentro import platform from PyQt4.QtGui import QSystemTrayIcon, QIcon, QMenu logger = logging.getLogger("encuentro.systray") def _should_fix(): """Tell if we should fix the Unity panel systray settings. Return None if don't need, else return the current conf. """ cmd = "gsettings get com.canonical.Unity.Panel systray-whitelist".split() try: out = subprocess.check_output(cmd) except Exception, err: # don't have gsettings, nothing to fix etype = err.__class__.__name__ logger.debug("No gsettings, no systray conf to fix (got %r %s)", etype, err) return try: conf = map(str, json.loads(out.strip().replace("'", '"'))) except ValueError: # don't understand the output, can't really fix it :/ logger.warning("Don't understand gsettings output: %r", out) return logger.info("gsettings conf: %r", conf) if "all" in conf or "encuentro" in conf: # we're ok! return # need to fix return conf def _fix_unity_systray(): """Check settings.""" conf = _should_fix() if conf is None: return conf.append("encuentro") cmd = ["gsettings", "set", "com.canonical.Unity.Panel", "systray-whitelist", str(conf)] try: out = subprocess.check_output(cmd) except OSError, err: logger.warning("Error trying to set the new conf: %s", err) else: logger.warning("New config set (result: %r)", out) def show(main_window): """Show a system tray icon with a small icon.""" _fix_unity_systray() icon = QIcon(platform.get_path("encuentro/logos/icon-192.png")) sti = QSystemTrayIcon(icon, main_window) if not sti.isSystemTrayAvailable(): logger.warning("System tray not available.") return def showhide(_): """Show or hide the main window.""" if main_window.isVisible(): main_window.hide() else: main_window.show() _menu = QMenu(main_window) _act = _menu.addAction("Mostrar/Ocultar") _act.triggered.connect(showhide) _act = _menu.addAction("Acerca de") _act.triggered.connect(main_window.open_about_dialog) _act = _menu.addAction("Salir") _act.triggered.connect(main_window.on_close) sti.setContextMenu(_menu) sti.show() encuentro-1.0/encuentro/ui/throbber.py000066400000000000000000000025751215743623200201720ustar00rootroot00000000000000# -*- coding: UTF-8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """A throbber.""" from PyQt4.QtGui import ( QLabel, QMovie, ) from PyQt4.QtCore import Qt from encuentro import platform class Throbber(QLabel): """A throbber.""" def __init__(self): super(Throbber, self).__init__() self.setAlignment(Qt.AlignCenter) fname = platform.get_path("encuentro/ui/media/throbber.gif") self._movie = QMovie(fname) self.setMovie(self._movie) def hide(self): """Overload to control the movie.""" self._movie.stop() super(Throbber, self).hide() def show(self): """Overload to control the movie.""" self._movie.start() super(Throbber, self).show() encuentro-1.0/encuentro/ui/wizard.py000066400000000000000000000137221215743623200176570ustar00rootroot00000000000000# -*- coding: utf8 -*- # Copyright 2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """The wizard that guides the user for the initial setup.""" import logging from PyQt4.QtGui import ( QCheckBox, QDialog, QDialogButtonBox, QLabel, QPushButton, QVBoxLayout, ) from encuentro.config import config logger = logging.getLogger('encuentro.wizard') TEXT_INIT = u""" Bienvenido al visor de contenido del Canal Encuentro y otros. Para poder usar el programa debe primero configurarlo! """ TEXT_EPISODES = u""" Primero tiene que actualizar la lista de episodios: puede actualizar la lista ahora desde esta misma ventana y en cualquier momento desde el menú del programa. """ TEXT_CONFIG = u""" Para poder descargar los programas de los distintos backends tiene que configurar algunos con usuario y clave; puede configurar el sistema ahora desde esta misma ventana o en cualquier momento desde el menú del programa. """ TEXT_END = u""" Felicitaciones, el programa está listo para usar :) """ # The steps for the wizard # - the text to show to the user # - the method to decide if the step should be ignored ("self._ign_"...) # - the text for the action button # - the action when clicked (will compose method with "self._act_") STEPS = [ (TEXT_INIT, None, None, None), (TEXT_EPISODES, "episode", u"Actualizar", "update"), (TEXT_CONFIG, "config", u"Configurar", "configure"), (TEXT_END, None, None, None), ] class WizardDialog(QDialog): """The dialog for update.""" def __init__(self, main_window): super(WizardDialog, self).__init__() self.main_window = main_window vbox = QVBoxLayout(self) # label and checkbox self.main_text = QLabel(u"init text") vbox.addWidget(self.main_text) self.notthisagain = QCheckBox(u"No mostrar automáticamente esta ayuda") nowizard = config.get('nowizard', False) self.notthisagain.setCheckState(nowizard) self.notthisagain.stateChanged.connect(self._notthisagain_toggled) vbox.addWidget(self.notthisagain) # buttons bbox = QDialogButtonBox() self.navbut_actn = QPushButton(u"init text") bbox.addButton(self.navbut_actn, QDialogButtonBox.ActionRole) self.navbut_prev = QPushButton(u"Anterior") bbox.addButton(self.navbut_prev, QDialogButtonBox.ActionRole) self.navbut_next = QPushButton(u"Siguiente") bbox.addButton(self.navbut_next, QDialogButtonBox.ActionRole) vbox.addWidget(bbox) self.show() self.step = 0 self._move(0) def _notthisagain_toggled(self, state): """The "not this again" checkbutton togled state.""" logger.info("Configuring 'nowizard' to %s", state) config['nowizard'] = state def _move(self, delta_step): """The engine for the wizard steps.""" self.step += delta_step logger.debug("Entering into step %d", self.step) (text, ign_func, act_label, act_func) = STEPS[self.step] # if this step should be ignored, just leave if ign_func is not None: m = getattr(self, "_ign_" + ign_func) if m(): # keep going return self._move(delta_step) # adjust navigation buttons if self.step == 0: self.navbut_prev.setEnabled(False) self.navbut_next.setText(u"Siguiente") self.navbut_next.clicked.disconnect() self.navbut_next.clicked.connect(lambda: self._move(1)) self.notthisagain.show() elif self.step == len(STEPS) - 1: self.navbut_prev.setEnabled(True) self.navbut_prev.clicked.disconnect() self.navbut_prev.clicked.connect(lambda: self._move(-1)) self.navbut_next.setText(u"Terminar") self.navbut_next.clicked.disconnect() self.navbut_next.clicked.connect(self.accept) self.notthisagain.hide() else: self.navbut_prev.setEnabled(True) self.navbut_prev.clicked.disconnect() self.navbut_prev.clicked.connect(lambda: self._move(-1)) self.navbut_next.setText(u"Siguiente") self.navbut_next.clicked.disconnect() self.navbut_next.clicked.connect(lambda: self._move(1)) self.notthisagain.hide() # adjust main text and action button self.main_text.setText(text) if act_label is None: self.navbut_actn.hide() else: self.navbut_actn.show() self.navbut_actn.setText(act_label) method_to_call = getattr(self, "_act_" + act_func) self.navbut_actn.clicked.disconnect() self.navbut_actn.clicked.connect(method_to_call) def _act_configure(self, _): """Open the config dialog.""" self.main_window.open_preferences() def _act_update(self, *a): """Open the update dialog.""" self.main_window.refresh_episodes() def _ign_episode(self): """Tell if the episode step should be ignored.""" return self.main_window.have_metadata() def _ign_config(self): """Tell if the configure step should be ignored.""" return self.main_window.have_config() if __name__ == '__main__': import sys from PyQt4.QtGui import QApplication app = QApplication(sys.argv) frame = WizardDialog() frame.show() frame.exec_() encuentro-1.0/encuentro/update.py000066400000000000000000000144671215743623200172330ustar00rootroot00000000000000# -*- coding: utf8 -*- # Copyright 2011-2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Update the episodes metadata.""" import bz2 import json import logging from twisted.internet import defer from twisted.web import client from encuentro.ui import dialogs BACKENDS_URL = "http://www.taniquetil.com.ar/encuentro/backends-v03.list" logger = logging.getLogger('encuentro.update') class UpdateEpisodes(object): """Update the episodes info.""" def __init__(self, main_window): self.main_window = main_window def background(self): """Trigger an update in background.""" self._update() def interactive(self): """Update episodes interactively.""" dialog = dialogs.UpdateDialog() dialog.show() self._update(dialog) @defer.inlineCallbacks def _update(self, dialog=None): """Update the content from server. If we have a dialog (interactive update), check frequently if it was closed, so we stop working for that request. """ if dialog: tell_user = lambda *t: dialog.append(u" ".join(map(unicode, t))) else: tell_user = lambda *t: None logger.info("Downloading backend list") tell_user("Descargando la lista de backends...") try: backends_file = yield client.getPage(BACKENDS_URL) except Exception, e: logger.error("Problem when downloading backends: %s", e) tell_user("Hubo un PROBLEMA al bajar la lista de backends:", e) return if dialog and dialog.closed: return backends_list = [l.strip().split() for l in backends_file.split("\n") if l and l[0] != '#'] backends = {} for b_name, b_dloader, b_url in backends_list: logger.info("Downloading backend metadata for %r", b_name) tell_user("Descargando la lista de episodios para backend %r..." % (b_name,)) try: compressed = yield client.getPage(b_url) except Exception, e: logger.error("Problem when downloading episodes: %s", e) tell_user("Hubo un PROBLEMA al bajar los episodios: ", e) return if dialog and dialog.closed: return tell_user("Descomprimiendo el archivo....") new_content = bz2.decompress(compressed) logger.debug("Downloaded data decompressed ok") content = json.loads(new_content) for item in content: item['downtype'] = b_dloader backends[b_name] = content if dialog and dialog.closed: return tell_user("Conciliando datos de diferentes backends") logger.debug("Merging backends data") new_data = self._merge(backends) tell_user("Actualizando los datos internos....") logger.debug("Updating internal metadata (%d)", len(new_data)) self.main_window.programs_data.merge( new_data, self.main_window.big_panel.episodes) tell_user(u"¡Todo terminado bien!") if dialog: dialog.accept() def _merge(self, backends): """Merge content from all backends. This is for v03, with only 'encuentro' and 'conectar' data to be really merged, other data just appended. """ raw_encuentro_data = backends.pop('encuentro') raw_conectar_data = backends.pop('conectar') enc_data = dict((x['episode_id'], x) for x in raw_encuentro_data) con_data = dict((x['episode_id'], x) for x in raw_conectar_data) common = set(enc_data) & set(con_data) logger.debug("Merging: encuentro=%d conectar=%d (common=%d)", len(enc_data), len(con_data), len(common)) # what is in not common in both goes untouched final_data = ([enc_data[epid] for epid in set(enc_data) - common] + [con_data[epid] for epid in set(con_data) - common]) # what is common, we need to do the merge for epid in common: enc_ep = enc_data[epid] con_ep = con_data[epid] enc_desc = enc_ep['description'] con_desc = con_ep['description'] if enc_desc == con_desc: description = enc_desc elif enc_desc is None: description = con_desc elif con_desc is None: description = enc_desc else: # not None, or they would have been the same, let's concat # both, shorter first if len(con_desc) < len(enc_desc): description = con_desc + ' ' + enc_desc else: description = enc_desc + ' ' + con_desc # if both are equal (None or not), it also works if enc_ep['duration'] is None: duration = con_ep['duration'] else: duration = enc_ep['duration'] if enc_ep['image_url'] is None: image_url = con_ep['image_url'] else: image_url = enc_ep['image_url'] d = dict(episode_id=epid, description=description, duration=duration, url=con_ep['url'], channel=con_ep['channel'], title=con_ep['title'], section=con_ep['section'], image_url=image_url, downtype=con_ep['downtype']) final_data.append(d) logger.debug("Merging: appending other data: %s", backends.keys()) for data in backends.itervalues(): final_data.extend(data) logger.debug("Merged, final: %d", len(final_data)) return final_data encuentro-1.0/qtreactor/000077500000000000000000000000001215743623200153655ustar00rootroot00000000000000encuentro-1.0/qtreactor/LICENSE000066400000000000000000000031701215743623200163730ustar00rootroot00000000000000Copyright (c) 2001-2010 Allen Short Andy Gayton Andrew Bennetts Antoine Pitrou Apple Computer, Inc. Benjamin Bruheim Bob Ippolito Canonical Limited Christopher Armstrong David Reid Donovan Preston Eric Mangold Eyal Lotem Itamar Shtull-Trauring James Knight Jason A. Mobarak Jean-Paul Calderone Jessica McKellar Jonathan Jacobs Jonathan Lange Jonathan D. Simms Jürgen Hermann Kevin Horn Kevin Turner Mary Gardiner Matthew Lefkowitz Massachusetts Institute of Technology Moshe Zadka Paul Swartz Pavel Pergamenshchik Ralph Meijer Sean Riley Software Freedom Conservancy Travis B. Hartwell Thijs Triemstra Thomas Herve Timothy Allen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. encuentro-1.0/qtreactor/README000066400000000000000000000033651215743623200162540ustar00rootroot00000000000000Unpack this directory into your PYTHONPATH. test with: trial --reactor=qt4 twisted (or twisted.test or twisted.test.test_internet) = Contributors = Many thanks to Darren Dale who provided the patch to fix the reactor for Qt4.4 = Using the Qt4Reactor = In your own code, BEFORE you import the reactor... app = QApplication(sys.argv) import qt4reactor qt4reactor.install() = Gui = There is a way to run trial using a gui... in bin, there is a routine gtrial. Put that in the same directory as trial and it pops up a trivial gui... hit the buton and it all runs the same... don't use the --reactor option when calling gtrial... but all the other options appear to work. This was just to make sure there wasn't anything strange with guis which there doesn't appear to be If you're writing a conventional Qt application and just want twisted as an addon, you can get that by calling reactor.runReturn() instead of run(). This call needs to occur after your installation of of the reactor and after QApplication.exec_() (or QCoreApplication.exec_() whichever you are using. reactor.run() will also work as expected in a typical twisted application more docs in qt4reactor.py Note that if a QApplication or QCoreApplication instance isn't constructed prior to calling reactor run, an internally owned QCoreApplication is created and destroyed. This won't work if you call runReturn instead of run unless you take responsibility for wacking QCoreApplication yourself... However, most users want this reactor to do gui stuff so this shouldn't be an issue. Performance impact of Qt has been reduced by minimizing use of signaling which is expensive. 186s for qt4reactor vs 180s for select for entire twisted trial suite. -glenn -- Glenn H. Tarbox, PhD glenn@tarbox.org encuentro-1.0/qtreactor/__init__.py000066400000000000000000000000001215743623200174640ustar00rootroot00000000000000encuentro-1.0/qtreactor/qt4reactor.py000066400000000000000000000242101215743623200200260ustar00rootroot00000000000000# Copyright (c) 2001-2011 Twisted Matrix Laboratories. # See LICENSE for details. """ This module provides support for Twisted to be driven by the Qt mainloop. In order to use this support, simply do the following:: | app = QApplication(sys.argv) # your code to init Qt | import qt4reactor | qt4reactor.install() alternatively: | from twisted.application import reactors | reactors.installReactor('qt4') Then use twisted.internet APIs as usual. The other methods here are not intended to be called directly. If you don't instantiate a QApplication or QCoreApplication prior to installing the reactor, a QCoreApplication will be constructed by the reactor. QCoreApplication does not require a GUI so trial testing can occur normally. Twisted can be initialized after QApplication.exec_() with a call to reactor.runReturn(). calling reactor.stop() will unhook twisted but leave your Qt application running API Stability: stable Maintainer: U{Glenn H Tarbox, PhD} Previous maintainer: U{Itamar Shtull-Trauring} Original port to QT4: U{Gabe Rudy} Subsequent port by therve """ import sys import time from zope.interface import implements from twisted.internet.interfaces import IReactorFDSet from twisted.python import log, runtime from twisted.internet import posixbase from twisted.python.runtime import platformType, platform try: from PyQt4.QtCore import QSocketNotifier, QObject, SIGNAL, QTimer, QCoreApplication from PyQt4.QtCore import QEventLoop except ImportError: from PySide.QtCore import QSocketNotifier, QObject, SIGNAL, QTimer, QCoreApplication from PySide.QtCore import QEventLoop class TwistedSocketNotifier(QObject): """ Connection between an fd event and reader/writer callbacks. """ def __init__(self, parent, reactor, watcher, socketType): QObject.__init__(self, parent) self.reactor = reactor self.watcher = watcher fd = watcher.fileno() self.notifier = QSocketNotifier(fd, socketType, parent) self.notifier.setEnabled(True) if socketType == QSocketNotifier.Read: self.fn = self.read else: self.fn = self.write QObject.connect(self.notifier, SIGNAL("activated(int)"), self.fn) def shutdown(self): self.notifier.setEnabled(False) self.disconnect(self.notifier, SIGNAL("activated(int)"), self.fn) self.fn = self.watcher = None self.notifier.deleteLater() self.deleteLater() def read(self, fd): if not self.watcher: return w = self.watcher # doRead can cause self.shutdown to be called so keep a reference to self.watcher def _read(): #Don't call me again, until the data has been read self.notifier.setEnabled(False) why = None try: why = w.doRead() inRead = True except: inRead = False log.err() why = sys.exc_info()[1] if why: self.reactor._disconnectSelectable(w, why, inRead) elif self.watcher: self.notifier.setEnabled(True) # Re enable notification following sucessfull read self.reactor._iterate(fromqt=True) log.callWithLogger(w, _read) def write(self, sock): if not self.watcher: return w = self.watcher def _write(): why = None self.notifier.setEnabled(False) try: why = w.doWrite() except: log.err() why = sys.exc_info()[1] if why: self.reactor._disconnectSelectable(w, why, False) elif self.watcher: self.notifier.setEnabled(True) self.reactor._iterate(fromqt=True) log.callWithLogger(w, _write) class QtReactor(posixbase.PosixReactorBase): implements(IReactorFDSet) def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp=QCoreApplication([]) self._ownApp=True else: self.qApp = QCoreApplication.instance() self._ownApp=False self._blockApp = None posixbase.PosixReactorBase.__init__(self) def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type) def addReader(self, reader): """ Add a FileDescriptor for notification of data available to read. """ self._add(reader, self._reads, QSocketNotifier.Read) def addWriter(self, writer): """ Add a FileDescriptor for notification of data available to write. """ self._add(writer, self._writes, QSocketNotifier.Write) def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown() def removeReader(self, reader): """ Remove a Selectable for notification of data available to read. """ self._remove(reader, self._reads) def removeWriter(self, writer): """ Remove a Selectable for notification of data available to write. """ self._remove(writer, self._writes) def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv def getReaders(self): return self._reads.keys() def getWriters(self): return self._writes.keys() def callLater(self,howlong, *args, **kargs): rval = super(QtReactor,self).callLater(howlong, *args, **kargs) self.reactorInvocation() return rval def reactorInvocation(self): self._timer.stop() self._timer.setInterval(0) self._timer.start() def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay, fromqt) iterate = _iterate def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000) if self.timeout() is None: timeout = 0.1 elif self.timeout() == 0: timeout = 0 else: timeout = self.timeout() self._timer.setInterval(timeout * 1000) self._timer.start() def runReturn(self, installSignalHandlers=True): self.startRunning(installSignalHandlers=installSignalHandlers) self.reactorInvocation() def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_() class QtEventReactor(QtReactor): def __init__(self, *args, **kwargs): self._events = {} super(QtEventReactor, self).__init__() def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """ self._events[event] = (fd, action) def removeEvent(self, event): """ Remove an event. """ if event in self._events: del self._events[event] def doEvents(self): handles = self._events.keys() if len(handles) > 0: val = None while val != WAIT_TIMEOUT: val = MsgWaitForMultipleObjects(handles, 0, 0, QS_ALLINPUT | QS_ALLEVENTS) if val >= WAIT_OBJECT_0 and val < WAIT_OBJECT_0 + len(handles): event_id = handles[val - WAIT_OBJECT_0] if event_id in self._events: fd, action = self._events[event_id] log.callWithLogger(fd, self._runAction, action, fd) elif val == WAIT_TIMEOUT: pass else: #print 'Got an unexpected return of %r' % val return def _runAction(self, action, fd): try: closed = getattr(fd, action)() except: closed = sys.exc_info()[1] log.deferr() if closed: self._disconnectSelectable(fd, closed, action == 'doRead') def timeout(self): t = super(QtEventReactor, self).timeout() return min(t, 0.01) def iterate(self, delay=None): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doEvents() self.doIteration(delay) def posixinstall(): """ Install the Qt reactor. """ p = QtReactor() from twisted.internet.main import installReactor installReactor(p) def win32install(): """ Install the Qt reactor. """ p = QtEventReactor() from twisted.internet.main import installReactor installReactor(p) if runtime.platform.getType() == 'win32': from win32event import CreateEvent, MsgWaitForMultipleObjects from win32event import WAIT_OBJECT_0, WAIT_TIMEOUT, QS_ALLINPUT, QS_ALLEVENTS install = win32install else: install = posixinstall __all__ = ["install"] encuentro-1.0/qtreactor/twisted/000077500000000000000000000000001215743623200170505ustar00rootroot00000000000000encuentro-1.0/qtreactor/twisted/plugins/000077500000000000000000000000001215743623200205315ustar00rootroot00000000000000encuentro-1.0/qtreactor/twisted/plugins/qt4.py000066400000000000000000000004071215743623200216140ustar00rootroot00000000000000# Copyright (c) 2001-2010 Twisted Matrix Laboratories. # see LICENSE for details from twisted.application.reactors import Reactor qt4 = Reactor('qt4', 'qt4reactor', 'Qt4 integration reactor') qt4bad = Reactor('qt4bad', 'qt4reactor_bad', 'Qt4 broken reactor') encuentro-1.0/setup.py000077500000000000000000000113671215743623200151060ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2011 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Build tar.gz for encuentro. Needed packages to run (using Debian/Ubuntu package names): python 2.6.6 python-mechanize 0.1.11 python-twisted-bin 8.2.0 python-twisted-web 8.2.0 python-qt4 4.9.1 python-xdg 0.15 python-notify 0.1.1 # not really needed, but provides notifications """ import os import shutil from distutils.command.install import install from distutils.core import setup class CustomInstall(install): """Custom installation class on package files. It copies all the files into the "PREFIX/share/PROJECTNAME" dir. """ def run(self): """Run parent install, and then save the install dir in the script.""" install.run(self) # fix installation path in the script(s) for script in self.distribution.scripts: script_path = os.path.join(self.install_scripts, os.path.basename(script)) with open(script_path, 'rb') as fh: content = fh.read() content = content.replace('@ INSTALLED_BASE_DIR @', self._custom_data_dir) with open(script_path, 'wb') as fh: fh.write(content) # fix the icon path, and save the .desktop file where it should be src_desktop = self.distribution.get_name() + '.desktop' if not os.path.exists(self._custom_apps_dir): os.makedirs(self._custom_apps_dir) dst_desktop = os.path.join(self._custom_apps_dir, src_desktop) with open(src_desktop, 'rb') as fh: content = fh.read() icon = os.path.join(self._custom_data_dir, 'encuentro', 'logos', 'icon-32.png') content = content.replace('@ INSTALLED_ICON @', icon) with open(dst_desktop, 'wb') as fh: fh.write(content) # install apport file if not os.path.exists(self._custom_apport_dir): os.makedirs(self._custom_apport_dir) shutil.copy("source_encuentro.py", self._custom_apport_dir) # version file shutil.copy("version.txt", self.install_lib) def finalize_options(self): """Alter the installation path.""" install.finalize_options(self) # the data path is under 'prefix' data_dir = os.path.join(self.prefix, "share", self.distribution.get_name()) apps_dir = os.path.join(self.prefix, "share", "applications") apport_dir = os.path.join(self.prefix, "share", "apport", "package-hooks") # if we have 'root', put the building path also under it (used normally # by pbuilder) if self.root is None: build_dir = data_dir else: build_dir = os.path.join(self.root, data_dir[1:]) apps_dir = os.path.join(self.root, apps_dir[1:]) apport_dir = os.path.join(self.root, apport_dir[1:]) # change the lib install directory so all package files go inside here self.install_lib = build_dir # save this custom data dir to later change the scripts self._custom_data_dir = data_dir self._custom_apps_dir = apps_dir self._custom_apport_dir = apport_dir setup( name='encuentro', version=open('version.txt').read().strip(), license='GPL-3', author='Facundo Batista', author_email='facundo@taniquetil.com.ar', description='Search, download and see the wonderful Encuentro content.', long_description='Simple application that allows to search, download ' \ 'and see the content of the Encuentro channel.', url='https://launchpad.net/encuentro', packages=["encuentro", "encuentro.ui", "qtreactor"], package_data={ "encuentro": ["ui/media/*", "logos/icon-*.png"], "": ["encuentro.desktop", "source_encuentro.py", "version.txt"], "qtreactor": ["qt4reactor.py", "README", "LICENSE", "twisted/plugins/qt4.py"], }, scripts=["bin/encuentro"], cmdclass={ 'install': CustomInstall, }, ) encuentro-1.0/source_encuentro.py000066400000000000000000000022501215743623200173140ustar00rootroot00000000000000 # Copyright 2011-2013 Facundo Batista # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # # For further info, check https://launchpad.net/encuentro """Configuration file for Apport.""" from apport.hookutils import attach_related_packages, attach_file_if_exists from encuentro import logger def add_info(report): """Add info to the report.""" # attach the log fname = logger.get_filename() attach_file_if_exists(report, fname, "EncuentroLog") # info about dependencies packages = ["python-mechanize", "python-twisted-bin", "python-qt4", "python-xdg"] attach_related_packages(report, packages) encuentro-1.0/version.txt000066400000000000000000000000041215743623200156010ustar00rootroot000000000000001.0