#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-

# Gestionnaire de photos expédiées par e-mail
# Projet #ProgX
# 11/15/2003 - 17:44:18
# GNU-GPL v2, (C)2003 Romain GUY, romain.guy@jext.org 

################################################################################
# IMPORTS
################################################################################

import email
import email.Encoders
import email.Header
import httplib
import mimetypes
import MySQLdb
import os
import os.path
import poplib
import re
import time
import urllib

from email.MIMEImage     import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText      import MIMEText

################################################################################
# PROGRAMME
################################################################################

def getPOPParameters(config):
  pop3 = ['host', 'user', 'pass', '0', config['PHOTO_HOST'], config['PHOTO_URL']]
  params = ('Interlope_POP3_Host', 'Interlope_POP3_User', 'Interlope_POP3_Password')

  db = MySQLdb.connect(passwd = config['MYSQL_PASSWORD'], db = config['MYSQL_DB'],
                       host = config['MYSQL_HOST'], user = config['MYSQL_USER'])
  for i in range(len(params)):
    c = db.cursor()
    c.execute('SELECT value FROM functions WHERE name=%s', (params[i], ))
    pop3[i] = c.fetchone()[0]
    c.close()

  c = db.cursor()
  c.execute('SELECT categoryid FROM category WHERE title=%s', (config['CATEGORY'], ))
  pop3[3] = c.fetchone()[0]
  c.close()

  db.close()

  return tuple(pop3)

def getConfiguration():
  configuration = { "MYSQL_HOST": "localhost",
                    "MYSQL_DB": "progx",
                    "MYSQL_USER": "root",
                    "MYSQL_PASSWORD": "",
                    "CATEGORY": "photos",
                    "PHOTO_HOST": "localhost",
                    "PHOTO_URL": "/addImage.php" }

  if os.path.exists("../conf/interlope.conf"):
    confFile = open("../conf/interlope.conf")
    for line in confFile.readlines():
      match = re.search('^([^=]+)=(.*)$', line)
      if match:
        configuration[match.group(1)] = match.group(2)
    confFile.close()

  return configuration

def handleMails(config):
  whiteList = ("[^@]+@jext.org",)
  whiteExts = (".jpg", )

  pop3 = poplib.POP3(config[0])
  pop3.user(config[1])
  pop3.pass_(config[2])

  numMessages = len(pop3.list()[1])

  for i in range(numMessages):
    response, text, length = pop3.retr(i + 1)
    mail = email.message_from_string("\n".join(text))
    if not mail.is_multipart():
      pop3.dele(i + 1)
      continue

    accepted = 0
    sender = mail["From"]

    match = re.search('.*<([^>]+)>', sender)
    if match:
      for whiteDomain in whiteList:
        if re.search(whiteDomain, match.group(1)) is not None:
          accepted = 1
          break

    if accepted:
      title = mail["Subject"]
      if title.find("=?ISO-8859-1?") == 0:
        title = email.Header.decode_header(title)[0][0]
  
      description = ""
      image       = None
      ext         = None

      for part in mail.walk():
        type = part.get_content_type()
        if type == "text/plain":
          description = part.get_payload(decode = 1).strip()
        elif type == "application/octet-stream" or type == "image/jpeg":
          filename = part.get_filename()
          if not filename:
            ext = mimetypes.guess_extension(part.get_type())
          else:
            ext = os.path.splitext(filename)[1]
  
          if ext and ext in whiteExts:
            image = part

      if image is not None and ext is not None:
        part = image

        msg = MIMEMultipart('form-data')
        del msg['MIME-Version']
        
        tatoo = str(int(time.time() + i))
        toPost = { 'title': title,
                   'comment': description,
                   'categoryid': str(config[3]),
                   'maxfilesize': tatoo,
                   'add': 'Ajouter' }
        
        for key, value in toPost.items():
          txt = MIMEText(value)
          del txt["Content-Type"]
          del txt["MIME-Version"]
          del txt["Content-Transfer-Encoding"]
          txt['Content-Disposition'] = 'form-data; name="' + key + '"'
          msg.attach(txt)

        img = MIMEImage(part.get_payload(decode = 1), "image/jpeg", email.Encoders.encode_noop)
        img['Content-Disposition'] = 'form-data; name="image"; filename="' + tatoo + ext + '"'
        del img["MIME-Version"]
        
        parts = str(msg).split('\n')[1:-1]
        boundary = msg.get_boundary()
        parts.append("--" + boundary)
        parts.append("\n".join(str(img).split('\n')[1:]))
        parts.append("--" + boundary + "--")

        name, value = parts[0].split(':')
        headers = { 'Accept': 'text/plain' }
        headers[name] = value.strip()

        http = httplib.HTTPConnection(config[4])
        http.request('POST', config[5], "\r\n".join(parts[1:]), headers)
        print "Image", i + 1, "/", numMessages, ":", http.getresponse().read()
        http.close()

    pop3.dele(i + 1)

  print numMessages, "mails processed."

  pop3.quit()

if __name__ == '__main__':
  config   = getConfiguration()
  pop3conf = getPOPParameters(config)
  handleMails(pop3conf)

# fin de interlope.py
