def testJoinParty(self):
     sampleAuthMessage1Ad = ad.AttrDict(self.sampleAuthMessage1)
     proxy.habiticaRegister(sampleAuthMessage1Ad.username,
                            sampleAuthMessage1Ad.email,
                            sampleAuthMessage1Ad.password,
                            sampleAuthMessage1Ad.our_uuid)
     #Create an inviter
     inviterUUID = uuid.uuid4()
     inviter = randomGen()
     inviter_email = inviter + '@save.world'
     inviter_id = proxy.habiticaRegister(inviter, inviter_email, inviter,
                                         inviterUUID)['data']['id']
     inviter_group_id = json.loads(
         proxy.habiticaProxy(inviterUUID, 'POST', "/api/v3/groups", {
             'type': 'party',
             'privacy': 'private',
             'name': inviter
         }).text)['data']['id']
     #Finally try to make this user (self) join the party
     group_id_returned = proxy.setup_party(self.testUserUUID,
                                           inviter_group_id, inviter_id)
     self.assertEqual(group_id_returned, inviter_group_id)
     #Now try to join again, it should throw an error
     with self.assertRaises(RuntimeError):
         proxy.setup_party(self.testUserUUID, inviter_group_id, inviter_id)
     delete_inviter = proxy.habiticaProxy(inviterUUID, "DELETE",
                                          "/api/v3/user",
                                          {'password': inviter})
     edb.get_habitica_db().remove({'user_id': inviterUUID})
  def testResetActiveTransportation(self):
    self.testAutomaticRewardActiveTransportation()

    #Get user data before resetting
    user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_before['bike_count']), 1500)

    habits_before = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None).json()
    bike_pts_before = [habit['history'] for habit in habits_before['data'] if habit['text'] == self.new_task_text]

    #Reset
    reset_ts = arrow.Arrow(2016,5,3,9).timestamp
    autocheck.reset_all_tasks_to_ts(self.testUUID, reset_ts, is_dry_run=False)

    # Check timestamp 
    user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_after['last_timestamp']), reset_ts)

    # Re-score points
    # This should give points for the second and third sections
    # So I expect to see an additional distance of 2.5 + 3.5 km = 6km
    autocheck.give_points_for_all_tasks(self.testUUID)

    #Get user data after scoring and check results
    # We already had bike_count = 1500, and this is a round number, so it
    # should continue to be 1500
    user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_after['bike_count']), 0)

    # and we should have 6 points more?
    habits_after = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None).json()
    bike_pts_after = [habit['history'] for habit in habits_after['data'] if habit['text'] == self.new_task_text]
    logging.debug("bike_pts_after = %s" % (len(bike_pts_after[0]) - len(bike_pts_before[0])))
    self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 3)
Example #3
0
    def testAutomaticRewardActiveTransportation(self):
        #Create test data -- code copied from TestTimeGrouping
        key = (2016, 5, 3)
        test_section_list = []
        #
        # Since PST is UTC-7, all of these will be in the same UTC day
        # 13:00, 17:00, 21:00
        # so we expect the local date and UTC bins to be the same
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 6, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 10, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 14, tzinfo=tz.gettz(PST)), PST))

        self._fillModeDistanceDuration(test_section_list)
        #logging.debug("durations = %s" % [s.data.duration for s in test_section_list])

        summary_ts = earmt.group_by_timestamp(
            self.testUUID,
            arrow.Arrow(2016, 5, 1).timestamp,
            arrow.Arrow(2016, 6, 1).timestamp, None, earmts.get_distance)
        logging.debug(
            "in testAutomaticRewardActiveTransportation, result = %s" %
            summary_ts)

        #Get user data before scoring
        user_before = list(edb.get_habitica_db().find(
            {'user_id': self.testUUID}))[0]['metrics_data']
        self.assertEqual(int(user_before['bike_count']), 0)
        habits_before = proxy.habiticaProxy(self.testUUID, 'GET',
                                            "/api/v3/tasks/user?type=habits",
                                            None).json()
        bike_pts_before = [
            habit['history'] for habit in habits_before['data']
            if habit['text'] == "Bike"
        ]
        #Score points
        autocheck.reward_active_transportation(self.testUUID)
        #Get user data after scoring and check results
        user_after = list(edb.get_habitica_db().find(
            {'user_id': self.testUUID}))[0]['metrics_data']
        self.assertEqual(int(user_after['bike_count']), 1500)
        habits_after = proxy.habiticaProxy(self.testUUID, 'GET',
                                           "/api/v3/tasks/user?type=habits",
                                           None).json()
        bike_pts_after = [
            habit['history'] for habit in habits_after['data']
            if habit['text'] == "Bike"
        ]
        self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 2)
def reset_user(reset_em_uuid):
    del_result = proxy.habiticaProxy(reset_em_uuid, "POST",
                                     "/api/v3/user/reset", {})
    update_result = edb.get_habitica_db().update({"user_id": reset_em_uuid},
                                 {"$set": {'metrics_data':
                                   {'last_timestamp': 0, 'bike_count': 0, 'walk_count': 0}}})
    logging.debug("reset result for %s = %s, %s" % (reset_em_uuid, del_result, update_result))
 def tearDown(self):
   edb.get_analysis_timeseries_db().remove({'user_id': self.testUUID})
   del_result = proxy.habiticaProxy(self.testUUID, "DELETE",
                                    "/api/v3/user",
                                    {'password': "******"})
   edb.get_habitica_db().remove({'user_id': self.testUUID})
   logging.debug("in tearDown, result = %s" % del_result)
def reset_user(reset_em_uuid):
    del_result = proxy.habiticaProxy(reset_em_uuid, "POST",
                                     "/api/v3/user/reset", {})
    update_result = edb.get_habitica_db().update({"user_id": reset_em_uuid},
                                 {"$set": {'metrics_data':
                                   {'last_timestamp': 0, 'bike_count': 0, 'walk_count': 0}}})
    logging.debug("reset result for %s = %s, %s" % (reset_em_uuid, del_result, update_result))
Example #7
0
def delete_tasks(uuid, task_list):
    method_uri = "/api/v3/tasks/"

    for task in task_list:
        curr_task_del_uri = method_uri + str(task["id"])
        result = proxy.habiticaProxy(uuid, 'DELETE', curr_task_del_uri, {})
        logging.debug("Result of deleting %s = %s" % (task["id"], result.json()))
 def tearDown(self):
     # https: // habitica.com / apidoc /  # api-User-UserDelete
     del_result = proxy.habiticaProxy(
         self.testUserUUID, "DELETE", "/api/v3/user",
         {'password': self.sampleAuthMessage1['password']})
     edb.get_habitica_db().remove({'user_id': self.testUserUUID})
     logging.debug("in tear_down, result = %s" % del_result)
 def tearDown(self):
   # https: // habitica.com / apidoc /  # api-User-UserDelete
   del_result = proxy.habiticaProxy(self.testUserUUID, "DELETE",
                                    "/api/v3/user",
                                    {'password': self.sampleAuthMessage1['password']})
   edb.get_habitica_db().remove({'user_id': self.testUserUUID})
   logging.debug("in tear_down, result = %s" % del_result)
 def tearDown(self):
   edb.get_analysis_timeseries_db().remove({'user_id': self.testUUID})
   del_result = proxy.habiticaProxy(self.testUUID, "DELETE",
                                    "/api/v3/user",
                                    {'password': "******"})
   edb.get_habitica_db().remove({'user_id': self.testUUID})
   logging.debug("in tearDown, result = %s" % del_result)
    def testResetActiveTransportation(self):
        self.testAutomaticRewardActiveTransportation()

        #Get user data before resetting
        user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_before['bike_count']), 1500)

        habits_before = proxy.habiticaProxy(self.testUUID, 'GET',
                                            "/api/v3/tasks/user?type=habits",
                                            None).json()
        bike_pts_before = [
            habit['history'] for habit in habits_before['data']
            if habit['text'] == self.new_task_text
        ]

        #Reset
        reset_ts = arrow.Arrow(2016, 5, 3, 9).timestamp
        autocheck.reset_all_tasks_to_ts(self.testUUID,
                                        reset_ts,
                                        is_dry_run=False)

        # Check timestamp
        user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_after['last_timestamp']), reset_ts)

        # Re-score points
        # This should give points for the second and third sections
        # So I expect to see an additional distance of 2.5 + 3.5 km = 6km
        autocheck.give_points_for_all_tasks(self.testUUID)

        #Get user data after scoring and check results
        # We already had bike_count = 1500, and this is a round number, so it
        # should continue to be 1500
        user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_after['bike_count']), 0)

        # and we should have 6 points more?
        habits_after = proxy.habiticaProxy(self.testUUID, 'GET',
                                           "/api/v3/tasks/user?type=habits",
                                           None).json()
        bike_pts_after = [
            habit['history'] for habit in habits_after['data']
            if habit['text'] == self.new_task_text
        ]
        logging.debug("bike_pts_after = %s" %
                      (len(bike_pts_after[0]) - len(bike_pts_before[0])))
        self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 3)
Example #12
0
def habiticaProxy():
    logging.debug("habitica registration request %s" % (request))
    user_uuid = getUUID(request)
    assert (user_uuid is not None)
    method = request.json['callOpts']['method']
    method_url = request.json['callOpts']['method_url']
    method_args = request.json['callOpts']['method_args']
    return habitproxy.habiticaProxy(user_uuid, method, method_url, method_args)
