def handleFitbit(self):
     print "----HANDLING FITBIT OAUTH REQUEST----"
     code = self.data[self.data.find("code")+5:self.data.find("HTTP")-1]
     if code == AppTCPHandler.last_code:
         print "----IGNORING DUPLICATE----"
         retval=self.generateClosePage()
         self.outputPage(retval)
         return
     print "{} and {} are not equal".format(code,AppTCPHandler.last_code)
     AppTCPHandler.last_code = code
     payload={"grant_type":"authorization_code",
              "client_id":FitBit.creds['client_id'],
              "redirect_uri":"http://localhost/fitbit",
              "code":code}
     authraw="{}:{}".format(FitBit.creds['client_id'], FitBit.creds['client_secret'])
     b64auth="Basic "+base64.b64encode(authraw)
     print "Code:",code
     print "Payload:",payload
     print "Fitbit:",authraw
     print "Base64Auth:",b64auth
     print "----SENDING TOKEN REQUEST----"
     response=requests.post("https://api.fitbit.com/oauth2/token",
                            data=payload,
                            headers={"Authorization":b64auth,"Content-Type":"application/x-www-form-urlencoded"})
     print response.headers
     print response.text
     parsed = json.loads(response.text)
     FitBit.storeLogin(parsed)
     FitBit.pullFromServer()
     retval=self.generateClosePage()
     self.outputPage(retval)
Exemple #2
0
    def __init__(self):
        self.info_dict = {}
        base = FitBitANT(debug=True)
        if not base.open():
            print "No devices connected!"
            return 1

        self.fitbit = FitBit(base)
        self.remote_info = None
Exemple #3
0
class FitBitClient(object):
    CLIENT_UUID = "2ea32002-a079-48f4-8020-0badd22939e3"
    FITBIT_HOST = "http://client.fitbit.com:80"
    START_PATH = "/device/tracker/uploadData"

    def __init__(self):
        self.info_dict = {}
        base = FitBitANT(debug=True)
        if not base.open():
            print "No devices connected!"
            return 1

        self.fitbit = FitBit(base)
        self.remote_info = None

    def form_base_info(self):
        self.info_dict.clear()
        self.info_dict["beaconType"] = "standard"
        self.info_dict["clientMode"] = "standard"
        self.info_dict["clientVersion"] = "1.3.3"
        self.info_dict["os"] = "Commodore 64"
        self.info_dict["clientId"] = self.CLIENT_UUID
        if self.remote_info:
            self.info_dict = dict(self.info_dict, **self.remote_info)

    def run_upload_request(self):
        self.fitbit.init_tracker_for_transfer()

        url = self.FITBIT_HOST + self.START_PATH

        # Start the request Chain
        self.form_base_info()
        while url is not None:
            res = urllib2.urlopen(url, urllib.urlencode(self.info_dict)).read()
            print res
            r = FitBitResponse(res)
            self.remote_info = r.response
            self.form_base_info()
            op_index = 0
            for o in r.opcodes:
                self.info_dict["opResponse[%d]" % op_index] = base64.b64encode(
                    ''.join([
                        chr(x) for x in self.fitbit.run_opcode(
                            o["opcode"], o["payload"])
                    ]))
                self.info_dict["opStatus[%d]" % op_index] = "success"
                op_index += 1
            urllib.urlencode(self.info_dict)
            print self.info_dict
            if r.host:
                url = "http://%s%s" % (r.host, r.path)
                print url
            else:
                print "No URL returned. Quitting."
                break
        self.fitbit.base.close()
Exemple #4
0
def init(*args):
    global tracker, base
    debug = False
    if len(args) >= 1:
        debug = bool(int(args[0]))
        if debug: print "Debug ON"
    base = getBase(debug)
    if base is None:
        print "No device connected."
        return
    tracker = FitBit(base)
    tracker.init_tracker_for_transfer()
Exemple #5
0
class FitBitClient(object):
    CLIENT_UUID = "2ea32002-a079-48f4-8020-0badd22939e3"
    FITBIT_HOST = "http://client.fitbit.com:80"
    START_PATH = "/device/tracker/uploadData"

    def __init__(self):
        self.info_dict = {}
        base = FitBitANT(debug=True)
        if not base.open():
            print "No devices connected!"
            return 1

        self.fitbit = FitBit(base)
        self.remote_info = None

    def form_base_info(self):
        self.info_dict.clear()
        self.info_dict["beaconType"] = "standard"
        self.info_dict["clientMode"] = "standard"
        self.info_dict["clientVersion"] = "1.3.3"
        self.info_dict["os"] = "Commodore 64"
        self.info_dict["clientId"] = self.CLIENT_UUID
        if self.remote_info:
            self.info_dict = dict(self.info_dict, **self.remote_info)

    def run_upload_request(self):
        self.fitbit.init_tracker_for_transfer()

        url = self.FITBIT_HOST + self.START_PATH

        # Start the request Chain
        self.form_base_info()
        while url is not None:
            res = urllib2.urlopen(url, urllib.urlencode(self.info_dict)).read()
            print res
            r = FitBitResponse(res)
            self.remote_info = r.response
            self.form_base_info()
            op_index = 0
            for o in r.opcodes:
                self.info_dict["opResponse[%d]" % op_index] = base64.b64encode(''.join([chr(x) for x in self.fitbit.run_opcode(o["opcode"], o["payload"])]))
                self.info_dict["opStatus[%d]" % op_index] = "success"
                op_index += 1
            urllib.urlencode(self.info_dict)
            print self.info_dict
            if r.host:
                url = "http://%s%s" % (r.host, r.path)
                print url
            else:
                print "No URL returned. Quitting."
                break
        self.fitbit.base.close()
Exemple #6
0
def init(*args):
    global tracker, base
    debug = False
    if len(args) >= 1:
        debug = bool(int(args[0]))
        if debug: print "Debug ON"
    conn = getConn()
    if conn is None:
        print "No device connected."
        return
    base = ANT(conn)
    tracker = FitBit(base)
    tracker.init_tracker_for_transfer()
Exemple #7
0
class FitBitClient(object):
    CLIENT_UUID = "2ea32002-a079-48f4-8020-0badd22939e3"
    #FITBIT_HOST = "http://client.fitbit.com:80"
    FITBIT_HOST = "https://client.fitbit.com"  # only used for initial request
    START_PATH = "/device/tracker/uploadData"

    def __init__(self):
        self.info_dict = {}
        base = FitBitANT(debug=True)

        for retries in (2, 1, 0):
            try:
                if not base.open():
                    print "No devices connected!"
                    return
            except Exception, e:
                print e
                if retries:
                    print "retrying"
                    time.sleep(5)
                else:
                    raise

        self.fitbit = FitBit(base)
        self.remote_info = None
Exemple #8
0
    def __init__(self):
        self.info_dict = {}
        base = FitBitANT(debug=True)
        if not base.open():
            print "No devices connected!"
            return 1

        self.fitbit = FitBit(base)
        self.remote_info = None
 def handleFitbit(self):
     print "----HANDLING FITBIT OAUTH REQUEST----"
     code = self.data[self.data.find("code") + 5:self.data.find("HTTP") - 1]
     if code == AppTCPHandler.last_code:
         print "----IGNORING DUPLICATE----"
         retval = self.generateClosePage()
         self.outputPage(retval)
         return
     print "{} and {} are not equal".format(code, AppTCPHandler.last_code)
     AppTCPHandler.last_code = code
     payload = {
         "grant_type": "authorization_code",
         "client_id": FitBit.creds['client_id'],
         "redirect_uri": "http://localhost/fitbit",
         "code": code
     }
     authraw = "{}:{}".format(FitBit.creds['client_id'],
                              FitBit.creds['client_secret'])
     b64auth = "Basic " + base64.b64encode(authraw)
     print "Code:", code
     print "Payload:", payload
     print "Fitbit:", authraw
     print "Base64Auth:", b64auth
     print "----SENDING TOKEN REQUEST----"
     response = requests.post("https://api.fitbit.com/oauth2/token",
                              data=payload,
                              headers={
                                  "Authorization":
                                  b64auth,
                                  "Content-Type":
                                  "application/x-www-form-urlencoded"
                              })
     print response.headers
     print response.text
     parsed = json.loads(response.text)
     FitBit.storeLogin(parsed)
     FitBit.pullFromServer()
     retval = self.generateClosePage()
     self.outputPage(retval)
Exemple #10
0
 def __init__(self, debug=False):
     self.info_dict = {}
     self.log_info = {}
     self.time = time.time()
     self.data = []
     base = getBase(debug)
     if base is None:
         print "No base found!"
         exit(1)
     self.fitbit = FitBit(base)
     if not self.fitbit:
         print "No devices connected!"
         exit(1)
