def update_item(event, context, is_test=False, session=None): """stores data related to item Parameters ---------- event: dict, required item Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ API Gateway Lambda Proxy Output Format: application/json Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html """ if session is None: session = get_db_session(is_test, session) # Parse event dict to Item object item = Item() json_event = event['item'] for key in json_event: setattr(item, key, json_event[key]) update_object(item, is_test, session)
def notify_users(is_test, session, item): """Notify user(s) about a closed item. Parameters ---------- is_test: boolean If this method is called from a test session: session The session item: Item The closed item """ if session == None: session = get_db_session(False, None) # TODO: This implementation is not ideal: 1.55 is rounded to 1.5. However, 1.56 is correctly rounded to 1.6. rating = round(item.result_score, 1) rating_text = "nicht vertrauenswürdig" if 2 <= rating < 3: rating_text = "eher nicht vertrauenswürdig" if 3 <= rating < 3.5: rating_text = "eher vertrauenswürdig" if rating >= 3.5: rating_text = "vertrauenswürdig" # get all submissions for the item submissions = submission_handler.get_submissions_by_item_id( item.id, is_test, session) notifications_successful = True for submission in submissions: if submission.telegram_id: try: notify_telegram_user(is_test, submission.telegram_id, item, rating, rating_text) submission.telegram_id = None except Exception: notifications_successful = False if submission.mail: if submission.status == 'confirmed': try: notify_mail_user(submission.mail, item, rating, rating_text) submission.mail = None except Exception: notifications_successful = False if notifications_successful: logger.info( "User(s) notified. Check logs to see if mail and/or telegram notifications were successful." ) update_object(submission, is_test, session) else: logger.exception( "An error occurred during closed item user notification. Please check logs." )
def give_experience_point(user_id, is_test, session): user = get_user_by_id(user_id, is_test, session) user.experience_points = user.experience_points + 1 new_level = session.query(Level) \ .filter(Level.required_experience_points <= user.experience_points) \ .order_by(Level.required_experience_points.desc()) \ .first() if new_level.id != user.level_id: user.level_id = new_level.id update_object(user, is_test, session)
def store_tag_for_item(item_id, str_tag, is_test, session): # search for tag in database tag = get_tag_by_content(str_tag, is_test, session) if tag is None: # store tag in database tag = Tag() tag.id = str(uuid4()) tag.tag = str_tag update_object(tag, is_test, session) # item tag already exists? itemtag = get_itemtag_by_tag_and_item_id(tag.id, item_id, is_test, session) if itemtag is None: # store item tag in database itemtag = ItemTag() itemtag.id = str(uuid4()) itemtag.item_id = item_id itemtag.tag_id = tag.id update_object(itemtag, is_test, session)
def close_review(review: Review, is_test, session) -> Review: review.status = "closed" review.finish_timestamp = helper.get_date_time_now(is_test) user_handler.give_experience_point(review.user_id, is_test, session) pair = review_pair_handler.get_review_pair_from_review( review, is_test, session) partner_review = get_partner_review(review, is_test, session) if partner_review != None and partner_review.status == 'closed': pair.is_good = True for answer in review.review_answers: partner_answer = review_answer_handler.get_partner_answer( partner_review, answer.review_question_id, is_test, session) if (answer.answer == None and partner_answer.answer != None) or ( answer.answer != None and partner_answer.answer == None): pair.is_good = False elif (answer.answer == 0 and partner_answer.answer != 0) or ( answer.answer != 0 and partner_answer.answer == 0): pair.is_good = False if pair.is_good: difference = review_pair_handler.compute_difference(pair) pair.variance = difference pair.is_good = True if difference <= 1 else False review.item.in_progress_reviews_level_1 -= 1 review.item.in_progress_reviews_level_2 -= 1 if pair.is_good: review.item.open_reviews -= 1 review.item.open_reviews_level_1 -= 1 review.item.open_reviews_level_2 -= 1 pairs = review_pair_handler.get_review_pairs_by_item( pair.item_id, is_test, session) if (len(list(filter(lambda p: p.is_good, pairs))) >= 4): review.item.status = "closed" review.item.close_timestamp = review.finish_timestamp review.item.result_score = item_handler.compute_item_result_score( review.item_id, is_test, session) update_object(review, is_test, session) update_object(pair, is_test, session) update_object(review.item, is_test, session) return review
def update_item(event, context, is_test=False, session=None): """Updates an item. Parameters ---------- event: dict, required API Gateway Lambda Proxy Input Format #api-gateway-simple-proxy-for-lambda-input-format Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ API Gateway Lambda Proxy Output Format: application/json Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html """ helper.log_method_initiated("Update item", event, logger) if session is None: session = get_db_session(is_test, session) item_id = event['pathParameters']['item_id'] item = item_handler.get_item_by_id(item_id, is_test, session) if item is None: response = { "statusCode": 404, "body": "No item found with the specified id." } response_cors = helper.set_cors(response, event, is_test) return response_cors body = event['body'] body = json.loads(body) if isinstance(body, str) else body for key in body: if hasattr(item, key): if not isinstance(body[key], dict) and not isinstance( body[key], list): setattr(item, key, body[key]) else: response = { "statusCode": 400, "body": "Could not update item. Provided input does not match item model." } response_cors = helper.set_cors(response, event, is_test) return response_cors item = update_object(item, is_test, session) if item is None: response = { "statusCode": 500, "body": "Could not write changes to db. Event id: {}".format( event['requestContext']['requestId']) } response_cors = helper.set_cors(response, event, is_test) return response_cors response = {"statusCode": 200, "body": json.dumps(item.to_dict())} response_cors = helper.set_cors(response, event, is_test) return response_cors
def store_factchecks(event, context, is_test=False, session=None): """stores data related to factchecks Parameters ---------- event: dict, required FactChecks item Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ """ if session is None: session = get_db_session(is_test, session) # Parse event dict to Item object for json_event in event['FactChecks']: if 'claimReview' not in json_event: # raise Exception('No claimReview found in factchecks!') return organization = FactChecking_Organization() factcheck = ExternalFactCheck() # What is the publishing organization? if 'publisher' not in json_event['claimReview'][0]: org_name = "Unknown" elif 'site' in json_event['claimReview'][0]['publisher']: org_name = json_event['claimReview'][0]['publisher']['site'] elif 'name' in json_event['claimReview'][0]['publisher']: org_name = json_event['claimReview'][0]['publisher']['name'] else: org_name = "Unknown" # Does the publishing organization already exist? try: organization = factchecking_organization_handler.get_organization_by_name( org_name, is_test, session) except Exception: # store organization in database organization.id = str(uuid4()) organization.name = org_name organization.counter_trustworthy = 0 organization.counter_not_trustworthy = 0 try: update_object(organization, is_test, session) except Exception as e: logger.error("Could not store Organization. Exception: %s", e, exc_info=True) factcheck_url = json_event['claimReview'][0]['url'] factcheck_title = json_event['claimReview'][0]['title'] item_id = event['item']['id'] try: # Does the factcheck already exist? factcheck = external_factcheck_handler.get_factcheck_by_url_and_item_id( factcheck_url, item_id, is_test, session) except Exception as e: # create new factcheck in database factcheck.id = str(uuid4()) # store factcheck in database factcheck.url = factcheck_url factcheck.title = factcheck_title factcheck.item_id = item_id factcheck.factchecking_organization_id = organization.id try: update_object(factcheck, is_test, session) except Exception as e: logger.error("Could not store factchecks. Exception: %s", e, exc_info=True) raise
def store_itemphrases(event, context, is_test=False, session=None): """stores key phrases of an item Parameters ---------- event: dict, required item KeyPhrases Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ API Gateway Lambda Proxy Output Format: application/json Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html """ if session is None: session = get_db_session(is_test, session) # Store all entities of the item for str_phrase in event['KeyPhrases']: phrase = Keyphrase() # search for entity in database try: phrase = keyphrase_handler.get_phrase_by_content( str_phrase, is_test, session) except Exception: # store phrase in database phrase.id = str(uuid4()) phrase.phrase = str_phrase try: update_object(phrase, is_test, session) except Exception as e: logger.error("Could not store key phrase. Exception: %s", e, exc_info=True) raise # store item keyphrase in database itemphrase = ItemKeyphrase() # item phrase already exists? item_id = event['item']['id'] try: itemphrase = keyphrase_handler.get_itemphrase_by_phrase_and_item_id( phrase.id, item_id, is_test, session) except Exception: itemphrase.id = str(uuid4()) itemphrase.item_id = item_id itemphrase.keyphrase_id = phrase.id try: update_object(itemphrase, is_test, session) except Exception as e: logger.error("Could not store item key phrase. Exception: %s", e, exc_info=True) raise
def store_itemurl(event, context, is_test=False, session=None): """stores urls referenced in item Parameters ---------- event: dict, required item Claim Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ API Gateway Lambda Proxy Output Format: application/json Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html """ if session is None: session = get_db_session(is_test, session) # Store all urls referenced in the item for str_url in event['Claim']['urls']: if str_url == "": continue # store claimant derived from url domain = urlparse(str_url).hostname claimant = Claimant() # claimant already exists? try: claimant = claimant_handler.get_claimant_by_name( domain, is_test, session) except Exception: # store claimant in database claimant.id = str(uuid4()) claimant.claimant = domain try: update_object(claimant, is_test, session) except Exception as e: logger.error("Could not store claimant. Exception: %s", e, exc_info=True) raise # search for url in database url = URL() try: url = url_handler.get_url_by_content(str_url, is_test, session) except Exception: # store url in database url.id = str(uuid4()) url.url = str_url url.claimant_id = claimant.id try: update_object(url, is_test, session) except Exception as e: logger.error("Could not store urls. Exception: %s", e, exc_info=True) raise itemurl = ItemURL() # itemurl already exists? item_id = event['item']['id'] try: itemurl = url_handler.get_itemurl_by_url_and_item_id( url.id, item_id, is_test, session) except Exception: # store itemurl in database itemurl.id = str(uuid4()) itemurl.item_id = item_id itemurl.url_id = url.id try: update_object(itemurl, is_test, session) except Exception as e: logger.error("Could not store itemurls. Exception: %s", e, exc_info=True) raise