Example #13
0
def habiticaProxy():
    logging.debug("habitica registration request %s" % (request))
    user_uuid = getUUID(request)
    assert(user_uuid is not None)
    method = request.json['callOpts']['method']
    method_url = request.json['callOpts']['method_url']
    method_args = request.json['callOpts']['method_args']
    return habitproxy.habiticaProxy(user_uuid, method, method_url,
                                    method_args)
 def testJoinParty(self):
     sampleAuthMessage1Ad = ad.AttrDict(self.sampleAuthMessage1)
     proxy.habiticaRegister(sampleAuthMessage1Ad.username, sampleAuthMessage1Ad.email,
                            sampleAuthMessage1Ad.password, sampleAuthMessage1Ad.our_uuid)
     #Create an inviter
     inviterUUID = uuid.uuid4()
     inviter = randomGen()
     inviter_email = inviter + '@save.world'
     inviter_id = proxy.habiticaRegister(inviter, inviter_email, inviter, inviterUUID)['data']['id']
     inviter_group_id = json.loads(proxy.habiticaProxy(inviterUUID, 'POST', "/api/v3/groups", {'type': 'party', 'privacy': 'private', 'name': inviter}).text)['data']['id']
     #Finally try to make this user (self) join the party
     group_id_returned = proxy.setup_party(self.testUserUUID, inviter_group_id, inviter_id)
     self.assertEqual(group_id_returned, inviter_group_id)
     #Now try to join again, it should throw an error
     with self.assertRaises(RuntimeError):
       proxy.setup_party(self.testUserUUID, inviter_group_id, inviter_id)
     delete_inviter = proxy.habiticaProxy(inviterUUID, "DELETE", "/api/v3/user", {'password': inviter})
     edb.get_habitica_db().remove({'user_id': inviterUUID})
Example #15
0
def get_tasks_from_habitica(user_id):
    tasks_uri = "/api/v3/tasks/user"
    # Get all tasks from the user
    try:
        result = hp.habiticaProxy(user_id, 'GET', tasks_uri, None)
        tasks = result.json()
    except AssertionError as e:
        logging.info("User %s has not registered for habitica, returning empty tasks" % user_id)
        tasks = {"data": []}

    logging.debug("For user %s, retrieved %s tasks from habitica" %
                  (user_id, len(tasks)))
    return tasks
Example #16
0
def get_tasks_from_habitica(user_id):
    tasks_uri = "/api/v3/tasks/user"
    # Get all tasks from the user
    try:
        result = hp.habiticaProxy(user_id, 'GET', tasks_uri, None)
        tasks = result.json()
    except AssertionError as e:
        logging.info("User %s has not registered for habitica, returning empty tasks" % user_id)
        tasks = {"data": []}

    logging.debug("For user %s, retrieved %s tasks from habitica" %
                  (user_id, len(tasks)))
    return tasks
 def testCreateNewHabit(self):
   new_habit = {'type': "habit", 'text': randomGen(),
                'notes': 'AUTOCHECK: {"mapper": "active_distance",'
                         '"args": {"walk_scale": 1000, "bike_scale": 3000}}'}
   habit_id = proxy.create_habit(self.testUUID, new_habit)
   logging.debug("in testCreateNewHabit, the new habit id is = %s" % habit_id)
   #Get user's list of habits and check that new habit is there
   response = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None)
   logging.debug("in testCreateNewHabit, GET habits response = %s" % response)
   habits = response.json()
   logging.debug("in testCreateNewHabit, this user's list of habits = %s" % habits)
   self.assertTrue(habit['_id'] == habit_id for habit in habits['data'])
   self.assertTrue(habit['text'] == new_habit['text'] for habit in habits['data'])
 def testCreateNewHabit(self):
   new_habit = {'type': "habit", 'text': randomGen(),
                'notes': 'AUTOCHECK: {"mapper": "active_distance",'
                         '"args": {"walk_scale": 1000, "bike_scale": 3000}}'}
   habit_id = proxy.create_habit(self.testUUID, new_habit)
   logging.debug("in testCreateNewHabit, the new habit id is = %s" % habit_id)
   #Get user's list of habits and check that new habit is there
   response = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None)
   logging.debug("in testCreateNewHabit, GET habits response = %s" % response)
   habits = response.json()
   logging.debug("in testCreateNewHabit, this user's list of habits = %s" % habits)
   self.assertTrue(habit['_id'] == habit_id for habit in habits['data'])
   self.assertTrue(habit['text'] == new_habit['text'] for habit in habits['data'])
  def testSleep(self):
      # The user information is randomly generated every time, so
      # every test has to start with creating the user
      sampleAuthMessage1Ad = ad.AttrDict(self.sampleAuthMessage1)
      proxy.habiticaRegister(sampleAuthMessage1Ad.username, sampleAuthMessage1Ad.email,
                             sampleAuthMessage1Ad.password, sampleAuthMessage1Ad.our_uuid)
      ret_sleep = proxy.habiticaProxy(self.testUserUUID, "POST",
                                        "/api/v3/user/sleep",
                                        {'data': True})
      ret_profile = proxy.habiticaProxy(self.testUserUUID, "GET",
                                        "/api/v3/user", None)
      ret_json = ret_profile.json()
      # User should be sleeping
      self.assertEqual(ret_json['data']['preferences']['sleep'], True)

      ret_sleep = proxy.habiticaProxy(self.testUserUUID, "POST",
                                      "/api/v3/user/sleep",
                                      {'data': False})

      ret_profile = proxy.habiticaProxy(self.testUserUUID, "GET",
                                        "/api/v3/user", None)
      ret_json = ret_profile.json()
      # User should not be sleeping
      self.assertEqual(ret_json['data']['preferences']['sleep'], False)
    def testSleep(self):
        # The user information is randomly generated every time, so
        # every test has to start with creating the user
        sampleAuthMessage1Ad = ad.AttrDict(self.sampleAuthMessage1)
        proxy.habiticaRegister(sampleAuthMessage1Ad.username,
                               sampleAuthMessage1Ad.email,
                               sampleAuthMessage1Ad.password,
                               sampleAuthMessage1Ad.our_uuid)
        ret_sleep = proxy.habiticaProxy(self.testUserUUID, "POST",
                                        "/api/v3/user/sleep", {'data': True})
        ret_profile = proxy.habiticaProxy(self.testUserUUID, "GET",
                                          "/api/v3/user", None)
        ret_json = ret_profile.json()
        # User should be sleeping
        self.assertEqual(ret_json['data']['preferences']['sleep'], True)

        ret_sleep = proxy.habiticaProxy(self.testUserUUID, "POST",
                                        "/api/v3/user/sleep", {'data': False})

        ret_profile = proxy.habiticaProxy(self.testUserUUID, "GET",
                                          "/api/v3/user", None)
        ret_json = ret_profile.json()
        # User should not be sleeping
        self.assertEqual(ret_json['data']['preferences']['sleep'], False)
 def testGetUserProfile(self):
     # The user information is randomly generated every time, so
     # every test has to start with creating the user
     sampleAuthMessage1Ad = ad.AttrDict(self.sampleAuthMessage1)
     proxy.habiticaRegister(sampleAuthMessage1Ad.username, sampleAuthMessage1Ad.email,
                            sampleAuthMessage1Ad.password, sampleAuthMessage1Ad.our_uuid)
     ret_profile = proxy.habiticaProxy(self.testUserUUID, "GET",
                                       "/api/v3/user", None)
     ret_json = ret_profile.json()
     logging.debug("Retrieved profile with keys %s" % ret_json.keys())
     logging.debug("profile data keys = %s" % ret_json['data'].keys())
     # User has just been created, so has no gear
     self.assertEqual(ret_json['data']['achievements']['ultimateGearSets'],
                      {'warrior': False, 'rogue': False, 'wizard': False,
                       'healer': False})
     self.assertEqual(ret_json['data']['newMessages'], {})
 def testGetUserProfile(self):
     # The user information is randomly generated every time, so
     # every test has to start with creating the user
     sampleAuthMessage1Ad = ad.AttrDict(self.sampleAuthMessage1)
     proxy.habiticaRegister(sampleAuthMessage1Ad.username, sampleAuthMessage1Ad.email,
                            sampleAuthMessage1Ad.password, sampleAuthMessage1Ad.our_uuid)
     ret_profile = proxy.habiticaProxy(self.testUserUUID, "GET",
                                       "/api/v3/user", None)
     ret_json = ret_profile.json()
     logging.debug("Retrieved profile with keys %s" % list(ret_json.keys()))
     logging.debug("profile data keys = %s" % list(ret_json['data'].keys()))
     # User has just been created, so has no gear
     self.assertEqual(ret_json['data']['achievements']['ultimateGearSets'],
                      {'warrior': False, 'rogue': False, 'wizard': False,
                       'healer': False})
     self.assertEqual(ret_json['data']['newMessages'], {})
Example #23
0
 def testCreateNewHabit(self):
     new_habit = {'type': "habit", 'text': randomGen()}
     habit_id = proxy.create_habit(self.testUUID, new_habit)
     logging.debug("in testCreateNewHabit, the new habit id is = %s" %
                   habit_id)
     #Get user's list of habits and check that new habit is there
     response = proxy.habiticaProxy(self.testUUID, 'GET',
                                    "/api/v3/tasks/user?type=habits", None)
     logging.debug("in testCreateNewHabit, GET habits response = %s" %
                   response)
     habits = response.json()
     logging.debug(
         "in testCreateNewHabit, this user's list of habits = %s" % habits)
     self.assertTrue(habit['_id'] == habit_id for habit in habits['data'])
     self.assertTrue(habit['text'] == new_habit['text']
                     for habit in habits['data'])
Example #24
0
def find_existing_auto_tasks(uuid):
    method_uri = "/api/v3/tasks/user"
    get_habits_uri = method_uri + "?type=habits"
    #First, get all habits and check if the habit requested already exists
    result = proxy.habiticaProxy(uuid, 'GET', get_habits_uri, None)
    habits = result.json()
    auto_tasks = []
    for habit in habits['data']:
        print(habit['text'], habit["notes"], habit["id"])
        if "automatically" in habit['notes']:
            logging.debug("Found auto task %s, %s, %s" %
                          (habit['text'], habit['notes'], habit['id']))
            auto_tasks.append(habit)
        else:
            if len(habit["challenge"]) > 0:
                logging.info("Found challenge task %s, %s, %s, unsure what to do" %
                             (habit['text'], habit['notes'], habit['id']))
            else:
                logging.debug("Found manual task %s, %s, %s" %
                              (habit['text'], habit['notes'], habit['id']))
    return auto_tasks
Example #25
0
 def testCreateExistingHabit(self):
     #try to create Bike
     existing_habit = {'type': "habit", 'text': "Bike"}
     habit_id = proxy.create_habit(self.testUUID, existing_habit)
     logging.debug("in testCreateExistingHabit, the new habit id is = %s" %
                   habit_id)
     #search this user's habits for the habit and check if there's exactly one
     response = proxy.habiticaProxy(self.testUUID, 'GET',
                                    "/api/v3/tasks/user?type=habits", None)
     logging.debug("in testCreateExistingHabit, GET habits response = %s" %
                   response)
     habits = response.json()
     logging.debug(
         "in testCreateExistingHabit, this user's list of habits = %s" %
         habits)
     self.assertTrue(habit['_id'] == habit_id for habit in habits['data'])
     self.assertTrue(habit['text'] == new_habit['text']
                     for habit in habits['data'])
     #search this user's habits for the habit and check if there's exactly one
     occurrences = (1 for habit in habits['data']
                    if habit['text'] == existing_habit['text'])
     self.assertEqual(sum(occurrences), 1)
import argparse
import sys
import logging

import emission.core.get_database as edb
import emission.net.ext_service.habitica.proxy as proxy

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "user_email",
        help=
        "the email address of the user whose habitica account you want to clean up"
    )

    args = parser.parse_args()
    del_uuid = edb.get_uuid_db().find_one({'user_email':
                                           args.user_email})['uuid']
    logging.debug("Found uuid %s" % del_uuid)
    del_habitica_creds = edb.get_habitica_db().find_one({'user_id': del_uuid})
    logging.debug("del_habitica_creds = %s" % del_habitica_creds)
    del_result = proxy.habiticaProxy(
        del_uuid, "DELETE", "/api/v3/user",
        {'password': del_habitica_creds['habitica_password']})
    logging.debug("delete result = %s" % del_result)
    def testAutomaticRewardActiveTransportation(self):
        # Create a task that we can retrieve later

        self.new_task_text = randomGen()
        new_habit = {
            'type':
            "habit",
            'text':
            self.new_task_text,
            'notes':
            'AUTOCHECK: {"mapper": "active_distance",'
            '"args": {"walk_scale": 1000, "bike_scale": 3000}}'
        }
        habit_id = proxy.create_habit(self.testUUID, new_habit)

        self.dummy_task = enehat.Task()
        self.dummy_task.task_id = habit_id
        logging.debug("in testAutomaticRewardActiveTransportation,"
                      "the new habit id is = %s and task is %s" %
                      (habit_id, self.dummy_task))

        #Create test data -- code copied from TestTimeGrouping
        key = (2016, 5, 3)
        test_section_list = []
        #
        # Since PST is UTC-7, all of these will be in the same UTC day
        # 13:00, 17:00, 21:00
        # so we expect the local date and UTC bins to be the same
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 6, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 10, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 14, tzinfo=tz.gettz(PST)), PST))

        self._fillModeDistanceDuration(test_section_list)
        #logging.debug("durations = %s" % [s.data.duration for s in test_section_list])

        summary_ts = earmt.group_by_timestamp(
            self.testUUID,
            arrow.Arrow(2016, 5, 1).timestamp,
            arrow.Arrow(2016, 6, 1).timestamp, None, [earmts.get_distance])
        logging.debug(
            "in testAutomaticRewardActiveTransportation, result = %s" %
            summary_ts)

        #Get user data before scoring
        user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertIsNone(user_before)

        # Needed to work, otherwise sections from may won't show up in the query!
        modification = {
            "last_timestamp": arrow.Arrow(2016, 5, 1).timestamp,
            "bike_count": 0,
            "walk_count": 0
        }
        autocheck.save_task_state(self.testUUID, self.dummy_task, modification)

        user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_before['bike_count']), 0)

        habits_before = proxy.habiticaProxy(self.testUUID, 'GET',
                                            "/api/v3/tasks/user?type=habits",
                                            None).json()
        bike_pts_before = [
            habit['history'] for habit in habits_before['data']
            if habit['text'] == self.new_task_text
        ]
        #Score points
        autocheck.give_points_for_all_tasks(self.testUUID)
        #Get user data after scoring and check results
        user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_after['bike_count']), 1500)
        habits_after = proxy.habiticaProxy(self.testUUID, 'GET',
                                           "/api/v3/tasks/user?type=habits",
                                           None).json()
        bike_pts_after = [
            habit['history'] for habit in habits_after['data']
            if habit['text'] == self.new_task_text
        ]
        self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 2)
Example #28
0
def reward_active_transportation(user_id):
    logging.debug("Entering habitica autocheck for user %s" % user_id)
    if edb.get_habitica_db().find({'user_id': user_id}).count() == 1:
        logging.debug("Habitica user: %s" %
                      list(edb.get_habitica_db().find({'user_id': user_id})))
        #make sure habits exist
        #bike
        bike_habit = {
            'type': "habit",
            'text': "Bike",
            'up': True,
            'down': False,
            'priority': 2
        }
        bike_habit_id = proxy.create_habit(user_id, bike_habit)
        #walk
        walk_habit = {
            'type': "habit",
            'text': "Walk",
            'up': True,
            'down': False,
            'priority': 2
        }
        walk_habit_id = proxy.create_habit(user_id, walk_habit)

        #get timestamps
        user_val = list(edb.get_habitica_db().find({"user_id": user_id
                                                    }))[0]['metrics_data']
        timestamp_from_db = user_val['last_timestamp']
        timestamp_now = arrow.utcnow().timestamp

        #Get metrics
        summary_ts = earmt.group_by_timestamp(user_id, timestamp_from_db,
                                              timestamp_now, None,
                                              earmts.get_distance)
        logging.debug("Metrics response: %s" % summary_ts)

        #get distances leftover from last timestamp
        bike_distance = user_val['bike_count']
        walk_distance = user_val['walk_count']

        #iterate over summary_ts and look for bike/on foot
        for item in summary_ts:
            try:
                bike_distance += item.BICYCLING
                logging.debug("bike_distance += %s" % item.BICYCLING)
            except AttributeError:
                logging.debug("no bike")
            try:
                walk_distance += item.ON_FOOT
                logging.debug("walk_distance += %s" % item.ON_FOOT)
            except AttributeError:
                logging.debug("no Android walk")
            try:
                walk_distance += item.WALKING
                logging.debug("walk_distance += %s" % item.WALKING)
            except AttributeError:
                logging.debug("no ios walk")
            try:
                walk_distance += item.RUNNING
                logging.debug("walk_distance += %s" % item.RUNNING)
            except AttributeError:
                logging.debug("no running")

        logging.debug("Finished with bike_distance == %s" % bike_distance)
        logging.debug("Finished with walk_distance == %s" % walk_distance)

        method_uri_walk = "/api/v3/tasks/" + walk_habit_id + "/score/up"
        method_uri_bike = "/api/v3/tasks/" + bike_habit_id + "/score/up"
        #reward user by scoring + habits
        # Walk: +1 for every km
        walk_pts = int(walk_distance // 1000)
        for i in range(walk_pts):
            res = proxy.habiticaProxy(user_id, 'POST', method_uri_walk, None)
            logging.debug("Request to score walk points %s" % res)
        # Bike: +1 for every 3 km
        bike_pts = int(bike_distance // 3000)
        for i in range(bike_pts):
            res2 = proxy.habiticaProxy(user_id, 'POST', method_uri_bike, None)
            logging.debug("Request to score bike points %s" % res2)

        #update the timestamp and bike/walk counts in db
        edb.get_habitica_db().update({"user_id": user_id}, {
            "$set": {
                'metrics_data': {
                    'last_timestamp': arrow.utcnow().timestamp,
                    'bike_count': bike_distance % 3000,
                    'walk_count': walk_distance % 1000
                }
            }
        },
                                     upsert=True)
        logging.debug("Habitica user after update: %s" %
                      list(edb.get_habitica_db().find({'user_id': user_id})))
  def testAutomaticRewardActiveTransportation(self):
    # Create a task that we can retrieve later

    self.new_task_text = randomGen()
    new_habit = {'type': "habit", 'text': self.new_task_text,
                 'notes': 'AUTOCHECK: {"mapper": "active_distance",'
                          '"args": {"walk_scale": 1000, "bike_scale": 3000}}'}
    habit_id = proxy.create_habit(self.testUUID, new_habit)

    self.dummy_task = enehat.Task()
    self.dummy_task.task_id = habit_id
    logging.debug("in testAutomaticRewardActiveTransportation,"
        "the new habit id is = %s and task is %s" % (habit_id, self.dummy_task))

    #Create test data -- code copied from TestTimeGrouping
    key = (2016, 5, 3)
    test_section_list = []
    #
    # Since PST is UTC-7, all of these will be in the same UTC day
    # 13:00, 17:00, 21:00
    # so we expect the local date and UTC bins to be the same
    test_section_list.append(
        self._createTestSection(arrow.Arrow(2016,5,3,6, tzinfo=tz.gettz(PST)),
                                PST))
    test_section_list.append(
        self._createTestSection(arrow.Arrow(2016,5,3,10, tzinfo=tz.gettz(PST)),
                                PST))
    test_section_list.append(
        self._createTestSection(arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)),
                                PST))

    self._fillModeDistanceDuration(test_section_list)
    #logging.debug("durations = %s" % [s.data.duration for s in test_section_list])

    summary_ts = earmt.group_by_timestamp(self.testUUID,
                                       arrow.Arrow(2016,5,1).timestamp,
                                       arrow.Arrow(2016,6,1).timestamp,
                                       None, [earmts.get_distance])
    logging.debug("in testAutomaticRewardActiveTransportation, result = %s" % summary_ts)
    
    #Get user data before scoring
    user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertIsNone(user_before)

    # Needed to work, otherwise sections from may won't show up in the query!
    modification = {"last_timestamp": arrow.Arrow(2016,5,1).timestamp, "bike_count": 0, "walk_count":0}
    autocheck.save_task_state(self.testUUID, self.dummy_task, modification)

    user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_before['bike_count']), 0)

    habits_before = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None).json()
    bike_pts_before = [habit['history'] for habit in habits_before['data'] if habit['text'] == self.new_task_text]
    #Score points
    autocheck.give_points_for_all_tasks(self.testUUID)
    #Get user data after scoring and check results
    user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_after['bike_count']),1500)
    habits_after = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None).json()
    bike_pts_after = [habit['history'] for habit in habits_after['data'] if habit['text'] == self.new_task_text]
    self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 2)
import logging
import uuid

import emission.core.get_database as edb
import emission.core.wrapper.user as ecwu
import emission.net.ext_service.habitica.proxy as proxy

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-e", "--user_email")
    group.add_argument("-u", "--user_uuid")

    args = parser.parse_args()

    if args.user_uuid:
        del_uuid = uuid.UUID(args.user_uuid)
    else:
        del_uuid = ecwu.User.fromEmail(args.user_email).uuid

    logging.debug("Found uuid %s" % del_uuid)
    del_habitica_creds = edb.get_habitica_db().find_one({'user_id': del_uuid})
    logging.debug("del_habitica_creds = %s" % del_habitica_creds)
    del_result = proxy.habiticaProxy(del_uuid, "DELETE",
                                     "/api/v3/user",
                                     {'password': del_habitica_creds['habitica_password']})
    logging.debug("delete result = %s" % del_result)
    edb.get_habitica_db().remove({'user_id': del_uuid})
def give_points(user_id, task, curr_state):

    #get timestamps
    # user_val = list(edb.get_habitica_db().find({"user_id": user_id}))[0]['metrics_data']

    # Note that
    walk_scale = task["args"]["walk_scale"]
    bike_scale = task["args"]["bike_scale"]

    if curr_state is None:
        timestamp_from_db = arrow.utcnow().timestamp
        leftover_bike = 0
        leftover_walk = 0
        curr_state = {
            'last_timestamp': timestamp_from_db,
            'bike_count': leftover_bike,
            'walk_count': leftover_walk
        }
    else:
        timestamp_from_db = curr_state['last_timestamp']
        leftover_bike = curr_state["bike_count"]
        leftover_walk = curr_state["walk_count"]

    timestamp_now = arrow.utcnow().timestamp

    #Get metrics
    summary_ts = earmt.group_by_timestamp(user_id, timestamp_from_db,
                                          timestamp_now, None,
                                          [earmts.get_distance])
    logging.debug("Metrics response: %s" % summary_ts)

    if summary_ts["last_ts_processed"] == None:
        new_state = curr_state
    else:
        #get distances leftover from last timestamp
        bike_distance = leftover_bike
        walk_distance = leftover_walk

        #iterate over summary_ts and look for bike/on foot
        for item in summary_ts["result"][0]:
            try:
                bike_distance += item.BICYCLING
                logging.debug("bike_distance += %s" % item.BICYCLING)
            except AttributeError:
                logging.debug("no bike")
            try:
                walk_distance += item.ON_FOOT
                logging.debug("walk_distance += %s" % item.ON_FOOT)
            except AttributeError:
                logging.debug("no Android walk")
            try:
                walk_distance += item.WALKING
                logging.debug("walk_distance += %s" % item.WALKING)
            except AttributeError:
                logging.debug("no ios walk")
            try:
                walk_distance += item.RUNNING
                logging.debug("walk_distance += %s" % item.RUNNING)
            except AttributeError:
                logging.debug("no running")

        logging.debug("Finished with bike_distance == %s" % bike_distance)
        logging.debug("Finished with walk_distance == %s" % walk_distance)

        method_uri_active_distance = "/api/v3/tasks/" + task.task_id + "/score/up"
        #reward user by scoring + habits
        # Walk: +1 for every km
        walk_pts = int(walk_distance // walk_scale)
        for i in range(walk_pts):
            res = proxy.habiticaProxy(user_id, 'POST',
                                      method_uri_active_distance, None)
            logging.debug("Request to score walk points %s" % res)
        # Bike: +1 for every 3 km
        bike_pts = int(bike_distance // bike_scale)
        for i in range(bike_pts):
            res2 = proxy.habiticaProxy(user_id, 'POST',
                                       method_uri_active_distance, None)
            logging.debug("Request to score bike points %s" % res2)

        #update the timestamp and bike/walk counts in db
        new_state = {
            'last_timestamp':
            summary_ts["last_ts_processed"] + esp.END_FUZZ_AVOID_LTE,
            'bike_count': bike_distance % bike_scale,
            'walk_count': walk_distance % walk_scale
        }

    logging.debug("Returning %s" % new_state)
    return new_state
def give_points(user_id, task, curr_state):

    #get timestamps
    # user_val = list(edb.get_habitica_db().find({"user_id": user_id}))[0]['metrics_data']

    # Note that
    walk_scale = task["args"]["walk_scale"]
    bike_scale = task["args"]["bike_scale"]

    if curr_state is None:
        timestamp_from_db = arrow.utcnow().timestamp
        leftover_bike = 0
        leftover_walk = 0
        curr_state = {'last_timestamp': timestamp_from_db,
                     'bike_count': leftover_bike,
                     'walk_count': leftover_walk}
    else:
        timestamp_from_db = curr_state['last_timestamp']
        leftover_bike = curr_state["bike_count"]
        leftover_walk = curr_state["walk_count"]

    timestamp_now = arrow.utcnow().timestamp
    
    #Get metrics
    summary_ts = earmt.group_by_timestamp(user_id, timestamp_from_db, timestamp_now,
                                          None, [earmts.get_distance])
    logging.debug("Metrics response: %s" % summary_ts)
    
    if summary_ts["last_ts_processed"] == None:
      new_state = curr_state
    else:
      #get distances leftover from last timestamp
      bike_distance = leftover_bike
      walk_distance = leftover_walk

      #iterate over summary_ts and look for bike/on foot
      for item in summary_ts["result"][0]:
        try:
            bike_distance += item.BICYCLING
            logging.debug("bike_distance += %s" % item.BICYCLING)
        except AttributeError:
            logging.debug("no bike")
        try:
            walk_distance += item.ON_FOOT
            logging.debug("walk_distance += %s" % item.ON_FOOT)
        except AttributeError:
            logging.debug("no Android walk")
        try:
            walk_distance += item.WALKING
            logging.debug("walk_distance += %s" % item.WALKING)
        except AttributeError:
            logging.debug("no ios walk")
        try:
            walk_distance += item.RUNNING
            logging.debug("walk_distance += %s" % item.RUNNING)
        except AttributeError:
            logging.debug("no running")
      
      logging.debug("Finished with bike_distance == %s" % bike_distance)
      logging.debug("Finished with walk_distance == %s" % walk_distance)

      method_uri_active_distance = "/api/v3/tasks/"+ task.task_id + "/score/up"
      #reward user by scoring + habits
      # Walk: +1 for every km
      walk_pts = int(walk_distance//walk_scale)
      for i in range(walk_pts):
        res = proxy.habiticaProxy(user_id, 'POST', method_uri_active_distance, None)
        logging.debug("Request to score walk points %s" % res)
      # Bike: +1 for every 3 km
      bike_pts = int(bike_distance//bike_scale)
      for i in range(bike_pts):
        res2 = proxy.habiticaProxy(user_id, 'POST', method_uri_active_distance, None)
        logging.debug("Request to score bike points %s" % res2)

      #update the timestamp and bike/walk counts in db
      new_state = {'last_timestamp': summary_ts["last_ts_processed"] + esp.END_FUZZ_AVOID_LTE,
              'bike_count': bike_distance%bike_scale,
              'walk_count': walk_distance%walk_scale}

    logging.debug("Returning %s" % new_state)
    return new_state