You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
162 lines
5.5 KiB
162 lines
5.5 KiB
/**
|
|
* @license
|
|
* Copyright Google Inc.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
// [START sheets_quickstart]
|
|
const fs = require('fs');
|
|
const readline = require('readline');
|
|
const {google} = require('googleapis');
|
|
|
|
// If modifying these scopes, delete token.json.
|
|
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
|
|
// The file token.json stores the user's access and refresh tokens, and is
|
|
// created automatically when the authorization flow completes for the first
|
|
// time.
|
|
const TOKEN_PATH = 'token.json';
|
|
|
|
// Load client secrets from a local file.
|
|
fs.readFile('credentials.json', (err, content) => {
|
|
if (err) return console.log('Error loading client secret file:', err);
|
|
// Authorize a client with credentials, then call the Google Sheets API.
|
|
authorize(JSON.parse(content), listMajors);
|
|
});
|
|
|
|
/**
|
|
* Create an OAuth2 client with the given credentials, and then execute the
|
|
* given callback function.
|
|
* @param {Object} credentials The authorization client credentials.
|
|
* @param {function} callback The callback to call with the authorized client.
|
|
*/
|
|
function authorize(credentials, callback) {
|
|
const {client_secret, client_id, redirect_uris} = credentials.installed;
|
|
const oAuth2Client = new google.auth.OAuth2(
|
|
client_id, client_secret, redirect_uris[0]);
|
|
|
|
// Check if we have previously stored a token.
|
|
fs.readFile(TOKEN_PATH, (err, token) => {
|
|
if (err) return getNewToken(oAuth2Client, callback);
|
|
oAuth2Client.setCredentials(JSON.parse(token));
|
|
callback(oAuth2Client);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Get and store new token after prompting for user authorization, and then
|
|
* execute the given callback with the authorized OAuth2 client.
|
|
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
|
|
* @param {getEventsCallback} callback The callback for the authorized client.
|
|
*/
|
|
function getNewToken(oAuth2Client, callback) {
|
|
const authUrl = oAuth2Client.generateAuthUrl({
|
|
access_type: 'offline',
|
|
scope: SCOPES,
|
|
});
|
|
console.log('Authorize this app by visiting this url:', authUrl);
|
|
const rl = readline.createInterface({
|
|
input: process.stdin,
|
|
output: process.stdout,
|
|
});
|
|
rl.question('Enter the code from that page here: ', (code) => {
|
|
rl.close();
|
|
oAuth2Client.getToken(code, (err, token) => {
|
|
if (err) return console.error('Error while trying to retrieve access token', err);
|
|
oAuth2Client.setCredentials(token);
|
|
// Store the token to disk for later program executions
|
|
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
|
|
if (err) return console.error(err);
|
|
console.log('Token stored to', TOKEN_PATH);
|
|
});
|
|
callback(oAuth2Client);
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Prints the names and majors of students in a sample spreadsheet:
|
|
* @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
|
|
* @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
|
|
*/
|
|
function listMajors(auth) {
|
|
const sheets = google.sheets({version: 'v4', auth});
|
|
sheets.spreadsheets.values.get({
|
|
spreadsheetId: '1GWnrP4WepYM8ERqSVGwKw5yxezMLnpdjxT0usn5mQKU',
|
|
range: 'i18n',
|
|
}, (err, res) => {
|
|
if (err) return console.log('The API returned an error: ' + err);
|
|
const rows = res.data.values;
|
|
|
|
// console.info(rows)
|
|
let keyIndex=rows[0].indexOf('key')
|
|
if (rows.length&&keyIndex!==-1&&rows[0][keyIndex+1]==='default') {
|
|
|
|
let keys=rows.slice(1).map((item,row)=>{return {row:row+1,key:item[keyIndex]}})
|
|
|
|
let i18n= rows[0].slice(keyIndex+1).map(()=>{return {}})
|
|
console.info(`共找到${i18n.length-1}种语言,${keys.length}个词条`)
|
|
keys.map((key,row)=>{
|
|
i18n.map((obj,column)=>{
|
|
|
|
if(!/^[a-zA-Z][0-9a-zA-Z_]+$/g.test(key.key)){
|
|
console.error(`第${row+1}行${key.key}不合法,key必须以英文字母开头,只能包含字母数字和下划线`)
|
|
return
|
|
}
|
|
|
|
if(key.key in obj){
|
|
console.warn(`第${row+1}行${key.key}已经在第${rows[key.row]}行定义了!`)
|
|
}
|
|
let value=rows[row+1][column+keyIndex+1]||''
|
|
if(value===''){
|
|
console.warn(`第${row+1}行${key.key}对应的${rows[0].slice(keyIndex+1)[column]}没有翻译!`)
|
|
}
|
|
obj[key.key]=value
|
|
})
|
|
})
|
|
|
|
console.info(i18n)
|
|
let dir='locale'
|
|
if (!fs.existsSync(dir)){
|
|
fs.mkdir(dir,function(error){
|
|
if(error){
|
|
console.log(error);
|
|
return false;
|
|
}
|
|
createFile(rows[0].slice(keyIndex+1),i18n)
|
|
})
|
|
}else{
|
|
createFile(rows[0].slice(keyIndex+1),i18n)
|
|
}
|
|
|
|
|
|
} else {
|
|
console.log('语言包没有翻译文本或格式不合法');
|
|
}
|
|
});
|
|
}
|
|
|
|
function createFile(languages,i18n){
|
|
languages.map((filename,index)=>{
|
|
fs.writeFile(`locale/${filename}.json`, JSON.stringify(i18n[index]), (err) => {
|
|
if (err) {
|
|
throw err;
|
|
}
|
|
});
|
|
})
|
|
}
|
|
// [END sheets_quickstart]
|
|
|
|
module.exports = {
|
|
SCOPES,
|
|
listMajors,
|
|
};
|
|
|