forked from AhmedAshrafAZ/cms-downloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
231 lines (207 loc) · 6.77 KB
/
index.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
'use strict';
const puppeteer = require('puppeteer');
const fs = require('fs');
const httpntlm = require('httpntlm');
const { exec } = require('child_process');
require('dotenv').config();
const machine_type = process.platform;
const fileSeparator = () => {
return machine_type === 'win32' ? '\\' : '/';
};
const pupp_options = {
headless: true,
};
const userAuthData = {
username: process.env.GUC_SK_USERNAME,
password: process.env.GUC_SK_PASSWORD,
};
const authenticateUser = () => {
return new Promise((resolve, reject) => {
httpntlm.get(
{
...userAuthData,
url: 'https://cms.guc.edu.eg/apps/student/HomePageStn.aspx',
rejectUnauthorized: false,
},
(err, res) => {
console.log(
res.statusCode === 200
? '[+] You are authorized\n============'
: '[!] You are not authorized. Please review your login credentials.'
);
resolve(res.statusCode === 200);
}
);
});
};
const navigateTo = async (page, target_link) => {
await page.goto(target_link, {
waitUntil: 'networkidle0',
timeout: 500000,
});
};
const getAvailableCourses = async (page) => {
console.log('[-] Fetching Courses');
return await page.evaluate(() => {
const courses_menu = document.querySelectorAll(
'ul[class="vertical-nav-menu metismenu"]'
)[0].childNodes[5].childNodes[3].childNodes;
const courses_links = [];
for (var i = 1; i < courses_menu.length; i += 2) {
if (!courses_menu[i].children[0].href.includes('ViewAllCourseStn'))
courses_links.push(courses_menu[i].children[0].href.trim());
}
return courses_links;
});
};
const getCourseName = async (page) => {
return await page.evaluate(() => {
let name = document
.querySelectorAll(
'span[id="ContentPlaceHolderright_ContentPlaceHoldercontent_LabelCourseName"]'
)[0]
.innerHTML.toString()
.trim();
name = name.substring(0, name.lastIndexOf('(')).trim(); // Remove courseID
name = name.replaceAll('|', '').replaceAll('(', '[').replaceAll(')', ']'); // Remove the '|' then replace () with []
return name.trim();
});
};
const getUnratedContent = async (page) => {
return await page.evaluate(() => {
const content = [];
document
.querySelectorAll(
'input[class="btn btn-danger close1"][style="display: none;"]' // The unrated content flag
)
.forEach((el) => {
content.push({
week: el.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.children[0].children[0].innerHTML.trim(),
name: el.parentElement.parentElement.children[0].children[0].download,
link: el.parentElement.parentElement.children[0].children[0].href,
});
});
return content;
});
};
const resolveContentName = async (page) => {
await page.evaluate(() => {
document.querySelectorAll('a[download]').forEach((el) => {
const fileName =
el.parentElement.parentElement.parentElement.children[0].children[0]
.innerHTML;
const fileExtension = el.href.split('.')[
document.querySelectorAll('a[download]')[0].href.split('.').length - 1
];
const fullName = `${fileName}.${fileExtension}`;
el.download = fullName;
});
});
};
const rateContent = async (page, content_name) => {
return await page.evaluate((content_name) => {
document
.querySelectorAll(`a[download="${content_name}"]`)[0]
.parentElement.parentElement.children[1].children[1].children[0].click();
}, content_name);
};
const downloadContent = async (page, course_name, content) => {
const download = (url, file_path, file_name) => {
if (!fs.existsSync(file_path)) fs.mkdirSync(file_path, { recursive: true });
console.log(`[-] Downloading file (${file_name})...`);
return new Promise((resolve, reject) => {
httpntlm.get(
{
...userAuthData,
url: url,
rejectUnauthorized: false,
binary: true,
},
(err, res) => {
// Request failed
if (err) {
console.log(
'There is an error in the request, please report it. Error is: ',
err.message
);
reject('Request Error');
}
// Request success, write to the file
fs.writeFile(
`${file_path}${fileSeparator()}${file_name}`,
res.body,
(err) => {
if (err) {
console.log(
'There is an error in file writing, please report it. Error is: ',
err.message
);
reject('FileWriting Error');
}
console.log(
`[+] Download completed. "${file_name}" is saved successfully in ${file_path}`
);
console.log('------------');
resolve();
}
);
}
);
});
};
const dir_name = `.${fileSeparator()}cms_downloads${fileSeparator()}${course_name}`;
for (let i = 0; i < content.length; i++) {
await download(
content[i].link,
`${dir_name}${fileSeparator()}${content[i].week.replace(':', '')}`,
content[i].name
);
// Rate the downloaded content
await rateContent(page, content[i].name);
}
};
// Start the script
console.log('[+] Everything is up-to-date');
console.log('============');
(async () => {
const browser = await puppeteer.launch(pupp_options);
const page = await browser.newPage();
// 00- Authenticate User
console.log('[-] Authenticating...');
let user_auth = await authenticateUser();
if (!user_auth) {
await browser.close();
return;
}
// 0- Go to CMS home page
await page.authenticate(userAuthData);
await navigateTo(
page,
'https://cms.guc.edu.eg/apps/student/HomePageStn.aspx'
);
// 1- Get Available Courses
const available_courses = await getAvailableCourses(page);
console.log('[+] Fetching Courses Done');
console.log('============');
for (let i = 0; i < available_courses.length; i++) {
// 2- Navigate to the course page
await navigateTo(page, available_courses[i]);
const course_name = await getCourseName(page);
// 3- Rename the download name
await resolveContentName(page);
// 4- Get unrated courses
const unrated_content = await getUnratedContent(page);
if (unrated_content.length === 0) {
console.log(
`There are no new (unrated) content in this course: ${course_name}`
);
console.log('============');
} else {
console.log(`Found new content in this course: ${course_name}`);
// 5- Start downloading 🔥. Then rate the downloaded.
await downloadContent(page, course_name, unrated_content);
}
}
// 6- End the session
await browser.close();
})();