--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/.hgignore Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,6 @@
+syntax: regexp
+
+^MANIFEST$
+^dist/
+\.sw[op]$
+\.pyc$
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/COPYING Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,620 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/MANIFEST.in Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,3 @@
+include degal/templates/*.html
+include degal/static/*
+include cgi-bin/*
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/README Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,1 @@
+XXX: write me
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/bin/degal Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,15 @@
+#!/usr/bin/env python2.5
+#
+# DeGAL - A pretty simple web image gallery
+# Copyright 2008 Tero Marttila
+#
+
+# import package
+import degal.main
+
+if __name__ == '__main__' :
+ import sys
+
+ # run entrypoint with command arguments, and exit with returned error code
+ sys.exit(degal.main.main(sys.argv))
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cgi-bin/inc.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,27 @@
+# config
+
+# location of DeGAL itself
+
+DEGAL_PATH = "/mnt/photos/public"
+
+
+
+if __name__ == '__main__' :
+ raise Exception("Don't access inc.py directly")
+
+# setup env
+
+import sys
+import os, os.path
+
+#def splitn (path, n) :
+# for i in xrange(0, n) :
+# path = os.path.split(path)[0]
+#
+# return path
+#
+#degal_path = splitn(os.path.join(os.getcwd(), __file__), 2)
+
+os.chdir(DEGAL_PATH)
+sys.path.append(DEGAL_PATH)
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cgi-bin/series.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,211 @@
+#!/usr/bin/env python2.4
+#
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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 2 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, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+import os
+import cgi
+import Cookie
+
+import inc
+from lib import shorturl, template, utils, settings
+
+#
+# load request params
+#
+vars = cgi.FieldStorage()
+
+# these are interpeted different ways, hence the generic naming
+arg1 = vars["keys"].value
+if 'index' in vars :
+ arg2 = vars["index"].value
+else :
+ arg2 = None
+
+# the cookie with the user's current series
+cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
+
+# a special action?
+if arg1 and arg1 in ('add', 'del', 'clear', 'view') or arg2 == 'load' :
+ # load the keys from the cookie
+ if 'series' in cookie :
+ keys = cookie["series"].value.split()
+ else :
+ keys = []
+
+ if arg2 == 'load' :
+ # set the keys in the user's cookie to those in the URL
+ keys = arg1.split()
+
+ elif arg1 == 'add' and arg2 not in keys :
+ # add a code to the list of keys
+ keys.append(arg2)
+
+ elif arg1 == 'del' and arg2 in keys :
+ # remove a key from the list of keys
+ keys.remove(arg2)
+
+ elif arg1 == 'clear' :
+ # clear out the set of keys
+ keys = []
+
+ elif arg1 == 'view' :
+ # just view them
+ pass
+
+ # set the series cookie value
+ cookie['series'] = ' '.join(keys)
+ cookie['series']['path'] = '/'
+
+ # if we have keys, redirect to them, otherwise, back to index we go
+ if keys :
+ redirect_to = "../%s/" % ('+'.join(keys))
+ else :
+ redirect_to = "../.."
+
+ # do the redirect
+ print "Status: 302"
+ print "Location: %s" % redirect_to
+ print cookie
+ print
+ print "Redirect..."
+else :
+ # we're just viewing
+ keys = arg1.split()
+
+ # is this "My Series"?
+ my_series = 'series' in cookie and cookie['series'].value.split() == keys
+
+ index = fname = None
+
+ if arg2 :
+ try :
+ index = int(arg2)
+ except ValueError :
+ fname = arg2
+
+ # our custom Series/Image classes, because they do act slightly differently
+
+ class Series (object) :
+ def __init__ (self, keys) :
+ self.images = []
+ prev = None
+
+ self.image_dict = dict()
+
+ images = shorturl.get_images(keys)
+
+ for index, (key, (dir, fname)) in enumerate(zip(keys, images)) :
+ img = Image(self, key, dir, fname, index)
+ self.images.append(img)
+ self.image_dict[fname] = img
+
+ img.prev = prev
+
+ if prev :
+ prev.next = img
+
+ prev = img
+
+ def render (self) :
+ if my_series :
+ descr = '<a href="../clear/" rel="nofollow">Clear your series</a>'
+ else :
+ descr = '<a href="load" rel="nofollow">Load as your series</a>'
+
+ return template.gallery.render(
+ stylesheet_url = utils.url("style.css", up=2),
+
+ breadcrumb = [(utils.url(up=1), "Index"), (utils.url(), "Series")],
+
+ dirs = None,
+ title = "Series",
+
+ num_pages = 1,
+ cur_page = 0,
+
+ images = self.images,
+
+ description = descr,
+
+ shorturl = None,
+ shorturl_code = None,
+ )
+
+ class Image (object) :
+ def __init__ (self, series, key, dir, fname, index) :
+ self.fname = fname
+ self.name = utils.url_join(dir, fname, abs=True)
+ self.html_name = utils.url(fname)
+ self.real_html_name = utils.url_join(dir, fname + ".html", abs=True)
+
+ self.thumb_name = utils.url_join(dir, settings.THUMB_DIR, fname, abs=True)
+ self.preview_name = utils.url_join(dir, settings.PREVIEW_DIR, fname, abs=True)
+
+ self.shorturl = key
+
+ self.prev = self.next = None
+
+ def render (self) :
+ descr = '<span style="font-size: x-small"><a href="%s.html">Standalone image</a></span>' % self.real_html_name
+
+ if my_series :
+ series_url = utils.url_join("del", self.shorturl, up=1)
+ series_verb = "Remove from"
+ else :
+ series_url = series_verb = ""
+
+ return template.image.render(
+ stylesheet_url = utils.url("style.css", up=3),
+
+ breadcrumb = [(utils.url(up=2), "Index"), (utils.url("."), "Series"), (self.html_name, self.fname)],
+
+ title = self.fname,
+
+ prev = self.prev,
+ img = self,
+ next = self.next,
+
+ description = descr,
+
+ img_size = None,
+ file_size = None,
+ timestamp = None,
+
+ shorturl = utils.url_join("s", self.shorturl, abs=True),
+ shorturl_code = self.shorturl,
+
+ series_url = series_url,
+ series_verb = series_verb,
+ )
+
+ series = Series(keys)
+
+ if fname :
+ html = series.image_dict[fname].render()
+ elif index :
+ html = series.images[index - 1].render()
+ else :
+ html = series.render()
+
+ print "Content-Type: text/html"
+ print
+ print html
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cgi-bin/shorturl.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,41 @@
+#!/usr/bin/env python2.5
+#
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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 2 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, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+import inc
+from lib import shorturl, req
+
+key = req.get_str('key')
+index = req.get_int('index', None)
+
+path = shorturl.html_path(key)
+
+if path :
+ print "Status: 302"
+ print "Location: ../%s" % path
+ print
+ print "../%s" % path
+
+else :
+ print "Status: 404"
+ print
+ print "404"
+
--- a/db/db.sql Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-CREATE TABLE 'nodes' (id INTEGER NOT NULL PRIMARY KEY, dirpath TEXT NOT NULL, filename TEXT NOT NULL);
-CREATE TABLE tags (image INTEGER NOT NULL, type TEXT, tag TEXT NOT NULL);
-CREATE VIEW images AS SELECT id, dirpath, filename FROM nodes WHERE filename != '';
-CREATE UNIQUE INDEX tags_unique_image_type ON tags (image, type);
-CREATE UNIQUE INDEX tags_unique_image_type_tag ON tags (image, type, tag);
--- a/de-cgi-bin/inc.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-# config
-
-# location of DeGAL itself
-
-DEGAL_PATH = "/mnt/photos/public"
-
-
-
-if __name__ == '__main__' :
- raise Exception("Don't access inc.py directly")
-
-# setup env
-
-import sys
-import os, os.path
-
-#def splitn (path, n) :
-# for i in xrange(0, n) :
-# path = os.path.split(path)[0]
-#
-# return path
-#
-#degal_path = splitn(os.path.join(os.getcwd(), __file__), 2)
-
-os.chdir(DEGAL_PATH)
-sys.path.append(DEGAL_PATH)
-
--- a/de-cgi-bin/series.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,211 +0,0 @@
-#!/usr/bin/env python2.4
-#
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import os
-import cgi
-import Cookie
-
-import inc
-from lib import shorturl, template, utils, settings
-
-#
-# load request params
-#
-vars = cgi.FieldStorage()
-
-# these are interpeted different ways, hence the generic naming
-arg1 = vars["keys"].value
-if 'index' in vars :
- arg2 = vars["index"].value
-else :
- arg2 = None
-
-# the cookie with the user's current series
-cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
-
-# a special action?
-if arg1 and arg1 in ('add', 'del', 'clear', 'view') or arg2 == 'load' :
- # load the keys from the cookie
- if 'series' in cookie :
- keys = cookie["series"].value.split()
- else :
- keys = []
-
- if arg2 == 'load' :
- # set the keys in the user's cookie to those in the URL
- keys = arg1.split()
-
- elif arg1 == 'add' and arg2 not in keys :
- # add a code to the list of keys
- keys.append(arg2)
-
- elif arg1 == 'del' and arg2 in keys :
- # remove a key from the list of keys
- keys.remove(arg2)
-
- elif arg1 == 'clear' :
- # clear out the set of keys
- keys = []
-
- elif arg1 == 'view' :
- # just view them
- pass
-
- # set the series cookie value
- cookie['series'] = ' '.join(keys)
- cookie['series']['path'] = '/'
-
- # if we have keys, redirect to them, otherwise, back to index we go
- if keys :
- redirect_to = "../%s/" % ('+'.join(keys))
- else :
- redirect_to = "../.."
-
- # do the redirect
- print "Status: 302"
- print "Location: %s" % redirect_to
- print cookie
- print
- print "Redirect..."
-else :
- # we're just viewing
- keys = arg1.split()
-
- # is this "My Series"?
- my_series = 'series' in cookie and cookie['series'].value.split() == keys
-
- index = fname = None
-
- if arg2 :
- try :
- index = int(arg2)
- except ValueError :
- fname = arg2
-
- # our custom Series/Image classes, because they do act slightly differently
-
- class Series (object) :
- def __init__ (self, keys) :
- self.images = []
- prev = None
-
- self.image_dict = dict()
-
- images = shorturl.get_images(keys)
-
- for index, (key, (dir, fname)) in enumerate(zip(keys, images)) :
- img = Image(self, key, dir, fname, index)
- self.images.append(img)
- self.image_dict[fname] = img
-
- img.prev = prev
-
- if prev :
- prev.next = img
-
- prev = img
-
- def render (self) :
- if my_series :
- descr = '<a href="../clear/" rel="nofollow">Clear your series</a>'
- else :
- descr = '<a href="load" rel="nofollow">Load as your series</a>'
-
- return template.gallery.render(
- stylesheet_url = utils.url("style.css", up=2),
-
- breadcrumb = [(utils.url(up=1), "Index"), (utils.url(), "Series")],
-
- dirs = None,
- title = "Series",
-
- num_pages = 1,
- cur_page = 0,
-
- images = self.images,
-
- description = descr,
-
- shorturl = None,
- shorturl_code = None,
- )
-
- class Image (object) :
- def __init__ (self, series, key, dir, fname, index) :
- self.fname = fname
- self.name = utils.url_join(dir, fname, abs=True)
- self.html_name = utils.url(fname)
- self.real_html_name = utils.url_join(dir, fname + ".html", abs=True)
-
- self.thumb_name = utils.url_join(dir, settings.THUMB_DIR, fname, abs=True)
- self.preview_name = utils.url_join(dir, settings.PREVIEW_DIR, fname, abs=True)
-
- self.shorturl = key
-
- self.prev = self.next = None
-
- def render (self) :
- descr = '<span style="font-size: x-small"><a href="%s.html">Standalone image</a></span>' % self.real_html_name
-
- if my_series :
- series_url = utils.url_join("del", self.shorturl, up=1)
- series_verb = "Remove from"
- else :
- series_url = series_verb = ""
-
- return template.image.render(
- stylesheet_url = utils.url("style.css", up=3),
-
- breadcrumb = [(utils.url(up=2), "Index"), (utils.url("."), "Series"), (self.html_name, self.fname)],
-
- title = self.fname,
-
- prev = self.prev,
- img = self,
- next = self.next,
-
- description = descr,
-
- img_size = None,
- file_size = None,
- timestamp = None,
-
- shorturl = utils.url_join("s", self.shorturl, abs=True),
- shorturl_code = self.shorturl,
-
- series_url = series_url,
- series_verb = series_verb,
- )
-
- series = Series(keys)
-
- if fname :
- html = series.image_dict[fname].render()
- elif index :
- html = series.images[index - 1].render()
- else :
- html = series.render()
-
- print "Content-Type: text/html"
- print
- print html
-
--- a/de-cgi-bin/shorturl.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-#!/usr/bin/env python2.5
-#
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import inc
-from lib import shorturl, req
-
-key = req.get_str('key')
-index = req.get_int('index', None)
-
-path = shorturl.html_path(key)
-
-if path :
- print "Status: 302"
- print "Location: ../%s" % path
- print
- print "../%s" % path
-
-else :
- print "Status: 404"
- print
- print "404"
-
--- a/degal Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,60 +0,0 @@
-#!/usr/bin/env python2.5
-#
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import os.path, os
-from optparse import OptionParser
-
-from lib import folder, shorturl, log
-
-def main (dir='.', targets=()) :
- root_filter = {}
-
- for target in targets :
- f = root_filter
- for path_part in target.split('/') :
- if path_part :
- if path_part not in f :
- f[path_part] = {}
-
- f = f[path_part]
-
- log.title("Indexing %s...", dir)
- root = folder.Folder(dir)
- root.index(root_filter)
- log.up()
-
- log.title("Syncing ShortURLs...")
- shorturl.updateDB(root)
- log.up()
-
- log.title("Rendering updated dirs...")
- root.render()
- log.up()
-
-if __name__ == '__main__' :
- parser = OptionParser(usage="usage: %prog [options] ... [target ...]")
-
- parser.add_option("-d", "--dir", dest="dir", help="look for images in DIR and write the HTML there", metavar="DIR", default=".")
-
- options, filter_targets = parser.parse_args()
-
- main(options.dir, filter_targets)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/__init__.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,3 @@
+"""
+ Degal - an image gallery
+"""
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/commands.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,42 @@
+"""
+ Implementations of the core CLI commands
+"""
+
+import log, shorturl, folder
+
+def main (dir='.', targets=()) :
+ """
+ Scan the given root dir for all images, and render updated ones
+ """
+
+ root_filter = {}
+
+ # parse the targets into the hierarchial root_filter that we use
+ for target in targets :
+ f = root_filter
+ for path_part in target.split('/') :
+ if path_part :
+ if path_part not in f :
+ f[path_part] = {}
+
+ f = f[path_part]
+
+ # build the index
+ log.title("Indexing %s...", dir)
+ root = folder.Folder(dir)
+ root.index(root_filter)
+ log.up()
+
+ # XXX: maintain shorturls stuff
+ if False :
+ log.title("Syncing ShortURLs...")
+ shorturl.updateDB(root)
+ log.up()
+
+ # render output
+ log.title("Rendering updated dirs...")
+ root.render()
+ log.up()
+
+ return 0
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/db.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,64 @@
+import sqlite3
+
+try :
+ conn = sqlite3.connect("db/degal.db")
+
+except sqlite3.OperationalError :
+ conn = None
+
+def execute (expr, *args) :
+ c = conn.cursor()
+ c.execute(expr, args)
+
+ return c
+
+def execute_many (expr, iter) :
+ c = conn.cursor()
+ c.executemany(expr, iter)
+
+ return c
+
+def insert (expr, *args) :
+ return execute_commit(expr, *args).lastrowid
+
+def insert_many (cb, expr, iter) :
+ """
+ Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id)
+ """
+
+ c = conn.cursor()
+
+ c.executemany(expr, _lastrowid_adapter(c, iter, cb))
+
+ return commit(c)
+
+def _lastrowid_adapter (c, iter, cb) :
+ for val, args in iter :
+ yield args
+
+ cb(val, c.lastrowid)
+
+def commit (cursor) :
+ try :
+ cursor.execute("COMMIT")
+ except sqlite3.OperationalError :
+ pass # ffs. INSERT just doesn't do anything otherwise
+
+ return cursor
+
+def execute_commit (expr, *args) :
+ return commit(execute(expr, *args))
+
+def execute_commit_many (expr, iter) :
+ return commit(execute_many(expr, iter))
+
+select = execute
+
+delete = execute_commit
+
+delete_many = execute_commit_many
+
+if conn :
+ cursor = conn.cursor
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/dexif.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,63 @@
+#
+# dexif.py - simple EXIF processing for Degal
+# Copyright (C) 2008, Santtu Pajukanta <santtu@pajukanta.fi>
+#
+# 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 2 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, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+from subprocess import Popen, PIPE
+
+# TODO This should be user configurable
+EXIFTOOL="/usr/bin/exiftool"
+
+outputTags = [
+# TODO Create date is in a useless format, needs some strptime love
+ ("CreateDate", "Create date"),
+ ("Model", "Camera model"),
+ ("Aperture", "Aperture"),
+ ("ExposureMode", "Exposure mode"),
+ ("ExposureCompensation", "Exposure compensation"),
+ ("ExposureTime", "Exposure time"),
+ ("Flash", "Flash mode"),
+ ("ISO", "ISO"),
+ ("ShootingMode", "Shooting mode"),
+ ("LensType", "Lens type"),
+ ("FocalLength", "Focal length")
+]
+
+
+class ExifError(Exception):
+ pass
+
+def parse_exif(filepath):
+ """parse_exif(filepath :: String) -> [(String, String)]
+
+ Parse EXIF tags from an image file and return them in a dict.
+ """
+
+ args = [EXIFTOOL, "-s", "-t", filepath]
+ etproc = Popen(args, stdout = PIPE)
+
+ output, errors = etproc.communicate()
+
+ if etproc.returncode < 0:
+ raise ExifError, "exiftool terminated by signal %d" % (-etproc.returnco)
+ elif etproc.returncode > 0:
+ raise ExifError, "exiftool failed with return code %d" % etproc.returncode
+
+ tags = dict(line.split("\t", 1) for line in output.split("\n") if line)
+ result = [(descr, tags[key]) for (key, descr) in outputTags if tags.has_key(key)]
+ return result
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/folder.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,309 @@
+import os, os.path
+
+import settings, image, utils, helpers, log
+from template import gallery as gallery_tpl
+from helpers import url_for_page
+
+def dirUp (count=1) :
+ """
+ Returns a relative path to the directly count levels above the current one
+ """
+
+ if not count :
+ return '.'
+
+ return os.path.join(*(['..']*count))
+
+class Folder (object) :
+ def __init__ (self, name='.', parent=None) :
+ # the directory name, no trailing /
+ self.name = unicode(name.rstrip(os.sep))
+
+ # our parent Folder, or None
+ self.parent = parent
+
+ # the path to this dir, as a relative path to the root of the image gallery, always starts with .
+ if parent and name :
+ self.path = parent.pathFor(self.name)
+ else :
+ self.path = self.name
+
+ # the url-path to the index.html file
+ self.html_path = self.path
+
+ # dict of fname -> Folder
+ self.subdirs = {}
+
+ # dict of fname -> Image
+ self.images = {}
+
+ # our human-friendly title
+ self.title = None
+
+ # our long-winded description
+ self.descr = ''
+
+ # is this folder non-empty?
+ self.alive = None
+
+ # self.images.values(), but sorted by filename
+ self.sorted_images = []
+
+ # the ShortURL key to this dir
+ self.shorturl_code = None
+
+ # were we filtered out?
+ self.filtered = False
+
+ def pathFor (self, *fnames) :
+ """
+ Return a root-relative path to the given path inside this dir
+ """
+ return os.path.join(self.path, *fnames)
+
+ def index (self, filters=None) :
+ """
+ Look for other dirs and images inside this dir. Filters must be either None,
+ whereupon all files will be included, or a dict of {filename -> next_filter}.
+ If given, only filenames that are present in the dict will be indexed, and in
+ the case of dirs, the next_filter will be passed on to that Folder's index
+ method.
+ """
+
+ if filters :
+ self.filtered = True
+
+ # iterate through listdir
+ for fname in os.listdir(self.path) :
+ # the full filesystem path to it
+ fpath = self.pathFor(fname)
+
+ # ignore dotfiles
+ if fname.startswith('.') :
+ log.debug("Skipping dotfile %s", fname)
+ continue
+
+ # apply filters
+ if filters :
+ if fname in filters :
+ next_filter = filters[fname]
+ else :
+ log.debug("Skip `%s' as we have a filter", fname)
+ continue
+ else :
+ next_filter = None
+
+ # recurse into subdirs, but not thumbs/previews
+ if (os.path.isdir(fpath)
+ and (fname not in (settings.THUMB_DIR, settings.PREVIEW_DIR))
+ and (self.parent or fname not in settings.ROOT_IGNORE)
+ ) :
+ log.down(fname)
+
+ f = Folder(fname, self)
+
+ try :
+ if f.index(next_filter) : # recursion
+ # if a subdir is alive, we are alive as well
+ self.subdirs[fname] = f
+ self.alive = True
+ except Exception, e :
+ log.warning("skip - %s: %s" % (type(e), e))
+
+ log.up()
+
+ # handle images
+ elif os.path.isfile(fpath) and utils.isImage(fname) :
+ log.next(fname)
+ self.images[fname] = image.Image(self, fname)
+
+ # ignore everything else
+ else :
+ log.debug("Ignoring file %s", fname)
+
+ # sort and link the images
+ if self.images :
+ self.alive = True
+
+ # sort the images
+ fnames = self.images.keys()
+ fnames.sort()
+
+ prev = None
+
+ # link
+ for fname in fnames :
+ img = self.images[fname]
+
+ img.prev = prev
+
+ if prev :
+ prev.next = img
+
+ prev = img
+
+ # add to the sorted images list
+ self.sorted_images.append(img)
+
+ # figure out our title/ descr. Must be done before our parent dir is rendered (self.title)
+ title_path = self.pathFor(settings.TITLE_FILE)
+
+ self.title, self.descr = utils.readTitleDescr(title_path)
+
+ # default title for the root dir
+ if self.title or self.descr :
+ self.alive = True
+ pass # use what was in the title file
+
+ elif not self.parent :
+ self.title = 'Index'
+
+ else :
+ self.title = self.name
+
+ if not self.alive :
+ log.debug("Dir %s isn't alive" % self.path)
+
+ return self.alive
+
+ def getObjInfo (self) :
+ """
+ Metadata for shorturls2.db
+ """
+ return 'dir', self.path, ''
+
+ def breadcrumb (self, forImg=None) :
+ """
+ Returns a [(fname, title)] list of this dir's parent dirs
+ """
+
+ f = self
+ b = []
+ d = 0
+
+ while f :
+ # functionality of the slightly-hacked-in variety
+ if f is self and forImg is not None :
+ url = helpers.url_for_page(self.getPageNumber(forImg))
+ else :
+ url = dirUp(d)
+
+ b.insert(0, (url, f.title))
+
+ d += 1
+ f = f.parent
+
+ return b
+
+ def getPageNumber (self, img) :
+ """
+ Get the page number that the given image is on
+ """
+
+ return self.sorted_images.index(img) // settings.IMAGE_COUNT
+
+ def countParents (self, acc=0) :
+ if self.parent :
+ return self.parent.countParents(acc+1)
+ else :
+ return acc
+
+ def inRoot (self, *fnames) :
+ """
+ Return a relative URL from this dir to the given path in the root dir
+ """
+
+ c = self.countParents()
+
+ return utils.url_join(*((['..']*c) + list(fnames)))
+
+ def render (self) :
+ """
+ Render the index.html, Images, and recurse into subdirs
+ """
+
+ # ded folders are skipped
+ if not self.alive :
+ # dead, skip, no output
+ return
+
+ index_mtime = utils.mtime(self.pathFor("index.html"))
+ dir_mtime = utils.mtime(self.path)
+
+ # if this dir's contents were filtered out, then we can't render the index.html, as we aren't aware of all the images in here
+ if self.filtered :
+ log.warning("Dir `%s' contents were filtered, so we won't render the gallery index again", self.path)
+
+ elif index_mtime > dir_mtime :
+ # no changes, pass, ignored
+ pass
+
+ else :
+ # create the thumb/preview dirs if needed
+ for dir in (settings.THUMB_DIR, settings.PREVIEW_DIR) :
+ path = self.pathFor(dir)
+
+ if not os.path.isdir(path) :
+ log.info("mkdir %s", dir)
+ os.mkdir(path)
+
+ # sort the subdirs
+ subdirs = self.subdirs.values()
+ subdirs.sort(key=lambda d: d.name)
+
+ # paginate!
+ images = self.sorted_images
+ image_count = len(images)
+ pages = []
+
+ while images :
+ pages.append(images[:settings.IMAGE_COUNT])
+ images = images[settings.IMAGE_COUNT:]
+
+ pagination_required = len(pages) > 1
+
+ if pagination_required :
+ log.info("%d pages @ %d images", len(pages), settings.IMAGE_COUNT)
+ elif not pages :
+ log.info("no images, render for subdirs")
+ pages = [[]]
+
+ for cur_page, images in enumerate(pages) :
+ if pagination_required and cur_page > 0 :
+ shorturl = "%s/%s" % (self.shorturl_code, cur_page+1)
+ else :
+ shorturl = self.shorturl_code
+
+ # render to index.html
+ gallery_tpl.render_to(self.pathFor(url_for_page(cur_page)),
+ stylesheet_url = self.inRoot('style.css'),
+ title = self.title,
+ breadcrumb = self.breadcrumb(),
+
+ dirs = subdirs,
+ images = images,
+
+ num_pages = len(pages),
+ cur_page = cur_page,
+
+ description = self.descr,
+
+ shorturl = self.inRoot('s', shorturl),
+ shorturl_code = shorturl,
+ )
+
+ # render images
+ image_count = len(self.sorted_images)
+ for i, img in enumerate(self.images.itervalues()) :
+ log.next("[%-4d/%4d] %s", i + 1, image_count, img.name)
+
+ img.render()
+
+ # recurse into subdirs
+ for dir in self.subdirs.itervalues() :
+ log.down(dir.name)
+
+ dir.render()
+
+ log.up()
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/formatbytes.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,116 @@
+###############################################################
+# Functions taken from pathutils.py Version 0.2.5 (2005/12/06), http://www.voidspace.org.uk/python/recipebook.shtml#utils
+# Copyright Michael Foord 2004
+# Released subject to the BSD License
+# Please see http://www.voidspace.org.uk/python/license.shtml
+
+###############################################################
+# formatbytes takes a filesize (as returned by os.getsize() )
+# and formats it for display in one of two ways !!
+
+# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
+# http://groups.google.com/group/pythonutils/
+# Comments, suggestions and bug reports welcome.
+# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
+# E-mail fuzzyman@voidspace.org.uk
+
+def formatbytes(sizeint, configdict=None, **configs):
+ """
+ Given a file size as an integer, return a nicely formatted string that
+ represents the size. Has various options to control it's output.
+
+ You can pass in a dictionary of arguments or keyword arguments. Keyword
+ arguments override the dictionary and there are sensible defaults for options
+ you don't set.
+
+ Options and defaults are as follows :
+
+ * ``forcekb = False`` - If set this forces the output to be in terms
+ of kilobytes and bytes only.
+
+ * ``largestonly = True`` - If set, instead of outputting
+ ``1 Mbytes, 307 Kbytes, 478 bytes`` it outputs using only the largest
+ denominator - e.g. ``1.3 Mbytes`` or ``17.2 Kbytes``
+
+ * ``kiloname = 'Kbytes'`` - The string to use for kilobytes
+
+ * ``meganame = 'Mbytes'`` - The string to use for Megabytes
+
+ * ``bytename = 'bytes'`` - The string to use for bytes
+
+ * ``nospace = True`` - If set it outputs ``1Mbytes, 307Kbytes``,
+ notice there is no space.
+
+ Example outputs : ::
+
+ 19Mbytes, 75Kbytes, 255bytes
+ 2Kbytes, 0bytes
+ 23.8Mbytes
+
+ .. note::
+
+ It currently uses the plural form even for singular.
+ """
+ defaultconfigs = { 'forcekb' : False,
+ 'largestonly' : True,
+ 'kiloname' : 'Kbytes',
+ 'meganame' : 'Mbytes',
+ 'bytename' : 'bytes',
+ 'nospace' : True}
+ if configdict is None:
+ configdict = {}
+ for entry in configs:
+ # keyword parameters override the dictionary passed in
+ configdict[entry] = configs[entry]
+ #
+ for keyword in defaultconfigs:
+ if not configdict.has_key(keyword):
+ configdict[keyword] = defaultconfigs[keyword]
+ #
+ if configdict['nospace']:
+ space = ''
+ else:
+ space = ' '
+ #
+ mb, kb, rb = bytedivider(sizeint)
+ if configdict['largestonly']:
+ if mb and not configdict['forcekb']:
+ return stringround(mb, kb)+ space + configdict['meganame']
+ elif kb or configdict['forcekb']:
+ if mb and configdict['forcekb']:
+ kb += 1024*mb
+ return stringround(kb, rb) + space+ configdict['kiloname']
+ else:
+ return str(rb) + space + configdict['bytename']
+ else:
+ outstr = ''
+ if mb and not configdict['forcekb']:
+ outstr = str(mb) + space + configdict['meganame'] +', '
+ if kb or configdict['forcekb'] or mb:
+ if configdict['forcekb']:
+ kb += 1024*mb
+ outstr += str(kb) + space + configdict['kiloname'] +', '
+ return outstr + str(rb) + space + configdict['bytename']
+
+def stringround(main, rest):
+ """
+ Given a file size in either (mb, kb) or (kb, bytes) - round it
+ appropriately.
+ """
+ # divide an int by a float... get a float
+ value = main + rest/1024.0
+ return str(round(value, 1))
+
+def bytedivider(nbytes):
+ """
+ Given an integer (probably a long integer returned by os.getsize() )
+ it returns a tuple of (megabytes, kilobytes, bytes).
+
+ This can be more easily converted into a formatted string to display the
+ size of the file.
+ """
+ mb, remainder = divmod(nbytes, 1048576)
+ kb, rb = divmod(remainder, 1024)
+ return (mb, kb, rb)
+
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/helpers.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,34 @@
+import urllib
+from formatbytes import formatbytes
+from datetime import datetime
+
+"""
+ Helper functions for use in templates
+"""
+
+def iter_is_first (seq) :
+ flag = True
+
+ for item in seq :
+ yield item, flag
+ flag = False
+
+def url_for_page (page) :
+ assert page >= 0
+
+ if page > 0 :
+ return 'index_%d.html' % page
+ else :
+ return 'index.html'
+
+def tag_for_img (page, img) :
+ return """<a href="%s"><img src="%s" /></a>""" % (page, img)
+
+def format_filesize (size) :
+ return formatbytes(size, forcekb=False, largestonly=True, kiloname='KiB', meganame='MiB', bytename='B', nospace=False)
+
+def format_timestamp (ts) :
+ return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
+
+def format_imgsize (size) :
+ return "%dx%d" % size
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/image.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,150 @@
+import os, os.path
+
+import PIL.Image
+
+import dexif
+
+import settings, utils, log
+from template import image as image_tpl
+
+"""
+ Handling induvidual Images
+"""
+
+class Image (object) :
+ def __init__ (self, dir, name) :
+ # the image filename, e.g. DSC3948.JPG
+ self.name = unicode(name)
+
+ # the Folder object that we are in
+ self.dir = dir
+
+ # the relative path from the root to us
+ self.path = dir.pathFor(self.name)
+
+ # the basename+ext, e.g. DSCR3948, .JPG
+ self.base_name, self.ext = os.path.splitext(self.name)
+
+ # our user-friendly title
+ self.title = self.name
+
+ # our long-winded description
+ self.descr = ''
+
+ # the image before and after us, both may be None
+ self.prev = self.next = None
+
+ # the image-relative names for the html page, thumb and preview images
+ self.html_name = self.name + ".html"
+ self.thumb_name = utils.url_join(settings.THUMB_DIR, self.name)
+ self.preview_name = utils.url_join(settings.PREVIEW_DIR, self.name)
+
+ # the root-relative paths to the html page, thumb and preview images
+ self.html_path = self.dir.pathFor(self.html_name)
+ self.thumb_path = self.dir.pathFor(settings.THUMB_DIR, self.name)
+ self.preview_path = self.dir.pathFor(settings.PREVIEW_DIR, self.name)
+
+ #
+ # Figured out after prepare
+ #
+
+ # (w, h) tuple
+ self.img_size = None
+
+ # the ShortURL code for this image
+ self.shorturl_code = None
+
+ # EXIF data
+ self.exif_data = {}
+
+ # what to use in the rendered templates, intended to be overridden by subclasses
+ self.series_act = "add"
+ self.series_verb = "Add to"
+
+ def getObjInfo (self) :
+ """
+ Metadata for shorturl2.db
+ """
+ return 'img', self.dir.path, self.name
+
+ def breadcrumb (self) :
+ """
+ Returns a [(fname, title)] list of this image's parents
+ """
+
+ return self.dir.breadcrumb(forImg=self) + [(self.html_name, self.title)]
+
+ def render (self) :
+ """
+ Write out the .html file
+ """
+
+ # stat the image file to get the filesize and mtime
+ st = os.stat(self.path)
+
+ self.filesize = st.st_size
+ self.timestamp = st.st_mtime
+
+ # open the image in PIL to get image attributes + generate thumbnails
+ img = PIL.Image.open(self.path)
+
+ self.img_size = img.size
+
+ for out_path, geom in ((self.thumb_path, settings.THUMB_GEOM), (self.preview_path, settings.PREVIEW_GEOM)) :
+ # if it doesn't exist, or it's older than the image itself, generate
+ if utils.mtime(out_path) < self.timestamp :
+ log.info("render [%sx%s]", geom[0], geom[1], wait=True)
+
+ # XXX: is this the most efficient way to do this? It seems slow
+ out_img = img.copy()
+ out_img.thumbnail(geom, resample=True)
+ out_img.save(out_path)
+
+ log.done()
+
+ # look for the metadata file
+ title_path = self.dir.pathFor(self.base_name + '.txt')
+
+ self.title, self.descr = utils.readTitleDescr(title_path)
+
+ if not self.title :
+ self.title = self.name
+
+ if utils.mtime(self.html_path) < self.timestamp :
+ log.info("render %s.html", self.name)
+
+ # parse the exif data from the file
+ try :
+ self.exif_data = dexif.parse_exif(self.path)
+ except dexif.ExifError, message:
+ log.warning("Reading EXIF data for %s failed: %s" % (self.filename, message))
+ self.exif_data = {}
+
+
+ image_tpl.render_to(self.html_path,
+ stylesheet_url = self.dir.inRoot('style.css'),
+ title = self.title,
+ breadcrumb = self.breadcrumb(),
+
+ prev = self.prev,
+ next = self.next,
+ img = self,
+
+ description = self.descr,
+
+ filename = self.name,
+ img_size = self.img_size,
+ file_size = self.filesize,
+ timestamp = self.timestamp,
+ exif_data = self.exif_data,
+
+ shorturl = self.dir.inRoot('s', self.shorturl_code),
+ shorturl_code = self.shorturl_code,
+
+ series_url = self.dir.inRoot('series/%s/%s' % (self.series_act, self.shorturl_code)),
+ series_verb = self.series_verb,
+ )
+
+ def __str__ (self) :
+ return "Image `%s' in `%s'" % (self.name, self.dir.path)
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/log.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,65 @@
+import logging, sys
+
+"""
+ Fancy tree-structured logging output
+"""
+
+log_level = logging.INFO
+stack = []
+
+class g :
+ out_depth = 0
+ node = None
+
+def title (title, *args) :
+ stack.append(title)
+
+ print "%s - %s" % (" "*g.out_depth, title % args)
+
+ g.out_depth += 1
+
+def down (dir_name, *args) :
+ stack.append(dir_name % args)
+ g.node = None
+
+def next (fname, *args) :
+ g.node = fname % args
+
+def up () :
+ stack.pop(-1)
+ g.node = None
+ g.out_depth = min(g.out_depth, len(stack))
+
+def done () :
+ print "done"
+
+def log (level, message, *args, **kwargs) :
+ wait = kwargs.get("wait", False)
+
+ if level >= log_level :
+ if g.out_depth != len(stack) :
+ for segment in stack[g.out_depth:] :
+ print "%sd %s" % (" "*g.out_depth, segment)
+ g.out_depth += 1
+
+ if g.node :
+ print "%sf %s" % (" "*g.out_depth, g.node)
+ g.node = None
+
+ if wait :
+ print "%s - %s..." % (" "*g.out_depth, message % args),
+ sys.stdout.flush()
+ else :
+ print "%s - %s" % (" "*g.out_depth, message % args)
+
+def _level (level) :
+ def _log_func (message, *args, **kwargs) :
+ log(level, message, *args, **kwargs)
+
+ return _log_func
+
+debug = _level(logging.DEBUG)
+info = _level(logging.INFO)
+warning = _level(logging.WARNING)
+error = _level(logging.ERROR)
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/main.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,35 @@
+"""
+ Main entry point for the command-line interface
+"""
+
+import commands
+
+from optparse import OptionParser
+
+def option_parser (command_name) :
+ """
+ Build the OptionParser that we use
+ """
+
+ # create parser using the given command
+ parser = OptionParser(prog=command_name)
+
+ # define options
+ parser.add_option('-d', "--dir", dest='dir', help="Use DIR as the image/HTML path [default: CWD]", metavar='DIR', default='.')
+
+ return parser
+
+def main (argv) :
+ """
+ Main entry point
+ """
+
+ # build optparser
+ parser = option_parser(argv[0])
+
+ # parse the given argv
+ options, filter_targets = parser.parse_args(argv[1:])
+
+ # run the selected command
+ return commands.main(options.dir, filter_targets)
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/req.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,49 @@
+import cgi
+import Cookie
+import os
+
+"""
+ XXX: legacy CGI crap
+"""
+
+vars = cgi.FieldStorage()
+
+# the cookie with the user's current series
+cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
+
+class token (object) :
+ pass
+
+REQUIRED_PARAM = token()
+
+def get_str (key, default=REQUIRED_PARAM) :
+ if key in vars :
+ return vars[key].value.decode('utf8', 'replace')
+ elif default is REQUIRED_PARAM :
+ raise ValueError("Required param %s" % key)
+ else :
+ return default
+
+def get_str_list (key, default=REQUIRED_PARAM) :
+ if key in vars :
+ return [val.decode('utf8', 'replace') for val in vars.getlist(key)]
+ elif default is REQUIRED_PARAM :
+ raise ValueError("Required param %s" % key)
+ else :
+ return default
+
+def get_int (key, default=REQUIRED_PARAM) :
+ if key in vars :
+ return int(vars[key].value)
+ elif default is REQUIRED_PARAM :
+ raise ValueError("Required param %s" % key)
+ else :
+ return default
+
+def get_int_list (key, default=REQUIRED_PARAM) :
+ if key in vars :
+ return [int(val) for val in vars.getlist(key)]
+ elif default is REQUIRED_PARAM :
+ raise ValueError("Required param %s" % key)
+ else :
+ return default
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/resources.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,10 @@
+"""
+ Resource management
+"""
+
+import pkg_resources
+
+# path to package template files
+TEMPLATE_DIR = pkg_resources.resource_filename('degal', 'templates')
+STATIC_DIR = pkg_resources.resource_filename('degal', 'static')
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/settings.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,25 @@
+
+"""
+ XXX: settings, bad
+"""
+
+TEMPLATE_DIR = './templates'
+TEMPLATE_EXT = 'html'
+
+IMAGE_EXTS = ('jpg', 'jpeg', 'png', 'gif', 'bmp')
+
+THUMB_DIR = 'thumbs'
+PREVIEW_DIR = 'previews'
+TITLE_FILE = 'title.txt'
+
+THUMB_GEOM = (160, 120)
+PREVIEW_GEOM = (640, 480)
+
+DEFAULT_TITLE = 'Image gallery'
+
+# how many image/page
+IMAGE_COUNT = 50
+
+VERSION = "0.5"
+ROOT_IGNORE = ('lib', 'templates')
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/shorturl.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,191 @@
+import struct
+import base64
+import shelve
+import os.path
+
+import utils, db, helpers, folder, image, log
+
+"""
+ Methods for generating/using ShortURLs
+"""
+
+def int2key (id) :
+ """
+ Turn an integer into a short-as-possible url-safe string
+ """
+ for type in ('B', 'H', 'I') :
+ try :
+ return base64.b64encode(struct.pack(type, id), '-_').rstrip('=')
+ except struct.error :
+ continue
+
+ raise Exception("ID overflow: %s" % id)
+
+def key2int (key) :
+ # base64 ignores extra padding, but if it doesn't, it's (4 - len%4), if len%4 != 0
+ # and it breaks on unicode strings
+ bytes = base64.b64decode(str(key + '='*6), '-_')
+
+ type = {
+ 1: 'B',
+ 2: 'H',
+ 4: 'I',
+ }[len(bytes)]
+
+ return struct.unpack(type, bytes)[0]
+
+class DB (object) :
+ def __init__ (self, read_only=True) :
+ self.db = shelve.open('shorturls2', read_only and 'r' or 'c')
+
+ def html_path (self, key, index) :
+ type, dirpath, fname = self.db[key]
+
+ if type == 'img' :
+ fname += '.html'
+ elif type == 'dir' :
+ fname = ''
+
+ if index :
+ dirpath = '../%s' % dirpath
+
+ if type == 'dir' and index > 1 :
+ fname = 'index_%s.html' % (index - 1)
+
+ return os.path.join(dirpath, fname)
+
+ def image_info (self, key) :
+ type, dirpath, fname = self.db[key]
+
+ if type != 'img' :
+ raise ValueError("%s is not an img" % key)
+
+ return dirpath, fname
+
+ def shorturls_for (self, paths) :
+ ret = []
+
+ for key in self.db.keys() :
+ if key.startswith('_') :
+ continue
+
+ type, dir, fname = self.db[key]
+ path = os.path.join(dir.lstrip('.').lstrip('/'), fname)
+ if path in paths :
+ ret.append(key)
+ paths.remove(path)
+
+ if paths :
+ raise ValueError("Paths not found: %s" % " ".join(paths))
+
+ return ret
+
+def html_path (key, index=None) :
+ dir, fname = node_info(key)
+
+ if fname :
+ return utils.url(dir, fname + '.html')
+ else :
+ return utils.url(dir, helpers.url_for_page(index or 0))
+
+def node_info (key) :
+ res = db.select("""SELECT dirpath, filename FROM nodes WHERE id=?""", key2int(key)).fetchone()
+
+ if res :
+ return res
+
+ else :
+ raise KeyError(key)
+
+def image_info (key) :
+ res = db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone()
+
+ if res :
+ return res
+
+ else :
+ raise KeyError(key)
+
+def get_images (keys) :
+ res = [db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone() for key in keys]
+
+ # don't mind if we don't get as many as we asked for?
+ if res :
+ return res
+
+ else :
+ raise KeyError(keys)
+
+def _got_obj_key (obj, id) :
+ key = int2key(id)
+
+ obj.shorturl_code = key
+
+ if isinstance(obj, folder.Folder) :
+ dir, fname = utils.strip_path(obj.path), ''
+ elif isinstance(obj, image.Image) :
+ dir, fname = utils.strip_path(obj.dir.path), obj.name
+ else :
+ assert(False, "%r %r" % (obj, id))
+
+ log.info("%6s -> %s/%s", key, dir, fname)
+
+def updateDB (root) :
+ """
+ Update the SQL database
+
+ type - one of 'img', 'dir'
+ dirpath - the path to the directory, e.g. '.', './foobar', './foobar/quux'
+ fname - the filename, one of '', 'DSC9839.JPG', 'this.png', etc.
+ """
+
+ dirqueue = [root]
+
+ # dict of (dir, fname) -> obj
+ paths = {}
+
+ while dirqueue :
+ dir = dirqueue.pop(0)
+
+ dirqueue.extend(dir.subdirs.itervalues())
+
+ if dir.alive :
+ pathtuple = (utils.strip_path(dir.path), '')
+
+ log.debug("dir %50s", pathtuple[0])
+
+ paths[pathtuple] = dir
+
+ for img in dir.images.itervalues() :
+ pathtuple = (utils.strip_path(img.dir.path), img.name)
+
+ log.debug("img %50s %15s", *pathtuple)
+
+ paths[pathtuple] = img
+
+ log.info("we have %d nodes", len(paths))
+
+ for (id, dir, fname) in db.select("SELECT id, dirpath, filename FROM nodes") :
+ try :
+ obj = paths.pop((dir, fname))
+ key = int2key(id)
+
+ obj.shorturl_code = key
+
+ log.debug("%s %50s %15s -> %d %s", dir and "img" or "dir", dir, fname, id, key)
+
+ except KeyError :
+ pass
+# log.warning("non-existant node (%d, %s, %s) in db", id, dir, fname)
+
+ if paths :
+ log.info("allocating shorturls for %d new nodes:", len(paths))
+
+ db.insert_many(
+ _got_obj_key,
+ "INSERT INTO nodes (dirpath, filename) VALUES (?, ?)",
+ ((obj, (path, fname)) for ((path, fname), obj) in paths.iteritems())
+ )
+ else :
+ log.info("no new images")
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/static/style.css Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,92 @@
+body {
+ background-color: #333333;
+ color: #cccccc;
+ font-family: "Arial", sans-serif;
+ font-size: small;
+}
+
+a, span.dragged {
+ color: #ff8800;
+ text-decoration: none;
+}
+
+a:hover {
+ text-decoration: underline;
+}
+
+#thumbnails, #image, #description, h1 {
+ text-align: center;
+}
+
+#thumbnails img {
+ margin: 0.2em;
+}
+
+img {
+ border: 1px solid #666666;
+}
+
+a:focus img {
+ border: 1px solid #cccccc;
+}
+
+img:hover, a:focus img:hover {
+ border: 1px solid #ff8800;
+}
+
+div#breadcrumb {
+
+}
+
+div#info {
+ font-size: x-small;
+ color: #666666;
+}
+
+div#info p {
+ padding: 0px;
+ margin: 0px;
+}
+
+p#about {
+ padding-top: 40px;
+ font-size: xx-small;
+ text-align: center;
+
+}
+
+div.paginate {
+ padding-top: 20px;
+ height: 50px;
+ width: 100%;
+ text-align: center;
+}
+
+div.paginate ul {
+ margin: 0px;
+ padding: 0px;
+
+ line-height: 30px;
+ white-space: nowrap;
+}
+
+div.paginate li {
+ list-style-type: none;
+ display: inline;
+}
+
+div.paginate li *,
+div.paginate li strong,
+div.paginate li span {
+ padding: 7px 10px;
+}
+
+div.paginate li span {
+ color: #444444;
+}
+
+div.paginate li a:hover {
+ text-decoration: none;
+ background-color: #666666;
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/template.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,49 @@
+from mako import exceptions
+from mako.lookup import TemplateLookup
+
+import settings, resources, helpers
+
+import log
+
+"""
+ Locating and rendering templates
+"""
+
+_lookup = TemplateLookup(
+ directories=[resources.TEMPLATE_DIR],
+# module_directory='%s/cache' % settings.TEMPLATE_DIR,
+ output_encoding='utf-8',
+ filesystem_checks=False, # this may need to be changed if used in a long-term process
+)
+
+TEMPLATE_GLOBALS = dict(
+ h = helpers,
+ version = settings.VERSION,
+)
+
+class Template (object) :
+ def __init__ (self, name) :
+ self.name = name
+ self.tpl = _lookup.get_template("%s.%s" % (name, settings.TEMPLATE_EXT))
+
+ def render (self, **data) :
+ data.update(TEMPLATE_GLOBALS)
+
+ try :
+ log.debug("render %s with %s", self.name, data)
+ return self.tpl.render(**data)
+ except :
+ data = exceptions.text_error_template().render()
+ log.error(data)
+
+ raise
+
+ def render_to (self, file, **data) :
+ fh = open(file, "w")
+ fh.write(self.render(**data))
+ fh.close()
+
+# templates
+gallery = Template("gallery")
+image = Template("image")
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/templates/gallery.html Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,59 @@
+<%! use_javascript = False %>
+<%inherit file="master.html" /> <!-- %> -->
+
+<%def name="pagination(num_pages, cur_page)"> <!-- %> -->
+% if num_pages > 1 :
+ <ul>
+
+% if cur_page > 0 :
+ <li><a href="${h.url_for_page(cur_page - 1)}">« Prev</a></li>
+% else :
+ <li><span>« Prev</span></li>
+% endif
+
+% for page in xrange(0, num_pages) :
+% if page == cur_page :
+ <li><strong>${page + 1}</strong></li>
+% else :
+ <li><a href="${h.url_for_page(page)}">${page + 1}</a></li>
+% endif
+% endfor
+
+% if cur_page < num_pages - 1 :
+ <li><a href="${h.url_for_page(cur_page + 1)}">Next »</a></li>
+% else :
+ <li><span>Next »</span></li>
+% endif
+ </ul>
+% endif
+</%def> <!-- %> -->
+
+ <h1>${title}</h1>
+ <div id="dirs">
+% if dirs :
+ <ul>
+% for dir in dirs :
+ <li><a href="${dir.name}">${dir.title}</a></li>
+% endfor
+ </ul>
+% endif
+ </div>
+ <div class="paginate">
+${pagination(num_pages, cur_page)}
+ </div>
+ <div id="thumbnails">
+% for img in images :
+ ${h.tag_for_img(img.html_name, img.thumb_name)}
+% endfor
+ </div>
+ <div class="paginate">
+${pagination(num_pages, cur_page)}
+ </div>
+ <p id="description">
+${description}
+ </p>
+% if shorturl :
+ <div id="info">
+ <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
+ </div>
+% endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/templates/image.html Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,36 @@
+<%! use_javascript = False %>
+<%inherit file="master.html" /> <!-- %> -->
+
+ <div id="image">
+ <h1>${title}</h1>
+ <p>
+% if prev :
+ ${h.tag_for_img(prev.html_name, prev.thumb_name)}
+% endif
+
+ ${h.tag_for_img(img.name, img.preview_name)}
+
+% if next :
+ ${h.tag_for_img(next.html_name, next.thumb_name)}
+% endif
+ </p>
+ <p>
+ ${description}
+ </p>
+ </div>
+ <div id="info">
+% if img_size and file_size and timestamp :
+ <p>File name: ${filename}</p>
+ <p>Dimensions: ${h.format_imgsize(img_size)}</p>
+ <p>File size: ${h.format_filesize(file_size)}</p>
+ <p>Last modified: ${h.format_timestamp(timestamp)}</p>
+% for key, value in exif_data :
+ <p>${key}: ${value}</p>
+% endfor
+
+% endif
+ <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
+% if series_url :
+ <p><a href="${series_url}" rel="nofollow">${series_verb}</a> series</p>
+% endif
+ </div>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/templates/master.html Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
+ "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head>
+ <title>${title}</title>
+ <link rel="Stylesheet" type="text/css" href="${stylesheet_url}" />
+% if self.module.use_javascript :
+ <script type="text/javascript" src="../javascript/prototype.js" />
+ <script type="text/javascript" src="../javascript/scriptaculous.js" />
+ <script type="text/javascript" src="../javascript/taggr.js" />
+% endif
+ </head>
+ <body>
+ <div id="breadcrumb">
+% for (( bc_url, bc_title), is_first) in h.iter_is_first(breadcrumb) :
+% if not is_first :
+ »
+% endif
+ <a href="${bc_url}">${bc_title}</a>
+% endfor
+ </div>
+ ${next.body()}
+ <p id="about"><a href="http://marttila.de/~terom/degal/">DeGAL</a> ${version}</p>
+ </body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/degal/utils.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,73 @@
+import os, os.path
+
+import settings
+
+"""
+ Miscellaneous utilities
+"""
+
+def isImage (fname) :
+ """
+ Is the given filename likely to be an image file?
+ """
+
+ fname = fname.lower()
+ base, ext = os.path.splitext(fname)
+ ext = ext.lstrip('.')
+
+ return ext in settings.IMAGE_EXTS
+
+def readFile (path) :
+ fo = open(path, 'r')
+ data = fo.read()
+ fo.close()
+
+ return data
+
+def fuzzyDecode (bytes) :
+ try :
+ return bytes.decode('utf8')
+ except UnicodeDecodeError :
+ return bytes.decode('latin1', 'replace')
+
+def readTitleDescr (path) :
+ """
+ Read a title.txt or <imgname>.txt file
+ """
+
+ if os.path.exists(path) :
+ content = readFile(path)
+
+ if '---' in content :
+ title, descr = content.split('---', 1)
+ else :
+ title, descr = content, ''
+
+ title, descr = fuzzyDecode(title), fuzzyDecode(descr)
+
+ return title.strip(), descr.strip()
+
+ return u"", u""
+
+def url (*parts, **kwargs) :
+ abs = kwargs.pop('abs', False)
+ up = kwargs.pop('up', 0)
+ trailing = kwargs.pop('trailing', False)
+
+ return '/'.join(([""]*int(abs)) + ([".."]*up) + list(parts) + ([""]*int(trailing)))
+
+url_join = url
+
+def path_join (*parts) :
+ return os.path.join(*[part for part in parts if part is not None])
+
+def strip_path (path) :
+ return path.lstrip('.').lstrip('/')
+
+def mtime (path) :
+ try :
+ return os.stat(path).st_mtime
+ except OSError :
+ # no such file or directory
+ return None
+
--- a/detool Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-#!/usr/bin/env python2.4
-#
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-from lib import settings
-from lib.log import misc as log
-from lib.utils import path_join
-import os, os.path, logging
-
-def move (options, args) :
- if len(args) < 2 :
- raise Exception("Must give one or more source files, and a destination dir")
-
- dest = args.pop(-1)
- srcs = args
-
- if not os.path.isdir(dest) :
- raise Exception("Given destination '%s' is not a directory" % dest)
-
- for subdir in (settings.THUMB_DIR, settings.PREVIEW_DIR) :
- path = os.path.join(dest, subdir)
-
- if not os.path.exists(path) :
- log.info("mkdir %s" % path)
- os.mkdir(path)
-
- for src in srcs :
- if not os.path.isfile(src) :
- raise Exception("Given source file '%s' is not a valid file" % src)
-
- for (pre, post) in (
- (None, None),
- (settings.THUMB_DIR, None),
- (settings.PREVIEW_DIR, None),
- (None, '.html'),
- ) :
- dir, fname = os.path.split(src)
-
- if post :
- fname += post
-
- src_path = path_join(dir, pre, fname)
- dst_path = path_join(dest, pre, fname)
-
- if os.path.isfile(src_path) :
- if not options.overwite and os.path.exists(dst_path) :
- log.warning("%s exists; skipping %s" % (dst_path, src_path))
- log.info("%s -> %s" % (src_path, dst_path))
- os.rename(src_path, dst_path)
-
-def help (options, args) :
- print "Available commands:"
-
- for name, func in COMMANDS.iteritems() :
- print "\t%s" % name
-
-COMMANDS = dict(
- move = move,
- mv = move,
- help = help,
-)
-
-if __name__ == '__main__' :
- from optparse import OptionParser
-
- parser = OptionParser(usage="usage: %prog <command> [options] [args ...]", version=settings.VERSION)
-
- parser.add_option("-q", "--quiet", dest="verbose", default=True)
- parser.add_option("-i", "--careful", dest="overwrite", help="Do not overwrite files", default=True)
-
- options, args = parser.parse_args()
-
- if options.verbose :
- log.setLevel(logging.INFO)
- else :
- log.setLevel(logging.ERROR)
-
- if not args :
- parser.error("Must supply a command. See `detool.py help` for a list of commands")
-
- command = args.pop(0).lower()
-
- if command not in COMMANDS :
- parser.error("Unknown command '%s'. Try `detool.py help`" % command)
-
- func = COMMANDS[command]
-
- func(options, args)
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/db.sql Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,5 @@
+CREATE TABLE 'nodes' (id INTEGER NOT NULL PRIMARY KEY, dirpath TEXT NOT NULL, filename TEXT NOT NULL);
+CREATE TABLE tags (image INTEGER NOT NULL, type TEXT, tag TEXT NOT NULL);
+CREATE VIEW images AS SELECT id, dirpath, filename FROM nodes WHERE filename != '';
+CREATE UNIQUE INDEX tags_unique_image_type ON tags (image, type);
+CREATE UNIQUE INDEX tags_unique_image_type_tag ON tags (image, type, tag);
--- a/lib/db.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import sqlite3
-
-conn = sqlite3.connect("db/degal.db")
-
-def execute (expr, *args) :
- c = conn.cursor()
- c.execute(expr, args)
-
- return c
-
-def execute_many (expr, iter) :
- c = conn.cursor()
- c.executemany(expr, iter)
-
- return c
-
-def insert (expr, *args) :
- return execute_commit(expr, *args).lastrowid
-
-def insert_many (cb, expr, iter) :
- """
- Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id)
- """
-
- c = conn.cursor()
-
- c.executemany(expr, _lastrowid_adapter(c, iter, cb))
-
- return commit(c)
-
-def _lastrowid_adapter (c, iter, cb) :
- for val, args in iter :
- yield args
-
- cb(val, c.lastrowid)
-
-def commit (cursor) :
- try :
- cursor.execute("COMMIT")
- except sqlite3.OperationalError :
- pass # ffs. INSERT just doesn't do anything otherwise
-
- return cursor
-
-def execute_commit (expr, *args) :
- return commit(execute(expr, *args))
-
-def execute_commit_many (expr, iter) :
- return commit(execute_many(expr, iter))
-
-select = execute
-
-delete = execute_commit
-
-delete_many = execute_commit_many
-
-cursor = conn.cursor
-
--- a/lib/dexif.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-#
-# dexif.py - simple EXIF processing for Degal
-# Copyright (C) 2008, Santtu Pajukanta <santtu@pajukanta.fi>
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-from subprocess import Popen, PIPE
-
-# TODO This should be user configurable
-EXIFTOOL="/usr/bin/exiftool"
-
-outputTags = [
-# TODO Create date is in a useless format, needs some strptime love
- ("CreateDate", "Create date"),
- ("Model", "Camera model"),
- ("Aperture", "Aperture"),
- ("ExposureMode", "Exposure mode"),
- ("ExposureCompensation", "Exposure compensation"),
- ("ExposureTime", "Exposure time"),
- ("Flash", "Flash mode"),
- ("ISO", "ISO"),
- ("ShootingMode", "Shooting mode"),
- ("LensType", "Lens type"),
- ("FocalLength", "Focal length")
-]
-
-
-class ExifError(Exception):
- pass
-
-def parse_exif(filepath):
- """parse_exif(filepath :: String) -> [(String, String)]
-
- Parse EXIF tags from an image file and return them in a dict.
- """
-
- args = [EXIFTOOL, "-s", "-t", filepath]
- etproc = Popen(args, stdout = PIPE)
-
- output, errors = etproc.communicate()
-
- if etproc.returncode < 0:
- raise ExifError, "exiftool terminated by signal %d" % (-etproc.returnco)
- elif etproc.returncode > 0:
- raise ExifError, "exiftool failed with return code %d" % etproc.returncode
-
- tags = dict(line.split("\t", 1) for line in output.split("\n") if line)
- result = [(descr, tags[key]) for (key, descr) in outputTags if tags.has_key(key)]
- return result
--- a/lib/folder.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,329 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import os, os.path
-
-import settings, image, utils, helpers, log
-from template import gallery as gallery_tpl
-from helpers import url_for_page
-
-def dirUp (count=1) :
- """
- Returns a relative path to the directly count levels above the current one
- """
-
- if not count :
- return '.'
-
- return os.path.join(*(['..']*count))
-
-class Folder (object) :
- def __init__ (self, name='.', parent=None) :
- # the directory name, no trailing /
- self.name = unicode(name.rstrip(os.sep))
-
- # our parent Folder, or None
- self.parent = parent
-
- # the path to this dir, as a relative path to the root of the image gallery, always starts with .
- if parent and name :
- self.path = parent.pathFor(self.name)
- else :
- self.path = self.name
-
- # the url-path to the index.html file
- self.html_path = self.path
-
- # dict of fname -> Folder
- self.subdirs = {}
-
- # dict of fname -> Image
- self.images = {}
-
- # our human-friendly title
- self.title = None
-
- # our long-winded description
- self.descr = ''
-
- # is this folder non-empty?
- self.alive = None
-
- # self.images.values(), but sorted by filename
- self.sorted_images = []
-
- # the ShortURL key to this dir
- self.shorturl_code = None
-
- # were we filtered out?
- self.filtered = False
-
- def pathFor (self, *fnames) :
- """
- Return a root-relative path to the given path inside this dir
- """
- return os.path.join(self.path, *fnames)
-
- def index (self, filters=None) :
- """
- Look for other dirs and images inside this dir. Filters must be either None,
- whereupon all files will be included, or a dict of {filename -> next_filter}.
- If given, only filenames that are present in the dict will be indexed, and in
- the case of dirs, the next_filter will be passed on to that Folder's index
- method.
- """
-
- if filters :
- self.filtered = True
-
- # iterate through listdir
- for fname in os.listdir(self.path) :
- # the full filesystem path to it
- fpath = self.pathFor(fname)
-
- # ignore dotfiles
- if fname.startswith('.') :
- log.debug("Skipping dotfile %s", fname)
- continue
-
- # apply filters
- if filters :
- if fname in filters :
- next_filter = filters[fname]
- else :
- log.debug("Skip `%s' as we have a filter", fname)
- continue
- else :
- next_filter = None
-
- # recurse into subdirs, but not thumbs/previews
- if (os.path.isdir(fpath)
- and (fname not in (settings.THUMB_DIR, settings.PREVIEW_DIR))
- and (self.parent or fname not in settings.ROOT_IGNORE)
- ) :
- log.down(fname)
-
- f = Folder(fname, self)
-
- try :
- if f.index(next_filter) : # recursion
- # if a subdir is alive, we are alive as well
- self.subdirs[fname] = f
- self.alive = True
- except Exception, e :
- log.warning("skip - %s: %s" % (type(e), e))
-
- log.up()
-
- # handle images
- elif os.path.isfile(fpath) and utils.isImage(fname) :
- log.next(fname)
- self.images[fname] = image.Image(self, fname)
-
- # ignore everything else
- else :
- log.debug("Ignoring file %s", fname)
-
- # sort and link the images
- if self.images :
- self.alive = True
-
- # sort the images
- fnames = self.images.keys()
- fnames.sort()
-
- prev = None
-
- # link
- for fname in fnames :
- img = self.images[fname]
-
- img.prev = prev
-
- if prev :
- prev.next = img
-
- prev = img
-
- # add to the sorted images list
- self.sorted_images.append(img)
-
- # figure out our title/ descr. Must be done before our parent dir is rendered (self.title)
- title_path = self.pathFor(settings.TITLE_FILE)
-
- self.title, self.descr = utils.readTitleDescr(title_path)
-
- # default title for the root dir
- if self.title or self.descr :
- self.alive = True
- pass # use what was in the title file
-
- elif not self.parent :
- self.title = 'Index'
-
- else :
- self.title = self.name
-
- if not self.alive :
- log.debug("Dir %s isn't alive" % self.path)
-
- return self.alive
-
- def getObjInfo (self) :
- """
- Metadata for shorturls2.db
- """
- return 'dir', self.path, ''
-
- def breadcrumb (self, forImg=None) :
- """
- Returns a [(fname, title)] list of this dir's parent dirs
- """
-
- f = self
- b = []
- d = 0
-
- while f :
- # functionality of the slightly-hacked-in variety
- if f is self and forImg is not None :
- url = helpers.url_for_page(self.getPageNumber(forImg))
- else :
- url = dirUp(d)
-
- b.insert(0, (url, f.title))
-
- d += 1
- f = f.parent
-
- return b
-
- def getPageNumber (self, img) :
- """
- Get the page number that the given image is on
- """
-
- return self.sorted_images.index(img) // settings.IMAGE_COUNT
-
- def countParents (self, acc=0) :
- if self.parent :
- return self.parent.countParents(acc+1)
- else :
- return acc
-
- def inRoot (self, *fnames) :
- """
- Return a relative URL from this dir to the given path in the root dir
- """
-
- c = self.countParents()
-
- return utils.url_join(*((['..']*c) + list(fnames)))
-
- def render (self) :
- """
- Render the index.html, Images, and recurse into subdirs
- """
-
- # ded folders are skipped
- if not self.alive :
- # dead, skip, no output
- return
-
- index_mtime = utils.mtime(self.pathFor("index.html"))
- dir_mtime = utils.mtime(self.path)
-
- # if this dir's contents were filtered out, then we can't render the index.html, as we aren't aware of all the images in here
- if self.filtered :
- log.warning("Dir `%s' contents were filtered, so we won't render the gallery index again", self.path)
-
- elif index_mtime > dir_mtime :
- # no changes, pass, ignored
- pass
-
- else :
- # create the thumb/preview dirs if needed
- for dir in (settings.THUMB_DIR, settings.PREVIEW_DIR) :
- path = self.pathFor(dir)
-
- if not os.path.isdir(path) :
- log.info("mkdir %s", dir)
- os.mkdir(path)
-
- # sort the subdirs
- subdirs = self.subdirs.values()
- subdirs.sort(key=lambda d: d.name)
-
- # paginate!
- images = self.sorted_images
- image_count = len(images)
- pages = []
-
- while images :
- pages.append(images[:settings.IMAGE_COUNT])
- images = images[settings.IMAGE_COUNT:]
-
- pagination_required = len(pages) > 1
-
- if pagination_required :
- log.info("%d pages @ %d images", len(pages), settings.IMAGE_COUNT)
- elif not pages :
- log.info("no images, render for subdirs")
- pages = [[]]
-
- for cur_page, images in enumerate(pages) :
- if pagination_required and cur_page > 0 :
- shorturl = "%s/%s" % (self.shorturl_code, cur_page+1)
- else :
- shorturl = self.shorturl_code
-
- # render to index.html
- gallery_tpl.render_to(self.pathFor(url_for_page(cur_page)),
- stylesheet_url = self.inRoot('style.css'),
- title = self.title,
- breadcrumb = self.breadcrumb(),
-
- dirs = subdirs,
- images = images,
-
- num_pages = len(pages),
- cur_page = cur_page,
-
- description = self.descr,
-
- shorturl = self.inRoot('s', shorturl),
- shorturl_code = shorturl,
- )
-
- # render images
- image_count = len(self.sorted_images)
- for i, img in enumerate(self.images.itervalues()) :
- log.next("[%-4d/%4d] %s", i + 1, image_count, img.name)
-
- img.render()
-
- # recurse into subdirs
- for dir in self.subdirs.itervalues() :
- log.down(dir.name)
-
- dir.render()
-
- log.up()
-
--- a/lib/formatbytes.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,116 +0,0 @@
-###############################################################
-# Functions taken from pathutils.py Version 0.2.5 (2005/12/06), http://www.voidspace.org.uk/python/recipebook.shtml#utils
-# Copyright Michael Foord 2004
-# Released subject to the BSD License
-# Please see http://www.voidspace.org.uk/python/license.shtml
-
-###############################################################
-# formatbytes takes a filesize (as returned by os.getsize() )
-# and formats it for display in one of two ways !!
-
-# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
-# http://groups.google.com/group/pythonutils/
-# Comments, suggestions and bug reports welcome.
-# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
-# E-mail fuzzyman@voidspace.org.uk
-
-def formatbytes(sizeint, configdict=None, **configs):
- """
- Given a file size as an integer, return a nicely formatted string that
- represents the size. Has various options to control it's output.
-
- You can pass in a dictionary of arguments or keyword arguments. Keyword
- arguments override the dictionary and there are sensible defaults for options
- you don't set.
-
- Options and defaults are as follows :
-
- * ``forcekb = False`` - If set this forces the output to be in terms
- of kilobytes and bytes only.
-
- * ``largestonly = True`` - If set, instead of outputting
- ``1 Mbytes, 307 Kbytes, 478 bytes`` it outputs using only the largest
- denominator - e.g. ``1.3 Mbytes`` or ``17.2 Kbytes``
-
- * ``kiloname = 'Kbytes'`` - The string to use for kilobytes
-
- * ``meganame = 'Mbytes'`` - The string to use for Megabytes
-
- * ``bytename = 'bytes'`` - The string to use for bytes
-
- * ``nospace = True`` - If set it outputs ``1Mbytes, 307Kbytes``,
- notice there is no space.
-
- Example outputs : ::
-
- 19Mbytes, 75Kbytes, 255bytes
- 2Kbytes, 0bytes
- 23.8Mbytes
-
- .. note::
-
- It currently uses the plural form even for singular.
- """
- defaultconfigs = { 'forcekb' : False,
- 'largestonly' : True,
- 'kiloname' : 'Kbytes',
- 'meganame' : 'Mbytes',
- 'bytename' : 'bytes',
- 'nospace' : True}
- if configdict is None:
- configdict = {}
- for entry in configs:
- # keyword parameters override the dictionary passed in
- configdict[entry] = configs[entry]
- #
- for keyword in defaultconfigs:
- if not configdict.has_key(keyword):
- configdict[keyword] = defaultconfigs[keyword]
- #
- if configdict['nospace']:
- space = ''
- else:
- space = ' '
- #
- mb, kb, rb = bytedivider(sizeint)
- if configdict['largestonly']:
- if mb and not configdict['forcekb']:
- return stringround(mb, kb)+ space + configdict['meganame']
- elif kb or configdict['forcekb']:
- if mb and configdict['forcekb']:
- kb += 1024*mb
- return stringround(kb, rb) + space+ configdict['kiloname']
- else:
- return str(rb) + space + configdict['bytename']
- else:
- outstr = ''
- if mb and not configdict['forcekb']:
- outstr = str(mb) + space + configdict['meganame'] +', '
- if kb or configdict['forcekb'] or mb:
- if configdict['forcekb']:
- kb += 1024*mb
- outstr += str(kb) + space + configdict['kiloname'] +', '
- return outstr + str(rb) + space + configdict['bytename']
-
-def stringround(main, rest):
- """
- Given a file size in either (mb, kb) or (kb, bytes) - round it
- appropriately.
- """
- # divide an int by a float... get a float
- value = main + rest/1024.0
- return str(round(value, 1))
-
-def bytedivider(nbytes):
- """
- Given an integer (probably a long integer returned by os.getsize() )
- it returns a tuple of (megabytes, kilobytes, bytes).
-
- This can be more easily converted into a formatted string to display the
- size of the file.
- """
- mb, remainder = divmod(nbytes, 1048576)
- kb, rb = divmod(remainder, 1024)
- return (mb, kb, rb)
-
-
--- a/lib/helpers.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-# template helper functions
-import urllib
-from formatbytes import formatbytes
-from datetime import datetime
-
-def iter_is_first (seq) :
- flag = True
-
- for item in seq :
- yield item, flag
- flag = False
-
-def url_for_page (page) :
- assert page >= 0
-
- if page > 0 :
- return 'index_%d.html' % page
- else :
- return 'index.html'
-
-def tag_for_img (page, img) :
- return """<a href="%s"><img src="%s" /></a>""" % (page, img)
-
-def format_filesize (size) :
- return formatbytes(size, forcekb=False, largestonly=True, kiloname='KiB', meganame='MiB', bytename='B', nospace=False)
-
-def format_timestamp (ts) :
- return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
-
-def format_imgsize (size) :
- return "%dx%d" % size
--- a/lib/image.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,166 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import os, os.path
-
-import PIL.Image
-
-import dexif
-
-import settings, utils, log
-from template import image as image_tpl
-
-class Image (object) :
- def __init__ (self, dir, name) :
- # the image filename, e.g. DSC3948.JPG
- self.name = unicode(name)
-
- # the Folder object that we are in
- self.dir = dir
-
- # the relative path from the root to us
- self.path = dir.pathFor(self.name)
-
- # the basename+ext, e.g. DSCR3948, .JPG
- self.base_name, self.ext = os.path.splitext(self.name)
-
- # our user-friendly title
- self.title = self.name
-
- # our long-winded description
- self.descr = ''
-
- # the image before and after us, both may be None
- self.prev = self.next = None
-
- # the image-relative names for the html page, thumb and preview images
- self.html_name = self.name + ".html"
- self.thumb_name = utils.url_join(settings.THUMB_DIR, self.name)
- self.preview_name = utils.url_join(settings.PREVIEW_DIR, self.name)
-
- # the root-relative paths to the html page, thumb and preview images
- self.html_path = self.dir.pathFor(self.html_name)
- self.thumb_path = self.dir.pathFor(settings.THUMB_DIR, self.name)
- self.preview_path = self.dir.pathFor(settings.PREVIEW_DIR, self.name)
-
- #
- # Figured out after prepare
- #
-
- # (w, h) tuple
- self.img_size = None
-
- # the ShortURL code for this image
- self.shorturl_code = None
-
- # EXIF data
- self.exif_data = {}
-
- # what to use in the rendered templates, intended to be overridden by subclasses
- self.series_act = "add"
- self.series_verb = "Add to"
-
- def getObjInfo (self) :
- """
- Metadata for shorturl2.db
- """
- return 'img', self.dir.path, self.name
-
- def breadcrumb (self) :
- """
- Returns a [(fname, title)] list of this image's parents
- """
-
- return self.dir.breadcrumb(forImg=self) + [(self.html_name, self.title)]
-
- def render (self) :
- """
- Write out the .html file
- """
-
- # stat the image file to get the filesize and mtime
- st = os.stat(self.path)
-
- self.filesize = st.st_size
- self.timestamp = st.st_mtime
-
- # open the image in PIL to get image attributes + generate thumbnails
- img = PIL.Image.open(self.path)
-
- self.img_size = img.size
-
- for out_path, geom in ((self.thumb_path, settings.THUMB_GEOM), (self.preview_path, settings.PREVIEW_GEOM)) :
- # if it doesn't exist, or it's older than the image itself, generate
- if utils.mtime(out_path) < self.timestamp :
- log.info("render [%sx%s]", geom[0], geom[1], wait=True)
-
- # XXX: is this the most efficient way to do this? It seems slow
- out_img = img.copy()
- out_img.thumbnail(geom, resample=True)
- out_img.save(out_path)
-
- log.done()
-
- # look for the metadata file
- title_path = self.dir.pathFor(self.base_name + '.txt')
-
- self.title, self.descr = utils.readTitleDescr(title_path)
-
- if not self.title :
- self.title = self.name
-
- if utils.mtime(self.html_path) < self.timestamp :
- log.info("render %s.html", self.name)
-
- # parse the exif data from the file
- try :
- self.exif_data = dexif.parse_exif(self.path)
- except dexif.ExifError, message:
- log.warning("Reading EXIF data for %s failed: %s" % (self.filename, message))
- self.exif_data = {}
-
-
- image_tpl.render_to(self.html_path,
- stylesheet_url = self.dir.inRoot('style.css'),
- title = self.title,
- breadcrumb = self.breadcrumb(),
-
- prev = self.prev,
- next = self.next,
- img = self,
-
- description = self.descr,
-
- filename = self.name,
- img_size = self.img_size,
- file_size = self.filesize,
- timestamp = self.timestamp,
- exif_data = self.exif_data,
-
- shorturl = self.dir.inRoot('s', self.shorturl_code),
- shorturl_code = self.shorturl_code,
-
- series_url = self.dir.inRoot('series/%s/%s' % (self.series_act, self.shorturl_code)),
- series_verb = self.series_verb,
- )
-
- def __str__ (self) :
- return "Image `%s' in `%s'" % (self.name, self.dir.path)
-
--- a/lib/log.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,81 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import logging, sys
-
-log_level = logging.INFO
-stack = []
-
-class g :
- out_depth = 0
- node = None
-
-def title (title, *args) :
- stack.append(title)
-
- print "%s - %s" % (" "*g.out_depth, title % args)
-
- g.out_depth += 1
-
-def down (dir_name, *args) :
- stack.append(dir_name % args)
- g.node = None
-
-def next (fname, *args) :
- g.node = fname % args
-
-def up () :
- stack.pop(-1)
- g.node = None
- g.out_depth = min(g.out_depth, len(stack))
-
-def done () :
- print "done"
-
-def log (level, message, *args, **kwargs) :
- wait = kwargs.get("wait", False)
-
- if level >= log_level :
- if g.out_depth != len(stack) :
- for segment in stack[g.out_depth:] :
- print "%sd %s" % (" "*g.out_depth, segment)
- g.out_depth += 1
-
- if g.node :
- print "%sf %s" % (" "*g.out_depth, g.node)
- g.node = None
-
- if wait :
- print "%s - %s..." % (" "*g.out_depth, message % args),
- sys.stdout.flush()
- else :
- print "%s - %s" % (" "*g.out_depth, message % args)
-
-def _level (level) :
- def _log_func (message, *args, **kwargs) :
- log(level, message, *args, **kwargs)
-
- return _log_func
-
-debug = _level(logging.DEBUG)
-info = _level(logging.INFO)
-warning = _level(logging.WARNING)
-error = _level(logging.ERROR)
-
--- a/lib/req.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import cgi
-import Cookie
-import os
-
-vars = cgi.FieldStorage()
-
-# the cookie with the user's current series
-cookie = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', None))
-
-class token (object) :
- pass
-
-REQUIRED_PARAM = token()
-
-def get_str (key, default=REQUIRED_PARAM) :
- if key in vars :
- return vars[key].value.decode('utf8', 'replace')
- elif default is REQUIRED_PARAM :
- raise ValueError("Required param %s" % key)
- else :
- return default
-
-def get_str_list (key, default=REQUIRED_PARAM) :
- if key in vars :
- return [val.decode('utf8', 'replace') for val in vars.getlist(key)]
- elif default is REQUIRED_PARAM :
- raise ValueError("Required param %s" % key)
- else :
- return default
-
-def get_int (key, default=REQUIRED_PARAM) :
- if key in vars :
- return int(vars[key].value)
- elif default is REQUIRED_PARAM :
- raise ValueError("Required param %s" % key)
- else :
- return default
-
-def get_int_list (key, default=REQUIRED_PARAM) :
- if key in vars :
- return [int(val) for val in vars.getlist(key)]
- elif default is REQUIRED_PARAM :
- raise ValueError("Required param %s" % key)
- else :
- return default
--- a/lib/settings.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-TEMPLATE_DIR = './templates'
-TEMPLATE_EXT = 'html'
-
-IMAGE_EXTS = ('jpg', 'jpeg', 'png', 'gif', 'bmp')
-
-THUMB_DIR = 'thumbs'
-PREVIEW_DIR = 'previews'
-TITLE_FILE = 'title.txt'
-
-THUMB_GEOM = (160, 120)
-PREVIEW_GEOM = (640, 480)
-
-DEFAULT_TITLE = 'Image gallery'
-
-# how many image/page
-IMAGE_COUNT = 50
-
-VERSION = "0.5"
-ROOT_IGNORE = ('lib', 'templates')
-
--- a/lib/shorturl.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,208 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import struct
-import base64
-import shelve
-import os.path
-
-
-import utils, db, helpers, folder, image, log
-
-def int2key (id) :
- """
- Turn an integer into a short-as-possible url-safe string
- """
- for type in ('B', 'H', 'I') :
- try :
- return base64.b64encode(struct.pack(type, id), '-_').rstrip('=')
- except struct.error :
- continue
-
- raise Exception("ID overflow: %s" % id)
-
-def key2int (key) :
- # base64 ignores extra padding, but if it doesn't, it's (4 - len%4), if len%4 != 0
- # and it breaks on unicode strings
- bytes = base64.b64decode(str(key + '='*6), '-_')
-
- type = {
- 1: 'B',
- 2: 'H',
- 4: 'I',
- }[len(bytes)]
-
- return struct.unpack(type, bytes)[0]
-
-class DB (object) :
- def __init__ (self, read_only=True) :
- self.db = shelve.open('shorturls2', read_only and 'r' or 'c')
-
- def html_path (self, key, index) :
- type, dirpath, fname = self.db[key]
-
- if type == 'img' :
- fname += '.html'
- elif type == 'dir' :
- fname = ''
-
- if index :
- dirpath = '../%s' % dirpath
-
- if type == 'dir' and index > 1 :
- fname = 'index_%s.html' % (index - 1)
-
- return os.path.join(dirpath, fname)
-
- def image_info (self, key) :
- type, dirpath, fname = self.db[key]
-
- if type != 'img' :
- raise ValueError("%s is not an img" % key)
-
- return dirpath, fname
-
- def shorturls_for (self, paths) :
- ret = []
-
- for key in self.db.keys() :
- if key.startswith('_') :
- continue
-
- type, dir, fname = self.db[key]
- path = os.path.join(dir.lstrip('.').lstrip('/'), fname)
- if path in paths :
- ret.append(key)
- paths.remove(path)
-
- if paths :
- raise ValueError("Paths not found: %s" % " ".join(paths))
-
- return ret
-
-def html_path (key, index=None) :
- dir, fname = node_info(key)
-
- if fname :
- return utils.url(dir, fname + '.html')
- else :
- return utils.url(dir, helpers.url_for_page(index or 0))
-
-def node_info (key) :
- res = db.select("""SELECT dirpath, filename FROM nodes WHERE id=?""", key2int(key)).fetchone()
-
- if res :
- return res
-
- else :
- raise KeyError(key)
-
-def image_info (key) :
- res = db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone()
-
- if res :
- return res
-
- else :
- raise KeyError(key)
-
-def get_images (keys) :
- res = [db.select("""SELECT dirpath, filename FROM images WHERE id=?""", key2int(key)).fetchone() for key in keys]
-
- # don't mind if we don't get as many as we asked for?
- if res :
- return res
-
- else :
- raise KeyError(keys)
-
-def _got_obj_key (obj, id) :
- key = int2key(id)
-
- obj.shorturl_code = key
-
- if isinstance(obj, folder.Folder) :
- dir, fname = utils.strip_path(obj.path), ''
- elif isinstance(obj, image.Image) :
- dir, fname = utils.strip_path(obj.dir.path), obj.name
- else :
- assert(False, "%r %r" % (obj, id))
-
- log.info("%6s -> %s/%s", key, dir, fname)
-
-def updateDB (root) :
- """
- Update the SQL database
-
- type - one of 'img', 'dir'
- dirpath - the path to the directory, e.g. '.', './foobar', './foobar/quux'
- fname - the filename, one of '', 'DSC9839.JPG', 'this.png', etc.
- """
-
- dirqueue = [root]
-
- # dict of (dir, fname) -> obj
- paths = {}
-
- while dirqueue :
- dir = dirqueue.pop(0)
-
- dirqueue.extend(dir.subdirs.itervalues())
-
- if dir.alive :
- pathtuple = (utils.strip_path(dir.path), '')
-
- log.debug("dir %50s", pathtuple[0])
-
- paths[pathtuple] = dir
-
- for img in dir.images.itervalues() :
- pathtuple = (utils.strip_path(img.dir.path), img.name)
-
- log.debug("img %50s %15s", *pathtuple)
-
- paths[pathtuple] = img
-
- log.info("we have %d nodes", len(paths))
-
- for (id, dir, fname) in db.select("SELECT id, dirpath, filename FROM nodes") :
- try :
- obj = paths.pop((dir, fname))
- key = int2key(id)
-
- obj.shorturl_code = key
-
- log.debug("%s %50s %15s -> %d %s", dir and "img" or "dir", dir, fname, id, key)
-
- except KeyError :
- pass
-# log.warning("non-existant node (%d, %s, %s) in db", id, dir, fname)
-
- if paths :
- log.info("allocating shorturls for %d new nodes:", len(paths))
-
- db.insert_many(
- _got_obj_key,
- "INSERT INTO nodes (dirpath, filename) VALUES (?, ?)",
- ((obj, (path, fname)) for ((path, fname), obj) in paths.iteritems())
- )
- else :
- log.info("no new images")
-
--- a/lib/template.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-from mako import exceptions
-from mako.lookup import TemplateLookup
-
-import settings, helpers
-
-import log
-
-_lookup = TemplateLookup(
- directories=[settings.TEMPLATE_DIR],
- module_directory='%s/cache' % settings.TEMPLATE_DIR,
- output_encoding='utf-8',
- filesystem_checks=False, # this may need to be changed if used in a long-term process
-)
-
-TEMPLATE_GLOBALS = dict(
- h = helpers,
- version = settings.VERSION,
-)
-
-class Template (object) :
- def __init__ (self, name) :
- self.name = name
- self.tpl = _lookup.get_template("%s.%s" % (name, settings.TEMPLATE_EXT))
-
- def render (self, **data) :
- data.update(TEMPLATE_GLOBALS)
-
- try :
- log.debug("render %s with %s", self.name, data)
- return self.tpl.render(**data)
- except :
- data = exceptions.text_error_template().render()
- log.error(data)
-
- raise
-
- def render_to (self, file, **data) :
- fh = open(file, "w")
- fh.write(self.render(**data))
- fh.close()
-
-# templates
-gallery = Template("gallery")
-image = Template("image")
-
--- a/lib/utils.py Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,89 +0,0 @@
-# DeGAL - A pretty simple web image gallery
-# Copyright (C) 2007 Tero Marttila
-# http://marttila.de/~terom/degal/
-#
-# 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 2 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, write to the
-# Free Software Foundation, Inc.,
-# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-import os, os.path
-
-import settings
-
-def isImage (fname) :
- """
- Is the given filename likely to be an image file?
- """
-
- fname = fname.lower()
- base, ext = os.path.splitext(fname)
- ext = ext.lstrip('.')
-
- return ext in settings.IMAGE_EXTS
-
-def readFile (path) :
- fo = open(path, 'r')
- data = fo.read()
- fo.close()
-
- return data
-
-def fuzzyDecode (bytes) :
- try :
- return bytes.decode('utf8')
- except UnicodeDecodeError :
- return bytes.decode('latin1', 'replace')
-
-def readTitleDescr (path) :
- """
- Read a title.txt or <imgname>.txt file
- """
-
- if os.path.exists(path) :
- content = readFile(path)
-
- if '---' in content :
- title, descr = content.split('---', 1)
- else :
- title, descr = content, ''
-
- title, descr = fuzzyDecode(title), fuzzyDecode(descr)
-
- return title.strip(), descr.strip()
-
- return u"", u""
-
-def url (*parts, **kwargs) :
- abs = kwargs.pop('abs', False)
- up = kwargs.pop('up', 0)
- trailing = kwargs.pop('trailing', False)
-
- return '/'.join(([""]*int(abs)) + ([".."]*up) + list(parts) + ([""]*int(trailing)))
-
-url_join = url
-
-def path_join (*parts) :
- return os.path.join(*[part for part in parts if part is not None])
-
-def strip_path (path) :
- return path.lstrip('.').lstrip('/')
-
-def mtime (path) :
- try :
- return os.stat(path).st_mtime
- except OSError :
- # no such file or directory
- return None
-
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/detool Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,106 @@
+#!/usr/bin/env python2.4
+#
+# DeGAL - A pretty simple web image gallery
+# Copyright (C) 2007 Tero Marttila
+# http://marttila.de/~terom/degal/
+#
+# 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 2 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, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+from lib import settings
+from lib.log import misc as log
+from lib.utils import path_join
+import os, os.path, logging
+
+def move (options, args) :
+ if len(args) < 2 :
+ raise Exception("Must give one or more source files, and a destination dir")
+
+ dest = args.pop(-1)
+ srcs = args
+
+ if not os.path.isdir(dest) :
+ raise Exception("Given destination '%s' is not a directory" % dest)
+
+ for subdir in (settings.THUMB_DIR, settings.PREVIEW_DIR) :
+ path = os.path.join(dest, subdir)
+
+ if not os.path.exists(path) :
+ log.info("mkdir %s" % path)
+ os.mkdir(path)
+
+ for src in srcs :
+ if not os.path.isfile(src) :
+ raise Exception("Given source file '%s' is not a valid file" % src)
+
+ for (pre, post) in (
+ (None, None),
+ (settings.THUMB_DIR, None),
+ (settings.PREVIEW_DIR, None),
+ (None, '.html'),
+ ) :
+ dir, fname = os.path.split(src)
+
+ if post :
+ fname += post
+
+ src_path = path_join(dir, pre, fname)
+ dst_path = path_join(dest, pre, fname)
+
+ if os.path.isfile(src_path) :
+ if not options.overwite and os.path.exists(dst_path) :
+ log.warning("%s exists; skipping %s" % (dst_path, src_path))
+ log.info("%s -> %s" % (src_path, dst_path))
+ os.rename(src_path, dst_path)
+
+def help (options, args) :
+ print "Available commands:"
+
+ for name, func in COMMANDS.iteritems() :
+ print "\t%s" % name
+
+COMMANDS = dict(
+ move = move,
+ mv = move,
+ help = help,
+)
+
+if __name__ == '__main__' :
+ from optparse import OptionParser
+
+ parser = OptionParser(usage="usage: %prog <command> [options] [args ...]", version=settings.VERSION)
+
+ parser.add_option("-q", "--quiet", dest="verbose", default=True)
+ parser.add_option("-i", "--careful", dest="overwrite", help="Do not overwrite files", default=True)
+
+ options, args = parser.parse_args()
+
+ if options.verbose :
+ log.setLevel(logging.INFO)
+ else :
+ log.setLevel(logging.ERROR)
+
+ if not args :
+ parser.error("Must supply a command. See `detool.py help` for a list of commands")
+
+ command = args.pop(0).lower()
+
+ if command not in COMMANDS :
+ parser.error("Unknown command '%s'. Try `detool.py help`" % command)
+
+ func = COMMANDS[command]
+
+ func(options, args)
\ No newline at end of file
--- a/scripts/lib Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-../lib/
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/setup.py Wed Jun 03 20:41:52 2009 +0300
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+
+from distutils.core import setup
+
+setup(
+ # metadata
+ name = "Degal",
+ version = "0.1",
+ description = "Image gallery script",
+ author = "Tero Marttila",
+ author_email = "terom@fixme.fi",
+ url = "http://projects.qmsk.net/degal",
+
+ # dependencies
+ requires = [
+ "mako",
+
+ ],
+
+ # manifest
+ packages = [
+ 'degal'
+ ],
+
+ package_data = {
+ 'degal': [ 'templates/*.html', 'static/*' ],
+ },
+
+ scripts = [
+ 'bin/degal',
+ 'scripts/fix_duplicate_shorturls.py', 'scripts/migrate_shorturls.py',
+ 'cgi-bin/series.py', 'cgi-bin/shorturl.py',
+ ],
+)
--- a/templates/gallery.html Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-<%! use_javascript = False %>
-<%inherit file="master.html" /> <!-- %> -->
-
-<%def name="pagination(num_pages, cur_page)"> <!-- %> -->
-% if num_pages > 1 :
- <ul>
-
-% if cur_page > 0 :
- <li><a href="${h.url_for_page(cur_page - 1)}">« Prev</a></li>
-% else :
- <li><span>« Prev</span></li>
-% endif
-
-% for page in xrange(0, num_pages) :
-% if page == cur_page :
- <li><strong>${page + 1}</strong></li>
-% else :
- <li><a href="${h.url_for_page(page)}">${page + 1}</a></li>
-% endif
-% endfor
-
-% if cur_page < num_pages - 1 :
- <li><a href="${h.url_for_page(cur_page + 1)}">Next »</a></li>
-% else :
- <li><span>Next »</span></li>
-% endif
- </ul>
-% endif
-</%def> <!-- %> -->
-
- <h1>${title}</h1>
- <div id="dirs">
-% if dirs :
- <ul>
-% for dir in dirs :
- <li><a href="${dir.name}">${dir.title}</a></li>
-% endfor
- </ul>
-% endif
- </div>
- <div class="paginate">
-${pagination(num_pages, cur_page)}
- </div>
- <div id="thumbnails">
-% for img in images :
- ${h.tag_for_img(img.html_name, img.thumb_name)}
-% endfor
- </div>
- <div class="paginate">
-${pagination(num_pages, cur_page)}
- </div>
- <p id="description">
-${description}
- </p>
-% if shorturl :
- <div id="info">
- <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
- </div>
-% endif
--- a/templates/image.html Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-<%! use_javascript = False %>
-<%inherit file="master.html" /> <!-- %> -->
-
- <div id="image">
- <h1>${title}</h1>
- <p>
-% if prev :
- ${h.tag_for_img(prev.html_name, prev.thumb_name)}
-% endif
-
- ${h.tag_for_img(img.name, img.preview_name)}
-
-% if next :
- ${h.tag_for_img(next.html_name, next.thumb_name)}
-% endif
- </p>
- <p>
- ${description}
- </p>
- </div>
- <div id="info">
-% if img_size and file_size and timestamp :
- <p>File name: ${filename}</p>
- <p>Dimensions: ${h.format_imgsize(img_size)}</p>
- <p>File size: ${h.format_filesize(file_size)}</p>
- <p>Last modified: ${h.format_timestamp(timestamp)}</p>
-% for key, value in exif_data :
- <p>${key}: ${value}</p>
-% endfor
-
-% endif
- <p>ShortURL: <a href="${shorturl}" rel="nofollow">${shorturl_code}</a></p>
-% if series_url :
- <p><a href="${series_url}" rel="nofollow">${series_verb}</a> series</p>
-% endif
- </div>
--- a/templates/master.html Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
- "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
- <head>
- <title>${title}</title>
- <link rel="Stylesheet" type="text/css" href="${stylesheet_url}" />
-% if self.module.use_javascript :
- <script type="text/javascript" src="../javascript/prototype.js" />
- <script type="text/javascript" src="../javascript/scriptaculous.js" />
- <script type="text/javascript" src="../javascript/taggr.js" />
-% endif
- </head>
- <body>
- <div id="breadcrumb">
-% for (( bc_url, bc_title), is_first) in h.iter_is_first(breadcrumb) :
-% if not is_first :
- »
-% endif
- <a href="${bc_url}">${bc_title}</a>
-% endfor
- </div>
- ${next.body()}
- <p id="about"><a href="http://marttila.de/~terom/degal/">DeGAL</a> ${version}</p>
- </body>
-</html>
--- a/www/style.css Wed Jun 03 20:41:10 2009 +0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,92 +0,0 @@
-body {
- background-color: #333333;
- color: #cccccc;
- font-family: "Arial", sans-serif;
- font-size: small;
-}
-
-a, span.dragged {
- color: #ff8800;
- text-decoration: none;
-}
-
-a:hover {
- text-decoration: underline;
-}
-
-#thumbnails, #image, #description, h1 {
- text-align: center;
-}
-
-#thumbnails img {
- margin: 0.2em;
-}
-
-img {
- border: 1px solid #666666;
-}
-
-a:focus img {
- border: 1px solid #cccccc;
-}
-
-img:hover, a:focus img:hover {
- border: 1px solid #ff8800;
-}
-
-div#breadcrumb {
-
-}
-
-div#info {
- font-size: x-small;
- color: #666666;
-}
-
-div#info p {
- padding: 0px;
- margin: 0px;
-}
-
-p#about {
- padding-top: 40px;
- font-size: xx-small;
- text-align: center;
-
-}
-
-div.paginate {
- padding-top: 20px;
- height: 50px;
- width: 100%;
- text-align: center;
-}
-
-div.paginate ul {
- margin: 0px;
- padding: 0px;
-
- line-height: 30px;
- white-space: nowrap;
-}
-
-div.paginate li {
- list-style-type: none;
- display: inline;
-}
-
-div.paginate li *,
-div.paginate li strong,
-div.paginate li span {
- padding: 7px 10px;
-}
-
-div.paginate li span {
- color: #444444;
-}
-
-div.paginate li a:hover {
- text-decoration: none;
- background-color: #666666;
-}
-