forked from openatx/atxserver2-ios-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wdaproxy.js
94 lines (76 loc) · 2.36 KB
/
wdaproxy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Libs
- https://github.com/websockets/ws
- https://github.com/HenningM/express-ws
- https://www.npmjs.com/package/websocket-stream
- https://www.npmjs.com/package/mjpeg-consumer
- https://github.com/request/request
*/
const express = require("express")
const proxy = require("express-http-proxy")
const request = require("request")
const cors = require("cors")
const program = require("commander")
const MjpegConsumer = require('mjpeg-consumer')
const websocketStream = require('websocket-stream/stream');
function makeApp(wdaServerUrl, mjpegServerUrl) {
const app = express()
require('express-ws')(app, null, {
perMessageDeflate: false,
});
app.use(cors())
app.use((err, req, res, next) => {
// log the error...
res.sendStatus(err.httpStatusCode).json(err)
})
app.get("/error", (req, res) => {
throw Error("hello")
})
app.get("/about", (req, res) => {
res.send("Express WebDriverAgent")
})
let clientCount = 0
let mjpegStream = null
// mjpeg stream to websocket stream
app.ws('/screen', function (ws, req) {
const stream = websocketStream(ws, {
binary: true
})
clientCount += 1
if (clientCount === 1) {
console.log("request "+ mjpegServerUrl)
let req = request(mjpegServerUrl)
.on("error", () => {
console.log("request error")
})
const consumer = new MjpegConsumer()
mjpegStream = req.pipe(consumer).on("close", () => {
console.log("request finish")
})
}
mjpegStream.pipe(stream)
.on('error', (e) => {
console.log(e)
})
ws.on('close', () => {
clientCount -= 1
mjpegStream.unpipe(stream)
if (clientCount === 0) {
mjpegStream.destroy()
}
})
});
app.use("/", proxy(wdaServerUrl))
return app
}
program
.version("0.1.0")
.option("-p, --port <port>", "listen port", parseInt)
.option("--wda-url <wdaUrl>", "wda server url")
.option("--mjpeg-url <mjpegUrl>", "mjpeg server url")
.parse(process.argv)
console.log(program.port)
const app = makeApp(program.wdaUrl, program.mjpegUrl)
app.listen(program.port, () => {
console.log("Listen on port", program.port)
})