#!/usr/bin/python
# -*- coding: utf-8 -*-

#Copyright (c) Angaran Stefano

#   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.

# Version: 0.2 
#
# Questo script consente di uploadare automaticamente la selezione corrente
# in GIMP su un blog WordPress. E' necessario utilizzare Firefox 3 ed essere
# autenticati sul blog con l'opzione "Ricordati di me" attivata. In questo modo
# i cookie vengono salvati permanentemente dal browser e possono essere utilizzati
# dallo script per eseguire l'autenticazione sul blog.
# Al momento lo script funziona solamente su sistemi Windows

# Testato con:
# - GIMP 2.6.6
# - Wordpress 2.7.1
# - Firefox 3.0.10
# - ActivePython 2.6.2 su Windows, Python 2.6.2 su Linux
# - Microsoft Windows 7 RC1, Microsoft Windows Vista SP1, Ubuntu 9.04

import sys, urllib2, httplib, cookielib, mimetypes, sqlite3
try:
    import win32clipboard
    from win32com.shell import shellcon, shell
    using_win32 = True
except:
    try:
        # se stiamo usando linux proviamo ad usare questi moduli
        import pygtk
        pygtk.require('2.0')
        import gtk, random, os
        using_win32 = False
    except:
        # non ci è andata bene..
        exit()    
    
from gimpfu import *

# variabili di configurazione
profile = 'profilo.default' # il nome del tuo profilo in Firefox. Per trovarlo in un sistema Windows premi i tasti Win+R, scrivi %appdata% e premi Invio.
						     # Ora naviga nella cartella Mozilla, poi in Firefox e poi in Profiles e utilizza il nome della cartella che trovi.
							 # Se trovi più di una cartella devi scoprire il nome del tuo profilo di default, contenuto nel file profiles.ini nella
							 # cartella %appdata/Mozilla/Firefox. Su Linux invece troverai la cartella del profilo nella cartella /home/tuo_nome/.mozilla/firefox
								   
blog_domain = 'blog.upyou.it' # il dominio del tuo blog
wordpress_path = '' # il percorso della tua installazione di wordpress ( ad esempio se il tuo blog è raggiungibile all'indirizzo:
					# http://www.mio_blog.it/wordpress/ dovrai inserire '/wordpress'.

gettext.install("gimp20-python", gimp.locale_directory, unicode=True)

def post_multipart(host, selector, cookies, fields, files):
    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """
    content_type, body = encode_multipart_formdata(fields, files)
    h = httplib.HTTPConnection(host)
    h.set_debuglevel(0)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; it; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
        'Content-Type': content_type,
		'Cookie' : cookies,
        'Accept-Encoding' : 'gzip,deflate'
    }
    h.request('POST', selector, body, headers)
    res = h.getresponse()
    return res.status, res.reason, res.read()

def encode_multipart_formdata(fields, files):
    """
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return (content_type, body) ready for httplib.HTTP instance
    """
    BOUNDARY = '---------------------------148682141113713'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('Content-Type: %s' % get_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body

def get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

def python_upload_to_wp(image, drawable, filename):
    # controllo che ci sia l'estensione altrimenti la aggiungo
    try:
        filename.index('.')
    except ValueError:
        filename += '.png'
    
    # dati profilo utente
    if using_win32:
        cookie_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) + '/Mozilla/Firefox/Profiles/' + profile + '/cookies.sqlite'
    else:
        cookie_path = os.getenv('HOME') + '/.mozilla/firefox/' + profile + '/cookies.sqlite'
        
    
	
    con = sqlite3.connect(cookie_path);
    cur = con.cursor()
    cur.execute("select host, path, isSecure, expiry, name, value from moz_cookies where host like ?", [blog_domain])

    pairs = []
    for item in cur.fetchall():
        pairs.append(item[4] + '=' + item[5])

    cookies = '; '.join(pairs)
	
	# scrivo nella clipboard

    pdb.gimp_edit_copy_visible(image)

	# apro la clipboard
    
    if using_win32:
        win32clipboard.OpenClipboard()
        format = win32clipboard.EnumClipboardFormats()
        data = win32clipboard.GetClipboardData(format)
        win32clipboard.CloseClipboard()
    else:
        clipboard = gtk.clipboard_get()
        data = clipboard.wait_for_image()
        # data è un'istanza della classe gtk.gdk.PixBuf
        random_filename = '/tmp/python-gimp-up-' + str(random.randint(10000, 99999)) + '.png'
        data.save(random_filename,'png')
        f = open(random_filename, 'rb')
        data = f.read()
        f.close()
        os.remove(random_filename)

    # trovo il nonce

    req = urllib2.Request('http://' + blog_domain + wordpress_path + '/wp-admin/media-new.php?flash=0')
    req.add_header('Cookie',cookies)
    res = urllib2.urlopen(req)
    content = res.read()
    i = content.find('name="_wpnonce" value="') + 23
    j = content.find('"', i)
    nonce = content[i:j]
    post_multipart(
        blog_domain, wordpress_path + '/wp-admin/media-upload.php?inline=&upload-page-form=',
        cookies,
        [('post_id','0'),('_wpnonce',nonce),('_wp_http_referer', wordpress_path + '/wp-admin/media-new.php?flash=0'),('html-upload','Upload')],
        [('async-upload',filename,data)])

register(
        "python-fu-upload-to-wp",
        "Upload the selection content as an image on a WordPress blog",
        "Upload the selection content as an image on a WordPress blog",
        "Stefano Angaran",
        "Stefano Angaran",
        "2009",
        _("_Upload..."),
        "RGB*, GRAY*",
        [
                (PF_IMAGE, "image", "The image", None),
                (PF_DRAWABLE, "drawable", "Drawable object", None),
				(PF_STRING, "filename", "Name of the uploaded file:", "out.png")
				#(PF_RADIO, "type", "The format of the image:", "png", (("gif", "gif"), ("jpg", "jpg"), ("png", "png")))

        ],
        [],
        python_upload_to_wp,
		menu="<Image>/Filters/Web",
		domain=("gimp20-python", gimp.locale_directory)
		)

main()

