PageRenderTime 48ms CodeModel.GetById 2ms app.highlight 39ms RepoModel.GetById 0ms app.codeStats 1ms

/New.py

https://bitbucket.org/dlrrb4714/uoa-cs302-2018-p2-ilee471
Python | 623 lines | 608 code | 3 blank | 12 comment | 2 complexity | f0d5a272ade5019cd0b677f58d99765c MD5 | raw file
  1    #!/usr/bin/python
  2""" cherrypy_example.py
  3
  4    COMPSYS302 - Software Design
  5    Author: Andrew Chen (andrew.chen@auckland.ac.nz)
  6    Last Edited: 19/02/2018
  7
  8    This program uses the CherryPy web server (from www.cherrypy.org).
  9"""
 10# Requires:  CherryPy 3.2.2  (www.cherrypy.org)
 11#            Python  (We use 2.7)
 12
 13# The address we listen for connections on
 14listen_ip = "0.0.0.0"
 15listen_port = 10002
 16
 17import cherrypy
 18import hashlib
 19import urllib2
 20import sqlite3
 21import json
 22import time
 23import socket
 24import base64
 25import mimetypes
 26import os
 27import os.path
 28import threading
 29import atexit
 30
 31openUser = ""
 32loggedIn = 0
 33user_id = ""
 34user_password = ""
 35
 36class MainApp(object):
 37
 38    #CherryPy Configuration
 39    _cp_config = {'tools.encode.on': True, 
 40                  'tools.encode.encoding': 'utf-8',
 41                  'tools.sessions.on' : 'True',
 42                 }                 
 43
 44    # If they try somewhere we don't know, catch it here and send them to the right place.
 45
 46    def __init__(self):
 47        cherrypy.engine.subscribe("stop", self.logoutOnExit)
 48
 49    @cherrypy.expose
 50    def default(self, *args, **kwargs):
 51        """The default page, given when we don't recognise where the request is for."""
 52        Page = "I don't know where you're trying to go, so have a 404 Error."
 53        cherrypy.response.status = 404
 54        return Page
 55
 56    # PAGES (which return HTML that can be viewed in browser)
 57    @cherrypy.expose
 58    def index(self):
 59        Page = "Welcome! This is a test website for COMPSYS302!<br/>"
 60        
 61        try:
 62            # Page += "Hello " + cherrypy.session['username'] + "!<br/>"
 63            # Page += "Here is some bonus text because you've logged in!<br/>"
 64            # Page += "Click here to <a href = 'usersOnline'>check online users.<a/><br/>"
 65            # Page += '<form action = "/sendMessage" method = "post" enctype="multipart/form-data">'
 66            # Page += 'To : <input type = "text" name = "destination"/><br/>'
 67            # Page += 'Message : <input type = "text" name = "message"/>'
 68            # Page += '<input type = "submit" value = "Send"/></form>'
 69            # Page += '<form action="/messages" method="post" enctype="multipart/form-data">'
 70            # Page += '<input type = "submit" value = "Check Messages"/></form>'
 71            # Page += '<form action="/retrieveProfile" method="post" enctype="multipart/form-data">'
 72            # Page += '<input type = "text" name = "prof"/>'
 73            # Page += '<input type = "submit" value = "Check Profile"/></form>'
 74            # Page += '<form action="/updateProfile" method="post" >'
 75            # Page += 'Name : <input type = "text" name = "fullname"/>'
 76            # Page += 'Position : <input type = "text" name = "position"/>'
 77            # Page += 'Description : <input type = "text" name = "description"/>'
 78            # Page += 'Location : <input type = "text" name = "location"/>'
 79            # Page += 'Picture : <input type = "file" name = "profile"/>'
 80            # Page += '<input type = "submit" value = "Update Profile"/></form>'
 81            # Page += '<form action="/sendFile" method="post" enctype="multipart/form=data">'
 82            # Page += 'To : <input type = "text" name = "destination"/><br/>'
 83            # Page += 'File : <input type = "file" name = "file"/>'
 84            # Page += '<input type = "submit" value = "Send"/></form>'
 85            # Page += '<form action="/logout" method="post" enctype="multipart/form-data">'
 86            # Page += '<input type ="submit" value = "Logout"/></form>'
 87            return self.loadMainPage()
 88
 89        except KeyError: #There is no username
 90            Page += "Click here to <a href='login'>login</a>."
 91        return Page
 92
 93    @cherrypy.expose
 94    def loadMainPage(self):
 95        conn = sqlite3.connect("profiles.db")
 96        c = conn.cursor()
 97        c.execute('''SELECT fullname, position, description, location, picture FROM profiles WHERE username = ?''',
 98                  (cherrypy.session['username'],))
 99        rows = c.fetchall()
