-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
189 lines (164 loc) · 6.92 KB
/
app.js
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
const express = require('express');
const axios = require('axios');
const app = express();
// 환경변수 및 상수
const {
DISCORD_WEBHOOK_URL,
FIGMA_API_TOKEN,
REPLACE_WORDS, // Optional - 디스코드 멘션으로 치환할 단어 (ex: @Designer)
PROJECT_NAME, // Optional - 피그마 프로젝트명 (미입력 시 팀 내 모든 이벤트를 수신)
} = process.env;
const WEBHOOK_ENDPOINT = '/figma-event';
const replaceWords = REPLACE_WORDS ? JSON.parse(REPLACE_WORDS) : null;
const replaceRegex = REPLACE_WORDS ? createRegexFromWords(REPLACE_WORDS) : null;
// 미들웨어
app.use(express.json());
// 유틸리티 함수
function createRegexFromWords(words) {
if (!words || words.length === 0) return null;
const regexStrings = words.flatMap(group => group.words.map(word => `(${word})`));
return new RegExp(regexStrings.join('|'), 'gi');
}
// 멘션 처리 함수
function replaceText(text) {
if (!replaceRegex || !REPLACE_WORDS) return text;
return text.replace(replaceRegex, match => {
const group = REPLACE_WORDS.find(g => g.words.includes(match.toLowerCase()));
return group ? group.replacement : match;
});
}
// Node ID를 가져오는 함수
async function getNodeIdFromComment(commentId, fileKey) {
try {
const url = `https://api.figma.com/v1/files/${fileKey}/comments`;
const headers = { 'X-Figma-Token': FIGMA_API_TOKEN };
const response = await axios.get(url, { headers });
if (response.status === 403 || response.status === 404) {
console.error(`Error ${response.status}: Check your API token and file key.`);
return null;
}
const comment = response.data.comments.find(c => c.id === commentId);
return comment ? comment.client_meta.node_id : null;
} catch (error) {
console.error('Error fetching node ID from comment:', error.response?.data || error.message);
return null;
}
}
// 부모 코멘트 원문을 가져오는 함수
async function getParentComment(parent_id, fileKey) {
try {
const url = `https://api.figma.com/v1/files/${fileKey}/comments`;
const headers = { 'X-Figma-Token': FIGMA_API_TOKEN };
const response = await axios.get(url, { headers });
if (response.status === 403 || response.status === 404) {
console.error(`Error ${response.status}: Check your API token and file key.`);
return null;
}
const parentComment = response.data.comments.find(c => c.id === parent_id);
return parentComment ? parentComment.message : null;
} catch (error) {
console.error('Error fetching parent comment:', error.response?.data || error.message);
return null;
}
}
// 디스코드 메세지 작성 (FILE_COMMENT)
async function handleFileComment(req) {
const { comment, file_name, file_key, comment_id, triggered_by, timestamp, parent_id } = req.body;
if (PROJECT_NAME && file_name !== PROJECT_NAME) {
console.error('This project is not included in the list.')
return { success: false, message: 'Unknown file name', status: 400 };
}
let message = "";
if (parent_id) {
const parentComment = await getParentComment(parent_id, file_key);
message += `>>> \`${replaceText(parentComment)}\`\n\n`;
}
if (Array.isArray(comment)) {
comment.forEach(item => {
if (item.text) {
message += `${replaceText(item.text)}\n`;
} else if (item.mention) {
message += `Mentioned user: ${item.mention}\n`;
}
});
} else if (comment.text) {
message += `${replaceText(comment.text)}\n`;
}
const node_id = await getNodeIdFromComment(parent_id == "" ? comment_id : parent_id, file_key); // Reply의 경우 parent의 node_id를 가져와야 하므로 parent_id를 사용해서 getNodeId
if (!node_id) {
console.error('Node ID not found');
return res.status(404).json({ success: false, message: 'Node ID not found' });
}
try {
await axios.post(DISCORD_WEBHOOK_URL, {
embeds: [{ // 임베드 형식으로 디스코드 메세지를 작성
"author": {
"name": triggered_by.handle,
"icon_url": triggered_by.img_url
},
"title": `[${file_name}] ${(parent_id) ? 'New reply on comment' : 'New comment thread on design'}`,
"url": `https://www.figma.com/design/${file_key}?node-id=${node_id}#${parent_id ? parent_id : comment_id}`, // node_id를 사용하여 코멘트 위치로 통하는 피그마 링크를 생성
"description": message,
"image": {
"url": `${(parent_id) ? 'https://media1.tenor.com/m/Be-YL9ewKnMAAAAC/diseñadorcliente4.gif' : 'https://media1.tenor.com/m/ehqokSFplPIAAAAd/design-designer.gif'}` // 이미지 (임의로 변경 가능)
},
"timestamp": timestamp,
"footer": {
"text": file_name
},
"color": `${(parent_id) ? '3244390' : '8482097'}` // 디스코드 임베드 블록 컬러 (Reply : Comment)
}]
});
return { success: true, message: 'Notification sent', status: 200 };
} catch (error) {
console.error('Error sending notification to Discord:', error.response?.data || error.message);
return { success: false, message: 'Error sending notification', status: 500 };
}
}
// 디스코드 메세지 작성 (FILE_VERSION_UPDATE)
async function handleVersionUpdate(req) {
const { file_name, file_key, triggered_by, description, label, timestamp } = req.body;
if (PROJECT_NAME && file_name !== PROJECT_NAME) {
return { success: false, message: 'Unknown file name', status: 400 };
}
try {
await axios.post(DISCORD_WEBHOOK_URL, {
embeds: [{
"author": {
"name": triggered_by.handle,
"icon_url": triggered_by.img_url
},
"title": `[${file_name}] **New version update on design: ${label}**`,
"url": `https://www.figma.com/design/${file_key}/%F0%9F%8C%A7%EF%B8%8F-ON%C2%B0C`, // 위치 정보가 필요 없으므로 getNodeId 없이 링크 생성
"description": `>>> ${description}`,
"image": {
"url": "https://i.namu.wiki/i/vcPIh-2LKgTCpeKuzLpVs1uGs9RHtZDezU438Wk5za0W18Zf_A9k7OO9kAz4yzWW31KjB2Talrzbldmvjv5KGw.gif" // 이미지 (임의로 변경 가능)
},
"timestamp": timestamp,
"color": `2379919` // 디스코드 임베드 블록 컬러
}]
});
return { success: true, message: 'Notification sent', status: 200 };
} catch (error) {
console.error('Error sending notification to Discord:', error.response?.data || error.message);
return { success: false, message: 'Error sending notification', status: 500 };
}
}
// 라우트
app.post(WEBHOOK_ENDPOINT, async (req, res) => {
const { event_type } = req.body;
let result;
switch (event_type) {
case 'FILE_COMMENT':
result = await handleFileComment(req);
break;
case 'FILE_VERSION_UPDATE':
result = await handleVersionUpdate(req);
break;
default:
res.status(400).send('Unknown event type');
return;
}
res.status(result.status).json({ success: result.success, message: result.message });
});
module.exports = app;