async def api_delete_comment(id, request): # user = request.__user__; # if user is None: # raise APIPermissionError('Please signin first.'); check_admin(request.__user__) comment = await Comment.find(id) if comment is None: raise APIResourceNotFoundError('comment') # if comment.user_id == request.__user__.id: # return None; await comment.remove() return dict(id=id)
async def api_modify_blog(id, request, *, name, summary, content): check_admin(request.__user__) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog = await Blog.find(id) blog.name = name.strip() blog.summary = summary.strip() blog.content = content.strip() await blog.update() return blog
def post(self): json_data = request.get_json() data = user_schema.load(json_data) admin = check_admin(data.get("admin_pass")) data = UserSchema(unknown=EXCLUDE).load(json_data) if User.get_by_username(data.get("username")) or User.get_by_email( data.get("email")): return { "message": "Username or email already taken" }, HTTPStatus.BAD_REQUEST if admin and check_email(data.get("email")): user = User(is_admin=True, is_turkuamk=True, **data) user.save() return UserSchema().dump(user), HTTPStatus.CREATED elif check_email(data.get('email')): user = User(is_turkuamk=True, **data) user.save() return user_schema_noadm.dump(user), HTTPStatus.CREATED else: user = User(**data) user.save() return user_schema_outsider.dump(user), HTTPStatus.CREATED
async def api_create_blog(request, *, name, summary, content): check_admin(request.__user__) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name, summary=summary, content=content) await blog.save() return blog
def restart_command_handler(update: telegram.Update, context: telegram.ext.CallbackContext) -> None: message = update.message bot = context.bot if not utils.check_admin(bot, message, analytics_handler, ADMIN_USER_ID): return bot.send_message(message.chat_id, 'Restarting...') threading.Thread(target=stop_and_restart).start()
def restart_command_handler(update: Update, context: CallbackContext): message = update.message bot = context.bot if not check_admin(bot, message, analytics, ADMIN_USER_ID): return bot.send_message(message.chat_id, 'Restarting...') Thread(target=stop_and_restart).start()
def users_command_handler(update: Update, context: CallbackContext): message = update.message bot = context.bot chat_id = message.chat_id if not check_admin(bot, message, analytics, ADMIN_USER_ID): return bot.send_message(chat_id, User.get_users_table('updated' in context.args), parse_mode=ParseMode.MARKDOWN)
def logs_command_handler(update: telegram.Update, context: telegram.ext.CallbackContext) -> None: message = update.message bot = context.bot chat_id = message.chat_id if not utils.check_admin(bot, message, analytics_handler, ADMIN_USER_ID): return try: bot.send_document(chat_id, open('errors.log', 'rb')) except telegram.TelegramError: bot.send_message(chat_id, 'Log is empty')
def logs_command_handler(update: Update, context: CallbackContext): message = update.message bot = context.bot chat_id = message.chat_id if not check_admin(bot, message, analytics, ADMIN_USER_ID): return try: bot.send_document(chat_id, open('errors.log', 'rb')) except: bot.send_message(chat_id, 'Log is empty')
def users_command_handler(update: telegram.Update, context: telegram.ext.CallbackContext) -> None: message = update.message bot = context.bot chat_id = message.chat_id if not utils.check_admin(bot, message, analytics_handler, ADMIN_USER_ID): return bot.send_message( chat_id=chat_id, text=database.User.get_users_table('updated' in context.args), parse_mode=telegram.ParseMode.MARKDOWN_V2)
def admin_race_notification(): try: check = check_admin(session["email"]) except: return redirect(url_for("admin.admin_login")) races = db.races if check == True: try: profile_pic = session["profile_pic"] facebook_name = session["facebook_name"] if request.method == "POST": race_name = str(request.form["race_name"]).strip() race_description = str( request.form["race_description"]).strip() race_difficulty = str(request.form["race_difficulty"]).strip() race = { "name": race_name, "difficulty": int(race_difficulty), "description": race_description, "flag": "not_visible", } races.insert_one(race) compute = calculate_races() races_data = compute[1] len_all_races = compute[2] return render_template( "admin_race_notification.html", profile_pic=session["profile_pic"], facebook_name=session["facebook_name"], email=session["email"], all_races=races_data, len_all_races=len_all_races, ) except: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login")) else: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login"))
def admin_message_notification(): try: check = check_admin(session["email"]) except: return redirect(url_for("admin.admin_login")) messages = db.messages if check == True: try: profile_pic = session["profile_pic"] facebook_name = session["facebook_name"] if request.method == "POST": msg_body = str(request.form["msg_body"]).strip() msg_topic = str(request.form["msg_topic"]).strip() message = { "body": msg_body, "topic": msg_topic, "flag": "not_visible", } messages.insert_one(message) compute = calculate_messages() messages_data = compute[1] len_all_messages = compute[2] return render_template( "admin_message_notification.html", profile_pic=session["profile_pic"], facebook_name=session["facebook_name"], email=session["email"], messages_data=messages_data, len_all_messages=len_all_messages, ) except: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login")) else: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login"))
def delete(self, name): user = User.get_by_id(get_jwt_identity()) json_data = request.get_json() password = json_data.get('password') required_user = User.get_by_username(name) if user.is_admin: if required_user is not None and check_admin(password): required_user.delete() return {"message": 'User successfully deleted'}, HTTPStatus.OK else: return { "message": 'User does not exist or admin password is wrong' }, HTTPStatus.BAD_REQUEST else: return {'message': 'Admins only'}, HTTPStatus.FORBIDDEN
def message_video_handler(update: telegram.Update, context: telegram.ext.CallbackContext) -> None: message = update.effective_message if message is None: return chat = update.effective_chat if chat is None: return chat_type = chat.type bot = context.bot if chat_type != telegram.Chat.PRIVATE: return if cli_args.debug and not utils.check_admin( bot, context, message, analytics_handler, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id attachment = message.video if attachment is None: return file_size = attachment.file_size if file_size is not None and not utils.ensure_size_under_limit( file_size, telegram.constants.MAX_FILESIZE_DOWNLOAD, update, context): return user = update.effective_user input_file_id = attachment.file_id if user is not None: create_or_update_user(bot, user) analytics_handler.track(context, analytics.AnalyticsType.MESSAGE, user) bot.send_chat_action(chat_id, telegram.ChatAction.TYPING) input_file = bot.get_file(input_file_id) input_file_url = input_file.file_path probe = None try: probe = ffmpeg.probe(input_file_url) except ffmpeg.Error: pass with io.BytesIO() as output_bytes: output_type = constants.OutputType.NONE invalid_format = None if probe: for stream in probe['streams']: codec_name = stream.get('codec_name') if codec_name is not None: invalid_format = codec_name if codec_name in constants.VIDEO_CODEC_NAMES: output_type = constants.OutputType.VIDEO_NOTE mp4_bytes = utils.convert(output_type, input_video_url=input_file_url) if not utils.ensure_valid_converted_file( file_bytes=mp4_bytes, update=update, context=context): return if mp4_bytes is not None: output_bytes.write(mp4_bytes) break continue if output_type == constants.OutputType.NONE: if invalid_format is None and input_file_url is not None: parts = os.path.splitext(input_file_url) if parts is not None and len(parts) >= 2: extension = parts[1] if extension is not None: invalid_format = extension[1:] bot.send_message( chat_id=chat_id, text=f'File type "{invalid_format}" is not yet supported.', reply_to_message_id=message_id) return output_bytes.seek(0) output_file_size = output_bytes.getbuffer().nbytes if output_type == constants.OutputType.VIDEO_NOTE: if not utils.ensure_size_under_limit( output_file_size, telegram.constants.MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, telegram.ChatAction.UPLOAD_VIDEO) utils.send_video_note(bot, chat_id, message_id, output_bytes) return bot.send_message(chat_id, 'File type is not yet supported.', reply_to_message_id=message_id)
def message_file_handler(update: telegram.Update, context: telegram.ext.CallbackContext) -> None: message = update.effective_message chat = update.effective_chat if chat is None: return chat_type = chat.type bot = context.bot if message is None: return if cli_args.debug and not utils.check_admin( bot, context, message, analytics_handler, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id attachment = message.effective_attachment if attachment is None: return if type(attachment) is list: if chat_type == telegram.Chat.PRIVATE: bot.send_message( chat_id, 'You need to send the image as a file to convert it to a sticker.', reply_to_message_id=message_id) return if not isinstance( attachment, (telegram.Audio, telegram.Document, telegram.Voice, telegram.Sticker)): return message_type = telegram.utils.helpers.effective_message_type(message) file_size = attachment.file_size if file_size is None: return if not utils.ensure_size_under_limit( file_size, telegram.constants.MAX_FILESIZE_DOWNLOAD, update, context): return user = message.from_user input_file_id = attachment.file_id input_file_name = None if isinstance(attachment, (telegram.Audio, telegram.Document)): input_file_name = attachment.file_name if input_file_name is None and isinstance(attachment, telegram.Audio): input_file_name = attachment.title if user is not None: create_or_update_user(bot, user) analytics_handler.track(context, analytics.AnalyticsType.MESSAGE, user) if chat_type == telegram.Chat.PRIVATE: bot.send_chat_action(chat_id, telegram.ChatAction.TYPING) input_file = bot.get_file(input_file_id) input_file_url = input_file.file_path probe = None try: probe = ffmpeg.probe(input_file_url) except ffmpeg.Error: pass with io.BytesIO() as output_bytes: output_type = constants.OutputType.NONE caption = None invalid_format = None if message_type == 'voice': output_type = constants.OutputType.FILE mp3_bytes = utils.convert(output_type, input_audio_url=input_file_url) if not utils.ensure_valid_converted_file( file_bytes=mp3_bytes, update=update, context=context): return if mp3_bytes is not None: output_bytes.write(mp3_bytes) output_bytes.name = 'voice.mp3' elif message_type == 'sticker': with io.BytesIO() as input_bytes: input_file.download(out=input_bytes) try: image = PIL.Image.open(input_bytes) with io.BytesIO() as image_bytes: image.save(image_bytes, format='PNG') image_bytes.seek(0) output_bytes.write(image_bytes.read()) output_type = constants.OutputType.PHOTO sticker = message['sticker'] emoji = sticker['emoji'] set_name = sticker['set_name'] caption = f'Sticker for the emoji "{emoji}" from the set "{set_name}"' except Exception as error: logger.error(f'PIL error: {error}') else: if probe: for stream in probe['streams']: codec_name = stream.get('codec_name') if codec_name is not None: invalid_format = codec_name if codec_name in constants.VIDEO_CODEC_NAMES: output_type = constants.OutputType.VIDEO mp4_bytes = utils.convert( output_type, input_video_url=input_file_url) if not utils.ensure_valid_converted_file( file_bytes=mp4_bytes, update=update, context=context): return if mp4_bytes is not None: output_bytes.write(mp4_bytes) break continue if output_type == constants.OutputType.NONE: for stream in probe['streams']: codec_name = stream.get('codec_name') if codec_name is not None: invalid_format = codec_name if codec_name in constants.AUDIO_CODEC_NAMES: output_type = constants.OutputType.AUDIO opus_bytes = utils.convert( output_type, input_audio_url=input_file_url) if not utils.ensure_valid_converted_file( file_bytes=opus_bytes, update=update, context=context): return if opus_bytes is not None: output_bytes.write(opus_bytes) break elif codec_name == 'opus': input_file.download(out=output_bytes) output_type = constants.OutputType.AUDIO break continue if output_type == constants.OutputType.NONE: with io.BytesIO() as input_bytes: input_file.download(out=input_bytes) input_bytes.seek(0) try: images = pdf2image.convert_from_bytes(input_bytes.read()) image = images[0] with io.BytesIO() as image_bytes: image.save(image_bytes, format='PNG') image_bytes.seek(0) output_bytes.write(image_bytes.read()) output_type = constants.OutputType.PHOTO except Exception as error: logger.error(f'pdf2image error: {error}') if output_type == constants.OutputType.NONE: try: image = PIL.Image.open(input_bytes) with io.BytesIO() as image_bytes: image.save(image_bytes, format='WEBP') image_bytes.seek(0) output_bytes.write(image_bytes.read()) output_type = constants.OutputType.STICKER except Exception as error: logger.error(f'PIL error: {error}') if output_type == constants.OutputType.NONE: if chat_type == telegram.Chat.PRIVATE: if invalid_format is None and input_file_url is not None: parts = os.path.splitext(input_file_url) if parts is not None and len(parts) >= 2: extension = parts[1] if extension is not None: invalid_format = extension[1:] bot.send_message( chat_id=chat_id, text=f'File type "{invalid_format}" is not yet supported.', reply_to_message_id=message_id) return output_bytes.seek(0) output_file_size = output_bytes.getbuffer().nbytes if caption is None and input_file_name is not None: caption = input_file_name[:telegram.constants.MAX_CAPTION_LENGTH] if output_type == constants.OutputType.AUDIO: if not utils.ensure_size_under_limit( output_file_size, telegram.constants.MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, telegram.ChatAction.UPLOAD_AUDIO) bot.send_voice(chat_id, output_bytes, caption=caption, reply_to_message_id=message_id) return elif output_type == constants.OutputType.VIDEO: if not utils.ensure_size_under_limit( output_file_size, telegram.constants.MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, telegram.ChatAction.UPLOAD_VIDEO) utils.send_video(bot, chat_id, message_id, output_bytes, caption, chat_type) return elif output_type == constants.OutputType.PHOTO: if not utils.ensure_size_under_limit( output_file_size, constants.MAX_PHOTO_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_photo(chat_id, output_bytes, caption=caption, reply_to_message_id=message_id) return elif output_type == constants.OutputType.STICKER: bot.send_sticker(chat_id, output_bytes, reply_to_message_id=message_id) return elif output_type == constants.OutputType.FILE: if not utils.ensure_size_under_limit( output_file_size, telegram.constants.MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, telegram.ChatAction.UPLOAD_DOCUMENT) bot.send_document(chat_id, output_bytes, reply_to_message_id=message_id) return if chat_type == telegram.Chat.PRIVATE: bot.send_message(chat_id, 'File type is not yet supported.', reply_to_message_id=message_id)
def admin_upload_results(): try: check = check_admin(session["email"]) except: return redirect(url_for("admin.admin_login")) if check == True: try: profile_pic = session["profile_pic"] facebook_name = session["facebook_name"] all_data = [] fields = [] admins = db.admin correct_data = False wrong_data = True error = "" notify = "" if request.method == "POST": file = request.files["file"] all_data = [] if file: file_name = secure_filename(file.filename) filetype = file_name.split(".")[1] if filetype == "csv": file.save( os.path.join(app.config['UPLOAD_CSV_TEMP'], file_name)) path_to_csv = os.path.join( app.config['UPLOAD_CSV_TEMP'], file_name) open_csv = open(path_to_csv, "rt") try: reader = csv.reader(open_csv) ct = 0 fields = [] for row in reader: dic = {} if ct == 0: fields = row[:] for i in range(len(fields)): fields[i] = fields[i].lower() else: counter = 0 for each in row: dic[fields[counter]] = each counter += 1 dic["valid"] = True ct += 1 if dic != {}: all_data.append(dic) except: pass finally: open_csv.close() ct = 0 flag = 0 for cur_data in all_data: for field in cur_data: if "name" in field: check_name = validate_name(cur_data[field]) if check_name == False: flag = 1 all_data[ct]["valid"] = False if "day" in field: if cur_data[field] != "DNF" and cur_data[ field] != "dnf" and cur_data[ field] != "Dnf": check_time = validate_time( cur_data[field]) if check_time == False: flag = 1 all_data[ct]["valid"] = False ct += 1 if flag == 0: correct_data = True return redirect( url_for("admin.admin_upload_csv", race_name=file_name)) else: error = "Invalid Data in CSV. Change and upload again." wrong_data = False else: error = "Upload file in CSV format only" return render_template("admin_upload_results.html", profile_pic=session["profile_pic"], facebook_name=session["facebook_name"], email=session["email"], all_data=all_data, fields=fields, correct_data=correct_data, wrong_data=wrong_data, error=error, notify=notify) except: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login")) else: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login"))
def message_text_handler(update: Update, context: CallbackContext): message = update.message chat_type = update.effective_chat.type bot = context.bot if cli_args.debug and not check_admin(bot, message, analytics, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id user = message.from_user entities = message.parse_entities() create_or_update_user(bot, user) analytics.track(AnalyticsType.MESSAGE, user) entity, text = next( ((entity, text) for entity, text in entities.items() if entity.type in [MessageEntity.URL, MessageEntity.TEXT_LINK]), None) if entity is None: return input_link = entity.url if input_link is None: input_link = text with io.BytesIO() as output_bytes: caption = None video_url = None try: yt_dl_options = {'logger': logger, 'no_color': True} with youtube_dl.YoutubeDL(yt_dl_options) as yt_dl: video_info = yt_dl.extract_info(input_link, download=False) if 'entries' in video_info: video = video_info['entries'][0] else: video = video_info if 'title' in video: caption = video['title'] else: caption = input_link requested_formats = video['requested_formats'] video_data = list( filter(lambda format: format['vcodec'] != 'none', requested_formats))[0] audio_data = list( filter(lambda format: format['acodec'] != 'none', requested_formats))[0] if not ensure_size_under_limit(video_data['filesize'], MAX_FILESIZE_UPLOAD, update, context): return video_url = video_data['url'] audio_url = audio_data['url'] except Exception as error: logger.error('youtube-dl error: {}'.format(error)) if chat_type == Chat.PRIVATE and (caption is None or video_url is None): bot.send_message(chat_id, 'No video found on "{}".'.format(input_link), disable_web_page_preview=True, reply_to_message_id=message_id) return mp4_bytes = convert(OutputType.VIDEO, input_video_url=video_url, input_audio_url=audio_url) output_bytes.write(mp4_bytes) output_bytes.seek(0) caption = caption[:MAX_CAPTION_LENGTH] # Video note isn't supported for videos downloaded from URLs yet. send_video(bot, chat_id, message_id, output_bytes, None, caption, chat_type)
def message_video_handler(update: Update, context: CallbackContext): message = update.effective_message chat_type = update.effective_chat.type bot = context.bot if chat_type != Chat.PRIVATE: return if cli_args.debug and not check_admin(bot, message, analytics, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id attachment = message.video if not ensure_size_under_limit(attachment.file_size, MAX_FILESIZE_DOWNLOAD, update, context): return user = update.effective_user input_file_id = attachment.file_id create_or_update_user(bot, user) analytics.track(AnalyticsType.MESSAGE, user) bot.send_chat_action(chat_id, ChatAction.TYPING) input_file = bot.get_file(input_file_id) input_file_url = input_file.file_path probe = None try: probe = ffmpeg.probe(input_file_url) except: pass with io.BytesIO() as output_bytes: output_type = OutputType.NONE invalid_format = None if probe: for stream in probe['streams']: codec_name = stream.get('codec_name') codec_type = stream.get('codec_type') if codec_name is not None and codec_type == VIDEO_CODED_TYPE: invalid_format = codec_name if codec_name in VIDEO_CODEC_NAMES: output_type = OutputType.VIDEO_NOTE mp4_bytes = convert(output_type, input_video_url=input_file_url) output_bytes.write(mp4_bytes) break else: continue if output_type == OutputType.NONE: if invalid_format is None: invalid_format = os.path.splitext(input_file_url)[1][1:] bot.send_message( chat_id, 'File type "{}" is not yet supported.'.format(invalid_format), reply_to_message_id=message_id) output_bytes.seek(0) output_file_size = output_bytes.getbuffer().nbytes if output_type == OutputType.VIDEO_NOTE: if not ensure_size_under_limit( output_file_size, MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, ChatAction.UPLOAD_VIDEO) send_video_note(bot, chat_id, message_id, output_bytes) return bot.send_message(chat_id, 'File type is not yet supported.', reply_to_message_id=message_id)
def message_file_handler(update: Update, context: CallbackContext): message = update.message chat_type = update.effective_chat.type bot = context.bot if cli_args.debug and not check_admin(bot, message, analytics, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id attachment = message.effective_attachment if type(attachment) is list: if chat_type == Chat.PRIVATE: bot.send_message( chat_id, 'You need to send the image as a file to convert it to a sticker.', reply_to_message_id=message_id) return if not ensure_size_under_limit(attachment.file_size, MAX_FILESIZE_DOWNLOAD, update, context): return user = message.from_user input_file_id = attachment.file_id input_file_name = attachment.file_name if getattr( attachment, 'file_name', None) else attachment.title create_or_update_user(bot, user) analytics.track(AnalyticsType.MESSAGE, user) if chat_type == Chat.PRIVATE: bot.send_chat_action(chat_id, ChatAction.TYPING) input_file = bot.get_file(input_file_id) input_file_url = input_file.file_path probe = None try: probe = ffmpeg.probe(input_file_url) except: pass with io.BytesIO() as output_bytes: output_type = OutputType.NONE invalid_format = None if probe: for stream in probe['streams']: codec_name = stream.get('codec_name') codec_type = stream.get('codec_type') if codec_name is not None and codec_type == VIDEO_CODED_TYPE: invalid_format = codec_name if codec_name == 'mp3': output_type = OutputType.AUDIO opus_bytes = convert(output_type, input_video_url=input_file_url) output_bytes.write(opus_bytes) break elif codec_name == 'opus': input_file.download(out=output_bytes) output_type = OutputType.AUDIO break elif codec_name in VIDEO_CODEC_NAMES: output_type = OutputType.VIDEO mp4_bytes = convert(output_type, input_video_url=input_file_url) output_bytes.write(mp4_bytes) break else: continue if output_type == OutputType.NONE: with io.BytesIO() as input_bytes: input_file.download(out=input_bytes) try: images = convert_from_bytes(input_bytes.getbuffer()) image = images[0] with io.BytesIO() as image_bytes: image.save(image_bytes, format='PNG') output_bytes.write(image_bytes.getbuffer()) output_type = OutputType.PHOTO except Exception as error: logger.error('pdf2image error: {}'.format(error)) if output_type == OutputType.NONE: try: image = Image.open(input_bytes) with io.BytesIO() as image_bytes: image.save(image_bytes, format='WEBP') output_bytes.write(image_bytes.getbuffer()) output_type = OutputType.STICKER except Exception as error: logger.error('PIL error: {}'.format(error)) if output_type == OutputType.NONE: if chat_type == Chat.PRIVATE: if invalid_format is None: invalid_format = os.path.splitext(input_file_url)[1][1:] bot.send_message(chat_id, 'File type "{}" is not yet supported.'.format( invalid_format), reply_to_message_id=message_id) return output_bytes.seek(0) output_file_size = output_bytes.getbuffer().nbytes caption = None if input_file_name is not None: caption = input_file_name[:MAX_CAPTION_LENGTH] if output_type == OutputType.AUDIO: if not ensure_size_under_limit( output_file_size, MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, ChatAction.UPLOAD_AUDIO) bot.send_voice(chat_id, output_bytes, caption=caption, reply_to_message_id=message_id) return elif output_type == OutputType.VIDEO: if not ensure_size_under_limit( output_file_size, MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, ChatAction.UPLOAD_VIDEO) send_video(bot, chat_id, message_id, output_bytes, attachment, caption, chat_type) return elif output_type == OutputType.PHOTO: if not ensure_size_under_limit( output_file_size, MAX_PHOTO_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_photo(chat_id, output_bytes, caption=caption, reply_to_message_id=message_id) return elif output_type == OutputType.STICKER: bot.send_sticker(chat_id, output_bytes, reply_to_message_id=message_id) return if chat_type == Chat.PRIVATE: bot.send_message(chat_id, 'File type is not yet supported.', reply_to_message_id=message_id)
def admin_upload_csv(race_name): try: check = check_admin(session["email"]) except: return redirect(url_for("admin.admin_login")) if check == True: check_file = os.path.isfile( os.path.join(app.config['UPLOAD_CSV_TEMP'], race_name)) if check_file == True: try: profile_pic = session["profile_pic"] facebook_name = session["facebook_name"] correct_data = False wrong_data = True error = "" notify = "" if request.method == "POST": db_race_difficulty = int( request.form["db_race_difficulty"].strip()) db_company_name = str( request.form["db_company_name"]).strip() db_company_description = str( request.form["db_company_description"]).strip() db_company_number = str( request.form["db_company_number"]).strip() db_company_email = str( request.form["db_company_email"]).strip() db_company_address_part_one = str( request.form["db_company_address_part_one"]).strip() db_company_address_part_two = str( request.form["db_company_address_part_two"]).strip() db_company_address_part_three = str( request.form["db_company_address_part_three"]).strip() db_company_address_part_four = str( request.form["db_company_address_part_four"]).strip() db_company_nation = str( request.form["db_company_nation"]).strip() db_race_date = str(request.form["db_race_date"]).strip() shutil.copy2( os.path.join(app.config['UPLOAD_CSV_TEMP'], race_name), os.path.join(app.config['UPLOAD_CSV_FINAL'], race_name)) os.remove( os.path.join(app.config['UPLOAD_CSV_TEMP'], race_name)) csv_to_json( os.path.join(app.config['UPLOAD_CSV_FINAL'], race_name), db_race_difficulty, db_company_name, db_company_description, db_company_number, db_company_email, db_company_address_part_one, db_company_address_part_two, db_company_address_part_three, db_company_address_part_four, db_company_nation, db_race_date) revise_all_ranks() notify = "Successfully updated CSV" return redirect(url_for("admin.admin_upload_results")) return render_template( "admin_csv_upload.html", profile_pic=session["profile_pic"], facebook_name=session["facebook_name"], email=session["email"], ) except: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login")) else: return redirect(url_for("admin.admin_upload_results")) else: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login"))
def message_text_handler(update: telegram.Update, context: telegram.ext.CallbackContext) -> None: message = update.effective_message if message is None: return chat = update.effective_chat if chat is None: return chat_type = chat.type bot = context.bot if cli_args.debug and not utils.check_admin( bot, context, message, analytics_handler, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id user = message.from_user entities = message.parse_entities() if user is not None: create_or_update_user(bot, user) analytics_handler.track(context, analytics.AnalyticsType.MESSAGE, user) valid_entities = { entity: text for entity, text in entities.items() if entity.type in [telegram.MessageEntity.URL, telegram.MessageEntity.TEXT_LINK] } entity, text = next(iter(valid_entities.items())) if entity is None: return input_link = entity.url if input_link is None: input_link = text with io.BytesIO() as output_bytes: caption = None video_url = None audio_url = None try: yt_dl_options = {'logger': logger, 'no_color': True} with youtube_dl.YoutubeDL(yt_dl_options) as yt_dl: video_info = yt_dl.extract_info(input_link, download=False) if 'entries' in video_info: video = video_info['entries'][0] else: video = video_info if 'title' in video: caption = video['title'] else: caption = input_link file_size = None if 'requested_formats' in video: requested_formats = video['requested_formats'] video_data = list( filter( lambda requested_format: requested_format['vcodec'] != 'none', requested_formats))[0] audio_data = list( filter( lambda requested_format: requested_format['acodec'] != 'none', requested_formats))[0] if 'filesize' in video_data: file_size = video_data['filesize'] video_url = video_data['url'] if file_size is None: file_size = utils.get_file_size(video_url) audio_url = audio_data['url'] elif 'url' in video: video_url = video['url'] file_size = utils.get_file_size(video_url) if file_size is not None: if not utils.ensure_size_under_limit( file_size, telegram.constants.MAX_FILESIZE_UPLOAD, update, context): return except Exception as error: logger.error(f'youtube-dl error: {error}') if chat_type == telegram.Chat.PRIVATE and (caption is None or video_url is None): bot.send_message(chat_id, 'No video found on this link.', disable_web_page_preview=True, reply_to_message_id=message_id) return mp4_bytes = utils.convert(constants.OutputType.VIDEO, input_video_url=video_url, input_audio_url=audio_url) if not utils.ensure_valid_converted_file( file_bytes=mp4_bytes, update=update, context=context): return if mp4_bytes is not None: output_bytes.write(mp4_bytes) output_bytes.seek(0) if caption is not None: caption = caption[:telegram.constants.MAX_CAPTION_LENGTH] utils.send_video(bot, chat_id, message_id, output_bytes, caption, chat_type)
async def api_delete_blogs(id, request): check_admin(request.__user__) blog = await Blog.find(id) if blog: await blog.remove() return dict(id=id)
def admin_tag_riders(): try: check = check_admin(session["email"]) except: return redirect(url_for("admin.admin_login")) users = db.users results = db.results race_name = "Hero_MTB_Himalaya_2016" if check == True: try: profile_pic = session["profile_pic"] facebook_name = session["facebook_name"] race_details = results.find_one({"race_name": str(race_name)}) straight_match = {} multiple_matches = {} for cur_ser_num in race_details["race_result"]: if race_details["race_result"][cur_ser_num]["rider_tag"] != "": straight_match[cur_ser_num] = { "rider_tag": race_details["race_result"][cur_ser_num]["rider_tag"], "name": race_details["race_result"][cur_ser_num]["name"] } else: name = race_details["race_result"][cur_ser_num]["name"] calculate_name = name.split() if len(calculate_name) > 1: if "." in calculate_name[0]: calculate_name = calculate_name[1] else: calculate_name = calculate_name[0] else: try: calculate_name = calculate_name[0] except: calculate_name = "" all_riders = users.find({}) cur_match = [] for cur_rider in all_riders: cur_rider_name = "" prefix = cur_rider["Name"]["prefix"] first_name = cur_rider["Name"]["first_name"] middle_name = cur_rider["Name"]["middle_name"] last_name = cur_rider["Name"]["last_name"] if prefix != "": cur_rider_name += prefix + " " if first_name != "": cur_rider_name += first_name + " " if middle_name != "": cur_rider_name += middle_name + " " if last_name != "": cur_rider_name += last_name + " " tag = str(cur_rider["_id"]) if calculate_name.lower() == first_name.lower(): cur_match.append({ "name": cur_rider_name, "rider_tag": tag }) multiple_matches[cur_ser_num] = { "name": name, "possible_matches": cur_match } return "a" except: #session.pop("email",None) #session.pop("facebook_name",None) #session.pop("profile_pic",None) #session.pop("facebook_token",None) return redirect(url_for("admin.admin_login")) else: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login"))
def update_race_rankings(): all_races_messages = calculate_races_messages() all_races = all_races_messages[0] all_messages = all_races_messages[1] len_all_races = all_races_messages[2] len_all_messages = all_races_messages[3] check = check_admin(session["email"]) Email = "" profile_pic = "" facebook_name = "" logged_in = False if "email" in session: logged_in = True Email = session["email"] if "profile_pic" in session: profile_pic = session["profile_pic"] if "facebook_name" in session: facebook_name = session["facebook_name"] try: user = users.find_one({"Email": session["email"]}) get_image = user.get("image", None) session["facebook_name"] = user.get("facebook_name", "") if get_image != None: session[ "profile_pic"] = "static/img/profile_images/" + get_image + "?r=" + str( randint(1, 10000000)) var = session["profile_pic"] if "?" in var: var = var.split("?")[0] var = ROOT_DIR + "/" + var (width, height) = get_size(var) else: (width, height) = (0, 100) except: (width, height) = (0, 100) get_html = print_html(profile_pic, facebook_name, height, Email) if check == True: results = db.results users = db.users race_name = request.args.get("race_name", "") if race_name != "": result = results.find_one({"race_name": race_name}) if result != None and result["active"] != "no" and result[ "active"] != "no": update_advantage_points(race_name) # Update the final score for the race difficulty = result.get("difficulty", 1) if difficulty == 0: difficulty = 1 for diff in range(difficulty): score_dic = [] max_total_time = float("-inf") min_total_time = float("inf") prev_ratings = {} for ser_num in result["race_result"]: cur_score = {} cur_score[ser_num] = { "adv_point": result["race_result"][ser_num]["advantage_point"], "total_time": result["race_result"][ser_num]["total_race_time"], } rider_tag = result["race_result"][ser_num]["rider_tag"] if rider_tag != "": user = users.find_one({"_id": ObjectId(rider_tag)}) try: prev_ratings[ser_num] = user["elo_rating"] except: pass if result["race_result"][ser_num][ "total_race_time"] != "DNF" and result[ "race_result"][ser_num][ "total_race_time"] != "" and result[ "race_result"][ser_num][ "total_race_time"] != "dnf": max_total_time = max( result["race_result"][ser_num] ["total_race_time"], max_total_time) min_total_time = min( result["race_result"][ser_num] ["total_race_time"], min_total_time) score_dic.append(cur_score) final_scores = {} div_factor = 100.0 / (max_total_time - min_total_time) dnf_riders = [] for scores in score_dic: adv_point = 0 for score in scores: ser_num = score cur_serial_num = "race_result.{ser_num}.final_score".format( ser_num=ser_num) cur_score = scores[score]["total_time"] adv_point = scores[score]["adv_point"] try: final_scores[ser_num] = "%.3f" % ( (int(max_total_time) - int(cur_score)) * div_factor + adv_point) results.update_one({"race_name": race_name}, { "$set": { str(cur_serial_num): float(final_scores[ser_num]) } }) except: dnf_riders.append(ser_num) results.update_one( {"race_name": race_name}, {"$set": { str(cur_serial_num): adv_point }}) final_scores = sorted(final_scores.items(), key=operator.itemgetter(1)) ct = 0 # Calculate the elo rating for every rider final_ratings = elo_match() ser_num_list = [] for i in final_scores: try: rating = float(prev_ratings[i[0]]) ser_num_list.append(i[0]) ct += 1 final_ratings.add_rider(i[0], ct, rating) except: pass final_ratings.calculate_elo_rating() #update elo_rating for every rider for i in ser_num_list: cur_rating = float("%.3f" % final_ratings.get_elo(i)) rider_tag = result["race_result"][i]["rider_tag"] if rider_tag != "": users.update_one( {"_id": ObjectId(rider_tag)}, {"$set": { "elo_rating": cur_rating, }}) # Update CGPA rating for every rider update_cgpa_ratings_with_name(race_name) return render_template( "update_rank.html", get_html=Markup(get_html), logged_in=logged_in, profile_pic=profile_pic, facebook_name=facebook_name, email=Email, all_races=all_races, len_all_races=len_all_races, all_messages=all_messages, len_all_messages=len_all_messages, race_name=race_name, ) else: return render_template( "error.html", error= "No Race Found , pass race name as argument -- /update_rankings?race_name={name of existing race}", get_html=Markup(get_html), logged_in=logged_in, profile_pic=profile_pic, facebook_name=facebook_name, email=Email, all_races=all_races, len_all_races=len_all_races, all_messages=all_messages, len_all_messages=len_all_messages, ) else: return render_template( "error.html", error= "No Race Found , pass race name as argument -- /update_rankings?race_name={name of existing race}", get_html=Markup(get_html), profile_pic=profile_pic, facebook_name=facebook_name, logged_in=logged_in, email=Email, all_races=all_races, len_all_races=len_all_races, all_messages=all_messages, len_all_messages=len_all_messages, ) else: return render_template( "error.html", error="You Are Not Admin", get_html=Markup(get_html), profile_pic=profile_pic, facebook_name=facebook_name, logged_in=logged_in, email=Email, all_races=all_races, len_all_races=len_all_races, all_messages=all_messages, len_all_messages=len_all_messages, )
def admin_dashboard(): try: check = check_admin(session["email"]) except: return redirect(url_for("admin.admin_login")) print 1 users = db.users if check == True: try: profile_pic = session["profile_pic"] facebook_name = session["facebook_name"] # Make it true on production consider_rider_tag = False if consider_rider_tag == False: total_registered_users = users.count() else: pass all_users = users.find({}) total_fully_reg_users = 0 for cur_rider in all_users: flag = 0 form_personal_profile = cur_rider.get("form_personal_profile", False) form_rider_profile = cur_rider.get("form_rider_profile", False) form_medical_profile = cur_rider.get("form_medical_profile", False) form_bike_profile = cur_rider.get("form_bike_profile", False) form_race_profile = cur_rider.get("form_race_profile", False) if form_personal_profile == False or form_rider_profile == False or form_bike_profile == False or form_medical_profile == False or form_race_profile == False: flag = 1 if flag == 0: total_fully_reg_users += 1 admins = db.admin allowed_emails = admins.find({}) for i in allowed_emails: allowed_emails = i["Email"] all_admins = [] for i in allowed_emails: all_admins.append(i.encode('utf-8')) return render_template( "admin_dashboard.html", profile_pic=session["profile_pic"], facebook_name=session["facebook_name"], email=session["email"], total_registered_users=total_registered_users, total_fully_reg_users=total_fully_reg_users, len_all_races=calculate_races()[2], all_admins=all_admins, ) except: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login")) else: session.pop("email", None) session.pop("facebook_name", None) session.pop("profile_pic", None) session.pop("facebook_token", None) return redirect(url_for("admin.admin_login"))