Esempio n. 1
0
def create_campaign():
    import uuid
    from flask import url_for, redirect
    from campaign_manager.forms.campaign import CampaignForm
    from campaign_manager.models.campaign import Campaign
    """Get campaign details.
    """
    form = CampaignForm(request.form)
    if form.validate_on_submit():
        data = form.data
        data.pop('csrf_token')
        data.pop('submit')

        data['uuid'] = uuid.uuid4().hex
        Campaign.create(data, form.uploader.data)
        return redirect(
            url_for(
                'campaign_manager.get_campaign',
                uuid=data['uuid'])
        )
    context = dict(
        oauth_consumer_key=OAUTH_CONSUMER_KEY,
        oauth_secret=OAUTH_SECRET
    )
    context['action'] = '/campaign_manager/create'
    context['campaigns'] = Campaign.all()
    context['categories'] = AbstractInsightsFunction.CATEGORIES
    context['functions'] = get_selected_functions()
    context['title'] = 'Create Campaign'
    return render_template(
        'create_campaign.html', form=form, **context)
Esempio n. 2
0
def edit_campaign(uuid):
    import datetime
    from flask import url_for, redirect
    from campaign_manager.forms.campaign import CampaignForm
    from campaign_manager.models.campaign import Campaign
    """Get campaign details.
    """
    try:
        campaign = Campaign.get(uuid)
        context = campaign.to_dict()

        if request.method == 'GET':
            form = CampaignForm()
            form.name.data = campaign.name
            form.campaign_managers.data = campaign.campaign_managers
            form.remote_projects.data = campaign.remote_projects
            form.types.data = campaign.types
            form.description.data = campaign.description
            form.geometry.data = json.dumps(campaign.geometry)
            form.map_type.data = campaign.map_type
            form.selected_functions.data = json.dumps(
                campaign.selected_functions)
            form.start_date.data = datetime.datetime.strptime(
                campaign.start_date, '%Y-%m-%d')
            if campaign.end_date:
                form.end_date.data = datetime.datetime.strptime(
                    campaign.end_date, '%Y-%m-%d')
        else:
            form = CampaignForm(request.form)
            if form.validate_on_submit():
                data = form.data
                data.pop('types_options')
                data.pop('csrf_token')
                data.pop('submit')
                campaign.update_data(data, form.uploader.data)
                Campaign.compute(campaign.uuid)

                return redirect(
                    url_for('campaign_manager.get_campaign',
                            uuid=campaign.uuid))
    except Campaign.DoesNotExist:
        return Response('Campaign not found')
    context['oauth_consumer_key'] = OAUTH_CONSUMER_KEY
    context['oauth_secret'] = OAUTH_SECRET
    context['map_provider'] = map_provider()
    context['url'] = '/edit/%s' % uuid
    context['action'] = 'edit'
    context['functions'] = get_selected_functions()
    context['title'] = 'Edit Campaign'
    context['maximum_area_size'] = MAX_AREA_SIZE
    context['uuid'] = uuid
    context['types'] = {}
    context['campaign_creator'] = campaign.campaign_creator
    context['link_to_omk'] = campaign.link_to_omk
    try:
        context['types'] = json.dumps(get_types()).replace(
            'True', 'true').replace('False', 'false')
    except ValueError:
        pass
    return render_template('create_campaign.html', form=form, **context)
Esempio n. 3
0
def generate_kml():
    """Generate KML file from geojson."""
    uuid = request.values.get('uuid', None)
    campaign_name = request.values.get('campaign_name', None)
    campaign = Campaign(uuid)

    # Get json for each type.
    types = campaign.get_s3_types()
    if types is None:
        return Response(json.dumps({'error': 'types not found'}), 400)

    data = []
    for t in types:
        data.append(campaign.get_type_geojsons(t))

    if len(data) == 0:
        return Response(json.dumps({'error': 'Data not found'}), 400)

    features = [i['features'] for sublist in data for i in sublist]

    # for each type, we need to get geojson.
    kml = Kml(name=campaign_name)

    file_name = hashlib.md5(
        uuid.encode('utf-8') + '{:%m-%d-%Y}'.format(datetime.today()).encode(
            'utf-8')).hexdigest() + '.kml'

    file_path = os.path.join(config.CACHE_DIR, file_name)

    # For now, let's work only with points.
    # TODO: include polygons in the kml file.
    features = [[f for f in sublist if f['geometry']['type'] == 'Point']
                for sublist in features]
    features = [item for sublist in features for item in sublist]

    for feature in features:
        tags = feature['properties']['tags']
        extended_data = ExtendedData()
        kml_name = ''

        if 'name' in tags.keys():
            kml_name = tags['name']
        elif 'amenity' in tags.keys():
            kml_name = tags['amenity']

        [
            extended_data.newdata(k, escape(v)) for k, v in tags.items()
            if k != 'name'
        ]
        kml.newpoint(name=kml_name,
                     extendeddata=extended_data,
                     coords=[(feature['geometry']['coordinates'][0],
                              feature['geometry']['coordinates'][1])])
    kml.save(path=file_path)
    if kml:
        # Save file into client storage device.
        return Response(json.dumps({'file_name': file_name}))
Esempio n. 4
0
    def get_campaigns(self, tag):
        """Returns campaign with tag.

        :param tag: tag to filter
        :type tag: str
        """
        return Campaign.all(**{'tags': tag})
Esempio n. 5
0
def edit_campaign(uuid):
    import datetime
    from flask import url_for, redirect
    from campaign_manager.forms.campaign import CampaignForm
    from campaign_manager.models.campaign import Campaign
    """Get campaign details.
    """
    try:
        campaign = Campaign.get(uuid)
        context = campaign.to_dict()
        if request.method == 'GET':
            form = CampaignForm()
            form.name.data = campaign.name
            form.campaign_status.data = campaign.campaign_status
            form.coverage.data = campaign.coverage
            form.campaign_managers.data = campaign.campaign_managers
            form.description.data = campaign.description
            form.geometry.data = json.dumps(campaign.geometry)
            form.selected_functions.data = json.dumps(campaign.selected_functions)
            form.start_date.data = datetime.datetime.strptime(
                campaign.start_date, '%Y-%m-%d')
            if campaign.end_date:
                form.end_date.data = datetime.datetime.strptime(
                    campaign.end_date, '%Y-%m-%d')
        else:
            form = CampaignForm(request.form)
            if form.validate_on_submit():
                data = form.data
                data.pop('csrf_token')
                data.pop('submit')
                campaign.update_data(data, form.uploader.data)
                return redirect(
                    url_for('campaign_manager.get_campaign',
                            uuid=campaign.uuid)
                )
    except Campaign.DoesNotExist:
        return Response('Campaign not found')
    context['oauth_consumer_key'] = OAUTH_CONSUMER_KEY
    context['oauth_secret'] = OAUTH_SECRET
    context['action'] = '/campaign_manager/edit/%s' % uuid
    context['campaigns'] = Campaign.all()
    context['categories'] = AbstractInsightsFunction.CATEGORIES
    context['functions'] = get_selected_functions()
    context['title'] = 'Edit Campaign'
    return render_template(
        'create_campaign.html', form=form, **context)
