コード例 #1
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
 def is_registered(self):
     """ Check that the app is currently registered (granted) """
     log(">>> is_registered")
     if self._registered:
         return True
     self._registered = (self.get_registration_status() == 'granted')
     return self._registered
コード例 #2
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
 def get_registration_status_diagnostic(self):
     """ Get the current registration status and display diagnosic """
     log(">>> get_registration_status_diagnostic")
     status = self.get_registration_status()
     track_id = self._conf.reg_params.get('track_id')
     if 'granted' == status:
         print('This app is already granted on Freebox Server' +
               ' (track_id={}).'.format(track_id) +
               ' You can now dialog with it.')
     elif 'pending' == status:
         print('This app grant is still pending: user should grant it' +
               ' on Freebox Server lcd/touchpad (track_id = {}).'.format(
                   track_id))
     elif 'unknown' == status:
         print(
             'This track_id ({}) is unknown by Freebox Server: '.format(
                 track_id) +
             'you have to register again to Freebox Server to get a new app_id.'
         )
     elif 'denied' == status:
         print(
             'This app has been denied by user on Freebox Server (track_id = {}).'
             .format(self._conf.reg_params.get('track_id')))
     elif 'timeout' == status:
         print(
             'Timeout occured for this app_id: you have to register again' +
             ' to Freebox Server to get a new app_id (current track_id = {}).'
             .format(track_id))
     else:
         print('Unexpected response: {}'.format(status))
     return status
コード例 #3
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def _set_wifi_radio_state(self, set_on):
        """ Utility to activate or deactivate wifi radio module """
        log('>>> set_wifi_radio_state {}'.format('ON' if set_on else 'OFF'))
        # PUT wifi status
        uri = '/wifi/config/'
        data = {'enabled': True} if set_on else {'enabled': False}
        timeout = 3 if not set_on else None

        # PUT
        try:
            resp = self._http.put(uri, data=data, timeout=timeout)
        except requests.exceptions.Timeout as exc:
            if not set_on:
                # If we are connected using wifi, disabling wifi will close connection
                # thus PUT response will never be received: a timeout is expected
                print('Wifi radio is now OFF')
                return 0
            else:
                # Forward timeout exception as should not occur
                raise exc

        if not resp.success:
            raise FbxException('Request failure: {}'.format(resp))

        if self._conf.resp_as_json:
            return resp.whole_content

        is_on = resp.result.get('enabled')
        print('Wifi radio is now {}'.format('ON' if is_on else 'OFF'))
        return is_on
コード例 #4
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_registration_status(self):
        """ Get the current registration status thanks to the track_id """
        log(">>> get_registration_status")
        if self._conf.has_registration_params():
            uri = '/login/authorize/{}'.format(
                self._conf.reg_params.get('track_id'))
            resp = self._http.get(uri, no_login=True)

            return resp.result.get('status')
        else:
            return "Not registered yet!"
コード例 #5
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_wifi_planning(self):
        """ Get the current status of wifi: 1 means planning enabled, 0 means no planning """
        log('>>> get_wifi_planning')
        uri = '/wifi/planning/'
        resp = self._http.get(uri)

        if self._conf.resp_as_json:
            return resp.whole_content

        is_on = resp.success and resp.result.get('use_planning')
        print('Wifi planning is {}'.format('ON' if is_on else 'OFF'))
        return is_on
コード例 #6
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_wifi_radio_state(self):
        """ Get the current status of wifi radio: 1 means ON, 0 means OFF """
        log('>>> get_wifi_radio_state')
        uri = '/wifi/config/'
        resp = self._http.get(uri)

        if self._conf.resp_as_json:
            return resp.whole_content

        is_on = resp.success and resp.result.get('enabled')
        print('Wifi is {}'.format('ON' if is_on else 'OFF'))
        return is_on
コード例 #7
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def mark_calls_as_read(self):
        """ Mark all the calls as read """
        log(">>> mark_calls_as_read")

        uri = '/call/log/mark_all_as_read/'
        data = {}
        resp = self._http.post(uri, data)

        if not resp.success:
            raise FbxException('Request failure: {}'.format(resp))

        # json response format
        if self._conf.resp_as_json:
            return resp.whole_content

        return 0
コード例 #8
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def _set_wifi_planning(self, set_on):
        """ Utility to activate or deactivate wifi planning mode """
        log('>>> set_wifi_planning {}'.format('ON' if set_on else 'OFF'))
        # PUT wifi planning
        url = '/wifi/planning/'
        data = {'use_planning': True} if set_on else {'use_planning': False}

        resp = self._http.put(url, data=data)

        if not resp.success:
            raise FbxException('Request failure: {}'.format(resp))

        if self._conf.resp_as_json:
            return resp.whole_content

        is_on = resp.result.get('use_planning')
        print('Wifi planning is now {}'.format('ON' if is_on else 'OFF'))
        return is_on
コード例 #9
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def register_app(self):
        """ Register this app to FreeboxOS to that user grants this apps via Freebox Server
LCD screen. This command shall be executed only once. """
        log(">>> register_app")
        register = True
        if self._conf.has_registration_params():
            status = self.get_registration_status_diagnostic()
            if 'granted' == status:
                register = False

        if register:
            self._conf._load_addressing_params()
            uri = '/login/authorize/'
            data = self._conf.app_desc
            # post it
            resp = self._http.post(uri, data=data, no_login=True)

            # save registration params
            if resp.success:
                params = {
                    'app_token': resp.result.get('app_token'),
                    'track_id': resp.result.get('track_id')
                }
                self._conf.reg_params = params
                print(
                    'Now you have to accept this app on your Freebox server:' +
                    ' take a look on its LCD screen.')
                print(
                    input(
                        'Press Enter key once you have accepted on LCD screen: '
                    ))
                # check new status (it seems to be mandatory to reach in 'granted' state)
                status = self.get_registration_status_diagnostic()
                print('{}'.format('OK' if 'granted' == status else 'NOK'))
            else:
                print('NOK')
コード例 #10
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
 def get_all_calls_list(self):
     """ List all the calls """
     log(">>> get_all_calls_list")
     return self._get_calls_list(False)
コード例 #11
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
 def get_new_calls_list(self):
     """ List new calls """
     log(">>> get_new_calls_list")
     return self._get_calls_list(True)
コード例 #12
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_contacts(self):
        """ List the port forwarding on going"""
        def load_from_archive(svc):
            contacts = FbxContacts(svc._ctrl, empty=True)
            t_contacts = FbxDbTable(u'contact', u'id',
                                    table_defs[u'contact'][u'cols_def'])
            contacts.load_from_db(svc._ctrl, FbxContact, t_contacts)
            return contacts

        if self._conf.resp_archive:
            self._contacts = load_from_archive(self)
        else:
            self._contacts = FbxContacts(self._ctrl)

        if len(self._contacts) == 0:
            if not self._conf.resp_restore:
                print('No port contacts')
                return 0

        if self._conf.resp_restore:
            self._contacts = FbxContacts(self._ctrl)
            # clean before populate
            for contact in self._contacts:
                data = {}
                url = u'/contact/{}'.format(contact.id)
                resp = self._http.delete(url, data=data)
            self._contacts = load_from_archive(self)
            i = 0
            for contact in self._contacts:
                i += 1
                # populate
                data = {
                    u"display_name": contact.display_name,
                    u"first_name": contact.first_name,
                    u"last_name": contact.last_name,
                    u"birthday": contact.birthday,
                    u"notes": contact.notes,
                    u"company": contact.company,
                    u"photo_url": contact.photo_url,
                }
                # print(u'Restore', data)
                url = u'/contact/'
                resp = self._http.post(url, data=data)
                client_id = resp.result['id']

                # print(resp.result)
                # print(client_id)
                if not resp.success:
                    raise FbxException('Request failure: {}'.format(resp))
                if contact.numbers is not None:
                    for number in contact.numbers:
                        # print(u'number: {}'.format(number))
                        data = {
                            u"contact_id": client_id,
                            u"number": number.number,
                            u"type": number.nbr_type,
                            u"is_default": number.is_default,
                            u"is_own": number.is_own,
                        }
                        url = u'/number/'
                        resp = self._http.post(url, data=data)
                        print(resp.result)
                if contact.addresses is not None:
                    for address in contact.addresses:
                        # print(u'address: {}'.format(address))
                        data = {
                            u"contact_id": client_id,
                            u"street": address.street,
                            u"type": address.address_type,
                            u"city": address.city,
                            u"zipcode": address.zipcode,
                            u"number": address.number,
                            u"country": address.country,
                            u"street2": address.street2,
                        }
                        url = u'/address/'
                        resp = self._http.post(url, data=data)
                        print(resp.result)
                if contact.emails is not None:
                    for email in contact.emails:
                        # print(u'email: {}'.format(email))
                        data = {
                            u"contact_id": client_id,
                            u"email": email.email,
                            u"type": email.email_type,
                        }
                        url = u'/email/'
                        resp = self._http.post(url, data=data)
                        print(resp.result)
                if contact.urls is not None:
                    for url in contact.urls:
                        # print(u'url: {}'.format(url))
                        data = {
                            u"contact_id": client_id,
                            u"url": url.url,
                            u"type": url.url_type,
                        }
                        url = u'/url/'
                        resp = self._http.post(url, data=data)
                        print(resp.result)
                # if i > 5: exit(0)
            return 0

        if self._conf.resp_as_json is False:
            print('{} contacts'.format(len(self._contacts)))

        if self._conf.resp_save:
            # todo : save to archive
            self._contacts.save_to_db()

        if self._conf.resp_as_json and self._conf.resp_archive is False:
            return self._contacts.json

        tcount = 0

        log(">>> get_contacts")
        print(u'Contacts')
        count = 0
        for contact in self._contacts:
            count += 1
            tcount += 1
            print(u'{}# {}'.format(count, contact))

        return tcount > 0
