PageRenderTime 179ms CodeModel.GetById 127ms RepoModel.GetById 1ms app.codeStats 0ms

/server/irc2you-server.py

https://code.google.com/
Python | 267 lines | 250 code | 16 blank | 1 comment | 3 complexity | 8e8e920d1df5be6f47572be8303da3a9 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #!/usr/bin/env python
  2. import logging
  3. log = logging.getLogger('notify')
  4. log.setLevel(logging.DEBUG)
  5. ch = logging.StreamHandler()
  6. ch.setLevel(logging.DEBUG)
  7. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  8. ch.setFormatter(formatter)
  9. log.addHandler(ch)
  10. import threading
  11. import os
  12. import sys
  13. import tempfile
  14. import SocketServer
  15. import xml.dom.minidom
  16. import configmanager
  17. import struct
  18. import socket
  19. import pwd
  20. from lxml import etree
  21. from lxml import objectify
  22. from configmanager import configManager
  23. from Queue import Queue
  24. from threading import Thread
  25. def initParser(schemaFile):
  26. if not os.path.exists(schemaFile):
  27. log.error("Could not find schema for messages. There should be a "
  28. "file named '"+schemaFile+"' in the script directory")
  29. sys.exit(1)
  30. messageSchema = etree.XMLSchema(file=open(schemaFile, "r"))
  31. return objectify.makeparser(schema = messageSchema)
  32. messageParser = initParser("resources/irc2you_message.xsd")
  33. messageParserChannel = initParser("resources/irc2you_message_channel.xsd")
  34. channelList = initParser("resources/irc2you_channelList.xsd")
  35. getNick = initParser("resources/irc2you_getNick.xsd")
  36. listofSockets = []
  37. class MyHandler(SocketServer.StreamRequestHandler):
  38. def finish(self):
  39. log.debug("closing socket")
  40. SocketServer.StreamRequestHandler.finish(self)
  41. log.debug("socket closed")
  42. def handle(self):
  43. while(True):
  44. log.debug("waiting for message")
  45. messageXML = self.rfile.readline()
  46. if(messageXML == ''):
  47. break
  48. log.debug("Message: " + messageXML)
  49. # Find username from unix socket
  50. pid, uid, gid = struct.unpack('3i', \
  51. self.request.getsockopt(socket.SOL_SOCKET, 17, \
  52. struct.calcsize('3i')))
  53. username = pwd.getpwuid(uid).pw_name
  54. #log.debug("client: " + str(self.server.socket))
  55. log.debug("pid: " + str(pid) + " uid: " + str(uid) + " gid: " + str(gid))
  56. log.debug(pwd.getpwuid(uid))
  57. try:
  58. message = objectify.fromstring(messageXML, messageParser)
  59. conf = configManager.getConfig(username)
  60. log.info("listans lengd" + str(len(message.context.item)))
  61. channel=message.channel.text
  62. log.info("channel"+message.channel.text)
  63. log.info("nummer 0:"+message.context.item[0].text)
  64. if len(message.context.item) >1 :
  65. log.info("nummer 1:"+message.context.item[1].text)
  66. log.info("nummer len-1:"+message.context.item[len(message.context.item)-1].text)
  67. idNummber=message.context.item[0].text.rpartition(":")[2].rsplit(" ")[0]
  68. log.info("numret vi soker: "+idNummber)
  69. log.info("----------------|"+message.channel+"|||"+message.sender+"|")
  70. if message.channel == message.sender:
  71. log.info("righ channel")
  72. if "yes" == str(message.message):
  73. log.info("shood add nummer i config")
  74. confPath = os.path.expanduser("~"+username)+'/.irssi/irc2you_config.xml'
  75. log.info('confpath:'+confPath)
  76. confFile = open(confPath,"r")
  77. confString=""
  78. while confFile:
  79. row= str(confFile.readline())
  80. confString += row
  81. log.debug(row)
  82. s = row.split()
  83. n = len(s)
  84. if n == 0:
  85. break
  86. confFile.close()
  87. confFilewrite = open(confPath,"w")
  88. if confString.find("<param name=\"id\">")!= -1 :
  89. log.info("har redan en tel koplad till sig")
  90. else :
  91. log.info("har inte en tel koplad till sig")
  92. SplitString=confString.rpartition("<engine type=\"android\">")
  93. newfileString=SplitString[0]+SplitString[1]+"\n <param name=\"andriod-id\">"+idNummber+"</param>"+SplitString[2]
  94. log.info(newfileString)
  95. confFilewrite.write(newfileString)
  96. #write to file
  97. #for n in message.context.item:
  98. confFilewrite.close()
  99. if conf:
  100. for n in conf.notifiers:
  101. log.debug("Executing notifier")
  102. n.execute(message)
  103. except etree.XMLSyntaxError as element:
  104. try:
  105. log.debug("faild to parse as hiligth trying channel")
  106. channel = objectify.fromstring(messageXML, messageParserChannel)
  107. log.debug(channel.returnport)
  108. for conection in listofSockets:
  109. if str(channel.returnport) in conection:
  110. listofSockets.pop()
  111. returnString="<channel><name>"+channel.channelName+"</name><rows>"
  112. if hasattr(channel,'rows'):
  113. for arow in channel.rows:
  114. #conection[channel.returnport].send(channel.rows.from)
  115. returnString +="<arow><msg>"+str(arow.msg)+"</msg>"
  116. returnString +="<name>"+str(arow.fromUser)+"</name>"
  117. returnString +="<timestamp>"+str(arow.timestamp)+"</timestamp></arow>"
  118. returnString +="</rows></channel>"
  119. log.debug("sending to andriodclienten:"+returnString)
  120. conection[str(channel.returnport)].send(returnString);
  121. conection[str(channel.returnport)].close();
  122. log.debug("is in the list returng list")
  123. except etree.XMLSyntaxError as element:
  124. try:
  125. log.debug("faild to parse as hiligth AND channel get channelList")
  126. log.debug("len av listan:"+str(len(listofSockets)))
  127. removeInt=0
  128. channel = objectify.fromstring(messageXML, channelList)
  129. for conection in listofSockets:
  130. if str(channel.returnport) in conection:
  131. listofSockets.pop()
  132. returnString="<channelList>"
  133. if hasattr(channel,'achannel'):
  134. for arow in channel.achannel:
  135. returnString+="<channel>"+arow+"</channel>"
  136. returnString+="</channelList>"
  137. log.debug("sending to andriod: "+returnString)
  138. log.debug(str(conection.keys())+" vs "+ channel.returnport)
  139. con = conection[str(channel.returnport)]
  140. con.send(returnString)
  141. con.close()
  142. except etree.XMLSyntaxError as element:
  143. try:
  144. log.debug("faild to parse as hiligth AND channel AND channelList now on get nick")
  145. log.debug("len av listan:"+str(len(listofSockets)))
  146. removeInt=0
  147. channel = objectify.fromstring(messageXML, getNick)
  148. for conection in listofSockets:
  149. if str(channel.returnport) in conection:
  150. listofSockets.pop()
  151. returnString="<nick>"
  152. if hasattr(channel,'nick'):
  153. returnString+= channel.nick
  154. returnString+="</nick>"
  155. log.debug(returnString)
  156. log.debug(str(conection.keys())+" vs "+ channel.returnport)
  157. con = conection[str(channel.returnport)]
  158. con.send(returnString)
  159. con.close()
  160. except etree.XMLSyntaxError as element:
  161. log.warn("Failed to parse message. Message: " + element.msg + \
  162. ", XML: " + messageXML)
  163. log.debug("===== This line has been intentionally left brlank =====\n")
  164. def setup(self):
  165. log.debug("setting up socket")
  166. SocketServer.StreamRequestHandler.setup(self)
  167. self.messageQueue = Queue()
  168. t = Thread(target=self.message_sender)
  169. t.daemon = True
  170. t.start()
  171. pid, uid, gid = struct.unpack('3i', \
  172. self.request.getsockopt(socket.SOL_SOCKET, 17, \
  173. struct.calcsize('3i')))
  174. log.debug("uid till persson:" + str(uid));
  175. username = pwd.getpwuid(uid).pw_name
  176. conf = configManager.getConfig(username)
  177. conf.messageQueue = self.messageQueue
  178. log.debug("done setting up socket")
  179. def message_sender(self):
  180. while True:
  181. try:
  182. log.debug("[server->client] Waiting for message")
  183. item = self.messageQueue.get()
  184. log.debug("[server->client] Got message " + str(item))
  185. # Todo: Determine format of item
  186. # Todo: validation of item
  187. log.debug("order:"+item['order'] +"|");
  188. if item['order'] in "send" :
  189. row="<send><order>send</order><channel>"+item['channel']+"</channel><message>"+item['message']+"</message></send>\n"
  190. log.debug("send: "+row)
  191. self.wfile.write(row)
  192. elif item['order'] in "getchanel" :
  193. listofSockets.append(dict({str(item['port']):item['conection']}))
  194. row = "<send><order>getchanel</order><returnport>" + str(item['port']) + "</returnport><channel>" + str(item['channel']) + "</channel></send>\n";
  195. log.debug("sending getchanel:"+row)
  196. self.wfile.write(row)
  197. elif item['order'] in "getChanelList" :
  198. log.debug("getChanelList +")
  199. log.debug(str(item['port'])+" ")
  200. listofSockets.append(dict({str(item['port']):item['conection']}))
  201. row = "<send><order>getchanelList</order><returnport>" + str(item['port']) + "</returnport></send>\n"
  202. log.debug("row :"+row)
  203. self.wfile.write(row)
  204. elif item['order'] in "getNick" :
  205. log.debug("getNick +")
  206. log.debug(str(item['port'])+" ")
  207. listofSockets.append(dict({str(item['port']):item['conection']}))
  208. row = "<send><order>getNick</order><returnport>" + str(item['port']) + "</returnport></send>\n"
  209. log.debug("row :"+row)
  210. self.wfile.write(row)
  211. else :
  212. log.debug("can not read line irc2you-server row ")
  213. log.debug("-----------------------")
  214. self.messageQueue.task_done()
  215. except Exception as e:
  216. print e
  217. def main(*args):
  218. class ThreadingUnixStreamServer(SocketServer.ThreadingMixIn, \
  219. SocketServer.UnixStreamServer): pass
  220. log.debug("starting server")
  221. # Set named socket path and delete old socket, if any
  222. namedsocket = os.path.join(tempfile.gettempdir(), 'irc2you_socket')
  223. if(os.path.exists(namedsocket)):
  224. os.remove(namedsocket)
  225. #server = SocketServer.UnixStreamServer(namedsocket, MyHandler)
  226. server = ThreadingUnixStreamServer(namedsocket, MyHandler)
  227. os.chmod(namedsocket, 0777)
  228. log.debug("Starting server...")
  229. server.serve_forever()
  230. return 0
  231. if __name__ == '__main__':
  232. sys.exit(main(*sys.argv))