galleryremote-0.6/0000755000175000017500000000000011543322134013616 5ustar pietropietrogalleryremote-0.6/README.txt0000644000175000017500000000063211543322134015315 0ustar pietropietroGalleryRemote Implementation of the Gallery Remote Protocol in a Python class. See docstrings for more information, and here for the Gallery Remote protocol specification: http://codex.gallery2.org/Gallery_Remote:Protocol Example usage: from galleryremote import Gallery my_gallery = Gallery('http://www.yoursite.com/gallery2', 2) my_gallery.login('username','password') albums = my_gallery.fetch_albums() galleryremote-0.6/setup.cfg0000644000175000017500000000006311543322134015436 0ustar pietropietro[egg_info] tag_build = dev tag_svn_revision = true galleryremote-0.6/LICENSE0000644000175000017500000004325411543322134014633 0ustar pietropietro GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. galleryremote-0.6/galleryremote/0000755000175000017500000000000011543322134016471 5ustar pietropietrogalleryremote-0.6/galleryremote/__init__.py0000644000175000017500000000162011543322134020601 0ustar pietropietro# See galleryremote.Gallery for complete documentation # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Written by Brent Woodruff # and John Sutherland from gallery import Gallery galleryremote-0.6/galleryremote/gallery.py0000644000175000017500000005475311543322134020520 0ustar pietropietro# -*- coding: utf-8 -*- # # Copyright © 2009-2011 Pietro Battiston # http://www.pietrobattiston.it # # Copyright (C) 2008 Brent Woodruff # http://www.fprimex.com # # Copyright (C) 2004 John Sutherland # http://garion.tzo.com/python/ # # This library 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 library 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 library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA __version__ = '0.6' USER_AGENT = 'python-galleryremote v. %s' % (__version__) CA_SYSTEM_DIR = '/etc/ssl/certs' import urllib2 import cookielib try: from M2Crypto import m2urllib2, SSL M2CRYPTO_AVAILABLE = True except: M2CRYPTO_AVAILABLE = False import StringIO import time import logging from multipart import multipart class GalleryException(Exception): """ The base class for exceptions related to error messages from gallery. """ class ConnectionException(Exception): """ The base class for exceptions related to connection to gallery. """ class NotSupportedException(Exception): """ For operations that only one version of Gallery supports, if asked with the other version. """ class Gallery: """ The Gallery class implements the Gallery Remote protocol as documented here: http://codex.gallery2.org/Gallery_Remote:Protocol The Gallery project is an open source web based photo album organizer written in php. Gallery's web site is: http://gallery.menalto.com/ This class is a 3rd party product which is not maintained by the creators of the Gallery project. Example usage: from galleryremote import Gallery my_gallery = Gallery('http://www.yoursite.com/gallery2', 2) my_gallery.login('username','password') albums = my_gallery.fetch_albums() """ def __init__(self, url, version=2): """ Create a Gallery for remote access. url - base address of the gallery version - version of the gallery being connected to (default 2), either 1 for Gallery1 or 2 for Gallery2 gallery-uploader is able to cope with secured connections, thanks to M2Crypto. It won't catch any exception, though: handling i.e. unverified certificates is entirely left to higher level applications, which must hence be ready to catch M2Crypto exceptions. Moreover, gallery-uploader works fine (only emits a warning) also if M2Crypto is not available, and in that case connections will NOT be secure! If you want to avoid this risk, you can simply assert gallery.M2CRYPTO_AVAILABLE . """ self.version = version # Gallery1 or Gallery2 if version == 1: self.url = url + '/gallery_remote2.php' else: # default to G2 self.url = url + '/main.php' # Until proven otherwise: self.secured = False if self.url.startswith( 'https://' ): if M2CRYPTO_AVAILABLE: self.secured = True else: print "WARNING: M2Crypto missing, gallery-uploader connections will not be secure!" self.cookiejar = cookielib.CookieJar() if self.secured: self.ssl_context = SSL.Context() self.ssl_context.load_verify_info( capath=CA_SYSTEM_DIR ) self.ssl_context.set_verify( SSL.verify_peer | SSL.verify_fail_if_no_peer_cert | SSL.verify_client_once, 20 ) self.opener = m2urllib2.build_opener( self.ssl_context, urllib2.HTTPCookieProcessor(self.cookiejar) ) else: self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar)) self.logged_in = 0 self.protocol_version = '2.5' self.auth_token = '' def _do_request(self, request, file_info=None): """ Send a request, encoded as described in the Gallery Remote protocol. request - a dictionary of protocol parameters and values file_info - a tuple with the field name and the filename to be added in the body """ boundary = '------python-galleryremote_boundary_%d' % int(time.time()) headers = {'User-agent' : USER_AGENT, 'Content-type':'multipart/form-data; boundary=%s' % boundary, 'Accept': 'text/plain'} if self.auth_token and self.version >= 2: request['g2_authToken'] = self.auth_token logging.debug( "Submitting auth token %s" % self.auth_token ) else: logging.debug( "Submitting no auth token" ) enc_request = multipart(boundary, request, file_info) logging.debug( '\n\t\tREQUEST\n' ) logging.debug( str(request) ) logging.debug( '\n\t\tHEADERS (OUT)\n' ) logging.debug( str(headers) ) req = urllib2.Request(self.url, enc_request, headers) response = self.opener.open( req ) info = response.info() logging.debug( "\n\t\tINFO (IN)\n" ) logging.debug( str(info) ) data = response.read() logging.debug( "\n\t\tDATA (IN)\n" ) logging.debug( str(data) ) response = self._parse_response( data ) if 'auth_token' in response: self.auth_token = response['auth_token'] logging.debug( "Got auth token %s" % self.auth_token ) else: logging.debug( "No auth token found in %s" % response ) if 'status' in response: # This _should be_ the right code to handle exceptions in Gallery 1, # but I didn't test; it was already there and assumed that 'status' # _was_ in response -- Pietro Battiston if response['status'] != '0': raise GalleryException, response['status_text'] else: # ... but apparently, in Gallery 2 exceptions response _doesn't_ # contain 'status' (FIXME: VERIFY!): if 'debug_exception' in response: raise GalleryException, response['debug_exception'] return response def _parse_response(self, response): """ Decode the response from a request, returning a request dict response - The response from a gallery request, encoded according to the gallery remote protocol """ myStr = StringIO.StringIO(response) header_found = False for line in myStr: if '#__GR2PROTO__' in line: header_found = True break if not header_found: # the 1st line should start with #__GR2PROTO__ ! raise ConnectionException, "Bad response: \n" + response resDict = {} # This operates still on myStr (on the lines _following_ the header): for myS in myStr: strList = myS.split('=', 2) try: resDict[strList[0]] = strList[1] if resDict[strList[0]].endswith('\n'): resDict[strList[0]] = resDict[strList[0]][:-1] except: resDict[strList[0]] = '' return resDict def _get(self, response, kwd): """ """ try: retval = response[kwd] except: retval = '' return retval def login(self, username, password): """ Establish an authenticated session to the remote gallery. username - A valid gallery user's username password - That valid user's password """ if self.version == 1: request = { 'protocol_version' : self.protocol_version, 'cmd' : 'login', 'uname' : username, 'password' : password } else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'login', 'g2_form[uname]' : username, 'g2_form[password]' : password } response = self._do_request(request) # as long as it comes back here without an exception, we're ok. self.logged_in = True def fetch_albums(self): """ Obtain a dict of albums contained in the gallery keyed by album name. In Gallery1, the name is alphanumeric. In Gallery2, the name is the unique identifying number for that album. """ if self.version == 1: request = { 'protocol_version' : self.protocol_version, 'cmd' : 'fetch-albums' } else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'fetch-albums' } response = self._do_request(request) # as long as it comes back here without an exception, we're ok. albums = {} for x in range(1, int(response['album_count']) + 1): album = {} album['name'] = self._get(response,'album.name.' + str(x)) album['title'] = self._get(response,'album.title.' + str(x)) album['summary'] = self._get(response,'album.summary.' + str(x)) album['parent'] = self._get(response,'album.parent.' + str(x)) album['resize_size'] = self._get(response,'album.resize_size.' + str(x)) album['perms.add'] = self._get(response,'album.perms.add.' + str(x)) album['perms.write'] = self._get(response,'album.perms.write.' + str(x)) album['perms.del_item'] = self._get(response,'album.perms.del_item.' + str(x)) album['perms.del_alb'] = self._get(response,'album.perms.del_alb.' + str(x)) album['perms.create_sub'] = self._get(response,'album.perms.create_sub.' + str(x)) album['perms.info.extrafields'] = self._get(response,'album.info.extrafields' + str(x)) album['ownerid'] = self._get(response,'album.ownerid' + str(x)) albums[album['name']] = album return albums def fetch_albums_prune(self): """ Obtain a dict of albums contained in the gallery keyed by album name. In Gallery1, the name is alphanumeric. In Gallery2, the name is the unique identifying number for that album. From the protocol docs: "The fetch_albums_prune command asks the server to return a list of all albums that the user can either write to, or that are visible to the user and contain a sub-album that is writable (including sub-albums several times removed)." """ if self.version == 1: request = { 'protocol_version' : self.protocol_version, 'cmd' : 'fetch-albums-prune' } else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'fetch-albums-prune' } response = self._do_request(request) # as long as it comes back here without an exception, we're ok. albums = {} for x in range(1, int(response['album_count']) + 1): album = {} album['name'] = self._get(response,'album.name.' + str(x)) album['title'] = self._get(response,'album.title.' + str(x)) album['summary'] = self._get(response,'album.summary.' + str(x)) album['parent'] = self._get(response,'album.parent.' + str(x)) album['resize_size'] = self._get(response,'album.resize_size.' + str(x)) album['perms.add'] = self._get(response,'album.perms.add.' + str(x)) album['perms.write'] = self._get(response,'album.perms.write.' + str(x)) album['perms.del_item'] = self._get(response,'album.perms.del_item.' + str(x)) album['perms.del_alb'] = self._get(response,'album.perms.del_alb.' + str(x)) album['perms.create_sub'] = self._get(response,'album.perms.create_sub.' + str(x)) album['perms.info.extrafields'] = self._get(response,'album.info.extrafields' + str(x)) album['ownerid'] = self._get(response,'album.ownerid' + str(x)) albums[album['name']] = album return albums def add_item(self, album, filename, caption, description): """ Add a photo to the specified album. album - album name / identifier filename - image to upload caption - string caption to add to the image description - string description to add to the image """ if self.version == 1: request = { 'protocol_version' : self.protocol_version, 'cmd' : 'add-item', 'set_albumName' : album, 'userfile_name' : filename, 'caption' : caption, 'extrafield.Description' : description } response = self._do_request(request, ('userfile', filename) ) else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'add-item', 'g2_form[set_albumName]' : album, 'g2_form[userfile_name]' : filename, 'g2_form[caption]' : caption, 'g2_form[extrafield.Description]' : description } response = self._do_request(request, ('g2_userfile', filename) ) def album_properties(self, album): """ Obtain album property information for the specified album. album - the album name / identifier to obtain information for """ if self.version == 1: request = { 'protocol_version' : self.protocol_version, 'cmd' : 'album-properties', 'set_albumName' : album } else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'album-properties', 'g2_form[set_albumName]' : album } response = self._do_request(request) res_dict = {} if response.has_key('auto_resize'): res_dict['auto_resize'] = response['auto_resize'] if response.has_key('add_to_beginning'): res_dict['add_to_beginning'] = response['add_to_beginning'] return res_dict def image_properties(self, image): """ Obtain image property information for the specified image. image - the identifier of the image for which we're interested in """ if self.version == 1: raise NotSupportedException, "Operation not supported in Gallery version 1" else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'image-properties', 'g2_form[id]' : image } response = self._do_request(request) res_dict = {} for key in ['name', 'raw_height', 'raw_width', 'raw_filesize',\ 'resizedName', 'resized_width', 'resized_height', 'thumbName',\ 'thumb_width', 'thumb_height', 'caption', 'title', 'force', 'hidden']: if response.has_key('image.'+key): res_dict[key] = response['image.'+key] return res_dict def new_album(self, parent, name=None, title=None, description=None): """ Add an album to the specified parent album. parent - album name / identifier to contain the new album name - unique string name of the new album title - string title of the album description - string description to add to the image """ if self.version == 1: request = { 'g2_controller' : 'remote:GalleryRemote', 'protocol_version' : self.protocol_version, 'cmd' : 'new-album', 'set_albumName' : parent } if name != None: request['newAlbumName'] = name if title != None: request['newAlbumTitle'] = title if description != None: request['newAlbumDesc'] = description else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'new-album', 'g2_form[set_albumName]' : parent } if name != None: request['g2_form[newAlbumName]'] = name if title != None: request['g2_form[newAlbumTitle]'] = title if description != None: request['g2_form[newAlbumDesc]'] = description response = self._do_request(request) return response['album_name'] def fetch_album_images(self, album): """ Get the image information for all images in the specified album. album - specifies the album from which to obtain image information """ if self.version == 1: request = { 'protocol_version' : self.protocol_version, 'cmd' : 'fetch-album-images', 'set_albumName' : album, 'albums_too' : 'no', 'extrafields' : 'yes' } else: request = { 'g2_controller' : 'remote:GalleryRemote', 'g2_form[protocol_version]' : self.protocol_version, 'g2_form[cmd]' : 'fetch-album-images', 'g2_form[set_albumName]' : album, 'g2_form[albums_too]' : 'no', 'g2_form[extrafields]' : 'yes' } response = self._do_request(request) # as long as it comes back here without an exception, we're ok. images = [] for x in range(1, int(response['image_count']) + 1): image = {} image['name'] = self._get(response, 'image.name.' + str(x)) image['title'] = self._get(response, 'image.title.' + str(x)) image['raw_width'] = self._get(response, 'image.raw_width.' + str(x)) image['raw_height'] = self._get(response, 'image.raw_height.' + str(x)) image['resizedName'] = self._get(response, 'image.resizedName.' + str(x)) image['resized_width'] = self._get(response, 'image.resized_width.' + str(x)) image['resized_height'] = self._get(response, 'image.resized_height.' + str(x)) image['thumbName'] = self._get(response, 'image.thumbName.' + str(x)) image['thumb_width'] = self._get(response, 'image.thumb_width.' + str(x)) image['thumb_height'] = self._get(response, 'image.thumb_height.' + str(x)) image['raw_filesize'] = self._get(response, 'image.raw_filesize.' + str(x)) image['caption'] = self._get(response, 'image.caption.' + str(x)) image['clicks'] = self._get(response, 'image.clicks.' + str(x)) image['capturedate.year'] = self._get(response, 'image.capturedate.year' + str(x)) image['capturedate.mon'] = self._get(response, 'image.capturedate.mon' + str(x)) image['capturedate.mday'] = self._get(response, 'image.capturedate.mday' + str(x)) image['capturedate.hours'] = self._get(response, 'image.capturedate.hours' + str(x)) image['capturedate.minutes'] = self._get(response, 'image.capturedate.minutes' + str(x)) image['capturedate.seconds'] = self._get(response, 'image.capturedate.seconds' + str(x)) image['description'] = self._get(response, 'image.extrafield.Description.' + str(x)) image['hidden'] = self._get(response, 'image.hidden.' + str(x)) images.append(image) return images def fetch_image(self, image, thumb=True): """ Get the image (this returns the real image data). If "thumb" is set, this will first do an "image-properties" request to get the name of the thumbnail, then get the thumbnail (if a thumbnail is not found, the image itself is returned). Alternatively, the name of the thumbnail can be passed directly as "image"; in this case, "thumb" must be False (since a thumbnail doesn't have a thumbnail!). FIXME: fetch_album_images already gets the name of each thumbnail, and it's very likely that it gets called before any call to fetch_image, so some caching of the information could spare many requests. """ if self.version == 1: # I must search for the image url in Gallery1 - Pietro raise NotImplementedError, "Image retrieval curretnly not implemented for Gallery 1" if thumb: image_info = self.image_properties(image) if 'thumName' in image_info: image = image_info[thumbname] image_url = self.url + '?g2_view=core.DownloadItem&g2_itemId=%s' % str(image) req = urllib2.Request(image_url) response = self.opener.open( req ) return response.read() galleryremote-0.6/galleryremote/multipart.py0000644000175000017500000000333011543322134021063 0ustar pietropietro# This file is part of GUP. # # It 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. # # It 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 it; if not, write to the Free Software Foundation, Inc., 51 # Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # Copyright (C) 2007 Julio Biason import mimetypes def multipart(boundary, arguments, file_info): """ Generates the body of a multipart data. """ parts = [] for key, value in arguments.iteritems(): parts.append('--%s' % boundary) parts.append('Content-disposition: form-data; name="%s"' % key) parts.append('') parts.append(value) if file_info is not None: content_type = mimetypes.guess_type(file_info[1])[0] or \ 'application/octet-stream' parts.append('--%s' % (boundary)) parts.append('Content-disposition: form-data; ' + \ 'name="%s"; filename="%s"' % (file_info[0], file_info[1])) parts.append('Content-Type: %s' % content_type) parts.append('Content-Transfer-Encoding: base64') parts.append('') image = file(file_info[1]) contents = image.read() image.close() parts.append(contents) parts.append('--%s--' % boundary) return '\r\n'.join(parts) galleryremote-0.6/ChangeLog0000644000175000017500000000177111543322134015376 0ustar pietropietrogalleryremote 0.6, 2011-03-26 * Use cookielib (to solve lighttpd incompatibility) * Improved debugging. * Set up for release maker (http://pietrobattiston.it/release_maker) 21-Nov-10 version 0.5 --------- Change author information to me (Pietro Battiston). 17-Oct-10 version 0.4 --------- If M2Crypto is present, it is used to verify SSL connections. Fixed license issues, by relicensing under GPL 2+. 30-Sep-10 version 0.3 --------- Fixed add_item with Gallery v.1 20-Oct-09 --------- Patches from Pietro Battiston, Guillaume Schmid, and Mike Miller Method add_item works now Use multipart from GUP instead of urllib2_file Also get 'hidden' attribute of images 04-Aug-08 --------- Added Gallery2 compatibility Changed fetch_albums and fetch_albums_prune to return dicts Added docstrings Created package and registered with Pypi 09-Jun-04 --------- Removed self.cookie='' from _doRequest to allow multiple transactions for each login. Fixed cut paste error in newAlbum. (both patches from Yuti Takhteyev) galleryremote-0.6/setup.py0000644000175000017500000000150611543322134015332 0ustar pietropietrofrom setuptools import setup, find_packages import sys, os setup(name='GalleryRemote', version='0.6', description="Implementation of the Gallery Remote protocol in Python.", long_description="""\ Implementation of the Gallery Remote protocol in Python.""", classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Topic :: Multimedia :: Graphics'], keywords='gallery gallery2 remote images pictures albums', author='Pietro Battiston', author_email='me@pietrobattiston.it', url='http://pietrobattiston.it/galleryremote', license='GPL', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False )