Skip to content

Commit 0ccd4b7

Browse files
committed
add channel line
1 parent 1906c74 commit 0ccd4b7

File tree

5 files changed

+136
-10
lines changed

5 files changed

+136
-10
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { PUBLIC_DOMAIN } from "@/config";
2+
import axios from "axios";
3+
import { Request, Response } from "express";
4+
import { BaseChannel } from "./base.channel";
5+
6+
export class LineChannel extends BaseChannel {
7+
pageToken: string;
8+
linePostURL: string;
9+
credentials: string;
10+
11+
constructor(id: string, contactId: string, contactName: string, channelType: string, credentials: string) {
12+
super(id, contactId, contactName, channelType);
13+
14+
let parseCredentials: LineChannel;
15+
16+
this.credentials = credentials;
17+
18+
if (credentials && typeof credentials == 'string') parseCredentials = JSON.parse(credentials);
19+
20+
if (parseCredentials) {
21+
this.pageToken = parseCredentials.pageToken;
22+
}
23+
24+
this.channelType = channelType;
25+
this.linePostURL = `https://api.line.me/v2/bot`;
26+
}
27+
28+
public async registerWebhook() {
29+
try {
30+
await axios({
31+
method: 'PUT',
32+
url: this.linePostURL + '/channel/webhook/endpoint',
33+
data: { endpoint: PUBLIC_DOMAIN + '/webhook/' + this.contactId },
34+
headers: {
35+
Authorization: `Bearer ${this.pageToken}`,
36+
'Content-Type': 'application/json',
37+
},
38+
});
39+
console.log(`[LIN] Registered webhook for ${this.channelType} - ${this.contactName} ${this.contactId}`);
40+
} catch (e) {
41+
console.log(`[LIN] Can not register webhook for ${this.channelType} - ${this.contactName} ${this.contactId}`);
42+
43+
}
44+
}
45+
46+
async getLineUserID() {
47+
try {
48+
const { data } = await axios({
49+
method: 'GET',
50+
url: this.linePostURL + '/info',
51+
headers: {
52+
Authorization: `Bearer ${this.pageToken}`,
53+
},
54+
});
55+
if (!data || !data.userId) throw new Error();
56+
57+
return data.userId;
58+
} catch (e) {
59+
console.log(`[LIN] Can not get user ID for ${this.channelType} - ${this.contactName} ${this.contactId}`);
60+
}
61+
}
62+
63+
async prepareMessage(req: Request, res: Response) {
64+
try {
65+
const { destination, events } = req.body;
66+
67+
if (!(events && events[0] && events[0].type == 'message')) return;
68+
69+
const lineUserId = await this.getLineUserID();
70+
71+
if (destination == lineUserId) {
72+
const { message, source } = events[0];
73+
74+
await this.postMessageToBot({ userId: source.userId, message: message.text, data: null });
75+
76+
console.log(`[LIN] Sent message: ${message.text} from ${lineUserId} to Bot`);
77+
}
78+
} catch (e) {
79+
console.log(`[LIN] ${this.contactId} Can not send message to Bot - ${e.message}`);
80+
}
81+
}
82+
83+
public async sendMessageToUser({ userId, text }) {
84+
const lineUserId = await this.getLineUserID();
85+
try {
86+
if (!text) return;
87+
88+
await axios({
89+
method: 'POST',
90+
url: this.linePostURL + '/message/push',
91+
data: {
92+
to: userId,
93+
messages: [{ type: 'text', text }],
94+
},
95+
headers: {
96+
Authorization: 'Bearer ' + this.pageToken,
97+
},
98+
})
99+
} catch (e) {
100+
console.log(`[LIN] Send message to User ${lineUserId} failed`);
101+
}
102+
}
103+
}

