-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
208 lines (184 loc) · 8.09 KB
/
index.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
const request = require('request');
const _ = require('lodash');
const Promise = require('bluebird');
const utils = require('./lib/utils');
const generateHash = utils.generateHash;
const mergeStrings = utils.mergeStrings;
const applyTagsToStrings = utils.applyTagsToStrings;
const apiUrl = 'https://www.transifex.com/api/2/';
const transifexLanguageCodeToIso = (languageCode) => languageCode.replace('_', '-');
const isoLanguageCodeToTransifex = (languageCode) => languageCode.replace('-', '_');
const logW = (level, message) => console.log("%s %s: %s", level, new Date(), message);
/**
* @param {{login:String, password:String, projectSlug: String, resourceSlug: String, skipTags: Array[String], obsoleteTag:String, requestConcurrency: Number, stringWillRemove:{tags:Array[String]}}} config
* @return {{getProjectLanguages,getTranslatedResource,getTranslationStats,getTranslatedResources,getLanguagesInfo}}
*/
const transifex = function (config) {
const concurrency = config.requestConcurrency || 5;
config.stringWillRemove = config.stringWillRemove || {tags: []};
config.obsoleteTag = config.obsoleteTag || 'obsolete';
config.logLevel = config.logLevel || 'error';
const resourceFile = `${config.projectSlug}/resource/${config.resourceSlug}/`;
if (config.logLevel === 'trace') {
// Generates a lot of messages.
request.debug = true;
}
const log = {
debug: (message) => {
if (config.logLevel === 'trace' || config.logLevel === 'debug') {
logW(config.logLevel, message);
}
return message;
},
error: (message) => {
if (config.logLevel === 'trace' || config.logLevel === 'debug' || config.logLevel === 'error') {
logW(config.logLevel, message);
}
return message;
}
};
const getRequestOptions = (url, method, data) => {
method = method || 'GET';
const options = {
url: `${apiUrl}${url}`,
method: method,
auth: {
'user': config.login,
'pass': config.password
},
json: true
};
if (method === 'PUT') {
options.json = data;
}
return options;
};
const makeRequestCall = (options, resolve, reject) => {
return request(options, (err, response, body) => {
if (!err && response.statusCode === 200) {
resolve(body);
} else {
const reason = err || body || response;
// Api rate limits reached. See https://docs.transifex.com/api/introduction#api-rate-limits
if (response.statusCode === 429) {
const secondsToWaitBeforeRetry = (response.headers['retry-after'] || 5 * 60) + 5;
log.error(`${options.url} - API rate limits reached: '${reason}' (429). Waiting ${secondsToWaitBeforeRetry}s to retry.`);
Promise
.delay(secondsToWaitBeforeRetry * 1000)
.then(() => makeRequestCall(options, resolve, reject));
} else {
reject(log.error(reason));
}
}
});
};
const makeRequest = (url, method, data) => {
const options = getRequestOptions(url, method, data);
return new Promise((resolve, reject) => makeRequestCall(options, resolve, reject));
};
const getResponse = (url) => makeRequest(url);
const getProjectLanguages = () => {
const url = `project/${config.projectSlug}/languages`;
return getResponse(url).then((data) => {
return data.map((item) => {
return {code: transifexLanguageCodeToIso(item['language_code'])};
});
});
};
const getTranslatedResource = (isoLanguageCode) => {
const url = `project/${resourceFile}translation/${isoLanguageCodeToTransifex(isoLanguageCode)}/?mode=reviewed`;
return getResponse(url).then((data) => data.content);
};
const getTranslatedResources = () => {
return getProjectLanguages()
.then((languages) => {
return Promise.all(languages.map((language) => {
return getTranslatedResource(language.code)
.then((content) => {
return {
lang: language.code,
content: content
};
})
}));
})
};
const getTranslationStats = (isoLanguageCode) => {
return getResponse(`project/${config.projectSlug}/language/${isoLanguageCodeToTransifex(isoLanguageCode)}?details`)
.then((details) => {
return {
totalTokensCount: details['total_segments'],
translatedTokensCount: details['translated_segments'],
reviewedTokensCount: details['reviewed_segments'],
translatedWordsCount: details['translated_words']
};
});
};
const getResourceStrings = (strings) => {
return Promise
.map(_.toArray(strings), (token) => {
const url = `project/${resourceFile}source/${generateHash(token)}`;
return getResponse(url).then((string) => {
string.token = token;
return string;
});
}, {concurrency: concurrency});
};
const putResourceStrings = (strings) => {
return Promise
.map(strings, (value) => {
const url = `project/${resourceFile}source/${generateHash(value.token)}`;
return makeRequest(url, 'PUT', _.omit(value, 'token'))
}, {concurrency: concurrency})
.then(() => strings);
};
const getLanguagesInfo = () => {
const url = `languages/`;
return getResponse(url).then((languages) => {
return languages.map((lang) => {
return {
code: transifexLanguageCodeToIso(lang.code),
name: lang.name
};
});
})
};
const removeStringsWithCertainTags = (strings, tags) => {
const content = utils.removeStringsWithCertainTags(strings, tags);
const url = `project/${resourceFile}content/`;
return makeRequest(url, 'PUT', {content: JSON.stringify(content)})
};
const updateResourceFile = (dictionaries) => {
const url = `project/${resourceFile}content/`;
log.debug('Get Transifex dictionaries content');
return getResponse(url).then((res) => {
log.debug('Merge Transifex and our dictionaries content');
const contentFromResource = JSON.parse(res.content);
return mergeStrings(dictionaries, contentFromResource);
}).then((strings) => {
log.debug('Put merged dictionaries to Transifex');
return Promise.all([makeRequest(url, 'PUT', {content: JSON.stringify(strings.updateStrings)}), strings]);
}).then((res) => {
log.debug('Get dictionaries including obsolete ones from Transifex');
return Promise.all([getResourceStrings(res[1].updateStrings), res[1].obsoleteStrings]);
}).then((res) => {
log.debug('Apply tags to result dictionaries');
return applyTagsToStrings(dictionaries, res[0], res[1], config)
}).then((strings) => {
log.debug('Put result dictionaries to Transifex');
return putResourceStrings(strings);
}).then((strings) => {
log.debug('Remove dictionaries with certain tags');
return removeStringsWithCertainTags(strings, config.stringWillRemove.tags)
});
};
return {
getProjectLanguages: getProjectLanguages,
getTranslationStats: getTranslationStats,
getTranslatedResource: getTranslatedResource,
getTranslatedResources: getTranslatedResources,
updateResourceFile: updateResourceFile,
getLanguagesInfo: getLanguagesInfo
};
};
module.exports = transifex;