Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

electron应用退出时保存状态与自动登录问题

最近在练习做网易云音乐项目在实现其中两个功能时遇到了一些问题,希望大佬能帮助解答

自动登录功能

实现思路

在用户登录时如果勾选了自动登录选项,就把用户的用户名与密码以加密形式保存在本地数据库,下次用户打开应用在App.vue挂载后直接读取并解密本地的用户名与密码,然后自动调用登录接口,从而实现自动登录。

加密与解密代码

const crypto = require('crypto');
const key = crypto.randomBytes(32); // 256 位的共享密钥
const iv = crypto.randomBytes(16); // 初始向量,16 字节
const algorithm = 'aes-256-gcm'; // 加密算法和操作模式
function encode(data) {//加密算法
// data:要加密的数据
  const cipher = crypto.createCipheriv(algorithm, key, iv); // 初始化加密算法
  let encrypted = cipher.update(data, 'utf8', 'hex');
  console.log(encrypted);
  return encrypted;
  
}
function decode(data) {//解密算法
// data:从本地数据库中读取的加密后的数据
  const decipher = crypto.createDecipheriv(algorithm, key, iv); // 初始化解密算法
  let decrypted = decipher.update(data, 'hex', 'utf8');
  return decrypted
}
export{
  encode,
  decode
}
  • 本地数据库:Nedb
  • 加密用的是node自带的crypto

问题

在解密保存的数据时发现无法还原,解密的结果是乱码。但是如果不将数据保存而是直接解密就没有问题。请问这是为什么?是因为Nedb以UTF-8的编码形式保存数据,而加密后的数据是hex编码形式,二者相冲突造成的么?

应用退出前保存所听的音乐

实现思路

在electron关闭时主进程向渲染进程通知渲染进程将当前的音乐信息保存到本地数据库。然后用户在下一次打开应用时直接读取。

相关代码

  • 关闭前发送通知
win = new BrowserWindow({
  width: 800, height: 600, webPreferences: {
    nodeIntegration: true
  },
  frame: false
})
 ...
win.on("close",()=>{
  win.webContents.send("close")
})
  • 渲染进程接到通知保存信息
const { ipcRenderer: ipc } = require("electron");
...
ipc.on("close", (res) => {
    ...
  localSetting.find({ index: { $exists: true }, name: { $exists: true }, }).then(
    async (musicInfo) => {
      if (musicInfo.length === 0) {
      //如果没有保存歌曲信息就先保存
         localSetting.insert([this.$store.state.musicInfo, this.$store.state.musicTime]);
          } else {
          //更新保存的歌曲信息
            let time = await localSetting.find({ currentTime: { $exists: true }, duration: { $exists: true }, })
            localSetting.update(musicInfo[0],this.$store.state.musicInfo)
            localSetting.update(time[0],this.$store.state.musicTime)
          }
        })
    })

问题

应用关闭后并没有将音乐信息插入或者更新

有没有大佬能告诉我这两个问题产生的原因是什么,该怎么解决?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

造成问题的原因应该是当close发起了一个通知,但是还没来的及执行,然后就程序退出了,应该把事情干完以后在关闭。
大概意思如下,直接上代码

win.on("close",(e)=>{
  //在这里应该阻止一下默认事件,不让它发起请求后立即关闭,等把事件做完以后在关闭,这里还要判断一下,不然真正退出的时候会有问题
  if(forceQuit){
      e.preventDefault();
      win.webContents.send("close")
  }
})
ipc.on("close", (res) => {
    ...localSetting
    等这里进行保存之后在关掉上面那个窗口或者整个软件
    forceQuit = false
    win.close()
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...