User:Reinischmax/IABooks.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | Documentation for this user script can be added at User:Reinischmax/IABooks. |
// This script adds buttons next to isbns on wikipedia pages that will redirect
// the user to a readable digital copy of the referenced book.
// <nowiki>
( function () {
function addBookIcon(id, metadata){
let toolTip = createBookWindow(metadata, id)
return createArchiveAnchor(id, toolTip)
}
function addDonateIcon(isbn){
let toolTip = createDonateWindow(isbn)
return createArchiveAnchor(false, toolTip)
}
function createBookWindow (metadata, id) {
let css = {
'cover_img': ' align-self: center; border: 1px solid black; border-radius: 3px; display:block; height:168px; margin:10px auto; width: 120px;',
'text_elements' : ' max-width: 100%; margin: auto; padding: 5px;',
'popup_box': 'text-align: center;',
'bottom_details': ' background-color: #eee; max-width: 100%; padding: 5px; margin: auto;'
}
let text_elements = $('<div>').attr({'style':css.text_elements }).append(
$('<p>').append($('<strong>').text(metadata.title)),
$('<p>').text(metadata.author)
)
let details = $('<div>').attr({'style': css.bottom_details }).append(
metadata.image ? $('<img>').attr({'src': metadata.image, 'style':css.cover_img }) : null,
$('<p>').text('Click To Read Now')
)
return $('<a>').append(text_elements, details).attr({'href': 'https://archive.org/details/' + id, 'style': css.popup_box})[0].outerHTML
}
function createDonateWindow(isbn){
let css = {
'text_elements' : 'color:black;max-width: 100%; margin: auto; padding: 5px;',
'popup_box': 'text-align: center;',
'bottom_details': ' background-color: #eee; color: black; max-width: 100%; padding: 5px; margin: auto;',
'vendors' : 'padding: 5px; margin: 5px; border: none; border-radius:3px; box-shadow: 2px 2px 1px darkgrey;'
}
let text_elements = $('<div>').attr({'style':css.text_elements }).append(
$('<p>').append($('<strong>').text("We don't have this book yet.")),
$('<p>').text("But you can help us get it.")
)
let vendors = $('<div>').append(
$('<button>').text('Amazon').attr({'style': css.vendors}).css('background-color', 'yellow'),
$('<button>').text('BWB').attr({'style': css.vendors}).css({'background-color': 'darkblue', 'color': 'white'})
)
let details = $('<div>').attr({'style': css.bottom_details }).append(
vendors,
$('<p>').text('Send your donation to:'),
$('<p>').text('Internet Archive'),
$('<p>').text('300 Funston Avenue'),
$('<p>').text('San Francisco, CA 94118')
)
getBookPrice(isbn).done(data =>{
// console.log(data.betterworldbooks.price)
return null
}).fail( function( xhr, status ) {
console.log(getErrorMessage(xhr))
});
return $('<div>').append(text_elements, details).attr({'style': css.popup_box})[0].outerHTML
}
function createArchiveAnchor (id, tt) {
if(id){
var popupButton = new OO.ui.PopupButtonWidget( {
label: '📖 Read Now',
target: '_blank',
framed: false,
classes: ['btn-archive-book'],
popup: {
$content: $(tt),
padded: false,
align: 'forwards',
classes: 'popup-archive',
width:180
}
} );
}else{
var popupButton = new OO.ui.PopupButtonWidget( {
label: '📚 Donate',
target: '_blank',
framed: false,
classes: ['btn-archive-donate'],
popup: {
$content: $(tt),
padded: false,
align: 'forwards',
classes: 'popup-archive',
width:180
}
} );
}
return popupButton
}
function getIdentifier (book) {
// identifier can be found as metadata.identifier or ocaid
if (book) {
var id = ''
if (book.metadata) {
id = book.metadata.identifier
} else {
id = book.ocaid
}
if (id) {
return id
}
}
return null
}
function getISBNFromCitation (citation) {
// Takes in HTMLElement and returns isbn number or null if isbn not found
let rawISBN = citation.text
let isbn = rawISBN.replace(/-/g, '')
return isbn
}
function getPageFromCitation(book){
let raw = book.parentElement.innerText
let re = /p{1,2}\.\s\d+-?\d*/g
return re.exec(raw)
}
// Get all books on wikipedia page through
// https://archive.org/services/context/books?url=...
function getWikipediaBooks (url) {
return $.ajax({
dataType: "json",
crossDomain: true,
url: 'https://archive.org/services/context/books?url=' + url,
beforeSend: function(jqXHR, settings) {
jqXHR.url = settings.url;
},
timeout: 10000
})
}
function getBookPrice(isbn){
return $.ajax({
dataType: "json",
crossDomain: true,
url: 'https://openlibrary.org/prices/isbn/'+isbn,
beforeSend: function(jqXHR, settings) {
jqXHR.url = settings.url;
},
timeout: 50000
})
}
function getMetadata(book){
if (book) {
if(book.metadata){
return {
"title" : book.metadata.title,
"author" : book.metadata.creator,
"image" : "https://archive.org/services/img/" + book.metadata.identifier,
"link" : book.metadata["identifier-access"],
"button_text": "Read Now",
"button_class": "btn btn-success resize_fit_center",
"readable" : true
}
}else{
return {
"title" : book.title,
"author" : book.authors_metadata ? book.authors_metadata.personal_name : "",
"image" : book.covers ? "https://covers.openlibrary.org/w/id/"+ book.covers[0]+"-M.jpg" : undefined,
"link" : "https://archive.org/donate/",
"button_text": "Donate",
"button_class": "btn btn-warning resize_fit_center",
"readable" : false
}
}
}
return false;
}
/**
* Customizes error handling
* @param status {string}
* @return {string}
*/
function getErrorMessage(req){
return "The requested service " + req.url + " failed: " + req.status + ", " + req.statusText
}
if( mw.config.get( "wgNamespaceNumber" ) === 0 ) {
$.when( mw.loader.using( [ 'oojs-ui-core' ], $.ready ).done( function () {
getWikipediaBooks(location.href).done(data => {
let books = $("a[title^='Special:BookSources']")
for (let book of books) {
let isbn = getISBNFromCitation(book)
let pageNumber = getPageFromCitation(book)
console.log(pageNumber)
let id = getIdentifier(data[isbn])
let metadata = getMetadata(data[isbn])
let icon
if (id) {
icon = addBookIcon(id, metadata)
}else{
icon = addDonateIcon(isbn)
}
book.parentElement.append(icon.$element[0])
}
$('.btn-archive-book').css({
'background-color': 'lightblue',
'border-radius': '3px',
'box-shadow': '2px 2px 1px darkgrey',
'color': 'white',
'margin': '0 4px 1px',
'padding': '0 2px 0'
})
$('.btn-archive-donate').css({
'background-color': 'lightgreen',
'border-radius': '3px',
'box-shadow': '2px 2px 1px darkgrey',
'color' : 'white',
'margin': '0 4px 1px',
'padding': '0 2px 0'
})
$('.popup-archive').css({'position': 'absolute'})
}).fail( function( xhr, status ) {
console.log(getErrorMessage(xhr))
});
});
}
}() );