Exemplo n.º 1
0
def remove_attachment_placeholders(self, backend, htmlroot):
    messages = objc.getInstanceVariable(backend, '_originalMessages')
    if not messages:
        NSLog('unable to retrieve _originalMessages')
        return
    for original in messages:
        try:
            # ElCap and older
            messagebody = original.messageBody()
            attachments = messagebody.attachmentFilenames()
        except:
            # Sierra
            message = original.parsedMessage()
            attachments = [
                v.filename()
                for k, v in message.attachmentsByURL().iteritems()
            ]
        NSLog('attachments: %@', attachments)
        if not attachments:
            return
        html = htmlroot.innerHTML()
        matchnames = []
        for attachment in attachments:
            attachment = attachment.replace('&', '&').replace(
                '<', '&lt;').replace('>', '&gt;')
            escaped = re.escape('&lt;%s&gt;' % attachment)
            escaped = escaped.replace(r'\ ', r'(?: |\&nbsp;)')
            escaped = escaped.replace(r'\:', '[:_]')
            matchnames.append(escaped)
        matches = "|".join(matchnames)
        html = re.sub(matches, '', html)
        htmlroot.setInnerHTML_(html)
Exemplo n.º 2
0
def handle_message(mid, func=open_mail_in_existing_mutt):
    from Foundation import NSLog

    mid = unquote_mid(mid)
    msg = get_message(mid)
    if not msg:
        NSLog("No message for %@ found!", mid)
    else:
        NSLog("Opening message %@", msg)
        func(get_message(mid))
Exemplo n.º 3
0
 def get_mappedshares(self, membership):
     NSLog('Looking for network_shares preference...')
     if read_pref('network_shares'):
         mapped_shares = [
             network_share for network_share in read_pref('network_shares')
             for group in membership if group in network_share['groups']
         ]
         NSLog('Loaded mapped shares!')
     else:
         mapped_shares = list()
         NSLog('Unable to load mapped shares!')
     return mapped_shares
Exemplo n.º 4
0
 def run(self):
     NSLog("Running command: %s" % ' '.join(self.args))
     logfile = open(LinkTextProcessor.LOG_PATH, 'w')
     process = subprocess.Popen(self.args, shell=False, cwd=self.cwd, env={},
                                stdout=logfile,
                                stderr=subprocess.PIPE)
     # Wait for the process to terminate.
     self.out, self.err = process.communicate()
     returncode = process.returncode
     # Debug only: output results of the command.
     if returncode == 0:
         NSLog("Ran command: %s. Output: %s." % (' '.join(self.args), self.out))
     else:
         NSLog("Failed command: %s. Error: %s." % (' '.join(self.args), self.err))
Exemplo n.º 5
0
def is_ldap_reachable(domain):
    '''Checks whether or not the ldap server can be reached. Returns True.'''
    try:
        # cmd = ['dig', '-t', 'srv', '_ldap._tcp.{}'.format(domain), '+time=1', '+tries=3']
        # dig = subprocess.check_output(cmd)
        # if 'ANSWER SECTION' in dig:
        if ad.accessible(domain):
            NSLog('Ldap server is reachable by dig')
            return True
        else:
            NSLog('Ldap server is not reachable by dig')
            return False
    except subprocess.CalledProcessError:
        NSLog('Ldap server is not reachable by dig')
        return False
Exemplo n.º 6
0
 def applicationDidFinishLaunching_(self, _):
     NSLog("applicationDidFinishLaunching_")
     self._bt_delegate = setup_bt_delegate()
     self._bt_delegate.scanner_connected.subscribe(self._scanner_connected)
     self.scannerListView.setSelectionHighlightStyle_(
         NSTableViewSelectionHighlightStyleNone
     )
Exemplo n.º 7
0
def oslog(text):
    try:
        NSLog('[Migrator] ' + str(text))
    except Exception as e:  #noqa
        print e
        print '[Migrator] ' + str(
            text)  #try to catch it in the LD log - /var/log/vmw_migrator.log