Esempio n. 6
0
def get_campaign_data(uuid):
    from campaign_manager.models.campaign import Campaign
    from campaign_manager.aws import S3Data
    """Get campaign details.
    """
    try:
        campaign = Campaign.get(uuid)
    except:
        abort(404)

    context = campaign.to_dict()
    context['s3_campaign_url'] = S3Data().url(uuid)
    campaign_manager_names = []
    for manager in parse_json_string(campaign.campaign_managers):
        campaign_manager_names.append(manager['name'])

    campaign_viewer_names = []
    for viewer in parse_json_string(campaign.campaign_viewers):
        campaign_viewer_names.append(viewer['name'])

    campaign_contributor_names = []
    for contributor in parse_json_string(campaign.campaign_contributors):
        campaign_contributor_names.append(contributor['name'])

    context['oauth_consumer_key'] = OAUTH_CONSUMER_KEY
    context['oauth_secret'] = OAUTH_SECRET
    context['map_provider'] = map_provider()
    context['campaign_manager_names'] = campaign_manager_names
    context['campaign_viewer_names'] = campaign_viewer_names
    context['campaign_contributor_names'] = campaign_contributor_names
    context['participants'] = len(campaign.campaign_managers)

    context['pct_covered_areas'] = campaign.calculate_areas_covered()

    if campaign.map_type != '':
        context['attribution'] = find_attribution(campaign.map_type)

    # Start date
    try:
        start_date = datetime.strptime(campaign.start_date, '%Y-%m-%d')
        context['start_date_date'] = start_date.strftime('%d %b')
        context['start_date_year'] = start_date.strftime('%Y')
    except TypeError:
        context['start_date_date'] = '-'
        context['start_date_year'] = '-'
    context['current_status'] = campaign.get_current_status()
    if context['current_status'] == 'active':
        context['current_status'] = 'running'

    # End date
    try:
        end_date = datetime.strptime(campaign.end_date, '%Y-%m-%d')
        context['end_date_date'] = end_date.strftime('%d %b')
        context['end_date_year'] = end_date.strftime('%Y')
    except TypeError:
        context['end_date_date'] = '-'
        context['end_date_year'] = '-'
    return context
Esempio n. 7
0
def create_campaign():
    import uuid
    from flask import url_for, redirect
    from campaign_manager.forms.campaign import CampaignForm
    """Get campaign details.
    """

    form = CampaignForm(request.form)
    if form.validate_on_submit():
        data = form.data
        data.pop('csrf_token')
        data.pop('submit')
        data.pop('types_options')

        data['uuid'] = uuid.uuid4().hex

        Campaign.create(data, form.uploader.data)
        Campaign.compute(data["uuid"])
        campaign = Campaign(data['uuid'])
        campaign.save()
        campaign.save_to_user_campaigns(data['user_id'], data['uuid'],
                                        Permission.ADMIN.name)

        return redirect(
            url_for('campaign_manager.get_campaign', uuid=data['uuid']))

    context = dict(oauth_consumer_key=OAUTH_CONSUMER_KEY,
                   oauth_secret=OAUTH_SECRET,
                   map_provider=map_provider())
    context['url'] = '/create'
    context['action'] = 'create'
    context['functions'] = get_selected_functions()
    context['title'] = 'Create Campaign'
    context['maximum_area_size'] = MAX_AREA_SIZE
    context['uuid'] = uuid.uuid4().hex
    context['types'] = {}
    context['link_to_omk'] = False
    context['feature_templates'] = get_types()
    try:
        context['types'] = json.dumps(get_types()).replace(
            'True', 'true').replace('False', 'false')
    except ValueError:
        pass
    return render_template('create_campaign.html', form=form, **context)
Esempio n. 8
0
def mock_get_campaign():
    campaign = Campaign()
    campaign.uuid = '111'
    campaign.name = 'test'
    campaign.total_participants_count = 3
    campaign.campaign_creator = 'test_creator'
    campaign.campaign_managers = [
        'test_manager1', 'test_manager2', 'test_creator'
    ]
    campaign._content_json = {'name': campaign.name, 'uuid': campaign.uuid}
    return [campaign]
Esempio n. 9
0
    def get_nearest_campaigns(self, coordinate, campaign_status, args):
        """Returns all nearest campaign.

        :param campaign_status: status of campaign, active or inactive
        :type campaign_status: str

        :param coordinate: coordinate of user e.g. -4.1412,1.412
        :type coordinate: str.
        """
        return Campaign.nearest_campaigns(coordinate, campaign_status, **args)
Esempio n. 10
0
def get_campaign_insight_function_data(uuid, insight_function_id):
    from campaign_manager.models.campaign import Campaign
    """Get campaign details.
    """
    try:
        campaign = Campaign.get(uuid)
        rendered_html = campaign.render_insights_function(insight_function_id)
        return Response(rendered_html)
    except Campaign.DoesNotExist:
        return Response('Campaign not found')
Esempio n. 11
0
def get_campaign_insight_function_data_metadata(uuid, insight_function_id):
    from campaign_manager.models.campaign import Campaign
    """Get campaign details.
    """
    try:
        campaign = Campaign.get(uuid)
        data = campaign.insights_function_data_metadata(insight_function_id)
        return Response(json.dumps(data))
    except Campaign.DoesNotExist:
        return Response('Campaign not found')
Esempio n. 12
0
def download_josm(uuid, file_name):
    """Download josm file."""
    campaign = Campaign.get(uuid)
    campaign_name = campaign.name + '.osm'
    file_path = os.path.join(config.CACHE_DIR, file_name)
    if not os.path.exists(file_path):
        abort(404)
    return send_file(file_path,
                     as_attachment=True,
                     attachment_filename=campaign_name)
Esempio n. 13
0
def get_osmcha_errors_function(uuid):
    try:
        campaign = Campaign.get(uuid)
        rendered_html = campaign.render_insights_function(
            insight_function_id='total-osmcha-errors',
            insight_function_name='OsmchaChangesets',
            additional_data=clean_argument(request.args))
        return Response(rendered_html)
    except Campaign.DoesNotExist:
        abort(404)
Esempio n. 14
0
def home():
    """Home page view.

    On this page a summary campaign manager view will shown.
    """
    context = dict(
        oauth_consumer_key=OAUTH_CONSUMER_KEY,
        oauth_secret=OAUTH_SECRET
    )
    context['campaigns'] = Campaign.all()
    # noinspection PyUnresolvedReferences
    return render_template('index.html', **context)
Esempio n. 15
0
def submit_campaign_data_to_json():
    import uuid
    from campaign_manager.forms.campaign import CampaignForm
    """Get campaign details."""

    form = CampaignForm(request.form)
    if form.validate_on_submit():
        try:
            data = form.data
            data.pop('csrf_token')
            data.pop('submit')
            data.pop('types_options')

            data['uuid'] = uuid.uuid4().hex
            campaign_data = Campaign.parse_campaign_data(
                data, form.uploader.data)
            return Response(Campaign.serialize(campaign_data))
        except Exception as e:
            print(e)
    else:
        return abort(500)
Esempio n. 16
0
def delete_campaign(uuid):
    try:
        campaign = Campaign.get(uuid)
        context = campaign.to_dict()
        # Get function from the model to delete S3 folders for the project
        campaign.delete()
        # Show a message to confirm the project is deleted
        flash('You successfully deleted a project!')
        # Return a status 200 to the frontend
        response = Response(status=200)
        return response
    except Campaign.DoesNotExist:
        abort(404)
Esempio n. 17
0
def campaign_coverage_upload_chunk_success(uuid):
    """Upload chunk handle success.
    """
    from campaign_manager.models.campaign import Campaign
    from campaign_manager.insights_functions.upload_coverage import (
        UploadCoverage)
    # validate coverage
    try:
        campaign = Campaign.get(uuid)
        coverage_function = UploadCoverage(campaign)
        coverage = coverage_function.get_function_raw_data()
        if not coverage:
            coverage_function.delete_coverage_files()
            return Response(
                json.dumps({
                    'success': False,
                    'reason': 'Shapefile is not valid.'
                }))
        if not check_geojson_is_polygon(coverage):
            coverage_function.delete_coverage_files()
            return Response(
                json.dumps({
                    'success': False,
                    'reason': 'It is not in polygon/multipolygon type.'
                }))

        try:
            coverage['features'][0]['properties']['date']
        except KeyError:
            coverage_function.delete_coverage_files()
            return Response(
                json.dumps({
                    'success': False,
                    'reason': 'Needs date attribute in shapefile.'
                }))

        campaign.coverage = {
            'last_uploader': request.args.get('uploader', ''),
            'last_uploaded': datetime.now().strftime('%Y-%m-%d'),
            'geojson': coverage
        }
        coverage_uploader = request.args.get('uploader', '')
        campaign.save(coverage_uploader)
        return Response(
            json.dumps({
                'success': True,
                'data': campaign.coverage,
                'files': coverage_function.get_coverage_files()
            }))
    except Campaign.DoesNotExist:
        abort(404)
