Example #1
0
 def post(self):
     data = api.payload 
     activity = Activity(vin=data['vin'], scan_time=data['scan_time'])
     data['act_id'] = time.time()
     activity.act_id = int(data['act_id'])
     if Van.objects(vin=activity.vin).first():
         activity.save()
         resp = Activity.objects.aggregate(*[
             { '$match': { 'act_id' : activity.act_id } },
             {
                 '$project': {
                     '_id': '$$REMOVE', 
                     'vin': '$vin', 
                     'act_id': '$act_id', 
                     'scan_time': {
                         '$dateToString': {
                             'format': '%Y-%m-%d %H:%M:%S', 
                             'date': '$scan_time'
                         }
                     }
                 }
             }
         ])
         resp_string = encoder.encode(list(resp))
         return json.loads(resp_string), 200
         # return jsonify(Activity.objects(act_id=activity.act_id))
     else:
         abort(400, 'This vin does not exist')
    def delete(self, idx, idx1):
        leader_id = idx
        activity_id = idx1
        activity = Activity.objects(activity_id=activity_id).first()

        if activity.leader_id == leader_id:
            Activity.objects(activity_id=activity_id).delete()
            return jsonify("The activity is deleted")
        return jsonify("You do not have authority")
    def post(self, idx, idx1):  # Apply a new activity
        applicant_id = idx
        activity_id = idx1

        # Search if the applicanttion has already existed in
        #  MongoDB collection 'Application'
        applications_exist = Application.objects(applicant_id=applicant_id)
        for application_exist in applications_exist:
            if application_exist.activity_id == activity_id:
                return jsonify("You already applied", 400)

        # Obtain applicant's information from collection 'User'
        user = User.objects(use_id=applicant_id).first()
        applicant_name = user.username

        # Obtain activity information from collection 'Activity'
        activity = Activity.objects(activity_id=activity_id).first()
        activity_name = activity.activity_name

        apply_id = Application.objects.count()
        apply_id += 1
        application = Application(apply_id=apply_id,
                                  applicant_id=applicant_id,
                                  applicant_name=applicant_name,
                                  activity_id=activity_id,
                                  activity_name=activity_name,
                                  status=0)
        application.save()
        return jsonify("Successfully apply", 200)
    def get(self):
        serachByLeader = request.form.get("leader")
        serachByActivity = request.form.get("activity")
        searchString = request.form.get("search")

        if serachByLeader:
            activities = Activity.objects(leader_name__startswith=searchString)
            #return jsonify(activities)
            return jsonify(activities)

        if serachByActivity:
            activities = Activity.objects(
                activity_name__startswith=searchString)

            return jsonify(activities)

        return jsonify(Activity.objects.all())
Example #5
0
def new_activity():
    if current_user.is_authenticated:
        form = ActivityForm()
        if request.method == 'GET':
            form.date_due.data = date.today()
        if form.validate_on_submit():
            if form.forClass_n_quest.data and form.forClass_quest.data:
                flash('Você não pode marcar as duas opções', 'danger')
                return redirect(url_for('activities'))
            if form.forClass_n_quest.data or form.forClass_quest.data:
                users = User.query.filter_by(
                    classITA=current_user.classITA).all()
                for user in users:
                    status = ('Pendente'
                              if form.forClass_quest.data else 'Ativo')
                    activity = Activity(
                        title=form.title.data,
                        content=form.content.data,
                        date_due=form.date_due.data,
                        priority=form.priority.data,
                        forClass_quest=form.forClass_quest.data,
                        forClass_n_quest=form.forClass_n_quest.data,
                        status=status,
                        progress=form.progress.data,
                        owner=user)
                    db.session.add(activity)
            else:
                activity = Activity(
                    title=form.title.data,
                    content=form.content.data,
                    date_due=form.date_due.data,
                    priority=form.priority.data,
                    forClass_quest=form.forClass_quest.data,
                    forClass_n_quest=form.forClass_n_quest.data,
                    status='Ativo',
                    progress=form.progress.data,
                    owner=current_user)
                db.session.add(activity)
            flash('Atividade criada com sucesso!', 'success')
            db.session.commit()
            return redirect(url_for('activities'))
        return render_template('new_activity.html',
                               form=form,
                               title='Nova Atividade')
    return redirect(url_for('login'))
    def put(self, idx, idx1):
        use_id = idx
        activity_id = int(idx1)
        activity = Activity.objects(activity_id=activity_id).first()
        if activity.leader_name == use_id:
            activity_id = idx1
            activity_name = request.form.get("activity")
            start_date_str = request.form.get("start")
            skills = request.form.get("skills")
            genre = request.form.get("genre")
            description = request.form.get("description")

            if not start_date_str:
                Activity.objects(activity_id=activity_id).update(
                    activity_name=activity_name,
                    genre=genre,
                    skills=skills,
                    description=description)

                return jsonify(Activity.objects(activity_id=activity_id))

            start_date_datetime = datetime.strptime(start_date_str,
                                                    '%Y-%m-%d %H:%M:%S')
            Activity.objects(activity_id=activity_id).update(
                activity_name=activity_name,
                start_date=start_date_datetime,
                genre=genre,
                skills=skills,
                description=description)

            return add_cors(jsonify(Activity.objects(activity_id=activity_id)))
        return jsonify("You do not have the authority")
Example #7
0
def get_activities():
    """
    Get activities from RK
    """

    assert session.access_token

    application.logger.debug('access_token = %s' % session.access_token)
    headers = {
        'Authorization': 'Bearer ' + session.access_token,
        'Accept': 'application/vnd.com.runkeeper.FitnessActivityFeed+json',
    }

    page = 0
    activities = []

    while True:
        rv = requests.get(
            'https://api.runkeeper.com/fitnessActivities?page=%d' % page,
            headers=headers)
        if rv.status_code != 200:
            flash(
                'get_activities(): Invalid response status code: %d' %
                rv.status_code, 'error')
            return redirect(url_for('index'))
        items = rv.json()['items']
        n = len(items)
        if len(items) == 0:
            break
        for i in range(n):
            t = parser.parse(items[i]['start_time'])
            d = float(items[i]['total_distance'])
            a = Activity(start_time=t, distance=d)
            activities.append(a.jsonify())
        page = page + 1

    # make it chronological
    activities = activities[::-1]

    fmt = 'Got %d activities'
    application.logger.debug(fmt % len(activities))
    flash(fmt % len(activities))

    return redirect(url_for('index'))
Example #8
0
def get_activities():
    """
    Get activities from RK
    """

    assert session.access_token

    application.logger.debug('access_token = %s' % session.access_token)
    headers = {
        'Authorization': 'Bearer ' + session.access_token,
        'Accept': 'application/vnd.com.runkeeper.FitnessActivityFeed+json',
        }

    page = 0
    activities = []

    while True:
        rv = requests.get('https://api.runkeeper.com/fitnessActivities?page=%d'
                          % page, headers=headers)
        if rv.status_code != 200:
            flash('get_activities(): Invalid response status code: %d'
                  % rv.status_code, 'error')
            return redirect(url_for('index'))
        items = rv.json()['items']
        n = len(items)
        if len(items) == 0:
            break
        for i in range(n):
            t = parser.parse(items[i]['start_time'])
            d = float(items[i]['total_distance'])
            a = Activity(start_time=t, distance=d)
            activities.append(a.jsonify())
        page = page+1

    # make it chronological
    activities = activities[::-1]

    fmt = 'Got %d activities'
    application.logger.debug(fmt % len(activities))
    flash(fmt % len(activities))

    return redirect(url_for('index'))
Example #9
0
def build_event(info, commit=False):
    """
    Extracts desired information from the response provided by the Eventbrite
    API, and creates an Activity object, which is then inserted into the
    database.
    """
    # Active Events: 108, 107, 109, 111, 119
    # Non-active Events: 113, 105, 115

    address_data = get_eventbrite_venue(info["venue_id"])
    if address_data is None or "address" not in address_data:
        return

    # Checks to ensure that the event is in Texas.
    address = address_data["address"]
    if "region" not in address or address["region"] != "TX":
        return

    is_active = (info["category_id"] == "108" or info["category_id"] == "107"
                 or info["category_id"] == "109"
                 or info["category_id"] == "111"
                 or info["category_id"] == "119")

    event = Activity(
        id="eventbrite" + info["id"],
        type="eventbrite",
        url=info["url"],
        name=info["name"]["text"],
        description=info["description"]["text"],
        latitude=address_data["latitude"],
        longitude=address_data["longitude"],
        location=address_data["address"]["localized_address_display"],
        is_active=is_active,
        is_active_string="Active" if is_active else "Casual",
        is_free=info["is_free"],
        is_free_string="free" if info["is_free"] else "paid",
        image_1=info["logo"]["url"] if "logo" in info else None,
        image_2=None,
        image_3=None,
        image_4=None,
        designation=None,
        weather=None,
        directions=None,
        date=info["end"]["local"][0:10]
        if info["end"]["local"] is not None else None,
    )

    if commit:
        db.session.add(event)
        db.session.commit()

    return event
    def post(self, idx):
        # activity_id is useful when all the activiteis to be shown ==>To be confirm
        use_id = idx
        user = User.objects(use_id=use_id).first()

        leader_id = user.user_id

        activities = Activity.objects.all()
        n = len(activities)
        activity_id = 0
        if n != 0:
            activity_id = activities[n - 1].activity_id
            activity_id += 1

        activity_name = request.form.get("activity")
        start_date_str = request.form.get("start")
        skills = request.form.get("skills")
        genre = request.form.get("genre")
        description = request.form.get("description")

        start_date_datetime = datetime.strptime(start_date_str,
                                                '%Y-%m-%d %H:%M:%S')

        #check if there is the same activity name
        isPresent = Activity.objects(activity_name=activity_name).first()
        if isPresent:
            return jsonify("Please select another name")

        activity = Activity(leader_id=leader_id,
                            activity_id=activity_id,
                            activity_name=activity_name,
                            leader_name=username,
                            open_date=datetime.utcnow(),
                            start_date=start_date_datetime,
                            genre=genre,
                            skills=skills,
                            description=description)
        activity.save()
        return (jsonify("Successfully build a new activity"))
Example #11
0
def build_park(info, commit=False):
    """
    Extracts desired information from the response provided by the National
    Parks API, and creates an Activity object, which is then inserted into the
    database.
    """
    # Converts the latitude-longitude string into a list.
    # Places latitude at index 0 and longitude at index 1.
    if "latLong" not in info:
        return
    if ["latLong"] == "":
        return
    location = (info["latLong"].replace("lat:",
                                        "").replace("long:",
                                                    "").replace(",",
                                                                "").split())
    if len(location) == 0:
        return

    main_address = info["addresses"][0]

    park = Activity(
        id="park" + info["id"],
        type="park",
        url=info["url"],
        name=info["name"],
        description=info["description"],
        latitude=location[0],
        longitude=location[1],
        location=((main_address["line3"] +
                   ", ") if main_address["line3"] != "" else "") +
        main_address["city"] + ", " + main_address["stateCode"],
        is_active=True,
        is_active_string="Active",
        is_free=True if info["entranceFees"][0]["cost"] == "0.0000" else False,
        is_free_string="free"
        if info["entranceFees"][0]["cost"] == "0.0000" else "paid",
        image_1=info["images"][0]["url"],
        image_2=info["images"][1]["url"],
        image_3=info["images"][2]["url"],
        image_4=info["images"][3]["url"],
        designation=info["designation"],
        weather=info["weatherInfo"],
        directions=info["directionsInfo"],
        date=None,
    )

    if commit:
        db.session.add(park)
        db.session.commit()
Example #12
0
    def save_activity(n_clicks, record_data, stream_list, activity_data,
                      intensity_factor, tss):
        """Create database record for activity and save data files."""
        if (n_clicks is None or n_clicks == 0 or record_data is None
                or stream_list is None or activity_data is None):
            raise PreventUpdate

        fname_json = f'application/activity_files/original/{activity_data["id"]}.json'
        fname_csv = f'application/activity_files/csv/{activity_data["id"]}.csv'

        # Create a new activity record in the database
        from application.models import db, Activity
        from sqlalchemy.exc import IntegrityError

        try:
            new_act = Activity(
                title=activity_data['name'],
                description=activity_data['description'],
                created=datetime.datetime.utcnow(),
                recorded=dateutil.parser.isoparse(activity_data['start_date']),
                tz_local=activity_data['timezone'],
                moving_time_s=activity_data['moving_time'],
                elapsed_time_s=activity_data['elapsed_time'],
                filepath_orig=fname_json,
                filepath_csv=fname_csv,
                # Fields below here not required
                strava_id=activity_data['id'],
                distance_m=activity_data['distance'],
                elevation_m=activity_data['total_elevation_gain'],
                intensity_factor=intensity_factor,
                tss=tss,
            )
            db.session.add(new_act)
            db.session.commit()

        except IntegrityError as e:
            print(e)
            return html.Div(['There was an error saving this activity.'])

        # Save the strava response json
        with open(fname_json, 'w') as outfile:
            json.dump(stream_list, outfile)

        # Save the processed DataFrame as CSV
        df = pd.DataFrame.from_records(record_data)
        df.to_csv(fname_csv)

        return f'Activity saved successfully! Internal ID = {new_act.id}'
Example #13
0
def build_meetup(info, commit=False):
    """
    Extracts desired information from the response provided by the Meetup
    API, and creates an Activity object, which is then inserted into the
    database.
    """

    # Active Categories: 15046, 15892, 638, 242, 1998, 25375, 933, 15672
    # No way to discern categories in returned data, so only requesting active categories.

    # Checks to ensure that the meetup has a description and is in Texas.
    if ("plain_text_description" not in info or "group" not in info
            or "state" not in info["group"] or info["group"]["state"] != "TX"):
        return

    meetup = Activity(
        id="meetup" + info["id"],
        type="meetup",
        url=info["link"],
        name=info["name"],
        description=info["plain_text_description"],
        latitude=info["group"]["lat"],
        longitude=info["group"]["lon"],
        location=info["group"]["localized_location"],
        is_active=True,
        is_active_string="Active",
        is_free=False,
        is_free_string="paid",
        image_1=info["featured_photo"]["photo_link"]
        if "featured_photo" in info else None,
        image_2=None,
        image_3=None,
        image_4=None,
        designation=None,
        weather=None,
        directions=None,
        date=info["local_date"],
    )

    if commit:
        db.session.add(meetup)
        db.session.commit()

    return meetup
    def post(self, idx):
        # The activities the user attended
        user_id = idx  # idx = user_id
        applications = Application.objects(applicant_id=user_id)
        apply_activities = []

        if applications:
            for application in applications:
                activity_id = application.activity_id
                activity_id = activity_id
                status = application.status

                activity = Activity.objects(activity_id=activity_id).first()

                activity_name = activity.activity_name
                open_date = activity.open_date
                genre = activity.genre
                leader_name = activity.leader_name

                open_date_local = time.local(open_date)
                format_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                            open_date_local)

                apply_activity_dict = {
                    "Project_Name": activity_name,
                    "Deadline": open_date,
                    "Deadline": format_time,
                    "Major": genre,
                    "Leader": leader_name,
                    "Application Status": status
                }

                apply_activities.append(apply_activity_dict)

            return jsonify(apply_activities, 200)

        return jsonify("You don't have any applied acticities", 400)
    def get(self, idx):  # idx = user_id
        user_id = idx
        activities = Activity.objects(leader_id=user_id).all()
        create_activities = []

        if activities:
            for activity in activities:

                activity_name = activity.activity_name
                applications = Application.objects(
                    activity_name=activity_name).all()
                application_list_zero = []
                application_list_one = []
                for application in applications:
                    if application.status == 0:
                        application_list_zero.append(application.applicant_id)
                    elif application.status == 1:
                        application_list_one.append(application.applicant_id)
                activity_id = activity.activity_id
                activity_name = activity.activity_name
                open_date = activity.open_date
                genre = activity.genre

                # '0': the application has not been decided by the leader
                # '1': the application is successful
                create_activity_dict = {
                    "Project_Name": activity_name,
                    "Deadline": open_date,
                    "Major": genre,
                    "0": application_list_zero,
                    "1": application_list_one
                }

                create_activities.append(create_activity_dict)
            return jsonify(create_activities, 200)

        return add_cors(jsonify("You do not have any created acticities", 400))
Example #16
0
 def delete(self, idx):
     Activity.objects(act_id=idx).delete()
     return jsonify( message='Activity was successfully deleted!')
 def get(self, idx, idx1):
     return jsonify(Activity.objects(activity_id=idx1))
Example #18
0
def create_activity(plannerid):
    try:
        jwttoken = request.headers.get('Authorization').split(' ')[1]
        user = jwt_auth.get_user_from_token(jwttoken)
        desiredplanner = Planner.query.filter_by(id=plannerid).one()
        if user.id != desiredplanner.user_id:
            raise Exception('access denied')
        activity_name = request.json.get('activity_name')
        start_date = request.json.get('start_date')
        start_time = request.json.get('start_time')
        end_date = request.json.get('end_date')
        end_time = request.json.get('end_time')
        description = request.json.get('description')
        atype = request.json.get('type')
        if not activity_name:
            raise Exception('activity_name cannot be empty')
        if not start_date:
            raise Exception('start_date cannot be empty')
        if not start_time:
            raise Exception('start_time cannot be empty')
        if not end_date:
            raise Exception('end_date cannot be empty')
        if not end_time:
            raise Exception('end_time cannot be empty')
        if not description:
            raise Exception('description cannot be empty')

        start_datetime = start_date + ' ' + start_time
        end_datetime = end_date + ' ' + end_time

        if atype == 1:
            start = request.json.get('start')
            stop = request.json.get('stop')
            if (start['name'] == "" or start['lat'] == ""
                    or start['lng'] == ""):
                raise Exception(
                    'Start location name, latitude or longtitude is missing')
            if (stop['name'] == "" or stop['lat'] == "" or stop['lng'] == ""):
                raise Exception(
                    'Stop location name, latitude or longtitude is missing')
            start_object = Location(name=start['name'],
                                    latitude=str(start['lat']),
                                    longtitude=str(start['lng']))
            stop_object = Location(name=stop['name'],
                                   latitude=str(stop['lat']),
                                   longtitude=str(stop['lng']))
            db.session.add(start_object)
            db.session.add(stop_object)
            db.session.commit()
            activity_object_stop = Activity(
                name=activity_name + " (end)",
                start=dt.datetime.strptime(end_datetime, '%Y-%m-%d %H:%M'),
                end=dt.datetime.strptime(end_datetime, '%Y-%m-%d %H:%M'),
                description=description,
                planner_ID=int(plannerid),
                serviceType_ID=int(atype),
                location_ID=stop_object.id)
            db.session.add(activity_object_stop)
            db.session.commit()
            activity_object_start = Activity(name=activity_name+" (start)",
            start=dt.datetime.strptime(start_datetime, '%Y-%m-%d %H:%M'),
            end=dt.datetime.strptime(start_datetime, '%Y-%m-%d %H:%M'),
            description=description, planner_ID=int(plannerid), serviceType_ID=int(atype),location_ID=start_object.id\
               , ref=activity_object_stop.id )
            db.session.add(activity_object_start)
            db.session.commit()
            return jsonify(dict(success=True, code=201))
        else:
            inl = request.json.get('in')
            if (inl['name'] == "" or inl['lat'] == "" or inl['lng'] == ""):
                raise Exception(
                    'Location name, latitude or longtitude is missing')
            in_object = Location(name=inl['name'],
                                 latitude=str(inl['lat']),
                                 longtitude=str(inl['lng']))
            db.session.add(in_object)
            db.session.commit()
            activity_object_in = Activity(
                name=activity_name,
                start=dt.datetime.strptime(start_datetime, '%Y-%m-%d %H:%M'),
                end=dt.datetime.strptime(end_datetime, '%Y-%m-%d %H:%M'),
                description=description,
                planner_ID=int(plannerid),
                serviceType_ID=int(atype),
                location_ID=in_object.id)
            db.session.add(activity_object_in)
            db.session.commit()
            return jsonify(dict(success=True, code=201))

    except Exception as e:
        db.session.rollback()
        return jsonify(dict(success=False, message=str(e), code=400))
Example #19
0
 def get(self, idx: int):
     return jsonify(Activity.objects(act_id=idx))