Bibliotecha/Source: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
No edit summary
Line 215: Line 215:
"""
"""
print content.format(book_name, authors, title)
print content.format(book_name, authors, title)
</source>
== weserver from dir - server.py ==
<source lang="python">
<html><body><h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body></html>
02:44 PM~/Documents/Projects/Bibliotecha/code/bibliotecha cat ../serve.py
#!/usr/bin/env python
import BaseHTTPServer, CGIHTTPServer
import cgitb; cgitb.enable()  ## This line enables CGI error reporting
import sys, os
import argparse
parser = argparse.ArgumentParser(description='Happy to serve you')
parser.add_argument('--port', type=int, default=8000,
  help='the port number to listen to')
args = parser.parse_args()
os.chdir("/home/andre/Bibliotecha/bibliotecha")
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", args.port)
handler.cgi_directories = ["/cgi-bin"]
print "Listening on http://localhost:{0}".format(args.port)
httpd = server(server_address, handler)
httpd.serve_forever()
</source>
</source>

Revision as of 13:46, 5 April 2014

Upload section

In order to serve the upload page:

  • Start a server from this directory
python serve.py	

FILE TREE

Bibliotecha/
├── bibliotecha
│   ├── book_form.html
│   ├── cgi-bin
│   │   └── book_get.py
│   ├── files
│   │   └── book_tmp.pdf
│   ├── index.html
│   └── jquery-1.10.2.min.js
├── LIBRARIAN_NOTES
├── README_Bibliotecha.txt
└── serve.py

upload form - book_form.html

<!DOCTYPE html>
<html xml:lang="en" lang="en">
  <head>
    <meta charset="UTF-8" />
    <script type="text/javascript" src="jquery-1.10.2.min.js"></script>
  </head>
  <body>
    <form class="book" name="book" method="post" enctype="multipart/form-data" action="cgi-bin/book_get.py">
      <!-- action -- The URI of a web page that processes the information submitted via the form. -->
      <div>
	<lable>Authors:</lable>
	<input type="text" name="authorone" placeholder="First_Name  Surname"  id="author_one" />
	<input type="text" name="authortwo" placeholder="First_Name  Surname"  id="author_two" />
	<input type="text" name="authorthree" placeholder="First_Name  Surname"  id="author_three" />
	<lable><small>* At least one author must be provided</small></lable>
	<br /><br />
	<lable>Title:</lable>
	<input type="text" name="title" value="" id="title" placeholder="Title"/>
	<br /><br />
	<lable>Category:</lable>
	<select name="tag" id="tag">
	  <option ></option>
	  <option value="Media theory">Media theory</option> 
	  <option value="Art">Art</option>
	  <option value="Music">Music</option>
	</select>
	<br /><br />
	<input type="file" name="book" value="" id="file"/> 
	<br /><br />

      </div>
      <br />
      <div>
	<button id="upload" disabled>Upload book</button>
      </div>
    </form>

    <script type="text/javascript">

      // on focus fields
      // do check if all the remaining 3 fields are selected
      // then enable upload

      
      var fileready = 0;

      function checkfields(){
      if( $('input#title').val() != '' && $('input#author_one').val() != '' && $('input#file').val() != '' && $('select#tag').val() != '' )
      { 
      // check file
      console.log('TITLE');			   
      //if file is there 
      if (fileready == 1)
      { document.getElementById("upload").disabled=false; }
      }
      else
      { document.getElementById("upload").disabled=true; }
      } 


      $(document).ready(    
      function(){

      
      $('select').change(
      function(){
      checkfields();
      }
      )
      $('input').focusout(
      function(){
      checkfields();
      }	    
      )

      $('input#file').focusout(
      function(){
      var file = document.getElementById('file');
      file.onchange = function(e){
      var ext = this.value.match(/\.([^\.]+)$/)[1];
      switch(ext)
      {
      // || 'epub'|| 'mobi': //epub, mobi, txt, djvu
      case 'pdf':
      fileready=1;
      break;
      case 'mobi':
      fileready=1;
      break;
      case 'epub':
      fileready=1;
      break;
      case 'txt':
      fileready=1;
      break;
      case 'djvu':
      fileready=1;
      break;

      default:
      fileready=0;
      this.value='';
      }
      };
      }
      )


      }
      )



      // 	<input type="text" name="title" value="" id="title" placeholder="Title"/>

    </script>

  </body>
</html>


cgi-script book upload - book_get.py

#!/usr/bin/env python
import os, subprocess, cgi, cgitb
import datetime, calendar
cgitb.enable()

print "Content-type: text/html"

#get file and metadata from html form
form = cgi.FieldStorage()
author_one= form["authorone"].value
author_two= ""
author_three = ""
if form["authortwo"].value != "" : #if more than 1 author
    author_two = form["authortwo"].value
    authors = author_one +" & "+ author_two
    if form["authorthree"].value != "" : 
        author_three = form["authorthree"].value
        authors = authors +" & "+ author_three
else:
    authors = author_one # +" "+ author_two +" "+ author_three

title = form["title"].value
book = form["book"]
tag=form["tag"].value
book_name = book.filename
book_extension = os.path.splitext(book_name)[1] 
now=datetime.datetime.now()
book_time = "book_tmp_" + str(calendar.timegm(now.timetuple())) + book_extension #add timestamp to temp file
book_path = "../bibliotecha/files/" 
book_path_file = book_path + book_time 
book_path_list = os.listdir( book_path )
book_path_list.sort()

#check number of stored files in book_path dir
tmp_books_n = len( book_path_list )
if tmp_books_n > 5: #if > 5 files
    os.remove(book_path+os.listdir(book_path)[0]) #remove the older

# save the book
if book.file: # field really is an upload
    with file(book_path_file,"w") as outfile:
        outfile.write(book.file.read())


# ADD BOOK TO CALIBRE LIBRARY
#subprocess.Popen(["calibredb", "add", book_path, "--title", title, "--authors", authors, "--tag", tag])
subprocess.Popen(["calibredb", "add", book_path_file, "--title", title, "--authors", authors, "--tag", tag, "--with-library", "/home/pi/bookcase"]) #last item = calibre library location 


# PRINT HTML REPLY
content="""
<!DOCTYPE html>
<html xml:lang="en" lang="en">
<head>
  <meta charset="UTF-8" />
</head>
  <body>
<p><b>{0}</b> by <b>{1}</b> under the title <b>{2}</b> is being added to the collection.<br/>
Our librarians are working hard on it, but it will take a couple of minutes.</p>
<p>Thank you for your contribution.</p>
<br/><br/>
<p><a href="http://10.1.0.1:8080">Browse the library's catalog'</a></p>
</body>
</html>
"""
print content.format(book_name, authors, title)

weserver from dir - server.py

<html><body><h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body></html>
02:44 PM~/Documents/Projects/Bibliotecha/code/bibliotecha cat ../serve.py
#!/usr/bin/env python
 
import BaseHTTPServer, CGIHTTPServer
import cgitb; cgitb.enable()  ## This line enables CGI error reporting
import sys, os

import argparse
parser = argparse.ArgumentParser(description='Happy to serve you')
parser.add_argument('--port', type=int, default=8000,
  help='the port number to listen to')
args = parser.parse_args()

os.chdir("/home/andre/Bibliotecha/bibliotecha")
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", args.port)
handler.cgi_directories = ["/cgi-bin"]

print "Listening on http://localhost:{0}".format(args.port)
httpd = server(server_address, handler)
httpd.serve_forever()