Unverified Commit 87eed40a authored by Isabella Skořepová's avatar Isabella Skořepová
Browse files

Add linter

parent 64b8ce12
module.exports = {
extends: ["airbnb-base", "prettier"],
plugins: ["prettier", "import"],
parser: "typescript-eslint-parser",
env: {
node: true,
},
rules: {
"prettier/prettier": [
"error",
{
singleQuote: true,
trailingComma: "all",
semi: false,
},
],
strict: ["error", "global"],
"no-unexpected-multiline": 0,
"no-restricted-syntax": 0,
"spaced-comment": 0,
"import/prefer-default-export": 0,
"no-continue": 0,
"no-await-in-loop": 0,
"import/no-commonjs": 0,
"no-console": 0, // we dont have specialised logger in this project
"no-empty": 0, // this is sometimes useful
"no-empty-function": 0, // this is sometimes useful
"class-methods-use-this": 0, // annoying
"prefer-destructuring": 0, // it is sometimes cleaner to write ti without destructuring
},
};
This diff is collapsed.
......@@ -6,7 +6,14 @@
"dependencies": {
"puppeteer": "^0.10.2"
},
"devDependencies": {},
"devDependencies": {
"eslint": "^4.7.0",
"eslint-config-airbnb-base": "^12.0.0",
"eslint-config-prettier": "^2.5.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-prettier": "^2.2.0",
"prettier-eslint": "^8.1.0"
},
"scripts": {
"start": "node src/index.js"
},
......
'use strict'
function timeout(ms) {
return new Promise(res => setTimeout(res, ms))
}
async function bot(travian) {
const queue = await travian.getQueue()
const buildings = await travian.getResourceBuildings()
if(queue.length < 1) {
console.log('Building queue is empty; Checking if building upgrade is possible')
const building = buildings.sort((a, b) => a.level < b.level ? -1 : 1)[0]
if (queue.length < 1) {
console.log(
'Building queue is empty; Checking if building upgrade is possible',
)
const building = buildings.sort((a, b) => (a.level < b.level ? -1 : 1))[0]
const time = await travian.getTimeWhenUpgradePossible(building.id)
if(!time) {
if (!time) {
console.log('adding lowest level resource building')
await timeout(5000)
await travian.upgradeBuilding(building.id)
} else {
const ms = time.getTime() - Date.now()
console.log('Building ('+building.id+') upgrade is not possible; waiting '+(ms/1000)+'s')
console.log(
`Building (${building.id}) upgrade is not possible; waiting ${ms /
1000}s`,
)
await timeout(ms)
}
} else {
console.log('Queue: '+queue.map(e => e.name+' '+e.level+' '+e.time).join('\n '))
console.log(
`Queue: ${queue
.map(e => `${e.name} ${e.level} ${e.time}`)
.join('\n ')}`,
)
}
await timeout(1000)
}
......
const puppeteer = require('puppeteer')
'use strict'
const fs = require('fs')
const { promisify } = require('util')
const Travian = require('./travian')
......@@ -17,12 +18,14 @@ console.log('starting')
const travian = impl(...args)
try {
await travian.login(await readCredentials())
while(true) {
// eslint-disable-next-line no-constant-condition
while (true) {
delete require.cache[require.resolve('./travian')]
delete require.cache[require.resolve('./bot')]
// eslint-disable-next-line global-require
await require('./bot').bot(require('./travian').travianImpl(...args))
}
} catch(e) {
} catch (e) {
travian.close()
console.error(e)
process.exit(1)
......@@ -30,4 +33,4 @@ console.log('starting')
})().catch(e => {
console.error(e)
process.exit(1)
});
})
'use strict'
const puppeteer = require('puppeteer')
const fs = require('fs')
const { promisify } = require('util')
const travianImpl = (page, browser, { state, setState }, { server, cookieStore, language }) => ({
const travianImpl = (
page,
browser,
{ state, setState },
{ server, language },
) => ({
async goto(path, opts = {}) {
if(state.path !== path) {
await page.goto(server+path, {
if (state.path !== path) {
await page.goto(server + path, {
waitUntil: 'networkidle',
...opts
...opts,
})
setState({ path })
}
......@@ -20,7 +25,7 @@ const travianImpl = (page, browser, { state, setState }, { server, cookieStore,
async login({ name, password }) {
await this.goto('dorf1.php')
if(await page.$('.outerLoginBox') !== null) {
if ((await page.$('.outerLoginBox')) !== null) {
await page.click('.account input')
await page.type(name)
await page.click('.pass input')
......@@ -35,6 +40,7 @@ const travianImpl = (page, browser, { state, setState }, { server, cookieStore,
async getResourceBuildings() {
await this.goto('dorf1.php')
const areaNames = await page.evaluate(() => {
/* global document */
const areas = Array.from(document.querySelectorAll('#rx area'))
return areas.map(a => ({ alt: a.alt, href: a.href }))
})
......@@ -43,27 +49,27 @@ const travianImpl = (page, browser, { state, setState }, { server, cookieStore,
.map(({ alt, href }) => {
const parts = alt.split(' ')
return {
level: Number.parseInt(parts[parts.length - 1]),
level: Number.parseInt(parts[parts.length - 1], 10),
type: parts.slice(0, parts.length - 2).join(' '),
id: href.replace(server+'build.php?id=', ''),
id: href.replace(`${server}build.php?id=`, ''),
}
})
.filter(a => a.type)
.map(a => ({
...a,
type: Object.entries(language.mines).find(([k,v]) => v === a.type)[0],
type: Object.entries(language.mines).find(([, v]) => v === a.type)[0],
}))
.sort((a,b) => a.type === b.type
? 0
: a.type > b.type
? 1
: -1
)
.sort((a, b) => {
if (a.type === b.type) return 0
return a.type > b.type ? 1 : -1
})
},
async getQueue() {
await this.goto('dorf1.php')
return await page.evaluate(() =>{
const buildings = Array.from(document.querySelectorAll('.buildingList li'))
return page.evaluate(() => {
const buildings = Array.from(
document.querySelectorAll('.buildingList li'),
)
return buildings.map(b => ({
time: b.children[2].children[0].innerHTML,
name: b.children[1].innerHTML.split('<')[0].trim(),
......@@ -72,33 +78,51 @@ const travianImpl = (page, browser, { state, setState }, { server, cookieStore,
})
},
async upgradeBuilding(id) {
await this.goto('build.php?id='+id)
await this.goto(`build.php?id=${id}`)
await page.click('.upgradeButtonsContainer .section1 button')
await this.networkIdle()
},
async getTimeWhenUpgradePossible(id) {
await this.goto('build.php?id='+id)
await this.goto(`build.php?id=${id}`)
const startDate = new Date()
const className = await page.$eval('.upgradeButtonsContainer .section1 button', el => el.className)
if(!/gold/.exec(className)) return 0
const timeString = await page.$eval('.contractCosts .statusMessage', el => el.innerHTML.split('<')[0])
const className = await page.$eval(
'.upgradeButtonsContainer .section1 button',
el => el.className,
)
if (!/gold/.exec(className)) return 0
const timeString = await page.$eval(
'.contractCosts .statusMessage',
el => el.innerHTML.split('<')[0],
)
const [month, day, hour, minute] = timeString
.replace(/^.* ([0-9]+)\.([0-9]+)\..* ([0-9]+):([0-9]+)/, '$2,$1,$3,$4')
.split(',')
.map(a => Number.parseInt(a, 10))
const date = new Date(new Date().getFullYear(), month-1, day, hour, minute)
if(startDate.getTime() - 1000*3600*24 > date.getTime()) {
const ndate = new Date(new Date().getFullYear()+1, month-1, day, hour, minute)
const date = new Date(
new Date().getFullYear(),
month - 1,
day,
hour,
minute,
)
if (startDate.getTime() - 1000 * 3600 * 24 > date.getTime()) {
const ndate = new Date(
new Date().getFullYear() + 1,
month - 1,
day,
hour,
minute,
)
return ndate
}
return date
},
close() {
return browser.close()
}
},
})
const generateArgs = async (_opts) => {
const generateArgs = async _opts => {
const opts = {
cookieStore: 'cookies.json',
headless: true,
......@@ -114,11 +138,11 @@ const generateArgs = async (_opts) => {
clay: 'Hlína',
iron: 'Železo',
wheat: 'Obilí',
}
},
},
..._opts,
}
if(!opts.server) throw new Error('You have to specify server')
if (!opts.server) throw new Error('You have to specify server')
const browser = await puppeteer.launch({ headless: opts.headless })
try {
const page = await browser.newPage()
......@@ -128,21 +152,23 @@ const generateArgs = async (_opts) => {
browser,
{
state,
setState: (patch) => { Object.assign(state, patch) },
setState: patch => {
Object.assign(state, patch)
},
},
opts,
]
} catch(e) {
} catch (e) {
browser.close()
throw e
}
}
const TravianFactory = async (_opts) => {
const TravianFactory = async _opts => {
const args = generateArgs(_opts)
try {
travianImpl(...args)
} catch(e) {
} catch (e) {
args[1].close()
throw e
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment