示例#1
0
    def retrieve_address(self, voter_address_id, voter_id=0, address_type=''):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        voter_address_on_stage = VoterAddress()
        voter_address_has_value = False

        if not positive_value_exists(address_type):
            # Provide a default
            address_type = BALLOT_ADDRESS

        try:
            if positive_value_exists(voter_address_id):
                voter_address_on_stage = VoterAddress.objects.get(id=voter_address_id)
                voter_address_id = voter_address_on_stage.id
                voter_address_found = True
                status = "VOTER_ADDRESS_FOUND_BY_ID"
                success = True
                voter_address_has_value = True if positive_value_exists(voter_address_on_stage.text_for_map_search) \
                    else False
            elif positive_value_exists(voter_id) and address_type in (BALLOT_ADDRESS, MAILING_ADDRESS,
                                                                      FORMER_BALLOT_ADDRESS):
                voter_address_on_stage = VoterAddress.objects.get(voter_id=voter_id, address_type=address_type)
                # If still here, we found an existing address
                voter_address_id = voter_address_on_stage.id
                voter_address_found = True
                status = "VOTER_ADDRESS_FOUND_BY_VOTER_ID_AND_ADDRESS_TYPE"
                success = True
                voter_address_has_value = True if positive_value_exists(voter_address_on_stage.text_for_map_search) \
                    else False
            else:
                voter_address_found = False
                status = "VOTER_ADDRESS_NOT_FOUND-MISSING_REQUIRED_VARIABLES"
                success = False
        except VoterAddress.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            status = "VOTER_ADDRESS_MULTIPLE_OBJECTS_RETURNED"
            exception_multiple_object_returned = True
            success = False
            voter_address_found = False
        except VoterAddress.DoesNotExist:
            error_result = True
            status = "VOTER_ADDRESS_DOES_NOT_EXIST"
            exception_does_not_exist = True
            success = True
            voter_address_found = False

        results = {
            'success':                  success,
            'status':                   status,
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'voter_address_found':      voter_address_found,
            'voter_address_has_value':  voter_address_has_value,
            'voter_address_id':         voter_address_id,
            'voter_address':            voter_address_on_stage,
        }
        return results
示例#2
0
    def save_new_voter_device_link(self, voter_device_id, voter_id):
        error_result = False
        exception_record_not_saved = False
        missing_required_variables = False
        voter_device_link_on_stage = VoterDeviceLink()
        voter_device_link_id = 0

        try:
            if positive_value_exists(voter_device_id) and positive_value_exists(voter_id):
                voter_device_link_on_stage.voter_device_id = voter_device_id
                voter_device_link_on_stage.voter_id = voter_id
                voter_device_link_on_stage.save()

                voter_device_link_id = voter_device_link_on_stage.id
            else:
                missing_required_variables = True
                voter_device_link_id = 0
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            error_result = True
            exception_record_not_saved = True

        results = {
            'error_result':                 error_result,
            'missing_required_variables':   missing_required_variables,
            'RecordNotSaved':               exception_record_not_saved,
            'voter_device_link_created':    True if voter_device_link_id > 0 else False,
            'voter_device_link':            voter_device_link_on_stage,
        }
        return results
示例#3
0
    def retrieve_daily_summaries(self, kind_of_action="", google_civic_election_id=0):
        # Start with today and cycle backwards in time
        daily_summaries = []
        day_on_stage = date.today()  # TODO: We need to work out the timezone questions
        number_found = 0
        maximum_attempts = 30
        attempt_count = 0

        try:
            # Limit the number of times this runs to EITHER 1) 5 positive numbers
            #  OR 2) 30 days in the past, whichever comes first
            while number_found <= 5 and attempt_count <= maximum_attempts:
                attempt_count += 1
                counter_queryset = GoogleCivicApiCounter.objects.all()
                if positive_value_exists(kind_of_action):
                    counter_queryset = counter_queryset.filter(kind_of_action=kind_of_action)
                if positive_value_exists(google_civic_election_id):
                    counter_queryset = counter_queryset.filter(google_civic_election_id=google_civic_election_id)

                # Find the number of these entries on that particular day
                counter_queryset = counter_queryset.filter(datetime_of_action__contains=day_on_stage)
                api_call_count = len(counter_queryset)

                # If any api calls were found on that date, pass it out for display
                if positive_value_exists(api_call_count):
                    daily_summary = {"date_string": day_on_stage, "count": api_call_count}
                    daily_summaries.append(daily_summary)
                    number_found += 1

                day_on_stage -= timedelta(days=1)
        except Exception:
            pass

        return daily_summaries
示例#4
0
    def save_facebook_user_values(self, voter, facebook_id, facebook_email=''):
        try:
            if facebook_id == 0:
                voter.facebook_id = 0
            elif positive_value_exists(facebook_id):
                voter.facebook_id = facebook_id

            if facebook_email == '' or facebook_email is False:
                voter.facebook_email = ''
            elif positive_value_exists(facebook_email):
                voter.facebook_email = facebook_email

            voter.save()
            success = True
            status = "SAVED_VOTER_FACEBOOK_VALUES"
        except Exception as e:
            status = "UNABLE_TO_SAVE_VOTER_FACEBOOK_VALUES"
            success = False
            handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        results = {
            'status':   status,
            'success':  success,
            'voter':    voter,
        }
        return results
示例#5
0
    def retrieve_ballot_item_for_voter(self, voter_id, google_civic_election_id, google_civic_district_ocd_id):
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        google_civic_ballot_item_on_stage = BallotItem()
        google_civic_ballot_item_id = 0

        if positive_value_exists(voter_id) and positive_value_exists(google_civic_election_id) and \
                positive_value_exists(google_civic_district_ocd_id):
            try:
                google_civic_ballot_item_on_stage = BallotItem.objects.get(
                    voter_id__exact=voter_id,
                    google_civic_election_id__exact=google_civic_election_id,
                    district_ocd_id=google_civic_district_ocd_id,  # TODO This needs to be rethunk
                )
                google_civic_ballot_item_id = google_civic_ballot_item_on_stage.id
            except BallotItem.MultipleObjectsReturned as e:
                handle_record_found_more_than_one_exception(e, logger=logger)
                exception_multiple_object_returned = True
            except BallotItem.DoesNotExist:
                exception_does_not_exist = True

        results = {
            'success':                          True if google_civic_ballot_item_id > 0 else False,
            'DoesNotExist':                     exception_does_not_exist,
            'MultipleObjectsReturned':          exception_multiple_object_returned,
            'google_civic_ballot_item':         google_civic_ballot_item_on_stage,
        }
        return results
示例#6
0
def positions_public_count_for_contest_measure(measure_id, measure_we_vote_id, stance_we_are_looking_for):
    """
    We want to return a JSON file with the number of orgs and public figures who support
    this particular measure
    """
    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListManager()
    all_positions_count_for_contest_measure = \
        position_list_manager.retrieve_public_positions_count_for_contest_measure(
            measure_id, measure_we_vote_id, stance_we_are_looking_for)

    if 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)

    json_data = {
        'status':                   'SUCCESSFUL_RETRIEVE_OF_PUBLIC_POSITION_COUNT_FOR_CONTEST_MEASURE',
        'success':                  True,
        'count':                    all_positions_count_for_contest_measure,
        'ballot_item_id':           convert_to_int(measure_id),
        'ballot_item_we_vote_id':   measure_we_vote_id,
        'kind_of_ballot_item':      MEASURE,
    }
    results = {
        'json_data': json_data,
    }
    return results
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')
示例#8
0
def retrieve_candidate_photos_for_election_view(request, election_id):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    google_civic_election_id = convert_to_int(election_id)

    # We only want to process if a google_civic_election_id comes in
    if not positive_value_exists(google_civic_election_id):
        messages.add_message(request, messages.ERROR, "Google Civic Election ID required.")
        return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))

    try:
        candidate_list = CandidateCampaign.objects.order_by('candidate_name')
        if positive_value_exists(google_civic_election_id):
            candidate_list = candidate_list.filter(google_civic_election_id=google_civic_election_id)
    except CandidateCampaign.DoesNotExist:
        pass

    display_messages = False
    force_retrieve = False
    # Loop through all of the candidates in this election
    for we_vote_candidate in candidate_list:
        retrieve_candidate_results = retrieve_candidate_photos(we_vote_candidate, force_retrieve)

        if retrieve_candidate_results['status'] and display_messages:
            messages.add_message(request, messages.INFO, retrieve_candidate_results['status'])

    return HttpResponseRedirect(reverse('candidate:candidate_list', args=()) + "?google_civic_election_id={var}".format(
        var=google_civic_election_id))
    def toggle_off_voter_position_like(self, position_like_id, voter_id,
                                       position_entered_id):
        if positive_value_exists(position_like_id):
            try:
                PositionLike.objects.filter(id=position_like_id).delete()
                status = "DELETED_BY_POSITION_LIKE_ID"
                success = True
            except Exception as e:
                status = "UNABLE_TO_DELETE_BY_POSITION_LIKE_ID: {error}".format(
                    error=e)
                success = False
        elif positive_value_exists(voter_id) and positive_value_exists(
                position_entered_id):
            try:
                PositionLike.objects.filter(
                    voter_id=voter_id,
                    position_entered_id=position_entered_id).delete()
                status = "DELETED_BY_VOTER_ID_AND_POSITION_ENTERED_ID"
                success = True
            except Exception as e:
                status = "UNABLE_TO_DELETE_BY_VOTER_ID_AND_POSITION_ENTERED_ID: {error}".format(
                    error=e)
                success = False
        else:
            status = "UNABLE_TO_DELETE_NO_VARIABLES"
            success = False

        results = {
            'status': status,
            'success': success,
        }
        return results
