diff options
Diffstat (limited to 'server/history.py')
-rw-r--r-- | server/history.py | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/server/history.py b/server/history.py new file mode 100644 index 0000000..d20dbe7 --- /dev/null +++ b/server/history.py @@ -0,0 +1,93 @@ +import cherrypy +import json +from lib import uuid +from lib import database +from time import time + +import event + +def loadAll(): + db = database.connect() + db.execute("SELECT event,button_id,time FROM history") + + results = [] + while True: + try: + button = () + button.loadFromDb(db.fetchone()) + results.append(button.toDict()) + except: + break + + return results + +class Button(object): + def __init__(self): + self.persisted = False + self.id = None + self.status = STATUS_INVENTORY + self.last_pressed = 0 + self.history = [] + + def toDict(self): + return { + 'id': self.id, + 'status': self.status, + 'last_pressed': self.last_pressed + } + + def toJSON(self): + return self.toDict() + + def loadById(self, id): + db = database.connect() + db.execute("SELECT id,status,last_pressed FROM buttons WHERE id = ?" , (str(id),)) + + return self.loadFromDb(db.fetchone()) + + def loadFromDb(self, dbrs): + if dbrs is None: + raise cherrypy.HTTPError(404, 'Button not found') + + self.persisted = True + self.id, self.status, self.last_pressed = dbrs + + return self + + def press(self): + if self.last_pressed: + self.history.insert(0, self.last_pressed) + + self.last_pressed = int(time()) + return self + + def save(self): + db = database.connect() + + # validate + if self.id is None: + raise cherrypy.HTTPError(500, "What u doin?") + + # upsert: update + elif self.persisted: + db.execute("UPDATE buttons SET status = ?, last_pressed = ? WHERE id = ?", + (self.status, self.last_pressed, self.id,) + ) + + # upsert: insert + else: + db.execute("INSERT INTO buttons VALUES (?, ?, ?)", (self.id, self.status, self.last_pressed)) + + db.connection.commit() + return self + + def delete(self): + db = database.connect() + + if self.id is None: + raise cherrypy.HTTPError(500, "uhh wat") + + db.execute("DELETE FROM buttons WHERE id = ?", (self.id,)) + db.connection.commit() + + return None |