コード例 #1
0
ファイル: __init__.py プロジェクト: bitsworking/blink-cocoa
 def get_modified(self, obj):
     with self.lock:
         try:
             if self.dirty.get(obj, False):
                 pool = NSAutoreleasePool.alloc().init()
                 old_password = self.oldvalues.get(obj, self.default)
                 new_password = self.values.get(obj, self.default)
                 account = (account for account, group in chain(*(attr.values.iteritems() for attr in Account.__dict__.itervalues() if isinstance(attr, SettingsGroupMeta))) if group is obj).next()
                 if self.label is None:
                     label = '%s (%s)' % (NSApp.delegate().applicationName, account.id)
                 else:
                     label = '%s %s (%s)' % (NSApp.delegate().applicationName, self.label, account.id)
                 k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                 if k is None and new_password:
                     EMGenericKeychainItem.addGenericKeychainItemForService_withUsername_password_(label, account.id, new_password)
                 elif k is not None:
                     if new_password:
                         k.setPassword_(new_password)
                     else:
                         k.removeFromKeychain()
                 return ModifiedValue(old=old_password, new=new_password)
             else:
                 return None
         finally:
             try:
                 self.oldvalues[obj] = self.values[obj]
             except KeyError:
                 self.oldvalues.pop(obj, None)
             self.dirty[obj] = False
コード例 #2
0
    def openMessageWindow(self, target, target_name, account, create_if_needed=True, note_new_message=True):
        for window in self.windows:
            for viewer in window.viewers:
                if viewer.matchesTargetAccount(target, account):
                    break
            else:
                continue
            break
        else:
            window, viewer = None, None

        if not viewer and create_if_needed:
            viewer = SMSViewController.alloc().initWithAccount_target_name_(account, target, target_name)
            if not self.windows:
                window = SMSWindowController.alloc().initWithOwner_(self)
                self.windows.append(window)
            else:
                window = self.windows[0]
            viewer.windowController = window
            window.addViewer_(viewer)
        elif viewer:
            window = self.windowForViewer(viewer)

        if window:
            if note_new_message:
                window.window().makeKeyAndOrderFront_(None)
                NSApp.delegate().noteNewMessage(window)

        return viewer
コード例 #3
0
    def retryTransfer_(self, sender):
        if self.oldTransferInfo:
            try:
                account = next(
                    (account for account in AccountManager().iter_accounts()
                     if account.id == self.oldTransferInfo.local_uri))
            except StopIteration:
                account = AccountManager().default_account
            target_uri = normalize_sip_uri_for_outgoing_session(
                self.oldTransferInfo.remote_uri,
                AccountManager().default_account)
            filenames = [
                unicodedata.normalize('NFC', self.oldTransferInfo.file_path)
            ]
            NSApp.delegate(
            ).contactsWindowController.sessionControllersManager.send_files_to_contact(
                account, target_uri, filenames)
        else:
            self.failed = False
            self.done = False

            self.updateProgressInfo()
            self.progressBar.setIndeterminate_(True)
            self.progressBar.startAnimation_(None)
            self.progressBar.setHidden_(True)

            self.updateChecksumProgressInfo(0)
            self.checksumProgressBar.setIndeterminate_(False)
            self.checksumProgressBar.startAnimation_(None)
            self.checksumProgressBar.setHidden_(False)

            self.sizeText.setTextColor_(NSColor.grayColor())
            self.relayoutForRetry()
            self.transfer.retry()
コード例 #4
0
    def end(self):
        if self.ended:
            return

        self.sessionController.log_debug(u"End %s" % self)

        self.ended = True

        NSApp.delegate().contactsWindowController.hideLocalVideoWindow()
        status = self.status
        if status in [STREAM_IDLE, STREAM_FAILED]:
            self.changeStatus(STREAM_IDLE)
        elif status == STREAM_PROPOSING:
            self.sessionController.cancelProposal(self.stream)
            self.changeStatus(STREAM_CANCELLING)
        else:
            self.sessionController.endStream(self)
            self.changeStatus(STREAM_IDLE)

        self.removeFromSession()
        self.videoWindowController.close()
        self.notification_center.discard_observer(self, sender=self.sessionController)

        dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5.0, self, "deallocTimer:", None, False)
        NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSEventTrackingRunLoopMode)
コード例 #5
0
    def init(self):
        if self:
            NSBundle.loadNibNamed_owner_("EnrollmentWindow", self)
            icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled")
            self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled)

            self.selectRadio_(self.radioMatrix)
            if not SIPManager().validateAddAccountAction():
                self.nextButton.setEnabled_(False)
                self.purchaseProLabel.setHidden_(False)

            if NSApp.delegate().contactsWindowController.first_run:
                NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount')

            if NSApp.delegate().applicationName == 'SIP2SIP':
                self.allowed_domains = ['sip2sip.info']
                self.syncWithiCloudCheckbox.setHidden_(True)
                self.syncWithiCloudCheckbox.setState_(NSOffState)
                self.domainButton.setHidden_(True)
                self.addressText.cell().setPlaceholderString_('*****@*****.**')

            if NSApp.delegate().applicationName == 'Blink':
                self.syncWithiCloudCheckbox.setHidden_(True)

        return self
コード例 #6
0
 def get_state(account, obj=None, skip=[]):
     state = {}
     if obj is None:
         obj = account
     for name in dir(obj.__class__):
         attribute = getattr(obj.__class__, name, None)
         if name in skip:
             continue
         if isinstance(attribute, SettingsGroupMeta):
             state[name] = get_state(account, getattr(obj, name), skip)
         elif isinstance(attribute, Setting):
             value = attribute.__getstate__(obj)
             if value is DefaultValue:
                 value = attribute.default
             if name == 'password':
                 if isinstance(obj, AuthSettings):
                     label = '%s (%s)' % (NSApp.delegate().applicationName, account.id)
                     keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                     value = unicode(keychain_item.password()) if keychain_item is not None else ''
                 elif isinstance(obj, LDAPSettingsExtension):
                     label = '%s LDAP (%s)' % (NSApp.delegate().applicationName, account.id)
                     keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                     value = unicode(keychain_item.password()) if keychain_item is not None else ''
             if name == 'web_password':
                 label = '%s WEB (%s)' % (NSApp.delegate().applicationName, account.id)
                 keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                 value = unicode(keychain_item.password()) if keychain_item is not None else ''
             if name == 'replication_password':
                 label = '%s ChatReplication (%s)' % (NSApp.delegate().applicationName, account.id)
                 keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                 value = unicode(keychain_item.password()) if keychain_item is not None else ''
             state[name] = value
     return state
コード例 #7
0
    def openMessageWindow(self,
                          target,
                          target_name,
                          account,
                          create_if_needed=True,
                          note_new_message=True):
        for window in self.windows:
            for viewer in window.viewers:
                if viewer.matchesTargetAccount(target, account):
                    break
            else:
                continue
            break
        else:
            window, viewer = None, None

        if not viewer and create_if_needed:
            viewer = SMSViewController.alloc().initWithAccount_target_name_(
                account, target, target_name)
            if not self.windows:
                window = SMSWindowController.alloc().initWithOwner_(self)
                self.windows.append(window)
            else:
                window = self.windows[0]
            viewer.windowController = window
            window.addViewer_(viewer)
        elif viewer:
            window = self.windowForViewer(viewer)

        if window:
            if note_new_message:
                window.window().makeKeyAndOrderFront_(None)
                NSApp.delegate().noteNewMessage(window)

        return viewer
コード例 #8
0
    def init(self):
        if self:
            NSBundle.loadNibNamed_owner_("EnrollmentWindow", self)
            icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled")
            self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled)

            self.selectRadio_(self.radioMatrix)
            if not SIPManager().validateAddAccountAction():
                self.nextButton.setEnabled_(False)
                self.purchaseProLabel.setHidden_(False)

            if NSApp.delegate().contactsWindowController.first_run:
                NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount')

            if NSApp.delegate().allowed_domains:
                self.allowed_domains = NSApp.delegate().allowed_domains
                self.syncWithiCloudCheckbox.setHidden_(True)
                self.syncWithiCloudCheckbox.setState_(NSOffState)
                self.domainButton.setHidden_(True)
                self.addressText.cell().setPlaceholderString_('user@' + self.allowed_domains[0])

            if not NSApp.delegate().icloud_enabled:
                self.syncWithiCloudCheckbox.setHidden_(True)

        return self
コード例 #9
0
 def matchesTargetAccount(self, target, account):
     that_contact = NSApp.delegate(
     ).contactsWindowController.getFirstContactMatchingURI(target)
     this_contact = NSApp.delegate(
     ).contactsWindowController.getFirstContactMatchingURI(self.target_uri)
     return (self.target_uri == target or
             (this_contact and that_contact
              and this_contact == that_contact)) and self.account == account
コード例 #10
0
ファイル: AlertPanel.py プロジェクト: bitsworking/blink-cocoa
 def muteBeforeSpeechWillStart(self):
     hasAudio = any(sess.hasStreamOfType("audio") for sess in self.sessionControllersManager.sessionControllers)
     if hasAudio:
         if not SIPManager().is_muted():
             NSApp.delegate().contactsWindowController.muteClicked_(None)
             self.muted_by_synthesizer = True
     if self.speech_recognizer:
         self.speech_recognizer.stopListening()
コード例 #11
0
ファイル: util.py プロジェクト: ronaldoussoren/blink-cocoa
def call_in_gui_thread(func, *args, **kwargs):
    if NSThread.isMainThread():
        func(*args, **kwargs)
    else:
        pool = NSAutoreleasePool.alloc().init()
        NSApp.delegate().performSelectorOnMainThread_withObject_waitUntilDone_(
            "callObject:", lambda: func(*args, **kwargs), False)
        del pool
コード例 #12
0
    def addContactPanelClicked_(self, sender):
        if sender.tag() == 1:
            NSApp.delegate().contactsWindowController.addContact(self.target_uri)

        self.addContactView.removeFromSuperview()
        frame = self.chatViewController.outputView.frame()
        frame.origin.y = 0
        frame.size = self.outputContainer.frame().size
        self.chatViewController.outputView.setFrame_(frame)
コード例 #13
0
    def addContactPanelClicked_(self, sender):
        if sender.tag() == 1:
            NSApp.delegate().contactsWindowController.addContact(
                uris=[(self.target_uri, 'sip')])

        self.addContactView.removeFromSuperview()
        frame = self.chatViewController.outputView.frame()
        frame.origin.y = 0
        frame.size = self.outputContainer.frame().size
        self.chatViewController.outputView.setFrame_(frame)
コード例 #14
0
 def _NH_BlinkSessionDidStart(self, sender, data):
     if self.status != STREAM_CONNECTED:
         if self.videoWindowController:
             if not self.media_received:
                 self.videoWindowController.showStatusLabel(
                     NSLocalizedString("Waiting for Media...", "Label"))
         audio_stream = self.sessionController.streamHandlerOfType("audio")
         if audio_stream and audio_stream.status in (
                 STREAM_CONNECTING, STREAM_CONNECTED
         ) and self.sessionController.video_consumer == 'audio':
             NSApp.delegate().contactsWindowController.showAudioDrawer()
コード例 #15
0
    def _NH_SIPApplicationWillStart(self, sender, data):
        settings = SIPSimpleSettings()
        _version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))
        settings.user_agent = "%s %s (MacOSX)" % (NSApp.delegate().applicationName, _version)
        BlinkLogger().log_debug("SIP User Agent: %s" % settings.user_agent)
        settings.save()

        self.migratePasswordsToKeychain()
        self.cleanupIcons()

        # Set audio settings compatible with AEC and Noise Suppression
        settings.audio.sample_rate = 32000 if settings.audio.echo_canceller.enabled else 48000
        if NSApp.delegate().service_provider_help_url and settings.service_provider.help_url != NSApp.delegate().service_provider_help_url:
            settings.service_provider.help_url = NSApp.delegate().service_provider_help_url
            settings.save()

        if NSApp.delegate().service_provider_name and settings.service_provider.name != NSApp.delegate().service_provider_name:
            settings.service_provider.name = NSApp.delegate().service_provider_name
            settings.save()

        BlinkLogger().log_debug("Audio engine sampling rate %dKHz covering 0-%dKHz spectrum" % (settings.audio.sample_rate/1000, settings.audio.sample_rate/1000/2))
        BlinkLogger().log_debug("Acoustic Echo Canceller is %s" % ('enabled' if settings.audio.echo_canceller.enabled else 'disabled'))

        account_manager = AccountManager()
        for account in account_manager.iter_accounts():
            must_save = False
            if account is not BonjourAccount() and account.sip.primary_proxy is None and account.sip.outbound_proxy and not account.sip.selected_proxy:
                account.sip.primary_proxy = account.sip.outbound_proxy

            if account is not BonjourAccount() and settings.tls.verify_server != account.tls.verify_server:
                account.tls.verify_server = settings.tls.verify_server

            if account.tls.certificate and os.path.basename(account.tls.certificate.normalized) != 'default.crt':
                account.tls.certificate = DefaultValue

            if account.rtp.encryption_type == '':
                account.rtp.encryption.enabled = False
            elif account.rtp.encryption_type == 'opportunistic':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'opportunistic'
            elif account.rtp.encryption_type == 'sdes_optional':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'sdes_optional'
            elif account.rtp.encryption_type == 'sdes_mandatory':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'sdes_mandatory'
            elif account.rtp.encryption_type == 'zrtp':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'zrtp'
            account.save()

        logger = FileLogger()
        logger.start()
        self.ip_address_monitor.start()
コード例 #16
0
    def doubleClick_(self, sender):
        row = self.contactTable.selectedRow()

        if row < 2:
            return

        try:
            contact = self.contacts[row]
        except IndexError:
            return

        NSApp.delegate().contactsWindowController.startSessionWithTarget(contact.uri)
コード例 #17
0
def openFileTransferSelectionDialog(account, dest_uri):
    if not NSApp.delegate().contactsWindowController.sessionControllersManager.isMediaTypeSupported("file-transfer"):
        return

    panel = NSOpenPanel.openPanel()
    panel.setTitle_(u"Send File")
    panel.setAllowsMultipleSelection_(True)
    if panel.runModal() != NSOKButton:
        return
    filenames = [unicodedata.normalize("NFC", file) for file in panel.filenames()]
    NSApp.delegate().contactsWindowController.sessionControllersManager.send_files_to_contact(
        account, dest_uri, filenames
    )
コード例 #18
0
ファイル: mschtml.py プロジェクト: ygini/munki
def build_update_status_page():
    '''returns our update status page'''
    page_name = u'updates.html'
    item_list = []
    other_updates = []

    status_title_default = NSLocalizedString(u"Checking for updates...",
                                             u"Checking For Updates message")
    page = {}
    page['update_rows'] = u''
    page['hide_progress_spinner'] = u''
    page['hide_problem_updates'] = u'hidden'
    page['hide_other_updates'] = u'hidden'
    page['other_updates_header_message'] = u''
    page['other_update_rows'] = u''

    # don't like this bit as it ties us to a different object
    status_controller = NSApp.delegate().statusController
    status_results_template = get_template('status_results_template.html')
    alert = {}
    alert['primary_status_text'] = (status_controller._status_message
                                    or NSLocalizedString(
                                        u"Update in progress.",
                                        u"Update In Progress primary text"))
    alert['secondary_status_text'] = (status_controller._status_detail
                                      or '&nbsp;')
    alert['hide_progress_bar'] = u''
    if status_controller._status_percent < 0:
        alert['progress_bar_attributes'] = u'class="indeterminate"'
    else:
        alert['progress_bar_attributes'] = (u'style="width: %s%%"' %
                                            status_controller._status_percent)
    page['update_rows'] = status_results_template.safe_substitute(alert)

    install_all_button_classes = []
    if status_controller._status_stopBtnHidden:
        install_all_button_classes.append(u'hidden')
    if status_controller._status_stopBtnDisabled:
        install_all_button_classes.append(u'disabled')
    page['install_all_button_classes'] = u' '.join(install_all_button_classes)

    # don't like this bit as it ties us yet another object
    page['update_count'] = NSApp.delegate(
    ).mainWindowController._status_title or status_title_default
    page['install_btn_label'] = NSLocalizedString(
        u"Cancel", u"Cancel button title/short action text")
    page['warning_text'] = u''

    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name, 'updates_template.html', page, footer=footer)
コード例 #19
0
ファイル: Otto.py プロジェクト: mcanthony/otto
 def tick_(self, notification):
     global server_process
     #print 'watchdog tick'
     if server_process and server_process.poll():
         print 'server exited.'
         shutItDown()
     elif not self.server_ready:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         result = sock.connect_ex(('127.0.0.1',8778))
         sock.close()
         if result == 0:
             self.server_ready = True
             # perhaps we should schedule a message to be sent here
             NSApp.delegate().serverReady()
コード例 #20
0
 def renderMessage(self, message):
     if message.direction == 'outgoing':
         icon = NSApp.delegate().contactsWindowController.iconPathForSelf()
     else:
         sender_uri = sipuri_components_from_string(message.cpim_from)[0]
         # TODO: How to render the icons from Address Book? Especially in sandbox mode we do not have access to other folders
         icon = NSApp.delegate().contactsWindowController.iconPathForURI(sender_uri)
     try:
         timestamp=ISOTimestamp(message.cpim_timestamp)
     except Exception:
         pass
     else:
         is_html = False if message.content_type == 'text' else True
         private = True if message.private == "1" else False
         self.chatViewController.showMessage(message.sip_callid, message.msgid, message.direction, message.cpim_from, icon, message.body, timestamp, is_private=private, recipient=message.cpim_to, state=message.status, is_html=is_html, history_entry=True, media_type=message.media_type, encryption=message.encryption if message.media_type == 'chat' else None)
コード例 #21
0
 def renderMessage(self, message):
     if message.direction == 'outgoing':
         icon = NSApp.delegate().contactsWindowController.iconPathForSelf()
     else:
         sender_uri = sipuri_components_from_string(message.cpim_from)[0]
         # TODO: How to render the icons from Address Book? Especially in sandbox mode we do not have access to other folders
         icon = NSApp.delegate().contactsWindowController.iconPathForURI(sender_uri)
     try:
         timestamp=ISOTimestamp(message.cpim_timestamp)
     except Exception:
         pass
     else:
         is_html = False if message.content_type == 'text' else True
         private = True if message.private == "1" else False
         self.chatViewController.showMessage(message.sip_callid, message.msgid, message.direction, message.cpim_from, icon, message.body, timestamp, is_private=private, recipient=message.cpim_to, state=message.status, is_html=is_html, history_entry=True, media_type=message.media_type, encryption=message.encryption if message.media_type == 'chat' else None)
コード例 #22
0
def openFileTransferSelectionDialog(account, dest_uri, filename=None):
    if not NSApp.delegate().contactsWindowController.sessionControllersManager.isMediaTypeSupported('file-transfer'):
        return

    panel = NSOpenPanel.openPanel()
    panel.setTitle_(NSLocalizedString("Select Files or Folders and Click Open to Send", "Window title"))
    panel.setDirectoryURL_(NSURL.URLWithString_(filename))

    panel.setAllowsMultipleSelection_(True)
    panel.setCanChooseDirectories_(True)

    if panel.runModal() != NSOKButton:
        return
    filenames = [unicodedata.normalize('NFC', file) for file in panel.filenames()]
    NSApp.delegate().contactsWindowController.sessionControllersManager.send_files_to_contact(account, dest_uri, filenames)
コード例 #23
0
    def windowDidExitFullScreen_(self, notification):
        self.sessionController.log_debug('windowDidExitFullScreen %s' % self)

        self.full_screen_in_progress = False
        self.full_screen = False
        NSApp.delegate().contactsWindowController.hideLocalVideoWindow()
        NotificationCenter().post_notification("BlinkVideoWindowFullScreenChanged", sender=self)

        if self.show_window_after_full_screen_ends is not None:
            self.show_window_after_full_screen_ends.makeKeyAndOrderFront_(None)
            self.show_window_after_full_screen_ends = None
        else:
            if self.window:
                self.window.orderFront_(self)
                self.window.setLevel_(NSFloatingWindowLevel if self.always_on_top else NSNormalWindowLevel)
コード例 #24
0
    def menuWillOpen_(self, menu):
        if menu == self.contactMenu:
            self.contactMenu.itemWithTag_(2).setEnabled_(False)
            self.contactMenu.itemWithTag_(3).setEnabled_(False)
            self.contactMenu.itemWithTag_(4).setEnabled_(False)
            try:
                row = self.contactTable.selectedRow()
            except:
                return

            if row < 2:
                return

            try:
                contact = self.contacts[row]
            except IndexError:
                return

            contact_exists = bool(contact.presence_contact is not None)
            if '@' in contact.uri:
                self.contactMenu.itemWithTag_(2).setEnabled_(not is_anonymous(contact.uri))
                self.contactMenu.itemWithTag_(3).setEnabled_(not contact_exists and not is_anonymous(contact.uri))
                self.contactMenu.itemWithTag_(4).setEnabled_(contact_exists)
            else:
                bonjour_contact = NSApp.delegate().contactsWindowController.model.getBonjourContactMatchingDeviceId(contact.uri)
                self.contactMenu.itemWithTag_(2).setEnabled_(bool(bonjour_contact))
                self.contactMenu.itemWithTag_(3).setEnabled_(False)
                self.contactMenu.itemWithTag_(4).setEnabled_(False)
コード例 #25
0
    def renderDailyEntries(self, results):
        getFirstContactMatchingURI = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI
        self.dayly_entries = NSMutableArray.array()
        for result in results:
            display_name = None
            try:
                found_contact = self.contact_cache[result[2]]
            except KeyError:
                found_contact = getFirstContactMatchingURI(result[2], exact_match=True)
                self.contact_cache[result[2]] = found_contact

            if found_contact:
                display_name = found_contact.name
                remote_uri = '%s <%s>' % (display_name, result[2]) if '@' in result[2] else display_name
            else:
                try:
                    display_name = self.display_name_cache[result[2]]
                except KeyError:
                    remote_uri = result[2]
                else:
                    remote_uri = '%s <%s>' % (display_name, result[2]) if '@' in result[2] else display_name

            entry = NSMutableDictionary.dictionaryWithObjectsAndKeys_(result[1], "local_uri", remote_uri, "remote_uri", result[2], "remote_uri_sql", result[0], 'date', result[3], 'type', display_name, "display_name")
            self.dayly_entries.addObject_(entry)

        self.dayly_entries.sortUsingDescriptors_(self.indexTable.sortDescriptors())
        self.indexTable.reloadData()

        if self.search_uris and not self.dayly_entries:
            self.contactTable.deselectAll_(True)
コード例 #26
0
    def tableView_acceptDrop_row_dropOperation_(self, table, info, row, oper):
        pboard = info.draggingPasteboard()
        if pboard.availableTypeFromArray_(["x-blink-sip-uri"]):
            group, blink_contact = eval(pboard.stringForType_("dragged-contact"))
            if blink_contact is not None:
                sourceGroup = NSApp.delegate().contactsWindowController.model.groupsList[group]
                sourceContact = sourceGroup.contacts[blink_contact]

                if len(sourceContact.uris) > 1:
                    point = table.window().convertScreenToBase_(NSEvent.mouseLocation())
                    event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
                                                                                                                                              NSLeftMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(), table.window().windowNumber(),
                                                                                                                                              table.window().graphicsContext(), 0, 1, 0)
                    invite_menu = NSMenu.alloc().init()
                    titem = invite_menu.addItemWithTitle_action_keyEquivalent_(u'Invite To Conference', "", "")
                    titem.setEnabled_(False)
                    for uri in sourceContact.uris:
                        titem = invite_menu.addItemWithTitle_action_keyEquivalent_('%s (%s)' % (uri.uri, uri.type), "addContactUriToInvitationList:", "")
                        titem.setIndentationLevel_(1)
                        titem.setTarget_(self)
                        titem.setRepresentedObject_(uri.uri)

                    NSMenu.popUpContextMenu_withEvent_forView_(invite_menu, event, table)
                    return True
                else:
                    participant = info.draggingPasteboard().stringForType_("x-blink-sip-uri")
                    self.addContactUriToInvitationList(participant)
                    return True
        return False
コード例 #27
0
    def run(self):
        contactsWindow = NSApp.delegate().contactsWindowController.window()
        worksWhenModal = contactsWindow.worksWhenModal()
        contactsWindow.setWorksWhenModal_(True)
        if not self.autostart:
            self.window.makeKeyAndOrderFront_(None)
            rc = NSApp.runModalForWindow_(self.window)
        self.window.orderOut_(self)
        contactsWindow.setWorksWhenModal_(worksWhenModal)

        if (self.autostart and self.validateConference()) or rc == NSOKButton:
            if self.audio.state() == NSOnState and self.chat.state() == NSOnState:
                media_type = ("chat", "audio")
            elif self.chat.state() == NSOnState:
                media_type = "chat"
            else:
                media_type = "audio"

            # make a copy of the participants and reset the table data source,
            participants = self._participants

            # Cocoa crashes if something is selected in the table view when clicking OK or Cancel button
            # reseting the data source works around this
            self._participants = []
            self.participantsTable.reloadData()
            # prevent loops
            if self.target in participants:
                participants.remove(self.target)
            return ServerConferenceRoom(self.target, media_type=media_type, participants=participants, nickname=self.nickname, start_when_participants_available=bool(self.startWhenParticipantsAvailable.state()))
        else:
            return None
コード例 #28
0
    def migratePasswordsToKeychain(self):
        if not NSApp.delegate().migrate_passwords_to_keychain:
            return

        account_manager = AccountManager()
        configuration_manager = ConfigurationManager()
        bonjour_account = BonjourAccount()
        for account in (account for account in account_manager.iter_accounts() if account is not bonjour_account):
            try:
                stored_auth_password = configuration_manager.get(account.__key__ + ['auth', 'password'])
            except ObjectNotFoundError:
                stored_auth_password = None
            try:
                stored_ldap_password = configuration_manager.get(account.__key__ + ['ldap', 'password'])
            except ObjectNotFoundError:
                stored_ldap_password = None
            try:
                stored_web_password = configuration_manager.get(account.__key__ + ['server', 'web_password'])
            except ObjectNotFoundError:
                stored_web_password = None
            if (stored_auth_password, stored_ldap_password, stored_web_password) != ('keychain', 'keychain', 'keychain'):
                Account.auth.password.dirty[account.auth] = True
                Account.ldap.password.dirty[account.ldap] = True
                Account.server.web_password.dirty[account.server] = True
                account.save()
コード例 #29
0
ファイル: SIPManager.py プロジェクト: uditha-atukorala/blink
    def migratePasswordsToKeychain(self):
        if NSApp.delegate().applicationName == 'SIP2SIP':
            return

        account_manager = AccountManager()
        configuration_manager = ConfigurationManager()
        bonjour_account = BonjourAccount()
        for account in (account for account in account_manager.iter_accounts() if account is not bonjour_account):
            try:
                stored_auth_password = configuration_manager.get(account.__key__ + ['auth', 'password'])
            except ObjectNotFoundError:
                stored_auth_password = None
            try:
                stored_ldap_password = configuration_manager.get(account.__key__ + ['ldap', 'password'])
            except ObjectNotFoundError:
                stored_ldap_password = None
            try:
                stored_web_password = configuration_manager.get(account.__key__ + ['server', 'web_password'])
            except ObjectNotFoundError:
                stored_web_password = None
            if (stored_auth_password, stored_ldap_password, stored_web_password) != ('keychain', 'keychain', 'keychain'):
                Account.auth.password.dirty[account.auth] = True
                Account.ldap.password.dirty[account.ldap] = True
                Account.server.web_password.dirty[account.server] = True
                account.save()
コード例 #30
0
    def tabView_didSelectTabViewItem_(self, tabView, item):
        if item.identifier() == "recent":
            self.captureView.hide()
            self.cameraLabel.setHidden_(True)
            self.useButton.setEnabled_(True)
        else:
            if NSApp.delegate(
            ).contactsWindowController.sessionControllersManager.isMediaTypeSupported(
                    'video'):
                self.captureView.show()
                self.cameraLabel.setHidden_(False)
                self.photoView.setHidden_(True)
                self.captureView.setHidden_(False)
                self.previewButton.setHidden_(True)
                #self.countdownCheckbox.setHidden_(False)
                self.mirrorButton.setHidden_(False)
                self.captureButton.setHidden_(False)
                if self.captureView.captureSession and self.captureView.captureSession.isRunning(
                ):
                    self.captureButton.setEnabled_(True)
                else:
                    self.captureButton.setEnabled_(False)

                self.useButton.setEnabled_(False)
            else:
                self.previewButton.setEnabled_(False)
コード例 #31
0
    def run(self):
        contactsWindow = NSApp.delegate().contactsWindowController.window()
        worksWhenModal = contactsWindow.worksWhenModal()
        contactsWindow.setWorksWhenModal_(True)
        if not self.autostart:
            self.window.makeKeyAndOrderFront_(None)
            rc = NSApp.runModalForWindow_(self.window)
        self.window.orderOut_(self)
        contactsWindow.setWorksWhenModal_(worksWhenModal)

        if (self.autostart and self.validateConference()) or rc == NSOKButton:
            if self.audio.state() == NSOnState and self.chat.state() == NSOnState:
                media_type = ("chat", "audio")
            elif self.chat.state() == NSOnState:
                media_type = "chat"
            else:
                media_type = "audio"

            # make a copy of the participants and reset the table data source,
            participants = self._participants

            # Cocoa crashes if something is selected in the table view when clicking OK or Cancel button
            # reseting the data source works around this
            self._participants = []
            self.participantsTable.reloadData()
            # prevent loops
            if self.target in participants:
                participants.remove(self.target)
            return ServerConferenceRoom(self.target, media_type=media_type, participants=participants, nickname=self.nickname, start_when_participants_available=bool(self.startWhenParticipantsAvailable.state()))
        else:
            return None
コード例 #32
0
ファイル: Simple.py プロジェクト: ferguson/otto
def openAbout():
    global about
    global aboutpolicy
    if not about:
        about = NSWindow.alloc()
        rect = Foundation.NSMakeRect(0,0,300,370)
        styleMask = NSTitledWindowMask | NSClosableWindowMask | \
            NSResizableWindowMask | NSMiniaturizableWindowMask
        about.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
        about.setTitle_('About Otto')
        #about.setBackgroundColor_(NSColor.blueColor()) # not working (try it on the webview instead)

        webview = WebKit.WebView.alloc()
        webview.initWithFrame_(rect)
        webview.setFrameLoadDelegate_(NSApp.delegate())

        respath = os.environ['RESOURCEPATH']
        print 'respath =', respath
        pageurl = Foundation.NSURL.URLWithString_('file://'+respath+'/static/html/about.html')
        aboutreq = Foundation.NSURLRequest.requestWithURL_(pageurl)
        webview.mainFrame().loadRequest_(aboutreq)

        aboutpolicy = AboutPolicyDelegate.alloc().init()
        webview.setPolicyDelegate_(aboutpolicy)

        about.setReleasedWhenClosed_(False)
        about.setContentView_(webview)

    if not about.isVisible():
      about.center()
      #about.display()
    about.orderFrontRegardless()
    about.makeKeyAndOrderFront_(None)
コード例 #33
0
    def tableView_acceptDrop_row_dropOperation_(self, table, info, row, oper):
        pboard = info.draggingPasteboard()
        if pboard.availableTypeFromArray_(["x-blink-sip-uri"]):
            group, blink_contact = eval(pboard.stringForType_("dragged-contact"))
            if blink_contact is not None:
                sourceGroup = NSApp.delegate().contactsWindowController.model.groupsList[group]
                sourceContact = sourceGroup.contacts[blink_contact]

                if len(sourceContact.uris) > 1:
                    point = table.window().convertScreenToBase_(NSEvent.mouseLocation())
                    event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
                                                                                                                                              NSLeftMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(), table.window().windowNumber(),
                                                                                                                                              table.window().graphicsContext(), 0, 1, 0)
                    invite_menu = NSMenu.alloc().init()
                    titem = invite_menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Invite To Conference", "Menu item"), "", "")
                    titem.setEnabled_(False)
                    for uri in sourceContact.uris:
                        titem = invite_menu.addItemWithTitle_action_keyEquivalent_('%s (%s)' % (uri.uri, uri.type), "addContactUriToInvitationList:", "")
                        titem.setIndentationLevel_(1)
                        titem.setTarget_(self)
                        titem.setRepresentedObject_(uri.uri)

                    NSMenu.popUpContextMenu_withEvent_forView_(invite_menu, event, table)
                    return True
                else:
                    participant = info.draggingPasteboard().stringForType_("x-blink-sip-uri")
                    self.addContactUriToInvitationList(participant)
                    return True
        return False