示例#10
0
def voter_ballot_items_retrieve_view(request):
    """
    (voterBallotItemsRetrieve) Request a skeleton of ballot data for this voter location,
    so that the web_app has all of the ids it needs to make more requests for data about each ballot item.
    :param request:
    :return:
    """
    voter_device_id = get_voter_device_id(request)  # We look in the cookies for voter_device_id
    # If passed in, we want to look at
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    use_test_election = request.GET.get('use_test_election', False)
    use_test_election = False if use_test_election == 'false' else use_test_election
    use_test_election = False if use_test_election == 'False' else use_test_election

    if positive_value_exists(use_test_election):
        google_civic_election_id = 2000  # The Google Civic API Test election
    elif not positive_value_exists(google_civic_election_id):
        # We look in the cookies for google_civic_election_id
        google_civic_election_id = get_google_civic_election_id_from_cookie(request)

    # This 'voter_ballot_items_retrieve_for_api' lives in apis_v1/controllers.py
    results = voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id)
    response = HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    # Save google_civic_election_id in the cookie so the interface knows
    google_civic_election_id_from_ballot_retrieve = results['google_civic_election_id']
    if positive_value_exists(google_civic_election_id_from_ballot_retrieve):
        set_google_civic_election_id_cookie(request, response, results['google_civic_election_id'])

    return response
示例#11
0
    def toggle_off_voter_position_like(self, position_like_id, voter_id, position_entered_id):
        if positive_value_exists(position_like_id):
            try:
                PositionLike.objects.filter(id=position_like_id).delete()
                status = "DELETED_BY_POSITION_LIKE_ID"
                success = True
            except Exception as e:
                status = "UNABLE_TO_DELETE_BY_POSITION_LIKE_ID: {error}".format(
                    error=e
                )
                success = False
        elif positive_value_exists(voter_id) and positive_value_exists(position_entered_id):
            try:
                PositionLike.objects.filter(voter_id=voter_id, position_entered_id=position_entered_id).delete()
                status = "DELETED_BY_VOTER_ID_AND_POSITION_ENTERED_ID"
                success = True
            except Exception as e:
                status = "UNABLE_TO_DELETE_BY_VOTER_ID_AND_POSITION_ENTERED_ID: {error}".format(
                    error=e
                )
                success = False
        else:
            status = "UNABLE_TO_DELETE_NO_VARIABLES"
            success = False

        results = {
            'status':   status,
            'success':  success,
        }
        return results
示例#12
0
def refresh_existing_voter_guides_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_guide_updated_count = 0

    # Cycle through existing voter_guides
    voter_guide_list_manager = VoterGuideListManager()
    voter_guide_manager = VoterGuideManager()
    results = voter_guide_list_manager.retrieve_all_voter_guides()
    if results['voter_guide_list_found']:
        voter_guide_list = results['voter_guide_list']
        for voter_guide in voter_guide_list:
            if positive_value_exists(voter_guide.organization_we_vote_id):
                if positive_value_exists(voter_guide.google_civic_election_id):
                    results = voter_guide_manager.update_or_create_organization_voter_guide_by_election_id(
                        voter_guide.organization_we_vote_id, voter_guide.google_civic_election_id)
                    if results['success']:
                        voter_guide_updated_count += 1
                elif positive_value_exists(voter_guide.vote_smart_time_span):
                    results = voter_guide_manager.update_or_create_organization_voter_guide_by_time_span(
                        voter_guide.organization_we_vote_id, voter_guide.vote_smart_time_span)
                    if results['success']:
                        voter_guide_updated_count += 1

    messages.add_message(request, messages.INFO,
                         '{voter_guide_updated_count} updated.'.format(
                             voter_guide_updated_count=voter_guide_updated_count,
                         ))
    return HttpResponseRedirect(reverse('voter_guide:voter_guide_list', args=()))
示例#13
0
def admin_home_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # Create a voter_device_id and voter in the database if one doesn't exist yet
    results = voter_setup(request)
    voter_api_device_id = results['voter_api_device_id']
    store_new_voter_api_device_id_in_cookie = results[
        'store_new_voter_api_device_id_in_cookie']

    google_civic_election_id = convert_to_int(
        request.GET.get('google_civic_election_id', 0))

    template_values = {
        'google_civic_election_id': google_civic_election_id,
    }
    response = render(request, 'admin_tools/index.html', template_values)

    # We want to store the voter_api_device_id cookie if it is new
    if positive_value_exists(voter_api_device_id) and positive_value_exists(
            store_new_voter_api_device_id_in_cookie):
        set_voter_api_device_id(request, response, voter_api_device_id)

    return response
示例#14
0
def refresh_twitter_candidate_details_for_election(google_civic_election_id):
    twitter_handles_added = 0
    profiles_refreshed_with_twitter_data = 0

    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_list_manager = CandidateCampaignListManager()
    return_list_of_objects = True
    candidates_results = candidate_list_manager.retrieve_all_candidates_for_upcoming_election(
        google_civic_election_id, return_list_of_objects)
    if candidates_results['candidate_list_found']:
        candidate_list = candidates_results['candidate_list_objects']

        for candidate in candidate_list:
            # Extract twitter_handle from google_civic_election information
            if positive_value_exists(candidate.twitter_url) \
                    and not positive_value_exists(candidate.candidate_twitter_handle):
                # If we got a twitter_url from Google Civic, and we haven't already stored a twitter handle, move it
                candidate.candidate_twitter_handle = extract_twitter_handle_from_text_string(candidate.twitter_url)
                candidate.save()
                twitter_handles_added += 1
            if positive_value_exists(candidate.candidate_twitter_handle):
                refresh_twitter_candidate_details(candidate)
                profiles_refreshed_with_twitter_data += 1

    status = "CANDIDATE_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success':                              True,
        'status':                               status,
        'twitter_handles_added':                twitter_handles_added,
        'profiles_refreshed_with_twitter_data': profiles_refreshed_with_twitter_data,
    }
    return results
示例#15
0
    def save_twitter_user_values(self, voter, twitter_user_object):
        try:
            # 'id': 132728535,
            if positive_value_exists(twitter_user_object.id):
                voter.twitter_id = twitter_user_object.id
            # 'id_str': '132728535',
            # 'utc_offset': 32400,
            # 'description': "Cars, Musics, Games, Electronics, toys, food, etc... I'm just a typical boy!",
            # 'profile_image_url': 'http://a1.twimg.com/profile_images/1213351752/_2_2__normal.jpg',
            if positive_value_exists(twitter_user_object.profile_image_url_https):
                voter.twitter_profile_image_url_https = twitter_user_object.profile_image_url_https
            # 'profile_background_image_url': 'http://a2.twimg.com/a/1294785484/images/themes/theme15/bg.png',
            # 'screen_name': 'jaeeeee',
            if positive_value_exists(twitter_user_object.screen_name):
                voter.twitter_screen_name = twitter_user_object.screen_name
            # 'lang': 'en',
            # 'name': 'Jae Jung Chung',
            # 'url': 'http://www.carbonize.co.kr',
            # 'time_zone': 'Seoul',
            voter.save()
            success = True
            status = "SAVED_VOTER_TWITTER_VALUES"
        except Exception as e:
            status = "UNABLE_TO_SAVE_VOTER_TWITTER_VALUES"
            success = False
            handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        results = {
            'status':   status,
            'success':  success,
            'voter':    voter,
        }
        return results
示例#16
0
    def update_voter_guide_social_media_statistics(self, organization):
        """
        Update voter_guide entry with details retrieved from Twitter, Facebook, or ???
        """
        success = False
        status = "ENTERING_UPDATE_VOTER_GUIDE_SOCIAL_MEDIA_STATISTICS"
        values_changed = False
        voter_guide = VoterGuide()

        if organization:
            if positive_value_exists(organization.twitter_followers_count):
                results = self.retrieve_most_recent_voter_guide_for_org(organization_we_vote_id=organization.we_vote_id)

                if results['voter_guide_found']:
                    voter_guide = results['voter_guide']
                    if positive_value_exists(voter_guide.id):
                        if voter_guide.twitter_followers_count != organization.twitter_followers_count:
                            voter_guide.twitter_followers_count = organization.twitter_followers_count
                            values_changed = True

            if positive_value_exists(values_changed):
                voter_guide.save()
                success = True
                status = "SAVED_ORG_TWITTER_DETAILS"
            else:
                success = True
                status = "NO_CHANGES_SAVED_TO_ORG_TWITTER_DETAILS"

        results = {
            'success':                  success,
            'status':                   status,
            'organization':             organization,
            'voter_guide':              voter_guide,
        }
        return results
示例#17
0
def quick_info_master_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
    language = request.GET.get('language', ENGLISH)

    quick_info_master_list = QuickInfoMaster.objects.order_by(
        'id')  # This order_by is temp
    if positive_value_exists(kind_of_ballot_item):
        quick_info_master_list = quick_info_master_list.filter(
            kind_of_ballot_item=kind_of_ballot_item)
    if positive_value_exists(language):
        quick_info_master_list = quick_info_master_list.filter(
            language=language)

    template_values = {
        'messages_on_stage': messages_on_stage,
        'quick_info_master_list': quick_info_master_list,
        'language_choices': LANGUAGE_CHOICES,
        'ballot_item_choices': KIND_OF_BALLOT_ITEM_CHOICES,
        'kind_of_ballot_item': kind_of_ballot_item,
        'language': language,
    }
    return render(request, 'quick_info/quick_info_master_list.html',
                  template_values)
示例#18
0
def refresh_existing_voter_guides_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_guide_updated_count = 0

    # Cycle through existing voter_guides
    voter_guide_list_manager = VoterGuideListManager()
    voter_guide_manager = VoterGuideManager()
    results = voter_guide_list_manager.retrieve_all_voter_guides()
    if results['voter_guide_list_found']:
        voter_guide_list = results['voter_guide_list']
        for voter_guide in voter_guide_list:
            if positive_value_exists(voter_guide.organization_we_vote_id):
                if positive_value_exists(voter_guide.google_civic_election_id):
                    results = voter_guide_manager.update_or_create_organization_voter_guide_by_election_id(
                        voter_guide.organization_we_vote_id,
                        voter_guide.google_civic_election_id)
                    if results['success']:
                        voter_guide_updated_count += 1
                elif positive_value_exists(voter_guide.vote_smart_time_span):
                    results = voter_guide_manager.update_or_create_organization_voter_guide_by_time_span(
                        voter_guide.organization_we_vote_id,
                        voter_guide.vote_smart_time_span)
                    if results['success']:
                        voter_guide_updated_count += 1

    messages.add_message(
        request, messages.INFO, '{voter_guide_updated_count} updated.'.format(
            voter_guide_updated_count=voter_guide_updated_count, ))
    return HttpResponseRedirect(
        reverse('voter_guide:voter_guide_list', args=()))
示例#19
0
def voter_authenticate_manually_view(request):
    messages_on_stage = get_messages(request)

    voter_api_device_id = get_voter_api_device_id(
        request)  # We look in the cookies for voter_api_device_id
    store_new_voter_api_device_id_in_cookie = False
    if not positive_value_exists(voter_api_device_id):
        # Create a voter_device_id and voter in the database if one doesn't exist yet
        results = voter_setup(request)
        voter_api_device_id = results['voter_api_device_id']
        store_new_voter_api_device_id_in_cookie = results[
            'store_new_voter_api_device_id_in_cookie']

    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    voter_id = convert_to_int(voter_id)
    voter_on_stage_found = False
    voter_on_stage = Voter()
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        voter_on_stage_found = True
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Voter.DoesNotExist:
        # This is fine, we will display an error
        pass

    if voter_on_stage_found:
        set_this_voter_as_admin = "UPDATE voter_voter SET is_admin=True WHERE id={voter_id};".format(
            voter_id=voter_id)
        unset_this_voter_as_admin = "UPDATE voter_voter SET is_admin=False WHERE id={voter_id};".format(
            voter_id=voter_id)

        set_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=True WHERE id={voter_id};" \
                                    "".format(voter_id=voter_id)
        unset_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=False WHERE id={voter_id};" \
                                      "".format(voter_id=voter_id)
        template_values = {
            'messages_on_stage': messages_on_stage,
            'voter': voter_on_stage,
            'voter_api_device_id': voter_api_device_id,
            'is_authenticated': request.user.is_authenticated(),
            'set_this_voter_as_admin': set_this_voter_as_admin,
            'unset_this_voter_as_admin': unset_this_voter_as_admin,
            'set_as_verified_volunteer': set_as_verified_volunteer,
            'unset_as_verified_volunteer': unset_as_verified_volunteer,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
        }
    response = render(request, 'voter/voter_authenticate_manually.html',
                      template_values)

    # We want to store the voter_api_device_id cookie if it is new
    # if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
    # DALE 2016-02-15 Always set if we have a voter_api_device_id
    if positive_value_exists(store_new_voter_api_device_id_in_cookie):
        set_voter_api_device_id(request, response, voter_api_device_id)

    return response
示例#20
0
def positions_public_count_for_api(candidate_id, candidate_we_vote_id,
                                   measure_id, measure_we_vote_id,
                                   stance_we_are_looking_for):
    if positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        results = positions_public_count_for_candidate_campaign(
            candidate_id, candidate_we_vote_id, stance_we_are_looking_for)
        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_public_count_for_contest_measure(
            measure_id, measure_we_vote_id, stance_we_are_looking_for)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        pass

    json_data = {
        'status': 'UNABLE_TO_RETRIEVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING',
        'success': False,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
示例#21
0
def candidate_politician_match_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    candidate_id = request.GET.get('candidate_id', 0)
    candidate_id = convert_to_int(candidate_id)
    # google_civic_election_id is included for interface usability reasons and isn't used in the processing
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    google_civic_election_id = convert_to_int(google_civic_election_id)

    if not positive_value_exists(candidate_id):
        messages.add_message(request, messages.ERROR, "The candidate_id variable was not passed in.")
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

    candidate_campaign_manager = CandidateCampaignManager()

    results = candidate_campaign_manager.retrieve_candidate_campaign_from_id(candidate_id)
    if not positive_value_exists(results['candidate_campaign_found']):
        messages.add_message(request, messages.ERROR,
                             "Candidate '{candidate_id}' not found.".format(candidate_id=candidate_id))
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

    we_vote_candidate = results['candidate_campaign']

    # Make sure we have a politician for this candidate. If we don't, create a politician entry, and save the
    # politician_we_vote_id in the candidate
    results = candidate_politician_match(we_vote_candidate)

    display_messages = True
    if results['status'] and display_messages:
        messages.add_message(request, messages.INFO, results['status'])
    return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)) +
                                "?google_civic_election_id=" + str(google_civic_election_id))
    def retrieve_voter_following_org_status(self, voter_id, voter_we_vote_id,
                                            organization_id,
                                            organization_we_vote_id):
        """
        Retrieve one follow entry so we can see if a voter is following or ignoring a particular org
        """

        if not positive_value_exists(voter_id) and positive_value_exists(
                voter_we_vote_id):
            # We need voter_id to call retrieve_follow_organization
            voter_manager = VoterManager()
            voter_id = voter_manager.fetch_local_id_from_we_vote_id(
                voter_we_vote_id)

        if not positive_value_exists(voter_id) and \
                not (positive_value_exists(organization_id) or positive_value_exists(organization_we_vote_id)):
            results = {
                'status': 'RETRIEVE_VOTER_FOLLOWING_MISSING_VARIABLES',
                'success': False,
                'follow_organization_found': False,
                'follow_organization_id': 0,
                'follow_organization': FollowOrganization(),
                'is_following': False,
                'is_not_following': True,
                'is_ignoring': False,
                'error_result': True,
                'DoesNotExist': False,
                'MultipleObjectsReturned': False,
            }
            return results

        return self.retrieve_follow_organization(0, voter_id, organization_id,
                                                 organization_we_vote_id)
