def getTextFromDialog(): textOfMyScript = """ tell application "System Events" set myWords to "This PDF is protected" & return & "Please enter the password:"******"Encrypted PDF" default answer "" buttons {"Cancel", "Continue"} default button 2 with icon 0 with hidden answer) end tell """ myScript = NSAppleScript.initWithSource_(NSAppleScript.alloc(), textOfMyScript) results, err = myScript.executeAndReturnError_(None) # results is an NSAppleEventDescriptor, which describes two things: # The button pressed (1), and the text returned (2). if not err: try: returnedInput = results.descriptorAtIndex_(2).stringValue() except: return None else: if returnedInput: return returnedInput else: return None else: print err return None
def __init__(self, source=None, path=None): """ source : str | None -- AppleScript source code path : str | None -- full path to .scpt/.applescript file Notes: - Either the path or the source argument must be provided. - If the script cannot be read/compiled, a ScriptError is raised. """ if path: url = NSURL.URLWithFilePath_(path) self._script, errorinfo = NSAppleScript.alloc( ).initWithContentsOfURL_error_(url, None) if errorinfo: raise ScriptError(errorinfo) elif source: self._script = NSAppleScript.alloc().initWithSource_(source) else: raise ValueError("Missing source or path argument.") if not self._script.isCompiled(): errorinfo = self._script.compileAndReturnError_(None)[1] if errorinfo: raise ScriptError(errorinfo)
def getTextFromDialog(): textOfMyScript = """ tell application "System Events" set myWords to "This PDF is protected" & return & "Please enter the password:"******"Encrypted PDF" default answer "" buttons {"Cancel", "Continue"} default button 2 with icon 0 with hidden answer) end tell """ myScript = NSAppleScript.initWithSource_(NSAppleScript.alloc(), textOfMyScript) results, err = myScript.executeAndReturnError_(None) # results is an NSAppleEventDescriptor, which describes two things: # The button pressed (1), and the text returned (2). if not err: try: returnedInput = results.descriptorAtIndex_(2).stringValue() except: return None else: if returnedInput: return returnedInput else: return None else: print(err) return None
def resume(self): notification_center = NotificationCenter() script = NSAppleScript.alloc().initWithSource_(self.check_active_script) result, error_info = script.executeAndReturnError_(None) if result and result.booleanValue(): script = NSAppleScript.alloc().initWithSource_(self.unmute_script) script.executeAndReturnError_(None)
def pause(self): notification_center = NotificationCenter() script = NSAppleScript.alloc().initWithSource_(self.check_active_script) result, error_info = script.executeAndReturnError_(None) if result and result.booleanValue(): script = NSAppleScript.alloc().initWithSource_(self.mute_script) script.executeAndReturnError_(None) notification_center.post_notification('%sPauseDidExecute' % self.application, sender=self, data=TimestampedNotificationData())
def get_browsers_tab(self): """ :return: the representation of current url """ text_of_my_script = """tell app "google chrome" to get the url of the active tab of window 1""" s = NSAppleScript.initWithSource_( NSAppleScript.alloc(), text_of_my_script) results, err = s.executeAndReturnError_(None) web_page_info = results.stringValue() return 'Web browser: {}'.format(web_page_info)
def apple_script(script): try: s = NSAppleScript.alloc().initWithSource_(script) res, err = s.executeAndReturnError_(None) return res.stringValue() except: return None
def get_info_mac(): """ Runs an AppleScript script to get the data. Exceptions aren't thrown inside get_info_mac because it automatically opens Spotify if it's closed. """ from Foundation import NSAppleScript apple_script_code = """ getCurrentlyPlayingTrack() on getCurrentlyPlayingTrack() tell application "Spotify" set isPlaying to player state as string set currentArtist to artist of current track as string set currentTrack to name of current track as string return {currentArtist, currentTrack, isPlaying} end tell end getCurrentlyPlayingTrack """ try: s = NSAppleScript.alloc().initWithSource_(apple_script_code) x = s.executeAndReturnError_(None) a = str(x[0]).split('"') if a[5].lower != 'playing': raise SpotifyPaused except IndexError: raise SpotifyClosed from None return a[3], a[1]
def init_chrome_tab_script(self): self.chrome_tab_script = NSAppleScript.alloc().initWithSource_( """ tell application "Google Chrome" get URL of active tab of first window end tell """)
def pause(self): notification_center = NotificationCenter() if self.paused: notification_center.post_notification('%sPauseDidExecute' % self.application, sender=self, data=TimestampedNotificationData()) else: script = NSAppleScript.alloc().initWithSource_(self.check_active_script) result, error_info = script.executeAndReturnError_(None) if result and result.booleanValue(): script = NSAppleScript.alloc().initWithSource_(self.status_script) result, error_info = script.executeAndReturnError_(None) if result and result.stringValue() == "playing": script = NSAppleScript.alloc().initWithSource_(self.pause_script) script.executeAndReturnError_(None) self.paused = True else: self.paused = False notification_center.post_notification('%sPauseDidExecute' % self.application, sender=self, data=TimestampedNotificationData())
def macobj(): """ Return usable MAC object """ # pylint:disable=no-name-in-module from Foundation import NSAppleScript obj = NSAppleScript.alloc() return obj
def activateApp(self, appName: str): # request = 'if app "' \ # + appName \ # + '" is running then tell app "' \ # + appName \ # + '" to activate' request = 'tell app "' + appName + '" to activate' command = NSAppleScript.alloc().initWithSource_(request) command.executeAndReturnError_(None)
def execute(cmd: str): """Execute AppleScript command abd returns exitcode, stdout and stderr. :param str cmd: apple script :return: exitcode, stdout and stderr""" result, error = NSAppleScript.alloc().initWithSource_( cmd).executeAndReturnError_(None) if error: raise AppleScriptError(error) return ae_converter.unpack(result)
def activateAppByPID(self, pid: int): # request = 'if app "' \ # + appName \ # + '" is running then tell app "' \ # + appName \ # + '" to activate' request = 'tell app "System Events"\n' \ 'tell (process id ' + str(pid) + ') to activate' command = NSAppleScript.alloc().initWithSource_(request) command.executeAndReturnError_(None)
def activateMe(self, gui): appName = gui.appTitle # request = 'if app "' \ # + appName \ # + '" is running then tell app "' \ # + appName \ # + '" to activate' request = 'if app "Keasy" is running then ' \ 'tell app "Keasy" to activate' command = NSAppleScript.alloc().initWithSource_(request) command.executeAndReturnError_(None)
def get_info_mac(): from Foundation import NSAppleScript apple_script_code = """ tell application "Spotify" current track's artist end tell """ s = NSAppleScript.alloc().initWithSource_(apple_script_code) x = s.executeAndReturnError_(None) y = str(x[0]) artist = y[33:len(y) - 3] apple_script_code = """ tell application "Spotify" current track's name end tell """ s = NSAppleScript.alloc().initWithSource_(apple_script_code) x = s.executeAndReturnError_(None) y = str(x[0]) track = y[33:len(y) - 3] return artist, track
def getSelection(): sendTextClipBoard(" ") script=''' tell application "System Events" keystroke "c" using command down end tell set theText to (the clipboard as text) return theText''' appleScript = NSAppleScript.alloc().initWithSource_(script) result = appleScript.executeAndReturnError_(objc.nil) return result[0].stringValue()
def runAppleScript(scriptSource, args=[]): s = NSAppleScript.alloc().initWithSource_(scriptSource) result, error = s.executeAndReturnError_(None) if error: print "AppleScript Error:" print error print "Tried to run:" for i, line in enumerate(scriptSource.splitlines()): print "%03i"%(i+1), line return False if result: return result.stringValue() else: return True
def runAppleScript(scriptSource, args=[]): s = NSAppleScript.alloc().initWithSource_(scriptSource) result, error = s.executeAndReturnError_(None) if error: print "AppleScript Error:" print error print "Tried to run:" for i, line in enumerate(scriptSource.splitlines()): print "%03i" % (i + 1), line return False if result: return result.stringValue() else: return True
def __init__(self, source=None, path=None): """ source : str | None -- AppleScript source code path : str | None -- full path to .scpt/.applescript file Notes: - Either the path or the source argument must be provided. - If the script cannot be read/compiled, a ScriptError is raised. """ if path: url = NSURL.URLWithFilePath_(path) self._script, errorinfo = NSAppleScript.alloc().initWithContentsOfURL_error_(url, None) if errorinfo: raise ScriptError(errorinfo) elif source: self._script = NSAppleScript.alloc().initWithSource_(source) else: raise ValueError("Missing source or path argument.") if not self._script.isCompiled(): errorinfo = self._script.compileAndReturnError_(None)[1] if errorinfo: raise ScriptError(errorinfo)
def __init__(self): self.src = """ if application "Spotify" is running then tell application "Spotify" set myTrack to name of current track set myArtist to artist of current track set myAlbum to album of current track set info to "" if player state as text is equal to "playing" set info to myArtist & " – " & myTrack & " – " & myAlbum end if end tell return info end if """ self.script = NSAppleScript.alloc().initWithSource_(self.src)
def get_info_mac(): from Foundation import NSAppleScript apple_script_code = """ getCurrentlyPlayingTrack() on getCurrentlyPlayingTrack() tell application "Spotify" set currentArtist to artist of current track as string set currentTrack to name of current track as string return {currentArtist, currentTrack} end tell end getCurrentlyPlayingTrack """ s = NSAppleScript.alloc().initWithSource_(apple_script_code) x = s.executeAndReturnError_(None) a = str(x[0]).split('"') return a[1], a[3]
def sign_in(): parser = argparse.ArgumentParser() parser.add_argument('--username', help='username') parser.add_argument('--password', help='password') args = parser.parse_args(sys.argv[2:]) path = os.path.join(os.path.dirname(__file__), 'sign_in.scpt') with open(path, "r") as script: txt = script.read() txt = txt.replace("item 1 of argv", '"' + args.username + '"') txt = txt.replace("item 2 of argv", '"' + args.password + '"') install = NSAppleScript.alloc().initWithSource_(txt) result, err_info = install.executeAndReturnError_(None) print err_info result, err_info = install.executeAndReturnError_(None) print err_info
def install_command_line_tools(): target = '/usr/local/bin/yaybu' if os.path.exists(target): if os.path.islink(target) and os.readlink(target) == YAYBUC: NSLog("Command line tools already installed") return alert = NSAlert.alloc().init() alert.setMessageText_("Enable command line support?") alert.setInformativeText_("Yaybu can install a symlink at '/usr/local/bin/yaybu' allowing you to run yaybu from a terminal via the 'yaybu' command.") alert.setAlertStyle_(NSInformationalAlertStyle) alert.addButtonWithTitle_("Yes") alert.addButtonWithTitle_("No") if alert.runModal() == "No": return source = 'do shell script "test ! -d /usr/local/bin && mkdir -p /usr/local/bin; rm -f %s; ln -s %s %s" with administrator privileges' % (target, YAYBUC, target) script = NSAppleScript.alloc().initWithSource_(source) script.executeAndReturnError_(None)
def generateSelectedMethodStubs(): from Foundation import NSAppleScript, objc getSelectedTextAppleScript = ''' tell application \"Xcode\" set current_document to text document 1 whose name ends with (word -1 of (get name of window 1)) tell current_document set documentContent to (get text of contents) set {startIdx, endIdx} to selected character range set len to endIdx - startIdx if (len > -1) then set selectedText to (text startIdx thru endIdx of documentContent) else set selectedText to \"\" end if return selectedText end tell end tell''' appleScript = NSAppleScript.alloc().initWithSource_(getSelectedTextAppleScript) result = appleScript.executeAndReturnError_(objc.nil) selected_text = result[0].stringValue() selected_stubs = selected_text.replace(";", "\n{\n}\n") while selected_stubs.endswith('\n'): selected_stubs = selected_stubs[:-1] return selected_stubs
def get_title(): from Foundation import NSAppleScript src = ''' global frontApp, frontAppName, windowTitle tell application "System Events" set frontApp to first application process whose frontmost is true set frontAppName to name of frontApp tell process frontAppName tell (1st window whose value of attribute "AXMain" is true) set windowTitle to value of attribute "AXTitle" end tell end tell end tell return windowTitle ''' s = NSAppleScript.alloc().initWithSource_(src) r, e = s.executeAndReturnError_(None) if e: print e['NSAppleScriptErrorBriefMessage'] raise Exception(e['NSAppleScriptErrorBriefMessage']) return r.stringValue()
def install(): parser = argparse.ArgumentParser() parser.add_argument('app', help='app') parser.add_argument('--company', help='company') args = parser.parse_args(sys.argv[2:]) # open location "macappstore://itunes.apple.com/app/id%d?mt=12" url = ("macappstore://" + "search.itunes.apple.com" + "/WebObjects/MZContentLink.woa/wa/link?mt=12&path=mac") if args.company: url += "%2f" + args.company url += "%2f" + args.app print url install = NSAppleScript.alloc().initWithSource_(''' tell application "System Events" to tell process "App Store" set frontmost to true --delay 5 open location "%s" --keystroke "f" using command down --keystroke "1Password" & return delay 5 set bButton to button 1 of group 1 of group 1 of UI element 1 of scroll area 1 of group 1 of group 1 of window 1 set bDescription to description of bButton log bDescription if bDescription starts with "Install" then click bButton delay 1 repeat until description of bButton starts with "Open" delay 1 end repeat end if end tell''' % url) result, err_info = install.executeAndReturnError_(None) print err_info
def get_flagged_emails(self, flag_index=0): """Return a list of (from, subject, message_id) tuples of mails flagged with _flag_index_.""" script = """ set flaggedList to {} tell application "Mail" set theMessages to every message in inbox whose flagged status is true and flag index is %d repeat with thisMessage in theMessages set fromMsg to (sender of thisMessage as string) set subjMsg to (subject of thisMessage as string) set msgID to message id of thisMessage set info to {fromMsg, subjMsg, msgID} copy info to end of flaggedList end repeat end tell return flaggedList """ % flag_index applescript = NSAppleScript.alloc().initWithSource_(script) desc, status = applescript.executeAndReturnError_(None) if desc == None: return [] mailcount = desc.numberOfItems() res = [[desc.descriptorAtIndex_(i).descriptorAtIndex_(j).stringValue() for j in range(1,4)] for i in range(1, mailcount+1)] return res
def getURLData(browserType): global url #global domains #global queryValues domain = "" queryValue = "" print "Starting getURLData Function" if browserType == "Google Chrome": out = NSAppleScript.alloc().initWithSource_("tell application \"Google Chrome\" to return URL of active tab of front window") urls = out.executeAndReturnError_(None) url = urls[0] url = url.stringValue() elif browserType == "Safari": out = NSAppleScript.alloc().initWithSource_("tell application \"Safari\" to return URL of front document") urls = out.executeAndReturnError_(None) url = urls[0] url = url.stringValue() elif browserType == "Firefox" or browserType == "Firefox Plugin Content (Shockwave Flash)": repl = mozrepl.Mozrepl() url = repl.execute("gLastValidURLStr") print url print "THATs the NON hacked value" print "Got the URL \n" + url urlParsed = urlparse(url) print urlParsed domain = urlParsed.netloc print "Got the domain: " + domain ### Parse Search String #### print "Running the Parse Search String Section" if bool(parse_qs(urlParsed.query)) or bool(parse_qs(urlParsed.fragment)): print "The user did a search on Google or Bing" if domain == "google.com" or domain == "www.google.com": try: print "google section" queryValue = parse_qs(urlParsed.fragment)['q'] print queryValue print "JUST PRINTED QUERY VALUES" except KeyError: print "Not a valid google url search" elif "bing.com" in domain: try: print "bing" queryValue = parse_qs(urlParsed.query)['q'] except KeyError: print "Not a valid bing url search" print "This is the queryValue: " + str(queryValue) print "Made it to end of function- get url" #START HERE print "VALUES to RETURN:" print url print domain print queryValue return url, domain, queryValue
def SetForegroundWindow(pid): NSAppleScript.alloc().initWithSource_(""" tell application "System Events" set the frontmost of first process whose unix id is %d to true end tell""" % pid).executeAndReturnError_(None)
def GetForegroundWindow(): return NSAppleScript.alloc().initWithSource_(""" tell application "System Events" return unix id of first process whose frontmost = true end tell""").executeAndReturnError_(None)[0].int32Value()
def init_safari_tab_script(self): self.safari_tab_script = NSAppleScript.alloc().initWithSource_(""" tell application "Safari" get URL of front document end tell """)
def set_wallpaper(self, path): script = NSAppleScript.alloc().initWithSource_(""" tell app "Finder" to set desktop picture to POSIX file "%s" """ % path) script.executeAndReturnError_(None)
import sys # work around needed for if not using the system python (such as with anaconda python distrib) #mod_path = '/System/Library/Frameworks/Python.framework/Versions/{0:}.{1:}/Extras/lib/python/PyObjC'.format( sys.version_info[0], sys.version_info[1] ) #sys.path.append(mod_path) from html_content import header_content from Foundation import NSAppleScript from datetime import datetime # create applescript code object s = NSAppleScript.alloc().initWithSource_( 'tell app "Safari" to {URL,name} of tabs of windows') # execute AS obj, get return value result, _ = s.executeAndReturnError_(None) # since we said {URL,name} we should have two items assert result.numberOfItems() == 2 # find number of tabs based on number of groups in the URL set num_windows = result.descriptorAtIndex_(1).numberOfItems() # create a simple dictionary tabs = dict(('window {0:}'.format(win_num), []) for win_num in range(1, num_windows + 1)) for page_idx, win_num in enumerate(tabs, start=1): urls = [ result.descriptorAtIndex_(1).descriptorAtIndex_( page_idx).descriptorAtIndex_(tab_num).stringValue()
Ubica el nombre de la app en uso en un archivo Si tenia una app anterior salvada, se compara y salva si cambia. """ app_list = [] start_time = '' previous_app_name = 'algo inventado' while True: current_time = datetime.now() new_app_name = get_active_app_name() if 'Safari' in new_app_name: # create applescript code object s = NSAppleScript.alloc().initWithSource_( # 'tell app "Safari" to {URL,name} of tabs of windows' "tell application \"Safari\" to return URL of front document as string" ) # execute AS obj, get return value result,_ = s.executeAndReturnError_(None) time.sleep(1) # find number of tabs based on number of groups in the URL set # num_windows = result.descriptorAtIndex_(1).numberOfItems() # create a simple dictionary # tabs = dict(('window {0:}'.format(win_num), []) for win_num in range(1, num_windows + 1)) # for page_idx, win_num in enumerate(tabs, start=1): # urls = [result.descriptorAtIndex_(1).descriptorAtIndex_(page_idx).descriptorAtIndex_(tab_num).stringValue() # for tab_num in range(1, result.descriptorAtIndex_(1).descriptorAtIndex_(page_idx).numberOfItems() + 1)]
#!/usr/bin/python from Foundation import NSAppleScript, NSBundle # Frogor hack https://goo.gl/mvQ7Gw bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() info['LSUIElement'] = '1' applescript = '''tell application "Finder" \ to get POSIX path of (get desktop picture as alias)''' app = NSAppleScript.alloc().initWithSource_(applescript) appresult = app.executeAndReturnError_(None) if appresult[0]: print("User is currently using:") print(appresult[0].data()) else: print("User is using the default desktop picture")
source = """ Tell application 'System Events' with timeout of 900 seconds display dialog 'Please enter your company username:'******'' with icon file ':System:Library:CoreServices:CoreTypes.bundle:Contents:Resources:UserIcon.icns' with title 'Login Password' with text buttons {'Ok'} default button 1 giving up after 700 end timeout end tell text returned of result """ sourcefile = '/tmp/' + os.path.basename(__file__) + os.urandom(16).hex() + '.applescript' with open(sourcefile, 'w+') as file: file.write(source) """ Running a AppleScript Embedded """ script = NSAppleScript.alloc().initWithSource_(source) # Compile and run if script.compileAndReturnError_(None)[0]: result, err = script.executeAndReturnError_(None) if not err: print('Result from embedded:') print(result.stringValue()) else: print('Failed Compile') """ Running a AppleScript File """ script, err = NSAppleScript.alloc().initWithContentsOfURL_error_(NSURL.fileURLWithPath_(sourcefile), None)
def resume(self): if self.paused: script = NSAppleScript.alloc().initWithSource_(self.resume_script) script.executeAndReturnError_(None) self.paused = False
def __init__(self): script_source = self._load_script() self.script = NSAppleScript.alloc().initWithSource_(script_source)
NSAlternateKeyMask, NSCommandKeyMask, NSControlKeyMask, NSShiftKeyMask, NSAlphaShiftKeyMask, NSApplicationActivationPolicyProhibited ) from Quartz import ( CGWindowListCopyWindowInfo, kCGWindowListExcludeDesktopElements, kCGWindowListOptionOnScreenOnly, kCGNullWindowID ) from PyObjCTools import AppHelper import config as cfg import signal import time CHROME_TITLE_SCRIPT = (NSAppleScript.alloc(). initWithSource_('tell application "Google Chrome" to return title of active tab of front window')) CHROME_URL_SCRIPT = (NSAppleScript.alloc(). initWithSource_('tell application "Google Chrome" to return URL of active tab of front window')) class Sniffer: def __init__(self): self.key_hook = lambda x: True self.mouse_button_hook = lambda x: True self.mouse_move_hook = lambda x: True self.screen_hook = lambda x: True self.last_check_windows = time.time() def createAppDelegate(self): sc = self class AppDelegate(NSObject):
def sign_out(): path = os.path.join(os.path.dirname(__file__), 'sign_out.scpt') with open(path, "r") as script: install = NSAppleScript.alloc().initWithSource_(script.read()) result, err_info = install.executeAndReturnError_(None) print err_info