This repository has been archived on 2024-02-26. You can view files and clone it, but cannot push or open issues or pull requests.
line-cost-js/CPBLClass.js
2021-12-26 15:15:28 +08:00

404 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const dateFormat = require('dateformat');
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const schedule = require('node-schedule');
const { decode } = require('querystring');
const LINENotifyClass = require('../api/LINENotifyClass');
/** CPBL */
class CPBLClass {
constructor(app) {
this.app = app;
this.LINENotify = new LINENotifyClass();
this.TimeList = [];
// var rule = new schedule.RecurrenceRule();
// // rule.minute = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
// rule.second = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
// // console.log(`設定任務 每${JSON.stringify(rule.minute)}分鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
// console.log(`設定任務 每${JSON.stringify(rule.second)}秒鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
// this.Timer = schedule.scheduleJob(rule, this.Update.bind(this));
}
async Update() {
// let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
// console.log("執行任務 現在時間: " + datetime);
// if (dateFormat(new Date(), "ss") === "00") {
// this.Timer.cancel();
// // console.log("取消任務 現在時間: " + datetime);
// }
if (this.TimeList.length > 0) {
for (let i = 0; i < this.TimeList.length; i++) {
this.RunTime(this.TimeList[i]);
}
} else {
this.CloseTime();
}
}
async AddTime(Data, event) {
let replyMsg = "";
let GameSno = Data["GameSno"];
let LineID = Data["LineID"];
let access_token = Data["access_token"];
let IsHaveGameSno = false;
let IsHaveLineID = false;
let Time = {
GameSno: GameSno,
LineID: [LineID],
access_token: [access_token]
}
for (let i = 0; i < this.TimeList.length; i++) {
if (this.TimeList[i]["GameSno"] === GameSno) {
IsHaveGameSno = true;
Time = this.TimeList[i];
for (let j = 0; j < this.TimeList[i]["LineID"].length; j++) {
if (this.TimeList[i]["LineID"][j] === LineID) {
IsHaveLineID = true;
break;
}
}
break;
}
}
let IsRUN = true;
let Response = await this.GetCPBL(GameSno);
if (Response === "比賽尚未開始" || Response[Response.length - 1].indexOf("比賽結束") !== -1) {
IsRUN = false;
}
if (Response === "比賽尚未開始") {
// await this.LINENotify.Send(access_token, Response);
} else {
let PushMsg = "";
for (let i = 0; i < Response.length; i++) {
let ThisPushMsg = Response[i];
if (PushMsg.length + ThisPushMsg.length > 1000) {
// await this.LINENotify.Send(access_token, PushMsg);
PushMsg = ThisPushMsg;
} else {
PushMsg += ThisPushMsg;
}
}
// await this.LINENotify.Send(access_token, PushMsg);
}
if (IsRUN) {
if (!IsHaveGameSno) {
// 沒有這場賽事
if (this.TimeList.length === 0) {
this.StartTime();
}
this.TimeList.push(Time);
} else if (IsHaveGameSno && !IsHaveLineID) {
// 有這場賽事但沒這個帳號
Time["LineID"].push(LineID);
Time["access_token"].push(access_token);
}
let Extra = {
GameSno: GameSno,
count: Response.length
}
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='CPBL RUN', \`Extra\`='${JSON.stringify(Extra)}' WHERE (\`userid\`='${LineID}');`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
} else {
replyMsg = "已停止中職轉播功能";
}
if (event) {
event.reply(replyMsg).then(function (data) {
// 當訊息成功回傳後的處理
}).catch(function (error) {
// 當訊息回傳失敗後的處理
});
}
}
StartTime() {
// var rule = '2 * * * * *';
// * * * * * *
// ┬ ┬ ┬ ┬ ┬ ┬
// │ │ │ │ │ |
// │ │ │ │ │ └ 星期几取值0 - 7其中 0 和 7 都表示是周日
// │ │ │ │ └─── 月份取值1 - 12
// │ │ │ └────── 日期取值1 - 31
// │ │ └───────── 时取值0 - 23
// │ └──────────── 分取值0 - 59
// └─────────────── 秒取值0 - 59可选
var rule = new schedule.RecurrenceRule();
// rule.date = "*";
// rule.dayOfWeek = "*";
// rule.hour = "*";
// rule.minute = "*";
// rule.year = "*";
// rule.month = "*";
let minute = 2;
let minute_arr = [];
for (let i = 0; i < 60; i++) {
if (i % minute === 0) {
minute_arr.push(i);
}
}
rule.second = new schedule.Range(0, 59, 2);
// rule.minute = minute_arr;
// rule.second = [0];
// rule.second = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
// console.log(`設定任務 每${minute}分鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
console.log(`設定任務 每${minute}秒鐘 現在時間: ` + dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss"));
// this.Timer = schedule.scheduleJob(rule, this.Update.bind(this));
this.Timer = schedule.scheduleJob(rule, () => {
console.log(`現在時間: ${dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss")}`);
});
}
CloseTime() {
this.Timer.cancel();
}
async GetCPBL(GameSno) {
let Data = {
GameSno: GameSno,
KindCode: "A",
Year: dateFormat(new Date(), "yyyy")
};
let url = "https://jianmiau.ml:3333/CPBL";
let Response = await this.GetData(url, Data);
Response = JSON.parse(Response);
// Response = [].concat.apply([], JSON.parse(Response));
return new Promise((resolve, reject) => {
// 傳入 resolve 與 reject表示資料成功與失敗
resolve(Response);
// reject()
});
}
DelTime(game_id) {
for (let i = 0; i < this.TimeList.length; i++) {
if (this.TimeList[i]["game_id"] === game_id) {
this.TimeList.splice(i, 1);
if (this.TimeList.length === 0) {
this.CloseTime();
}
}
}
}
async RunTime(Time) {
let GameSno = Time["GameSno"];
let LineID = Time["LineID"];
let access_token = Time["access_token"];
let Response = await this.GetCPBL(GameSno);
let IsRUN = true;
if (Response === "比賽尚未開始" || Response[Response.length - 1].indexOf("比賽結束") !== -1) {
IsRUN = false;
}
for (let i = 0; i < LineID.length; i++) {
let Query = `SELECT * FROM \`line-cost-status\` WHERE \`userId\` = '${LineID[i]}' LIMIT 1;`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
let Data = res_Query;
let Status = Data[0]['Status'];
if (Status === "CPBL RUN") {
let Extra = JSON.parse(Data[0]["Extra"]);
let GameSno = Extra["GameSno"];
let count = Extra["count"];
if (Response.length > count) {
let PushMsg = "";
for (let i = count; i < Response.length; i++) {
let ThisPushMsg = Response[i];
if (PushMsg.length + ThisPushMsg.length > 1000) {
await this.LINENotify.Send(access_token, PushMsg);
PushMsg = ThisPushMsg;
} else {
PushMsg += ThisPushMsg;
}
}
await this.LINENotify.Send(access_token, PushMsg);
if (IsRUN) {
let Extra = {
GameSno: GameSno,
count: Response.length
}
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='CPBL RUN', \`Extra\`='${JSON.stringify(Extra)}' WHERE (\`userid\`='${LineID[i]}');`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
} else {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
let Query = `UPDATE \`line-cost-status\` SET \`datetime\`='${datetime}', \`Status\`='', \`Extra\`='' WHERE (\`userid\`='${LineID[i]}');`;
let res_Query = await this.app.Tools_MYSQLDB.Query(Query);
PushMsg = "已停止中職轉播功能";
let res_Msg = this.app.bot.push(LineID[i], PushMsg);
}
// await this.LINENotify.Send(access_token, PushMsg);
}
}
}
if (!IsRUN) {
this.DelTime(game_id);
}
}
async GetCPBLList(DateTime, access_token) {
// let game_id = Time["game_id"];
// let cpbldata = Time["cpbldata"];
// let LineID = Time["LineID"];
let url = "https://jianmiau.ml:3333/CPBLList";
let Data = {
today: DateTime
// today: "2021-09-26"
};
let Response = await this.GetData(url, Data);
Response = [].concat.apply([], JSON.parse(Response));
let columns = [];
for (let i = 0; i < Response.length; i++) {
let img = [];
let team = [];
let data = "";
let game = Response[i];
let info = {
"樂天桃猿": {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/R.png"
},
"富邦悍將": {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/F.png"
},
"味全龍": {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/D.png"
},
"中信兄弟": {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/B.png"
},
"統一7-ELEVEn獅": {
img: "https://jianmiau.ml/MyWeb/Resources/CPBL/L.png"
},
}
let url = `https://karolchang.github.io/cpbl-vue/#/record/${game.GameSno}/A/2021`;
let gametime = game.PreExeDate.split("T");
// let nowUNIXtime = Date.now();
// let gameUNIXtime = new Date(`${gametime[0]} ${gametime[1]}`).getTime();
// let IsStart = nowUNIXtime - gameUNIXtime > 0;
data = `action=hasgame&game_date=${gametime[0]}&time=${gametime[1]}&GameSno=${game.GameSno}&access_token=${access_token}`;
let Data_columns = {
"thumbnailImageUrl": info[game.HomeTeamName].img,
"imageBackgroundColor": "#FFFFFF",
"title": `${game.VisitingTeamName} VS ${game.HomeTeamName}`,
"text": `比賽場地 ${game.FieldAbbe} ${gametime[0]} ${gametime[1]}`,
"defaultAction": {
"type": "uri",
"label": "比賽網站",
"uri": url
},
"actions": [
{
// "type": "uri",
// "label": "比賽網站",
// "uri": url
"type": "postback",
"label": "追蹤比賽",
"data": data
}
]
};
columns.push(Data_columns);
}
// columns = [
// {
// "thumbnailImageUrl": "https://jianmiau.ml/MyWeb/Resources/CPBL/L.png",
// "imageBackgroundColor": "#FFFFFF",
// "title": "this is menu",
// "text": "description",
// "defaultAction": {
// "type": "uri",
// "label": "View detail",
// "uri": "http://example.com/page/123"
// },
// "actions": [
// {
// "type": "postback",
// "label": "Buy",
// "data": "action=buy&itemid=111"
// }
// ]
// },
// {
// "thumbnailImageUrl": "https://jianmiau.ml/MyWeb/Resources/CPBL/B.png",
// "imageBackgroundColor": "#000000",
// "title": "this is menu",
// "text": "description",
// "defaultAction": {
// "type": "uri",
// "label": "View detail",
// "uri": "http://example.com/page/222"
// },
// "actions": [
// {
// "type": "postback",
// "label": "Buy",
// "data": "action=buy&itemid=222"
// }
// ]
// }
// ]
return new Promise((resolve, reject) => {
// 傳入 resolve 與 reject表示資料成功與失敗
resolve(columns);
// reject()
});
}
async CPBLBind(Date) {
let url = `https://notify-bot.line.me/oauth/authorize?response_type=code&scope=notify&response_mode=form_post&client_id=Jj4K1D7XxtmDeXJGF3c0vV&redirect_uri=https://jianmiau.ml:3333/LINENotify&state=${userId}$${displayName}`;
let shorturl = await this.Tools.shorturl(url);
let Data_columns = [
{
"thumbnailImageUrl": "https://www.line-community.me/awards/uimage/5b46aedf851f74a6af8eaab8",
"imageBackgroundColor": "#FFFFFF",
"title": "點擊綁定",
"text": "點擊後將會進行綁定",
"defaultAction": {
"type": "uri",
"label": "點擊綁定",
"uri": shorturl
},
"actions": [
{
"type": "uri",
"label": "點擊綁定",
"uri": shorturl
}
]
}
];
return new Promise((resolve, reject) => {
// 傳入 resolve 與 reject表示資料成功與失敗
resolve(Data_columns);
// reject()
});
}
/**
* 取得表
* @param Url Url
* @param arrange 是否需要整理
*/
GetData(Url, Data) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 400) {
var response = xhr.responseText;
resolve(response);
} else {
reject("");
}
}
};
xhr.open("POST", Url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(Data));
});
}
}
module.exports = CPBLClass