Browse Source

formatted to conform with pep8 - closes #13

pull/18/head
theycallmemac 3 years ago
parent
commit
db8cdf144c
6 changed files with 181 additions and 66 deletions
  1. +11
    -1
      CHANGELOG.md
  2. +146
    -45
      scripts/dcurooms.py
  3. +5
    -5
      setup.py
  4. +5
    -4
      tests/test_available_now.py
  5. +1
    -1
      tests/test_builder.py
  6. +13
    -10
      tests/test_lookup.py

+ 11
- 1
CHANGELOG.md View File

@@ -246,5 +246,15 @@ __contributor:__ theycallmemac
- added new test_lookup.py test too

---
---

__entry:__ 04-01-2018
__contributor:__ theycallmemac

---

- setup.py, scripts/dcurooms.py, tests/test_lookup.py, tests/test_available_now.py, tests/test_builder.py
- all scripts named here were formatted to conform with pep8
- this was done using autopep8

---

+ 146
- 45
scripts/dcurooms.py View File

@@ -1,11 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# import libraries
import sys
if sys.version_info[0] < 3:
from cookielib import LWPCookieJar
else:
from http.cookiejar import LWPCookieJar
import datetime
import smtplib
from optparse import OptionParser
@@ -13,35 +10,71 @@ from mechanicalsoup import StatefulBrowser
from requests import get
from bs4 import BeautifulSoup


if sys.version_info[0] < 3:
from cookielib import LWPCookieJar
else:
from http.cookiejar import LWPCookieJar

__author__ = "theycallmemac"
__version__ = '1.0.0'
__copyright__ = 'Copyright (c) 2017 theycallmemac'
__license__ = 'GPL-3.0'


def setup_options():
parser = OptionParser(description='Displays and books rooms around the DCU campus via provided timetable/module details', prog='dcurooms', version='%prog ' + __version__, usage='%prog [option]')
parser.add_option("-l", "--lookup", action="store_true", help="returns information given a specific room, week, day and hour")
parser.add_option("-b", "--book", action="store_true", help="book a room by providing the room, DD/MM/YYYY, start time, and end time")
parser.add_option("-a", "--available", action="store_true", help="returns only the rooms/labs that are free in a building")
parser.add_option("-n", "--now", action="store_true", help="show the status of each room/lab as it is at the current time of checking")
# building options which can be passed
parser.add_option("-L", "--computing", action="store_true", help="displays the status of the labs in the School of Computing")
parser.add_option("-C", "--grattan", action="store_true", help="displays the status of rooms in the Henry Grattan building")
parser = OptionParser(
description='Displays info and books room around DCU.',
prog='dcurooms',
version='%prog ' + __version__,
usage='%prog [option]')
parser.add_option(
"-l",
"--lookup",
action="store_true",
help="returns information given a specific room, week, day and hour")
parser.add_option(
"-b",
"--book",
action="store_true",
help="books a room by providing the room, D/M/YYYY, start, and end")
parser.add_option(
"-a",
"--available",
action="store_true",
help="returns only the rooms/labs that are free in a building")
parser.add_option(
"-n",
"--now",
action="store_true",
help="show the status of each room/lab as it is currently")
# building options which can be passed
parser.add_option(
"-L",
"--computing",
action="store_true",
help="displays the status of the labs in the School of Computing")
parser.add_option(
"-C",
"--grattan",
action="store_true",
help="displays the status of rooms in the Henry Grattan building")
return parser

return parser

def check_arguments(week, day):
if int(week) not in range(1, 53) or int(day) not in range(1,7):
if int(week) not in range(1, 53) or int(day) not in range(1, 7):
print("Incorrect parameters passed.")
sys.exit()
else:
pass


def search_dictionary(times, time):
if time not in times:
print("Outside scheduled timetables. Please try again at 08:00.")
sys.exit()
for k,v in times.items():
for k, v in times.items():
if k == time:
time = v
break
@@ -49,6 +82,7 @@ def search_dictionary(times, time):
pass
return time


def get_current_time(date):
day = date.weekday()
hour = date.hour
@@ -62,20 +96,30 @@ def get_current_time(date):
week = week_no + offset - 1
return str(week), str(day + 1), str(hour), str(minute)


def build_timetable(room, week, day, hour):
browser = StatefulBrowser()
cookie_jar = LWPCookieJar()
browser.set_cookiejar(cookie_jar)
browser.user_agent = [("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")]
url = "https://www101.dcu.ie/timetables/feed.php?room=" + room + "&week1=" + week + "&hour=" + str(hour) + "&day=" + day + "&template=location"
browser.user_agent = [
("User-Agent",
"""Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/58.0.3029.110
Safari/537.36""")]
url = "https://www101.dcu.ie/timetables/feed.php?room=" + room + \
"&week1=" + week + "&hour=" + str(hour) + \
"&day=" + day + "&template=location"
browser.open(url)
return browser, url


def fill_form(args):
browser = StatefulBrowser()
cookie_jar = LWPCookieJar()
browser.set_cookiejar(cookie_jar)
room, date, from_time, to_time = args[0], args[1].split("/"), args[2][:2] + ":" + args[2][2:], args[3][:2] + ":" + args[3][2:]
room, date, from_time, to_time = args[0], args[1].split(
"/"), args[2][:2] + ":" + args[2][2:], args[3][:2] + ":" + args[3][2:]
day, month, year = date[0], date[1], date[2]
if sys.version_info[0] < 3:
name = raw_input("Name of society: ")
@@ -102,17 +146,21 @@ def fill_form(args):
browser["submitted[email_address]"] = email
return browser


def check_room(timetable_url):
html = get(timetable_url)
soup = BeautifulSoup(html.text, "lxml")
tr = soup.select('tr')
return str(tr[12].getText().strip()) + " -> " + str(tr[14].getText().strip())
return str(tr[12].getText().strip()) + " -> " + \
str(tr[14].getText().strip())


def make_booking(form):
request = form.request
response = form.submit_selected()
return "Form submitted successfully."


def draft_email(args):
if sys.version_info[0] < 3:
gmail_user = raw_input("Your gmail: ")
@@ -125,13 +173,18 @@ def draft_email(args):
name = input("Society name: ")
person = input("Your name: ")
FROM = gmail_user
TO = 'irene.mcevoy@dcu.ie' if type('irene.mcevoy@dcu.ie') is list else ['irene.mcevoy@dcu.ie']
TO = ['irene.mcevoy@dcu.ie']
SUBJECT = 'Lab Booking'
BODY = "Just wondering if you could book " + args[0] + " on the " + args[1] + " from " + args[2][:2] + ":" + args[2][2:] + " to " + args[3][:2] + ":" + args[3][2:] + " for " + name + ".\n\nThank you,\n" + person + "."
BODY = "Just wondering if you could book " + args[0] + " on the " + \
args[1] + " from " + args[2][:2] + ":" + \
args[2][2:] + " to " + args[3][:2] + ":" + args[3][2:] + \
" for " + name + \
".\n\nThank you,\n" + person + "."
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, BODY)
return gmail_user, gmail_password, FROM, TO, message


def send_email(gmail_user, gmail_password, FROM, TO, message):
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
@@ -141,31 +194,73 @@ def send_email(gmail_user, gmail_password, FROM, TO, message):
server.sendmail(FROM, TO, message)
server.close()
print("Your email has been sent.")
except:
except BaseException:
print("Email failed to send.")


