Пример #1
0
def login_api(request):
    try:
        params = extract_post_params(request)
        if 'username' in params and 'password' in params:
            username = params['username']
            password = params['password']
            print('-------------- Sign In -------------')
            print("User: "******"\tPassword: ", password)
            if is_user_valid(username, password):
                participant = Participant.objects.get(id=username)
                participant.last_login_datetime = datetime.datetime.now(
                ).timestamp()
                participant.save()
                return JsonResponse(data={'result': RES_SUCCESS})
            else:
                return JsonResponse(data={
                    'result': RES_FAILURE,
                    'reason': 'wrong credentials passed'
                })
        else:
            return JsonResponse(data={'result': RES_BAD_REQUEST})
    except Exception or ValueError as e:
        print(str(e))
        return JsonResponse(
            data={
                'result': RES_BAD_REQUEST,
                'reason':
                'Username or Password was not passed as a POST argument!'
            })
Пример #2
0
def handle_usage_stats_submit(request):
    try:
        params = extract_post_params(request)
        if 'username' not in params or 'password' not in params or 'app_usage' not in params:
            raise ValueError(
                'username/password/app_usage is not in request params')
        if not is_user_valid(params['username'], params['password']):
            return JsonResponse({'result': RES_FAILURE})
        else:
            username = params['username']
            participant = Participant.objects.get(id=username)
            for element in params['app_usage'].split(','):
                package_name, last_time_used, total_time_in_foreground = [
                    int(value) if value.isdigit() else value
                    for value in element.split(' ')
                ]
                app_usage_stats.store_usage_changes(
                    user=participant,
                    package_name=package_name,
                    end_timestamp=last_time_used,
                    total_time_in_foreground=total_time_in_foreground)
            return JsonResponse(data={'result': RES_SUCCESS})
    except ValueError as e:
        print(e)
        return JsonResponse({'result': RES_BAD_REQUEST})
Пример #3
0
def heartbeat_smartphone_api(request):
    try:
        params = extract_post_params(request)
        if 'username' in params and 'password' in params:
            username = params['username']
            password = params['password']
            if is_user_valid(username, password):
                print("Heartbeat phone: ", username)
                participant = Participant.objects.get(id=username)
                participant.heartbeat_smartphone = datetime.datetime.now(
                ).timestamp()
                participant.save()
                return JsonResponse(data={'result': RES_SUCCESS})
            else:
                return JsonResponse(data={
                    'result': RES_FAILURE,
                    'reason': 'wrong credentials passed'
                })
        else:
            return JsonResponse(data={'result': RES_BAD_REQUEST})
    except ValueError as e:
        print(str(e))
        return JsonResponse(
            data={
                'result': RES_BAD_REQUEST,
                'reason':
                'Username or Password was not passed as a POST argument!'
            })
Пример #4
0
def register_api(request):
    try:
        params = extract_post_params(request)
        if 'username' in params and 'password' in params and 'phone_num' in params:
            username = params['username']
            phone = params['phone_num']
            password = params['password']
            if user_exists(username):
                return JsonResponse(data={
                    'result': RES_FAILURE,
                    'reason': 'username is taken'
                })
            else:
                new_participant = models.Participant(
                    username=username,
                    phone_num=phone,
                    password=password,
                    register_datetime=datetime.datetime.now().timestamp())
                new_participant.save()

                for i in range(1, 32):
                    ema_user_data = Response(username=new_participant,
                                             day_num=i)
                    ema_user_data.save()

                return JsonResponse(data={'result': RES_SUCCESS})
    except ValueError as e:
        print(str(e))
        return JsonResponse(
            data={
                'result':
                RES_BAD_REQUEST,
                'reason':
                'either username or phone number or password was not passed as a POST argument!'
            })
Пример #5
0
def submit_geofencing_api(request):
    try:
        params = extract_post_params(request)
        if 'username' not in params or 'password' not in params or 'locations' not in params:
            raise ValueError('username/password/locations is not in request params')
        if not is_user_valid(params['username'], params['password']):
            return JsonResponse({'result': RES_FAILURE})
        else:
            username = params['username']
            participant = Participant.objects.get(id=username)
            reg_time = participant.register_datetime
            json_array_locations = params["locations"]
            for item in json_array_locations:
                location_id = item['id']
                time_enter = item['timestamp_enter']
                time_exit = item['timestamp_exit']

                if time_enter == 0 or time_exit == 0:
                    return JsonResponse({'result': RES_BAD_REQUEST, "message": "location enter/exit time is 0"})

                new_location = models.geofencing(username=participant, timestamp_enter=time_enter, timestamp_exit=time_exit, location=location_id, day_num=get_day_num(time_exit, reg_time))
                new_location.save()
                print("{0}, {1}, {2}".format(location_id, time_enter, time_exit))

            return JsonResponse(data={'result': RES_SUCCESS})
    except ValueError as e:
        print(e)
        return JsonResponse({'result': RES_BAD_REQUEST})
