PageRenderTime 24ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/windmill/browser/safari.py

https://github.com/romainpreston/windmill
Python | 204 lines | 183 code | 5 blank | 16 comment | 2 complexity | 1af64c608903fb692ab11cdc33c1a92d MD5 | raw file
  1. # Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
  2. # Copyright (c) 2009 Domen Kozar <domen@dev.si>
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import commands
  16. import tempfile
  17. import logging
  18. import signal
  19. import killableprocess
  20. import subprocess
  21. import sys, os
  22. if not sys.version.startswith('2.4'):
  23. import urlparse
  24. else:
  25. # python 2.4
  26. from windmill.tools import urlparse_25 as urlparse
  27. from StringIO import StringIO
  28. import windmill
  29. logger = logging.getLogger(__name__)
  30. """
  31. Colossus:/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Support mikeal$ ./networksetup -getwebproxy "AirPort" [14:12]
  32. cp: /Library/Preferences/SystemConfiguration/preferences.plist.old: Permission denied
  33. Enabled: No
  34. Server: 127.0.0.1
  35. Port: 4444
  36. Authenticated Proxy Enabled: 0
  37. Colossus:/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Support mikeal$ ./networksetup -setwebproxystate "AirPort" on [14:12]
  38. cp: /Library/Preferences/SystemConfiguration/preferences.plist.old: Permission denied
  39. Colossus:/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Support mikeal$ ./networksetup -getwebproxy "AirPort" [14:13]
  40. cp: /Library/Preferences/SystemConfiguration/preferences.plist.old: Permission denied
  41. Enabled: Yes
  42. Server: 127.0.0.1
  43. Port: 4444
  44. Authenticated Proxy Enabled: 0
  45. Colossus:/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Support mikeal$ whoami [14:13]
  46. Usage: networksetup -setwebproxy <networkservice> <domain> <port number> <authenticated> <username> <password>
  47. mikeal
  48. """
  49. html_redirection = """
  50. <html>
  51. <head>
  52. <script type="text/javascript">
  53. var i = function(){
  54. window.location = "{replace}";
  55. }
  56. </script>
  57. </head>
  58. <body onload="i();">
  59. </body>
  60. <html>"""
  61. def getoutput(l):
  62. tmp = tempfile.mktemp()
  63. x = open(tmp, 'w')
  64. subprocess.call(l, stdout=x, stderr=x)
  65. x.close(); x = open(tmp, 'r')
  66. r = x.read() ; x.close()
  67. os.remove(tmp)
  68. return r
  69. def dprint(s):
  70. if len(s) is not 0:
  71. print s.rstrip('\n')
  72. if 'Library/Preferences/SystemConfiguration/preferences.plist.old' in s:
  73. print "** To remove this error `chmod -R 777` the directory that shows the permission error"
  74. def find_default_interface_name():
  75. if windmill.settings['NETWORK_INTERFACE_NAME'] is not None:
  76. return windmill.settings['NETWORK_INTERFACE_NAME']
  77. target_host = urlparse.urlparse(windmill.settings['TEST_URL']).hostname
  78. x = ['/sbin/route', 'get', target_host]
  79. interface_id = [l for l in getoutput(x).splitlines() if 'interface' in l][0].split(":")[-1].strip()
  80. all_inet = getoutput([windmill.settings['NETWORKSETUP_BINARY'], '-listallhardwareports']).splitlines()
  81. try:
  82. i = all_inet.index([l for l in all_inet if 'Device: '+interface_id in l][0])
  83. interface_name = all_inet[i - 1].split(':')[-1].strip()
  84. # interface_name = [ l for l in all_inet if l.find(interface_id) is not -1 ][0].split('\n')[0].split(':')[-1]
  85. # if interface_name[0] == ' ':
  86. # interface_name = interface_name.strip()
  87. # if interface_name[-1] == ' ':
  88. # interface_name = interface_name.rstrip()
  89. except IndexError:
  90. print "ERROR: Cannot figure out interface name, please set NETWORK_INTERFACE_NAME in local settings file"
  91. from windmill.bin import admin_lib
  92. admin_lib.teardown(admin_lib.shell_objects_dict)
  93. sys.exit()
  94. # interfaces = getoutput().split('\n\n')
  95. # print 'interfaces::\n', '\n'.join(interfaces)
  96. # for line in interfaces:
  97. # if not line.startswith('(') and line.find('(1)') is not -1:
  98. # line = '(1)'+line.split('(1)')[-1]
  99. # if line.find('Device: '+interface) is not -1:
  100. # interface_name = ' '.join(line.splitlines()[0].split()[1:])
  101. return interface_name
  102. class Safari(object):
  103. def __init__(self):
  104. self.safari_binary = windmill.settings['SAFARI_BINARY']
  105. self.test_url = windmill.settings['TEST_URL']
  106. def create_redirect(self):
  107. self.redirection_page = tempfile.mktemp(suffix='.html')
  108. f = open(self.redirection_page, 'w')
  109. test_url = windmill.get_test_url(windmill.settings['TEST_URL'])
  110. f.write( html_redirection.replace('{replace}', test_url) )
  111. f.flush() ; f.close()
  112. def set_proxy_mac(self):
  113. """Set local Proxy"""
  114. self.netsetup_binary = windmill.settings['NETWORKSETUP_BINARY']
  115. interface_name = find_default_interface_name()
  116. uri = urlparse.urlparse(self.test_url)
  117. set_proxy_command = [ self.netsetup_binary, '-setwebproxy',
  118. interface_name, '127.0.0.1',
  119. str(windmill.settings['SERVER_HTTP_PORT'])
  120. ]
  121. dprint(getoutput(set_proxy_command))
  122. enable_proxy_command = [ self.netsetup_binary, '-setwebproxystate',
  123. interface_name, 'on'
  124. ]
  125. dprint(getoutput(enable_proxy_command))
  126. if windmill.has_ssl:
  127. set_ssl_proxy_command = [ self.netsetup_binary, '-setsecurewebproxy',
  128. interface_name, '127.0.0.1',
  129. str(windmill.settings['SERVER_HTTP_PORT'])
  130. ]
  131. dprint(getoutput(set_proxy_command))
  132. enable_ssl_proxy_command = [ self.netsetup_binary, '-setsecurewebproxystate',
  133. interface_name, 'on'
  134. ]
  135. dprint(getoutput(enable_proxy_command))
  136. self.create_redirect()
  137. self.interface_name = interface_name
  138. def unset_proxy_mac(self):
  139. getoutput([self.netsetup_binary, '-setwebproxystate', self.interface_name, 'off'])
  140. getoutput([self.netsetup_binary, '-setsecurewebproxystate', self.interface_name, 'off'])
  141. def set_proxy_windows(self):
  142. self.create_redirect()
  143. import ie
  144. self.ie_obj = ie.InternetExplorer()
  145. self.ie_obj.set_proxy()
  146. def unset_proxy_windows(self):
  147. self.ie_obj.unset_proxy()
  148. def start(self):
  149. """Start Safari"""
  150. if sys.platform == 'darwin':
  151. self.set_proxy_mac()
  152. elif sys.platform in ('cygwin', 'win32'):
  153. self.set_proxy_windows()
  154. # Workaround for bug in nose
  155. if hasattr(sys.stdout, 'fileno'):
  156. kwargs = {'stdout':sys.stdout ,'stderr':sys.stderr, 'stdin':sys.stdin}
  157. else:
  158. kwargs = {'stdout':sys.__stdout__ ,'stderr':sys.__stderr__, 'stdin':sys.stdin}
  159. self.p_handle = killableprocess.runCommand([self.safari_binary, self.redirection_page], **kwargs)
  160. logger.info([self.safari_binary, self.redirection_page])
  161. def kill(self, kill_signal=None):
  162. """Stop Safari"""
  163. if sys.platform == 'darwin':
  164. self.unset_proxy_mac()
  165. elif sys.platform in ('cygwin', 'win32'):
  166. self.unset_proxy_windows()
  167. try:
  168. self.p_handle.kill(group=True)
  169. except:
  170. logger.error('Cannot kill Safari')
  171. def stop(self):
  172. self.kill(signal.SIGTERM)
  173. def is_alive(self):
  174. if self.p_handle.poll() is None:
  175. return False
  176. return True