Mac OS X menu item for quickly enabling/disabling HTTP proxy
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

137 lines
5.1 KiB

  1. #!/usr/bin/env python
  2. from Foundation import *
  3. from AppKit import *
  4. from SystemConfiguration import *
  5. import commands, re
  6. class ToggleProxy(NSObject):
  7. def applicationDidFinishLaunching_(self, notification):
  8. # load icon files
  9. self.icons = {
  10. '0-0-0' : NSImage.imageNamed_("icon-0-0-0"),
  11. '1-0-0' : NSImage.imageNamed_("icon-1-0-0"),
  12. '0-1-0' : NSImage.imageNamed_("icon-0-1-0"),
  13. '0-0-1' : NSImage.imageNamed_("icon-0-0-1"),
  14. '1-1-0' : NSImage.imageNamed_("icon-1-1-0"),
  15. '1-0-1' : NSImage.imageNamed_("icon-1-0-1"),
  16. '1-1-1' : NSImage.imageNamed_("icon-1-1-1")
  17. }
  18. # make status bar item
  19. self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
  20. self.statusitem.retain()
  21. self.statusitem.setHighlightMode_(False)
  22. self.statusitem.setEnabled_(True)
  23. self.statusitem.setImage_(self.icons['0-0-0'])
  24. # insert a menu into the status bar item
  25. self.menu = NSMenu.alloc().init()
  26. self.statusitem.setMenu_(self.menu)
  27. # add items to menu
  28. self.httpMenuItem = self.menu.addItemWithTitle_action_keyEquivalent_(
  29. "HTTP proxy",
  30. "toggleHttpProxy:",
  31. "")
  32. self.httpsMenuItem = self.menu.addItemWithTitle_action_keyEquivalent_(
  33. "HTTPS proxy",
  34. "toggleHttpsProxy:",
  35. "")
  36. self.socksMenuItem = self.menu.addItemWithTitle_action_keyEquivalent_(
  37. "SOCKS proxy",
  38. "toggleSocksProxy:",
  39. "")
  40. self.menu.addItem_(NSMenuItem.separatorItem())
  41. self.menu.addItemWithTitle_action_keyEquivalent_(
  42. "Quit",
  43. "quitApp:",
  44. "")
  45. # open connection to the dynamic (configuration) store
  46. self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy", self.dynamicStoreCallback, None)
  47. # start working
  48. self.loadNetworkServices()
  49. self.watchForProxyChanges()
  50. self.updateProxyStatus()
  51. @property
  52. def interface(self):
  53. # get primary interface
  54. return SCDynamicStoreCopyValue(self.store, 'State:/Network/Global/IPv4')['PrimaryInterface']
  55. def loadNetworkServices(self):
  56. """ load list of network services """
  57. self.services = {}
  58. output = commands.getoutput("/usr/sbin/networksetup listnetworkserviceorder")
  59. for servicename, service, device in re.findall(r'\(\d\)\s*(.*?)(?:\n|\r\n?)\(Hardware Port:\s*(.*?), Device:\s*(.*?)\)', output, re.MULTILINE):
  60. self.services[device] = servicename
  61. def watchForProxyChanges(self):
  62. """ install a watcher for proxy changes """
  63. SCDynamicStoreSetNotificationKeys(self.store, None, [ 'State:/Network/Global/Proxies' ])
  64. source = SCDynamicStoreCreateRunLoopSource(None, self.store, 0)
  65. loop = NSRunLoop.currentRunLoop().getCFRunLoop()
  66. CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
  67. def dynamicStoreCallback(self, store, keys, info):
  68. """ callback for watcher """
  69. self.updateProxyStatus()
  70. def updateProxyStatus(self):
  71. """ update proxy status """
  72. # load proxy dictionary
  73. proxydict = SCDynamicStoreCopyProxies(None)
  74. # get status for primary interface
  75. status = proxydict['__SCOPED__'][self.interface]
  76. # update menu items according to their related proxy state
  77. self.httpMenuItem.setState_( status.get('HTTPEnable', False) and NSOnState or NSOffState )
  78. self.httpsMenuItem.setState_( status.get('HTTPSEnable', False) and NSOnState or NSOffState )
  79. self.socksMenuItem.setState_( status.get('SOCKSEnable', False) and NSOnState or NSOffState )
  80. # update icon
  81. self.statusitem.setImage_(
  82. self.icons['%d-%d-%d' % (
  83. status.get('HTTPEnable', False) and 1 or 0,
  84. status.get('HTTPSEnable', False) and 1 or 0,
  85. status.get('SOCKSEnable', False) and 1 or 0
  86. )]
  87. )
  88. def quitApp_(self, sender):
  89. NSApp.terminate_(self)
  90. def toggleHttpProxy_(self, sender):
  91. self.toggleProxy(self.httpMenuItem, 'webproxy')
  92. def toggleHttpsProxy_(self, sender):
  93. self.toggleProxy(self.httpsMenuItem, 'securewebproxy')
  94. def toggleSocksProxy_(self, sender):
  95. self.toggleProxy(self.socksMenuItem, 'socksfirewallproxy')
  96. def toggleProxy(self, item, target):
  97. """ callback for clicks on menu item """
  98. servicename = self.services.get(self.interface)
  99. if not servicename:
  100. NSLog("interface '%s' not found in services?" % self.interface)
  101. return
  102. newstate = item.state() == NSOffState and 'on' or 'off'
  103. commands.getoutput("/usr/sbin/networksetup -set%sstate '%s' %s" % (
  104. target,
  105. servicename,
  106. newstate
  107. ))
  108. self.updateProxyStatus()
  109. if __name__ == '__main__':
  110. sharedapp = NSApplication.sharedApplication()
  111. toggler = ToggleProxy.alloc().init()
  112. sharedapp.setDelegate_(toggler)
  113. sharedapp.run()