#!/usr/local/bin/python2.4

usage = """Syntax: nerdpics file [file ...]

Author: Michal Guerquin
June 2005

Upload files listed as arguments to Nerdpics,
http://nerdpics.net/. Username and password
are hardcoded in the source file.

Example usage: nerdpics `find . -name *.jpg`
"""

USERNAME = "anonymouscoward"
PASSWORD = "cowardlypassword"

import httplib, mimetypes, os, time

def post_multipart(host="", selector="", headers=(), 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.HTTP(host)
    h.putrequest('POST', selector)
    h.putheader('Host', host)
    for k,v in headers:
      h.putheader(k,v)
    h.putheader('Content-Type', content_type)
    h.putheader('Content-Length', str(len(body)))
    h.endheaders()
    h.send(body)
    errcode, errmsg, headers = h.getreply()
    return headers, h.file.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 = '----------ThIs_Is_tHe_bouNdaRY_$'
    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'

files = os.sys.argv[1:]
if not files:
  os.sys.exit(usage)

print >>os.sys.stderr, "Logging in to www.nerdpics.net"
headers, content = post_multipart(host="www.nerdpics.net", selector="/index.php", fields=(("UserName",USERNAME),("Password",PASSWORD),("logIn","1")))
cookie_str = headers.getheader("Set-Cookie")

if content.find("bad Username/Password")>0:
  print >>os.sys.stderr, "Bad username/password"
else:
  print >>os.sys.stderr, "Logged in with cookie:", cookie_str

  for f in files:
    try:
      size = os.stat(f)[6]
      print >>os.sys.stderr, f, "- processing", size, "bytes"

      time_start = time.time()
      headers, content = post_multipart(host="www.nerdpics.net", selector="/addpic.php", headers=(("Cookie", cookie_str),("User-Agent","mikeg's nerdpics script")), fields=(("pictureAdd", "1"),), files=(("PictureFile",f,open(f).read()),))
      time_end = time.time()
      print >>os.sys.stderr, f, "- done at", time.ctime(), "%d bytes/s" % (size/(time_end-time_start))
    except "hello":
      print >>os.sys.stderr, "Error accessing file: ", f