コード例 #13
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_port_forwardings(self):
        """ List the port forwarding on going"""
        def load_from_archive(svc):
            pfwds = FbxPortForwardings(svc._ctrl, empty=True)
            t_pfwds = FbxDbTable(u'fw_redir', u'id',
                                 table_defs[u'fw_redir'][u'cols_def'])
            pfwds.load_from_db(svc._ctrl, FbxPortForwarding, t_pfwds)
            return pfwds

        if self._conf.resp_archive:
            self._pfwds = load_from_archive(self)
        else:
            self._pfwds = FbxPortForwardings(self._ctrl)

        if len(self._pfwds) == 0:
            print('No port forwardings')
            return 0

        if self._conf.resp_restore:
            self._pfwds_arc = load_from_archive(self)
            # look for missing port forwardings
            print(u'\nMissing port forwardings')
            for pwd_arc in self._pfwds_arc:
                pwd_fbx = self._pfwds.get_by_id(pwd_arc.id)
                if pwd_fbx is None:
                    print(pwd_arc)
                    if fbx_question_yn(u'Restore'):
                        data = {
                            u"enabled": pwd_arc.enabled,
                            u"comment": pwd_arc.comment,
                            u"lan_port": pwd_arc.lan_port,
                            u"wan_port_end": pwd_arc.wan_port_end,
                            u"wan_port_start": pwd_arc.wan_port_start,
                            u"lan_ip": pwd_arc.lan_ip,
                            u"ip_proto": pwd_arc.ip_proto,
                            u"src_ip": pwd_arc.src_ip,
                        }
                        print(u'Restore', data)
                        url = u'/fw/redir/'
                        resp = self._http.post(url, data=data)
                        if not resp.success:
                            raise FbxException(
                                'Request failure: {}'.format(resp))

            return 0

        if self._conf.resp_as_json is False:
            print('{} port forwardings'.format(len(self._pfwds)))

        if self._conf.resp_save:
            # todo : save to archive
            self._pfwds.save_to_db()

        if self._conf.resp_as_json and self._conf.resp_archive is False:
            return self._pfwds.json

        tcount = 0

        log(">>> get_enabled_port_forwarding")
        print(u'Enabled port forwardings')
        count = 0
        for pfwd in self._pfwds:
            if pfwd.enabled is False:
                continue
            count += 1
            tcount += 1
            # pfwd to be displayed
            print(u'{}# {}'.format(count, pfwd))

        log(">>> get_disabled_port_forwarding")
        print(u'Disabled port forwardings')
        count = 0
        for pfwd in self._pfwds:
            if pfwd.enabled is True:
                continue
            count += 1
            tcount += 1
            # pfwd to be displayed
            print(u'{}# {}'.format(count, pfwd))

        return tcount > 0
コード例 #14
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_dhcp_leases(self):
        """ List the DHCP dynamic leases on going"""

        log(">>> get_dynamic_leases")
        self._st_leases = FbxDhcpStaticLeases(self._ctrl)

        if self._conf.resp_archive:
            self._dyn_leases = FbxDhcpDynamicLeases(self._ctrl, empty=True)
            t_dyn_leases = FbxDbTable(
                u'dynamic_lease', u'mac',
                table_defs[u'dynamic_lease'][u'cols_def'])
            self._dyn_leases.load_from_db(self._ctrl, FbxDhcpDynamicLease,
                                          t_dyn_leases)
        else:
            self._dyn_leases = FbxDhcpDynamicLeasesX(self._ctrl,
                                                     self._st_leases)

        if len(self._dyn_leases) == 0:
            print('No DHCP leases')
            return 0

        if self._conf.resp_as_json is False:
            print('{} DHCP leases'.format(len(self._dyn_leases)))

        if self._conf.resp_save:
            self._dyn_leases.save_to_db()

        if self._conf.resp_as_json and self._conf.resp_archive is False:
            return self._dyn_leases.json

        tcount = 0
        count = 0

        print('\nList of reachable leases:')
        for dyn_lease in self._dyn_leases:
            if dyn_lease.reachable is False:
                continue
            count += 1
            tcount += 1
            # st_lease to be displayed
            print(u'{}# {}'.format(count, dyn_lease))

        count = 0

        print('\nList of unreachable leases:')
        for dyn_lease in self._dyn_leases:
            if dyn_lease.reachable:
                continue
            count += 1
            tcount += 1
            # st_lease to be displayed
            print(u'{}# {}'.format(count, dyn_lease))

        return tcount > 0

        return

        if self._conf.resp_restore:
            for k, v in self._arc_o_dict.items():
                """ Create static lease"""
                if (k not in self._fbx_o_dict.keys()) and v.is_static:
                    print(v)
                    """ Restore Y/N"""
                    to_restore = False
                    answer = None
                    while answer not in ("y", "n", "Y", "N", "o", "O"):
                        answer = input(u"Restore Y/N): ")
                        if answer in ("y", "Y", "o", "O"):
                            to_restore = True
                        elif answer in ("n", "N"):
                            to_restore = False
                    if to_restore:
                        """ Create missing static lease"""
                        uri = u'/dhcp/static_lease/'
                        data = {"mac": v.mac, "ip": v.ip, "comment": v.comment}
                        resp = self._http.post(uri, data)
                        if not resp.success:
                            uri = u'/dhcp/static_lease/{}'.format(v.mac)
                            data = {"ip": v.ip, "comment": v.comment}
                            resp = self._http.put(uri, data)
                            if not resp.success:
                                print(u'Create failed')
                            print(u'Updated')
                            continue
                        print(u'Created')
                """ Update static lease"""
                if (k in self._fbx_o_dict.keys()) and v.is_static:
                    # todo : compare v with self._fbx_o_dict[k]
                    to_update = False
                    ofbx = self._fbx_o_dict[k]
                    # print(ofbx.comment, v.comment)
                    if (ofbx.comment != v.comment) or (ofbx.ip != v.ip):
                        to_update = True
                    if to_update:
                        print(v, u'\n Archive:\n', ofbx)
                        to_restore = False
                        answer = None
                        while answer not in ("y", "n", "Y", "N", "o", "O"):
                            answer = input(u"Update Y/N): ")
                            if answer in ("y", "Y", "o", "O"):
                                to_restore = True
                            elif answer in ("n", "N"):
                                to_restore = False
                        if to_restore:
                            """ Create missing static lease"""
                            uri = u'/dhcp/static_lease/{}'.format(v.mac)
                            data = {"ip": v.ip, "comment": v.comment}
                            resp = self._http.put(uri, data)
                            if not resp.success:
                                print(u'Update failed')
            return

        log(">>> get_dhcp_leases")
        # GET dhcp leases
        uri = '/dhcp/dynamic_lease/'
        resp = self._http.get(uri)

        if not resp.success:
            raise FbxException('Request failure: {}'.format(resp))

        # json response format
        if self._conf.resp_as_json:
            return resp.whole_content

        # human response format
        leases = resp.result
        if leases is None:
            print('No DHCP leases')
            return 0

        count = self.save_to_archive(FbxDhcpDynamicLease, leases)

        count = 1

        # To do : use self._fbx_o_dict

        for olease in self._fbx_o_dict.values():
            print(u'  #{}: {}'.format(count, olease))
            count += 1

        return

        count = 1

        for lease in leases:
            if 'host' in lease and lease.get('host').get('reachable'):
                olease = FbxDhcpDynamicLease(self, lease)
                print(u'  #{}: {}'.format(count, olease))
                count += 1

        count = 1
        print('List of unreachable leases:')
        for lease in leases:
            if 'host' in lease and not lease.get('host').get('reachable'):
                olease = FbxDhcpDynamicLease(self, lease)
                print(u'  #{}: {}'.format(count, olease))
                count += 1

        count = 1
        print('List of other leases:')
        for lease in leases:
            if 'host' not in lease:
                olease = FbxDhcpDynamicLease(self, lease)
                print(u'  #{}: {}'.format(count, olease))
                count += 1
        return 0
コード例 #15
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
    def get_static_leases(self):
        """ List the DHCP leases on going"""

        log(">>> get_static_leases")
        self._dyn_leases = FbxDhcpDynamicLeases(self._ctrl)

        def load_from_archive(svc):
            st_leases = FbxDhcpStaticLeases(svc._ctrl, empty=True)
            t_st_leases = FbxDbTable(u'static_lease', u'id',
                                     table_defs[u'static_lease'][u'cols_def'])
            st_leases.load_from_db(svc._ctrl, FbxDhcpStaticLease, t_st_leases)
            return st_leases

        if self._conf.resp_archive:
            self._st_leases = load_from_archive(self)
        else:
            self._st_leases = FbxDhcpStaticLeasesX(self._ctrl,
                                                   self._dyn_leases)

        if self._conf.resp_restore:
            self._st_leases_arc = load_from_archive(self)
            # look for missing static leases
            print(u'\nMissing leases')
            for st_lease_arc in self._st_leases_arc:
                st_lease_fbx = self._st_leases.get_by_id(st_lease_arc.mac)
                if st_lease_fbx is None:
                    print(st_lease_arc)
                    if fbx_question_yn(u'Restore'):
                        data = {
                            u"mac": st_lease_arc.mac,
                            u"ip": st_lease_arc.ip,
                            u"comment": st_lease_arc.comment
                        }
                        print(u'Restore', data)
                        url = u'/dhcp/static_lease/'
                        resp = self._http.post(url, data=data)
                        if not resp.success:
                            raise FbxException(
                                'Request failure: {}'.format(resp))

            # look for leases to update
            print(u'\nLeases to update')
            for st_lease_arc in self._st_leases_arc:
                st_lease_fbx = self._st_leases.get_by_id(st_lease_arc.mac)
                if st_lease_fbx is not None:
                    data = {u"mac": st_lease_arc.mac}
                    to_restore = False
                    for key in [u'ip', u'comment']:
                        if getattr(st_lease_arc, key) != getattr(
                                st_lease_fbx, key):
                            to_restore = True
                            data[key] = getattr(st_lease_arc, key)
                    if to_restore:
                        print(st_lease_arc)
                        print(st_lease_fbx)
                        print(data)
                        if fbx_question_yn(u'Update'):
                            print(u'Update', data)
                            url = u'/dhcp/static_lease/{}'.format(
                                st_lease_arc.mac)
                            resp = self._http.put(url, data=data)
                            if not resp.success:
                                raise FbxException(
                                    'Request failure: {}'.format(resp))
            return 0

        if self._conf.resp_save:
            self._st_leases.save_to_db()

        if self._conf.resp_as_json and self._conf.resp_archive is False:
            return self._st_leases.json

        count = 0
        # for new call only, we display new calls only
        for st_lease in self._st_leases:
            # if new_only and call.new is False:
            #     continue
            count += 1
            # st_lease to be displayed
            print(u'{}# {}'.format(count, st_lease))

        return count > 0
コード例 #16
0
ファイル: fbxosctrl.py プロジェクト: afer92/fbxosctrl
 def reboot(self):
     """ Reboot the freebox server now! """
     log(">>> reboot")
     uri = '/system/reboot/'
     self._http.post(uri, timeout=3)
     return True