コード例 #34
0
    def rightMouseDown_(self, event):
        point = self.window().convertScreenToBase_(NSEvent.mouseLocation())
        event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
            NSRightMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(),
            self.window().windowNumber(),
            self.window().graphicsContext(), 0, 1, 0)

        videoDevicesMenu = NSMenu.alloc().init()
        lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(
            NSLocalizedString("Select Video Camera", "Menu item"), "", "")
        lastItem.setEnabled_(False)
        videoDevicesMenu.addItem_(NSMenuItem.separatorItem())

        i = 0
        for item in NSApp.delegate().video_devices:
            if item not in (None, 'system_default'):
                i += 1

            lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(
                item, "changeVideoDevice:", "")
            lastItem.setRepresentedObject_(item)
            if SIPApplication.video_device.real_name == item:
                lastItem.setState_(NSOnState)

        if i > 1:
            videoDevicesMenu.addItem_(NSMenuItem.separatorItem())
            settings = SIPSimpleSettings()
            lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(
                NSLocalizedString("Auto Rotate Cameras", "Menu item"),
                "toggleAutoRotate:", "")
            lastItem.setState_(NSOnState if settings.video.
                               auto_rotate_cameras else NSOffState)

        NSMenu.popUpContextMenu_withEvent_forView_(videoDevicesMenu, event,
                                                   self.window().contentView())
コード例 #35
0
ファイル: Otto.py プロジェクト: mcanthony/otto
def openAbout():
    global about
    global linkpolicy
    if not about:
        about = NSWindow.alloc()
        rect = Foundation.NSMakeRect(0,0,300,370)
        styleMask = NSTitledWindowMask | NSClosableWindowMask | \
            NSResizableWindowMask | NSMiniaturizableWindowMask
        about.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
        about.setTitle_('About Otto')
        #about.setBackgroundColor_(NSColor.blueColor()) # not working (try it on the webview instead)

        webview = WebKit.WebView.alloc()
        webview.initWithFrame_(rect)
        webview.setFrameLoadDelegate_(NSApp.delegate())

        respath = os.environ['RESOURCEPATH']
        pageurl = Foundation.NSURL.URLWithString_('file://'+respath+'/static/html/about.html')
        aboutreq = Foundation.NSURLRequest.requestWithURL_(pageurl)
        webview.mainFrame().loadRequest_(aboutreq)

        if not linkpolicy:
            linkpolicy = LinkPolicyDelegate.alloc().init()
        webview.setPolicyDelegate_(linkpolicy)

        about.setReleasedWhenClosed_(False)
        about.setContentView_(webview)

    if not about.isVisible():
      about.center()
      #about.display()
    about.orderFrontRegardless()
    about.makeKeyAndOrderFront_(None)
コード例 #36
0
 def delegate(cls):
     if not NSThread.isMainThread():
         thread = threading.current_thread()
         pool = getattr(thread, 'ns_autorelease_pool', None)
         if pool is None:
             print("--- calling NSApp.delegate() without an autorelease pool from {}".format(thread))
             traceback.print_stack()
     return NSApp.delegate()
コード例 #37
0
ファイル: mschtml.py プロジェクト: munki/munki
def build_update_status_page():
    '''returns our update status page'''
    page_name = u'updates.html'
    item_list = []
    other_updates = []
    
    status_title_default = NSLocalizedString(u"Checking for updates...",
                                             u"Checking For Updates message")
    page = {}
    page['update_rows'] = u''
    page['hide_progress_spinner'] = u''
    page['hide_problem_updates'] = u'hidden'
    page['hide_other_updates'] = u'hidden'
    page['other_updates_header_message'] = u''
    page['other_update_rows'] = u''
    
    # don't like this bit as it ties us to a different object
    status_controller = NSApp.delegate().statusController
    status_results_template = get_template('status_results_template.html')
    alert = {}
    alert['primary_status_text'] = (
        status_controller._status_message
        or NSLocalizedString(u"Update in progress.", u"Update In Progress primary text"))
    alert['secondary_status_text'] = (status_controller._status_detail or '&nbsp;')
    alert['hide_progress_bar'] = u''
    if status_controller._status_percent < 0:
        alert['progress_bar_attributes'] = u'class="indeterminate"'
    else:
        alert['progress_bar_attributes'] = (u'style="width: %s%%"'
                                            % status_controller._status_percent)
    page['update_rows'] = status_results_template.safe_substitute(alert)
    
    install_all_button_classes = []
    if status_controller._status_stopBtnHidden:
        install_all_button_classes.append(u'hidden')
    if status_controller._status_stopBtnDisabled:
        install_all_button_classes.append(u'disabled')
    page['install_all_button_classes'] = u' '.join(install_all_button_classes)

    # don't like this bit as it ties us yet another object
    page['update_count'] = NSApp.delegate().mainWindowController._status_title or status_title_default
    page['install_btn_label'] = NSLocalizedString(u"Cancel", u"Cancel button title/short action text")
    page['warning_text'] = u''

    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name, 'updates_template.html', page, footer=footer)
コード例 #38
0
ファイル: __init__.py プロジェクト: bitsworking/blink-cocoa
 def __setstate__(self, obj, value):
     with self.lock:
         if value is None and not self.nillable:
             raise ValueError("setting attribute is not nillable")
         if value is not None:
             if value == u'keychain':
                 pool = NSAutoreleasePool.alloc().init()
                 account = (account for account, group in chain(*(attr.values.iteritems() for attr in Account.__dict__.itervalues() if isinstance(attr, SettingsGroupMeta))) if group is obj).next()
                 if self.label is None:
                     label = '%s (%s)' % (NSApp.delegate().applicationName, account.id)
                 else:
                     label = '%s %s (%s)' % (NSApp.delegate().applicationName, self.label, account.id)
                 k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                 value = unicode(k.password()) if k is not None else u''
             value = self.type(value)
         self.oldvalues[obj] = self.values[obj] = value
         self.dirty[obj] = False
コード例 #39
0
 def keyDown_(self, event):
     key = event.characters()
     if key == "\r":
         self.target().performSelector_withObject_(self.doubleAction(),
                                                   self)
     else:
         self.window().makeFirstResponder_(
             NSApp.delegate().contactsWindowController.searchBox)
コード例 #40
0
    def end(self):
        if self.ended:
            return

        self.sessionController.log_debug("End %s" % self)
        self.ended = True

        if self.sessionController.waitingForLocalVideo:
            self.stop_wait_for_camera_timer()
            self.sessionController.cancelBeforeDNSLookup()

        if self.sessionController.video_consumer == "audio":
            NSApp.delegate().contactsWindowController.detachVideo(
                self.sessionController)
        elif self.sessionController.video_consumer == "chat":
            NSApp.delegate().chatWindowController.detachVideo(
                self.sessionController)

        status = self.status
        if status in [STREAM_IDLE, STREAM_FAILED]:
            self.changeStatus(STREAM_IDLE)
        elif status == STREAM_PROPOSING:
            self.sessionController.cancelProposal(self)
            self.changeStatus(STREAM_CANCELLING)
        else:
            self.sessionController.endStream(self)
            self.changeStatus(STREAM_IDLE)

        self.removeFromSession()

        self.videoRecorder.stop()

        self.videoWindowController.close()

        self.notification_center.remove_observer(
            self,
            sender=self.sessionController,
            name='VideoRemovedByRemoteParty')

        dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
            5.0, self, "deallocTimer:", None, False)
        NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer,
                                                     NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            dealloc_timer, NSEventTrackingRunLoopMode)
コード例 #41
0
    def __init__(self):
        if NSApp.delegate().applicationName == 'Blink':
            NSUserDefaults.standardUserDefaults().setObject_forKey_("Disabled", "iCloudSyncEnabled")

        if NSApp.delegate().applicationName not in ('Blink Pro'):
            return

        major, minor = platform.mac_ver()[0].split('.')[0:2]
        if (int(major) == 10 and int(minor) >= 7) or int(major) > 10:
            self.notification_center = NotificationCenter()
            enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled")
            if enabled is None:
                NSUserDefaults.standardUserDefaults().setObject_forKey_("Enabled", "iCloudSyncEnabled")
                self.start()
            elif enabled == "Enabled" :
                self.start()

            NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "userDefaultsDidChange:", "NSUserDefaultsDidChangeNotification", NSUserDefaults.standardUserDefaults())
コード例 #42
0
    def add_to_history(self, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status):
        try:
            controller = (controller for controller in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers if controller.session == self.session).next()
        except StopIteration:
            history_id = str(uuid.uuid1())
        else:
            history_id = controller.history_id

        ChatHistory().add_message(history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, "html", "0", status)
コード例 #43
0
    def add_to_history(self, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status):
        try:
            controller = next((controller for controller in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers if controller.session == self.session))
        except StopIteration:
            history_id = str(uuid.uuid1())
        else:
            history_id = controller.history_id

        ChatHistory().add_message(history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, "html", "0", status)
コード例 #44
0
ファイル: SIPManager.py プロジェクト: AGProjects/blink-cocoa
    def _NH_SIPApplicationDidStart(self, sender, data):
        settings = SIPSimpleSettings()
        settings.audio.enable_aec = settings.audio.echo_canceller.enabled
        settings.audio.sound_card_delay = settings.audio.echo_canceller.tail_length
        self._app.engine.enable_colorbar_device = False

        BlinkLogger().log_debug("SDK loaded")
        BlinkLogger().log_debug("SIP device ID: %s" % settings.instance_id)
        available_codecs_print = list(beautify_audio_codec(codec.decode()) for codec in self._app.engine._ua.available_codecs)
        codecs_print = list(beautify_audio_codec(codec) for codec in settings.rtp.audio_codec_list)
        BlinkLogger().log_info("Available audio codecs: %s" % ", ".join(available_codecs_print))
        BlinkLogger().log_info("Enabled audio codecs: %s" % ", ".join(codecs_print))

        if settings.audio.input_device is None:
            BlinkLogger().log_info("Switching audio input device to system default")
            settings.audio.input_device = 'system_default'
        if settings.audio.output_device is None:
            BlinkLogger().log_info("Switching audio output device to system default")
            settings.audio.output_device = 'system_default'
        if settings.audio.alert_device is None:
            BlinkLogger().log_info("Switching audio alert device to system default")
            settings.audio.alert_device = 'system_default'

        try:
            from VideoController import VideoController
        except ImportError:
            pass
        else:
            if settings.video.max_bitrate is not None and settings.video.max_bitrate > 10000:
                settings.video.max_bitrate = 4.0

            available_video_codecs_print = list(beautify_video_codec(codec.decode()) for codec in self._app.engine._ua.available_video_codecs)
            video_codecs_print = list(beautify_video_codec(codec) for codec in settings.rtp.video_codec_list)
            BlinkLogger().log_info("Available video codecs: %s" % ", ".join(available_video_codecs_print))
            BlinkLogger().log_info("Enabled video codecs: %s" % ", ".join(video_codecs_print))
            BlinkLogger().log_info(u"Available video cameras: %s" % ", ".join(NSApp.delegate().video_devices))
            if settings.video.device != "system_default" and settings.video.device != self._app.video_device.real_name and self._app.video_device.real_name != None:
                settings.video.device = self._app.video_device.real_name
                BlinkLogger().log_info(u"Using video camera %s" % self._app.video_device.real_name)
            elif settings.video.device is None:
                devices = list(device for device in self._app.engine.video_devices if device not in ('system_default', None))
                if devices:
                    BlinkLogger().log_info("Switching video camera to %s" % devices[0])
                    settings.video.device = devices[0]
            else:
                BlinkLogger().log_info("Using video camera %s" % self._app.video_device.real_name)
        settings.save()

        bonjour_account = BonjourAccount()
        if bonjour_account.enabled:
            for transport in settings.sip.transport_list:
                try:
                    BlinkLogger().log_debug('Bonjour Account listens on %s' % bonjour_account.contact[transport])
                except KeyError:
                    pass

        self.init_configurations()
コード例 #45
0
ファイル: mschtml.py プロジェクト: poundbangbash/munki
def build_updates_page():
    '''available/pending updates'''
    page_name = u'updates.html'

    # need to consolidate/centralize this flag. Accessing it this way is ugly.
    if NSApp.delegate().mainWindowController._update_in_progress:
        return build_update_status_page()

    item_list = MunkiItems.getEffectiveUpdateList()

    other_updates = [
        item for item in MunkiItems.getOptionalInstallItems()
        if item['status'] == 'update-available'
    ]

    page = {}
    page['update_rows'] = u''
    page['hide_progress_spinner'] = u'hidden'
    page['hide_other_updates'] = u'hidden'
    page['install_all_button_classes'] = u''

    item_template = get_template('update_row_template.html')

    if item_list:
        for item in item_list:
            escapeAndQuoteCommonFields(item)
            page['update_rows'] += item_template.safe_substitute(item)
    elif not other_updates:
        status_results_template = get_template('status_results_template.html')
        alert = {}
        alert['primary_status_text'] = NSLocalizedString(
            u"Your software is up to date.",
            u"No Pending Updates primary text")
        alert['secondary_status_text'] = NSLocalizedString(
            u"There is no new software for your computer at this time.",
            u"No Pending Updates secondary text")
        alert['hide_progress_bar'] = u'hidden'
        alert['progress_bar_value'] = u''
        page['update_rows'] = status_results_template.safe_substitute(alert)

    count = len(item_list)
    page['update_count'] = msclib.updateCountMessage(count)
    page['install_btn_label'] = msclib.getInstallAllButtonTextForCount(count)
    page['warning_text'] = get_warning_text()

    page['other_updates_header_message'] = NSLocalizedString(
        u"Other available updates", u"Other Available Updates label")
    page['other_update_rows'] = u''

    if other_updates:
        page['hide_other_updates'] = u''
        for item in other_updates:
            escapeAndQuoteCommonFields(item)
            page['other_update_rows'] += item_template.safe_substitute(item)

    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name, 'updates_template.html', page, footer=footer)
コード例 #46
0
ファイル: mschtml.py プロジェクト: 50kaliber/munki
def build_updates_page():
    '''available/pending updates'''
    page_name = u'updates.html'
    
    # need to consolidate/centralize this flag. Accessing it this way is ugly.
    if NSApp.delegate().mainWindowController._update_in_progress:
        return build_update_status_page()

    item_list = MunkiItems.getEffectiveUpdateList()

    other_updates = [
        item for item in MunkiItems.getOptionalInstallItems()
        if item['status'] == 'update-available']

    page = {}
    page['update_rows'] = u''
    page['hide_progress_spinner'] = u'hidden'
    page['hide_other_updates'] = u'hidden'
    page['install_all_button_classes'] = u''
    
    item_template = get_template('update_row_template.html')

    if item_list:
        for item in item_list:
            escapeAndQuoteCommonFields(item)
            page['update_rows'] += item_template.safe_substitute(item)
    elif not other_updates:
        status_results_template = get_template('status_results_template.html')
        alert = {}
        alert['primary_status_text'] = NSLocalizedString(
             u"Your software is up to date.", u"No Pending Updates primary text")
        alert['secondary_status_text'] = NSLocalizedString(
             u"There is no new software for your computer at this time.",
             u"No Pending Updates secondary text")
        alert['hide_progress_bar'] = u'hidden'
        alert['progress_bar_value'] = u''
        page['update_rows'] = status_results_template.safe_substitute(alert)

    count = len(item_list)
    page['update_count'] = msclib.updateCountMessage(count)
    page['install_btn_label'] = msclib.getInstallAllButtonTextForCount(count)
    page['warning_text'] = get_warning_text()

    page['other_updates_header_message'] = NSLocalizedString(
        u"Other available updates",
        u"Other Available Updates label")
    page['other_update_rows'] = u''

    if other_updates:
        page['hide_other_updates'] = u''
        for item in other_updates:
            escapeAndQuoteCommonFields(item)
            page['other_update_rows'] += item_template.safe_substitute(item)
    
    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name, 'updates_template.html', page, footer=footer)
コード例 #47
0
    def _NH_SIPAccountGotMessageSummary(self, account, data):
        BlinkLogger().log_debug("Received voicemail notification for account %s" % account.id)
        summary = data.message_summary
        if summary.summaries.get('voice-message') is None:
            return
        voice_messages = summary.summaries['voice-message']
        new_messages = int(voice_messages['new_messages'])
        old_messages = int(voice_messages['old_messages'])
        MWIData.store(account, summary)
        if summary.messages_waiting and new_messages > 0:
            nc_title = NSLocalizedString("New Voicemail Message", "System notification title") if new_messages == 1 else NSLocalizedString("New Voicemail Messages", "System notification title")
            nc_subtitle = NSLocalizedString("On Voicemail Server", "System notification subtitle")
            if old_messages > 0:
                nc_body = NSLocalizedString("You have %d new and ", "System notification body") % new_messages + NSLocalizedString("%d old voicemail messages", "System notification body") % old_messages
            else:
                nc_body = NSLocalizedString("You have %d new voicemail messages", "System notification body") % new_messages
            NSApp.delegate().gui_notify(nc_title, nc_body, nc_subtitle)

        self.notification_center.post_notification('BlinkAccountGotMessageSummary', sender=account, data=data)
コード例 #48
0
    def windowDidEnterFullScreen_(self, notification):
        if self.window:
            if self.streamController.ended:
                self.window.orderOut_(self)
                return

        self.sessionController.log_debug('windowDidEnterFullScreen %s' % self)

        self.full_screen_in_progress = False
        self.full_screen = True
        self.stopMouseOutTimer()
        NSApp.delegate().contactsWindowController.showLocalVideoWindow()
        NotificationCenter().post_notification("BlinkVideoWindowFullScreenChanged", sender=self)

        if self.videoControlPanel:
            self.videoControlPanel.show()
            self.videoControlPanel.window().makeKeyAndOrderFront_(None)

        if self.window:
            self.window.setLevel_(NSNormalWindowLevel)
コード例 #49
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()
コード例 #50
0
    def sendMessage(self, content, content_type="text/plain"):
        # entry point for sending messages, they will be added to self.message_queue
        if content_type != "application/im-iscomposing+xml":
            icon = NSApp.delegate().contactsWindowController.iconPathForSelf()

            if not isinstance(content, OTRInternalMessage):
                timestamp = ISOTimestamp.now()
                hash = hashlib.sha1()
                content = content.decode() if isinstance(content,
                                                         bytes) else content
                hash.update((content + str(timestamp)).encode("utf-8"))
                id = hash.hexdigest()
                call_id = ''

                encryption = ''
                if self.encryption.active:
                    encryption = 'verified' if self.encryption.verified else 'unverified'

                self.chatViewController.showMessage(call_id,
                                                    id,
                                                    'outgoing',
                                                    None,
                                                    icon,
                                                    content,
                                                    timestamp,
                                                    state="sent",
                                                    media_type='sms',
                                                    encryption=encryption)

                recipient = ChatIdentity(self.target_uri, self.display_name)
                mInfo = MessageInfo(id,
                                    sender=self.account,
                                    recipient=recipient,
                                    timestamp=timestamp,
                                    content_type=content_type,
                                    content=content,
                                    status="queued",
                                    encryption=encryption)

                self.messages[id] = mInfo
                self.message_queue.put(mInfo)
            else:
                self.message_queue.put(content)

        # Async DNS lookup
        if host is None or host.default_ip is None:
            self.setRoutesFailed(
                NSLocalizedString("No Internet connection", "Label"))
            return

        if self.last_route is None:
            self.lookup_destination(self.target_uri)
        else:
            self.setRoutesResolved([self.last_route])
コード例 #51
0
 def toolbarButtonClicked_(self, sender):
     if sender.itemIdentifier() == 'smileys':
         chatViewController = self.selectedSessionController().chatViewController
         chatViewController.expandSmileys = not chatViewController.expandSmileys
         sender.setImage_(NSImage.imageNamed_("smiley_on" if chatViewController.expandSmileys else "smiley_off"))
         chatViewController.toggleSmileys(chatViewController.expandSmileys)
     elif sender.itemIdentifier() == 'history' and NSApp.delegate().applicationName != 'Blink Lite':
         contactWindow = self._owner._owner
         contactWindow.showHistoryViewer_(None)
         session = self.selectedSessionController()
         contactWindow.historyViewer.filterByURIs((format_identity_to_string(session.target_uri),))
コード例 #52
0
    def makeDragImage(self):
        if self.delegate is None:
            return

        image = NSImage.alloc().initWithSize_(self.frame().size)
        image.lockFocus()

        frame = self.frame()
        frame.origin = NSZeroPoint
        rect = NSInsetRect(frame, 1.5, 1.5)

        if self.conferencing and not self.draggedOut:
            NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set()
        else:
            NSColor.whiteColor().colorWithAlphaComponent_(0.7).set()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
        path.fill()

        if self.selected:
            path.setLineWidth_(3)
            NSColor.grayColor().set()
        else:
            path.setLineWidth_(1)
            NSColor.grayColor().set()
        path.stroke()

        NSColor.blackColor().set()
        point = NSMakePoint(8, NSMaxY(frame)-20)
        uri = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=False, format='compact')
        NSString.stringWithString_(uri).drawAtPoint_withAttributes_(point,
              NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(12), NSFontAttributeName))
        point = NSMakePoint(8, 6)
        if self.conferencing:
            NSString.stringWithString_(NSLocalizedString("Drop outside to remove from conference", "Audio session label")).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))
        else:
            audio_sessions = [sess.hasStreamOfType("audio") for sess in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers]
            if self.delegate.transferEnabled:
                text = NSLocalizedString("Drop this over a session or contact", "Audio session label") if len(audio_sessions) > 1 else NSLocalizedString("Drop this over a contact to transfer", "Audio session label")
            else:
                text = NSLocalizedString("Drop this over a session to conference", "Audio session label")
            NSString.stringWithString_(text).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))

        icon = NSImage.imageNamed_("NSEveryone")
        rect = frame
        s = icon.size()
        p = NSMakePoint(NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8)
        r = NSMakeRect(0, 0, s.width, s.height)
        icon.drawAtPoint_fromRect_operation_fraction_(p, r, NSCompositeSourceOver, 0.5)

        image.unlockFocus()
        return image
コード例 #53
0
    def performDragOperation_(self, info):
        if self.delegate is None:
            return

        source = info.draggingSource()
        pboard = info.draggingPasteboard()

        if pboard.types().containsObject_(NSFilenamesPboardType):
            filenames = [unicodedata.normalize('NFC', file) for file in pboard.propertyListForType_(NSFilenamesPboardType) if os.path.isfile(file)]
            if filenames:
                self.sessionControllersManager.send_files_to_contact(self.delegate.sessionController.account, self.delegate.sessionController.target_uri, filenames)
            return

        def unhighlight(view):
            view.highlighted = False
            view.setNeedsDisplay_(True)
        unhighlight(self)
        self.foreachConferenceSession(unhighlight)

        if hasattr(self.delegate, 'sessionBoxDidAddConferencePeer'):
            if pboard.availableTypeFromArray_(["x-blink-audio-session"]):
                info.draggingSource().draggedOut = False
                info.draggingSource().setNeedsDisplay_(True)
                return self.delegate.sessionBoxDidAddConferencePeer(self, source.delegate)

            elif pboard.availableTypeFromArray_(["dragged-contact"]):
                group, blink_contact = eval(pboard.stringForType_("dragged-contact"))
                if blink_contact is not None:
                    sourceGroup = NSApp.delegate().contactsWindowController.model.groupsList[group]
                    sourceContact = sourceGroup.contacts[blink_contact]

                    if len(sourceContact.uris) > 1:
                        point = self.window().convertScreenToBase_(NSEvent.mouseLocation())
                        event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
                                                                                                                                                  NSLeftMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(), self.window().windowNumber(),
                                                                                                                                                  self.window().graphicsContext(), 0, 1, 0)
                        invite_menu = NSMenu.alloc().init()
                        titem = invite_menu.addItemWithTitle_action_keyEquivalent_(u'Invite To Conference', "", "")
                        titem.setEnabled_(False)
                        for uri in sourceContact.uris:
                            titem = invite_menu.addItemWithTitle_action_keyEquivalent_('%s (%s)' % (uri.uri, uri.type), "userClickedInviteToConference:", "")
                            titem.setIndentationLevel_(1)
                            titem.setTarget_(self)
                            titem.setRepresentedObject_(str(uri.uri))

                        NSMenu.popUpContextMenu_withEvent_forView_(invite_menu, event, self)
                    elif pboard.availableTypeFromArray_(["x-blink-sip-uri"]):
                        uri = str(pboard.stringForType_("x-blink-sip-uri"))
                        return self.delegate.sessionBoxDidAddConferencePeer(self, uri)

            elif pboard.availableTypeFromArray_(["x-blink-sip-uri"]):
                uri = str(pboard.stringForType_("x-blink-sip-uri"))
                return self.delegate.sessionBoxDidAddConferencePeer(self, uri)
コード例 #54
0
    def doubleClick_(self, sender):
        row = self.contactTable.selectedRow()

        if row < 2:
            return

        try:
            contact = self.contacts[row]
        except IndexError:
            return

        if '@' in contact.uri:
            NSApp.delegate().contactsWindowController.startSessionWithTarget(contact.uri)
        else:
            bonjour_contact = NSApp.delegate().contactsWindowController.model.getBonjourContactMatchingDeviceId(contact.uri)
            if not bonjour_contact:
                BlinkLogger().log_info("Bonjour neighbour %s was not found on this network" % contact.name)
                message = NSLocalizedString("Bonjour neighbour %s was not found on this network. ", "label") % contact.name
                NSRunAlertPanel(NSLocalizedString("Error", "Window title"), message, NSLocalizedString("OK", "Button title"), None, None)
                return
            NSApp.delegate().contactsWindowController.startSessionWithTarget(bonjour_contact.uri)
