def set_frontend_config(db: directives.PeeweeSession, instance_name: hug.types.text, long_instance_name: hug.types.text, contact_info_bookings: hug.types.text, contact_info_appointments: hug.types.text = None, form_fields: hug.types.text = "base,address,dayOfBirth,reason", for_real: hug.types.smart_boolean = False): with db.atomic(): if not contact_info_appointments: appointments_contact = contact_info_bookings else: appointments_contact = contact_info_appointments template = { "instanceName": f"{instance_name}", "longInstanceName": f"{long_instance_name}", "contactInfoCoupons": f"{contact_info_bookings}", "contactInfoAppointment": f"{appointments_contact}", "formFields": form_fields.split(","), } if not for_real: print(f"This would update the config with '{json.dumps(template, indent=2)}'. Run with --for_real if you " f"are sure.") sys.exit(1) else: print( f"Updating the config with '{json.dumps(template, indent=2)}'.") try: config = FrontendConfig.get() config.config = template except FrontendConfig.DoesNotExist: config = FrontendConfig.create(config=template) config.save() print("Done.")
def get_goat_movies(genres: hug.types.text, api_key: hug.types.text, hug_timer=5): """ Get a list of the most upvoted (GOAT) movies. Input: gg_id, genres, api_key URL: http://HOST:PORT/get_single_training_movie?genres=none&api_key=API_KEY """ if (check_api_token(api_key) == True): # API KEY VALID if ((genres == ' ') | (genres == '%20')): result = db.movie.find().sort([('goat_upvotes', -1)])[:10] # print("a") return build_goat_json(result, hug_timer) else: print("b") genres.replace('%20', ' ') # Browser pushes ' ', NodeJS pushes '%20' if (' ' in genres): genres = genres.split(' ') # Splitting the genre string into a list of genres! genre_list_check = isinstance(genres, list) # Check if the genres variable is a list (or a single genre string) print("is list? {}".format(genre_list_check)) print("genres: {}".format(genres)) if (genre_list_check == True): # Multiple genres detected! Count the quantity of movies w/ all of these genres! movie_count = db.movie.find({"genre": {'$all': genres}}).sort([('goat_upvotes', -1)]).count() else: # Single genre detected! Count how many movies there are w/ this genre movie_count = db.movie.find({"genre": genres}).sort([('goat_upvotes', -1)]).count() print("movie count: {}".format(movie_count)) if (movie_count > 0): print("greater than 0") # Results found! if (movie_count >= 10): # More than 10 movies found? Let's limit top-k to 10! k_limit = 10 else: # Less than 10 movies found? Let's reduce the top-k limit! k_limit = movie_count if (genre_list_check == True): # Multiple genre 'all' search result = db.movie.find({"genre": {'$all': genres}}).sort([('goat_upvotes', -1)])[:k_limit] else: # Single genre search result = db.movie.find({"genre": genres}).sort([('goat_upvotes', -1)])[:k_limit] return build_goat_json(result, hug_timer) else: # No results, provide json result for nodejs to detect! return {'success': False, 'valid_key': True, 'took': float(hug_timer)} else: # API KEY INVALID! return {'success': False, 'valid_key': False, 'took': float(hug_timer)}
def get_single_training_movie(gg_id: hug.types.text, genres: hug.types.text, actors: hug.types.text, api_key: hug.types.text, hug_timer=5): """ Get a single movie for the training bot section. Retrieves a list of movies the user has previously voted for, used as a filter! URL: http://HOST:PORT/get_single_training_movie?gg_id=anonymous_google_id&genres=none&actors=none&api_key=API_KEY """ if (check_api_token(api_key) == True): # API KEY VALID user_id = get_user_id_by_gg_id(gg_id) # Get the user's movie rating user ID (incremental) if user_id is not None: imdb_list = get_voted_movie_by_user_id(user_id) # Produce a list of the user's previously rated movies. if ((genres == ' ') | (genres == '%20')): remaining_count = db.movie.find({'imdbID': {'$nin': imdb_list}}).count() result = db.movie.find({'imdbID': {'$nin': imdb_list}})[0] # Filter out the list of previously voted for movies, sorted by imdb vote data (rating, quantity votes), takes top 1. return build_training_response(result, hug_timer, remaining_count) else: genres.replace('%20', ' ') # Browser pushes ' ', NodeJS pushes '%20' if (' ' in genres): #blah! genres = genres.split(' ') #print(genres) genre_list_check = isinstance(genres, list) if (genre_list_check == True): remaining_count = db.movie.find({'imdbID': {'$nin': imdb_list}, "genre": {'$all': genres}}).count() else: remaining_count = db.movie.find({'imdbID': {'$nin': imdb_list}, "genre": genres}).count() if (remaining_count > 0): # Results found! Return 1 result to the user. if (genre_list_check == True): result = db.movie.find({'imdbID': {'$nin': imdb_list}, "genre": {'$all': genres}})[0] else: result = db.movie.find({'imdbID': {'$nin': imdb_list}, "genre": genres})[0] return build_training_response(result, hug_timer, remaining_count) else: # No results, provide json result for nodejs to detect! return {'success': False, 'valid_key': True, 'took': float(hug_timer)} else: # Invalid GG_ID return {'success': False, 'valid_key': True, 'took': float(hug_timer)} else: # API KEY INVALID! return {'success': False, 'valid_key': False, 'took': float(hug_timer)}
def token_verify(self, token: hug.types.text): log.info('try to verify this token: ' + str(token)) for word in token.split(' '): try: validPayloadFromToken = jwt.decode(jwt=word, key=self.__apikey__, verify=True, algorithms='HS256') log.info('validPayloadFromToken: ' + str(validPayloadFromToken)) return validPayloadFromToken except Exception as e: log.debug( "This word in 'Authorization' field of the HTTP-Header is not a valid JWT token: '" + word + "'") return False
def sms(msisdn: hug.types.number, to: hug.types.number, text: hug.types.text, **kwargs): """ Looks for messages in the format <phone num> <from name> <message body>""" for key, val in kwargs.items(): print(f"{key}: {val}") if int(msisdn) not in allowed_nums: print("Phone number not allowed.") return ('', 200) try: to_num, from_name, message = text.split(" ", 2) except ValueError: raise UserError( "The message needs to be: " "<number> <from> <message> where the number is a UK mobile number" "and the <from> is up to 9 letters no spaces.") to_num = _parse_number(to_num) from_name = _parse_from_name(from_name) if (len(message) > 480): raise UserError( f"The message is too long ({len(message)}/480 characters)") client.send_message({ 'from': from_name, 'to': to_num, 'text': message, }) client.send_message({ 'from': from_name, 'to': os.environ.get("ALEX_PHONE_NUM"), 'text': message, }) return ('', 200)