Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Merge from gist: cross-browser compatibility, fallback on nophoto url…
…, handle U-prefixed matric numbers
  • Loading branch information
beng-hee-eu committed Apr 24, 2014
commit 6503331387bfcbfec3a8e003ac41ec26a0398bd9
75 changes: 44 additions & 31 deletions IVLE photos/classmate-photos.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,48 @@

// Credits: Camillus Cai for the full matric number function

var normalize = function (id) {
var matches = id.toUpperCase().match(/^A\d{7}|U\d{6,7}/);
if (matches) {
var match = matches[0];
if (match[0] === 'U' && match.length === 8) {
match = match.slice(0, 3) + match.slice(4);
}
var weights = {
U: [0, 1, 3, 1, 2, 7],
A: [1, 1, 1, 1, 1, 1]
}[match[0]];
for (var i = 0, sum = 0, digits = match.slice(-6); i < 6; i++) {
sum += weights[i] * digits[i];
}
return match + 'YXWURNMLJHEAB'[sum % 13];
}
};

var nopics = document.evaluate('//img[@src="/images/nophoto.jpg" and @id]', document, null, 6, null);
for (var i = 0; i < nopics.snapshotLength; i++) {
var fullMatric = normalize(nopics.snapshotItem(i).id);
if (fullMatric) {
var img = nopics.snapshotItem(i);
img.onerror = function () {
var next = {'U':'P', 'P':'X', 'X':null}[this.src.slice(-1)];
if (next) {
this.src = this.src.slice(0, -1) + next;
}
(function () {
var calculateNUSMatricNumber = function (id) {
var matches = id.toUpperCase().match(/^A\d{7}|U\d{6,7}/);
if (matches) {
var match = matches[0];

// Discard 3rd digit from U-prefixed NUSNET ID
if (match[0] === 'U' && match.length === 8) {
match = match.slice(0, 3) + match.slice(4);
}

var weights = {
U: [0, 1, 3, 1, 2, 7],
A: [1, 1, 1, 1, 1, 1]
}[match[0]];

for (var i = 0, sum = 0, digits = match.slice(-6); i < 6; i++) {
sum += weights[i] * digits[i];
}

return match + 'YXWURNMLJHEAB'[sum % 13];
}
};
img.src = 'https://mysoc.nus.edu.sg/mysoc/images/stdphoto.php?matric=' + fullMatric + '&type=U';
}
}

var PHOTO_URL = 'https://mysoc.nus.edu.sg/mysoc/images/stdphoto.php?matric=';
var NOPHOTO_URL = 'https://ivle.nus.edu.sg/images/nophoto.jpg';
var TYPES = ['U', 'P', 'X'];

var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
if (img.id && img.src === NOPHOTO_URL) {
var matricNumber = calculateNUSMatricNumber(img.id);
if (matricNumber) {
(function () {
var typeIndex = 0;
img.onerror = function () {
this.src = typeIndex < TYPES.length ? PHOTO_URL + matricNumber + '&type=' + TYPES[typeIndex++] : NOPHOTO_URL;
}
img.onerror.call(img);
})();
}
}
}
})();
45 changes: 0 additions & 45 deletions matric.js

This file was deleted.