예제 #1
0
def get_apps():
    # credit to the Munki project for borrowing code, thanks Munki!
    apps_dict = {}
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(
        NSPredicate.predicateWithFormat_(
            "(kMDItemContentType = 'com.apple.application-bundle')"))
    query.setSearchScopes_(['/Applications'])
    query.startQuery()
    start_time = 0
    max_time = 20
    while query.isGathering() and start_time <= max_time:
        start_time += 0.3
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()
    # check if the app returns a None value for this query, some apps may have embedded Applescripts
    # that will return a None value and will be set to blank
    for app in query.results():
        name = app.valueForAttribute_('kMDItemDisplayName')
        if name:
            version = app.valueForAttribute_('kMDItemVersion') or ''
            apps_dict[name] = version

    return apps_dict
예제 #2
0
파일: info.py 프로젝트: y010204025/munki
def find_apps_in_dirs(dirlist):
    """Do spotlight search for type applications within the
    list of directories provided. Returns a list of paths to applications
    these appear to always be some form of unicode string.
    """
    applist = []
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(
        NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")'))
    query.setSearchScopes_(dirlist)
    query.startQuery()
    # Spotlight isGathering phase - this is the initial search. After the
    # isGathering phase Spotlight keeps running returning live results from
    # filesystem changes, we are not interested in that phase.
    # Run for 0.3 seconds then check if isGathering has completed.
    runtime = 0
    maxruntime = 20
    while query.isGathering() and runtime <= maxruntime:
        runtime += 0.3
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()

    if runtime >= maxruntime:
        display.display_warning(
            'Spotlight search for applications terminated due to excessive '
            'time. Possible causes: Spotlight indexing is turned off for a '
            'volume; Spotlight is reindexing a volume.')

    for item in query.results():
        pathname = item.valueForAttribute_('kMDItemPath')
        if pathname and not is_excluded_filesystem(pathname):
            applist.append(pathname)

    return applist
예제 #3
0
def get_apps(tag, removal):
    """use spotlight to find apps by custom tag"""
    # main dictionary
    removals = {}
    # set NSMetaDatQuery predicate by your custom tag with value of true
    predicate = "%s = 'true'" % tag
    # build and execute the spotlight query
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(NSPredicate.predicateWithFormat_(predicate))
    query.setSearchScopes_(['/Applications'])
    query.startQuery()
    start_time = 0
    max_time = 20
    while query.isGathering() and start_time <= max_time:
        start_time += 0.3
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()
    # iterate through the results to grab spotlight attributes
    for item in query.results():
        app = item.valueForAttribute_('kMDItemFSName')
        path = item.valueForAttribute_('kMDItemPath')
        customtag = item.valueForAttribute_(removal)
        if customtag:
            # build nested dictionary of tagged apps and attribute values
            removals[app] = {}
            removals[app]['path'] = path
            removals[app]['method'] = customtag

    return removals
예제 #4
0
파일: info.py 프로젝트: chrisgrande/munki
def find_apps_in_dirs(dirlist):
    """Do spotlight search for type applications within the
    list of directories provided. Returns a list of paths to applications
    these appear to always be some form of unicode string.
    """
    applist = []
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(
        NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")'))
    query.setSearchScopes_(dirlist)
    query.startQuery()
    # Spotlight isGathering phase - this is the initial search. After the
    # isGathering phase Spotlight keeps running returning live results from
    # filesystem changes, we are not interested in that phase.
    # Run for 0.3 seconds then check if isGathering has completed.
    runtime = 0
    maxruntime = 20
    while query.isGathering() and runtime <= maxruntime:
        runtime += 0.3
        NSRunLoop.currentRunLoop(
            ).runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()

    if runtime >= maxruntime:
        display.display_warning(
            'Spotlight search for applications terminated due to excessive '
            'time. Possible causes: Spotlight indexing is turned off for a '
            'volume; Spotlight is reindexing a volume.')

    for item in query.results():
        pathname = item.valueForAttribute_('kMDItemPath')
        if pathname and not is_excluded_filesystem(pathname):
            applist.append(pathname)

    return applist
예제 #5
0
    def _addDirectory(self):
        '''
        Add directory to settings
        '''
        panel = NSOpenPanel.openPanel()
        panel.setCanChooseFiles_(False)
        panel.setCanChooseDirectories_(True)
        panel.setAllowsMultipleSelection_(True)
        if panel.runModal() == NSModalResponseOK:
            for url in panel.URLs():
                pred = NSPredicate.predicateWithFormat_(
                    "path == %@", url.path())
                if self.data['paths'].filteredArrayUsingPredicate_(
                        pred).count() > 0:
                    continue

                directory = Directory.alloc().init()
                directory.path = url.path()
                directory.enable = True
                directory.depth = 1

                self.tableView.beginUpdates()
                self.data['paths'].addObject_(directory)
                index = NSIndexSet.indexSetWithIndex_(
                    self.data['paths'].count() - 1)
                self.tableView.insertRowsAtIndexes_withAnimation_(
                    index, NSTableViewAnimationSlideUp)
                self.tableView.endUpdates()

                # Save to file
                self.saveSettings()
예제 #6
0
 def predicate_evaluates_as_true(self, predicate_string):
     '''Evaluates predicate against our environment dictionary'''
     try:
         predicate = NSPredicate.predicateWithFormat_(predicate_string)
     except Exception, err:
         raise ProcessorError("Predicate error for '%s': %s" %
                              (predicate_string, err))
예제 #7
0
 def predicate_evaluates_as_true(self, predicate_string):
     '''Evaluates predicate against our environment dictionary'''
     try:
         predicate = NSPredicate.predicateWithFormat_(predicate_string)
     except Exception, err:
         raise ProcessorError(
             "Predicate error for '%s': %s"
             % (predicate_string, err))
예제 #8
0
파일: snippet.py 프로젝트: szabo92/gistable
def doComparison(comp_string, obj):
    print 'Comparison: %s' % comp_string
    try:
        p = NSPredicate.predicateWithFormat_(comp_string)
    except Exception, e:
        print >> sys.stderr, "WARNING: %s" % e
        print False
        print
        return
예제 #9
0
    def predicate_evaluates_as_true(self, predicate_string):
        """Evaluates predicate against our environment dictionary"""
        try:
            predicate = NSPredicate.predicateWithFormat_(predicate_string)
        except Exception as err:
            raise ProcessorError(f"Predicate error for '{predicate_string}': {err}")

        result = predicate.evaluateWithObject_(self.env)
        self.output(f"({predicate_string}) is {result}")
        return result
예제 #10
0
    def predicate_evaluates_as_true(self, predicate_string):
        '''Evaluates predicate against our environment dictionary'''
        try:
            predicate = NSPredicate.predicateWithFormat_(predicate_string)
        except Exception as err:
            raise ProcessorError("Predicate error for '%s': %s" %
                                 (predicate_string, err))

        result = predicate.evaluateWithObject_(self.env)
        self.output("(%s) is %s" % (predicate_string, result))
        return result
예제 #11
0
파일: info.py 프로젝트: chrisgrande/munki
def predicate_evaluates_as_true(predicate_string, additional_info=None):
    '''Evaluates predicate against our info object'''
    display.display_debug1('Evaluating predicate: %s', predicate_string)
    info_object = predicate_info_object()
    if isinstance(additional_info, dict):
        info_object.update(additional_info)
    try:
        predicate = NSPredicate.predicateWithFormat_(predicate_string)
    except BaseException, err:
        display.display_warning('%s', err)
        # can't parse predicate, so return False
        return False
예제 #12
0
파일: info.py 프로젝트: y010204025/munki
def predicate_evaluates_as_true(predicate_string, additional_info=None):
    '''Evaluates predicate against our info object'''
    display.display_debug1('Evaluating predicate: %s', predicate_string)
    info_object = predicate_info_object()
    if isinstance(additional_info, dict):
        info_object.update(additional_info)
    try:
        predicate = NSPredicate.predicateWithFormat_(predicate_string)
    except BaseException, err:
        display.display_warning('%s', err)
        # can't parse predicate, so return False
        return False
예제 #13
0
    def predicate_evaluates_as_true(self, predicate_string):
        """Evaluates predicate against our environment dictionary"""
        try:
            predicate = NSPredicate.predicateWithFormat_(predicate_string)
        except Exception as err:
            raise ProcessorError(
                "Predicate error for '%s': %s" % (predicate_string, err)
            )

        result = predicate.evaluateWithObject_(self.env)
        self.output("(%s) is %s" % (predicate_string, result))
        return result
예제 #14
0
    def loadPathSettings(cls):
        '''
        Load the active paths from setting file
        :return An array which contain the active paths
        '''
        settings = cls.load()
        # Filter the directory when enable
        pred = NSPredicate.predicateWithFormat_("enable == 1")
        # Retrieve active path array
        paths = settings['paths'].filteredArrayUsingPredicate_(
            pred).valueForKeyPath_("path")

        settings['paths'] = paths

        return settings
    def get_url(self, os_ver):
        try:
            f = urllib2.urlopen(CHECK_URL)
            plist_text = f.read()
            f.close()
        except BaseException as e:
            raise ProcessorError('Could not retrieve check URL %s' % CHECK_URL)

        plist_filename = os.path.join(self.env['RECIPE_CACHE_DIR'], PLIST_FN)

        try:
            plistf = open(plist_filename, 'w')
            plistf.write(plist_text)
            plistf.close()
        except:
            raise ProcessorError('Could not write NVIDIA plist file %s' %
                                 plist_filename)

        try:
            plist = FoundationPlist.readPlist(plist_filename)
        except:
            raise ProcessorError('Could not read NVIDIA plist file %s' %
                                 plist_filename)

        # the Version is blank here due to the plist NSPredicate
        # testing it to not be the current version.
        pred_obj = {
            'Ticket': {
                'Version': ''
            },
            'SystemVersion': {
                'ProductVersion': os_ver
            }
        }

        for rule in plist['Rules']:
            try:
                predicate = NSPredicate.predicateWithFormat_(rule['Predicate'])
            except:
                raise ProcessorError('Problem with NSPredicate: %s' %
                                     rule['Predicate'])

            if predicate.evaluateWithObject_(pred_obj):
                return rule['Codebase']

        raise ProcessorError('No valid Predicate rules found!')
	def get_url(self, os_ver):
		try:
			f = urllib2.urlopen(CHECK_URL)
			plist_text = f.read()
			f.close()
		except BaseException as e:
			raise ProcessorError('Could not retrieve check URL %s' % CHECK_URL)

		plist_filename = os.path.join(self.env['RECIPE_CACHE_DIR'], PLIST_FN)

		try:
			plistf = open(plist_filename, 'w')
			plistf.write(plist_text)
			plistf.close()
		except:
			raise ProcessorError('Could not write NVIDIA plist file %s' % plist_filename)

		try:
			plist = FoundationPlist.readPlist(plist_filename)
		except:
			raise ProcessorError('Could not read NVIDIA plist file %s' % plist_filename)

		# the Version is blank here due to the plist NSPredicate
		# testing it to not be the current version.
		pred_obj = {'Ticket': {'Version': ''}, 'SystemVersion': {'ProductVersion': os_ver}}

		for rule in plist['Rules']:
			try:
				predicate = NSPredicate.predicateWithFormat_(rule['Predicate'])
			except:
				raise ProcessorError('Problem with NSPredicate: %s' % rule['Predicate'])
	
			if predicate.evaluateWithObject_(pred_obj):
				return rule['Codebase']
			
		raise ProcessorError('No valid Predicate rules found!')
예제 #17
0
from Foundation import NSObject, NSNotificationCenter, NSMetadataQuery, NSPredicate, NSMetadataQueryUserHomeScope, \
        NSMetadataQueryDidFinishGatheringNotification
from PyObjCTools import AppHelper

# from ConsoleReactor import ConsoleReactor
# host = '127.0.0.1'
# port = 0
# interpreterPath = sys.executable
# scriptPath = unicode(os.path.abspath('tcpinterpreter.py'))
# commandReactor = ConsoleReactor.alloc().init()
# interp = AsyncPythonInterpreter.alloc().initWithHost_port_interpreterPath_scriptPath_commandReactor_(host, port, interpreterPath, scriptPath, commandReactor)
# interp.connect()

query = NSMetadataQuery.alloc().init()
query.setPredicate_(NSPredicate.predicateWithFormat_( 'kMDItemKind = "Aperture Library"' ))
scopes = [NSMetadataQueryUserHomeScope]             
query.setSearchScopes_( scopes )


class ThisEventLoopStopper(NSObject):
    def interpFinished_(self, notification):
        AppHelper.stopEventLoop()
stopper = ThisEventLoopStopper.alloc().init()

NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', NSMetadataQueryDidFinishGatheringNotification, query)
query.startQuery()

# NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', u'AsyncPythonInterpreterClosed', interp)
AppHelper.runConsoleEventLoop(installInterrupt=True)
예제 #18
0
	def evaluate_predicate(self, eval_obj, predicate_str):
		try:
			predicate = NSPredicate.predicateWithFormat_(predicate_str)
		except:
			raise ProcessorError('Problem with NSPredicate: %s' % rule['Predicate'])
		return predicate.evaluateWithObject_(eval_obj)
예제 #19
0
 def _process(self):
     predicate = NSPredicate.predicateWithFormat_argumentArray_('bundleIdentifier == %@', ['com.apple.iTunes'])
     return self._system_events.processes().filteredArrayUsingPredicate_(predicate)[0]
예제 #20
0
 def _playlist(self, persistentID):
     predicate = NSPredicate.predicateWithFormat_argumentArray_('persistentID == %@', [persistentID.hex])
     return self._library.userPlaylists().filteredArrayUsingPredicate_(predicate)[0]
예제 #21
0
 def workspaceFilterPredicate(self):
     return NSPredicate.predicateWithFormat_(
         "NOT (self.value BEGINSWITH '<')")
 def workspaceFilterPredicate(self):
     return NSPredicate.predicateWithFormat_("NOT (self.value BEGINSWITH '<')")
예제 #23
0
 def _process(self):
     predicate = NSPredicate.predicateWithFormat_argumentArray_(
         'bundleIdentifier == %@', ['com.apple.iTunes'])
     return self._system_events.processes().filteredArrayUsingPredicate_(
         predicate)[0]
예제 #24
0
 def _playlist(self, persistentID):
     predicate = NSPredicate.predicateWithFormat_argumentArray_(
         'persistentID == %@', [persistentID.hex])
     return self._library.userPlaylists().filteredArrayUsingPredicate_(
         predicate)[0]