-
Notifications
You must be signed in to change notification settings - Fork 739
Expand file tree
/
Copy pathtranslate.ts
More file actions
588 lines (524 loc) · 15.9 KB
/
translate.ts
File metadata and controls
588 lines (524 loc) · 15.9 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import { I18N } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysMenuEntity } from '../entity/sys/menu';
import {
App,
Config,
ILogger,
IMidwayApplication,
Inject,
Provide,
Scope,
ScopeEnum,
} from '@midwayjs/core';
import * as path from 'path';
import * as fs from 'fs';
import axios from 'axios';
import { DictInfoEntity } from '../../dict/entity/info';
import { DictTypeEntity } from '../../dict/entity/type';
/**
* 翻译服务
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class BaseTranslateService {
@InjectEntityModel(BaseSysMenuEntity)
baseSysMenuEntity: Repository<BaseSysMenuEntity>;
@InjectEntityModel(DictInfoEntity)
dictInfoEntity: Repository<DictInfoEntity>;
@InjectEntityModel(DictTypeEntity)
dictTypeEntity: Repository<DictTypeEntity>;
// 基础路径
basePath: string;
@App()
app: IMidwayApplication;
@Inject()
logger: ILogger;
@Config('cool.i18n')
config: {
/** 是否开启 */
enable: boolean;
/** 语言 */
languages: string[];
/** 翻译服务 */
serviceUrl?: string;
};
menuMap: Record<string, string> = {};
msgMap: Record<string, string> = {};
commMap: Record<string, string> = {};
// 添加字典映射
dictMap: Record<string, string> = {};
/**
* 检查是否存在锁文件
*/
private checkLockFile(type: 'menu' | 'msg' | 'comm'): boolean {
const lockFile = path.join(this.basePath, type, '.lock');
return fs.existsSync(lockFile);
}
/**
* 创建锁文件
*/
private createLockFile(type: 'menu' | 'msg' | 'comm'): void {
const lockFile = path.join(this.basePath, type, '.lock');
fs.writeFileSync(lockFile, new Date().toISOString());
}
/**
* 加载翻译文件到内存
*/
async loadTranslations() {
if (!this.config?.enable) {
return;
}
if (!this.basePath) {
this.basePath = path.join(this.app.getBaseDir(), '..', this.app.getEnv() === 'local' ? 'src' : 'dist', 'locales');
}
// 清空现有映射
this.menuMap = {};
this.msgMap = {};
this.dictMap = {};
this.commMap = {};
// 加载菜单翻译
await this.loadTypeTranslations('menu', this.menuMap);
// 加载消息翻译
await this.loadTypeTranslations('msg', this.msgMap);
// 加载通用消息翻译
await this.loadTypeTranslations('comm', this.commMap);
// 加载字典翻译
await this.loadDictTranslations();
}
/**
* 加载指定类型的翻译
* @param type 翻译类型
* @param map 映射对象
*/
private async loadTypeTranslations(
type: 'menu' | 'msg' | 'comm',
map: Record<string, string>
) {
const dirPath = path.join(this.basePath, type);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file.endsWith('.json')) {
const language = file.replace('.json', '');
const content = fs.readFileSync(path.join(dirPath, file), 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
map[`${language}:${key}`] = value as string;
}
}
}
}
}
/**
* 加载字典翻译
*/
private async loadDictTranslations() {
const dictTypes = ['info', 'type'];
for (const dictType of dictTypes) {
const dirPath = path.join(this.basePath, 'dict', dictType);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file.endsWith('.json')) {
const language = file.replace('.json', '');
const content = fs.readFileSync(path.join(dirPath, file), 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
this.dictMap[`${language}:dict:${dictType}:${key}`] =
value as string;
}
}
}
}
}
}
/**
* 更新翻译映射
* @param type 类型 menu | msg
* @param language 语言
*/
async updateTranslationMap(type: 'menu' | 'msg', language: string) {
const dirPath = path.join(this.basePath, type);
const file = path.join(dirPath, `${language}.json`);
if (fs.existsSync(file)) {
const content = fs.readFileSync(file, 'utf-8');
const translations = JSON.parse(content);
const map = type === 'menu' ? this.menuMap : this.msgMap;
for (const [key, value] of Object.entries(translations)) {
map[`${language}:${key}`] = value as string;
}
}
}
/**
* 翻译
* @param type 类型 menu | msg | dict
* @param language 语言
* @param text 原文
* @returns 翻译后的文本
*/
translate(
type: 'menu' | 'msg' | 'dict:info' | 'dict:type' | 'comm',
language: string,
text: string
): string {
// 处理字典翻译
if (type === 'dict:info' || type === 'dict:type') {
const key = `${language}:${type}:${text}`;
return this.dictMap[key] || text.split(':').pop() || text;
}
// 处理菜单和消息翻译
const map = type === 'menu' ? this.menuMap : this.msgMap;
const key = `${language}:${text}`;
return map[key] || text;
}
/**
* 检查翻译
*/
async check() {
if (this.config?.enable && this.app.getEnv() == 'local') {
this.basePath = path.join(this.app.getBaseDir(), '..', 'src', 'locales');
const menuLockExists = this.checkLockFile('menu');
const msgLockExists = this.checkLockFile('msg');
const commLockExists = this.checkLockFile('comm');
const dictLockExists = this.checkDictLockFile();
if (
!menuLockExists ||
!msgLockExists ||
!dictLockExists ||
!commLockExists
) {
const tasks = [];
if (!msgLockExists) {
tasks.push(this.genBaseMsg());
}
if (!menuLockExists) {
tasks.push(this.genBaseMenu());
}
if (!dictLockExists) {
tasks.push(this.genBaseDict());
}
if (!commLockExists) {
tasks.push(this.genCommMsg());
}
// 启动旋转动画
const spinner = ['|', '/', '-', '\\'];
let index = 0;
const interval = setInterval(() => {
process.stdout.write(`\r${spinner[index++]} i18n translate...`);
index %= spinner.length;
}, 200);
try {
await Promise.all(tasks);
} finally {
clearInterval(interval);
// 加载翻译文件到内存
await this.loadTranslations();
await this.loadDictTranslations();
process.stdout.write('\r✅ i18n translate success!!!\n');
}
} else {
this.logger.debug('Translation lock files exist, skipping translation');
// 直接加载翻译文件到内存
await this.loadTranslations();
await this.loadDictTranslations();
}
}
}
/**
* 检查字典锁文件
*/
private checkDictLockFile(): boolean {
const lockFile = path.join(this.basePath, 'dict', '.lock');
return fs.existsSync(lockFile);
}
/**
* 创建字典锁文件
*/
private createDictLockFile(): void {
const lockFile = path.join(this.basePath, 'dict', '.lock');
fs.writeFileSync(lockFile, new Date().toISOString());
}
/**
* 生成基础字典
*/
async genBaseDict() {
try {
// 检查是否存在锁文件
if (this.checkDictLockFile()) {
this.logger.debug('Dictionary lock file exists, skipping translation');
return;
}
const infos = await this.dictInfoEntity.find();
const types = await this.dictTypeEntity.find();
// 确保目录存在
const infoDir = path.join(this.basePath, 'dict', 'info');
const typeDir = path.join(this.basePath, 'dict', 'type');
fs.mkdirSync(infoDir, { recursive: true });
fs.mkdirSync(typeDir, { recursive: true });
// 生成中文基础文件
const infoContent = {};
const typeContent = {};
for (const info of infos) {
infoContent[info.name] = info.name;
}
for (const type of types) {
typeContent[type.name] = type.name;
}
const infoFile = path.join(infoDir, 'zh-cn.json');
const typeFile = path.join(typeDir, 'zh-cn.json');
const infoText = JSON.stringify(infoContent, null, 2);
const typeText = JSON.stringify(typeContent, null, 2);
fs.writeFileSync(infoFile, infoText);
fs.writeFileSync(typeFile, typeText);
this.logger.debug('Base dictionary files generated successfully');
// 翻译其他语言
if (this.config?.enable && this.config.languages) {
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
// 翻译 info 字典
translatePromises.push(
this.invokeTranslate(infoText, language, infoDir, 'dict')
);
// 翻译 type 字典
translatePromises.push(
this.invokeTranslate(typeText, language, typeDir, 'dict')
);
}
}
await Promise.all(translatePromises);
this.logger.debug('Dictionary translations completed successfully');
}
// 创建锁文件
this.createDictLockFile();
// 更新翻译映射
await this.loadDictTranslations();
} catch (error) {
this.logger.error('Failed to generate dictionary:', error);
throw error;
}
}
/**
* 更新字典翻译映射
* @param language 语言
*/
async updateDictTranslationMap(language: string) {
const infoFile = path.join(
this.basePath,
'dict',
'info',
`${language}.json`
);
const typeFile = path.join(
this.basePath,
'dict',
'type',
`${language}.json`
);
if (fs.existsSync(infoFile)) {
const content = fs.readFileSync(infoFile, 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
this.dictMap[`${language}:dict:info:${key}`] = value as string;
}
}
if (fs.existsSync(typeFile)) {
const content = fs.readFileSync(typeFile, 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
this.dictMap[`${language}:dict:type:${key}`] = value as string;
}
}
}
/**
* 生成基础菜单
*/
async genBaseMenu() {
const menus = await this.baseSysMenuEntity.find();
const file = path.join(this.basePath, 'menu', 'zh-cn.json');
const content = {};
for (const menu of menus) {
content[menu.name] = menu.name;
}
// 确保目录存在
const msgDir = path.dirname(file);
if (!fs.existsSync(msgDir)) {
fs.mkdirSync(msgDir, { recursive: true });
}
const text = JSON.stringify(content, null, 2);
fs.writeFileSync(file, text);
this.logger.debug('base menu generate success');
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
translatePromises.push(
this.invokeTranslate(
text,
language,
path.join(this.basePath, 'menu'),
'menu'
)
);
}
}
await Promise.all(translatePromises);
this.createLockFile('menu');
}
/**
* 生成基础消息
*/
async genBaseMsg() {
const file = path.join(this.basePath, 'msg', 'zh-cn.json');
const scanPath = path.join(this.app.getBaseDir(), '..', 'src', 'modules');
const messages = {};
// 递归扫描目录
const scanDir = (dir: string) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
scanDir(fullPath);
} else if (file.endsWith('.ts')) {
const content = fs.readFileSync(fullPath, 'utf-8');
const matches = content.match(
/throw new CoolCommException\((['"])(.*?)\1\)/g
);
if (matches) {
matches.forEach(match => {
const message = match.match(/(['"])(.*?)\1/)[2];
messages[message] = message;
});
}
}
}
};
// 开始扫描
scanDir(scanPath);
// 确保目录存在
const msgDir = path.dirname(file);
if (!fs.existsSync(msgDir)) {
fs.mkdirSync(msgDir, { recursive: true });
}
// 写入文件
const text = JSON.stringify(messages, null, 2);
fs.writeFileSync(file, text);
this.logger.debug('base msg generate success');
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
translatePromises.push(
this.invokeTranslate(
text,
language,
path.join(this.basePath, 'msg'),
'msg'
)
);
}
}
await Promise.all(translatePromises);
this.createLockFile('msg');
}
/**
* 生成通用消息
*/
async genCommMsg() {
const file = path.join(this.basePath, 'comm', 'zh-cn.json');
const scanPath = path.join(this.app.getBaseDir(), '..', 'src', 'modules');
const messages = {};
// 递归扫描目录
const scanDir = (dir: string) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
scanDir(fullPath);
} else if (file.endsWith('.ts')) {
const content = fs.readFileSync(fullPath, 'utf-8');
const matches = content.match(
/this.translate.comm\((['"])(.*?)\1\)/g
);
if (matches) {
matches.forEach(match => {
const message = match.match(/(['"])(.*?)\1/)[2];
messages[message] = message;
});
}
}
}
};
// 开始扫描
scanDir(scanPath);
// 确保目录存在
const msgDir = path.dirname(file);
if (!fs.existsSync(msgDir)) {
fs.mkdirSync(msgDir, { recursive: true });
}
// 写入文件
const text = JSON.stringify(messages, null, 2);
fs.writeFileSync(file, text);
this.logger.debug('base comm generate success');
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
translatePromises.push(
this.invokeTranslate(
text,
language,
path.join(this.basePath, 'comm'),
'comm'
)
);
}
}
await Promise.all(translatePromises);
this.createLockFile('comm');
}
/**
* 通用消息翻译
* @param text 文本
* @returns 翻译后的文本对象,包含各语言的翻译
*/
comm(text: string) {
const translations = {};
for (const lang of this.config.languages) {
const langFile = path.join(this.basePath, 'comm', `${lang}.json`);
if (fs.existsSync(langFile)) {
const content = JSON.parse(fs.readFileSync(langFile, 'utf-8'));
translations[lang] = content[text] || text;
}
}
return translations;
}
/**
* 调用翻译
* @param text 文本
* @param language 语言
* @param dirPath 目录
* @param type 类型
* @returns
*/
async invokeTranslate(
text: string,
language: string,
dirPath: string,
type: 'menu' | 'msg' | 'dict' | 'comm' = 'msg'
) {
this.logger.debug(`${type} ${language} translate start`);
const response = await axios.post(I18N.DEFAULT_SERVICE_URL, {
label: 'i18n-node',
params: {
text,
language,
},
stream: false,
});
const file = path.join(dirPath, `${language}.json`);
fs.writeFileSync(file, response.data.data.result.data);
this.logger.debug(`${type} ${language} translate success`);
}
}