-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.js
92 lines (79 loc) · 2.4 KB
/
image.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
const fs = require('fs');
const https = require('https');
const path = require('path');
const { app } = require('electron');
const destinationDir = app.getPath('userData');
const destinationFilePath = path.join(destinationDir, 'background.jpg');
function getBackgroundImage() {
return new Promise((resolve, reject) => {
if (fs.existsSync(destinationFilePath)) {
resolve(destinationFilePath);
} else {
resolve(null); // Background image not found
}
});
}
function changeBackgroundImage(event, image) {
return new Promise((resolve, reject) => {
try {
const sourceStream = fs.createReadStream(image);
const destinationStream = fs.createWriteStream(destinationFilePath);
sourceStream.on('error', (err) => {
reject('Error reading the source file: ' + err.message);
});
destinationStream.on('error', (err) => {
reject('Error writing the destination file: ' + err.message);
});
destinationStream.on('finish', () => {
resolve();
event.reply('image-task-finished', { success: true });
});
sourceStream.pipe(destinationStream);
} catch (error) {
reject('Error: ' + error.message);
}
});
}
function changeBackgroundImageByUrl(event, url) {
return new Promise((resolve, reject) => {
https.get(url, (response) => {
if (response.statusCode === 200) {
const imageFile = fs.createWriteStream(destinationFilePath);
response.pipe(imageFile);
imageFile.on('finish', () => {
imageFile.close();
resolve();
event.reply('image-task-finished', { success: true });
});
imageFile.on('error', (error) => {
reject('Error writing the image file: ' + error.message);
event.reply('download-error', error.message);
});
} else {
reject('HTTP status code: ' + response.statusCode);
event.reply('download-error', 'HTTP status code: ' + response.statusCode);
}
}).on('error', (error) => {
reject('Error downloading image: ' + error.message);
event.reply('download-error', error.message);
});
});
}
function deleteBackgroundImage(event) {
return new Promise((resolve, reject) => {
fs.unlink(destinationFilePath, (error) => {
if (error) {
reject('Error deleting background image: ' + error.message);
} else {
resolve();
event.reply('image-task-finished', { success: true });
}
});
});
}
module.exports = {
getBackgroundImage,
changeBackgroundImage,
changeBackgroundImageByUrl,
deleteBackgroundImage,
};