コード例 #1
0
ファイル: timetable.py プロジェクト: Mwall93/A4_Scheduler
    def timetableStudent(id):
        Mrows = Database.getRows(
            'SELECT module FROM `studentModule` WHERE `student` = %s', (id, ))

        if len(Mrows) == 0:
            return None

        module = rows[0]

        srows = Database.getRows(
            'SELECT id FROM `moduleSession` WHERE `module` = %s', (module, ))

        if len(srows) == 0:
            return None

        session = rows[0]

        rows = Database.getRows(
            'SELECT all FROM `roombooking` WHERE `module_session` = %s',
            (session, ))

        if len(srows) == 0:
            return None

        times = timetable()
        times.setmodule(rows[0]['id'])
        times.setStart(rows[0]['identifier'])
        times.setEnd(rows[0]['building_floor'])
        times.setRoom(rows[0]['building'])

        return times
コード例 #2
0
ファイル: Campus.py プロジェクト: Mwall93/A4_Scheduler
    def save(self):
        if self.id == None:
            # insert
            Database.execute('INSERT INTO `Campus` (`name`) VALUES (%s)', (self.row['name'],))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute('UPDATE `Campus` SET `name` = %s WHERE `id` = %s', (self.row['name'], self.id))
コード例 #3
0
    def save(self):
        if self.id == None:
            # insert
            Database.execute('INSERT INTO `Building` (`name`, `floor_count`, `campus`) VALUES (%s, %s, %s)', (self.row['name'], self.row['floor_count'], self.row['campus'],))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute('UPDATE `Building` SET `name` = %s, `floor_count` = %s, `campus` = %s WHERE `id` = %s', (self.row['name'],self.row['floor_count'],self.row['campus'], self.id))
コード例 #4
0
ファイル: PasswordReset.py プロジェクト: Mwall93/A4_Scheduler
    def save(self):
        if self.id == None:
            # insert
            Database.execute('INSERT INTO `PasswordReset` (`token`, `user_id`, `user_type`,`expires`) VALUES (%s, %s, %s, %s)', (self.row['token'], self.row['user_id'], self.row['user_type'], self.row['expires'],))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute('UPDATE `PasswordReset` SET `token` = %s, `user_id` = %s, `user_type` = %s , `expires` = %s WHERE `id` = %s', (self.row['token'],self.row['user_id'],self.row['user_type'], self.row['expires'], self.id))
コード例 #5
0
ファイル: ApiSession.py プロジェクト: Mwall93/A4_Scheduler
def create(user_id, user_type, ip_addr, user_agent):
    """ Creates a session in the database """
    signature = ip_addr + user_agent
    signature = hashlib.sha256(signature.encode('utf-8')).hexdigest()
    token = str(uuid.uuid4()).replace('-', '')
    expires = time.time() + 30 * 60

    Database.execute(
        'INSERT INTO `ApiSession` (`user_id`, `user_type`, `signature`, `expires`, `token`) VALUES (%s, %s, %s, %s, %s)',
        (int(user_id), user_type, signature, expires, token))

    return token
コード例 #6
0
ファイル: StudentModule.py プロジェクト: Mwall93/A4_Scheduler
    def save(self):
        if self.id == None:
            # insert
            Database.execute(
                'INSERT INTO `StudentModule` (`module`,`student`, `enrolment_date`) VALUES (%s, %s, %s)',
                (self.row['module'], self.row['student'],
                 self.row['enrolment_date']))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute(
                'UPDATE `StudentModule` SET `module` = %s ,`student` = %s, `enrolment_date` = %s WHERE `id` = %s',
                (self.row['module'], self.row['student'],
                 self.row['enrolment_date'], self.id))
コード例 #7
0
    def save(self):
        if self.id == None:
            # insert
            Database.execute(
                'INSERT INTO `Room` (`identifier`, `building_floor`, `building`, `capacity`) VALUES (%s, %s, %s, %s)',
                (self.row['identifier'], self.row['building_floor'],
                 self.row['building'], self.row['capacity']))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute(
                'UPDATE `Room` SET `identifier` = %s, `building_floor` = %s, `building` = %s, `capacity` = %s WHERE `id` = %s',
                (self.row['identifier'], self.row['building_floor'],
                 self.row['building'], self.row['capacity'], self.id))
コード例 #8
0
ファイル: GUI.py プロジェクト: awingray/myRCS
 def launchFile(self):
     ## Prompts a file dialog with only 2 available file types
     ## Once file is selected, dialog returns the file's path (filename)
     filename = tkFileDialog.askopenfilename(
         filetypes=[('word files', '.docx'), ('text files', '.txt')])
     ## Splits file's path into a tuple of directory string and extension string
     filepath, file_ext = os.path.splitext(filename)
     if filename:
         if file_ext == ".txt":
             ## Executable file for notepad program
             filepath = "C:/Windows/notepad.exe"
         elif file_ext == ".docx":
             ## Executable file for Microsoft Word program
             filepath = "C:/Program Files (x86)/Microsoft Office/root/Office16/WINWORD.EXE"
         try:
             ## Create sub process
             proc = subprocess.Popen([filepath, filename])
             proc.wait()
         except (OSError, subprocess.CalledProcessError):
             return "Failed, file is damaged or program has crashed!"
         ## Prompts dialog for user to input revision message
         message = tkSimpleDialog.askstring("Commit message",
                                            "What are the changes?")
         rcsFile = File(filename, Database())
         rcsFile.add(message)
     ## Update file list with the new changes
     self.updatefileList()
コード例 #9
0
    def save(self):
        if self.id == None:
            # insert
            Database.execute(
                'INSERT INTO `ModuleSessionType` (`name`, `display_name`) VALUES (%s, %s)',
                (
                    self.row['name'],
                    self.row['display_name'],
                ))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute(
                'UPDATE `ModuleSessionType` SET `name` = %s, `display_name` = %s WHERE `id` = %s',
                (self.row['name'], self.row['display_name'], self.id))
コード例 #10
0
ファイル: app.py プロジェクト: Mwall93/A4_Scheduler
def hook():
    if not request.endpoint == 'static':
        Database.connect()
    #return

    if request.endpoint == 'static':
        return

    if request.endpoint is None:
        return

    if request.endpoint.startswith('Api.') or request.endpoint.startswith(
            'Auth.'):
        return

    if not Authorization.isLoggedIn(session.get('user')):
        return redirect(url_for('Auth.Login'))
コード例 #11
0
ファイル: ApiSession.py プロジェクト: Mwall93/A4_Scheduler
def isValidToken(token, ip_addr, user_agent):
    """ Checks if the specified authentication token is valid """
    session = Database.getRows(
        'SELECT `user_id`, `signature`, `expires` FROM `ApiSession` WHERE `token` = %s LIMIT 1',
        (token, ))

    # Check if session exists
    if len(session) != 1:
        return False

    # Check if session expired
    if session[0]['expires'] < time.time():
        Database.execute('DELETE FROM `ApiSession` WHERE token = %s',
                         (token, ))
        return False

    # Check if signature matches
    signature = ip_addr + user_agent
    signature = hashlib.sha256(signature.encode('utf-8')).hexdigest()

    if signature != session[0]['signature']:
        Database.execute('DELETE FROM `ApiSession` WHERE token = %s',
                         (token, ))
    # Everything is okay, Renew the token
    Database.execute('UPDATE `ApiSession` SET expires = %s WHERE token = %s',
                     (time.time() + 30 * 60, token))

    return True
コード例 #12
0
    def __init__(self, core, name):

        # Expose core and plugin name for subclasses
        self.core = core
        self.name = name
        self.database = Database(databaseName="databases/" + self.name + ".db")

        # Expose logger for subclasses
        self.logger = logging.getLogger("plugins." + self.name)
コード例 #13
0
ファイル: ModuleSession.py プロジェクト: Mwall93/A4_Scheduler
    def save(self):
        if self.id == None:
            # insert
            Database.execute(
                'INSERT INTO `ModuleSession` (`module`, `staff`, `type`) VALUES (%s, %s, %s)',
                (
                    self.row['module'],
                    self.row['staff'],
                    self.row['type'],
                ))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute(
                'UPDATE `ModuleSession` SET `module` = %s, `staff` = %s, `type` = %s WHERE `id` = %s',
                (self.row['module'], self.row['staff'], self.row['type'],
                 self.id))
コード例 #14
0
	def __init__(self, method):

		self.db = Database.Db()

		if method == "newContact":
			self.newContact()
		elif method == "listContact":
			self.listContact()
		elif method == "searchContact":
			self.searchContact()
コード例 #15
0
    async def on_ready(self):
        print(f"\tClient Name:\t{self.user.name}")
        print(f"\tClient ID:\t{self.user.id}")
        print(f"\tClient Disc:\t{self.user.discriminator}\n")

        await self.load_extensions()

        self.redditCmd = RedditCommandsManager(
            self,
            os.getenv("REDDIT_CLIENT_ID"),
            os.getenv("REDDIT_CLIENT_SECRET"),
            os.getenv("REDDIT_NAME"),
            os.getenv("REDDIT_PASS"),
        )

        self.musicCmd = MusicCommandsManager(self)
        await self.musicCmd.init()

        self.db = Database()
コード例 #16
0
ファイル: Term.py プロジェクト: Mwall93/A4_Scheduler
    def save(self):
        if self.id == None:
            # insert
            Database.execute(
                'INSERT INTO `Term` (`start_date`, `end_date`, `term`) VALUES (%s, %s, %s)',
                (
                    self.row['start_date'],
                    self.row['end_date'],
                    self.row['term'],
                ))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute(
                'UPDATE `Term` SET `start_date` = %s, `end_date` = %s, `term` = %s WHERE `id` = %s',
                (self.row['start_date'], self.row['end_date'],
                 self.row['term'], self.id))
コード例 #17
0
ファイル: GUI.py プロジェクト: awingray/myRCS
 def addFile(self):
     ## Prompts a file dialog with only 2 available file types
     filename = tkFileDialog.askopenfilename(
         filetypes=[('text files', '.txt'), ('word files', '.docx')])
     ## Prompts dialog for user to input revision message
     message = tkSimpleDialog.askstring("First commit",
                                        "What are the details?")
     rcsFile = File(filename, Database())
     rcsFile.add(message)
     ## Update file list with the new changes
     self.updatefileList()
コード例 #18
0
    def save(self):
        if self.id == None:
            # insert
            Database.execute(
                'INSERT INTO `RoomBooking` (`room`, `time_from`, `time_to`,`module_session`) VALUES (%s, %s, %s, %s)',
                (
                    self.row['room'],
                    self.row['time_from'],
                    self.row['time_to'],
                    self.row['module_session'],
                ))

            rows = Database.getRows('SELECT LAST_INSERT_ID() AS insert_id')
            self.id = rows[0]['insert_id']
        else:
            # update
            Database.execute(
                'UPDATE `RoomBooking` SET `room` = %s, `time_from` = %s, `time_to` = %s, `module_session` = %s WHERE `id` = %s',
                (self.row['room'], self.row['time_from'], self.row['time_to'],
                 self.row['module_session'], self.id))
コード例 #19
0
ファイル: ApiSession.py プロジェクト: Mwall93/A4_Scheduler
def getUserId(token):
    """ Gets the user ID that is assigned to the token """
    session = Database.getRows(
        'SELECT `user_id`, `user_type` FROM `ApiSession` WHERE token = %s',
        (token, ))

    # Do a sanity check
    if len(session) != 1:
        return None

    return int(session[0]['user_id']), session[0]['user_type']
コード例 #20
0
    def get_old_game(self, message, client):
        try:
            game = Database.get_game(message['id'])
        except KeyError:
            return self.send_reply(client, "error",
                                   "'id'-parameter is missing")

        if game:
            self.send_reply(client, "info", game)
        else:
            self.send_reply(client, "error", "Game id doesn't exist")
コード例 #21
0
ファイル: Campus.py プロジェクト: Mwall93/A4_Scheduler
    def findById(id):
        rows = Database.getRows('SELECT * FROM `Campus` WHERE `id` = %s', (id,))

        if len(rows) == 0:
            return None
        
        campus = Campus()
        campus.setId(rows[0]['id'])
        campus.setName(rows[0]['name'])

        return campus
コード例 #22
0
ファイル: Campus.py プロジェクト: Mwall93/A4_Scheduler
    def findBy(field, value):
        rows = Database.getRows('SELECT * FROM `Campus` WHERE ' + field +' = %s', (value,))

        out = []

        for i in rows:
            campus = Campus()
            campus.setId(i['id'])
            campus.setName(i['name'])
            out.append(campus)

        return out
コード例 #23
0
ファイル: Campus.py プロジェクト: Mwall93/A4_Scheduler
    def all():
        rows = Database.getRows('SELECT * FROM `Campus`')

        out = []

        for i in rows:
            campus = Campus()
            campus.setId(i['id'])
            campus.setName(i['name'])
            out.append(campus)

        return out
コード例 #24
0
    def all():
        rows = Database.getRows('SELECT * FROM `ModuleSessionType`')

        out = []

        for i in rows:
            sessionType = ModuleSessionType()
            sessionType.setId(i['id'])
            sessionType.setName(i['name'])
            sessionType.setDisplayName(i['display_name'])
            out.append(sessionType)

        return out
コード例 #25
0
ファイル: Term.py プロジェクト: Mwall93/A4_Scheduler
    def findById(id):
        rows = Database.getRows('SELECT * FROM `Term` WHERE `id` = %s', (id, ))

        if len(rows) == 0:
            return None

        term = Term()
        term.setId(rows[0]['id'])
        term.setStartDate(rows[0]['start_date'])
        term.setEndDate(rows[0]['end_date'])
        term.setTerm(rows[0]['term'])

        return term
コード例 #26
0
    def findById(id):
        rows = Database.getRows(
            'SELECT * FROM `ModuleSessionType` WHERE `id` = %s', (id, ))

        if len(rows) == 0:
            return None

        sessionType = ModuleSessionType()
        sessionType.setId(rows[0]['id'])
        sessionType.setName(rows[0]['name'])
        sessionType.setDisplayName(rows[0]['display_name'])

        return sessionType
コード例 #27
0
    def all():
        rows = Database.getRows('SELECT * FROM `StaffRole`')

        out = []

        for i in rows:
            staffRole = StaffRole()
            staffRole.setId(i['id'])
            staffRole.setName(i['name'])
            staffRole.setDisplayName(i['display_name'])
            out.append(staffRole)

        return out
コード例 #28
0
    def findById(id):
        rows = Database.getRows('SELECT * FROM `StaffRole` WHERE `id` = %s',
                                (id, ))

        if len(rows) == 0:
            return None

        staffRole = StaffRole()
        staffRole.setId(rows[0]['id'])
        staffRole.setName(rows[0]['name'])
        staffRole.setDisplayName(rows[0]['display_name'])

        return staffRole
コード例 #29
0
ファイル: Module.py プロジェクト: Mwall93/A4_Scheduler
    def all():
        rows = Database.getRows('SELECT * FROM `Module`')

        out = []

        for i in rows:
            module = Module()
            module.setId(i['id'])
            module.setName(i['name'])
            module.setLeader(i['leader'])
            out.append(module)

        return out
コード例 #30
0
ファイル: Module.py プロジェクト: Mwall93/A4_Scheduler
    def findById(id):
        rows = Database.getRows('SELECT * FROM `Module` WHERE `id` = %s',
                                (id, ))

        if len(rows) == 0:
            return None

        module = Module()
        module.setId(rows[0]['id'])
        module.setName(rows[0]['name'])
        module.setLeader(rows[0]['leader'])

        return module
コード例 #31
0
ファイル: ACL.py プロジェクト: Hotallday/Arcbot
class ACL():
    def __init__(self):
        self.database = Database(databaseName="databases/ACL.db")
        self.database.addTable(ACLUser)

    def getOwner(self):
        """
            Summary:
                Returns the ID of the bot owner if there is one

            Args:
                None

            Returns:
                (String): ID of bot owner
        """
        try:
            user = ACLUser.get(owner=True)
            return user.id
        except:
            return None

    def setOwner(self, uid):
        """
            Summary:
                Sets the bot owner

            Args:
                uid (str): ID of the target user

            Returns:
                None
        """
        user, created = self.database.ACLUser.get_or_create(id=uid)

        if(created):
            user.id = uid
            user.access = 1000
            user.owner = True
            user.save()
        else:
            user.owner = True
            user.save()

    def setAccess(self, uid, access, cname=""):
        """
            Summary:
                Sets the database access for a specific user

            Args:
                uid (str): ID of the target user

            Returns:
                (Bool): Successful or Not
        """
        # Check if trying to change owner
        if(self.getOwner == uid):
            return False

        # Set user access
        user, created = self.database.ACLUser.get_or_create(id=uid)

        if(created):
            user.id = uid
            user.access = access
            user.cname = cname
            user.save()
        else:
            user.access = access
            user.cname = cname
            user.save()

        return True

    def getAccess(self, uid):
        """
            Summary:
                Gets the database access for the specified user

            Args:
                uid (str): ID of the target user

            Returns:
                (Int): Access level of the target user, or -1 if not found
        """
        try:
            user = ACLUser.get(id=uid)
            return user.access
        except:
            return -1

    def deleteUser(self, uid):
        """
            Summary:
                Deletes a user from the ACL database

            Args:
                uid (str): ID of the target user

            Returns:
                (Bool): Successful or Not
        """
        try:
            user = self.database.ACLUser.get(id=uid)
            if(user):
                user.delete_instance()
                return True
            else:
                return False
        except:
            return False
コード例 #32
0
ファイル: ACL.py プロジェクト: Hotallday/Arcbot
 def __init__(self):
     self.database = Database(databaseName="databases/ACL.db")
     self.database.addTable(ACLUser)