-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathmega.js
More file actions
72 lines (63 loc) · 2.48 KB
/
mega.js
File metadata and controls
72 lines (63 loc) · 2.48 KB
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
import * as mega from 'megajs';
// Mega authentication credentials
const auth = {
email: '[email protected]', // Replace with your Mega email
password: 'abc@1234!', // Replace with your Mega password
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
};
// Function to upload a file to Mega and return the URL
export const upload = (data, name) => {
return new Promise((resolve, reject) => {
try {
// Authenticate with Mega storage
const storage = new mega.Storage(auth, () => {
// Upload the data stream (e.g., file stream) to Mega
const uploadStream = storage.upload({ name: name, allowUploadBuffering: true });
// Pipe the data into Mega
data.pipe(uploadStream);
// When the file is successfully uploaded, resolve with the file's URL
storage.on("add", (file) => {
file.link((err, url) => {
if (err) {
reject(err); // Reject if there's an error getting the link
} else {
storage.close(); // Close the storage session once the file is uploaded
resolve(url); // Return the file's link
}
});
});
// Handle errors during file upload process
storage.on("error", (error) => {
reject(error);
});
});
} catch (err) {
reject(err); // Reject if any error occurs during the upload process
}
});
};
// Function to download a file from Mega using a URL
export const download = (url) => {
return new Promise((resolve, reject) => {
try {
// Get file from Mega using the URL
const file = mega.File.fromURL(url);
file.loadAttributes((err) => {
if (err) {
reject(err);
return;
}
// Download the file buffer
file.downloadBuffer((err, buffer) => {
if (err) {
reject(err);
} else {
resolve(buffer); // Return the file buffer
}
});
});
} catch (err) {
reject(err);
}
});
};