Skip to content

Commit

Permalink
Merge pull request #7 from Augugrumi/cache
Browse files Browse the repository at this point in the history
Cache
  • Loading branch information
Polpetta authored Dec 13, 2017
2 parents 7bfb799 + 3ddca00 commit c914144
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 32 deletions.
80 changes: 59 additions & 21 deletions torrearchimedebot/bot/handlers/parsing.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import requests
from lxml import html
from .utility import *
import requests
import sys
import json
from .utility import *
import time
import threading
import logging

class Results:
def __init__(self, time = '', activity = '', professor = '', activityType = ''):
Expand All @@ -16,18 +19,29 @@ def __init__(self, time = '', activity = '', professor = '', activityType = ''):
self.activity = activity
self.professor = professor
self.activityType = activityType

def __str__(self):
return json.dumps(self, default=lambda o: o.__dict__, indent=4)


def isEmpty(self):
return (self.timeStart == '' and
self.timeEnd == '' and
self.activity == '' and
self.professor == '' and
self.activity == '')

class Scedule:
def json2Schedule(jsonString):
data = json.loads(jsonString)
schedule = data["schedule"]
results = []
for r in schedule:
key = r
r = r.replace("-", " - ")
results.append(Results(r, schedule[key][0], schedule[key][1], schedule[key][2]))
return Schedule(data["room"], results)

class Schedule:
def __init__(self, room, records):
self.room = room
self.schedule = {}
Expand Down Expand Up @@ -82,51 +96,75 @@ def parse(self, room):
cells += [c for c in row.xpath(URLParser.XPATH_TO_ACTIVITY_TYPE) if c.strip()]
if (len(cells)<=0):
records.append(Results())
#print(Results)
elif (len(cells)==3):
records.append(Results(cells[0], cells[1], cells[2]))
#print(Results(cells[0], cells[1], cells[2]))
elif (len(cells)==4):
records.append(Results(cells[0], cells[1], cells[2], cells[3]))
#print(Results(cells[0], cells[1], cells[2], cells[3]))
else :
records.append(Results())
return records

def parseSchedule(self, room):
return Scedule(room, self.parse(room))
return Schedule(room, self.parse(room))

def nowSchedule():
parser = URLParser()
rooms = retrieve_rooms()
schedule = ''
roomActivities = ''
delimiter = '\t'
scheduleAccess = ScheduleAccess()
rooms = retrieve_rooms()
for room in rooms:
schedule = parser.parseSchedule(room)
roomSceduleNow = schedule.now()
roomActivities += '*' + room + '*'
if (roomSceduleNow != ''):
for s in roomSceduleNow:
schedule = scheduleAccess.getScheduleForRoom(room)
roomScheduleNow = schedule.now()
roomActivities += '*' + room + '*'
if (roomScheduleNow != ''):
for s in roomScheduleNow:
roomActivities += delimiter + s
else:
roomActivities += delimiter + "The room is now free"
roomActivities += '\n'
return roomActivities

def nowFree():
parser = URLParser()
rooms = retrieve_rooms()
schedule = ''
roomActivities = ''
delimiter = '\t'
scheduleAccess = ScheduleAccess()
rooms = retrieve_rooms()
for room in rooms:
schedule = parser.parseSchedule(room)
roomSceduleNow = schedule.now()
if (roomSceduleNow == ''):
schedule = scheduleAccess.getScheduleForRoom(room)
roomScheduleNow = schedule.now()
if (roomScheduleNow == ''):
roomActivities += room
roomActivities += '\n'
if (roomActivities != ''):
return roomActivities
else:
return "No room is free"
return "No room is free"

class ScheduleAccess:
allSchedules = {}

def __init__(self):
if (ScheduleAccess.allSchedules == {}):
ScheduleUpdater.lookupFromServer()

def getSchedule(self):
return ScheduleAccess.allSchedules

def getScheduleForRoom(self, roomId):
return ScheduleAccess.allSchedules[roomId]

class ScheduleUpdater:
def lookupFromServer():
logging.getLogger().info('Taking data from server')
parser = URLParser()
rooms = retrieve_rooms()
schedule = ''
for room in rooms:
schedule = parser.parseSchedule(room)
ScheduleAccess.allSchedules[room] = schedule

def startUpdater():
ScheduleUpdater.lookupFromServer()
threading.Timer(3600, startUpdater).start()
19 changes: 11 additions & 8 deletions torrearchimedebot/bot/handlers/room_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def __init__(self, roomId):
self.roomId = roomId

def handleMessage(self):
return schedulePrettyfier(URLParser().parseSchedule(self.roomId))
return schedulePrettyfier(ScheduleAccess().getScheduleForRoom(self.roomId))

def schedulePrettyfier(scheduleObj):
"""Take the activity and format it to be displayed in a message"""
Expand All @@ -18,7 +18,7 @@ def schedulePrettyfier(scheduleObj):
toReturn = "The room is always empty today!"
else:
delimiter = "\t"
for time in schedule:
for time in sorted(schedule):

activity = schedule[time]
#Check if it is present the activity type
Expand All @@ -35,15 +35,18 @@ def schedulePrettyfier(scheduleObj):
#Add all the data
toReturn += time
for i in range(0, stop):
toReturn += delimiter + activity[i]

toReturn += delimiter + activity[i] \
.replace('_', ' ') \
.replace('*', ' ') \
.replace('[', ' ') \
.replace(']', ' ') \
.replace('`', ' ')

#End markdown text modifier
if (time_in_range(time)):
toReturn += ' 👈 *'
elif (before_now(time)):
toReturn += '_'

toReturn += "\n"
return toReturn

#print(RoomHandler('1C150').handleMessage())
toReturn += "\n"
return toReturn
9 changes: 7 additions & 2 deletions torrearchimedebot/bot/handlers/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ def retrieve_rooms():
'2AB45',
'2BC30',
'2BC60',
'LabTA'
'LabTA',
'LabP036',
'LabP140',
'LuF1',
'LuM250',
'P200'
]
return rooms
return rooms
5 changes: 4 additions & 1 deletion torrearchimedebot/bot/telegram_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
from bot.handlers.now_handler import NowHandler
from bot.handlers.free_handler import FreeHandler
from bot.handlers.info_handler import InfoHandler
from .handlers.utility import *
from bot.handlers.utility import *
from bot.handlers.parsing import startUpdater
import logging
import os

class TelegramController:

def __init__(self):
startUpdater()

self._updater = Updater(token=os.environ['TG_TOKEN'])
self._dispatcher = self._updater.dispatcher

Expand Down

0 comments on commit c914144

Please sign in to comment.