#coding=utf8
import SocketServer,urllib2,urllib,os,time
from random import Random
import os
import ConfigParser
import md5

def Log(data):
  LogFile = open("../Log/Log","a")
  ISOTIMEFORMAT='%Y-%m-%d %X'
  LogFile.write("-"*50+"\n"+time.strftime( ISOTIMEFORMAT, time.localtime( time.time() ) )+":\n"+data+"\n")
  LogFile.close()

def RetValue(ID,Key):
  if(os.path.exists("../User/Team/"+ID+"/"+Key) == True):
    return open("../User/Team/"+ID+"/"+Key,"r").read()
  else:
    return ""

def RetName(ID):
  return open("../User/Name/"+ID,"r").read()

def RetTeamList():
  path = "../User/Team/"
  for i in os.walk(path):
    return i[1]

def RetDataCount(ID):
  path = "../User/Team/"+ID+"/"
  count = 0
  for i in os.walk(path):
    return len(i[2])

def random_str(randomlength=8): 
    str = ''  
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random() 
    for i in range(randomlength): 
        str+=chars[random.randint(0, length)]
    return str

def GetMD5(toMD5):
  m1 = md5.new()
  m1.update(toMD5)
  return m1.hexdigest()

def HandleReg(ID,NAME,PW):
  if(ID.find(">")>=0 or NAME.find(">")>=0):
    return 3
  if(ID=="" or NAME=="" or PW ==""):
    return 1
  elif(os.path.exists("../User/Password/"+ID) == True):
    return 2
  else: 
    UserFile = open("../User/Password/"+ID,"w")
    UserFile.write(GetMD5(PW))
    UserFile.close()
    UserFile = open("../User/Name/"+ID,"w")
    UserFile.write(NAME);
    UserFile.close()
    os.makedirs("../User/Team/"+ID+"/")
  return 0

def HandleLogin(ID,PW):
  if(ID=="" or PW ==""):
    return 1
  elif(os.path.exists("../User/Password/"+ID) == False):
    return 2
  if(GetMD5(PW) == open("../User/Password/"+ID).read()):
    LoginCookies = random_str()
    UserFile = open("../User/Cookies/"+ID,"w")
    UserFile.write(LoginCookies)
    UserFile.close()
  else:
    return 3
  return 0

def GetConfig(secs,key):
  cf = ConfigParser.ConfigParser()
  cf.read("../Seting/Seting.ini")
  return cf.get(secs,key)

def GetMoName(MoID):
  try:
    return open("../User/Name/"+MoID).read()
  except:
    return ""

def GetMoCookies(MoID):
  try:
    return open("../User/Cookies/"+MoID).read()
  except:
    return ""

def DealIndex():
  WebFile = open("../Web/index.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("Index","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("Index","PageTitle"),1)
  WebFileData = WebFileData.replace("%&Tips&%",GetConfig("Index","Tips"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("Index","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("Index","About2"),1)
  WebFileData = WebFileData.replace("%&RegName&%",GetConfig("Index","RegName"),1)
  WebFileData = WebFileData.replace("%&LoginName&%",GetConfig("Index","LoginName"),1)
  return WebFileData

def DealAdmin():
  WebFile = open("../Web/admin.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("AdminPage","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("AdminPage","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("AdminPage","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("AdminPage","About2"),1)
  return WebFileData

def DealReg():
  WebFile = open("../Web/reg.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("Reg","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("Reg","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("Reg","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("Reg","About2"),1)
  WebFileData = WebFileData.replace("%&MoNumberName&%",GetConfig("Reg","MoNumberName"),1)
  WebFileData = WebFileData.replace("%&MoNameName&%",GetConfig("Reg","MoNameName"),1)
  WebFileData = WebFileData.replace("%&MoPasswordName&%",GetConfig("Reg","MoPasswordName"),1)
  return WebFileData

def DealLogin():
  WebFile = open("../Web/login.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("Login","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("Login","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("Login","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("Login","About2"),1)
  WebFileData = WebFileData.replace("%&MoNumberName&%",GetConfig("Reg","MoNumberName"),1)
  WebFileData = WebFileData.replace("%&MoPasswordName&%",GetConfig("Reg","MoPasswordName"),1)
  return WebFileData

def PostDealReg(_ClientData):
  WebFile = open("../Web/regpost.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("RegPost","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("RegPost","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("RegPost","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("RegPost","About2"),1)
  MoNumber = _ClientData[_ClientData.find("MoNumber=")+len("MoNumber="):]
  MoNumber = MoNumber[:MoNumber.find("&")]
  MoName = _ClientData[_ClientData.find("MoName=")+len("MoName="):]
  MoName = urllib.unquote(MoName[:MoName.find("&")])
  MoPassword = _ClientData[_ClientData.find("MoPassword=")+len("MoPassword="):]
  RegReturn = HandleReg(MoNumber,MoName,MoPassword)
  if(RegReturn == 0):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("RegPost","TipsSuccess"),1)
  elif(RegReturn == 1):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("RegPost","TipsNone"),1)
  elif(RegReturn == 2):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("RegPost","TipsExists"),1)
  elif(RegReturn == 3):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("RegPost","TipsNo"),1)
  return WebFileData

def GetMainList(MoID,First):
  RetHTMLForm = ""
  cf = ConfigParser.ConfigParser()
  cf.read("../Seting/Seting.ini")
  for key in cf.options("Main"):
    keyvalue = GetConfig("Main",key)
    if(First == 0):
      #首次登录
      if(keyvalue[:3] == "str"):
        RetHTMLForm = RetHTMLForm + '<tr><td>'+keyvalue[4:]+':</td><td><input name="'+key+'" type="text" value="" style="font-family: \'微软雅黑\';font-size: 16px;"/></td></tr>\r\n'
      elif(keyvalue[:3] == "int"):
        RetHTMLForm = RetHTMLForm + '<tr><td>'+keyvalue[4:]+':</td><td><input name="'+key+'" type="number" value="" style="font-family: \'微软雅黑\';font-size: 16px;"/></td></tr>\r\n'
      elif(keyvalue[:3] == "ins"):
        if(keyvalue[4:] == "0"):
          RetHTMLForm = RetHTMLForm + '<tr><td>'+GetConfig("Reg","MoNumberName")+':</td><td><p style="font-family: \'微软雅黑\';font-size: 16px;">'+MoID+'</p></td></tr>\r\n'
        elif(keyvalue[4:] == "1"):
          RetHTMLForm = RetHTMLForm + '<tr><td>'+GetConfig("Reg","MoNameName")+':</td><td><p style="font-family: \'微软雅黑\';font-size: 16px;">'+GetMoName(MoID)+'</p></td></tr>\r\n'
    else:
      if(keyvalue[:3] == "str"):
        if(os.path.exists("../User/Team/"+MoID+"/"+key) == True):
          Value = open("../User/Team/"+MoID+"/"+key).read()
        else:
          Value = ""
        RetHTMLForm = RetHTMLForm + '<tr><td>'+keyvalue[4:]+':</td><td><input name="'+key+'" type="text" value="'+Value+'" style="font-family: \'微软雅黑\';font-size: 16px;"/></td></tr>\r\n'
      elif(keyvalue[:3] == "int"):
        if(os.path.exists("../User/Team/"+MoID+"/"+key) == True):
          Value = open("../User/Team/"+MoID+"/"+key).read()
        else:
          Value = ""
        RetHTMLForm = RetHTMLForm + '<tr><td>'+keyvalue[4:]+':</td><td><input name="'+key+'" type="number" value="'+Value+'" style="font-family: \'微软雅黑\';font-size: 16px;"/></td></tr>\r\n'
      elif(keyvalue[:3] == "ins"):
        if(keyvalue[4:] == "0"):
          RetHTMLForm = RetHTMLForm + '<tr><td>'+GetConfig("Reg","MoNumberName")+':</td><td><p style="font-family: \'微软雅黑\';font-size: 16px;">'+MoID+'</p></td></tr>\r\n'
        elif(keyvalue[4:] == "1"):
          RetHTMLForm = RetHTMLForm + '<tr><td>'+GetConfig("Reg","MoNameName")+':</td><td><p style="font-family: \'微软雅黑\';font-size: 16px;">'+GetMoName(MoID)+'</p></td></tr>\r\n'
  return RetHTMLForm

def LoginSuccess(_LoginNumber):
  WebFile = open("../Web/main.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("MainPage","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("MainPage","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("MainPage","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("MainPage","About2"),1)
  WebFileData = WebFileData.replace("%&Cookies&%",GetMoCookies(_LoginNumber),1)
  WebFileData = WebFileData.replace("%&LoginID&%",_LoginNumber,1)
  if(RetDataCount(_LoginNumber) == 0):
    #首次登录
    WebFileData = WebFileData.replace("%&Form&%",GetMainList(_LoginNumber,0),1)
  else:
    WebFileData = WebFileData.replace("%&Form&%",GetMainList(_LoginNumber,1),1)
  return WebFileData
  
def PostDealLogin(_ClientData):
  WebFile = open("../Web/loginpost.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("LoginPost","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("LoginPost","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("LoginPost","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("LoginPost","About2"),1)
  LoginNumber = _ClientData[_ClientData.find("LoginNumber=")+len("LoginNumber="):]
  LoginNumber = LoginNumber[:LoginNumber.find("&")]
  LoginPassword = _ClientData[_ClientData.find("LoginPassword=")+len("LoginPassword="):]
  LoginRet = HandleLogin(LoginNumber,LoginPassword)
  if(LoginRet == 0):
    return LoginSuccess(LoginNumber)
  elif(LoginRet == 1):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("LoginPost","TipsNone"),1)
  elif(LoginRet == 2):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("LoginPost","TipsNoExists"),1)
  elif(LoginRet == 3):
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("LoginPost","TipsErrPW"),1)
  return WebFileData

def PostDealChange(_ClientData):
  RetHTMLTable = ""
  WebFile = open("../Web/changepost.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("ChangePage","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("ChangePage","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("ChangePage","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("ChangePage","About2"),1)
  LoginKey = _ClientData[_ClientData.find("LoginKey=")+len("LoginKey="):]
  LoginKey = LoginKey[:LoginKey.find("&")]
  LoginID = _ClientData[_ClientData.find("LoginID=")+len("LoginID="):]
  LoginID = LoginID[:LoginID.find("&")]
  if(GetMoCookies(LoginID) == LoginKey): 
    ParamsList = []
    ParamsValueList = []
    ParamsNameList = []
    cf = ConfigParser.ConfigParser()
    cf.read("../Seting/Seting.ini")
    for key in cf.options("Main"):
      keyvalue = GetConfig("Main",key)
      if(keyvalue[:3] == "str" or keyvalue[:3] == "int"):
        ParamsList.append(key)
        ParamsNameList.append(keyvalue[4:])
    for key in ParamsList:
      ParamsValue = _ClientData[_ClientData.find(key+"=")+len(key+"="):]
      ParamsValue = ParamsValue[:ParamsValue.find("&")]
      ParamsValueList.append(urllib.unquote(ParamsValue))
      print urllib.unquote(ParamsValue)
      if(urllib.unquote(ParamsValue).find(">")>=0):
        WebFileData = WebFileData.replace("%&Tips&%",GetConfig("ChangePage","TipsNoNo"),1)
        WebFileData = WebFileData.replace("%&Table&%","",1)
        return WebFileData
    for key in range(0,len(ParamsList)):
      RetHTMLTable = RetHTMLTable + '<tr style="background-color: aliceblue;"><td style="width:50%">'+ParamsNameList[key]+'</td><td style="width:50%">'+ParamsValueList[key]+'</td></tr>\r\n'
      UserFile = open("../User/Team/"+LoginID+"/"+ParamsList[key],"w")
      UserFile.write(ParamsValueList[key])
      UserFile.close()
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("ChangePage","TipsSuccess"),1)
    WebFileData = WebFileData.replace("%&Table&%",RetHTMLTable,1)
  else:
    WebFileData = WebFileData.replace("%&Tips&%",GetConfig("ChangePage","TipsNo"),1)
  return WebFileData

def PostDealAdmin(_ClientData):
  RetHTMLTable = ""
  WebFile = open("../Web/adminmain.html","r")
  WebFileData = WebFile.read()
  WebFile.close()
  WebFileData = WebFileData.replace("%&Title&%",GetConfig("AdminPost","Title"),1)
  WebFileData = WebFileData.replace("%&PageTitle&%",GetConfig("AdminPost","PageTitle"),1)
  WebFileData = WebFileData.replace("%&About1&%",GetConfig("AdminPost","About1"),1)
  WebFileData = WebFileData.replace("%&About2&%",GetConfig("AdminPost","About2"),1)
  WebFileData = WebFileData.replace("%&ListName1&%",GetConfig("AdminPost","ListName1"),1)
  WebFileData = WebFileData.replace("%&ListName2&%",GetConfig("AdminPost","ListName2"),1)
  AdminName = _ClientData[_ClientData.find("LoginNumber=")+len("LoginNumber="):]
  AdminName = AdminName[:AdminName.find("&")]
  AdminPW = _ClientData[_ClientData.find("LoginPassword=")+len("LoginPassword="):]
  AdminPW = GetMD5(AdminPW)
  if(AdminName == GetConfig("Admin","Name") and AdminPW == GetConfig("Admin","Password")):
    WebFileData = WebFileData.replace("%&Count&%",str(len(RetTeamList())),1)
    cf = ConfigParser.ConfigParser()
    cf.read("../Seting/Seting.ini")
    for ID in RetTeamList():
      RetHTMLTable = RetHTMLTable + '<tr><td>'+GetConfig("Reg","MoNameName")+':'+RetName(ID)+"<br>"+GetConfig("Reg","MoNumberName")+':'+ID+'</td><td>'
      for key in cf.options("Main"):
        keyvalue = GetConfig("Main",key)
        if(keyvalue[:3] == "str" or keyvalue[:3] == "int"):
          if(RetDataCount(ID) != 0):
            RetHTMLTable = RetHTMLTable + keyvalue[4:] + ':' + RetValue(ID,key) + "<br>"
      RetHTMLTable = RetHTMLTable + '</td></tr>'
    WebFileData = WebFileData.replace("%&Table&%",RetHTMLTable,1)
    return WebFileData
  return ""



class MyRequestHandler(SocketServer.BaseRequestHandler):
  def handle(self):
    Log('客户端请求地址:'+str(self.client_address))
    print u'客户端请求地址:', self.client_address
    ClientData=self.request.recv(10240)
    Log(ClientData)
    print ClientData
    self.request.send("HTTP/1.1 200 OK\nContext-Type: text/html\n\n")
    if(ClientData.find("GET ")>=0):
      GetPath=ClientData[ClientData.find("GET ")+len("GET "):]
      GetPath=GetPath[:GetPath.find(" HTTP/1.1")]
      Log("客户端请求GET："+GetPath)
      print u"客户端请求GET：", GetPath
      if(GetPath == '/'):
        self.request.send(DealIndex())       
      elif(GetPath == '/Image/Logo.png'):
        WebFile = open("../Web/Image/Logo.png","rb")
        self.request.send(WebFile.read())
        WebFile.close()
      elif(GetPath == '/reg'):
        self.request.send(DealReg())
      elif(GetPath == '/login'):
        self.request.send(DealLogin())
      elif(GetPath == '/'+GetConfig("Admin","Path")):
        self.request.send(DealAdmin())
    elif(ClientData.find("POST ")>=0):
      PostPath=ClientData[ClientData.find("POST ")+len("POST "):]
      PostPath=PostPath[:PostPath.find(" HTTP/1.1")]
      Log("客户端请求POST："+PostPath)
      print u"客户端请求POST：", PostPath
      if(PostPath == '/regpost'):
        self.request.send(PostDealReg(ClientData))
      elif(PostPath == '/loginpost'):
        self.request.send(PostDealLogin(ClientData))
      elif(PostPath == '/chagepost'):
        self.request.send(PostDealChange(ClientData))
      elif(PostPath == '/adminlogin'):
        self.request.send(PostDealAdmin(ClientData))

tcpServ = SocketServer.ThreadingTCPServer((GetConfig("Net","Domain"),int(GetConfig("Net","Port"))), MyRequestHandler)
Log('ProjectSU服务程序启动完毕')
print u'ProjectSU服务程序启动完毕'
Log('201611161347修订版本')
print u'201611161347修订版本'
print u"浏览器输入 http://"+GetConfig("Net","Domain")+":"+GetConfig("Net","Port")
tcpServ.serve_forever()
