Merge branch 'newui' of git@github.com:openlibrary/bookreader into newui
[bookreader.git] / BookReaderIA / datanode / BookReaderJSIA.php
index 29f910d..016e988 100644 (file)
@@ -18,6 +18,8 @@ This file is part of BookReader.
     along with BookReader.  If not, see <http://www.gnu.org/licenses/>.
 */
 
+header('Content-Type: application/javascript');
+
 $id = $_REQUEST['id'];
 $itemPath = $_REQUEST['itemPath'];
 $subPrefix = $_REQUEST['subPrefix'];
@@ -36,8 +38,6 @@ if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home di
     $server .= ':80/~rkumar';
 } else if (strpos($_SERVER["REQUEST_URI"], "/~testflip") === 0) { // Serving out of home dir
     $server .= ':80/~testflip';
-} else if (strpos($_SERVER["REQUEST_URI"], "/~mccabe") === 0) { // Serving out of home dir
-    $server .= ':80/~mccabe';
 }
 
 if (! $subPrefix) {
@@ -330,6 +330,80 @@ br.getEmbedCode = function() {
     return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
 }
 
+// getOpenLibraryRecord
+br.getOpenLibraryRecord = function(callback) {
+    // Try looking up by ocaid first, then by source_record
+    
+    var jsonURL = 'http://openlibrary.org/query.json?type=/type/edition&*=&ocaid=' + br.bookId;
+    $.ajax({
+        url: jsonURL,
+        success: function(data) {
+            if (data && data.length > 0) {
+                callback(br, data[0]);
+            } else {
+                // try sourceid
+                jsonURL = 'http://openlibrary.org/query.json?type=/type/edition&*=&source_records=ia:' + br.bookId;
+                $.ajax({
+                    url: jsonURL,
+                    success: function(data) {
+                        if (data && data.length > 0) {
+                            callback(br, data[0]);
+                        }
+                    },
+                    dataType: 'jsonp'
+                });
+            }
+        },
+        dataType: 'jsonp'
+    });
+}
+
+// getInfoDiv
+br.getInfoDiv = function() {
+    // $$$ it might make more sense to have a URL on openlibrary.org that returns this info
+
+    var escapedTitle = BookReader.util.escapeHTML(this.bookTitle);
+    var domainRe = /(\w+\.(com|org))/;
+    var domain = domainRe.exec(this.bookUrl)[1];
+    // XXX use different icon for archive.org
+    var html = [
+                '<div class="BRfloatCover">',
+                    '<a href="', this.bookUrl, '"><img src="http://www.archive.org/download/', this.bookId, '/page/cover_t.jpg" alt="', escapedTitle, '" height="140"/></a>',
+                '</div>',
+                '<div class="BRfloatMeta">',
+                    '<div class="BRfloatTitle">',
+                        '<h2><a href="', this.bookUrl, '" class="title">', escapedTitle, '</a></h2>',
+                        // $$$ lookup on OL
+                        // 'by',
+                        // '<a href="Open Library Author Page">Book Author</a>',
+                    '</div>',
+                    '<p>Published ', this.bookPublished,
+                    //, <a href="Open Library Publisher Page">Publisher name</a>',
+                    '</p>',
+                    //'<p>Written in <a href="Open Library Language page">Language</a></p>',
+                    '<h3>Other Formats</h3>',
+                    '<ul class="links">',
+                        '<li><a href="http://www.archive.org/download/', this.bookId, '/', this.subPrefix, '.pdf">PDF</a><span>|</span></li>',
+                        '<li><a href="http://www.archive.org/download/', this.bookId, '/', this.subPrefix, '_djvu.txt">Plain Text</a><span>|</span></li>',
+                        '<li><a href="http://www.archive.org/download/', this.bookId, '/', this.subPrefix, '_daisy.zip">DAISY</a><span>|</span></li>',
+                        '<li><a href="http://www.archive.org/download/', this.bookId, '/', this.subPrefix, '.epub">ePub</a><span>|</span></li>',
+                        '<li><a href="https://www.amazon.com/gp/digital/fiona/web-to-kindle?clientid=IA&itemid=', this.bookId, '&docid=', this.subPrefix, '">Send to Kindle</a><span>|</span></li>',
+                        '<li><a href="', this.bookUrl, '">More...</a></li>',
+                    '</ul>',
+                    '<p class="moreInfo"><span></span>More information on <a href="'+ this.bookUrl + '">' + domain + '</a>.</p>',
+                '</div>',
+            '</div>',
+            '<div class="BRfloatFoot">',
+                // XXX add link to bug tracker
+                '<a href="http://openlibrary.org/contact" class="problem">Report a problem</a>',
+                '<span>|</span>',
+                '<a href="http://openlibrary.org/dev/docs/bookreader">About the Bookreader</a>',
+            '</div>'
+    ];
+    
+    return html.join('\n');
+}
+
 br.pageW =  [
             <?
             $i=0;
@@ -404,10 +478,23 @@ br.archiveFormat = '<?echo $archiveFormat;?>';
 
 # Load some values from meta.xml
 if ('' != $metaData->{'page-progression'}) {
-  echo "br.pageProgression = '" . $metaData->{"page-progression"} . "';";
+  echo "br.pageProgression = '" . $metaData->{"page-progression"} . "';\n";
 } else {
   // Assume page progression is Left To Right
-  echo "br.pageProgression = 'lr';";
+  echo "br.pageProgression = 'lr';\n";
+}
+
+$useOLAuth = false;
+foreach ($metaData->xpath('//collection') as $collection) {
+    if('browserlending' == $collection) {
+        $useOLAuth = true;
+    }
+}
+
+if ($useOLAuth) {
+    echo "br.olAuth = true;\n";
+} else {
+    echo "br.olAuth = false;\n";
 }
 
 # Special cases
@@ -445,9 +532,100 @@ if (typeof(brConfig) != 'undefined') {
     }
 } // brConfig
 
-br.cleanupMetadata();
-br.init();
 
+function OLAuth() {
+    this.authUrl = 'http://openlibrary.org/ia_auth/' + br.bookId;
+    this.olConnect = false;
+    return this;
+}
+
+OLAuth.prototype.init = function() {
+    var htmlStr =  '<p style="text-align:center;"><b>Authenticating in-browser loan with openlibrary.org!</b></p>';
+    htmlStr    +=  '<p>Please wait...</p>';
+
+    this.showPopup("#ddd", "#000", htmlStr);
+    $.ajax({url:this.authUrl, dataType:'jsonp', jsonpCallback:'olAuth.initCallback'});
+}
+
+OLAuth.prototype.showPopup = function(bgColor, textColor, msg) {
+    this.popup = document.createElement("div");
+    $(this.popup).css({
+        position: 'absolute',
+        top:      '20px',
+        left:     ($('#BookReader').attr('clientWidth')-400)/2 + 'px',
+        width:    '400px',
+        padding:  "20px",
+        border:   "3px double #999999",
+        zIndex:   3,
+        backgroundColor: bgColor,
+        color: textColor
+    }).appendTo('#BookReader');
+
+    this.popup.innerHTML = msg;
+
+}
+
+OLAuth.prototype.initCallback = function(obj) {
+    if (false == obj.success) {
+        $(this.popup).css({
+            backgroundColor: "#f00",
+            color: "#fff"
+        });
+
+        this.popup.innerHTML = obj.msg;
+        return;
+    }
+    
+    //user is authenticated
+    this.setCookie(obj.token);
+    this.olConnect = true;
+    this.startPolling();    
+    br.init();
+}
+
+OLAuth.prototype.callback = function(obj) {
+    if (false == obj.success) {
+        this.showPopup("#f00", "#fff", obj.msg);
+        clearInterval(this.poller);
+        this.ttsPoller = null;
+    } else {
+        this.olConnect = true;
+        this.setCookie(obj.token);
+    }
+}
+
+OLAuth.prototype.setCookie = function(value) {
+    var date = new Date();
+    date.setTime(date.getTime()+(24*60*60*1000));  //one day expiry
+    var expiry = date.toGMTString();
+    var cookie = 'loan-'+br.bookId+'='+value;
+    cookie    += '; expires='+expiry;
+    cookie    += '; path=/; domain=.archive.org;';
+    document.cookie = cookie; 
+}
+
+OLAuth.prototype.startPolling = function () {    
+    var self = this;
+    this.poller=setInterval(function(){
+        if (!self.olConnect) {
+          self.showPopup("#f00", "#fff", 'Cound not connect to Open Library for authentication. Please check to see if you are still connected to the Internet, and then reload this web page.');
+          clearInterval(self.poller);
+          self.ttsPoller = null;        
+        } else {
+          self.olConnect = false;
+          //be sure to add random param to authUrl to avoid stale cache
+          $.ajax({url:self.authUrl+'?rand='+Math.random(), dataType:'jsonp', jsonpCallback:'olAuth.callback'});
+        }
+    },300000);   
+}
+
+br.cleanupMetadata();
+if (br.olAuth) {
+    var olAuth = new OLAuth();
+    olAuth.init();
+} else {
+    br.init();
+}
 <?
 
 
@@ -502,3 +680,4 @@ function findImageStack($subPrefix, $filesData) {
 }
 
 ?>
+