keywords.js 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/**
 *
 * @author: shijian<jian.shi@yoho.cn>
 * @date: 17/5/31
 */

'use strict';
const _ = require('lodash');
const Router = require('koa-router');
const moment = require('moment');
const pager = require('../utils/pager');
const Mysql = require('../../../lib/mysql-promise');
const Promise = require('bluebird');
const r = new Router();
const rp = require('request-promise');
const config = require('../../../config/config');
const ExpandModel = require('../models/expandModel');
const singleBrandKeyPre = config.singleBrandKeyPre;
const singleSortKeyPre = config.singleSortKeyPre;
const qs = require('querystring');
const lestGoodsNum = 3;
const seoModel = require('../models/seoModel');

const multiAsync=(multi)=>{
    return multi.execAsync().then(function(res) {
        return res;
    });
}

//查看
const getDataList = async(ctx, key, page, limit)=>{
    let multi = ctx.redis.multi();
    let start = (page-1)*limit;
    let end = (page)*limit-1;
    multi.lrange(key, start, end).LLEN(key);
    return multiAsync(multi);
}

const getDataValues = async(ctx, arr)=>{
    let multi = ctx.redis.multi();
    arr.forEach(item=>{
        multi.get(item);
    });
    return multiAsync(multi);
}
//删除
const delDataValues = async(ctx, arr)=>{
    let multi = ctx.redis.multi();
    arr.forEach(item=>{
        let key = `keywords_mana:${item}`;
        multi.del(key).lrem('keywords_mana_list', 1, key);
    });
    return multiAsync(multi);
}
//添加
const addDataValues = async(ctx, value)=>{
    let multi = ctx.redis.multi();
    let key=`keywords_mana:${value}`;
    multi.set(key, value);
    multi.lrem('keywords_mana_list', 1, key).lpush('keywords_mana_list', key);
    
    return multiAsync(multi);
}
//编辑
const editDataValues = async(ctx, value, oldValue)=>{
    try{
        await delDataValues(ctx, [oldValue]);
        await addDataValues(ctx, value);
        return true;
    }catch(e){
        return false;
    }
    
}
//搜索
const searchDataValues = async(ctx, value)=>{
    let multi = ctx.redis.multi();
    let key=`keywords_mana:*${value}*`;
    multi.KEYS(key);
    return multiAsync(multi);
}

const mgets = async(ctx, item) => {
    let redis = ctx.redis;
    let operation = [];
    item = _.uniq(item);

    if (item.length <= 0) {
        return Promise.resolve({});
    }

    return redis.mgetAsync(item).then(d => {
        let ddata = {};

        _.each(item, (el, index) => {
            ddata[el] = d[index];
        });

        return ddata;
    });
};

//通过小分类同步中分类和大分类
const getMsort = async(ctx) => {
    let redis = ctx.redis;

    return redis.getAsync(`global:yoho:sorts`).then((sorts) => {
        let sData = {};
        sorts = JSON.parse(sorts) || [];

        _.forEach(_.get(sorts, 'data.sort'), (msort) => {
            _.forEach(_.get(msort, 'sub'), (misort) => {
                _.forEach(_.get(misort, 'sub'), (sort) => {
                    if (!sData[sort.sort_id]) {
                        sData[sort.sort_id] = {
                            msort: msort.sort_id,
                            msort_name: msort.sort_name,
                            misort: misort.sort_id,
                            misort_name: misort.sort_name,
                            sort_id: sort.sort_id,
                            sort_name: sort.sort_name,
                        };
                    }
                })
            })
        })

        return sData;
    });
};

r.get('/', async(ctx) => {
    let resData = {};
    let q = ctx.request.query,
    page = parseInt(`0${ctx.query.page}`, 10) || 1,
    limit = parseInt(`0${ctx.query.limit}`, 10) || 10;
    let r = await getDataList(ctx, "keywords_mana_list", page, limit);
    let result = [];
    if(r[0].length)result = await getDataValues(ctx, r[0]);
    let total = r[1];
    resData.pager = pager(Math.floor((total - 1) / limit) + 1, ctx.query);
    resData.tabs = result;
    await ctx.render('action/keywords', resData);
});