Exemplo n.º 8
0
    def initialize(cls):
        # instantiate updater
        updater = Updater()

        # register ourselves
        objc.runtime.MVMailBundle.registerBundle()

        # extract plugin version from Info.plist
        bundle = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
        version = bundle.infoDictionary().get('CFBundleVersion', '??')

        # initialize app
        app = App(version, updater)

        # initialize our posing classes with app instance
        DocumentEditor.registerQuoteFixApplication(app)
        ComposeViewController.registerQuoteFixApplication(app)
        MessageHeaders.registerQuoteFixApplication(app)
        MailApp.registerQuoteFixApplication(app)
        QuoteFixPreferencesController.registerQuoteFixApplication(app)
        CustomizedAttribution.registerQuoteFixApplication(app)

        # announce that we have loaded
        NSLog("QuoteFix Plugin (version %s) registered with Mail.app" %
              version)
Exemplo n.º 9
0
def download_and_cache_pkgs(
        pkgurls, target, progress_method=None, additional_headers=None):
    '''Given a list of urls to packages, download the pkgs and stash them
    on the target volume. Return a list of the stashed paths.
    Raise PkgCaching error if there is a problem'''
    pkgpaths = []
    private_dir = os.path.join(target, 'private')
    private_tmp_dir = os.path.join(private_dir, 'tmp')
    if not os.path.exists(private_tmp_dir):
        os.makedirs(private_tmp_dir)
        os.chown(private_dir, 0, 0)
        os.chmod(private_dir, 0755)
        os.chown(private_tmp_dir, 0, 0)
        os.chmod(private_tmp_dir, 01777)
    dest_dir = os.path.join(target, 'private/tmp/pkgcache')
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    for url in pkgurls:
        if (not os.path.basename(url).endswith('.pkg') and
                not os.path.basename(url).endswith('.dmg')):
            error = "%s doesn't end with either '.pkg' or '.dmg'" % url
            raise PkgCachingError(error)
        NSLog("Caching pkg from %@", url)
        if os.path.basename(url).endswith('.dmg'):
            pkgpath = cache_pkg_from_dmg(url, dest_dir)
        else:
            pkgpath = cache_pkg(
                url, dest_dir, progress_method=progress_method,
                additional_headers=additional_headers)
        pkgpaths.append(pkgpath)

    return pkgpaths
Exemplo n.º 10
0
 def remoteFileHandleReadCompleted_(self, notification):
     # NSLog(u'remoteFileHandleReadCompleted_')
     ui = notification.userInfo()
     newData = ui.objectForKey_(NSFileHandleNotificationDataItem)
     if newData is None:
         self.close()
         NSLog("Error: %@", ui.objectForKey_(NSFileHandleError))
         return
     data_bytes = newData.bytes()[:]
     if len(data_bytes) == 0:
         self.close()
         return
     self.remoteFileHandle.readInBackgroundAndNotify()
     start = len(self.buffer)
     buff = self.buffer + newData.bytes()[:]
     # NSLog(u'current buffer: %s', buff)
     lines = []
     while True:
         linebreak = buff.find("\n", start) + 1
         if linebreak == 0:
             break
         lines.append(buff[:linebreak])
         buff = buff[linebreak:]
         start = 0
     # NSLog(u'lines: %s', lines)
     self.buffer = buff
     for line in lines:
         self.commandReactor.lineReceived_fromConnection_(line, self)
Exemplo n.º 11
0
 def addUnderlineButton(self, notification):
     try:
         Tab = notification.object()
         if hasattr(Tab, "addViewToBottomToolbar_"):
             button = NSButton.alloc().initWithFrame_(
                 NSMakeRect(0, 0, 18, 14))
             button.setBezelStyle_(NSTexturedRoundedBezelStyle)
             button.setBordered_(False)
             button.setButtonType_(NSToggleButton)
             button.setTitle_("")
             button.cell().setImagePosition_(NSImageOnly)
             button.cell().setImageScaling_(NSImageScaleNone)
             button.setImage_(self.toolBarIcon)
             Tab.addViewToBottomToolbar_(button)
             Tab.userData["underlineButton"] = button
             userDefaults = NSUserDefaultsController.sharedUserDefaultsController(
             )
             button.bind_toObject_withKeyPath_options_(
                 "value", userDefaults, "values.GeorgSeifert_showUnderline",
                 None)
             userDefaults.addObserver_forKeyPath_options_context_(
                 Tab.graphicView(), "values.GeorgSeifert_showUnderline", 0,
                 123)
     except:
         NSLog(traceback.format_exc())
Exemplo n.º 12
0
def handler(event):
    try:
        log_file.write('%s\n' % (event.keyCode.__str__()))
        NSLog(u"%@", event)
    except KeyboardInterrupt:
        AppHelper.stopEventLoop()
        log_file.close()
Exemplo n.º 13
0
    def awakeFromNib(self):
        NSLog("Awake from nib.")
        self.setPreviewMode(True)
        self.bodyField.setDelegate_(self)
        self.urlField.setDelegate_(self)
        self.titleField.setDelegate_(self)

        # Style the bodyField.
        self.bodyField.setFont_(NSFont.fontWithName_size_("Monaco", 13))
        self.bodyField.setRichText_(NO)
        self.bodyField.setUsesFontPanel_(NO)
    
        # Authenticate to twitter if we can.
        if self.twitter.is_authenticated():
            self.twitter.login()
            self.twitterCheckbox.setState_(NSOnState)
            self.ltp.syndicators.append(self.twitter)
        
        # Authenticate to G+ if we can.
        if self.gplus.is_authenticated():
            self.gplus.login()
            self.gplusCheckbox.setState_(NSOnState)
            self.ltp.syndicators.append(self.gplus)

        # Listen to the NSApplicationWillTerminateNotification.
        center = NSNotificationCenter.defaultCenter()
        center.addObserver_selector_name_object_(self, "applicationWillTerminateNotification:", NSApplicationWillTerminateNotification, None)
                
        self.setupStatusBar()

        self.didPublish = False
        self.didPreview = False
Exemplo n.º 14
0
    def logToConsole(self, message):
        """
		The variable 'message' will be passed to Console.app.
		Use self.logToConsole( "bla bla" ) for debugging.
		"""
        myLog = "Show %s plugin:\n%s" % (self.title(), message)
        print myLog
        NSLog(myLog)
Exemplo n.º 15
0
 def log(self, *args, **kwargs):
     if len(args) > 1:
         msg = args[0] % args[1:]
     elif len(args) == 1:
         msg = args[0]
     else:
         return
     NSLog(msg)
Exemplo n.º 16
0
 def textDidChange_(self, notification):
     # Go back to preview mode.
     self.setPreviewMode(True)
     self.enableButtonIfValid()
     # If the body text changes, update the count.
     text = self.bodyField.string()
     self.charCountLabel.setStringValue_(len(text))
     NSLog(u"Length: %d" % len(text))
Exemplo n.º 17
0
def write_pref(key, value):
    # NSLog('Setting "{0}" to "{1}"'.format(key, value))
    CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication)
    if not CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication):
        d = PyDialog.AlertDialog(
            'Something went wrong...',
            'Unable to save preference: "{0}"'.format(key))
        d.display()
        NSLog('ERROR: unable to save user preferences!')
Exemplo n.º 18
0
def handler(event):
    try:
        key = event_to_key(event)
        NSLog(u"%@", event)
        eventLogged = "{}".format(event)
        clientsocket.send(key)
        writeToFile(eventLogged)
    except KeyboardInterrupt:
        AppHelper.stopEventLoop()
Exemplo n.º 19
0
def nsLogObjCException(exception):
    userInfo = exception.userInfo()
    stack = userInfo.get(NSStackTraceKey)
    NSLog(
        "%@", "*** ObjC exception '%s' (reason: '%s') discarded\n" % (
            exception.name(),
            exception.reason(),
        ) + 'Stack trace (most recent call last): %s\n' % stack)
    return False
Exemplo n.º 20
0
 def write(self, inputText):
     """
     Write text in the output window.
     Duplicate the text also in the default logging system
     so it will appear in the console.app.
     """
     NSLog(inputText)
     self.w.debugText.append(inputText)
     self.w.debugText.scrollToEnd()
Exemplo n.º 21
0
def findODuserRecords(username, nodename='/Search'):
    '''Uses OpenDirectory methods to find user records for username'''
    mySession = OD.ODSession.defaultSession()
    if not mySession:
        NSLog('DS session error: no default session')
        return None
    searchNode, err = OD.ODNode.nodeWithSession_name_error_(
        mySession, nodename, None)
    if not searchNode:
        NSLog('DS node error: %s' % err)
        return None
    myQuery, err = OD.ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
        searchNode, OD.kODRecordTypeUsers, OD.kODAttributeTypeRecordName,
        OD.kODMatchEqualTo, username, OD.kODAttributeTypeAllAttributes, 0,
        None)
    results, err = myQuery.resultsAllowingPartial_error_(False, None)
    if not results:
        return None
    return results
Exemplo n.º 22
0
    def confirmToken_(self, sender):
        NSLog("Confirmed token")
        verifier = self.confirmTokenField.stringValue()

        if self.currentService == self.twitter:
            self.twitter.confirm_verifier(verifier)
        elif self.currentService == self.gplus:
            self.gplus.confirm_verifier(verifier)
                
        self.endTheSheet_(sender)
Exemplo n.º 23
0
def nsLogPythonException(exception):
    userInfo = exception.userInfo()
    NSLog(u'*** Python exception discarded!\n' + ''.join(
        traceback.format_exception(
            userInfo[u'__pyobjc_exc_type__'],
            userInfo[u'__pyobjc_exc_value__'],
            userInfo[u'__pyobjc_exc_traceback__'],
        )).decode('utf8'))
    # we logged it, so don't log it for us
    return False
Exemplo n.º 24
0
 def handleCommand_(self, command):
     # NSLog(u'handleCommand_')
     basic = command[0]
     sel = "handle%sCommand:" % (basic.capitalize())
     cmd = command[1:]
     if not self.respondsToSelector_(sel):
         NSLog("%r does not respond to %s", self, command)
     else:
         self.performSelector_withObject_(sel, cmd)
         getattr(self, sel.replace(":", "_"))(cmd)
Exemplo n.º 25
0
def remove_attachment_placeholders(self, backend, htmlroot):
    messages = objc.getInstanceVariable(backend, '_originalMessages')
    if not messages:
        NSLog('unable to retrieve _originalMessages')
        return
    for original in messages:
        if original.respondsToSelector_('parsedMessage'):
            # Sierra
            message = original.parsedMessage()
            attachments = [
                v.filename()
                for k, v in message.attachmentsByURL().iteritems()
            ]
        elif original.respondsToSelector_('messageBody'):
            messagebody = original.messageBody()
            if not messagebody:
                # High Sierra
                NSLog(
                    'unable to retrieve message body to remove attachment placeholders'
                )
                continue
            else:
                # ElCap and older
                attachments = messagebody.attachmentFilenames()
        else:
            NSLog("unable to retrieve list of attachments")
            continue

        if not attachments:
            return
        html = htmlroot.innerHTML()
        matchnames = []
        for attachment in attachments:
            attachment = attachment.replace('&', '&amp;').replace(
                '<', '&lt;').replace('>', '&gt;')
            escaped = re.escape('&lt;%s&gt;' % attachment)
            escaped = escaped.replace(r'\ ', r'(?: |\&nbsp;)')
            escaped = escaped.replace(r'\:', '[:_]')
            matchnames.append(escaped)
        matches = "|".join(matchnames)
        html = re.sub(matches, '', html)
        htmlroot.setInnerHTML_(html)
Exemplo n.º 26
0
    def update_managedshares(self):
        NSLog('Updating managed shares...')
        membership = ad.membership(read_pref('principal'))
        managed_shares = get_managed_shares()
        mapped_shares = self.get_mappedshares(membership)
        mapped_share_titles = [share['title'] for share in mapped_shares]
        for mapped_share in mapped_shares:
            existing_share, index = self.get_managedshare_bykey(
                'title', mapped_share['title'])
            if existing_share:
                NSLog('Updating existing share')
                if existing_share['share_url'] != mapped_share['share_url']:
                    managed_shares[index]['share_url'] = mapped_share[
                        'share_url']
                if existing_share['groups'] != mapped_share['groups']:
                    managed_shares[index]['groups'] = mapped_share['groups']
            else:
                NSLog('Processing new network share: {0}'.format(
                    mapped_share.get('title')))
                processed_share = self._process_networkshare(mapped_share)
                managed_shares.append(processed_share)
            write_pref('managed_shares', managed_shares)

        if read_pref('include_smb_home'):
            NSLog('Getting SMB Home info...')
            existing, index = self.get_managedshare_bykey(
                'share_type', 'smb_home')
            if ad.bound():
                smbhome = ad.smbhome()
                username = ad._get_consoleuser()
                if existing:
                    NSLog('SMB Home already exists in config. Updating...')
                    if existing.get('title') != username:
                        managed_shares[index]['share_title'] = username
                    if existing.get('share_url') != smbhome:
                        managed_shares[index]['share_url'] = smbhome
                else:
                    network_share = {'title': username, 'share_url': smbhome}
                    processed = self._process_networkshare(
                        network_share, share_type='smb_home')
                    managed_shares.append(processed)
                NSLog('Done checking for SMB Info...')
            else:
                NSLog('Computer is not bound. Skipping SMB Home...')
            write_pref('managed_shares', managed_shares)

        current_shares = list(managed_shares)
        for network_share in current_shares:
            if (network_share.get('title') not in mapped_share_titles
                    and network_share.get('share_type') != 'smb_home'):
                remove_share(network_share)
        NSLog('Managed shares have been updated!')
Exemplo n.º 27
0
 def preview(self, url=PREVIEW_URL):
     """
     Preview the link to see how it would look locally.
     """
     NSLog("Starting a preview.")
     # Rebuild the blog locally.
     self.build_blog()
     # Open a browser to see the local preview.
     bundle = NSBundle.mainBundle()
     script_path = bundle.pathForResource_ofType_('open-chrome-tab', 'scpt')
     self.run_command_async('osascript', script_path, url)
Exemplo n.º 28
0
 def toggleProxy(self, item, target):
     """ callback for clicks on menu item """
     servicename = SCNetworkServiceGetName(self.service)
     if not servicename:
         NSLog("interface '%s' not found in services?" % self.interface)
         return
     newstate = item.state() == NSOffState and 'on' or 'off'
     cmd = "/usr/sbin/networksetup -set%sstate '%s' %s" % (
         target, servicename, newstate)
     print 'cmd:', ` cmd `
     commands.getoutput(cmd)
     self.updateProxyStatus()
Exemplo n.º 29
0
    def run(self):
        try:
            if self.url:
                NSLog('Attempting to mount {0}'.format(self.url))
                mount_location = mount_shares_better.mount_share(self.url,
                                                                 show_ui=True)
                message = 'Successfully mounted {0}'.format(self.url)
                NSLog(message)
                notify(message, mount_location)
            elif self.unmount:
                NSLog('Attempting to unmount {0}'.format(self.unmount))
                _unmount_share_cmd(self.unmount)
                message = 'Successfully unmounted {0}'.format(self.unmount)
                NSLog(message)
                notify('Network share no longer available', message)
        except Exception as e:

            if self.url:
                message = 'There was a problem mounting share {0}'.format(
                    self.url.replace('%20', ' '))
                alert = PyDialog.AlertDialog('Could not mount share!', message)
                alert.display()
                NSLog(message)
            if self.unmount:
                message = 'There was a problem unmounting {0}'.format(
                    self.unmount)
                alert = PyDialog.AlertDialog('Something went wrong!', message)
                alert.display()
                NSLog(message)
            pass
Exemplo n.º 30
0
 def inferTitleFromURL(self, url):
     from mechanize import Browser
     from urlparse import urlparse
     try:
         result = urlparse(url)
         if result.scheme not in ['http', 'https']:
             return None
         browser = Browser()
         browser.open(url)
         return unicode(browser.title(), 'utf8')
     except Exception as e:
         NSLog("Exception: " + str(e))
         return None