#!/usr/bin/env python
#
# Author: Julius Sipila (julius.sipila@gmail.com)
#
# This is simple python command line script for Nokia N900 command-line sharing plugin.
# It allows users to share pictures to a remote Gallery3 server (see http://gallery.menalto.com).
#
# Requires:
# Python Gallery 3 Library (pylibgal) available from http://stuffivelearned.org/doku.php?id=programming:python:libgal3
# Note: the Python version on N900 does not include json. You need to modify the following three libg3 files:
# G3Items.py Gallery3.py and Requests.py (on N900 these can be found in /usr/lib/python2.5/site-packages/libg3/)
# E.g.
# original:
# import urllib2, os, json
# N900:
# import urllib2, os
# import simplejson as json
#
# Recommended (for integration to the N900 sharing UI):
# Command-Line Sharing plugin (sharing-cli) installed on the Nokia N900 (available in Maemo extras-devel)
# If you use the Command-Line Sharing plugin:
# 1. as root copy this script to /usr/bin/g3_share.py and make it executable (chmod a+x /usr/bin/g3_share.py)
# 2. set the details of your gallery3 in the script
# 3. put the following command in the plugin setup:
# g3_share.py -i %s -o %s
# 

import getopt, sys, os
import libg3
from libg3.Errors import G3RequestError, G3UnknownError

def main():
    """
Send file to a remote Gallery3 server (see: http://gallery.menalto.com).

Example usage:
g3_share.py -s www.example.com -b /gallery3 -d "Test/Incoming Pics" -u g3_username -p g3_password -i local_file.jpg -o remote_item_title
If you set the details of your gallery in the script you can shorten the command line options to minimal:
g3_share.py -i local_file.jpg -o remote_item_title
"""
    g3_url = 'www.example.com'
    g3_base = '/gallery3'
    g3_dir = 'Test/Incoming Pics' # assuming in the gallery root level an album named 'Test' which contains album named 'Incoming Pics'
    inputfile = None
    outputfile = None
    g3_user = 'your_gallery3_username'
    g3_passwd = 'your_gallery3_passwd'
    port = 80
    ssl = False # not tested with SSL = True !
 
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hs:b:d:u:p:i:o:",
        ["help", "gallery3-server-url=", "gallery3-base", "gallery3-dir=", "gallery3-user=", "gallery3-password=",
        "local-file=", "remote-file="])
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-s", "--gallery3-server-url"):
            g3_url = a
        elif o in ("-b", "--gallery3-base"):
            g3_base = a
        elif o in ("-d", "--gallery3-dir"):
            g3_dir = a
        elif o in ("-u", "--gallery3-user"):
            g3_user = a
        elif o in ("-p", "--gallery3-password"):      
            g3_passwd = a
        elif o in ("-i", "--local-file"):
            inputfile = a
        elif o in ("-o", "--remote-file"):      
            outputfile = a  
        else:
            assert False, "unhandled option"
    
    if outputfile == None:
        outputfile = os.path.splitext(os.path.basename(inputfile))[0]

    outputfile = os.path.splitext(outputfile)[0]
    
    if None in [g3_url, g3_base, g3_dir, inputfile, outputfile, g3_user, g3_passwd]:
        usage()
        sys.exit()

    try:
        gal = libg3.login(g3_url, g3_user, g3_passwd, g3_base, port, ssl)
        if gal == None:
            raise("libg3.login returned None. Wrong credentials maybe?")
    except:
        print "Cannot connect to gallery. Exiting.."
        sys.exit(2)
    
    root = gal.getRoot()
    
    # trying to find specified directory on the remote gallery
    # first split the directory path 
    album_path_list = list(os.path.split(g3_dir))
    
    if len(album_path_list)==2 and album_path_list[0] == '':
        album_path_list.pop(0)
    
    print "Navigating to the specified album starting from the gallery root album.."    
    current_root = root
    try:
        while len(album_path_list)>0:
            print str(current_root) + '...' 
            current_path_item = album_path_list.pop(0)
            current_albums = current_root.Albums
            #print [album.title for album in current_albums]
            current_root = current_albums[[album.title for album in current_albums].index(current_path_item)]
    except:
        print "Cannot find specified album \"%s\" on the remote host\nExiting.." % g3_dir
        sys.exit(2)
        
    print "Successfully navigated to the album: \"%s\"" % g3_dir
    if current_root.can_edit:
        print "Permission check OK. Can add items"
    else:
        print "No permission to add items. Exiting.."
        sys.exit(2)
    
    try:
        locImage = libg3.LocalImage(inputfile)
    except:
        print "Could not load local file \"%s\". Exiting.." %inputfile
        sys.exit(2)
    try:
        print "Sending file \"%s\" to remote server as \"%s\".." % (inputfile, outputfile)
        newRemoteImage = current_root.addImage(locImage, outputfile, '')
        print "Done!"

    # for some reason urllib2 on N900 throws HTTPError when it receives HTTP status 201 (not an error..)
    # we catch these "errors" here and assume everything is OK..
    except G3UnknownError, e:
        err = str(e)
        if err.find('HTTP Error 201'):
            print "urllib2 raised an error: %s" % err
            print "HTTP status code is 201 (Item created), ignoring the error!"
            print "Done!"
            sys.exit(0)
        else:
            print err
            sys.exit(2)
    return 0

def usage():
    print main.__doc__

if __name__ == "__main__":
    main()
