Skip to content
This repository was archived by the owner on Jan 18, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions src/controllers/instance-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const AssignmentController = require('./assignment-controller.js');
const InstanceType = require('../data/instance-type.js');
const Device = require('../models/device.js');
const { GeofenceType, Geofence } = require('../models/geofence.js');
const Instance = require('../models/instance.js');
const { AutoInstanceController, AutoType } = require('./instances/auto.js');
const { CircleInstanceController, CircleType } = require('./instances/circle.js');
Expand Down Expand Up @@ -31,7 +32,7 @@ class InstanceController {
for (let i = 0; i < instances.length; i++) {
let inst = instances[i];
console.log(`[InstanceController] Starting ${inst.name}...`);
this.addInstance(inst);
await this.addInstance(inst);
console.log(`[InstanceController] Started ${inst.name}`);
let filtered = devices.filter(x => x.instanceName === inst.name);
for (let j = 0; j < filtered.length; j++) {
Expand Down Expand Up @@ -74,17 +75,21 @@ class InstanceController {
return this.instances[name];
}

addInstance(instance) {
async addInstance(instance) {
let instanceController;
let geofence = await Geofence.getByName(instance.geofence);
switch (instance.type) {
case InstanceType.CirclePokemon:
case InstanceType.CircleRaid:
case InstanceType.CircleSmartRaid: {
let coordsArray = [];
if (instance.data['area']) {
coordsArray = instance.data['area'];
let area = instance.geofence
? geofence.data['area']
: instance.data['area'];
if (area) {
coordsArray = area;
} else {
let coords = instance.data['area'];
let coords = area;
for (let coord in coords) {
coordsArray.push({ lat: coord.lat, lon: coord.lon });
}
Expand All @@ -107,10 +112,13 @@ class InstanceController {
case InstanceType.AutoQuest:
case InstanceType.PokemonIV: {
let areaArray = [];
if (instance.data['area']) {
let area = instance.geofence
? geofence.data['area']
: instance.data['area'];
if (area) {
// areaArray = instance.data['area']; //[[Coord]]
//} else {
let areas = instance.data['area']; //[[[String: Double]]]
let areas = area; //[[[String: Double]]]
for (let i = 0; i < areas.length; i++) {
let coords = areas[i];
for (let j = 0; j < coords.length; j++) {
Expand Down Expand Up @@ -157,7 +165,7 @@ class InstanceController {
}
}

reloadInstance(newInstance, oldInstanceName) {
async reloadInstance(newInstance, oldInstanceName) {
let oldInstance = this.instances[oldInstanceName];
if (oldInstance) {
for (let uuid in this.devices) {
Expand All @@ -170,7 +178,7 @@ class InstanceController {
this.instances[oldInstanceName].stop();
this.instances[oldInstanceName] = null;
}
this.addInstance(newInstance);
await this.addInstance(newInstance);
}


Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const apiRoutes = require('./routes/api.js');
const uiRoutes = require('./routes/ui.js');
const routes = new DeviceController();

// TODO: Fix caching of `default.js`

(async () => {
// View engine
app.set('view engine', 'mustache');
Expand Down
174 changes: 174 additions & 0 deletions src/models/geofence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
'use strict';

const config = require('../config.json');
const MySQLConnector = require('../services/mysql.js');
const db = new MySQLConnector(config.db);

const GeofenceType = {
Circle: 'circle',
Geofence: 'geofence'
};

class Geofence {

constructor(name, type, data) {
this.name = name;
this.type = type;
this.data = data;
}

/**
* Load all geofences/circle routes.
*/
static async getAll() {
let sql = `
SELECT name, type, data
FROM geofence
`;
let results = await db.query(sql)
.then(x => x)
.catch(err => {
console.error('[Geofence] Error:', err);
return null;
});
let geofences = [];
if (results) {
for (let i = 0; i < results.length; i++) {
let result = results[i];
geofences.push(new Geofence(
result.name,
result.type,
JSON.parse(result.data)
));
}
}
return geofences;
}

/**
* Get geofence by name.
*/
static async getByName(name) {
let sql = `
SELECT name, type, data
FROM geofence
WHERE name = ?
`;
let args = [name];
let results = await db.query(sql, args)
.then(x => x)
.catch(err => {
console.error('[Geofence] Error:', err);
return null;
});
if (results && results.length > 0) {
let result = results[0];
return new Geofence(
result.name,
result.type,
JSON.parse(result.data)
);
}
return null;
}

static async deleteByName(name) {
let sql = `
DELETE FROM geofence
WHERE name = ?
`;
let args = [name];
try {
let results = await db.query(sql, args);
console.log('[Geofence] DeleteByName:', results);
} catch (err) {
console.error('[Geofence] Error:', err);
}
}

async create() {
let sql = `
INSERT INTO geofence (name, type, data) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
type=VALUES(type),
data=VALUES(data)
`;
let args = [this.name, this.type, JSON.stringify(this.data || {})];
try {
let results = await db.query(sql, args);
console.log('[Geofence] Save:', results);
} catch (err) {
console.error('[Geofence] Error:', err);
}
}

async save(oldName) {
let sql = `
UPDATE geofence SET name = ?, type = ?, data = ?
WHERE name = ?
`;
let args = [this.name, this.type, JSON.stringify(this.data || {}), oldName];
try {
let results = await db.query(sql, args);
console.log('[Geofence] Save:', results);
} catch (err) {
console.error('[Geofence] Error:', err);
}
}

static areaToGeofences(area) {
let coordArray = [];
let areaRows = area.split('\n');
let currentIndex = 0;
for (let i = 0; i < areaRows.length; i++) {
const areaRow = areaRows[i];
let rowSplit = areaRow.split(',');
if (rowSplit.length === 2) {
let lat = parseFloat(rowSplit[0].trim());
let lon = parseFloat(rowSplit[1].trim());
if (lat && lon) {
while (coordArray.length !== currentIndex + 1) {
coordArray.push([]);
}
coordArray[currentIndex].push({
lat: lat,
lon: lon
});
}
} else if (areaRow.includes('[') && areaRow.includes(']') &&
coordArray.length > currentIndex && coordArray[currentIndex].length !== 0) {
currentIndex++;
}
}
return coordArray;
}

static areaToCirclePoints(area) {
let coords = [];
let areaRows = area.split('\n');
for (let i = 0; i < areaRows.length; i++) {
const areaRow = areaRows[i];
let rowSplit = areaRow.split(',');
if (rowSplit.length === 2) {
let lat = parseFloat(rowSplit[0].trim());
let lon = parseFloat(rowSplit[1].trim());
if (lat && lon) {
coords.push({ lat: lat, lon: lon });
}
}
}
return coords;
}

static fromString(type) {
switch (type) {
case 'circle':
return 'Circle';
case 'geofence':
return 'Geofence';
}
return null;
}
}

module.exports = { GeofenceType, Geofence };
19 changes: 11 additions & 8 deletions src/models/instance.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

const config = require('../config.json');
const InstanceType = require('../data/instance-type.js');
const MySQLConnector = require('../services/mysql.js');
const db = new MySQLConnector(config.db);

Expand All @@ -13,10 +12,11 @@ class Instance {
* @param type Type of instance.
* @param data Instance data containing area coordinates, minimum and maximum account level, etc.
*/
constructor(name, type, data, count = 0) {
constructor(name, type, data, geofence, count = 0) {
this.name = name;
this.type = type;
this.data = data;
this.geofence = geofence;
this.count = count;
}

Expand All @@ -25,7 +25,7 @@ class Instance {
*/
static async getAll() {
let sql = `
SELECT name, type, data, count
SELECT name, type, data, geofence, count
FROM instance AS inst
LEFT JOIN (
SELECT COUNT(instance_name) AS count, instance_name
Expand All @@ -47,6 +47,7 @@ class Instance {
result.name,
result.type,
JSON.parse(result.data),
result.geofence,
result.count || 0
);
instances.push(instance);
Expand All @@ -60,7 +61,7 @@ class Instance {
*/
static async getByName(name) {
let sql = `
SELECT name, type, data
SELECT name, type, data, geofence
FROM instance
WHERE name = ?
`;
Expand All @@ -76,7 +77,8 @@ class Instance {
return new Instance(
result.name,
result.type,
JSON.parse(result.data)
JSON.parse(result.data),
result.geofence
);
}
return null;
Expand All @@ -98,12 +100,13 @@ class Instance {

async save() {
let sql = `
INSERT INTO instance (name, type, data) VALUES (?, ?, ?)
INSERT INTO instance (name, type, data, geofence) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
type=VALUES(type),
data=VALUES(data)
data=VALUES(data),
geofence=VALUES(geofence)
`;
let args = [this.name, this.type, JSON.stringify(this.data || {})];
let args = [this.name, this.type, JSON.stringify(this.data || {}), this.geofence];
try {
let results = await db.query(sql, args);
//console.log('[Instance] Save:', results);
Expand Down
19 changes: 18 additions & 1 deletion src/routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const InstanceController = require('../controllers/instance-controller.js');
const defaultData = require('../data/default.js');
const Assignment = require('../models/assignment.js');
const Device = require('../models/device.js');
const { Geofence } = require('../models/geofence.js');
const Instance = require('../models/instance.js');
const utils = require('../services/utils.js');

Expand Down Expand Up @@ -76,8 +77,10 @@ router.post('/instances', async (req, res) => {
if (instances.length > 0) {
for (let i = 0; i < instances.length; i++) {
let instance = instances[i];
instance.area_count = instance.data.area ? instance.data.area.length : 0;
let geofence = await Geofence.getByName(instance.geofence);
instance.area_count = geofence && geofence.data ? geofence.data.area.length : instance.data && instance.data.area ? instance.data.area.length : 'ERR';
instance.type = Instance.fromString(instance.type);
instance.geofence = instance.geofence ? instance.geofence : '';
instance.status = await InstanceController.instance.getInstanceStatus(instance);
instance.buttons = `<a href="/instance/edit/${encodeURIComponent(instance.name)}" role="button" class="btn btn-primary">Edit Instance</a>`;
}
Expand All @@ -86,6 +89,20 @@ router.post('/instances', async (req, res) => {
res.json({ data: data });
});

router.post('/geofences', async (req, res) => {
const data = {};
let geofences = await Geofence.getAll();
if (geofences.length > 0) {
for (let i = 0; i < geofences.length; i++) {
let geofence = geofences[i];
geofence.type = Geofence.fromString(geofence.type);
geofence.buttons = `<div class="btn-group" role="group"><a href="/geofence/edit/${encodeURIComponent(geofence.name)}" role="button" class="btn btn-primary">Edit</a>`;
}
}
data.geofences = geofences;
res.json({ data: data });
});

router.get('/ivqueue/:name', async (req, res) => {
const name = req.params.name;
const queue = InstanceController.instance.getIVQueue(name);
Expand Down
Loading