-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n.js
More file actions
345 lines (330 loc) · 16.3 KB
/
Copy pathi18n.js
File metadata and controls
345 lines (330 loc) · 16.3 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"use strict";
(() => {
const STORAGE_KEY = "discordExportLanguage";
const SUPPORTED = new Set(["ru", "en"]);
const listeners = new Set();
const messages = {
ru: {
"app.subtitle": "Сообщения и вложения",
"language.label": "Язык интерфейса",
"connection.caption": "Подключение",
"connection.refresh": "Обновить",
"source.title": "Источник",
"source.subtitle": "Выберите, откуда взять сообщения",
"source.mode": "Режим экспорта",
"source.current": "Открытый чат или канал",
"source.dm": "Личный чат",
"source.server": "Сервер или канал",
"source.currentOpen": "Сейчас открыт",
"source.openDiscord": "Открой нужный чат в Discord",
"source.openDiscordFull": "Открой нужный чат или канал в Discord",
"source.discordTabMissing": "Вкладка Discord не найдена",
"source.dms": "Личные чаты",
"source.guilds": "Серверы",
"source.refreshList": "Обновить список",
"source.dmAria": "Личный чат",
"source.guildAria": "Сервер",
"source.channelAria": "Канал",
"source.loadList": "Сначала загрузите список",
"source.loadGuilds": "Сначала загрузите серверы",
"source.chooseDm": "Выберите личный чат",
"source.noDms": "Личные чаты не найдены",
"source.chooseGuild": "Выберите сервер",
"source.noGuilds": "Серверы не найдены",
"source.loading": "Загрузка…",
"source.loadingChannels": "Загрузка каналов…",
"source.chooseChannel": "Выберите канал или весь сервер",
"source.wholeServer": "Весь сервер ({count} каналов)",
"source.thread": "ветка",
"source.serverHint": "Весь сервер включает видимые каналы и активные ветки.",
"source.channelFallback": "Канал {id}",
"period.title": "Период",
"period.subtitle": "Начальная и конечная даты включительно",
"period.start": "Начало",
"period.end": "Конец",
"period.allHistory": "Вся доступная история",
"period.fullHistory": "Будет экспортирована вся история",
"period.invalid": "Период задан некорректно",
"period.oneDay": "Выбран один календарный день",
"period.days": "Выбрано: {count} {unit}",
"period.day.one": "день",
"period.day.few": "дня",
"period.day.many": "дней",
"action.export": "Экспортировать",
"action.preparing": "Подготавливаю…",
"action.pause": "Пауза",
"action.continue": "Продолжить",
"action.stop": "Остановить",
"action.downloadAttachments": "Скачать вложения",
"auth.checking": "Проверяю Discord…",
"auth.openTab": "Открой discord.com в отдельной вкладке",
"auth.reloaded": "Discord обновлён — подожди пару секунд",
"auth.failed": "Не удалось подключиться. Обнови Discord и открой любой чат",
"auth.ready": "Discord подключён",
"error.discordTabMissing": "Вкладка Discord не найдена.",
"error.notConnected": "Discord ещё не подключён. Обнови вкладку.",
"error.api": "Ошибка Discord API",
"error.endDate": "Выберите конечную дату.",
"error.startDate": "Выберите начальную дату.",
"error.dateOrder": "Конец периода должен быть позже начала.",
"error.openSource": "Сначала открой нужный чат или канал в Discord.",
"error.chooseDm": "Выберите личный чат.",
"error.chooseGuild": "Выберите сервер.",
"error.chooseChannel": "Выберите канал или весь сервер.",
"error.channelMissing": "Выбранный канал не найден.",
"error.discordDisconnected": "Discord не подключён.",
"error.createExport": "Не удалось создать экспорт.",
"export.documentTitle": "Экспорт Discord",
"export.preparing": "Подготовка экспорта…",
"export.status": "Состояние",
"export.loadingSettings": "Загружаю настройки…",
"export.preparingMessages": "Подготавливаю список сообщений…",
"export.progress": "Прогресс",
"export.messages": "Сообщения",
"export.attachments": "Вложения",
"export.requests": "Запросы",
"export.sources": "Источники",
"export.dialog": "Диалог",
"export.dialogs": "Диалоги",
"export.channel": "Канал",
"export.channels": "Каналы",
"export.result": "Результат",
"export.files": "Файлы экспорта",
"export.filesHelp": "Станут доступны после завершения или остановки экспорта.",
"export.errors": "Пропущенные каналы и ошибки",
"badge.running": "Работает",
"badge.paused": "Пауза",
"badge.done": "Готово",
"badge.error": "Ошибка",
"status.rateLimited": "Discord ограничил частоту запросов",
"status.retryAfter": "Продолжу автоматически через {seconds} сек.",
"status.networkError": "Временная ошибка сети",
"status.retry": "Повтор {attempt}/3 через 2 секунды…",
"status.loadingSource": "Загружаю {name}",
"status.sourcePage": "{source} {current} из {total}, страница {page}",
"status.stopped": "Экспорт остановлен",
"status.partial": "Можно скачать частичный результат: {count} сообщений.",
"status.completed": "Экспорт завершён",
"status.received": "Получено {count} сообщений.",
"status.paused": "Экспорт на паузе",
"status.pauseHelp": "Текущий запрос завершится, новые запросы пока не отправляются.",
"status.resuming": "Продолжаю экспорт",
"status.resumeHelp": "Загрузка сообщений возобновлена.",
"status.stopping": "Останавливаю экспорт…",
"status.stopHelp": "После текущего запроса будет доступен частичный результат.",
"status.failed": "Экспорт завершился с ошибкой",
"status.attachmentsProgress": "Вложения {current}/{total}",
"error.connectionLost": "Соединение с Discord потеряно. Обнови вкладку и запусти экспорт заново.",
"error.unexpectedMessages": "Discord вернул неожиданный формат сообщений.",
"error.attachment": "{filename}: не удалось скачать ({message})",
"error.attachments": "Вложения: {message}",
"error.jobId": "В URL отсутствует идентификатор экспорта.",
"error.jobMissing": "Задание экспорта не найдено. Открой popup расширения и запусти его заново."
},
en: {
"app.subtitle": "Messages and attachments",
"language.label": "Interface language",
"connection.caption": "Connection",
"connection.refresh": "Refresh",
"source.title": "Source",
"source.subtitle": "Choose where to export messages from",
"source.mode": "Export mode",
"source.current": "Open chat or channel",
"source.dm": "Direct message",
"source.server": "Server or channel",
"source.currentOpen": "Currently open",
"source.openDiscord": "Open a chat in Discord",
"source.openDiscordFull": "Open the required chat or channel in Discord",
"source.discordTabMissing": "Discord tab not found",
"source.dms": "Direct messages",
"source.guilds": "Servers",
"source.refreshList": "Refresh list",
"source.dmAria": "Direct message",
"source.guildAria": "Server",
"source.channelAria": "Channel",
"source.loadList": "Load the list first",
"source.loadGuilds": "Load servers first",
"source.chooseDm": "Choose a direct message",
"source.noDms": "No direct messages found",
"source.chooseGuild": "Choose a server",
"source.noGuilds": "No servers found",
"source.loading": "Loading…",
"source.loadingChannels": "Loading channels…",
"source.chooseChannel": "Choose a channel or the whole server",
"source.wholeServer": "Whole server ({count} channels)",
"source.thread": "thread",
"source.serverHint": "The whole server includes visible channels and active threads.",
"source.channelFallback": "Channel {id}",
"period.title": "Date range",
"period.subtitle": "Start and end dates are inclusive",
"period.start": "Start",
"period.end": "End",
"period.allHistory": "All available history",
"period.fullHistory": "All available history will be exported",
"period.invalid": "The selected date range is invalid",
"period.oneDay": "One calendar day selected",
"period.days": "Selected: {count} days",
"period.day.one": "day",
"period.day.few": "days",
"period.day.many": "days",
"action.export": "Export",
"action.preparing": "Preparing…",
"action.pause": "Pause",
"action.continue": "Resume",
"action.stop": "Stop",
"action.downloadAttachments": "Download attachments",
"auth.checking": "Checking Discord…",
"auth.openTab": "Open discord.com in another tab",
"auth.reloaded": "Discord refreshed — wait a couple of seconds",
"auth.failed": "Could not connect. Refresh Discord and open any chat",
"auth.ready": "Discord connected",
"error.discordTabMissing": "Discord tab not found.",
"error.notConnected": "Discord is not connected yet. Refresh the tab.",
"error.api": "Discord API error",
"error.endDate": "Choose an end date.",
"error.startDate": "Choose a start date.",
"error.dateOrder": "The end date must be later than the start date.",
"error.openSource": "Open the required chat or channel in Discord first.",
"error.chooseDm": "Choose a direct message.",
"error.chooseGuild": "Choose a server.",
"error.chooseChannel": "Choose a channel or the whole server.",
"error.channelMissing": "The selected channel was not found.",
"error.discordDisconnected": "Discord is not connected.",
"error.createExport": "Could not create the export.",
"export.documentTitle": "Discord Export",
"export.preparing": "Preparing export…",
"export.status": "Status",
"export.loadingSettings": "Loading settings…",
"export.preparingMessages": "Preparing the message list…",
"export.progress": "Progress",
"export.messages": "Messages",
"export.attachments": "Attachments",
"export.requests": "Requests",
"export.sources": "Sources",
"export.dialog": "Conversation",
"export.dialogs": "Conversations",
"export.channel": "Channel",
"export.channels": "Channels",
"export.result": "Result",
"export.files": "Export files",
"export.filesHelp": "Available after the export is finished or stopped.",
"export.errors": "Skipped channels and errors",
"badge.running": "Running",
"badge.paused": "Paused",
"badge.done": "Done",
"badge.error": "Error",
"status.rateLimited": "Discord rate limit reached",
"status.retryAfter": "Continuing automatically in {seconds}s.",
"status.networkError": "Temporary network error",
"status.retry": "Retry {attempt}/3 in 2 seconds…",
"status.loadingSource": "Loading {name}",
"status.sourcePage": "{source} {current} of {total}, page {page}",
"status.stopped": "Export stopped",
"status.partial": "You can download a partial result: {count} messages.",
"status.completed": "Export complete",
"status.received": "Downloaded {count} messages.",
"status.paused": "Export paused",
"status.pauseHelp": "The current request will finish; new requests are paused.",
"status.resuming": "Resuming export",
"status.resumeHelp": "Message loading has resumed.",
"status.stopping": "Stopping export…",
"status.stopHelp": "A partial result will be available after the current request.",
"status.failed": "Export failed",
"status.attachmentsProgress": "Attachments {current}/{total}",
"error.connectionLost": "The Discord connection was lost. Refresh the tab and start the export again.",
"error.unexpectedMessages": "Discord returned an unexpected message format.",
"error.attachment": "{filename}: download failed ({message})",
"error.attachments": "Attachments: {message}",
"error.jobId": "The export job ID is missing from the URL.",
"error.jobMissing": "Export job not found. Open the extension popup and start it again."
}
};
let language = "ru";
let initialized = false;
function normalizeLanguage(value) {
return SUPPORTED.has(value) ? value : "ru";
}
function t(key, parameters = {}) {
const template =
messages[language]?.[key] ?? messages.ru[key] ?? String(key);
return template.replace(/\{(\w+)\}/g, (_, name) =>
parameters[name] == null ? `{${name}}` : String(parameters[name])
);
}
function locale() {
return language === "en" ? "en-US" : "ru-RU";
}
function apply(root = document) {
root.documentElement.lang = language;
for (const element of root.querySelectorAll("[data-i18n]")) {
element.textContent = t(element.dataset.i18n);
}
for (const element of root.querySelectorAll("[data-i18n-title]")) {
element.title = t(element.dataset.i18nTitle);
}
for (const element of root.querySelectorAll("[data-i18n-aria-label]")) {
element.setAttribute("aria-label", t(element.dataset.i18nAriaLabel));
}
for (const button of root.querySelectorAll("[data-language]")) {
const active = button.dataset.language === language;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
}
}
function notify() {
apply();
for (const listener of listeners) {
listener(language);
}
}
async function setLanguage(value, { persist = true } = {}) {
const next = normalizeLanguage(value);
const changed = next !== language;
language = next;
if (persist) {
await chrome.storage.local.set({ [STORAGE_KEY]: language });
}
if (changed || initialized) {
notify();
}
}
async function initialize(preferredLanguage) {
if (initialized) {
apply();
return language;
}
let storedLanguage = preferredLanguage;
if (!storedLanguage) {
const stored = await chrome.storage.local.get(STORAGE_KEY);
storedLanguage = stored[STORAGE_KEY];
}
language = normalizeLanguage(
storedLanguage ||
(String(navigator.language || "").toLowerCase().startsWith("ru")
? "ru"
: "en")
);
for (const button of document.querySelectorAll("[data-language]")) {
button.addEventListener("click", () => {
void setLanguage(button.dataset.language);
});
}
initialized = true;
notify();
return language;
}
function onChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
}
window.DiscordExportI18n = {
initialize,
locale,
onChange,
setLanguage,
t,
get language() {
return language;
}
};
})();