Пример #6
0
def register_api(request):
    try:
        params = extract_post_params(request)
        if 'username' in params and 'password' in params and 'phone_num' in params and 'device_info' in params:
            username = params['username']
            phone = params['phone_num']
            name = params['name']
            device_info = params['device_info']
            password = params['password']
            print('-------------- Sign Up -------------')
            print("User: "******"\tPassword: ", password)

            now_date = datetime.datetime.now()

            if user_exists(username):
                return JsonResponse(data={
                    'result': RES_FAILURE,
                    'reason': 'username is taken'
                })
            else:
                # create a new participant
                new_participant = models.Participant(
                    id=username,
                    phone_num=phone,
                    name=name,
                    device_info=device_info,
                    password=password,
                    register_datetime=now_date.timestamp(),
                    heartbeat_smartwatch=now_date.timestamp(),
                    heartbeat_smartphone=now_date.timestamp())
                new_participant.save()

                # create EMA entries for this user
                for day in range(1, EXPERIMENT_DURATION + 1):
                    for order in range(1, NUMBER_OF_EMA + 1):
                        now_date = now_date.replace(hour=EMA_HOURS[order - 1],
                                                    minute=0,
                                                    second=0,
                                                    microsecond=0)
                        ema_user_data = Response(
                            username=new_participant,
                            day_num=day,
                            ema_order=order,
                            time_expected=now_date.timestamp())
                        ema_user_data.save()
                    now_date = now_date + datetime.timedelta(days=1)

                return JsonResponse(data={'result': RES_SUCCESS})
        else:
            return JsonResponse(data={'result': RES_BAD_REQUEST})
    except Exception or ValueError as e:
        print(str(e))
        return JsonResponse(
            data={
                'result':
                RES_BAD_REQUEST,
                'reason':
                'either username or phone number or password was not passed as a POST argument!'
            })
Пример #7
0
def get_user_stat_api(request):
    try:
        params = extract_post_params(request)
        if 'username' in params and 'password' in params:
            username = params['username']
            password = params['password']
            if is_user_valid(username, password):
                participant = Participant.objects.get(id=username)
                # User stats variables
                current_day_num = participant.current_day_num()
                ema_counter = 0  # num of responded emas for that day
                last_hb_phone = participant.heartbeat_smartphone_diff_min(
                )  # in minutes
                data_loaded_phone = participant.daily_data_load()

                # region Number of ema responses
                # ema_obj = Response.objects.filter(username=participant_obj, day_num=current_day_num)

                ema_responses = Response.objects.filter(
                    username=participant,
                    day_num=current_day_num).order_by('time_expected')
                ema_resp = []
                stress_data = []
                for ema in ema_responses:
                    if ema.time_responded != 0:
                        ema_resp += ['1']
                        stress_data += [ema.answer1]
                        ema_counter += 1
                    else:
                        ema_resp += ['0']

                return JsonResponse(
                    data={
                        'result': RES_SUCCESS,
                        'day_number': current_day_num,
                        'ema_responses_number': ema_counter,
                        'ema_responses': ema_resp,
                        'heartbeat_phone': last_hb_phone,
                        'data_loaded_phone': data_loaded_phone,
                        'stress_data': stress_data
                    })
            else:
                return JsonResponse(data={
                    'result': RES_FAILURE,
                    'reason': 'wrong credentials passed'
                })
        else:
            return JsonResponse(data={'result': RES_BAD_REQUEST})
    except ValueError as e:
        print(str(e))
        return JsonResponse(
            data={
                'result': RES_BAD_REQUEST,
                'reason':
                'Username or Password was not passed as a POST argument!'
            })