Esempio n. 18
0
def get_campaign(uuid):
    from campaign_manager.models.campaign import Campaign
    """Get campaign details.
    """
    try:
        campaign = Campaign.get(uuid)
        context = campaign.to_dict()
        context['oauth_consumer_key'] = OAUTH_CONSUMER_KEY
        context['oauth_secret'] = OAUTH_SECRET
        context['geometry'] = json.dumps(campaign.geometry)
        context['selected_functions'] = campaign.get_selected_functions_in_string()

        # Calculate remaining day
        try:
            current = datetime.now()
            end_date = datetime.strptime(campaign.end_date, '%Y-%m-%d')
            remaining = end_date - current
            context['remaining_days'] = remaining.days if remaining.days > 0 else 0
        except TypeError:
            context['remaining_days'] = '-'

        # Start date
        try:
            start_date = datetime.strptime(campaign.start_date, '%Y-%m-%d')
            context['start_date_date'] = start_date.strftime('%d %b')
            context['start_date_year'] = start_date.strftime('%Y')
        except TypeError:
            context['start_date_date'] = '-'
            context['start_date_year'] = '-'

        # End date
        try:
            start_date = datetime.strptime(campaign.end_date, '%Y-%m-%d')
            context['end_date_date'] = end_date.strftime('%d %b')
            context['end_date_year'] = end_date.strftime('%Y')
        except TypeError:
            context['end_date_date'] = '-'
            context['end_date_year'] = '-'

        # Participant
        context['participants'] = len(campaign.campaign_managers)

        return render_template(
            'campaign_detail.html', **context)
    except Campaign.DoesNotExist:
        context = dict(
            oauth_consumer_key=OAUTH_CONSUMER_KEY,
            oauth_secret=OAUTH_SECRET
        )
        return render_template(
            'campaign_not_found.html', **context)
Esempio n. 19
0
def download_kml(uuid, file_name):
    """Download campaign as a kml file"""
    campaign = Campaign.get(uuid)

    file_path = os.path.join(config.CACHE_DIR, file_name)

    campaign_file_name = campaign.name + '.kml'

    if not os.path.exists(file_path):
        abort(404)

    return send_file(file_path,
                     as_attachment=True,
                     attachment_filename=campaign_file_name)
Esempio n. 20
0
def get_campaign(uuid):
    from campaign_manager.models.campaign import Campaign
    from campaign_manager.aws import S3Data
    """Get campaign details.
    """

    try:
        campaign = Campaign.get(uuid)
    except:
        abort(404)

    context = campaign.to_dict()
    context['s3_campaign_url'] = S3Data().url(uuid)

    context['types'] = list(
        map(lambda type: type[1]['type'], context['types'].items()))

    context['oauth_consumer_key'] = OAUTH_CONSUMER_KEY
    context['oauth_secret'] = OAUTH_SECRET
    context['map_provider'] = map_provider()
    context['participants'] = len(campaign.campaign_managers)

    context['pct_covered_areas'] = campaign.calculate_areas_covered()

    if campaign.map_type != '':
        context['attribution'] = find_attribution(campaign.map_type)

    # Start date
    try:
        start_date = datetime.strptime(campaign.start_date, '%Y-%m-%d')
        context['start_date_date'] = start_date.strftime('%d %b')
        context['start_date_year'] = start_date.strftime('%Y')
    except TypeError:
        context['start_date_date'] = '-'
        context['start_date_year'] = '-'
    context['current_status'] = campaign.get_current_status()
    if context['current_status'] == 'active':
        context['current_status'] = 'running'

    # End date
    try:
        end_date = datetime.strptime(campaign.end_date, '%Y-%m-%d')
        context['end_date_date'] = end_date.strftime('%d %b')
        context['end_date_year'] = end_date.strftime('%Y')
    except TypeError:
        context['end_date_date'] = '-'
        context['end_date_year'] = '-'

    return render_template('campaign_detail.html', **context)
Esempio n. 21
0
    def get(self, coordinate, tag):
        """Get all nearest campaigns.

        :param coordinate: coordinate of user e.g. -4.1412,1.412
        :type coordinate: str

        :param tag: tag to filter
        :type tag: str
        """
        campaigns = Campaign.nearest_campaigns(coordinate, **{'tags': tag})
        campaigns_json = []

        for campaign in campaigns:
            campaigns_json.append(campaign.json())

        return campaigns_json
Esempio n. 22
0
def mock_get_campaign():
    campaign = Campaign()
    campaign.uuid = '111'
    campaign.name = 'test'
    campaign.total_participants_count = 3
    campaign.campaign_creator = 'test_creator'
    campaign.campaign_managers = [{
        'name': 'test_manager1',
        'osm_id': '12345'
    }, {
        'name': 'test_manager2',
        'osm_id': '54321'
    }, {
        'name': 'test_creator',
        'osm_id': '98765'
    }]
    campaign._content_json = {'name': campaign.name, 'uuid': campaign.uuid}
    return [campaign]
Esempio n. 23
0
def get_osmcha_errors_data(uuid):
    try:
        campaign = Campaign.get(uuid)
        page_size = request.args.get('page_size', None)
        page = request.args.get('page', None)
        osmcha_changeset = OsmchaChangesets(campaign=campaign)

        if page_size:
            osmcha_changeset.max_page = int(page_size)
        if page:
            osmcha_changeset.current_page = int(page)

        osmcha_changeset.run()
        data = osmcha_changeset.get_function_data()
        return jsonify(data)
    except Campaign.DoesNotExist:
        abort(404)
Esempio n. 24
0
 def get_campaigns(self):
     """Returns campaigns.
     """
     return Campaign.all(campaign_status='active')
Esempio n. 25
0
 def get_campaign(self, uuid):
     """Return campaign."""
     return Campaign(uuid=uuid)
Esempio n. 26
0
def mock_get_nearest_campaign(coordinate):
    campaign = Campaign()
    campaign.uuid = '111'
    campaign.name = 'test'
    campaign._content_json = {'name': campaign.name, 'uuid': campaign.uuid}
    return [campaign]
Esempio n. 27
0
def mock_get_campaigns_with_tag(tag):
    campaign = Campaign()
    campaign.uuid = '111'
    campaign.name = 'test'
    campaign._content_json = {'name': campaign.name, 'uuid': campaign.uuid}
    return [campaign]
Esempio n. 28
0
 def setUp(self):
     self.uuid = 'ff6ff8fcfdd847c48dd1bc3c9107b397'
     self.campaign = Campaign(self.uuid)
Esempio n. 29
0
def thumbnail(image):
    map_image = os.path.join(Campaign.get_thumbnail_folder(), image)
    if not os.path.exists(map_image):
        return send_file('./campaign_manager/static/img/no_map.png')
    return send_file(map_image)
Esempio n. 30
0
def generate_geometry():
    for campaign in Campaign.all('all'):
        geojson_path = Campaign.get_geojson_file(campaign.uuid)
        if not geojson_path:
            campaign.save(save_to_git=False)