Beispiel #1
0
 def delete(self, id):
     user = current_user()
     activity = query_activity(id)
     if activity is None:
         return jsonify(falseReturn("该活动不存在"))
     if activity.sponsor_student_number != user.student_number:
         return jsonify(falseReturn("非法删除,只有该活动的作者才可以删除该活动"))
     Activity.delete_activity(activity)
     return jsonify(trueReturn("删除活动成功"))
Beispiel #2
0
 def new_activity(self, module_name, ip_address, user_id, action_type,
                  action_details, channel):
     activity = Activity(module_name=module_name,
                         ip_address=ip_address,
                         user_id=user_id,
                         action_type=action_type,
                         action_details=action_details,
                         channel=channel)
     activity.save()
     return activity
Beispiel #3
0
    def setUp(self):
        """This method sets up the variables for the tests"""
        self.activity_1 = Activity('Swim with dolphins', 25)
        self.activity_2 = Activity('Visit Christ the redeemer', 23)
        self.activity_3 = Activity('Naked walk on the beach', 20)

        self.activities = {
            self.activity_1.name: self.activity_1,
            self.activity_2.name: self.activity_2
        }
        self.bucketlist_1 = BucketList('Trip to Rio')
        self.bucketlist_2 = BucketList('Trip to Brazil', self.activities)
def record_activity(template, login_user=None, **kwargs):
    """
    record an activity
    """
    if login_user:
        actor = login_user.email + ' (' + str(login_user.id) + ')'
    else:
        actor = 'Anonymous'
    id_str = ' (%d)'
    sequence = '"%s"'
    # add more information for objects
    for k in kwargs:
        v = kwargs[k]
        if k.find('_id') > -1:
            kwargs[k] = str(v)
        elif k.startswith('user'):
            kwargs[k] = sequence % v.email + id_str % v.id
        elif k.startswith('role'):
            kwargs[k] = sequence % v.title_name
        elif k.startswith('session'):
            kwargs[k] = sequence % v.title + id_str % v.id
        elif k.startswith('track'):
            kwargs[k] = sequence % v.name + id_str % v.id
        elif k.startswith('speaker'):
            kwargs[k] = sequence % v.name + id_str % v.id
        else:
            kwargs[k] = str(v)
    try:
        msg = ACTIVITIES[template].format(**kwargs)
    except Exception:  # in case some error happened, not good
        msg = '[ERROR LOGGING] %s' % template

    activity = Activity(actor=actor, action=msg)
    save_to_db(activity, 'Activity Recorded')
Beispiel #5
0
 def get(self, student_number):
     activities = query_someone_activity(student_number)
     if activities is None:
         return jsonify(true_data_Return("null", "null", "无数据"))
     data = []
     for i in activities:
         data.append(Activity.get_simple_activity(i))
     return jsonify(true_data_Return(data, "", "获取数据成功"))
Beispiel #6
0
 def insert_user_activity_pref(user_id, preference):
     query = """INSERT INTO t_user_activity_preference (workout_type_id, preference_priority, user_id) VALUES (
               %s, %s, %s)"""
     activity_types = Activity.get_activity_type()
     for activity in preference:
         activity_query = query % (activity_types.get(activity), int(preference.get(activity)), user_id)
         Db.execute_insert_query(activity_query)
     return
Beispiel #7
0
 def get(self, id):
     activity = query_activity(id)
     if activity is None:
         return jsonify(falseReturn("该活动不存在"))
     data = []
     data.append(Activity.get_activities(activity))
     history("activity", activity.title, id)
     return jsonify(true_data_Return(data, "", "获取数据成功"))
Beispiel #8
0
def favorite_activity(action, profile, activity):
    node = Profile.objects(pk=profile).first()
    activity = Activity.objects(pk=activity).first()
    if (action == 'add'):
        RelationShips.favorite(node, activity)
    else:
        RelationShips.un_favorite(node, activity)
    return node
def main():
    with app.app_context():
        activities = Activity.get_activities_since_with_user_bio(last_parsed_activity())
        calculate_activity_calories_burnt(activities)
        if not activities:
            exit()
        write_last_parsed_activity(activities[len(activities)-1].get('id'))
        first_activity_time = get_datetime_from_activity_timestamp(activities[0].get('start_datetime'))
        last_activity_time = get_datetime_from_activity_timestamp(activities[len(activities)-1].get('start_datetime'))
        goals = get_items_by_user_id(Goal.get_user_goals(first_activity_time, last_activity_time))
        sessions = get_items_by_user_id(SessionModel.get_user_sessions_in_duration(first_activity_time, last_activity_time))
        goal_activities = []
        for activity in activities:
            goal_activities.append(
             "('{0}',{1},{2},{3})".format(activity.get('user_id'),
                                          get_item_id_of_item_inclusive_activity(activity, goals),
                                          activity.get('id'),
                                          get_item_id_of_item_inclusive_activity(activity, sessions))
            )
        Activity.insert_goal_session_activity_mapping(goal_activities)
Beispiel #10
0
    def setUp(self):
        """This method sets up the variables for the tests"""
        self.date_of_birth = datetime.strptime('Jun 1 1970', '%b %d %Y')
        self.activity_1 = Activity('Swim with dolphins', 25)
        self.bucketlist_1 = BucketList('Trip to Rio')
        self.bucketlist_2 = BucketList('Trip to Brazil')
        self.sharing_pool = SharingPool()

        self.bucketlists = {self.bucketlist_1.title: self.bucketlist_1}
        self.user_no_bucket = User('homie', 'duff', 'Homer', 'Simpson',
                                   self.date_of_birth)
        self.user_bucket = User('marge', 'maggie', 'Marge', 'Simpson',
                                self.date_of_birth, self.bucketlists)
def parse_additional_activities(activities_page):
    try:
        activities_raw = [[
            cell.text for cell in row("td")
        ] for row in BeautifulSoup(activities_page.content, features="lxml")(
            "tr", "even")]
        activities = [
            Activity(*[field for field in activity_raw]).__dict__
            for activity_raw in activities_raw
        ]
    except:
        activities = None

    return activities
Beispiel #12
0
    def get(self, keyword):
        activities = Activity.query.filter(
            Activity.title.ilike('%' + keyword + '%')).all()
        articles = Article.query.filter(
            Article.title.ilike('%' + keyword + '%')).all()
        result = []
        for i in range(len(articles)):
            a = Article.get_simple_article(articles[i])
            result.append(a)

        for i in range(len(activities)):
            a = Activity.get_simple_activity(activities[i])
            result.append(a)
        result_number = len(activities) + len(articles)
        data = [result_number, result]
        print(data)
        return jsonify(true_data_Return(data, "", "获取数据成功"))
Beispiel #13
0
class TestActivity(unittest.TestCase):
    """Test cases for the Activity class"""

    def setUp(self):
        """This method sets up the variables for the tests"""
        self.activity_1 = Activity('Swim with dolphins', 25)
        self.activity_2 = Activity('Visit Christ the redeemer', 23)

    def test_activity_instance(self):
        """This method tests if the Activity class creates an instance of itself"""
        self.assertIsInstance(self.activity_1, Activity,
                              msg='The object should be an instance of the `Activity` class')

    def test_instance_type(self):
        """This method tests if the Activity class creates a type of itself"""
        self.assertTrue((type(self.activity_2) is Activity), msg='The object should be of type `Activity`')

    def test_activity_attributes(self):
        """This method tests if the class assigns the right attributes to User instances"""
        self.assertEqual('Swim with dolphins', self.activity_1.name,
                         msg='The object first_name should be `Swim with dolphins`')

    def test_status_change(self):
        """This method tests if the Activity class changes the status of an instance"""
        self.activity_1.change_status(True)
        self.assertTrue(self.activity_1.status, msg='The object should be of have a status `True`')

    def test_rename(self):
        """This method tests if the Activity class changes the name of an instance"""
        self.activity_1.rename("Have fun!")
        self.assertEqual(self.activity_1.name, "Have fun!", msg='The object name should be `Have fun!`')

    def test_age_change(self):
        """This method tests if the Activity class changes the target_age of an instance"""
        self.activity_2.change_target_age(30)
        self.assertEqual(self.activity_2.target_age, 30, msg='The object target_age should be 30')

    def test_image_change(self):
        """This method tests if the Activity class changes the image url of an instance"""
        self.activity_1.change_image_url("app/static/img/gallery/activity_1.jpg")
        self.assertEqual(self.activity_1.image_url, "app/static/img/gallery/activity_1.jpg",
                         msg='The object image_url should be `app/static/img/gallery/activity_1.jpg`')
