-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
298 lines (264 loc) · 9.88 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
const {app, BrowserWindow, ipcMain, shell} = require("electron");
const path = require("path");
const os = require('os');
const net = require('net')
const express = require('express')
const http = require('http')
const https = require('https')
const fs = require('fs')
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const config = require("./config/atlasChart.js");
const apiRequests = require('./apiserver/apimain');
const {main} = require("@popperjs/core");
const portfinder = require('portfinder');
portfinder.basePort = 3000;
let currentPort = 3000;
require('electron-reload')([path.join(__dirname, '/Bootstrap5'), path.join(__dirname, '/Modernize')]);
const Store = require('electron-store');
Store.initRenderer()
let navbarLanguage = "en"
if (!(new Store).get('language')){
(new Store).set("language","en")
}
// The MongoDB URI should look as following (SRV for mongoAtlas)
// mongodb://myDatabaseUser:D1fficultP%[email protected]:27017/?authSource=admin&replicaSet=myRepl
// mongodb+srv://myDatabaseUser:D1fficultP%[email protected]/?authSource=admin&replicaSet=myRepl
if (!(new Store).get('mongoURI')){
(new Store).set("mongoURI","mongodb://127.0.0.1:27017")
}
if(!(new Store).get("mongoDB")){
(new Store).set("mongoDB","prod")
}
const i18next = require('i18next');
const Backend = require('i18next-electron-fs-backend');
const {MongoClient, ServerApiVersion} = require("mongodb");
const i18nextOptions = {
debug: true,
lng: 'en', // 默认语言
fallbackLng: 'en',
ns: ['translations'],
defaultNS: 'translations',
backend: {
loadPath: path.join(__dirname, '/i18nLocales/{{lng}}/{{ns}}.json'),
addPath: path.join(__dirname, '/i18nLocales/{{lng}}/{{ns}}.missing.json')
}
};
ipcMain.on('change-language', (event, language) => {
i18next.changeLanguage(language);
mainWindow.webContents.send('set-language', language);
});
ipcMain.on('get-user-data-path', (event) => {
event.returnValue = app.getPath('userData')
})
ipcMain.on('open-external', (event, url) => {
shell.openExternal(url);
});
ipcMain.on('print-pdf', (event, pdfFilename) => {
// shell.openExternal(path.join('file://', path.join(__dirname, pdfFilename)));
let win = new BrowserWindow({ show: true });
win.loadURL(path.join('file://', path.join(__dirname, pdfFilename)))
});
let mainWindow;
function createWindow(portNumber) {
mainWindow = new BrowserWindow({
width: 1280,
height: 800,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true,
// Additional security options
contextIsolation: false, // 需要使用IPC Renderer,保持为False
enableRemoteModule: true, // Consider setting this to true in production
},
});
try {
if (!(new Store).get('mongoURI') || !(new Store).get("mongoDB")){
} else if (pingMongoDB((new Store).get('mongoURI'),(new Store).get("mongoDB"))){
//尝试链接数据库,ping,如果无响应则跳转设置页面
// mainWindow.loadFile('Bootstrap5/pages/index.html')
mainWindow.loadFile('Modernize/pages/home/index.html')
} else {
mainWindow.loadFile("Bootstrap5/settings/settings.html")
}
} catch (err) {
mainWindow.loadFile('index.html')
console.error(err)
}
mainWindow.on("closed", function () {
mainWindow = null;
});
const networkInterfaces = os.networkInterfaces();
let address;
for (let name in networkInterfaces) {
const iface = networkInterfaces[name];
for (let i = 0; i < iface.length; i++) {
const alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
address = alias.address;
break;
}
}
if (address) break;
}
mainWindow.webContents.on('did-finish-load', () => {
const addressSet = getIPAddress() ? getIPAddress() : [];
mainWindow.webContents.send('server-info', {address, portNumber, addressSet});
});
mainWindow.on('resize', () => {
let [width, height] = mainWindow.getSize();
mainWindow.webContents.send('window-resize', {width, height});
});
mainWindow.webContents.on('did-fail-load',(ev,errorCode, errorDescription, validatedURL,isMainFrame) =>{
console.log("Failed on URL"+validatedURL)
if (isMainFrame){
// Failed in main Frame, load 404 page
mainWindow.loadFile(path.join(__dirname,'Modernize/pages/errors/400.html'))
}
})
mainWindow.webContents.on('ERR_FILE',(ev,errorCode, errorDescription, validatedURL,isMainFrame) =>{
console.log("Failed on URL"+validatedURL)
if (isMainFrame){
// Failed in main Frame, load 404 page
// mainWindow.loadFile(path.join(__dirname,'404.html'))
}
})
ipcMain.on('print', (event) => {
mainWindow.webContents.print({
pageSize: "A4",
},(success, failureReason)=>{
if (failureReason){
console.error(failureReason);
}
});
});
}
async function pingMongoDB(dburi, dbname){
// 新增内容:ping之后检测是否可以成功连接数据库的所有collection,如果不可则跳转到Settings
let client = new MongoClient(dburi, {
serverApi: {
version: ServerApiVersion.v1, strict: true, deprecationErrors: true, useNewUrlParser: true, useUnifiedTopology: true
}
});
let results = false
try {
await client.connect();
let targetDB = client.db(dbname);
let response = await targetDB.command({ping: 1})
let collectionList = ['pollinglog','pollingsession','preloadlog','products','settings']
let collectionResults = true
collectionList.forEach(eachCollection=>{
response = targetDB.listCollections({name:eachCollection})
if (response.length === 0){
collectionResults = false
}
})
results = collectionResults;
} catch (e) {
console.error(e)
results = false
} finally {
await client.close();
}
return results
}
function getIPAddress() {
const networkInterfaces = os.networkInterfaces();
let addressSet = [];
for (let interface in networkInterfaces) {
networkInterfaces[interface].forEach(details => {
// Skip internal (i.e. 127.0.0.1) and non-ipv4 addresses
if (!details.internal && details.family === 'IPv4' && details.address !== '127.0.0.1') {
addressSet.push(details.address);
}
});
}
return addressSet
}
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
});
app.setAsDefaultProtocolClient("warehouseelec");
const expressApp = express()
expressApp.use(bodyParser.urlencoded({ extended: false }));
expressApp.use(bodyParser.json());
expressApp.use(cors())
expressApp.use("/api", apiRequests);
expressApp.use("/stocks",express.static(path.join(__dirname,"stocks")))
expressApp.use("/",express.static(path.join(__dirname, 'public')));
const credentials = {key: fs.readFileSync(path.join(__dirname, 'config/key.pem'), 'utf8'),
cert:fs.readFileSync(path.join(__dirname, 'config/cert.pem'), 'utf8')}
// 20240901新,添加Embedded SDK,允许访问charts
expressApp.post("/jwt",(req, res)=>{
// Future adding user auth
const payload = {userId:"user"}
const tokenSecretKey = config.atlasChartProfiles[0].atlas_jwt
const jwt_token = jwt.sign(payload, tokenSecretKey, {
algorithm:"HS256",
expiresIn: '1h'
})
res.json({token:jwt_token})
})
function authJWT(req, res, next) {
const token = req.headers.authorization
if (token) {
jwt.verify(token, config.atlasChartProfiles[0].atlas_jwt, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
}
MongoClient.connect(config.atlasChartProfiles[0].atlas_url, { useNewUrlParser: true, useUnifiedTopology: true })
.then(client => {
const db = client.db();
const dashboardCollection = db.collection('dashboards');
app.get('/dashboard', authenticateJWT, (req, res) => {
dashboardCollection.findOne({ _id: config.atlasChartProfiles[0].atlas_dashboardId })
.then(dashboard => {
if (dashboard) {
res.json(dashboard);
} else {
res.status(404).send('Dashboard not found');
}
})
.catch(error => res.status(500).send('Error fetching dashboard'));
});
})
.catch(error => console.error('Failed to connect to the database:', error));
// 20231020新增,允许用户多开,通过推演端口号
function checkPort(port, callback) {
const server = net.createServer();
server.listen(port, () => {
server.once('close', () => {
callback(true);
});
server.close();
});
server.on('error', () => {
callback(false);
});
}
// Finally
app.whenReady().then(() => {
// 使用portfinder插件查找可用端口,原有方法可能出现undefined
portfinder.getPort((err,port)=>{
if(err){
console.error("Error when get portNo with portfinder:",err)
return
}
expressApp.listen(port, ()=>{
console.log(`HTTP running at http://localhost:${port}`)
createWindow(port)
})
const httpsServer = https.createServer(credentials, expressApp);
httpsServer.listen(port+1, () => {
console.log(`HTTPS running at http://localhost:${port+1}`);
});
})
})