def upload_manual_post_text(): res = {'status': '', 'data': {}, 'error': {}} req_data = request.get_json() name = generate_unique_string(req_data['name']) body = req_data['body'] md5 = string2md5(body) if len(req_data['name']) > 50: return api_response({ 'status': 'notok', 'error:': 'Name is longer than 50 chars' }) new_post = PostModel(name=name, body=body, md5=md5, post_type_id=app_constants.POST_TYPE_TEXT, user_id=g.user.id) try: db.session.add(new_post) db.session.commit() except IntegrityError as unique: db.session.rollback() return api_response({ 'status': 'notok', 'error:': 'Post already added in DB' }) res['status'] = 'ok' res['data'] = 'Post added to DB' return api_response(res)
def signup(): req_data = request.get_json() res = {'status': '', 'data': {}, 'error': {}} email = req_data['email'] name = req_data['name'] password = req_data['password'] secret_word = req_data['secret_word'] if not re.match(email_regexp, email): res['status'] = app_constants.notok_status res['error'] = 'Email pattern not ok !' return api_response(res, 400) elif validate_password( password) != True: #poate ar trebui sa scriu altfel asta :) res['status'] = app_constants.notok_status res['error'] = validate_password(password) return api_response(res, 400) elif secret_word != current_app.config['SECRET_WORD_REGISTRATION']: res['status'] = app_constants.notok_status res['error'] = 'Wrong secret word !' return api_response(res, 400) else: user = UserModel.query.filter_by(email=email).first() if not user: new_user = UserModel(name=name, email=email, password=password) role = RoleModel.query.get(app_constants.ROLE_USER) new_user.roles.append(role) new_user.set_password(password) db.session.add(new_user) db.session.commit() res['status'] = app_constants.ok_status return api_response(res) else: res['status'] = app_constants.notok_status res['error'] = 'User already exist !' return api_response(res, 400)
def decorated_auth(*args, **kwargs): if token_name not in request.headers: res['error'] = {'message' : 'Authentication token is not available, please login to get one'} res['status'] = 'notok' return api_response(res, status_code=401) request_token = request.headers.get(token_name) data = Auth.decode_token(request_token) if data['error']: return api_response(data, status_code=401) # return Response( # mimetype="application/json", # response=json.dumps(data), # status=401 # ) user_id = data['data']['user_id'] if current_app.config['JWT_CHECK_DB']: user_token = UserTokenModel.query.filter_by(token=request_token).first() if (user_token is None) or (user_token.user_id != user_id): res['error'] = {'message' : 'Invalid Token DB'} res['status'] = 'notok' return api_response(res, status_code=401) logged_user = UserModel.query.filter_by(id = user_id).first() if not logged_user: res['error'] = {'message' : 'User does not exist, invalid token'} res['status'] = 'notok' return api_response(res, status_code=401) g.user = logged_user return func(*args, **kwargs)
def forgot_password_process(p_token): res = {'status': app_constants.ok_status, 'data': {}, 'error': {}} req_data = request.get_json() new_password = req_data['password'] user = UserModel.verify_reset_password(p_token) if not user: res['status'] = app_constants.notok_status res['error'] = 'Token is incorrect !' return api_response(res, 401) user.set_password(new_password) db.session.commit() res['status'] = app_constants.ok_status return api_response(res, 200)
def upload_post_text(): res = {'status': '', 'data': {}, 'error': {}} req_data = request.get_json() source_type = req_data['source_type'] nr_of_calls = req_data['nr_of_calls'] post_list = [] post_list_success = [] post_list_failed = [] ## source type must be: api or json file if source_type == 'chuck_norris': for i in range(nr_of_calls): chuk_joke = get_chuck_norris_facts() ## call chuck norris api chuck_url = chuk_joke['url'] chuck_body = chuk_joke['value'] post_list.append({ 'name': chuck_url, 'body': chuck_body, 'error:': '' }) elif os.path.splitext(source_type)[ 1] == '.json': ## file should be .json type in utils/jokes ... file_path = current_app.root_path + '/utils/joke_files/' + source_type with open(file_path) as file: data = json.load(file) for line in data: name = source_type + '-' + str(line['name']) body = line['body'] post_list.append({'name': name, 'body': body, 'error:': ''}) else: res['status'] = 'notok' res['error'] = 'Incorrect post source' return api_response(res) ## add list of posts to DB for post in post_list: md5 = string2md5(post['body']) new_post = PostModel(name=post['name'], body=post['body'], md5=md5, post_type_id=app_constants.POST_TYPE_TEXT, user_id=g.user.id) try: db.session.add(new_post) db.session.commit() post_list_success.append(post) except IntegrityError as unique: db.session.rollback() post.update({'error:': 'Post already added in DB'}) post_list_failed.append(post) res['status'] = 'ok' res['data'] = {'success': post_list_success, 'failed': post_list_failed} return api_response(res)
def forgot_password_request(): req_data = request.get_json() res = {'status': '', 'data': {}, 'error': {}} email = req_data['email'] user = UserModel.query.filter_by(email=email).first() if user: current_app.logger.info('send email password') send_password_reset_email(user) res['status'] = app_constants.ok_status return api_response(res, 200) else: res['status'] = app_constants.notok_status res['error'] = "User {0} not found in database !".format(email) return api_response(res, 401)
def get_followers(): api = create_api() followers_list = [] added_followers = [] removed_followers = [] current_user = api.me() for item in tweepy.Cursor(api.followers, id=current_user._json['screen_name']).items(500): followers_list.append(item) ## check if current followers exist in database for follower in followers_list: id_follower = follower._json['id_str'] name_follower = follower._json['screen_name'] new_user = TwitterFollowersModel.query.filter_by(id_follower=id_follower).first() if new_user == None: new_follower = TwitterFollowersModel(id_follower=id_follower, screen_name=name_follower, active=1) db.session.add(new_follower) db.session.commit() added_followers.append({'id': id_follower, 'name': name_follower}) ## check if follower from database are still with us followers_db = TwitterFollowersModel.query.filter_by(active=1).all() for follower in followers_db: if follower.id_follower not in [item._json['id_str'] for item in followers_list]: follower.active = 0 db.session.add(follower) db.session.commit() removed_followers.append({'id': follower.id_follower, 'name': follower.screen_name}) result = {'added_followers': added_followers, 'removed_followers': removed_followers} return api_response({'status': 'ok', 'data': result, 'error': ''})
def publish_post_to_twitter(): res = {'status': '', 'data': {}, 'error': ''} api = create_api() post_sql = f"select p.id as post_id, p.body as post_body \ from {cfg_db_schema}.post p \ left join {cfg_db_schema}.post_platform pp on pp.post_id = p.id and pp.platform_id = {PLATFORM_TWITTER_ID} \ where pp.platform_id is null \ order by p.md5 \ limit 1;" result_sql = execute_query(post_sql) if len(result_sql) != 0: db_post_body = result_sql[0]['post_body'] db_post_id = result_sql[0]['post_id'] db_post_body_hastags = sanitize_tweet(db_post_body, current_app.config['TWITTER_TWEET_LEN']) ## limit tweet to maximum allowed try: ## from here: https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html post = PostModel.query.get(db_post_id) platform = PlatformModel.query.get(PLATFORM_TWITTER_ID) post_platform = PostPlatformModel(error=0) post_platform.platform = platform post_platform.post = post post.platform.append(post_platform) db.session.add(post) db.session.commit() ## add tweet tw_status = api.update_status(db_post_body_hastags) tw_status_id = tw_status._json['id'] ## add tweet api.create_favorite(tw_status_id) ## like previous added tweet except Exception as ex_tw: ## if error then update post_platform error with 1 post_platform = PostPlatformModel.query.filter_by(post_id=post.id, platform_id=platform.id).first() post_platform.error = 1 post_platform.error_msg = str(ex_tw)[:200] db.session.commit() current_app.logger.info(f'Twitter ERROR: {ex_tw}') res['status'] = 'notok' res['error'] = f'Unable to post, Twitter API problem: {ex_tw}' return api_response(res, status_code=500) res['status'] = 'ok' res['data'] = db_post_body return api_response(res) else: Api.log_db('publish_post_to_twitter', 'No more post available in DB to publish on Twitter') return api_response({'status': 'notok', 'data': {}, 'error': 'Posts not available'}, status_code=500)
def login(): req_data = request.get_json() res = {'status': app_constants.ok_status, 'data': {}, 'error': {}} email = req_data['email'] password = req_data['password'] user = UserModel.query.filter_by(email=email).first() if user and user.check_password(password): jwt_token = Auth.generate_token(user.id) res['status'] = app_constants.ok_status res['data'] = {'token': jwt_token} if current_app.config['JWT_CHECK_DB']: user_token = UserTokenModel(token=jwt_token, user_id=user.id) db.session.add(user_token) db.session.commit() return api_response(res, 200) else: res['status'] = app_constants.notok_status res['error'] = 'User or password is incorrect' return api_response(res, 401)
def upload_post_files(): res = {'status': '', 'data': {}, 'error': {}} files = request.files.getlist('files[]') if len(files) == 0: res['status'] = 'notok' res['error'] = 'No files selected' return api_response(res) valid_files = [] invalid_files = [] for file in files: file_read = file.read( ) #!!! i need to store de read value into a variable because the cursor moves to end after every read if is_allowed_for_post(file.filename): filename = secure_filename( file.filename) + '_' + generate_random_string() md5 = hashlib.md5(file_read).hexdigest() files_existing = PostModel.query.filter_by(md5=md5).all() if len(files_existing) == 0: image_str = str(image2base64(file_read)) new_post = PostModel( name=filename, body=image_str, md5=md5, post_type_id=app_constants.POST_TYPE_IMAGE, user_id=g.user.id) db.session.add(new_post) db.session.commit() valid_files.append({'name': file.filename, 'error': ''}) else: invalid_files.append({ 'name': file.filename, 'error': 'File already exist' }) else: invalid_files.append({ 'name': file.filename, 'error': 'Wrong format' }) # current_app.logger.info(f'Fisierele valide sunt: {valid_files}') # current_app.logger.info(f'Fisierele invalide sunt: {invalid_files}') return api_response(valid_files + invalid_files)
def change_password(): res = {'status': app_constants.ok_status, 'data': {}, 'error': {}} req_data = request.get_json() old_password = req_data['old_password'] new_password = req_data['new_password'] current_user = g.user if not current_user.check_password(old_password): res['status'] = app_constants.notok_status res['error'] = 'Old password is not ok !' return api_response(res, 401) elif validate_password(new_password) != True: res['status'] = app_constants.notok_status res['error'] = validate_password(new_password) return api_response(res, 401) else: user = current_user user.set_password(new_password) db.session.add(user) db.session.commit() res['status'] = app_constants.ok_status res['data'] = 'Password changed !' return api_response(res, 200)
def wrapper(*args, **kwargs): perm_sql = f"select distinct u.id, u.name u_name, p.id permi_id, p.name perm_name \ from {cfg_db_schema}.users u \ inner join {cfg_db_schema}.users_role ur on ur.user_id = u.id \ inner join {cfg_db_schema}.\"role\" r on r.id = ur.role_id \ inner join {cfg_db_schema}.role_permission rp on rp.role_id = ur.role_id \ inner join {cfg_db_schema}.permission p on p.id = rp.permission_id \ where u.id = {g.user.id}" perm_res = execute_query(perm_sql) permissions_name = [] for dict_list in perm_res: for key, value in dict_list.items(): if key == 'perm_name': permissions_name.append(value) for expected_arg in expected_args: if expected_arg not in permissions_name or permissions_name is None: return api_response({'error': f"You dont have enough permissions: {', '.join(expected_args)}"}) return func(*args, **kwargs)
def publish_reaction_to_reply(): """Get last 10 reply on my tweets and add a like/reply/retweet !!! IMPORTANT Need to get replies from last checked reply(stored in DB / since_id=p_tweet_id) to avoid duplicate reply from logged user """ res = {'status': '', 'data': {}, 'error': ''} nr_replies_checked_cfg = current_app.config['LAST_REPLIES_CHECKED'] last_reply_db_config = PlatformConfigModel.query.filter_by(platform_id=PLATFORM_TWITTER_ID, id_config=1).first() ## if no value is set in DB then get only the last reply / else get last current_app.config['LAST_REPLIES_CHECKED'] replies api = create_api() if last_reply_db_config.value == '': # current_app.logger.info('no value set') replies = tweepy.Cursor(api.search, q='to:{}'.format('@' + current_app.config['TWITTER_USER']), result_type='recent' , tweet_mode='extended').items(1) else: # current_app.logger.info(f'value is set at: {last_reply_db_config.value}') replies = tweepy.Cursor(api.search, q='to:{}'.format('@' + current_app.config['TWITTER_USER']), since_id=last_reply_db_config.value, ## here get last tweet liked result_type='recent' , tweet_mode='extended').items(nr_replies_checked_cfg) last_reply_tweet_id = last_reply_db_config.value replies_list = [reply for reply in replies] replies_list_revert = [r for r in reversed(replies_list)] quotes=[] db_quotes = QuoteModel.query.filter_by(active=1).all() for quote in db_quotes: quotes.append(quote.body) for reply in replies_list_revert: last_reply_tweet_id = reply.id try: reply_text = reply._json['full_text'] # random_reply = sanitize_tweet(random.choice(confucius_quotes), current_app.config['TWITTER_TWEET_LEN']) ## limit tweet to maximum allowed random_reply = sanitize_tweet(get_string_from_inside_list(reply_text, quotes), current_app.config['TWITTER_TWEET_LEN']) ## limit tweet to maximum allowed ## react to reply api.create_favorite(last_reply_tweet_id) api.update_status(status = random_reply, in_reply_to_status_id = last_reply_tweet_id , auto_populate_reply_metadata=True) except Exception as e: current_app.logger.info(f"LIKE ERROR: reply: {reply.id} text: {reply._json['full_text']} for reply: {reply.in_reply_to_status_id} ERROR: {e}") # current_app.logger.info(f"reply: {reply.id} text: {reply._json['full_text']} for reply: {reply.in_reply_to_status_id} txt: {random.choice(confucius_quotes)}") last_reply_db_config.value = last_reply_tweet_id; db.session.commit() return api_response({'status': 'ok', 'data': 'Reaction to reply added !', 'error': ''})
def publish_reaction_to_hastags(): api = create_api() req_data = request.get_json() reaction_type = req_data['reaction_type'] last_tweet_db_config = PlatformConfigModel.query.filter_by(platform_id=PLATFORM_TWITTER_ID, id_config=2).first() last_user_tweet = api.user_timeline(count=1, tweet_mode='extended')[0] if int(last_tweet_db_config.value) != last_user_tweet._json['id'] and not hasattr(last_user_tweet , 'retweeted_status'): ## check if my last tweet is retweet, if not the do your magic, else do nothing hastags = [hastag['text'] for hastag in last_user_tweet._json['entities']['hashtags']] for hastag in hastags[:5]: ## get only 5 hastags for tweet in tweepy.Cursor(api.search, q=f"#{hastag}").items(3): ## get only last tweet per hastag try: if reaction_type == 'like': api.create_favorite(tweet._json['id']) ## like tweet elif reaction_type == 'retweet': api.retweet(tweet._json['id']) ## retweet tweet elif reaction_type == 'all': api.create_favorite(tweet._json['id']) ## like tweet api.retweet(tweet._json['id']) ## retweet tweet except Exception as e: current_app.logger.info(e) last_tweet_db_config.value = last_user_tweet._json['id'] db.session.commit() return api_response({'status': 'ok', 'data': 'Reaction to hastags added !', 'error': ''})
def repopulate_post_platform(): api = create_api() current_user = api.me() for status in tweepy.Cursor(api.user_timeline, id=current_user._json['screen_name'], count=500, tweet_mode="extended").items(500): try: only_text = status.full_text[:status.full_text.index('\n#')] tw = PostModel.query.filter_by(body=only_text).first() platform = PlatformModel.query.get(1) if tw != None: try: post_platform = PostPlatformModel(error=0) post_platform.platform = platform post_platform.post = tw tw.platform.append(post_platform) db.session.add(tw) db.session.commit() except Exception as e: print(f'Exception on id {tw.id}: {e}') else: print(f'Not found {status.full_text}') except Exception as e2: print(f'Exception on {status.full_text}: {e2}') return api_response({'status': 'ok', 'data': 'ok', 'error': ''})
def page_not_found(error): return api_response({'error': 'No data found'}, 404)
def testmain(): return api_response({'status': 'App is working !'})
def server_error(error): return api_response({'error': 'Something went wrong'}, 500)