def main():
parser = setup_options()
(options, arguments) = parser.parse_args()
times = {'0800':'1', '0830':'2', '0900':'3', '0930':'4', '1000':'5', '1030':'6', '1100':'7', '1130':'8', '1200':'9', '1230':'10',
'1300':'11', '1330':'12', '1400':'13', '1430':'14', '1500':'15', '1530':'16', '1600':'17', '1630':'18', '1700':'19', '1730':'20',
'1800':'21', '1830':'22', '1900':'23', '1930':'24', '2000':'25', '2030':'26', '2100':'27', '2130':'28', '2200':'29', '2230':'30'
}
c = ['LG25','LG26','LG27','L101','L114','L125','L128']
g = ['CG01', 'CG02','CG03','CG04','CG05','CG06','CG11','CG12','CG20','CG68','C166']
times = {
'0800': '1',
'0830': '2',
'0900': '3',
'0930': '4',
'1000': '5',
'1030': '6',
'1100': '7',
'1130': '8',
'1200': '9',
'1230': '10',
'1300': '11',
'1330': '12',
'1400': '13',
'1430': '14',
'1500': '15',
'1530': '16',
'1600': '17',
'1630': '18',
'1700': '19',
'1730': '20',
'1800': '21',
'1830': '22',
'1900': '23',
'1930': '24',
'2000': '25',
'2030': '26',
'2100': '27',
'2130': '28',
'2200': '29',
'2230': '30'}
c = ['LG25', 'LG26', 'LG27', 'L101', 'L114', 'L125', 'L128']
g = [
'CG01',
'CG02',
'CG03',
'CG04',
'CG05',
'CG06',
'CG11',
'CG12',
'CG20',
'CG68',
'C166']
details = sys.argv[2:]

if options.book == True:
if options.book:
if len(details) < 4:
print("Booking a room requires more arguments. See the help for details.")
print("Booking requires more arguments. See the help for details.")
sys.exit()
else:
if details[0] in c:
user, password, from_who, to_who, message = draft_email(details)
user, password, from_who, to_who, message = draft_email(
details)
if sys.version_info[0] < 3:
confimation = raw_input("\nIs this the correct information? (y/n): ").lower()
confimation = raw_input(
"\nIs this the correct information? (y/n): ").lower()
else:
confirmation = input("\nIs this the correct information? (y/n): ").lower()
confirmation = input(
"\nIs this the correct information? (y/n): ").lower()
if confirmation == "y":
send_email(user, password, from_who, to_who, message)
else:
@@ -175,9 +270,11 @@ def main():
elif details[0] in g:
form = fill_form(details)
if sys.version_info[0] < 3:
confimation = raw_input("\nIs this the correct information? (y/n): ").lower()
confimation = raw_input(
"\nIs this the correct information? (y/n): ").lower()
else:
confirmation = input("\nIs this the correct information? (y/n): ").lower()
confirmation = input(
"\nIs this the correct information? (y/n): ").lower()
if confirmation == "y":
room_booked = make_booking(form)
print(room_booked)
@@ -191,18 +288,19 @@ def main():
elif len(details) > 5:
print("Too many arguments passed.")
sys.exit()
elif options.lookup == True:
if options.computing == True:
elif options.lookup:
if options.computing:
lst = c
elif options.grattan == True:
elif options.grattan:
lst = g
else:
if len(details) <= 3:
print("Not enough arguments passed.")
sys.exit()
room, week, day, time = details[0], details[1], details[2], details[3]
room, week = details[0], details[1]
day, time = details[2], details[3]
if room not in c and room not in g:
print("That room does not exist or is not supported by this program.")
print("That room is not supported by this program.")
sys.exit()
check_arguments(week, day)
time = search_dictionary(times, time)
@@ -216,13 +314,13 @@ def main():
for room in lst:
timetable, url = build_timetable("GLA." + room, week, day, time)
status = check_room(url)
if options.available == True:
if options.available:
if len(status) <= 9:
print(room + ": " + status)
else:
print(room + ": " + status)
sys.exit()
elif options.now == True:
elif options.now:
week, day, hour, minute = get_current_time(datetime.datetime.now())
if int(hour) < 8 or int(hour) >= 23:
print("Outside scheduled timetables. Try again at 08:00.")
@@ -233,19 +331,22 @@ def main():
minute = '00'
check_arguments(week, day)
time = search_dictionary(times, hour + minute)
if options.computing == True:
if options.computing:
lst = c
elif options.grattan == True:
elif options.grattan:
lst = g
for room in lst:
timetable, url = build_timetable("GLA." + room, week, day, time)
status = check_room(url)
if options.available == True:
if options.available:
if len(status) <= 9:
print(room + ": " + status)
else:
print(room + ": " + status)
else:
parser.print_help()


