# HG changeset patch # User goffi@necton2 # Date 1251545699 -7200 # Node ID c4bc297b82f029b7b02a08e125c7a31e57fe233d sat: - first public release, initial commit diff -r 000000000000 -r c4bc297b82f0 LICENSE --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LICENSE Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff -r 000000000000 -r c4bc297b82f0 README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,114 @@ +SàT +(c) Jérôme Poisson aka Goffi 2008,2009 + +SàT is a XMPP (Jabber) client. + + + + + +** LICENSE ** + +SàT 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. + +SàT 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 SàT. If not, see . + + + +It is currently in a very alpha stage, and absolutely not usable for everyday use, use at your own risks ! + + + + + +** WTF ? ** +SàT is a XMPP (Jabber) client, made on a daemon/frontend architecture. Its aim is not only to be an instant messagery client: XMPP offer a lot more, and differents tools will come in the future. + +For the moment, the frontends are: + +* wix: a wxwidget frontend, the main graphical frontend +* sortilège: a ncurses client, for screen lovers +* jp: the command line toolkit. The tool for geeks by geeks + +other frontends planed in the near future: + +* a web frontend +* a KDE 4 frontend, as KDE is my main desktop environment + + + + + +** How to use it ? ** + +SàT is really at an early dev stage, so it's maybe the buggiest software you have ever seen, and there are for the moment absolutely nothing to ease the installation and use (but it will be the case ASAP, one of the goal of the project is the ease of use). +You must have the main dir (with sat inside) and frontend in your PYTHONPATH. For exemple, if you have uncompressed the soft in /tmp/useless_soft: + +$ export PYTHONPATH=$PYTHONPATH:/tmp/useless_soft:/tmp/useless_soft/frontends + +if you wants to access jp, it can be a good idea to export its dir to your PATH: + +$ export PATH=$PATH:/tmp/useless_soft/frontends/jp + +There will probably be a wiki doc in the future. + + + + + +** Misc ** + +-- Shortcuts for sortilège (temporary): +C-L: access contact list (enter to valid) +F2: Show/Hide contact list +C-S: Short representation of contacts in chat window +C-C: Use colors... or not +C-T: Timestamp +C-X: Leave +-- + +SàT is the acronym (yes another one :( ) in tribute to the song Salut à Toi from the Bérurier Noir band. I recommand also the excelent cover from Les Ogres de Barback. +jp stands for Jabber coPy or JumP. If you look well, you can also find my initials ;) +sortilège means "spell" in french, and it is ncurses based... +wix come of course from the WX of wxwidgets and just sound cool :). + + + + + +** Credit ** + +proxy65: +SàT (plugin_xep_0065) use nearly all the code from proxy65 (http://code.google.com/p/proxy65/) wich was coded by Dave Smith (2002-2004) and maintained by Fabio Forno (2007-2008). +As the original MIT license allow, the code is reused and sublicensed until GPL v3 to follow the rest of the code. Thanks a lot to them ! + +progressbar: +SàT (jp) use ProgressBar (http://pypi.python.org/pypi/progressbar/2.2), a class coded by Nilton Volpato which allow the textual representation of progression. thanks to him + +twisted: +SàT is based on the twisted framework (http://twistedmatrix.com/trac/), a very great tools which offer a lot of protocols management. There are too many contributors to name them here, so take a look on the website :). Again, thanks to them + +and the others: +and of course, nothing would be possible without Python (http://www.python.org/), Gnu and the Free Software Foundation (http://www.gnu.org, http://www.fsf.org/), the Linux Kernel (http://www.kernel.org/), and the coder of the tools I use like Vim (http://www.vim.org/), Mercurial (http://www.selenic.com/mercurial/wiki/), or all the KDE stuff (http://www.kde.org/ and of course http://amarok.kde.org/), etc. Thanks thanks thanks, thank to everybody in the Free (Libre) chain for making a part of the dream. + + + + + +** Contact ** + +You can contact me on goffi@goffi.org . Yes I know, I don't give my JID ;) +You'll find the latest version on my website: http://www.goffi.org (it's mainly in french, I will probably make a little part in english in the future). + + + +This software is dedicated to Roger Poisson. diff -r 000000000000 -r c4bc297b82f0 frontends/jp/jp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/jp/jp Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,253 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- + +""" +jp: a SAT command line tool +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +#consts +name = "jp" +version = "0.0.1" +about = name+" v"+version+""" (c) Jérôme Poisson (aka Goffi) 2009 + +--- +"""+name+""" Copyright (C) 2009 Jérôme Poisson (aka Goffi) +This program comes with ABSOLUTELY NO WARRANTY; +This is free software, and you are welcome to redistribute it +under certain conditions. +--- + +This software is a command line tool for jabber +Get the latest version at http://www.goffi.org +""" + +global pbar_available +pbar_available = True #checked before using ProgressBar + +### logging ### +import logging +from logging import debug, info, error, warning +logging.basicConfig(level=logging.DEBUG, + format='%(message)s') +### + +import sys +import os +from os.path import abspath, basename, dirname +from optparse import OptionParser +import pdb +from tools.jid import JID +import gobject +from sat_bridge_frontend.DBus import DBusBridgeFrontend +import tarfile +try: + from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed +except ImportError, e: + info ('ProgressBar not available, please download it at http://pypi.python.org/pypi/progressbar') + info ('Progress bar deactivated\n--\n') + pbar_available=False + + + + +class JP(): + def __init__(self): + self.bridge=DBusBridgeFrontend() + self.transfert_id = None + + def check_options(self): + """Check command line options""" + usage=""" + %prog [options] [FILE1 FILE2 ...] JID + %prog -w [options] [JID1 JID2 ...] + + %prog --help for options list + """ + parser = OptionParser(usage=usage,version=about) + + parser.add_option("-b", "--bz2", action="store_true", default=False, + help="Make a bzip2 tarball") + parser.add_option("-w", "--wait-file", action="store_true", default=False, + help="Wait for a file to be sent by a contact") + parser.add_option("-m", "--multiple", action="store_true", default=False, + help="Accept multiple files (you'll have to stop manually)") + parser.add_option("-f", "--force", action="store_true", default=False, + help="Force overwritting of existing files") + parser.add_option("-p", "--progress", action="store_true", default=False, + help="Show progress bar") + parser.add_option("-s", "--separate", action="store_true", default=False, + help="Separate xmpp messages: send one message per line instead of one message alone.") + parser.add_option("-n", "--new-line", action="store_true", default=False, + help="Add a new line at the beginning of the input (usefull for ascii art ;))") + + (self.options, args) = parser.parse_args() + + if len(args) < 1 and not self.options.wait_file: + parser.error("You must specify the destination JID (Jabber ID)") + + if self.options.wait_file: + #several jid + self.dest_jids = args + else: + #one dest_jid, other args are files + self.dest_jid = JID(args[-1]) + if not self.dest_jid.is_valid: + error ("%s is not a valid JID !", self.dest_jid) + exit(1) + self.files = args[:-1] + + if not pbar_available and self.options.progress: + self.options.progress = False + error ("Option progress is not available, deactivated.") + + if self.options.progress or self.options.wait_file: + self.start_loop = True #We have to use loop for these options + else: + self.start_loop = False + + + return args + + def check_jabber_status(self): + """Check that jabber status is allright""" + if not self.bridge.isConnected(): + error("SAT is not conneted, please connect before using jp") + exit(1) + + + def send_stdin(self): + """Send incomming data on stdin to jabber contact""" + header = "\n" if self.options.new_line else "" + + if self.options.separate: #we send stdin in several messages + if header: + self.bridge.sendMessage(self.dest_jid, header) + while (True): + line = sys.stdin.readline() + if not line: + break + self.bridge.sendMessage(self.dest_jid, line.replace("\n","")) + else: + self.bridge.sendMessage(self.dest_jid, header + "".join(sys.stdin.readlines())) + + def send_files(self): + """Send files to jabber contact""" + + for file in self.files: + if not os.path.exists(file): + error ("File [%s] doesn't exist !" % file) + exit(1) + if not self.options.bz2 and os.path.isdir(file): + error ("[%s] is a dir ! Please send files inside or use compression" % file) + exit(1) + + if self.options.bz2: + tmpfile = (basename(self.files[0]) or basename(dirname(self.files[0])) ) + '.tar.bz2' #FIXME: tmp, need an algorithm to find a good name/path + if os.path.exists(tmpfile): + error ("tmp file (%s) already exists ! Please remove it", tmpfile) + exit(1) + warning("bz2 is an experimental option at an early dev stage, use with caution") + #FIXME: check free space, writting perm, tmp dir, filename (watch for OS used) + info("Starting compression, please wait...") + sys.stdout.flush() + bz2=tarfile.open(tmpfile, "w:bz2") + for file in self.files: + info("Adding %s", file) + bz2.add(file) + bz2.close() + info("OK !") + path = abspath(tmpfile) + self.transfert_id = self.bridge.sendFile(self.dest_jid, path) + else: + for file in self.files: + path = abspath(file) + self.transfert_id = self.bridge.sendFile(self.dest_jid, path) #FIXME: show progress only for last transfert_id + + #TODO: manage ProgressBar + + def askConfirmation(self, type, id, data): + """CB used for file transfert, accept files depending on parameters""" + answer_data={} + if type == "FILE_TRANSFERT": + if self.dest_jids and not data['from'] in self.dest_jids: + return #file is not sent by a filtered jid + + answer_data["dest_path"] = os.getcwd()+'/'+data['filename'] + + if self.options.force or not os.path.exists(answer_data["dest_path"]): + self.bridge.confirmationAnswer(id, True, answer_data) + info("Accepted file [%s] from %s", data['filename'], data['from']) + self.transfert_id = id + else: + self.bridge.confirmationAnswer(id, False, answer_data) + warning("Refused file [%s] from %s: a file with the same name already exist", data['filename'], data['from']) + + + if not self.options.multiple and not self.options.progress: + #we just accept one file + self.loop.quit() + + + def wait_file(self): + """Wait for a file and write it on local dir""" + self.bridge.register("askConfirmation", self.askConfirmation, "request") + + def progressCB(self): + if self.transfert_id: + data = self.bridge.getProgress(self.transfert_id) + if data: + if not data['position']: + data['position'] = '0' + if not self.pbar: + #first answer, we must construct the bar + self.pbar = ProgressBar(int(data['size']),["Progress: ",Percentage()," ",Bar()," ",FileTransferSpeed()," ",ETA()]) + self.pbar.start() + + self.pbar.update(int(data['position'])) + elif self.pbar: + self.pbar.finish() + if not self.options.multiple: + self.loop.quit() + return False + + return True + + def go(self): + self.check_options() + self.check_jabber_status() + if self.options.wait_file: + self.wait_file() + else: + if not self.files: #we send message only if there are no files to send + self.send_stdin() + else: + self.send_files() + + if self.start_loop: + self.loop = gobject.MainLoop() + if self.options.progress: + self.pbar = None + gobject.timeout_add(10, self.progressCB) + try: + self.loop.run() + except KeyboardInterrupt: + info("User interruption: good bye") + + +if __name__ == "__main__": + jp = JP() + jp.go() diff -r 000000000000 -r c4bc297b82f0 frontends/quick_frontend/__init__.py diff -r 000000000000 -r c4bc297b82f0 frontends/quick_frontend/quick_app.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/quick_frontend/quick_app.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,159 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +helper class for making a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from logging import debug, info, error +from tools.jid import JID +from sat_bridge_frontend.DBus import DBusBridgeFrontend +from quick_frontend.quick_contact_management import QuickContactManagement + + + +class QuickApp(): + """This class contain the main methods needed for the frontend""" + + def __init__(self): + self.rosterList = {} + self.CM = QuickContactManagement() #a short name if more handy + + ## bridge ## + self.bridge=DBusBridgeFrontend() + self.bridge.register("newContact", self.newContact) + self.bridge.register("newMessage", self.newMessage) + self.bridge.register("presenceUpdate", self.presenceUpdate) + self.bridge.register("paramUpdate", self.paramUpdate) + self.bridge.register("contactDeleted", self.contactDeleted) + self.bridge.register("askConfirmation", self.askConfirmation, "request") + + ###now we get the essential params### + self.whoami=JID(self.bridge.getParam("JabberID","Connection")[0]) + self.watched=self.bridge.getParam("Watched", "Misc")[0].split() #TODO: put this in a plugin + + ## misc ## + self.onlineContact = set() #FIXME: temporary + + if self.bridge.isConnected(): + self.setStatusOnline(True) + + ### now we fill the contact list ### + for contact in self.bridge.getContacts(): + self.newContact(contact[0], contact[1], contact[2]) + + for status in self.bridge.getPresenceStatus(): + self.presenceUpdate(status[0], status[1], status[2], status[3], status[4]) + + + def newContact(self, JabberId, attributes, groups): + jid=JID(JabberId) + self.rosterList[jid.short]=(dict(attributes), list(groups)) + + def newMessage(self, from_jid, msg, type, to_jid): + sender=JID(from_jid) + addr=JID(to_jid) + win = addr if sender.short == self.whoami.short else sender + self.chat_wins[win.short].printMessage(sender, msg) + + def setStatusOnline(self, online=True): + pass + + def presenceUpdate(self, jabber_id, type, show, status, priority): + debug ("presence update for %s (type=%s, show=%s, status=%s)", jabber_id, type, show, status); + jid=JID(jabber_id) + debug ("jid.short=%s whoami.short=%s", jid.short, self.whoami.short) + + ### subscription management ### + if type=="subscribed": + # this is a subscription confirmation, we just have to inform user + self.showDialog("The contact %s has accepted your subscription" % jid.short, 'Subscription confirmation') + return + elif type=="unsubscribed": + # this is a subscription refusal, we just have to inform user + self.showDialog("The contact %s has refused your subscription" % jid.short, 'Subscription refusal', 'error') + return + elif type=="subscribe": + # this is a subscrition request, we have to ask for user confirmation + answer = self.showDialog("The contact %s wants to subscribe to your presence.\nDo you accept ?" % jid.short, 'Subscription confirmation', 'question') + if answer: + self.bridge.setPresence(type="subscribed", to=jid.short) + else: + self.bridge.setPresence(type="unsubscribed", to=jid.short) + return + ### subscription management end ### + + if jid.short==self.whoami.short: + if not type: + self.setStatusOnline(True) + elif type=="unavailable": + self.setStatusOnline(False) + return + + if not type: + name="" + group="" + if self.rosterList.has_key(jid.short): + if self.rosterList[jid.short][0].has_key("name"): + name=self.rosterList[jid.short][0]["name"] + if self.rosterList[jid.short][0].has_key("show"): + name=self.rosterList[jid.short][0]["show"] + if self.rosterList[jid.short][0].has_key("status"): + name=self.rosterList[jid.short][0]["status"] + if len(self.rosterList[jid.short][1]): + group=self.rosterList[jid.short][1][0] + + #FIXME: must be moved in a plugin + if jid.short in self.watched and not jid.short in self.onlineContact: + self.showAlert("Watched jid [%s] is connected !" % jid.short) + + self.onlineContact.add(jid) #FIXME onlineContact is useless with CM, must be removed + self.CM.add(jid) + self.contactList.replace(jid, show=show, status=status, name=name, group=group) + + + if type=="unavailable" and jid.short in self.onlineContact: + self.onlineContact.remove(jid.short) + self.CM.remove(jid) + self.contactList.remove(jid) + + + def showDialog(self, message, title, type="info"): + raise NotImplementedError + + def showAlert(self, message): + pass #FIXME + + def paramUpdate(self, name, value, namespace): + debug("param update: [%s] %s = %s", namespace, name, value) + if (namespace,name) == ("Connection", "JabberID"): + debug ("Changing ID to %s", value) + self.whoami=JID(value) + elif (namespace,name) == ("Misc", "Watched"): + self.watched=value.split() + + def contactDeleted(self, jid): + target = JID(jid) + try: + self.onlineContact.remove(target.short) + except KeyError: + pass + self.contactList.remove(self.CM.get_full(jid)) + self.CM.remove(target) + + def askConfirmation(self, type, id, data): + raise NotImplementedError diff -r 000000000000 -r c4bc297b82f0 frontends/quick_frontend/quick_chat.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/quick_frontend/quick_chat.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,47 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +helper class for making a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from logging import debug, info, error +from tools.jid import JID + + + +class QuickChat(): + + def __init__(self, to_jid, host): + self.to_jid = to_jid + self.host = host + + def historyPrint(self, size=20, keep_last=False): + """Print the initial history""" + debug ("now we print history") + history=self.host.bridge.getHistory(self.host.whoami.short, self.to_jid, 20) + stamps=history.keys() + stamps.sort() + for stamp in stamps: + self.printMessage(JID(history[stamp][0]), history[stamp][1], stamp) + if keep_last: ##FIXME hack for sortilege + self.last_history = stamps[-1] if stamps else None + + def printMessage(self, from_jid, msg, timestamp): + """Print message in chat window. Must be implemented by child class""" + raise NotImplementedError + diff -r 000000000000 -r c4bc297b82f0 frontends/quick_frontend/quick_chat_list.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/quick_frontend/quick_chat_list.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,41 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +helper class for making a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from tools.jid import JID + + +class QuickChatList(dict): + """This class is used to manage the list of chat windows. + It act as a dict, but create a chat window when the name is found for the first time.""" + + def __init__(self, host): + dict.__init__(self) + self.host = host + + def __getitem__(self,name_param): + name=JID(name_param).short + if not self.has_key(name): + #we have to create the chat win + self[name] = self.createChat(name) + return dict.__getitem__(self,name) + + def createChat(self, name): + raise NotImplementedError diff -r 000000000000 -r c4bc297b82f0 frontends/quick_frontend/quick_contact_list.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/quick_frontend/quick_contact_list.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,42 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +helper class for making a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from logging import debug, info, error +from tools.jid import JID + + +class QuickContactList(): + + def __init__(self): + debug("Contact List init") + self.jid_ids={} + + def replace(self, jid, name="", show="", status="", group=""): + """add a contact to the list""" + raise NotImplementedError + + def remove(self, jid): + """remove a contact from the list""" + raise NotImplementedError + + def add(self, jid, name="", show="", status="", group=""): + """add a contact to the list""" + raise NotImplementedError diff -r 000000000000 -r c4bc297b82f0 frontends/quick_frontend/quick_contact_management.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/quick_frontend/quick_contact_management.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,47 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +helper class for making a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from logging import debug, info, error +from tools.jid import JID +import pdb + + +class QuickContactManagement(): + """This helper class manage the contacts and ease the use of nicknames and shortcuts""" + + def __init__(self): + self.__contactlist = {} + + def add(self, jid_param): + jid=JID(jid_param) + self.__contactlist[jid.short] = {'name':jid, 'last_resource':jid.resource} + + def remove(self, jid_param): + jid=JID(jid_param) + try: + del self.__contactlist[jid.short] + except KeyError: + pass + + def get_full(self, jid_param): + jid=JID(jid_param) + return jid.short+'/'+self.__contactlist[jid.short]['last_resource'] + diff -r 000000000000 -r c4bc297b82f0 frontends/sat_bridge_frontend/DBus.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sat_bridge_frontend/DBus.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,89 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- + +""" +SAT communication bridge +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from bridge_frontend import BridgeFrontend +import dbus, dbus.glib + + +class DBusBridgeFrontend(BridgeFrontend): + def __init__(self): + self.sessions_bus = dbus.SessionBus() + self.db_object = self.sessions_bus.get_object('org.goffi.SAT', + '/org/goffi/SAT/bridge') + self.db_comm_iface = dbus.Interface(self.db_object, + dbus_interface='org.goffi.SAT.communication') + self.db_req_iface = dbus.Interface(self.db_object, + dbus_interface='org.goffi.SAT.request') + #props = self.db_comm_iface.getProperties() + + def register(self, functionName, handler, iface="communication"): + if iface == "communication": + self.db_comm_iface.connect_to_signal(functionName, handler) + elif iface == "request": + self.db_req_iface.connect_to_signal(functionName, handler) + + def connect(self): + return self.db_comm_iface.connect() + + def getContacts(self): + return self.db_comm_iface.getContacts() + + def getPresenceStatus(self): + return self.db_comm_iface.getPresenceStatus() + + def sendMessage(self, to, message): + return self.db_comm_iface.sendMessage(to, message) + + def sendFile(self, to, path): + return self.db_comm_iface.sendFile(to, path) + + def setPresence(self, to="", type="", show="", status="", priority=0): + return self.db_comm_iface.setPresence(to, type, show, status, priority) + + def setParam(self, name, value, namespace="default"): + return self.db_comm_iface.setParam(name, value, namespace) + + def getParam(self, name, namespace="default"): + return self.db_comm_iface.getParam(name, namespace) + + def getParams(self, namespace="default"): + return self.db_comm_iface.getParams(namespace) + + def getParamsCategories(self): + return self.db_comm_iface.getParamsCategories() + + def getHistory(self, from_jid, to_jid, size): + return self.db_comm_iface.getHistory(from_jid, to_jid, size) + + def addContact(self, jid): + return self.db_comm_iface.addContact(jid) + + def delContact(self, jid): + return self.db_comm_iface.delContact(jid) + + def isConnected(self): + return self.db_comm_iface.isConnected() + + def confirmationAnswer(self, id, accepted, data): + return self.db_req_iface.confirmationAnswer(id, accepted, data) + + def getProgress(self, id): + return self.db_req_iface.getProgress(id) diff -r 000000000000 -r c4bc297b82f0 frontends/sat_bridge_frontend/__init__.py diff -r 000000000000 -r c4bc297b82f0 frontends/sat_bridge_frontend/bridge_frontend.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sat_bridge_frontend/bridge_frontend.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,28 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- + +""" +SAT communication bridge +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +class BridgeFrontend: + def __init__(self): + print "Bridge frontend initialization" + + + def register(self, functionName, handler): + raise NotImplementedError diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/__init__.py diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/boxsizer.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sortilege/boxsizer.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,88 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +sortilege: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +from window import Window +import os,pdb + + +def echo(message): + return + os.system('echo "'+str(message)+'" >> /tmp/toto') + + +class BoxSizer: + """This class manage the position of the window like boxes.""" + + + + def __init__(self, parent): + self.__parent=parent + self.boxes=[] + + + + def appendRow(self, win): + self.boxes.append([win]) + + def appendColum(self, index, win): + if len(self.boxes)<=index: + #TODO: throw an error here + return + self.boxes[index].append(win) + + def update(self): + """Resize boxes""" + oriY=0 + visible_row=[] + for row in self.boxes: + current_row=[] + oriX=0 + for win in row: + x=win.getOriX() + y=win.getOriY() + w=win.getOriWidth() + h=win.getOriHeight() + if win.isHidden(): + if len(current_row)>1 and win is row[-1]: + #if the last win is hidden, we expand previous visible one + current_row[-1][2] = current_row[-1][2] + (win.getX() - oriX)+win.getWidth() + else: + echo ("ajout de %s à current row" % (win.__class__.__name__)) + current_row.append([win, h+y-oriY, w+x-oriX, oriY, oriX]) + oriX=oriX+w + + if oriX!=0: + echo ("ligne visible (dernier: %s)" % win.__class__.__name__) + oriY=oriY+h + visible_row.append(current_row) + elif visible_row: + #if all the row is empty, we take the space + for box in visible_row[-1]: + echo ("on augmente %s de %d" % (box[0].__class__.__name__, h)) + box[1]=box[1]+h + oriY=oriY+h #this only happen if it's not the first visible row + else: + echo ("ligne invisible") + + for row in visible_row: + for win in row: + win[0].resize(win[1], win[2], win[3], win[4]) diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/chat.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sortilege/chat.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,154 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +sortilege: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + + +import os.path +import pdb +from logging import debug, info, error +from window import Window +import os +from time import time, localtime, strftime +import curses +import curses.ascii as ascii +from tools.jid import JID +from quick_frontend.quick_chat import QuickChat + + +def C(k): + """return the value of Ctrl+key""" + return ord(ascii.ctrl(k)) + +class Chat(Window, QuickChat): + + def __init__(self, to_id, host): + QuickChat.__init__(self, to_id, host) + self.__parent=host.stdscr + self.to_id=JID(to_id) + self.content=[] + self.__scollIdx=0 + Window.__init__(self, self.__parent, self.__parent.getmaxyx()[0]-2, self.__parent.getmaxyx()[1]-30, 0,30, code=host.code) + + #history + self.historyPrint(50, True) + + self.hide() + + def resize(self, height, width, y, x): + Window.resize(self, height, width, y, x) + self.update() + + def resizeAdapt(self): + """Adapt window size to self.__parent size. + Must be called when self.__parent is resized.""" + self.resize(self.__parent.getmaxyx()[0]-2, self.__parent.getmaxyx()[1]-30, 0,30) + self.update() + + def __getHeader(self, line): + """Return the header of a line (eg: "[12:34] ").""" + header='' + if self.host.chatParams["timestamp"]: + header = header + '[%s] ' % strftime("%H:%M", localtime(float(line[0]))) + if self.host.chatParams['short_nick']: + header = header + ('> ' if line[1]==self.host.whoami.short else '** ') + else: + header = header + '<%s> ' % line[1] + return header + + def update(self): + if self.isHidden(): + echo ("fenetre cachee") + return + Window.update(self) + content=[] #what is really printed + irange=range(len(self.content)) + irange.reverse() #we print the text upward + for idx in irange: + header=self.__getHeader(self.content[idx]) + msg=self.content[idx][2] + part=0 #part of the text + if JID(self.content[idx][1]).short==self.host.whoami.short: + att_header=curses.color_pair(1) + else: + att_header=curses.color_pair(2) + + while (msg): + if part==0: + hd=header + att=att_header + max=self.rWidth-len(header) + else: + hd="" + att=0 + max=self.rWidth + + LF = msg.find('\n') #we look for Line Feed + if LF != -1 and LF < max: + max = LF + next = max + 1 #we skip the LF + else: + next = max + + content.insert(part,[att,hd, msg[:max]]) + msg=msg[next:] #we erase treated part + part=part+1 + + if len(content)>=self.rHeight+self.__scollIdx: + #all the screen is filled, we can continue + break + + if self.__scollIdx>0 and len(content) 0: + self.__scollIdx = self.__scollIdx - 1 + self.update() + + def printMessage(self, jid, msg, timestamp=""): + if timestamp=="": + current_time=time() + timestamp=str(current_time) + if self.last_history and current_time - float(self.last_history) < 5: #FIXME: Q&D fix to avoid double print on new chat window + return + self.content.append([timestamp,jid.short,msg]) + self.update() + + def handleKey(self, k): + if k == C('p'): + self.scrollIdxUp() + elif k == C('n'): + self.scrollIdxDown() + diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/editbox.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sortilege/editbox.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,176 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +sortilege: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +import curses +from curses import ascii +from window import Window + +def C(k): + """return the value of Ctrl+key""" + return ord(ascii.ctrl(k)) + +def A(k): + """return the value of Alt+key""" + return ord(ascii.alt(k)) + +class EditBox(Window): + """This class manage the edition of text""" + + def __init__(self, parent, header, code="utf-8"): + self.__header=header + self.__text = unicode() + self.__curs_pos=0 + self.__buffer=str() + self.__replace_mode=False + self.__parent=parent + self.__code=code + + Window.__init__(self, self.__parent, 1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-1,0, code=code) + self.update() + + def registerEnterCB(self, CB): + self.__enterCB=CB + + def resizeAdapt(self): + """Adapt window size to self.__parent size. + Must be called when self.__parent is resized.""" + self.resize(1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-1,0) + self.update() + + def __getTextToPrint(self): + """return the text printed on the edit line""" + width = self.rWidth - len(self.__header) -1 + if self.__curs_pos0: + self.__curs_pos = self.__curs_pos - 1 + + def __inc_cur(self): + """move cursor on the right""" + if self.__curs_pos=self.rWidth: + pos=self.rWidth-1 + self.move(0, pos) + + def clear_text(self): + """Clear the text of the edit box""" + self.__text="" + self.__curs_pos=0 + + def replace_cur(self): + """must be called earch time the cursor is moved""" + self.move_cur(self.__curs_pos) + self.noutrefresh() + + def activate(self, state=True): + cursor_mode = 1 if state else 0 + curses.curs_set(cursor_mode) + Window.activate(self,state) + + def handleKey(self, k): + if ascii.isgraph(k) or ascii.isblank(k): + pacman = 0 if not self.__replace_mode else 1 + self.__text = self.__text[:self.__curs_pos] + chr(k) + self.__text[self.__curs_pos + pacman:] + self.__curs_pos = self.__curs_pos + 1 + + elif k==ascii.NL: + try: + self.__enterCB(self.__text) + except NameError: + pass # TODO: thrown an error here + self.clear_text() + + elif k==curses.KEY_BACKSPACE: + self.__text = self.__text[:self.__curs_pos-1]+self.__text[self.__curs_pos:] + self.__dec_cur() + + elif k==curses.KEY_DC: + self.__text = self.__text[:self.__curs_pos]+self.__text[self.__curs_pos+1:] + + elif k==curses.KEY_IC: + self.__replace_mode = not self.__replace_mode + + elif k==curses.KEY_LEFT: + self.__dec_cur() + + elif k==curses.KEY_RIGHT: + self.__inc_cur() + + elif k==curses.KEY_HOME or k==C('a'): + self.__curs_pos=0 + + elif k==curses.KEY_END or k==C('e'): + self.__curs_pos=len(self.__text) + + elif k==C('k'): + self.__text = self.__text[:self.__curs_pos] + + elif k==C('w'): + before = self.__text[:self.__curs_pos] + pos = before.rstrip().rfind(" ")+1 + self.__text = before[:pos] + self.__text[self.__curs_pos:] + self.__curs_pos = pos + + elif k>255: + self.__buffer="" + + else: ## FIXME: dangerous code, must be checked ! (specialy buffer overflow) ## + #We now manage unicode + self.__buffer = self.__buffer+chr(k) + decoded=unicode() + if len(self.__buffer)>4: + self.__buffer="" + return + try: + decoded = self.__buffer.decode(self.__code) + except UnicodeDecodeError, e: + if e.reason!="unexpected end of data": + self.__buffer="" + return + if len(self.__buffer)==1: ## FIXME: awful ! only for test ! + self.__buffer="" + return + self.__text = self.__text + decoded + self.__curs_pos = self.__curs_pos + 1 + self.__buffer="" + + self.update() + diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/sortilege.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sortilege/sortilege.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,379 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +sortilege: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +import curses +import pdb +from window import Window +from editbox import EditBox +from statusbar import StatusBar +from chat import Chat +from tools.jid import JID +import logging +from logging import debug, info, error +import locale +import sys, os +import gobject +import time +from curses import ascii +import locale +from signal import signal, SIGWINCH +import fcntl +import struct +import termios +from boxsizer import BoxSizer +from quick_frontend.quick_chat_list import QuickChatList +from quick_frontend.quick_contact_list import QuickContactList +from quick_frontend.quick_app import QuickApp + +### logging configuration FIXME: put this elsewhere ### +logging.basicConfig(level=logging.CRITICAL, #TODO: configure it top put messages in a log file + format='%(message)s') +### + +const_APP_NAME = "Sortilège" +const_CONTACT_WIDTH = 30 + +def ttysize(): + """This function return term size. + Comes from Donn Cave from python list mailing list""" + buf = 'abcdefgh' + buf = fcntl.ioctl(0, termios.TIOCGWINSZ, buf) + row, col, rpx, cpx = struct.unpack('hhhh', buf) + return row, col + +def C(k): + """return the value of Ctrl+key""" + return ord(ascii.ctrl(k)) + +class ChatList(QuickChatList): + """This class manage the list of chat windows""" + + def __init__(self, host): + QuickChatList.__init__(self, host) + self.sizer=host.sizer + + def createChat(self, name): + chat = Chat(name, self.host) + self.sizer.appendColum(0,chat) + self.sizer.update() + return chat + + +class ContactList(Window, QuickContactList): + + def __init__(self): + QuickContactList.__init__(self) + self.__index=0 #indicate which contact is selected (ie: where we are) + Window.__init__(self, stdscr, stdscr.getmaxyx()[0]-2,const_CONTACT_WIDTH,0,0, True, "Contact List", code=code) + + def resize(self, height, width, y, x): + Window.resize(self, height, width, y, x) + self.update() + + def resizeAdapt(self): + """Adapt window size to stdscr size. + Must be called when stdscr is resized.""" + self.resize(stdscr.getmaxyx()[0]-2,const_CONTACT_WIDTH,0,0) + self.update() + + def registerEnterCB(self, CB): + self.__enterCB=CB + + def replace(self, jid, name="", show="", status="", group=""): + """add a contact to the list""" + self.jid_ids[jid] = name or jid + self.update() + + def indexUp(self): + """increment select contact index""" + if self.__index < len(self.jid_ids)-1: #we dont want to select a missing contact + self.__index = self.__index + 1 + self.update() + + def indexDown(self): + """decrement select contact index""" + if self.__index > 0: + self.__index = self.__index - 1 + self.update() + + def remove(self, jid): + """remove a contact from the list""" + del self.jid_ids[jid] + if self.__index >= len(self.jid_ids) and self.__index > 0: #if select index is out of border, we put it on the last contact + self.__index = len(self.jid_ids)-1 + self.update() + + def update(self): + """redraw all the window""" + if self.isHidden(): + return + Window.update(self) + viewList=[] + for jid in self.jid_ids: + viewList.append(self.jid_ids[jid]) + viewList.sort() + begin=0 if self.__index ", self.code) + self.editBar.activate(False) + self.statusBar = StatusBar(stdscr, self.code) + self.statusBar.hide(True) + self.addWin(self.contactList) + self.addWin(self.editBar) + self.addWin(self.statusBar) + self.sizer=BoxSizer(stdscr) + self.sizer.appendRow(self.contactList) + self.sizer.appendRow(self.statusBar) + self.sizer.appendRow(self.editBar) + self.currentChat=None + + self.contactList.registerEnterCB(self.onContactChoosed) + self.editBar.registerEnterCB(self.onTextEntered) + + self.chat_wins=ChatList(self) + + QuickApp.__init__(self) #XXX: yes it's an unusual place for the constructor of a parent class, but the init order is important + + signal (SIGWINCH, self.onResize) #we manage SIGWINCH ourselves, because the loop is not called otherwise + + #last but not least, we adapt windows' sizes + self.sizer.update() + self.editBar.replace_cur() + curses.doupdate() + + self.loop.run() + + def addWin(self, win): + self.listWins.append(win) + + def color(self, activate=True): + if activate: + debug ("Activation des couleurs") + curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) + curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) + else: + debug ("Desactivation des couleurs") + curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK) + curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) + + + def showChat(self, chat): + debug ("show chat") + if self.currentChat: + debug ("hide de %s", self.currentChat) + self.chat_wins[self.currentChat].hide() + self.currentChat=chat + debug ("show de %s", self.currentChat) + self.chat_wins[self.currentChat].show() + self.chat_wins[self.currentChat].update() + + + ### EVENTS ### + + def onContactChoosed(self, jid_txt): + """Called when a contact is selected in contact list.""" + jid=JID(jid_txt) + debug ("contact choose: %s", jid) + self.showChat(jid.short) + self.statusBar.remove_item(jid.short) + if len(self.statusBar)==0: + self.statusBar.hide() + self.sizer.update() + + + def onTextEntered(self, text): + jid=JID(self.whoami) + self.bridge.sendMessage(self.currentChat, text) + + def showDialog(self, message, title, type="info"): + if type==question: + raise NotImplementedError + pass + + + def presenceUpdate(self, jabber_id, type, show, status, priority): + QuickApp.presenceUpdate(self, jabber_id, type, show, status, priority) + self.editBar.replace_cur() + curses.doupdate() + + def newMessage(self, from_jid, msg, type, to_jid): + QuickApp.newMessage(self, from_jid, msg, type, to_jid) + sender=JID(from_jid) + addr=JID(to_jid) + win = addr if sender.short == self.whoami.short else sender #FIXME: duplicate code with QuickApp + if (self.currentChat==None): + self.currentChat=win.short + self.showChat(win.short) + + # we show the window in the status bar + if not self.currentChat == win.short: + self.statusBar.add_item(win.short) + self.statusBar.show() + self.sizer.update() + self.statusBar.update() + + self.editBar.replace_cur() + curses.doupdate() + + def onResize(self, sig, stack): + """Called on SIGWINCH. + resize the screen and launch the loop""" + height, width = ttysize() + curses.resizeterm(height, width) + gobject.idle_add(self.callOnceLoop) + + def callOnceLoop(self): + """Call the loop and return false (for not being called again by gobject mainloop). + Usefull for calling loop when there is no input in stdin""" + self.loopCB() + return False + + def __key_handling(self, k): + """Handle key and transmit to active window.""" + + ### General keys, handled _everytime_ ### + if k == C('x'): + if os.getenv('TERM')=='screen': + os.system('screen -X remove') + else: + self.loop.quit() + + ## windows navigation + elif k == C('l') and not self.contactList.isHidden(): + """We go to the contact list""" + self.contactList.activate(not self.contactList.isActive()) + if self.currentChat: + self.editBar.activate(not self.contactList.isActive()) + + elif k == curses.KEY_F2: + self.contactList.hide(not self.contactList.isHidden()) + if self.contactList.isHidden(): + self.contactList.activate(False) #TODO: auto deactivation when hiding ? + if self.currentChat: + self.editBar.activate(True) + self.sizer.update() + + ## Chat Params ## + elif k == C('c'): + self.chatParams["color"] = not self.chatParams["color"] + self.color(self.chatParams["color"]) + elif k == C('t'): + self.chatParams["timestamp"] = not self.chatParams["timestamp"] + self.chat_wins[self.currentChat].update() + elif k == C('s'): + self.chatParams["short_nick"] = not self.chatParams["short_nick"] + self.chat_wins[self.currentChat].update() + + ## misc ## + elif k == curses.KEY_RESIZE: + stdscr.erase() + height, width = stdscr.getmaxyx() + if height<5 and width<35: + stdscr.addstr("Pleeeeasse, I can't even breathe !") + else: + for win in self.listWins: + win.resizeAdapt() + for win in self.chat_wins.keys(): + self.chat_wins[win].resizeAdapt() + self.sizer.update() # FIXME: everything need to be managed by the sizer + + ## we now throw the key to win handlers ## + else: + for win in self.listWins: + if win.isActive(): + win.handleKey(k) + if self.currentChat: + self.chat_wins[self.currentChat].handleKey(k) + + def loopCB(self, source="", cb_condition=""): + """This callback is called by the main loop""" + #pressed = self.contactList.window.getch() + pressed = stdscr.getch() + if pressed != curses.ERR: + self.__key_handling(pressed) + self.editBar.replace_cur() + curses.doupdate() + + + return True + + +sat = SortilegeApp() +sat.start() diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/statusbar.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sortilege/statusbar.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,77 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +sortilege: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +import curses +from window import Window +import os + +def echo(message): + return + os.system('echo "'+str(message)+'" >> /tmp/toto') + +class StatusBar(Window): + """This class manage the edition of text""" + + def __init__(self, parent, code="utf-8"): + self.__parent=parent + self.__code=code + self.__items=set() + + Window.__init__(self, self.__parent, 1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-2,0, code=code) + + def __len__(self): + return len(self.__items) + + def resizeAdapt(self): + """Adapt window size to self.__parent size. + Must be called when self.__parent is resized.""" + self.resize(1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-2,0) + self.update() + + def update(self): + if self.isHidden(): + echo ("status bar hidden") + return + echo ("update status bar") + Window.update(self) + x=0 + for item in self.__items: + pitem="[%s] " % item + self.addYXStr(0, x, pitem, curses.A_REVERSE) + x = x + len(pitem) + if x>=self.rWidth: + break + self.addYXStr(0, x, (self.rWidth-x)*" ", curses.A_REVERSE) + self.noutrefresh() + + def clear_text(self): + """Clear the text of the edit box""" + del(self.__items[:]) + + def add_item(self, item): + self.__items.add(item) + self.update() + + def remove_item(self, item): + if item in self.__items: + self.__items.remove(item) + self.update() diff -r 000000000000 -r c4bc297b82f0 frontends/sortilege/window.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/sortilege/window.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,164 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +sortilege: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +import curses +import os +import pdb + + +def echo(message): + return + os.system('echo "'+str(message)+'" >> /tmp/toto') + +class Window(): + def __init__(self, parent, height, width, y, x, border=False, title="", code="utf-8"): + self.__border=border + self.__title=title + self.__active=False + self.__parent=parent + self.__code=code + self.__hide=False + + self.resize(height, width, y, x) + self.oriCoords=self.__coords #FIXME: tres moche, a faire en mieux + + def hide(self, hide=True): + self.__hide=hide + + def show(self): + self.__hide=False + + def isHidden(self): + return self.__hide + + def getY(self): + return self.__coords[2] + + def getX(self): + return self.__coords[3] + + def getHeight(self): + return self.__coords[0] + + def getWidth(self): + return self.__coords[1] + + + #FIXME: tres moche, a faire en plus joli + def getOriY(self): + return self.oriCoords[2] + + def getOriX(self): + return self.oriCoords[3] + + def getOriHeight(self): + return self.oriCoords[0] + + def getOriWidth(self): + return self.oriCoords[1] + + def defInsideCoord(self): + """define the inside coordinates (win coordinates minus decorations)""" + height,width,y,x=self.__coords + self.oriX = x if not self.__border else x+1 + self.oriY = y if not self.__border else y+1 + self.endX = x+width if not self.__border else x+width-2 + self.endY = y+height if not self.__border else y+height-2 + self.rWidth = width if not self.__border else width-2 + self.rHeight = height if not self.__border else height-2 + + def resize(self, height, width, y, x): + self.__coords=[height, width, y, x] + + # we check that coordinates are under limits + self.__coordAdjust(self.__coords) + height,width,y,x=self.__coords + + echo ("newwin %d %d %d %d" % (height, width, y, x)) + self.window = self.__parent.subwin(height, width, y, x) + self.defInsideCoord() + + def __coordAdjust(self, coords): + """Check that coordinates are under limits, adjust them else otherwise""" + height,width,y,x=coords + parentY, parentX = self.__parent.getbegyx() + parentHeight, parentWidth = self.__parent.getmaxyx() + + if y < parentY: + y = parentY + if x < parentX: + x = parentX + if height > parentHeight - y: + height = parentHeight - y + if width > parentWidth - x: + width = parentWidth - x + coords[0], coords[1], coords[2], coords[3] = [height, width, y, x] + + + def activate(self,state=True): + """Declare this window as current active one""" + self.__active=state + self.update() + + def isActive(self): + return self.__active + + def addYXStr(self, y, x, text, attr = 0, limit=0): + if self.__border: + x=x+1 + y=y+1 + n = self.rWidth-x if not limit else limit + encoded = text.encode(self.__code) + adjust = len(encoded) - len(text) # hack because addnstr doesn't manage unicode + try: + self.window.addnstr(y, x, encoded, n + adjust, attr) + except: + #We have to catch error to write on last line last col FIXME: is there a better way ? + pass + + def move(self, y, x): + self.window.move(y,x) + + def noutrefresh(self): + self.window.noutrefresh() + + def update(self): + """redraw all the window""" + if self.__hide: + return + self.clear() + + def border(self): + """redraw the border and title""" + y,x = self.window.getbegyx() + width = self.window.getmaxyx()[1] + if self.__border: + self.window.border() + if self.__title: + if len(self.__title)>width: + self.__title="" + else: + self.window.addstr(y,x+(width-len(self.__title))/2, self.__title) + + def clear(self): + self.window.clear() + self.border() diff -r 000000000000 -r c4bc297b82f0 frontends/wix/__init__.py diff -r 000000000000 -r c4bc297b82f0 frontends/wix/chat.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/wix/chat.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,118 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +wix: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + + +import wx +import os.path +import pdb +from logging import debug, info, error +from tools.jid import JID +from quick_frontend.quick_chat import QuickChat + + +idSEND = 1 + +class Chat(wx.Frame, QuickChat): + """The chat Window for one to one conversations""" + + def __init__(self, to_jid, host): + wx.Frame.__init__(self, None, title=to_jid, pos=(0,0), size=(400,200)) + QuickChat.__init__(self, to_jid, host) + + self.chatWindow = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE | wx.TE_RICH | wx.TE_READONLY) + self.textBox = wx.TextCtrl(self, -1, style = wx.TE_PROCESS_ENTER) + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.sizer.Add(self.chatWindow, 1, flag=wx.EXPAND) + self.sizer.Add(self.textBox, flag=wx.EXPAND) + self.SetSizer(self.sizer) + self.SetAutoLayout(True) + self.createMenus() + + #events + self.Bind(wx.EVT_CLOSE, self.onClose, self) + self.Bind(wx.EVT_TEXT_ENTER, self.onEnterPressed, self.textBox) + + #fonts + self.font={} + self.font["points"] = self.chatWindow.GetFont().GetPointSize() + self.font["family"] = self.chatWindow.GetFont().GetFamily() + + self.historyPrint() + + #misc + self.textBox.SetFocus() + self.Hide() #We hide because of the show toggle + + def createMenus(self): + info("Creating menus") + actionMenu = wx.Menu() + actionMenu.Append(idSEND, "&SendFile CTRL-s"," Send a file to contact") + menuBar = wx.MenuBar() + menuBar.Append(actionMenu,"&Action") + self.SetMenuBar(menuBar) + + #events + wx.EVT_MENU(self, idSEND, self.onSendFile) + + def __del__(self): + debug ("Chat window destructor") + wx.Frame.__del__(self) + + def onClose(self, event): + """Close event: we only hide the frame.""" + event.Veto() + self.Show() ## this is a workaround to a wxpython bug: + ## with Raise on hidden frame, Hide doesn't work anymore + ## TODO: check this and repport bug to wxpython devs + self.Hide() + + def onEnterPressed(self, event): + """Behaviour when enter pressed in send line.""" + self.host.bridge.sendMessage(self.to_jid, event.GetString()) + self.textBox.Clear() + + + + def printMessage(self, from_jid, msg, timestamp=""): #FIXME: factorize with printDistantMessage + """Print the message with differents colors depending on where it comes from.""" + jid=JID(from_jid) + mymess = (jid.short == self.host.whoami.short) #mymess = True if message comes from local user + _font = wx.Font(self.font["points"], self.font["family"], wx.NORMAL, wx.BOLD) + self.chatWindow.SetDefaultStyle(wx.TextAttr( "BLACK" if mymess else "BLUE", font=_font)) + self.chatWindow.AppendText("[%s] " % jid) + _font = wx.Font(self.font["points"], self.font["family"], wx.ITALIC if mymess else wx.NORMAL, wx.NORMAL) + self.chatWindow.SetDefaultStyle(wx.TextAttr("BLACK", font=_font)) + self.chatWindow.AppendText("%s\n" % msg) + if not mymess: + self.Raise() #FIXME: too intrusive + + ### events ### + + def onSendFile(self, e): + debug("Send File") + filename = wx.FileSelector("Choose a file to send", flags = wx.FD_FILE_MUST_EXIST) + if filename: + debug("filename: %s",filename) + full_jid = self.host.CM.get_full(self.to_jid) + id = self.host.bridge.sendFile(full_jid, filename) + self.host.waitProgress(id, "File Transfer", "Copying %s" % os.path.basename(filename)) + diff -r 000000000000 -r c4bc297b82f0 frontends/wix/main_window.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/wix/main_window.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,377 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +wix: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +import wx +from chat import Chat +from param import Param +import gobject +import os.path +import pdb +from tools.jid import JID +from logging import debug, info, error +from quick_frontend.quick_chat_list import QuickChatList +from quick_frontend.quick_contact_list import QuickContactList +from quick_frontend.quick_app import QuickApp + + +msgOFFLINE = "offline" +msgONLINE = "online" +idCONNECT = 1 +idEXIT = 2 +idPARAM = 3 +idADD_CONTACT = 4 +idREMOVE_CONTACT = 5 +const_DEFAULT_GROUP = "Unclassed" +const_STATUS = {"Online":"", + "Want to discuss":"chat", + "AFK":"away", + "Do Not Disturb":"dnd", + "Away":"xa"} + +class ChatList(QuickChatList): + """This class manage the list of chat windows""" + + def __init__(self, host): + QuickChatList.__init__(self, host) + + def createChat(self, name): + return Chat(name, self.host) + + + +class ContactList(wx.TreeCtrl, QuickContactList): + """Customized control to manage contacts.""" + + def __init__(self, parent): + wx.TreeCtrl.__init__(self, parent, style = wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS) + QuickContactList.__init__(self) + self.jid_ids={} + self.groups={} + self.root=self.AddRoot("") + self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.onActivated, self) + + #icons + isz = (16,16) + il = wx.ImageList(isz[0], isz[1]) + self.icon_online = il.Add(wx.ArtProvider_GetBitmap(wx.ART_TICK_MARK, wx.ART_OTHER, isz)) + self.icon_unavailable = il.Add(wx.ArtProvider_GetBitmap(wx.ART_CROSS_MARK, wx.ART_OTHER, isz)) + self.AssignImageList(il) + + self.__addNode(const_DEFAULT_GROUP) + + def __addNode(self, label): + """Add an item container""" + ret=self.AppendItem(self.root, label) + self.SetPyData(ret, "[node]") + self.SetItemBold(ret) + self.groups[label]=ret + + def replace(self, jid, name="", show="", status="", group=""): + debug("status = %s show = %s",status, show) + if not self.jid_ids.has_key(jid): + self.add(jid, name, show, status, group) + else: + debug ("updating %s",jid) + self.__presentItem(jid, name, show, status, group) + + def __presentItem(self, jid, name, show, status, group): + """Make a nice presentation of the contact in the list.""" + id=self.jid_ids[jid] + label= "%s [%s] \n %s" % ((name or jid), (show or "online"), status) + self.SetItemText(id, label) + + # icon + if not show or show=="chat": + self.SetItemImage(id, self.icon_online) + else: + self.SetItemImage(id, self.icon_unavailable) + + #colour + if not show: + self.SetItemTextColour(id, wx.BLACK) + elif show=="chat": + self.SetItemTextColour(id, wx.GREEN) + elif show=="away": + self.SetItemTextColour(id, wx.BLUE) + else: + self.SetItemTextColour(id, wx.RED) + + def add(self, jid, name="", show="", status="", group=""): + """add a contact to the list""" + debug ("adding %s",jid) + dest_group=group or const_DEFAULT_GROUP + if not self.groups.has_key(dest_group): + self.__addNode(dest_group) + self.jid_ids[jid]=self.AppendItem(self.groups[dest_group], "") + self.__presentItem(jid, name, show, status, group) + self.SetPyData(self.jid_ids[jid], "[contact]"+jid) + self.EnsureVisible(self.jid_ids[jid]) + self.Refresh() #FIXME: Best way ? + + def remove(self, jid): + """remove a contact from the list""" + debug ("removing %s",jid) + self.Delete(self.jid_ids[jid]) + del self.jid_ids[jid] + self.Refresh() #FIXME: Best way ? + + def onActivated(self, event): + """Called when a contact is clicked or activated with keyboard.""" + if self.GetPyData(event.GetItem()).startswith("[contact]"): + self.onActivatedCB(self.GetPyData(event.GetItem())[9:]) + else: + event.Skip() + + def getSelection(self): + """Return the selected contact, or an empty string if there is not""" + data = self.GetPyData(self.GetSelection()) + if not data or not data.startswith("[contact]"): + return "" + return JID(data[9:]) + + def registerActivatedCB(self, cb): + """Register a callback with manage contact activation.""" + self.onActivatedCB=cb + +class MainWindow(wx.Frame, QuickApp): + """main app window""" + + def __init__(self): + wx.Frame.__init__(self,None, title="SAT Wix", size=(400,200)) + + + #Frame elements + self.contactList = ContactList(self) + self.contactList.registerActivatedCB(self.onContactActivated) + self.chat_wins=ChatList(self) + self.CreateStatusBar() + self.SetStatusText(msgOFFLINE) + self.createMenus() + + #ToolBar + self.tools=self.CreateToolBar() + self.statusBox = wx.ComboBox(self.tools, -1, "Online", choices=const_STATUS.keys(), + style=wx.CB_DROPDOWN | wx.CB_READONLY) + self.tools.AddControl(self.statusBox) + self.tools.AddSeparator() + self.statusTxt=wx.TextCtrl(self.tools, -1, style = wx.TE_PROCESS_ENTER) + self.tools.AddControl(self.statusTxt) + self.Bind(wx.EVT_COMBOBOX, self.onStatusChange, self.statusBox) + self.Bind(wx.EVT_TEXT_ENTER, self.onStatusChange, self.statusTxt) + self.tools.Disable() + + #events + self.Bind(wx.EVT_CLOSE, self.onClose, self) + + QuickApp.__init__(self) + + self.Show() + + def createMenus(self): + info("Creating menus") + connectMenu = wx.Menu() + connectMenu.Append(idCONNECT, "&Connect CTRL-c"," Connect to the server") + connectMenu.Append(idPARAM,"&Parameters"," Configure the program") + connectMenu.AppendSeparator() + connectMenu.Append(idEXIT,"E&xit"," Terminate the program") + contactMenu = wx.Menu() + contactMenu.Append(idADD_CONTACT, "&Add contact"," Add a contact to your list") + contactMenu.Append(idREMOVE_CONTACT, "&Remove contact"," Remove the selected contact from your list") + menuBar = wx.MenuBar() + menuBar.Append(connectMenu,"&General") + menuBar.Append(contactMenu,"&Contacts") + self.SetMenuBar(menuBar) + + #events + wx.EVT_MENU(self, idCONNECT, self.onConnectRequest) + wx.EVT_MENU(self, idPARAM, self.onParam) + wx.EVT_MENU(self, idEXIT, self.onExit) + wx.EVT_MENU(self, idADD_CONTACT, self.onAddContact) + wx.EVT_MENU(self, idREMOVE_CONTACT, self.onRemoveContact) + + + def newMessage(self, from_jid, msg, type, to_jid): + QuickApp.newMessage(self, from_jid, msg, type, to_jid) + + def showAlert(self, message): + # TODO: place this in a separate class + popup=wx.PopupWindow(self) + ### following code come from wxpython demo + popup.SetBackgroundColour("CADET BLUE") + st = wx.StaticText(popup, -1, message, pos=(10,10)) + sz = st.GetBestSize() + popup.SetSize( (sz.width+20, sz.height+20) ) + x=(wx.DisplaySize()[0]-popup.GetSize()[0])/2 + popup.SetPosition((x,0)) + popup.Show() + wx.CallLater(5000,popup.Destroy) + + def showDialog(self, message, title="", type="info"): + if type == 'info': + flags = wx.OK | wx.ICON_INFORMATION + elif type == 'error': + flags = wx.OK | wx.ICON_ERROR + elif type == 'question': + flags = wx.OK | wx.ICON_QUESTION + else: + flags = wx.OK | wx.ICON_INFORMATION + dlg = wx.MessageDialog(self, message, title, flags) + answer = dlg.ShowModal() + dlg.Destroy() + return True if (answer == wx.ID_YES or answer == wx.ID_OK) else False + + def setStatusOnline(self, online=True): + """enable/disable controls, must be called when local user online status change""" + if online: + self.SetStatusText(msgONLINE) + self.tools.Enable() + else: + self.SetStatusText(msgOFFLINE) + self.tools.Disable() + return + + + def presenceUpdate(self, jabber_id, type, show, status, priority): + QuickApp.presenceUpdate(self, jabber_id, type, show, status, priority) + + def askConfirmation(self, type, id, data): + #TODO: refactor this in QuickApp + debug ("Confirmation asked") + answer_data={} + if type == "FILE_TRANSFERT": + debug ("File transfert confirmation asked") + dlg = wx.MessageDialog(self, "The contact %s wants to send you the file %s\nDo you accept ?" % (data["from"], data["filename"]), + 'File Request', + wx.YES_NO | wx.ICON_QUESTION + ) + answer=dlg.ShowModal() + if answer==wx.ID_YES: + filename = wx.FileSelector("Where do you want to save the file ?", flags = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) + if filename: + answer_data["dest_path"] = filename + self.bridge.confirmationAnswer(id, True, answer_data) + self.waitProgress(id, "File Transfer", "Copying %s" % os.path.basename(filename)) + else: + answer = wx.ID_NO + if answer==wx.ID_NO: + self.bridge.confirmationAnswer(id, False, answer_data) + + dlg.Destroy() + + + + + def progressCB(self, id, title, message): + data = self.bridge.getProgress(id) + if data: + if not data['position']: + data['position'] = '0' + if not self.pbar: + #first answer, we must construct the bar + self.pbar = wx.ProgressDialog(title, message, int(data['size']), None, + wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME) + self.pbar.finish_value = int(data['size']) + + self.pbar.Update(int(data['position'])) + elif self.pbar: + self.pbar.Update(self.pbar.finish_value) + return + + wx.CallLater(10, self.progressCB, id, title, message) + + def waitProgress (self, id, title, message): + self.pbar = None + wx.CallLater(10, self.progressCB, id, title, message) + + + + ### events ### + + def onContactActivated(self, jid): + debug ("onContactActivated: %s", jid) + if self.chat_wins[jid].IsShown(): + self.chat_wins[jid].Hide() + else: + self.chat_wins[jid].Show() + + def onConnectRequest(self, e): + self.bridge.connect() + + def __updateStatus(self): + show = const_STATUS[self.statusBox.GetValue()] + status = self.statusTxt.GetValue() + self.bridge.setPresence(show=show, status=status) + + def onStatusChange(self, e): + debug("Status change request") + self.__updateStatus() + + def onParam(self, e): + debug("Param request") + param=Param(self.bridge.setParam, self.bridge.getParam, self.bridge.getParams, self.bridge.getParamsCategories) + + def onExit(self, e): + self.Close() + + def onAddContact(self, e): + debug("Add contact request") + dlg = wx.TextEntryDialog( + self, 'Please enter new contact JID', + 'Adding a contact', 'name@server.ext') + + if dlg.ShowModal() == wx.ID_OK: + jid=JID(dlg.GetValue()) + if jid.is_valid(): + self.bridge.addContact(jid.short) + else: + error ("'%s' is an invalid JID !", jid) + #TODO: notice the user + + dlg.Destroy() + + def onRemoveContact(self, e): + debug("Remove contact request") + target = self.contactList.getSelection() + if not target: + dlg = wx.MessageDialog(self, "You haven't selected any contact !", + 'Error', + wx.OK | wx.ICON_ERROR + ) + dlg.ShowModal() + dlg.Destroy() + return + + dlg = wx.MessageDialog(self, "Are you sure you want to delete %s from your roster list ?" % target.short, + 'Contact suppression', + wx.YES_NO | wx.ICON_QUESTION + ) + + if dlg.ShowModal() == wx.ID_YES: + info("Unsubsribing %s presence", target.short) + self.bridge.delContact(target.short) + + dlg.Destroy() + + def onClose(self, e): + info("Exiting...") + e.Skip() + diff -r 000000000000 -r c4bc297b82f0 frontends/wix/param.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/wix/param.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,95 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +wix: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + + +import wx +import pdb +from logging import debug, info, error + + +class Param(wx.Frame): + def __init__(self, setParam, getParam, getParams, getParamsCategories, title="Configuration"): + super(Param, self).__init__(None, title=title) + + self.setParam=setParam + self.getParam=getParam + self.getParams=getParams + self.getParamsCategories=getParamsCategories + + self.modified={} # dict of modified data (i.e. what we have to save) + + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.notebook=wx.Notebook(self, -1, style=wx.NB_LEFT) + self.sizer.Add(self.notebook, 1, flag=wx.EXPAND) + self.SetSizer(self.sizer) + self.SetAutoLayout(True) + + #events + self.Bind(wx.EVT_CLOSE, self.onClose, self) + + self.MakeModal() + + for category in self.getParamsCategories(): + self.addCategory(category) + + self.Show() + + def addCategory(self, category): + panel=wx.Panel(self.notebook) + panel.sizer = wx.BoxSizer(wx.VERTICAL) + + for param in self.getParams(category): + sizer = wx.BoxSizer(wx.HORIZONTAL) + label=wx.StaticText(panel, -1, param[0]+" ") + if param[2]=="string": + ctrl = wx.TextCtrl(panel, -1, param[1]) + elif param[2]=="password": + ctrl = wx.TextCtrl(panel, -1, param[1], style=wx.TE_PASSWORD) + else: + error("FIXME FIXME FIXME") #FIXME ! + raise NotImplementedError + ctrl.param_id=(param[0], category) + sizer.Add(label) + sizer.Add(ctrl, 1, flag=wx.EXPAND) + panel.sizer.Add(sizer, flag=wx.EXPAND) + + panel.Bind(wx.EVT_TEXT, self.onTextChanged, ctrl) + panel.SetSizer(panel.sizer) + panel.SetAutoLayout(True) + self.notebook.AddPage(panel, category) + + def onTextChanged(self, event): + """Called when a paramated is modified""" + self.modified[event.GetEventObject().param_id]=event.GetString() + event.Skip() + + + def onClose(self, event): + """Close event: we have to save the params.""" + debug("close") + #now we save the modifier params + for param in self.modified: + self.setParam(param[0], self.modified[param], param[1]) + + self.MakeModal(False) + event.Skip() + diff -r 000000000000 -r c4bc297b82f0 frontends/wix/wix.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/frontends/wix/wix.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,48 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +wix: a SAT frontend +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +import wx +from sat_bridge_frontend.DBus import DBusBridgeFrontend +import pdb +import logging +from logging import debug, info, error +from main_window import MainWindow + +### logging configuration FIXME: put this elsewhere ### +logging.basicConfig(level=logging.DEBUG, + format='%(message)s') +### + + +class SATApp(wx.App): + def __init__(self, redirect=False, filename=None, useBestVisual=False, clearSigInt=True): + super(SATApp,self).__init__(redirect, filename, useBestVisual, clearSigInt) + + def OnInit(self): + self.main = MainWindow() + self.main.Show(True) + self.SetTopWindow(self.main) + return True + + +sat = SATApp() +sat.MainLoop() diff -r 000000000000 -r c4bc297b82f0 plugins/__init__.py diff -r 000000000000 -r c4bc297b82f0 plugins/plugin_xep_0065.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plugins/plugin_xep_0065.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,493 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- +""" +SAT plugin for managing xep-0065 + +Copyright (C) +2002-2004 Dave Smith (dizzyd@jabber.org) +2007-2008 Fabio Forno (xmpp:ff@jabber.bluendo.com) +2009 Jérôme Poisson (goffi@goffi.org) + +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 . + +-- + +This program is based on proxy65 (http://code.google.com/p/proxy65), +originaly written by David Smith and modified by Fabio Forno. +It is sublicensed under GPL v3 (or any later version) as allowed by the original +license. + +-- + +Here is a copy of the original license: + +Copyright (C) +2002-2004 Dave Smith (dizzyd@jabber.org) +2007-2008 Fabio Forno (xmpp:ff@jabber.bluendo.com) + +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. +""" + +from logging import debug, info, error +from twisted.internet import protocol, reactor +from twisted.protocols.basic import FileSender +from twisted.words.xish import domish +import struct +from binascii import hexlify +import hashlib, pdb + + +PLUGIN_INFO = { +"name": "XEP 0065 Plugin", +"import_name": "XEP_0065", +"type": "XEP", +"main": "XEP_0065", +"description": """Implementation of SI File Transfert""" +} + +STATE_INITIAL = 0 +STATE_AUTH = 1 +STATE_REQUEST = 2 +STATE_READY = 3 +STATE_AUTH_USERPASS = 4 +STATE_TARGET_INITIAL = 5 +STATE_TARGET_AUTH = 6 +STATE_TARGET_REQUEST = 7 +STATE_TARGET_READY = 8 +STATE_LAST = 9 + +STATE_CONNECT_PENDING = STATE_LAST + 1 + +SOCKS5_VER = 0x05 + +ADDR_IPV4 = 0x01 +ADDR_DOMAINNAME = 0x03 +ADDR_IPV6 = 0x04 + +CMD_CONNECT = 0x01 +CMD_BIND = 0x02 +CMD_UDPASSOC = 0x03 + +AUTHMECH_ANON = 0x00 +AUTHMECH_USERPASS = 0x02 +AUTHMECH_INVALID = 0xFF + +REPLY_SUCCESS = 0x00 +REPLY_GENERAL_FAILUR = 0x01 +REPLY_CONN_NOT_ALLOWED = 0x02 +REPLY_NETWORK_UNREACHABLE = 0x03 +REPLY_HOST_UNREACHABLE = 0x04 +REPLY_CONN_REFUSED = 0x05 +REPLY_TTL_EXPIRED = 0x06 +REPLY_CMD_NOT_SUPPORTED = 0x07 +REPLY_ADDR_NOT_SUPPORTED = 0x08 + + + + + +class SOCKSv5(protocol.Protocol, FileSender): + def __init__(self): + debug("Protocol init") + self.state = STATE_INITIAL + self.buf = "" + self.supportedAuthMechs = [ AUTHMECH_ANON ] + self.supportedAddrs = [ ADDR_DOMAINNAME ] + self.enabledCommands = [ CMD_CONNECT ] + self.peersock = None + self.addressType = 0 + self.requestType = 0 + self.activeConns = {} + self.pendingConns = {} + self.transfered = 0 #nb of bytes already copied + + def _startNegotiation(self): + debug("_startNegotiation") + self.state = STATE_TARGET_AUTH + self.transport.write(struct.pack('!3B', SOCKS5_VER, 1, AUTHMECH_ANON)) + + def _parseNegotiation(self): + debug("_parseNegotiation") + try: + # Parse out data + ver, nmethod = struct.unpack('!BB', self.buf[:2]) + methods = struct.unpack('%dB' % nmethod, self.buf[2:nmethod+2]) + + # Ensure version is correct + if ver != 5: + self.transport.write(struct.pack('!BB', SOCKS5_VER, AUTHMECH_INVALID)) + self.transport.loseConnection() + return + + # Trim off front of the buffer + self.buf = self.buf[nmethod+2:] + + # Check for supported auth mechs + for m in self.supportedAuthMechs: + if m in methods: + # Update internal state, according to selected method + if m == AUTHMECH_ANON: + self.state = STATE_REQUEST + elif m == AUTHMECH_USERPASS: + self.state = STATE_AUTH_USERPASS + # Complete negotiation w/ this method + self.transport.write(struct.pack('!BB', SOCKS5_VER, m)) + return + + # No supported mechs found, notify client and close the connection + self.transport.write(struct.pack('!BB', SOCKS5_VER, AUTHMECH_INVALID)) + self.transport.loseConnection() + except struct.error: + pass + + def _parseUserPass(self): + debug("_parseUserPass") + try: + # Parse out data + ver, ulen = struct.unpack('BB', self.buf[:2]) + uname, = struct.unpack('%ds' % ulen, self.buf[2:ulen + 2]) + plen, = struct.unpack('B', self.buf[ulen + 2]) + password, = struct.unpack('%ds' % plen, self.buf[ulen + 3:ulen + 3 + plen]) + # Trim off fron of the buffer + self.buf = self.buf[3 + ulen + plen:] + # Fire event to authenticate user + if self.authenticateUserPass(uname, password): + # Signal success + self.state = STATE_REQUEST + self.transport.write(struct.pack('!BB', SOCKS5_VER, 0x00)) + else: + # Signal failure + self.transport.write(struct.pack('!BB', SOCKS5_VER, 0x01)) + self.transport.loseConnection() + except struct.error: + pass + + def sendErrorReply(self, errorcode): + debug("sendErrorReply") + # Any other address types are not supported + result = struct.pack('!BBBBIH', SOCKS5_VER, errorcode, 0, 1, 0, 0) + self.transport.write(result) + self.transport.loseConnection() + + def addConnection(self, address, connection): + info("Adding connection: %s, %s", address, connection) + olist = self.pendingConns.get(address, []) + if len(olist) <= 1: + olist.append(connection) + self.pendingConns[address] = olist + return True + else: + return False + + def removePendingConnection(self, address, connection): + olist = self.pendingConns[address] + if len(olist) == 1: + del self.pendingConns[address] + else: + olist.remove(connection) + self.pendingConns[address] = olist + + def removeActiveConnection(self, address): + del self.activeConns[address] + + def _parseRequest(self): + debug("_parseRequest") + try: + # Parse out data and trim buffer accordingly + ver, cmd, rsvd, self.addressType = struct.unpack('!BBBB', self.buf[:4]) + + # Ensure we actually support the requested address type + if self.addressType not in self.supportedAddrs: + self.sendErrorReply(REPLY_ADDR_NOT_SUPPORTED) + return + + # Deal with addresses + if self.addressType == ADDR_IPV4: + addr, port = struct.unpack('!IH', self.buf[4:10]) + self.buf = self.buf[10:] + elif self.addressType == ADDR_DOMAINNAME: + nlen = ord(self.buf[4]) + addr, port = struct.unpack('!%dsH' % nlen, self.buf[5:]) + self.buf = self.buf[7 + len(addr):] + else: + # Any other address types are not supported + self.sendErrorReply(REPLY_ADDR_NOT_SUPPORTED) + return + + # Ensure command is supported + if cmd not in self.enabledCommands: + # Send a not supported error + self.sendErrorReply(REPLY_CMD_NOT_SUPPORTED) + return + + # Process the command + if cmd == CMD_CONNECT: + self.connectRequested(addr, port) + elif cmd == CMD_BIND: + self.bindRequested(addr, port) + else: + # Any other command is not supported + self.sendErrorReply(REPLY_CMD_NOT_SUPPORTED) + + except struct.error, why: + return None + + def _makeRequest(self): + debug("_makeRequest") + self.state = STATE_TARGET_REQUEST + sha1 = hashlib.sha1(self.sid + self.initiator_jid + self.target_jid).hexdigest() + request = struct.pack('!5B%dsH' % len(sha1), SOCKS5_VER, CMD_CONNECT, 0, ADDR_DOMAINNAME, len(sha1), sha1, 0) + self.transport.write(request) + + def _parseRequestReply(self): + debug("_parseRequestReply") + try: + ver, rep, rsvd, self.addressType = struct.unpack('!BBBB', self.buf[:4]) + # Ensure we actually support the requested address type + if self.addressType not in self.supportedAddrs: + self.sendErrorReply(REPLY_ADDR_NOT_SUPPORTED) + return + + # Deal with addresses + if self.addressType == ADDR_IPV4: + addr, port = struct.unpack('!IH', self.buf[4:10]) + self.buf = self.buf[10:] + elif self.addressType == ADDR_DOMAINNAME: + nlen = ord(self.buf[4]) + addr, port = struct.unpack('!%dsH' % nlen, self.buf[5:]) + self.buf = self.buf[7 + len(addr):] + else: + # Any other address types are not supported + self.sendErrorReply(REPLY_ADDR_NOT_SUPPORTED) + return + + # Ensure reply is OK + if rep != REPLY_SUCCESS: + self.loseConnection() + return + + debug("Saving file in %s.", self.data["dest_path"]) + self.dest_file = open(self.data["dest_path"], 'w') + self.state = STATE_TARGET_READY + self.activateCB(self.target_jid, self.initiator_jid, self.sid, self.IQ_id) + + + except struct.error, why: + return None + + def connectionMade(self): + debug("connectionMade (mode = %s)" % self.mode) + self.host.registerProgressCB(self.transfert_id, self.getProgress) + + if self.mode == "target": + self.state = STATE_TARGET_INITIAL + self._startNegotiation() + + def connectRequested(self, addr, port): + debug(("connectRequested")) + # Check for special connect to the namespace -- this signifies that the client + # is just checking to ensure it can connect to the streamhost + if addr == "http://jabber.org/protocol/bytestreams": + self.connectCompleted(addr, 0) + self.transport.loseConnection() + return + + # Save addr, for cleanup + self.addr = addr + + # Check to see if the requested address is already + # activated -- send an error if so + if addr in self.activeConns: + self.sendErrorReply(socks5.REPLY_CONN_NOT_ALLOWED) + return + + # Add this address to the pending connections + if self.addConnection(addr, self): + self.connectCompleted(addr, 0) + self.transport.stopReading() + else: + self.sendErrorReply(socks5.REPLY_CONN_REFUSED) + + def getProgress(self, data): + """Fill data with position of current transfert""" + data["size"] = self.filesize + try: + data["position"] = str(self.dest_file.tell()) + except (ValueError, AttributeError): + data["position"] = "" + + def fileTransfered(self, d): + info("File transfer completed, closing connection") + self.transport.loseConnection() + + def updateTransfered(self, data): + self.transfered+=len(data) + return data + + def connectCompleted(self, remotehost, remoteport): + debug("connectCompleted") + if self.addressType == ADDR_IPV4: + result = struct.pack('!BBBBIH', SOCKS5_VER, REPLY_SUCCESS, 0, 1, remotehost, remoteport) + elif self.addressType == ADDR_DOMAINNAME: + result = struct.pack('!BBBBB%dsH' % len(remotehost), SOCKS5_VER, REPLY_SUCCESS, 0, + ADDR_DOMAINNAME, len(remotehost), remotehost, remoteport) + self.transport.write(result) + self.state = STATE_READY + self.dest_file=open(self.filepath) + d=self.beginFileTransfer(self.dest_file, self.transport, self.updateTransfered) + d.addCallback(self.fileTransfered) + + def bindRequested(self, addr, port): + pass + + def authenticateUserPass(self, user, passwd): + debug("User/pass: %s/%s", user, passwd) + return True + + def dataReceived(self, buf): + if self.state == STATE_TARGET_READY: + self.dest_file.write(buf) + self.transfered+=len(buf) + return + + self.buf = self.buf + buf + if self.state == STATE_INITIAL: + self._parseNegotiation() + if self.state == STATE_AUTH_USERPASS: + self._parseUserPass() + if self.state == STATE_REQUEST: + self._parseRequest() + if self.state == STATE_TARGET_AUTH: + ver, method = struct.unpack('!BB', buf) + self.buf = self.buf[2:] + if ver!=SOCKS5_VER or method!=AUTHMECH_ANON: + self.transport.loseConnection() + else: + self._makeRequest() + if self.state == STATE_TARGET_REQUEST: + self._parseRequestReply() + + + def clientConnectionLost(self, reason): + debug("clientConnectionLost") + self.transport.loseConnection() + + def connectionLost(self, reason): + debug("connectionLost") + self.host.removeProgressCB(self.transfert_id) + if self.state == STATE_CONNECT_PENDING: + self.removePendingConnection(self.addr, self) + else: + self.transport.unregisterProducer() + if self.peersock != None: + self.peersock.peersock = None + self.peersock.transport.unregisterProducer() + self.peersock = None + self.removeActiveConnection(self.addr) + +class Socks5ServerFactory(protocol.ServerFactory): + protocol = SOCKSv5 + protocol.mode = "initiator" #FIXME: Q&D way, fix it + + + def startedConnecting(self, connector): + debug ("Socks 5 server connection started") + + def clientConnectionLost(self, connector, reason): + debug ("Socks 5 server connection lost (reason: %s)", reason) + +class Socks5ClientFactory(protocol.ClientFactory): + protocol = SOCKSv5 + protocol.mode = "target" #FIXME: Q&D way, fix it + + def startedConnecting(self, connector): + debug ("Socks 5 client connection started") + + def clientConnectionLost(self, connector, reason): + debug ("Socks 5 client connection lost (reason: %s)", reason) + + +class XEP_0065(): + def __init__(self, host): + info("Plugin XEP_0065 initialization") + self.host = host + debug("registering") + self.server_factory = Socks5ServerFactory() + self.server_factory.protocol.host = self.host #needed for progress CB + self.client_factory = Socks5ClientFactory() + host.add_IQ_cb("http://jabber.org/protocol/bytestreams", self.getFile) + port = int(self.host.memory.getParamV("Port", "File Transfert")) + info("Launching Socks5 Stream server on port %d", port) + reactor.listenTCP(port, self.server_factory) + + def setData(self, data, id): + self.data = data + self.transfert_id = id + + def sendFile(self, id, filepath, size): + #lauching socks5 initiator + self.server_factory.protocol.mode = "initiator" + self.server_factory.protocol.filepath = filepath + self.server_factory.protocol.filesize = size + self.server_factory.protocol.transfert_id = id + + def getFile(self, stanza): + """Get file using byte stream""" + SI_elem = stanza.firstChildElement() + IQ_id = stanza['id'] + for element in SI_elem.elements(): + if element.name == "streamhost": + info ("Stream proposed: host=[%s] port=[%s]", element['host'], element['port']) + factory = self.client_factory + self.server_factory.protocol.mode = "target" + factory.protocol.host = self.host #needed for progress CB + factory.protocol.data = self.data + factory.protocol.transfert_id = self.transfert_id + factory.protocol.filesize = self.data["size"] + factory.protocol.sid = SI_elem['sid'] + factory.protocol.initiator_jid = element['jid'] + factory.protocol.target_jid = self.host.me.full() + factory.protocol.IQ_id = IQ_id + factory.protocol.activateCB = self.activateStream + reactor.connectTCP(element['host'], int(element['port']), factory) + + def activateStream(self, from_jid, to_jid, sid, IQ_id): + debug("activating stream") + result = domish.Element(('', 'iq')) + result['type'] = 'result' + result['id'] = IQ_id + result['from'] = from_jid + result['to'] = to_jid + query = result.addElement('query', 'http://jabber.org/protocol/bytestreams') + query['sid'] = sid + streamhost = query.addElement('streamhost-used') + streamhost['jid'] = to_jid #FIXME: use real streamhost + self.host.xmlstream.send(result) + diff -r 000000000000 -r c4bc297b82f0 plugins/plugin_xep_0096.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plugins/plugin_xep_0096.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,170 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +SAT plugin for managing xep-0096 +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from logging import debug, info, error +from twisted.words.xish import domish +from twisted.internet import protocol +from twisted.words.protocols.jabber import client, jid, xmlstream, error +import os.path +from twisted.internet import reactor #FIXME best way ??? + + +PLUGIN_INFO = { +"name": "XEP 0096 Plugin", +"import_name": "XEP_0096", +"type": "XEP", +"dependencies": ["XEP_0065"], +"main": "XEP_0096", +"description": """Implementation of SI File Transfert""" +} + +class XEP_0096: + def __init__(self, host): + info("Plugin XEP_0096 initialization") + self.host = host + self._waiting_for_approval = {} + host.add_IQ_cb("http://jabber.org/protocol/si", self.xep_96) + host.bridge.register("sendFile", self.sendFile) + + + def xep_96(self, IQ): + info ("XEP-0096 management") + SI_elem = IQ.firstChildElement() + debug(SI_elem.toXml()) + filename = "" + file_size = "" + for element in SI_elem.elements(): + if element.name == "file": + info ("File proposed: name=[%s] size=%s", element['name'], element['size']) + filename = element["name"] + file_size = element["size"] + elif element.name == "feature": + from_jid = IQ["from"] + self._waiting_for_approval[IQ["id"]] = (element, from_jid, file_size) + data={ "filename":filename, "from":from_jid, "size":file_size } + self.host.askConfirmation(IQ["id"], "FILE_TRANSFERT", data, self.confirmationCB) + + def confirmationCB(self, id, accepted, data): + """Called on confirmation answer""" + if accepted: + data['size'] = self._waiting_for_approval[id][2] + self.host.plugins["XEP_0065"].setData(data, id) + self.approved(id) + else: + debug ("Transfert [%s] refused", id) + del(self._waiting_for_approval[id]) + + def approved(self, id): + """must be called when a file transfert has be accepted by client""" + debug ("Transfert [%s] accepted", id) + + if ( not self._waiting_for_approval.has_key(id) ): + error ("Approved unknow id !") + #TODO: manage this (maybe approved by several frontends) + else: + element, from_id, size = self._waiting_for_approval[id] + del(self._waiting_for_approval[id]) + self.negociate(element, id, from_id) + + def negociate(self, feat_elem, id, to_jid): + #TODO: put this in a plugin + #FIXME: over ultra mega ugly, need to be generic + info ("Feature negociation") + data = feat_elem.firstChildElement() + field = data.firstChildElement() + #FIXME: several options ! Q&D code for test only + option = field.firstChildElement() + value = option.firstChildElement() + if unicode(value) == "http://jabber.org/protocol/bytestreams": + #ugly, as usual, need to be entirely rewritten (just for test !) + result = domish.Element(('', 'iq')) + result['type'] = 'result' + result['id'] = id + result['to'] = to_jid + si = result.addElement('si', 'http://jabber.org/protocol/si') + file = si.addElement('file', 'http://jabber.org/protocol/si/profile/file-transfer') + feature = si.addElement('feature', 'http://jabber.org/protocol/feature-neg') + x = feature.addElement('x', 'jabber:x:data') + x['type'] = 'submit' + field = x.addElement('field') + field['var'] = 'stream-method' + value = field.addElement('value') + value.addContent('http://jabber.org/protocol/bytestreams') + self.host.xmlstream.send(result) + + def fileCB(self, answer): + if answer['type']=="result": #FIXME FIXME FIXME ugly ugly ugly ! and temp FIXME FIXME FIXME + info("SENDING UGLY ANSWER") + offer=client.IQ(self.host.xmlstream,'set') + offer["from"]=self.host.me.full() + offer["to"]=answer['from'] + query=offer.addElement('query', 'http://jabber.org/protocol/bytestreams') + query['mode']='tcp' + streamhost=query.addElement('streamhost') + streamhost['host']=self.host.memory.getParamV("IP", "File Transfert") + streamhost['port']=self.host.memory.getParamV("Port", "File Transfert") + streamhost['jid']=self.host.me.full() + offer.send() + + + + + def sendFile(self, to, filepath): + """send a file using XEP-0096 + Return an unique id to identify the transfert + """ + debug ("sendfile (%s) to %s", filepath, to ) + print type(filepath), type(to) + + statinfo = os.stat(filepath) + + offer=client.IQ(self.host.xmlstream,'set') + debug ("Transfert ID: %s", offer["id"]) + + self.host.plugins["XEP_0065"].sendFile(offer["id"], filepath, str(statinfo.st_size)) + + offer["from"]=self.host.me.full() + offer["to"]=jid.JID(to).full() + si=offer.addElement('si','http://jabber.org/protocol/si') + si["mime-type"]='text/plain' + si["profile"]='http://jabber.org/protocol/si/profile/file-transfer' + file = si.addElement('file', 'http://jabber.org/protocol/si') + file['name']=os.path.basename(filepath) + file['size']=str(statinfo.st_size) + + ### + # FIXME: Ugly temporary hard coded implementation of XEP-0020 & XEP-0004, + # Need to be recoded elsewhere in a more generic way + ### + + feature=si.addElement('feature', "http://jabber.org/protocol/feature-neg") + x=feature.addElement('x', "jabber:x:data") + x['type']='form' + field=x.addElement('field') + field['type']='list-single' + field['var']='stream-method' + option = field.addElement('option') + value = option.addElement('value', content='http://jabber.org/protocol/bytestreams') + + offer.addCallback(self.fileCB) + offer.send() + return offer["id"] #XXX: using IQ id as file transfert id seems OK as IQ id are required + diff -r 000000000000 -r c4bc297b82f0 sat --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sat Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,367 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +SAT: a jabber client +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +from twisted.internet import glib2reactor, protocol +glib2reactor.install() + +from twisted.words.protocols.jabber import client, jid, xmlstream, error +from twisted.words.xish import domish + +from twisted.internet import reactor +import pdb + +from sat_bridge.DBus import DBusBridge +import logging +from logging import debug, info, error + +import signal, sys +import os.path + +from tools.memory import Memory +from glob import glob + + +### logging configuration FIXME: put this elsewhere ### +logging.basicConfig(level=logging.DEBUG, + format='%(message)s') +### + + + + +class SAT: + + def __init__(self): + self.reactor=reactor + self.memory=Memory() + self.server_features=[] #XXX: temp dic, need to be transfered into self.memory in the future + self.connected=False #FIXME: use twisted var instead + + self._iq_cb_map = {} #callback called when ns is found on IQ + self._waiting_conf = {} #callback called when a confirmation is received + self._progress_cb_map = {} #callback called when a progress is requested (key = progress id) + self.plugins = {} + + self.bridge=DBusBridge() + self.bridge.register("connect", self.connect) + self.bridge.register("getContacts", self.memory.getContacts) + self.bridge.register("getPresenceStatus", self.memory.getPresenceStatus) + self.bridge.register("sendMessage", self.sendMessage) + self.bridge.register("setParam", self.setParam) + self.bridge.register("getParam", self.memory.getParam) + self.bridge.register("getParams", self.memory.getParams) + self.bridge.register("getParamsCategories", self.memory.getParamsCategories) + self.bridge.register("getHistory", self.memory.getHistory) + self.bridge.register("setPresence", self.setPresence) + self.bridge.register("addContact", self.addContact) + self.bridge.register("delContact", self.delContact) + self.bridge.register("isConnected", self.isConnected) + self.bridge.register("confirmationAnswer", self.confirmationAnswer) + self.bridge.register("getProgress", self.getProgress) + + self._import_plugins() + self.connect() + + + def _import_plugins(self): + """Import all plugins found in plugins directory""" + #TODO: manage dependencies + plug_lst = [os.path.splitext(plugin)[0] for plugin in map(os.path.basename,glob ("plugins/plugin*.py"))] + + for plug in plug_lst: + plug_path = 'plugins.'+plug + __import__(plug_path) + mod = sys.modules[plug_path] + plug_info = mod.PLUGIN_INFO + info ("importing plugin: %s", plug_info['name']) + self.plugins[plug_info['import_name']] = getattr(mod, plug_info['main'])(self) + + def connect(self): + if (self.connected): + info("already connected !") + return + info("Connecting...") + self.me = jid.JID(self.memory.getParamV("JabberID", "Connection")) + self.factory = client.XMPPClientFactory(self.me, self.memory.getParamV("Password", "Connection")) + self.factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT,self.authd) + self.factory.addBootstrap(xmlstream.INIT_FAILED_EVENT,self.failed) + reactor.connectTCP(self.memory.getParamV("Server", "Connection"), 5222, self.factory) + self.connectionStatus="online" #TODO: check if connection is OK + self.connected=True #TODO: use startedConnecting and clientConnectionLost of XMPPClientFactory + + + def run(self): + debug("running app") + reactor.run() + + def stop(self): + debug("stopping app") + reactor.stop() + + def authd(self,xmlstream): + self.xmlstream=xmlstream + roster=client.IQ(xmlstream,'get') + roster.addElement(('jabber:iq:roster', 'query')) + roster.addCallback(self.rosterCb) + roster.send() + debug("server = %s",self.memory.getParamV("Server", "Connection")) + + ###FIXME: tmp disco ### + self.memory.registerFeature("http://jabber.org/protocol/disco#info") + self.disco(self.memory.getParamV("Server", "Connection"), self.serverDisco) + + + #we now send our presence status + self.setPresence(status="Online") + + # add a callback for the messages + xmlstream.addObserver('/message', self.gotMessage) + xmlstream.addObserver('/presence', self.presenceCb) + xmlstream.addObserver("/iq[@type='set' or @type='get']", self.iqCb) + #reactor.callLater(2,self.sendFile,"goffi2@jabber.goffi.int/Psi", "/tmp/fakefile") + + def sendMessage(self,to,msg,type='chat'): + #FIXME: check validity of recipient + debug("Sending jabber message to %s...", to) + message = domish.Element(('jabber:client','message')) + message["to"] = jid.JID(to).full() + message["from"] = self.me.full() + message["type"] = type + message.addElement("body", "jabber:client", msg) + self.xmlstream.send(message) + self.memory.addToHistory(self.me, self.me, jid.JID(to), message["type"], unicode(msg)) + self.bridge.newMessage(message['from'], unicode(msg), to=message['to']) #We send back the message, so all clients are aware of it + + def setParam(self, name, value, namespace): + """set wanted paramater and notice observers""" + info ("setting param: %s=%s in namespace %s", name, value, namespace) + self.memory.setParam(name, value, namespace) + self.bridge.paramUpdate(name, value, namespace) + + def setRoster(self, to): + """Add a contact to roster list""" + to_jid=jid.JID(to) + roster=client.IQ(self.xmlstream,'set') + query=roster.addElement(('jabber:iq:roster', 'query')) + item=query.addElement("item") + item.attributes["jid"]=to_jid.userhost() + roster.send() + #TODO: check IQ result + + def delRoster(self, to): + """Remove a contact from roster list""" + to_jid=jid.JID(to) + roster=client.IQ(self.xmlstream,'set') + query=roster.addElement(('jabber:iq:roster', 'query')) + item=query.addElement("item") + item.attributes["jid"]=to_jid.userhost() + item.attributes["subscription"]="remove" + roster.send() + #TODO: check IQ result + + + def failed(self,xmlstream): + debug("failed: %s", xmlstream.getErrorMessage()) + debug("failed: %s", dir(xmlstream)) + + def isConnected(self): + return self.connected + + ## jabber methods ## + + def disco (self, item, callback, node=None): + """XEP-0030 Service discovery Feature.""" + disco=client.IQ(self.xmlstream,'get') + disco["from"]=self.me.full() + disco["to"]=item + disco.addElement(('http://jabber.org/protocol/disco#info', 'query')) + disco.addCallback(callback) + disco.send() + + + def setPresence(self, to="", type="", show="", status="", priority=0): + """Send our presence information""" + presence = domish.Element(('jabber:client', 'presence')) + if not type in ["", "unavailable", "subscribed", "subscribe", + "unsubscribe", "unsubscribed", "prob", "error"]: + error("Type error !") + #TODO: throw an error + return + + if to: + presence.attributes["to"]=to + if type: + presence.attributes["type"]=type + + for element in ["show", "status", "priority"]: + if locals()[element]: + presence.addElement(element).addContent(unicode(locals()[element])) + + self.xmlstream.send(presence) + + def addContact(self, to): + """Add a contact in roster list""" + to_jid=jid.JID(to) + self.setRoster(to_jid.userhost()) + self.setPresence(to_jid.userhost(), "subscribe") + + def delContact(self, to): + """Remove contact from roster list""" + to_jid=jid.JID(to) + self.delRoster(to_jid.userhost()) + self.bridge.contactDeleted(to) + + def gotMessage(self,message): + debug (u"got_message from: %s", message["from"]) + for e in message.elements(): + if e.name == "body": + self.bridge.newMessage(message["from"], e.children[0]) + self.memory.addToHistory(self.me, jid.JID(message["from"]), self.me, "chat", e.children[0]) + break + + ## callbacks ## + + def add_IQ_cb(self, ns, cb): + """Add an IQ callback on namespace ns""" + debug ("Registered callback for namespace %s", ns) + self._iq_cb_map[ns]=cb + + def iqCb(self, stanza): + info ("iqCb") + debug ("="*20) + debug ("DEBUG:\n") + debug (stanza.toXml().encode('utf-8')) + debug ("="*20) + #FIXME: temporary ugly code + uri = stanza.firstChildElement().uri + if self._iq_cb_map.has_key(uri): + self._iq_cb_map[uri](stanza) + #TODO: manage errors stanza + + def presenceCb(self, elem): + info ("presence update for [%s]", elem.getAttribute("from")) + debug("\n\nXML=\n%s\n\n", elem.toXml()) + presence={} + presence["jid"]=elem.getAttribute("from") + presence["type"]=elem.getAttribute("type") or "" + presence["show"]="" + presence["status"]="" + presence["priority"]=0 + + for item in elem.elements(): + if presence.has_key(item.name): + presence[item.name]=item.children[0] + + ### we check if the status is not about subscription ### + #TODO: check that from jid is one we wants to subscribe (ie: check a recent subscription asking) + if jid.JID(presence["jid"]).userhost()!=self.me.userhost(): + if presence["type"]=="subscribed": + debug ("subscription answer") + elif presence["type"]=="unsubscribed": + debug ("unsubscription answer") + elif presence["type"]=="subscribe": + #FIXME: auto answer for subscribe request, must be checked ! + debug ("subscription request") + self.setPresence(to=presence["jid"], type="subscribed") + else: + #We keep presence information only if it is not for subscription + self.memory.addPresenceStatus(presence["jid"], presence["type"], presence["show"], + presence["status"], int(presence["priority"])) + + #now it's time to notify frontends + self.bridge.presenceUpdate(presence["jid"], presence["type"], presence["show"], + presence["status"], int(presence["priority"])) + + def rosterCb(self,roster): + for contact in roster.firstChildElement().elements(): + info ("new contact in roster list: %s", contact['jid']) + #and now the groups + groups=[] + for group in contact.elements(): + if group.name!="group": + error("Unexpected element !") + break + groups.append(str(group)) + self.memory.addContact(contact['jid'], contact.attributes, groups) + self.bridge.newContact(contact['jid'], contact.attributes, groups) + + def serverDisco(self, disco): + """xep-0030 Discovery Protocol.""" + for element in disco.firstChildElement().elements(): + if element.name=="feature": + debug ("Feature dectetee: %s",element["var"]) + self.server_features.append(element["var"]) + elif element.name=="identity": + debug ("categorie= %s",element["category"]) + debug ("features= %s",self.server_features) + + ## Generic HMI ## + + def askConfirmation(self, id, type, data, cb): + """Add a confirmation callback""" + if self._waiting_conf.has_key(id): + error ("Attempt to register two callbacks for the same confirmation") + else: + self._waiting_conf[id] = cb + self.bridge.askConfirmation(type, id, data) + + + def confirmationAnswer(self, id, accepted, data): + """Called by frontends to answer confirmation requests""" + debug ("Received confirmation answer for id [%s]: %s", id, "accepted" if accepted else "refused") + if not self._waiting_conf.has_key(id): + error ("Received an unknown confirmation") + else: + cb = self._waiting_conf[id] + del self._waiting_conf[id] + cb(id, accepted, data) + + def registerProgressCB(self, id, CB): + """Register a callback called when progress is requested for id""" + self._progress_cb_map[id] = CB + + def removeProgressCB(self, id): + """Remove a progress callback""" + if not self._progress_cb_map.has_key(id): + error ("Trying to remove an unknow progress callback") + else: + del self._progress_cb_map[id] + + def getProgress(self, id): + """Return a dict with progress information + data['position'] : current possition + data['size'] : end_position + """ + data = {} + try: + self._progress_cb_map[id](data) + except KeyError: + pass + #debug("Requested progress for unknown id") + return data + + +app=SAT() #TODO: tmp, use twisted way instead +app.run() + +app.memory.save() #FIXME: not the best place +debug("Good Bye") diff -r 000000000000 -r c4bc297b82f0 sat_bridge/DBus.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sat_bridge/DBus.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,202 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- + +""" +SAT: a jabber client +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + +from bridge import Bridge +import dbus +import dbus.service +import dbus.mainloop.glib +import pdb +from logging import debug, info, error + +class DbusObject(dbus.service.Object): + + def __init__(self, bus, path): + dbus.service.Object.__init__(self, bus, path) + debug("Init DbusObject...") + self.cb={} + + def register(self, name, cb): + self.cb[name]=cb + + ### signals ### + + @dbus.service.signal("org.goffi.SAT.communication", + signature='sa{ss}as') + def newContact(self, contact, attributes, groups): + debug("new contact signal (%s) sended", contact) + + @dbus.service.signal("org.goffi.SAT.communication", + signature='ssss') + def newMessage(self, from_jid, msg, type='chat', to=''): + debug("new message signal (from:%s msg:%s type:%s to:%s) sended", from_jid, msg, type, to) + + @dbus.service.signal("org.goffi.SAT.communication", + signature='ssssi') + def presenceUpdate(self, jid, type, show, status, priority): + debug("presence update signal (from:%s type: %s show:%s status:\"%s\" priority:%d) sended" , jid, type, show, status, priority) + + @dbus.service.signal("org.goffi.SAT.communication", + signature='sss') + def paramUpdate(self, name, value, namespace): + debug("param update signal: %s=%s in namespace %s", name, value, namespace) + + @dbus.service.signal("org.goffi.SAT.communication", + signature='s') + def contactDeleted(self, jid): + debug("contact deleted signal: %s", jid) + + @dbus.service.signal("org.goffi.SAT.request", + signature='ssa{ss}') + def askConfirmation(self, type, id, data): + debug("asking for confirmation: id = [%s] type = %s data = %s", id, type, data) + + + + ### methods ### + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='', out_signature='') + def connect(self): + info ("Connection asked") + return self.cb["connect"]() + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='', out_signature='a(sa{ss}as)') + def getContacts(self): + debug("getContacts...") + return self.cb["getContacts"]() + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='', out_signature='a(ssssi)') + def getPresenceStatus(self): + debug("getPresenceStatus...") + return self.cb["getPresenceStatus"]() + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='ss', out_signature='') + def sendMessage(self, to, message): + debug("sendMessage...") + self.cb["sendMessage"](to, message) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='ss', out_signature='s') + def sendFile(self, to, path): + debug("sendFile...") + return self.cb["sendFile"](to, path) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='ssssi', out_signature='') + def setPresence(self, to="", type="", show="", status="", priority=0): + self.cb["setPresence"](to, type, show, status, priority) + + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='sss', out_signature='') + def setParam(self, name, value, namespace="default"): + self.cb["setParam"](name, str(value), namespace) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='ss', out_signature='(ss)') + def getParam(self, name, namespace="default"): + return self.cb["getParam"](name, namespace) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='s', out_signature='a(sss)') + def getParams(self, namespace): + return self.cb["getParams"](namespace) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='', out_signature='as') + def getParamsCategories(self): + return self.cb["getParamsCategories"]() + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='ssi', out_signature='a{i(ss)}') + def getHistory(self, from_jid, to_jid, size): + debug("History asked for %s", to_jid) + return self.cb["getHistory"](from_jid, to_jid, size) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='s', out_signature='') + def addContact(self, jid): + debug("Subscription asked for %s", jid) + return self.cb["addContact"](jid) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='s', out_signature='') + def delContact(self, jid): + debug("Unsubscription asked for %s", jid) + return self.cb["delContact"](jid) + + @dbus.service.method("org.goffi.SAT.communication", + in_signature='', out_signature='b') + def isConnected(self): + debug("Connection status requested") + return self.cb["isConnected"]() + + @dbus.service.method("org.goffi.SAT.request", + in_signature='sba{ss}', out_signature='') + def confirmationAnswer(self, id, accepted, data): + debug("Answer for confirmation [%s]: %s", id, "Accepted" if accepted else "Refused") + return self.cb["confirmationAnswer"](id, accepted, data) + + @dbus.service.method("org.goffi.SAT.request", + in_signature='s', out_signature='a{ss}') + def getProgress(self, id): + #debug("Progress asked for %s", id) + return self.cb["getProgress"](id) + +class DBusBridge(Bridge): + def __init__(self): + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + Bridge.__init__(self) + info ("Init DBus...") + self.session_bus = dbus.SessionBus() + self.dbus_name = dbus.service.BusName("org.goffi.SAT", self.session_bus) + self.dbus_bridge = DbusObject(self.session_bus, '/org/goffi/SAT/bridge') + + def newContact(self, contact, attributes, groups): + self.dbus_bridge.newContact(contact, attributes, groups) + + def newMessage(self,from_jid,msg,type='chat', to=''): + debug("sending message...") + self.dbus_bridge.newMessage(from_jid, msg, type, to) + + def presenceUpdate(self, jid, type, show, status, priority): + debug("updating presence for %s",jid) + self.dbus_bridge.presenceUpdate(jid, type, show, status, priority) + + def paramUpdate(self, name, value, namespace): + debug("updating param [%s] %s ", namespace, name) + self.dbus_bridge.paramUpdate(name, value, namespace) + + def contactDeleted(self, jid): + debug("sending contact deleted signal %s ", jid) + self.dbus_bridge.contactDeleted(jid) + + def askConfirmation(self, type, id, data): + self.dbus_bridge.askConfirmation(type, id, data) + + def register(self, name, callback): + debug("enregistrement de %s",name) + self.dbus_bridge.register(name, callback) + diff -r 000000000000 -r c4bc297b82f0 sat_bridge/__init__.py diff -r 000000000000 -r c4bc297b82f0 sat_bridge/bridge.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sat_bridge/bridge.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,68 @@ +#!/usr/bin/python +#-*- coding: utf-8 -*- + +""" +SAT: a jabber client +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from logging import debug, info, error + +class Bridge: + def __init__(self): + info ("Bridge initialization") + + ##signals + def newContact(self, contact): + raise NotImplementedError + + def newMessage(self, from_jid, msg, type='chat'): + raise NotImplementedError + + def presenceUpdate(self, type, jid, show, status, priority): + raise NotImplementedError + + def paramUpdate(self, name, value): + raise NotImplementedError + + + ##methods + def connect(self): + raise NotImplementedError + + def getContacts(self): + raise NotImplementedError + + def getPresenceStatus(self): + raise NotImplementedError + + def sendMessage(self): + raise NotImplementedError + + def setPresence(self, to="", type="", show="", status="", priority=0): + raise NotImplementedError + + def setParam(self, name, value, namespace): + raise NotImplementedError + + def getParam(self, name, namespace): + raise NotImplementedError + + def getParams(self, namespace): + raise NotImplementedError + + def getHistory(self, from_jid, to_jid, size): + raise NotImplementedError diff -r 000000000000 -r c4bc297b82f0 tools/__init__.py diff -r 000000000000 -r c4bc297b82f0 tools/jid.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/jid.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,51 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +SAT: a jabber client +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + + + +class JID(str): + """This class help manage JID (Node@Domaine/Resource)""" + + def __new__(cls, jid): + self = str.__new__(cls, jid) + self.__parse() + return self + + def __parse(self): + """find node domaine and resource""" + node_end=self.find('@') + if node_end<0: + node_end=len(self) + domain_end=self.find('/') + if domain_end<1: + domain_end=len(self) + self.node=self[:node_end] + self.domain=self[node_end+1:domain_end] + self.resource=self[domain_end+1:] + if node_end==len(self): + self.short=self + else: + self.short=self.node+'@'+self.domain + + def is_valid(self): + """return True if the jid is xmpp compliant""" + #FIXME: always return True for the moment + return True diff -r 000000000000 -r c4bc297b82f0 tools/memory.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/memory.py Sat Aug 29 13:34:59 2009 +0200 @@ -0,0 +1,183 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +SAT: a jabber client +Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) + +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 . +""" + +from __future__ import with_statement + +import os.path +import time +import pickle +from logging import debug, info, error + +const_SAVEFILE_PARAM=os.path.expanduser("~/.sat_param.save") +const_SAVEFILE_HISTORY=os.path.expanduser("~/.sat_history.save") + +class Memory: + """This class manage all persistent informations""" + + def __init__(self): + info ("Memory manager init") + self.contact={} + self.presenceStatus={} + self.params={} + self.history={} + self.disco={} #XXX: maybe best in a separate class + self.features={} + self.load() + + def load_default_params(self): + """Load default value, in case of no save file or error.""" + + self.createParam("JabberID", "goffi@jabber.goffi.int/TestScript", "string", "Connection") + self.createParam("Password", "toto", "password", "Connection") + self.createParam("Server", "jabber.goffi.int", "string", "Connection") + self.createParam("IP", "192.168.0.2", "string", "File Transfert") + self.createParam("Port", "28915", "string", "File Transfert") + self.createParam("Watched", "test@jabber.goffi.int", "string", "Misc") #TODO: a mettre dans un plugin + + def load(self): + """Load parameters and all memory things from file/db""" + + #first parameters + if os.path.exists(const_SAVEFILE_PARAM): + try: + with open(const_SAVEFILE_PARAM, 'r') as params_pickle: + self.params=pickle.load(params_pickle) + debug("params loaded") + except: + error ("Can't load params !") + self.load_default_params() + else: + self.load_default_params() + + #history + if os.path.exists(const_SAVEFILE_HISTORY): + try: + with open(const_SAVEFILE_HISTORY, 'r') as history_pickle: + self.history=pickle.load(history_pickle) + debug("history loaded") + except: + error ("Can't load history !") + + + def save(self): + """Save parameters and all memory things to file/db""" + with open(const_SAVEFILE_PARAM, 'w') as params_pickle: + pickle.dump(self.params, params_pickle) + with open(const_SAVEFILE_HISTORY, 'w') as history_pickle: + pickle.dump(self.history, history_pickle) + + def addToHistory(self, me_jid, from_jid, to_jid, type, message): + me_short=me_jid.userhost() + from_short=from_jid.userhost() + to_short=to_jid.userhost() + + if from_jid==me_jid: + key=to_short + else: + key=from_short + + if not self.history.has_key(me_short): + self.history[me_short]={} + if not self.history[me_short].has_key(key): + self.history[me_short][key]={} + + self.history[me_short][key][int(time.time())] = (from_short, message) + + def getHistory(self, from_jid, to_jid, size): + ret={} + if not self.history.has_key(from_jid): + error("source JID not found !") + #TODO: throw an error here + return {} + if not self.history[from_jid].has_key(to_jid): + error("dest JID not found !") + #TODO: throw an error here + return {} + stamps=self.history[from_jid][to_jid].keys() + stamps.sort() + for stamp in stamps[-size:]: + ret[stamp]=self.history[from_jid][to_jid][stamp] + + return ret + + def addContact(self, JID, attributes, groups): + debug("Memory addContact: %s",JID) + assert(isinstance(attributes,dict)) + assert(isinstance(groups,list)) + self.contact[JID]=[attributes, groups] + + def addPresenceStatus(self, jid, type, show, status, priority): + self.presenceStatus[jid]=[type, show, status, priority] + + def getContacts(self): + debug ("Memory getContact OK (%s)", self.contact) + ret=[] + for contact in self.contact: + ret.append([contact] + [self.contact[contact][0]] + [self.contact[contact][1]]) #very ugly I know ! + return ret + + def getPresenceStatus(self): + status=[] + for contact, contactStatus in self.presenceStatus.items(): + status.append([contact]+contactStatus) + debug ("Memory getPresenceStatus (%s)", status) + return status + + def getParamV(self, name, namespace): + """Helper method to get the value in the good type + getParamV stands for GetParamValue""" + if not self.params.has_key(namespace) or not self.params[namespace].has_key(name): + error("Requested param %s in namespace %s doesn't exist !" , name, namespace) + return None + return self.params[namespace][name][0] + + + def getParam(self, name, namespace): + if self.params.has_key(namespace) and self.params[namespace].has_key(name): + return self.params[namespace][name] + return ["",""] + + def getParams(self, namespace): + if self.params.has_key(namespace): + ret=[] + for name in self.params[namespace]: + ret.append([name] + self.params[namespace][name]) + return ret + return [[]] + + def getParamsCategories(self): + """return the namespaces availables""" + return self.params.keys() + + def setParam(self, name, value, namespace): + if not self.params.has_key(namespace) or not self.params[namespace].has_key(name): + return #TODO: throw an error + self.params[namespace][name][0]=value; + + def createParam (self, name, value, type, namespace): + ### TODO: add desciption in params + if not self.params.has_key(namespace): + self.params[namespace]={} + self.params[namespace][name]=[value,type]; + + def registerFeature(self, feature, callback=None): + self.features[feature]=callback +