Skip to content

Instantly share code, notes, and snippets.

@korc
Created August 3, 2014 05:42
Show Gist options
  • Save korc/9fe451e8e2f78fb38174 to your computer and use it in GitHub Desktop.
Save korc/9fe451e8e2f78fb38174 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from bottle import Bottle, response, request, HTTPResponse
import subprocess
import os
import json
import sys
ADB=os.environ.get("ADB", "adb")
app=Bottle()
@app.get("/")
def index():
response.content_type="text/html"
return """
<html><head>
<script>
"use strict";
window.addEventListener("load", function() {
var img=document.createElement("img");
img.src="/screenshot.png";
var m={};
img.addEventListener("mousedown", function(ev) {
ev.preventDefault();
ev.stopPropagation();
m.x1=ev.offsetX; m.y1=ev.offsetY;
}, true);
img.addEventListener("mouseup", function(ev) {
m.x2=ev.offsetX; m.y2=ev.offsetY
var xhr=new XMLHttpRequest();
xhr.open("POST", "/mouse", true);
xhr.responseType="json";
xhr.setRequestHeader("Content-Type", "application/json");
xhr.addEventListener("load", function() {
img.src=img.src.replace(/#.*/,"")+"#"+(new Date()).getTime();
}, false);
xhr.send(JSON.stringify(m));
}, true);
img.addEventListener("error", function(ev) {
console.log("img errored");
}, false);
document.body.appendChild(img);
var reloadBtn=document.createElement("input");
reloadBtn.value="R";
reloadBtn.type="button";
img.style.float="left";
var reloadTimer;
reloadBtn.addEventListener("click", function() {
if(reloadTimer) reloadTimer=window.clearInterval(reloadTimer);
else reloadTimer=window.setInterval(function() {
img.src=img.src.replace(/#.*/,"")+"#"+(new Date()).getTime();
}, 1000);
reloadBtn.style.borderStyle=reloadTimer?"inset":"";
}, false);
document.body.appendChild(reloadBtn);
}, false);
</script>
</head><body>
</body></html>
"""
@app.post("/mouse")
def post_mouse():
cmd=[ADB,"shell","input"]
m=request.json
if m["x1"]==m["x2"] and m["y1"]==m["y2"]: cmd.extend(["tap", str(m["x1"]), str(m["y1"])])
else: cmd.extend(["swipe"]+map(str, [m["x1"], m["y1"], m["x2"], m["y2"]]))
proc=subprocess.Popen(cmd, stderr=subprocess.PIPE)
response.content_type="application/json"
ret=dict(exit_st=proc.wait())
err=proc.stderr.read()
if err: ret["err"]=err
return json.dumps(ret)
@app.get("/screenshot.png")
def screenshot():
cmd=[ADB,"shell","screencap","-p"]
proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output=proc.stdout.read().replace("\r\n","\n")
response.content_type="image/png"
ret=dict(exit_st=proc.wait())
if ret["exit_st"]:
ret["err"]=proc.stderr.read()
sys.stderr.write("screencap error: %s"%(ret["err"],))
return HTTPResponse(json.dumps(ret), 503, content_type="application/json")
return output
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment