123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870 |
- /** @format */
- const gulp = require('gulp')
- const del = require('del')
- const shell = require('gulp-shell')
- const replace = require('gulp-replace')
- const fs = require('fs')
- const zip = require('gulp-zip')
- const path = require('path')
- const Sftp = require('ssh2-sftp-client')
- const WebSocket = require('ws')
- const https = require('https')
- const minimist = require('minimist')
- const GulpSSH = require('gulp-ssh')
- const vinylPaths = require('vinyl-paths')
- const rename = require('gulp-rename')
- const ChineseStoryCfg = require('./config/output/ChineseStoryCfg.js')
- const ChineseWordCfg = require('./config/output/ChineseWordCfg.js')
- const PinyinChange = require('./config/output/PinyinChange.js')
- const PoetryQuestionCfg = require('./config/output/PoetryQuestionCfg.js')
- // 配置
- const knownOptions = {
- string: 'version',
- string: 'cocosPath',
- string: 'buildPath',
- string: 'debugBool',
- string: 'releaseBool',
- string: 'h5RemoteUrl',
- string: 'configUrl',
- string: 'packageName',
- string: 'keystorePath',
- string: 'isQQ',
- string: 'isTT',
- string: 'appid',
- string: 'appType',
- default: {
- version: '1',
- cocosPath: 'D:/cocosEditors/Creator/2.4.8/CocosCreator.exe',
- buildPath: './build',
- debugBool: 'false',
- releaseBool: 'false',
- h5RemoteUrl: '/www/wwwroot/zedu-cocos-jxb-dev/',
- configUrl: '',
- packageName: 'com.zedu',
- autoCompile: 'false',
- keystorePath: 'D:/keystore/key.store',
- appid: 'wx7a1fbe2f424a93b4',
- isQQ: 'false',
- isTT: 'false',
- appType: 1,
- gameType: 1,
- },
- }
- const options = minimist(process.argv.slice(2), knownOptions)
- const resServerConfig = {
- host: options.debugBool == 'true' || options.releaseBool == 'true' ? '47.107.63.156' : '47.107.63.156',
- port: 22,
- username: 'root',
- privateKey: fs.readFileSync('D:\\cer\\id_rsa'),
- }
- let getGulpSSH = (isTest = true) => {
- return new GulpSSH({
- ignoreErrors: false,
- sshConfig: {
- host: isTest ? '47.107.63.156' : '47.107.63.156',
- port: 22,
- username: 'root',
- privateKey: fs.readFileSync('D:\\cer\\id_rsa'),
- },
- })
- }
- const zipName = 'upload.zip'
- const testResUrl = ''
- const onlineResUrl = ''
- const localUploadUrl = path.join(options.buildPath, 'upload')
- // shell
- let shellTask = `${options.cocosPath} --path ./ --build "buildPath=${options.buildPath};platform=wechatgame;debug=${options.debugBool};"`
- let h5ShellTask = `${options.cocosPath} --path ./ --build "buildPath=${
- options.buildPath
- };platform=web-mobile;embedWebDebugger=${options.debugBool == 'true' || options.releaseBool == 'true'};debug=${
- options.debugBool
- };"`
- let IOSShellTask = `${options.cocosPath} --path ./ --build "buildPath=${options.buildPath};platform=ios;template=link;debug=${options.debugBool};"`
- let AndroidShellTask = `${options.cocosPath} --path ./ --build "buildPath=${options.buildPath};platform=android;template=link;debug=${options.debugBool};autoCompile=${options.autoCompile};useDebugKeystore=false;keystorePath=${options.keystorePath};keystorePassword=888888;keystoreAlias=app-key;keystoreAliasPassword=666666;apiLevel=android-30;appABIs=['arm64-v8a','armeabi-v7a'];packageName=${options.packageName};md5Cache=false;"`
- let wxsubshellTask = `${options.cocosPath} --path ./wx_sub --build "buildPath=./build/;platform=wechatgame-subcontext"`
- let TTShellTask = `${options.cocosPath} --path ./ --build "buildPath=${options.buildPath};platform=bytedance;debug=${options.debugBool};mainIsRemote=true;"`
- let win32ShellTask = `${options.cocosPath} --path ./ --build "buildPath=${options.buildPath};platform=win32;template=link;debug=${options.debugBool};md5Cache=false;"`
- // 文件修改
- gulp.task('copy:Regular', () =>
- gulp
- .src('./assets/script/data/ConstValue.ts')
- .pipe(replace('DEBUG = true', 'DEBUG = ' + options.debugBool))
- .pipe(replace('DEBUG = false', 'DEBUG = ' + options.debugBool))
- .pipe(gulp.dest('./assets/script/data')),
- )
- gulp.task('copy:index', () =>
- gulp
- .src('./build-templates/web-mobile/index.html')
- .pipe(
- replace(
- '<script src="vconsole.min.js"></script>',
- `<script src="${
- options.debugBool == 'true' || options.releaseBool == 'true' ? 'vconsole.min.js' : ''
- }"></script>`,
- ),
- )
- .pipe(
- replace(
- '<script src=""></script>',
- `<script src="${
- options.debugBool == 'true' || options.releaseBool == 'true' ? 'vconsole.min.js' : ''
- }"></script>`,
- ),
- )
- .pipe(gulp.dest('./build-templates/web-mobile')),
- )
- const updateJson = (jsonUrl, key, value, key2) => {
- const json = JSON.parse(fs.readFileSync(jsonUrl).toString())
- if (key2) {
- json[key2][key] = value
- } else {
- json[key] = value
- }
- fs.writeFileSync(jsonUrl, JSON.stringify(json, '', ' '))
- }
- gulp.task('copy:REMOTE_SERVER_ROOT', cb => {
- let url = options.debugBool == 'true' ? testResUrl : onlineResUrl
- url += options.isQQ == 'true' ? 'card-qq' : 'card-wx'
- updateJson('./settings/wechatgame.json', 'REMOTE_SERVER_ROOT', url)
- updateJson('./settings/wechatgame.json', 'appid', options.appid)
- updateJson('./settings/builder.json', 'REMOTE_SERVER_ROOT', url, 'wechatgame')
- updateJson('./settings/builder.json', 'appid', options.appid, 'wechatgame')
- cb()
- })
- // 资源上传
- const copy = (src, dst) => fs.writeFileSync(dst, fs.readFileSync(src))
- const mkdirsSync = dirname => {
- if (fs.existsSync(dirname)) {
- return true
- } else if (mkdirsSync(path.dirname(dirname))) {
- fs.mkdirSync(dirname)
- return true
- }
- return false
- }
- const delDir = dirPath => {
- let files = []
- if (fs.existsSync(dirPath)) {
- files = fs.readdirSync(dirPath)
- files.forEach(file => {
- const curPath = path.join(dirPath, file)
- if (fs.statSync(curPath).isDirectory()) {
- delDir(curPath) // 递归删除文件夹
- } else {
- fs.unlinkSync(curPath) // 删除文件
- }
- })
- fs.rmdirSync(dirPath)
- }
- }
- const readFileList = (filePath, filesList = []) => {
- const files = fs.readdirSync(filePath)
- files.forEach(fileName => {
- const fullPath = path.join(filePath, fileName)
- if (fs.statSync(fullPath).isDirectory()) {
- readFileList(fullPath, filesList) // 递归读取文件
- } else {
- filesList.push(fullPath)
- }
- })
- return filesList
- }
- const curUpLoadResRecord = []
- let UpLoadResRecordKeys = []
- const UpLoadResRecordUrl = options.debugBool == 'true' ? './UpLoadResTestRecord.txt' : './UpLoadResRecord.txt'
- const uploadRes = (inputPath, platfrom) => {
- const files = readFileList(inputPath)
- if (!fs.existsSync(UpLoadResRecordUrl)) {
- fs.writeFileSync(UpLoadResRecordUrl, '', 'utf-8')
- }
- UpLoadResRecordKeys = fs.readFileSync(UpLoadResRecordUrl, 'utf-8').split('\r\n')
- UpLoadResRecordKeys = UpLoadResRecordKeys.filter(value => value != '')
- delDir(localUploadUrl) // 清空打包文件夹
- mkdirsSync(localUploadUrl) // 建立打包文件夹
- // 分析差异文件,拷贝到打包文件夹
- for (let i = 0; i < files.length; i++) {
- if (UpLoadResRecordKeys.indexOf(files[i]) < 0 || files[i].indexOf('index.html') != -1) {
- const dist = files[i].replace(path.join(options.buildPath, platfrom), localUploadUrl)
- // console.log(i, files[i], dist);
- mkdirsSync(path.resolve(dist, '..')) // 确保拷贝前目录存在
- if (fs.existsSync(files[i])) {
- copy(files[i], dist)
- } else {
- console.log(' uploadRes copy file:', files[i], 'no exist')
- }
- curUpLoadResRecord.push(files[i])
- }
- }
- mkdirsSync(path.join(localUploadUrl, 'empty'))
- // 拷贝分享目录
- /*
- const share = readFileList('./share');
- for (let i = 0; i < share.length; i++) {
- const dist = path.join(localUploadUrl, share[i]);
- mkdirsSync(path.resolve(dist, '..')); // 确保拷贝前目录存在
- copy(share[i], dist);
- }
- */
- }
- gulp.task('copy:uploadRes', cb => {
- let platform = 'wechatgame'
- if (options.isTT == 'true') platform = 'bytedance'
- uploadRes(`${options.buildPath}/${platform}/remote/`, platform)
- cb()
- })
- gulp.task('copy:uploadResH5', cb => {
- uploadRes(`${options.buildPath}/web-mobile/`, 'web-mobile')
- cb()
- })
- gulp.task('Zip', () => gulp.src(`${localUploadUrl}/**/*`).pipe(zip(zipName)).pipe(gulp.dest(localUploadUrl)))
- let preTime = 0
- let curByte = 0
- const ftpUpload = (cb, remoteUrl) => {
- let sftp = new Sftp()
- sftp.connect(resServerConfig)
- .then(() => {
- console.log(
- 'sftp连接成功,上传中... ',
- zipName,
- 'localUploadUrl-->',
- path.join(localUploadUrl, zipName),
- 'remoteUrl--->',
- `${remoteUrl}${zipName}`,
- )
- return sftp.fastPut(path.join(localUploadUrl, zipName), `${remoteUrl}${zipName}`, {
- step: (cur, chunk, total) => {
- if (preTime == 0) {
- preTime = Date.now()
- curByte = cur
- }
- const stepTime = Date.now() - preTime
- if (stepTime > 1000) {
- preTime = Date.now()
- const stepByte = cur - curByte
- console.log(((cur / total) * 100).toFixed(2), '% ', (stepByte / 1024).toFixed(2), 'kb/s')
- curByte = cur
- }
- },
- })
- })
- .then(() => {
- console.log('上传完成!')
- cb()
- })
- .catch(err => {
- console.log('sftp报错', err)
- })
- .finally(data => {
- console.log('sftpfinally', data)
- sftp.end()
- })
- }
- let unZipSucc = true
- let getDeleteJsonList = function (path, list) {
- let files = fs.readdirSync(path)
- files.forEach(item => {
- let stat = fs.statSync(path + item)
- if (stat.isDirectory()) {
- getDeleteJsonList(path + item + '/', list)
- } else if (stat.size > 0 * 1024) {
- list.push(path + item)
- }
- })
- return list
- }
- gulp.task('clean:res', cb => {
- let platform = 'wechatgame'
- if (options.isTT == 'true') platform = 'bytedance'
- let list = []
- let path = `${options.buildPath}/${platform}/remote/`
- getDeleteJsonList(path, list)
- console.log(list)
- del.sync(list, {force: true, allowEmpty: true})
- cb()
- })
- gulp.task('updateUploadUrl', cb => {
- if (unZipSucc) {
- let apendStr = ''
- for (let i = 0; i < curUpLoadResRecord.length; i++) {
- apendStr += `${curUpLoadResRecord[i]}\r\n`
- }
- fs.appendFileSync(UpLoadResRecordUrl, apendStr, 'utf-8')
- } else {
- console.log('远程解压缩失败')
- }
- cb()
- })
- let getRemoteUrl = () => {
- let url = ''
- return url
- }
- gulp.task('SFTP', cb => ftpUpload(cb, getRemoteUrl()))
- gulp.task('H5SFTP', cb => ftpUpload(cb, options.h5RemoteUrl))
- gulp.task('UnZip', cb => {
- cb()
- // return getGulpSSH()
- // .shell(['cd ' + options.h5RemoteUrl, 'unzip -Co upload.zip -d ./'])
- })
- gulp.task('uploadQiniu', shell.task(`java -DwebRoot=${localUploadUrl} -DdirPath=${localUploadUrl} -jar qiniu.jar`))
- gulp.task('uploadResContinueH5', gulp.series('copy:uploadResH5', 'Zip', 'H5SFTP', 'UnZip', 'updateUploadUrl'))
- gulp.task('uploadResContinueH5qiniu', gulp.series('copy:uploadResH5', 'uploadQiniu', 'updateUploadUrl'))
- gulp.task('uploadResContinue', gulp.series('copy:uploadRes', 'Zip', 'SFTP', 'UnZip', 'clean:res', 'updateUploadUrl'))
- Date.prototype.Format = function (fmt) {
- let o = {
- 'Y+': this.getFullYear(), // 年
- 'M+': this.getMonth() + 1, // 月份
- 'd+': this.getDate(), // 日
- 'h+': this.getHours(), // 小时
- 'm+': this.getMinutes(), // 分
- 's+': this.getSeconds(), // 秒
- 'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
- 'S+': this.getMilliseconds(), // 毫秒
- }
- if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, `${this.getFullYear()}`.substr(4 - RegExp.$1.length))
- for (let k in o)
- if (new RegExp(`(${k})`).test(fmt))
- fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length))
- return fmt
- }
- gulp.task('version', () => {
- let filePath = './assets/resources/version.json'
- let obj = {}
- obj.time = new Date().Format('YYMMddhhmmss')
- obj.appType = options.appType
- obj.gameType = options.gameType
- fs.writeFileSync(filePath, JSON.stringify(obj))
- return gulp.src('./build-templates/jsb-link/main.js')
- .pipe(replace(/window\._game_res_version = \'\d{12}\'/g, `window._game_res_version = \'${obj.time}\'`))
- .pipe(gulp.dest('./build-templates/jsb-link/'))
- })
- gulp.task(
- 'wxsub',
- gulp.series(
- /*'compile-wxsub','copywxsub'*/ cb => {
- cb()
- },
- ),
- )
- gulp.task('copywxsub', () => gulp.src('./wx_sub/build/**/*').pipe(gulp.dest(`${options.buildPath}/wechatgame`)))
- gulp.task('compile-wxsub', shell.task(wxsubshellTask))
- gulp.task(
- 'WX',
- gulp.series('version', 'copy:Regular', 'copy:REMOTE_SERVER_ROOT', shell.task(shellTask), 'uploadResContinue'),
- )
- gulp.task('H5', gulp.series('version', 'copy:Regular', 'copy:index', shell.task(h5ShellTask), 'uploadResContinueH5'))
- gulp.task(
- 'H5qiniu',
- gulp.series('version', 'copy:Regular', 'copy:index', shell.task(h5ShellTask), 'uploadResContinueH5qiniu'),
- )
- gulp.task('IOS', gulp.series('version', 'copy:Regular', shell.task(IOSShellTask)))
- gulp.task('Android', gulp.series('version', 'copy:Regular', shell.task(AndroidShellTask)))
- gulp.task('TT', gulp.series('version', 'copy:Regular', shell.task(TTShellTask), 'uploadResContinue'))
- gulp.task('win32', gulp.series('version', 'copy:Regular', shell.task(win32ShellTask)))
- const {URL} = require('url')
- const cwd = process.cwd()
- const root = cwd
- ;(exts = ['.jpg', '.png']), (max = 5200000) // 5MB == 5242848.754299136
- const tinypngoptions = {
- method: 'POST',
- hostname: 'tinypng.com',
- path: '/web/shrink',
- headers: {
- rejectUnauthorized: false,
- 'Postman-Token': Date.now(),
- 'Cache-Control': 'no-cache',
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'User-Agent':
- 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
- },
- }
- // 生成随机IP, 赋值给 X-Forwarded-For
- function getRandomIP() {
- return Array.from(Array(4))
- .map(() => parseInt(Math.random() * 255))
- .join('.')
- }
- let allUploadFiles = []
- let allSuccessUploadFiles = new Map()
- let curAllUploadCount = 0
- let maxReq = 500
- let fileUploadIDs = new Map()
- let tinyPngRecords = new Map()
- // 获取文件列表
- function fileList(folder) {
- let files = fs.readdirSync(folder)
- files.forEach(file1 => {
- let file = path.join(folder, file1)
- let stats = fs.statSync(file)
- if (
- // 必须是文件,小于5MB,后缀 jpg||png
- stats.size <= max &&
- stats.isFile() &&
- exts.includes(path.extname(file))
- ) {
- // 通过 X-Forwarded-For 头部伪造客户端IP
- console.log('可以压缩:' + file)
- allUploadFiles.push(file)
- }
- if (stats.isDirectory()) fileList(file + '/')
- })
- }
- let crypto = require('crypto')
- function MD5(img) {
- let buffer = fs.readFileSync(img)
- let fsHash = crypto.createHash('md5')
- fsHash.update(buffer)
- return fsHash.digest('hex')
- }
- function popUploadFiles(cb) {
- for (let i = 0; i < maxReq; i++) {
- let file = allUploadFiles.pop()
- if (file) {
- let hasRecord = false
- let recordData = tinyPngRecords.get(file)
- if (recordData && recordData == MD5(path.join(cwd, file))) {
- hasRecord = true
- }
- if (hasRecord) {
- allSuccessUploadFiles.set(file, true)
- if (allSuccessUploadFiles.size == curAllUploadCount) {
- cb()
- } else {
- let curCount = allSuccessUploadFiles.size
- if (curCount % maxReq == 0) popUploadFiles(cb)
- console.log('当前总进度:', allSuccessUploadFiles.size, '/', curAllUploadCount)
- }
- } else {
- fileUpload(file, cb)
- }
- }
- }
- }
- // 过滤文件格式,返回所有jpg,png图片
- function fileFilter(file) {
- // fs.stat(file, (err, stats) => {
- // if (err) return console.error(err);
- //
- // });
- }
- // 异步API,压缩图片
- // {"error":"Bad request","message":"Request is invalid"}
- // {"input": { "size": 887, "type": "image/png" },"output": { "size": 785, "type": "image/png", "width": 81, "height": 81, "ratio": 0.885, "url": "https://tinypng.com/web/output/7aztz90nq5p9545zch8gjzqg5ubdatd6" }}
- function fileUpload(img, cb) {
- tinypngoptions.headers['X-Forwarded-For'] = getRandomIP()
- let fileUploadID = fileUploadIDs.get(img)
- if (fileUploadID) clearTimeout(fileUploadID)
- var req = https.request(tinypngoptions, function (res) {
- res.on('data', buf => {
- try {
- let obj = JSON.parse(buf.toString())
- if (obj.error) {
- console.log(`[${img}]:压缩失败!报错:${obj.message}`)
- }
- fileUpdate(img, obj, cb)
- } catch (e) {
- }
- })
- })
- req.write(fs.readFileSync(img), 'binary')
- req.on('error', e => {
- console.error('fileUpload error:', e)
- })
- req.end()
- fileUploadID = setTimeout(() => {
- req.destroy()
- fileUpload(img, cb)
- }, 10000)
- fileUploadIDs.set(img, fileUploadID)
- }
- // 该方法被循环调用,请求图片数据
- function fileUpdate(imgpath, obj, cb, index) {
- const outputDir = path.join(cwd, '')
- let img = imgpath
- imgpath = path.join(cwd, '', imgpath.replace(cwd, ''))
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir)
- }
- let options = new URL(obj.output.url)
- let req = https.request(options, res => {
- let body = ''
- res.setEncoding('binary')
- res.on('data', function (data) {
- body += data
- })
- res.on('end', function () {
- fs.writeFile(imgpath, body, 'binary', err => {
- if (err) console.error(err)
- console.log(
- `[${imgpath}] \n 压缩成功,原始大小-${obj.input.size},压缩大小-${obj.output.size},优化比例-${obj.output.ratio}`,
- )
- // 替换文件md5或者新增
- let recordData = tinyPngRecords.get(img)
- let fileMd5 = MD5(img)
- if (recordData) {
- let content = fs.readFileSync(tinyPngRecordUrl, 'utf-8')
- content.replace(img + '||' + recordData, img + '||' + fileMd5)
- fs.writeFileSync(tinyPngRecordUrl, content, 'utf-8')
- } else {
- let str = '\r\n' + img + '||' + fileMd5
- fs.appendFileSync(tinyPngRecordUrl, str, 'utf-8')
- }
- let fileUploadID = fileUploadIDs.get(img)
- if (fileUploadID) clearTimeout(fileUploadID)
- allSuccessUploadFiles.set(img, true)
- if (allSuccessUploadFiles.size == curAllUploadCount) {
- cb()
- } else {
- let curCount = allSuccessUploadFiles.size
- if (curCount % maxReq == 0) popUploadFiles(cb)
- console.log('当前总进度:', allSuccessUploadFiles.size, '/', curAllUploadCount)
- }
- })
- })
- })
- req.on('error', e => {
- console.error(e)
- })
- req.end()
- }
- let tinyPngRecordUrl = './tinyPngRecordUrl.txt'
- gulp.task('tinypng', function (cb) {
- if (!fs.existsSync(tinyPngRecordUrl)) {
- fs.writeFileSync(tinyPngRecordUrl, '', 'utf-8')
- }
- let tinyPngRecordArr = fs.readFileSync(tinyPngRecordUrl, 'utf-8').split('\r\n')
- for (let i = 0; i < tinyPngRecordArr.length; i++) {
- let obj = tinyPngRecordArr[i].split('||')
- tinyPngRecords.set(obj[0], obj[1])
- }
- fileList('./assets')
- curAllUploadCount = allUploadFiles.length
- console.log('tinypng curAllUploadCount:', curAllUploadCount)
- popUploadFiles(cb)
- })
- let semeArr = ['S231', 'S232', 'S341', 'S342', 'S451', 'S452', 'S561', 'S562']
- let curG = 'D:/zedu_jxb/assets/gameChildSeme'
- gulp.task('copyPng', cb => {
- semeArr.forEach(value => {
- for (let i = 1; i < 17; i++) {
- let g = i.toString().padStart(2, '0')
- fs.writeFileSync(
- `${curG}/${value}/G${g}/bg.png`,
- fs.readFileSync(`D:/zedu_home/gameRes/gameHomeSeme/${value}/G${g}/P01/bg.png`),
- )
- }
- })
- cb()
- })
- gulp.task('deletePng', () => {
- return gulp.src([`${curG}/S***/G**/P**/bg.png`, `${curG}/S***/G**/P**/bg.png.meta`]).pipe(vinylPaths(del))
- })
- gulp.task('deletePart', () => {
- return gulp.src([`${curG}/S***/G**/P**/*`]).pipe(vinylPaths(del))
- })
- gulp.task('deletePrefab', () => {
- return gulp.src([`${curG}/S***/G**/**.prefab`, `${curG}/S***/G**/**.prefab.meta`]).pipe(vinylPaths(del))
- })
- gulp.task('deleteDataJson', () => {
- return gulp.src([`${curG}/S***/G**/P**/data.json`, `${curG}/S***/G**/P**/data.json.meta`]).pipe(vinylPaths(del))
- })
- gulp.task('modifyDataJson', cb => {
- for (let value of semeArr) {
- for (let i = 1; i <= 16; i++) {
- for (let j = 1; j <= 16; j++) {
- let path = `${curG}/${value}/G${i.toString().padStart(2, '0')}/P${j
- .toString()
- .padStart(2, '0')}/data_${value.replace('S', '')}_${i}_${j}.json`
- if (fs.existsSync(path)) {
- let obj = JSON.parse(fs.readFileSync(path, 'utf-8'))
- if (obj.gameMode == 0) {
- obj.gameMode = 6
- fs.writeFileSync(path, JSON.stringify(obj, null, 2))
- }
- }
- }
- }
- }
- cb()
- })
- gulp.task('copyMp3', () => {
- return gulp.src([`D:/zedu_jxb/gameRes/gameChildSeme/**/**~1.mp3`]).pipe(rename(function (path) {
- // Updates the object in-place
- path.basename = path.basename.replace("~1", "")
- })).pipe(gulp.dest('D:/zedu_jxb/gameRes/gameChildSeme/'))
- })
- let qiniu = require("qiniu");
- let qiniuJS = require("qiniu-js");
- var accessKey = '0Alb-OTi_yKnSAa71Ey_4vPtNVlGJOMWUrYMh_ql';
- var secretKey = '28QoQoyhUSIO8zhZnSOwtJeBXSDcCWp_0f72tSnL';
- var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
- function uptoken(bucket, keyToOverwrite) {
- var options = {
- scope: bucket + ":" + keyToOverwrite,
- expires: 7200
- }
- var putPolicy = new qiniu.rs.PutPolicy(options);
- var uploadToken = putPolicy.uploadToken(mac);
- return uploadToken;
- }
- //构造上传函数
- function qiniuUploadFile(localFile) {
- let key = localFile.replace('D:/zedu_jxb/packages-hot-update/manifest/', '')
- if (localFile.includes('build/jsb-link')) {
- key = localFile.replace('D:/zedu_jxb/build/jsb-link/', '')
- }
- key = 'hotupdate/' + key
- //生成上传 Token
- token = uptoken('zedu-cdn', key);
- let config = new qiniu.conf.Config()
- config.zone = qiniu.zone.Zone_z2
- var formUploader = new qiniu.form_up.FormUploader(config);
- // 文件上传
- formUploader.putFile(token, key, localFile, new qiniu.form_up.PutExtra(), function (respErr,
- respBody, respInfo) {
- if (respErr) {
- throw respErr;
- }
- if (respInfo.statusCode == 200) {
- console.log('七牛上传成功:-------------》', respBody);
- } else {
- qiniuUploadFile(localFile)
- console.log('七牛上传失败:-------------》', respInfo);
- }
- });
- }
- let bucketPathName = ['', '', '', '', '', '', 'chinese', 'math', 'poetry', 'pinyin']
- bucketPathName[100] = 'win32'
- let upLoadHotAssets = {}
- const UpLoadHotUrl = './UpLoadHotResRecord.txt'
- const uploadHotRes = () => {
- let projectManifestUrl = `D:/zedu_jxb/packages-hot-update/${bucketPathName[options.gameType]}/manifest/project.manifest`
- let versionManifestUrl = `D:/zedu_jxb/packages-hot-update/${bucketPathName[options.gameType]}/manifest/version.manifest`
- let files = []
- readFileList('D:/zedu_jxb/build/jsb-link/assets', files)
- readFileList('D:/zedu_jxb/build/jsb-link/src', files)
- if (!fs.existsSync(UpLoadHotUrl)) {
- fs.writeFileSync(UpLoadHotUrl, JSON.stringify({}), 'utf-8')
- }
- let curAssets = JSON.parse(fs.readFileSync(projectManifestUrl, 'utf-8')).assets
- upLoadHotAssets = JSON.parse(fs.readFileSync(UpLoadHotUrl, 'utf-8'))
- delDir(localUploadUrl) // 清空打包文件夹
- mkdirsSync(localUploadUrl) // 建立打包文件夹
- copy(projectManifestUrl, localUploadUrl + '\\project.manifest')
- copy(versionManifestUrl, localUploadUrl + '\\version.manifest')
- // 分析差异文件,拷贝到打包文件夹
- for (let i = 0; i < files.length; i++) {
- let file = files[i]
- let srcKey = file.replace('D:\\zedu_jxb\\build\\jsb-link\\', '').replace(new RegExp('\\\\', 'g'), '/')
- let srcObj = upLoadHotAssets[srcKey]
- if (!srcObj || curAssets[srcKey].md5 != srcObj.md5) {
- const dist = file.replace('D:\\zedu_jxb\\build\\jsb-link', localUploadUrl)
- // console.log(i, files[i], dist);
- mkdirsSync(path.resolve(dist, '..')) // 确保拷贝前目录存在
- if (fs.existsSync(file)) {
- copy(file, dist)
- upLoadHotAssets[srcKey] = srcObj
- } else {
- console.log(' uploadRes copy file:', file, 'no exist')
- }
- }
- }
- }
- gulp.task('updateHotUploadTxt', cb => {
- fs.writeFileSync(UpLoadHotUrl, JSON.stringify(upLoadHotAssets), 'utf-8')
- cb()
- })
- gulp.task('QiniuHotFresh', (cb) => {
- var dirsToRefresh = [
- 'https://hotupdate.zhi-edu.com/'
- ];
- var cdnManager = new qiniu.cdn.CdnManager(mac);
- //单次请求链接不可以超过10个,如果超过,请分批发送请求
- cdnManager.refreshDirs(dirsToRefresh, function (err, respBody, respInfo) {
- if (err) {
- throw err;
- }
- console.log(respInfo.statusCode);
- if (respInfo.statusCode == 200) {
- console.log(dirsToRefresh, '七牛cdn刷新成功');
- }
- });
- cb()
- })
- gulp.task('uploadQiniuHot', shell.task(`java -DwebRoot=${localUploadUrl} -DdirPath=${localUploadUrl} -Dbucket=zedu-hotupdate -DbucketPath=${bucketPathName[options.gameType]} -jar qiniu.jar`))
- gulp.task('copyUploadHot', (cb) => {
- uploadHotRes()
- cb()
- })
- gulp.task('uploadHotUpdate', gulp.series('copyUploadHot', 'uploadQiniuHot', 'updateHotUploadTxt', 'QiniuHotFresh'))
- let semeWordPinyin = {}
- let semeStroke = {}
- const {pinyin} = require('pinyin-pro');
- var cnchar = require('cnchar');
- var cncharorder = require('cnchar-order');
- let getTsFileString = (jsobj, fileName) => {
- var s = `export let ${fileName}=\r\n{`
- for (let key in jsobj) {
- s += `\r\n '${key}':{ `
- for (let key1 in jsobj[key]) {
- s += `${key1}: '${jsobj[key][key1]}', `
- }
- s = s.substr(0, s.length - 2)
- s += ' },'
- }
- s = s.substr(0, s.length - 1) // 单个对象为表去掉多余的数组逗号
- s += '\r\n}'
- return s
- }
- gulp.task('getpinyin', (cb) => {
- let newCfg = {}
- cnchar.use(cncharorder)
- for (let key in ChineseWordCfg) {
- let wordCfg = ChineseWordCfg[key]
- let word = wordCfg.word
- let strokeArr = cnchar.stroke(word, 'order', 'detail')[0]
- let tempArr = []
- strokeArr.forEach((item) => {
- if (item.name == '点2') {
- item.shape = '丶'
- }
- tempArr.push(item.shape.split('|')[0])
- })
- let obj = {}
- obj.id = wordCfg.id
- obj.word = word
- obj.phrase1 = wordCfg.phrase1
- obj.phrase2 = wordCfg.phrase2
- obj.pinyin = pinyin(word)
- obj.stroke = tempArr.join('、')
- let pinyinchange = PinyinChange[wordCfg.id]
- if (pinyinchange) {
- obj.pinyin = pinyinchange.newpy
- }
- newCfg[key] = obj
- }
- fs.writeFileSync('./assets/script/config/ChineseWordCfg.ts', getTsFileString(newCfg, 'ChineseWordCfg'), 'utf-8')
- cb()
- })
- gulp.task('getstorypinyin', (cb) => {
- let newCfg = {}
- cnchar.use(cncharorder)
- let semeArr = [231, 232, 341, 342, 451, 452, 561, 562]
- for (let i = 0; i < semeArr.length; i++) {
- for (let j = 1; j < 17; j++) {
- let key = semeArr[i] + '_' + j
- let oldCfg = {}
- if (ChineseStoryCfg[key]) oldCfg = ChineseStoryCfg[key]
- let obj = {}
- obj.title = oldCfg.title == undefined ? '' : oldCfg.title
- obj.tip = oldCfg.tip == undefined ? '' : oldCfg.tip
- obj.titlePinyin = (oldCfg.titlePinyin == undefined || oldCfg.titlePinyin == 0) ? pinyin(obj.title) : oldCfg.titlePinyin
- obj.story = oldCfg.story == undefined ? '' : oldCfg.story
- // obj.storyPinyin = ''
- // for (let i = 0; i < obj.story.length; i++) {
- // obj.storyPinyin += pinyin(obj.story.charAt(i))
- // }
- obj.storyPinyin = (oldCfg.storyPinyin == undefined || oldCfg.storyPinyin == 0) ? pinyin(obj.story) : oldCfg.storyPinyin
- obj.story = obj.story.replace(new RegExp('\n', 'g'), '\\n').replace(new RegExp('\t', 'g'), '\\t').replace(new RegExp('\b', 'g'), '\\b')
- obj.storyPinyin = obj.storyPinyin.replace(new RegExp('\n', 'g'), '\\n').replace(new RegExp('\t', 'g'), '\\t').replace(new RegExp('\b', 'g'), '\\b')
- let pinyinchange = PinyinChange[key]
- // 取消配置修改
- if (pinyinchange && false) {
- let oldArr = pinyinchange.oldpy.split('|')
- let newArr = pinyinchange.newpy.split('|')
- for (let k = 0; k < oldArr.length; k++) {
- if (newArr[k]) {
- obj.storyPinyin = obj.storyPinyin.replace(new RegExp(oldArr[k], 'g'), newArr[k])
- obj.titlePinyin = obj.titlePinyin.replace(new RegExp(oldArr[k], 'g'), newArr[k])
- }
- }
- }
- obj.isCenter = oldCfg.isCenter
- newCfg[key] = obj
- }
- }
- fs.writeFileSync('./assets/script/config/ChineseStoryCfg.ts', getTsFileString(newCfg, 'ChineseStoryCfg'), 'utf-8')
- cb()
- })
- gulp.task('copyWrite', (cb) => {
- cnchar.use(cncharorder)
- for (let key in ChineseWordCfg) {
- let value = ChineseWordCfg[key].word
- copy('D:/cocosProject/SSRSVGWriterComponent/assets/resources/hanzi-writer-data/' + value + '.json', './assets/gameChineseSeme/writedata/' + value + '.json')
- }
- cb()
- })
- gulp.task('getpoetry', (cb) => {
- let cfg = {}
- for (let key in PoetryQuestionCfg) {
- cfg[key] = {}
- Object.assign(cfg[key], PoetryQuestionCfg[key])
- cfg[key].poetry = cfg[key].poetry.replace(/\n/g, '\\n')
- cfg[key].poetryPinyin = cfg[key].poetryPinyin.replace(/\n /g, '\\n')
- }
- fs.writeFileSync('./assets/script/config/PoetryQuestionCfg.ts', getTsFileString(cfg, 'PoetryQuestionCfg'), {encoding: 'utf8'})
- cb()
- })
- gulp.task('normalCfg', (cb) => {
- let cfgName = ['PoetryStoryCfg']
- for (let name of cfgName) {
- let curJs = require(`./config/output/${name}.js`)
- if (!curJs) curJs = {}
- let cfg = {}
- for (let key in curJs) {
- cfg[key] = {}
- Object.assign(cfg[key], curJs[key])
- }
- fs.writeFileSync(`./assets/script/config/${name}.ts`, getTsFileString(cfg, name), {encoding: 'utf8'})
- }
- cb()
- })
- gulp.task('excle2js', shell.task('excel2x -i ./config -o ./config/output -t js_alone'))
- gulp.task('updateConfig', gulp.series('excle2js', 'getpinyin', 'getstorypinyin', 'getpoetry', 'normalCfg'))
|