Пример #8
0
def submit_audio(request):
    try:
        params = extract_post_params(request)
        if 'username' not in params or 'password' not in params or 'file' not in request.FILES:
            raise ValueError('username/password/file is not in request params')
        if not is_user_valid(params['username'], params['password']):
            return JsonResponse({'result': RES_FAILURE})
        else:
            username = params['username']
            audio_file = request.FILES['file']
            timestamp = audio_file.name[:audio_file.name.index('.')]
            audio_data = audio_file.read()

            with open('audio/%s_%s.mp4' % (username, timestamp), 'wb') as w:
                w.write(audio_data)

            convert_command = 'C:\\ffmpeg\\bin\\ffmpeg.exe -i audio/%s_%s.mp4 -ab 160k -ac 2 -ar 44100 -vn audio/%s_%s.wav' % (username, timestamp, username, timestamp)
            subprocess.call(convert_command, shell=True)
            return JsonResponse(data={'result': RES_SUCCESS})
    except ValueError as e:
        print(e)
        return JsonResponse({'result': RES_BAD_REQUEST})
Пример #9
0
def submit_api(request):
    try:
        params = extract_post_params(request)

        if 'username' not in params or 'password' not in params or 'file' not in request.FILES:
            raise ValueError('username/password/file is not in request params')
        if not is_user_valid(params['username'], params['password']):
            print("Response RES_FAILURE")
            return JsonResponse({'result': RES_FAILURE})
        else:
            username = params['username']
            participant = Participant.objects.get(id=username)
            reg_time = participant.register_datetime

            csv_file = request.FILES['file']
            device_name = csv_file.name.split('_')[0]
            data_set = csv_file.read().decode('ascii')
            io_string = io.StringIO(data_set)

            print("File received", username, ";\tsize: ",
                  len(data_set) / 1024, ";\tfilename: ", csv_file.name)

            if len(data_set) == 0:
                print("File length is 0")
                return JsonResponse(data={'result': RES_SUCCESS})

            new_filename, created = ReceivedFilenames.objects.get_or_create(
                username=participant, filename=csv_file.name)
            if created:
                new_filename.save()
            else:
                print("Duplicate file", new_filename.username.id,
                      ";\tfilename: ", new_filename.filename)
                return JsonResponse(data={'result': RES_SUCCESS})

            data_src_tmp = ''
            line_num_tmp = 0
            try:
                # region Processing the received data

                file_read = csv.reader(io_string, delimiter=',', quotechar="|")

                for idx, column in enumerate(file_read):
                    data_src = column[0]
                    values = column[1]

                    data_src_tmp = data_src
                    line_num_tmp = idx

                    if data_src == SRC_ACC_SP:
                        # new_raw_data = models.acc_sp(username=participant, timestamp=timestamp, value_x=val_x, value_y=val_y, value_z=val_z, ema_order=ema_order, day_num=get_day_num(float(timestamp), reg_time))
                        elems = values.split(" ")
                        ema_order = 0
                        if len(elems) == 4:
                            # old version
                            timestamp, val_x, val_y, val_z = elems
                            pass
                        else:
                            timestamp, val_x, val_y, val_z, ema_order = elems
                        new_raw_data = models.acc_sp(username=participant,
                                                     timestamp=timestamp,
                                                     value_x=val_x,
                                                     value_y=val_y,
                                                     value_z=val_z,
                                                     ema_order=ema_order,
                                                     day_num=get_day_num(
                                                         float(timestamp),
                                                         reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_ACC_SW:
                        timestamp, val_x, val_y, val_z, ema_order = values.split(
                            " ")
                        new_raw_data = models.acc_sw(username=participant,
                                                     timestamp=timestamp,
                                                     value_x=val_x,
                                                     value_y=val_y,
                                                     value_z=val_z,
                                                     ema_order=ema_order,
                                                     day_num=get_day_num(
                                                         float(timestamp),
                                                         reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_STEP_DETECTOR:
                        timestamp = values
                        new_raw_data = models.step_detector(
                            username=participant,
                            timestamp=timestamp,
                            day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_SIGNIFICANT_MOTION:
                        timestamp = values
                        new_raw_data = models.significant_motion(
                            username=participant,
                            timestamp=timestamp,
                            day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_UNLOCKED_DUR:
                        start, end, duration = values.split(" ")
                        new_raw_data = models.unlocked_dur(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            duration=duration,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_STATIONARY_DUR:
                        start, end, duration = values.split(" ")
                        new_raw_data = models.stationary_dur(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            duration=duration,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_PHONE_CALLS:
                        start, end, call_type, duration = values.split(" ")
                        new_raw_data = models.phone_calls(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            call_type=call_type,
                            duration=duration,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_LIGHT:
                        timestamp, value = values.split(" ")
                        new_raw_data = models.light_intensity(
                            username=participant,
                            timestamp=timestamp,
                            value=value,
                            day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_HRM_SW:
                        timestamp, value, ema_order = values.split(" ")
                        new_raw_data = models.hrm(username=participant,
                                                  timestamp=timestamp,
                                                  value=value,
                                                  ema_order=ema_order,
                                                  day_num=get_day_num(
                                                      float(timestamp),
                                                      reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_GPS_LOCATIONS:
                        timestamp, lat, lng, accuracy, altitude = values.split(
                            " ")
                        new_raw_data = models.gps_locations(
                            username=participant,
                            timestamp=timestamp,
                            lat=lat,
                            lng=lng,
                            accuracy=accuracy,
                            altitude=altitude,
                            day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_ACTIVITY:
                        timestamp, activity_type, confidence = values.split(
                            " ")
                        new_raw_data = models.activities(
                            username=participant,
                            timestamp=timestamp,
                            activity_type=activity_type,
                            confidence=confidence,
                            day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_TOTAL_DIST_COVERED:
                        start, end, value, ema_order = values.split(" ")
                        new_raw_data = models.total_dist_covered(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            value=value,
                            ema_order=ema_order,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_MAX_DIST_FROM_HOME:
                        start, end, value, ema_order = values.split(" ")
                        new_raw_data = models.max_dist_from_home(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            value=value,
                            ema_order=ema_order,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_MAX_DIST_TWO_LOCATIONS:
                        start, end, value, ema_order = values.split(" ")
                        new_raw_data = models.max_dist_two_locations(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            value=value,
                            ema_order=ema_order,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_RADIUS_OF_GYRATION:
                        start, end, value, ema_order = values.split(" ")
                        new_raw_data = models.radius_of_gyration(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            value=value,
                            ema_order=ema_order,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_STDDEV_OF_DISPLACEMENT:
                        start, end, value, ema_order = values.split(" ")
                        new_raw_data = models.stddev_of_displacement(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            value=value,
                            ema_order=ema_order,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_NUM_OF_DIF_PLACES:
                        start, end, value, ema_order = values.split(" ")
                        new_raw_data = models.num_of_dif_places(
                            username=participant,
                            timestamp_start=start,
                            timestamp_end=end,
                            value=value,
                            ema_order=ema_order,
                            day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_AUDIO_LOUDNESS:
                        timestamp, value = values.split(" ")
                        new_raw_data = models.audio_loudness(
                            username=participant,
                            timestamp=timestamp,
                            value=value,
                            day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    '''
                    elif data_src == SRC_SP_STATIONARY_DUR:
                        start, end, duration = values.split(" ")
                        new_raw_data = models.stationary_dur(username=participant, timestamp_start=start, timestamp_end=end, duration=duration, day_num=get_day_num(float(end), reg_time))
                        new_raw_data.save()
                    elif data_src == SRC_SP_APP_USAGE:
                        timestamp, pkg_name, app_name, duration = values.split("||")
                        new_raw_data = models.app_usage(username=participant, timestamp_start=timestamp, pkg_name=pkg_name, app_name=app_name, value=duration, day_num=get_day_num(float(timestamp), reg_time))
                        new_raw_data.save()
                    '''
                # endregion

                # region Setting amount of data loaded by user
                cur_datetime = datetime.datetime.now()
                last_ds_phone = datetime.datetime.fromtimestamp(
                    participant.last_ds_smartphone)
                last_ds_watch = datetime.datetime.fromtimestamp(
                    participant.last_ds_smartwatch)

                if device_name == DEVICE_TYPE_PHONE:
                    if cur_datetime.day == last_ds_phone.day:
                        participant.daily_data_size_smartphone = participant.daily_data_size_smartphone + (
                            len(data_set) / 1024)
                    else:
                        participant.daily_data_size_smartphone = len(
                            data_set) / 1024
                    participant.last_ds_smartphone = cur_datetime.timestamp()
                elif device_name == DEVICE_TYPE_WATCH:
                    if cur_datetime.day == last_ds_watch.day:
                        participant.daily_data_size_smartwatch = participant.daily_data_size_smartwatch + (
                            len(data_set) / 1024)
                    else:
                        participant.daily_data_size_smartwatch = len(
                            data_set) / 1024
                    participant.last_ds_smartwatch = cur_datetime.timestamp()

                participant.save()
                # endregion
            except Exception as ex:
                print("Ex: ", ex)
                print("filename: ", csv_file.name, data_src_tmp, line_num_tmp)
                print("Response RES_FAILURE", username, ";\tsize: ",
                      len(data_set) / 1024, ";\tfilename: ", csv_file.name)
                return JsonResponse({'result': RES_FAILURE})

            print("Response RES_SUCCESS", username, ";\tsize: ",
                  len(data_set) / 1024, ";\tfilename: ", csv_file.name)
            return JsonResponse(data={'result': RES_SUCCESS})
    except ValueError as e:
        print(e)
        print("Response RES_BAD_REQUEST")
        return JsonResponse({'result': RES_BAD_REQUEST})
Пример #10
0
def submit_api(request):
    try:
        params = extract_post_params(request)
        if 'username' not in params or 'password' not in params or 'file' not in request.FILES:
            raise ValueError('username/password/file is not in request params')
        if not is_user_valid(params['username'], params['password']):
            return JsonResponse({'result': RES_FAILURE})
        else:
            username = params['username']
            participant = Participant.objects.get(username=username)

            csv_file = request.FILES['file']
            device_name = csv_file.name.split('_')[0]
            data_set = csv_file.read().decode('UTF-8')

            # region Precessing the received data
            print("User: "******";\tsource: ", device_name)
            print("File: ", csv_file.name, ";\tsize: ", len(data_set) / 1024)
            io_string = io.StringIO(data_set)
            for column in csv.reader(io_string, delimiter=',', quotechar="|"):
                data_src = column[0]
                timestamp = column[1]
                values = column[2]

                if data_src == DATA_SRC_ACC:
                    val_x, val_y, val_z = values.split(" ")
                    new_raw_data = models.acc(username=participant,
                                              timestamp=timestamp,
                                              value_x=val_x,
                                              value_y=val_y,
                                              value_z=val_z,
                                              device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_STEP_DETECTOR:
                    new_raw_data = models.step_detector(username=participant,
                                                        timestamp=timestamp,
                                                        device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_SIGNIFICANT_MOTION:
                    new_raw_data = models.significant_motion(
                        username=participant,
                        timestamp=timestamp,
                        device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_STATIONARY_DUR:
                    new_raw_data = models.stationary_dur(
                        username=participant,
                        timestamp_endtime=timestamp,
                        duration=values,
                        device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_UNLOCKED_DUR:
                    new_raw_data = models.unlocked_dur(
                        username=participant,
                        timestamp_endtime=timestamp,
                        duration=values,
                        device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_PHONE_CALLS:
                    call_type, duration = values.split("/")
                    new_raw_data = models.phone_calls(username=participant,
                                                      timestamp=timestamp,
                                                      call_type=call_type,
                                                      duration=duration,
                                                      device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_LIGHT:
                    new_raw_data = models.light_intensity(username=participant,
                                                          timestamp=timestamp,
                                                          value=values,
                                                          device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_APP_USAGE:
                    app_name, duration = values.split("|")
                    new_raw_data = models.app_usage(username=participant,
                                                    timestamp=timestamp,
                                                    app_name=app_name,
                                                    value=duration,
                                                    device=device_name)
                    new_raw_data.save()
                elif data_src == DATA_SRC_HRM:
                    new_raw_data = models.hrm(username=participant,
                                              timestamp=timestamp,
                                              value=values,
                                              device=device_name)
                    new_raw_data.save()
            # endregion

            # region Setting amount of data loaded by user
            cur_datetime = datetime.datetime.now()
            last_heart_beat_phone = datetime.datetime.fromtimestamp(
                participant.heartbeat_smartphone)
            last_heart_beat_watch = datetime.datetime.fromtimestamp(
                participant.heartbeat_smartwatch)

            if device_name == DEVICE_TYPE_PHONE:
                if cur_datetime.day == last_heart_beat_phone.day:
                    participant.daily_data_size_smartphone = participant.daily_data_size_smartphone + (
                        len(data_set) / 1024)
                else:
                    participant.daily_data_size_smartphone = len(
                        data_set) / 1024
            elif device_name == DEVICE_TYPE_WATCH:
                if cur_datetime.day == last_heart_beat_watch.day:
                    participant.daily_data_size_smartwatch = participant.daily_data_size_smartwatch + (
                        len(data_set) / 1024)
                else:
                    participant.daily_data_size_smartwatch = len(
                        data_set) / 1024
            participant.save()
            # endregion

            return JsonResponse(data={'result': RES_SUCCESS})
    except ValueError as e:
        print(e)
        return JsonResponse({'result': RES_BAD_REQUEST})