示例#23
0
    def retrieve_voter_following_org_status(self, voter_id, voter_we_vote_id,
                                            organization_id, organization_we_vote_id):
        """
        Retrieve one follow entry so we can see if a voter is following or ignoring a particular org
        """

        if not positive_value_exists(voter_id) and positive_value_exists(voter_we_vote_id):
            # We need voter_id to call retrieve_follow_organization
            voter_manager = VoterManager()
            voter_id = voter_manager.fetch_local_id_from_we_vote_id(voter_we_vote_id)

        if not positive_value_exists(voter_id) and \
                not (positive_value_exists(organization_id) or positive_value_exists(organization_we_vote_id)):
            results = {
                'status':                       'RETRIEVE_VOTER_FOLLOWING_MISSING_VARIABLES',
                'success':                      False,
                'follow_organization_found':    False,
                'follow_organization_id':       0,
                'follow_organization':          FollowOrganization(),
                'is_following':                 False,
                'is_not_following':             True,
                'is_ignoring':                  False,
                'error_result':                 True,
                'DoesNotExist':                 False,
                'MultipleObjectsReturned':      False,
            }
            return results

        return self.retrieve_follow_organization(0, voter_id, organization_id, organization_we_vote_id)
    def retrieve_contest_office(self,
                                contest_office_id,
                                contest_office_we_vote_id='',
                                maplight_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        contest_office_on_stage = ContestOffice()

        try:
            if positive_value_exists(contest_office_id):
                contest_office_on_stage = ContestOffice.objects.get(
                    id=contest_office_id)
                contest_office_id = contest_office_on_stage.id
                contest_office_we_vote_id = contest_office_on_stage.we_vote_id
                status = "RETRIEVE_OFFICE_FOUND_BY_ID"
            elif positive_value_exists(contest_office_we_vote_id):
                contest_office_on_stage = ContestOffice.objects.get(
                    we_vote_id=contest_office_we_vote_id)
                contest_office_id = contest_office_on_stage.id
                contest_office_we_vote_id = contest_office_on_stage.we_vote_id
                status = "RETRIEVE_OFFICE_FOUND_BY_WE_VOTE_ID"
            elif positive_value_exists(maplight_id):
                contest_office_on_stage = ContestOffice.objects.get(
                    maplight_id=maplight_id)
                contest_office_id = contest_office_on_stage.id
                contest_office_we_vote_id = contest_office_on_stage.we_vote_id
                status = "RETRIEVE_OFFICE_FOUND_BY_MAPLIGHT_ID"
            else:
                status = "RETRIEVE_OFFICE_SEARCH_INDEX_MISSING"
        except ContestOffice.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            exception_multiple_object_returned = True
            status = "RETRIEVE_OFFICE_MULTIPLE_OBJECTS_RETURNED"
        except ContestOffice.DoesNotExist:
            exception_does_not_exist = True
            status = "RETRIEVE_OFFICE_NOT_FOUND"

        results = {
            'success':
            True if convert_to_int(contest_office_id) > 0 else False,
            'status':
            status,
            'error_result':
            error_result,
            'DoesNotExist':
            exception_does_not_exist,
            'MultipleObjectsReturned':
            exception_multiple_object_returned,
            'contest_office_found':
            True if convert_to_int(contest_office_id) > 0 else False,
            'contest_office_id':
            convert_to_int(contest_office_id),
            'contest_office_we_vote_id':
            contest_office_we_vote_id,
            'contest_office':
            contest_office_on_stage,
        }
        return results
示例#25
0
    def update_or_create_contest_office(self, we_vote_id, maplight_id, google_civic_election_id,
                                        office_name, updated_contest_office_values):
        """
        Either update or create an office entry.
        """
        exception_multiple_object_returned = False
        new_office_created = False
        contest_office_on_stage = ContestOffice()

        if not google_civic_election_id:
            success = False
            status = 'MISSING_GOOGLE_CIVIC_ELECTION_ID'
        # DALE 2016-05-10 Since we are allowing offices to be created prior to Google Civic data
        # being available, we need to remove our reliance on district_id or district_name
        # elif not (district_id or district_name):
        #     success = False
        #     status = 'MISSING_DISTRICT_ID'
        elif not office_name:
            success = False
            status = 'MISSING_OFFICE'
        else:  # state_code not required due to some federal offices
            try:
                if positive_value_exists(we_vote_id):
                    contest_office_on_stage, new_office_created = ContestOffice.objects.update_or_create(
                        google_civic_election_id__exact=google_civic_election_id,
                        we_vote_id__iexact=we_vote_id,
                        defaults=updated_contest_office_values)
                elif positive_value_exists(maplight_id):
                    contest_office_on_stage, new_office_created = ContestOffice.objects.update_or_create(
                        google_civic_election_id__exact=google_civic_election_id,
                        maplight_id__exact=maplight_id,
                        defaults=updated_contest_office_values)
                else:
                    contest_office_on_stage, new_office_created = ContestOffice.objects.update_or_create(
                        google_civic_election_id__exact=google_civic_election_id,
                        # district_id__exact=district_id,
                        # district_name__iexact=district_name,  # Case doesn't matter
                        office_name__iexact=office_name,  # Case doesn't matter
                        # state_code__iexact=state_code,  # Case doesn't matter
                        defaults=updated_contest_office_values)
                success = True
                status = 'CONTEST_OFFICE_SAVED'
            except ContestOffice.MultipleObjectsReturned as e:
                handle_record_found_more_than_one_exception(e, logger=logger)
                success = False
                status = 'MULTIPLE_MATCHING_CONTEST_OFFICES_FOUND'
                exception_multiple_object_returned = True

        results = {
            'success':                  success,
            'status':                   status,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'new_office_created':       new_office_created,
            'contest_office':           contest_office_on_stage,
            'saved':                    new_office_created,
            'updated':                  True if success and not new_office_created else False,
            'not_processed':            True if not success else False,
        }
        return results
示例#26
0
def scrape_and_save_social_media_from_all_organizations(state_code=''):
    facebook_pages_found = 0
    twitter_handles_found = 0
    force_retrieve = False
    temp_count = 0

    organization_manager = OrganizationManager()
    organization_list_query = Organization.objects.order_by('organization_name')
    if positive_value_exists(state_code):
        organization_list_query = organization_list_query.filter(state_served_code=state_code)

    organization_list = organization_list_query
    for organization in organization_list:
        twitter_handle = False
        facebook_page = False
        if not organization.organization_website:
            continue
        if (not positive_value_exists(organization.organization_twitter_handle)) or force_retrieve:
            scrape_results = scrape_social_media_from_one_site(organization.organization_website)

            # Only include a change if we have a new value (do not try to save blank value)
            if scrape_results['twitter_handle_found'] and positive_value_exists(scrape_results['twitter_handle']):
                twitter_handle = scrape_results['twitter_handle']
                twitter_handles_found += 1

            if scrape_results['facebook_page_found'] and positive_value_exists(scrape_results['facebook_page']):
                facebook_page = scrape_results['facebook_page']
                facebook_pages_found += 1

            save_results = organization_manager.update_organization_social_media(organization, twitter_handle,
                                                                                 facebook_page)

        if save_results['success']:
            organization = save_results['organization']

        # ######################################
        # If we have a Twitter handle for this org, refresh the data
        if organization.organization_twitter_handle:
            results = retrieve_twitter_user_info(organization.organization_twitter_handle)

            if results['success']:
                save_results = organization_manager.update_organization_twitter_details(
                    organization, results['twitter_json'])

                if save_results['success']:
                    results = update_social_media_statistics_in_other_tables(organization)
        # ######################################
        # temp_count += 1
        # if temp_count > 10:
        #     break

    status = "ORGANIZATION_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success':                  True,
        'status':                   status,
        'twitter_handles_found':    twitter_handles_found,
        'facebook_pages_found':     facebook_pages_found,
    }
    return results
示例#27
0
def polling_locations_import_from_structured_json(structured_json):
    """
    This pathway in requires a we_vote_id, and is not used when we import from Google Civic
    :param structured_json:
    :return:
    """
    polling_location_manager = PollingLocationManager()
    polling_locations_saved = 0
    polling_locations_updated = 0
    polling_locations_not_processed = 0
    for one_polling_location in structured_json:
        we_vote_id = one_polling_location['we_vote_id'] if 'we_vote_id' in one_polling_location else ''
        line1 = one_polling_location['line1'] if 'line1' in one_polling_location else ''
        city = one_polling_location['city'] if 'city' in one_polling_location else ''
        state = one_polling_location['state'] if 'state' in one_polling_location else ''

        if positive_value_exists(we_vote_id) and positive_value_exists(line1) and positive_value_exists(city) and \
                positive_value_exists(state):
            proceed_to_update_or_create = True
        else:
            proceed_to_update_or_create = False

        if proceed_to_update_or_create:
            # Values that are not required
            polling_location_id = one_polling_location['polling_location_id'] \
                if 'polling_location_id' in one_polling_location else ''
            location_name = one_polling_location['location_name'] if 'location_name' in one_polling_location else ''
            polling_hours_text = one_polling_location['polling_hours_text'] \
                if 'polling_hours_text' in one_polling_location else ''
            directions_text = one_polling_location['directions_text'] \
                if 'directions_text' in one_polling_location else ''
            line2 = one_polling_location['line2'] if 'line2' in one_polling_location else ''
            zip_long = one_polling_location['zip_long'] if 'zip_long' in one_polling_location else ''

            results = polling_location_manager.update_or_create_polling_location(
                we_vote_id, polling_location_id, location_name, polling_hours_text, directions_text,
                line1, line2, city, state, zip_long)
        else:
            polling_locations_not_processed += 1
            results = {
                'success': False,
                'status': 'Required value missing, cannot update or create'
            }

        if results['success']:
            if results['new_polling_location_created']:
                polling_locations_saved += 1
            else:
                polling_locations_updated += 1
        else:
            polling_locations_not_processed += 1
    polling_locations_results = {
        'success':          True,
        'status':           "POLLING_LOCATIONS_IMPORT_PROCESS_COMPLETE",
        'saved':            polling_locations_saved,
        'updated':          polling_locations_updated,
        'not_processed':    polling_locations_not_processed,
    }
    return polling_locations_results
示例#28
0
def politician_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    state_code = request.GET.get('state_code', '')
    politician_search = request.GET.get('politician_search', '')
    google_civic_election_id = convert_to_int(
        request.GET.get('google_civic_election_id', 0))
    politician_list = []

    try:
        politician_list = Politician.objects.all()
        if positive_value_exists(state_code):
            politician_list = politician_list.filter(state_code=state_code)

        filters = []
        if positive_value_exists(politician_search):
            new_filter = Q(politician_name__icontains=politician_search)
            filters.append(new_filter)

            new_filter = Q(
                politician_twitter_handle__icontains=politician_search)
            filters.append(new_filter)

            new_filter = Q(political_party__icontains=politician_search)
            filters.append(new_filter)

            new_filter = Q(we_vote_id__icontains=politician_search)
            filters.append(new_filter)

            # Add the first query
            if len(filters):
                final_filters = filters.pop()

                # ...and "OR" the remaining items in the list
                for item in filters:
                    final_filters |= item

                politician_list = politician_list.filter(final_filters)

        politician_list = politician_list.order_by('politician_name')[:200]
    except ObjectDoesNotExist:
        # This is fine, create new
        pass

    election_list = Election.objects.order_by('-election_day_text')

    template_values = {
        'messages_on_stage': messages_on_stage,
        'google_civic_election_id': google_civic_election_id,
        'politician_list': politician_list,
        'politician_search': politician_search,
        'election_list': election_list,
        'state_code': state_code,
    }
    return render(request, 'politician/politician_list.html', template_values)