if __name__ == '__main__':
main()


+ 5
- 5
setup.py View File

@@ -1,4 +1,4 @@
#!/usr/bin/env python
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from setuptools import find_packages
@@ -6,8 +6,8 @@ setup(name='dcurooms',
version='1.0.0',
description='Shows room information around the DCU campus',
author='theycallmemac',
url='https://github.com/theycallmemac/dcuroomsi',
license = 'GPL-3.0',
url='https://github.com/theycallmemac/dcurooms',
license='GPL-3.0',
scripts=['scripts/dcurooms', 'scripts/dcurooms.py'],
install_requires=[
'MechanicalSoup', 'bs4', 'requests'
@@ -20,5 +20,5 @@ setup(name='dcurooms',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
])
'Programming Language :: Python :: 3.6'])

+ 5
- 4
tests/test_available_now.py View File

@@ -1,14 +1,14 @@


import unittest
import sys
import datetime
import os
sys.path.append('../')


class AvailableNowTestCase(unittest.TestCase):
def test_options(self):
available_result = os.system("cd scripts/ && python dcurooms.py -anC > ../tests/available_output.txt")
available_result = os.system("""cd scripts/ && python dcurooms.py -anC
> ../tests/available_output.txt""")
self.assertTrue(available_result == 0)

def test_available_output(self):
@@ -16,7 +16,8 @@ class AvailableNowTestCase(unittest.TestCase):
with open('available_output.txt') as f:
for line in f:
if len(line.strip()[14:]) > 0:
self.assertEqual("Outside scheduled timetables. Try again at 08:00.", line.strip())
self.assertEqual("""Outside scheduled timetables.
Try again at 08:00.""", line.strip())
else:
self.assertEqual("", line.strip()[14:])



+ 1
- 1
tests/test_builder.py View File

@@ -1,9 +1,9 @@

import unittest
import sys
import requests
sys.path.append('.')
from scripts.dcurooms import build_timetable

class BuildTimetableTestCase(unittest.TestCase):
def test_return_val(self):
val = build_timetable("CG04", "24", "14", "4")


+ 13
- 10
tests/test_lookup.py View File

@@ -1,37 +1,40 @@


import unittest
import sys
import datetime
import os
sys.path.append('../')


class LookupTestCase(unittest.TestCase):
def test_options(self):
room_result = os.system("cd scripts/ && python dcurooms.py -l CG12 21 1 1800 > ../tests/lookup_room_output.txt")
building_result = os.system("cd scripts/ && python dcurooms.py -lL 9 4 1500 > ../tests/lookup_building_output.txt")
room_result = os.system("""cd scripts/ &&
python dcurooms.py -l CG12 21 1 1800
> ../tests/lookup_room_output.txt""")
building_result = os.system("""cd scripts/ &&
python dcurooms.py -lL 9 4 1500
> ../tests/lookup_building_output.txt""")

self.assertTrue(room_result == 0) and self.assertTrue(building_result == 0)
self.assertTrue(room_result == 0)
self.assertTrue(building_result == 0)

def test_lookup_output(self):
if self.test_options():
with open('lookup_room_output.txt') as f:
for line in f:
if len(line.strip()[14:]) > 0:
self.assertEqual("Outside scheduled timetables. Try again at 08:00.", line.strip())
self.assertEqual("""Outside scheduled timetables.
Try again at 08:00.""", line.strip())
else:
self.assertEqual("", line.strip()[14:])

with open('lookup_building_output.txt') as f:
for line in f:
if len(line.strip()[14:]) > 0:
self.assertEqual("Outside scheduled timetables. Try again at 08:00.", line.strip())
self.assertEqual("""Outside scheduled timetables.
Try again at 08:00.""", line.strip())
else:
self.assertEqual("", line.strip()[14:])




if __name__ == '__main__':
unittest.main()


Loading…
Cancel
Save