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
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
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
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
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()
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))
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))
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
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
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
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
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
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!')
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)
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)
def _process(self): predicate = NSPredicate.predicateWithFormat_argumentArray_('bundleIdentifier == %@', ['com.apple.iTunes']) return self._system_events.processes().filteredArrayUsingPredicate_(predicate)[0]
def _playlist(self, persistentID): predicate = NSPredicate.predicateWithFormat_argumentArray_('persistentID == %@', [persistentID.hex]) return self._library.userPlaylists().filteredArrayUsingPredicate_(predicate)[0]
def workspaceFilterPredicate(self): return NSPredicate.predicateWithFormat_( "NOT (self.value BEGINSWITH '<')")
def workspaceFilterPredicate(self): return NSPredicate.predicateWithFormat_("NOT (self.value BEGINSWITH '<')")
def _process(self): predicate = NSPredicate.predicateWithFormat_argumentArray_( 'bundleIdentifier == %@', ['com.apple.iTunes']) return self._system_events.processes().filteredArrayUsingPredicate_( predicate)[0]
def _playlist(self, persistentID): predicate = NSPredicate.predicateWithFormat_argumentArray_( 'persistentID == %@', [persistentID.hex]) return self._library.userPlaylists().filteredArrayUsingPredicate_( predicate)[0]