meshenger/meshenger_clientserve.py

79 lines
1.8 KiB
Python
Raw Normal View History

2014-04-04 18:39:32 +02:00
#!/usr/bin/python
import logging
import cgi
import os
import socket
from BaseHTTPServer import HTTPServer
2014-04-04 18:39:32 +02:00
import SimpleHTTPServer
import urlparse
2014-04-28 22:44:59 +02:00
import unicodedata
2014-04-04 18:39:32 +02:00
2014-04-28 22:44:59 +02:00
class ClientServeHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
2014-04-28 23:57:39 +02:00
messageDir = "msg"
"""
Serve index and messages
"""
def do_GET(self):
2014-04-28 23:49:38 +02:00
if self.path == '/':
2014-04-28 23:49:38 +02:00
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
f = os.path.join( "webapp.html")
with open( f, 'r') as the_file:
self.wfile.write(the_file.read())
2014-04-28 23:57:39 +02:00
elif self.path == '/index' or self.path.startswith( "/"+self.messageDir ):
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
else:
self.send_response(200) #serve the webapp on every url requested
2014-04-04 18:39:32 +02:00
self.send_header('Content-type', 'text/html')
self.end_headers()
f = os.path.join( "webapp.html")
with open( f, 'r') as the_file:
self.wfile.write(the_file.read())
2014-04-04 18:39:32 +02:00
"""
Allow clients to post messages
"""
def do_POST(self):
if self.path == '/send':
2014-04-04 18:39:32 +02:00
length = int(self.headers['Content-Length'])
post_data = urlparse.parse_qs(self.rfile.read(length).decode('utf-8'))
2014-04-28 22:44:59 +02:00
self.writeMessage( post_data["time"][0].encode('ascii','ignore'), post_data["message"][0])
2014-04-04 18:39:32 +02:00
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('message created')
def writeMessage(self, time, message):
2014-04-28 22:44:59 +02:00
f = os.path.join( self.messageDir, time)
2014-04-04 18:39:32 +02:00
if os.path.isfile( f ):
return
with open( f, 'a') as the_file:
the_file.write(message)
2014-04-28 22:44:59 +02:00
class ClientServe():
def __init__(self, port):
2014-04-28 22:44:59 +02:00
server = HTTPServer( ('', port), ClientServeHandler)
server.serve_forever()
def main():
2014-04-28 22:44:59 +02:00
clientServe = ClientServe(80)
if __name__ == '__main__':
main()