app.js 9.51 KB
var express = require('express');
const request = require('request');
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const TOKEN = 'OVIxKODBqM8Pn2dpFtFeSLsDbBvApfTu88rh8wFGOzfvgvPjmBH0A4XKii97VxIDO9shYyTix4qGq32vwvL895Rbss5VSVEiU/XG5lOdyTLgECkSQKOdObSetZwcVHbGmzZJ+0Cz5vZrB5KuImOwrwdB04t89/1O/w1cDnyilFU='
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "2017103989.oss2021.tk"
const sslport = 23023;

const bodyParser = require('body-parser');
var app = express();


var holder1 = '';
var holder2 = '';



app.use(bodyParser.json());
app.post('/hook', function (req, res) {

    var eventObj = req.body.events[0];
    var source = eventObj.source;
    var message = eventObj.message;
    // request log
    console.log('======================', new Date() ,'======================');
    console.log('[request]', req.body);
    console.log('[request source] ', eventObj.source);
    console.log('[request message]', eventObj.message);
    if(eventObj.type == 'postback')
    {   
        if(eventObj.postback.data == 'action=datetemp&selectId=1')
        {
            console.log("optimizer 실행")
            app.use('/simages', express.static(__dirname + '/src'));
            optimizer(eventObj.replyToken, holder1, holder2, eventObj.postback.params.date)
            app.use('/simages', express.static(__dirname + '/src'));
        }
    }
    else
    {
        if(eventObj.message.text.indexOf(' ') != -1)
        {   
            date(eventObj.replyToken, eventObj.message.text)
        }
        else
        {
            basicinform(eventObj.replyToken, eventObj.message.text)
        }

    }
    

    res.sendStatus(200);
    
});

function basicinform(replyToken, message) {
    var pystring;
    const spawn = require("child_process").spawn;
    const process = spawn("python", ["basic.py", message]);
    const Callback = (data) => {
        pystring = data.toString();
        if(pystring[0] == '1')
        {
            pystring = pystring.replace('1현', '현');
            request.post(
                {
                    url: TARGET_URL,
                    headers: {
                        'Authorization': `Bearer ${TOKEN}`
                    },
                    json: {
                        "replyToken":replyToken,
                        "messages":[
                            {
                                "type":"text",
                                "text":pystring
                            }
                        ]
                    }
                },(error, response, body) => {
                    console.log(body)
                });
        }
        else
        {
            var candarr = pystring.split('\n')
            request.post(
                {
                    url: TARGET_URL,
                    headers: {
                        'Authorization': `Bearer ${TOKEN}`
                    },
                    json: {
                        "replyToken":replyToken,
                        "messages":[
                            {
                                "type": "text",
                                "text": pystring,
                                "quickReply": {
                                  "items": [
                                    {
                                      "type": "action",
                                      "action": {
                                        "type": "message",
                                        "label": candarr[0],
                                        "text": candarr[0]
                                      }
                                    },
                                    {
                                      "type": "action",
                                      "action": {
                                        "type": "message",
                                        "label": candarr[1],
                                        "text": candarr[1]
                                      }
                                    },
                                    {
                                        "type": "action",
                                        "action": {
                                          "type": "message",
                                          "label": candarr[2],
                                          "text": candarr[2]
                                        }
                                    }
                                  ]
                                }
                              }
                        ]
                        
                    }
                },(error, response, body) => {
                    console.log(body)
                });
        }
    };
    process.stdout.on("data", Callback);
}

function optimizer(replyToken, stock1, stock2, sdate) {
    sdate = sdate.toString();
    console.log(typeof(stock1), typeof(stock2), typeof(sdate))
    console.log(stock1, stock2, sdate)
    const spawn = require("child_process").spawn;
    const process = spawn("python", ["optimizer.py", stock1, stock2, sdate]);
    const Callback = (data) => {
        console.log(stock1, stock2, sdate)
        request.post(
            {
                url: TARGET_URL,
                headers: {
                    'Authorization': `Bearer ${TOKEN}`
                },
                json: {
                    "replyToken":replyToken,
                    "messages":[
                        {
                            "type":"text",
                            "text":'조회하신 ' + holder1 +', ' + holder2 + '의 백테스트 결과입니다.'
                        },
                        {
                            "type":"image",
                            "originalContentUrl": "https://2017103989.oss2021.tk:23023/simages/test.png",
                            "previewImageUrl": "https://2017103989.oss2021.tk:23023/simages/test.png"                            
                        }
                    ]
                }
            },(error, response, body) => {
            console.log(body)
            });
    }
    process.stdout.on("data", Callback);
}

function date(replyToken, message) {
    var holder = message.split(' ')
    holder1 = holder[0]
    holder2 = holder[1]
    var today = new Date();   
    var year = today.getFullYear();
    var month = today.getMonth() + 1;
    var date = today.getDate();
    if(month < 10)
    {
        month = '0'+ month  
    }
    if(date < 10)
    {
        date = '0'+ date  
    }
    var stoday = year + '-' + month + '-' + date;


    const messageObject = {
        "type": "template",
        "altText": "this is a buttons template",
        "template": {
            "type": "buttons",
            "title": "조회하실 날짜를 선택하세요.",
            "text": "선택하신 날짜에서 현재(오늘)까지 조회됩니다.",
            "actions": [
                {
                  "type": "datetimepicker",
                  "label": "날짜 선택",
                  "mode": "date",
                  "initial":"2020-01-01",
                  "max":stoday,
                  "min":"2010-01-01",
                  "data": "action=datetemp&selectId=1"
                },
                {
                  "type": "postback",
                  "label": "처음부터 다시할래요",
                  "data": "action=cancel&selectId=2"
                },
            ]
        }
    };
    request.post(
        {
            url: TARGET_URL,
            headers: {
                'Authorization': `Bearer ${TOKEN}`
            },
            json: {
                "replyToken":replyToken,
                "messages":[
                    // {
                    //     "type":"text",
                    //     "text":'조회하실 날짜를 선택하세요. 선택하신 날짜에서 현재까지 조회됩니다.',
                    //     "quickReply": {
                    //         "items": [
                    //             {
                    //             "type": "action",
                    //             "action": {
                    //             "type": "datetimepicker",
                    //             "label":"날짜 선택하기",
                    //             "data":"storeId=12345",
                    //             "mode":"date",
                    //             "initial":"2015-01-01",
                    //             "max":stoday,
                    //             "min":"2010-01-01"
                    //                 }
                    //             }
                    //         ]
                    //     }
                    // },
                    // {
                    //     "type":"text",
                    //     "text":req.body.postback.params
                    // }
                    messageObject
                ]

                
            }
        },(error, response, body) => {
        console.log(body)
        });

    

}

try {
    const option = {
      ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
      key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
      cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
    };
  
    HTTPS.createServer(option, app).listen(sslport, () => {
      console.log(`[HTTPS] Server is started on port ${sslport}`);
    });
  } catch (error) {
    console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
    console.log(error);
  }