├── src ├── utils │ ├── path.utils.ts │ ├── cmd.utils.ts │ └── device.utils.ts ├── config │ ├── config.ts │ └── logger.ts ├── index.ts ├── schema │ ├── device.type.ts │ └── wda.types.ts ├── modules │ ├── wda-control │ │ ├── wda-endpoints.ts │ │ ├── wda-service.ts │ │ ├── wda.go.ios.ts │ │ └── wda.control.ts │ ├── tunnel │ │ └── tunnel.manager.ts │ ├── wda-stream │ │ ├── wda.stream.ts │ │ └── mjpeg.parser.ts │ ├── idf.ts │ └── device-management │ │ └── device.manager.ts ├── server │ ├── server.ts │ ├── sock.io.ts │ └── sock.handler.ts └── routes │ └── device.routes.ts ├── images └── idf-screenshot-01.png ├── nodemon.json ├── public ├── static │ ├── js │ │ ├── config.js │ │ ├── renderer │ │ │ ├── back.frame.js │ │ │ ├── render.loop.js │ │ │ ├── pipeline.js │ │ │ └── front.frame.js │ │ ├── events │ │ │ ├── button.events.js │ │ │ └── canvas.events.js │ │ ├── socket │ │ │ └── socket.io.js │ │ ├── device.js │ │ ├── index.js │ │ └── external │ │ │ └── jquery.touchSwipe.min.js │ ├── images │ │ └── icons │ │ │ ├── appstore.png │ │ │ ├── safari.png │ │ │ └── settings.png │ └── css │ │ ├── device.button.css │ │ └── device.css ├── index.html └── device.html ├── jest.config.js ├── tests └── wda.test.ts ├── tsconfig.json ├── init.sh ├── LICENSE ├── package.json ├── README.md └── .gitignore /src/utils/path.utils.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/idf-screenshot-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoCodeStack/ios-device-farm/HEAD/images/idf-screenshot-01.png -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": ".ts,.js", 4 | "ignore": [], 5 | "exec": "npx ts-node ./src/index.ts" 6 | } 7 | -------------------------------------------------------------------------------- /public/static/js/config.js: -------------------------------------------------------------------------------- 1 | const hostname = "localhost"; 2 | const port = 9000; 3 | const uri = `http://${hostname}:${port}`; 4 | -------------------------------------------------------------------------------- /public/static/images/icons/appstore.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoCodeStack/ios-device-farm/HEAD/public/static/images/icons/appstore.png -------------------------------------------------------------------------------- /public/static/images/icons/safari.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoCodeStack/ios-device-farm/HEAD/public/static/images/icons/safari.png -------------------------------------------------------------------------------- /public/static/images/icons/settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoCodeStack/ios-device-farm/HEAD/public/static/images/icons/settings.png -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest').JestConfigWithTsJest} */ 2 | module.exports = { 3 | preset: "ts-jest", 4 | testEnvironment: "node", 5 | }; 6 | -------------------------------------------------------------------------------- /src/config/config.ts: -------------------------------------------------------------------------------- 1 | import "dotenv/config"; 2 | 3 | export const APP_ENV = { 4 | NAME: process.env.APP_NAME ?? "ios-device-farm", 5 | PORT: process.env.PORT ?? 8000, 6 | WEBDRIVERAGENT_PROJECT: process.cwd() + "/ext/WebDriverAgent", 7 | GO_IOS: process.cwd() + "/node_modules/go-ios/dist/go-ios-darwin-amd64_darwin_amd64/ios", 8 | }; 9 | -------------------------------------------------------------------------------- /tests/wda.test.ts: -------------------------------------------------------------------------------- 1 | import "jest"; 2 | import WDA from "../src/modules/wda/wda"; 3 | import { Device } from "../src/schema/device"; 4 | 5 | const wda = new WDA({ udid: "0", name: "a", version: "" } as Device); 6 | 7 | describe("WDA Tests", () => { 8 | it("should initilize", () => { 9 | expect(wda.getDevice().udid).toEqual("0"); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /public/static/js/renderer/back.frame.js: -------------------------------------------------------------------------------- 1 | // BackFrame to hold the incoming frame 2 | class BackFrame { 3 | constructor() { 4 | this.blob = null; 5 | } 6 | 7 | swap(blob) { 8 | this.blob = blob; 9 | } 10 | 11 | consume() { 12 | const blob = this.blob; 13 | this.blob = null; 14 | return blob; 15 | } 16 | 17 | destroy() { 18 | this.consume(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "lib": ["es6"], 6 | "allowJs": true, 7 | "outDir": "build", 8 | "rootDir": "src", 9 | "strict": true, 10 | "noImplicitAny": true, 11 | "esModuleInterop": true, 12 | "resolveJsonModule": true 13 | }, 14 | "exclude": ["node_modules", "public", "test", "ext"], 15 | "include": ["src/**/*"] 16 | } 17 | -------------------------------------------------------------------------------- /public/static/js/events/button.events.js: -------------------------------------------------------------------------------- 1 | function homeButtonClick() { 2 | if (socket) { 3 | socket.emit("command", { udid: device.udid, cmd: "homescreen" }); 4 | } 5 | } 6 | 7 | function takeScreenshot() { 8 | if (socket) { 9 | socket.emit("command", { udid: device.udid, cmd: "homescreen" }); 10 | } 11 | } 12 | 13 | function actionSwitchApp() { 14 | if (socket) { 15 | socket.emit("command", { udid: device.udid, cmd: "homescreen" }); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { DeviceManager } from "./modules/device-management/device.manager"; 2 | import IDF from "./modules/idf"; 3 | import "./server/server"; 4 | 5 | /** 6 | * IDF contain global variables 7 | * It requires to persist data of connected devices 8 | * and its processes 9 | */ 10 | export var IDFMap = { 11 | client_map: new Map(), 12 | }; 13 | IDFMap.client_map = new Map(); 14 | 15 | /** 16 | * Maintain only one device manager 17 | */ 18 | DeviceManager.getInstance(); 19 | -------------------------------------------------------------------------------- /src/schema/device.type.ts: -------------------------------------------------------------------------------- 1 | export type Device = { 2 | id: number; 3 | name: string; 4 | udid: string; 5 | version: string; 6 | status: Status; 7 | dpr: number; 8 | height: number; 9 | width: number; 10 | }; 11 | 12 | export enum Status { 13 | AVAILABLE, 14 | BUSY, 15 | OFFLINE, 16 | } 17 | 18 | export const getDeviceVersion = (version: string) => { 19 | try { 20 | const parts = version.split("."); 21 | const firstPart = parts[0]; 22 | if (firstPart) { 23 | return parseInt(firstPart); 24 | } 25 | } catch (error) {} 26 | return 17; 27 | }; 28 | -------------------------------------------------------------------------------- /init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # variables 4 | TARGET_DIR="ext/WebDriverAgent" 5 | REPO_URL="https://github.com/AutoCodeStack/WebDriverAgent.git" 6 | 7 | # Check if the target directory exists 8 | if [ ! -d "$TARGET_DIR" ]; then 9 | echo "Directory $TARGET_DIR does not exist. Creating it..." 10 | mkdir -p "$TARGET_DIR" 11 | else 12 | echo "Directory $TARGET_DIR already exists." 13 | fi 14 | 15 | # Clone the repository into the target directory 16 | echo "Cloning the repository $REPO_URL into $TARGET_DIR..." 17 | git clone "$REPO_URL" "$TARGET_DIR" 18 | 19 | echo "Done!" -------------------------------------------------------------------------------- /public/static/css/device.button.css: -------------------------------------------------------------------------------- 1 | /* Include the CSS here */ 2 | .deviceButtonGroup { 3 | transition: all 0.2s ease; /* Smooth transitions for all changes */ 4 | outline: none; /* Remove the default focus outline */ 5 | height: 50px; 6 | width: 100%; 7 | } 8 | 9 | .deviceButtonGroup:active { 10 | box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3); /* Smaller shadow to simulate press */ 11 | transform: scale(0.98); /* Slightly scale down to give a press effect */ 12 | } 13 | 14 | .deviceButtonGroup:focus { 15 | box-shadow: 0 0 0 4px rgba(0, 123, 255, 0.5); /* Outline for focus indication */ 16 | transform: translateY(-1px); /* Slight lift effect on focus */ 17 | } 18 | -------------------------------------------------------------------------------- /src/schema/wda.types.ts: -------------------------------------------------------------------------------- 1 | enum WdaCommands { 2 | OPEN_URL = "open_url", 3 | TAP = "tap", 4 | TEXT_INPUT = "text_input", 5 | HOMESCREEN = "homescreen", 6 | SWIPE = "swipe", 7 | } 8 | 9 | export const buildCommand = (data: any): Command => { 10 | return { udid: data.udid, cmd: data.cmd as WdaCommands, values: data.data }; 11 | }; 12 | 13 | type Session = { 14 | sessionId: string; 15 | value: { 16 | sessionId: string; 17 | capabilities: { 18 | sdkVersion: string; 19 | device: string; 20 | }; 21 | }; 22 | }; 23 | 24 | type Command = { 25 | udid: string; 26 | cmd: WdaCommands; 27 | values: any; 28 | }; 29 | 30 | export { Session, WdaCommands, Command }; 31 | 32 | //udid 33 | // cmd 34 | -------------------------------------------------------------------------------- /public/static/js/socket/socket.io.js: -------------------------------------------------------------------------------- 1 | function connect(udid) { 2 | socket = io("http://localhost:9000"); 3 | const sockData = { udid: udid }; 4 | socket.on("connect", () => { 5 | socket.emit("devicePrepare", sockData, (data) => { 6 | console.log(data); 7 | renderLoop.start(); 8 | hideLoader(); 9 | canvasRect = canvas.getBoundingClientRect(); 10 | }); 11 | }); 12 | 13 | socket.on("message", (message) => { 14 | console.log(message); 15 | }); 16 | 17 | socket.on("imageFrame", (message) => { 18 | var blob = new Blob([message], { type: "image/jpeg" }); 19 | pipeline.push(blob); 20 | }); 21 | 22 | socket.on("disconnect", () => { 23 | renderLoop.stop(); 24 | pipeline.destroy(); 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /public/static/js/renderer/render.loop.js: -------------------------------------------------------------------------------- 1 | // RenderLoop to handle drawing frames onto the canvas 2 | class RenderLoop { 3 | constructor(pipeline, canvas) { 4 | this.timer = null; 5 | this.pipeline = pipeline; 6 | this.canvas = canvas; 7 | this.context = canvas.getContext("2d"); 8 | } 9 | 10 | start() { 11 | this.stop(); 12 | this.next(); 13 | } 14 | 15 | stop() { 16 | cancelAnimationFrame(this.timer); 17 | } 18 | 19 | next() { 20 | this.timer = requestAnimationFrame(() => this.run()); 21 | } 22 | 23 | run() { 24 | const frame = this.pipeline.consume(); 25 | if (frame) { 26 | this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); 27 | this.context.drawImage(frame.image, 0, 0, this.canvas.width, this.canvas.height); 28 | } 29 | this.next(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/modules/wda-control/wda-endpoints.ts: -------------------------------------------------------------------------------- 1 | export enum HttpMethod { 2 | GET = "GET", 3 | POST = "POST", 4 | DELETE = "DELETE", 5 | } 6 | 7 | export enum WdaEndpoints { 8 | CREATE_SESSION = "/session", 9 | DELETE_SESSION = "/session/:sessionId", 10 | OPEN_URL = "/session/:sessionId/url", 11 | ENTER_TEXT = "/session/:sessionId/wda/keys", 12 | CUSTOM_TAP = "/session/:sessionId/wda/custom/tap", 13 | WDA_HOMESCREEN = "/wda/homescreen", 14 | SWIPE = "/session/:sessionId/wda/custom/swipe", 15 | } 16 | 17 | export const getEndpoint = (endpoint: WdaEndpoints, params?: Record): string => { 18 | let endpointStr = endpoint as string; 19 | if (params) { 20 | Object.keys(params).forEach((key) => { 21 | endpointStr = endpointStr.replace(`:${key}`, params[key]); 22 | }); 23 | } 24 | return endpointStr; 25 | }; 26 | -------------------------------------------------------------------------------- /public/static/js/renderer/pipeline.js: -------------------------------------------------------------------------------- 1 | // Pipeline to manage the flow of frames 2 | class Pipeline { 3 | constructor() { 4 | this.back = new BackFrame(); 5 | this.mid = new FrontFrame("mid"); 6 | this.front = new FrontFrame("front"); 7 | } 8 | 9 | push(blob) { 10 | this.back.swap(blob); 11 | 12 | if (!this.mid.loading && !this.mid.loaded) { 13 | this.mid.load(this.back.consume()); 14 | } 15 | } 16 | 17 | consume() { 18 | if (this.mid.loaded) { 19 | const temp = this.mid; 20 | this.mid = this.front; 21 | this.front = temp; 22 | this.mid.load(this.back.consume()); 23 | } else if (!this.mid.loading) { 24 | this.mid.load(this.back.consume()); 25 | } 26 | 27 | return this.front.consume(); 28 | } 29 | 30 | destroy() { 31 | this.back.destroy(); 32 | this.mid.destroy(); 33 | this.front.destroy(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/modules/wda-control/wda-service.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosInstance, AxiosRequestConfig, Method } from "axios"; 2 | import { HttpMethod, WdaEndpoints, getEndpoint } from "./wda-endpoints"; 3 | 4 | class WdaService { 5 | axiosInstance: AxiosInstance; 6 | 7 | constructor(port: number) { 8 | const baseUrl = `http://localhost:${port}`; 9 | this.axiosInstance = axios.create({ baseURL: baseUrl, timeout: 10000 }); 10 | } 11 | 12 | apiCall = async (endpoint: WdaEndpoints, method: HttpMethod, data?: any, params?: any) => { 13 | try { 14 | const requestConfig: AxiosRequestConfig = { 15 | url: getEndpoint(endpoint, params), 16 | method: method, 17 | data: data, 18 | }; 19 | return await this.axiosInstance.request(requestConfig); 20 | } catch (error: Error | any) { 21 | return Promise.resolve(error.response); 22 | } 23 | }; 24 | } 25 | 26 | export { WdaService }; 27 | -------------------------------------------------------------------------------- /src/utils/cmd.utils.ts: -------------------------------------------------------------------------------- 1 | export const getTunnelCommandArgs = (udid: string, port: number) => { 2 | return ["forward", `--udid=${udid}`, `${port}`, `${port}`]; 3 | }; 4 | 5 | export const getXcodeBuildCommandArgs = (udid: string, controlPort: number, streamPort: number) => { 6 | return ["test", "-scheme", "WebDriverAgentRunner", "-destination", `id=${udid}`, `USE_PORT=${controlPort}`, `MJPEG_SERVER_PORT=${streamPort}`]; 7 | }; 8 | 9 | export const getRunTestCommandArgs = (udid: string, controlPort: number, streamPort: number) => { 10 | return [ 11 | "runwda", 12 | "--bundleid=com.extrabits.WebDriverAgentRunner.xctrunner", 13 | "--testrunnerbundleid=com.extrabits.WebDriverAgentRunner.xctrunner", 14 | "--xctestconfig=WebDriverAgentRunner.xctest", 15 | "--udid", 16 | udid, 17 | "--env", 18 | `USE_PORT=${controlPort}`, 19 | "--env", 20 | `MJPEG_SERVER_PORT=${streamPort}`, 21 | ]; 22 | }; 23 | -------------------------------------------------------------------------------- /src/server/server.ts: -------------------------------------------------------------------------------- 1 | import express, { Request, Response } from "express"; 2 | import { Server as SocketIOServer } from "socket.io"; 3 | import http from "http"; 4 | import logger from "../config/logger"; 5 | import { initializeSocket } from "./sock.io"; 6 | import deviceRoute from "../routes/device.routes"; 7 | import { APP_ENV } from "../config/config"; 8 | 9 | const app = express(); 10 | const server: http.Server = http.createServer(app); 11 | const io = new SocketIOServer(server); 12 | 13 | app.use(express.static("public")); 14 | 15 | app.get("/", (req: Request, res: Response) => { 16 | res.sendFile(__dirname + "/index.html"); 17 | }); 18 | 19 | app.use("/api/device", deviceRoute); 20 | 21 | server.on("error", (error) => { 22 | logger.error(`Server error: ${error.message}`); 23 | }); 24 | 25 | server.listen(APP_ENV.PORT, () => { 26 | logger.info(`Server is listening on port ${APP_ENV.PORT}`); 27 | initializeSocket(io); 28 | }); 29 | -------------------------------------------------------------------------------- /src/config/logger.ts: -------------------------------------------------------------------------------- 1 | import { createLogger, format, transports, Logger } from "winston"; 2 | import * as path from "path"; 3 | 4 | const { combine, timestamp, printf, colorize } = format; 5 | 6 | // Define the custom format for log messages 7 | const logFormat = printf(({ level, message, timestamp }) => { 8 | return `${timestamp} [${level}]: ${message}`; 9 | }); 10 | 11 | // Initialize the logger 12 | const logger: Logger = createLogger({ 13 | level: "info", // Set the default log level 14 | format: combine(timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), logFormat), 15 | transports: [ 16 | new transports.Console({ 17 | format: combine(colorize(), logFormat), 18 | }), 19 | new transports.File({ 20 | filename: path.join(__dirname, "../../logs/error.log"), 21 | level: "error", 22 | }), 23 | new transports.File({ filename: path.join(__dirname, "../../logs/combined.log") }), 24 | ], 25 | exitOnError: false, // Do not exit on handled exceptions 26 | }); 27 | 28 | export default logger; 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 AutoCodeStack 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/routes/device.routes.ts: -------------------------------------------------------------------------------- 1 | //verifyLogin 2 | import Router, { Request, Response } from "express"; 3 | import logger from "../config/logger"; 4 | import { DeviceManager } from "../modules/device-management/device.manager"; 5 | 6 | const deviceRoute = Router(); 7 | 8 | deviceRoute.get("/list", async (req: Request, res: Response) => { 9 | try { 10 | const devices = await DeviceManager.getInstance().getDevices(); 11 | if (devices) { 12 | res.status(200).send({ devices: devices }); 13 | return; 14 | } 15 | } catch (error) { 16 | logger.error(error); 17 | logger.error(`error controller.getDevices`); 18 | } 19 | res.status(200).send({ devices: [] }); 20 | return; 21 | }); 22 | 23 | deviceRoute.put("/status/:udid/:status", async (req: Request, res: Response) => { 24 | try { 25 | const udid = req.params.udid; 26 | const status = req.params.status as unknown as number; 27 | // const device = DeviceManager.getInstance().getDevice(udid); 28 | // if (device && device.status !== 1) { 29 | // DeviceManager.getInstance().changeDeviceStatus(device.id, status); 30 | // res.send({ status: true }).status(200); 31 | // return; 32 | // } 33 | } catch (error) { 34 | logger.error(error); 35 | } 36 | res.send("").status(400); 37 | }); 38 | 39 | export default deviceRoute; 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ios-device-farm", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "npx nodemon", 8 | "build": "rimraf ./build && tsc", 9 | "start": "npm run build && node build/index.js", 10 | "test": "jest" 11 | }, 12 | "keywords": [], 13 | "author": "", 14 | "license": "ISC", 15 | "devDependencies": { 16 | "@types/axios": "^0.14.0", 17 | "@types/bluebird": "^3.5.42", 18 | "@types/busboy": "^1.5.3", 19 | "@types/express": "^4.17.21", 20 | "@types/jest": "^29.5.12", 21 | "@types/node": "^20.10.5", 22 | "@types/sharp": "^0.32.0", 23 | "@types/socket.io": "^3.0.2", 24 | "@types/teen_process": "^2.0.4", 25 | "@types/winston": "^2.4.4", 26 | "jest": "^29.7.0", 27 | "nodemon": "^3.0.2", 28 | "rimraf": "^5.0.5", 29 | "ts-jest": "^29.1.4", 30 | "ts-node": "^10.9.2", 31 | "typescript": "^5.4.5" 32 | }, 33 | "dependencies": { 34 | "applesign": "^5.0.0", 35 | "async-mutex": "^0.5.0", 36 | "axios": "^1.7.2", 37 | "bluebird": "^3.7.2", 38 | "busboy": "^1.6.0", 39 | "dotenv": "^16.4.5", 40 | "express": "^4.19.2", 41 | "find-free-ports": "^3.1.1", 42 | "go-ios": "^1.0.134", 43 | "sharp": "^0.33.4", 44 | "socket.io": "^4.7.5", 45 | "teen_process": "^2.1.3", 46 | "winston": "^3.13.0" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /public/static/js/renderer/front.frame.js: -------------------------------------------------------------------------------- 1 | // FrontFrame to manage image loading and rendering 2 | class FrontFrame { 3 | constructor(name) { 4 | this.name = name; 5 | this.blob = null; 6 | this.image = new Image(); 7 | this.url = null; 8 | this.loading = false; 9 | this.loaded = false; 10 | this.fresh = false; 11 | 12 | // Arrow functions automatically bind 'this' to the class instance 13 | this.image.onload = () => { 14 | this.loading = false; 15 | this.loaded = true; 16 | this.fresh = true; 17 | }; 18 | 19 | this.image.onerror = () => { 20 | this.loading = false; 21 | this.loaded = false; 22 | }; 23 | } 24 | 25 | load(blob) { 26 | // Reset before loading a new blob 27 | this.reset(); 28 | 29 | if (!blob) return; 30 | 31 | this.blob = blob; 32 | this.url = URL.createObjectURL(this.blob); 33 | this.loading = true; 34 | this.loaded = false; 35 | this.fresh = false; 36 | this.image.src = this.url; 37 | } 38 | 39 | reset() { 40 | this.loading = false; 41 | this.loaded = false; 42 | if (this.blob) { 43 | URL.revokeObjectURL(this.url); 44 | this.blob = null; 45 | this.url = null; 46 | } 47 | } 48 | 49 | consume() { 50 | if (!this.fresh) return null; 51 | this.fresh = false; 52 | return this; 53 | } 54 | 55 | destroy() { 56 | this.reset(); 57 | this.image = null; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/server/sock.io.ts: -------------------------------------------------------------------------------- 1 | import { Server as SocketIOServer, Socket } from "socket.io"; 2 | import logger from "../config/logger"; 3 | import { handleCommand, handleDestroy, handleDevicePrepare } from "./sock.handler"; 4 | 5 | // Function to initialize socket.io server and define event handlers 6 | export const initializeSocket = (io: SocketIOServer) => { 7 | io.on("connection", (socket: Socket) => { 8 | logger.info("New client connected", socket.id); 9 | 10 | socket.on("command", async (data: any, callback: Function) => { 11 | await handleCommand(socket, data, callback); 12 | }); 13 | 14 | socket.on("devicePrepare", async (data: any, callback: Function) => { 15 | await handleDevicePrepare(socket, data, callback); 16 | }); 17 | 18 | socket.on("disconnect", async (reason) => { 19 | logger.info(`Client disconnected ${socket.id}: ${reason}`); 20 | await handleDestroy(socket); 21 | }); 22 | 23 | socket.on("error", async (error: Error) => { 24 | logger.info(`[error] client error`); 25 | logger.info(error); 26 | await handleDestroy(socket); 27 | }); 28 | 29 | socket.on("connect_error", (err) => { 30 | logger.info(`Connect Error: ${err.message}`); 31 | }); 32 | }); 33 | 34 | io.on("error", (error: Error) => { 35 | logger.error("socker error occured"); 36 | logger.error(error); 37 | io.removeAllListeners(); 38 | }); 39 | 40 | io.on("disconnect", (error: Error) => { 41 | logger.error("socket disconnected"); 42 | logger.error(error); 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ios-device-farm 2 | 3 | # WORK IN PROGRESS :construction: 4 | 5 | # wait for full instruction to run 6 | 7 | Project Description - goes here 8 | 9 | ### Requirements 10 | 11 | - NodeJS 16+ 12 | - macOS 13 | - Xcode 13+ 14 | - iPhone Devices with Developer Mode Enabled [Enabling Developer Mode on a Device](https://developer.apple.com/documentation/xcode/enabling-developer-mode-on-a-device) 15 | 16 | > [!NOTE] 17 | > iPad is not supported as of now. 18 | 19 | ### Initialize 20 | 21 | Open terminal and perform following steps 22 | 23 | 1. clone this repository `git clone https://github.com/AutoCodeStack/ios-device-farm.git` 24 | 2. `cd ios-device-farm` 25 | 3. `sh init.sh` 26 | 27 | In order to run a WebDriverAgent on iphone devices we need to setup/build for the first time. If you are familiar with Xcode and Signing Capabilities then you do it. Othewise follow below process to configure. 28 | 29 | [Real Device Configuration](https://github.com/appium/appium-xcuitest-driver/blob/master/docs/preparation/real-device-config.md) 30 | 31 | You can find WebDriverAgent project under below repo only after Initialize command completed 32 | 33 | `./ext/WebDriverAgent/WebDriverAgent.xcodeproj` 34 | 35 | ### Build 36 | 37 | ```nodejs 38 | npm install 39 | ``` 40 | 41 | ### Run 42 | 43 | ```nodejs 44 | npm run start 45 | ``` 46 | 47 | Now connect a iphone and open http://localhost:9000 in your browser. 48 | 49 | ![ios-device-farm](https://github.com/AutoCodeStack/ios-device-farm/blob/main/images/idf-screenshot-01.png) 50 | -------------------------------------------------------------------------------- /public/static/js/events/canvas.events.js: -------------------------------------------------------------------------------- 1 | function tapListener(event, target) { 2 | const x = event.clientX; 3 | const y = event.clientY; 4 | const rect = canvas.getBoundingClientRect(); 5 | const canvasX = x - rect.left; 6 | const canvasY = y - rect.top; 7 | const scaledCoordinates = scaler(canvasWidth, canvasHeight, canvasX, canvasY, device.width, device.height); 8 | socket.emit("command", { udid: device.udid, cmd: "tap", data: { x: scaledCoordinates.xp, y: scaledCoordinates.yp } }); 9 | } 10 | 11 | function swipeListener(event, direction, distance, duration, fingerCount, fingerData) { 12 | const rect = canvas.getBoundingClientRect(); 13 | const canvasStartX = fingerData[0].start.x - rect.left; 14 | const canvasStartY = fingerData[0].start.y - rect.top; 15 | 16 | const canvasEndX = fingerData[0].end.x - rect.left; 17 | const canvasEndY = fingerData[0].end.y - rect.top; 18 | 19 | const scaledCoordinatesStart = scaler(canvasWidth, canvasHeight, canvasStartX, canvasStartY, device.width, device.height); 20 | const scaledCoordinatesEnd = scaler(canvasWidth, canvasHeight, canvasEndX, canvasEndY, device.width, device.height); 21 | 22 | socket.emit("command", { 23 | udid: device.udid, 24 | cmd: "swipe", 25 | data: { 26 | velocity: 0.5, 27 | x1: scaledCoordinatesStart.xp, 28 | y1: scaledCoordinatesStart.yp, 29 | x2: scaledCoordinatesEnd.xp, 30 | y2: scaledCoordinatesEnd.yp, 31 | }, 32 | }); 33 | } 34 | 35 | function scaler(bW, bH, x, y, rW, rH) { 36 | x = (x / bW) * rW; 37 | y = (y / bH) * rH; 38 | return { xp: Math.floor(x), yp: Math.floor(y) }; 39 | } 40 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Login 01 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
DeviceUDIDVersion#
28 |
29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/modules/tunnel/tunnel.manager.ts: -------------------------------------------------------------------------------- 1 | import { SubProcess } from "teen_process"; 2 | import logger from "../../config/logger"; 3 | import { APP_ENV } from "../../config/config"; 4 | import EventEmitter from "events"; 5 | import { getTunnelCommandArgs } from "../../utils/cmd.utils"; 6 | 7 | class TunnelManager extends EventEmitter { 8 | private udid: string; 9 | private controlProc?: SubProcess; 10 | private streamProc?: SubProcess; 11 | 12 | constructor(udid: string) { 13 | super(); 14 | this.udid = udid; 15 | } 16 | 17 | async startControlTunnel(port: number): Promise { 18 | const [proc, sd] = this.createTunnelProcess(port); 19 | this.controlProc = proc; 20 | return await this.controlProc.start(sd, 60000); 21 | } 22 | 23 | async startStreamTunnel(port: number): Promise { 24 | const [proc, sd] = this.createTunnelProcess(port); 25 | this.streamProc = proc; 26 | return this.streamProc.start(sd, 60000); 27 | } 28 | 29 | private createTunnelProcess(port: number): [SubProcess, any] { 30 | const match = `Start listening on port ${port} forwarding to port ${port} on device`; 31 | const proc = new SubProcess(APP_ENV.GO_IOS, getTunnelCommandArgs(this.udid, port)); 32 | proc.on("die", this.onTunnelDie); 33 | const sd = (stdout: string, stderr: string) => stderr.includes(match); 34 | return [proc, sd]; 35 | } 36 | 37 | async stopTunnels(): Promise { 38 | if (this.controlProc) { 39 | await this.controlProc.stop("SIGINT"); 40 | logger.info("Tunnel process stopped successfully."); 41 | this.removeListeners(this.controlProc); 42 | } 43 | 44 | if (this.streamProc) { 45 | await this.streamProc.stop("SIGINT"); 46 | logger.info("Mjpeg Tunnel process stopped successfully."); 47 | this.removeListeners(this.streamProc); 48 | } 49 | } 50 | 51 | removeListeners(p?: SubProcess): void { 52 | p?.removeAllListeners("die"); 53 | } 54 | 55 | private onTunnelDie = async (code: number, signal: NodeJS.Signals) => { 56 | this.emit("tunnel_die", code, signal); 57 | }; 58 | } 59 | 60 | export { TunnelManager }; 61 | -------------------------------------------------------------------------------- /public/static/js/device.js: -------------------------------------------------------------------------------- 1 | var device = null; 2 | var ratio; 3 | var canvasHeight; 4 | var canvasWidth; 5 | var canvasRect; 6 | 7 | var pipeline = new Pipeline(); 8 | var canvas = document.getElementById("screen"); 9 | var renderLoop = new RenderLoop(pipeline, canvas); 10 | var socket = null; 11 | 12 | window.addEventListener("message", (event) => { 13 | device = event.data; 14 | if (device.udid === undefined || device.udid === null) { 15 | window.location.assign("../index.html"); 16 | } 17 | ratio = device.width / device.height; 18 | canvasHeight = window.innerHeight - 100; 19 | canvasWidth = canvasHeight * ratio; 20 | 21 | var canvas = document.getElementById("screen"); 22 | canvas.width = canvasWidth * device.dpr; 23 | canvas.height = canvasHeight * device.dpr; 24 | canvas.style.width = `${canvasWidth}px`; 25 | canvas.style.height = `${canvasHeight}px`; 26 | 27 | initlize(); 28 | }); 29 | 30 | window.addEventListener("resize", () => { 31 | canvasHeight = window.innerHeight - 100; 32 | canvasWidth = canvasHeight * ratio; 33 | canvas.width = canvasWidth * device.dpr; 34 | canvas.height = canvasHeight * device.dpr; 35 | canvas.style.width = `${canvasWidth}px`; 36 | canvas.style.height = `${canvasHeight}px`; 37 | canvasRect = canvas.getBoundingClientRect(); 38 | }); 39 | 40 | function initlize() { 41 | showLoader("Preparing Device"); 42 | connect(device.udid); 43 | $("#device_name").text(device.name); 44 | $("#screen").swipe({ swipe: swipeListener, tap: tapListener }); 45 | } 46 | 47 | function showLoader(text) { 48 | $(".loader-background").css("display", "block"); 49 | $(".loader").css("display", "block"); 50 | $("#main").css("display", "none"); 51 | $("#loader-text").text(text); 52 | } 53 | 54 | function hideLoader() { 55 | $(".loader-background").css("display", "none"); 56 | $(".loader").css("display", "none"); 57 | $("#main").css("display", "block"); 58 | } 59 | 60 | $("#screen").mouseenter(function () { 61 | $("#screen").css("cursor", "crosshair"); 62 | }); 63 | $("#screen").mouseleave(function () { 64 | $("#screen").css("cursor", "default"); 65 | }); 66 | -------------------------------------------------------------------------------- /src/server/sock.handler.ts: -------------------------------------------------------------------------------- 1 | import { Socket } from "socket.io"; 2 | import { IDFMap } from ".."; 3 | import logger from "../config/logger"; 4 | import IDF from "../modules/idf"; 5 | import { DeviceManager } from "../modules/device-management/device.manager"; 6 | 7 | const handleCommand = async (socket: Socket, data: any, callback: Function) => { 8 | try { 9 | const ideviceFarm = IDFMap.client_map.get(socket.id); 10 | if (ideviceFarm) { 11 | await ideviceFarm.sendCommand(data); 12 | return; 13 | } 14 | } catch (error: Error | any) { 15 | logger.error(`Error fetching devices from device manager`); 16 | return; 17 | } 18 | }; 19 | 20 | const handleDevicePrepare = async (socket: Socket, data: any, callback: Function) => { 21 | try { 22 | const udid = data.udid; 23 | if (udid) { 24 | const device = DeviceManager.getInstance().getDeviceByUdid(udid); 25 | if (device) { 26 | DeviceManager.getInstance().markDeviceAsBusy(device.udid); 27 | const ideviceFarm = new IDF(device.udid, device.version, socket); 28 | await ideviceFarm.start(); 29 | IDFMap.client_map.set(socket.id, ideviceFarm); 30 | callback(sock_response(true, "successfully created client")); 31 | return; 32 | } else { 33 | logger.error(`Error fetching devices from device manager`); 34 | } 35 | } else { 36 | logger.error(`Error fetching devices from device manager`); 37 | callback(sock_response(true, "please send udid along with other params")); 38 | return; 39 | } 40 | } catch (error: Error | any) { 41 | logger.error(`Error generated in onPrepare`, error); 42 | } 43 | callback(sock_response(false, "there was an error occured, please connect with developer")); 44 | }; 45 | 46 | const handleDestroy = async (socket: Socket) => { 47 | try { 48 | const ideviceFarm = IDFMap.client_map.get(socket.id); 49 | if (ideviceFarm) { 50 | DeviceManager.getInstance().markDeviceAsAvailable(ideviceFarm.udid); 51 | await ideviceFarm.stop(); 52 | IDFMap.client_map.delete(socket.id); 53 | } 54 | } catch (error: Error | any) { 55 | logger.error(`Error generated in handleDestroy`); 56 | logger.error(error); 57 | } 58 | }; 59 | 60 | const sock_response = (status: boolean, msg: string) => { 61 | return { status: status, msg: msg }; 62 | }; 63 | 64 | export { handleCommand, handleDevicePrepare, handleDestroy }; 65 | -------------------------------------------------------------------------------- /src/modules/wda-control/wda.go.ios.ts: -------------------------------------------------------------------------------- 1 | import { SubProcess } from "teen_process"; 2 | import { getRunTestCommandArgs } from "../../utils/cmd.utils"; 3 | import { APP_ENV } from "../../config/config"; 4 | import logger from "../../config/logger"; 5 | 6 | class WdaGoIOS { 7 | controlPort: number; 8 | streamPort: number; 9 | udid: string; 10 | version: number; 11 | private runWdaProc?: SubProcess; 12 | private tunnelProc?: SubProcess; 13 | 14 | constructor(udid: string, version: number, controlPort: number, streamPort: number) { 15 | this.udid = udid; 16 | this.version = version; 17 | this.controlPort = controlPort; 18 | this.streamPort = streamPort; 19 | } 20 | 21 | async start(): Promise { 22 | await this.startTunnel(); 23 | const args = getRunTestCommandArgs(this.udid, this.controlPort, this.streamPort); 24 | this.runWdaProc = new SubProcess(APP_ENV.GO_IOS, args); 25 | this.runWdaProc.on("output", (stdout, stderr) => { 26 | logger.error(`stderr: ${stderr}`); 27 | }); 28 | this.runWdaProc.on("die", this.onProcessDie); 29 | await this.runWdaProc.start(0); 30 | return await new Promise((f) => setTimeout(f, 5000)); 31 | } 32 | 33 | async startTunnel(): Promise { 34 | this.tunnelProc = new SubProcess(APP_ENV.GO_IOS, ["tunnel", "start", "--userspace", "--udid", this.udid]); 35 | this.tunnelProc.on("output", (stdout, stderr) => { 36 | logger.error(`stderr: ${stderr}`); 37 | }); 38 | this.tunnelProc.on("die", this.onProcessDie); 39 | await this.tunnelProc.start(0); 40 | await new Promise((f) => setTimeout(f, 5000)); 41 | } 42 | 43 | async stop(): Promise { 44 | if (this.tunnelProc) { 45 | await this.tunnelProc.stop("SIGINT"); 46 | logger.info("tunnel for device stopped successfully."); 47 | } 48 | 49 | if (this.runWdaProc) { 50 | await this.runWdaProc.stop("SIGINT"); 51 | logger.info("runwda process stopped"); 52 | this.removeListeners(); 53 | } 54 | } 55 | 56 | removeListeners(): void { 57 | if (this.tunnelProc) { 58 | this.tunnelProc.removeAllListeners(); 59 | } 60 | 61 | if (this.runWdaProc) { 62 | this.runWdaProc.removeAllListeners(); 63 | } 64 | } 65 | 66 | private onProcessDie = async (code: number, signal: NodeJS.Signals) => { 67 | logger.error(`runwda died ${code} ${signal}`); 68 | }; 69 | } 70 | 71 | export default WdaGoIOS; 72 | -------------------------------------------------------------------------------- /public/static/js/index.js: -------------------------------------------------------------------------------- 1 | var devices = null; 2 | $(() => { 3 | setInterval(() => { 4 | getDevices(); 5 | }, 2000); 6 | }); 7 | 8 | function getDevices() { 9 | const devicesListUri = "http://localhost:9000/api/device/list"; 10 | 11 | $.ajax({ 12 | url: devicesListUri, 13 | type: "GET", 14 | success: function (result) { 15 | const tbodyDevices = $("#tbody-devices"); 16 | tbodyDevices.empty(); // Clear existing device rows 17 | devices = result.devices; 18 | result.devices.forEach((device) => { 19 | const { name, udid, version, status } = device; 20 | const statusNumber = Number(status); 21 | 22 | let statusText, btnClass, disabled; 23 | 24 | switch (statusNumber) { 25 | case 0: 26 | statusText = "Use"; 27 | btnClass = "btn-success"; // Button color for "Use" status 28 | disabled = "enabled"; 29 | break; 30 | case 1: 31 | statusText = "Busy"; 32 | btnClass = "btn-danger"; // Button color for "Busy" status 33 | disabled = "disabled"; 34 | break; 35 | default: 36 | statusText = "Offline"; 37 | btnClass = "btn-secondary"; // Button color for "Offline" status 38 | disabled = "disabled"; 39 | break; 40 | } 41 | 42 | const tr = ` 43 | 44 | ${name} 45 | ${udid} 46 | ${version} 47 | 48 | 51 | 52 | `; 53 | 54 | tbodyDevices.append(tr); 55 | }); 56 | }, 57 | error: function (error) { 58 | console.error("Error fetching devices:", error); 59 | if (error.status === 401) { 60 | window.location.assign("/login"); 61 | } else { 62 | alert("Failed to fetch devices. Please try again later."); 63 | } 64 | }, 65 | }); 66 | } 67 | 68 | function redirectToControl(element) { 69 | var $row = $(element).closest("tr"); 70 | var $udid = $row.find(".udid").text(); 71 | const selectedDevice = devices.find((device) => device.udid == $udid); 72 | const newWindow = window.open("/device.html", "_blank"); 73 | newWindow.addEventListener("load", () => { 74 | newWindow.postMessage(selectedDevice, "*"); 75 | }); 76 | } 77 | -------------------------------------------------------------------------------- /src/modules/wda-stream/wda.stream.ts: -------------------------------------------------------------------------------- 1 | import net from "net"; 2 | import { EventEmitter } from "events"; 3 | import MjpegParser from "./mjpeg.parser"; 4 | import logger from "../../config/logger"; 5 | 6 | class WdaStreamClient extends EventEmitter { 7 | private client: net.Socket | null = null; 8 | private consumer = new MjpegParser(); 9 | 10 | constructor() { 11 | super(); // Call the EventEmitter constructor 12 | } 13 | 14 | async connect(connectPort: number): Promise { 15 | if (this.client) { 16 | this.client.destroy(); // Clean up any existing connection 17 | } 18 | 19 | this.client = new net.Socket(); 20 | try { 21 | // Await the connection 22 | await new Promise((resolve, reject) => { 23 | this.client?.connect({ port: connectPort }, resolve); 24 | this.client?.on("error", reject); 25 | }); 26 | 27 | // Send initial message or perform initial action 28 | this.client.write("hello"); 29 | 30 | // Listen for data and emit events 31 | this.client.pipe(this.consumer).on("data", (data: Buffer) => { 32 | this.emit("data", data); // Emit data for async processing 33 | }); 34 | 35 | logger.info("Connected successfully"); 36 | } catch (err) { 37 | console.error("Connection error:", (err as Error).message); 38 | this.client?.destroy(); 39 | throw err; 40 | } 41 | } 42 | 43 | async waitForFirstData(): Promise { 44 | if (!this.client) { 45 | throw new Error("Client is not connected"); 46 | } 47 | 48 | return new Promise((resolve, reject) => { 49 | this.once("data", resolve); // Resolve with the first data chunk received 50 | this.once("error", reject); // Reject on error 51 | this.once("close", () => reject(new Error("Connection closed"))); // Reject if the connection is closed 52 | }); 53 | } 54 | 55 | async startProcessing(): Promise { 56 | try { 57 | const firstData = await this.waitForFirstData(); 58 | logger.info("tcp fetch started"); 59 | } catch (err) { 60 | console.error("Failed to start processing:", (err as Error).message); 61 | throw err; 62 | } 63 | } 64 | 65 | async handleContinuousStream(callback: (data: Buffer) => void): Promise { 66 | if (!this.client) { 67 | throw new Error("Client is not connected"); 68 | } 69 | this.on("data", callback); // Register the callback to handle each data chunk 70 | } 71 | 72 | async disconnect(): Promise { 73 | if (this.client) { 74 | this.client.destroy(); 75 | this.client = null; 76 | } 77 | } 78 | } 79 | 80 | export { WdaStreamClient }; 81 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | package-lock.json 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | build 94 | 95 | # Gatsby files 96 | .cache/ 97 | # Comment in the public line in if your project uses Gatsby and not Next.js 98 | # https://nextjs.org/blog/next-9-1#public-directory-support 99 | # public 100 | 101 | # vuepress build output 102 | .vuepress/dist 103 | 104 | # vuepress v2.x temp and cache directory 105 | .temp 106 | .cache 107 | 108 | # Docusaurus cache and generated files 109 | .docusaurus 110 | 111 | # Serverless directories 112 | .serverless/ 113 | 114 | # FuseBox cache 115 | .fusebox/ 116 | 117 | # DynamoDB Local files 118 | .dynamodb/ 119 | 120 | # TernJS port file 121 | .tern-port 122 | 123 | # Stores VSCode versions used for testing VSCode extensions 124 | .vscode-test 125 | 126 | # yarn v2 127 | .yarn/cache 128 | .yarn/unplugged 129 | .yarn/build-state.yml 130 | .yarn/install-state.gz 131 | .pnp.* 132 | 133 | #external 134 | ext 135 | 136 | -------------------------------------------------------------------------------- /src/modules/wda-stream/mjpeg.parser.ts: -------------------------------------------------------------------------------- 1 | // Import necessary modules and types 2 | import { Transform, TransformCallback, TransformOptions } from "stream"; 3 | import { Buffer } from "buffer"; 4 | import sharp from "sharp"; 5 | 6 | // Regex to find the Content-Length header in the HTTP response 7 | const lengthRegex = /Content-Length:\s*(\d+)/i; 8 | 9 | const soi = Buffer.from([0xff, 0xd8]); 10 | const eoi = Buffer.from([0xff, 0xd9]); 11 | 12 | // Define the class that extends the Transform stream 13 | class MjpegParser extends Transform { 14 | private buffer: Buffer | null = null; 15 | private reading: boolean = false; 16 | private contentLength: number | null = null; 17 | private bytesWritten: number = 0; 18 | 19 | constructor(options?: TransformOptions) { 20 | super(options); 21 | } 22 | 23 | private _initFrame(len: number, chunk: Buffer, start: number, end: number) { 24 | this.contentLength = len; 25 | this.buffer = Buffer.alloc(len); 26 | this.bytesWritten = 0; 27 | 28 | const hasStart = typeof start !== "undefined" && start > -1; 29 | const hasEnd = typeof end !== "undefined" && end > -1 && end > start; 30 | 31 | if (hasStart) { 32 | let bufEnd = chunk.length; 33 | 34 | if (hasEnd) { 35 | bufEnd = end + eoi.length; 36 | } 37 | 38 | chunk.copy(this.buffer, 0, start, bufEnd); 39 | this.bytesWritten = chunk.length - start; 40 | 41 | // If we have the EOI bytes, send the frame 42 | if (hasEnd) { 43 | this._sendFrame(); 44 | } else { 45 | this.reading = true; 46 | } 47 | } 48 | } 49 | 50 | private _readFrame(chunk: Buffer, start: number, end: number) { 51 | const bufStart = start > -1 && start < end ? start : 0; 52 | const bufEnd = end > -1 ? end + eoi.length : chunk.length; 53 | 54 | chunk.copy(this.buffer!, this.bytesWritten, bufStart, bufEnd); 55 | this.bytesWritten += bufEnd - bufStart; 56 | 57 | if (end > -1 || this.bytesWritten === this.contentLength) { 58 | this._sendFrame(); 59 | } else { 60 | this.reading = true; 61 | } 62 | } 63 | 64 | /** 65 | * Handle sending the frame to the next stream and resetting state 66 | */ 67 | private async _sendFrame() { 68 | this.reading = false; 69 | if (this.buffer) { 70 | sharp(this.buffer) 71 | .jpeg({ quality: 75 }) 72 | .toBuffer() 73 | .then((data: Buffer) => { 74 | this.push(data); 75 | }) 76 | .catch((err: any) => { 77 | console.log(err); 78 | }); 79 | } 80 | } 81 | 82 | _transform(chunk: Buffer, encoding: BufferEncoding, done: TransformCallback) { 83 | const start = chunk.indexOf(soi); 84 | const end = chunk.indexOf(eoi); 85 | const len = parseInt((lengthRegex.exec(chunk.toString("ascii")) || [])[1]); 86 | 87 | if (this.buffer && (this.reading || start > -1)) { 88 | this._readFrame(chunk, start, end); 89 | } 90 | 91 | if (len) { 92 | this._initFrame(len, chunk, start, end); 93 | } 94 | 95 | done(); 96 | } 97 | } 98 | 99 | export default MjpegParser; 100 | -------------------------------------------------------------------------------- /src/modules/wda-control/wda.control.ts: -------------------------------------------------------------------------------- 1 | import logger from "../../config/logger"; 2 | import { Command, Session, WdaCommands } from "../../schema/wda.types"; 3 | import { HttpMethod, WdaEndpoints } from "./wda-endpoints"; 4 | import { WdaService } from "./wda-service"; 5 | 6 | class WdaControlClient { 7 | service: WdaService; 8 | sessionId: string = "0"; 9 | 10 | constructor(port: number) { 11 | this.service = new WdaService(port); 12 | } 13 | 14 | async createWdaSession(): Promise { 15 | try { 16 | const postData = { capabilities: {} }; 17 | const response = await this.service.apiCall(WdaEndpoints.CREATE_SESSION, HttpMethod.POST, postData); 18 | const session: Session = response.data; 19 | if (session?.sessionId) { 20 | this.sessionId = session.sessionId; 21 | } else { 22 | throw new Error("Invalid session data received"); 23 | } 24 | } catch (error: any) { 25 | logger.error(`Failed to create WDA session: ${error.message || error}`); 26 | throw new Error("Failed to create WDA session"); 27 | } 28 | } 29 | 30 | async deleteWdaSession(): Promise { 31 | try { 32 | const response = await this.service.apiCall(WdaEndpoints.DELETE_SESSION, HttpMethod.DELETE, null, { sessionId: this.sessionId }); 33 | logger.info("WDA session deleted", response.data); 34 | const session: Session = response.data; 35 | if (session) { 36 | return session; 37 | } else { 38 | throw new Error(response.data?.value?.message || "Failed to delete WDA session"); 39 | } 40 | } catch (error: any) { 41 | logger.error(`Failed to delete WDA session: ${error.message || error}`); 42 | throw new Error("Failed to delete WDA session"); 43 | } finally { 44 | this.sessionId = "0"; 45 | } 46 | } 47 | 48 | async performCommand(command: Command): Promise<{ success: boolean }> { 49 | const params = { sessionId: this.sessionId }; 50 | try { 51 | let endpoint: WdaEndpoints; 52 | let method: HttpMethod; 53 | let postData: any = command.values; 54 | switch (command.cmd) { 55 | case WdaCommands.OPEN_URL: 56 | endpoint = WdaEndpoints.OPEN_URL; 57 | method = HttpMethod.POST; 58 | break; 59 | case WdaCommands.TAP: 60 | endpoint = WdaEndpoints.CUSTOM_TAP; 61 | method = HttpMethod.POST; 62 | break; 63 | case WdaCommands.TEXT_INPUT: 64 | endpoint = WdaEndpoints.ENTER_TEXT; 65 | method = HttpMethod.POST; 66 | break; 67 | case WdaCommands.HOMESCREEN: 68 | console.log("homescreen"); 69 | endpoint = WdaEndpoints.WDA_HOMESCREEN; 70 | method = HttpMethod.POST; 71 | postData = null; // HOMESCREEN might not require data 72 | break; 73 | case WdaCommands.SWIPE: 74 | console.log("swipe"); 75 | endpoint = WdaEndpoints.SWIPE; 76 | method = HttpMethod.POST; 77 | break; 78 | default: 79 | logger.error("Unknown command"); 80 | return { success: false }; 81 | } 82 | 83 | const response = await this.service.apiCall(endpoint, method, postData, params); 84 | if (response.status === 200) { 85 | return { success: true }; 86 | } else { 87 | throw new Error(response.data?.value?.message || "Unknown command execution error"); 88 | } 89 | } catch (error: any) { 90 | logger.error(`Command execution failed: ${error.message || error}`); 91 | throw new Error(`Failed to execute command`); 92 | } 93 | } 94 | } 95 | 96 | export { WdaControlClient }; 97 | -------------------------------------------------------------------------------- /public/static/css/device.css: -------------------------------------------------------------------------------- 1 | .brc { 2 | border-radius: 0 !important; 3 | border-left-color: rgb(0, 74, 153) !important; 4 | } 5 | .nopadding { 6 | padding: 0 !important; 7 | margin: 0 !important; 8 | } 9 | 10 | .centerAlign { 11 | text-align: center; 12 | } 13 | 14 | .textPadding { 15 | padding: 15px; 16 | height: 50px; 17 | } 18 | 19 | .titleBar { 20 | height: 50px; 21 | } 22 | 23 | .primaryText { 24 | color: white; 25 | } 26 | 27 | .primaryBackground { 28 | background-color: #282828; 29 | } 30 | 31 | .fixedScreen { 32 | width: 480px; 33 | text-align: center; 34 | margin-bottom: 0 !important; 35 | } 36 | 37 | .loader { 38 | border: 2px solid #f3f3f3; 39 | border-radius: 50%; 40 | border-top: 2px solid #fd2020; 41 | width: 80px; 42 | height: 80px; 43 | -webkit-animation: spin 2s linear infinite; /* Safari */ 44 | animation: spin 2s linear infinite; 45 | left: calc(50% - 40px); 46 | position: relative; 47 | } 48 | 49 | .loader-background { 50 | width: 400px; 51 | height: 100px; 52 | top: calc(50% - 50px); 53 | left: calc(50% - 200px); 54 | position: fixed; 55 | } 56 | 57 | .p-bg { 58 | background-color: white; 59 | } 60 | 61 | .s-bg { 62 | background-color: rgb(245, 245, 247); 63 | } 64 | 65 | .p-card-bg { 66 | background-color: #282828; 67 | color: white; 68 | } 69 | 70 | /* Safari */ 71 | @-webkit-keyframes spin { 72 | 0% { 73 | -webkit-transform: rotate(0deg); 74 | } 75 | 100% { 76 | -webkit-transform: rotate(360deg); 77 | } 78 | } 79 | 80 | @keyframes spin { 81 | 0% { 82 | transform: rotate(0deg); 83 | } 84 | 100% { 85 | transform: rotate(360deg); 86 | } 87 | } 88 | 89 | .canvasScreen { 90 | image-rendering: optimizeQuality; 91 | } 92 | 93 | .normalText { 94 | color: #f3f3f3; 95 | } 96 | 97 | input { 98 | --c: orange; /* active color */ 99 | --g: 8px; /* the gap */ 100 | --l: 1px; /* line thickness*/ 101 | --s: 15px; /* thumb size*/ 102 | 103 | width: 100%; 104 | height: var(--s); /* needed for Firefox*/ 105 | --_c: color-mix(in srgb, var(--c), #000 var(--p, 0%)); 106 | -webkit-appearance: none; 107 | -moz-appearance: none; 108 | appearance: none; 109 | background: none; 110 | cursor: pointer; 111 | overflow: hidden; 112 | } 113 | input:focus-visible, 114 | input:hover { 115 | --p: 25%; 116 | } 117 | input:active, 118 | input:focus-visible { 119 | --_b: var(--s); 120 | } 121 | /* chromium */ 122 | input[type="range" i]::-webkit-slider-thumb { 123 | height: var(--s); 124 | aspect-ratio: 1; 125 | border-radius: 50%; 126 | box-shadow: 0 0 0 var(--_b, var(--l)) inset var(--_c); 127 | border-image: linear-gradient(90deg, var(--_c) 50%, #ababab 0) 1/0 100vw/0 calc(100vw + var(--g)); 128 | clip-path: polygon(0 calc(50% + var(--l) / 2), -100vw calc(50% + var(--l) / 2), -100vw calc(50% - var(--l) / 2), 0 calc(50% - var(--l) / 2), 0 0, 100% 0, 100% calc(50% - var(--l) / 2), 100vw calc(50% - var(--l) / 2), 100vw calc(50% + var(--l) / 2), 100% calc(50% + var(--l) / 2), 100% 100%, 0 100%); 129 | -webkit-appearance: none; 130 | appearance: none; 131 | transition: 0.3s; 132 | } 133 | /* Firefox */ 134 | input[type="range"]::-moz-range-thumb { 135 | height: var(--s); 136 | width: var(--s); 137 | background: none; 138 | border-radius: 50%; 139 | box-shadow: 0 0 0 var(--_b, var(--l)) inset var(--_c); 140 | border-image: linear-gradient(90deg, var(--_c) 50%, #ababab 0) 1/0 100vw/0 calc(100vw + var(--g)); 141 | clip-path: polygon(0 calc(50% + var(--l) / 2), -100vw calc(50% + var(--l) / 2), -100vw calc(50% - var(--l) / 2), 0 calc(50% - var(--l) / 2), 0 0, 100% 0, 100% calc(50% - var(--l) / 2), 100vw calc(50% - var(--l) / 2), 100vw calc(50% + var(--l) / 2), 100% calc(50% + var(--l) / 2), 100% 100%, 0 100%); 142 | -moz-appearance: none; 143 | appearance: none; 144 | transition: 0.3s; 145 | } 146 | @supports not (color: color-mix(in srgb, red, red)) { 147 | input { 148 | --_c: var(--c); 149 | } 150 | } 151 | 152 | .right-text-alignment { 153 | text-align: right; 154 | } 155 | 156 | .card-container { 157 | margin-top: 10px; 158 | } 159 | 160 | .icon-button { 161 | margin-right: 15px; 162 | width: 35px; 163 | height: 35px; 164 | padding: 0; 165 | border: none; 166 | background: rgba(0, 0, 0, 0); 167 | } 168 | 169 | .p-border-icon { 170 | width: 100%; 171 | height: 100%; 172 | overflow: hidden; 173 | border-radius: 8px !important; 174 | border-width: 0.5px; 175 | } 176 | 177 | .input-file { 178 | display: block; 179 | } 180 | -------------------------------------------------------------------------------- /src/modules/idf.ts: -------------------------------------------------------------------------------- 1 | import findFreePorts from "find-free-ports"; 2 | import { TunnelManager } from "./tunnel/tunnel.manager"; 3 | import { WdaControlClient } from "./wda-control/wda.control"; 4 | import { WdaStreamClient } from "./wda-stream/wda.stream"; 5 | import logger from "../config/logger"; 6 | import { Socket } from "socket.io"; 7 | import { buildCommand } from "../schema/wda.types"; 8 | import { SubProcess } from "teen_process"; 9 | import WdaGoIOS from "./wda-control/wda.go.ios"; 10 | import { getDeviceVersion } from "../schema/device.type"; 11 | 12 | class IDF { 13 | tunnelManager: TunnelManager; 14 | wdaStreamClient: WdaStreamClient; 15 | wdaControlClient?: WdaControlClient; 16 | wdaGoIOS?: WdaGoIOS; 17 | 18 | udid: string; 19 | version: number; 20 | socketClient: Socket; 21 | 22 | controlPort?: number; 23 | streamPort?: number; 24 | 25 | streamClient?: SubProcess; 26 | 27 | constructor(udid: string, version: string, socket: Socket) { 28 | this.socketClient = socket; 29 | this.udid = udid; 30 | this.tunnelManager = new TunnelManager(udid); 31 | this.wdaStreamClient = new WdaStreamClient(); 32 | this.version = getDeviceVersion(version); 33 | } 34 | 35 | getPorts() { 36 | return [this.controlPort, this.streamPort]; 37 | } 38 | 39 | async sendCommand(data: any) { 40 | logger.info(`send command ${JSON.stringify(data)}`); 41 | try { 42 | if (this.wdaControlClient) { 43 | const cmd = buildCommand(data); 44 | await this.wdaControlClient.performCommand(cmd); 45 | } 46 | } catch (error) { 47 | logger.error(`error in send command`, error); 48 | } 49 | } 50 | 51 | async start() { 52 | const [controlPort, streamPort] = await findFreePorts(2); 53 | this.controlPort = controlPort; 54 | this.streamPort = streamPort; 55 | /** 56 | * start tunnel for control port 57 | */ 58 | try { 59 | await this.tunnelManager.startControlTunnel(controlPort); 60 | } catch (error) { 61 | logger.error(`error start tunnel for control port`, error); 62 | await this.stop(); 63 | return false; 64 | } 65 | 66 | /** 67 | * start tunnel for stream port 68 | */ 69 | try { 70 | await this.tunnelManager.startStreamTunnel(streamPort); 71 | } catch (error) { 72 | logger.error(`error start tunnel for stream port`, error); 73 | await this.stop(); 74 | return false; 75 | } 76 | 77 | /** 78 | * start webdriveragent 79 | */ 80 | try { 81 | this.wdaGoIOS = new WdaGoIOS(this.udid, this.version, controlPort, streamPort); 82 | await this.wdaGoIOS.start(); 83 | } catch (error) { 84 | logger.error(`error start tunnel for stream port`, error); 85 | await this.stop(); 86 | return false; 87 | } 88 | 89 | /** 90 | * start stream 91 | */ 92 | try { 93 | await this.wdaStreamClient.connect(streamPort); 94 | await this.wdaStreamClient.startProcessing(); 95 | } catch (error) { 96 | logger.error(`error start tunnel for stream port`, error); 97 | await this.stop(); 98 | return false; 99 | } 100 | 101 | /** 102 | * start wda control 103 | */ 104 | try { 105 | this.wdaControlClient = new WdaControlClient(controlPort); 106 | await this.wdaControlClient.createWdaSession(); 107 | } catch (error) { 108 | logger.error(`error creating wda control client`, error); 109 | await this.stop(); 110 | return false; 111 | } 112 | 113 | /** 114 | * setup listeners now and send data to socket 115 | */ 116 | this.tunnelManager?.on("tunnel_die", (code: number, signal: NodeJS.Signals) => { 117 | logger.info(`tunnel process died due to ${code} - ${signal}`); 118 | }); 119 | 120 | this.wdaStreamClient?.on("data", (data: any) => { 121 | if (this.socketClient.connected) { 122 | this.socketClient.emit("imageFrame", data); 123 | } 124 | }); 125 | 126 | // this.wdaGoIOS.on("webdriver_died", (code: number, signal: NodeJS.Signals) => { 127 | // logger.info(`webdriveragent died due to ${code} - ${signal}`); 128 | // }); 129 | } 130 | 131 | async stop() { 132 | try { 133 | await this.wdaControlClient?.deleteWdaSession(); 134 | } catch (error) { 135 | logger.error(`error in stop wda control client deleteWdaSession`, error); 136 | } 137 | 138 | try { 139 | await this.wdaGoIOS?.stop(); 140 | } catch (error) { 141 | logger.error(`error in stop webdriveragent stopAll`, error); 142 | } 143 | 144 | try { 145 | await this.wdaStreamClient.disconnect(); 146 | } catch (error) { 147 | logger.error(`error in stop wda stream client disconnect`, error); 148 | } 149 | 150 | try { 151 | await this.tunnelManager.stopTunnels(); 152 | } catch (error) { 153 | logger.error(`error in stop tunnels stopAll`, error); 154 | } 155 | 156 | this.removeListeners(); 157 | } 158 | 159 | removeListeners(): void { 160 | if (this.tunnelManager) { 161 | this.tunnelManager.removeAllListeners(); 162 | } 163 | 164 | if (this.wdaGoIOS) { 165 | this.wdaGoIOS.removeListeners(); 166 | } 167 | 168 | if (this.wdaStreamClient) { 169 | this.wdaStreamClient.removeAllListeners(); 170 | } 171 | } 172 | } 173 | 174 | export default IDF; 175 | -------------------------------------------------------------------------------- /src/modules/device-management/device.manager.ts: -------------------------------------------------------------------------------- 1 | import { SubProcess } from "teen_process"; 2 | import { Mutex } from "async-mutex"; 3 | import { Device, Status } from "../../schema/device.type"; 4 | import logger from "../../config/logger"; 5 | import { getDeviceName, getDeviceSize } from "../../utils/device.utils"; 6 | import { exec } from "teen_process"; 7 | import { APP_ENV } from "../../config/config"; 8 | 9 | class DeviceManager { 10 | private static instance: DeviceManager; 11 | private devices: Map = new Map(); 12 | private mutex = new Mutex(); 13 | iosListenProcess = new SubProcess("ios", ["listen"]); 14 | 15 | constructor() { 16 | this.listenToDeviceEvents(); 17 | } 18 | 19 | public static getInstance(): DeviceManager { 20 | if (!DeviceManager.instance) { 21 | DeviceManager.instance = new DeviceManager(); 22 | } 23 | return DeviceManager.instance; 24 | } 25 | 26 | private async attachedEvent(deviceId: number, properties: any) { 27 | const release = await this.mutex.acquire(); 28 | try { 29 | const udid = properties.SerialNumber; 30 | let device = this.devices.get(udid); 31 | if (device) { 32 | device.id = deviceId; 33 | device.status = Status.AVAILABLE; 34 | } else { 35 | const deviceSize = getDeviceSize(properties.productType); 36 | device = { 37 | id: deviceId, 38 | name: getDeviceName(properties.productType), 39 | udid: udid, 40 | version: properties.version, 41 | status: Status.AVAILABLE, 42 | dpr: deviceSize.dpr, 43 | height: deviceSize.viewportHeight, 44 | width: deviceSize.viewportWidth, 45 | }; 46 | this.devices.set(udid, device); 47 | } 48 | logger.info(`Device (${device.udid}) is now available`); 49 | } finally { 50 | release(); 51 | } 52 | } 53 | 54 | private async datachedEvent(deviceId: number) { 55 | const release = await this.mutex.acquire(); 56 | try { 57 | let device = this.getDeviceById(deviceId); 58 | if (device) { 59 | device.status = Status.OFFLINE; 60 | logger.info(`Device (${device?.udid}) is offline`); 61 | } else { 62 | logger.error(`Device (${deviceId}) was not found`); 63 | } 64 | } finally { 65 | release(); 66 | } 67 | } 68 | 69 | public async markDeviceAsBusy(udid: string): Promise { 70 | const release = await this.mutex.acquire(); 71 | try { 72 | const device = this.getDeviceByUdid(udid); 73 | if (device) { 74 | device.status = Status.BUSY; 75 | logger.info(`Device ${udid} (${device.udid}) is now busy`); 76 | } else { 77 | logger.error(`Device ${udid} not found`); 78 | } 79 | } finally { 80 | release(); 81 | } 82 | } 83 | 84 | public async markDeviceAsAvailable(udid: string): Promise { 85 | const release = await this.mutex.acquire(); 86 | try { 87 | const device = this.getDeviceByUdid(udid); 88 | if (device) { 89 | device.status = Status.AVAILABLE; 90 | logger.info(`Device ${udid} (${device.udid}) is now available`); 91 | } else { 92 | logger.error(`Device ${udid} not found`); 93 | } 94 | } finally { 95 | release(); 96 | } 97 | } 98 | 99 | public getDevices(): Device[] { 100 | return Array.from(this.devices.values()); 101 | } 102 | 103 | public getDeviceByUdid(udid: string): Device | undefined { 104 | return Array.from(this.devices.values()).find((device) => device.udid === udid); 105 | } 106 | 107 | public getDeviceById(id: number): Device | undefined { 108 | return Array.from(this.devices.values()).find((device) => device.id === id); 109 | } 110 | 111 | private async listenToDeviceEvents() { 112 | this.iosListenProcess.on("lines-stdout", (lines: string[]) => { 113 | lines.forEach((line) => this.handleEvent(line)); 114 | }); 115 | 116 | this.iosListenProcess.on("lines-stderr", (lines: string[]) => { 117 | lines.forEach((line) => logger.warn(`Error: ${line}`)); 118 | }); 119 | 120 | this.iosListenProcess.on("exit", (code: number, signal: string) => { 121 | logger.info(`ios listen process exited with code ${code} from signal ${signal}`); 122 | }); 123 | 124 | try { 125 | await this.iosListenProcess.start(); 126 | } catch (error) { 127 | logger.error(`Failed to start ios listen process: ${error}`); 128 | } 129 | } 130 | 131 | private async handleEvent(line: string) { 132 | try { 133 | const eventData = JSON.parse(line); 134 | const { MessageType, DeviceID, Properties } = eventData; 135 | if (MessageType === "Attached") { 136 | let { stdout, stderr, code } = await exec(APP_ENV.GO_IOS, ["info", "--udid", `${Properties.SerialNumber}`]); 137 | if (code == 0) { 138 | const deviceInfo = JSON.parse(stdout); 139 | Properties.version = deviceInfo.ProductVersion; 140 | Properties.productType = deviceInfo.ProductType; 141 | await this.attachedEvent(DeviceID, Properties); 142 | } 143 | } else if (MessageType === "Detached") { 144 | await this.datachedEvent(DeviceID); 145 | } else { 146 | logger.error(`Unknown event occured for device : ${MessageType}`); 147 | } 148 | } catch (error) { 149 | logger.error(`Failed to parse or handle event: ${line}, error: ${error}`); 150 | } 151 | } 152 | } 153 | 154 | export { DeviceManager }; 155 | -------------------------------------------------------------------------------- /src/utils/device.utils.ts: -------------------------------------------------------------------------------- 1 | type DeviceMap = { [key: string]: string }; 2 | 3 | const iPhoneModels: DeviceMap = { 4 | "iPhone1,1": "iPhone (Original)", 5 | "iPhone1,2": "iPhone 3G", 6 | "iPhone2,1": "iPhone 3GS", 7 | "iPhone3,1": "iPhone 4", 8 | "iPhone3,2": "iPhone 4", 9 | "iPhone3,3": "iPhone 4", 10 | "iPhone4,1": "iPhone 4S", 11 | "iPhone5,1": "iPhone 5", 12 | "iPhone5,2": "iPhone 5", 13 | "iPhone5,3": "iPhone 5c", 14 | "iPhone5,4": "iPhone 5c", 15 | "iPhone6,1": "iPhone 5s", 16 | "iPhone6,2": "iPhone 5s", 17 | "iPhone7,2": "iPhone 6", 18 | "iPhone7,1": "iPhone 6 Plus", 19 | "iPhone8,1": "iPhone 6s", 20 | "iPhone8,2": "iPhone 6s Plus", 21 | "iPhone8,4": "iPhone SE (1st generation)", 22 | "iPhone9,1": "iPhone 7", 23 | "iPhone9,3": "iPhone 7", 24 | "iPhone9,2": "iPhone 7 Plus", 25 | "iPhone9,4": "iPhone 7 Plus", 26 | "iPhone10,1": "iPhone 8", 27 | "iPhone10,4": "iPhone 8", 28 | "iPhone10,2": "iPhone 8 Plus", 29 | "iPhone10,5": "iPhone 8 Plus", 30 | "iPhone10,3": "iPhone X", 31 | "iPhone10,6": "iPhone X", 32 | "iPhone11,8": "iPhone XR", 33 | "iPhone11,2": "iPhone XS", 34 | "iPhone11,4": "iPhone XS Max", 35 | "iPhone11,6": "iPhone XS Max", 36 | "iPhone12,1": "iPhone 11", 37 | "iPhone12,3": "iPhone 11 Pro", 38 | "iPhone12,5": "iPhone 11 Pro Max", 39 | "iPhone12,8": "iPhone SE (2nd generation)", 40 | "iPhone13,1": "iPhone 12 Mini", 41 | "iPhone13,2": "iPhone 12", 42 | "iPhone13,3": "iPhone 12 Pro", 43 | "iPhone13,4": "iPhone 12 Pro Max", 44 | "iPhone14,4": "iPhone 13 Mini", 45 | "iPhone14,5": "iPhone 13", 46 | "iPhone14,2": "iPhone 13 Pro", 47 | "iPhone14,3": "iPhone 13 Pro Max", 48 | "iPhone14,6": "iPhone SE (3rd generation)", 49 | "iPhone14,7": "iPhone 14", 50 | "iPhone14,8": "iPhone 14 Plus", 51 | "iPhone15,2": "iPhone 14 Pro", 52 | "iPhone15,3": "iPhone 14 Pro Max", 53 | }; 54 | 55 | const iPadModels: DeviceMap = { 56 | "iPad1,1": "iPad (1st generation)", 57 | "iPad2,1": "iPad 2", 58 | "iPad2,2": "iPad 2", 59 | "iPad2,3": "iPad 2", 60 | "iPad2,4": "iPad 2", 61 | "iPad3,1": "iPad (3rd generation)", 62 | "iPad3,2": "iPad (3rd generation)", 63 | "iPad3,3": "iPad (3rd generation)", 64 | "iPad3,4": "iPad (4th generation)", 65 | "iPad3,5": "iPad (4th generation)", 66 | "iPad3,6": "iPad (4th generation)", 67 | "iPad4,1": "iPad Air", 68 | "iPad4,2": "iPad Air", 69 | "iPad4,3": "iPad Air", 70 | "iPad5,3": "iPad Air 2", 71 | "iPad5,4": "iPad Air 2", 72 | "iPad6,11": "iPad (5th generation)", 73 | "iPad6,12": "iPad (5th generation)", 74 | "iPad7,5": "iPad (6th generation)", 75 | "iPad7,6": "iPad (6th generation)", 76 | "iPad7,11": "iPad (7th generation)", 77 | "iPad7,12": "iPad (7th generation)", 78 | "iPad11,6": "iPad (8th generation)", 79 | "iPad11,7": "iPad (8th generation)", 80 | "iPad12,1": "iPad (9th generation)", 81 | "iPad12,2": "iPad (9th generation)", 82 | "iPad11,3": "iPad Air (3rd generation)", 83 | "iPad11,4": "iPad Air (3rd generation)", 84 | "iPad13,1": "iPad Air (4th generation)", 85 | "iPad13,2": "iPad Air (4th generation)", 86 | "iPad13,16": "iPad Air (5th generation)", 87 | "iPad13,17": "iPad Air (5th generation)", 88 | "iPad2,5": "iPad mini", 89 | "iPad2,6": "iPad mini", 90 | "iPad2,7": "iPad mini", 91 | "iPad4,4": "iPad mini 2", 92 | "iPad4,5": "iPad mini 2", 93 | "iPad4,6": "iPad mini 2", 94 | "iPad4,7": "iPad mini 3", 95 | "iPad4,8": "iPad mini 3", 96 | "iPad4,9": "iPad mini 3", 97 | "iPad5,1": "iPad mini 4", 98 | "iPad5,2": "iPad mini 4", 99 | "iPad11,1": "iPad mini (5th generation)", 100 | "iPad11,2": "iPad mini (5th generation)", 101 | "iPad14,1": "iPad mini (6th generation)", 102 | "iPad14,2": "iPad mini (6th generation)", 103 | "iPad6,3": "iPad Pro (9.7-inch)", 104 | "iPad6,4": "iPad Pro (9.7-inch)", 105 | "iPad7,3": "iPad Pro (10.5-inch)", 106 | "iPad7,4": "iPad Pro (10.5-inch)", 107 | "iPad8,1": "iPad Pro (11-inch) (1st generation)", 108 | "iPad8,2": "iPad Pro (11-inch) (1st generation)", 109 | "iPad8,3": "iPad Pro (11-inch) (1st generation)", 110 | "iPad8,4": "iPad Pro (11-inch) (1st generation)", 111 | "iPad8,9": "iPad Pro (11-inch) (2nd generation)", 112 | "iPad8,10": "iPad Pro (11-inch) (2nd generation)", 113 | "iPad13,4": "iPad Pro (11-inch) (3rd generation)", 114 | "iPad13,5": "iPad Pro (11-inch) (3rd generation)", 115 | "iPad13,6": "iPad Pro (11-inch) (3rd generation)", 116 | "iPad13,7": "iPad Pro (11-inch) (3rd generation)", 117 | "iPad14,3": "iPad Pro (11-inch) (4th generation)", 118 | "iPad14,4": "iPad Pro (11-inch) (4th generation)", 119 | "iPad6,7": "iPad Pro (12.9-inch) (1st generation)", 120 | "iPad6,8": "iPad Pro (12.9-inch) (1st generation)", 121 | "iPad7,1": "iPad Pro (12.9-inch) (2nd generation)", 122 | "iPad7,2": "iPad Pro (12.9-inch) (2nd generation)", 123 | "iPad8,5": "iPad Pro (12.9-inch) (3rd generation)", 124 | "iPad8,6": "iPad Pro (12.9-inch) (3rd generation)", 125 | "iPad8,7": "iPad Pro (12.9-inch) (3rd generation)", 126 | "iPad8,8": "iPad Pro (12.9-inch) (3rd generation)", 127 | "iPad8,11": "iPad Pro (12.9-inch) (4th generation)", 128 | "iPad8,12": "iPad Pro (12.9-inch) (4th generation)", 129 | "iPad13,8": "iPad Pro (12.9-inch) (5th generation)", 130 | "iPad13,9": "iPad Pro (12.9-inch) (5th generation)", 131 | "iPad13,10": "iPad Pro (12.9-inch) (5th generation)", 132 | "iPad13,11": "iPad Pro (12.9-inch) (5th generation)", 133 | "iPad14,5": "iPad Pro (12.9-inch) (6th generation)", 134 | "iPad14,6": "iPad Pro (12.9-inch) (6th generation)", 135 | }; 136 | 137 | export const getDeviceSize = (machineId: string) => { 138 | return iPhoneDevicesSizes[machineId] || { dpr: 3, viewportWidth: 430, viewportHeight: 932 }; 139 | }; 140 | 141 | const iPhoneDevicesSizes: { [key: string]: any } = { 142 | "iPhone8,4": { dpr: 2, viewportWidth: 320, viewportHeight: 568 }, // iPhone SE (1st Gen) 143 | "iPhone12,8": { dpr: 2, viewportWidth: 375, viewportHeight: 667 }, // iPhone SE (2nd Gen) 144 | "iPhone7,2": { dpr: 2, viewportWidth: 375, viewportHeight: 667 }, // iPhone 6 145 | "iPhone8,1": { dpr: 2, viewportWidth: 375, viewportHeight: 667 }, // iPhone 6s 146 | "iPhone9,3": { dpr: 2, viewportWidth: 375, viewportHeight: 667 }, // iPhone 7 147 | "iPhone10,1": { dpr: 2, viewportWidth: 375, viewportHeight: 667 }, // iPhone 8 148 | "iPhone7,1": { dpr: 3, viewportWidth: 414, viewportHeight: 736 }, // iPhone 6 Plus 149 | "iPhone8,2": { dpr: 3, viewportWidth: 414, viewportHeight: 736 }, // iPhone 6s Plus 150 | "iPhone9,4": { dpr: 3, viewportWidth: 414, viewportHeight: 736 }, // iPhone 7 Plus 151 | "iPhone10,2": { dpr: 3, viewportWidth: 414, viewportHeight: 736 }, // iPhone 8 Plus 152 | "iPhone10,3": { dpr: 3, viewportWidth: 375, viewportHeight: 812 }, // iPhone X 153 | "iPhone11,2": { dpr: 3, viewportWidth: 375, viewportHeight: 812 }, // iPhone XS 154 | "iPhone11,4": { dpr: 3, viewportWidth: 414, viewportHeight: 896 }, // iPhone XS Max 155 | "iPhone11,8": { dpr: 2, viewportWidth: 414, viewportHeight: 896 }, // iPhone XR 156 | "iPhone12,1": { dpr: 2, viewportWidth: 414, viewportHeight: 896 }, // iPhone 11 157 | "iPhone12,3": { dpr: 3, viewportWidth: 375, viewportHeight: 812 }, // iPhone 11 Pro 158 | "iPhone12,5": { dpr: 3, viewportWidth: 414, viewportHeight: 896 }, // iPhone 11 Pro Max 159 | "iPhone13,1": { dpr: 3, viewportWidth: 360, viewportHeight: 780 }, // iPhone 12 Mini 160 | "iPhone13,2": { dpr: 3, viewportWidth: 390, viewportHeight: 844 }, // iPhone 12 161 | "iPhone13,3": { dpr: 3, viewportWidth: 390, viewportHeight: 844 }, // iPhone 12 Pro 162 | "iPhone13,4": { dpr: 3, viewportWidth: 428, viewportHeight: 926 }, // iPhone 12 Pro Max 163 | "iPhone14,4": { dpr: 3, viewportWidth: 360, viewportHeight: 780 }, // iPhone 13 Mini 164 | "iPhone14,5": { dpr: 3, viewportWidth: 390, viewportHeight: 844 }, // iPhone 13 165 | "iPhone14,2": { dpr: 3, viewportWidth: 393, viewportHeight: 852 }, // iPhone 14 Pro 166 | "iPhone14,3": { dpr: 3, viewportWidth: 430, viewportHeight: 932 }, // iPhone 14 Pro Max 167 | "iPhone15,2": { dpr: 3, viewportWidth: 393, viewportHeight: 852 }, // iPhone 15 Pro 168 | "iPhone15,3": { dpr: 3, viewportWidth: 430, viewportHeight: 932 }, // iPhone 15 Pro Max 169 | }; 170 | 171 | export function getDeviceName(machineId: string): string { 172 | return iPhoneModels[machineId] || iPadModels[machineId] || "iPhone"; 173 | } 174 | -------------------------------------------------------------------------------- /public/device.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Device 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |
21 |
22 |

23 | Loading...

24 |
25 | 187 | 188 | 189 | 191 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | -------------------------------------------------------------------------------- /public/static/js/external/jquery.touchSwipe.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * @fileOverview TouchSwipe - jQuery Plugin 3 | * @version 1.6.18 4 | * 5 | * @author Matt Bryson http://www.github.com/mattbryson 6 | * @see https://github.com/mattbryson/TouchSwipe-Jquery-Plugin 7 | * @see http://labs.rampinteractive.co.uk/touchSwipe/ 8 | * @see http://plugins.jquery.com/project/touchSwipe 9 | * @license 10 | * Copyright (c) 2010-2015 Matt Bryson 11 | * Dual licensed under the MIT or GPL Version 2 licenses. 12 | * 13 | */ 14 | 15 | !function(factory){"function"==typeof define&&define.amd&&define.amd.jQuery?define(["jquery"],factory):factory("undefined"!=typeof module&&module.exports?require("jquery"):jQuery)}(function($){"use strict";function init(options){return!options||void 0!==options.allowPageScroll||void 0===options.swipe&&void 0===options.swipeStatus||(options.allowPageScroll=NONE),void 0!==options.click&&void 0===options.tap&&(options.tap=options.click),options||(options={}),options=$.extend({},$.fn.swipe.defaults,options),this.each(function(){var $this=$(this),plugin=$this.data(PLUGIN_NS);plugin||(plugin=new TouchSwipe(this,options),$this.data(PLUGIN_NS,plugin))})}function TouchSwipe(element,options){function touchStart(jqEvent){if(!(getTouchInProgress()||$(jqEvent.target).closest(options.excludedElements,$element).length>0)){var event=jqEvent.originalEvent?jqEvent.originalEvent:jqEvent;if(!event.pointerType||"mouse"!=event.pointerType||0!=options.fallbackToMouseEvents){var ret,touches=event.touches,evt=touches?touches[0]:event;return phase=PHASE_START,touches?fingerCount=touches.length:options.preventDefaultEvents!==!1&&jqEvent.preventDefault(),distance=0,direction=null,currentDirection=null,pinchDirection=null,duration=0,startTouchesDistance=0,endTouchesDistance=0,pinchZoom=1,pinchDistance=0,maximumsMap=createMaximumsData(),cancelMultiFingerRelease(),createFingerData(0,evt),!touches||fingerCount===options.fingers||options.fingers===ALL_FINGERS||hasPinches()?(startTime=getTimeStamp(),2==fingerCount&&(createFingerData(1,touches[1]),startTouchesDistance=endTouchesDistance=calculateTouchesDistance(fingerData[0].start,fingerData[1].start)),(options.swipeStatus||options.pinchStatus)&&(ret=triggerHandler(event,phase))):ret=!1,ret===!1?(phase=PHASE_CANCEL,triggerHandler(event,phase),ret):(options.hold&&(holdTimeout=setTimeout($.proxy(function(){$element.trigger("hold",[event.target]),options.hold&&(ret=options.hold.call($element,event,event.target))},this),options.longTapThreshold)),setTouchInProgress(!0),null)}}}function touchMove(jqEvent){var event=jqEvent.originalEvent?jqEvent.originalEvent:jqEvent;if(phase!==PHASE_END&&phase!==PHASE_CANCEL&&!inMultiFingerRelease()){var ret,touches=event.touches,evt=touches?touches[0]:event,currentFinger=updateFingerData(evt);if(endTime=getTimeStamp(),touches&&(fingerCount=touches.length),options.hold&&clearTimeout(holdTimeout),phase=PHASE_MOVE,2==fingerCount&&(0==startTouchesDistance?(createFingerData(1,touches[1]),startTouchesDistance=endTouchesDistance=calculateTouchesDistance(fingerData[0].start,fingerData[1].start)):(updateFingerData(touches[1]),endTouchesDistance=calculateTouchesDistance(fingerData[0].end,fingerData[1].end),pinchDirection=calculatePinchDirection(fingerData[0].end,fingerData[1].end)),pinchZoom=calculatePinchZoom(startTouchesDistance,endTouchesDistance),pinchDistance=Math.abs(startTouchesDistance-endTouchesDistance)),fingerCount===options.fingers||options.fingers===ALL_FINGERS||!touches||hasPinches()){if(direction=calculateDirection(currentFinger.start,currentFinger.end),currentDirection=calculateDirection(currentFinger.last,currentFinger.end),validateDefaultEvent(jqEvent,currentDirection),distance=calculateDistance(currentFinger.start,currentFinger.end),duration=calculateDuration(),setMaxDistance(direction,distance),ret=triggerHandler(event,phase),!options.triggerOnTouchEnd||options.triggerOnTouchLeave){var inBounds=!0;if(options.triggerOnTouchLeave){var bounds=getbounds(this);inBounds=isInBounds(currentFinger.end,bounds)}!options.triggerOnTouchEnd&&inBounds?phase=getNextPhase(PHASE_MOVE):options.triggerOnTouchLeave&&!inBounds&&(phase=getNextPhase(PHASE_END)),phase!=PHASE_CANCEL&&phase!=PHASE_END||triggerHandler(event,phase)}}else phase=PHASE_CANCEL,triggerHandler(event,phase);ret===!1&&(phase=PHASE_CANCEL,triggerHandler(event,phase))}}function touchEnd(jqEvent){var event=jqEvent.originalEvent?jqEvent.originalEvent:jqEvent,touches=event.touches;if(touches){if(touches.length&&!inMultiFingerRelease())return startMultiFingerRelease(event),!0;if(touches.length&&inMultiFingerRelease())return!0}return inMultiFingerRelease()&&(fingerCount=fingerCountAtRelease),endTime=getTimeStamp(),duration=calculateDuration(),didSwipeBackToCancel()||!validateSwipeDistance()?(phase=PHASE_CANCEL,triggerHandler(event,phase)):options.triggerOnTouchEnd||options.triggerOnTouchEnd===!1&&phase===PHASE_MOVE?(options.preventDefaultEvents!==!1&&jqEvent.preventDefault(),phase=PHASE_END,triggerHandler(event,phase)):!options.triggerOnTouchEnd&&hasTap()?(phase=PHASE_END,triggerHandlerForGesture(event,phase,TAP)):phase===PHASE_MOVE&&(phase=PHASE_CANCEL,triggerHandler(event,phase)),setTouchInProgress(!1),null}function touchCancel(){fingerCount=0,endTime=0,startTime=0,startTouchesDistance=0,endTouchesDistance=0,pinchZoom=1,cancelMultiFingerRelease(),setTouchInProgress(!1)}function touchLeave(jqEvent){var event=jqEvent.originalEvent?jqEvent.originalEvent:jqEvent;options.triggerOnTouchLeave&&(phase=getNextPhase(PHASE_END),triggerHandler(event,phase))}function removeListeners(){$element.unbind(START_EV,touchStart),$element.unbind(CANCEL_EV,touchCancel),$element.unbind(MOVE_EV,touchMove),$element.unbind(END_EV,touchEnd),LEAVE_EV&&$element.unbind(LEAVE_EV,touchLeave),setTouchInProgress(!1)}function getNextPhase(currentPhase){var nextPhase=currentPhase,validTime=validateSwipeTime(),validDistance=validateSwipeDistance(),didCancel=didSwipeBackToCancel();return!validTime||didCancel?nextPhase=PHASE_CANCEL:!validDistance||currentPhase!=PHASE_MOVE||options.triggerOnTouchEnd&&!options.triggerOnTouchLeave?!validDistance&¤tPhase==PHASE_END&&options.triggerOnTouchLeave&&(nextPhase=PHASE_CANCEL):nextPhase=PHASE_END,nextPhase}function triggerHandler(event,phase){var ret,touches=event.touches;return(didSwipe()||hasSwipes())&&(ret=triggerHandlerForGesture(event,phase,SWIPE)),(didPinch()||hasPinches())&&ret!==!1&&(ret=triggerHandlerForGesture(event,phase,PINCH)),didDoubleTap()&&ret!==!1?ret=triggerHandlerForGesture(event,phase,DOUBLE_TAP):didLongTap()&&ret!==!1?ret=triggerHandlerForGesture(event,phase,LONG_TAP):didTap()&&ret!==!1&&(ret=triggerHandlerForGesture(event,phase,TAP)),phase===PHASE_CANCEL&&touchCancel(event),phase===PHASE_END&&(touches?touches.length||touchCancel(event):touchCancel(event)),ret}function triggerHandlerForGesture(event,phase,gesture){var ret;if(gesture==SWIPE){if($element.trigger("swipeStatus",[phase,direction||null,distance||0,duration||0,fingerCount,fingerData,currentDirection]),options.swipeStatus&&(ret=options.swipeStatus.call($element,event,phase,direction||null,distance||0,duration||0,fingerCount,fingerData,currentDirection),ret===!1))return!1;if(phase==PHASE_END&&validateSwipe()){if(clearTimeout(singleTapTimeout),clearTimeout(holdTimeout),$element.trigger("swipe",[direction,distance,duration,fingerCount,fingerData,currentDirection]),options.swipe&&(ret=options.swipe.call($element,event,direction,distance,duration,fingerCount,fingerData,currentDirection),ret===!1))return!1;switch(direction){case LEFT:$element.trigger("swipeLeft",[direction,distance,duration,fingerCount,fingerData,currentDirection]),options.swipeLeft&&(ret=options.swipeLeft.call($element,event,direction,distance,duration,fingerCount,fingerData,currentDirection));break;case RIGHT:$element.trigger("swipeRight",[direction,distance,duration,fingerCount,fingerData,currentDirection]),options.swipeRight&&(ret=options.swipeRight.call($element,event,direction,distance,duration,fingerCount,fingerData,currentDirection));break;case UP:$element.trigger("swipeUp",[direction,distance,duration,fingerCount,fingerData,currentDirection]),options.swipeUp&&(ret=options.swipeUp.call($element,event,direction,distance,duration,fingerCount,fingerData,currentDirection));break;case DOWN:$element.trigger("swipeDown",[direction,distance,duration,fingerCount,fingerData,currentDirection]),options.swipeDown&&(ret=options.swipeDown.call($element,event,direction,distance,duration,fingerCount,fingerData,currentDirection))}}}if(gesture==PINCH){if($element.trigger("pinchStatus",[phase,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData]),options.pinchStatus&&(ret=options.pinchStatus.call($element,event,phase,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData),ret===!1))return!1;if(phase==PHASE_END&&validatePinch())switch(pinchDirection){case IN:$element.trigger("pinchIn",[pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData]),options.pinchIn&&(ret=options.pinchIn.call($element,event,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData));break;case OUT:$element.trigger("pinchOut",[pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData]),options.pinchOut&&(ret=options.pinchOut.call($element,event,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData))}}return gesture==TAP?phase!==PHASE_CANCEL&&phase!==PHASE_END||(clearTimeout(singleTapTimeout),clearTimeout(holdTimeout),hasDoubleTap()&&!inDoubleTap()?(doubleTapStartTime=getTimeStamp(),singleTapTimeout=setTimeout($.proxy(function(){doubleTapStartTime=null,$element.trigger("tap",[event.target]),options.tap&&(ret=options.tap.call($element,event,event.target))},this),options.doubleTapThreshold)):(doubleTapStartTime=null,$element.trigger("tap",[event.target]),options.tap&&(ret=options.tap.call($element,event,event.target)))):gesture==DOUBLE_TAP?phase!==PHASE_CANCEL&&phase!==PHASE_END||(clearTimeout(singleTapTimeout),clearTimeout(holdTimeout),doubleTapStartTime=null,$element.trigger("doubletap",[event.target]),options.doubleTap&&(ret=options.doubleTap.call($element,event,event.target))):gesture==LONG_TAP&&(phase!==PHASE_CANCEL&&phase!==PHASE_END||(clearTimeout(singleTapTimeout),doubleTapStartTime=null,$element.trigger("longtap",[event.target]),options.longTap&&(ret=options.longTap.call($element,event,event.target)))),ret}function validateSwipeDistance(){var valid=!0;return null!==options.threshold&&(valid=distance>=options.threshold),valid}function didSwipeBackToCancel(){var cancelled=!1;return null!==options.cancelThreshold&&null!==direction&&(cancelled=getMaxDistance(direction)-distance>=options.cancelThreshold),cancelled}function validatePinchDistance(){return null===options.pinchThreshold||pinchDistance>=options.pinchThreshold}function validateSwipeTime(){var result;return result=!options.maxTimeThreshold||!(duration>=options.maxTimeThreshold)}function validateDefaultEvent(jqEvent,direction){if(options.preventDefaultEvents!==!1)if(options.allowPageScroll===NONE)jqEvent.preventDefault();else{var auto=options.allowPageScroll===AUTO;switch(direction){case LEFT:(options.swipeLeft&&auto||!auto&&options.allowPageScroll!=HORIZONTAL)&&jqEvent.preventDefault();break;case RIGHT:(options.swipeRight&&auto||!auto&&options.allowPageScroll!=HORIZONTAL)&&jqEvent.preventDefault();break;case UP:(options.swipeUp&&auto||!auto&&options.allowPageScroll!=VERTICAL)&&jqEvent.preventDefault();break;case DOWN:(options.swipeDown&&auto||!auto&&options.allowPageScroll!=VERTICAL)&&jqEvent.preventDefault();break;case NONE:}}}function validatePinch(){var hasCorrectFingerCount=validateFingers(),hasEndPoint=validateEndPoint(),hasCorrectDistance=validatePinchDistance();return hasCorrectFingerCount&&hasEndPoint&&hasCorrectDistance}function hasPinches(){return!!(options.pinchStatus||options.pinchIn||options.pinchOut)}function didPinch(){return!(!validatePinch()||!hasPinches())}function validateSwipe(){var hasValidTime=validateSwipeTime(),hasValidDistance=validateSwipeDistance(),hasCorrectFingerCount=validateFingers(),hasEndPoint=validateEndPoint(),didCancel=didSwipeBackToCancel(),valid=!didCancel&&hasEndPoint&&hasCorrectFingerCount&&hasValidDistance&&hasValidTime;return valid}function hasSwipes(){return!!(options.swipe||options.swipeStatus||options.swipeLeft||options.swipeRight||options.swipeUp||options.swipeDown)}function didSwipe(){return!(!validateSwipe()||!hasSwipes())}function validateFingers(){return fingerCount===options.fingers||options.fingers===ALL_FINGERS||!SUPPORTS_TOUCH}function validateEndPoint(){return 0!==fingerData[0].end.x}function hasTap(){return!!options.tap}function hasDoubleTap(){return!!options.doubleTap}function hasLongTap(){return!!options.longTap}function validateDoubleTap(){if(null==doubleTapStartTime)return!1;var now=getTimeStamp();return hasDoubleTap()&&now-doubleTapStartTime<=options.doubleTapThreshold}function inDoubleTap(){return validateDoubleTap()}function validateTap(){return(1===fingerCount||!SUPPORTS_TOUCH)&&(isNaN(distance)||distanceoptions.longTapThreshold&&distance=0?LEFT:angle<=360&&angle>=315?LEFT:angle>=135&&angle<=225?RIGHT:angle>45&&angle<135?DOWN:UP}function getTimeStamp(){var now=new Date;return now.getTime()}function getbounds(el){el=$(el);var offset=el.offset(),bounds={left:offset.left,right:offset.left+el.outerWidth(),top:offset.top,bottom:offset.top+el.outerHeight()};return bounds}function isInBounds(point,bounds){return point.x>bounds.left&&point.xbounds.top&&point.y