Beispiel #1
0
def validTicketRequired(f):
    '''Middleware for checking that a correct email address and ticket number is being used'''
    log.start()

    @wraps(f)
    def decoratedFunction(*args, **kwargs):
        email_address = None
        ticket_number = None

        if request.is_json:
            data = request.get_json()
            email_address = data.get('email_address')
            ticket_number = data.get('ticket_number')

        if email_address is None or ticket_number is None:
            return responses.respondUnauthorized(
                'No email address or ticket number supplied')
        else:
            guest = cache.get(email_address)

            if guest is None:
                return responses.respondUnauthorized('Incorrect email address')

            if ticket_number != guest['ticket_number']:
                return responses.respondUnauthorized('Incorrect ticket number')

        return f(*args, **kwargs, name=guest['name'])

    return decoratedFunction
Beispiel #2
0
def classificationJob():
    '''Handler for the /classification-job POST endpoint \n
    Creates and starts a classification job. \n
    Returns the job data immediately and classification continues in a background thread.
    '''
    try:
        log.start()
        log.info('/classification-job'.center(20, '-'))
        if request.is_json:
            json_data = request.get_json()

            job = {}
            job_id = random.randint(100, 200)
            job['id'] = job_id
            job['classes'] = json_data['classes']
            job['complete'] = False
            job['percentage'] = 0
            jobs[f'{job_id}'] = job

            classification_thread = threading.Thread(
                name=f'classification {job_id}', target=startClassificationJob, args=(job,))
            classification_thread.start()

            return responses.respondCreated(job)
        else:
            return responses.respondBadRequest('No categories defined')
    except Exception as error:
        log.error('Error: ', error)
        return responses.respondInternalServerError(error)
def updateTableOccupancy(table_number, name):
    '''Edit table occupancy
    '''
    log.start()
    log.info(f'PUT: /table/{table_number}'.center(20, '-'))
    data_is_valid = validateDataForUpdate(request)
    if data_is_valid:
        try:
            occupant = request.get_json()
            occupant['name'] = name

            succeded, message = functions.updateTableOccupancy(
                table_number, occupant)

            if succeded:
                return responses.respondOk(message)
            else:
                return responses.respondBadRequest(message)
        except Exception as error:
            log.info('error while selecting seat')
            log.info('*'.center(20, '-'))
            return responses.respondInternalServerError(error)
    else:
        log.info('*'.center(20, '-'))
        return responses.respondBadRequest('Invalid data sent')
Beispiel #4
0
def createUploadJob():
    '''Handler function for uploading a set of folders. \n
    Creates and starts upload jobs for the folders specified in the
    post requests' json payload. \n
    Returns upload job ids immediately and uploads continue in a background thread
    '''
    try:
        log.start()
        log.info(f'/upload-job'.center(20, '-'))
        classes = validateDataForPostUploadJob(request)
        if not classes == False:
            functions.setToken(request.headers.get('Token'))
            all_folders = functions.getFolderNames('')

            folders_to_upload = [
                name for name in classes if name in all_folders]

            upload_jobs = []
            for folder in folders_to_upload:
                job_id = random.randint(300, 400)
                job = {'type': 'upload', 'complete': False,
                       'percentage': 0, 'id': job_id}
                jobs[f'{job_id}'] = job
                upload_jobs.append(job)
                upload_thread = threading.Thread(name=f'{folder}-upload', target=functions.uploadFiles, args=(
                    f'{folder}', job, f'/{folder}', ))
                upload_thread.start()

            return responses.respondCreated(upload_jobs)
        else:
            return responses.respondBadRequest('Classes not sent')
    except Exception as error:
        return responses.respondInternalServerError(error)
def getTableOccupancy(table_number):
    '''Get a tables occupants
    '''
    log.start()
    log.info(f'GET: /table/{table_number}'.center(20, '-'))
    try:
        occupancy = functions.getTableOccupancy(table_number)
        return responses.respondWithData(occupancy)
    except Exception as error:
        log.info('error while trying to retreiving occupancy data')
        log.info('*'.center(20, '-'))
        return responses.respondInternalServerError(error)
Beispiel #6
0
def checkClassificationJobStatus(job_id):
    '''Handler for checking the status of a classification job \n
    Responds with the data for the specified job
    '''
    try:
        log.start()
        log.info(f'/classification-job/{job_id}')
        try:
            job = jobs[job_id]
            return responses.respondWithData(job)
        except KeyError as error:
            log.error('Jobs:', jobs)
            return responses.respondBadRequest(f'Job {job_id} not found')
    except Exception as error:
        log.error('Error:', type(error))
        return responses.respondInternalServerError(error)
Beispiel #7
0
def checkUploadJobStatus(job_id):
    '''Handler for checking the status of an upload. \n
    Returns data on the job with the specified id
    '''
    try:
        log.start()
        log.info(f'/upload-job/{job_id}'.center(20, '-'))
        try:
            job = jobs[job_id]
            return responses.respondWithData(job)
        except KeyError as error:
            return responses.respondBadRequest(f'Job {job_id} not found')
    except Exception as error:
        log.error('Error:', type(error))
        log.error('Jobs:', jobs)
        return responses.respondInternalServerError(error)
Beispiel #8
0
def authenticate(f):
    '''Middleware for checking that a correct email address and ticket number is being used'''
    log.start()

    @wraps(f)
    def decoratedFunction(*args, **kwargs):
        service_key = request.headers.get('Authorization', None)

        if service_key is None:
            return responses.respondUnauthorized('No service key supplied')
        else:
            if service_key != os.environ['SERVICE_KEY']:
                return responses.respondUnauthorized('Incorrect service key')
            else:
                return f(*args, **kwargs)

    return decoratedFunction
Beispiel #9
0
def checkDownloadJobStatus(job_id):
    '''Handler function for checking the status of a download job. \n
    Responds with the data for the specified job
    '''
    try:
        log.start()
        log.info(f'/download-job/{job_id}'.center(20, '-'))
        try:
            job = jobs[job_id]
            return responses.respondWithData(job)
        except KeyError as error:
            log.info(jobs)
            return responses.respondBadRequest(f'Job {job_id} not found')
    except Exception as error:
        log.error('Error:', type(error))
        log.error('Jobs:', jobs)
        return responses.respondInternalServerError(error)
Beispiel #10
0
def createDownloadJob():
    '''Handler function for starting a download job. \n
    Creates and starts a download job. \n
    Returns the job data immediately and downloads continue in a background thread.
     '''
    try:
        log.start()
        log.info('/download-job'.center(20, '-'))
        functions.setToken(request.headers.get('Token'))
        job_id = random.randint(100, 200)
        job = {'type': 'download', 'complete': False,
               'percentage': 0, 'id': job_id}
        jobs[f'{job_id}'] = job
        download_thread = threading.Thread(
            target=functions.downloadFiles, args=(job,))
        download_thread.start()
        return responses.respondCreated(job)
    except Exception as error:
        return responses.respondInternalServerError(error)
Beispiel #11
0
				else:
					self.year = _movie.releasedate.year

			log.trace("Movie Located in TMDB")
			self.tmdb_id = _movie.id
			self.imdb_id = _movie.imdb
			self.slug = self.title
			self.cast = _movie.cast
			if hasattr(_movie, "alternate_titles"):
				self.alternate_title = _movie.alternate_titles

		return


if __name__ == "__main__":

	from sys import argv
	from common import logger
	from logging import DEBUG; TRACE = 5; VERBOSE = 15
	logger.initialize(level=DEBUG)
	DadVision.args = DadVision.cmdoptions.ParseArgs(argv[1:])

	logger.start(DadVision.args.logfile, DEBUG, timed=DadVision.args.timed)

	movie = TMDB()

	if len(DadVision.args.pathname) > 0:
		for pathname in DadVision.args.pathname:
			movie.media_details(pathname)
			movie = movie.tmdb()
Beispiel #12
0
	Library.args = library.options.parser.parse_args(sys.argv[1:])
	log.debug("Parsed command line: {!s}".format(library.args))

	log_level = logging.getLevelName(library.args.loglevel.upper())

	if library.args.logfile == 'daddyvision.log':
		log_file = '{}.log'.format(__pgmname__)
	else:
		log_file = os.path.expanduser(library.args.logfile)

	# If an absolute path is not specified, use the default directory.
	if not os.path.isabs(log_file):
		log_file = os.path.join(logger.LogDir, __pgmname__, log_file)

	logger.start(log_file, log_level, timed=True)

	if library.args.loglevel != 'DEBUG' and library.args.loglevel != 'TRACE':
		if len(library.args.library) != 1:
			library.options.parser.error('Command Error: Missing keyword - "start", "restart" or "stop" needed')
		if library.args.library[0].lower() not in ['start', 'restart', 'stop']:
			library.options.parser.error('Command Error: Invalid keyword - "start", "restart" or "stop" needed')

	try:
		from subprocess import Popen, PIPE
		_p = Popen(["git", "describe", "HEAD", "--long", "--tags"],
				   cwd=os.path.dirname(os.path.dirname(__file__)),
				   stdout=PIPE)
		#_p = Popen(["svnversion", "/usr/local/lib/python2.7/dist-packages/dadvision/"], stdout=PIPE)
		REVISION = _p.communicate()[0]
		REVISION = '{}'.format(REVISION.strip('\n').strip())
Beispiel #13
0
__license__ = "GPL"


class DadVision(object):

	from common import logger
	settings = Settings()
	cmdoptions = CmdOptions()
	args = {}


	def __init__(self):
		super(DadVision, self).__init__()


if __name__ == '__main__':

	from sys import argv
	from logging import INFO, DEBUG, ERROR; TRACE = 5; VERBOSE = 15
	from common import logger
	log = logger.logging.getLogger(__pgmname__)
	logger.initialize(level=DEBUG)
	DadVision.args = DadVision.cmdoptions.ParseArgs(argv[1:])

	logger.start(DadVision.args.logfile, DadVision.args.loglevel, timed=DadVision.args.timed)

	log.info("*** LOGGING STARTED ***")

	_lib_paths = DadVision.args.pathname

	pass
    Library.args = library.options.parser.parse_args(sys.argv[1:])
    log.debug("Parsed command line: {!s}".format(library.args))

    log_level = logging.getLevelName(library.args.loglevel.upper())

    if library.args.logfile == "daddyvision.log":
        log_file = "{}.log".format(__pgmname__)
    else:
        log_file = os.path.expanduser(library.args.logfile)

        # If an absolute path is not specified, use the default directory.
    if not os.path.isabs(log_file):
        log_file = os.path.join(logger.LogDir, __pgmname__, log_file)

    logger.start(log_file, log_level, timed=True)

    if library.args.loglevel != "DEBUG" and library.args.loglevel != "TRACE":
        if len(library.args.library) != 1:
            library.options.parser.error('Command Error: Missing keyword - "start", "restart" or "stop" needed')
        if library.args.library[0].lower() not in ["start", "restart", "stop"]:
            library.options.parser.error('Command Error: Invalid keyword - "start", "restart" or "stop" needed')

    try:
        from subprocess import Popen, PIPE

        _p = Popen(
            ["git", "describe", "HEAD", "--long", "--tags"], cwd=os.path.dirname(os.path.dirname(__file__)), stdout=PIPE
        )
        # _p = Popen(["svnversion", "/usr/local/lib/python2.7/dist-packages/dadvision/"], stdout=PIPE)
        REVISION = _p.communicate()[0]
Beispiel #15
0
class DadVision(object):

    from common import logger
    settings = Settings()
    cmdoptions = CmdOptions()
    args = {}

    def __init__(self):
        super(DadVision, self).__init__()


if __name__ == '__main__':

    from sys import argv
    from logging import INFO, DEBUG, ERROR
    TRACE = 5
    VERBOSE = 15
    from common import logger
    log = logger.logging.getLogger(__pgmname__)
    logger.initialize(level=DEBUG)
    DadVision.args = DadVision.cmdoptions.ParseArgs(argv[1:])

    logger.start(DadVision.args.logfile,
                 DadVision.args.loglevel,
                 timed=DadVision.args.timed)

    log.info("*** LOGGING STARTED ***")

    _lib_paths = DadVision.args.pathname

    pass