-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontent.js
217 lines (187 loc) · 9.02 KB
/
content.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
// UMD Schedule of Classes
const contentContainerClass = ".soc-content-container"
// PLaceholder for professor that hasn't been assigned
const instructorHidderClasses = '.hidden.section-deliveryFilter' // Element that stops instructor from being displayed
// Container holding the instructor name
// Span holding instructor name
// PlanetTerp
const baseApiCallPlanetTerp = 'https://planetterp.com/api/v1/professor?name=';
const ratingPlanetTerpClass = ".rating-planet-terp"; // Class for planet terp rating objects
const logoPlanetTerpPath = '/images/PlanetTerpLogo.png'; // Goes next to rating
const planetTerpBlue = "#0099FC"; // Color of planetTerp logo
// RateMyProfessor
const baseApiCallRateMyProfessor = 'https://www.ratemyprofessors.com/search/teachers?sid=U2Nob29sLTEyNzA=&query=';
const ratingRateMyProfessorClass = ".rating-rate-my-professor"; // Class for RMP rating objects
const logoRateMyProfessorPath = 'images/RateMyProfessorLogo.png'; // Logo next to rating
const rateMyProfessorBlue = '#0021FF'; //Color of RMP logo
// CORS proxy
const proxy = "https://nextjs-cors-anywhere.vercel.app/api?endpoint=";
const profInfo = {}; // Store professor ratings, links, slug, etc
/**
* Returns the names of all the professors on the page
*/
function getProfessors() {
const names = new Set();
const profs = document.querySelectorAll(".section-instructor");
for (const prof of profs) {
// Support for n profs seperated by a comma
prof.childNodes[0].textContent.split(',').filter((name) => name !== 'Instructor: TBA').forEach((name) => {
names.add(name.trim());
});
}
return names;
}
/**
* Fetch average rating for a given professor from Planet Terps API
* and add to professorRatings
*
* @param {*} name Professor's name (first last)
*/
async function getInfoPT(name) {
// Encode the name for the api call using URLParameterEncoding
/* Fetch professor ratings from Planet Terp */
await fetch(baseApiCallPlanetTerp + encodeURIComponent(name)).then(r => r.json()).then((result) => {
if ('error' in result && result['error'] === 'professor not found') {
throw new Error('Professor not found');
}
profInfo[name]['pt'] = {};
profInfo[name]['pt']['rating'] = result['average_rating'];
profInfo[name]['pt']['url'] = `https://planetterp.com/professor/${result['slug']}`;
}).catch((error) => {
console.log('Could not get data about ' + name + ' from Planet Terp. ', error);
/* Couldn't find professor */
profInfo[name]['pt'] = null;
});
}
async function getInfoRMP(name) {
let apiCall = baseApiCallRateMyProfessor + encodeURIComponent(name);
//set the request's mode to 'no-cors
await fetch(proxy + apiCall).then(r => r.text()).then((result) => {
// Find the index where "window.__RELAY_STORE__ = " appears, then get the json string between the next matching { and }
const start = result.indexOf("window.__RELAY_STORE__ = ") + 25;
const end = result.indexOf("};", start) + 1;
const json = result.substring(start, end);
const data = JSON.parse(json);
// the data is store with random IDs as keys and objects as values. Iterate through object values until the value has a key firstname and lastname
let possibleMatches = Object.values(data).filter((value) => 'firstName' in value && 'lastName' in value);
profInfo[name]['rmp'] = {};
if (possibleMatches.length === 0) {
throw new Error('Professor not found');
}
profInfo[name]['rmp']['rating'] = possibleMatches[0]['avgRating'];
profInfo[name]['rmp']['url'] = `https://www.ratemyprofessors.com/ShowRatings.jsp?tid=${possibleMatches[0]['legacyId']}`;
}).catch((error) => {
console.log('Could not get data about ' + name + ' from Rate My Professor. ', error);
profInfo[name]['rmp'] = null;
});
}
function displayRatingPT(name) {
const sectionInfos = [...document.querySelectorAll(".section-instructor")].filter(e => e.textContent === name);
for (const section of sectionInfos) {
// remove all elements with 'rating-loading' class rating-loading, remove it.
if(section.nextSibling.className === 'rating-loading') {
section.nextSibling.remove();
console.log('removed loading');
}
// Remove ratings if already added
section.querySelectorAll(ratingPlanetTerpClass).forEach(e => e.remove());
if (profInfo[name]["pt"] != null) {
/* Place an image next to rating with planet terp logo
also with link to professor reviews on planet terp */
const imageLink = document.createElement('a');
imageLink.href = profInfo[name]["pt"]['url'];
const image = document.createElement('img');
image.src = chrome.runtime.getURL(logoPlanetTerpPath);
image.style.marginLeft = "5px";
image.style.marginRight = "3px";
imageLink.appendChild(image);
section.appendChild(imageLink);
/* Create display element with link to professor reviews */
const node = document.createElement("a");
const rating = profInfo[name]["pt"]['rating'] ? profInfo[name]["pt"]['rating'].toFixed(2) : 'N/A';
const textNode = document.createTextNode(rating);
node.appendChild(textNode);
node.href = profInfo[name]["pt"]['url'];
node.target = "_blank";
node.className = 'rating-planet-terp';
node.style.color = planetTerpBlue;
section.appendChild(node);
}
}
}
function displayRatingRMP(name) {
const sectionInfos = [...document.querySelectorAll(".section-instructor")].filter(e => e.innerText === name);
for (const section of sectionInfos) {
/* Verify rating not already added */
if (section.querySelectorAll(ratingRateMyProfessorClass).length === 0) {
// remove all elements with 'rating-loading' class rating-loading, remove it.
if(section.nextSibling.className === 'rating-loading') {
section.nextSibling.remove();
console.log('removed loading');
}
if (!(profInfo[name]["rmp"] == null)) {
/* Place an image next to rating with planet terp logo also with link to professor reviews on planet terp */
const imageLink = document.createElement('a');
imageLink.href = profInfo[name]['rmp']['url'];
const image = document.createElement('img');
image.src = chrome.runtime.getURL(logoRateMyProfessorPath);
image.style.marginLeft = "5px";
image.style.marginRight = "3px";
imageLink.appendChild(image);
section.appendChild(imageLink);
/* Create display element with link to professor reviews */
const node = document.createElement("a");
const textNode = document.createTextNode(profInfo[name]["rmp"]['rating'].toFixed(2));
node.appendChild(textNode);
node.href = profInfo[name]["rmp"]['url'];
node.target = "_blank";
node.className = 'rating-rate-my-professor';
node.style.color = rateMyProfessorBlue;
section.appendChild(node);
}
}
}
}
function showLoading(name) {
const sectionInfos = [...document.querySelectorAll(".section-instructor")].filter(e => e.innerText === name);
for (const section of sectionInfos) {
const node = document.createElement("span");
const textNode = document.createTextNode("Ratings Loading...");
node.appendChild(textNode);
node.className = 'rating-loading';
node.style.color = 'grey';
section.parentNode.insertBefore(node, section.nextSibling);
}
}
async function updateRatings() {
/* Get professors visible on page */
const names = getProfessors();
const fetches = [];
for (const name of names) {
if (!(name in profInfo)) {
profInfo[name] = {};
showLoading(name);
fetches.push(getInfoPT(name).then(() => displayRatingPT(name)));
fetches.push(getInfoRMP(name).then(() => displayRatingRMP(name)));
} else {
displayRatingPT(name);
displayRatingRMP(name);
}
}
await Promise.all(fetches);
// console.log('done!')
}
/* Display ratings for all professors
that are initially visiable */
$(document).ready(updateRatings)
/* Observe if professors become visible */
const observer = new MutationObserver(mutations => {
mutations.forEach(function (mutation) {
if (mutation.attributeName !== 'style') return;
if (mutation.target.className !== "hidden section-deliveryFilter") return;
updateRatings();
});
});
/* Get all elements that control whether professors are visible */
/* Monitor entire subtree for attribute changes */
observer.observe(document.querySelector(contentContainerClass), {subtree: true, attributes: true});