예제 #1
0
def create_sleep_from_log(user, sleep):
    log_id = sleep["logId"]

    try:
        sleep = Sleep.get(fitbit_id=log_id)
        return False
    except:
        main_sleep = sleep["isMainSleep"]
        start_time = log_date_for_string(user, sleep["startTime"])
        duration = int(sleep["duration"])
        end_time = start_time + timedelta(milliseconds=duration)

        s = Sleep.objects.create(is_main_sleep=main_sleep,
                                 fitbit_id=log_id,
                                 start_time=string_for_date(start_time),
                                 duration=duration,
                                 end_time=string_for_date(end_time),
                                 user=user)
        watervibe.register_sample("fitbit",
                                  user.id,
                                  "sleep",
                                  day_of_the_week=start_time.isoweekday())

        s.save()
        return True
예제 #2
0
    def test_sleep_log(self):
        date = string_for_date(now() - timedelta(days=1))
        print "[****START TEST SLEEP LOG %s****]" % date
        log = users.sleep_log(self.user, now() - timedelta(days=1))
        print "[****START TEST SLEEP LOG %s****]" % date

        print log
예제 #3
0
def sleep_log(user, date):
    date_string = string_for_date(date, time=False)
    fitted_sleep_url = sleep_log_url.replace("-", user.fitbit_id).replace(
        "*", date_string)
    headers = authorization.api_request_header_for(user)
    response = requests.get(fitted_sleep_url, headers=headers)
    json_response = json.loads(response.content)

    try:
        return json_response["sleep"]
    except:
        return []
예제 #4
0
def refresh_access_for_user(user):
	access_info, errors = request_access_info(refresh_token = user.fitbit_refresh_token, grant_type = "refresh_token")
	if errors is not None:
		return None


	expiration_date = timezone.now() + timedelta(seconds = access_info["expires_in"])
	
	user.fitbit_access_token = access_info["access_token"]
	user.fitbit_refresh_token = access_info["refresh_token"]
	user.fitbit_access_token_expiration = string_for_date(expiration_date)
	user.save()
예제 #5
0
def set_alarm(user, device, date, day):
    fitted_alarm_url = add_alarm_url.replace("-", user.fitbit_id).replace(
        "*", device.fitbit_id)
    headers = authorization.api_request_header_for(user)
    fitbit_t = fitbit_time.time_from_date(date)
    print "Setting alarm for " + fitbit_t
    parameters = {
        'time': fitbit_t,
        'enabled': "true",
        'recurring': "false",
        'weekDays': day
    }
    response = requests.post(fitted_alarm_url,
                             headers=headers,
                             data=parameters)

    json_response = json.loads(response.content)

    try:
        json_response = json_response["trackerAlarm"]
        alarm_id = json_response["alarmId"]
        alarm_time = fitbit_time.string_for_date(date)
        alarm = Alarm.objects.create(fitbit_id=alarm_id,
                                     time=alarm_time,
                                     user=user,
                                     device=device)
        alarm.save()
    except:
        try:
            if json_response["errors"][0]["fieldName"] == 'deviceId':
                # Device probably doesn't support alarms
                device.delete()
                return None
            elif json_response["errors"][0][
                    "message"] == "Cannot add more than 8 alarms to tracker.":
                alarms_cleared = clear_used_alarms_on_device(user, device)
                if alarms_cleared == True:
                    return set_alarm(user, device, date, day)
                print "Failed to set alarm for %s. No spots." % fitbit_t
                return None
            else:
                print "Failed to set alarm for %s. %s" % (fitbit_t,
                                                          json_response)
                return None
        except:
            # Often an authorization error
            print "Failed to set alarm for %s: %s" % (fitbit_t, json_response)
            return None

    print "Success."
    return alarm
예제 #6
0
def authorize(request):

    access_info, errors = request_access_info(code=request.GET['code'])
    if errors is not None:
        return views.error(
            request,
            "Something went wrong authenticating with FitBit. Please try again."
        )

    user_id = access_info["user_id"]
    access_token = access_info["access_token"]
    scope = access_info["scope"]
    refresh_token = access_info["refresh_token"]
    expiration_date = fitbit_time.now() + timedelta(
        seconds=access_info["expires_in"])
    expiration_date = fitbit_time.string_for_date(expiration_date)

    try:
        user = User.objects.get(fitbit_id=user_id)
        user.access_token = access_token
        user.scope = scope
        user.refresh_token = refresh_token
        user.access_token_expiration = expiration_date
        user.save()
    except:
        user = User.objects.create(fitbit_id=user_id,
                                   access_token=access_token,
                                   scope=scope,
                                   refresh_token=refresh_token)
        user.save()

    users.update_profile(user)
    devices = device.get_devices_for(user)

    if devices is None:
        return views.error(
            request,
            "No device on your FitBit account supports silent alarms. Please try again after adding a device to your FitBit account."
        )

    if "sleep" in user.scope:
        subscription.subscribe(user, "sleep")

    import alarms
    if (alarms.user_alarms_count(user) == 8):
        print "User account is full"
        return views.alarms_full(request)

    watervibe.watervibe.register_fitbit_user(user)

    return views.authorization_success(request, user)
예제 #7
0
def sync_logs_of_type(user, type):
    try:
        last_sync = date_for_string(getattr(
            user, "last_%s_sync" % type)).replace(
                tzinfo=dateutil.tz.tzoffset(None, 0)) - timedelta(days=1)
    except:
        last_sync = now() - timedelta(days=30)

    days_since_last_sync = (now() - last_sync).days

    for x in range(1, days_since_last_sync):
        date = last_sync + timedelta(days=x)
        new_log = globals()[type + "_log"](user, date)
        for log in new_log:
            log_id = log["logId"]
            globals()["create_%s_from_log" % type](user, log)

    user.last_sleep_sync = string_for_date(now())
    user.save()