100        print rows
101        self.usersOnline()
102        return open('html/mainpage.html').read().format(username=self.makeUserList(), fullname=rows[0][0],
103                                                        position=rows[0][1], description=rows[0][2],
104                                                        location=rows[0][3], picture=rows[0][4])
105
106    def makeUserList(self):
107        users = json.loads(self.getList())
108        userlist = '<form action="/loadMessages" method="post">'
109        for i in users:
110            userlist += '<button name="username" value="' + users[i]["username"] + '">' + users[i]["username"] + "</button><br/>"
111        userlist += '</form>'
112        return userlist
113
114    @cherrypy.expose
115    def loadUpdateProfile(self):
116        return open('html/updateprofile.html').read().format(username=self.makeUserList())
117
118    @cherrypy.expose
119    def loadMessages(self, username=None):
120        global openUser
121        openUser = username
122        users = json.loads(self.getList())
123        messageList = ""
124        conn = sqlite3.connect("messages.db")
125        c = conn.cursor()
126        try:
127            c.execute(
128                '''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
129        except sqlite3.OperationalError:
130            pass
131        if openUser == cherrypy.session['username']:
132            c.execute(
133                '''SELECT sender, destination, message, stamp, file, filetype FROM messages WHERE sender = ? AND destination = ?''',
134                (cherrypy.session['username'],cherrypy.session['username']))
135            rows = c.fetchall()
136            print rows
137            for i in rows:
138                if i[4] == 0:
139                    messageList += '<h1 class = "mine">' + i[2] + "<h1/><br/>"
140                else:
141                    if i[4] == 1:
142                        if i[5].find("image") != -1:
143                            messageList += '<img class = "mine" width="20%" src ="' + i[2] + '" alt = "Received File"><img/>'
144                        elif i[5].find("video") != -1:
145                            messageList += '<video class = "mine" width="20%" controls src="' + i[2] + '"><video/>'
146                        elif i[5].find("audio") != -1:
147                            messageList += '<audio class = "mine" controls src="' + i[2] + '"><audio/>'
148                        elif i[5].find("application") != -1:
149                            messageList += '<a class = "mine pdf" ' + "href = '" + i[2] + "'>" + i[2] + "<a/>"
150        else:
151            for i in users:
152                if users[i]["username"] == username:
153                    c.execute('''SELECT sender, destination, message, stamp, file, filetype FROM messages WHERE sender = ? OR destination = ?''', (username, username))
154                    rows = c.fetchall()
155                    print rows
156                    for i in rows:
157                        if i[0] == cherrypy.session['username']:
158                            if i[4] == 0:
159                                messageList += '<h1 class = "mine">' + i[2] + "<h1/><br/>"
160                            else:
161                                if i[5].find("image") != -1:
162                                    messageList += '<img class = "mine" src ="' + i[2] + '" alt = "Received File"><img/><br/>'
163                                elif i[5].find("video") != -1:
164                                    messageList += '<video class = "mine" width="300" height = "200" controls src="' + i[2] + '"><video/><br/>'
165                                elif i[5].find("audio") != -1:
166                                    messageList += '<audio class = "mine" controls src="' + i[2] + '"><audio/><br/>'
167                                elif i[5].find("application") != -1:
168                                    messageList += '<a class = "mine pdf" ' + "href = '" + i[2] + "'>" + i[2] + "<a/><br/>"
169                        else:
170                            if i[4] == 0:
171                                messageList += '<h1 class = "theirs">' + i[2] + "<h1/><br/>"
172                            else:
173                                if i[4] == 1:
174                                    if i[5].find("image") != -1:
175                                        messageList += '<img class = "theirs" src ="' + i[2] + '" alt = "Received File"><img/><br/>'
176                                    elif i[5].find("video") != -1:
177                                        messageList += '<video class = "theirs" width="300" height = "200" controls src="' + i[2] + '"><video/><br/>'
178                                    elif i[5].find("audio") != -1:
179                                        messageList += '<audio class = "theirs" controls src="' + i[2] + '"><audio/><br/>'
180                                    elif i[5].find("application") != -1:
181                                        messageList += '<a class = "mine pdf" ' + "href = '" + i[2] + "'>" + i[2] + "<a/><br/>"
182                    print messageList
183        self.retrieveProfile(openUser)
184        conn = sqlite3.connect("profiles.db")
185        c = conn.cursor()
186        c.execute('''SELECT fullname, position, description, location, picture FROM profiles WHERE username = ?''', (openUser,))
187        rows = c.fetchall()
188        return open('html/messages.html').read().format(username=self.makeUserList(), messages=messageList,
189                                                        fullname=rows[0][0], position=rows[0][1],
190                                                        description=rows[0][2], location=rows[0][3],
191                                                        picture=rows[0][4])
192
193    @cherrypy.expose
194    def loadOnlineUsers(self):
195        users = json.loads(self.getList())
196        list = ""
197        for i in users:
198            list += "<button>" + i + "</button>"
199        open('html/mainpage.html').read().format(username = list)
200
201    @cherrypy.expose
202    def login(self):
203
204        return open('html/1.html').read()
205    
206        # Page = '<form action="/signin" method="post" enctype="multipart/form-data">'
207        # Page += 'Username: <input type="text" name="username"/><br/>'
208        # Page += 'Password: <input type="password" name="password"/>'
209        # Page += '<input type="submit" value="Poos"/></form>'
210        # return Page
211
212    @cherrypy.expose
213    def loggedoff(self):
214        Page = "You have successfully logged off!<br/>"
215        Page += "Click here to <a href = 'login'>login again</a>."
216        return Page
217
218    @cherrypy.expose
219    def logofferror(self):
220        Page = 'Something went wrong! You may have not been logged in.<br/>'
221        Page += "Click here to <a href = 'login'>return to the login page</a>."
222        return Page
223
224    @cherrypy.expose
225    def messages(self):
226        Page = 'Messages:<br/><br/>'
227        conn = sqlite3.connect("messages.db")
228        c = conn.cursor()
229        try:
230            c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
231        except sqlite3.OperationalError:
232            pass
233        c.execute('''SELECT * FROM messages''')
234
235        rows = c.fetchall()
236        print rows
237        for i in rows:
238            Page += "Sender : " + str(i[1]) + "<br/>"
239            Page += "Destination : " + str(i[2]) + "<br/>"
240            Page += "Message : " + str(i[3]) + "<br/>"
241            Page += "Stamp : " + str(i[4]) + "<br/>" + "<br/>"
242        conn.close()
243        return Page
244
245    @cherrypy.expose
246    def sum(self, a=0, b=0): #All inputs are strings by default
247        output = int(a)+int(b)
248        return str(output)
249
250    @cherrypy.expose
251    def ping(self, sender):
252        return '0'
253
254    @cherrypy.expose
255    def getList(self):
256        username = cherrypy.session['username']
257        password = cherrypy.session['password']
258        res = urllib2.urlopen("http://cs302.pythonanywhere.com/getList?username=" + username
259                              + "&password=" + password
260                              + "&json=1").read()
261        return res
262
263    @cherrypy.tools.json_in()
264    @cherrypy.expose
265    def receiveMessage(self):
266        received = cherrypy.request.json
267        conn = sqlite3.connect("messages.db")
268        c = conn.cursor()
269        try:
270            c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
271        except sqlite3.OperationalError:
272            pass
273        if received["sender"] == received["destination"]:
274            pass
275        else:
276            c.execute('''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES(?,?,?,?,?,?)''', (received["sender"], received["destination"], received["message"], received["stamp"], 0, ""))
277            conn.commit()
278        conn.close()
279        return '0'
280
281    @cherrypy.expose
282    def sendMessage(self, message = None):
283        username = cherrypy.session['username']
284        users = json.loads(self.getList())
285        # url = "http://" + users[i]["ip"] + ":" + users[i]["port"] + "/ping?sender=" + username
286        # if urllib2.urlopen(url).read() == '0':
287        conn = sqlite3.connect("messages.db")
288        c = conn.cursor()
289        try:
290            c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
291        except sqlite3.OperationalError:
292            pass
293        for i in users:
294            if users[i]["username"] == openUser and urllib2.urlopen("http://" + users[i]["ip"] + ":" + users[i]["port"] + "/ping?sender=" + username).read() == '0':
295                url = "http://" + users[i]["ip"] + ":" + users[i]["port"] + "/receiveMessage"
296                mes = { "sender" : cherrypy.session['username'], "destination" : openUser, "message" : message, "stamp" : time.time()}
297                data = json.dumps(mes)
298                req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
299                urllib2.urlopen(req)
300                c.execute('''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES(?,?,?,?,?,?)''', (username, openUser, message, time.time(), 0, "None"))
301                conn.commit()
302        conn.close()
303        return self.loadMessages(openUser)
304        # raise cherrypy.HTTPRedirect(/loadMessages?openUser)
305
306    @cherrypy.expose
307    def usersOnline(self):
308        res = json.loads(self.getList())
309        conn = sqlite3.connect("list.db")
310        c = conn.cursor()
311        try:
312            c.execute('''CREATE TABLE users(id INTEGER PRIMARY KEY, username TEXT, ip TEXT, location TEXT, lastLogin TEXT, port TEXT)''')
313        except sqlite3.OperationalError:
314            pass
315        c.execute('''DELETE FROM users''')
316        for i in res:
317            c.execute('''INSERT INTO users(username, ip, location, lastLogin, port) VALUES(?,?,?,?,?)''', (res[i]["username"],res[i]["ip"],res[i]["location"],res[i]["lastLogin"],res[i]["port"]))
318        conn.commit()
319        Page = ''
320        c.execute('''SELECT * FROM users''')
321        rows = c.fetchall()
322        for row in rows:
323            Page += "Username : " + str(row[1]) + "<br/>"
324            Page += "IP : " + str(row[2]) + "<br/>"
325            Page += "Location :" + str(row[3]) + "<br/>"
326            Page += "Last Login : " + str(row[4]) + "<br/>"
327            Page += "Port : " + str(row[5]) + "<br/>" + "<br/>"
328        conn.close()
329        return Page
330
331    @cherrypy.expose
332    def retrieveProfile(self, prof = None):
333        users = json.loads(self.getList())
334        conn = sqlite3.connect("profiles.db")
335        c = conn.cursor()
336        try:
337            c.execute('''CREATE TABLE profiles(username TEXT PRIMARY KEY, lastUpdated TEXT, fullname TEXT, position TEXT, description TEXT, location TEXT, picture TEXT, encoding TEXT, encryption TEXT, decryptionKey TEXT)''')
338        except sqlite3.OperationalError:
339            pass
340        for i in users:
341            if users[i]["username"] == prof:
342                url = 'http://' + users[i]["ip"] + ":" + users[i]["port"] + "/getProfile"
343                data = json.dumps({"profile_username" : prof, "sender" : cherrypy.session['username']})
344                req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
345                received = json.loads(urllib2.urlopen(req).read())
346                try:
347                    c.execute('''INSERT INTO profiles(username, lastUpdated, fullname, position, description, location, picture) VALUES(?,?,?,?,?,?,?)''', (prof, received["lastUpdated"], received["fullname"], received["position"], received["description"], received["location"], received["picture"]))
348                except sqlite3.IntegrityError:
349                    c.execute('''UPDATE profiles SET lastUpdated = ?, fullname = ?, position = ?, description = ?, location = ?, picture = ? WHERE username = ?''', (received["lastUpdated"], received["fullname"], received["position"], received["description"], received["location"], received["picture"], prof))
350                except KeyError:
351                    print "Error! Profile not valid"
352                    raise cherrypy.HTTPRedirect('/')
353                conn.commit()
354        conn.close()
355
356    @cherrypy.tools.json_in()
357    @cherrypy.expose
358    def getProfile(self):
359        received = cherrypy.request.json
360        conn = sqlite3.connect("profiles.db")
361        c = conn.cursor()
362        c.execute('''SELECT lastUpdated, fullname, position, description, location, picture FROM profiles WHERE username = ?''', (received['profile_username'],))
363        rows = c.fetchall()
364        profile = {"lastUpdated" : str(rows[0][0]), "fullname" : str(rows[0][1]), "position" : str(rows[0][2]), "description" : str(rows[0][3]), "location" : str(rows[0][4]), "picture" : str(rows[0][5])}
365        print profile
366        data = json.dumps(profile)
367        return data
368
369    @cherrypy.expose
370    def createInitialProfile(self):
371        conn = sqlite3.connect("profiles.db")
372        c = conn.cursor()
373        try:
374            c.execute('''CREATE TABLE profiles(username TEXT PRIMARY KEY, lastUpdated TEXT, fullname TEXT, position TEXT, description TEXT, location TEXT, picture TEXT, encoding TEXT, encryption TEXT, decryptionKey TEXT)''')
375        except sqlite3.OperationalError:
376            print "1"
377            pass
378        try:
379            c.execute(
380                '''INSERT INTO profiles(username, lastUpdated, fullname, position, description, location, picture) VALUES(?,?,?,?,?,?,?)''',
381                (cherrypy.session['username'], time.time(), "(No Name)", "", "", "", "static/whitesquare.jpg"))
382        except sqlite3.IntegrityError:
383            pass
384        conn.commit()
385        conn.close()
386
387    @cherrypy.expose
388    def updateProfile(self, fullname = None, position = None, description = None, location = None, profile = None):
389        username = cherrypy.session['username']
390        conn = sqlite3.connect("list.db")
391        c = conn.cursor()
392        c.execute('''SELECT ip, port FROM users WHERE username = ?''', (username,))
393        rows = c.fetchall()
394        conn = sqlite3.connect("profiles.db")
395        c = conn.cursor()
396        try:
397            f = open(profile, "r")
398            pic = f.name
399        except IOError:
400            pic = "whitesquare.jpg"
401            print pic
402        if fullname == "":
403            fullname = "(No Name)"
404        print fullname
405        try:
406            c.execute('''CREATE TABLE profiles(username TEXT PRIMARY KEY, username TEXT, lastUpdated TEXT, fullname TEXT, position TEXT, description TEXT, location TEXT, picture TEXT, encoding TEXT, encryption TEXT, decryptionKey TEXT)''')
407        except sqlite3.OperationalError:
408            pass
409        c.execute('''UPDATE profiles SET lastUpdated = ?, fullname = ?, position = ?, description = ?, location = ?, picture = ? WHERE username = ?''',
410                  (time.time(), fullname, position, description, location, "http://" + rows[0][0] + ":" + rows[0][1] + "/static/" + pic, "ilee471"))
411        conn.commit()
412        conn.close()
413        raise cherrypy.HTTPRedirect('/')
414
415    @cherrypy.tools.json_in()
416    @cherrypy.expose
417    def receiveFile(self):
418        received = cherrypy.request.json
419        decoded = base64.decodestring(received["file"])
420        cwd = os.getcwd()
421        os.chdir(cwd+"/files")
422        res = open(received["filename"], "wb")
423        res.write(decoded)
424        res.close()
425        os.chdir(cwd)
426        conn = sqlite3.connect("messages.db")
427        c = conn.cursor()
428        print received["content_type"]
429        try:
430            c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
431        except sqlite3.OperationalError:
432            pass
433        c.execute('''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES (?,?,?,?,?,?)''',
434                (received["sender"], received["destination"], "static/files/" + received["filename"], received["stamp"],
435                   1, received["content_type"]))
436        conn.commit()
437        conn.close()
438        return '0'
439
440    @cherrypy.expose
441    def sendFile(self, destination = None, file = None):
442        destination = openUser
443        # if destination is None or file is None:
444        #     raise cherrypy.HTTPRedirect('/')
445        users = json.loads(self.getList())
446        for i in users:
447            if users[i]["username"] == destination and urllib2.urlopen("http://" + users[i]["ip"] + ":" + users[i]["port"] + "/ping?sender=" + cherrypy.session['username']).read() == '0':
448                r = file.file.read()
449                file_data = base64.encodestring(r)  # base 64 encoding of file data
450                filename = file.filename
451                cwd = os.getcwd()
452                os.chdir(cwd + "/files")
453                save = open(filename, "wb")
454                save.write(r)
455                save.close()
456                os.chdir(cwd)
457                if os.path.getsize("files/" + filename) < 5000000:
458                    print filename
459                    content_type = str(file.content_type)
460                    conn = sqlite3.connect("messages.db")
461                    c = conn.cursor()
462                    try:
463                        c.execute(
464                            '''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
465                    except sqlite3.OperationalError:
466                        pass
467                    c.execute(
468                        '''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES (?,?,?,?,?,?)''',
469                        (user_id, destination, "static/files/" + filename, time.time(), 1, content_type))
470                    conn.commit()
471                    conn.close()
472                    json_data = {"sender": cherrypy.session['username'], "destination": destination, "file": file_data,
473                                 "filename": filename, "content_type": content_type, "stamp": time.time()}
474                    data = json.dumps(json_data)
475                    url = "http://" + users[i]["ip"] + ":" + users[i]["port"] + "/receiveFile"
476                    req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
477                    urllib2.urlopen(req)
478        return self.loadMessages(openUser)
479
480    # LOGGING IN AND OUT
481    @cherrypy.expose
482    def signin(self, username=None, password=None):
483        """Check their name and password and send them either to the main page, or back to the main login screen."""
484        self.location()
485        error = self.authoriseUserLogin(username,password, cherrypy.session['location'])
486        if error == 0:
487            cherrypy.session['username'] = username
488            cherrypy.session['password'] = hashlib.sha256(password+username).hexdigest()
489            global user_id
490            global user_password
491            user_id = cherrypy.session['username']
492            user_password = cherrypy.session['password']
493            self.initializeLoginThread()
494            self.createInitialProfile()
495            raise cherrypy.HTTPRedirect('/')
496        else:
497            raise cherrypy.HTTPRedirect('/login')
498
499    @cherrypy.expose
500    def logout(self):
501        error = self.signout()
502        if error == 0:
503            raise cherrypy.HTTPRedirect('/loggedoff')
504        else:
505            raise cherrypy.HTTPRedirect('/logofferror')
506
507    @cherrypy.expose
508    def location(self):
509        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
510        s.connect(("8.8.8.8", 80))
511        ip = (s.getsockname()[0])
512        s.close()
513        if ip.find("10.103") == 0:
514            lo = "0"
515        elif ip.find("172.23") == 0:
516            lo = "1"
517        else:
518            lo = "2"
519        cherrypy.session['location'] = lo
520
521    @cherrypy.expose
522    def signout(self):
523        """Logs the current user out, expires their session"""
524        print user_id
525        print user_password
526        res = urllib2.urlopen("http://cs302.pythonanywhere.com/logoff?username=" + user_id
527                                + "&password=" + user_password)
528        num = res.read()
529        try:
530            cherrypy.lib.sessions.expire()
531        except KeyError:
532            pass
533        print num
534        if num[0] == '0':
535            return 0
536        else:
537            return 1
538
539    def initializeLoginThread(self):
540        if cherrypy.session['username'] is None:
541            raise cherrypy.HTTPRedirect('/login')
542        else:
543            cherrypy.session['logged'] = threading.Event()
544            cherrypy.session['logged'].set()
545            thread = threading.Thread(target = self.autorelogin, args=(cherrypy.session['username'], cherrypy.session['password'],
546                                      cherrypy.session['logged'], cherrypy.session['location']))
547            thread.daemon = True
548            thread.start()
549
550    def autorelogin(self, username = "", password = "", logged = "", location = ""):
551        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
552        s.connect(("8.8.8.8", 80))
553        ip = (s.getsockname()[0])
554        #ip = "172.23.20.177"
555        s.close()
556
557        while logged.isSet():
558            req = urllib2.Request("http://cs302.pythonanywhere.com/report?username=" + username
559                            + "&password=" + password
560                            + "&location=" + location
561                            + "&ip=" + ip
562                            + "&port=" + str(listen_port))
563            num = urllib2.urlopen(req).read()
564            time.sleep(60)
565
566
567    def authoriseUserLogin(self, username, password, location):
568        print username
569        print password
570        password = hashlib.sha256(password + username).hexdigest()
571        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
572        s.connect(("8.8.8.8", 80))
573        ip = (s.getsockname() [0])
574        #ip = "172.23.20.177"
575        s.close()
576        res = urllib2.urlopen("http://cs302.pythonanywhere.com/report?username=" + username
577                             + "&password=" + password
578                             + "&location=" + location
579                             + "&ip=" + ip
580                             + "&port=" + str(listen_port))
581        num = res.read()
582        if num[0] == '0':
583            global loggedIn
584            loggedIn = 1
585            return 0
586        else:
587            return 1
588
589    @cherrypy.expose
590    def logoutOnExit(self):
591        if loggedIn == 1:
592            print 1
593            cherrypy.session['logged'].clear()
594            self.signout()
595          
596def runMainApp():
597    # Create an instance of MainApp and tell Cherrypy to send all requests under / to it. (ie all of them)
598    cherrypy.tree.mount(MainApp(), "/")
599    c = { '/static' : {
600        'tools.staticdir.on' : True,
601        'tools.staticdir.dir' : os.path.abspath(os.getcwd())
602        }}
603    cherrypy.tree.mount(MainApp(), "/", c)
604
605    # Tell Cherrypy to listen for connections on the configured address and port.
606    cherrypy.config.update({'server.socket_host': listen_ip,
607                            'server.socket_port': listen_port,
608                            'engine.autoreload.on': True,
609                           })
610
611    print "========================="
612    print "University of Auckland"
613    print "COMPSYS302 - Software Design Application"
614    print "========================================"                       
615    
616    # Start the web server
617    cherrypy.engine.start()
618
619    # And stop doing anything else. Let the web server take over.
620    cherrypy.engine.block()
621 
622#Run the function to start everything
623runMainApp()