def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """
        
        try:
            if self.adapter.DEBUG:
                print(">>>>>> INCOMING API REQUEST <<<<<<<<<")
                print(">>> REQUEST.PATH = " + str(request.path))
                print(">>> REQUEST.BODY = " + str(request.body))
        
        
            if request.method != 'POST' or request.path != '/example-api':
                return APIResponse(status=404)

            # echo back the body
            return APIResponse(
              status=200,
              content_type='application/json',
              content=json.dumps(request.body),
            )
        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
Exemple #2
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """

        try:

            if request.method != 'POST':
                return APIResponse(status=404)

            if request.path == '/init' or request.path == '/update_items':

                try:

                    if request.path == '/init':
                        if self.DEBUG:
                            print("Getting the initialisation data")

                        try:
                            state = 'ok'

                            # Check if a token is present
                            if self.token == None:
                                state = 'This addon requires an authorization token to work. Visit the settings page of this addon to learn more.'

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({
                                    'state':
                                    state,
                                    'items':
                                    self.persistent_data['items']
                                }),
                            )
                        except Exception as ex:
                            print("Error getting init data: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps({
                                    'state': "Internal error: no thing data",
                                    'items': []
                                }),
                            )

                    elif request.path == '/update_items':
                        try:
                            self.persistent_data['items'] = request.body[
                                'items']

                            #print("")
                            # Get all the things via the API.
                            try:
                                self.things = self.api_get("/things")
                                #print("Did the things API call")
                            except Exception as ex:
                                print(
                                    "Error getting updated things data via API: "
                                    + str(ex))

                            # try to get the correct property type (integer/float)
                            try:
                                for item in self.persistent_data['items']:
                                    #print("_item: " + str(item))
                                    if 'thing2' in item and 'property2' in item:
                                        for thing in self.things:
                                            thing_id = str(thing['id'].rsplit(
                                                '/', 1)[-1])
                                            #print("__id: " + str(thing_id))
                                            if str(item['thing2']) == thing_id:
                                                #print("BINGO. Props:")
                                                #print(str(thing['properties']))
                                                for thing_property_key in thing[
                                                        'properties']:

                                                    property_id = thing[
                                                        'properties'][
                                                            thing_property_key][
                                                                'links'][0][
                                                                    'href'].rsplit(
                                                                        '/',
                                                                        1)[-1]
                                                    #print("property_id = " + str(property_id))
                                                    if str(item['property2']
                                                           ) == property_id:
                                                        #print("bingo for property: " + str(property_id))
                                                        #print("___type: " + str(thing['properties'][thing_property_key]['type']))

                                                        #self.persistent_data['items'][item]['property2_type'] = str(thing['properties'][thing_property_key]['type'])
                                                        item['property2_type'] = str(
                                                            thing['properties']
                                                            [thing_property_key]
                                                            ['type'])

                            except Exception as ex:
                                print(
                                    "Error finding if property should be int or float: "
                                    + str(ex))

                            self.save_persistent_data()

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state': 'ok'}),
                            )
                        except Exception as ex:
                            if self.DEBUG:
                                print("Error saving updated items: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps("Error updating items: " +
                                                   str(ex)),
                            )

                    else:
                        return APIResponse(
                            status=500,
                            content_type='application/json',
                            content=json.dumps("API error"),
                        )

                except Exception as ex:
                    if self.DEBUG:
                        print("Error while handling request: " + str(ex))
                    return APIResponse(
                        status=500,
                        content_type='application/json',
                        content=json.dumps("Error in API handler"),
                    )

            else:
                return APIResponse(status=404)

        except Exception as e:
            if self.DEBUG:
                print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
                status=500,
                content_type='application/json',
                content=json.dumps("API Error"),
            )
Exemple #3
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """

        try:

            if request.method != 'POST':
                return APIResponse(status=404)

            if request.path == '/init' or request.path == '/list' or request.path == '/delete' or request.path == '/save' or request.path == '/wake':

                try:

                    if request.path == '/list':
                        if self.DEBUG:
                            print("LISTING")
                        # Get the list of photos
                        try:
                            data = self.scan_photo_dir()
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({
                                    'state': state,
                                    'data': data,
                                    'settings': {
                                        'interval': self.interval,
                                        'contain': self.contain,
                                        'clock': self.clock
                                    }
                                }),
                            )
                        except Exception as ex:
                            print("Error getting init data: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps(
                                    "Error while getting thing data: " +
                                    str(ex)),
                            )

                    elif request.path == '/delete':
                        if self.DEBUG:
                            print("DELETING")
                        try:
                            data = []
                            #target_data_type = self.data_types_lookup_table[int(request.body['property_id'])]
                            #print("target data type from internal lookup table: " + str(target_data_type))
                            # action, data_type, property_id, new_value, old_date, new_date
                            data = self.delete_file(
                                str(request.body['filename']))
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({
                                    'state': state,
                                    'data': data
                                }),
                            )
                        except Exception as ex:
                            print("Error getting thing data: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps(
                                    "Error while changing point: " + str(ex)),
                            )

                    elif request.path == '/save':
                        if self.DEBUG:
                            print("SAVING")
                        try:
                            data = []

                            data = self.save_photo(
                                str(request.body['filename']),
                                str(request.body['filedata']),
                                str(request.body['parts_total']),
                                str(request.body['parts_current'])
                            )  #new_value,date,property_id
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({
                                    'state': state,
                                    'data': data
                                }),
                            )
                        except Exception as ex:
                            print("Error deleting point(s): " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps(
                                    "Error while deleting point(s): " +
                                    str(ex)),
                            )

                    elif request.path == '/wake':
                        if self.DEBUG:
                            print("WAKING")

                        try:

                            cmd = 'DISPLAY=:0 xset dpms force on'
                            os.system(cmd)

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state': 'woken'}),
                            )
                        except Exception as ex:
                            print("Error waking dispay: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps(
                                    "Error while waking up the display: " +
                                    str(ex)),
                            )

                    else:
                        return APIResponse(
                            status=500,
                            content_type='application/json',
                            content=json.dumps("API error"),
                        )

                except Exception as ex:
                    print(str(ex))
                    return APIResponse(
                        status=500,
                        content_type='application/json',
                        content=json.dumps("Error"),
                    )

            else:
                return APIResponse(status=404)

        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
                status=500,
                content_type='application/json',
                content=json.dumps("API Error"),
            )
Exemple #4
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """
        
        try:
        
            if request.method != 'POST':
                return APIResponse(status=404)
            
            if request.path == '/init' or request.path == '/update_items':

                try:
                    
                    if request.path == '/init':
                        if self.DEBUG:
                            print("Getting the initialisation data")
                            
                        try:
                            state = 'ok'
        
                            # Check if a token is present
                            if self.token == None:
                                state = 'This addon requires an authorization token to work. Visit the settings page of this addon to learn more.'


                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state' : state, 'items' : self.persistent_data['items']}),
                            )
                        except Exception as ex:
                            print("Error getting init data: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps({'state' : "Internal error: no thing data", 'items' : []}),
                            )
                            
                    
                    elif request.path == '/update_items':
                        try:
                            self.persistent_data['items'] = request.body['items']
                            
                            
                            #print("")
                            # Get all the things via the API.
                            try:
                                self.things = self.api_get("/things")
                                #print("Did the things API call")
                            except Exception as ex:
                                print("Error getting updated things data via API: " + str(ex))
                                
                            # try to get the correct property type (integer/float)
                            try:
                                for item in self.persistent_data['items']:
                                    #print("_item: " + str(item))
                                    if 'thing1' in item and 'property1' in item:
                                        
                                        try:
                                            for thing in self.things:
                                                thing_id = str(thing['id'].rsplit('/', 1)[-1])
                                                
                                                if str(item['thing1']) == thing_id:
                                                    #print("__id SPOTTED: " + str(thing_id))
                                                    try:
                                                        #print("thing = " + str(thing))
                                                        potential_atype = None
                                                        #print("Thing = " + str(thing))
                                                        #if '@type' in thing:
                                                        try:
                                                            if hasattr(thing, '@type'):
                                                                #print("existing @type spotted in thing")
                                                                if len(thing['@type']) == 1:
                                                                    potential_atype = str(thing['@type'][0])
                                                                    
                                                        except Exception as ex:
                                                            print("Error checking for @type in thing: " + str(ex))
                                                            
                                                        #print("thing['properties'] = " + str(thing['properties']))
                                                            
                                                        for thing_property_key in thing['properties']:
                                            
                                                            property_id = thing['properties'][thing_property_key]['links'][0]['href'].rsplit('/', 1)[-1]
                                                            if self.DEBUG:
                                                                print("property_id = " + str(property_id))
                                                            if str(item['property1']) == property_id:
                                                                try:
                                                                    #print("full property: " + str(thing['properties'][thing_property_key]))

                                                                    done = False
                                                                    item['property1_type'] = str(thing['properties'][thing_property_key]['type'])
                                                            
                                                                    if '@type' in thing['properties'][thing_property_key]:
                                                                        if potential_atype != None:
                                                                            # Cloning a property that already has a capability
                                                                            #print("___atype: " + str(thing['properties'][thing_property_key]['@type']))
                                                                            item['thing1_atype'] = potential_atype
                                                                            item['property1_atype'] = str(thing['properties'][thing_property_key]['@type'])
                                                                            done = True
                                                                        else:
                                                                            atype = str(thing['properties'][thing_property_key]['@type'])

                                                                            if atype == 'AlarmProperty':
                                                                                item['thing1_atype'] = 'Alarm'
                                                                                item['property1_atype'] = atype
                                                                                done = True
                                                                            elif atype == 'OpenProperty':
                                                                                item['thing1_atype'] = 'DoorSensor'
                                                                                item['property1_atype'] = atype
                                                                                done = True
                                                                            elif atype == 'LockedProperty':
                                                                                item['thing1_atype'] = 'Lock'
                                                                                item['property1_atype'] = atype
                                                                                done = True
                                                                            elif atype == 'MotionProperty':
                                                                                item['thing1_atype'] = 'MotionSensor'
                                                                                item['property1_atype'] = atype
                                                                                done = True
                                                                            #elif atype == 'BrightnessProperty': # doesn't work, creates a boolean
                                                                            #    item['thing1_atype'] = 'Light'
                                                                            #    item['property1_atype'] = atype
                                                                            #    done = True
                                                                                
                                                                                
                                                                        # Todo: we could look up the corresponding thing @type if a property @type is provided.
                                                                    if done == False:
                                                                        # here we figure out a fitting capabiliy if the property doesn't have one yet. This is required for it to show up as the highlighted property.
                                                                
                                                                        if item['property1_type'] == 'number' or item['property1_type'] == 'integer':
                                                                            item['property1_atype'] = 'LevelProperty'
                                                                            item['thing1_atype'] = 'MultiLevelSensor'
                                                                            if 'unit' in thing['properties'][thing_property_key]:
                                                                                if thing['properties'][thing_property_key]['unit'].lower() == 'watt': # or thing['properties'][thing_property_key]['unit'].lower() == 'kwh':
                                                                                    if self.DEBUG:
                                                                                        print("spotted a kwh or watt") 
                                                                                    # technically using kwh is wrong here. But hey, I want that icon!
                                                                                    item['property1_atype'] = 'InstantaneousPowerProperty'
                                                                                    item['thing1_atype'] = 'EnergyMonitor'
                                                                            
                                                                        if item['property1_type'] == 'boolean':
                                                                            item['property1_atype'] = 'OnOffProperty'
                                                                            item['thing1_atype'] = 'OnOffSwitch'
                                                                            if 'readOnly' in thing['properties'][thing_property_key]:
                                                                                if bool(thing['properties'][thing_property_key]['readOnly']) == True:
                                                                                    item['property1_atype'] = 'BooleanProperty'
                                                                                    item['thing1_atype'] = 'BinarySensor'
                                        
                                                                    if self.DEBUG:
                                                                        print("item['thing1_atype'] has been deduced as: " + str(item['thing1_atype']))
                                                                        print("item['property1_atype'] has been deduced as: " + str(item['property1_atype']))
                                                                    
                                                                except Exception as ex:
                                                                    print("Error while analysing properties: " + str(ex))
                                                                
                                                    except Exception as ex:
                                                        print("Error while checking for @type in thing: " + str(ex))
                                        
                                        
                                        except Exception as ex:
                                            print("Error while while looping over things: " + str(ex))
                                            continue

                                        
                            except Exception as ex:
                                print("Error finding if property should be int or float: " + str(ex))
                            
                            self.save_persistent_data()
                            
                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state' : 'ok'}),
                            )
                        except Exception as ex:
                            print("Error saving updated items: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps("Error updating items: " + str(ex)),
                            )
                        
                    else:
                        return APIResponse(
                            status=500,
                            content_type='application/json',
                            content=json.dumps("API error"),
                        )
                        
                        
                except Exception as ex:
                    print("Init issue: " + str(ex))
                    return APIResponse(
                        status=500,
                        content_type='application/json',
                        content=json.dumps("Error in API handler"),
                    )
                    
            else:
                return APIResponse(status=404)
                
        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
                status=500,
                content_type='application/json',
                content=json.dumps("API Error"),
            )
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """

        try:

            if request.method != 'POST':
                return APIResponse(status=404)

            if request.path == '/init' or request.path == '/set-time' or request.path == '/set-ntp' or request.path == '/shutdown' or request.path == '/reboot':

                try:
                    if request.path == '/init':
                        response = {}

                        if self.DEBUG:
                            print("Initialising")
                        try:
                            now = datetime.datetime.now()
                            current_ntp_state = True

                            try:
                                for line in run_command(
                                        "timedatectl show").splitlines():
                                    if self.DEBUG:
                                        print(line)
                                    if line.startswith('NTP=no'):
                                        current_ntp_state = False
                            except Exception as ex:
                                print("Error getting NTP status: " + str(ex))

                            response = {
                                'hours': now.hour,
                                'minutes': now.minute,
                                'ntp': current_ntp_state
                            }
                            if self.DEBUG:
                                print("Init response: " + str(response))
                        except Exception as ex:
                            print("Init error: " + str(ex))

                        return APIResponse(
                            status=200,
                            content_type='application/json',
                            content=json.dumps(response),
                        )

                    elif request.path == '/set-time':
                        try:
                            self.set_time(str(request.body['hours']),
                                          request.body['minutes'])
                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps("Time set"),
                            )
                        except Exception as ex:
                            print("Error setting time: " + str(ex))
                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps(
                                    "Error while setting time: " + str(ex)),
                            )

                    elif request.path == '/set-ntp':
                        print("New NTP state = " + str(request.body['ntp']))
                        self.set_ntp_state(request.body['ntp'])
                        return APIResponse(
                            status=200,
                            content_type='application/json',
                            content=json.dumps(
                                "Changed Network Time state to " +
                                str(request.body['ntp'])),
                        )

                    elif request.path == '/shutdown':
                        self.shutdown()
                        return APIResponse(
                            status=200,
                            content_type='application/json',
                            content=json.dumps("Shutting down"),
                        )

                    elif request.path == '/reboot':
                        self.reboot()
                        return APIResponse(
                            status=200,
                            content_type='application/json',
                            content=json.dumps("Restarting"),
                        )

                except Exception as ex:
                    print(str(ex))

            else:
                return APIResponse(status=404)

        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
Exemple #6
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """
        
        
        try:
            #if self.adapter.DEBUG:
            print(">>>>>> INCOMING API REQUEST <<<<<<<<<")
            print(">>> REQUEST.PATH = " + str(request.path))
            print(">>> REQUEST.BODY = " + str(request.body))

            if request.path == '/full_lan_path':
                print("API call to full_lan_path")
                try:
        
                    
                        
                    
                    self.full_lan_path = "gateway.local:8686"
                        
                    try:
                        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                        try:
                            # doesn't even have to be reachable
                            s.connect(('192.126.199.199', 1))
                            lan_ip = s.getsockname()[0]
                        except:
                            lan_ip = 'gateway.local'
                        finally:
                            s.close()
                        
                        self.full_lan_path = str(lan_ip) + ":8686/"
                    except Exception as ex:
                        print("Error, unable to get local lan path: " + str(ex))        
        
        
        
                    if self.adapter.ssl_enabled:
                        self.full_lan_path = "https://" + self.full_lan_path
                    else:
                        self.full_lan_path = "http://" + self.full_lan_path
        
                    response = {'ssl_enabled':self.adapter.ssl_enabled, 'full_lan_path':self.full_lan_path}
                    if self.adapter.DEBUG:
                        print("Returning local path: " + str(response))
        
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps(response),
                    )

                except Exception as ex:
                    print("Error returning local path data: " + str(ex))

            else:
                return APIResponse(
                  status=500,
                  content_type='application/json',
                  content=json.dumps({"state":"Error, invalid path"}),
                )

        except Exception as ex:
            print("Error responding to request: " + str(ex))
Exemple #7
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """

        try:

            if request.method != 'POST':
                print("Warning: received non-post request")
                return APIResponse(status=404)

            if request.path == '/run' or request.path == '/restart':

                try:

                    if request.path == '/run':
                        try:
                            run_result = self.run(str(request.body['command']))
                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps(run_result),
                            )
                        except Exception as ex:
                            print("Error running command: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps("Error running command: " +
                                                   str(ex)),
                            )

                    elif request.path == '/restart':
                        self.restart()
                        return APIResponse(
                            status=200,
                            content_type='application/json',
                            content=json.dumps("Restarting"),
                        )
                    else:
                        return APIResponse(
                            status=500,
                            content_type='application/json',
                            content=json.dumps("API error"),
                        )

                except Exception as ex:
                    print(str(ex))
                    return APIResponse(
                        status=500,
                        content_type='application/json',
                        content=json.dumps("Error"),
                    )

            else:
                return APIResponse(status=404)

        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
                status=500,
                content_type='application/json',
                content=json.dumps("API Error"),
            )
Exemple #8
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """
        
        try:
        
            if request.method != 'POST':
                return APIResponse(status=404)
            
            if request.path == '/init' or request.path == '/update' or request.path == '/scan' or request.path == '/exit':

                try:
                    
                    if request.path == '/init':
                        if self.DEBUG:
                            print("/init - Getting the initialisation data")
                            
                        try:
                            state = 'ok'

                            #print("making bluetooth discoverable")
                            #self.bl.make_discoverable()
                            
                            #self.bl.start_scan()
                            #sleep(1)
                            
                            #print(str( self.bl.get_available_controllers() ))
            
                            
                            #self.bl.make_pairable()
                            self.bl.make_discoverable()
                            
                            
            
                            self.bl.start_scan()
                            
                            #self.available_devices = self.bl.get_available_devices()
                            #print(str(self.available_devices))
                            
                            #self.bl.stop_scan()
                            
                            
                            #self.bl.start_scan()
            
                            sleep(3)
                            self.bl.stop_scan()

                            paired_devices = self.bl.get_paired_devices()
                            
                            if self.DEBUG:
                                print("raw paired devices:")
                                print(str(paired_devices))
                            
                            for i in range(len(paired_devices)):
                                paired_devices[i]['paired'] = True
                                paired_devices[i]['trusted'] = False
                                paired_devices[i]['connected'] = False
                                
                                try:
                                    mac = paired_devices[i]['mac']
                                    #print("getting extra info for paired device: " + str(mac))
                                    info_test = [] #self.bl.get_device_info(mac) # disabled, as it caused issues.
                                    #print(str(info_test))
                                    trusted = False
                                    connected = False
                                    for line in info_test:
                                        print(str(line))
                                        if 'Trusted: yes' in line:
                                            print("it was already trusted")
                                            paired_devices[i]['trusted'] = True
                                        if 'Connected: yes' in line:
                                            print("it was already connected")
                                            paired_devices[i]['connected'] = True
                                except Exception as ex:
                                    print("error doing extra test if connected: " + str(ex))
                            
                            if self.DEBUG:
                                print("Init paired:")
                                print(str(paired_devices))
                            
                            

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state' : state, 'items' : paired_devices}),
                            )
                        except Exception as ex:
                            print("Error getting init data: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps({'state' : "Initialisation error", 'items' : []}),
                            )
                            
                            
                            
                    elif request.path == '/scan':
                        if self.DEBUG:
                            print("/scan - Scanning for bluetooth devices")
                            
                        try:
                            state = 'ok'
                            
                            #self.bl = Bluetoothctl()
                            #self.bl.make_agent()
                            
                            #self.bl.make_discoverable()
                            #self.bl.make_pairable()
                            
            
                            #self.bl.start_scan()
                            
                            #sleep(5)
                            #self.bl.stop_scan()
                            
                            #self.available_devices = self.bl.get_available_devices()
                            #print(str(self.available_devices))
                            
                            
                            all_devices = []
                            
                            paired_devices = self.bl.get_paired_devices()
                            
                            if self.DEBUG:
                                print("raw paired devices:")
                                print(str(paired_devices))
                            
                            
                            for i in range(len(paired_devices)):
                                paired_devices[i]['paired'] = True
                                paired_devices[i]['trusted'] = False
                                paired_devices[i]['connected'] = False
                                
                                
                                try:
                                    mac = paired_devices[i]['mac']
                                    #print("getting extra info for paired device: " + str(mac))
                                    info_test = [] # getting device info was causing issues
                                    #info_test = self.bl.get_device_info(mac)
                                    #print(str(info_test))
                                    trusted = False
                                    connected = False
                                    for line in info_test:
                                        print(str(line))
                                        if 'Trusted: yes' in line:
                                            print("it was already trusted")
                                            paired_devices[i]['trusted'] = True
                                        if 'Connected: yes' in line:
                                            print("it was already connected")
                                            paired_devices[i]['connected'] = True
                                except Exception as ex:
                                    print("error doing extra test if connected: " + str(ex))
                                
                                all_devices.append(paired_devices[i])
                                
                                
                            discovered_devices = self.bl.get_discoverable_devices()
                            
                            if self.DEBUG:
                                print("raw discovered devices:")
                                print(str(discovered_devices))
                            
                            for i in range(len(discovered_devices)):
                                discovered_devices[i]['paired'] = False
                                discovered_devices[i]['trusted'] = False
                                discovered_devices[i]['connected'] = False
                                all_devices.append(discovered_devices[i])
                            
                            #self.bl.stop_scan()

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state' : state, 'items' : all_devices }),
                            )
                        except Exception as ex:
                            print("Error during scan: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps({'state' : "Error while doing scan", 'items' : []}),
                            )
                            
                            
                            
                            
                            
                    elif request.path == '/update':
                        if self.DEBUG:
                            print("/update - Updating a single device")
                            
                            
                        
                            #get_device_info
                    
                        try:
                            state = 'ok'
                            action = str(request.body['action'])
                            mac = str(request.body['mac'])
                            update = "" 
                            
                            print(str(action))
                            
                            if action == 'info':
                                if self.DEBUG:
                                    print("getting info")
                                update = 'Unable to get detailed information'
                                try:
                                    update = self.bl.get_device_info(mac)
                                    #sleep(2)
                                except Exception as ex:
                                    print("error getting device info: " + str(ex))
                                    state = False
                                
                            elif action == 'pair':
                                if self.DEBUG:
                                    print("pairing...")
                                update = ''
                                try:
                                    #update = self.bl.trust(mac)
                                    #print(str(update))
                                    state = self.bl.pair(mac)
                                    #sleep(2)
                                    #print("pair succes?____")
                                    #print(str(state))
                                    #print("---------")
                                    #sleep(2)
                                    if state:
                                        update = 'paired succesfully'
                                        state = self.bl.trust(mac)
                                        #print("trust success?_____")
                                        #print(str(state))
                                        #print("---------")
                                        #sleep(2)
                                        if state:
                                            update = 'paired and connected succesfully'
                                            state2 = self.bl.connect(mac)
                                            #print("connect success?")
                                            #print(str(state2))
                                            if state2:
                                                update = 'paired, connected and trusted succesfully'
                                            else:
                                                update = 'paired, connected succesfully, but was unable to setup automatic reconnecting'
                                except Exception as ex:
                                    print("error pairing: " + str(ex))
                                    state = False
                            
                            
                            elif action == 'connect':
                                if self.DEBUG:
                                    print("connecting...")
                                update = ''
                                try:
                                    state = self.bl.trust(mac)
                                    if state:
                                        if self.DEBUG:
                                            print("Succesfully trusted device")
                                        state = self.bl.connect(mac)
                                        #sleep(2)
                                        if self.DEBUG:
                                            print("connect succes?____")
                                            print(str(state))
                                            print("---------")
                                    
                                        try:
                                            info_test = self.bl.get_device_info(mac)
                                            #print(str(info_test))
                                            for line in info_test:
                                                if self.DEBUG:
                                                    print(str(line))
                                                if 'Connected: yes' in line:
                                                    if self.DEBUG:
                                                        print("it was already connected")
                                                    state = True
                                        except Exception as ex:
                                            print("error doing extra test if connected: " + str(ex))
                                        
                                        #sleep(2)
                                        if state:
                                            update = 'connected succesfully'
                                except Exception as ex:
                                    print("error in connecting: " + str(ex))
                                    state = False
                                
                            elif action == 'unpair':
                                if self.DEBUG:
                                    print("unpairing...")
                                update = 'Unable to unpair'
                                try:
                                    state = self.bl.remove(mac)
                                    if self.DEBUG:
                                        print("remove success?______")
                                        print(str(state))
                                        print("---------")
                                    #sleep(2)
                                except Exception as ex:
                                    print("error in pairing: " + str(ex))
                                    state = False
                                

                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state' : state, 'mac': mac,'update' : update }),
                            )
                        except Exception as ex:
                            print("Error updating: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps({'state' : "Error while updating device", 'update' : "Server error"}),
                            )
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                    
                    elif request.path == '/exit':
                        try:
                            if self.DEBUG:
                                print("/exit called")
                            #self.bl.stop_scan()
                            self.bl.make_pairable(False)
                            self.bl.make_discoverable(False)
                            
                            self.bl.exit()
                            
                            return APIResponse(
                                status=200,
                                content_type='application/json',
                                content=json.dumps({'state' : 'ok'}),
                            )
                        except Exception as ex:
                            print("Error updating items: " + str(ex))
                            return APIResponse(
                                status=500,
                                content_type='application/json',
                                content=json.dumps("Error updating: " + str(ex)),
                            )
                        
                    else:
                        return APIResponse(
                            status=500,
                            content_type='application/json',
                            content=json.dumps("Invalid path"),
                        )
                        
                        
                except Exception as ex:
                    print("API handler issue: " + str(ex))
                    return APIResponse(
                        status=500,
                        content_type='application/json',
                        content=json.dumps("Valid path, but general error in API handler"),
                    )
                    
            else:
                return APIResponse(status=404)
                
        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
                status=500,
                content_type='application/json',
                content=json.dumps("API Error"),
            )
Exemple #9
0
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """
        if self.DEBUG:
            print("> > >  REQUEST < < <")
        try:
        
            if request.method != 'POST':
                print("- was not a POST request, ignoring")
                return APIResponse(status=404)
            
            if request.path == '/ajax':
                
                action = str(request.body['action'])    
                print("ajax action = " + str(action))
                
                if action == 'init':
                    print('ajax handling init')
                    print("self.adapter.persistent_data = " + str(self.adapter.persistent_data))
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message' : 'initialization complete', 'ssid':self.adapter.ssid, 'password':self.adapter.hotspot_password , 'cable_needed':self.adapter.cable_needed, 'debug': self.DEBUG}),
                    )
                    
                elif action == 'latest':
                    print('ajax handling latest')
                    #print("self.persistent_data = " + str(self.persistent_data))
                    filtered_animals = {}
                    try:
                        filtered_animals = self.filter_animals()
                    except:
                        print("Error while filtering animals")
                    
                    print("self.adapter.seconds = " + str(self.adapter.seconds))
                    
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message' : 'updated data received', 'animals': filtered_animals, 'master_blocklist': self.adapter.persistent_data['master_blocklist'], 'seconds':self.adapter.seconds }),
                    )
                    
                elif action == 'abort':
                    print('ajax handling abort')
                    #print("self.persistent_data = " + str(self.persistent_data))
                    self.adapter.allow_launch = False
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message' : 'launch has been aborted' }),
                    )
                    
                elif action == 'launch':
                    print('ajax handling abort')
                    #print("self.persistent_data = " + str(self.persistent_data))
                    self.adapter.allow_launch = True
                    self.adapter.seconds == 89
                    
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message' : 'launch has been aborted' }),
                    )
                    
                elif action == 'delete' or action == 'clear':
                    print('ajax handling delete')
                    #print("self.persistent_data = " + str(self.persistent_data))
                    mac = str(request.body['mac'])
                    state = False
                    try:
                        #self.adapter.persistent_data['animals'].pop(mac);
                        self.adapter.persistent_data['animals'][mac]['requests'] = []
                        self.adapter.persistent_data['animals'][mac]['domains'] = {}
                        self.adapter.persistent_data['animals'][mac]['delete_timestamp'] = time.time()
                        state = True
                        self.adapter.save_persistent_data()
                    except Exception as ex:
                        print("failed to delete item from dictionary")
                    
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : state, 'message' : 'Connections record was reset' }),
                    )
                    
                elif action == 'set_permission':
                    mac = str(request.body['mac'])
                    domain = str(request.body['domain'])
                    permission = str(request.body['permission'])
                    print("permission = " + permission)
                    print("permission domain = " + domain)
                    print("permission mac = " + mac)
                    self.adapter.persistent_data['animals'][mac]['domains'][domain]['permission'] = permission
                    
                    if permission == 'allowed' and domain in self.adapter.persistent_data['master_blocklist']:
                        print("- should remove domain from blocklist")
                        self.adapter.persistent_data['master_blocklist'].remove(domain)
                        self.adapter.update_dnsmasq()
                        
                        if self.adapter.dnsmasq_pid != None:
                            print("sending sighup to " + str(self.adapter.dnsmasq_pid))
                            #os.kill(self.adapter.dnsmasq_pid, SIGHUP)
                            #os.system("sudo kill -SIGHUP " + str(self.adapter.dnsmasq_pid))
                            os.system("sudo kill -s HUP " + str(self.adapter.dnsmasq_pid))
                            # sudo kill -s HUP $pid
                        
                    if permission == 'blocked' and domain not in self.adapter.persistent_data['master_blocklist']:
                        print("- should add domain to blocklist")
                        self.adapter.persistent_data['master_blocklist'].append(domain)
                        self.adapter.update_dnsmasq()
                        
                    
                    self.adapter.save_persistent_data()
                    

                        
                    
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message': 'permission was changed', 'animals':self.adapter.persistent_data['animals'] }),
                    )
                    
                elif action == 'remove_from_master_blocklist':
                    self.adapter.persistent_data['master_blocklist'].remove(request.body['domain'])
                    #print("self.persistent_data['thing_settings'] = " + str(self.persistent_data['thing_settings'])) 
                    self.adapter.save_persistent_data()
                     
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message': 'domain removed succesfully'}),
                    )
                    
                elif action == 'add_to_master_blocklist':
                    self.adapter.persistent_data['master_blocklist'].append(request.body['domain'])
                    #print("self.persistent_data['thing_settings'] = " + str(self.persistent_data['thing_settings'])) 
                    self.adapter.save_persistent_data()
                     
                    return APIResponse(
                      status=200,
                      content_type='application/json',
                      content=json.dumps({'state' : True, 'message': 'settings saved succesfully'}),
                    )
                else:
                    return APIResponse(status=404)
                    
            else:
                return APIResponse(status=404)
                
        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
              status=500,
              content_type='application/json',
              content=json.dumps("API Error"),
            )
    def handle_request(self, request):
        """
        Handle a new API request for this handler.

        request -- APIRequest object
        """
        
        try:
        
            if request.method != 'POST':
                return APIResponse(status=404)
            
            if request.path == '/init' or request.path == '/get_property_data' or request.path == '/point_change_value' or request.path == '/point_delete' or request.path == '/internal_logs':

                try:
                    
                    if request.path == '/init':
                        
                        # Get the list of properties that are being logged
                        try:
                            data = self.get_init_data()
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'
                            
                            return APIResponse(
                              status=200,
                              content_type='application/json',
                              content=json.dumps({'state' : state, 'data' : data}),
                            )
                        except Exception as ex:
                            print("Error getting init data: " + str(ex))
                            return APIResponse(
                              status=500,
                              content_type='application/json',
                              content=json.dumps("Error while getting thing data: " + str(ex)),
                            )
                            
                            
                    
                    elif request.path == '/get_property_data':
                        try:
                            target_data_type = self.data_types_lookup_table[int(request.body['property_id'])]
                            print("target data type from internal lookup table: " + str(target_data_type))
                            data = self.get_property_data( str(request.body['property_id']), target_data_type )
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'
                            
                            return APIResponse(
                              status=200,
                              content_type='application/json',
                              content=json.dumps({'state' : state, 'data' : data}),
                            )
                        except Exception as ex:
                            print("Error getting thing data: " + str(ex))
                            return APIResponse(
                              status=500,
                              content_type='application/json',
                              content=json.dumps("Error while getting thing data: " + str(ex)),
                            )
                            
                            
                    elif request.path == '/point_change_value':
                        try:
                            data = []
                            target_data_type = self.data_types_lookup_table[int(request.body['property_id'])]
                            print("target data type from internal lookup table: " + str(target_data_type))
                            # action, data_type, property_id, new_value, old_date, new_date
                            data = self.point_change_value( str(request.body['action']), target_data_type, str(request.body['property_id']), str(request.body['new_value']), str(request.body['old_date']), str(request.body['new_date']) )
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'
                            
                            return APIResponse(
                              status=200,
                              content_type='application/json',
                              content=json.dumps({'state' : state, 'data' : data}),
                            )
                        except Exception as ex:
                            print("Error getting thing data: " + str(ex))
                            return APIResponse(
                              status=500,
                              content_type='application/json',
                              content=json.dumps("Error while changing point: " + str(ex)),
                            )
                            
                            
                            
                            
                    elif request.path == '/point_delete':
                        print("POINT DELETE CALLED")
                        try:
                            data = []
                            
                            target_data_type = self.data_types_lookup_table[int(request.body['property_id'])]
                            print("target data type from internal lookup table: " + str(target_data_type))
                            
                            data = self.point_delete(str(request.body['property_id']), target_data_type, str(request.body['start_date']), str(request.body['end_date']) ) #new_value,date,property_id
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'
                            
                            return APIResponse(
                              status=200,
                              content_type='application/json',
                              content=json.dumps({'state' : state, 'data' : data}),
                            )
                        except Exception as ex:
                            print("Error deleting point(s): " + str(ex))
                            return APIResponse(
                              status=500,
                              content_type='application/json',
                              content=json.dumps("Error while deleting point(s): " + str(ex)),
                            )
                            
                            
                        
                        
                    elif request.path == '/internal_logs':
                        print("INTERNAL LOGS CALLED")
                        try:
                            data = []
                               
                            action = "get"
                            filename = "all"
                            try:
                                filename = str(request.body['filename']) 
                            except:
                                print("No specific filename provided")
                            try:
                                action = str(request.body['action']) 
                            except:
                                print("No specific action provided, will read data.")
                               
                            data = self.internal_logs(action, filename)
                            if isinstance(data, str):
                                state = 'error'
                            else:
                                state = 'ok'
                            
                            return APIResponse(
                              status=200,
                              content_type='application/json',
                              content=json.dumps({'state' : state, 'data' : data}),
                            )
                        except Exception as ex:
                            print("Error deleting point(s): " + str(ex))
                            return APIResponse(
                              status=500,
                              content_type='application/json',
                              content=json.dumps("Error while getting logs data: " + str(ex)),
                            )
                        
                        
                    else:
                        return APIResponse(
                          status=500,
                          content_type='application/json',
                          content=json.dumps("API error"),
                        )
                        
                        
                except Exception as ex:
                    print(str(ex))
                    return APIResponse(
                      status=500,
                      content_type='application/json',
                      content=json.dumps("Error"),
                    )
                    
            else:
                return APIResponse(status=404)
                
        except Exception as e:
            print("Failed to handle UX extension API request: " + str(e))
            return APIResponse(
              status=500,
              content_type='application/json',
              content=json.dumps("API Error"),
            )