r.get('/delKeywords', async(ctx) => {
    let q = ctx.request.query;
    let keys = JSON.parse(q['keywords']);
    try{
        await delDataValues(ctx, keys);
        ctx.body = {
            code: 200,
            message: 'success',
            data: ''
        };
    }catch(e){
        ctx.body = {
            code: 500,
            message: 'fail',
            data: ''
        };
    }    
});

r.get('/addKeywords', async(ctx) => {
    let q = ctx.request.query;
    let key = q['keywords'];
    try{
        await addDataValues(ctx, key);
        ctx.body = {
            code: 200,
            message: 'success',
            data: ''
        };
    }catch(e){
        ctx.body = {
            code: 500,
            message: 'fail',
            data: ''
        };
    }    
});

r.get('/editKeywords', async(ctx) => {
    let q = ctx.request.query;
    let key = JSON.parse(q['keywords']);
    try{
        await editDataValues(ctx, key[0], key[1]);
        ctx.body = {
            code: 200,
            message: 'success',
            data: ''
        };
    }catch(e){
        ctx.body = {
            code: 500,
            message: 'fail',
            data: ''
        };
    }    
});

r.get('/searchKeywords', async(ctx) => {
    let q = ctx.request.query;
    let key = q['association'];
    let r = await searchDataValues(ctx, key);
    let result = [];
    if(r[0].length)result = await getDataValues(ctx, r[0]);
    ctx.body = {
        code: 200,
        message: 'success',
        data: result,
        total:1
    }; 
});



const insertWord = (keyword, mysql) => {
    return mysql.query(`SELECT id FROM seo_keywords WHERE keyword = ? AND status = 1`, [keyword]).then(d => {
        console.log(keyword, d, '--+++++++++++++++++++++++-');
        if (d.length <= 0) {
            return mysql.query(
                `INSERT INTO seo_keywords SET keyword = ?, is_push = ?, yoho_goods_num= ?, add_time = ?`,
                [keyword, 1, -2, moment().unix()]
            );
        }
        return d;
    });
}

const getRootKeyword = (ids, mysql) => {
    let len = ids.length;
    let marks = [];

    if (len <= 0) {
        return Promise.resolve({});
    }

    for(let i = 0; i < len; i++) {
        marks.push('?');
    } 
    return mysql.query(`SELECT id, keyword FROM seo_keywords_root WHERE id IN (${marks.join(',')}) AND status = 1;`, ids).then(d => {
        let ddata = {};

        _.each(d, (item) => {
            ddata[item.id] = item.keyword;
        });

        return ddata;
    });
}

//redis关键词同步到mysql
r.get('/syncWord', async(ctx) => {
    let mysql = new Mysql();

    return getDataList(ctx, "keywords_mana_list", 0, -1).then(d => {
        return getDataValues(ctx, d[0]);
    }).then(ddata => {
        return Promise.map(ddata, (word) => insertWord(word, mysql), {concurrency: 15});
    }).then(d => {
        return ctx.body = {
            code: 200,
            message: 'success',
            data: d
        }; 
    });
});

r.get('/expand', async(ctx) => {
    let resData = {};
    let q = ctx.request.query;
    let query = q.query || '';
    let page = parseInt(`0${ctx.query.page}`, 10) || 1;
    let limit = parseInt(`0${ctx.query.limit}`, 10) || 10;
    let mysql = new Mysql();
    let total = 0;
    let typeList = [
        {
            type: 'keyword',
            name: '关键词'
        },
        {
            type: 'wordroot',
            name: '词根ID'
        },
        {
            type: 'goodnum',
            name: '商品数'
        }
    ];
    let type = q.type || typeList[0].type;
    let typeName = _.result(_.find(typeList, {'type': type}), 'name') || typeList[0].name;
    let wheres = '';
    let conditions = [];

    switch (query && type) {
        case 'keyword': 
            wheres = ` AND keyword like '%%${query}%'`;
            break;
        case 'wordroot': 
            wheres += ' AND root_id = ?'
            conditions.push(query);
            break;
        case 'brand': 
            wheres += ' AND brand_id = ?'
            conditions.push(query);
            break;
        case 'sort': 
            wheres += ' AND sort_id = ?'
            conditions.push(query);
            break;
        case 'goodnum': 
            wheres += ' AND yoho_goods_num >= ?'
            conditions.push(query);
            break;
    }

    let d = await mysql.query(`SELECT COUNT(*) as total FROM seo_keywords WHERE status = 1 ${wheres}`, conditions);

    total = d[0] && d[0].total || 0;
    conditions.push((page - 1) * limit, limit);

    d = await mysql.query(`SELECT * FROM seo_keywords WHERE status = 1 ${wheres} ORDER BY id DESC limit ?, ?`, conditions);

    let sortIds = [];
    let brandIds = [];
    let rootIds = [];

    resData.pager = pager(Math.floor((total - 1) / limit) + 1, ctx.query);

    _.each(d, (val) => {
        if (val.brand_id) {
            brandIds.push(`${singleBrandKeyPre}${val.brand_id}`);
        }

        if (val.root_id) {
            rootIds.push(val.root_id);
        }
    });

    brandIds = await mgets(ctx, brandIds);
    sortIds = await getMsort(ctx);
    rootIds = await getRootKeyword(rootIds, mysql);

    resData.tabs = _.map(d, (elem) => {
        return Object.assign({}, elem, {
            root: rootIds[elem.root_id],
            brand: brandIds[`${singleBrandKeyPre}${elem.brand_id}`],
            sort: sortIds[elem.sort_id] && sortIds[elem.sort_id].sort_name,
            misort: sortIds[elem.sort_id] && sortIds[elem.sort_id].misort_name,
            msort: sortIds[elem.sort_id] && sortIds[elem.sort_id].msort_name,
            is_push: elem.is_push ? '是' : '否',
            add_time:  elem.add_time && moment(elem.add_time * 1000).format('YYYY-MM-DD HH:mm'),
        });
    });

    resData.typeList = typeList;
    resData.typeName = typeName;
    resData.type = type;
    resData.query = query;

    return ctx.render('action/keywords/expand', resData);
});

r.post('/expand/del', async(ctx) => {
    let q = ctx.request.body;
    let ids = q.ids && JSON.parse(q.ids) || [];

    let len = ids.length;
    let marks = [];

    if (len <= 0) {
        return ctx.body = {
            code: 400,
            message: 'ids is empty',
            data: ''
        }; 
    }

    let mysql = new Mysql();
    for(let i = 0; i < len; i++) {
        marks.push('?');
    } 

    return mysql.query(`UPDATE seo_keywords SET status = 0 WHERE id IN (${marks.join(',')})`, ids).then(d => {
        return ctx.body = {
            code: 200,
            message: 'success',
            data: d
        }; 
    });
});

/**
 * [yohobuy-chanping关联词生成]
 * @param  {[type]} '/expand/randWords' [description]
 * @param  {[type]} async(ctx           [description]
 * @return {[type]}                     [description]
 */
r.post('/expand/randWords', async(ctx) => {
    let key = `global:yoho:seo:keywords:isRun`;

    return ctx.redis.getAsync(key).then((d) => {

        if (d) {
            return ctx.body = {
                code: 201,
                message: '正在执行中...'
            };
        }

        let expandModel = new ExpandModel(ctx);

        return expandModel.getRanData().then(d => {
            return ctx.body = {
                code: 200,
                message: 'success'
            };
        });
    });
});

const baiduUrls = {
    urls: 'http://data.zz.baidu.com/urls',
    update: 'http://data.zz.baidu.com/update',
    del: 'http://data.zz.baidu.com/del'
};
/**
 * 将链接推送到百度站长
 * @param params object {site: 'https://www.yohobuy.com', type: 'mip'} 默认不需要type
 * @param urls
 */
