Example #1
0
def voter_guide_possibility_retrieve_for_api(voter_device_id, voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    voter_guide_possibility_url = voter_guide_possibility_url  # TODO Use scrapy here
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # TODO We will need the voter_id here so we can control volunteer actions

    voter_guide_possibility_manager = VoterGuidePossibilityManager()
    results = voter_guide_possibility_manager.retrieve_voter_guide_possibility_from_url(voter_guide_possibility_url)

    json_data = {
        'voter_device_id':              voter_device_id,
        'voter_guide_possibility_url':  results['voter_guide_possibility_url'],
        'voter_guide_possibility_id':   results['voter_guide_possibility_id'],
        'organization_we_vote_id':      results['organization_we_vote_id'],
        'public_figure_we_vote_id':     results['public_figure_we_vote_id'],
        'owner_we_vote_id':             results['owner_we_vote_id'],
        'status':                       results['status'],
        'success':                      results['success'],
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #2
0
def voter_guide_possibility_retrieve_for_api(voter_device_id,
                                             voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    voter_guide_possibility_url = voter_guide_possibility_url  # TODO Use scrapy here
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    # TODO We will need the voter_id here so we can control volunteer actions

    voter_guide_possibility_manager = VoterGuidePossibilityManager()
    results = voter_guide_possibility_manager.retrieve_voter_guide_possibility_from_url(
        voter_guide_possibility_url)

    json_data = {
        'voter_device_id': voter_device_id,
        'voter_guide_possibility_url': results['voter_guide_possibility_url'],
        'voter_guide_possibility_id': results['voter_guide_possibility_id'],
        'organization_we_vote_id': results['organization_we_vote_id'],
        'public_figure_we_vote_id': results['public_figure_we_vote_id'],
        'owner_we_vote_id': results['owner_we_vote_id'],
        'status': results['status'],
        'success': results['success'],
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_position_like_off_save_for_api(voter_device_id, position_like_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_like_manager = PositionLikeManager()
    if positive_value_exists(position_like_id) or \
            (positive_value_exists(voter_id) and positive_value_exists(position_entered_id)):
        results = position_like_manager.toggle_off_voter_position_like(
            position_like_id, voter_id, position_entered_id)
        status = results['status']
        success = results['success']
    else:
        status = 'UNABLE_TO_DELETE_POSITION_LIKE-INSUFFICIENT_VARIABLES'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #4
0
def voter_photo_save_for_api(voter_device_id, facebook_profile_image_url_https, facebook_photo_variable_exists):
    facebook_profile_image_url_https = facebook_profile_image_url_https.strip()

    device_id_results = is_voter_device_id_valid(voter_device_id)
    if not device_id_results['success']:
        results = {
                'status': device_id_results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
                'facebook_profile_image_url_https': facebook_profile_image_url_https,
            }
        return results

    if not facebook_photo_variable_exists:
        results = {
                'status': "MISSING_VARIABLE-AT_LEAST_ONE_PHOTO",
                'success': False,
                'voter_device_id': voter_device_id,
                'facebook_profile_image_url_https': facebook_profile_image_url_https,
            }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id < 0:
        results = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
            'facebook_profile_image_url_https': facebook_profile_image_url_https,
        }
        return results

    # At this point, we have a valid voter

    voter_manager = VoterManager()
    results = voter_manager.update_voter_photos(voter_id,
                                                facebook_profile_image_url_https, facebook_photo_variable_exists)

    if results['success']:
        if positive_value_exists(facebook_profile_image_url_https):
            status = "VOTER_FACEBOOK_PHOTO_SAVED"
        else:
            status = "VOTER_PHOTOS_EMPTY_SAVED"

        results = {
                'status': status,
                'success': True,
                'voter_device_id': voter_device_id,
                'facebook_profile_image_url_https': facebook_profile_image_url_https,
            }

    else:
        results = {
                'status': results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
                'facebook_profile_image_url_https': facebook_profile_image_url_https,
            }
    return results
Example #5
0
def voter_address_save_for_api(voter_device_id, address_raw_text, address_variable_exists):
    device_id_results = is_voter_device_id_valid(voter_device_id)
    if not device_id_results['success']:
        results = {
                'status': device_id_results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
            }
        return results

    if not address_variable_exists:
        results = {
                'status': "MISSING_POST_VARIABLE-ADDRESS",
                'success': False,
                'voter_device_id': voter_device_id,
            }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return results

    # At this point, we have a valid voter

    voter_address_manager = VoterAddressManager()
    address_type = BALLOT_ADDRESS

    # We wrap get_or_create because we want to centralize error handling
    results = voter_address_manager.update_or_create_voter_address(voter_id, address_type, address_raw_text.strip())

    if results['success']:
        if positive_value_exists(address_raw_text):
            status = "VOTER_ADDRESS_SAVED"
        else:
            status = "VOTER_ADDRESS_EMPTY_SAVED"

        results = {
                'status': status,
                'success': True,
                'voter_device_id': voter_device_id,
                'text_for_map_search': address_raw_text,
            }

    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
        # delete all currently matching addresses and save again
    else:
        results = {
                'status': results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
            }
    return results
Example #6
0
def voter_guide_possibility_save_for_api(voter_device_id,
                                         voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    if not voter_guide_possibility_url:
        json_data = {
            'status': "MISSING_POST_VARIABLE-URL",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    # At this point, we have a valid voter

    voter_guide_possibility_manager = VoterGuidePossibilityManager()

    # We wrap get_or_create because we want to centralize error handling
    results = voter_guide_possibility_manager.update_or_create_voter_guide_possibility(
        voter_guide_possibility_url.strip())
    if results['success']:
        json_data = {
            'status': "VOTER_GUIDE_POSSIBILITY_SAVED",
            'success': True,
            'voter_device_id': voter_device_id,
            'voter_guide_possibility_url': voter_guide_possibility_url,
        }

    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
    # delete all currently matching addresses and save again?
    else:
        json_data = {
            'status': results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
        }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #7
0
def voter_create(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = 0
    # Make sure a voter record hasn't already been created for this
    existing_voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if existing_voter_id:
        json_data = {
            'status': "VOTER_ALREADY_EXISTS",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # Create a new voter and return the id
    voter_manager = VoterManager()
    results = voter_manager.create_voter()

    if results['voter_created']:
        voter = results['voter']

        # Now save the voter_device_link
        voter_device_link_manager = VoterDeviceLinkManager()
        results = voter_device_link_manager.save_new_voter_device_link(voter_device_id, voter.id)

        if results['voter_device_link_created']:
            voter_device_link = results['voter_device_link']
            voter_id_found = True if voter_device_link.voter_id > 0 else False

            if voter_id_found:
                voter_id = voter_device_link.voter_id

    if voter_id:
        json_data = {
            'status': "VOTER_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_id': voter_id,  # We may want to remove this after initial testing
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_NOT_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_position_like_status_retrieve_for_api(voter_device_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':               'VALID_VOTER_DEVICE_ID_MISSING',
            'success':              False,
            'voter_device_id':      voter_device_id,
            'is_liked':             False,
            'position_entered_id':  position_entered_id,
            'position_like_id':     0,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':               "VALID_VOTER_ID_MISSING",
            'success':              False,
            'voter_device_id':      voter_device_id,
            'is_liked':             False,
            'position_entered_id':  position_entered_id,
            'position_like_id':     0,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_like_manager = PositionLikeManager()
    if positive_value_exists(position_entered_id):
        position_like_id = 0
        results = position_like_manager.retrieve_position_like(position_like_id, voter_id, position_entered_id)
        status = results['status']
        success = results['success']
        is_liked = results['is_liked']
        position_like_id = results['position_like_id']
    else:
        status = 'UNABLE_TO_RETRIEVE-POSITION_ENTERED_ID_MISSING'
        success = False
        is_liked = False
        position_like_id = 0

    json_data = {
        'status':               status,
        'success':              success,
        'voter_device_id':      voter_device_id,
        'is_liked':             is_liked,
        'position_entered_id':  position_entered_id,
        'position_like_id':     position_like_id,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #9
0
def positions_count_for_api(voter_device_id, candidate_id,
                            candidate_we_vote_id, measure_id,
                            measure_we_vote_id, stance_we_are_looking_for):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING ",
            'success': False,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    show_positions_this_voter_follows = True
    if positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        results = positions_count_for_candidate_campaign(
            voter_id, candidate_id, candidate_we_vote_id,
            stance_we_are_looking_for, show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(
            measure_we_vote_id):
        results = positions_count_for_contest_measure(
            voter_id, measure_id, measure_we_vote_id,
            stance_we_are_looking_for, show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        status = 'UNABLE_TO_RETRIEVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #10
0
def facebook_disconnect_for_api(voter_device_id):  # facebookDisconnect
    """

    :param voter_device_id:
    :return:
    """
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'success': False,
            'status': "VALID_VOTER_MISSING",
            'voter_device_id': voter_device_id,
        }
        return results

    voter = results['voter']

    facebook_id = 0
    results = voter_manager.save_facebook_user_values(voter, facebook_id)
    status = results['status']
    success = results['success']

    if success:
        results = {
            'success': True,
            'status': status,
            'voter_device_id': voter_device_id,
        }
    else:
        results = {
            'success': False,
            'status': status,
            'voter_device_id': voter_device_id,
        }
    return results
Example #11
0
def facebook_disconnect_for_api(voter_device_id):  # facebookDisconnect
    """

    :param voter_device_id:
    :return:
    """
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'success': False,
            'status': "VALID_VOTER_MISSING",
            'voter_device_id': voter_device_id,
        }
        return results

    voter = results['voter']

    facebook_id = 0
    results = voter_manager.save_facebook_user_values(voter, facebook_id)
    status = results['status']
    success = results['success']

    if success:
        results = {
            'success': True,
            'status': status,
            'voter_device_id': voter_device_id,
        }
    else:
        results = {
            'success': False,
            'status': status,
            'voter_device_id': voter_device_id,
        }
    return results
Example #12
0
def voter_address_retrieve_for_api(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # ##################
    # Temp code to test authentication
    # user = PasswordlessAuthBackend.authenticate(username=user.username)
    # login(request, user)
    # ##################

    voter_address_manager = VoterAddressManager()
    results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)

    if results['voter_address_found']:
        voter_address = results['voter_address']
        json_data = {
            'voter_device_id': voter_device_id,
            'address_type': voter_address.address_type if voter_address.address_type else '',
            'text_for_map_search': voter_address.text_for_map_search if voter_address.text_for_map_search else '',
            'latitude': voter_address.latitude if voter_address.latitude else '',
            'longitude': voter_address.longitude if voter_address.longitude else '',
            'normalized_line1': voter_address.normalized_line1 if voter_address.normalized_line1 else '',
            'normalized_line2': voter_address.normalized_line2 if voter_address.normalized_line2 else '',
            'normalized_city': voter_address.normalized_city if voter_address.normalized_city else '',
            'normalized_state': voter_address.normalized_state if voter_address.normalized_state else '',
            'normalized_zip': voter_address.normalized_zip if voter_address.normalized_zip else '',
            'success': True,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_ADDRESS_NOT_RETRIEVED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #13
0
def voter_guide_possibility_save_for_api(voter_device_id, voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    if not voter_guide_possibility_url:
        json_data = {
                'status': "MISSING_POST_VARIABLE-URL",
                'success': False,
                'voter_device_id': voter_device_id,
            }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # At this point, we have a valid voter

    voter_guide_possibility_manager = VoterGuidePossibilityManager()

    # We wrap get_or_create because we want to centralize error handling
    results = voter_guide_possibility_manager.update_or_create_voter_guide_possibility(
        voter_guide_possibility_url.strip())
    if results['success']:
        json_data = {
                'status': "VOTER_GUIDE_POSSIBILITY_SAVED",
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guide_possibility_url': voter_guide_possibility_url,
            }

    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
        # delete all currently matching addresses and save again?
    else:
        json_data = {
                'status': results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
            }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #14
0
def voter_retrieve_list_for_api(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results["success"]:
        results2 = {"success": False, "json_data": results["json_data"]}
        return results2

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id > 0:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        if results["voter_found"]:
            voter_id = results["voter_id"]
    else:
        # If we are here, the voter_id could not be found from the voter_device_id
        json_data = {"status": "VOTER_NOT_FOUND_FROM_DEVICE_ID", "success": False, "voter_device_id": voter_device_id}
        results = {"success": False, "json_data": json_data}
        return results

    if voter_id:
        voter_list = Voter.objects.all()
        voter_list = voter_list.filter(id=voter_id)

        if len(voter_list):
            results = {"success": True, "voter_list": voter_list}
            return results

    # Trying to mimic the Google Civic error codes scheme
    errors_list = [
        {
            "domain": "TODO global",
            "reason": "TODO reason",
            "message": "TODO Error message here",
            "locationType": "TODO Error message here",
            "location": "TODO location",
        }
    ]
    error_package = {"errors": errors_list, "code": 400, "message": "Error message here"}
    json_data = {
        "error": error_package,
        "status": "VOTER_ID_COULD_NOT_BE_RETRIEVED",
        "success": False,
        "voter_device_id": voter_device_id,
    }
    results = {"success": False, "json_data": json_data}
    return results
Example #15
0
def positions_count_for_api(voter_device_id,
                            candidate_id, candidate_we_vote_id,
                            measure_id, measure_we_vote_id,
                            stance_we_are_looking_for):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING ",
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    show_positions_this_voter_follows = True
    if positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        results = positions_count_for_candidate_campaign(voter_id,
                                                         candidate_id, candidate_we_vote_id,
                                                         stance_we_are_looking_for,
                                                         show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(measure_we_vote_id):
        results = positions_count_for_contest_measure(voter_id,
                                                      measure_id, measure_we_vote_id,
                                                      stance_we_are_looking_for,
                                                      show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        status = 'UNABLE_TO_RETRIEVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #16
0
def voter_all_stars_status_retrieve_for_api(voter_device_id):
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'success': False,
            'star_list': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'star_list': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    star_item_list = StarItemList()
    results = star_item_list.retrieve_star_item_list_for_voter(voter_id)
    status = results['status']
    success = results['success']

    star_list = []
    if success:
        star_item_list = results['star_item_list']
        for star_item in star_item_list:
            # Create a list of star information needed by API
            one_star = {
                'ballot_item_we_vote_id': star_item.ballot_item_we_vote_id(),
                'star_on': star_item.is_starred(),
            }
            star_list.append(one_star)

    json_data = {
        'status': status,
        'success': success,
        'star_list': star_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #17
0
def voter_all_stars_status_retrieve_for_api(voter_device_id):
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':       "VALID_VOTER_DEVICE_ID_MISSING",
            'success':      False,
            'star_list':    [],
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':       "VALID_VOTER_ID_MISSING",
            'success':      False,
            'star_list':    [],
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    star_item_list = StarItemList()
    results = star_item_list.retrieve_star_item_list_for_voter(voter_id)
    status = results['status']
    success = results['success']

    star_list = []
    if success:
        star_item_list = results['star_item_list']
        for star_item in star_item_list:
            # Create a list of star information needed by API
            one_star = {
                'ballot_item_we_vote_id':   star_item.ballot_item_we_vote_id(),
                'star_on':                  star_item.is_starred(),
            }
            star_list.append(one_star)

    json_data = {
        'status':       status,
        'success':      success,
        'star_list':    star_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #18
0
def voter_star_on_save_for_api(voter_device_id, office_id, candidate_id, measure_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    star_item_manager = StarItemManager()
    if positive_value_exists(office_id):
        results = star_item_manager.toggle_on_voter_starred_office(voter_id, office_id)
        status = "STAR_ON_OFFICE " + results['status']
        success = results['success']
    elif positive_value_exists(candidate_id):
        results = star_item_manager.toggle_on_voter_starred_candidate(voter_id, candidate_id)
        status = "STAR_ON_CANDIDATE " + results['status']
        success = results['success']
    elif positive_value_exists(measure_id):
        results = star_item_manager.toggle_on_voter_starred_measure(voter_id, measure_id)
        status = "STAR_ON_MEASURE " + results['status']
        success = results['success']
    else:
        status = 'UNABLE_TO_SAVE_ON-OFFICE_ID_AND_CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #19
0
def voter_opposing_save(voter_device_id, candidate_id, measure_id):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_entered_manager = PositionEnteredManager()
    if positive_value_exists(candidate_id):
        results = position_entered_manager.toggle_on_voter_oppose_for_candidate_campaign(voter_id, candidate_id)
        # toggle_off_voter_support_for_candidate_campaign
        status = "OPPOSING_CANDIDATE " + results['status']
        success = results['success']
    elif positive_value_exists(measure_id):
        results = position_entered_manager.toggle_on_voter_oppose_for_contest_measure(voter_id, measure_id)
        status = "OPPOSING_MEASURE " + results['status']
        success = results['success']
    else:
        status = 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #20
0
def voter_ballot_items_retrieve_from_google_civic_for_api(
        voter_device_id, text_for_map_search='', use_test_election=False):
    """
    We are telling the server to explicitly reach out to the Google Civic API and retrieve the ballot items
    for this voter.
    """
    # Confirm that we have a Google Civic API Key (GOOGLE_CIVIC_API_KEY)
    if not positive_value_exists(GOOGLE_CIVIC_API_KEY):
        results = {
            'status': 'NO_GOOGLE_CIVIC_API_KEY',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Confirm that we have the URL where we retrieve voter ballots (VOTER_INFO_URL)
    if not positive_value_exists(VOTER_INFO_URL):
        results = {
            'status':
            'MISSING VOTER_INFO_URL in config/environment_variables.json',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    google_civic_election_id = 0
    status = ''
    success = False
    election_date_text = ''
    election_description_text = ''
    election_data_retrieved = False
    polling_location_retrieved = False
    contests_retrieved = False
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(
            voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(
            text_for_map_search, google_civic_election_id, use_test_election)

        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']
            election_date_text = one_ballot_json['election']['electionDay']
            election_description_text = one_ballot_json['election']['name']

            # We may receive some election data, but not all of the data we need
            if one_ballot_results['election_data_retrieved']:
                election_data_retrieved = True
                success = True

            if one_ballot_results['polling_location_retrieved']:
                polling_location_retrieved = True
                success = True

            if one_ballot_results['contests_retrieved']:
                contests_retrieved = True

                # Now that we know we have new ballot data, we need to delete prior ballot data for this election
                # because when we change voterAddress, we usually get different ballot items
                ballot_item_list_manager = BallotItemListManager()
                # We include a google_civic_election_id, so only the ballot info for this election is removed
                google_civic_election_id_to_delete = one_ballot_json[
                    'election']['id']  # '0' would mean "delete all"
                if positive_value_exists(google_civic_election_id_to_delete):
                    ballot_item_list_manager.delete_all_ballot_items_for_voter(
                        voter_id, google_civic_election_id_to_delete)

                # store_on_ballot... adds an entry to the BallotReturned table
                # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api
                store_one_ballot_results = store_one_ballot_from_google_civic_api(
                    one_ballot_json, voter_id)
                if store_one_ballot_results['success']:
                    status += 'RETRIEVED_FROM_GOOGLE_CIVIC_AND_STORED_BALLOT_FOR_VOTER '
                    success = True
                    google_civic_election_id = store_one_ballot_results[
                        'google_civic_election_id']
                else:
                    status += 'UNABLE_TO-store_one_ballot_from_google_civic_api'
        elif 'error' in one_ballot_results['structured_json']:
            if one_ballot_results['structured_json']['error'][
                    'message'] == 'Election unknown':
                success = False  # It is only successful if new ballot data is retrieved.
            else:
                success = False
            status += "GOOGLE_CIVIC_API_ERROR: " + one_ballot_results[
                'structured_json']['error']['message']

        else:
            status += 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status += 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    # If a google_civic_election_id was not returned, outside of this function we search again using a test election,
    # so that during our initial user testing, ballot data is returned in areas where elections don't currently exist

    results = {
        'success': success,
        'status': status,
        'voter_device_id': voter_device_id,
        'google_civic_election_id': google_civic_election_id,
        'text_for_map_search': text_for_map_search,
        'election_date_text': election_date_text,
        'election_description_text': election_description_text,
        'election_data_retrieved': election_data_retrieved,
        'polling_location_retrieved': polling_location_retrieved,
        'contests_retrieved': contests_retrieved,
    }
    return results
Example #21
0
def twitter_sign_in_start_for_api(voter_device_id,
                                  return_url):  # twitterSignInStart
    """

    :param voter_device_id:
    :param return_url: Where to direct the browser at the very end of the process
    :return:
    """
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': '',
            'voter_info_retrieved': False,
            'switch_accounts': False,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status': "VALID_VOTER_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': '',
            'voter_info_retrieved': False,
            'switch_accounts': False,
        }
        return results

    voter = results['voter']

    if voter.twitter_access_token and voter.twitter_access_secret:
        # If here the voter might already be signed in, so we don't want to ask them to approve again
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY,
                                   TWITTER_CONSUMER_SECRET)
        auth.set_access_token(voter.twitter_access_token,
                              voter.twitter_access_secret)

        api = tweepy.API(auth)

        try:
            tweepy_user_object = api.me()
            success = True
        # What is the error situation where the twitter_access_token and twitter_access_secret are no longer valid?
        # We need to deal with this (wipe them from the database and rewind to the right place in the process
        except tweepy.RateLimitError:
            success = False
            status = 'TWITTER_RATE_LIMIT_ERROR'
        except tweepy.error.TweepError as error_instance:
            success = False
            status = ''
            error_tuple = error_instance.args
            for error_dict in error_tuple:
                for one_error in error_dict:
                    status += '[' + one_error['message'] + '] '

        if success:
            # Reach out to the twitterSignInRequestVoterInfo -- no need to redirect
            empty_return_url = ""
            voter_info_results = twitter_sign_in_request_voter_info_for_api(
                voter_device_id, empty_return_url)

            success = voter_info_results['success']
            status = "SKIPPED_AUTH_DIRECT_REQUEST_VOTER_INFO: " + voter_info_results[
                'status']
            results = {
                'status': status,
                'success': success,
                'voter_device_id': voter_device_id,
                'twitter_redirect_url': '',
                'voter_info_retrieved':
                voter_info_results['voter_info_retrieved'],
                'switch_accounts': voter_info_results[
                    'switch_accounts'],  # If true, new voter_device_id returned
            }
            return results
        else:
            # Somehow reset tokens and start over.
            pass

    callback_url = WE_VOTE_SERVER_ROOT_URL + "/apis/v1/twitterSignInRequestAccessToken/"
    callback_url += "?voter_device_id=" + voter_device_id
    callback_url += "&return_url=" + return_url

    # This is where
    twitter_authorization_url = ''

    try:
        # We take the Consumer Key and the Consumer Secret, and request a token & token_secret
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY,
                                   TWITTER_CONSUMER_SECRET, callback_url)
        twitter_authorization_url = auth.get_authorization_url()
        request_token_dict = auth.request_token
        twitter_request_token = ''
        twitter_request_token_secret = ''

        if 'oauth_token' in request_token_dict:
            twitter_request_token = request_token_dict['oauth_token']
        if 'oauth_token_secret' in request_token_dict:
            twitter_request_token_secret = request_token_dict[
                'oauth_token_secret']

        # We save these values in the Voter table, and then return a twitter_authorization_url where the voter signs in
        # Once they sign in to the Twitter login, they are redirected back to the We Vote callback_url
        # On that callback_url page, we are told if they are signed in
        #  on Twitter or not, and capture an access key we can use to retrieve information about the Twitter user
        # NOTE: Regarding the callback url, I think this can just be a direct call to the API server,
        #  since we have the voter_device_id
        if positive_value_exists(
                twitter_request_token) and positive_value_exists(
                    twitter_request_token_secret):
            voter.twitter_request_token = twitter_request_token
            voter.twitter_request_secret = twitter_request_token_secret
            voter.save()

            success = True
            status = "TWITTER_REDIRECT_URL_RETRIEVED"
        else:
            success = False
            status = "TWITTER_REDIRECT_URL_NOT_RETRIEVED"

    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_START: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            for one_error in error_dict:
                status += '[' + one_error['message'] + '] '

    if success:
        results = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': twitter_authorization_url,
            'voter_info_retrieved': False,
            'switch_accounts': False,
        }
    else:
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': '',
            'voter_info_retrieved': False,
            'switch_accounts': False,
        }
    return results
Example #22
0
def quick_info_text_save_for_api(  # TODO to be converted
        voter_device_id, quick_info_id, quick_info_we_vote_id,
        google_civic_election_id,
        office_we_vote_id,
        candidate_we_vote_id,
        measure_we_vote_id,
        statement_text,
        statement_html
        ):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data_from_results = results['json_data']
        json_data = {
            'status':                   json_data_from_results['status'],
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'quick_info_id':              quick_info_id,
            'quick_info_we_vote_id':      quick_info_we_vote_id,
            'new_quick_info_created':     False,
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id':        office_we_vote_id,
            'candidate_we_vote_id':     candidate_we_vote_id,
            'measure_we_vote_id':       measure_we_vote_id,
            'statement_text':           statement_text,
            'statement_html':           statement_html,
            'last_updated':             '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_manager = VoterManager()
    voter_results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
    voter_id = voter_results['voter_id']
    if not positive_value_exists(voter_id):
        json_data = {
            'status':                   "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'quick_info_id':              quick_info_id,
            'quick_info_we_vote_id':      quick_info_we_vote_id,
            'new_quick_info_created':     False,
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id':        office_we_vote_id,
            'candidate_we_vote_id':     candidate_we_vote_id,
            'measure_we_vote_id':       measure_we_vote_id,
            'statement_text':           statement_text,
            'statement_html':           statement_html,
            'last_updated':             '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter = voter_results['voter']
    quick_info_id = convert_to_int(quick_info_id)
    quick_info_we_vote_id = quick_info_we_vote_id.strip().lower()

    existing_unique_identifier_found = positive_value_exists(quick_info_id) \
        or positive_value_exists(quick_info_we_vote_id)
    new_unique_identifier_found = positive_value_exists(voter_id) \
        and positive_value_exists(google_civic_election_id) and (
        positive_value_exists(office_we_vote_id) or
        positive_value_exists(candidate_we_vote_id) or
        positive_value_exists(measure_we_vote_id)
    )
    unique_identifier_found = existing_unique_identifier_found or new_unique_identifier_found
    # We must have these variables in order to create a new entry
    required_variables_for_new_entry = positive_value_exists(voter_id) \
        and positive_value_exists(google_civic_election_id) and (
        positive_value_exists(office_we_vote_id) or
        positive_value_exists(candidate_we_vote_id) or
        positive_value_exists(measure_we_vote_id)
    )
    if not unique_identifier_found:
        results = {
            'status':                   "QUICK_INFO_REQUIRED_UNIQUE_IDENTIFIER_VARIABLES_MISSING",
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'quick_info_id':              quick_info_id,
            'quick_info_we_vote_id':      quick_info_we_vote_id,
            'new_quick_info_created':     False,
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id':        office_we_vote_id,
            'candidate_we_vote_id':     candidate_we_vote_id,
            'measure_we_vote_id':       measure_we_vote_id,
            'statement_text':           statement_text,
            'statement_html':           statement_html,
            'last_updated':             '',
        }
        return results
    elif not existing_unique_identifier_found and not required_variables_for_new_entry:
        results = {
            'status':                   "NEW_QUICK_INFO_REQUIRED_VARIABLES_MISSING",
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'quick_info_id':              quick_info_id,
            'quick_info_we_vote_id':      quick_info_we_vote_id,
            'new_quick_info_created':     False,
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id':        office_we_vote_id,
            'candidate_we_vote_id':     candidate_we_vote_id,
            'measure_we_vote_id':       measure_we_vote_id,
            'statement_text':           statement_text,
            'statement_html':           statement_html,
            'last_updated':             '',
        }
        return results

    quick_info_manager = QuickInfoManager()
    save_results = quick_info_manager.update_or_create_quick_info(
        quick_info_id=quick_info_id,
        quick_info_we_vote_id=quick_info_we_vote_id,
        voter_we_vote_id=voter.we_vote_id,
        google_civic_election_id=google_civic_election_id,
        office_we_vote_id=office_we_vote_id,
        candidate_we_vote_id=candidate_we_vote_id,
        measure_we_vote_id=measure_we_vote_id,
        statement_text=statement_text,
        statement_html=statement_html,
    )

    if save_results['success']:
        quick_info = save_results['quick_info']
        results = {
            'success':                  save_results['success'],
            'status':                   save_results['status'],
            'voter_device_id':          voter_device_id,
            'quick_info_id':              quick_info.id,
            'quick_info_we_vote_id':      quick_info.we_vote_id,
            'new_quick_info_created':     save_results['new_quick_info_created'],
            'is_support':               quick_info.is_support(),
            'is_oppose':                quick_info.is_oppose(),
            'is_information_only':      quick_info.is_information_only(),
            'google_civic_election_id': quick_info.google_civic_election_id,
            'office_we_vote_id':        quick_info.contest_office_we_vote_id,
            'candidate_we_vote_id':     quick_info.candidate_campaign_we_vote_id,
            'measure_we_vote_id':       quick_info.contest_measure_we_vote_id,
            'statement_text':           quick_info.statement_text,
            'statement_html':           quick_info.statement_html,
            'last_updated':             '',
        }
        return results
    else:
        results = {
            'success':                  False,
            'status':                   save_results['status'],
            'voter_device_id':          voter_device_id,
            'quick_info_id':              quick_info_id,
            'quick_info_we_vote_id':      quick_info_we_vote_id,
            'new_quick_info_created':     False,
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id':        office_we_vote_id,
            'candidate_we_vote_id':     candidate_we_vote_id,
            'measure_we_vote_id':       measure_we_vote_id,
            'statement_text':           statement_text,
            'statement_html':           statement_html,
            'last_updated':             '',
        }
        return results
Example #23
0
def position_list_for_ballot_item_for_api(voter_device_id, office_id, candidate_id, measure_id,
                                          stance_we_are_looking_for=ANY_STANCE,
                                          show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the position identifiers from orgs, friends and public figures the voter follows
    This list of information is used to retrieve the detailed information
    """
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        position_list = []
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        position_list = []
        json_data = {
            'status': "VALID_VOTER_ID_MISSING ",
            'success': False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_list_manager = PositionListManager()
    if positive_value_exists(candidate_id):
        candidate_we_vote_id = ''
        all_positions_list = position_list_manager.retrieve_all_positions_for_candidate_campaign(
                candidate_id, candidate_we_vote_id, stance_we_are_looking_for)
        kind_of_ballot_item = CANDIDATE
        ballot_item_id = candidate_id
    elif positive_value_exists(measure_id):
        measure_we_vote_id = ''
        all_positions_list = position_list_manager.retrieve_all_positions_for_contest_measure(
                measure_id, measure_we_vote_id, stance_we_are_looking_for)
        kind_of_ballot_item = MEASURE
        ballot_item_id = measure_id
    elif positive_value_exists(office_id):
        office_we_vote_id = ''
        all_positions_list = position_list_manager.retrieve_all_positions_for_contest_office(
                office_id, office_we_vote_id, stance_we_are_looking_for)
        kind_of_ballot_item = OFFICE
        ballot_item_id = measure_id
    else:
        position_list = []
        json_data = {
            'status':           'POSITION_LIST_RETRIEVE_MISSING_BALLOT_ITEM_ID',
            'success':          False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    follow_organization_list_manager = FollowOrganizationList()
    organizations_followed_by_voter = \
        follow_organization_list_manager.retrieve_follow_organization_by_voter_id_simple_id_array(voter_id)

    if show_positions_this_voter_follows:
        position_objects = position_list_manager.calculate_positions_followed_by_voter(
            voter_id, all_positions_list, organizations_followed_by_voter)
        positions_count = len(position_objects)
        status = 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_FOLLOWED'
        success = True
    else:
        position_objects = position_list_manager.calculate_positions_not_followed_by_voter(
            all_positions_list, organizations_followed_by_voter)
        positions_count = len(position_objects)
        status = 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_NOT_FOLLOWED'
        success = True

    position_list = []
    for one_position in position_objects:
        # Whose position is it?
        if positive_value_exists(one_position.organization_we_vote_id):
            speaker_type = ORGANIZATION
            speaker_id = one_position.organization_id
            speaker_we_vote_id = one_position.organization_we_vote_id
            one_position_success = True
        elif positive_value_exists(one_position.voter_id):
            speaker_type = VOTER
            speaker_id = one_position.voter_id
            speaker_we_vote_id = one_position.voter_we_vote_id
            one_position_success = True
        elif positive_value_exists(one_position.public_figure_we_vote_id):
            speaker_type = PUBLIC_FIGURE
            speaker_id = one_position.public_figure_id
            speaker_we_vote_id = one_position.public_figure_we_vote_id
            one_position_success = True
        else:
            speaker_type = UNKNOWN_VOTER_GUIDE
            speaker_id = None
            speaker_we_vote_id = None
            one_position_success = False

        if one_position_success:
            one_position_dict_for_api = {
                'position_id':          one_position.id,
                'position_we_vote_id':  one_position.we_vote_id,
                'speaker_label':        'Organization Name TEMP',  # TODO DALE Add this to PositionEntered
                'speaker_type':         speaker_type,
                'speaker_id':           speaker_id,
                'speaker_we_vote_id':   speaker_we_vote_id,
                'is_support':           one_position.is_support(),
                'is_oppose':            one_position.is_oppose(),
            }
            position_list.append(one_position_dict_for_api)

    json_data = {
        'status':           status,
        'success':          success,
        'count':            positions_count,
        'kind_of_ballot_item': kind_of_ballot_item,
        'ballot_item_id':   ballot_item_id,
        'position_list':    position_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #24
0
def voter_retrieve_for_api(voter_device_id):  # voterRetrieve
    """
    Used by the api
    :param voter_device_id:
    :return:
    """
    voter_manager = VoterManager()
    voter_id = 0
    voter_created = False

    if positive_value_exists(voter_device_id):
        # If a voter_device_id is passed in that isn't valid, we want to throw an error
        device_id_results = is_voter_device_id_valid(voter_device_id)
        if not device_id_results['success']:
            json_data = {
                    'status':           device_id_results['status'],
                    'success':          False,
                    'voter_device_id':  voter_device_id,
                    'voter_created':    False,
                    'voter_found':      False,
                }
            return json_data

        voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
        if not positive_value_exists(voter_id):
            json_data = {
                'status':           "VOTER_NOT_FOUND_FROM_DEVICE_ID",
                'success':          False,
                'voter_device_id':  voter_device_id,
                'voter_created':    False,
                'voter_found':      False,
            }
            return json_data
    else:
        # If a voter_device_id isn't passed in, automatically create a new voter_device_id and voter
        voter_device_id = generate_voter_device_id()

        # We make sure a voter record hasn't already been created for this new voter_device_id, so we don't create a
        # security hole by giving a new person access to an existing account. This should never happen because it is
        # so unlikely that we will ever generate an existing voter_device_id with generate_voter_device_id.
        existing_voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
        if existing_voter_id:
            json_data = {
                'status':           "VOTER_ALREADY_EXISTS_BUT_ACCESS_RESTRICTED",
                'success':          False,
                'voter_device_id':  voter_device_id,
                'voter_created':    False,
                'voter_found':      False,
            }
            return json_data

        results = voter_manager.create_voter()

        if results['voter_created']:
            voter = results['voter']

            # Now save the voter_device_link
            voter_device_link_manager = VoterDeviceLinkManager()
            results = voter_device_link_manager.save_new_voter_device_link(voter_device_id, voter.id)

            if results['voter_device_link_created']:
                voter_device_link = results['voter_device_link']
                voter_id_found = True if voter_device_link.voter_id > 0 else False

                if voter_id_found:
                    voter_id = voter_device_link.voter_id
                    voter_created = True

        if not positive_value_exists(voter_id):
            json_data = {
                'status':           "VOTER_NOT_FOUND_AFTER_BEING_CREATED",
                'success':          False,
                'voter_device_id':  voter_device_id,
                'voter_created':    False,
                'voter_found':      False,
            }
            return json_data

    # At this point, we should have a valid voter_id
    results = voter_manager.retrieve_voter_by_id(voter_id)
    if results['voter_found']:
        voter = results['voter']

        if voter_created:
            status = 'VOTER_CREATED'
        else:
            status = 'VOTER_FOUND'
        json_data = {
            'status':                           status,
            'success':                          True,
            'voter_device_id':                  voter_device_id,
            'voter_created':                    voter_created,
            'voter_found':                      True,
            'we_vote_id':                       voter.we_vote_id,
            'facebook_id':                      voter.facebook_id,
            'email':                            voter.email,
            'facebook_email':                   voter.facebook_email,
            'facebook_profile_image_url_https': voter.facebook_profile_image_url_https,
            'full_name':                        voter.get_full_name(),
            'first_name':                       voter.first_name,
            'last_name':                        voter.last_name,
            'twitter_screen_name':              voter.twitter_screen_name,
            'signed_in_personal':               voter.signed_in_personal(),
            'signed_in_facebook':               voter.signed_in_facebook(),
            'signed_in_google':                 voter.signed_in_google(),
            'signed_in_twitter':                voter.signed_in_twitter(),
            'linked_organization_we_vote_id':   voter.linked_organization_we_vote_id,
            'voter_photo_url':                  voter.voter_photo_url(),
        }
        return json_data

    else:
        status = results['status']
        json_data = {
            'status':                           status,
            'success':                          False,
            'voter_device_id':                  voter_device_id,
            'voter_created':                    False,
            'voter_found':                      False,
            'we_vote_id':                       '',
            'facebook_id':                      '',
            'email':                            '',
            'facebook_email':                   '',
            'facebook_profile_image_url_https': '',
            'full_name':                        '',
            'first_name':                       '',
            'last_name':                        '',
            'twitter_screen_name':              '',
            'signed_in_personal':               False,
            'signed_in_facebook':               False,
            'signed_in_google':                 False,
            'signed_in_twitter':                False,
            'linked_organization_we_vote_id':   '',
            'voter_photo_url':                  '',
        }
        return json_data
Example #25
0
def voter_address_retrieve_for_api(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        voter_address_retrieve_results = {
            'status': results['status'],
            'success': False,
            'address_found': False,
            'voter_device_id': voter_device_id,
        }
        return voter_address_retrieve_results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        voter_address_retrieve_results = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'address_found': False,
            'voter_device_id': voter_device_id,
        }
        return voter_address_retrieve_results

    voter_address_manager = VoterAddressManager()
    results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)

    if results['voter_address_found']:
        voter_address = results['voter_address']
        status = "VOTER_ADDRESS_RETRIEVE-ADDRESS_FOUND"

        voter_address_retrieve_results = {
            'voter_device_id': voter_device_id,
            'address_type': voter_address.address_type if voter_address.address_type else '',
            'text_for_map_search': voter_address.text_for_map_search if voter_address.text_for_map_search else '',
            'google_civic_election_id': voter_address.google_civic_election_id if voter_address.google_civic_election_id
            else 0,
            'latitude': voter_address.latitude if voter_address.latitude else '',
            'longitude': voter_address.longitude if voter_address.longitude else '',
            'normalized_line1': voter_address.normalized_line1 if voter_address.normalized_line1 else '',
            'normalized_line2': voter_address.normalized_line2 if voter_address.normalized_line2 else '',
            'normalized_city': voter_address.normalized_city if voter_address.normalized_city else '',
            'normalized_state': voter_address.normalized_state if voter_address.normalized_state else '',
            'normalized_zip': voter_address.normalized_zip if voter_address.normalized_zip else '',
            'address_found': True,
            'success': True,
            'status': status,
        }
        return voter_address_retrieve_results
    else:
        voter_address_retrieve_results = {
            'status': "VOTER_ADDRESS_NOT_FOUND",
            'success': False,
            'address_found': False,
            'voter_device_id': voter_device_id,
            'address_type': '',
            'text_for_map_search': '',
            'google_civic_election_id': 0,
            'latitude': '',
            'longitude': '',
            'normalized_line1': '',
            'normalized_line2': '',
            'normalized_city': '',
            'normalized_state': '',
            'normalized_zip': '',
        }
        return voter_address_retrieve_results
Example #26
0
def voter_photo_save_for_api(voter_device_id, facebook_profile_image_url_https,
                             facebook_photo_variable_exists):
    facebook_profile_image_url_https = facebook_profile_image_url_https.strip()

    device_id_results = is_voter_device_id_valid(voter_device_id)
    if not device_id_results['success']:
        results = {
            'status': device_id_results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
            'facebook_profile_image_url_https':
            facebook_profile_image_url_https,
        }
        return results

    if not facebook_photo_variable_exists:
        results = {
            'status': "MISSING_VARIABLE-AT_LEAST_ONE_PHOTO",
            'success': False,
            'voter_device_id': voter_device_id,
            'facebook_profile_image_url_https':
            facebook_profile_image_url_https,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id < 0:
        results = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
            'facebook_profile_image_url_https':
            facebook_profile_image_url_https,
        }
        return results

    # At this point, we have a valid voter

    voter_manager = VoterManager()
    results = voter_manager.update_voter_photos(
        voter_id, facebook_profile_image_url_https,
        facebook_photo_variable_exists)

    if results['success']:
        if positive_value_exists(facebook_profile_image_url_https):
            status = "VOTER_FACEBOOK_PHOTO_SAVED"
        else:
            status = "VOTER_PHOTOS_EMPTY_SAVED"

        results = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'facebook_profile_image_url_https':
            facebook_profile_image_url_https,
        }

    else:
        results = {
            'status': results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
            'facebook_profile_image_url_https':
            facebook_profile_image_url_https,
        }
    return results
Example #27
0
def voter_address_retrieve_for_api(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        voter_address_retrieve_results = {
            'status': results['status'],
            'success': False,
            'address_found': False,
            'voter_device_id': voter_device_id,
        }
        return voter_address_retrieve_results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        voter_address_retrieve_results = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'address_found': False,
            'voter_device_id': voter_device_id,
        }
        return voter_address_retrieve_results

    voter_address_manager = VoterAddressManager()
    results = voter_address_manager.retrieve_ballot_address_from_voter_id(
        voter_id)

    if results['voter_address_found']:
        voter_address = results['voter_address']
        status = "VOTER_ADDRESS_RETRIEVE-ADDRESS_FOUND"

        voter_address_retrieve_results = {
            'voter_device_id':
            voter_device_id,
            'address_type':
            voter_address.address_type if voter_address.address_type else '',
            'text_for_map_search':
            voter_address.text_for_map_search
            if voter_address.text_for_map_search else '',
            'google_civic_election_id':
            voter_address.google_civic_election_id
            if voter_address.google_civic_election_id else 0,
            'latitude':
            voter_address.latitude if voter_address.latitude else '',
            'longitude':
            voter_address.longitude if voter_address.longitude else '',
            'normalized_line1':
            voter_address.normalized_line1
            if voter_address.normalized_line1 else '',
            'normalized_line2':
            voter_address.normalized_line2
            if voter_address.normalized_line2 else '',
            'normalized_city':
            voter_address.normalized_city
            if voter_address.normalized_city else '',
            'normalized_state':
            voter_address.normalized_state
            if voter_address.normalized_state else '',
            'normalized_zip':
            voter_address.normalized_zip
            if voter_address.normalized_zip else '',
            'address_found':
            True,
            'success':
            True,
            'status':
            status,
        }
        return voter_address_retrieve_results
    else:
        voter_address_retrieve_results = {
            'status': "VOTER_ADDRESS_NOT_FOUND",
            'success': False,
            'address_found': False,
            'voter_device_id': voter_device_id,
            'address_type': '',
            'text_for_map_search': '',
            'google_civic_election_id': 0,
            'latitude': '',
            'longitude': '',
            'normalized_line1': '',
            'normalized_line2': '',
            'normalized_city': '',
            'normalized_state': '',
            'normalized_zip': '',
        }
        return voter_address_retrieve_results
Example #28
0
def voter_create_for_api(voter_device_id):  # voterCreate
    # If a voter_device_id isn't passed in, automatically create a new voter_device_id
    if not positive_value_exists(voter_device_id):
        voter_device_id = generate_voter_device_id()
    else:
        # If a voter_device_id is passed in that isn't valid, we want to throw an error
        results = is_voter_device_id_valid(voter_device_id)
        if not results['success']:
            return HttpResponse(json.dumps(results['json_data']),
                                content_type='application/json')

    voter_id = 0
    voter_we_vote_id = ''
    # Make sure a voter record hasn't already been created for this
    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if results['voter_found']:
        voter = results['voter']
        voter_id = voter.id
        voter_we_vote_id = voter.we_vote_id
        json_data = {
            'status': "VOTER_ALREADY_EXISTS",
            'success': True,
            'voter_device_id': voter_device_id,
            'voter_id': voter_id,
            'voter_we_vote_id': voter_we_vote_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    # Create a new voter and return the voter_device_id
    voter_manager = VoterManager()
    results = voter_manager.create_voter()

    if results['voter_created']:
        voter = results['voter']

        # Now save the voter_device_link
        voter_device_link_manager = VoterDeviceLinkManager()
        results = voter_device_link_manager.save_new_voter_device_link(
            voter_device_id, voter.id)

        if results['voter_device_link_created']:
            voter_device_link = results['voter_device_link']
            voter_id_found = True if voter_device_link.voter_id > 0 else False

            if voter_id_found:
                voter_id = voter.id
                voter_we_vote_id = voter.we_vote_id

    if voter_id:
        json_data = {
            'status': "VOTER_CREATED",
            'success': True,
            'voter_device_id': voter_device_id,
            'voter_id': voter_id,
            'voter_we_vote_id': voter_we_vote_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_NOT_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_id': 0,
            'voter_we_vote_id': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
Example #29
0
def voter_guides_to_follow_retrieve_for_api(voter_device_id,  # voterGuidesToFollow
                                            kind_of_ballot_item='', ballot_item_we_vote_id='',
                                            google_civic_election_id=0, search_string='',
                                            maximum_number_to_retrieve=0):
    # Get voter_id from the voter_device_id so we can figure out which voter_guides to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'ERROR_GUIDES_TO_FOLLOW_NO_VOTER_DEVICE_ID',
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
        }
        results = {
            'success': False,
            'google_civic_election_id': 0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
        }
        results = {
            'success': False,
            'google_civic_election_id': 0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results

    voter_guide_list = []
    voter_guides = []
    try:
        if positive_value_exists(kind_of_ballot_item) and positive_value_exists(ballot_item_we_vote_id):
            results = retrieve_voter_guides_to_follow_by_ballot_item(voter_id,
                                                                     kind_of_ballot_item, ballot_item_we_vote_id,
                                                                     search_string)
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']
        elif positive_value_exists(google_civic_election_id):
            # This retrieve also does the reordering
            results = retrieve_voter_guides_to_follow_by_election_for_api(voter_id, google_civic_election_id,
                                                                          search_string,
                                                                          maximum_number_to_retrieve,
                                                                          'twitter_followers_count', 'desc')
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']
        else:
            results = retrieve_voter_guides_to_follow_generic_for_api(voter_id, search_string,
                                                                      maximum_number_to_retrieve,
                                                                      'twitter_followers_count', 'desc')
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']

    except Exception as e:
        status = 'FAILED voter_guides_to_follow_retrieve_for_api, retrieve_voter_guides_for_election ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        success = False

    if success:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        linked_organization_we_vote_id = ""
        if results['voter_found']:
            voter = results['voter']
            linked_organization_we_vote_id = voter.linked_organization_we_vote_id

        number_added_to_list = 0
        position_manager = PositionEnteredManager()
        position = PositionEntered()
        for voter_guide in voter_guide_list:
            if positive_value_exists(voter_guide.organization_we_vote_id) \
                    and linked_organization_we_vote_id == voter_guide.organization_we_vote_id:
                # Do not return your own voter guide to follow
                continue

            position_found = False
            one_voter_guide = {
                'we_vote_id': voter_guide.we_vote_id,
                'google_civic_election_id': voter_guide.google_civic_election_id,
                'time_span': voter_guide.vote_smart_time_span,
                'voter_guide_display_name': voter_guide.voter_guide_display_name(),
                'voter_guide_image_url': voter_guide.voter_guide_image_url(),
                'voter_guide_owner_type': voter_guide.voter_guide_owner_type,
                'organization_we_vote_id': voter_guide.organization_we_vote_id,
                'public_figure_we_vote_id': voter_guide.public_figure_we_vote_id,
                'twitter_description': voter_guide.twitter_description,
                'twitter_followers_count': voter_guide.twitter_followers_count,
                'twitter_handle': voter_guide.twitter_handle,
                'owner_voter_id': voter_guide.owner_voter_id,
                'last_updated': voter_guide.last_updated.strftime('%Y-%m-%d %H:%M'),
            }
            if positive_value_exists(ballot_item_we_vote_id):
                if kind_of_ballot_item == CANDIDATE:
                    organization_manager = OrganizationManager()
                    organization_id = organization_manager.fetch_organization_id(
                        voter_guide.organization_we_vote_id)
                    results = position_manager.retrieve_organization_candidate_campaign_position_with_we_vote_id(
                        organization_id, ballot_item_we_vote_id)
                    if results['position_found']:
                        position = results['position']
                        position_found = True
                elif kind_of_ballot_item == MEASURE:
                    organization_manager = OrganizationManager()
                    organization_id = organization_manager.fetch_organization_id(
                        voter_guide.organization_we_vote_id)
                    results = position_manager.retrieve_organization_contest_measure_position_with_we_vote_id(
                        organization_id, ballot_item_we_vote_id)
                    if results['position_found']:
                        position = results['position']
                        position_found = True

                if position_found:
                    one_voter_guide['is_support'] = position.is_support()
                    one_voter_guide['is_positive_rating'] = position.is_positive_rating()
                    one_voter_guide['is_support_or_positive_rating'] = position.is_support_or_positive_rating()
                    one_voter_guide['is_oppose'] = position.is_oppose()
                    one_voter_guide['is_negative_rating'] = position.is_negative_rating()
                    one_voter_guide['is_oppose_or_negative_rating'] = position.is_oppose_or_negative_rating()
                    one_voter_guide['is_information_only'] = position.is_information_only()
                    one_voter_guide['ballot_item_display_name'] = position.ballot_item_display_name
                    one_voter_guide['speaker_display_name'] = position.speaker_display_name
                    one_voter_guide['statement_text'] = position.statement_text
                    one_voter_guide['more_info_url'] = position.more_info_url
                    one_voter_guide['vote_smart_rating'] = position.vote_smart_rating
                    one_voter_guide['vote_smart_time_span'] = position.vote_smart_time_span

            voter_guides.append(one_voter_guide.copy())
            if positive_value_exists(maximum_number_to_retrieve):
                number_added_to_list += 1
                if number_added_to_list >= maximum_number_to_retrieve:
                    break

        if len(voter_guides):
            json_data = {
                'status': status + ' VOTER_GUIDES_TO_FOLLOW_RETRIEVED',
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guides': voter_guides,
                'google_civic_election_id': google_civic_election_id,
                'search_string': search_string,
                'ballot_item_we_vote_id': ballot_item_we_vote_id,
                'maximum_number_to_retrieve': maximum_number_to_retrieve,
            }
        else:
            json_data = {
                'status': status + ' NO_VOTER_GUIDES_FOUND',
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guides': voter_guides,
                'google_civic_election_id': google_civic_election_id,
                'search_string': search_string,
                'ballot_item_we_vote_id': ballot_item_we_vote_id,
                'maximum_number_to_retrieve': maximum_number_to_retrieve,
            }

        results = {
            'success': success,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results
    else:
        json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'maximum_number_to_retrieve': maximum_number_to_retrieve,
        }

        results = {
            'success': False,
            'google_civic_election_id': 0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results
Example #30
0
def twitter_sign_in_start_for_api(voter_device_id):  # twitterSignInStart
    """

    :param voter_device_id:
    :return:
    """
    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': '',
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status': "VALID_VOTER_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': '',
        }
        return results

    voter = results['voter']
    callback_url = WE_VOTE_SERVER_ROOT_URL + "/twitter/process_sign_in_response/"
    redirect_url = ''

    try:
        # We take the Consumer Key and the Consumer Secret, and request a token & token_secret
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY,
                                   TWITTER_CONSUMER_SECRET, callback_url)
        redirect_url = auth.get_authorization_url()
        request_token_dict = auth.request_token
        twitter_request_token = ''
        twitter_request_token_secret = ''

        if 'oauth_token' in request_token_dict:
            twitter_request_token = request_token_dict['oauth_token']
        if 'oauth_token_secret' in request_token_dict:
            twitter_request_token_secret = request_token_dict[
                'oauth_token_secret']

        # We save these values in the Voter table, and then return a redirect_url where the user can sign in
        # Once they sign in to the Twitter login, they are redirected back to the We Vote callback_url
        # On that callback_url page (a Django/Python page as opposed to ReactJS), we are told if they are signed in
        #  on Twitter or not, and capture an access key we can use to retrieve information about the Twitter user
        if positive_value_exists(
                twitter_request_token) and positive_value_exists(
                    twitter_request_token_secret):
            voter.twitter_request_token = twitter_request_token
            voter.twitter_request_secret = twitter_request_token_secret
            voter.save()

            success = True
            status = "TWITTER_REDIRECT_URL_RETRIEVED"
        else:
            success = False
            status = "TWITTER_REDIRECT_URL_NOT_RETRIEVED"

    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_START: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            for one_error in error_dict:
                status += '[' + one_error['message'] + '] '

    if success:
        results = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': redirect_url,
        }
    else:
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'twitter_redirect_url': '',
        }
    return results
Example #31
0
def search_all_for_api(text_from_search_field, voter_device_id):
    """

    :param text_from_search_field:
    :param voter_device_id:
    :return:
    """
    if not positive_value_exists(text_from_search_field):
        results = {
            'status':                   'TEXT_FROM_SEARCH_FIELD_MISSING',
            'success':                  True,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    if not positive_value_exists(ELASTIC_SEARCH_CONNECTION_STRING):
        results = {
            'status':                   'MISSING_ELASTIC_SEARCH_CONNECTION_STRING',
            'success':                  False,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status':                   'VALID_VOTER_DEVICE_ID_MISSING',
            'success':                  False,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status':                   "VALID_VOTER_ID_MISSING",
            'success':                  False,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    elastic_search_object = Elasticsearch([ELASTIC_SEARCH_CONNECTION_STRING],
                                          timeout=2, max_retries=1, retry_on_timeout=True)

    # query = {"query": {"match": {"candidate_name": text_from_search_field}}}
    query = {"query": {"multi_match": {"type": "phrase_prefix",
                                       "query": text_from_search_field,
                                       "fields": ["candidate_name",
                                                  "candidate_twitter_handle", "twitter_name",
                                                  "measure_subtitle", "measure_text", "measure_title",
                                                  "office_name", "first_name", "middle_name", "last_name",
                                                  "party", "organization_name", "organization_twitter_handle",
                                                  "twitter_description"]}}}

    # Example of querying ALL indexes
    search_results = []
    search_count = 0
    try:
        res = elastic_search_object.search(body=query)
        # See bottom of this file for example results from Elastic Search

        for hit in res['hits']['hits']:
            one_search_result_type = hit['_type']
            one_search_result_id = hit['_id']
            one_search_result_dict = hit['_source']
            one_search_result_score = hit['_score']
            if one_search_result_type == "office":
                link_internal = "/office/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['office_name'],
                    'result_image':             "",
                    'result_subtitle':          "",
                    'result_summary':           "",
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "OFFICE",
                    'google_civic_election_id': one_search_result_dict['google_civic_election_id'],
                    'state_code':               one_search_result_dict['state_code'],
                    'twitter_handle':           "",
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "candidate":
                if positive_value_exists(one_search_result_dict['candidate_twitter_handle']):
                    link_internal = "/" + one_search_result_dict['candidate_twitter_handle']
                else:
                    link_internal = "/candidate/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['candidate_name'],
                    'result_image':             "",
                    'result_subtitle':          "",
                    'result_summary':           "",
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "CANDIDATE",
                    'google_civic_election_id': one_search_result_dict['google_civic_election_id'],
                    'state_code':               one_search_result_dict['state_code'],
                    'twitter_handle':           one_search_result_dict['candidate_twitter_handle'],
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "measure":
                if positive_value_exists(one_search_result_dict['measure_twitter_handle']):
                    link_internal = "/" + one_search_result_dict['measure_twitter_handle']
                else:
                    link_internal = "/measure/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['measure_title'],
                    'result_image':             "",
                    'result_subtitle':          one_search_result_dict['measure_subtitle'],
                    'result_summary':           one_search_result_dict['measure_text'],
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "MEASURE",
                    'google_civic_election_id': one_search_result_dict['google_civic_election_id'],
                    'state_code':               one_search_result_dict['state_code'],
                    'twitter_handle':           one_search_result_dict['measure_twitter_handle'],
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "organization":
                if 'organization_twitter_handle' in one_search_result_dict and \
                        positive_value_exists(one_search_result_dict['organization_twitter_handle']):
                    link_internal = "/" + one_search_result_dict['organization_twitter_handle']
                else:
                    link_internal = "/voterguide/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['organization_name'],
                    'result_image':             "",
                    'result_subtitle':          "",
                    'result_summary':           one_search_result_dict['twitter_description'],
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "ORGANIZATION",
                    'google_civic_election_id': 0,
                    'state_code':               one_search_result_dict['state_served_code'],
                    'twitter_handle':           one_search_result_dict['organization_twitter_handle'],
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "politician":
                # If we are here, then we should skip out. We can't display politicians w/o twitter_handle yet
                break
                # if positive_value_exists(one_search_result_dict['politician_twitter_handle']):
                #     link_internal = "/" + one_search_result_dict['politician_twitter_handle']
                # else:
                #     link_internal = "/candidate/" + one_search_result_dict['we_vote_id']
                #
                # one_search_result = {
                #     'result_title': one_search_result_dict['name'],
                #     'result_image':             "",
                #     'result_subtitle':          "",
                #     'result_summary':           "",
                #     'result_score':             one_search_result_score,
                #     'link_internal':            link_internal,
                #     'kind_of_owner':            "POLITICIAN",
                #     'google_civic_election_id': 0,
                #     'state_code':               one_search_result_dict['state_served_code'],
                #     'twitter_handle':           one_search_result_dict['politician_twitter_handle,'],
                #     'we_vote_id':               one_search_result_dict['we_vote_id'],
                #     'local_id':                 one_search_result_id,
                # }
                # search_results.append(one_search_result)
                # search_count += 1
        status = "SEARCH_ALL_COMPLETE"
        success = True

    except Exception as e:
        status = 'ELASTIC_SEARCH_EXCEPTION'
        success = False

    results = {
        'status':                   status,
        'success':                  success,
        'text_from_search_field':   text_from_search_field,
        'voter_device_id':          voter_device_id,
        'search_results_found':     True if search_count > 0 else False,
        'search_results':           search_results,
    }
    return results
Example #32
0
def voter_guides_to_follow_retrieve_for_api(
        voter_device_id,  # voterGuidesToFollow
        kind_of_ballot_item='',
        ballot_item_we_vote_id='',
        google_civic_election_id=0,
        search_string='',
        maximum_number_to_retrieve=0):
    # Get voter_id from the voter_device_id so we can figure out which voter_guides to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'ERROR_GUIDES_TO_FOLLOW_NO_VOTER_DEVICE_ID',
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
        }
        results = {
            'success': False,
            'google_civic_election_id':
            0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':
            "ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
        }
        results = {
            'success': False,
            'google_civic_election_id':
            0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results

    voter_guide_list = []
    voter_guides = []
    try:
        if positive_value_exists(
                kind_of_ballot_item) and positive_value_exists(
                    ballot_item_we_vote_id):
            results = retrieve_voter_guides_to_follow_by_ballot_item(
                voter_id, kind_of_ballot_item, ballot_item_we_vote_id,
                search_string)
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']
        elif positive_value_exists(google_civic_election_id):
            # This retrieve also does the reordering
            results = retrieve_voter_guides_to_follow_by_election_for_api(
                voter_id, google_civic_election_id, search_string,
                maximum_number_to_retrieve, 'twitter_followers_count', 'desc')
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']
        else:
            results = retrieve_voter_guides_to_follow_generic(
                voter_id, search_string, maximum_number_to_retrieve,
                'twitter_followers_count', 'desc')
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']

    except Exception as e:
        status = 'FAILED voter_guides_to_follow_retrieve_for_api, retrieve_voter_guides_for_election ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        success = False

    if success:
        number_added_to_list = 0
        for voter_guide in voter_guide_list:
            one_voter_guide = {
                'we_vote_id':
                voter_guide.we_vote_id,
                'google_civic_election_id':
                voter_guide.google_civic_election_id,
                'time_span':
                voter_guide.vote_smart_time_span,
                'voter_guide_display_name':
                voter_guide.voter_guide_display_name(),
                'voter_guide_image_url':
                voter_guide.voter_guide_image_url(),
                'voter_guide_owner_type':
                voter_guide.voter_guide_owner_type,
                'organization_we_vote_id':
                voter_guide.organization_we_vote_id,
                'public_figure_we_vote_id':
                voter_guide.public_figure_we_vote_id,
                'twitter_description':
                voter_guide.twitter_description,
                'twitter_followers_count':
                voter_guide.twitter_followers_count,
                'owner_voter_id':
                voter_guide.owner_voter_id,
                'last_updated':
                voter_guide.last_updated.strftime('%Y-%m-%d %H:%M'),
            }
            voter_guides.append(one_voter_guide.copy())
            if positive_value_exists(maximum_number_to_retrieve):
                number_added_to_list += 1
                if number_added_to_list >= maximum_number_to_retrieve:
                    break

        if len(voter_guides):
            json_data = {
                'status': status + ' VOTER_GUIDES_TO_FOLLOW_RETRIEVED',
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guides': voter_guides,
                'google_civic_election_id': google_civic_election_id,
                'search_string': search_string,
                'ballot_item_we_vote_id': ballot_item_we_vote_id,
                'maximum_number_to_retrieve': maximum_number_to_retrieve,
            }
        else:
            json_data = {
                'status': status + ' NO_VOTER_GUIDES_FOUND',
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guides': voter_guides,
                'google_civic_election_id': google_civic_election_id,
                'search_string': search_string,
                'ballot_item_we_vote_id': ballot_item_we_vote_id,
                'maximum_number_to_retrieve': maximum_number_to_retrieve,
            }

        results = {
            'success': success,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results
    else:
        json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'maximum_number_to_retrieve': maximum_number_to_retrieve,
        }

        results = {
            'success': False,
            'google_civic_election_id':
            0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results
Example #33
0
def voter_create_for_api(voter_device_id):  # voterCreate
    # If a voter_device_id isn't passed in, automatically create a new voter_device_id
    if not positive_value_exists(voter_device_id):
        voter_device_id = generate_voter_device_id()
    else:
        # If a voter_device_id is passed in that isn't valid, we want to throw an error
        results = is_voter_device_id_valid(voter_device_id)
        if not results['success']:
            return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = 0
    voter_we_vote_id = ''
    # Make sure a voter record hasn't already been created for this
    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
    if results['voter_found']:
        voter = results['voter']
        voter_id = voter.id
        voter_we_vote_id = voter.we_vote_id
        json_data = {
            'status': "VOTER_ALREADY_EXISTS",
            'success': True,
            'voter_device_id': voter_device_id,
            'voter_id':         voter_id,
            'voter_we_vote_id': voter_we_vote_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # Create a new voter and return the voter_device_id
    voter_manager = VoterManager()
    results = voter_manager.create_voter()

    if results['voter_created']:
        voter = results['voter']

        # Now save the voter_device_link
        voter_device_link_manager = VoterDeviceLinkManager()
        results = voter_device_link_manager.save_new_voter_device_link(voter_device_id, voter.id)

        if results['voter_device_link_created']:
            voter_device_link = results['voter_device_link']
            voter_id_found = True if voter_device_link.voter_id > 0 else False

            if voter_id_found:
                voter_id = voter.id
                voter_we_vote_id = voter.we_vote_id

    if voter_id:
        json_data = {
            'status':           "VOTER_CREATED",
            'success':          True,
            'voter_device_id':  voter_device_id,
            'voter_id':         voter_id,
            'voter_we_vote_id': voter_we_vote_id,

        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status':           "VOTER_NOT_CREATED",
            'success':          False,
            'voter_device_id':  voter_device_id,
            'voter_id':         0,
            'voter_we_vote_id': '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #34
0
def voter_retrieve_for_api(voter_device_id):  # voterRetrieve
    """
    Used by the api
    :param voter_device_id:
    :return:
    """
    voter_manager = VoterManager()
    voter_id = 0
    voter_created = False

    if positive_value_exists(voter_device_id):
        # If a voter_device_id is passed in that isn't valid, we want to throw an error
        device_id_results = is_voter_device_id_valid(voter_device_id)
        if not device_id_results['success']:
            json_data = {
                'status': device_id_results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
                'voter_created': False,
                'voter_found': False,
            }
            return json_data

        voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
        if not positive_value_exists(voter_id):
            json_data = {
                'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
                'success': False,
                'voter_device_id': voter_device_id,
                'voter_created': False,
                'voter_found': False,
            }
            return json_data
    else:
        # If a voter_device_id isn't passed in, automatically create a new voter_device_id and voter
        voter_device_id = generate_voter_device_id()

        # We make sure a voter record hasn't already been created for this new voter_device_id, so we don't create a
        # security hole by giving a new person access to an existing account. This should never happen because it is
        # so unlikely that we will ever generate an existing voter_device_id with generate_voter_device_id.
        existing_voter_id = fetch_voter_id_from_voter_device_link(
            voter_device_id)
        if existing_voter_id:
            json_data = {
                'status': "VOTER_ALREADY_EXISTS_BUT_ACCESS_RESTRICTED",
                'success': False,
                'voter_device_id': voter_device_id,
                'voter_created': False,
                'voter_found': False,
            }
            return json_data

        results = voter_manager.create_voter()

        if results['voter_created']:
            voter = results['voter']

            # Now save the voter_device_link
            voter_device_link_manager = VoterDeviceLinkManager()
            results = voter_device_link_manager.save_new_voter_device_link(
                voter_device_id, voter.id)

            if results['voter_device_link_created']:
                voter_device_link = results['voter_device_link']
                voter_id_found = True if voter_device_link.voter_id > 0 else False

                if voter_id_found:
                    voter_id = voter_device_link.voter_id
                    voter_created = True

        if not positive_value_exists(voter_id):
            json_data = {
                'status': "VOTER_NOT_FOUND_AFTER_BEING_CREATED",
                'success': False,
                'voter_device_id': voter_device_id,
                'voter_created': False,
                'voter_found': False,
            }
            return json_data

    # At this point, we should have a valid voter_id
    results = voter_manager.retrieve_voter_by_id(voter_id)
    if results['voter_found']:
        voter = results['voter']

        if voter_created:
            status = 'VOTER_CREATED'
        else:
            status = 'VOTER_FOUND'
        json_data = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'voter_created': voter_created,
            'voter_found': True,
            'we_vote_id': voter.we_vote_id,
            'facebook_id': voter.facebook_id,
            'email': voter.email,
            'facebook_email': voter.facebook_email,
            'facebook_profile_image_url_https':
            voter.facebook_profile_image_url_https,
            'full_name': voter.get_full_name(),
            'first_name': voter.first_name,
            'last_name': voter.last_name,
            'twitter_screen_name': voter.twitter_screen_name,
            'signed_in_personal': voter.signed_in_personal(),
            'signed_in_facebook': voter.signed_in_facebook(),
            'signed_in_google': voter.signed_in_google(),
            'signed_in_twitter': voter.signed_in_twitter(),
            'linked_organization_we_vote_id':
            voter.linked_organization_we_vote_id,
            'voter_photo_url': voter.voter_photo_url(),
        }
        return json_data

    else:
        status = results['status']
        json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_created': False,
            'voter_found': False,
            'we_vote_id': '',
            'facebook_id': '',
            'email': '',
            'facebook_email': '',
            'facebook_profile_image_url_https': '',
            'full_name': '',
            'first_name': '',
            'last_name': '',
            'twitter_screen_name': '',
            'signed_in_personal': False,
            'signed_in_facebook': False,
            'signed_in_google': False,
            'signed_in_twitter': False,
            'linked_organization_we_vote_id': '',
            'voter_photo_url': '',
        }
        return json_data
Example #35
0
def facebook_sign_in_for_api(voter_device_id,
                             facebook_id=None,
                             facebook_email=None):  # facebookSignIn
    """

    :param voter_device_id:
    :return:
    """
    status = ""
    success = False
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
            'facebook_id': facebook_id,
            'facebook_email': facebook_email,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'success': False,
            'status': "VALID_VOTER_MISSING",
            'voter_device_id': voter_device_id,
            'facebook_id': facebook_id,
            'facebook_email': facebook_email,
        }
        return results

    voter = results['voter']

    results_from_facebook_id = voter_manager.retrieve_voter_by_facebook_id(
        facebook_id)
    if positive_value_exists(results_from_facebook_id['voter_found']):
        voter_found_with_facebook_id = results_from_facebook_id['voter']
        if voter_found_with_facebook_id.id == voter.id:
            # If here, the owner of the facebook_id is already the current primary voter
            status += "FACEBOOK_SIGN_IN-ALREADY_LINKED_TO_THIS_FACEBOOK_ACCOUNT "
            success = True
            # Only save if the email is different than what is saved
            if positive_value_exists(facebook_email) or facebook_email == '':
                results = voter_manager.save_facebook_user_values(
                    voter, facebook_id, facebook_email)
                status += results['status']
                success = results['success']
        else:
            # If here, we need to merge accounts TODO

            # ...but for now we are simply going to switch to the earlier account and abandon
            # the newer account
            if positive_value_exists(facebook_email) or facebook_email == '':
                results = voter_manager.save_facebook_user_values(
                    voter_found_with_facebook_id, facebook_id, facebook_email)
                status += results['status'] + ", "
                success = results['success']

            # Relink this voter_device_id to the original account
            voter_device_manager = VoterDeviceLinkManager()
            voter_device_link_results = voter_device_manager.retrieve_voter_device_link(
                voter_device_id)
            voter_device_link = voter_device_link_results['voter_device_link']

            update_voter_device_link_results = voter_device_manager.update_voter_device_link(
                voter_device_link, voter_found_with_facebook_id)
            if update_voter_device_link_results['voter_device_link_updated']:
                status += "FACEBOOK_SIGN_IN-ALREADY_LINKED_TO_OTHER_ACCOUNT-TRANSFERRED "
                success = True
            else:
                status = "FACEBOOK_SIGN_IN-ALREADY_LINKED_TO_OTHER_ACCOUNT-COULD_NOT_TRANSFER "
                success = False
    else:
        # An existing account linked to this facebook account was not found
        results = voter_manager.save_facebook_user_values(
            voter, facebook_id, facebook_email)
        status = results['status']
        success = results['success']

    if success:
        results = {
            'success': True,
            'status': status,
            'voter_device_id': voter_device_id,
            'facebook_id': facebook_id,
            'facebook_email': facebook_email,
        }
    else:
        results = {
            'success': False,
            'status': status,
            'voter_device_id': voter_device_id,
            'facebook_id': facebook_id,
            'facebook_email': facebook_email,
        }
    return results
Example #36
0
def voter_supporting_save_for_api(voter_device_id, candidate_id,
                                  candidate_we_vote_id, measure_id,
                                  measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing, voterSupportingSave
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    position_entered_manager = PositionEnteredManager()
    if positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
                candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
                candidate_we_vote_id)

        results = position_entered_manager.toggle_on_voter_support_for_candidate_campaign(
            voter_id, candidate_id)
        status = "SUPPORTING_CANDIDATE " + results['status']
        success = results['success']

        json_data = {
            'status': status,
            'success': success,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(
            measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        # Since we can take in either measure_id or measure_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(measure_id):
            measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
                measure_id)
        elif positive_value_exists(measure_we_vote_id):
            measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(
                measure_we_vote_id)

        results = position_entered_manager.toggle_on_voter_support_for_contest_measure(
            voter_id, measure_id)
        status = "SUPPORTING_MEASURE " + results['status']
        success = results['success']

        json_data = {
            'status': status,
            'success': success,
            'ballot_item_id': convert_to_int(measure_id),
            'ballot_item_we_vote_id': measure_we_vote_id,
            'kind_of_ballot_item': MEASURE,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        status = 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
        'ballot_item_id': 0,
        'ballot_item_we_vote_id': '',
        'kind_of_ballot_item': '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #37
0
def voter_retrieve_list_for_api(voter_device_id):
    """
    This is used for voterExportView
    :param voter_device_id:
    :return:
    """
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results2 = {
            'success': False,
            'json_data': results['json_data'],
        }
        return results2

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id > 0:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        if results['voter_found']:
            voter_id = results['voter_id']
    else:
        # If we are here, the voter_id could not be found from the voter_device_id
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        results = {
            'success': False,
            'json_data': json_data,
        }
        return results

    if voter_id:
        voter_list = Voter.objects.all()
        voter_list = voter_list.filter(id=voter_id)

        if len(voter_list):
            results = {
                'success': True,
                'voter_list': voter_list,
            }
            return results

    # Trying to mimic the Google Civic error codes scheme
    errors_list = [
        {
            'domain':  "TODO global",
            'reason':  "TODO reason",
            'message':  "TODO Error message here",
            'locationType':  "TODO Error message here",
            'location':  "TODO location",
        }
    ]
    error_package = {
        'errors':   errors_list,
        'code':     400,
        'message':  "Error message here",
    }
    json_data = {
        'error': error_package,
        'status': "VOTER_ID_COULD_NOT_BE_RETRIEVED",
        'success': False,
        'voter_device_id': voter_device_id,
    }
    results = {
        'success': False,
        'json_data': json_data,
    }
    return results
def position_like_count_for_api(voter_device_id, position_entered_id, limit_to_voters_network=False):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':               'VALID_VOTER_DEVICE_ID_MISSING',
            'success':              False,
            'voter_device_id':      voter_device_id,
            'position_entered_id':  position_entered_id,
            'voter_network_likes':  False,
            'all_likes':            False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':               "VALID_VOTER_ID_MISSING",
            'success':              False,
            'voter_device_id':      voter_device_id,
            'position_entered_id':  position_entered_id,
            'voter_network_likes':  False,
            'all_likes':            False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_like_list_manager = PositionLikeListManager()
    type_of_count = False
    number_of_likes = False
    if positive_value_exists(position_entered_id):
        if limit_to_voters_network:
            if positive_value_exists(voter_id):
                results = position_like_list_manager.count_voter_network_position_likes(position_entered_id, voter_id)
                status = results['status']
                success = results['success']
                all_likes = False
                voter_network_likes = results['number_of_likes']
                type_of_count = 'VOTER_NETWORK'
                number_of_likes = results['number_of_likes']
            else:
                status = 'UNABLE_TO_RETRIEVE_VOTER_NETWORK_COUNT-VOTER_ID_MISSING'
                success = False
                all_likes = False
                voter_network_likes = False
        else:
            results = position_like_list_manager.count_all_position_likes(position_entered_id)
            status = results['status']
            success = results['success']
            all_likes = results['number_of_likes']
            voter_network_likes = False
            type_of_count = 'ALL'
            number_of_likes = results['number_of_likes']
    else:
        status = 'UNABLE_TO_RETRIEVE_COUNT-POSITION_ENTERED_ID_MISSING'
        success = False
        all_likes = False
        voter_network_likes = False

    json_data = {
        'status':               status,
        'success':              success,
        'voter_device_id':      voter_device_id,
        'position_entered_id':  position_entered_id,
        'type_of_count':        type_of_count,
        'number_of_likes':      number_of_likes,
        'all_likes':            all_likes,
        'voter_network_likes':  voter_network_likes,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #39
0
def voter_position_retrieve_for_api(voter_device_id, office_we_vote_id, candidate_we_vote_id, measure_we_vote_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    office_we_vote_id = office_we_vote_id.strip()
    candidate_we_vote_id = candidate_we_vote_id.strip()
    measure_we_vote_id = measure_we_vote_id.strip()

    if not positive_value_exists(office_we_vote_id) and \
            not positive_value_exists(candidate_we_vote_id) and \
            not positive_value_exists(measure_we_vote_id):
        json_data = {
            'status':                   "POSITION_RETRIEVE_MISSING_AT_LEAST_ONE_BALLOT_ITEM_ID",
            'success':                  False,
            'position_id':              0,
            'position_we_vote_id':      '',
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': '',
            'office_we_vote_id':        '',
            'candidate_we_vote_id':     '',
            'measure_we_vote_id':       '',
            'stance':                   '',
            'statement_text':           '',
            'statement_html':           '',
            'more_info_url':            '',
            'last_updated':             '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_manager = PositionEnteredManager()

    if positive_value_exists(office_we_vote_id):
        results = position_manager.retrieve_voter_contest_office_position_with_we_vote_id(
            voter_id, office_we_vote_id)

    elif positive_value_exists(candidate_we_vote_id):
        results = position_manager.retrieve_voter_candidate_campaign_position_with_we_vote_id(
            voter_id, candidate_we_vote_id)

    elif positive_value_exists(measure_we_vote_id):
        results = position_manager.retrieve_voter_contest_measure_position_with_we_vote_id(
            voter_id, measure_we_vote_id)

    # retrieve_position results
    # results = {
    #     'error_result':             error_result,
    #     'DoesNotExist':             exception_does_not_exist,
    #     'MultipleObjectsReturned':  exception_multiple_object_returned,
    #     'position_found':           True if position_id > 0 else False,
    #     'position_id':              position_id,
    #     'position':                 position_on_stage,
    #     'is_support':               position_on_stage.is_support(),
    #     'is_oppose':                position_on_stage.is_oppose(),
    #     'is_no_stance':             position_on_stage.is_no_stance(),
    #     'is_information_only':      position_on_stage.is_information_only(),
    #     'is_still_deciding':        position_on_stage.is_still_deciding(),
    # }

    if results['position_found']:
        position = results['position']
        json_data = {
            'success':                  True,
            'status':                   results['status'],
            'position_id':              position.id,
            'position_we_vote_id':      position.we_vote_id,
            'is_support':               results['is_support'],
            'is_oppose':                results['is_oppose'],
            'is_information_only':      results['is_information_only'],
            'google_civic_election_id': position.google_civic_election_id,
            'office_we_vote_id':        position.contest_office_we_vote_id,
            'candidate_we_vote_id':     position.candidate_campaign_we_vote_id,
            'measure_we_vote_id':       position.contest_measure_we_vote_id,
            'stance':                   position.stance,
            'statement_text':           position.statement_text,
            'statement_html':           position.statement_html,
            'more_info_url':            position.more_info_url,
            'last_updated':             '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status':                   results['status'],
            'success':                  False,
            'position_id':              0,
            'position_we_vote_id':      '',
            'is_support':               False,
            'is_oppose':                False,
            'is_information_only':      False,
            'google_civic_election_id': '',
            'office_we_vote_id':        '',
            'candidate_we_vote_id':     '',
            'measure_we_vote_id':       '',
            'stance':                   '',
            'statement_text':           '',
            'statement_html':           '',
            'more_info_url':            '',
            'last_updated':             '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #40
0
def voter_star_status_retrieve_for_api(voter_device_id, office_id,
                                       office_we_vote_id, candidate_id,
                                       candidate_we_vote_id, measure_id,
                                       measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'is_starred': False,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'is_starred': False,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    star_item_manager = StarItemManager()
    if positive_value_exists(office_id) or positive_value_exists(
            office_we_vote_id):
        contest_office_manager = ContestOfficeManager()
        # Since we can take in either office_id or office_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(office_id):
            office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(
                office_id)
        elif positive_value_exists(office_we_vote_id):
            office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(
                office_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        candidate_campaign_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       office_id,
                                                       candidate_campaign_id,
                                                       contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status': status,
            'success': success,
            'voter_device_id': voter_device_id,
            'is_starred': is_starred,
            'ballot_item_id': convert_to_int(office_id),
            'ballot_item_we_vote_id': office_we_vote_id,
            'kind_of_ballot_item': OFFICE,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
                candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
                candidate_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id,
                                                       candidate_id,
                                                       contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status': status,
            'success': success,
            'voter_device_id': voter_device_id,
            'is_starred': is_starred,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(
            measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        # Since we can take in either measure_id or measure_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(measure_id):
            measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
                measure_id)
        elif positive_value_exists(measure_we_vote_id):
            measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(
                measure_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        candidate_campaign_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id,
                                                       candidate_campaign_id,
                                                       measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status': status,
            'success': success,
            'voter_device_id': voter_device_id,
            'is_starred': is_starred,
            'ballot_item_id': convert_to_int(measure_id),
            'ballot_item_we_vote_id': measure_we_vote_id,
            'kind_of_ballot_item': MEASURE,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        status = 'UNABLE_TO_SAVE-OFFICE_ID_AND_CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False
        is_starred = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'is_starred': is_starred,
        'office_id': convert_to_int(office_id),
        'candidate_id': convert_to_int(candidate_id),
        'measure_id': convert_to_int(measure_id),
        'ballot_item_id': 0,
        'ballot_item_we_vote_id': '',
        'kind_of_ballot_item': '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
def quick_info_text_save_for_api(  # TODO to be converted
        voter_device_id, quick_info_id, quick_info_we_vote_id,
        google_civic_election_id, office_we_vote_id, candidate_we_vote_id,
        measure_we_vote_id, statement_text, statement_html):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data_from_results = results['json_data']
        json_data = {
            'status': json_data_from_results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
            'quick_info_id': quick_info_id,
            'quick_info_we_vote_id': quick_info_we_vote_id,
            'new_quick_info_created': False,
            'is_support': False,
            'is_oppose': False,
            'is_information_only': False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id': office_we_vote_id,
            'candidate_we_vote_id': candidate_we_vote_id,
            'measure_we_vote_id': measure_we_vote_id,
            'statement_text': statement_text,
            'statement_html': statement_html,
            'last_updated': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_manager = VoterManager()
    voter_results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    voter_id = voter_results['voter_id']
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
            'quick_info_id': quick_info_id,
            'quick_info_we_vote_id': quick_info_we_vote_id,
            'new_quick_info_created': False,
            'is_support': False,
            'is_oppose': False,
            'is_information_only': False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id': office_we_vote_id,
            'candidate_we_vote_id': candidate_we_vote_id,
            'measure_we_vote_id': measure_we_vote_id,
            'statement_text': statement_text,
            'statement_html': statement_html,
            'last_updated': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter = voter_results['voter']
    quick_info_id = convert_to_int(quick_info_id)
    quick_info_we_vote_id = quick_info_we_vote_id.strip().lower()

    existing_unique_identifier_found = positive_value_exists(quick_info_id) \
        or positive_value_exists(quick_info_we_vote_id)
    new_unique_identifier_found = positive_value_exists(voter_id) \
        and positive_value_exists(google_civic_election_id) and (
        positive_value_exists(office_we_vote_id) or
        positive_value_exists(candidate_we_vote_id) or
        positive_value_exists(measure_we_vote_id)
    )
    unique_identifier_found = existing_unique_identifier_found or new_unique_identifier_found
    # We must have these variables in order to create a new entry
    required_variables_for_new_entry = positive_value_exists(voter_id) \
        and positive_value_exists(google_civic_election_id) and (
        positive_value_exists(office_we_vote_id) or
        positive_value_exists(candidate_we_vote_id) or
        positive_value_exists(measure_we_vote_id)
    )
    if not unique_identifier_found:
        results = {
            'status':
            "QUICK_INFO_REQUIRED_UNIQUE_IDENTIFIER_VARIABLES_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'quick_info_id': quick_info_id,
            'quick_info_we_vote_id': quick_info_we_vote_id,
            'new_quick_info_created': False,
            'is_support': False,
            'is_oppose': False,
            'is_information_only': False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id': office_we_vote_id,
            'candidate_we_vote_id': candidate_we_vote_id,
            'measure_we_vote_id': measure_we_vote_id,
            'statement_text': statement_text,
            'statement_html': statement_html,
            'last_updated': '',
        }
        return results
    elif not existing_unique_identifier_found and not required_variables_for_new_entry:
        results = {
            'status': "NEW_QUICK_INFO_REQUIRED_VARIABLES_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'quick_info_id': quick_info_id,
            'quick_info_we_vote_id': quick_info_we_vote_id,
            'new_quick_info_created': False,
            'is_support': False,
            'is_oppose': False,
            'is_information_only': False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id': office_we_vote_id,
            'candidate_we_vote_id': candidate_we_vote_id,
            'measure_we_vote_id': measure_we_vote_id,
            'statement_text': statement_text,
            'statement_html': statement_html,
            'last_updated': '',
        }
        return results

    quick_info_manager = QuickInfoManager()
    save_results = quick_info_manager.update_or_create_quick_info(
        quick_info_id=quick_info_id,
        quick_info_we_vote_id=quick_info_we_vote_id,
        voter_we_vote_id=voter.we_vote_id,
        google_civic_election_id=google_civic_election_id,
        office_we_vote_id=office_we_vote_id,
        candidate_we_vote_id=candidate_we_vote_id,
        measure_we_vote_id=measure_we_vote_id,
        statement_text=statement_text,
        statement_html=statement_html,
    )

    if save_results['success']:
        quick_info = save_results['quick_info']
        results = {
            'success': save_results['success'],
            'status': save_results['status'],
            'voter_device_id': voter_device_id,
            'quick_info_id': quick_info.id,
            'quick_info_we_vote_id': quick_info.we_vote_id,
            'new_quick_info_created': save_results['new_quick_info_created'],
            'is_support': quick_info.is_support(),
            'is_oppose': quick_info.is_oppose(),
            'is_information_only': quick_info.is_information_only(),
            'google_civic_election_id': quick_info.google_civic_election_id,
            'office_we_vote_id': quick_info.contest_office_we_vote_id,
            'candidate_we_vote_id': quick_info.candidate_campaign_we_vote_id,
            'measure_we_vote_id': quick_info.contest_measure_we_vote_id,
            'statement_text': quick_info.statement_text,
            'statement_html': quick_info.statement_html,
            'last_updated': '',
        }
        return results
    else:
        results = {
            'success': False,
            'status': save_results['status'],
            'voter_device_id': voter_device_id,
            'quick_info_id': quick_info_id,
            'quick_info_we_vote_id': quick_info_we_vote_id,
            'new_quick_info_created': False,
            'is_support': False,
            'is_oppose': False,
            'is_information_only': False,
            'google_civic_election_id': google_civic_election_id,
            'office_we_vote_id': office_we_vote_id,
            'candidate_we_vote_id': candidate_we_vote_id,
            'measure_we_vote_id': measure_we_vote_id,
            'statement_text': statement_text,
            'statement_html': statement_html,
            'last_updated': '',
        }
        return results
Example #42
0
def twitter_sign_in_request_voter_info_for_api(voter_device_id,
                                               return_url,
                                               switch_accounts_if_needed=True):
    """
    twitterSignInRequestVoterInfo
    When here, the incoming voter_device_id should already be authenticated
    :param voter_device_id:
    :param return_url: Where to return the browser when sign in process is complete
    :param switch_accounts_if_needed:
    :return:
    """

    twitter_handle = ''
    twitter_handle_found = False
    tweepy_user_object = None
    twitter_user_object_found = False
    voter_info_retrieved = False
    switch_accounts = False

    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
            'twitter_handle': twitter_handle,
            'twitter_handle_found': twitter_handle_found,
            'voter_info_retrieved': voter_info_retrieved,
            'switch_accounts': switch_accounts,
            'return_url': return_url,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status': "VALID_VOTER_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'twitter_handle': twitter_handle,
            'twitter_handle_found': twitter_handle_found,
            'voter_info_retrieved': voter_info_retrieved,
            'switch_accounts': switch_accounts,
            'return_url': return_url,
        }
        return results

    voter = results['voter']

    auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
    auth.set_access_token(voter.twitter_access_token,
                          voter.twitter_access_secret)

    api = tweepy.API(auth)

    try:
        tweepy_user_object = api.me()
        twitter_json = tweepy_user_object._json

        success = True
        status = 'TWITTER_SIGN_IN_REQUEST_VOTER_INFO_SUCCESSFUL'
        twitter_handle = tweepy_user_object.screen_name
        twitter_handle_found = True
        twitter_user_object_found = True
    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_SIGN_IN_REQUEST_VOTER_INFO_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_REQUEST_VOTER_INFO_TWEEPY_ERROR: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            for one_error in error_dict:
                status += '[' + one_error['message'] + '] '

    if twitter_user_object_found:
        # We need to deal with these cases

        # 1) Does account already exist?
        results = voter_manager.retrieve_voter_by_twitter_id(
            tweepy_user_object.id)
        if results['voter_found'] and switch_accounts_if_needed:
            voter_found_with_twitter_id = results['voter']

            switch_accounts = True

            # Relink this voter_device_id to the original account
            voter_device_manager = VoterDeviceLinkManager()
            voter_device_link_results = voter_device_manager.retrieve_voter_device_link(
                voter_device_id)
            voter_device_link = voter_device_link_results['voter_device_link']

            update_voter_device_link_results = voter_device_manager.update_voter_device_link(
                voter_device_link, voter_found_with_twitter_id)
            if update_voter_device_link_results['voter_device_link_updated']:
                # Transfer access token and secret
                voter_found_with_twitter_id.twitter_access_token = voter.twitter_access_token
                voter_found_with_twitter_id.twitter_access_secret = voter.twitter_access_secret
                voter_found_with_twitter_id.save()

                status += "TWITTER_SIGN_IN-ALREADY_LINKED_TO_OTHER_ACCOUNT-TRANSFERRED "
                success = True
                save_user_results = voter_manager.save_twitter_user_values(
                    voter_found_with_twitter_id, tweepy_user_object)

                if save_user_results['success']:
                    voter_info_retrieved = True
                status += save_user_results['status']
            else:
                status = "TWITTER_SIGN_IN-ALREADY_LINKED_TO_OTHER_ACCOUNT-COULD_NOT_TRANSFER "
                success = False

        # 2) If account doesn't exist for this person, save
        else:
            save_user_results = voter_manager.save_twitter_user_values(
                voter, tweepy_user_object)

            if save_user_results['success']:
                voter_info_retrieved = True

    results = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'twitter_handle': twitter_handle,
        'twitter_handle_found': twitter_handle_found,
        'voter_info_retrieved': voter_info_retrieved,
        'switch_accounts': switch_accounts,
        'return_url': return_url,
    }
    return results
Example #43
0
def voter_ballot_items_retrieve_from_google_civic_for_api(
        voter_device_id, text_for_map_search='', use_test_election=False):
    """
    We are telling the server to explicitly reach out to the Google Civic API and retrieve the ballot items
    for this voter.
    """
    # Confirm that we have a Google Civic API Key (GOOGLE_CIVIC_API_KEY)
    if not positive_value_exists(GOOGLE_CIVIC_API_KEY):
        results = {
            'status': 'NO_GOOGLE_CIVIC_API_KEY',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Confirm that we have the URL where we retrieve voter ballots (VOTER_INFO_URL)
    if not positive_value_exists(VOTER_INFO_URL):
        results = {
            'status': 'MISSING VOTER_INFO_URL in config/environment_variables.json',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    google_civic_election_id = 0
    status = ''
    success = False
    election_date_text = ''
    election_description_text = ''
    election_data_retrieved = False
    polling_location_retrieved = False
    contests_retrieved = False
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(
            text_for_map_search, google_civic_election_id, use_test_election)

        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']
            election_date_text = one_ballot_json['election']['electionDay']
            election_description_text = one_ballot_json['election']['name']

            # We may receive some election data, but not all of the data we need
            if one_ballot_results['election_data_retrieved']:
                election_data_retrieved = True
                success = True

            if one_ballot_results['polling_location_retrieved']:
                polling_location_retrieved = True
                success = True

            if one_ballot_results['contests_retrieved']:
                contests_retrieved = True

                # Now that we know we have new ballot data, we need to delete prior ballot data for this election
                # because when we change voterAddress, we usually get different ballot items
                ballot_item_list_manager = BallotItemListManager()
                # We include a google_civic_election_id, so only the ballot info for this election is removed
                google_civic_election_id_to_delete = one_ballot_json['election']['id']  # '0' would mean "delete all"
                if positive_value_exists(google_civic_election_id_to_delete):
                    ballot_item_list_manager.delete_all_ballot_items_for_voter(
                        voter_id, google_civic_election_id_to_delete)

                # store_on_ballot... adds an entry to the BallotReturned table
                # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api
                store_one_ballot_results = store_one_ballot_from_google_civic_api(one_ballot_json, voter_id)
                if store_one_ballot_results['success']:
                    status += 'RETRIEVED_FROM_GOOGLE_CIVIC_AND_STORED_BALLOT_FOR_VOTER '
                    success = True
                    google_civic_election_id = store_one_ballot_results['google_civic_election_id']
                else:
                    status += 'UNABLE_TO-store_one_ballot_from_google_civic_api'
        elif 'error' in one_ballot_results['structured_json']:
            if one_ballot_results['structured_json']['error']['message'] == 'Election unknown':
                success = False  # It is only successful if new ballot data is retrieved.
            else:
                success = False
            status += "GOOGLE_CIVIC_API_ERROR: " + one_ballot_results['structured_json']['error']['message']

        else:
            status += 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status += 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    # If a google_civic_election_id was not returned, outside of this function we search again using a test election,
    # so that during our initial user testing, ballot data is returned in areas where elections don't currently exist

    results = {
        'success': success,
        'status': status,
        'voter_device_id': voter_device_id,
        'google_civic_election_id': google_civic_election_id,
        'text_for_map_search': text_for_map_search,
        'election_date_text': election_date_text,
        'election_description_text': election_description_text,
        'election_data_retrieved': election_data_retrieved,
        'polling_location_retrieved': polling_location_retrieved,
        'contests_retrieved': contests_retrieved,
    }
    return results
Example #44
0
def twitter_sign_in_request_access_token_for_api(voter_device_id,
                                                 incoming_request_token, incoming_oauth_verifier,
                                                 return_url):
    """
    twitterSignInRequestAccessToken
    After signing in and agreeing to the application's terms, the user is redirected back to the application with
    the same request token and another value, this time the OAuth verifier.

    Within this function we use
    1) the request token and
    2) request secret along with the
    3) OAuth verifier to get an access token, also from Twitter.
    :param voter_device_id:
    :param incoming_request_token:
    :param incoming_oauth_verifier:
    :param return_url: If a value is provided, return to this URL when the whole process is complete
    :return:
    """
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url':                   return_url,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status': "VALID_VOTER_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
        return results

    voter = results['voter']

    if not voter.twitter_request_token == incoming_request_token:
        results = {
            'status': "TWITTER_REQUEST_TOKEN_DOES_NOT_MATCH_STORED_VOTER_VALUE",
            'success': False,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
        return results

    twitter_access_token = ''
    twitter_access_token_secret = ''
    try:
        # We take the Request Token, Request Secret, and OAuth Verifier and request an access_token
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
        auth.request_token = {'oauth_token': voter.twitter_request_token,
                              'oauth_token_secret': voter.twitter_request_secret}
        auth.get_access_token(incoming_oauth_verifier)
        if positive_value_exists(auth.access_token) and positive_value_exists(auth.access_token_secret):
            twitter_access_token = auth.access_token
            twitter_access_token_secret = auth.access_token_secret

    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_REQUEST_ACCESS_TOKEN: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            count = 0
            # for one_error in error_dict:
            #     status += '[' + one_error[count] + '] '
            #     count += 1

    try:
        # We save these values in the Voter table
        if positive_value_exists(twitter_access_token) and positive_value_exists(twitter_access_token_secret):
            voter.twitter_access_token = twitter_access_token
            voter.twitter_access_secret = twitter_access_token_secret
            voter.save()

            success = True
            status = "TWITTER_ACCESS_TOKEN_RETRIEVED_AND_SAVED"
        else:
            success = False
            status = "TWITTER_ACCESS_TOKEN_NOT_RETRIEVED"
    except Exception as e:
        success = False
        status = "TWITTER_ACCESS_TOKEN_NOT_SAVED"

    if success:
        results = {
            'status':                           status,
            'success':                          True,
            'voter_device_id':                  voter_device_id,
            'access_token_and_secret_returned': True,
            'return_url':                       return_url,
        }
    else:
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
    return results
Example #45
0
def twitter_sign_in_request_access_token_for_api(voter_device_id,
                                                 incoming_request_token,
                                                 incoming_oauth_verifier,
                                                 return_url):
    """
    twitterSignInRequestAccessToken
    After signing in and agreeing to the application's terms, the user is redirected back to the application with
    the same request token and another value, this time the OAuth verifier.

    Within this function we use
    1) the request token and
    2) request secret along with the
    3) OAuth verifier to get an access token, also from Twitter.
    :param voter_device_id:
    :param incoming_request_token:
    :param incoming_oauth_verifier:
    :param return_url: If a value is provided, return to this URL when the whole process is complete
    :return:
    """
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success': False,
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(
        voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status': "VALID_VOTER_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
        return results

    voter = results['voter']

    if not voter.twitter_request_token == incoming_request_token:
        results = {
            'status':
            "TWITTER_REQUEST_TOKEN_DOES_NOT_MATCH_STORED_VOTER_VALUE",
            'success': False,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
        return results

    twitter_access_token = ''
    twitter_access_token_secret = ''
    try:
        # We take the Request Token, Request Secret, and OAuth Verifier and request an access_token
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY,
                                   TWITTER_CONSUMER_SECRET)
        auth.request_token = {
            'oauth_token': voter.twitter_request_token,
            'oauth_token_secret': voter.twitter_request_secret
        }
        auth.get_access_token(incoming_oauth_verifier)
        if positive_value_exists(auth.access_token) and positive_value_exists(
                auth.access_token_secret):
            twitter_access_token = auth.access_token
            twitter_access_token_secret = auth.access_token_secret

    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_REQUEST_ACCESS_TOKEN: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            count = 0
            # for one_error in error_dict:
            #     status += '[' + one_error[count] + '] '
            #     count += 1

    try:
        # We save these values in the Voter table
        if positive_value_exists(
                twitter_access_token) and positive_value_exists(
                    twitter_access_token_secret):
            voter.twitter_access_token = twitter_access_token
            voter.twitter_access_secret = twitter_access_token_secret
            voter.save()

            success = True
            status = "TWITTER_ACCESS_TOKEN_RETRIEVED_AND_SAVED"
        else:
            success = False
            status = "TWITTER_ACCESS_TOKEN_NOT_RETRIEVED"
    except Exception as e:
        success = False
        status = "TWITTER_ACCESS_TOKEN_NOT_SAVED"

    if success:
        results = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': True,
            'return_url': return_url,
        }
    else:
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'access_token_and_secret_returned': False,
            'return_url': return_url,
        }
    return results
Example #46
0
def positions_count_for_all_ballot_items_for_api(
        voter_device_id,
        google_civic_election_id=0,
        show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the a list of the support and oppose counts from the orgs, friends and
    public figures the voter follows
    """
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':
            "VALID_VOTER_DEVICE_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

    if not positive_value_exists(google_civic_election_id):
        # We must have an election id to proceed -- otherwise we don't know what ballot items to work with
        voter_device_link_manager = VoterDeviceLinkManager()
        voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
            voter_device_id)
        if voter_device_link_results['voter_device_link_found']:
            voter_device_link = voter_device_link_results['voter_device_link']
            if positive_value_exists(
                    voter_device_link.google_civic_election_id):
                google_civic_election_id = voter_device_link.google_civic_election_id
        if not positive_value_exists(google_civic_election_id):
            voter_address_manager = VoterAddressManager()
            voter_address_results = voter_address_manager.retrieve_address(
                0, voter_id)
            if voter_address_results['voter_address_found']:
                voter_address = voter_address_results['voter_address']
                if positive_value_exists(
                        voter_address.google_civic_election_id):
                    google_civic_election_id = voter_address.google_civic_election_id
        google_civic_election_id = convert_to_int(google_civic_election_id)

    if not positive_value_exists(google_civic_election_id):
        json_data = {
            'status':
            "GOOGLE_CIVIC_ELECTION_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

    follow_organization_list_manager = FollowOrganizationList()
    organizations_followed_by_voter = \
        follow_organization_list_manager.retrieve_follow_organization_by_voter_id_simple_id_array(voter_id)

    # Get a list of all candidates and measures from this election (in the active election)
    ballot_item_results = voter_ballot_items_retrieve_for_one_election_for_api(
        voter_device_id, voter_id, google_civic_election_id)
    ballot_item_list = ballot_item_results['ballot_item_list']

    # The list where we capture results
    ballot_item_list_results = []

    # ballot_item_list is populated with contest_office and contest_measure entries
    for one_ballot_item in ballot_item_list:
        # Retrieve all positions for each ballot item
        if one_ballot_item['kind_of_ballot_item'] == OFFICE:
            results = candidate_list_object.retrieve_all_candidates_for_office(
                0, one_ballot_item['we_vote_id'])
            success = results['success']
            candidate_list = results['candidate_list']

            if success:
                for candidate in candidate_list:
                    # Loop through all candidates under this office
                    support_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, SUPPORT)
                    oppose_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, OPPOSE)
                    finalize_results = finalize_support_and_oppose_positions_count(
                        voter_id, show_positions_this_voter_follows,
                        organizations_followed_by_voter,
                        support_positions_list_for_one_ballot_item,
                        oppose_positions_list_for_one_ballot_item)
                    one_ballot_item_results = {
                        'ballot_item_we_vote_id':
                        candidate.we_vote_id,
                        'support_count':
                        finalize_results['support_positions_count'],
                        'oppose_count':
                        finalize_results['oppose_positions_count'],
                    }
                    ballot_item_list_results.append(one_ballot_item_results)
        elif one_ballot_item['kind_of_ballot_item'] == MEASURE:
            support_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 SUPPORT)
            oppose_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 OPPOSE)
            finalize_results = finalize_support_and_oppose_positions_count(
                voter_id, show_positions_this_voter_follows,
                organizations_followed_by_voter,
                support_positions_list_for_one_ballot_item,
                oppose_positions_list_for_one_ballot_item)
            one_ballot_item_results = {
                'ballot_item_we_vote_id': one_ballot_item['we_vote_id'],
                'support_count': finalize_results['support_positions_count'],
                'oppose_count': finalize_results['oppose_positions_count'],
            }
            ballot_item_list_results.append(one_ballot_item_results)
        else:
            # Skip the rest of this loop
            continue

    json_data = {
        'success': True,
        'status': "POSITIONS_COUNT_FOR_ALL_BALLOT_ITEMS",
        'google_civic_election_id': google_civic_election_id,
        'ballot_item_list': ballot_item_list_results,
    }
    return json_data
Example #47
0
def twitter_sign_in_start_for_api(voter_device_id, return_url):  # twitterSignInStart
    """

    :param voter_device_id:
    :param return_url: Where to direct the browser at the very end of the process
    :return:
    """
    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success':              False,
            'status':               "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id':      voter_device_id,
            'twitter_redirect_url': '',
            'voter_info_retrieved': False,
            'switch_accounts':      False,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status':               "VALID_VOTER_MISSING",
            'success':              False,
            'voter_device_id':      voter_device_id,
            'twitter_redirect_url': '',
            'voter_info_retrieved': False,
            'switch_accounts':      False,
        }
        return results

    voter = results['voter']

    if voter.twitter_access_token and voter.twitter_access_secret:
        # If here the voter might already be signed in, so we don't want to ask them to approve again
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
        auth.set_access_token(voter.twitter_access_token, voter.twitter_access_secret)

        api = tweepy.API(auth)

        try:
            tweepy_user_object = api.me()
            success = True
        # What is the error situation where the twitter_access_token and twitter_access_secret are no longer valid?
        # We need to deal with this (wipe them from the database and rewind to the right place in the process
        except tweepy.RateLimitError:
            success = False
            status = 'TWITTER_RATE_LIMIT_ERROR'
        except tweepy.error.TweepError as error_instance:
            success = False
            status = ''
            error_tuple = error_instance.args
            for error_dict in error_tuple:
                for one_error in error_dict:
                    status += '[' + one_error['message'] + '] '

        if success:
            # Reach out to the twitterSignInRequestVoterInfo -- no need to redirect
            empty_return_url = ""
            voter_info_results = twitter_sign_in_request_voter_info_for_api(voter_device_id, empty_return_url)

            success = voter_info_results['success']
            status = "SKIPPED_AUTH_DIRECT_REQUEST_VOTER_INFO: " + voter_info_results['status']
            results = {
                'status':               status,
                'success':              success,
                'voter_device_id':      voter_device_id,
                'twitter_redirect_url': '',
                'voter_info_retrieved': voter_info_results['voter_info_retrieved'],
                'switch_accounts':      voter_info_results['switch_accounts'],  # If true, new voter_device_id returned
            }
            return results
        else:
            # Somehow reset tokens and start over.
            pass

    callback_url = WE_VOTE_SERVER_ROOT_URL + "/apis/v1/twitterSignInRequestAccessToken/"
    callback_url += "?voter_device_id=" + voter_device_id
    callback_url += "&return_url=" + return_url

    # This is where
    twitter_authorization_url = ''

    try:
        # We take the Consumer Key and the Consumer Secret, and request a token & token_secret
        auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, callback_url)
        twitter_authorization_url = auth.get_authorization_url()
        request_token_dict = auth.request_token
        twitter_request_token = ''
        twitter_request_token_secret = ''

        if 'oauth_token' in request_token_dict:
            twitter_request_token = request_token_dict['oauth_token']
        if 'oauth_token_secret' in request_token_dict:
            twitter_request_token_secret = request_token_dict['oauth_token_secret']

        # We save these values in the Voter table, and then return a twitter_authorization_url where the voter signs in
        # Once they sign in to the Twitter login, they are redirected back to the We Vote callback_url
        # On that callback_url page, we are told if they are signed in
        #  on Twitter or not, and capture an access key we can use to retrieve information about the Twitter user
        # NOTE: Regarding the callback url, I think this can just be a direct call to the API server,
        #  since we have the voter_device_id
        if positive_value_exists(twitter_request_token) and positive_value_exists(twitter_request_token_secret):
            voter.twitter_request_token = twitter_request_token
            voter.twitter_request_secret = twitter_request_token_secret
            voter.save()

            success = True
            status = "TWITTER_REDIRECT_URL_RETRIEVED"
        else:
            success = False
            status = "TWITTER_REDIRECT_URL_NOT_RETRIEVED"

    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_START: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            for one_error in error_dict:
                status += '[' + one_error['message'] + '] '

    if success:
        results = {
            'status':               status,
            'success':              True,
            'voter_device_id':      voter_device_id,
            'twitter_redirect_url': twitter_authorization_url,
            'voter_info_retrieved': False,
            'switch_accounts':      False,
        }
    else:
        results = {
            'status':               status,
            'success':              False,
            'voter_device_id':      voter_device_id,
            'twitter_redirect_url': '',
            'voter_info_retrieved': False,
            'switch_accounts':      False,
        }
    return results
Example #48
0
def positions_count_for_all_ballot_items_for_api(voter_device_id, google_civic_election_id=0,
                                                 show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the a list of the support and oppose counts from the orgs, friends and
    public figures the voter follows
    """
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':                   "VALID_VOTER_DEVICE_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success':                  False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list':         [],
        }
        return json_data

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':                   "VALID_VOTER_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success':                  False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list':         [],
        }
        return json_data

    if not positive_value_exists(google_civic_election_id):
        # We must have an election id to proceed -- otherwise we don't know what ballot items to work with
        voter_device_link_manager = VoterDeviceLinkManager()
        voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
        if voter_device_link_results['voter_device_link_found']:
            voter_device_link = voter_device_link_results['voter_device_link']
            if positive_value_exists(voter_device_link.google_civic_election_id):
                google_civic_election_id = voter_device_link.google_civic_election_id
        if not positive_value_exists(google_civic_election_id):
            voter_address_manager = VoterAddressManager()
            voter_address_results = voter_address_manager.retrieve_address(0, voter_id)
            if voter_address_results['voter_address_found']:
                voter_address = voter_address_results['voter_address']
                if positive_value_exists(voter_address.google_civic_election_id):
                    google_civic_election_id = voter_address.google_civic_election_id
        google_civic_election_id = convert_to_int(google_civic_election_id)

    if not positive_value_exists(google_civic_election_id):
        json_data = {
            'status':                   "GOOGLE_CIVIC_ELECTION_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success':                  False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list':         [],
        }
        return json_data

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

    follow_organization_list_manager = FollowOrganizationList()
    organizations_followed_by_voter = \
        follow_organization_list_manager.retrieve_follow_organization_by_voter_id_simple_id_array(voter_id)

    # Get a list of all candidates and measures from this election (in the active election)
    ballot_item_results = voter_ballot_items_retrieve_for_one_election_for_api(voter_device_id, voter_id,
                                                                               google_civic_election_id)
    ballot_item_list = ballot_item_results['ballot_item_list']

    # The list where we capture results
    ballot_item_list_results = []

    # ballot_item_list is populated with contest_office and contest_measure entries
    for one_ballot_item in ballot_item_list:
        # Retrieve all positions for each ballot item
        if one_ballot_item['kind_of_ballot_item'] == OFFICE:
            results = candidate_list_object.retrieve_all_candidates_for_office(0, one_ballot_item['we_vote_id'])
            success = results['success']
            candidate_list = results['candidate_list']

            if success:
                for candidate in candidate_list:
                    # Loop through all candidates under this office
                    support_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, SUPPORT)
                    oppose_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, OPPOSE)
                    finalize_results = finalize_support_and_oppose_positions_count(
                        voter_id, show_positions_this_voter_follows,
                        organizations_followed_by_voter,
                        support_positions_list_for_one_ballot_item,
                        oppose_positions_list_for_one_ballot_item)
                    one_ballot_item_results = {
                        'ballot_item_we_vote_id': candidate.we_vote_id,
                        'support_count': finalize_results['support_positions_count'],
                        'oppose_count': finalize_results['oppose_positions_count'],
                    }
                    ballot_item_list_results.append(one_ballot_item_results)
        elif one_ballot_item['kind_of_ballot_item'] == MEASURE:
            support_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 SUPPORT)
            oppose_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 OPPOSE)
            finalize_results = finalize_support_and_oppose_positions_count(
                voter_id, show_positions_this_voter_follows,
                organizations_followed_by_voter,
                support_positions_list_for_one_ballot_item,
                oppose_positions_list_for_one_ballot_item)
            one_ballot_item_results = {
                'ballot_item_we_vote_id': one_ballot_item['we_vote_id'],
                'support_count': finalize_results['support_positions_count'],
                'oppose_count': finalize_results['oppose_positions_count'],
            }
            ballot_item_list_results.append(one_ballot_item_results)
        else:
            # Skip the rest of this loop
            continue

    json_data = {
        'success':                  True,
        'status':                   "POSITIONS_COUNT_FOR_ALL_BALLOT_ITEMS",
        'google_civic_election_id': google_civic_election_id,
        'ballot_item_list':         ballot_item_list_results,
    }
    return json_data
Example #49
0
def twitter_sign_in_request_voter_info_for_api(voter_device_id, return_url, switch_accounts_if_needed=True):
    """
    twitterSignInRequestVoterInfo
    When here, the incoming voter_device_id should already be authenticated
    :param voter_device_id:
    :param return_url: Where to return the browser when sign in process is complete
    :param switch_accounts_if_needed:
    :return:
    """

    twitter_handle = ''
    twitter_handle_found = False
    tweepy_user_object = None
    twitter_user_object_found = False
    voter_info_retrieved = False
    switch_accounts = False

    # Get voter_id from the voter_device_id
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'success':              False,
            'status':               "VALID_VOTER_DEVICE_ID_MISSING",
            'voter_device_id':      voter_device_id,
            'twitter_handle':       twitter_handle,
            'twitter_handle_found': twitter_handle_found,
            'voter_info_retrieved': voter_info_retrieved,
            'switch_accounts':      switch_accounts,
            'return_url':           return_url,
        }
        return results

    voter_manager = VoterManager()
    results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
    if not positive_value_exists(results['voter_found']):
        results = {
            'status':               "VALID_VOTER_MISSING",
            'success':              False,
            'voter_device_id':      voter_device_id,
            'twitter_handle':       twitter_handle,
            'twitter_handle_found': twitter_handle_found,
            'voter_info_retrieved': voter_info_retrieved,
            'switch_accounts':      switch_accounts,
            'return_url':           return_url,
        }
        return results

    voter = results['voter']

    auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
    auth.set_access_token(voter.twitter_access_token, voter.twitter_access_secret)

    api = tweepy.API(auth)

    try:
        tweepy_user_object = api.me()
        twitter_json = tweepy_user_object._json

        success = True
        status = 'TWITTER_SIGN_IN_REQUEST_VOTER_INFO_SUCCESSFUL'
        twitter_handle = tweepy_user_object.screen_name
        twitter_handle_found = True
        twitter_user_object_found = True
    except tweepy.RateLimitError:
        success = False
        status = 'TWITTER_SIGN_IN_REQUEST_VOTER_INFO_RATE_LIMIT_ERROR'
    except tweepy.error.TweepError as error_instance:
        success = False
        status = 'TWITTER_SIGN_IN_REQUEST_VOTER_INFO_TWEEPY_ERROR: '
        error_tuple = error_instance.args
        for error_dict in error_tuple:
            for one_error in error_dict:
                status += '[' + one_error['message'] + '] '

    if twitter_user_object_found:
        # We need to deal with these cases

        # 1) Does account already exist?
        results = voter_manager.retrieve_voter_by_twitter_id(tweepy_user_object.id)
        if results['voter_found'] and switch_accounts_if_needed:
            voter_found_with_twitter_id = results['voter']

            switch_accounts = True

            # Relink this voter_device_id to the original account
            voter_device_manager = VoterDeviceLinkManager()
            voter_device_link_results = voter_device_manager.retrieve_voter_device_link(voter_device_id)
            voter_device_link = voter_device_link_results['voter_device_link']

            update_voter_device_link_results = voter_device_manager.update_voter_device_link(
                voter_device_link, voter_found_with_twitter_id)
            if update_voter_device_link_results['voter_device_link_updated']:
                # Transfer access token and secret
                voter_found_with_twitter_id.twitter_access_token = voter.twitter_access_token
                voter_found_with_twitter_id.twitter_access_secret = voter.twitter_access_secret
                voter_found_with_twitter_id.save()

                status += "TWITTER_SIGN_IN-ALREADY_LINKED_TO_OTHER_ACCOUNT-TRANSFERRED "
                success = True
                save_user_results = voter_manager.save_twitter_user_values(voter_found_with_twitter_id,
                                                                           tweepy_user_object)

                if save_user_results['success']:
                    voter_info_retrieved = True
                status += save_user_results['status']
            else:
                status = "TWITTER_SIGN_IN-ALREADY_LINKED_TO_OTHER_ACCOUNT-COULD_NOT_TRANSFER "
                success = False

        # 2) If account doesn't exist for this person, save
        else:
            save_user_results = voter_manager.save_twitter_user_values(voter, tweepy_user_object)

            if save_user_results['success']:
                voter_info_retrieved = True

    results = {
        'status':                       status,
        'success':                      success,
        'voter_device_id':              voter_device_id,
        'twitter_handle':               twitter_handle,
        'twitter_handle_found':         twitter_handle_found,
        'voter_info_retrieved':         voter_info_retrieved,
        'switch_accounts':              switch_accounts,
        'return_url':                   return_url,
    }
    return results
Example #50
0
def voter_supporting_save_for_api(voter_device_id, candidate_id, candidate_we_vote_id, measure_id, measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing, voterSupportingSave
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_entered_manager = PositionEnteredManager()
    if positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(candidate_we_vote_id)

        results = position_entered_manager.toggle_on_voter_support_for_candidate_campaign(voter_id, candidate_id)
        status = "SUPPORTING_CANDIDATE " + results['status']
        success = results['success']

        json_data = {
            'status':                   status,
            'success':                  success,
            'ballot_item_id':           convert_to_int(candidate_id),
            'ballot_item_we_vote_id':   candidate_we_vote_id,
            'kind_of_ballot_item':      CANDIDATE,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        # Since we can take in either measure_id or measure_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(measure_id):
            measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(measure_id)
        elif positive_value_exists(measure_we_vote_id):
            measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(measure_we_vote_id)

        results = position_entered_manager.toggle_on_voter_support_for_contest_measure(voter_id, measure_id)
        status = "SUPPORTING_MEASURE " + results['status']
        success = results['success']

        json_data = {
            'status':                   status,
            'success':                  success,
            'ballot_item_id':           convert_to_int(measure_id),
            'ballot_item_we_vote_id':   measure_we_vote_id,
            'kind_of_ballot_item':      MEASURE,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        status = 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
        'ballot_item_id':           0,
        'ballot_item_we_vote_id':   '',
        'kind_of_ballot_item':      '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #51
0
def voter_retrieve_list_for_api(voter_device_id):
    """
    This is used for voterExportView
    :param voter_device_id:
    :return:
    """
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results2 = {
            'success': False,
            'json_data': results['json_data'],
        }
        return results2

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id > 0:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        if results['voter_found']:
            voter_id = results['voter_id']
    else:
        # If we are here, the voter_id could not be found from the voter_device_id
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        results = {
            'success': False,
            'json_data': json_data,
        }
        return results

    if voter_id:
        voter_list = Voter.objects.all()
        voter_list = voter_list.filter(id=voter_id)

        if len(voter_list):
            results = {
                'success': True,
                'voter_list': voter_list,
            }
            return results

    # Trying to mimic the Google Civic error codes scheme
    errors_list = [{
        'domain': "TODO global",
        'reason': "TODO reason",
        'message': "TODO Error message here",
        'locationType': "TODO Error message here",
        'location': "TODO location",
    }]
    error_package = {
        'errors': errors_list,
        'code': 400,
        'message': "Error message here",
    }
    json_data = {
        'error': error_package,
        'status': "VOTER_ID_COULD_NOT_BE_RETRIEVED",
        'success': False,
        'voter_device_id': voter_device_id,
    }
    results = {
        'success': False,
        'json_data': json_data,
    }
    return results
Example #52
0
def voter_guides_to_follow_retrieve_for_api(
        voter_device_id,  # voterGuidesToFollow
        kind_of_ballot_item='',
        ballot_item_we_vote_id='',
        google_civic_election_id=0,
        search_string='',
        maximum_number_to_retrieve=0):
    # Get voter_id from the voter_device_id so we can figure out which voter_guides to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'ERROR_GUIDES_TO_FOLLOW_NO_VOTER_DEVICE_ID',
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
        }
        results = {
            'success': False,
            'google_civic_election_id':
            0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':
            "ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
        }
        results = {
            'success': False,
            'google_civic_election_id':
            0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results

    voter_guide_list = []
    voter_guides = []
    try:
        if positive_value_exists(
                kind_of_ballot_item) and positive_value_exists(
                    ballot_item_we_vote_id):
            results = retrieve_voter_guides_to_follow_by_ballot_item(
                voter_id, kind_of_ballot_item, ballot_item_we_vote_id,
                search_string)
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']
        elif positive_value_exists(google_civic_election_id):
            # This retrieve also does the reordering
            results = retrieve_voter_guides_to_follow_by_election_for_api(
                voter_id, google_civic_election_id, search_string,
                maximum_number_to_retrieve, 'twitter_followers_count', 'desc')
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']
        else:
            results = retrieve_voter_guides_to_follow_generic_for_api(
                voter_id, search_string, maximum_number_to_retrieve,
                'twitter_followers_count', 'desc')
            success = results['success']
            status = results['status']
            voter_guide_list = results['voter_guide_list']

    except Exception as e:
        status = 'FAILED voter_guides_to_follow_retrieve_for_api, retrieve_voter_guides_for_election ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        success = False

    if success:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        linked_organization_we_vote_id = ""
        if results['voter_found']:
            voter = results['voter']
            linked_organization_we_vote_id = voter.linked_organization_we_vote_id

        number_added_to_list = 0
        position_manager = PositionEnteredManager()
        position = PositionEntered()
        for voter_guide in voter_guide_list:
            if positive_value_exists(voter_guide.organization_we_vote_id) \
                    and linked_organization_we_vote_id == voter_guide.organization_we_vote_id:
                # Do not return your own voter guide to follow
                continue

            position_found = False
            one_voter_guide = {
                'we_vote_id':
                voter_guide.we_vote_id,
                'google_civic_election_id':
                voter_guide.google_civic_election_id,
                'time_span':
                voter_guide.vote_smart_time_span,
                'voter_guide_display_name':
                voter_guide.voter_guide_display_name(),
                'voter_guide_image_url':
                voter_guide.voter_guide_image_url(),
                'voter_guide_owner_type':
                voter_guide.voter_guide_owner_type,
                'organization_we_vote_id':
                voter_guide.organization_we_vote_id,
                'public_figure_we_vote_id':
                voter_guide.public_figure_we_vote_id,
                'twitter_description':
                voter_guide.twitter_description,
                'twitter_followers_count':
                voter_guide.twitter_followers_count,
                'twitter_handle':
                voter_guide.twitter_handle,
                'owner_voter_id':
                voter_guide.owner_voter_id,
                'last_updated':
                voter_guide.last_updated.strftime('%Y-%m-%d %H:%M'),
            }
            if positive_value_exists(ballot_item_we_vote_id):
                if kind_of_ballot_item == CANDIDATE:
                    organization_manager = OrganizationManager()
                    organization_id = organization_manager.fetch_organization_id(
                        voter_guide.organization_we_vote_id)
                    results = position_manager.retrieve_organization_candidate_campaign_position_with_we_vote_id(
                        organization_id, ballot_item_we_vote_id)
                    if results['position_found']:
                        position = results['position']
                        position_found = True
                elif kind_of_ballot_item == MEASURE:
                    organization_manager = OrganizationManager()
                    organization_id = organization_manager.fetch_organization_id(
                        voter_guide.organization_we_vote_id)
                    results = position_manager.retrieve_organization_contest_measure_position_with_we_vote_id(
                        organization_id, ballot_item_we_vote_id)
                    if results['position_found']:
                        position = results['position']
                        position_found = True

                if position_found:
                    one_voter_guide['is_support'] = position.is_support()
                    one_voter_guide[
                        'is_positive_rating'] = position.is_positive_rating()
                    one_voter_guide[
                        'is_support_or_positive_rating'] = position.is_support_or_positive_rating(
                        )
                    one_voter_guide['is_oppose'] = position.is_oppose()
                    one_voter_guide[
                        'is_negative_rating'] = position.is_negative_rating()
                    one_voter_guide[
                        'is_oppose_or_negative_rating'] = position.is_oppose_or_negative_rating(
                        )
                    one_voter_guide[
                        'is_information_only'] = position.is_information_only(
                        )
                    one_voter_guide[
                        'ballot_item_display_name'] = position.ballot_item_display_name
                    one_voter_guide[
                        'speaker_display_name'] = position.speaker_display_name
                    one_voter_guide['statement_text'] = position.statement_text
                    one_voter_guide['more_info_url'] = position.more_info_url
                    one_voter_guide[
                        'vote_smart_rating'] = position.vote_smart_rating
                    one_voter_guide[
                        'vote_smart_time_span'] = position.vote_smart_time_span

            voter_guides.append(one_voter_guide.copy())
            if positive_value_exists(maximum_number_to_retrieve):
                number_added_to_list += 1
                if number_added_to_list >= maximum_number_to_retrieve:
                    break

        if len(voter_guides):
            json_data = {
                'status': status + ' VOTER_GUIDES_TO_FOLLOW_RETRIEVED',
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guides': voter_guides,
                'google_civic_election_id': google_civic_election_id,
                'search_string': search_string,
                'ballot_item_we_vote_id': ballot_item_we_vote_id,
                'maximum_number_to_retrieve': maximum_number_to_retrieve,
            }
        else:
            json_data = {
                'status': status + ' NO_VOTER_GUIDES_FOUND',
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guides': voter_guides,
                'google_civic_election_id': google_civic_election_id,
                'search_string': search_string,
                'ballot_item_we_vote_id': ballot_item_we_vote_id,
                'maximum_number_to_retrieve': maximum_number_to_retrieve,
            }

        results = {
            'success': success,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results
    else:
        json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_guides': [],
            'google_civic_election_id': google_civic_election_id,
            'search_string': search_string,
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'maximum_number_to_retrieve': maximum_number_to_retrieve,
        }

        results = {
            'success': False,
            'google_civic_election_id':
            0,  # Force the reset of google_civic_election_id cookie
            'ballot_item_we_vote_id': ballot_item_we_vote_id,
            'json_data': json_data,
        }
        return results
Example #53
0
def voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):
    """

    :param voter_device_id:
    :param google_civic_election_id: This variable either was stored in a cookie, or passed in explicitly so we can
    get the ballot items related to that election.
    :return:
    """
    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results["success"]:
        json_data = {
            "status": "VALID_VOTER_DEVICE_ID_MISSING",
            "success": False,
            "voter_id": 0,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
        results = {
            "success": False,
            "json_data": json_data,
            "google_civic_election_id": 0,  # Force the clearing of google_civic_election_id
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            "status": "VALID_VOTER_ID_MISSING",
            "success": False,
            "voter_id": voter_id,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
        results = {
            "success": False,
            "json_data": json_data,
            "google_civic_election_id": 0,  # Force the clearing of google_civic_election_id
        }
        return results

    ballot_item_list_manager = BallotItemListManager()
    # If we get here without a google_civic_election_id, we need to choose one from the ballot items that are already
    #  stored. If we proceed to retrieve_all_ballot_items_for_voter without a google_civic_election_id, we will get
    #  ballot items from a variety of elections.
    # This logic looks for all of the elections we have ballot information for, and displays the most recent election
    #  (not counting the test election)
    if not positive_value_exists(google_civic_election_id):
        google_civic_election_id = ballot_item_list_manager.fetch_most_recent_google_civic_election_id()

    # If an election id STILL wasn't found, then we probably don't have any ballot items stored locally, so we
    #  need to go out to google civic. BUT we will proceed and attempt to retrieve ballot items without an election_id

    ballot_item_list = []
    ballot_items_to_display = []
    try:
        results = ballot_item_list_manager.retrieve_all_ballot_items_for_voter(voter_id, google_civic_election_id)
        success = results["success"]
        status = results["status"]
        ballot_item_list = results["ballot_item_list"]
    except Exception as e:
        status = "FAILED voter_ballot_items_retrieve. " "{error} [type: {error_type}]".format(
            error=e, error_type=type(e)
        )
        handle_exception(e, logger=logger, exception_message=status)
        success = False

    if success:
        for ballot_item in ballot_item_list:
            if ballot_item.contest_office_we_vote_id:
                kind_of_ballot_item = OFFICE
                ballot_item_id = ballot_item.contest_office_id
                we_vote_id = ballot_item.contest_office_we_vote_id
                try:
                    candidate_list_object = CandidateCampaignList()
                    results = candidate_list_object.retrieve_all_candidates_for_office(ballot_item_id, we_vote_id)
                    candidates_to_display = []
                    if results["candidate_list_found"]:
                        candidate_list = results["candidate_list"]
                        for candidate in candidate_list:
                            # This should match values returned in candidates_retrieve_for_api
                            one_candidate = {
                                "id": candidate.id,
                                "we_vote_id": candidate.we_vote_id,
                                "ballot_item_display_name": candidate.candidate_name,
                                "candidate_photo_url": candidate.fetch_photo_url(),
                                "order_on_ballot": candidate.order_on_ballot,
                                "kind_of_ballot_item": CANDIDATE,
                            }
                            candidates_to_display.append(one_candidate.copy())
                except Exception as e:
                    # status = 'FAILED candidates_retrieve. ' \
                    #          '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
                    candidates_to_display = []
                one_ballot_item = {
                    "ballot_item_display_name": ballot_item.ballot_item_display_name,
                    "google_civic_election_id": ballot_item.google_civic_election_id,
                    "google_ballot_placement": ballot_item.google_ballot_placement,
                    "local_ballot_order": ballot_item.local_ballot_order,
                    "kind_of_ballot_item": kind_of_ballot_item,
                    "id": ballot_item_id,
                    "we_vote_id": we_vote_id,
                    "candidate_list": candidates_to_display,
                }
                ballot_items_to_display.append(one_ballot_item.copy())
            elif ballot_item.contest_measure_we_vote_id:
                kind_of_ballot_item = MEASURE
                ballot_item_id = ballot_item.contest_measure_id
                we_vote_id = ballot_item.contest_measure_we_vote_id
                one_ballot_item = {
                    "ballot_item_display_name": ballot_item.ballot_item_display_name,
                    "google_civic_election_id": ballot_item.google_civic_election_id,
                    "google_ballot_placement": ballot_item.google_ballot_placement,
                    "local_ballot_order": ballot_item.local_ballot_order,
                    "kind_of_ballot_item": kind_of_ballot_item,
                    "id": ballot_item_id,
                    "we_vote_id": we_vote_id,
                }
                ballot_items_to_display.append(one_ballot_item.copy())

        json_data = {
            "status": "VOTER_BALLOT_ITEMS_RETRIEVED",
            "success": True,
            "voter_device_id": voter_device_id,
            "ballot_item_list": ballot_items_to_display,
            "google_civic_election_id": google_civic_election_id,
        }
    else:
        json_data = {
            "status": status,
            "success": False,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
    results = {
        "success": success,
        "google_civic_election_id": google_civic_election_id,  # We want to save google_civic_election_id in cookie
        "json_data": json_data,
    }
    return results
Example #54
0
def voter_star_status_retrieve_for_api(voter_device_id,
                                       office_id, office_we_vote_id,
                                       candidate_id, candidate_we_vote_id,
                                       measure_id, measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':                   'VALID_VOTER_DEVICE_ID_MISSING',
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'is_starred':               False,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':                   "VALID_VOTER_ID_MISSING",
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'is_starred':               False,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    star_item_manager = StarItemManager()
    if positive_value_exists(office_id) or positive_value_exists(office_we_vote_id):
        contest_office_manager = ContestOfficeManager()
        # Since we can take in either office_id or office_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(office_id):
            office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(office_id)
        elif positive_value_exists(office_we_vote_id):
            office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(office_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        candidate_campaign_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id, office_id,
                                                       candidate_campaign_id, contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status':                   status,
            'success':                  success,
            'voter_device_id':          voter_device_id,
            'is_starred':               is_starred,
            'ballot_item_id':           convert_to_int(office_id),
            'ballot_item_we_vote_id':   office_we_vote_id,
            'kind_of_ballot_item':      OFFICE,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(candidate_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id, contest_office_id, candidate_id,
                                                       contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status':                   status,
            'success':                  success,
            'voter_device_id':          voter_device_id,
            'is_starred':               is_starred,
            'ballot_item_id':           convert_to_int(candidate_id),
            'ballot_item_we_vote_id':   candidate_we_vote_id,
            'kind_of_ballot_item':      CANDIDATE,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        # Since we can take in either measure_id or measure_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(measure_id):
            measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(measure_id)
        elif positive_value_exists(measure_we_vote_id):
            measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(measure_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        candidate_campaign_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id, contest_office_id, candidate_campaign_id,
                                                       measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status':                   status,
            'success':                  success,
            'voter_device_id':          voter_device_id,
            'is_starred':               is_starred,
            'ballot_item_id':           convert_to_int(measure_id),
            'ballot_item_we_vote_id':   measure_we_vote_id,
            'kind_of_ballot_item':      MEASURE,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        status = 'UNABLE_TO_SAVE-OFFICE_ID_AND_CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False
        is_starred = False

    json_data = {
        'status':                   status,
        'success':                  success,
        'voter_device_id':          voter_device_id,
        'is_starred':               is_starred,
        'office_id':                convert_to_int(office_id),
        'candidate_id':             convert_to_int(candidate_id),
        'measure_id':               convert_to_int(measure_id),
        'ballot_item_id':           0,
        'ballot_item_we_vote_id':   '',
        'kind_of_ballot_item':      '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')