Exemple #11
0
 def __init__(self, debug=False):
     self.info_dict = {}
     self.log_info = {}
     self.time = time.time()
     self.data = []
     conn = getConn()
     if conn is None:
         print "No base found!"
         exit(1)
     base = ANT(conn)
     self.fitbit = FitBit(base)
     if not self.fitbit:
         print "No devices connected!"
         exit(1)
Exemple #12
0
 def __init__(self):
     self.info_dict = {}
     base = FitBitANT(debug=True)
     self.fitbit = FitBit(base)
     self.remote_info = None
     for retries in (2, 1, 0):
         try:
             if not base.open():
                 print "No devices connected!"
                 exit(1)
         except Exception, e:
             print e
             if retries:
                 print "retrying"
                 time.sleep(5)
             else:
                 raise
Exemple #13
0
 def __init__(self):
     self.info_dict = {}
     self.fitbit = None
     for base in [bc(debug=self.DEBUG) for bc in self.BASES]:
         for retries in (2, 1, 0):
             try:
                 if base.open():
                     print "Found %s base" % (base.NAME, )
                     self.fitbit = FitBit(base)
                     self.remote_info = None
                     break
                 else:
                     break
             except Exception, e:
                 print e
                 if retries:
                     print "retrying"
                     time.sleep(5)
         else:
             raise
         if self.fitbit:
             break
Exemple #14
0
 def pullAndBlock(self):
     """Pulls steps and updates list of blocked sites"""
     FitBit.pullFromServer()
     self.block()
Exemple #15
0
import thread
import time
from plumbum.cmd import cp
from app_constants import AppConstants
from rewardfit import RewardFit
from app_server import AppServer
from fitbit import FitBit

def checkHostsFile():
    """Will check if hosts has been backed up and back it up if needed"""
    if not os.path.isfile("/etc/hosts.backup"):
        cp["/etc/hosts", "/etc/hosts.backup"]()

if __name__ == "__main__":
    server = AppServer()
    try:
        checkHostsFile()
        FitBit.tryLogin()
        rf = RewardFit(server=server)
        thread.start_new_thread(rf.updateLoop, ())
        time.sleep(.1)  # makes stdout cleaner
        server.runServer()
    except IOError as e:
        if e[0] == errno.EPERM:
            print "Require root permission to run!"
    except KeyboardInterrupt:
        print "Caught interrupt. Closing"
    finally:
        print "Closing"
        server.killServer()
Exemple #16
0
from plumbum.cmd import cp
from app_constants import AppConstants
from rewardfit import RewardFit
from app_server import AppServer
from fitbit import FitBit


def checkHostsFile():
    """Will check if hosts has been backed up and back it up if needed"""
    if not os.path.isfile("/etc/hosts.backup"):
        cp["/etc/hosts", "/etc/hosts.backup"]()


if __name__ == "__main__":
    server = AppServer()
    try:
        checkHostsFile()
        FitBit.tryLogin()
        rf = RewardFit(server=server)
        thread.start_new_thread(rf.updateLoop, ())
        time.sleep(.1)  # makes stdout cleaner
        server.runServer()
    except IOError as e:
        if e[0] == errno.EPERM:
            print "Require root permission to run!"
    except KeyboardInterrupt:
        print "Caught interrupt. Closing"
    finally:
        print "Closing"
        server.killServer()
Exemple #17
0
def main():
    #base = DynastreamANT(True)
    base = FitBitANT(debug=True)
    if not base.open():
        print "No devices connected!"
        return 1

    device = FitBit(base)

    device.init_tracker_for_transfer()

    device.get_tracker_info()
    # print device.tracker

    device.parse_bank2_data(device.run_data_bank_opcode(0x02))
    print "---"
    device.parse_bank0_data(device.run_data_bank_opcode(0x00))
    device.run_data_bank_opcode(0x04)
    d = device.run_data_bank_opcode(0x02) # 13
    for i in range(0, len(d), 13):
        print ["%02x" % x for x in d[i:i+13]]
    d = device.run_data_bank_opcode(0x00) # 7
    print ["%02x" % x for x in d[0:7]]
Exemple #18
0
 def pullAndBlock(self):
     """Pulls steps and updates list of blocked sites"""
     FitBit.pullFromServer()
     self.block()
Exemple #19
0
class FitBitClient(object):
    CLIENT_UUID = "2ea32002-a079-48f4-8020-0badd22939e3"
    FITBIT_HOST = "client.fitbit.com"
    START_PATH = "/device/tracker/uploadData"

    def __init__(self, debug=False):
        self.info_dict = {}
        self.log_info = {}
        self.time = time.time()
        self.data = []
        conn = getConn()
        if conn is None:
            print "No base found!"
            exit(1)
        base = ANT(conn)
        self.fitbit = FitBit(base)
        if not self.fitbit:
            print "No devices connected!"
            exit(1)

    def __del__(self):
        self.close()
        self.fitbit = None

    def form_base_info(self, remote_info=None):
        self.info_dict.clear()
        self.info_dict["beaconType"] = "standard"
        self.info_dict["clientMode"] = "standard"
        self.info_dict["clientVersion"] = "1.0"
        self.info_dict["os"] = "libfitbit"
        self.info_dict["clientId"] = self.CLIENT_UUID
        if remote_info:
            self.info_dict.update(remote_info)
        for f in ['deviceInfo.serialNumber','userPublicId']:
            if f in self.info_dict:
                self.log_info[f] = self.info_dict[f]

    def dump_connection(self, directory='~/.fitbit'):
        directory = os.path.expanduser(directory)
        data = yaml.dump(self.data)
        if 'userPublicId' in self.log_info:
            directory = os.path.join(directory, self.log_info['userPublicId'])
            if not os.path.isdir(directory):
                os.makedirs(directory)
            f = open(os.path.join(directory,'connection-%d.txt' % int(self.time)), 'w')
            f.write(data)
            f.close()
        print data

    def close(self):
        self.dump_connection()
        print 'Closing USB device'
        try:
            self.fitbit.base.connection.close()
        except AttributeError:
            pass
        self.fitbit.base = None

    def run_upload_requests(self):
        self.fitbit.init_tracker_for_transfer()

        conn = FitBitRequest(self.FITBIT_HOST, self.START_PATH, https=True)

        # Start the request Chain
        self.form_base_info()
        while conn is not None:
            self.form_base_info(conn.response)

            self.info_dict.update(conn.run_opcodes(self.fitbit))

            conn.upload(self.info_dict)

            self.data.append(conn.dump())
            conn = conn.getNext()

        self.fitbit.command_sleep()
Exemple #20
0
def main():
    #base = DynastreamANT(True)
    base = FitBitANT(debug=True)
    if not base.open():
        print "No devices connected!"
        return 1

    device = FitBit(base)

    device.init_tracker_for_transfer()

    device.get_tracker_info()
    # print device.tracker

    device.parse_bank2_data(device.run_data_bank_opcode(0x02))
    print "---"
    device.parse_bank0_data(device.run_data_bank_opcode(0x00))
    device.run_data_bank_opcode(0x04)
    d = device.run_data_bank_opcode(0x02)  # 13
    for i in range(0, len(d), 13):
        print["%02x" % x for x in d[i:i + 13]]
    d = device.run_data_bank_opcode(0x00)  # 7
    print["%02x" % x for x in d[0:7]]
    print["%02x" % x for x in d[7:14]]
    j = 0
    for i in range(14, len(d), 3):
        print d[i:i + 3]
        j += 1
    print "Records: %d" % (j)
    device.parse_bank1_data(device.run_data_bank_opcode(0x01))

    # for i in range(0, len(d), 14):
    #     print ["%02x" % x for x in d[i:i+14]]
    base.close()
    return 0
Exemple #21
0
def test():
    global base
    if base is None:
        base = getBase(True)
        if base is None:
            print "No devices connected!"
            return 1

    device = FitBit(base)

    device.init_tracker_for_transfer()

    device.get_tracker_info()
    # print device.tracker

    device.parse_bank2_data(device.run_data_bank_opcode(0x02))
    print "---"
    device.parse_bank0_data(device.run_data_bank_opcode(0x00))
    device.run_data_bank_opcode(0x04)
    d = device.run_data_bank_opcode(0x02) # 13
    for i in range(0, len(d), 13):
        print ["%02x" % x for x in d[i:i+13]]
    d = device.run_data_bank_opcode(0x00) # 7
    print ["%02x" % x for x in d[0:7]]