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 #2
0
    def __init__(self):
        super(Blink, self).__init__(sys.argv)
        self.setAttribute(Qt.AA_DontShowIconsInMenus, False)
        self.sip_application = SIPApplication()
        self.first_run = False

        self.setOrganizationDomain("ag-projects.com")
        self.setOrganizationName("AG Projects")
        self.setApplicationName("Blink")
        self.setApplicationVersion(__version__)

        self.main_window = MainWindow()
        self.chat_window = ChatWindow()
        self.main_window.__closed__ = True
        self.chat_window.__closed__ = True
        self.main_window.installEventFilter(self)
        self.chat_window.installEventFilter(self)

        self.main_window.addAction(self.chat_window.control_button.actions.main_window)
        self.chat_window.addAction(self.main_window.quit_action)
        self.chat_window.addAction(self.main_window.help_action)
        self.chat_window.addAction(self.main_window.redial_action)
        self.chat_window.addAction(self.main_window.join_conference_action)
        self.chat_window.addAction(self.main_window.mute_action)
        self.chat_window.addAction(self.main_window.silent_action)
        self.chat_window.addAction(self.main_window.preferences_action)
        self.chat_window.addAction(self.main_window.transfers_window_action)
        self.chat_window.addAction(self.main_window.logs_window_action)
        self.chat_window.addAction(self.main_window.received_files_window_action)
        self.chat_window.addAction(self.main_window.screenshots_window_action)

        self.ip_address_monitor = IPAddressMonitor()
        self.log_manager = LogManager()
        self.presence_manager = PresenceManager()
        self.session_manager = SessionManager()
        self.update_manager = UpdateManager()

        # Prevent application from exiting after last window is closed if system tray was initialized
        if self.main_window.system_tray_icon:
            self.setQuitOnLastWindowClosed(False)

        self.main_window.check_for_updates_action.triggered.connect(self.update_manager.check_for_updates)
        self.main_window.check_for_updates_action.setVisible(self.update_manager != Null)

        if getattr(sys, 'frozen', False):
            XMLDocument.schema_path = Resources.get('xml-schemas')

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(ContactExtension)
        Group.register_extension(GroupExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        notification_center = NotificationCenter()
        notification_center.add_observer(self, sender=self.sip_application)

        branding.setup(self)
Example #3
0
    def __init__(self):
        super(Blink, self).__init__(sys.argv)
        self.setAttribute(Qt.AA_DontShowIconsInMenus, False)
        self.sip_application = SIPApplication()
        self.first_run = False

        self.setOrganizationDomain("ag-projects.com")
        self.setOrganizationName("AG Projects")
        self.setApplicationName("Blink")
        self.setApplicationVersion(__version__)

        self.main_window = MainWindow()
        self.chat_window = ChatWindow()
        self.main_window.__closed__ = True
        self.chat_window.__closed__ = True
        self.main_window.installEventFilter(self)
        self.chat_window.installEventFilter(self)

        self.main_window.addAction(self.chat_window.control_button.actions.main_window)
        self.chat_window.addAction(self.main_window.quit_action)
        self.chat_window.addAction(self.main_window.help_action)
        self.chat_window.addAction(self.main_window.redial_action)
        self.chat_window.addAction(self.main_window.join_conference_action)
        self.chat_window.addAction(self.main_window.mute_action)
        self.chat_window.addAction(self.main_window.silent_action)
        self.chat_window.addAction(self.main_window.preferences_action)
        self.chat_window.addAction(self.main_window.transfers_window_action)
        self.chat_window.addAction(self.main_window.logs_window_action)
        self.chat_window.addAction(self.main_window.received_files_window_action)
        self.chat_window.addAction(self.main_window.screenshots_window_action)

        self.ip_address_monitor = IPAddressMonitor()
        self.log_manager = LogManager()
        self.presence_manager = PresenceManager()
        self.session_manager = SessionManager()
        self.update_manager = UpdateManager()

        # Prevent application from exiting after last window is closed if system tray was initialized
        if self.main_window.system_tray_icon:
            self.setQuitOnLastWindowClosed(False)

        self.main_window.check_for_updates_action.triggered.connect(self.update_manager.check_for_updates)
        self.main_window.check_for_updates_action.setVisible(self.update_manager != Null)

        if getattr(sys, "frozen", False):
            XMLDocument.schema_path = Resources.get("xml-schemas")

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(ContactExtension)
        Group.register_extension(GroupExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        notification_center = NotificationCenter()
        notification_center.add_observer(self, sender=self.sip_application)

        branding.setup(self)
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()
         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 #5
0
    def init(self):

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(BlinkContactExtension)
        Group.register_extension(BlinkGroupExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        self._app.start(FileStorage(ApplicationData.directory))

        # start session mgr
        SessionManager()
Example #6
0
    def __init__(self):
        self.application = SIPApplication()
        self.stopping = False
        self.stop_event = Event()

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        self.account_model = AccountModel()
        self.bonjour_services = BonjourServices()
        self.hal = HardwareAbstractionLayer()
        self.session_manager = SessionManager()
        self.web_handler = WebHandler()
    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 #8
0
    def start(self, options):
        self.options = options
        if self.options.enable_bonjour:
            ServerConfig.enable_bonjour = True

        notification_center = NotificationCenter()
        notification_center.add_observer(self, sender=self)
        notification_center.add_observer(self, name='ThorNetworkGotFatalError')

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        SIPSimpleSettings.register_extension(SylkServerSettingsExtension)

        super(SylkServer, self).start(MemoryStorage())
Example #9
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 #10
0
    def __init__(self):
        super(Blink, self).__init__(sys.argv)
        self.application = SIPApplication()
        self.auxiliary_thread = AuxiliaryThread()
        self.first_run = False
        self.main_window = MainWindow()

        self.update_manager = UpdateManager()
        self.main_window.check_for_updates_action.triggered.connect(self.update_manager.check_for_updates)
        self.main_window.check_for_updates_action.setVisible(self.update_manager != Null)

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)
        session_manager = SessionManager()
        session_manager.initialize(self.main_window, self.main_window.session_model)
Example #11
0
    def init(self):
        self._version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))

        #first_start = not os.path.exists(ApplicationData.get('config'))

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(BlinkContactExtension)
        ContactGroup.register_extension(BlinkContactGroupExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        self._app.start(FileStorage(ApplicationData.directory))
        self.init_configurations()

        # start session mgr
        SessionManager()
Example #12
0
	def _NH_SIPApplicationDidStart(self, notification):
		logging.info("Application started")

		# configure our account
		self.my_account = Account("*@62.220.30.149")
		self.my_account.sip.register = False
		self.my_account.enabled = True
		self.my_account.save()
Example #13
0
    def init(self):
        self._version = str(
            NSBundle.mainBundle().infoDictionary().objectForKey_(
                "CFBundleShortVersionString"))

        #first_start = not os.path.exists(ApplicationData.get('config'))

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(BlinkContactExtension)
        ContactGroup.register_extension(BlinkContactGroupExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        self._app.start(FileStorage(ApplicationData.directory))
        self.init_configurations()

        # start session mgr
        SessionManager()
Example #14
0
    def run(self):
        account_manager = AccountManager()
        configuration = ConfigurationManager()
        engine = Engine()

        # start output thread
        self.output.start()

        # startup configuration
        Account.register_extension(AccountExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)
        SIPApplication.storage = FileStorage(config_directory)
        try:
            configuration.start()
        except ConfigurationError, e:
            raise RuntimeError(
                "failed to load sipclient's configuration: %s\nIf an old configuration file is in place, delete it or move it and recreate the configuration using the sip_settings script."
                % str(e))
Example #15
0
    def init(self):
        if NSApp.delegate().account_extension:
            Account.register_extension(NSApp.delegate().account_extension)
        else:
            Account.register_extension(AccountExtension)

        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(BlinkContactExtension)
        Group.register_extension(BlinkGroupExtension)
        ContactURI.register_extension(BlinkContactURIExtension)
        if NSApp.delegate().general_extension:
            SIPSimpleSettings.register_extension(NSApp.delegate().general_extension)
        else:
            SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        app = AppKit.NSApplication.sharedApplication()
        self._app.start(FileStorage(ApplicationData.directory))

        # start session mgr
        SessionManager()
Example #16
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
    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
Example #18
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 #19
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 #20
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
Example #22
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 #23
0
class SimpleCallApplication(SIPApplication):
	def __init__(self):
		SIPApplication.__init__(self)
		self.player = None
		self.ended = Event()
		self.logeng = SIPEngineLogObserver()

		notification_center = NotificationCenter()
		notification_center.add_observer(self)
		notification_center.add_observer(self.logeng, name="SIPEngineLog")

		SIPSimpleSettings.sip.udp_port=5060
		SIPSimpleSettings.sip.transport_list=['udp']

	# Application Events
	@run_in_green_thread
	def _NH_SIPApplicationDidStart(self, notification):
		logging.info("Application started")

		# configure our account
		self.my_account = Account("*@62.220.30.149")
		self.my_account.sip.register = False
		self.my_account.enabled = True
		self.my_account.save()
	
	def _NH_SIPApplicationDidEnd(self, notification):
		logging.info("Application ended")
		self.ended.set()
		
	# Account Events
	def _NH_SIPAccountWillActivate(self, notification):
		logging.info("Account Activating!")
	
	def _NH_SIPAccountDidActivate(self, notification):
		logging.info("Account Activated!")
	
	# Session Events
	@run_in_green_thread
	def _NH_SIPSessionNewIncoming(self, notification):
		logging.info("Incoming")
		
		# lets accept it
		session = notification.sender
		session.send_ring_indication()
		session.accept([AudioStream()])

	def _NH_SIPSessionWillStart(self, notification):
		logging.info("Session will start")

	def _NH_SIPSessionGotRingIndication(self, notification):
		logging.info('Ringing!')

	def _NH_SIPSessionDidStart(self, notification):
		session = notification.sender
		logging.info('Session started - Local: %s - Remote: %s', str(session.local_identity), str(session.remote_identity))

		session.my_player = WavePlayer(SIPApplication.voice_audio_mixer, "/root/Sleep Away.wav", loop_count=0, initial_play=False)
		audio_stream = session.streams[0]
		audio_stream.bridge.add(session.my_player)
		session.my_player.play()

	def _NH_SIPSessionDidFail(self, notification):
		logging.info('Failed to connect')

	def _NH_SIPSessionWillEnd(self, notification):
		logging.info('Session will end')
		session = notification.sender

		session.my_player.stop()
		audio_stream = session.streams[0]
		audio_stream.bridge.remove(session.my_player)

	def _NH_SIPSessionDidEnd(self, notification):
		logging.info('Session ended')

	def _NH_SIPSessionDidProcessTransaction(self, notification):
		logging.info('Transaction processed - method: %s - code: %s -  reason: %s' % (notification.data.method, notification.data.code, notification.data.reason))
Example #24
0
            BlinkLogger().log_error(u"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']
Example #25
0
    def updateAccountFromCloud(self, key):
        def set_state(obj, state):
            for name, value in state.iteritems():
                attribute = getattr(obj.__class__, name, None)
                if isinstance(attribute, SettingsGroupMeta):
                    group = getattr(obj, name)
                    set_state(group, value)
                elif isinstance(attribute, Setting):
                    if issubclass(attribute.type, bool) and isinstance(value, bool):
                        value = str(value)
                    try:
                        attribute.__setstate__(obj, value)
                    except ValueError:
                        pass
                    else:
                        attribute.dirty[obj] = True

        json_data = self.cloud_storage.stringForKey_(key)
        am = AccountManager()
        if json_data:
            try:
                data = cjson.decode(json_data)
            except TypeError:
                # account has been deleted in the mean time
                try:
                    account = am.get_account(key)
                    if isinstance(account, Account):
                        # don't delete account because iCloud is unreliable
                        # account.delete()
                        pass
                except KeyError:
                    pass

            try:
                account = am.get_account(key)
            except KeyError:
                account = Account(key)
            set_state(account, data)
            account.save()

            # update keychain passwords
            if isinstance(account, Account):
                passwords = {'auth': {'label': '%s (%s)'      % (NSApp.delegate().applicationName, account.id), 'value': account.auth.password},
                             'web':  {'label': '%s WEB (%s)'  % (NSApp.delegate().applicationName, account.id), 'value': account.server.web_password},
                             'ldap': {'label': '%s LDAP (%s)' % (NSApp.delegate().applicationName, account.id), 'value': account.ldap.password},
                             'chat': {'label': '%s ChatReplication (%s)' % (NSApp.delegate().applicationName, account.id), 'value': account.chat.replication_password}
                            }
                for p in passwords.keys():
                    label = passwords[p]['label']
                    value = passwords[p]['value']
                    k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                    if k is None and value:
                        EMGenericKeychainItem.addGenericKeychainItemForService_withUsername_password_(label, account.id, value)
                    elif k is not None:
                        if value:
                            k.setPassword_(value)
                        else:
                            k.removeFromKeychain()
        else:
            try:
                account = am.get_account(key)
                if isinstance(account, Account):
                    pass
                    # don't delete account because iCloud is unreliable
                    # account.delete()
            except KeyError:
                pass

        self.notification_center.post_notification("SIPAccountChangedByICloud", sender=self, data=NotificationData(account=key))
Example #26
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):
        display_name = unicode(self.newDisplayNameText.stringValue())
        username = unicode(self.newUsernameText.stringValue())
        password = unicode(self.newPasswordText.stringValue())
        email = unicode(self.newEmailText.stringValue())

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

        url = SIPSimpleSettings().server.enrollment_url

        tzname = datetime.datetime.now(tzlocal()).tzname() or ""
        if not tzname:
            BlinkLogger().log_warning(u"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(
            u"Requesting creation of a new SIP account at %s" % url)

        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        raw_response = urllib2.urlopen(req)
        json_data = raw_response.read()

        try:
            response = cjson.decode(json_data.replace('\\/', '/'))
        except TypeError:
            error_message = 'Cannot decode json data from enrollment server'

        if response:
            if not response["success"]:
                BlinkLogger().log_info(
                    u"Enrollment Server failed to create SIP account: %(error_message)s"
                    % response)
                error_message = response["error_message"]
            else:
                BlinkLogger().log_info(
                    u"Enrollment Server successfully created SIP account %(sip_address)s"
                    % response)
                data = defaultdict(lambda: None, response)
                tls_path = None if data['passport'] is None else SIPManager(
                ).save_certificates(data)

                try:
                    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

                except KeyError:
                    sip_address = None
        else:
            sip_address = None
            error_message = "No response received from %s" % url

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

        if not sip_address:
            NSRunAlertPanel("Sign Up to SIP Account",
                            "Error creating account: %s" % error_message, "OK",
                            None, None)
            return False

        try:
            account = Account(str(sip_address))
        except ValueError, e:
            NSRunAlertPanel("Sign Up to SIP Account",
                            "Cannot add SIP Account: %s" % str(e), "OK", None,
                            None)
            return False
                    except KeyError:
                        sip_address = 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, 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
Example #29
0
     print "Failed to read json data from ~/.blink_account: %s" % e
     return
 except cjson.DecodeError, e:
     print "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'] or None
     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.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'])
Example #30
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)
            )
    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
Example #32
0
    def _update_account_from_cloud(self, key):
        account_manager = AccountManager()
        json_data = self.cloud_storage.stringForKey_(key)

        if json_data:
            try:
                data = json.loads(json_data)
            except (TypeError, json.decoder.JSONDecodeError):
                # account has been deleted in the mean time. don't delete account locally because iCloud is unreliable.
                data = {}

            try:
                account = account_manager.get_account(key)
            except KeyError:
                account = Account(key)
            self._set_state(account, data)
            account.save()

            # update keychain passwords
            if isinstance(account, Account):
                application_name = NSApp.delegate().applicationName
                passwords = {
                    'auth': {
                        'label': '{} ({})'.format(application_name,
                                                  account.id),
                        'value': account.auth.password
                    },
                    'web': {
                        'label': '{} WEB ({})'.format(application_name,
                                                      account.id),
                        'value': account.server.web_password
                    },
                    'ldap': {
                        'label':
                        '{} LDAP ({})'.format(application_name, account.id),
                        'value':
                        account.ldap.password
                    },
                    'chat': {
                        'label':
                        '{} ChatReplication ({})'.format(
                            application_name, account.id),
                        'value':
                        account.chat.replication_password
                    }
                }
                for p in list(passwords.keys()):
                    label = passwords[p]['label']
                    value = passwords[p]['value']
                    k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(
                        label, account.id)
                    if k is None and value:
                        EMGenericKeychainItem.addGenericKeychainItemForService_withUsername_password_(
                            label, account.id, value)
                    elif k is not None:
                        if value:
                            k.setPassword_(value)
                        else:
                            k.removeFromKeychain()

        self.notification_center.post_notification(
            "SIPAccountChangedByICloud",
            sender=self,
            data=NotificationData(account=key))