Browse Source

fetch chat and messages

master
jefry 4 years ago
parent
commit
d300e49ecc
12 changed files with 283 additions and 64 deletions
  1. +52
    -0
      api/chats/config/routes.json
  2. +8
    -0
      api/chats/controllers/chats.js
  3. +8
    -0
      api/chats/models/chats.js
  4. +33
    -0
      api/chats/models/chats.settings.json
  5. +8
    -0
      api/chats/services/chats.js
  6. +1
    -0
      api/message/controllers/message.js
  7. +18
    -8
      api/message/models/message.settings.json
  8. +8
    -0
      api/session-data/services/session-data.js
  9. +48
    -48
      config/functions/cron.js
  10. +9
    -8
      model/messageModel.js
  11. +1
    -0
      package.json
  12. +89
    -0
      util/util.js

+ 52
- 0
api/chats/config/routes.json View File

@@ -0,0 +1,52 @@
{
"routes": [
{
"method": "GET",
"path": "/chats",
"handler": "chats.find",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/chats/count",
"handler": "chats.count",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/chats/:id",
"handler": "chats.findOne",
"config": {
"policies": []
}
},
{
"method": "POST",
"path": "/chats",
"handler": "chats.create",
"config": {
"policies": []
}
},
{
"method": "PUT",
"path": "/chats/:id",
"handler": "chats.update",
"config": {
"policies": []
}
},
{
"method": "DELETE",
"path": "/chats/:id",
"handler": "chats.delete",
"config": {
"policies": []
}
}
]
}

+ 8
- 0
api/chats/controllers/chats.js View File

@@ -0,0 +1,8 @@
'use strict';

/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/concepts/controllers.html#core-controllers)
* to customize this controller
*/

module.exports = {};

+ 8
- 0
api/chats/models/chats.js View File

@@ -0,0 +1,8 @@
'use strict';

/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/concepts/models.html#lifecycle-hooks)
* to customize this model
*/

module.exports = {};

+ 33
- 0
api/chats/models/chats.settings.json View File

@@ -0,0 +1,33 @@
{
"kind": "collectionType",
"collectionName": "chats",
"info": {
"name": "Chats",
"description": ""
},
"options": {
"increments": true,
"timestamps": true,
"draftAndPublish": true
},
"attributes": {
"session_key": {
"model": "session-data"
},
"name": {
"type": "string"
},
"unreadCount": {
"type": "integer"
},
"chatId": {
"type": "json"
},
"phoneNumber": {
"type": "string"
},
"timestamp": {
"type": "datetime"
}
}
}

+ 8
- 0
api/chats/services/chats.js View File

@@ -0,0 +1,8 @@
'use strict';

/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/concepts/services.html#core-services)
* to customize this service
*/

module.exports = {};

+ 1
- 0
api/message/controllers/message.js View File

@@ -28,6 +28,7 @@ module.exports = {
});
if (data["TYPE"] == "READY") {
result = await messageModel.getAllChats();
console.log(JSON.stringify(result["DATA"]));
}
ctx.body = result;
} catch (e) {


+ 18
- 8
api/message/models/message.settings.json View File

@@ -11,7 +11,7 @@
"draftAndPublish": true
},
"attributes": {
"send_to": {
"to": {
"type": "string",
"regex": "\\+?([ -]?\\d+)+|\\(\\d+\\)([ -]\\d+)",
"required": true
@@ -27,21 +27,31 @@
"plugin": "upload",
"required": false
},
"template_key": {
"model": "message-template"
},
"state": {
"type": "string",
"private": false
},
"raw_text": {
"body": {
"type": "string"
},
"session_datum_key": {
"model": "session-data"
},
"keterangan": {
"type": "string"
},
"isForwarded": {
"type": "boolean",
"default": false
},
"chat_key": {
"model": "chats"
},
"from": {
"type": "string"
},
"messageId": {
"type": "string"
},
"timestamp": {
"type": "datetime"
}
}
}

+ 8
- 0
api/session-data/services/session-data.js View File

@@ -14,4 +14,12 @@ module.exports = {
});
return arrKeys;
},
sessionCheck: async (sessionId) => {
const sessions = await strapi.api["session-data"].services[
"session-data"
].getId({
_sort: "phonenumber:desc",
});
return sessions.includes(sessionId);
},
};

+ 48
- 48
config/functions/cron.js View File

@@ -1,5 +1,6 @@
"use strict";
const messageModel = require("../../model/messageModel");
const utils = require("../../util/util");
const { parseMultipartData, sanitizeEntity } = require("strapi-utils");
/**
* Cron config that gives you an opportunity
@@ -71,57 +72,56 @@ module.exports = {
if (Object.keys(clients).length == 0) taskSendingMessage = false;
else {
for (const i of Object.keys(clients)) {
const sessions = await strapi.api["session-data"].services[
var sessionsValid = await strapi.api[
"session-data"
].getId({
_sort: "phonenumber:desc",
});
if (!sessions.includes(parseInt(i))) {
].services["session-data"].sessionCheck(parseInt(i));
if (!sessionsValid) {
delete clients[parseInt(i)];
} else {
const messages = await strapi.api.message.services.message.find(
{
_sort: "session_datum_key:desc",
state: "QUEUE",
session_datum_key: i,
}
);
for (const message of messages) {
// console.log(clients[i] != null, i, clients);
try {
if (clients[i] != null) {
await strapi.api.message.services.message.update(
{ id: message.id },
{ state: "SENDING" }
);
let send = await messageModel.sendMessage(
clients[i],
message["send_to"],
message["raw_text"]
);
// console.log(send);
if (send["STATUS"] == 1) {
await strapi.api.message.services.message.update(
{ id: message.id },
{ state: "SENT" }
);
} else {
await strapi.api.message.services.message.update(
{ id: message.id },
{
state: "ERROR",
keterangan: send["DATA"],
}
);
}
}
} catch (e) {
await strapi.api.message.services.message.update(
{ id: message.id },
{ state: "ERROR", keterangan: e.message }
);
}
}
// const messages = await strapi.api.message.services.message.find(
// {
// _sort: "session_datum_key:desc",
// state: "QUEUE",
// session_datum_key: i,
// }
// );
// for (const message of messages) {
// // console.log(clients[i] != null, i, clients);
// try {
// if (clients[i] != null) {
// await strapi.api.message.services.message.update(
// { id: message.id },
// { state: "SENDING" }
// );
// let send = await messageModel.sendMessage(
// clients[i],
// message["send_to"],
// message["raw_text"]
// );
// // console.log(send);
// if (send["STATUS"] == 1) {
// await strapi.api.message.services.message.update(
// { id: message.id },
// { state: "SENT" }
// );
// } else {
// await strapi.api.message.services.message.update(
// { id: message.id },
// {
// state: "ERROR",
// keterangan: send["DATA"],
// }
// );
// }
// }
// } catch (e) {
// await strapi.api.message.services.message.update(
// { id: message.id },
// { state: "ERROR", keterangan: e.message }
// );
// }
// }
await utils.refreshChat(clients[i], parseInt(i));
}
}
taskSendingMessage = false;


+ 9
- 8
model/messageModel.js View File

@@ -159,23 +159,24 @@ var sendMessage = async function (client, phone_number, textMessage) {
}
};

var getChatbyPhoneNumber = async function (phone_number) {
var getMessagebyId = async function (client, chatId, param = {}) {
try {
if (!client.info) {
throw { message: "Client Is Not Ready !" };
}
let phoneNumber = reformatMobilePhone(phone_number);
let chats = await client.getChatById(phoneNumber);
let messageList = await chats.fetchMessages();
var chat = await client.getChatById(chatId._serialized);
var messageList = await chat.fetchMessages(param);
// console.log(messageList);
return { STATUS: 1, DATA: messageList };
} catch (e) {
// console.log(e);
return { STATUS: 0, DATA: e.message };
}
};

var getAllChats = async function () {
var getAllChats = async function (client) {
try {
if (!client.info) {
if (!client || !client.info) {
throw { message: "Client Is Not Ready !" };
}
let chatList = await client.getChats();
@@ -255,7 +256,7 @@ module.exports = {
destroySession: destroySession,
getClientState: getClientState,
getClientState: getClientState,
getChatbyPhoneNumber: getChatbyPhoneNumber,
asyncLoadClient: asyncLoadClient,
getMessagebyId: getMessagebyId,
getAllChats: getAllChats,
asyncLoadClient: asyncLoadClient,
};

+ 1
- 0
package.json View File

@@ -12,6 +12,7 @@
"devDependencies": {},
"dependencies": {
"knex": "<0.20.0",
"moment": "^2.29.1",
"mysql": "latest",
"qrcode-terminal": "^0.12.0",
"strapi": "3.4.1",


+ 89
- 0
util/util.js View File

@@ -0,0 +1,89 @@
"use strict";
const messageModel = require("../model/messageModel");
const { parseMultipartData, sanitizeEntity } = require("strapi-utils");
const moment = require("moment");

const refreshChat = async function (client, sessionsId) {
try {
if (client && sessionsId) {
var chatId;
var result = await messageModel.getAllChats(client);
if (result["STATUS"] == 1) {
for (var i = 0; i < result["DATA"].length; i++) {
var chatsExist = await strapi.api["chats"].services[
"chats"
].findOne({
session_key: sessionsId,
phoneNumber: result["DATA"][i]["id"].user,
});
if (!chatsExist) {
await strapi.query("chats").create({
session_key: sessionsId,
name: result["DATA"][i]["name"],
unreadCount: result["DATA"][i]["unreadCount"],
timestamp: moment
.unix(result["DATA"][i]["timestamp"])
.toDate(),
chatId: result["DATA"][i]["id"],
phoneNumber: result["DATA"][i]["id"].user,
});
chatsExist = await strapi.api["chats"].services[
"chats"
].findOne({
session_key: sessionsId,
phoneNumber: result["DATA"][i]["id"].user,
});
}
chatId = chatsExist.id;
var messages = await messageModel.getMessagebyId(
client,
result["DATA"][i]["id"]
);
if (messages["STATUS"] == 1) {
for (var j = 0; j < messages["DATA"].length; j++) {
var Exist = await strapi.api["message"].services[
"message"
].findOne({
messageId: messages["DATA"][j]["id"].id,
});
if (!Exist) {
// console.log(chatId);
await strapi.query("message").create({
messageId: messages["DATA"][j]["id"].id,
to: messages["DATA"][j]["to"],
from: messages["DATA"][j]["from"],
body: messages["DATA"][j]["body"],
state: messages["DATA"][j]["fromMe"]
? "SENT"
: "RECIEVED",
isForwarded:
messages["DATA"][j]["isForwarded"] ==
undefined
? false
: messages["DATA"][j][
"isForwarded"
],
chat_key: chatId,
timestamp: moment
.unix(messages["DATA"][j]["timestamp"])
.toDate(),
});
}
}
}
}
} else {
throw { message: result["DATA"] };
}
}

// console.log("done populating chats");
} catch (e) {
console.log("error", e.message || e);
// return { STATUS: 0, DATA: e.message || e };
}
};

module.exports = {
refreshChat: refreshChat,
};

Loading…
Cancel
Save