const sendUrlsToBaidu = (params, urls) => {
    let paramsDef = {
        token: config.baiduToken
    };

    // 过滤无效的参数
    _.forEach(params, (val, key) => {
        if (!val) {
            delete params[key];
        }
    });

    qs.escape = (str) => {
        return str;
    };

    let options = {
        url: `${baiduUrls.urls}?${qs.stringify(Object.assign(paramsDef, params), null, null, {})}`,
        headers: {
            'Content-Type': 'text/plain'
        },
        method: 'post',
        form: urls.join('\n'),
        json: true,
        timeout: 10000,
        gzip: true
    };

    return rp(options).then(result => {
        console.log(Object.assign(params, result, {length: urls.length}));
        if (result) {
            return true;
        } else {
            return false;
        }
    });
};
/**
 * 推送urls
 * @params limit url条数
 * @return boolean
 */
const sendUrls = (limit, page) => {

    // 调用limit条未推送关键词
    let mysql = new Mysql();

    return mysql.query(`select id, keyword from seo_keywords where is_push=0 and yoho_goods_num > ${lestGoodsNum} and status=1 order by id asc limit ${(page-1)*limit}, ${limit}`).then(d => {
        let pcPages = [],
            wapPages = [];

        _.forEach(d, (val) => {
            pcPages.push(`https://www.yohobuy.com/chanpin/${val.id}.html`);
            wapPages.push(`https://m.yohobuy.com/chanpin/${val.id}.html`);
        })

        // 根据 site 推送相应站点
        return Promise.all([sendUrlsToBaidu({site: 'https://www.yohobuy.com'}, pcPages),sendUrlsToBaidu({site: 'https://m.yohobuy.com'}, wapPages)]).then(result => {
            let updateSql = `UPDATE seo_keywords SET is_push = 1 WHERE id >= ${_.get(_.first(d), 'id')} and id <= ${_.get(_.last(d), 'id')}  and yoho_goods_num > ${lestGoodsNum} and status=1`;

            // 更新关键词推送状态
            return mysql.query(updateSql).then(updateRes => {
                return updateRes;
            });
        })
    });
}

const getPushTotal = () => {
    let mysql = new Mysql();

    return mysql.query(`select count(id) from seo_keywords where  is_push=0 and yoho_goods_num > ${lestGoodsNum} and status=1`).then(d=>{
        return _.get(d, '0.count(id)', 0);
    });
}

/**
 * 推送url到百度(获取2000条未推送关键词,监测是否还有未推关键词,如果有再推2000,直到全部推送)
 */

r.get('/sendUrl', async(ctx, next) => {
    let result = {
        code: 200,
        message: '暂未开放!'
    };

    let total = await getPushTotal(); // 待推送总数

    let limit = 2000; // 每次推送的条数

    if (total === 0) {
        result.message = '没有需要推送的词!';
    } else {
        let intervalTime = Math.floor(total/limit) + 1;

        // 推送2000条
        let interval = setInterval(() => {
                sendUrls(limit, intervalTime);

            if (--intervalTime < 1) {
                clearInterval(interval);
            }

        }, 1000);
        result.message = `${intervalTime*10} 秒后查看推送结果`;
    }
    ctx.response.body = result;
});

r.get('/add', async (ctx) => {

    let model = new seoModel(ctx);
    let resData = await model.addRootWordsData();

    await ctx.render('action/keywords/add', Object.assign(resData, {
        title: '添加关键词'
    }));
});

r.post('/add', async (ctx) => {
    let mysql = new Mysql();
    let keyword = ctx.request.body.keywords || '';
    let brand = ctx.request.body.brand || 0;
    let msort = ctx.request.body.msort || 0;
    let misort = ctx.request.body.misort || 0;
    let sort = ctx.request.body.sort || 0;
    let addTime = Date.parse(new Date())/1000;

    let result = {code: 400, message: ''};

    if (_.isEmpty(keyword)) {
        selectSql.message = '关键词必填';
        return ctx.response.body = result;
    }

    let select = await mysql.query(`select id from seo_keywords where keyword='${keyword}' limit 1`);

    if (_.get(select, '[0].id', 0) > 0) {
        result.message = '关键词已经存在';
        return ctx.response.body = result;
    }

    await mysql.query(`insert into seo_keywords (keyword, brand_id, msort, misort, sort_id, add_time) values ('${keyword}', ${brand}, ${msort}, ${misort}, ${sort}, ${addTime})`);

    result.code = 200;
    return ctx.response.body = result;
})
module.exports = r;