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

# Gestionnaire de news expédiées par e-mail
# Projet #ProgX
# 15:34 08/09/2004
# GNU-GPL v2, (C)2004 Romain GUY, romain.guy@jext.org 

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

import mimetools
import mimify
import MySQLdb
import os
import os.path
import poplib
import re
import socket
import string
import StringIO
import time
import urllib

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

def getPOPParameters(config):
  pop3 = ['host', 'user', 'pass']
  params = ('Brinborion_POP3_Host', 'Brinborion_POP3_User', 'Brinborion_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()
  db.close()

  return tuple(pop3)

def getConfiguration():
  configuration = { "MYSQL_HOST": "localhost",
                    "MYSQL_DB": "progx",
                    "MYSQL_USER": "root",
                    "MYSQL_PASSWORD": "" }

  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(pop3conf):
  whiteList = ("[^@]+@(jext|progx).org",)

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

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

  for i in range(numMessages):
    response, text, length = pop3.retr(i + 1)
    strio = StringIO.StringIO(string.join(text, "\n"))
    mail = mimetools.Message(strio)

    if string.lower(mail.getmaintype()) != "text":
      pop3.dele(i + 1)
      continue

    accepted = 0
    sender = mail.getheader("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 = None
      title = mail.getheader("Subject")
      title = mimify.mime_decode_header(title)
  
      description = None
      description = string.join(strio.readlines(), '')
      description = string.replace(description, '\n', '<br />')

      if description is not None and title is not None:
        db = MySQLdb.connect(passwd = config['MYSQL_PASSWORD'], db = config['MYSQL_DB'],
                             host = config['MYSQL_HOST'], user = config['MYSQL_USER'])
        c = db.cursor()
        c.execute("SELECT login FROM admins WHERE email=%s", (match.group(1), ))
        login = c.fetchone()[0]
        c.close()

        c = db.cursor()
        c.execute("INSERT INTO news VALUES ('', %s, %s, %s, %s, '')", (int(time.time()), title, description, login))
        c.close()

        c = db.cursor()
        c.execute("UPDATE admins SET news=news+1 WHERE login=%s", (login, ))
        c.close()

        db.close()

        print "News", i + 1, "/", numMessages

    pop3.dele(i + 1)

  print numMessages, "mails processed."
  pop3.quit()

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

# fin de interlope.py
