source: trunk/LocationDo/action.py @ 212

Last change on this file since 212 was 212, checked in by Nicholas Riley, 15 years ago

LocationDo?.py: in 4111, open NX, move windows around (very brittle,
but seems to work OK), and don't SSH to yt until we can wait for
Kerberos tickets to be valid; at home, ensure Kerberos ticket
validity; add a bunch more locations

action.py: handle both "Expired" and "Expired (IP Address Changed)"
messages from Kerberos; open app with name action needed because NX
Client has no bundle ID or creator; move window action (very rough)

File size: 4.2 KB
Line 
1from Authorization import Authorization, kAuthorizationFlagDestroyRights
2from Foundation import NSBundle, NSNotificationCenter, NSObject, NSURL
3from AppKit import NSWorkspace
4from appscript import app, k, its
5from appscript.specifier import CommandError
6import os, osax, subprocess, tempfile, SCNetworkReachability
7
8appBundle = NSBundle.mainBundle()
9
10def ensureKerberosPrincipalsValid(principals):
11    # XXX still doesn't play well with the automatic ticket renewal the Kerberos app does
12    kerberosApp = app(id='edu.mit.Kerberos.KerberosApp')
13    validPrincipals = kerberosApp.caches.filter((its.time_remaining.startswith('Expired')).NOT).principal.get()
14    for principal in principals:
15        if principal not in validPrincipals:
16            # XXX make these async
17            kerberosApp.renew_tickets(for_principal=principal)
18            # kerberosApp.get_tickets(for_principal=principal)
19
20def setVolumePercent(percent):
21    # XXX should use CoreAudio: see Pester/Source/NJRSoundManager.m
22    osax.setvolume(int(7 * percent))
23
24def _openURL(url):
25    ws = NSWorkspace.sharedWorkspace()
26    url = NSURL.URLWithString_(url)
27    return ws.openURL_(url)
28
29class _LDURLWatcher(NSObject):
30    def URLIsReachable_(self, notification):
31        _openURL(notification.object())
32
33_urlWatcher = _LDURLWatcher.alloc().init()
34NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
35    _urlWatcher, 'URLIsReachable:', SCNetworkReachability.SCNetworkIsReachable,
36    None)
37
38def openURL(url):
39    hostname = NSURL.URLWithString_(url).host()
40    if not SCNetworkReachability.notify_when_reachable(hostname, url):
41        _openURL(url)
42
43def openInBackground(path):
44    ws = NSWorkspace.sharedWorkspace()
45    path = os.path.expanduser(path)
46    return ws.openFile_withApplication_andDeactivate_(path, None, False)
47
48def openApplicationWithName(name):
49    ws = NSWorkspace.sharedWorkspace()
50    return ws.launchApplication_(name)
51
52def setDisplayBrightnessPercent(percent):
53    # XXX create brightness module
54    pathToBrightness = appBundle.pathForResource_ofType_('brightness', None)
55    subprocess.call([pathToBrightness, str(percent)], stderr=subprocess.STDOUT,
56                    stdout=subprocess.PIPE)
57
58def setAdiumStatus(status):
59    # XXX doesn't match preset status if available
60    adiumApp = app(id='com.adiumX.adiumX')
61    if adiumApp.my_status_type() == k.offline:
62        adiumApp.my_status.status_message_string.set(status)
63    else:
64        adiumApp.my_status_message.set(status)
65    adiumApp.my_status_type.set(k.available)
66
67def moveWindow(appName, windowName, position, ifSizeMatches=None):
68    # XXX support locations relative to screen corners
69    systemEventsApp = app(id='com.apple.systemevents')
70    try:
71        if ifSizeMatches:
72            size = tuple(systemEventsApp.processes[appName].windows[windowName].size())
73            ifSizeMatches = tuple(ifSizeMatches)
74            if size != ifSizeMatches:
75                print "Window size didn't match: %s in %s" % (windowName, appName)
76                print "- Wanted %s, got %s" % (ifSizeMatches, size) 
77                return False
78        systemEventsApp.processes[appName].windows[windowName].position.set(position)
79    except CommandError:
80        print "CommandError: %s in %s" % (windowName, appName)
81        return False
82    return True
83
84def terminalDo(command):
85    # XXX if this launches Terminal, it inherits our PYTHONPATH
86    terminalApp = app(id='com.apple.Terminal')
87    # XXX this does not create a new Terminal window; fix
88    terminalApp.do_script(command + '; exit')
89
90_auth = None
91
92def authorizationDo(command, *args):
93    global _auth
94    if not _auth:
95        _auth = Authorization(destroyflags=(kAuthorizationFlagDestroyRights,))
96    return _auth.executeWithPrivileges(command, *args)
97
98def stopVPNC():
99    # killall uses your uid, not your euid to determine which user's
100    # processes to kill; without '-u root', this fails
101    authorizationDo('/usr/bin/killall', '-u', 'root', 'vpnc')
102
103def startVPNC(vpncProfile=None):
104    stopVPNC()
105    args = ['--kernel-ipsec']
106    if vpncProfile:
107        args.append('/etc/vpnc/%s.conf' % vpncProfile)
108    # XXX get password from keychain, then use:
109    # authorizationDo('/usr/local/sbin/vpnc', *args)
110    terminalDo('sudo /usr/local/sbin/vpnc %s' % ' '.join(args))
Note: See TracBrowser for help on using the repository browser.