Beispiel #14
0
def record_activity(template, login_user=None, **kwargs):
    """
    record an activity
    """
    if not login_user and hasattr(g, 'user'):
        login_user = g.user
    if not login_user and login.current_user.is_authenticated:
        login_user = login.current_user
    if login_user:
        actor = login_user.email + ' (' + str(login_user.id) + ')'
    else:
        actor = 'Anonymous'
    id_str = ' (%d)'
    sequence = '"%s"'
    # add more information for objects
    for k in kwargs:
        v = kwargs[k]
        if k.find('_id') > -1:
            kwargs[k] = str(v)
        elif k.startswith('user'):
            kwargs[k] = sequence % v.email + id_str % v.id
        elif k.startswith('role'):
            kwargs[k] = sequence % v.title_name
        elif k.startswith('session'):
            kwargs[k] = sequence % v.title + id_str % v.id
        elif k.startswith('track'):
            kwargs[k] = sequence % v.name + id_str % v.id
        elif k.startswith('speaker'):
            kwargs[k] = sequence % v.name + id_str % v.id
        else:
            kwargs[k] = str(v)
    try:
        msg = ACTIVITIES[template].format(**kwargs)
    except Exception:  # in case some error happened, not good
        msg = '[ERROR LOGGING] %s' % template
    # conn.execute(Activity.__table__.insert().values(
    #     actor=actor, action=msg, time=datetime.now()
    # ))
    activity = Activity(actor=actor, action=msg)
    save_to_db(activity, 'Activity Recorded')
Beispiel #15
0
 def post(self):
     user = current_user()
     try:
         title = request.form['title']
         bt = request.form['begin_time']
         et = request.form['end_time']
         content = request.form['content']
     except:
         return jsonify(falseReturn("缺少必要信息"))
     try:
         begin_time = int(
             time.mktime(time.strptime(bt, "%Y-%m-%d %H:%M:%S")))
         end_time = int(time.mktime(time.strptime(et, "%Y-%m-%d %H:%M:%S")))
     except:
         return jsonify(falseReturn("时间格式错误"))
     activity_id = create_id()
     sponsor_student_number = user.student_number
     new = Activity(title, begin_time, end_time, activity_id,
                    sponsor_student_number, content)
     db.session.add(new)
     session_commit()
     return jsonify(trueReturn("创建活动成功"))
Beispiel #16
0
def add_bucket_activity():
    name = request.form['name']
    bucket_title = request.form['bucket_title']
    target_age = request.form['target_age']
    new_activity = Activity(name, target_age)
    bucketlist_list7 = current_bucketlists[session.get('username')]
    for bucketlist7 in bucketlist_list7:
        if bucket_title == bucketlist7.title:
            activity_list = [new_activity]
            if current_activities:
                if bucket_title in current_activities.keys():
                    activity_list = current_activities[bucket_title]
                    exists3 = False
                    for activity1 in activity_list:
                        if activity1.name == new_activity.name:
                            exists3 = True
                            break
                    if not exists3:
                        activity_list.append(new_activity)
                        break
            current_activities[bucket_title] = activity_list
            break
    return redirect(url_for('home'))
Beispiel #17
0
def get_rec_session():

    MAX_LENGTH = 60
    for user, days in input.iteritems():
        result = []
        lst_pre_act = Activity.get_activity_by_priority(user)
        pref_activity = lst_pre_act[0]
        global done
        for day in days:
            session = {"user_id": user, "start_datetime": "", "end_datetime": "", "session_type": "NOT_NOTIFIED"}
            today = day.get("date")[:10]
            fslots = day.get("free_slots")
            rslots = day.get("rec_slots")
            done = False
            c_session = day.get("existing_session")

            # if existing session is available for the day
            if c_session:
                s_start = Util.convert_string_to_datetime(c_session.get('start_time'))
                s_end = Util.convert_string_to_datetime(c_session.get('end_time'))
                s_length = (s_end - s_start).seconds/60

                given_length = math.floor(day.get("duration").get(pref_activity))

                # TODO: add logic to check the max length of session

                delta = s_length + (given_length - s_length)
                new_end = s_start + timedelta(minutes=delta)

                # check for free slots if it contains the slot
                for slot in fslots:

                    tmp_st = Util.convert_string_to_datetime(today+" "+slot.get('start'))
                    tmp_end = Util.convert_string_to_datetime(today+" "+slot.get('end'))

                    if s_start >= tmp_st and new_end <= tmp_end:
                        session["start_datetime"] = str(s_start)
                        session["end_datetime"] = str(new_end)

                        # TODO: add session to database
                        result.append({day.get("date")[:10]: session})
                        done = True
                        break

            # if existing session is not available for the day
            else:
                # per rec session check conflict with available slots
                global done
                done = False
                for rec_session in rslots:
                    if done:
                        break
                    for a_session in fslots:
                        latest_start = max(Util.convert_string_to_datetime(today+" "+rec_session.get("start")),
                                           Util.convert_string_to_datetime(today+" "+a_session.get("start")))

                        earliest_end = min(Util.convert_string_to_datetime(today+" "+rec_session.get("end")),
                                           Util.convert_string_to_datetime(today+" "+a_session.get("end")))

                        temp_overlap = (earliest_end - latest_start).seconds/60
                        act_length = math.floor(day.get("duration").get(pref_activity))

                        if temp_overlap >= act_length:
                            session["start_datetime"] = str(latest_start)
                            session["end_datetime"] = str(latest_start + timedelta(minutes=act_length))
                            result.append({day.get("date")[:10]: session})
                            done = True
                            break

                for free_session in fslots:
                    free_session

        print result
Beispiel #18
0
 def apply(self, query, value):
     activity = Activity.objects(name__icontains=value).first()
     return query.filter(activities__in=[activity.id])
Beispiel #19
0
def create(activity_id=None):
    if activity_id:

        activity = Activity.query.get(activity_id)

        if not activity:
            abort(404)

        title = _("Edit") + " " + str(activity.name)
    else:
        activity = Activity()
        title = _('Create activity')

    form = init_form(CreateForm, obj=activity)

    if request.method == 'POST':

        if form.validate_on_submit():
            form.populate_obj(activity)

            # Facebook ID location, not used yet
            activity.venue = 1

            # Set a custom_form if it actually exists
            form_id = int(form.form_id.data)
            if form_id == 0:
                form_id = None

            activity.form_id = form_id
            activity.owner_id = current_user.id

            if activity.id and activity.google_event_id:
                flash(_('The activity has been edited.'), 'success')

                google.update_activity(activity.google_event_id,
                                       form.nl_name.data,
                                       form.nl_description.data,
                                       form.location.data,
                                       form.start_time.data.isoformat(),
                                       form.end_time.data.isoformat())
            else:
                flash(_('The activity has been created.'), 'success')

                google_activity = google.insert_activity(
                    form.nl_name.data, form.nl_description.data,
                    form.location.data, form.start_time.data.isoformat(),
                    form.end_time.data.isoformat())

                if google_activity:
                    activity.google_event_id = google_activity['id']

            db.session.add(activity)

            file = request.files.get('picture')

            if file and file.filename:
                picture = file_service.add_file(FileCategory.ACTIVITY_PICTURE,
                                                file, file.filename)

                old_picture_id = activity.picture_file_id
                activity.picture_file_id = picture.id

                if old_picture_id:
                    old_picture = file_service.get_file_by_id(old_picture_id)
                    file_service.delete_file(old_picture)

            db.session.commit()

            return redirect(url_for('activity.get_activity',
                                    activity_id=activity.id))

    return render_template('activity/edit.htm', activity=activity, form=form,
                           title=title)
Beispiel #20
0
 def setUp(self):
     """This method sets up the variables for the tests"""
     self.activity_1 = Activity('Swim with dolphins', 25)
     self.activity_2 = Activity('Visit Christ the redeemer', 23)
Beispiel #21
0
def create(activity_id=None):
    # Need to be logged in + actie group or admin etc.
    if not ModuleAPI.can_write('activity'):
        return abort(403)

    if activity_id:

        activity = Activity.query.get(activity_id)

        if not activity:
            abort(404)

        title = _("Edit") + " " + str(activity.name)
    else:
        activity = Activity()
        title = _('Create activity')

    form = CreateForm(request.form, activity)

    if request.method == 'POST':
        if form.validate_on_submit():

            picture = activity.picture

            form.populate_obj(activity)

            file = request.files['picture']

            if file.filename and allowed_file(file.filename):
                picture = secure_filename(file.filename)

                if not activity.picture and os.path.isfile(
                        os.path.join('app/static/activity_pictures', picture)):
                    flash(_('An image with this name already exists.'),
                          'danger')
                    return render_template('activity/create.htm',
                                           activity=activity,
                                           form=form,
                                           title=title)

                fpath = os.path.join('app/static/activity_pictures', picture)
                file.save(fpath)
                os.chmod(fpath, 0o644)

                # Remove old picture
                if activity.picture:
                    try:
                        os.remove(os.path.join(
                            'app/static/activity_pictures',
                            activity.picture))
                    except OSError:
                        print(_('Cannot delete image, image does not exist') +
                              ": " + str(activity.picture))

            elif not picture:
                picture = None

            activity.venue = 1  # Facebook ID location, not used yet  # noqa

            # Set a custom_form if it actually exists
            form_id = int(form.form_id.data)
            if form_id == 0:
                form_id = None

            activity.form_id = form_id

            activity.picture = picture
            activity.owner_id = current_user.id

            if activity.id and activity.google_event_id:
                flash(_('The activity has been edited.'), 'success')

                google.update_activity(activity.google_event_id,
                                       form.nl_name.data,
                                       form.nl_description.data,
                                       form.location.data,
                                       form.start_time.data.isoformat(),
                                       form.end_time.data.isoformat())
            else:
                flash(_('The activity has been created.'), 'success')

                google_activity = google.insert_activity(
                    form.nl_name.data, form.nl_description.data,
                    form.location.data, form.start_time.data.isoformat(),
                    form.end_time.data.isoformat())

                if google_activity:
                    activity.google_event_id = google_activity['id']

            db.session.add(activity)
            db.session.commit()

            return redirect(url_for('activity.get_activity',
                                    activity_id=activity.id))
        else:
            flash_form_errors(form)

    return render_template('activity/create.htm', activity=activity, form=form,
                           title=title)
Beispiel #22
0
from datetime import datetime
import datetime as dtime

from app.common.database import Db
from app.common.util import Util
from app.common.config import session_status
from app.models.calendars import CalendarModel, CalendarEventsModel
import time
from app.models.activity import Activity

activity_type = Activity.get_activity_type()


class SessionModel(object):
    @staticmethod
    def insert_user_session(user_id, session_details):
        if SessionModel._has_session_period_overlap(user_id, session_details['start_datetime'],
                                                    session_details['end_datetime']):
            return -2
        query = """INSERT INTO t_user_session (
                    user_id,
                    name,
                    workout_type_id,
                    start_datetime,
                    end_datetime,
                    session_feedback_id,
                    session_status,
                    created_datetime,
                    modified_datetime
                    ) VALUES (
                    %(user_id)s,
Beispiel #23
0
def get_rec_sessions():
    input = get_user_free_rec_slots()
    act_type = Activity.get_activity_type()
    MAX_LENGTH = 45
    for user, days in input.iteritems():
        result = []
        lst_pre_act = Activity.get_activity_by_priority(user)
        pref_activity = lst_pre_act[0]
        global done
        for day in days:

            session = {"user_id": user, "start_datetime": "", "end_datetime": "", "session_status": "NOT_NOTIFIED",
                       "name": "Smart Session", "session_feedback_id": 0, "workout_type_id": act_type.get(pref_activity) }

            today = day.get("date")[:10]
            fslots = day.get("free_slots")
            rslots = day.get("rec_slots")
            done = False
            c_session = day.get("existing_session")

            # if existing session is available for the day
            if c_session:
                c_session = c_session[0]
                s_start = c_session.get('start_datetime')
                s_end = c_session.get('end_datetime')
                s_length = (s_end - s_start).seconds/60

                given_length = math.floor(day.get("duration").get(pref_activity))

                delta = s_length + (given_length - s_length)
                if(delta > MAX_LENGTH):
                    new_end = s_start + timedelta(minutes=MAX_LENGTH)
                else:
                    new_end = s_start + timedelta(minutes=delta)

                if(delta > MAX_LENGTH):
                    given_length = MAX_LENGTH

                # check for free slots if it contains the slot
                for slot in fslots:

                    tmp_st = Util.convert_string_to_datetime(today+" "+slot.get('start'))
                    tmp_end = Util.convert_string_to_datetime(today+" "+slot.get('end'))

                    if s_start >= tmp_st and new_end <= tmp_end:
                        session["start_datetime"] = str(s_start)
                        session["end_datetime"] = str(new_end)
                        
                        SessionModel.update_session(user, str(c_session.get("id")), session)
                        result.append({day.get("date")[:10]: session})
                        done = True
                        break

                for rec_slot in rslots:

                    tmp_st = Util.convert_string_to_datetime(today+" "+rec_slot.get('start'))
                    tmp_end = Util.convert_string_to_datetime(today+" "+rec_slot.get('end'))

                    tmp_length = (tmp_end - tmp_st).seconds/60

                    if(tmp_length > given_length):

                        session["start_datetime"] = str(tmp_st)
                        session["end_datetime"] = str(tmp_st + timedelta(minutes=given_length))
                        
                        SessionModel.update_session(user, str(c_session.get("id")), session)
                        result.append({day.get("date")[:10]: session})
                        done = True
                        break


            # if existing session is not available for the day
            else:
                # per rec session check conflict with available slots
                done = False
                for rec_session in rslots:
                    for a_session in fslots:
                        latest_start = max(Util.convert_string_to_datetime(today+" "+rec_session.get("start")),
                                           Util.convert_string_to_datetime(today+" "+a_session.get("start")))

                        earliest_end = min(Util.convert_string_to_datetime(today+" "+rec_session.get("end")),
                                           Util.convert_string_to_datetime(today+" "+a_session.get("end")))

                        temp_overlap = (earliest_end - latest_start).seconds/60
                        act_length = math.floor(day.get("duration").get(pref_activity))

                        if temp_overlap >= act_length or temp_overlap >= MAX_LENGTH:
                            session["start_datetime"] = str(latest_start)
                            if act_length> MAX_LENGTH:
                                session["end_datetime"] = str(latest_start + timedelta(minutes=MAX_LENGTH))
                            else:
                                session["end_datetime"] = str(latest_start + timedelta(minutes=act_length))

                            # TODO: add session to database
                            SessionModel.insert_user_session(user, session)
                            result.append({day.get("date")[:10]: session})
                            done = True
                            break

                    if done:
                        break