def import_transaction_file(self, transaction_file_path):
        self.browser.execute_script("AppMessenger.fireEvent('panelchanged', 1);") # transacoes

        time.sleep(5)

        elem = self.browser.find_elements_by_xpath("//*[contains(@class,'x-btn x-importar x-btn-noicon')]") # importar
        elem[0].click()

        elem = self.browser.find_element_by_xpath("//b[contains(text(),'Avan')]") # avancar
        elem.click()

        elem = self.browser.find_element_by_name("file")
        elem.send_keys(transaction_file_path)


        elem = self.browser.find_elements_by_xpath("//*[contains(@class,'x-form-trigger x-form-arrow-trigger')]")
        elem[7].click()

        app('Firefox').activate()
        app('System Events').keystroke('\r')

        elem = self.browser.find_element_by_xpath("//b[contains(text(),'Avan')]") # avancar
        elem.click()

        time.sleep(20) # uploading...

        elem = self.browser.find_elements_by_link_text("aqui") # clicking at aqui link
        elem[0].click()

        elem = self.browser.find_elements_by_xpath("//*[contains(text(),'Importar arquivo')]") # clicar no importar arquivo
        elem[-1].click()

        time.sleep(20)
Ejemplo n.º 2
0
 def new(self,url=None):
     """make and return new window"""
     app("Safari").make(new=k.document)
     r=app("Safari").windows.first
     if url:
         window(r).current_tab.url=url
     return window(r)
Ejemplo n.º 3
0
	def PUT(self, new_playlist):
		"""Modifies the tracks in an iTunes playlist"""
		if self.special:
			raise error.InvalidRequestError("Attempted to change special playlist '%s'" % self.ref.name)
		
		new_tracks = new_playlist['playlist']['tracks']
		new_ids = [track["track"]["id"] for track in new_tracks]
		
		try:
			current_ids = self.ref.tracks.persistent_ID.get()
		except CommandError:
			current_ids = []
		
		#remove all tracks no longer in list
		for i, current_id in enumerate(current_ids):
			if not new_ids.count(current_id):
				self.ref.tracks[its.persistent_ID == current_id].delete()
				del current_ids[i]
		
		#add all new tracks to list
		for new_id in new_ids:
			if not current_ids.count(new_id):
				new_track = app('iTunes').user_playlists['Music'].file_tracks[its.persistent_ID == new_id].first()
				app('iTunes').duplicate(new_track, to=self.ref)
		
		#rearrange new list
		for index, track_id in enumerate(new_ids):
			location_reference = self.ref.tracks[index+1].before
			track = self.ref.tracks[its.persistent_ID == track_id].first()
			app('iTunes').move(track,to=location_reference)
		
		self.tracks = [Track(track_ref = x) for x in self.ref.file_tracks.get()]
Ejemplo n.º 4
0
    def _do_delete(self, j, *args):
        def op(dupe):
            j.add_progress()
            return self._do_delete_dupe(dupe, *args)

        self.deleted_aperture_photos = False
        marked = [dupe for dupe in self.results.dupes if self.results.is_marked(dupe)]
        j.start_job(self.results.mark_count, tr("Sending dupes to the Trash"))
        if any(isinstance(dupe, IPhoto) for dupe in marked):
            j.add_progress(0, desc=tr("Talking to iPhoto. Don't touch it!"))
            try:
                a = app("iPhoto")
                a.activate(timeout=0)
                a.select(a.photo_library_album(timeout=0), timeout=0)
            except (CommandError, RuntimeError, ApplicationNotFoundError):
                pass
        if any(isinstance(dupe, AperturePhoto) for dupe in marked):
            self.deleted_aperture_photos = True
            j.add_progress(0, desc=tr("Talking to Aperture. Don't touch it!"))
            try:
                a = app("Aperture")
                a.activate(timeout=0)
            except (CommandError, RuntimeError, ApplicationNotFoundError):
                pass
        self.results.perform_on_marked(op, True)
Ejemplo n.º 5
0
def help(constructor, identity, style, flags, aemreference, commandname=''):
	id = (constructor, identity, style)
	if id not in _cache:
		if constructor == 'path':
			appobj = appscript.app(identity)
		elif constructor == 'pid':
			appobj = appscript.app(pid=identity)
		elif constructor == 'url':
			appobj = appscript.app(url=identity)
		elif constructor == 'aemapp':
			appobj = appscript.app(aemapp=aem.Application(desc=identity))
		elif constructor == 'current':
			appobj = appscript.app()
		else:
			raise RuntimeError, 'Unknown constructor: %r' % constructor
		output = StringIO()		
		helpobj = Help(appobj, style, output)
		_cache[id] = (appobj, helpobj, output)
	ref, helpobj, output = _cache[id]
	output.truncate(0)
	if aemreference is not None:
		ref = ref.AS_newreference(aemreference)
	if commandname:
		ref = getattr(ref, commandname)
	helpobj.help(flags, ref)
	s = output.getvalue()
	if NSUserDefaults.standardUserDefaults().boolForKey_(u'enableLineWrap'):
		res = []
		textwrapper = textwrap.TextWrapper(width=NSUserDefaults.standardUserDefaults().integerForKey_(u'lineWrap'), 
				subsequent_indent=' ' * 12)
		for line in s.split('\n'):
			res.append(textwrapper.fill(line))
		s = u'\n'.join(res)
	return s
Ejemplo n.º 6
0
 def __init__(self, spec=None, add_book=None, xl=None):
     if xl is None:
         self.xl = appscript.app(name=spec or 'Microsoft Excel', newinstance=True, terms=mac_dict)
         self.activate()  # Makes it behave like on Windows
     elif isinstance(xl, int):
         self.xl = appscript.app(pid=xl, terms=mac_dict)
     else:
         self.xl = xl
Ejemplo n.º 7
0
 def start_scanning(self):
     if self.directories.has_itunes_path():
         try:
             app(ITUNES, terms=tunes)
         except ApplicationNotFoundError:
             self.view.show_message(tr("The iTunes application couldn't be found."))
             return
     DupeGuruBase.start_scanning(self)
Ejemplo n.º 8
0
	def _set_position(self, value):
		try:
			duration = app('iTunes').current_track.duration()
			if value > duration or value < 0:
				raise error.InvalidRequestError("Track position %s is not valid" % value)
			app('iTunes').player_position.set(value)
		except CommandError:
			raise error.InvalidRequestError("Cannot set position when iTunes has no current track.")
Ejemplo n.º 9
0
 def special_key(self, key, using=None):
     """send non printable key
     
     using is list of special key like:
     ['control_down', 'command_down', 'option_down']
     """
     sp_keys = [ getattr(appscript.k, sp_key) for sp_key in using if hasattr(appscript.k, sp_key) ]
     appscript.app('System Events').keystroke(key , using=sp_keys)
Ejemplo n.º 10
0
 def start_scanning(self):
     if self.directories.has_iphoto_path():
         try:
             app("iPhoto")
         except ApplicationNotFoundError:
             self.view.show_message(tr("The iPhoto application couldn't be found."))
             return
     DupeGuruBase.start_scanning(self)
Ejemplo n.º 11
0
    def activate(self, steal_focus=False):
        asn = subprocess.check_output(['lsappinfo', 'visibleprocesslist', '-includehidden']).decode('utf-8')
        frontmost_asn = asn.split(' ')[0]
        pid_info_frontmost = subprocess.check_output(['lsappinfo', 'info', '-only', 'pid', frontmost_asn]).decode('utf-8')
        pid_frontmost = int(pid_info_frontmost.split('=')[1])

        appscript.app('System Events').processes[its.unix_id == self.pid].frontmost.set(True)
        if not steal_focus:
            appscript.app('System Events').processes[its.unix_id == pid_frontmost].frontmost.set(True)
Ejemplo n.º 12
0
def clean_up():
    """
    Since AppleScript cannot access Excel while a Macro is running, we have to run the Python call in a
    background process which makes the call return immediately: we rely on the StatusBar to give the user
    feedback.
    This function is triggered when the interpreter exits and runs the CleanUp Macro in VBA to show any
    errors and to reset the StatusBar.
    """
    if is_excel_running():
        app('Microsoft Excel').run_VB_macro('CleanUp')
Ejemplo n.º 13
0
def get_workbook(fullname):
    """
    Get the appscript Workbook object.
    On Mac, it seems that we don't have to deal with >1 instances of Excel,
    as each spreadsheet opens in a separate window anyway.
    """
    filename = os.path.basename(fullname)
    xl_workbook = app('Microsoft Excel').workbooks[filename]
    xl_app = app('Microsoft Excel')
    return xl_app, xl_workbook
Ejemplo n.º 14
0
def set_wallpaper(image_file_with_path):

    filepath = os.path.abspath(image_file_with_path)

    try:
        app('Finder').desktop_picture.set(mactypes.File(filepath))
        return True

    except Exception:
        return False
    def test_by_id(self):
        for name in ["com.apple.textedit", "com.apple.finder"]:
            a = appscript.app(id=name)
            self.assertNotEqual(None, a)
            self.assertEqual(appscript.reference.Application, a.__class__)
            self.assertEqual(appscript.reference.Reference, a.name.__class__)

        self.assertEqual("app(u'/Applications/TextEdit.app')", str(appscript.app(id="com.apple.textedit")))

        self.assertRaises(appscript.ApplicationNotFoundError, appscript.app, id="non.existent.app")
Ejemplo n.º 16
0
def mate(self):
    frame, lineno = self.stack[self.curindex]
    filename = self.canonic(frame.f_code.co_filename)
    if exists(filename):
        tm_url = 'txmt://open?url=file://%s&line=%d&column=2' % (filename, lineno)
        if have_appscript:
            app("TextMate").get_url(tm_url)
        else:
            osa_cmd = 'tell application "TextMate" to get url "%s"' % tm_url
            system('osascript -e \'%s\'' % osa_cmd)
Ejemplo n.º 17
0
def reset_status_bar():
    """
    Since Apple Script cannot access Excel while a Macro is running, we have to run the Python call in a
    background process which makes the call return immediately: we rely on the StatusBar to give the user
    feedback.
    This function is triggered when the interpreter exits and makes sure that the StatusBar in Excel is
    reset. Due to a bug in Apple Script, False doesn't reset it properly so we're calling it through an
    Excel Macro to get it right.
    """
    app('Microsoft Excel').run_VB_macro('ResetStatusBar')
def mate(self):
    frame, lineno = self.stack[self.curindex]
    filename = self.canonic(frame.f_code.co_filename)
    if exists(filename):
        filename = realpath(filename)
        tm_url = 'txmt://open?url=file://%s&line=%d&column=2' % (filename, lineno)
        if have_appscript:
            app("TextMate").get_url(tm_url)
        else:
            osa_cmd = OSA_TEMEPLATE % tm_url
            system('osascript -e \'%s\'' % osa_cmd)
Ejemplo n.º 19
0
 def focus(*msg):
     if msg[2][0]=='borg':
         window.activate()
         window.switch_to()
         window.minimize()
         window.maximize()
         window.set_visible(False)
         window.set_visible(True)
     if msg[2][0]=='max':
         import appscript
         appscript.app('MaxMSP Runtime').activate()
Ejemplo n.º 20
0
 def __init__(self, name=None):
     try:
         if name:
             self.og = appscript.app(name)
         else:
             try:
                 self.og = appscript.app('OmniGraffle.app')
             except:
                 self.og = appscript.app('OmniGraffle Professional 5.app')
     except:
         raise "Could not find OmniGraffle application"
Ejemplo n.º 21
0
def autofit(range_, axis):
    address = range_.xl_range.get_address()
    app('Microsoft Excel').screen_updating.set(False)
    if axis == 0 or axis == 'rows' or axis == 'r':
        range_.xl_sheet.rows[address].autofit()
    elif axis == 1 or axis == 'columns' or axis == 'c':
        range_.xl_sheet.columns[address].autofit()
    elif axis is None:
        range_.xl_sheet.rows[address].autofit()
        range_.xl_sheet.columns[address].autofit()
    app('Microsoft Excel').screen_updating.set(True)
Ejemplo n.º 22
0
	def _set_current_track_id(self, new_track_id):
		try:
			track_ref = app('iTunes').user_playlists['Music'].file_tracks[its.persistent_ID==new_track_id].first()
		except CommandError:
			raise error.InvalidRequestError("Current track id '%s' not found" % new_track_id)
		
		state = self.state
		app('iTunes').play(track_ref)
		if state == 'stopped':
			self.state = 'paused'
		else:
			self.state = state
Ejemplo n.º 23
0
def main():

    # app('System Events').keystroke('n', using=[k.shift_down, k.command_down])
    # app('System Events').keystroke('n', using=[])

    # for keys without description, we use key code
    # app('System Events').key_code("107")

    # cmd + down arrow
    # app('System Events').key_code("126", using=[k.command_down])

    app("iTunes").output_volume("50")
    def test_by_name(self):
        for name in ["/Applications/TextEdit.app", "Finder.app", "System Events"]:
            a = appscript.app(name)
            self.assertNotEqual(None, a)
            self.assertEqual(appscript.reference.Application, a.__class__)
            self.assertEqual(appscript.reference.Reference, a.name.__class__)

        self.assertEqual("app(u'/Applications/TextEdit.app')", str(appscript.app("TextEdit")))
        self.assertEqual("app(u'/Applications/TextEdit.app')", str(appscript.app(name="TextEdit")))

        self.assertRaises(appscript.ApplicationNotFoundError, appscript.app, "/non-existent/app")
        self.assertRaises(appscript.ApplicationNotFoundError, appscript.app, "non-existent.app")
Ejemplo n.º 25
0
def _makehelpobj(appname, style):
	# TO DO: osax support
	try:
		if appname.startswith('eppc://'):
			appobj = appscript.app(url=appname)
		else:
			appobj = appscript.app(appname)
	except appscript.ApplicationNotFoundError:
		raise EventHandlerError(-10000, 'Application %s not found.' % appname)
	helpobj = appscriptsupport.Help(appobj, style, StringIO())
#	del helpobj._handlers['h']
#	del helpobj._handlers['s']
	return helpobj
Ejemplo n.º 26
0
def main(image_path):
    try:
        from appscript import app, mactypes
        app('Finder').desktop_picture.set(mactypes.File(image_path))
    except ImportError:
        err('could not import appscript. please ensure ')
        err('appscript is installed.\n')
        return False
    except:
        err('error setting wallpaper!')
        return False
    else:
        return True
Ejemplo n.º 27
0
def autofit_sheet(sheet, axis):
    #TODO: combine with autofit that works on Range objects
    num_columns = sheet.xl_sheet.count(each=kw.column)
    num_rows = sheet.xl_sheet.count(each=kw.row)
    xl_range = get_range_from_indices(sheet.xl_sheet, 1, 1, num_rows, num_columns)
    address = xl_range.get_address()
    app('Microsoft Excel').screen_updating.set(False)
    if axis == 0 or axis == 'rows' or axis == 'r':
        sheet.xl_sheet.rows[address].autofit()
    elif axis == 1 or axis == 'columns' or axis == 'c':
        sheet.xl_sheet.columns[address].autofit()
    elif axis is None:
        sheet.xl_sheet.rows[address].autofit()
        sheet.xl_sheet.columns[address].autofit()
    app('Microsoft Excel').screen_updating.set(True)
Ejemplo n.º 28
0
def clean_up():
    """
    Since AppleScript cannot access Excel while a Macro is running, we have to run the Python call in a
    background process which makes the call return immediately: we rely on the StatusBar to give the user
    feedback.
    This function is triggered when the interpreter exits and runs the CleanUp Macro in VBA to show any
    errors and to reset the StatusBar.
    """
    if is_excel_running():
        # Prevents Excel from reopening if it has been closed manually or never been opened
        try:
            app('Microsoft Excel').run_VB_macro('CleanUp')
        except CommandError:
            # Excel files initiated from Python don't have the xlwings VBA module
            pass
Ejemplo n.º 29
0
	def test_by_name(self):
		for name in [
				'/Applications/TextEdit.app',
				'Finder.app',
				'System Events'
		]:
			a = appscript.app(name)
			self.assertNotEqual(None, a)
			self.assertEqual(appscript.reference.Application, a.__class__)
			self.assertEqual(appscript.reference.Reference, a.name.__class__)
		
		self.assertEqual("app(u'/Applications/TextEdit.app')", str(appscript.app('TextEdit')))
		self.assertEqual("app(u'/Applications/TextEdit.app')", str(appscript.app(name='TextEdit')))
		
		self.assertRaises(appscript.ApplicationNotFoundError, appscript.app, '/non-existent/app')
		self.assertRaises(appscript.ApplicationNotFoundError, appscript.app, 'non-existent.app')
Ejemplo n.º 30
0
        def osx_connect():
            complete_osx_command = "cd \"%s\" && clear && %s && exit" % (
                self.lab.path, connect_command)

            if terminal == "TMUX":
                from ..trdparty.libtmux.tmux import TMUX

                logging.debug(
                    "Attaching `%s` to TMUX session `%s` with command `%s`" %
                    (self.name, self.lab.name, complete_osx_command))

                TMUX.get_instance().add_window(self.lab.name,
                                               self.name,
                                               complete_osx_command,
                                               cwd=self.lab.path)
            else:
                import appscript
                logging.debug("Opening OSX terminal with command: %s." %
                              complete_osx_command)
                terminal_app = appscript.app(terminal)
                if terminal == 'iTerm':
                    window = terminal_app.create_window_with_default_profile()
                    window.current_session.write(text=complete_osx_command)
                elif terminal == 'Terminal':
                    terminal_app.do_script(complete_osx_command)
Ejemplo n.º 31
0
def autofit_sheet(sheet, axis):
    #TODO: combine with autofit that works on Range objects
    num_columns = sheet.xl_sheet.count(each=kw.column)
    num_rows = sheet.xl_sheet.count(each=kw.row)
    xl_range = get_range_from_indices(sheet.xl_sheet, 1, 1, num_rows,
                                      num_columns)
    address = xl_range.get_address()
    app('Microsoft Excel').screen_updating.set(False)
    if axis == 0 or axis == 'rows' or axis == 'r':
        sheet.xl_sheet.rows[address].autofit()
    elif axis == 1 or axis == 'columns' or axis == 'c':
        sheet.xl_sheet.columns[address].autofit()
    elif axis is None:
        sheet.xl_sheet.rows[address].autofit()
        sheet.xl_sheet.columns[address].autofit()
    app('Microsoft Excel').screen_updating.set(True)
Ejemplo n.º 32
0
	def test_by_pid(self):
		pid = int(commands.getoutput("top -l1 | grep Finder | awk '{ print $1 }'"))
		a = appscript.app(pid=pid)
		self.assertEqual(appscript.reference.Application, a.__class__)
		self.assertEqual(appscript.reference.Reference, a.name.__class__)
		self.assertEqual("app(pid=%i)" % pid, str(a))
		self.assertEqual('Finder', a.name.get())
Ejemplo n.º 33
0
 def __init__(self, *args, **kwargs):
     super(VoiceOver, self).__init__(*args, **kwargs)
     try:
         from appscript import app
         self.app = app('VoiceOver')
     except ImportError:
         raise OutputError
Ejemplo n.º 34
0
def change_mac_background(file_path):
    """
    Change the background on Mac operating systems
    """
    try:
        from appscript import app, mactypes
        app('Finder').desktop_picture.set(mactypes.File(file_path))
    except ImportError:
        import subprocess
        SCRIPT = """
                 /usr/bin/osascript<<END
                 tell application "Finder" to
                 set desktop picture to POSIX file "%s"
                 end tell
                 END
                 """
        subprocess.Popen(SCRIPT % file_path, shell=True)
Ejemplo n.º 35
0
 def test_by_pid(self):
     pid = int(
         commands.getoutput("top -l1 | grep Finder | awk '{ print $1 }'"))
     a = appscript.app(pid=pid)
     self.assertEqual(appscript.reference.Application, a.__class__)
     self.assertEqual(appscript.reference.Reference, a.name.__class__)
     self.assertEqual("app(pid=%i)" % pid, str(a))
     self.assertEqual('Finder', a.name.get())
Ejemplo n.º 36
0
 def test_by_creator(self):
     a = appscript.app(creator='ttxt')
     self.assertEqual(appscript.reference.Application, a.__class__)
     self.assertEqual(appscript.reference.Reference, a.name.__class__)
     self.assertEqual("app(u'/Applications/TextEdit.app')", str(a))
     self.assertRaises(appscript.ApplicationNotFoundError,
                       appscript.app,
                       id='!self.$o')
Ejemplo n.º 37
0
 def __init__(self, configfile, topdir, refdir):
     # generate regular expression to parse video files
     today = datetime.date.today()
     monthre = '|'.join([today.replace(month=m).strftime("%b") \
                         for m in range(1,13)])
     self.filecre = re.compile(r'^(?P<show>.*)\.[sS](?P<season>\d\d)[eE]' \
                               r'(?P<episode>\d\d)')
     self.showbcre = re.compile(r'(?P<season>\d+)\-\s?(?P<episode>\d+).*' \
                               r'\s(?P<date>\d+\s(' + monthre + \
                               r')\s\d+).*' \
                               r'<a.*\shref="(?P<url>.*)"' + \
                               r'>(?P<title>.*)</a>')
     # application handlers
     self.qtime = appscript.app('QuickTime Player')
     self.itunes = appscript.app('iTunes')
     self._load_config(configfile, topdir, refdir)
     self._query_shows()
Ejemplo n.º 38
0
def runNewCmd(cmd):
    '''
    根据操作系统的不同采用不同的执行方式在新的终端中执行命令
    '''
    import subprocess
    cmds = cmd.split()
    linux = ['gnome-terminal', '-x']
    for i in cmds:
        linux.append(i)
    system_ = getsys()
    if system_ == 'windows':
        subprocess.call('start /wait ' + cmd, shell=True)
    elif system_ == 'linux':
        subprocess.call(linux)
    else:
        import appscript
        appscript.app('Terminal').do_script(cmd)
Ejemplo n.º 39
0
    def vpn(self):
        system_events = AppRunner(app("System Events"))
        network_preferences = AppRunner(system_events.network_preferences,
                                        self.quit_apps)
        services = AppRunner(network_preferences.services, self.quit_apps)
        vpn = AppRunner(services[self.vpn_name], self.quit_apps)

        return vpn
Ejemplo n.º 40
0
def get_itunes_library():
    app = appscript.app('iTunes')
    playlists = app.library_playlists.get()

    if len(playlists) != 1:
        raise Exception('There are {} libraries!'.format(len(playlists)))

    return playlists[0]
Ejemplo n.º 41
0
def appium_webdriver(dr):
    try:
        session_id = dr.session_id
        command_executor = dr.command_executor._url
        desired_capabilities = str(dr.desired_capabilities)

        cmd = 'start python -i "%s" %s %s "%s"' % (appium_function, session_id,
                                                   command_executor,
                                                   desired_capabilities)
        if isMac:
            appscript.app("Terminal").do_script(cmd)
        else:
            os.system("start " + cmd)
        return 1
    except Exception as err:
        traceback.print_exc()
        return err
Ejemplo n.º 42
0
def set_new_wallpaper(image_name, current_wallpaper):
    new_wallpaper = open(current_wallpaper, "w+")
    new_wallpaper.write(image_name)
    if HOST_OS == 'Darwin':
        # Apple
        from appscript import app, mactypes
        app('Finder').desktop_picture.set(mactypes.File(os.path.join(ROOT_DIR, image_name)))
    elif HOST_OS == 'Windows':
        # Windows
        import ctypes
        ctypes.windll.user32.SystemParametersInfoW(20, 0, os.path.join(ROOT_DIR, image_name) , 3)
    else:
        error_handler("Unsupported OS")

    new_wallpaper.close()
    print("")
    print(TermStyle.BOLD + TermStyle.OKGREEN + f"[+] New Wallpaper Set - {image_name}" + TermStyle.ENDC)
Ejemplo n.º 43
0
def get_itunes_playlists():
    """
    Get list of playlist from iTunes

    :return: playlists in iTunes
    :rtype: list
    """
    return app(detect_app()).user_playlists()
Ejemplo n.º 44
0
def change_background_image():
    """Changes desktop background to NASA POD pulled from API

	Arguments: None
	
	Usage: Currently only works on Macs. Ensure a valid API key is added.
	"""

    #Calculate current date and yesterday's date
    now = datetime.now()
    month = str(now.month)
    day = str(now.day)
    if (now.month < 10):
        month = '0' + str(now.month)
    if (now.day < 10):
        day = '0' + str(now.day)
    year = str(now.year)
    timestamp = month + day + year

    yesterday = datetime.now() - timedelta(days=1)
    yesterday_month = str(yesterday.month)
    yesterday_day = str(yesterday.day)
    if (yesterday.month < 10):
        yesterday_month = '0' + str(yesterday.month)
    if (yesterday.day < 10):
        yesterday_day = '0' + str(yesterday.day)
    yesterday_year = str(yesterday.year)
    yesterday_timestamp = yesterday_month + yesterday_day + yesterday_year

    path = os.path.dirname(os.path.realpath(__file__))

    #Pull image url from NASA POD API
    api_response = requests.get(
        'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY)
    link = api_response.json()['hdurl']
    urllib.request.urlretrieve(link, path + '/' + timestamp + '.jpg')

    #Change desktop background to NASA image and remove previous image
    app('Finder').desktop_picture.set(
        mactypes.File(path + '/' + timestamp + '.jpg'))

    try:
        os.remove(path + yesterday_timestamp + '.jpg')
    except:
        pass
Ejemplo n.º 45
0
    def __init__(self):
        try:
            self.app = appscript.app('System Events')
        except appscript.reference.CommandError as e:
            raise SystemEventsError('Appscript initialization error: {0}'.format(e))

        for ref in self.app.users.get():
            u = OSXUserAccount(self, ref)
            self[u.name] = u
Ejemplo n.º 46
0
def activate_terminal():
    terminal_program = os.environ.get("VIMPDBHOOK_TERMINAL_APP", "iTerm")
    limit = 100
    app = appscript.app(terminal_program)
    while limit > 0:
        limit -= 1
        app.activate()
        if app.frontmost():
            return
Ejemplo n.º 47
0
def change_osx_background(filename):
    from appscript import app, mactypes  # use applescript modules

    se = app('System Events')  # fetch system events
    desktops = se.desktops.display_name.get()  # get all available displays
    for d in desktops:
        desk = se.desktops[d]
        # set wallpaper for each display
        desk.picture.set(mactypes.File(filename))
Ejemplo n.º 48
0
 def start_browser(self, config, url, options):
     """
     Start browser and load website.
     """
     try:
         self.sysevents = appscript.app('System Events')
     except MacOS.Error, error:
         code, message = error
         raise RuntimeError(message)
Ejemplo n.º 49
0
    def test_by_name(self):
        for name in [
                '/Applications/TextEdit.app', 'Finder.app', 'System Events'
        ]:
            a = appscript.app(name)
            self.assertNotEqual(None, a)
            self.assertEqual(appscript.reference.Application, a.__class__)
            self.assertEqual(appscript.reference.Reference, a.name.__class__)

        self.assertEqual("app(u'/Applications/TextEdit.app')",
                         str(appscript.app('TextEdit')))
        self.assertEqual("app(u'/Applications/TextEdit.app')",
                         str(appscript.app(name='TextEdit')))

        self.assertRaises(appscript.ApplicationNotFoundError, appscript.app,
                          '/non-existent/app')
        self.assertRaises(appscript.ApplicationNotFoundError, appscript.app,
                          'non-existent.app')
Ejemplo n.º 50
0
 def do(j):
     a = app(ITUNES, terms=tunes)
     a.activate(timeout=0)
     for index, track in enumerate(j.iter_with_progress(self.dead_tracks)):
         if index % 100 == 0:
             time.sleep(.1)
         try:
             track.delete(timeout=0)
         except CommandError as e:
             logging.warning('Error while trying to remove a track from iTunes: %s' % str(e))
Ejemplo n.º 51
0
 def callback(self, objs):
     paths = [
         mactypes.File(f.filename).hfspath
         for path in objs[0].iterfiles()
     ]
     try:
         tracks = appscript.app('iTunes').add(paths)
         msg = '%d track(s) added to iTunes' % (len(tracks), )
     except appscript.reference.CommandError, x:
         msg = 'Failed: %s' % (x.errormessage, )
Ejemplo n.º 52
0
	def test_by_pid(self):
		p = subprocess.Popen("top -l1 | grep Finder | awk '{ print $1 }'", 
				shell=True, stdout=subprocess.PIPE)
		p.wait()
		pid = int(p.stdout.read())
		a = appscript.app(pid=pid)
		self.assertEqual(appscript.reference.Application, a.__class__)
		self.assertEqual(appscript.reference.Reference, a.name.__class__)
		self.assertEqual("app(pid=%i)" % pid, str(a))
		self.assertEqual('Finder', a.name.get())
Ejemplo n.º 53
0
 def start_browser(self, config, url, options):
     """
     Start browser and load website.
     """
     try:
         self.safari = appscript.app('Safari')
         retry(self.safari.activate)
     except MacOS.Error, error:
         code, message = error
         raise RuntimeError(message)
Ejemplo n.º 54
0
def test_opening():
    files = glob.glob('%s/*.pdf' % to_process_dir)
    if files:
        acrobat = app(u'Adobe Acrobat Professional')
        for fn in files:
            print fn
            acrobat.open(fn)
            # acrobat.documents[1].close()
        # acrobat.quit()
        return acrobat
Ejemplo n.º 55
0
def main():

    print(len(sys.argv))  # Debug the arg by output to terminal

    # Build the "today" URL variable
    url = "https://www.gocomics.com/calvinandhobbesespanol/"
    if len(sys.argv) < 2:
        today = datetime.datetime.now()
        url += today.strftime("%Y/%m/%d/")
    else:
        url += sys.argv[1]
        if url[-1] != "/":
            url += "/"

    print(url)  # Debug the string by output to terminal

    # Request URL, Open it, Read in data
    req = urllib.request.Request(url)
    resp = urllib.request.urlopen(req)
    respData = resp.read()

    # Regex to find the comic graphic asset
    if re.search(r"https://assets\.amuniversal[^\"]*", str(respData)):
        comic = re.findall(r"https://assets\.amuniversal[^\"]*",
                           str(respData))[0]
    else:
        return 1

    print(comic)  # Debug the string of the comic found

    # Grab asset and write to workstation
    try:
        os.remove("/tmp/liveComic.png")
    except OSError:
        pass

    urlretrieve(comic, "/tmp/liveComic.png")

    # Set wallpaper
    app("Finder").desktop_picture.set(mactypes.File("/tmp/liveComic.png"))

    return 0
Ejemplo n.º 56
0
        def osx_connect():
            complete_osx_command = "cd \"%s\" && clear && %s && exit" % (
                self.lab.path, connect_command)

            if terminal == "/usr/local/bin/tmux":
                from ..trdparty.libtmux.tmux import TMUX

                logging.debug(
                    "Attaching `%s` to TMUX session `%s` with command `%s`" %
                    (self.name, self.lab.name, complete_osx_command))

                TMUX.get_instance().add_window(self.lab.name,
                                               self.name,
                                               complete_osx_command,
                                               cwd=self.lab.path)
            else:
                import appscript
                logging.debug("Opening OSX terminal with command: %s." %
                              complete_osx_command)
                appscript.app('Terminal').do_script(complete_osx_command)
Ejemplo n.º 57
0
def itunes_connect():
    app = appscript.app('iTunes')

    # iTunes 10.6.3 breaks compatability with appscript
    try:
        v = app.version()
    except AttributeError:
        # load iTunes using a static glue (dumped from iTunes 10.6.1)
        # I restored iTunes 10.6.1 from Time Machine and then used:
        # appscript.terminology.dump("/Applications/iTunes.app", "iTunesGlue.py")
        # and copied the file to /Library/Python/2.7/site-packages
        # then restored the original iTunes application
        # if self.debug: print("attempting to use static glue to connect to iTunes")
        import iTunesGlue
        app = appscript.app('iTunes', terms=iTunesGlue)
        v = app.version() + " [fudged]"

    print("connected to iTunes version %s" % v)

    return app
Ejemplo n.º 58
0
def runContainer(appPort, containerPort, image, imageOptions, containerName):
    print("Starting new container ...")
    if runningOn != "Windows":
        appscript.app('Terminal').do_script(
            "docker run -t -i -p {}:{} --add-host=docker.local:172.16.123.1 {} {}"
            .format(appPort, containerPort, image, imageOptions))
    else:
        os.popen("Start \"{}\" cmd /c cmd /k docker run -p {}:{} {} {}".format(
            containerName, appPort, containerPort, image, imageOptions))
    print("Waiting for {} to start ...".format(containerName))
    while True:
        runningContainers = dockerCli.containers.list(
            all=True,
            filters={
                'status': "running",
                'expose': "{}/tcp".format(appPort)
            })
        if runningContainers != []:
            break
        time.sleep(1)
Ejemplo n.º 59
0
    def __init__(self, config=None):
        self.config = self.__read_config__(config)

        try:
            self.app = appscript.app('System Events')
            self.location = self.app.network_preferences.get(
            ).current_location.get()

        except appscript.reference.CommandError, e:
            raise NetworkConfigError('Appscript initialization error: %s' %
                                     e.errormessage)
Ejemplo n.º 60
0
    def insertPlot(self):
        """
		Inserts plot into new worksheet.
		"""
        newSheet = app(u'Microsoft Excel').active_workbook.make(
            at=app.active_workbook.end, new=k_app.worksheet)
        # get HFS style path
        applescriptCommand = 'return POSIX file "%s" as string' % self.ntf.name
        p = Popen(['osascript', '-e', applescriptCommand], stdout=PIPE)
        osxPath = p.communicate()[0].strip('\n')
        newPic = app(u'Microsoft Excel').make(at=newSheet.beginning,
                                              new=k_app.picture,
                                              with_properties={
                                                  k_app.file_name: osxPath,
                                                  k_app.height:
                                                  self.pixelSize[1],
                                                  k_app.width:
                                                  self.pixelSize[0]
                                              })
        self.ntf.close()