def addExistingAccount(self):
        try:
            display_name = str(self.displayNameText.stringValue().strip())
            address = str(self.addressText.stringValue().strip())
            password = str(self.passwordText.stringValue().strip())
            sync_with_icloud = True if self.syncWithiCloudCheckbox.state() == NSOnState else False

            account = Account(str(address))
            account.display_name = display_name
            account.auth.password = password
            account.enabled = True
            account.gui.sync_with_icloud = sync_with_icloud
            account.xcap.enabled = True if self.syncContactsCheckBox.state() == NSOnState else False
            account.presence.enabled = True if self.syncContactsCheckBox.state() == NSOnState else False

            if account.id.domain == 'sip2sip.info':
                account.server.settings_url = "https://blink.sipthor.net/settings.phtml"
                account.ldap.hostname = "ldap.sipthor.net"
                account.ldap.dn = "ou=addressbook, dc=sip2sip, dc=info"
                account.ldap.enabled = True
                account.nat_traversal.use_ice = True
                account.rtp.srtp_encryption = 'optional'

            account.save()
        except ValueError as e:
            NSRunAlertPanel(NSLocalizedString("Sign In to SIP Account", "Window title"), NSLocalizedString("Cannot add SIP Account: %s", "Label") % e, NSLocalizedString("OK", "Button title"), None, None)
            return False

        AccountManager().default_account = account

        return True
    def addExistingAccount(self):
        try:
            display_name = unicode(self.displayNameText.stringValue())
            address = unicode(self.addressText.stringValue())
            password = unicode(self.passwordText.stringValue())
            sync_with_icloud = True if self.syncWithiCloudCheckbox.state() == NSOnState else False

            account = Account(str(address))
            account.display_name = display_name
            account.auth.password = password
            account.enabled = True
            account.gui.sync_with_icloud = sync_with_icloud
            account.xcap.enabled = True if self.syncContactsCheckBox.state() == NSOnState else False
            account.presence.enabled = True if self.syncContactsCheckBox.state() == NSOnState else False

            if account.id.domain == 'sip2sip.info':
                account.server.settings_url = "https://blink.sipthor.net/settings.phtml"
                account.ldap.hostname = "ldap.sipthor.net"
                account.ldap.dn = "ou=addressbook, dc=sip2sip, dc=info"
                account.ldap.enabled = True
                account.nat_traversal.use_ice = True
                account.rtp.srtp_encryption = 'optional'

            account.save()
        except ValueError, e:
            NSRunAlertPanel(NSLocalizedString("Sign In to SIP Account", "Window title"), NSLocalizedString("Cannot add SIP Account: %s", "Label") % e, NSLocalizedString("OK", "Button title"), None, None)
            return False
Example #3
0
def handle_accounts():
    if request.method == 'GET':
        # Retrieve accounts list
        accounts = AccountManager().get_accounts()
        accs = []
        for account in accounts:
            state = get_state(account)
            state['id'] = account.id
            if 'auth' in state:
                state['auth']['password'] = '******'
            accs.append(state)
        return jsonify({'accounts': accs})
    elif request.method == 'POST':
        # Create account
        state = get_json(request)
        if not state:
            return error_response(400, 'error processing POST body')
        account_id = state.pop('id', None)
        if not account_id:
            return error_response(400, 'account ID was not specified')
        try:
            account = Account(account_id)
        except DuplicateIDError:
            return error_response(409, 'duplicated account ID')
        try:
            set_state(account, state)
        except ValueError, e:
            account.delete()
            return error_response(400, str(e))
        account.enabled = True
        account.save()
        state = get_state(account)
        if 'auth' in state:
            state['auth']['password'] = '******'
        return jsonify({'account': state}), 201
Example #4
0
 def _create_sip_account(self, username, password, email_address, display_name, timezone=None):
     red = '#cc0000'
     if timezone is None and sys.platform != 'win32':
         try:
             timezone = open('/etc/timezone').read().strip()
         except (OSError, IOError):
             try:
                 timezone = '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
             except (OSError, IOError):
                 pass
     enrollment_data = dict(username=username.lower().encode('utf-8'),
                            password=password.encode('utf-8'),
                            email=email_address.encode('utf-8'),
                            display_name=display_name.encode('utf-8'),
                            tzinfo=timezone)
     try:
         settings = SIPSimpleSettings()
         data = urllib.parse.urlencode(dict(enrollment_data))
         response = urllib.request.urlopen(settings.server.enrollment_url, data.encode())
         response_data = json.loads(response.read().decode('utf-8').replace(r'\/', '/'))
         response_data = defaultdict(lambda: None, response_data)
         if response_data['success']:
             try:
                 passport = response_data['passport']
                 if passport is not None:
                     certificate_path = self._save_certificates(response_data['sip_address'], passport['crt'], passport['key'], passport['ca'])
                 else:
                     certificate_path = None
             except (GNUTLSError, IOError, OSError):
                 certificate_path = None
             account_manager = AccountManager()
             try:
                 account = Account(response_data['sip_address'])
             except DuplicateIDError:
                 account = account_manager.get_account(response_data['sip_address'])
             account.enabled = True
             account.display_name = display_name or None
             account.auth.password = password
             account.sip.outbound_proxy = response_data['outbound_proxy']
             account.nat_traversal.msrp_relay = response_data['msrp_relay']
             account.xcap.xcap_root = response_data['xcap_root']
             account.tls.certificate = certificate_path
             account.server.conference_server = response_data['conference_server']
             account.server.settings_url = response_data['settings_url']
             account.save()
             account_manager.default_account = account
             call_in_gui_thread(self.accept)
         elif response_data['error'] == 'user_exists':
             call_in_gui_thread(self.username_editor.addException, username)
         else:
             call_in_gui_thread(setattr, self.create_status_label, 'value', Status(response_data['error_message'], color=red))
     except (json.decoder.JSONDecodeError, KeyError):
         call_in_gui_thread(setattr, self.create_status_label, 'value', Status('Illegal server response', color=red))
     except urllib.error.URLError as e:
         call_in_gui_thread(setattr, self.create_status_label, 'value', Status('Failed to contact server: %s' % e.reason, color=red))
     finally:
         call_in_gui_thread(self.setEnabled, True)
Example #5
0
 def _create_sip_account(self, username, password, email_address, display_name, timezone=None):
     red = '#cc0000'
     if timezone is None and sys.platform != 'win32':
         try:
             timezone = open('/etc/timezone').read().strip()
         except (OSError, IOError):
             try:
                 timezone = '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
             except (OSError, IOError):
                 pass
     enrollment_data = dict(username=username.lower().encode('utf-8'),
                            password=password.encode('utf-8'),
                            email=email_address.encode('utf-8'),
                            display_name=display_name.encode('utf-8'),
                            tzinfo=timezone)
     try:
         settings = SIPSimpleSettings()
         response = urllib2.urlopen(settings.server.enrollment_url, urllib.urlencode(dict(enrollment_data)))
         response_data = cjson.decode(response.read().replace(r'\/', '/'))
         response_data = defaultdict(lambda: None, response_data)
         if response_data['success']:
             from blink import Blink
             try:
                 certificate_path = None
                 passport = response_data['passport']
                 if passport is not None:
                     certificate_path = Blink().save_certificates(response_data['sip_address'], passport['crt'], passport['key'], passport['ca'])
             except (GNUTLSError, IOError, OSError):
                 pass
             account_manager = AccountManager()
             try:
                 account = Account(response_data['sip_address'])
             except DuplicateIDError:
                 account = account_manager.get_account(response_data['sip_address'])
             account.enabled = True
             account.display_name = display_name or None
             account.auth.password = password
             account.sip.outbound_proxy = response_data['outbound_proxy']
             account.nat_traversal.msrp_relay = response_data['msrp_relay']
             account.xcap.xcap_root = response_data['xcap_root']
             account.tls.certificate = certificate_path
             account.server.conference_server = response_data['conference_server']
             account.server.settings_url = response_data['settings_url']
             account.save()
             account_manager.default_account = account
             call_in_gui_thread(self.accept)
         elif response_data['error'] == 'user_exists':
             call_in_gui_thread(self.username_editor.addException, username)
         else:
             call_in_gui_thread(setattr, self.create_status_label, 'value', Status(response_data['error_message'], color=red))
     except (cjson.DecodeError, KeyError):
         call_in_gui_thread(setattr, self.create_status_label, 'value', Status('Illegal server response', color=red))
     except urllib2.URLError, e:
         call_in_gui_thread(setattr, self.create_status_label, 'value', Status('Failed to contact server: %s' % e.reason, color=red))
Example #6
0
 def _SH_AcceptButtonClicked(self):
     if self.panel_view.currentWidget() is self.add_account_panel:
         account = Account(self.sip_address)
         account.enabled = True
         account.display_name = self.display_name
         account.auth.password = self.password
         call_in_auxiliary_thread(account.save)
         account_manager = AccountManager()
         account_manager.default_account = account
         self.accept()
     else:
         self.setEnabled(False)
         self.create_status_label.value = Status("Creating account on server...")
         self._create_sip_account(self.username, self.password, self.email_address, self.display_name)
Example #7
0
 def _SH_AcceptButtonClicked(self):
     if self.panel_view.currentWidget() is self.add_account_panel:
         account = Account(self.sip_address)
         account.enabled = True
         account.display_name = self.display_name or None
         account.auth.password = self.password
         account.save()
         account_manager = AccountManager()
         account_manager.default_account = account
         self.accept()
     else:
         self.setEnabled(False)
         self.create_status_label.value = Status('Creating account on server...')
         self._create_sip_account(self.username, self.password, self.email_address, self.display_name)
    def addExistingAccount(self):
        try:
            display_name = unicode(self.displayNameText.stringValue())
            address = unicode(self.addressText.stringValue())
            password = unicode(self.passwordText.stringValue())

            account = Account(str(address))
            account.display_name = display_name
            account.auth.password = password
            account.enabled = True
            account.save()
        except ValueError, e:
            NSRunAlertPanel("Sign In to SIP Account", "Cannot add SIP Account: %s"%str(e), "OK", None, None)
            return False
    def addExistingAccount(self):
        try:
            display_name = unicode(self.displayNameText.stringValue())
            address = unicode(self.addressText.stringValue())
            password = unicode(self.passwordText.stringValue())

            account = Account(str(address))
            account.display_name = display_name
            account.auth.password = password
            account.enabled = True
            account.save()
        except ValueError, e:
            NSRunAlertPanel("Sign In to SIP Account",
                            "Cannot add SIP Account: %s" % str(e), "OK", None,
                            None)
            return False
Example #10
0
 def _SH_AcceptButtonClicked(self):
     if self.panel_view.currentWidget() is self.add_account_panel:
         account = Account(self.sip_address)
         account.enabled = True
         account.display_name = self.display_name or None
         account.auth.password = self.password
         if account.id.domain == 'sip2sip.info':
             account.server.settings_url = "https://blink.sipthor.net/settings.phtml"
         account.save()
         account_manager = AccountManager()
         account_manager.default_account = account
         self.accept()
     else:
         self.setEnabled(False)
         self.create_status_label.value = Status(
             'Creating account on server...')
         self._create_sip_account(self.username, self.password,
                                  self.email_address, self.display_name)
Example #11
0
	def add_account(self, name, username, password):
		if name in self.accounts:
			raise Exception("Already got account with that name")
		
		logging.info("adding account: %s", name)
		
		# clear the event, in case something went wrong
		self.registering.clear()
		
		# register/create the account
		new_account = Account(name)
		new_account.auth.username = username
		new_account.auth.password = password
		new_account.sip.register_interval = 30
		new_account.enabled = True
		new_account.save()
		
		# wait for it to be completly created
		self.registering.wait()
		
		# remember our account
		self.accounts[name] = new_account
Example #12
0
            if data['ldap_password']:
                account.ldap.password = data['ldap_password']

            if data['ldap_transport']:
                account.ldap.transport = data['ldap_transport']

            if data['ldap_port']:
                account.ldap.port = data['ldap_port']

        if data['passport'] is not None:
            cert_path = self.save_certificates(data)
            if cert_path:
                account.tls.certificate = cert_path

        account.enabled = True
        account.save()

        account_manager.default_account = default_account

        settings = SIPSimpleSettings()
        settings.service_provider.name      = data['service_provider_name']
        settings.service_provider.help_url  = data['service_provider_help_url']
        settings.service_provider.about_url = data['service_provider_about_url']
        settings.save()

    def get_audio_recordings_directory(self):
        return ApplicationData.get('history')

    def get_contacts_backup_directory(self):
        path = ApplicationData.get('contacts_backup')
Example #13
0
            default_account = account_manager.default_account
        account.auth.username = data['auth_username']
        account.auth.password = data['password'] or ''
        account.sip.outbound_proxy = data['outbound_proxy']
        account.xcap.xcap_root = data['xcap_root']
        account.nat_traversal.msrp_relay = data['msrp_relay']
        account.server.conference_server = data['conference_server']
        account.server.settings_url = data['settings_url']
        if data['passport'] is not None:
            try:
                passport = data['passport']
                certificate_path = self.save_certificates(account_id, passport['crt'], passport['key'], passport['ca'])
                account.tls.certificate = certificate_path
            except (GNUTLSError, IOError, OSError):
                pass
        account.enabled = True
        account.save()
        account_manager.default_account = default_account

    def save_certificates(self, sip_address, crt, key, ca):
        crt = crt.strip() + os.linesep
        key = key.strip() + os.linesep
        ca = ca.strip() + os.linesep
        X509Certificate(crt)
        X509PrivateKey(key)
        X509Certificate(ca)
        makedirs(ApplicationData.get('tls'))
        certificate_path = ApplicationData.get(os.path.join('tls', sip_address+'.crt'))
        file = open(certificate_path, 'w')
        os.chmod(certificate_path, 0600)
        file.write(crt+key)
Example #14
0
    def _create_sip_account(self, username, password, email_address, display_name, timezone=None):
        red = "#cc0000"
        if timezone is None and sys.platform != "win32":
            try:
                timezone = open("/etc/timezone").read().strip()
            except (OSError, IOError):
                try:
                    timezone = "/".join(os.readlink("/etc/localtime").split("/")[-2:])
                except (OSError, IOError):
                    pass
        enrollment_data = dict(
            username=username.lower().encode("utf-8"),
            password=password.encode("utf-8"),
            email=email_address.encode("utf-8"),
            display_name=display_name.encode("utf-8"),
            tzinfo=timezone,
        )
        try:
            settings = SIPSimpleSettings()
            response = urllib2.urlopen(settings.server.enrollment_url, urllib.urlencode(dict(enrollment_data)))
            response_data = cjson.decode(response.read().replace(r"\/", "/"))
            response_data = defaultdict(lambda: None, response_data)
            if response_data["success"]:
                from blink import Blink

                try:
                    certificate_path = None
                    passport = response_data["passport"]
                    if passport is not None:
                        certificate_path = Blink().save_certificates(
                            response_data["sip_address"], passport["crt"], passport["key"], passport["ca"]
                        )
                except (GNUTLSError, IOError, OSError):
                    pass
                account_manager = AccountManager()
                try:
                    account = Account(response_data["sip_address"])
                except AccountExists:
                    account = account_manager.get_account(response_data["sip_address"])
                account.enabled = True
                account.display_name = display_name
                account.auth.password = password
                account.sip.outbound_proxy = response_data["outbound_proxy"]
                account.nat_traversal.msrp_relay = response_data["msrp_relay"]
                account.xcap.xcap_root = response_data["xcap_root"]
                account.tls.certificate = certificate_path
                account.server.settings_url = response_data["settings_url"]
                account.save()
                account_manager.default_account = account
                call_in_gui_thread(self.accept)
            elif response_data["error"] == "user_exists":
                call_in_gui_thread(self.username_editor.addException, username)
            else:
                call_in_gui_thread(
                    setattr, self.create_status_label, "value", Status(response_data["error_message"], color=red)
                )
        except (cjson.DecodeError, KeyError):
            call_in_gui_thread(setattr, self.create_status_label, "value", Status("Illegal server response", color=red))
        except urllib2.URLError, e:
            call_in_gui_thread(
                setattr, self.create_status_label, "value", Status("Failed to contact server: %s" % e.reason, color=red)
            )
Example #15
0
    def fetch_account(self):
        """Fetch the SIP account from ~/.blink_account and create/update it as needed"""
        filename = os.path.expanduser('~/.blink_account')
        if not os.path.exists(filename):
            return
        try:
            data = open(filename).read()
            data = json.loads(data.decode().replace('\\/', '/'))
        except (OSError, IOError) as e:
            BlinkLogger().log_error("Failed to read json data from ~/.blink_account: %s" % e)
            return
        except ValueError as e:
            BlinkLogger().log_error("Failed to decode json data from ~/.blink_account: %s" % e)
            return
        finally:
            unlink(filename)

        data = defaultdict(lambda: None, data)
        account_id = data['sip_address']
        if account_id is None:
            return

        account_manager = AccountManager()

        try:
            account = account_manager.get_account(account_id)
        except KeyError:
            account = Account(account_id)
            account.display_name = data['display_name']
            default_account = account
        else:
            default_account = account_manager.default_account

        account.auth.username            = data['auth_username']
        account.auth.password            = data['password'] or ''
        account.sip.outbound_proxy       = data['outbound_proxy']
        account.xcap.xcap_root           = data['xcap_root']
        account.nat_traversal.msrp_relay = data['msrp_relay']
        account.server.settings_url      = data['settings_url']
        account.web_alert.alert_url      = data['web_alert_url']
        account.server.web_password      = data['web_password']
        account.conference.server_address = data['conference_server']

        if data['ldap_hostname']:
            account.ldap.enabled  = True
            account.ldap.hostname = data['ldap_hostname']
            account.ldap.dn       = data['ldap_dn']
            account.ldap.username = data['ldap_username']

            if data['ldap_password']:
                account.ldap.password = data['ldap_password']

            if data['ldap_transport']:
                account.ldap.transport = data['ldap_transport']

            if data['ldap_port']:
                account.ldap.port = data['ldap_port']

        if data['passport'] is not None:
            cert_path = self.save_certificates(data)
            if cert_path:
                account.tls.certificate = cert_path

        account.enabled = True
        account.save()

        account_manager.default_account = default_account

        settings = SIPSimpleSettings()
        settings.service_provider.name      = data['service_provider_name']
        settings.service_provider.help_url  = data['service_provider_help_url']
        settings.service_provider.about_url = data['service_provider_about_url']
        settings.save()
    def createNewAccount(self):
        sip_address = None
        display_name = str(self.newDisplayNameText.stringValue().strip())
        username = str(self.newUsernameText.stringValue().strip())
        password = str(self.newPasswordText.stringValue().strip())
        email = str(self.newEmailText.stringValue())

        self.progressIndicator.setHidden_(False)
        self.domainButton.setHidden_(True)
        self.progressText.setHidden_(False)
        self.progressIndicator.setUsesThreadedAnimation_(True)
        self.progressIndicator.startAnimation_(None)
        self.window.display()

        url = SIPSimpleSettings().server.enrollment_url

        sip_address = None

        tzname = datetime.datetime.now(tzlocal()).tzname() or ""

        if not tzname:
            BlinkLogger().log_warning("Unable to determine timezone")

        values = {'password'     : password.encode("utf8"),
                  'username'     : username.encode("utf8"),
                  'email'        : email.encode("utf8"),
                  'display_name' : display_name.encode("utf8"),
                  'tzinfo'       : tzname }

        BlinkLogger().log_info("Requesting creation of a new SIP account at %s" % url)

        data = urllib.parse.urlencode(values)
        req = urllib.request.Request(url, data.encode("utf-8"))

        try:
            raw_response = urllib.request.urlopen(req)
        except urllib.error.URLError as e:
            error_message = NSLocalizedString("Cannot connect to enrollment server: %s", "Enrollment panel label") % e
        except urllib.error.HTTPError as e:
            error_message = NSLocalizedString("Error from enrollment server: %s", "Enrollment panel label") % e
        else:
            raw_data = raw_response.read().decode().replace('\\/', '/')

            try:
                json_data = json.loads(raw_data)
            except (TypeError, json.decoder.JSONDecodeError):
                error_message = NSLocalizedString("Cannot decode data from enrollment server", "Enrollment panel label")
            else:

                try:
                    success = json_data["success"]
                except (TypeError, KeyError):
                    success = False
                
                if not success:
                    BlinkLogger().log_info("Enrollment Server failed to create SIP account")
                    try:
                        error_message = json_data["error_message"]
                    except (TypeError, KeyError):
                        error_message == 'Cannot read server response'
                else:
                    BlinkLogger().log_info("Enrollment Server successfully created SIP account")

                    data = defaultdict(lambda: None, json_data)
                    tls_path = None if data['passport'] is None else SIPManager().save_certificates(data)

                    sip_address = data['sip_address']
                    try:
                        outbound_proxy = data['outbound_proxy']
                    except KeyError:
                        outbound_proxy = None

                    try:
                        xcap_root = data['xcap_root']
                    except KeyError:
                        xcap_root = None

                    try:
                        msrp_relay = data['msrp_relay']
                    except KeyError:
                        msrp_relay = None

                    try:
                        settings_url = data['settings_url']
                    except KeyError:
                        settings_url = None

                    try:
                        web_alert_url = data['web_alert_url']
                    except KeyError:
                        web_alert_url = None

                    try:
                        web_password = data['web_password']
                    except KeyError:
                        web_password = None

                    try:
                        conference_server = data['conference_server']
                    except KeyError:
                        conference_server = None

                    try:
                        ldap_hostname = data['ldap_hostname']
                    except KeyError:
                        ldap_hostname = None

                    try:
                        ldap_transport = data['ldap_transport']
                    except KeyError:
                        ldap_transport = None

                    try:
                        ldap_port = data['ldap_port']
                    except KeyError:
                        ldap_port = None

                    try:
                        ldap_username = data['ldap_username']
                    except KeyError:
                        ldap_username = None

                    try:
                        ldap_password = data['ldap_password']
                    except KeyError:
                        ldap_password = None

                    try:
                        ldap_dn = data['ldap_dn']
                    except KeyError:
                        ldap_dn = None


        self.progressIndicator.stopAnimation_(None)
        self.progressIndicator.setHidden_(True)
        self.progressText.setHidden_(True)
        self.domainButton.setHidden_(False)

        if sip_address is None:
            BlinkLogger().log_info(error_message)
            NSRunAlertPanel(NSLocalizedString("Sign Up to SIP Account", "Window title"),
                            NSLocalizedString("Error creating SIP account: %s", "Label") % error_message, NSLocalizedString("OK", "Button title"), None, None)
            return False

        try:
            account = Account(str(sip_address))
        except ValueError as e:
            NSRunAlertPanel(NSLocalizedString("Sign Up to SIP Account", "Window title"), NSLocalizedString("Cannot add SIP Account: %s", "Label") % e, NSLocalizedString("OK", "Button title"), None, None)
            return False
        else:
            NSApp.delegate().contactsWindowController.created_accounts.add(account.id)

        account.display_name = display_name
        account.auth.password = password
        account.nat_traversal.use_ice = True
        account.rtp.srtp_encryption = 'optional'

        if tls_path:
            account.tls.certificate = tls_path

        account.sip.outbound_proxy = outbound_proxy
        account.xcap.xcap_root = xcap_root
        account.nat_traversal.msrp_relay = msrp_relay

        if settings_url:
            account.server.settings_url = settings_url

        if web_alert_url:
            account.web_alert.alert_url = web_alert_url

        if web_password:
            account.server.web_password = web_password

        if conference_server:
            account.conference.server_address = conference_server

        if ldap_hostname:
            account.ldap.enabled = True
            account.ldap.hostname = ldap_hostname
            account.ldap.dn = ldap_dn
            account.ldap.username = ldap_username
            if ldap_password:
                account.ldap.password = ldap_password

            if ldap_transport:
                account.ldap.transport = ldap_transport

            if ldap_port:
                account.ldap.port = ldap_port

        sync_with_icloud = bool(self.syncWithiCloudCheckbox.state())
        account.gui.sync_with_icloud = sync_with_icloud

        account.save()

        NSRunAlertPanel(NSLocalizedString("SIP Account Created", "Window title"), NSLocalizedString("Your new SIP Address is:\n\n%s", "Label") % sip_address, NSLocalizedString("Continue", "Button title"), None, None)

        # enable account only after Continue pressed to give server time to update
        account.enabled = True
        account.save()
        AccountManager().default_account = account

        return True