Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import json
- from selenium import webdriver
- from selenium.webdriver.support.wait import WebDriverWait
- from flask import Flask, make_response, request, jsonify
- from time import sleep
- from io import BytesIO
- from itertools import product
- from PIL import Image
- from threading import Semaphore
- app = Flask(__name__)
- # Sends an internal request to the browser
- def send(cmd, params={}):
- resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
- url = driver.command_executor._url + resource
- body = json.dumps({'cmd':cmd, 'params': params})
- response = driver.command_executor._request('POST', url, body)
- if response['status']: raise Exception(response.get('value'))
- return response.get('value')
- def clear_cache(driver, timeout=60):
- """Clear the cookies and cache for the ChromeDriver instance."""
- # navigate to the settings page
- driver.get('chrome://settings/clearBrowserData')
- # wait for the button to appear
- wait = WebDriverWait(driver, timeout)
- wait.until(get_clear_browsing_button)
- # click the button to clear the cache
- get_clear_browsing_button(driver).click()
- # wait for the button to be gone before returning
- wait.until_not(get_clear_browsing_button)
- @app.route("/clearcaches")
- def clear():
- global cache
- # There are two caches to clear (this script's cache variable and the browser's
- cache = {}
- clear_cache(driver)
- _last_url = None
- SEMAPHORE = Semaphore()
- @app.route("/prime")
- def prime():
- global _last_url
- url = request.args.get('url')
- if _last_url == url:
- return 'ok'
- _last_url = url
- with SEMAPHORE:
- driver.get(url)
- # Send transparency request to browser
- send("Emulation.setDefaultBackgroundColorOverride", \
- {'color': {'r': 0, 'g': 0, 'b': 0, 'a': 0}})
- # Wait until a div element with the id of "done" appears in the DOM
- WebDriverWait(driver, 200).until(lambda x: x.find_element_by_id("done"))
- return 'ok'
- #COUNTER = 1
- #CACHE = {} # (x, y, z) => bytes (image data)
- @app.route("/tile/<x>/<y>/<z>.png")
- def tile(x, y, z):
- rx, ry, rz = map(int, (x, y, z))
- round = 1
- x = rx - rx % round
- y = ry - ry % round
- z = rz
- size = 256
- scale = 2 ** z
- with SEMAPHORE:
- element = driver.find_element_by_tag_name('svg')
- location = element.location
- width = int(element.get_attribute('width'))
- height = int(element.get_attribute('height'))
- tx = -x * size
- ty = -y * size
- transform = "translate(%dpx, %dpx) scale(%f)" % (tx, ty, scale)
- driver.execute_script('document.documentElement.style.setProperty("--transform", arguments[0])', transform)
- screenshot = driver.get_screenshot_as_png()
- data = screenshot
- response = make_response(data)
- response.headers.set('Content-Type', 'image/png')
- return response
- @app.route("/event/", methods=["POST"])
- def post_event():
- body = request.get_json(force=True)
- assert body['type'] in ('click', 'mousedown', 'mouseup', 'mousemove')
- x, y, z = body['tile']['x'], body['tile']['y'], body['tile']['z']
- rx, ry, rz = map(int, (x, y, z))
- x = rx
- y = ry
- z = rz
- size = 256
- scale = 2 ** z
- ox, oy = body['offset']['x'], body['offset']['y']
- element = driver.find_element_by_tag_name('svg')
- width = int(element.get_attribute('width'))
- height = int(element.get_attribute('height'))
- location = element.location
- tx = -x * size
- ty = -y * size
- transform = "translate(%dpx, %dpx) scale(%f)" % (tx, ty, scale)
- if body['type'] == 'mousedown':
- driver.execute_script('document.documentElement.style.setProperty("--transform", arguments[0])', transform)
- ActionChains(driver) \
- .move_to_element_with_offset(element, ox, oy) \
- .click_and_hold() \
- .perform()
- elif body['type'] == 'click':
- driver.execute_script('document.documentElement.style.setProperty("--transform", arguments[0])', transform)
- ActionChains(driver) \
- .move_to_element_with_offset(element, ox, oy) \
- .click() \
- .perform()
- elif body['type'] == 'mousemove':
- ActionChains(driver) \
- .move_to_element_with_offset(element, ox, oy) \
- .perform()
- elif body['type'] == 'mouseup':
- ActionChains(driver) \
- .move_to_element_with_offset(element, ox, oy) \
- .release() \
- .perform()
- return jsonify({
- 'status': 'success',
- })
- @app.route("/")
- def index():
- return 'ok'
- if __name__ == '__main__':
- options = webdriver.ChromeOptions()
- options.add_argument('--no-sandbox')
- options.add_argument('--headless')
- options.add_argument('--disable-web-security')
- options.add_argument('--hide-scrollbars')
- options.binary_location = '/usr/bin/chromium-browser'
- cache = {}
- driver = webdriver.Chrome('/resources/chromedriver', chrome_options=options, desired_capabilities={"acceptInsecureCerts": True})
- driver.set_window_size(256, 256)
- app.run(host='0.0.0.0', port=8030, threaded=True, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement