Commit f3f6dfbd authored by Medicean's avatar Medicean

自动更新调整

parent 891b7197
......@@ -7,11 +7,17 @@
const config = require('./config');
const superagent = require('superagent');
const fs = require("fs");
const path = require('path');
const through = require("through");
const tar = require('tar');
class Update {
constructor(electron) {
this.logger = new electron.Logger('Update');
electron.ipcMain.on('check-update', this.checkUpdate.bind(this));
electron.ipcMain
.on('check-update', this.checkUpdate.bind(this))
.on('update-download', this.onDownlaod.bind(this));
}
/**
......@@ -67,6 +73,83 @@ class Update {
}
return false;
}
/**
* 监听下载请求
* @param {Object} event ipcMain事件对象
* @param {Object} opts 下载配置
* @return {[type]} [description]
*/
onDownlaod(event, opt) {
const hash = opt['hash'];
if (!hash) {
return
}
let that = this;
let savePath = path.join(config.tmpPath, "antsword.tar.gz");
let tempData = [];
let totalsize = 0;
let downsize = 0;
let url="https://github.com/AntSwordProject/AntSword/archive/master.tar.gz";
superagent.head(url)
.set('User-Agent', "antSword/v2.0")
.redirects(5)
.timeout(30000)
.end((err, res)=>{
if(err){
event.sender.send(`update-error-${hash}`, err);
}else{
totalsize = parseInt(res.header['content-length']);
superagent
.get(url)
.set('User-Agent', "antSword/v2.0")
.redirects(5)
// .proxy(APROXY_CONF['uri'])
// 设置超时会导致文件过大时写入出错
// .timeout(timeout)
.pipe(through(
(chunk) => {
downsize += chunk.length;
var progress = parseInt(downsize/totalsize*100);
tempData.push(chunk);
event.sender.send(`update-dlprogress-${hash}`, progress);
},
() => {
that.logger.debug("Download end.");
let tempDataBuffer = Buffer.concat(tempData);
if (downsize != totalsize) {
event.sender.send(`update-error-${hash}`, "Download Error.");
return
}
event.sender.send(`update-dlend-${hash}`, tempDataBuffer.length);
// 同步写入文件
fs.writeFileSync(savePath, tempDataBuffer);
// 删除内存数据
tempDataBuffer = tempData = null;
// TODO: 需不需要备份?
// TODO: 删除原来的 node_modules 目录
// 解压数据
tar.x({
file: savePath,
strip: 1,
C: process.env.AS_WORKDIR,
}).then(_=>{
that.logger.info("update success.");
event.sender.send(`update-success`);
fs.unlink(savePath);
}, err=>{
event.sender.send(`update-error-${hash}`, err);
fs.unlink(savePath);
});
}
));
}
});
}
}
module.exports = Update;
......@@ -240,12 +240,82 @@ ipcRenderer
* @return {[type]} [description]
*/
.on('notification-update', (e, opt) => {
const LANG = antSword["language"]["settings"]["update"];
let n = new Notification(antSword['language']['update']['title'], {
body: antSword['language']['update']['body'](opt['ver'])
});
n.addEventListener('click', () => {
antSword.shell.openExternal(opt['url']);
});
const WIN = require('ui/window');
let win = new WIN({
title: antSword['language']['update']['title'],
height:130,
width:280
});
win.win.button("minmax").hide();
win.win.denyResize();
let uplayout = win.win.attachLayout('1C');
uplayout.cells('a').hideHeader();
let formdata = [
{type:"label" , name:"form_msg", label:LANG["prompt"]["body"](opt['ver']), offsetLeft: 5},
{type: "block", list:[
{type:"button" , name:"updatebtn", value: `<i class="fa fa-cloud-download"></i> ${LANG["prompt"]["btns"]["ok"]}`, className:"background-color: #39c;"},
{type:"newcolumn", offset:15},
{type:"button" , name:"canclebtn", value: `${LANG["prompt"]["btns"]["no"]}`},
]
}];
uplayout.cells('a').attachForm(formdata, true);
win.win.attachEvent('onParkUp', () => {
win.win.setPosition(document.body.clientWidth-300,document.body.clientHeight-150);
return true;
});
win.win.attachEvent('onParkDown', () =>{
win.win.centerOnScreen();
return true;
});
const form = uplayout.cells('a').attachForm(formdata, true);
form.attachEvent("onButtonClick", (name)=>{
switch (name) {
case "updatebtn":
const hash = (String(+new Date) + String(Math.random())).substr(10, 10).replace('.', '_');
//折叠
win.win.park();
antSword.ipcRenderer.send("update-download", {hash: hash});
win.win.progressOn();
win.setTitle(LANG["message"]["prepare"]);
antSword['ipcRenderer']
.on(`update-dlprogress-${hash}`, (event, progress)=>{
win.setTitle(LANG["message"]["dling"](progress));
})
.once(`update-dlend-${hash}`,(event)=>{
win.setTitle(LANG["message"]["dlend"]);
win.win.progressOff();
toastr.success(antSword["language"]["success"], LANG["message"]["extract"]);
})
.once(`update-error-${hash}`, (event, err)=>{
toastr.error(antSword["language"]['error'], LANG["message"]["fail"](err));
win.win.progressOff();
win.close();
});
break;
case "canclebtn":
win.close();
break;
}
});
})
.on('update-success', (e, opt)=>{
const LANG = antSword['language']['settings']['update'];
toastr.success(antSword["language"]["success"], LANG["message"]["success"]);
layer.confirm(LANG['message']['success'], {
icon: 1, shift: 6,
title: LANG['prompt']['title']
}, (_) => {
// location.reload();
antSword.remote.app.quit();
});
})
/**
* 重新加载本地插件
......
......@@ -444,6 +444,7 @@ module.exports = {
ok: 'Update',
no: 'Cancel'
},
body: (ver) => `Found new version v${ver}, update now?`,
title: 'Update to version',
changelog: 'Change Logs: ',
sources: 'Download source: ',
......@@ -453,6 +454,10 @@ module.exports = {
}
},
message: {
prepare: "Connecte to server...",
dling: (progress)=> `Downloading...${progress}%`,
dlend: "Download completed",
extract: "Unpacking, don't close AntSword",
ing: 'Downloading..',
fail: (err) => `Update failed! [${err}]`,
success: 'Update success! Please manually restart the application later!'
......@@ -531,7 +536,8 @@ module.exports = {
},
update: {
title: 'Found updates',
body: (ver) => `New version: ${ver}`
body: (ver) => `New version: ${ver}, view changelog`,
},
viewsite: {
toolbar: {
......
......@@ -442,9 +442,10 @@ module.exports = {
},
prompt: {
btns: {
ok: '更新',
no: '取消'
ok: '立即更新',
no: '下次再说'
},
body: (ver) => `发现新版本 v${ver}, 是否更新?`,
title: '版本更新',
changelog: '更新日志:',
sources: '更新来源:',
......@@ -454,6 +455,10 @@ module.exports = {
}
},
message: {
prepare: "连接更新服务器...",
dling: (progress)=> `正在下载更新包...${progress}%`,
dlend: "下载完毕",
extract: "正在解压, 请务关闭程序",
ing: '努力更新中。。',
fail: (err) => `更新失败!【${err}】`,
success: '更新成功!请稍后手动重启应用!'
......@@ -532,7 +537,7 @@ module.exports = {
},
update: {
title: '发现更新',
body: (ver) => `新的版本:${ver}`
body: (ver) => `新的版本:${ver}, 查看更新日志`,
},
viewsite: {
toolbar: {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment