Jump to content

User:Reinischmax/IABooks.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Reinischmax (talk | contribs) at 01:56, 18 December 2018. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// 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 () {
	if( mw.config.get( "wgNamespaceNumber" ) === 0 ) {
		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', 'darkyellow'),
				$('<button>').text('BWB').attr({'style': css.vendors}).css('background-color', 'darkblue')
			)
			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)
			}).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
		}
		
		// 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
		}
		mw.loader.using( [ 'oojs-ui-core' ], function () {
			getWikipediaBooks(location.href).done(data => {
		    let books = $("a[title^='Special:BookSources']")
		    for (let book of books) {
		      let isbn = getISBNFromCitation(book)
		      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))
		  });
		})
	}
});