server/src/channels/messenger.channel.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export class MessengerChannel extends BaseChannel {
3333
let challenge = req.query['hub.challenge'];
3434

3535
if (mode === 'subscribe' && this.webhookSecret == token) {
36-
console.log(`channel ${this.channelType} - ${this.contactName} ${this.contactId} webhook verified!`);
36+
console.log(`[MSG] channel ${this.channelType} - ${this.contactName} ${this.contactId} webhook verified!`);
3737
return challenge;
3838
} else {
3939
console.error(`[MSG] Verification channel ${this.channelType} - ${this.contactName} ${this.contactId} failed!`);
@@ -89,9 +89,9 @@ export class MessengerChannel extends BaseChannel {
8989
message: { text },
9090
},
9191
});
92-
console.log(`[MSG] Sent: ${text} to ${userId}`);
92+
console.log(`[MSG] Sent message: ${text} from ${userId} to Bot`);
9393
} catch (e) {
94-
console.log(`[MSG] ${this.contactId} Can not send message to messenger ${e.message}`);
94+
console.log(`[MSG] ${this.contactId} Can not send message to Bot - ${e.message}`);
9595
}
9696
}
9797

server/src/services/channels.service.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { LineChannel } from '@/channels/line.channel';
12
import { MessengerChannel } from '@/channels/messenger.channel';
23
import { LOCALE_KEY } from '@/constants';
34
import { db } from '@/database/db';
@@ -238,7 +239,7 @@ export class ChannelService {
238239
initChannel(channel: ChannelInfo) {
239240
const { id, contactId, contactName, channelType, credentials } = channel;
240241

241-
console.log(`Init channel: ${channelType} - ${contactName} ${contactId}`);
242+
console.log(`[Init channel] ${channelType} - ${contactName} ${contactId}`);
242243

243244
switch (channelType) {
244245
case 'MSG':
@@ -249,10 +250,20 @@ export class ChannelService {
249250
channelType,
250251
credentials
251252
);
252-
default:
253-
console.log(
254-
`Init channel: Does not support channel type ${channel.channelType}`
253+
case 'LIN':
254+
const linChannel = new LineChannel(
255+
id,
256+
contactId,
257+
contactName,
258+
channelType,
259+
credentials
255260
);
261+
262+
linChannel.registerWebhook();
263+
264+
return linChannel;
265+
default:
266+
console.log(`[Init channel] Does not support channel type ${channel.channelType}`);
256267
break;
257268
}
258269

server/src/services/conversation.service.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { LineChannel } from "@/channels/line.channel";
12
import { MessengerChannel } from "@/channels/messenger.channel";
23
import { Request } from "express-serve-static-core";
34
import { Service } from "typedi";
@@ -26,9 +27,15 @@ export class ConversationService {
2627

2728
if (['typing', 'stop-typing'].includes(type)) return await messengerChannel.sendActionToUser({ userId: recipient.id, type });
2829

30+
break;
31+
case 'LIN':
32+
const lineChannel = new LineChannel(id, from.id, contactName, channelType, credentials);
33+
34+
if (type == 'message') return await lineChannel.sendMessageToUser({ userId: recipient.id, text })
35+
2936
break;
3037
default:
31-
console.log(`Send message to Bot: Does not support channel type ${channelType}`);
38+
console.log(`[Incoming message] Send message to Bot: Does not support channel type ${channelType}`);
3239
break;
3340
}
3441
}

server/src/services/webhook.service.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { LineChannel } from "@/channels/line.channel";
12
import { MessengerChannel } from "@/channels/messenger.channel";
23
import { LOCALE_KEY } from "@/constants";
34
import { HttpException } from "@/exceptions/http-exception";
@@ -47,7 +48,7 @@ export class WebhookService {
4748
const expectedChannel = await this.chanelService.findOneByContactId(contactId);
4849

4950
if (!expectedChannel) {
50-
console.log('Incoming message: Can not find channel with id ', req.params.id);
51+
console.log('[Incoming message] Can not find channel with id ', req.params.id);
5152
return;
5253
}
5354

@@ -60,8 +61,12 @@ export class WebhookService {
6061
const messengerChannel = new MessengerChannel(id, contactId, contactName, channelType, credentials);
6162
prepareMessage = await messengerChannel.prepareMessage(req, res);
6263
break;
64+
case 'LIN':
65+
const lineChannel = new LineChannel(id, contactId, contactName, channelType, credentials);
66+
prepareMessage = await lineChannel.prepareMessage(req, res);
67+
break;
6368
default:
64-
console.log(`Incoming message: Does not support channel type ${channelType}`);
69+
console.log(`[Incoming message] Does not support channel type ${channelType}`);
6570
break;
6671
}
6772

0 commit comments

Comments
 (0)