Skip to content

Commit

Permalink
Further improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
frizz925 committed Aug 1, 2017
1 parent 092a81d commit 661f583
Show file tree
Hide file tree
Showing 15 changed files with 271 additions and 29 deletions.
4 changes: 1 addition & 3 deletions extension/manifest.sample.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
"128": "images/icon-128.png"
},
"background": {
"scripts": [
"dist/background.js"
]
"page": "pages/background.html"
},
"page_action": {
"default_icon": {
Expand Down
14 changes: 14 additions & 0 deletions extension/pages/background.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Granblue Autopilot</title>
</head>
<body>
<!-- Viramate Web API -->
<iframe id="viramate_api" src="chrome-extension://fgpokpknehglcioijejfeebigdnbnokj/content/api.html"></iframe>
<script src="../dist/background.js"></script>
</body>
</html>
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
},
"dependencies": {
"axios": "^0.16.2",
"body-parser": "^1.17.2",
"express": "^4.15.3",
"jquery": "^3.2.1",
"lodash": "^4.17.4",
Expand Down
1 change: 1 addition & 0 deletions server/config.sample.ini
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[Server]
ListenerPort = 49544
ControllerPort = 49545
ChatBotPort = 49546
ActionTimeoutInMs = 60000
Scenario = GuildWar
BotTimeoutInMins = 60
Expand Down
17 changes: 13 additions & 4 deletions src/background.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import liveReload from "./background/liveReload";
import ViramateApi from "./background/ViramateApi";
import LiveReload from "./background/LiveReload";
import io from "socket.io-client";

if (process.env.NODE_ENV !== "production") {
liveReload();
LiveReload();
}

const viramateApi = new ViramateApi(document.querySelector("#viramate_api"));
const serverUrl = window.serverUrl || "http://localhost:49544/";
const subscribers = [];
const broadcast = (payload) => {
Expand Down Expand Up @@ -32,12 +34,19 @@ function startIo(tab) {
console.log("Stopped socket");
});
socket.on("action", ({action, id, payload, timeout}) => {
if (action == "viramate") {
viramateApi.sendApiRequest(payload, id).then((result) => {
socket.emit("action", {id, action, payload: result});
}, (result) => {
socket.emit("action.fail", {id, action, payload: result});
});
return;
}

var rejected = false;
function sendMessage() {
if (rejected) return;
console.log("SEND", id, {action, payload});
chrome.tabs.sendMessage(tab.id, {action, payload, timeout}, (data) => {
console.log("RECV", id, data);
if (data == undefined && socket) {
setTimeout(sendMessage, 500);
return;
Expand Down
37 changes: 37 additions & 0 deletions src/background/ViramateApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import shortid from "shortid";

export default class ViramateApi {
constructor(host) {
this.host = host;
this.pending = {};
window.addEventListener("message", ::this.onMessage, false);
}

generateId() {
return shortid.generate();
}

sendApiRequest(request, id) {
id = id || this.generateId();
return new Promise((resolve, reject) => {
request.id = id;
this.pending[request.id] = {resolve, reject};
this.host.contentWindow.postMessage(request, "*");
});
}

onMessage(evt) {
if (evt.data.type !== "result") return;
if (!evt.data.id) return;
const promise = this.pending[evt.data.id];
if (!promise) return;

if (evt.data.result && evt.data.result.error) {
promise.reject(evt.data.result);
} else {
promise.resolve(evt.data.result);
}

delete this.pending[evt.data.id];
}
}
2 changes: 1 addition & 1 deletion src/contentscript/actions/location.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export default {
window.location.hash = hash;
window.setTimeout(() => {
done("OK");
}, 5000);
}, 1000);
}
};
38 changes: 25 additions & 13 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import axios from "axios";
import shortid from "shortid";
import SocketIO from "socket.io";
import Express from "express";
import bodyParser from "body-parser";
import forEach from "lodash/forEach";

import packer from "~/lib/messaging/packer";
import EventRun from "./server/EventRun";
import Worker from "./server/Worker";
import WorkerManager from "./server/WorkerManager";
import RaidQueue from "./server/RaidQueue";

export default class Server {
constructor(initConfig, configHandler) {
Expand All @@ -22,6 +25,7 @@ export default class Server {
};
this.sockets = {};

this.raidQueue = new RaidQueue();
this.app = Express();
this.server = http.Server(this.app);
this.io = SocketIO(this.server);
Expand All @@ -30,7 +34,16 @@ export default class Server {
}

setupExpress(app) {
app.post("/stop", ::this.stop);
app.use(bodyParser.text());
app.post("/stop", (req, res) => {
this.stop();
res.end();
});
app.post("/raid", (req, res) => {
console.log("New raid: " + req.body);
this.raidQueue.push(req.body);
res.end();
});
}

setupSocket(io) {
Expand All @@ -57,21 +70,22 @@ export default class Server {
this.refreshConfig(config);

const botTimeout = Number(config.Server.BotTimeoutInMins);
const runner = new EventRun(config, (action, payload, timeout) => {
const manager = new WorkerManager(this, socket);
const worker = new Worker(this, config, (action, payload, timeout) => {
return this.sendAction(socket, action, payload, timeout);
});
}, manager);
const timer = setTimeout(() => {
if (!this.sockets[socket.id]) return;
console.log("Bot reaches maximum time. Disconnecting...");
this.stopSocket(socket.id);
}, botTimeout * 60 * 1000);

this.sockets[socket.id] = {
socket, runner, timer,
socket, worker, timer,
actions: {}
};
this.makeRequest("start").then(() => {
runner.start(scenario);
worker.start(scenario);
}, (err) => {
console.error(err);
});
Expand Down Expand Up @@ -136,12 +150,12 @@ export default class Server {
reject(payload);
done();
},
timer: setTimeout(() => {
timer: timeout > 0 ? setTimeout(() => {
if (!resolved) {
reject(new Error(`Action ${expression} timed out!`));
}
done();
}, timeout)
}, timeout) : 0
};

const data = packer(actionName, payload);
Expand All @@ -155,17 +169,15 @@ export default class Server {
}

stopSocket(id) {
if (!this.sockets[id]) {
throw new Error("Socket ID not found!");
}
const {socket, runner, timer, actions} = this.sockets[id];
if (!this.sockets[id]) return;
const {socket, worker, timer, actions} = this.sockets[id];
delete this.sockets[id];
forEach(actions, ({timer}) => {
clearTimeout(timer);
});
clearTimeout(timer);
socket.disconnect();
runner.stop();
worker.stop();
return this;
}

Expand Down
25 changes: 25 additions & 0 deletions src/server/RaidQueue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default class RaidQueue {
constructor() {
this.queue = [];
this.callbacks = [];
}

push(code) {
if (this.callbacks.length > 0) {
const callback = this.callbacks.shift();
callback(code);
} else {
this.queue.push(code);
}
}

pop() {
return new Promise((resolve) => {
if (this.queue.length > 0) {
resolve(this.queue.pop());
} else {
this.callbacks.push(resolve);
}
});
}
}
29 changes: 26 additions & 3 deletions src/server/EventRun.js → src/server/Worker.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import axios from "axios";
import _ from "lodash";
import actionClick from "./actions/click";
import actionSupport from "./actions/support";
import actionBattle from "./actions/battle";
import actionScenario from "./actions/scenario";
import actionRaid from "./actions/raid";

/*
* Every single action must return a Promise.
* These promises will be handled by the scenario runner.
*/
const actions = _.assign({
"execute": function(action, payload) {
return this.sendAction(action, payload);
},
"check": function(selector) {
if (_.isFunction(selector)) {
const callback = selector;
Expand Down Expand Up @@ -40,13 +49,24 @@ const actions = _.assign({
return new Promise((resolve) => {
setTimeout(resolve, timeout || 1);
});
},
"chatbot": function(text) {
const port = this.config.Server.ChatBotPort;
return axios.post(`http://localhost:${port}/backup`, {
type: "text",
text
});
}
}, actionScenario, actionClick, actionSupport, actionBattle);
},
actionScenario, actionClick,
actionSupport, actionBattle, actionRaid);

export default class EventRun {
constructor(config, sendAction) {
export default class Worker {
constructor(server, config, sendAction, manager) {
this.server = server;
this.config = config;
this.sendAction = sendAction;
this.manager = manager;
this.port = Number(this.config.Server.ControllerPort);
this.actions = _.reduce(actions, (result, action, name) => {
result[name] = action.bind(this);
Expand Down Expand Up @@ -123,13 +143,16 @@ export default class EventRun {
}

start(initialScenario) {
if (this.running) return;
this.running = true;
this.runScenario(initialScenario);
return this;
}

stop() {
if (!this.running) return;
this.running = false;
this.manager.stop();
return this;
}
}
11 changes: 11 additions & 0 deletions src/server/WorkerManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default class WorkerManager {
constructor(server, socket) {
this.server = server;
this.socket = socket;
}

stop() {
this.server.stopSocket(this.socket.id);
return this;
}
}
9 changes: 8 additions & 1 deletion src/server/actions/battle.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import _ from "lodash";
import battleLogic from "./battle/logic";
import battleBackup from "./battle/backup";

const selectors = {
"attack": ".btn-attack-start.display-on",
Expand Down Expand Up @@ -156,5 +157,11 @@ export default {
}, nextHandler]
);
},
"battle.logic": battleLogic
"battle.enemy": function(number) {
return this.actions.click(".btn-targeting.enemy-" + number);
},

// Extras
"battle.logic": battleLogic,
"battle.backup": battleBackup
};
Loading

0 comments on commit 661f583

Please sign in to comment.