コード例 #55
0
ファイル: SIPManager.py プロジェクト: uditha-atukorala/blink
    def _NH_SIPApplicationWillStart(self, sender, data):
        settings = SIPSimpleSettings()
        _version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))
        settings.user_agent = "%s %s (MacOSX)" % (NSApp.delegate().applicationName, _version)
        BlinkLogger().log_info(u"SIP User Agent: %s" % settings.user_agent)

        self.migratePasswordsToKeychain()
        self.cleanupIcons()

        # Set audio settings compatible with AEC and Noise Supressor
        settings.audio.sample_rate = 32000 if settings.audio.echo_canceller.enabled else 48000
        if NSApp.delegate().applicationName == 'SIP2SIP':
            settings.service_provider.help_url  = 'http://wiki.sip2sip.info'
            settings.service_provider.name = 'SIP2SIP'
        settings.save()
        BlinkLogger().log_info(u"Audio engine sampling rate %dKHz covering 0-%dKHz spectrum" % (settings.audio.sample_rate/1000, settings.audio.sample_rate/1000/2))
        BlinkLogger().log_info(u"Acoustic Echo Canceller is %s" % ('enabled' if settings.audio.echo_canceller.enabled else 'disabled'))

        # Although this setting is set at enrollment time, people who have downloaded previous versions will not have it
        account_manager = AccountManager()
        for account in account_manager.iter_accounts():
            must_save = False
            if account is not BonjourAccount() and account.sip.primary_proxy is None and account.sip.outbound_proxy and not account.sip.selected_proxy:
                account.sip.primary_proxy = account.sip.outbound_proxy
                must_save = True

            if account is not BonjourAccount() and settings.tls.verify_server != account.tls.verify_server:
                account.tls.verify_server = settings.tls.verify_server
                must_save = True

            if account.tls.certificate and os.path.basename(account.tls.certificate.normalized) != 'default.crt':
                account.tls.certificate = DefaultValue
                must_save = True

            if must_save:
                account.save()

        logger = FileLogger()
        logger.start()
        self.ip_address_monitor.start()
コード例 #56
0
ファイル: SIPManager.py プロジェクト: uditha-atukorala/blink
    def _NH_SIPAccountGotMessageSummary(self, account, data):
        BlinkLogger().log_info(u"Received voicemail notification for account %s" % account.id)
        summary = data.message_summary
        if summary.summaries.get('voice-message') is None:
            return
        voice_messages = summary.summaries['voice-message']
        growl_data = NotificationData()
        new_messages = int(voice_messages['new_messages'])
        old_messages = int(voice_messages['old_messages'])
        growl_data.new_messages = new_messages
        growl_data.old_messages = old_messages
        MWIData.store(account, summary)
        if summary.messages_waiting and growl_data.new_messages > 0:
            self.notification_center.post_notification("GrowlGotMWI", sender=self, data=growl_data)

            nc_title = NSLocalizedString("New Voicemail Message", "System notification title") if new_messages == 1 else NSLocalizedString("New Voicemail Messages", "System notification title")
            nc_subtitle = NSLocalizedString("On Voicemail Server", "System notification subtitle")
            if old_messages > 0:
                nc_body = NSLocalizedString("You have %d new and " % new_messages, "System notification body") + NSLocalizedString("%d old voicemail messages" %  old_messages, "System notification body")
            else:
                nc_body = NSLocalizedString("You have %d new voicemail messages" % new_messages, "System notification body")
            NSApp.delegate().gui_notify(nc_title, nc_body, nc_subtitle)
コード例 #57
0
def openFileTransferSelectionDialog(account, dest_uri, filename=None):
    if not NSApp.delegate(
    ).contactsWindowController.sessionControllersManager.isMediaTypeSupported(
            'file-transfer'):
        return

    panel = NSOpenPanel.openPanel()
    panel.setTitle_(
        NSLocalizedString("Select Files or Folders and Click Open to Send",
                          "Window title"))
    panel.setDirectoryURL_(NSURL.URLWithString_(filename))

    panel.setAllowsMultipleSelection_(True)
    panel.setCanChooseDirectories_(True)

    if panel.runModal() != NSOKButton:
        return
    filenames = [
        unicodedata.normalize('NFC', file) for file in panel.filenames()
    ]
    NSApp.delegate(
    ).contactsWindowController.sessionControllersManager.send_files_to_contact(
        account, dest_uri, filenames)
コード例 #58
0
    def sendMessage(self, text, content_type="text/plain"):
        self.lookup_destination(self.target_uri)

        timestamp = ISOTimestamp.now()
        hash = hashlib.sha1()
        hash.update(text.encode("utf-8")+str(timestamp))
        msgid = hash.hexdigest()
        call_id = ''

        if content_type != "application/im-iscomposing+xml":
            icon = NSApp.delegate().contactsWindowController.iconPathForSelf()
            self.chatViewController.showMessage(call_id, msgid, 'outgoing', None, icon, text, timestamp, state="sent", media_type='sms')

            recipient=CPIMIdentity(self.target_uri, self.display_name)
            self.messages[msgid] = MessageInfo(msgid, sender=self.account, recipient=recipient, timestamp=timestamp, content_type=content_type, text=text, status="queued")

        self.queue.append((msgid, text, content_type))
コード例 #59
0
    def gotMessage(self, sender, call_id, message, is_html=False, is_replication_message=False, timestamp=None):
        self.enableIsComposing = True
        icon = NSApp.delegate().contactsWindowController.iconPathForURI(format_identity_to_string(sender))
        timestamp = timestamp or ISOTimestamp.now()

        hash = hashlib.sha1()
        hash.update(message.encode('utf-8')+str(timestamp)+str(sender))
        msgid = hash.hexdigest()

        self.chatViewController.showMessage(call_id, msgid, 'incoming', format_identity_to_string(sender), icon, message, timestamp, is_html=is_html, state="delivered", media_type='sms')

        self.notification_center.post_notification('ChatViewControllerDidDisplayMessage', sender=self, data=NotificationData(direction='incoming', history_entry=False, remote_party=format_identity_to_string(sender), local_party=format_identity_to_string(self.account) if self.account is not BonjourAccount() else 'bonjour', check_contact=True))

        # save to history
        if not is_replication_message:
            message = MessageInfo(msgid, call_id=call_id, direction='incoming', sender=sender, recipient=self.account, timestamp=timestamp, text=message, content_type="html" if is_html else "text", status="delivered")
            self.add_to_history(message)
コード例 #60
0
    def replay_history(self):
        blink_contact = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI(self.target_uri)
        if not blink_contact:
            remote_uris = self.remote_uri
        else:
            remote_uris = list(str(uri.uri) for uri in blink_contact.uris if '@' in uri.uri)


        zoom_factor = self.chatViewController.scrolling_zoom_factor

        if zoom_factor:
            period_array = {
                1: datetime.datetime.now()-datetime.timedelta(days=2),
                2: datetime.datetime.now()-datetime.timedelta(days=7),
                3: datetime.datetime.now()-datetime.timedelta(days=31),
                4: datetime.datetime.now()-datetime.timedelta(days=90),
                5: datetime.datetime.now()-datetime.timedelta(days=180),
                6: datetime.datetime.now()-datetime.timedelta(days=365),
                7: datetime.datetime.now()-datetime.timedelta(days=3650)
                }

            after_date = period_array[zoom_factor].strftime("%Y-%m-%d")

            if zoom_factor == 1:
                self.zoom_period_label = 'Displaying messages from last day'
            elif zoom_factor == 2:
                self.zoom_period_label = 'Displaying messages from last week'
            elif zoom_factor == 3:
                self.zoom_period_label = 'Displaying messages from last month'
            elif zoom_factor == 4:
                self.zoom_period_label = 'Displaying messages from last three months'
            elif zoom_factor == 5:
                self.zoom_period_label = 'Displaying messages from last six months'
            elif zoom_factor == 6:
                self.zoom_period_label = 'Displaying messages from last year'
            elif zoom_factor == 7:
                self.zoom_period_label = 'Displaying all messages'
                self.chatViewController.setHandleScrolling_(False)

            results = self.history.get_messages(remote_uri=remote_uris, media_type=('chat', 'sms'), after_date=after_date, count=10000, search_text=self.chatViewController.search_text)
        else:
            results = self.history.get_messages(remote_uri=remote_uris, media_type=('chat', 'sms'), count=self.showHistoryEntries, search_text=self.chatViewController.search_text)

        messages = [row for row in reversed(results)]
        self.render_history_messages(messages)