示例#29
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
示例#30
0
def candidate_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
    candidate_search = request.GET.get('candidate_search', '')
    candidate_list = []

    try:
        candidate_list = CandidateCampaign.objects.all()
        if positive_value_exists(google_civic_election_id):
            candidate_list = candidate_list.filter(google_civic_election_id=google_civic_election_id)

        filters = []
        if positive_value_exists(candidate_search):
            new_filter = Q(candidate_name__icontains=candidate_search)
            filters.append(new_filter)

            new_filter = Q(candidate_twitter_handle__icontains=candidate_search)
            filters.append(new_filter)

            new_filter = Q(candidate_url__icontains=candidate_search)
            filters.append(new_filter)

            new_filter = Q(party__icontains=candidate_search)
            filters.append(new_filter)

            new_filter = Q(we_vote_id__icontains=candidate_search)
            filters.append(new_filter)

            # Add the first query
            if len(filters):
                final_filters = filters.pop()

                # ...and "OR" the remaining items in the list
                for item in filters:
                    final_filters |= item

                candidate_list = candidate_list.filter(final_filters)

        candidate_list = candidate_list.order_by('candidate_name')[:200]
    except CandidateCampaign.DoesNotExist:
        # This is fine, create new
        pass

    election_list = Election.objects.order_by('-election_day_text')

    template_values = {
        'messages_on_stage':        messages_on_stage,
        'candidate_list':           candidate_list,
        'candidate_search':         candidate_search,
        'election_list':            election_list,
        'google_civic_election_id': google_civic_election_id,
    }
    return render(request, 'candidate/candidate_list.html', template_values)
示例#31
0
def voter_authenticate_manually_view(request):
    messages_on_stage = get_messages(request)

    voter_api_device_id = get_voter_api_device_id(request)  # We look in the cookies for voter_api_device_id
    store_new_voter_api_device_id_in_cookie = False
    if not positive_value_exists(voter_api_device_id):
        # Create a voter_device_id and voter in the database if one doesn't exist yet
        results = voter_setup(request)
        voter_api_device_id = results['voter_api_device_id']
        store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']

    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    voter_id = convert_to_int(voter_id)
    voter_on_stage_found = False
    voter_on_stage = Voter()
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        voter_on_stage_found = True
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Voter.DoesNotExist:
        # This is fine, we will display an error
        pass

    if voter_on_stage_found:
        set_this_voter_as_admin = "UPDATE voter_voter SET is_admin=True WHERE id={voter_id};".format(voter_id=voter_id)
        unset_this_voter_as_admin = "UPDATE voter_voter SET is_admin=False WHERE id={voter_id};".format(
            voter_id=voter_id)

        set_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=True WHERE id={voter_id};" \
                                    "".format(voter_id=voter_id)
        unset_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=False WHERE id={voter_id};" \
                                      "".format(voter_id=voter_id)
        template_values = {
            'messages_on_stage':            messages_on_stage,
            'voter':                        voter_on_stage,
            'voter_api_device_id':          voter_api_device_id,
            'is_authenticated':             request.user.is_authenticated(),
            'set_this_voter_as_admin':      set_this_voter_as_admin,
            'unset_this_voter_as_admin':    unset_this_voter_as_admin,
            'set_as_verified_volunteer':    set_as_verified_volunteer,
            'unset_as_verified_volunteer':  unset_as_verified_volunteer,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,

        }
    response = render(request, 'voter/voter_authenticate_manually.html', template_values)

    # We want to store the voter_api_device_id cookie if it is new
    # if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
    # DALE 2016-02-15 Always set if we have a voter_api_device_id
    if positive_value_exists(store_new_voter_api_device_id_in_cookie):
        set_voter_api_device_id(request, response, voter_api_device_id)

    return response
示例#32
0
def scrape_website_for_social_media_view(request, organization_id, force_retrieve=False):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    facebook_page = False
    twitter_handle = False

    organization_manager = OrganizationManager()
    results = organization_manager.retrieve_organization(organization_id)

    if not results['organization_found']:
        messages.add_message(request, messages.INFO, results['status'])
        return HttpResponseRedirect(reverse('organization:organization_edit', args=(organization_id,)))

    organization = results['organization']

    if not organization.organization_website:
        messages.add_message(request, messages.ERROR, "No organizational website found.")
        return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)))

    if (not positive_value_exists(organization.organization_twitter_handle)) or \
            (not positive_value_exists(organization.organization_facebook)) or force_retrieve:
        scrape_results = scrape_social_media_from_one_site(organization.organization_website)

        if scrape_results['twitter_handle_found']:
            twitter_handle = scrape_results['twitter_handle']
            messages.add_message(request, messages.INFO, "Twitter handle found: " + twitter_handle)
        else:
            messages.add_message(request, messages.INFO, "No Twitter handle found: " + scrape_results['status'])

        if scrape_results['facebook_page_found']:
            facebook_page = scrape_results['facebook_page']
            messages.add_message(request, messages.INFO, "Facebook page found: " + facebook_page)

    save_results = organization_manager.update_organization_social_media(organization, twitter_handle,
                                                                         facebook_page)
    if save_results['success']:
        organization = save_results['organization']
    else:
        organization.organization_twitter_handle = twitter_handle  # Store it temporarily

    # ######################################
    if organization.organization_twitter_handle:
        results = retrieve_twitter_user_info(organization.organization_twitter_handle)

        if results['success']:
            save_results = organization_manager.update_organization_twitter_details(
                organization, results['twitter_json'])

            if save_results['success']:
                organization = save_results['organization']
                results = update_social_media_statistics_in_other_tables(organization)
    # ######################################

    return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)))
示例#33
0
    def retrieve_candidate_campaign(
            self, candidate_campaign_id, candidate_campaign_we_vote_id=None, candidate_maplight_id=None,
            candidate_name=None, candidate_vote_smart_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        candidate_campaign_on_stage = CandidateCampaign()

        try:
            if positive_value_exists(candidate_campaign_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(id=candidate_campaign_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_ID"
            elif positive_value_exists(candidate_campaign_we_vote_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(we_vote_id=candidate_campaign_we_vote_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_WE_VOTE_ID"
            elif positive_value_exists(candidate_maplight_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(maplight_id=candidate_maplight_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_MAPLIGHT_ID"
            elif positive_value_exists(candidate_vote_smart_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(vote_smart_id=candidate_vote_smart_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_VOTE_SMART_ID"
            elif positive_value_exists(candidate_name):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(candidate_name=candidate_name)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_NAME"
            else:
                status = "RETRIEVE_CANDIDATE_SEARCH_INDEX_MISSING"
        except CandidateCampaign.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            exception_multiple_object_returned = True
            status = "RETRIEVE_CANDIDATE_MULTIPLE_OBJECTS_RETURNED"
        except CandidateCampaign.DoesNotExist:
            exception_does_not_exist = True
            status = "RETRIEVE_CANDIDATE_NOT_FOUND"

        results = {
            'success':                  True if convert_to_int(candidate_campaign_id) > 0 else False,
            'status':                   status,
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'candidate_campaign_found': True if convert_to_int(candidate_campaign_id) else False,
            'candidate_campaign_id':    convert_to_int(candidate_campaign_id),
            'candidate_campaign_we_vote_id':    candidate_campaign_we_vote_id,
            'candidate_campaign':       candidate_campaign_on_stage,
        }
        return results
示例#34
0
def organization_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    organization_state_code = request.GET.get('organization_state', '')
    google_civic_election_id = request.GET.get('google_civic_election_id', '')
    candidate_we_vote_id = request.GET.get('candidate_we_vote_id', '')
    organization_search = request.GET.get('organization_search', '')

    messages_on_stage = get_messages(request)
    organization_list_query = Organization.objects.all()
    if positive_value_exists(organization_state_code):
        organization_list_query = organization_list_query.filter(state_served_code__iexact=organization_state_code)

    if positive_value_exists(organization_search):
        filters = []
        new_filter = Q(organization_name__icontains=organization_search)
        filters.append(new_filter)

        new_filter = Q(organization_twitter_handle__icontains=organization_search)
        filters.append(new_filter)

        new_filter = Q(organization_website__icontains=organization_search)
        filters.append(new_filter)

        new_filter = Q(we_vote_id__icontains=organization_search)
        filters.append(new_filter)

        # Add the first query
        if len(filters):
            final_filters = filters.pop()

            # ...and "OR" the remaining items in the list
            for item in filters:
                final_filters |= item

            organization_list_query = organization_list_query.filter(final_filters)

    organization_list_query = organization_list_query.order_by('organization_name')

    organization_list = organization_list_query

    state_list = STATE_CODE_MAP
    sorted_state_list = sorted(state_list.items())

    template_values = {
        'messages_on_stage':        messages_on_stage,
        'candidate_we_vote_id':     candidate_we_vote_id,
        'google_civic_election_id': google_civic_election_id,
        'organization_list':        organization_list,
        'organization_search':      organization_search,
        'organization_state':       organization_state_code,
        'state_list':               sorted_state_list,
    }
    return render(request, 'organization/organization_list.html', template_values)
示例#35
0
    def retrieve_candidate_campaign(
            self, candidate_campaign_id, candidate_campaign_we_vote_id=None, candidate_maplight_id=None,
            candidate_name=None, candidate_vote_smart_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        candidate_campaign_on_stage = CandidateCampaign()

        try:
            if positive_value_exists(candidate_campaign_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(id=candidate_campaign_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_ID"
            elif positive_value_exists(candidate_campaign_we_vote_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(we_vote_id=candidate_campaign_we_vote_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_WE_VOTE_ID"
            elif positive_value_exists(candidate_maplight_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(maplight_id=candidate_maplight_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_MAPLIGHT_ID"
            elif positive_value_exists(candidate_vote_smart_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(vote_smart_id=candidate_vote_smart_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_VOTE_SMART_ID"
            elif positive_value_exists(candidate_name):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(candidate_name=candidate_name)
                candidate_campaign_id = candidate_campaign_on_stage.id
                candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_NAME"
            else:
                status = "RETRIEVE_CANDIDATE_SEARCH_INDEX_MISSING"
        except CandidateCampaign.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            exception_multiple_object_returned = True
            status = "RETRIEVE_CANDIDATE_MULTIPLE_OBJECTS_RETURNED"
        except CandidateCampaign.DoesNotExist:
            exception_does_not_exist = True
            status = "RETRIEVE_CANDIDATE_NOT_FOUND"

        results = {
            'success':                  True if convert_to_int(candidate_campaign_id) > 0 else False,
            'status':                   status,
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'candidate_campaign_found': True if convert_to_int(candidate_campaign_id) else False,
            'candidate_campaign_id':    convert_to_int(candidate_campaign_id),
            'candidate_campaign_we_vote_id':    candidate_campaign_we_vote_id,
            'candidate_campaign':       candidate_campaign_on_stage,
        }
        return results
示例#36
0
def organization_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    organization_state_code = request.GET.get('organization_state', '')
    google_civic_election_id = request.GET.get('google_civic_election_id', '')
    candidate_we_vote_id = request.GET.get('candidate_we_vote_id', '')
    organization_search = request.GET.get('organization_search', '')

    messages_on_stage = get_messages(request)
    organization_list_query = Organization.objects.all()
    if positive_value_exists(organization_state_code):
        organization_list_query = organization_list_query.filter(state_served_code__iexact=organization_state_code)

    if positive_value_exists(organization_search):
        filters = []
        new_filter = Q(organization_name__icontains=organization_search)
        filters.append(new_filter)

        new_filter = Q(organization_twitter_handle__icontains=organization_search)
        filters.append(new_filter)

        new_filter = Q(organization_website__icontains=organization_search)
        filters.append(new_filter)

        new_filter = Q(we_vote_id__icontains=organization_search)
        filters.append(new_filter)

        # Add the first query
        if len(filters):
            final_filters = filters.pop()

            # ...and "OR" the remaining items in the list
            for item in filters:
                final_filters |= item

            organization_list_query = organization_list_query.filter(final_filters)

    organization_list_query = organization_list_query.order_by('organization_name')

    organization_list = organization_list_query

    state_list = STATE_CODE_MAP
    sorted_state_list = sorted(state_list.items())

    template_values = {
        'messages_on_stage':        messages_on_stage,
        'candidate_we_vote_id':     candidate_we_vote_id,
        'google_civic_election_id': google_civic_election_id,
        'organization_list':        organization_list,
        'organization_search':      organization_search,
        'organization_state':       organization_state_code,
        'state_list':               sorted_state_list,
    }
    return render(request, 'organization/organization_list.html', template_values)
示例#37
0
 def get_candidate_state(self):
     if positive_value_exists(self.state_code):
         return self.state_code
     else:
         # Pull this from ocdDivisionId
         if positive_value_exists(self.ocd_division_id):
             ocd_division_id = self.ocd_division_id
             return extract_state_from_ocd_division_id(ocd_division_id)
         else:
             return ''
示例#38
0
 def get_ballot_item_we_vote_id(self):
     if positive_value_exists(self.contest_office_we_vote_id):
         return self.contest_office_we_vote_id
     elif positive_value_exists(self.candidate_campaign_we_vote_id):
         return self.candidate_campaign_we_vote_id
     elif positive_value_exists(self.politician_we_vote_id):
         return self.politician_we_vote_id
     elif positive_value_exists(self.contest_measure_we_vote_id):
         return self.contest_measure_we_vote_id
     return None
示例#39
0
 def get_ballot_item_we_vote_id(self):
     if positive_value_exists(self.contest_office_we_vote_id):
         return self.contest_office_we_vote_id
     elif positive_value_exists(self.candidate_campaign_we_vote_id):
         return self.candidate_campaign_we_vote_id
     elif positive_value_exists(self.politician_we_vote_id):
         return self.politician_we_vote_id
     elif positive_value_exists(self.contest_measure_we_vote_id):
         return self.contest_measure_we_vote_id
     return None
示例#40
0
 def get_kind_of_ballot_item(self):
     if positive_value_exists(self.contest_office_we_vote_id):
         return OFFICE
     elif positive_value_exists(self.candidate_campaign_we_vote_id):
         return CANDIDATE
     elif positive_value_exists(self.politician_we_vote_id):
         return POLITICIAN
     elif positive_value_exists(self.contest_measure_we_vote_id):
         return MEASURE
     return None
示例#41
0
 def get_kind_of_ballot_item(self):
     if positive_value_exists(self.contest_office_we_vote_id):
         return OFFICE
     elif positive_value_exists(self.candidate_campaign_we_vote_id):
         return CANDIDATE
     elif positive_value_exists(self.politician_we_vote_id):
         return POLITICIAN
     elif positive_value_exists(self.contest_measure_we_vote_id):
         return MEASURE
     return None
 def get_office_state(self):
     if positive_value_exists(self.state_code):
         return self.state_code
     else:
         # Pull this from ocdDivisionId
         if positive_value_exists(self.ocd_division_id):
             ocd_division_id = self.ocd_division_id
             return extract_state_from_ocd_division_id(ocd_division_id)
         else:
             return ''
示例#43
0
def candidate_delete_process_view(request):
    """
    Delete this candidate
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    candidate_id = convert_to_int(request.GET.get('candidate_id', 0))
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    # Retrieve this candidate
    candidate_on_stage_found = False
    candidate_on_stage = CandidateCampaign()
    if positive_value_exists(candidate_id):
        try:
            candidate_query = CandidateCampaign.objects.filter(id=candidate_id)
            if len(candidate_query):
                candidate_on_stage = candidate_query[0]
                candidate_on_stage_found = True
        except Exception as e:
            messages.add_message(request, messages.ERROR, 'Could not find candidate -- exception.')

    if not candidate_on_stage_found:
        messages.add_message(request, messages.ERROR, 'Could not find candidate.')
        return HttpResponseRedirect(reverse('candidate:candidate_list', args=()) +
                                    "?google_civic_election_id=" + str(google_civic_election_id))

    # Are there any positions attached to this candidate that should be moved to another
    # instance of this candidate?
    position_list_manager = PositionListManager()
    retrieve_public_positions = True  # The alternate is positions for friends-only
    position_list = position_list_manager.retrieve_all_positions_for_candidate_campaign(retrieve_public_positions, candidate_id)
    if positive_value_exists(len(position_list)):
        positions_found_for_this_candidate = True
    else:
        positions_found_for_this_candidate = False

    try:
        if not positions_found_for_this_candidate:
            # Delete the candidate
            candidate_on_stage.delete()
            messages.add_message(request, messages.INFO, 'Candidate Campaign deleted.')
        else:
            messages.add_message(request, messages.ERROR, 'Could not delete -- '
                                                          'positions still attached to this candidate.')
            return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))
    except Exception as e:
        messages.add_message(request, messages.ERROR, 'Could not delete candidate -- exception.')
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

    return HttpResponseRedirect(reverse('candidate:candidate_list', args=()) +
                                "?google_civic_election_id=" + str(google_civic_election_id))
示例#44
0
def scrape_and_save_social_media_for_candidates_in_one_election(
        google_civic_election_id=0):
    facebook_pages_found = 0
    twitter_handles_found = 0
    force_retrieve = False
    status = ""
    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_manager = CandidateCampaignManager()
    candidate_list_manager = CandidateCampaignListManager()
    return_list_of_objects = True
    results = candidate_list_manager.retrieve_all_candidates_for_upcoming_election(
        google_civic_election_id, return_list_of_objects)
    status += results['status']
    if results['success']:
        candidate_list = results['candidate_list_objects']
    else:
        candidate_list = []

    for candidate in candidate_list:
        twitter_handle = False
        facebook_page = False
        if not candidate.candidate_url:
            continue
        if (not positive_value_exists(
                candidate.candidate_twitter_handle)) or force_retrieve:
            scrape_results = scrape_social_media_from_one_site(
                candidate.candidate_url)

            # Only include a change if we have a new value (do not try to save blank value)
            if scrape_results['twitter_handle_found'] and positive_value_exists(
                    scrape_results['twitter_handle']):
                twitter_handle = scrape_results['twitter_handle']
                twitter_handles_found += 1

            if scrape_results['facebook_page_found'] and positive_value_exists(
                    scrape_results['facebook_page']):
                facebook_page = scrape_results['facebook_page']
                facebook_pages_found += 1

            save_results = candidate_manager.update_candidate_social_media(
                candidate, twitter_handle, facebook_page)

        # ######################################
        # We refresh the Twitter information in another function

    status = "ORGANIZATION_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success': True,
        'status': status,
        'twitter_handles_found': twitter_handles_found,
        'facebook_pages_found': facebook_pages_found,
    }
    return results
示例#45
0
def organization_search_for_api(organization_name, organization_twitter_handle,
                                organization_website, organization_email):
    organization_name = organization_name.strip()
    organization_twitter_handle = organization_twitter_handle.strip()
    organization_website = organization_website.strip()
    organization_email = organization_email.strip()

    # We need at least one term to search for
    if not positive_value_exists(organization_name) \
            and not positive_value_exists(organization_twitter_handle)\
            and not positive_value_exists(organization_website)\
            and not positive_value_exists(organization_email):
        json_data = {
            'status': "ORGANIZATION_SEARCH_ALL_TERMS_MISSING",
            'success': False,
            'organization_name': organization_name,
            'organization_twitter_handle': organization_twitter_handle,
            'organization_website': organization_website,
            'organization_email': organization_email,
            'organizations_list': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    organization_list_manager = OrganizationListManager()
    results = organization_list_manager.organization_search_find_any_possibilities(
        organization_name, organization_twitter_handle, organization_website,
        organization_email)

    if results['organizations_found']:
        organizations_list = results['organizations_list']
        json_data = {
            'status': results['status'],
            'success': True,
            'organization_name': organization_name,
            'organization_twitter_handle': organization_twitter_handle,
            'organization_website': organization_website,
            'organization_email': organization_email,
            'organizations_list': organizations_list,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        json_data = {
            'status': results['status'],
            'success': False,
            'organization_name': organization_name,
            'organization_twitter_handle': organization_twitter_handle,
            'organization_website': organization_website,
            'organization_email': organization_email,
            'organizations_list': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
示例#46
0
    def retrieve_voter(self, voter_id, email="", voter_we_vote_id="", twitter_request_token="", facebook_id=""):
        voter_id = convert_to_int(voter_id)
        if not validate_email(email):
            # We do not want to search for an invalid email
            email = None
        if positive_value_exists(voter_we_vote_id):
            voter_we_vote_id = voter_we_vote_id.strip()
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        voter_on_stage = Voter()

        try:
            if positive_value_exists(voter_id):
                voter_on_stage = Voter.objects.get(id=voter_id)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            elif email is not "" and email is not None:
                voter_on_stage = Voter.objects.get(email=email)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            elif positive_value_exists(voter_we_vote_id):
                voter_on_stage = Voter.objects.get(we_vote_id=voter_we_vote_id)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            elif positive_value_exists(twitter_request_token):
                voter_on_stage = Voter.objects.get(twitter_request_token=twitter_request_token)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            elif positive_value_exists(facebook_id):
                voter_on_stage = Voter.objects.get(facebook_id=facebook_id)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            else:
                voter_id = 0
                error_result = True
        except Voter.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            exception_multiple_object_returned = True
        except Voter.DoesNotExist as e:
            error_result = True
            exception_does_not_exist = True

        results = {
            "error_result": error_result,
            "DoesNotExist": exception_does_not_exist,
            "MultipleObjectsReturned": exception_multiple_object_returned,
            "voter_found": True if voter_id > 0 else False,
            "voter_id": voter_id,
            "voter": voter_on_stage,
        }
        return results
示例#47
0
def retrieve_twitter_data_for_all_organizations(state_code='',
                                                google_civic_election_id=0,
                                                first_retrieve_only=False):
    number_of_twitter_accounts_queried = 0
    number_of_organizations_updated = 0

    organization_manager = OrganizationManager()
    organization_list_query = Organization.objects.order_by(
        'organization_name')
    if positive_value_exists(state_code):
        organization_list_query = organization_list_query.filter(
            state_served_code=state_code)

    # TODO DALE limit this to organizations that have a voter guide in a particular election

    organization_list = organization_list_query
    for organization in organization_list:
        # ######################################
        # If we have a Twitter handle for this org, refresh the data
        if organization.organization_twitter_handle:
            retrieved_twitter_data = False
            if first_retrieve_only:
                if not positive_value_exists(
                        organization.twitter_followers_count):
                    results = retrieve_twitter_user_info(
                        organization.organization_twitter_handle)
                    retrieved_twitter_data = results['success']
                    number_of_twitter_accounts_queried += 1
            else:
                results = retrieve_twitter_user_info(
                    organization.organization_twitter_handle)
                retrieved_twitter_data = results['success']
                number_of_twitter_accounts_queried += 1

            if retrieved_twitter_data:
                number_of_organizations_updated += 1
                save_results = organization_manager.update_organization_twitter_details(
                    organization, results['twitter_json'])

                if save_results['success']:
                    results = update_social_media_statistics_in_other_tables(
                        organization)

    status = "ALL_ORGANIZATION_TWITTER_DATA_RETRIEVED"
    results = {
        'success': True,
        'status': status,
        'number_of_twitter_accounts_queried':
        number_of_twitter_accounts_queried,
        'number_of_organizations_updated': number_of_organizations_updated,
    }
    return results
示例#48
0
def remove_duplicate_candidate_view(request):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    candidate_id = request.GET.get('candidate_id', 0)

    remove_duplicate_process = request.GET.get('remove_duplicate_process',
                                               False)

    missing_variables = False

    if not positive_value_exists(google_civic_election_id):
        messages.add_message(request, messages.ERROR,
                             "Google Civic Election ID required.")
        missing_variables = True
    if not positive_value_exists(candidate_id):
        messages.add_message(request, messages.ERROR, "Candidate ID required.")
        missing_variables = True

    if missing_variables:
        return HttpResponseRedirect(
            reverse('candidate:candidate_list', args=()) +
            "?google_civic_election_id={var}"
            "".format(var=google_civic_election_id))

    candidate_campaign_list_manager = CandidateCampaignList()
    results = candidate_campaign_list_manager.remove_duplicate_candidate(
        candidate_id, google_civic_election_id)
    if results['success']:
        if remove_duplicate_process:
            # Continue this process
            return HttpResponseRedirect(
                reverse('candidate:find_and_remove_duplicate_candidates',
                        args=()) + "?google_civic_election_id=" +
                google_civic_election_id)
        else:
            messages.add_message(request, messages.ERROR, results['status'])
            return HttpResponseRedirect(
                reverse('candidate:candidate_edit', args=(candidate_id, )))
    else:
        messages.add_message(
            request, messages.ERROR,
            "Could not remove candidate {candidate_id} '{candidate_name}'."
            "".format(candidate_id=candidate_id,
                      candidate_name=candidate_id))  # TODO Add candidate_name
        return HttpResponseRedirect(
            reverse('candidate:candidate_list', args=()) +
            "?google_civic_election_id={var}"
            "".format(var=google_civic_election_id))
示例#49
0
    def retrieve_organization(self, organization_id, we_vote_id=None, vote_smart_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        organization_on_stage = Organization()
        organization_on_stage_id = 0
        status = "ERROR_ENTERING_RETRIEVE_ORGANIZATION"
        try:
            if positive_value_exists(organization_id):
                status = "ERROR_RETRIEVING_ORGANIZATION_WITH_ID"
                organization_on_stage = Organization.objects.get(id=organization_id)
                organization_on_stage_id = organization_on_stage.id
                status = "ORGANIZATION_FOUND_WITH_ID"
            elif positive_value_exists(we_vote_id):
                status = "ERROR_RETRIEVING_ORGANIZATION_WITH_WE_VOTE_ID"
                organization_on_stage = Organization.objects.get(we_vote_id=we_vote_id)
                organization_on_stage_id = organization_on_stage.id
                status = "ORGANIZATION_FOUND_WITH_WE_VOTE_ID"
            elif positive_value_exists(vote_smart_id):
                status = "ERROR_RETRIEVING_ORGANIZATION_WITH_VOTE_SMART_ID"
                organization_on_stage = Organization.objects.get(vote_smart_id=vote_smart_id)
                organization_on_stage_id = organization_on_stage.id
                status = "ORGANIZATION_FOUND_WITH_VOTE_SMART_ID"
        except Organization.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger)
            error_result = True
            exception_multiple_object_returned = True
            status = "ERROR_MORE_THAN_ONE_ORGANIZATION_FOUND"
            # logger.warn("Organization.MultipleObjectsReturned")
        except Organization.DoesNotExist:
            error_result = True
            exception_does_not_exist = True
            status += ", ORGANIZATION_NOT_FOUND"
            # logger.warn("Organization.DoesNotExist")

        organization_on_stage_found = True if organization_on_stage_id > 0 else False
        results = {
            'success':                      True if organization_on_stage_found else False,
            'status':                       status,
            'organization_found':           organization_on_stage_found,
            'organization_id':
                organization_on_stage.id if organization_on_stage.id else organization_on_stage_id,
            'we_vote_id':
                organization_on_stage.we_vote_id if organization_on_stage.we_vote_id else we_vote_id,
            'organization':                 organization_on_stage,
            'error_result':                 error_result,
            'DoesNotExist':                 exception_does_not_exist,
            'MultipleObjectsReturned':      exception_multiple_object_returned,
        }
        return results
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')
示例#51
0
    def retrieve_quick_info_master(self,
                                   quick_info_master_id,
                                   quick_info_master_we_vote_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        quick_info_master = QuickInfoMaster()
        success = False

        try:
            if positive_value_exists(quick_info_master_id):
                status = "RETRIEVE_QUICK_INFO_MASTER_FOUND_WITH_ID"
                quick_info_master = QuickInfoMaster.objects.get(
                    id=quick_info_master_id)
                quick_info_master_id = quick_info_master.id
                success = True
            elif positive_value_exists(quick_info_master_we_vote_id):
                status = "RETRIEVE_QUICK_INFO_MASTER_FOUND_WITH_WE_VOTE_ID"
                quick_info_master = QuickInfoMaster.objects.get(
                    we_vote_id=quick_info_master_we_vote_id)
                quick_info_master_id = quick_info_master.id
                success = True
            else:
                status = "RETRIEVE_QUICK_INFO_MASTER_INSUFFICIENT_VARIABLES"
        except QuickInfoMaster.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            exception_multiple_object_returned = True
            success = False
            status = "RETRIEVE_QUICK_INFO_MASTER_MULTIPLE_FOUND"
        except QuickInfoMaster.DoesNotExist:
            error_result = False
            exception_does_not_exist = True
            success = True
            status = "RETRIEVE_QUICK_INFO_MASTER_NONE_FOUND"

        results = {
            'success': success,
            'status': status,
            'error_result': error_result,
            'DoesNotExist': exception_does_not_exist,
            'MultipleObjectsReturned': exception_multiple_object_returned,
            'quick_info_master_found':
            True if quick_info_master_id > 0 else False,
            'quick_info_master_id': quick_info_master_id,
            'quick_info_master': quick_info_master,
        }
        return results
示例#52
0
def scrape_and_save_social_media_from_all_organizations(
        state_code='', force_retrieve=False):
    facebook_pages_found = 0
    twitter_handles_found = 0

    organization_manager = OrganizationManager()
    organization_list_query = Organization.objects.order_by(
        'organization_name')
    if positive_value_exists(state_code):
        organization_list_query = organization_list_query.filter(
            state_served_code=state_code)

    organization_list = organization_list_query
    for organization in organization_list:
        twitter_handle = False
        facebook_page = False
        if not organization.organization_website:
            continue
        if (not positive_value_exists(
                organization.organization_twitter_handle)) or force_retrieve:
            scrape_results = scrape_social_media_from_one_site(
                organization.organization_website)

            # Only include a change if we have a new value (do not try to save blank value)
            if scrape_results['twitter_handle_found'] and positive_value_exists(
                    scrape_results['twitter_handle']):
                twitter_handle = scrape_results['twitter_handle']
                twitter_handles_found += 1

            if scrape_results['facebook_page_found'] and positive_value_exists(
                    scrape_results['facebook_page']):
                facebook_page = scrape_results['facebook_page']
                facebook_pages_found += 1

            save_results = organization_manager.update_organization_social_media(
                organization, twitter_handle, facebook_page)

        # ######################################
        # We refresh the Twitter information in another function

    status = "ORGANIZATION_SOCIAL_MEDIA_SCRAPED"
    results = {
        'success': True,
        'status': status,
        'twitter_handles_found': twitter_handles_found,
        'facebook_pages_found': facebook_pages_found,
    }
    return results
    def retrieve_position_like(self, position_like_id, voter_id,
                               position_entered_id):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        position_like = PositionLike()

        try:
            if positive_value_exists(position_like_id):
                position_like = PositionLike.objects.get(id=position_like_id)
                position_like_id = position_like.id
                status = 'POSITION_LIKE_FOUND_WITH_ID'
                success = True
            elif positive_value_exists(voter_id) and positive_value_exists(
                    position_entered_id):
                position_like = PositionLike.objects.get(
                    voter_id=voter_id, position_entered_id=position_entered_id)
                position_like_id = position_like.id
                status = 'POSITION_LIKE_FOUND_WITH_VOTER_ID_AND_POSITION_ID'
                success = True
            else:
                status = 'POSITION_LIKE_NOT_FOUND-MISSING_VARIABLES'
                success = False
        except PositionLike.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            exception_multiple_object_returned = True
            status = 'POSITION_LIKE_NOT_FOUND_MultipleObjectsReturned'
            success = False
        except PositionLike.DoesNotExist:
            error_result = False
            exception_does_not_exist = True
            status = 'POSITION_LIKE_NOT_FOUND_DoesNotExist'
            success = True

        position_like_found = True if position_like_id > 0 else False
        results = {
            'status': status,
            'success': success,
            'position_like_found': position_like_found,
            'position_like_id': position_like_id,
            'position_like': position_like,
            'is_liked': position_like_found,
            'error_result': error_result,
            'DoesNotExist': exception_does_not_exist,
            'MultipleObjectsReturned': exception_multiple_object_returned,
        }
        return results
def elections_import_from_structured_json(structured_json):

    election_manager = ElectionManager()
    elections_saved = 0
    elections_updated = 0
    elections_not_processed = 0
    for one_election in structured_json:
        logger.debug(
            u"google_civic_election_id: {google_civic_election_id}, election_name: {election_name}, "
            u"election_day_text: {election_day_text}".format(**one_election))

        google_civic_election_id = one_election["google_civic_election_id"] \
            if "google_civic_election_id" in one_election else ''
        election_name = one_election[
            "election_name"] if "election_name" in one_election else ''
        election_day_text = one_election[
            "election_day_text"] if "election_day_text" in one_election else ''
        ocd_division_id = one_election[
            "ocd_division_id"] if "ocd_division_id" in one_election else ''
        state_code = one_election[
            "state_code"] if "state_code" in one_election else ''

        # Make sure we have the minimum required variables
        if not positive_value_exists(
                google_civic_election_id) or not positive_value_exists(
                    election_name):
            elections_not_processed += 1
            continue

        results = election_manager.update_or_create_election(
            google_civic_election_id, election_name, election_day_text,
            ocd_division_id, state_code)
        if results['success']:
            if results['new_election_created']:
                elections_saved += 1
            else:
                elections_updated += 1
        else:
            elections_not_processed += 1

    elections_results = {
        'success': True,
        'status': "ELECTION_IMPORT_PROCESS_COMPLETE",
        'saved': elections_saved,
        'updated': elections_updated,
        'not_processed': elections_not_processed,
    }
    return elections_results
示例#55
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')
示例#56
0
    def retrieve_all_candidates_for_office(self, office_id, office_we_vote_id):
        candidate_list = []
        candidate_list_found = False

        if not positive_value_exists(office_id) and not positive_value_exists(office_we_vote_id):
            status = 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING'
            results = {
                'success':              True if candidate_list_found else False,
                'status':               status,
                'office_id':            office_id,
                'office_we_vote_id':    office_we_vote_id,
                'candidate_list_found': candidate_list_found,
                'candidate_list':       candidate_list,
            }
            return results

        try:
            candidate_queryset = CandidateCampaign.objects.all()
            if positive_value_exists(office_id):
                candidate_queryset = candidate_queryset.filter(contest_office_id=office_id)
            elif positive_value_exists(office_we_vote_id):
                candidate_queryset = candidate_queryset.filter(contest_office_we_vote_id=office_we_vote_id)
            candidate_queryset = candidate_queryset.order_by('-twitter_followers_count')
            candidate_list = candidate_queryset

            if len(candidate_list):
                candidate_list_found = True
                status = 'CANDIDATES_RETRIEVED'
            else:
                status = 'NO_CANDIDATES_RETRIEVED'
        except CandidateCampaign.DoesNotExist:
            # No candidates found. Not a problem.
            status = 'NO_CANDIDATES_FOUND_DoesNotExist'
            candidate_list = []
        except Exception as e:
            handle_exception(e, logger=logger)
            status = 'FAILED retrieve_all_candidates_for_office ' \
                     '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))

        results = {
            'success':              True if candidate_list_found else False,
            'status':               status,
            'office_id':            office_id,
            'office_we_vote_id':    office_we_vote_id,
            'candidate_list_found': candidate_list_found,
            'candidate_list':       candidate_list,
        }
        return results
示例#57
0
def measure_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    google_civic_election_id = convert_to_int(
        request.GET.get('google_civic_election_id', 0))

    try:
        measure_list = ContestMeasure.objects.order_by('measure_title')
        if positive_value_exists(google_civic_election_id):
            measure_list = measure_list.filter(
                google_civic_election_id=google_civic_election_id)
    except ContestMeasure.DoesNotExist:
        # This is fine
        measure_list = ContestMeasure()
        pass

    election_list = Election.objects.order_by('-election_day_text')

    template_values = {
        'messages_on_stage': messages_on_stage,
        'measure_list': measure_list,
        'election_list': election_list,
        'google_civic_election_id': google_civic_election_id,
    }
    return render(request, 'measure/measure_list.html', template_values)
def retrieve_google_civic_election_id_for_voter(voter_id):
    """
    Grab the first ballot_item we can find for this voter and return the google_civic_election_id
    This is a rough way to do this and the preferred method is ballot/controllers.py choose_election_from_existing_data
    """
    google_civic_election_id = 0
    success = False

    if positive_value_exists(voter_id):
        try:
            ballot_item_query = BallotItem.objects.filter(
                voter_id__exact=voter_id, )
            ballot_item_list = list(ballot_item_query[:1])
            if ballot_item_list:
                one_ballot_item = ballot_item_list[0]
                google_civic_election_id = one_ballot_item.google_civic_election_id
                success = True
        except BallotItem.DoesNotExist:
            pass

    results = {
        'success': success,
        'google_civic_election_id': google_civic_election_id,
    }
    return results
示例#59
0
def position_list_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))

    position_list_manager = PositionListManager()

    if positive_value_exists(google_civic_election_id):
        public_only = True
        position_list = position_list_manager.retrieve_all_positions_for_election(google_civic_election_id, ANY_STANCE,
                                                                                  public_only)
    else:
        position_list = PositionEntered.objects.order_by('position_id')[:500]  # This order_by is temp

    election_list = Election.objects.order_by('-election_day_text')

    template_values = {
        'messages_on_stage': messages_on_stage,
        'position_list': position_list,
        'election_list': election_list,
        'google_civic_election_id': google_civic_election_id,
    }
    return render(request, 'position/position_list.html', template_values)