1 Star 0 Fork 51

llpku/weweChat

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.js 19.60 KB
一键复制 编辑 原始数据 按行查看 历史
小楼楼 提交于 2018-07-25 20:41 . Fix #147
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
import fs from 'fs';
import tmp from 'tmp';
import { app, powerMonitor, BrowserWindow, Tray, Menu, ipcMain, clipboard, shell, nativeImage, dialog } from 'electron';
import windowStateKeeper from 'electron-window-state';
import AutoLaunch from 'auto-launch';
import { autoUpdater } from 'electron-updater';
import axios from 'axios';
import pkg from './package.json';
let forceQuit = false;
let downloading = false;
let mainWindow;
let tray;
let settings = {};
let isFullScreen = false;
let isWin = process.platform === 'win32';
let isOsx = process.platform === 'darwin';
let isSuspend = false;
let userData = app.getPath('userData');
let imagesCacheDir = `${userData}/images`;
let voicesCacheDir = `${userData}/voices`;
let mainMenu = [
{
label: pkg.name,
submenu: [
{
label: `About ${pkg.name}`,
selector: 'orderFrontStandardAboutPanel:',
},
{
label: 'Preferences...',
accelerator: 'Cmd+,',
click() {
mainWindow.show();
mainWindow.webContents.send('show-settings');
}
},
{
type: 'separator'
},
{
role: 'hide'
},
{
role: 'hideothers'
},
{
role: 'unhide'
},
{
label: 'Check for updates',
accelerator: 'Cmd+U',
click() {
checkForUpdates();
}
},
{
type: 'separator'
},
{
label: 'Quit weweChat',
accelerator: 'Command+Q',
selector: 'terminate:',
click() {
forceQuit = true;
mainWindow = null;
app.quit();
}
}
]
},
{
label: 'File',
submenu: [
{
label: 'New Chat',
accelerator: 'Cmd+N',
click() {
mainWindow.show();
mainWindow.webContents.send('show-newchat');
}
},
{
label: 'Search...',
accelerator: 'Cmd+F',
click() {
mainWindow.show();
mainWindow.webContents.send('show-search');
}
},
{
label: 'Batch Send Message',
accelerator: 'Cmd+B',
click() {
mainWindow.show();
mainWindow.webContents.send('show-batchsend');
}
},
{
type: 'separator',
},
{
label: 'Insert emoji',
accelerator: 'Cmd+I',
click() {
mainWindow.show();
mainWindow.webContents.send('show-emoji');
}
},
{
type: 'separator',
},
{
label: 'Next conversation',
accelerator: 'Cmd+J',
click() {
mainWindow.show();
mainWindow.webContents.send('show-next');
}
},
{
label: 'Previous conversation',
accelerator: 'Cmd+K',
click() {
mainWindow.show();
mainWindow.webContents.send('show-previous');
}
},
]
},
{
label: 'Conversations',
submenu: [
{
label: 'Loading...',
}
],
},
{
label: 'Contacts',
submenu: [
{
label: 'Loading...',
}
],
},
{
},
{
label: 'Edit',
submenu: [
{
role: 'undo'
},
{
role: 'redo'
},
{
type: 'separator'
},
{
role: 'cut'
},
{
role: 'copy'
},
{
role: 'paste'
},
{
role: 'pasteandmatchstyle'
},
{
role: 'delete'
},
{
role: 'selectall'
}
]
},
{
label: 'View',
submenu: [
{
label: isFullScreen ? 'Exit Full Screen' : 'Enter Full Screen',
accelerator: 'Shift+Cmd+F',
click() {
isFullScreen = !isFullScreen;
mainWindow.show();
mainWindow.setFullScreen(isFullScreen);
}
},
{
label: 'Toggle Conversations',
accelerator: 'Shift+Cmd+M',
click() {
mainWindow.show();
mainWindow.webContents.send('show-conversations');
}
},
{
type: 'separator',
},
{
label: ''
},
{
type: 'separator',
},
{
role: 'toggledevtools'
},
{
role: 'togglefullscreen'
}
]
},
{
role: 'window',
submenu: [
{
role: 'minimize'
},
{
role: 'close'
}
]
},
{
role: 'help',
submenu: [
{
label: 'Feedback',
click() {
shell.openExternal('https://github.com/trazyn/weweChat/issues');
}
},
{
label: 'Fork me on Github',
click() {
shell.openExternal('https://github.com/trazyn/weweChat');
}
},
{
type: 'separator'
},
{
label: '💕 Follow me on Twitter 👏',
click() {
shell.openExternal('https://twitter.com/var_darling');
}
}
]
}
];
let trayMenu = [
{
label: `You have 0 messages`,
click() {
mainWindow.show();
mainWindow.webContents.send('show-messages');
}
},
{
label: 'Toggle main window',
click() {
let isVisible = mainWindow.isVisible();
isVisible ? mainWindow.hide() : mainWindow.show();
}
},
{
type: 'separator'
},
{
label: 'Preferences...',
accelerator: 'Cmd+,',
click() {
mainWindow.show();
mainWindow.webContents.send('show-settings');
}
},
{
label: 'Fork me on Github',
click() {
shell.openExternal('https://github.com/trazyn/weweChat');
}
},
{
type: 'separator'
},
{
label: 'Toggle DevTools',
accelerator: 'Alt+Command+I',
click() {
mainWindow.show();
mainWindow.toggleDevTools();
}
},
{
label: 'Hide menu bar icon',
click() {
mainWindow.webContents.send('hide-tray');
}
},
{
type: 'separator'
},
{
label: 'Check for updates',
accelerator: 'Cmd+U',
click() {
checkForUpdates();
}
},
{
label: 'Quit weweChat',
accelerator: 'Command+Q',
selector: 'terminate:',
click() {
forceQuit = true;
mainWindow = null;
app.quit();
}
}
];
let avatarPath = tmp.dirSync();
let avatarCache = {};
let avatarPlaceholder = `${__dirname}/src/assets/images/user-fallback.png`;
const icon = `${__dirname}/src/assets/images/dock.png`;
async function getIcon(cookies, userid, src) {
var cached = avatarCache[userid];
var icon;
if (cached) {
return cached;
}
if (cookies && src) {
try {
let response = await axios({
url: src,
method: 'get',
responseType: 'arraybuffer',
headers: {
Cookie: cookies,
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8',
},
});
// eslint-disable-next-line
let base64 = new Buffer(response.data, 'binary').toString('base64');
icon = `${avatarPath.name}/${userid}.jpg`;
fs.writeFileSync(icon, base64.replace(/^data:image\/png;base64,/, ''), 'base64');
} catch (ex) {
console.error(ex);
icon = avatarPlaceholder;
}
}
var image = nativeImage.createFromPath(icon);
image = image.resize({ width: 24, height: 24 });
avatarCache[userid] = image;
return image;
}
function checkForUpdates() {
if (downloading) {
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
title: pkg.name,
message: `Downloading...`,
detail: `Please leave the app open, the new version is downloading. You'll receive a new dialog when downloading is finished.`
});
return;
}
autoUpdater.checkForUpdates();
}
function updateTray(unread = 0) {
if (!isOsx) {
// Always show the tray icon on windows
settings.showOnTray = true;
}
// Update unread mesage count
trayMenu[0].label = `You have ${unread} messages`;
if (settings.showOnTray) {
if (tray
&& updateTray.lastUnread === unread) {
return;
}
let contextmenu = Menu.buildFromTemplate(trayMenu);
let icon = unread
? `${__dirname}/src/assets/images/icon-new-message.png`
: `${__dirname}/src/assets/images/icon.png`
;
// Make sure the last tray has been destroyed
setTimeout(() => {
if (!tray) {
// Init tray icon
tray = new Tray(icon);
tray.on('right-click', () => {
tray.popUpContextMenu();
});
let clicked = false;
tray.on('click', () => {
if (clicked) {
mainWindow.show();
clicked = false;
} else {
clicked = true;
setTimeout(() => {
clicked = false;
}, 400);
}
});
}
tray.setImage(icon);
tray.setContextMenu(contextmenu);
});
} else {
if (!tray) return;
tray.destroy();
tray = null;
}
// Avoid tray icon been recreate
updateTray.lastUnread = unread;
}
async function autostart() {
var launcher = new AutoLaunch({
name: 'weweChat',
path: '/Applications/wewechat.app',
});
if (settings.startup) {
if (!isOsx) {
mainWindow.webContents.send('show-errors', {
message: 'Currently only supports the OSX.'
});
return;
}
launcher.enable()
.catch(ex => {
console.error(ex);
});
} else {
launcher.disable();
}
}
function createMenu() {
var menu = Menu.buildFromTemplate(mainMenu);
if (isOsx) {
Menu.setApplicationMenu(menu);
} else {
mainWindow.setMenu(null);
}
}
const createMainWindow = () => {
var mainWindowState = windowStateKeeper({
defaultWidth: 745,
defaultHeight: 500,
});
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
minWidth: 745,
minHeight: 450,
transparent: true,
titleBarStyle: 'hiddenInset',
backgroundColor: 'none',
resizable: false,
webPreferences: {
scrollBounce: true
},
frame: !isWin,
icon
});
mainWindow.setSize(350, 460);
mainWindow.loadURL(
`file://${__dirname}/src/index.html`
);
mainWindow.webContents.on('did-finish-load', () => {
try {
mainWindow.show();
mainWindow.focus();
} catch (ex) { }
});
mainWindow.webContents.on('new-window', (event, url) => {
event.preventDefault();
shell.openExternal(url);
});
mainWindow.on('close', e => {
if (forceQuit) {
mainWindow = null;
app.quit();
} else {
e.preventDefault();
mainWindow.hide();
}
});
ipcMain.on('settings-apply', (event, args) => {
settings = args.settings;
mainWindow.setAlwaysOnTop(!!settings.alwaysOnTop);
try {
updateTray();
autostart();
} catch (ex) {
console.error(ex);
}
});
ipcMain.on('show-window', event => {
if (!mainWindow.isVisible()) {
mainWindow.show();
mainWindow.focus();
}
});
ipcMain.on('menu-update', async(event, args) => {
var { cookies, contacts = [], conversations = [] } = args;
var conversationsMenu = mainMenu.find(e => e.label === 'Conversations');
var contactsMenu = mainMenu.find(e => e.label === 'Contacts');
var shouldUpdate = false;
if (!isOsx) {
return;
}
if (conversations.length
&& conversations.map(e => e.name).join() !== conversationsMenu.submenu.map(e => e.label).join()) {
shouldUpdate = true;
conversations = await Promise.all(
conversations.map(async(e, index) => {
let icon = await getIcon(cookies, e.id, e.avatar);
return {
label: e.name,
accelerator: `Cmd+${index}`,
icon,
click() {
mainWindow.show();
mainWindow.webContents.send('message-chatto', {
id: e.id,
});
}
};
})
);
conversationsMenu.submenu = conversations;
}
if (contacts.length) {
shouldUpdate = true;
contacts = await Promise.all(
contacts.map(async e => {
let icon = await getIcon(cookies, e.id, e.avatar);
return {
label: e.name,
icon,
click() {
mainWindow.show();
mainWindow.webContents.send('show-userinfo', {
id: e.id,
});
}
};
})
);
contactsMenu.submenu = contacts;
}
if (shouldUpdate) {
createMenu();
}
});
ipcMain.on('message-unread', (event, args) => {
var counter = args.counter;
if (settings.showOnTray) {
updateTray(counter);
}
});
ipcMain.on('file-paste', (event) => {
var image = clipboard.readImage();
var args = { hasImage: false };
if (!image.isEmpty()) {
let filename = tmp.tmpNameSync() + '.png';
args = {
hasImage: true,
filename,
raw: image.toPNG(),
};
fs.writeFileSync(filename, image.toPNG());
}
event.returnValue = args;
});
ipcMain.on('file-download', async(event, args) => {
var filename = args.filename;
fs.writeFileSync(filename, args.raw.replace(/^data:image\/png;base64,/, ''), {
encoding: 'base64',
// Overwrite file
flag: 'wx',
});
event.returnValue = filename;
});
ipcMain.on('open-file', async(event, filename) => {
shell.openItem(filename);
});
ipcMain.on('open-folder', async(event, dir) => {
shell.openItem(dir);
});
ipcMain.on('open-map', (event, args) => {
event.preventDefault();
shell.openExternal(args.map);
});
ipcMain.on('open-image', async(event, args) => {
var filename = `${imagesCacheDir}/img_${args.dataset.id}`;
fs.writeFileSync(filename, args.base64.replace(/^data:image\/png;base64,/, ''), 'base64');
shell.openItem(filename);
});
ipcMain.on('is-suspend', (event, args) => {
event.returnValue = isSuspend;
});
ipcMain.once('logined', event => {
mainWindow.setResizable(true);
mainWindow.setSize(mainWindowState.width, mainWindowState.height);
mainWindowState.manage(mainWindow);
});
powerMonitor.on('resume', () => {
isSuspend = false;
mainWindow.webContents.send('os-resume');
});
powerMonitor.on('suspend', () => {
isSuspend = true;
});
if (isOsx) {
app.setAboutPanelOptions({
applicationName: pkg.name,
applicationVersion: pkg.version,
copyright: 'Made with 💖 by trazyn. \n https://github.com/trazyn/weweChat',
credits: `With the invaluable help of: \n web.wechat.com`,
version: pkg.version
});
}
[imagesCacheDir, voicesCacheDir].map(e => {
if (!fs.existsSync(e)) {
fs.mkdirSync(e);
}
});
mainWindow.webContents.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8');
createMenu();
};
app.setName(pkg.name);
app.dock && app.dock.setIcon(icon);
app.on('ready', createMainWindow);
app.on('before-quit', () => {
// Fix issues #14
forceQuit = true;
});
app.on('activate', e => {
if (!mainWindow.isVisible()) {
mainWindow.show();
}
});
autoUpdater.on('update-not-available', e => {
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
title: pkg.name,
message: `${pkg.name} is up to date :)`,
detail: `${pkg.name} ${pkg.version} is currently the newest version available, It looks like you're already rocking the latest version!`
});
console.log('Update not available.');
});
autoUpdater.on('update-available', e => {
downloading = true;
checkForUpdates();
});
autoUpdater.on('error', err => {
dialog.showMessageBox({
type: 'error',
buttons: ['Cancel update'],
title: pkg.name,
message: `Failed to update ${pkg.name} :(`,
detail: `An error occurred in retrieving update information, Please try again later.`,
});
downloading = false;
console.error(err);
});
autoUpdater.on('update-downloaded', info => {
var { releaseNotes, releaseName } = info;
var index = dialog.showMessageBox({
type: 'info',
buttons: ['Restart', 'Later'],
title: pkg.name,
message: `The new version has been downloaded. Please restart the application to apply the updates.`,
detail: `${releaseName}\n\n${releaseNotes}`
});
downloading = false;
if (index === 1) {
return;
}
autoUpdater.quitAndInstall();
setTimeout(() => {
mainWindow = null;
app.quit();
});
});
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/llpku/weweChat.git
git@gitee.com:llpku/weweChat.git
llpku
weweChat
weweChat
master

搜索帮助