-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
241 lines (197 loc) · 6.42 KB
/
Copy pathapp.js
File metadata and controls
241 lines (197 loc) · 6.42 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
const els = {
idInstance: document.getElementById('idInstance'),
apiTokenInstance: document.getElementById('apiTokenInstance'),
messageChatNumber: document.getElementById('messageChatNumber'),
messageChatSuffix: document.getElementById('messageChatSuffix'),
messageText: document.getElementById('messageText'),
fileChatNumber: document.getElementById('fileChatNumber'),
fileChatSuffix: document.getElementById('fileChatSuffix'),
fileUrl: document.getElementById('fileUrl'),
fileName: document.getElementById('fileName'),
getSettingsBtn: document.getElementById('getSettingsBtn'),
getStateInstanceBtn: document.getElementById('getStateInstanceBtn'),
sendMessageBtn: document.getElementById('sendMessageBtn'),
sendFileByUrlBtn: document.getElementById('sendFileByUrlBtn'),
responseOutput: document.getElementById('responseOutput'),
statusBadge: document.getElementById('statusBadge'),
lastAction: document.getElementById('lastAction'),
copyBtn: document.getElementById('copyBtn'),
clearBtn: document.getElementById('clearBtn')
};
const actionButtons = [
els.getSettingsBtn,
els.getStateInstanceBtn,
els.sendMessageBtn,
els.sendFileByUrlBtn
];
function pretty(value) {
return JSON.stringify(value, null, 2);
}
function setStatus(text, type = 'idle') {
els.statusBadge.textContent = text;
els.statusBadge.className = 'badge';
if (type === 'ok') {
els.statusBadge.classList.add('ok');
}
if (type === 'error') {
els.statusBadge.classList.add('error');
}
}
function setLoading(isLoading, label = 'Загрузка...') {
actionButtons.forEach((btn) => {
btn.disabled = isLoading;
});
if (isLoading) {
setStatus(label);
}
}
function updateResponse(payload) {
els.responseOutput.textContent = pretty(payload);
}
function updateLastAction(actionName) {
const now = new Date();
els.lastAction.textContent = `Последнее действие: ${actionName} · ${now.toLocaleTimeString()}`;
}
function getCredentials() {
const idInstance = els.idInstance.value.trim();
const apiTokenInstance = els.apiTokenInstance.value.trim();
if (!idInstance || !apiTokenInstance) {
throw new Error('Введите idInstance и ApiTokenInstance');
}
return { idInstance, apiTokenInstance };
}
function buildChatId(number, suffix) {
const cleanNumber = number.trim().replace(/\s+/g, '');
if (!cleanNumber) {
throw new Error('Введите номер чата');
}
return `${cleanNumber}${suffix}`;
}
function buildUrl(path) {
const { idInstance, apiTokenInstance } = getCredentials();
if (idInstance.length < 4) {
throw new Error('idInstance должен содержать минимум 4 символа');
}
const apiHost = `${idInstance.slice(0, 4)}.api.greenapi.com`;
return `https://${apiHost}/waInstance${idInstance}/${path}/${apiTokenInstance}`;
}
function extractFileName(url) {
try {
const parsed = new URL(url);
const rawName = parsed.pathname.split('/').filter(Boolean).pop();
if (!rawName || !rawName.includes('.')) {
return 'downloaded-file';
}
return rawName;
} catch {
return 'downloaded-file';
}
}
let isFileNameEditedManually = false;
els.fileUrl.addEventListener('input', () => {
if (!isFileNameEditedManually) {
els.fileName.value = extractFileName(els.fileUrl.value.trim());
}
});
els.fileName.addEventListener('input', () => {
isFileNameEditedManually = els.fileName.value.trim() !== '';
});
async function callGreenApi(path, method = 'GET', body) {
const url = buildUrl(path);
const options = {
method,
headers: {
'Content-Type': 'application/json'
}
};
if (body !== undefined) {
options.body = JSON.stringify(body);
}
const response = await fetch(url, options);
const rawText = await response.text();
let data;
try {
data = JSON.parse(rawText);
} catch {
data = rawText;
}
return {
ok: response.ok,
status: response.status,
data
};
}
async function handleRequest(actionName, path, method, bodyBuilder) {
try {
setLoading(true, `${actionName}...`);
updateLastAction(actionName);
const body = bodyBuilder ? bodyBuilder() : undefined;
const result = await callGreenApi(path, method, body);
updateResponse(result.data);
if (result.ok) {
setStatus(`Успешно: ${result.status}`, 'ok');
} else {
setStatus(`Ошибка: ${result.status}`, 'error');
}
} catch (error) {
updateResponse({
error: error.message
});
setStatus('Ошибка запроса', 'error');
} finally {
setLoading(false);
}
}
els.getSettingsBtn.addEventListener('click', () => {
handleRequest('getSettings', 'getSettings', 'GET');
});
els.getStateInstanceBtn.addEventListener('click', () => {
handleRequest('getStateInstance', 'getStateInstance', 'GET');
});
els.sendMessageBtn.addEventListener('click', () => {
handleRequest('sendMessage', 'sendMessage', 'POST', () => {
const number = els.messageChatNumber.value;
const suffix = els.messageChatSuffix.value;
const message = els.messageText.value.trim();
if (!message) {
throw new Error('Для sendMessage нужно заполнить message');
}
return {
chatId: buildChatId(number, suffix),
message
};
});
});
els.sendFileByUrlBtn.addEventListener('click', () => {
handleRequest('sendFileByUrl', 'sendFileByUrl', 'POST', () => {
const number = els.fileChatNumber.value;
const suffix = els.fileChatSuffix.value;
const urlFile = els.fileUrl.value.trim();
const fileName = els.fileName.value.trim() || extractFileName(urlFile);
if (!urlFile) {
throw new Error('Для sendFileByUrl нужно заполнить fileUrl');
}
if (!fileName) {
throw new Error('Для sendFileByUrl нужно указать fileName');
}
return {
chatId: buildChatId(number, suffix),
urlFile,
fileName,
caption: 'File from GREEN-API test page'
};
});
});
els.copyBtn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(els.responseOutput.textContent);
setStatus('JSON скопирован', 'ok');
} catch {
setStatus('Не удалось скопировать JSON', 'error');
}
});
els.clearBtn.addEventListener('click', () => {
updateResponse({ message: 'Поле ответа очищено' });
setStatus('Поле очищено');
els.lastAction.textContent = 'Последнее действие: нет';
});