Commit b1890143 by 马玮

Add logs

parent fc4fa244
......@@ -8,11 +8,9 @@ const config = require('config');
const captcha = require('./lib/captcha');
const Spider = require('./lib/spider');
const DealerHelper = require('./lib/helpers/Dealer');
var log4js = require('log4js');
var logger = log4js.getLogger();
logger.level = 'debug';
logger.debug("Some debug messages");
const DI = require('./lib/DI');
const Promise = require('bluebird');
const readline = require('readline');
program
.version('0.1.0')
......@@ -38,11 +36,11 @@ if (commandError.length > 0) {
// console.log(process.pid);
(async () => {
console.time('程序耗时');
const account = await DealerHelper.getAccount({
accountID: program.accountID
});
// new Buffer('hnmz147852.').toString('base64')
// new Buffer('Q2hlY2hlbmcyMzUj', 'base64').toString();
const params = Object.assign({
task: program.task,
accountID: program.accountID,
......@@ -50,5 +48,25 @@ if (commandError.length > 0) {
}, account);
const spider = new Spider(params);
spider.execute();
await spider.execute();
// console.timeEnd('程序耗时');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// rl.write('正在释放资源...\n预计3秒后退出: ');
DI.shutdownLogger(async () => {
// for (let i = 3; i > 0; i -= 1) {
// rl.write(String(i));
// await Promise.delay(1000);
// readline.moveCursor(process.stdout,-1);
// }
// readline.clearLine(process.stdout, 0);
// readline.moveCursor(process.stdout, -1, -1);
// rl.write('\n');
// rl.close();
// console.log('程序结束');
// process.exit(0);
});
})();
\ No newline at end of file
const config = require('config');
const log4js = require('log4js');
const poolCluster = require('./database/poolCluster');
// 自定义模块
......@@ -7,6 +8,24 @@ class DI {
this.params = params;
}
static getLogger() {
const level = process.env.NODE_LOG_LEVEL || error;
log4js.configure({
appenders: {
console: { type: 'console' },
carspider: { type: 'file', filename: 'logs/dealer/carspider.log', maxLogSize: 10485760, backups: 3, compress: true },
},
categories: {
default: { appenders: [ 'console', 'carspider' ], level: level }
}
});
return log4js.getLogger();
}
static shutdownLogger(cb) {
log4js.shutdown(cb);
}
static async getConnection(nodeID) {
return new Promise(function(resolve, reject) {
poolCluster.getConnection(nodeID, function (err, connection) {
......
......@@ -37,7 +37,6 @@ class LoginError extends AppError {
constructor(options) {
if (typeof options === 'string') {
options = {message: options}
console.log('LoginError options:', options);
}
options = options || {};
options.code = options.code || {};
......
......@@ -5,31 +5,26 @@ const errors = require('../errors');
const Promise = require('bluebird');
const poolCluster = require('../database/poolCluster');
const DI = require('../DI');
const logger = DI.getLogger();
Promise.promisifyAll(redis);
class DealerHelper {
static async getCookies(params) {
return new Promise(async (resolve, reject) => {
try {
const account = await this.getAccount({
accountID: params.accountID
});
try {
let cookies = JSON.parse(account['cookies']);
resolve(cookies);
} catch (e) {
reject(e);
}
} catch (e) {
reject(e);
}
});
try {
const account = await this.getAccount({
accountID: params.accountID
});
return [null, JSON.parse(account['cookies'])];
} catch (e) {
logger.error(e);
return [e, null];
}
}
static async getHeaderCookie(params) {
try {
const cookies = await DealerHelper.getCookies(params);
const [CookiesError, cookies] = await DealerHelper.getCookies(params);
const cookieStrs = [];
cookies.forEach((cookie) => {
......@@ -38,7 +33,8 @@ class DealerHelper {
return cookieStrs.join(';');
} catch (e) {
return null;
logger.error(e);
return [e, null];
}
}
......@@ -63,7 +59,7 @@ class DealerHelper {
if (err) {
reject(err);
} else {
console.info('cookie保存成功');
logger.info(`accountID: ${params.accountID}, cookie保存成功`);
resolve(true);
}
}
......
......@@ -7,6 +7,8 @@ const config = require('config');
const captcha = require('../captcha');
const errors = require('../errors');
const DealerHelper = require('../helpers/Dealer');
const DI = require('../DI');
const logger = DI.getLogger();
class Base {
constructor(params) {
......@@ -24,33 +26,33 @@ class Base {
if (this.loginTimes < this.maxLoginTimes) {
this.loginTimes += 1;
console.log(`accountID: ${this.params.accountID}, 开始尝试登录: ${this.loginTimes}次`);
logger.info(`accountID: ${this.params.accountID}, 开始尝试登录: ${this.loginTimes}次`);
let loginSuccess = await this.tryLogin();
let [loginError, loginStatus] = await this.tryLogin();
if (loginSuccess) {
console.log(`accountID: ${this.params.accountID}, 尝试登录成功: ${this.loginTimes}次`);
return true;
if (loginStatus) {
logger.info(`accountID: ${this.params.accountID}, 尝试登录成功: ${this.loginTimes}次`);
return [loginError, loginStatus];
} else {
console.log(`accountID: ${this.params.accountID}, 尝试登录失败: ${this.loginTimes}次`);
logger.info(`accountID: ${this.params.accountID}, 尝试登录失败: ${this.loginTimes}次`);
}
console.log(`accountID: ${this.params.accountID}, 开始表单登录: ${this.loginTimes}次`);
loginSuccess = await this.login();
if (loginSuccess) {
console.log(`accountID: ${this.params.accountID}, 表单登录成功: ${this.loginTimes}次`);
return true;
logger.info(`accountID: ${this.params.accountID}, 开始表单登录: ${this.loginTimes}次`);
[loginError, loginStatus] = await this.login();
if (loginStatus) {
logger.info(`accountID: ${this.params.accountID}, 表单登录成功: ${this.loginTimes}次`);
return [loginError, loginStatus];
} else {
console.log(`accountID: ${this.params.accountID}, 表单登录失败: ${this.loginTimes}次`);
await this.retryLogin();
logger.info(`accountID: ${this.params.accountID}, 表单登录失败: ${this.loginTimes}次`);
return await this.retryLogin();
}
} else {
console.log(`accountID: ${this.params.accountID}, 触发登录失败上限: ${this.loginTimes}次`);
return false;
logger.error(`accountID: ${this.params.accountID}, 触发登录失败上限: ${this.loginTimes}次`);
return [new errors.LoginError('登录失败').toString(), 0];
}
} catch (e) {
console.log(e.toString());
return false;
logger.fatal(new errors.LoginError(e));
return [e.toString(), 0];
}
}
}
......
......@@ -15,10 +15,12 @@ const captcha = require('../../captcha');
const errors = require('../../errors');
const DealerHelper = require('../../helpers/Dealer');
const Base = require('../Base');
const DI = require('../../DI');
Promise.promisifyAll(redis);
Promise.promisifyAll(fs);
axios.defaults.withCredentials = true;
const logger = DI.getLogger();
class Autohome extends Base {
constructor(params) {
......@@ -45,17 +47,17 @@ class Autohome extends Base {
async tryLogin() {
// 随机返回登录状态
// return randomInt(0, 0);
// return [new errors.TryLoginError('登录失效'), randomInt(0, 1)];
let newCookies;
let oldCookies = await DealerHelper.getCookies(this.params);
let loginSuccess = false;
let loginStatus = false;
const [cookiesError, oldCookies] = await DealerHelper.getCookies(this.params);
if (oldCookies) {
const horseman = new Horseman({
ignoreSSLErrors: true
});
loginSuccess =
loginStatus =
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
......@@ -68,116 +70,104 @@ class Autohome extends Base {
await horseman.close();
}
if (loginSuccess) {
if (loginStatus) {
const params = this.params;
params.cookies = newCookies;
if (this.params.verbose) {
console.log(`accountID: ${this.params.accountID}, cookies: ${JSON.stringify(newCookies)}`);
}
logger.debug(`accountID: ${this.params.accountID}, cookies: ${JSON.stringify(newCookies)}`);
await DealerHelper.saveCookies(params);
return true;
return [null, 1];
} else {
throw new errors.TryLoginError('登录失效');
return [new errors.TryLoginError('登录失效'), 0];
}
}
async login() {
// 随机返回登录状态
// return randomInt(0, 0);
try {
console.log('开始表单登录');
// return [new errors.LoginError('登录失败'), randomInt(0, 1)];
logger.info('开始表单登录');
const username = this.params.username;
const password = this.params.password;
console.log('用户名:', username);
console.log('密码:', password);
const username = this.params.username;
const password = this.params.password;
logger.info('用户名:', username);
logger.info('密码:', password);
const horseman = new Horseman({
ignoreSSLErrors: true
});
const horseman = new Horseman({
ignoreSSLErrors: true
});
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.open('http://ics.Autohome.com.cn/passport/');
horseman.on('onResourceRequested', (requestData, networkRequest) => {
});
// 验证码存储到磁盘
const base64Text =
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.open('http://ics.Autohome.com.cn/passport/');
.screenshot('tmp/workflow/autohome/beforeCaptcha.png')
.crop('#imgValidCodeDealer', 'tmp/workflow/autohome/captcha.png')
.cropBase64('#imgValidCodeDealer', 'PNG');
horseman.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
console.log('networkRequest', networkRequest);
});
// 验证码解码
let captchaText;
try {
const captchaType = config.get(this.params.website)['captchaType'];
captchaText = await captcha.decodeBase64(captchaType, base64Text);
console.info('captchaText:', captchaText);
} catch (e) {
logger.error(e);
return;
}
// 验证码存储到磁盘
const base64Text =
await
horseman
.screenshot('tmp/workflow/autohome/beforeCaptcha.png')
.crop('#imgValidCodeDealer', 'tmp/workflow/autohome/captcha.png')
.cropBase64('#imgValidCodeDealer', 'PNG');
// 验证码解码
let captchaText;
try {
const captchaType = config.get(this.params.website)['captchaType'];
captchaText = await captcha.decodeBase64(captchaType, base64Text);
console.info('captchaText:', captchaText);
} catch (e) {
console.log(e.toString());
return;
}
// 填写登录表单
await
horseman
.type('input[id="UserNameDealer"]', username)
.type('input[id="PasswordDealer"]', password)
.type('input[id="checkCodeDealer"]', captchaText)
.screenshot('tmp/workflow/autohome/typeLoginForm.png');
// 填写登录表单
// 提交登录表单
const loginStatus =
await
horseman
.type('input[id="UserNameDealer"]', username)
.type('input[id="PasswordDealer"]', password)
.type('input[id="checkCodeDealer"]', captchaText)
.screenshot('tmp/workflow/autohome/typeLoginForm.png');
.click('[id="btnDealer"]')
.wait(1000)
// .waitForNextPage({ timeout: 10000 })
.screenshot('tmp/workflow/autohome/submitLoginForm.png')
.exists('#loginout');
if (loginStatus) {
const cookies = await horseman.cookies();
const params = this.params;
params.cookies = cookies;
// 提交登录表单
loginSuccess =
await
horseman
.click('[id="btnDealer"]')
.wait(1000)
// .waitForNextPage({ timeout: 10000 })
.screenshot('tmp/workflow/autohome/submitLoginForm.png')
.exists('#loginout');
logger.debug(`accountID: ${this.params.accountID}, cookies: ${JSON.stringify(cookies)}`);
if (loginSuccess) {
const cookies = await horseman.cookies();
const params = this.params;
params.cookies = cookies;
await DealerHelper.saveCookies(params);
}
if (this.params.verbose) {
console.log('cookies:', JSON.stringify(cookies));
}
await horseman.close();
await DealerHelper.saveCookies(params);
}
await horseman.close();
if (loginSuccess) {
return true;
} else {
throw new errors.LoginError('登录失败');
}
} catch (e) {
throw new errors.LoginError(`登录异常: ${e}`);
if (loginStatus) {
return [null, 1];
} else {
return [new errors.LoginError('登录失败'), 0];
}
}
// 抓取线索
async fetchClues() {
try {
try {
const loginSuccess = await this.retryLogin();
return;
} catch (e) {
console.log(e.message);
// TODO:登录失败可能需要重新登录
const [loginError, loginStatus] = await this.retryLogin();
if (!loginStatus) {
// TODO:需要考虑密码、验证码等因素
// TODO:如果抓取线索过程中cookie失效可能也需要尝试重新登录
return;
......@@ -209,9 +199,9 @@ class Autohome extends Base {
params.assignDealerId = 0;
const fetchByPage = async () => {
if (!rowcount) {
console.log(`线索日期: ${params.startTime} - ${params.endtime}`);
logger.info(`线索日期: ${params.startTime} - ${params.endtime}`);
}
console.log(`线索页面: ${params.pageIndex}`);
logger.info(`线索页面: ${params.pageIndex}`);
axios.get('http://ics.Autohome.com.cn/Dms/Order/SearchOrderList', {
params: params,
headers:{
......@@ -225,7 +215,7 @@ class Autohome extends Base {
if (!rowcount) {
rowcount = clueData.result.rowcount;
console.log('只进入一次总数:', rowcount);
logger.info('线索总数:', rowcount);
}
const clues = [];
......@@ -240,6 +230,7 @@ class Autohome extends Base {
// 田淮蒲 18300683353
const salesMatch = l.SalesNameStr.match(/(\S+)\s(\d+)/);
clue.customerIndex = customerIndex;
clue.customerId = idMatch[1] || 0;
clue.customerName = (cheerio.load(l.CustomerNameStr).text() || '').trim();
clue.customerPhone = (phoneAreaMatch[1] || '').trim();
......@@ -254,21 +245,12 @@ class Autohome extends Base {
clue.createdAt = l.LeadTimeStr.trim();
clues.push(clue);
console.log('客户序号:', customerIndex);
console.log('客户ID:', clue.customerId);
console.log('客户姓名:', clue.customerName);
console.log('客户号码:', clue.customerPhone);
console.log('客户地区:', clue.customerArea);
console.log('负责销售:', clue.salesmanName);
console.log('销售号码:', clue.salesPhone);
console.log('线索获得时间:', clue.createdAt);
console.log('上牌地区:', clue.licenseArea);
console.log('线索意向车型:', clue.intentionDes);
logger.debug(JSON.stringify(clue));
// TODO: just for debug, remove them later
console.log('线索类型:', clue.orderType);
console.log('线索状态:', clue.orderState);
console.log('===========================================================================');
logger.debug('线索类型:', clue.orderType);
logger.debug('线索状态:', clue.orderState);
logger.debug('===========================================================================');
}
if (this.params.dealerID) {
......@@ -282,7 +264,7 @@ class Autohome extends Base {
// 判断是否抓取完全
if (customerIndex < rowcount) {
let randomSecs = randomInt(1, 2);
console.log(`随机等待${randomSecs}秒`);
logger.info(`随机等待${randomSecs}秒`);
await Promise.delay(randomSecs*1000).then(async function() {
params.pageIndex += 1;
await fetchByPage();
......@@ -293,7 +275,7 @@ class Autohome extends Base {
await fetchByPage();
return;
} catch (e) {
console.dir(e.stack);
console.dir(e);
// throw e;
}
}
......
......@@ -45,10 +45,10 @@ class Easypass extends Base {
async tryLogin() {
// 随机返回登录状态
// return randomInt(0, 1);
// return [new errors.TryLoginError('登录失效'), randomInt(0, 1)];
let newCookies;
let oldCookies = await DealerHelper.getCookies(this.params);
let loginSuccess = false;
let loginStatus = false;
const [cookiesError, oldCookies] = await DealerHelper.getCookies(this.params);
if (oldCookies) {
console.log('oldCookies:', JSON.stringify(oldCookies));
......@@ -56,7 +56,7 @@ class Easypass extends Base {
ignoreSSLErrors: true
});
loginSuccess =
loginStatus =
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
......@@ -69,36 +69,22 @@ class Easypass extends Base {
await horseman.close();
}
if (loginSuccess) {
if (loginStatus) {
const params = this.params;
params.cookies = newCookies;
console.log('newCookies:', JSON.stringify(newCookies));
await DealerHelper.saveCookies(params);
if (this.params.task === 'tryLogin') {
console.log('尝试登陆成功');
}
return true;
return [null, 1];
} else {
throw new errors.TryLoginError('登录失效');
return [new errors.TryLoginError('登录失效'), 0];
}
}
async login() {
// 随机返回登录状态
// return randomInt(0, 1);
let loginSuccess;
try {
loginSuccess = await this.tryLogin();
} catch (e) {
console.log(e.message);
}
if (loginSuccess) {
return true;
} else {
console.log('尝试登录失败');
}
// return [new errors.LoginError('登录失败'), randomInt(0, 1)];
console.log('开始表单登录');
const username = this.params.username;
......@@ -144,16 +130,17 @@ class Easypass extends Base {
.screenshot('tmp/workflow/easypass/typeLoginForm.png');
// 提交登录表单
loginSuccess =
const loginStatus =
await
horseman
.click('[id="btnLogin"]')
.screenshot('tmp/workflow/easypass/beforeSubmitLoginForm.png')
.waitForNextPage({ timeout: 5000 })
.wait(1000)
// .waitForNextPage({ timeout: 5000 })
.screenshot('tmp/workflow/easypass/submitLoginForm.png')
.exists('#myAccountLi');
if (loginSuccess) {
if (loginStatus) {
const cookies = await horseman .cookies();
const params = this.params;
params.cookies = cookies;
......@@ -161,26 +148,25 @@ class Easypass extends Base {
await DealerHelper.saveCookies(params);
}
await horseman.close();
if (loginSuccess) {
return true;
if (loginStatus) {
return [null, 1];
} else {
throw new errors.LoginError('登录失败');
return [new errors.LoginError('登录失败'), 0];
}
}
// 抓取线索
async fetchClues() {
try {
try {
const loginSuccess = await this.retryLogin();
return;
} catch (e) {
console.log(e.message);
// 登录失败更新数据库cookie状态
const [loginError, loginStatus] = await this.retryLogin();
if (!loginStatus) {
// TODO:需要考虑密码、验证码等因素
// TODO:如果抓取线索过程中cookie失效可能也需要尝试重新登录
return;
}
const cookies = await DealerHelper.getCookies(this.params);
const [cookiesError, cookies] = await DealerHelper.getCookies(this.params);
if (cookies) {
const horseman = new Horseman({
......@@ -276,7 +262,7 @@ class Easypass extends Base {
throw new Error('no cookie');
}
} catch (e) {
throw e;
console.log(e.toString());
}
}
}
......
......@@ -12,6 +12,9 @@ async function t () {
return 't';
}
// new Buffer('hnmz147852.').toString('base64')
// new Buffer('Q2hlY2hlbmcyMzUj', 'base64').toString();
async function test (l) {
await Promise.delay(l*1000).then(async function() {
console.log('过了' + l + '秒');
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment