Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.33 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import json
  4. from selenium import webdriver
  5. from selenium.webdriver.support.wait import WebDriverWait
  6. from flask import Flask, make_response, request, jsonify
  7. from time import sleep
  8. from io import BytesIO
  9. from itertools import product
  10. from PIL import Image
  11. from threading import Semaphore
  12.  
  13. app = Flask(__name__)
  14.  
  15. # Sends an internal request to the browser
  16. def send(cmd, params={}):
  17. resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
  18. url = driver.command_executor._url + resource
  19. body = json.dumps({'cmd':cmd, 'params': params})
  20. response = driver.command_executor._request('POST', url, body)
  21. if response['status']: raise Exception(response.get('value'))
  22. return response.get('value')
  23.  
  24. def clear_cache(driver, timeout=60):
  25. """Clear the cookies and cache for the ChromeDriver instance."""
  26. # navigate to the settings page
  27. driver.get('chrome://settings/clearBrowserData')
  28.  
  29. # wait for the button to appear
  30. wait = WebDriverWait(driver, timeout)
  31. wait.until(get_clear_browsing_button)
  32.  
  33. # click the button to clear the cache
  34. get_clear_browsing_button(driver).click()
  35.  
  36. # wait for the button to be gone before returning
  37. wait.until_not(get_clear_browsing_button)
  38.  
  39. @app.route("/clearcaches")
  40. def clear():
  41. global cache
  42.  
  43. # There are two caches to clear (this script's cache variable and the browser's
  44. cache = {}
  45. clear_cache(driver)
  46.  
  47. _last_url = None
  48.  
  49. SEMAPHORE = Semaphore()
  50.  
  51. @app.route("/prime")
  52. def prime():
  53. global _last_url
  54. url = request.args.get('url')
  55. if _last_url == url:
  56. return 'ok'
  57.  
  58. _last_url = url
  59.  
  60. with SEMAPHORE:
  61. driver.get(url)
  62.  
  63. # Send transparency request to browser
  64. send("Emulation.setDefaultBackgroundColorOverride", \
  65. {'color': {'r': 0, 'g': 0, 'b': 0, 'a': 0}})
  66.  
  67. # Wait until a div element with the id of "done" appears in the DOM
  68. WebDriverWait(driver, 200).until(lambda x: x.find_element_by_id("done"))
  69.  
  70. return 'ok'
  71.  
  72. #COUNTER = 1
  73. #CACHE = {} # (x, y, z) => bytes (image data)
  74.  
  75. @app.route("/tile/<x>/<y>/<z>.png")
  76. def tile(x, y, z):
  77. rx, ry, rz = map(int, (x, y, z))
  78. round = 1
  79. x = rx - rx % round
  80. y = ry - ry % round
  81. z = rz
  82. size = 256
  83. scale = 2 ** z
  84.  
  85. with SEMAPHORE:
  86. element = driver.find_element_by_tag_name('svg')
  87. location = element.location
  88.  
  89. width = int(element.get_attribute('width'))
  90. height = int(element.get_attribute('height'))
  91.  
  92. tx = -x * size
  93. ty = -y * size
  94. transform = "translate(%dpx, %dpx) scale(%f)" % (tx, ty, scale)
  95.  
  96. driver.execute_script('document.documentElement.style.setProperty("--transform", arguments[0])', transform)
  97.  
  98. screenshot = driver.get_screenshot_as_png()
  99.  
  100. data = screenshot
  101.  
  102. response = make_response(data)
  103. response.headers.set('Content-Type', 'image/png')
  104. return response
  105.  
  106. @app.route("/event/", methods=["POST"])
  107. def post_event():
  108. body = request.get_json(force=True)
  109. assert body['type'] in ('click', 'mousedown', 'mouseup', 'mousemove')
  110. x, y, z = body['tile']['x'], body['tile']['y'], body['tile']['z']
  111. rx, ry, rz = map(int, (x, y, z))
  112. x = rx
  113. y = ry
  114. z = rz
  115. size = 256
  116. scale = 2 ** z
  117. ox, oy = body['offset']['x'], body['offset']['y']
  118.  
  119. element = driver.find_element_by_tag_name('svg')
  120.  
  121. width = int(element.get_attribute('width'))
  122. height = int(element.get_attribute('height'))
  123. location = element.location
  124.  
  125. tx = -x * size
  126. ty = -y * size
  127. transform = "translate(%dpx, %dpx) scale(%f)" % (tx, ty, scale)
  128.  
  129. if body['type'] == 'mousedown':
  130. driver.execute_script('document.documentElement.style.setProperty("--transform", arguments[0])', transform)
  131. ActionChains(driver) \
  132. .move_to_element_with_offset(element, ox, oy) \
  133. .click_and_hold() \
  134. .perform()
  135.  
  136. elif body['type'] == 'click':
  137. driver.execute_script('document.documentElement.style.setProperty("--transform", arguments[0])', transform)
  138. ActionChains(driver) \
  139. .move_to_element_with_offset(element, ox, oy) \
  140. .click() \
  141. .perform()
  142.  
  143. elif body['type'] == 'mousemove':
  144. ActionChains(driver) \
  145. .move_to_element_with_offset(element, ox, oy) \
  146. .perform()
  147.  
  148. elif body['type'] == 'mouseup':
  149. ActionChains(driver) \
  150. .move_to_element_with_offset(element, ox, oy) \
  151. .release() \
  152. .perform()
  153.  
  154. return jsonify({
  155. 'status': 'success',
  156. })
  157.  
  158. @app.route("/")
  159. def index():
  160. return 'ok'
  161.  
  162. if __name__ == '__main__':
  163. options = webdriver.ChromeOptions()
  164. options.add_argument('--no-sandbox')
  165. options.add_argument('--headless')
  166. options.add_argument('--disable-web-security')
  167. options.add_argument('--hide-scrollbars')
  168. options.binary_location = '/usr/bin/chromium-browser'
  169.  
  170. cache = {}
  171.  
  172. driver = webdriver.Chrome('/resources/chromedriver', chrome_options=options, desired_capabilities={"acceptInsecureCerts": True})
  173. driver.set_window_size(256, 256)
  174. app.run(host='0.0.0.0', port=8030, threaded=True, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement