def days_to_return_book(borrow_date):
    """
    A mini JSON parser to extract how many days should a borrowed book be returned
    :param borrow_date: the date in which the book is borrowed
    :return: a new date with added days
    """
    with open('config.json') as file:
        data = json.load(file)
    return borrow_date + timedelta(days=Parser.get_instance().days_to_return)
Exemple #2
0
 def __init__(self):
     if Analytics._instance is not None:
         raise Exception("This is a singleton class")
     else:
         """Enter your own info here"""
         Analytics._instance = self
         self.parser = Parser.get_instance()
         self._host = self.parser.host
         self._user = self.parser.user
         self._password = self.parser.password
         self._database = self.parser.database
def event_insert(user_email, book_id, name):
    """
    This function is responsible for adding an event to users' Google Calendar to remind them of the due date
    :param user_email: user's email
    :param book_id: book's id
    :param name: user's name
    :return: none
    """
    if g_mail_check(user_email) is None:
        return None
    else:
        date = datetime.now()
        time = date.time().strftime('%H:%M:%S')
        end = '{:%H:%M:%S}'.format(datetime.now() + timedelta(hours=1))
        due_date = (date + timedelta(days=Parser.get_instance().calendar_reminder)).strftime("%Y-%m-%d")
        time_start = "{}T{}+07:00".format(due_date, time)
        time_end = "{}T{}+07:00".format(due_date, end)
        readable_time_end = '{} {} GMT+07:00'.format(due_date, end)
        req = requests.get(url='http://127.0.0.1:5000/books/{}'.format(book_id))
        data = req.json()
        event = {
            "summary": "Reminder for {} to return {}".format(name, data['title']),
            "location": "RMIT University Vietnam Library",
            "description": "Please return {} to the University Library before {}".format(data['title'], readable_time_end),
            "start": {
                "dateTime": time_start,
                "timeZone": "Asia/Ho_Chi_Minh",
            },
            "end": {
                "dateTime": time_end,
                "timeZone": "Asia/Ho_Chi_Minh",
            },
            "attendees": [
                {"email": user_email},
            ],
            "reminders": {
                "useDefault": False,
                "overrides": [
                    {"method": "email", "minutes": 120},
                    {"method": "popup", "minutes": 60},
                ],
            }
    }
    event = service.events().insert(calendarId="primary", body=event).execute()
    print("Event created! Please check your Google Calendar")
    # Extracting Google Calendar event ID
    string = event.get("htmlLink").split('=')[1]
    lens = len(string)
    lenx = lens - (lens % 4 if lens % 4 else 4)
    decoded_string = base64.b64decode(string[:lenx])
    event_id = str(decoded_string).split(' ')[0][2:].strip()
    return event_id
Exemple #4
0
from search_service import Search
from return_service import ReturnService
import time
import socket, socket_utils
from config_parser import Parser
from qr_reader.qr_scanner import QRScanner
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
HOST = Parser.get_instance().host
PORT = Parser.get_instance().port
ADDRESS = (HOST, PORT)


class Menu:
    _instance = None
    # Only one instance of this class should exist
    @staticmethod
    def get_instance():
        """
        This method returns a singleton Menu class
        :return: an instance of Menu class
        """
        if Menu._instance is None:
            Menu()
        return Menu._instance

    def __init__(self):
        if Menu._instance is not None:
            raise Exception("This class is singleton")
        else:
            Menu._instance = self
Exemple #5
0

def initializeLock(l):
    """

    :param l: Lock
    :return:
    """
    # Lock needs to be global for it to be passed to map
    global lock
    lock = l


if __name__ == '__main__':
    # Load the configuration
    config = Parser().parse_config('config/config.conf', 'AWS')

    # Get only the files with a timestamp of today

    # Split the files into smaller files, each one containing no more than 500,000 json lines
    directory = '{0}*.gz'.format(config['flat_data'])
    file_names = glob.glob(directory)

    today_files = []
    today = datetime.datetime.now()

    for file_name in file_names:
        file_date = datetime.datetime.fromtimestamp(
            os.path.getmtime(file_name))
        if file_date.day == today.day and file_date.month == today.month and file_date.year == today.year:
            today_files.append(file_name)
Exemple #6
0
from socket import *
import time
from config_parser import Parser


class TimeServer:
    def __init__(self, deception):
        self.addr = ('localhost', 123)
        self.socket = socket(AF_INET, SOCK_DGRAM)
        self.deception = deception

    def run(self):
        self.socket.bind(self.addr)

        while True:
            print('wait data...')

            conn, addr = self.socket.recvfrom(1024)
            print(bytes.decode(conn))
            print('client addr: ', addr)
            self.socket.sendto(
                str.encode(time.ctime(time.time() + self.deception)), addr)


if __name__ == '__main__':
    conf_parser = Parser()
    deception = conf_parser.get_deception("settings.ini")
    time_server = TimeServer(deception)
    time_server.run()
Exemple #7
0
def send_email(user_email):
    """
    This class will send an email with a QR code attached to users who choose to opt in the Quick Return service
    :param user_email: email of user
    :return: none
    """
    fromaddr = Parser.get_instance().email
    toaddr = user_email
    # instance of MIMEMultipart
    msg = MIMEMultipart()

    # storing the senders email address
    msg['From'] = fromaddr

    # storing the receivers email address
    msg['To'] = toaddr

    # storing the subject
    msg['Subject'] = "RMIT University Library - Quick Return Service's QR Code"

    # string to store the body of the mail
    body = "Here is your QR code."

    # attach the body with the msg instance
    msg.attach(MIMEText(body, 'plain'))

    # open the file to be sent
    filename = "image.png"
    attachment = open("qr_codes/image.png", "rb")

    # instance of MIMEBase and named as p
    p = MIMEBase('application', 'octet-stream')

    # To change the payload into encoded form
    p.set_payload((attachment).read())

    # encode into base64
    encoders.encode_base64(p)

    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    # attach the instance 'p' to instance 'msg'
    msg.attach(p)

    # creates SMTP session
    s = smtplib.SMTP('smtp.gmail.com', 587)

    # start TLS for security
    s.starttls()

    # Authentication
    s.login(fromaddr, "GAtech321")

    # Converts the Multipart msg into a string
    text = msg.as_string()

    # sending the mail
    s.sendmail(fromaddr, toaddr, text)

    # terminating the session
    s.quit()