#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys,os
import re
import ConfigParser

import memcache
import urlparse
import smtplib
from email.mime.text import MIMEText
import urlparse

from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler

class RequestHandler(BaseHTTPRequestHandler):
    def sendmail(self, email):
        sender = 'admin@xxx.com'
        mailto = email       
        #邮件信息
        msg =MIMEText("new password is 365im")
        msg['Subject'] = 'reg ok'
        msg['to'] = mailto
        msg['From'] = sender
        
        #连接发送服务器
        smtp = smtplib.SMTP('mail.xxx.com')
        smtp.login('admin@xxx.com', 'password')
        
        #发送
        smtp.sendmail(sender,mailto,msg.as_string())
        smtp.quit()
        print 'Send OK'
        
    def checkAccountValid(self, email): #返回0表示此邮箱可用
         
        if len(email) < 6: #x@a.cn,最少6个符
            return -1
        
        if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) == None:
            return -2
        
        value = mc.get(email)
        if (value == None):
            return 0

        return 1
    
    def _writeheaders(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
    def do_HEAD(self):
        self._writeheaders()
    def do_GET(self):
        self._writeheaders()
        #4011,4012,4013,4014 total 4 xmpp client, idle or busy can get from memcached
        #self.wfile.write(self.path[0:14])
        ret='0'
       
        if self.path[0:12] == '/reg_new_user': #http://xxx/reg_new_user/user,pw,time,code
         
            url=self.path[12:];
            #ret=str2;
            strlist=url.split(',')
            if len(strlist)!=4:
                ret='0';
            else:
                mail=strlist[0]
                #pw=strlist[1]
                time=strlist[2]
                code=strlist[3]
                if (self.checkAccountValid(mail) == 0):
                    value="365im"+"|"+time+code
                    mc.set(mail, value)
               
        else:
            ret='0'
        self.wfile.write(ret)
        

host = ''
port = 5300
memcache_host='ip:port'

try:
    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    host=config.get('serverinfo', 'host')
    port=config.get('serverinfo', 'port')
    memcache_host = config.get('serverinfo', 'memcache')
    print 'Init OK'
		serveraddr = (host, int(port))
		mc = memcache.Client([memcache_host],debug=0)
		srvr = HTTPServer(serveraddr,RequestHandler)
		srvr.serve_forever()
  
except:
    print 'Open failled'
    exit()



