-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·204 lines (173 loc) · 5.66 KB
/
app.js
File metadata and controls
executable file
·204 lines (173 loc) · 5.66 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
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
const http = require("http");
const fs = require("fs");
const cheerio = require("cheerio");
// Define the base URL to iterate over
const baseUrl = "ezshare.card";
const rootUrlPath = "dir?dir=A:";
// Define the output directory for downloaded files
const outputDir = "downloaded_files";
// Set a delay
const delay = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
const convertTimeStringToDate = (timeString) => {
const [datePart, timePart] = timeString.split(" ");
const [year, month, day] = datePart.split("-");
const [hours, minutes, seconds] = timePart.split(":");
// JavaScript Date constructor expects month to be zero-based, so subtract 1 from the month value
return new Date(year, month - 1, day, hours, minutes, seconds);
};
// Download Files
const prepareDownloadFile = async ({ url: href, fileName }) => {
console.log("Downloading:", href);
const filePath = `${outputDir}/${fileName}`;
try {
await downloadFile(href, filePath);
console.log(`Downloaded: ${href}`);
} catch (error) {
console.error(`Error downloading: ${href}`, error);
}
};
// Create the output directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
// makes an http request to get the file size of the targeted file
const getFileSize = async (url) => {
return new Promise((resolve, reject) => {
http
.request(url, { method: "HEAD" }, (response) => {
const contentLength = response.headers["content-length"]; // gets the file size
if (!contentLength) {
reject("Content-Length header not found");
}
resolve(parseInt(contentLength, 10));
})
.on("error", (err) => {
reject(err);
})
.end();
});
};
// this function downloads files, it takes in the url and destination as a parameter
const downloadFile = (url, dest) => {
return new Promise(async (resolve, reject) => {
try {
const serverFileSize = await getFileSize(url);
console.log("Server file size:", serverFileSize); // gets the file size from the http request
if (fs.existsSync(dest)) {
const localFileSize = fs.statSync(dest).size; // gets local file size
console.log("Local file size:", localFileSize);
if (localFileSize === serverFileSize || serverFileSize === 147) {
// Local file already exists with the same size or equal to 147, skip the download
console.log(
"A local file with the same name exists that is the same size or higher, skipping download."
);
resolve();
return;
}
}
const file = fs.createWriteStream(dest);
http
.get(url, (response) => {
response.pipe(file);
file.on("finish", () => {
file.close();
console.log("Download completed.");
resolve();
});
})
.on("error", (err) => {
fs.unlink(dest, (err) => {
if (err) {
console.log(err);
} else {
console.log("File Removed.");
}
});
reject(err.message);
});
} catch (error) {
reject(error);
}
});
};
// Get HTML information from ezShare using an HTTP request
const getHtmlInfo = async (url, path) => {
return new Promise((resolve, reject) => {
const options = {
hostname: url,
port: 80,
path: path,
method: "GET",
};
const req = http.request(options, (res) => {
let resData = "";
res.on("data", (chunk) => {
resData += chunk;
});
res.on("end", () => {
resolve(resData);
});
});
req.on("error", (error) => {
reject(error);
});
req.end();
});
};
// This function receives HTML and returns a list of directories and files
const getDirListFromHtml = (html) => {
const retrieveHtml = cheerio.load(html);
const preElement = retrieveHtml("pre");
const preTextArr = preElement.first().text().split("\n");
const entries = { dirs: [], files: [] };
preElement.find("a").each((index, element) => {
const href = retrieveHtml(element).attr("href");
const name = retrieveHtml(element).text().trim();
const isDirectory = !href.includes("http");
if (isDirectory) {
//this filters out any . and .. ensuring that it will not recursive go into the previous folder
if (name !== "." && name !== "..") {
entries.dirs.push({ url: href, fileName: name });
}
} else {
// this filters out any file formats not needed
if (!name.endsWith(".hprj") && !name.endsWith(".cfg")) {
entries.files.push({ url: href, fileName: name });
}
}
});
return entries;
};
// Recursively fetches the file structure from directories and subdirectories
const getFileStructure = async (dir, files) => {
const listOfFileAndFolders = await downloadDirPathParseOutDirAndFileList(dir);
if (listOfFileAndFolders.dirs.length === 0) {
files.push(...listOfFileAndFolders.files);
} else {
for (const folder of listOfFileAndFolders.dirs) {
await getFileStructure(folder.url, files);
}
files.push(...listOfFileAndFolders.files);
}
};
const downloadDirPathParseOutDirAndFileList = async (path) => {
try {
const html = await getHtmlInfo(baseUrl, path);
const dirList = getDirListFromHtml(html);
return dirList;
} catch (error) {
console.error("Error", error);
throw error;
}
};
const getAllFiles = async () => {
const allFiles = [];
await getFileStructure(rootUrlPath, allFiles);
for (const file of allFiles) {
await delay(1000); // one and a half seconds delay to not overload the server
await prepareDownloadFile(file);
}
};
getAllFiles();