def on_checkbutton1_toggled(self, widget): if not self.lentlist.get_iter_first(): return db_query = sql() #logging.info(widget) # Get widget state # Set book as borrowed or not with borrower as key. # What if I have two copies and they get borrowed? if self.lent.get_active(): # Checked foo = self.lent_select.get_active() bid = self.lentlist[foo][0] #logging.info(bid) if bid != 0 and self.mybook.id != 0 and self.orig_book.copies > 0: db_query.add_borrow(self.mybook.id, bid) self.mybook.borrower_id = bid self.status.set_text(_("Book has been marked as borrowed.")) self.orig_book.copies -= 1 else: self.status.set_text(_("Book has been NOT marked as borrowed.")) #self.lent.set_active(False) self.lent_date.set_text(str(self.o_date)) else: # Unchecked self.lent_date.set_text(str("")) foo = self.lent_select.get_active() bid = self.lentlist[foo][0] if bid != 0: result = db_query.update_borrows(self.mybook.id, bid) if result: self.orig_book.copies += 1 self.mybook.borrower_id = None self.status.set_text(_("Book has been marked as returned.")) else: self.status.set_text(_("Book has been NOT marked as returned.")) self.copies.set_text(str(self.orig_book.copies))
def get_book_list(self, selection): ''' Get the book lists from the databases. Params: selection -- BORRORWED or ALL Which set to get. ''' db_query = sql() result = {} #self.booklist.clear() num_ebooks = 0 if selection == ALL: result, numrows = db_query.get_all_books() #logging.info(numrows) self.fill_booklist(result) try: import calibre e_books = calibre.calibre() self.booklist, num_ebooks = e_books.insert_data2(self.booklist) except: print ("Cannot find any e-books.\n") pass # Do nothing if it's not available. self.status1.set_text("Book count = " + str(numrows) + ". E-book count = " + str(num_ebooks)) elif selection == BORROWED: result = db_query.get_borrowed_books() self.fill_booklist(result)
def get_book_list(self, selection): ''' Get the book lists from the databases. Params: selection -- BORRORWED or ALL Which set to get. ''' db_query = sql() result = {} num_ebooks = 0 if selection == ALL: result, numrows = db_query.get_all_books() self.fill_booklist(result) try: import calibre e_books = calibre.calibre() self.booklist, num_ebooks = e_books.insert_data2(self.booklist) except: print("Cannot find any e-books.\n") pass # Do nothing if it's not available. self.status1.set_text("Book count = " + str(numrows) + ". E-book count = " + str(num_ebooks)) elif selection == BORROWED: result = db_query.get_borrowed_books() self.fill_booklist(result)
def on_button_export_clicked(self, widget): ''' Export the entire database to CSV. from MySQL with a single command such as: ''' filename = None db_query = sql() ext = gtk.FileFilter() ext.add_pattern("*.csv") dialog = gtk.FileChooserDialog("Save CSV as", None,gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) dialog.set_filter(ext) response = dialog.run() if response == gtk.RESPONSE_OK: filename = dialog.get_filename() print("Selected filepath: %s" % dialog.get_filename()) dialog.destroy() logging.info(filename) ## Now just export direct from the DB result, numrows = db_query.get_all_books() with open(filename, 'wb') as csvfile: fieldnames = ["isbn","title", "author", "abstract","year", "publisher","rating"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() for book in result: logging.debug(book) writer.writerow(book) return
def on_button_export_clicked(self, widget): ''' Export the current list view to CSV. ''' filename = None db_query = sql() ext = gtk.FileFilter() ext.add_pattern("*.csv") dialog = gtk.FileChooserDialog("Save CSV as", None,gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) dialog.set_filter(ext) response = dialog.run() if response == gtk.RESPONSE_OK: filename = dialog.get_filename() print("Selected filepath: %s" % dialog.get_filename()) dialog.destroy() logging.info(filename) with open(filename, 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"') model = self.booklist myiter = model.get_iter_first() if myiter is not None: while str(myiter) != 'None': row = [] if myiter is not None: row.append(model.get_value(myiter, 9)) row.append(model.get_value(myiter, 1)) row.append(model.get_value(myiter, 2)) myiter = model.iter_next(myiter) csvwriter.writerow(row) return
def make_qr_code(self): ''' Make a QR code for the book. This could be useful somewhere I guess. It contains the ISBN, title and Authors of the book. Maybe it should contain the owner name , yes YOU, just in case you ever need to split up you and your parter's books. You know why that might be needed. TODO. Maybe print the ISBN too. Change output dir DONE: Store images in the DB ''' from db_queries import sql as sql db_query = sql() if QR_CODE: import getpass user = getpass.getuser() # Do the QR thang qr_data = 'ISBN:'+ str(self.abook.id) \ + ';TITLE:' + str(self.abook.title) \ + ';AUTHORS:' + str(self.abook.authors) \ + ";OWNER:" + user qr = qrencode.encode(qr_data) # Rescale using the size and add a 1 px border size = qr[1] qr = qrencode.encode_scaled(qr_data, (size*3)+2) img = qr[2] count = db_query.get_qrcode_count(self.abook.id) if count == 0: sql = 'INSERT INTO qrcodes(caption,img) VALUES(%s,%s)' # But how to get them back out again? See below. args = ("ISBN: " + str(self.abook.id), img, ) self.cur.execute (sql, args) self.db.commit()
def update_db(self): db_query = sql() book = copy.copy(self.mybook) result = db_query.get_by_id(self.mybook.id) if self.mybook.id == 0: return if book.is_empty(): return # Do nothing if no data if result == None: # If no book in DB, add it # Make sure we don't add an empty book. We could also use this to if not str.isdigit(book.year.encode('ascii', 'ignore')): book.year = 0 #DB query fix for empty date field. book_id = db_query.insert_book_object(book) book.id = book_id # Update the book with it's new id from the DB. self.set_location() INFO("New book has been inserted.") self.status.set_text(_("New book has been inserted.")) self.orig_book = copy.copy(book) # So we can compare again. #check for changes if we have a copy of the original data. # If the book is not empty else: INFO("Something changed so an update is needed") db_query.update_book(book, book.id) db_query.insert_unique_author(book.authors) self.status.set_text(_(" Book has been updated.")) self.orig_book = copy.copy(book) # So we can compare again. del book
def update_db(self): db_query = sql() book = copy.copy(self.mybook) #logging.info(self.orig_book.compare(book)) result = db_query.get_by_id(book.id) #logging.info(result) if result == None: # If no book in DB, add it # Make sure we don't add an empty book. We could also use this to #check for changes if we have a copy of the original data. book_data = book.title + book.authors + book.isbn + book.abstract \ + book.year + book.publisher + book.city #logging.info(book_data) if book_data == '': return # Do nothing if no data if not str.isdigit(book.year): book.year = 0 #DB query fix for empty date field. book.owner = getpass.getuser() # Assume owner is current logged in person db_query.insert_book_object(book) #book.id = db_query.insert_book_complete(book.title, book.authors, book.isbn, book.abstract, book.year,\ # book.publisher, book.city ,book.mtype, book.add_date, book.owner)['LAST_INSERT_ID()'] #logging.info(book.id) db_query.insert_unique_author(book.authors) self.status.set_text(_(" Book has been inserted.")) self.orig_book = copy.copy(book) # So we can compare again. # If a change has been made... elif self.orig_book.compare(book) != 0: #logging.info("Something changed so an update is needed") self.update_book() db_query.update_book(book.title, book.authors, book.abstract,book.year,book.publisher, book.city, book.mtype,book.owner, book.id) #logging.info(book.mtype) db_query.insert_unique_author(book.authors) self.status.set_text(_(" Book has been updated.")) self.orig_book = copy.copy(book) # So we can compare again. del book
def update_db(self, ): db_query = sql() book = copy.copy(self.mybook) DEBUG(book.id) result = db_query.get_by_id(book.id) DEBUG(result) if result == None: # If no book in DB, add it # Make sure we don't add an empty book. We could also use this to if not book.year: book.year = 0 #DB query fix for empty date field. book_id = db_query.insert_book_object(book) book.id = book_id # Update the book with it's new id from the DB. self.set_location() INFO("New book has been inserted.") DEBUG(book_id) self.status.set_text(_("New book has been inserted.")) else: book_id = result['id'] if book_id == self.mybook.id: # It already exists so we update #check for changes if we have a copy of the original data. # If the book is not empty INFO("Book has been updated") db_query.update_book(book, book.id) db_query.insert_unique_author(book.authors) self.status.set_text(_(" Book has been updated.")) self.mybook = copy.copy(book) # So we can compare again. del book
def on_button_export_clicked(self, widget): ''' Export the current list view to CSV. ''' filename = None db_query = sql() ext = gtk.FileFilter() ext.add_pattern("*.csv") dialog = gtk.FileChooserDialog("Save CSV as", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) dialog.set_filter(ext) response = dialog.run() if response == gtk.RESPONSE_OK: filename = dialog.get_filename() print("Selected filepath: %s" % dialog.get_filename()) dialog.destroy() logging.info(filename) with open(filename, 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"') model = self.booklist myiter = model.get_iter_first() if myiter is not None: while str(myiter) != 'None': row = [] if myiter is not None: row.append(model.get_value(myiter, 9)) row.append(model.get_value(myiter, 1)) row.append(model.get_value(myiter, 2)) myiter = model.iter_next(myiter) csvwriter.writerow(row) return
def update_db(self): db_query = sql() book = copy.copy(self.mybook) #logging.info(self.orig_book.compare(book)) result = db_query.get_by_id(book.id) logging.debug(result) logging.debug(book.is_empty()) if book.is_empty(): return # Do nothing if no data if result == None: # If no book in DB, add it # Make sure we don't add an empty book. We could also use this to if not str.isdigit(book.year): book.year = 0 #DB query fix for empty date field. #book.owner = getpass.getuser() # Assume owner is current logged in person db_query.insert_book_object(book) #db_query.insert_unique_author(book.authors) self.status.set_text(_(" Book has been inserted.")) self.orig_book = copy.copy(book) # So we can compare again. #check for changes if we have a copy of the original data. # If the book is not empty else: logging.info("Something changed so an update is needed") #self.update_book() db_query.update_book(book, book.id) #logging.info(book.mtype) db_query.insert_unique_author(book.authors) self.status.set_text(_(" Book has been updated.")) self.orig_book = copy.copy(book) # So we can compare again. del book
def on_checkbutton1_toggled(self, widget): if not self.lentlist.get_iter_first(): return db_query = sql() # Get widget state # Set book as borrowed or not with borrower as key. # What if I have two copies and they get borrowed? if self.lent.get_active(): # Checked foo = self.lent_select.get_active() bid = self.lentlist[foo][0] if bid != 0 and self.mybook.id != 0 and self.orig_book.copies > 0: db_query.add_borrow(self.mybook.id, bid) self.mybook.borrower_id = bid self.status.set_text(_("Book has been marked as borrowed.")) else: self.status.set_text( _("Book has been NOT marked as borrowed.")) self.lent_date.set_text(str(self.o_date)) else: # Unchecked self.lent_date.set_text(str("")) foo = self.lent_select.get_active() bid = self.lentlist[foo][0] if bid != 0: result = db_query.update_borrows(self.mybook.id, bid) if result: self.mybook.borrower_id = None self.status.set_text( _("Book has been marked as returned.")) else: self.status.set_text( _("Book has been NOT marked as returned.")) self.copies.set_text(str(self.orig_book.copies))
def add_dvd(self, proc, ean8): ''' Add the DVD and open the dialog to edit the details. @param None @param ean8 ''' from add_edit import add_edit db_query = sql() dvd = db_query.get_by_isbn(ean8) if dvd: DEBUG(dvd) adder = add_edit() adder.populate(dvd['id']) else: import upc_lookup lookup = upc_lookup.UPCLookup() data = lookup.get_response(ean8).json() try: adder = add_edit() DEBUG(data['items'][0]['ean']) adder.isbn.set_text(str(data['items'][0]['ean'])) adder.title.set_text(str(data['items'][0]['title'])) adder.mtype.set_text("DVD/CD") adder.populate_borrowers() adder.populate_locations() adder.populate_rating(row['rating']) adder.populate_values() adder.display() except: buff = self.text_view.get_buffer() buff.insert_at_cursor (_("This item doesn't exist!" )) return None self.real_scanner()
def getBookLocation(self, isbn): db_query = sql() location_string = None result = db_query.get_location_by_isbn(isbn) # Could be multiple but unlikely for row in result: print row location_string += row return location_string
def getBookLocation(self, isbn): db_query = sql() location_string = None result = db_query.get_location_by_isbn(isbn) # Could be multiple but unlikely DEBUG(result) for row in result: print (row) location_string = row['room'] + " : " + row['shelf'] return location_string
def fill_booklist(self, result, append=False): ''' Authors names are stored in regular text, we want so get them by family,first name order. This iterates through the result and and appends to the liststore with the author names re-ordered. @param Result cursor from query @param append boolean, whether to append to list. ''' db_query = sql() if not append: self.booklist.clear() column = self.treeview.get_column(3) column.set_title(_('Abstract')) for row in result: # Deal with rearranging author names to last, first if row['author'] != None: name = row['author'] name = name.split() else: name = '' if len(name) > 0: author = [] author.append(name[-1]) # Last part author.append(", ") # Decoration author.append( ' '.join(name[0:-1]) ) # All except last part adding a space between them author = ''.join(author) # Join all elements into a string else: author = "N/A" abstract = row['abstract'] # If a book is borrowed, display who to in the 1st column # If you have lent it to someone try: if row['borrower'] != None: column = self.treeview.get_column(0) column.set_title(_('Borrower')) row['mtype'] = "" b_book = db_query.get_book_borrower_by_book_id(row['id']) if b_book: #abstract = b_book['name'] + " : " + str(b_book['o_date']) row['mtype'] = b_book['name'] + " : " + str( b_book['o_date']) except: pass ## If you've borrowed it from someone else.display who from in the abtract column if row['owner'] != getpass.getuser(): abstract = " " + str(row['owner']) self.booklist.append([ row['isbn'], author, row['title'], abstract, row['publisher'], row['city'], str(row['year']), row['id'], row['copies'], row['mtype'] ])
def set_location(self): ''' Set the book's location ''' db_query = sql() idx = self.location_dropdown.get_active() if idx > 0: lid = self.location_liststore[idx][0] self.mybook.where = lid db_query.update_book_location(self.mybook.id, lid) return
def populate(self): '''If we are passed a bid > 0 populate the dialog. ''' db_query = sql() logging.info(self.bid) if self.bid > 0: result = db_query.get_one_borrower(self.bid) logging.info(result) self.name.set_text(result["name"]) self.contact.set_text(result["contact"]) self.notes.set_text(str(result["notes"]))
def export_csv(self): ''' Export the entire database to CSV when called from the command line. ''' db_query = sql() result, numrows = db_query.get_all_books() with open('books.csv', 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"') #, quoting=csv.QUOTE_MINIMAL) for row in result: csvwriter.writerow([row['mtype'],row['author'], row['title']]) return
def on_button_scan_clicked(self, widget): ''' Do the scan, query the database and store the results. TODO: Need to find better way to enumerate cameras. TODO: Need to find how to do this on Windoze, gstreamer for both? TODO: If we already have a book display its location. ''' ## Is there a real scanner attached? if self.dev: self.real_scanner() return proc = None db_query = sql() device = None buff = self.text_view.get_buffer() buff.set_text(_("To begin press scan.")) self.text_view.set_buffer(buff) if system == "Linux": try: for i in self.getVideoDevices(): # Get the first found device. device = i[1] except: buff.set_text (_("Cannot find camera on this Operating system.")) self.text_view.set_buffer(buff) del buff,proc return ## No video device elif system == "Windows": # TODO: Windows camera stuff. pass else: # TODO: Write code for other systems. Others can do this perhaps. buff.set_text (_("Cannot find camera on this Operating system.")) self.text_view.set_buffer(buff) del buff,proc return # create a Processor proc = zbar.Processor() # configure the Processor proc.parse_config('enable') buff = self.text_view.get_buffer() # enable the preview window try: proc.init(device) except: buff.set_text (_("No camera present!")) self.text_view.set_buffer(buff) del buff,proc return proc.visible = True # Read one barcode (or until window closed) if proc.process_one(): logging.info(proc.results) for symbol in proc.results: bar = symbol.data self.add_book(proc, bar)
def on_button_remove_clicked(self, widget): ''' Remove selected book from database ''' db_query = sql() dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Are you sure you want to delete this book?") dlg_val = dialog.run() DEBUG(dlg_val) dialog.destroy() del dialog if dlg_val == -9:return db_query.remove_book(self.mybook.id) self.status.set_text (_(" Book has been removed.")) INFO("Book has been removed.")
def on_button_remove_clicked(self, widget): ''' Remove selected book from database ''' db_query = sql() dialog = gtk.MessageDialog( None, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Are you sure you want to delete this book?") dlg_val = dialog.run() DEBUG(dlg_val) dialog.destroy() del dialog if dlg_val == -9: return db_query.remove_book(self.mybook.id) self.status.set_text(_(" Book has been removed.")) INFO("Book has been removed.")
def fill_booklist(self, result, append=False): ''' Authors names are stored in regular text, we want so get them by family,first name order. This iterates through the result and and appends to the liststore with the author names re-ordered. @param Result cursor from query @param append boolean, whether to append to list. ''' db_query = sql() if not append: self.booklist.clear() column = self.treeview.get_column(3) column.set_title(_('Abstract')) for row in result: # Deal with rearranging author names to last, first if row['author'] != None: name=row['author'] name = name.split() else: name = '' if len(name) > 0 : author = [] author.append(name[-1]) # Last part author.append(", ") # Decoration author.append(' '.join(name[0:-1])) # All except last part adding a space between them author = ''.join(author) # Join all elements into a string else: author = "N/A" abstract = row['abstract'] # If a book is borrowed, display who to in the 1st column # If you have lent it to someone try: if row['borrower'] != None: column = self.treeview.get_column(0) column.set_title(_('Borrower')) row['mtype'] = "" b_book = db_query.get_book_borrower_by_book_id(row['id']) if b_book: #abstract = b_book['name'] + " : " + str(b_book['o_date']) row['mtype'] = b_book['name'] + " : " + str(b_book['o_date']) except: pass ## If you've borrowed it from someone else.display who from in the abtract column if row['owner'] != getpass.getuser(): abstract = " " + str(row['owner']) self.booklist.append([row['isbn'], author, row['title'], abstract, row['publisher'], row['city'], str(row['year']), row['id'], row['copies'], row['mtype']])
def on_button_remove_clicked(self, widget): '''Remove a book from the database. ''' db_query = sql() # Remove a scanned book from the database. print (_("You removed this book.")) buff = self.text_view.get_buffer() try: self.cur.execute("DELETE FROM books WHERE isbn = %s;", str(self.abook.isbn)) buff.insert_at_cursor (_( "\n\nYou removed this book.")) self.text_view.set_buffer(buff) except: buff.insert_at_cursor (_( "\n\nCould not remove book!")) self.text_view.set_buffer(buff)
def on_save_clicked_cb(self, widget): ''' Save any updates to the database. ''' db_query = sql() room = self.room_entry.get_text() shelf = self.shelf_entry.get_text() if shelf == '' or room == '': logging.info("Nothing to save") self.run() # Re-run else we close. return logging.info("Saving: "+room+", "+shelf) db_query.add_location(room, shelf) # Dont close, just re-run the dialog self.run()
def on_button_remove_clicked(self, widget): '''Remove a book from the database. ''' db_query = sql() # Remove a scanned book from the database. print "You removed this book." buff = self.text_view.get_buffer() try: self.cur.execute("DELETE FROM books WHERE isbn = %s;", str(self.abook.isbn)) buff.insert_at_cursor (_( "\n\nYou removed this book.")) self.text_view.set_buffer(buff) except: buff.insert_at_cursor (_( "\n\nCould not remove book!")) self.text_view.set_buffer(buff)
def on_save_clicked_cb(self, widget): ''' Save any updates to the database. ''' db_query = sql() room = self.room_entry.get_text() shelf = self.shelf_entry.get_text() if shelf == '' or room == '': logging.info("Nothing to save") self.run() # Re-run else we close. return logging.info("Saving: " + room + ", " + shelf) db_query.add_location(room, shelf) # Dont close, just re-run the dialog self.run()
def add_dvd(self, proc, ean8): ''' Add the DVD and open the dialog to edit the details. @param None @param ean8 ''' from add_edit import add_edit adder = add_edit() db_query = sql() dvd = db_query.get_by_isbn(ean8) if dvd: DEBUG(dvd) adder.populate(dvd['id']) else: adder.isbn.set_text(str(ean8)) adder.display()
def populate_locations(self): db_query = sql() locations = db_query.get_locations() self.location_liststore.clear() loc = self.mybook.where for where in locations: rs = where['room'] + ' - ' + where['shelf'] self.location_liststore.append([where['id'], rs]) self.location_liststore.prepend([0, '']) # Now set the dropdown to the books location n = 0 for lid in self.location_liststore: if lid[0] == loc: self.location_dropdown.set_active(n) return n += 1
def on_button_search_clicked(self, widget): ''' Get the search string from entry_search, query the DB and display the result. ''' db_query = sql() search_string = self.search_string.get_text() if search_string == "": return result = db_query.search_books(search_string) self.fill_booklist(result,False) # Now search the calibre database. try: import calibre search = calibre.calibre() result = search.search_calibre(search_string, self.booklist) # search and add to booklist except: pass # Do nothing return
def on_button_add_clicked(self, widget): ''' Add a book, DVD or CD to the database. Arguably I could have used "ON DUPLICATE KEY", using the isbn as the key, here but it may happen that several books will have empty isbn values for instance, books printed before ISBN was invented. result = self.cur.execute ("SELECT count(isbn) as count FROM books WHERE isbn = %s;", str(self.abook.isbn)) TODO Move all DB stuff to db_queries.py ''' db_query = sql() a_name = str(self.abook.authors) a_mtype = str(self.abook.mtype) self.cur.execute("INSERT IGNORE INTO authors(name) values(%s);", [a_name]) self.cur.execute("SELECT * FROM authors WHERE name=%s;",[a_name]) result = self.cur.fetchall() author_id = result[0][0] values = (str(self.abook.title), str(self.abook.authors), str(self.abook.id), str(self.abook.abstract),self.abook.year, str(self.abook.publisher),str(self.abook.city),1,author_id, datetime.date.today(), str(self.abook.mtype)) self.cur.execute("INSERT INTO books\ (title, author, isbn,abstract, year, publisher, city, copies, author_id, add_date,mtype)\ VALUES(%s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s);", values) self.db.commit() # Get and insert the track listing # TODO: Move DB stuff to db_queries if str(self.abook.mtype) == 'Music': self.cur.execute("SELECT id FROM books WHERE title=%s AND author=%s LIMIT 1;",\ [str(self.abook.title), str(self.abook.authors)]) res = self.cur.fetchall() cdid = res[0][0] tracks = self.get_cd_tracks() for track in tracks: self.cur.execute("INSERT INTO cd_tracks(cdid,tracknum,trackname,tracklen) \ VALUES(%s,%s,%s,%s);", \ [cdid, track['index'],track['name'],str(track['length'])]) #self.db.commit() self.cur.execute("UPDATE books SET year = %s WHERE id = %s",[self.abook.year, cdid]) self.db.commit() buff = self.text_view.get_buffer() buff.insert_at_cursor(_( "\n\nYou added this " + str(self.abook.mtype) + ".\n")) self.text_view.set_buffer(buff) self.make_qr_code() print "You added this", str(self.abook.mtype)
def on_button_add_clicked(self, widget): ''' Add a borrower to the database. ''' db_query = sql() logging.info("Added a borrower") logging.info(self.name.get_text()) if len(self.name.get_text()) > 0: if self.bid == 0: db_query.add_new_borrower(self.name.get_text(),self.contact.get_text(), self.notes.get_text()) else: db_query.update_borrower(self.name.get_text(),self.contact.get_text(), self.notes.get_text(), self.bid) self.status.set_text("Added a borrower.") else: logging.info("Nothing to add.") self.status.set_text("Nothing to add.") self.button_cancel.set_label(_("CLOSE"))
def on_button_print_clicked(self,widget): ''' Create a pdf of the current users. Optionally open the default reader for viewing and printing of the document. ''' db_query = sql() try: import time, os from reportlab.lib.enums import TA_LEFT from reportlab.lib.pagesizes import A4 from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm except ImportError, e: print e messages.pop_info(e) return
def on_button_print_clicked(self, widget): ''' Create a pdf of the current users. Optionally open the default reader for viewing and printing of the document. ''' db_query = sql() try: import time, os from reportlab.lib.enums import TA_LEFT from reportlab.lib.pagesizes import A4 from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm except ImportError, e: print e messages.pop_info(e) return
def populate(self,book_id): db_query = sql() #logging.debug(book_id) row = db_query.get_by_id(book_id) #logging.info(result) #for row in result: # Populate GUI if row['isbn'] != None: self.isbn.set_text(row['isbn']) if row['author'] != None: self.author.set_text(row['author']) self.title.set_text(row['title']) abs_buffer = self.abstract.get_buffer() #logging.debug(abs_buffer) abs_buffer.set_text(row['abstract']) if row['publisher'] != None: self.publisher.set_text(row['publisher']) if row['city'] != None: self.city.set_text(row['city']) if row['year'] != None: self.year.set_text(str(row['year'])) if row['owner'] != None: self.book_owner.set_text(str(row['owner'])) self.mtype.set_text(str(row['mtype'])) self.copies.set_text(str(row['copies'])) # Populate a book object self.orig_book.isbn =row['isbn'] self.orig_book.id = row['id'] self.orig_book.authors = row['author'] self.orig_book.title = row['title'] self.orig_book.abstract = row['abstract'] self.orig_book.publisher = row['publisher'] self.orig_book.city = row['city'] self.orig_book.year = row['year'] self.orig_book.copies = row['copies'] self.orig_book.where = row['location'] self.orig_book.owner = row['owner'] self.orig_book.rating = row['rating'] #logging.info(self.orig_book.where) self.orig_book.mtype = row['mtype'] if row['add_date'] != "": self.orig_book.add_date = row['add_date'] else: # Dunno? datetime.date.today() perhaps? pass self.mybook = copy.copy(self.orig_book) self.populate_borrowers() self.populate_locations() self.populate_rating(row['rating'])
def on_comboboxentry1_changed(self,widget): ''' Do things when selection is changed Need to check if the selected borrower has the book and set the checkbutton status to suit ''' db_query = sql() if not self.lentlist.get_iter_first(): return # If we can't iterate then the list is empty foo = self.lent_select.get_active() bid = self.lentlist[foo][0] if bid > 0: self.add_button.set_label(_("EDIT")) else: self.lent.set_active(False) self.add_button.set_label(_("ADD")) # Get list of borrows for this book result = db_query.get_borrows(self.mybook.id,bid) if result == 0: self.lent.set_active(False) else: self.lent.set_active(False)
def populate(self, book_id): db_query = sql() row = db_query.get_by_id(book_id) # Populate GUI if row['isbn'] != None: self.isbn.set_text(row['isbn']) if row['author'] != None: self.author.set_text(row['author']) self.title.set_text(row['title']) abs_buffer = self.abstract.get_buffer() abs_buffer.set_text(row['abstract']) if row['publisher'] != None: self.publisher.set_text(row['publisher']) if row['city'] != None: self.city.set_text(row['city']) if row['year'] != None: self.year.set_text(str(row['year'])) if row['owner'] != None: self.book_owner.set_text(str(row['owner'])) self.mtype.set_text(str(row['mtype'])) self.copies.set_text(str(row['copies'])) # Populate a book object self.orig_book.value = row['value'] self.orig_book.isbn = row['isbn'] self.orig_book.id = row['id'] self.orig_book.authors = row['author'] self.orig_book.title = row['title'] self.orig_book.abstract = row['abstract'] self.orig_book.publisher = row['publisher'] self.orig_book.city = row['city'] self.orig_book.year = str(row['year']).strip() self.orig_book.copies = row['copies'] self.orig_book.where = row['location'] self.orig_book.owner = row['owner'] self.orig_book.rating = row['rating'] self.orig_book.mtype = row['mtype'] if row['add_date'] != "": self.orig_book.add_date = row['add_date'] else: # Dunno? datetime.date.today() perhaps? pass self.mybook = copy.copy(self.orig_book) self.populate_borrowers() self.populate_locations() self.populate_rating(row['rating']) self.populate_values()
def on_comboboxentry1_changed(self, widget): ''' Do things when selection is changed Need to check if the selected borrower has the book and set the checkbutton status to suit ''' db_query = sql() if not self.lentlist.get_iter_first(): return # If we can't iterate then the list is empty foo = self.lent_select.get_active() bid = self.lentlist[foo][0] if bid > 0: self.add_button.set_label(_("EDIT")) else: self.lent.set_active(False) self.add_button.set_label(_("ADD")) # Get list of borrows for this book result = db_query.get_borrows(self.mybook.id, bid) if result == 0: self.lent.set_active(False) else: self.lent.set_active(False)
def make_qr_code(self): ''' Make a QR code for the book. This could be useful somewhere I guess. It contains the ISBN, title and Authors of the book. Maybe it should contain the owner name , yes YOU, just in case you ever need to split up you and your parter's books. You know why that might be needed. TODO. Maybe print the ISBN too. Change output dir DONE: Store images in the DB ''' from db_queries import sql as sql db_query = sql() if QR_CODE: import getpass user = getpass.getuser() # Do the QR thang qr_data = 'ISBN:'+ str(self.abook.id) \ + ';TITLE:' + str(self.abook.title) \ + ';AUTHORS:' + str(self.abook.authors) \ + ";OWNER:" + user qr = qrencode.encode(qr_data) # Rescale using the size and add a 1 px border size = qr[1] qr = qrencode.encode_scaled(qr_data, (size*3)+2) img = qr[2] count = db_query.get_qrcode_count(self.abook.id) if count == 0: sql = 'INSERT INTO qrcodes(caption,img) VALUES(%s,%s)' # But how to get them back out again? See below. args = ("ISBN: " + str(self.abook.id), img, ) self.cur.execute (sql, args) self.db.commit() #pixmap,mask = pixbuf.render_pixmap_and_mask() #img.save('tmp.png', 'png') # Display it in the GUI #self.qr_img.set_from_image(img, mask) # may need to be gtk.image #self.qr_img.set_from_file('tmp.png') # fix this, I don't like using tmp files '''
def add_book(self, proc, isbn): from add_edit import add_edit #buff = self.text_view.get_buffer() DEBUG(isbn) db_query = sql() # Check if exists and increment book count if so. count = db_query.get_book_count_by_isbn(isbn) DEBUG(count) if count: try: location = self.getBookLocation(isbn) DEBUG(location) if count > 0 and location != None: buff = self.text_view.get_buffer() buff.insert_at_cursor (_("You already have " \ + str(count) \ + " copies in the database!\n It's located at: " \ + location \ + ".\n")) self.text_view.set_buffer(buff) return except Exception as e: DEBUG(e) try: if self.abook.webquery(isbn) != None: INFO(self.abook.print_book()) buff = self.text_view.get_buffer() buff.set_text(self.abook.print_book()) self.text_view.set_buffer(buff) else: buff.set_text (_("No data returned, retry?")) self.text_view.set_buffer(buff) # hide the preview window if proc: proc.visible = False except Exception as e: buff = self.text_view.get_buffer() buff.set_text("No book with ISBN " + isbn + " found") #buff.set_text(repr(e.message)) self.text_view.set_buffer(buff) DEBUG(e) self.real_scanner()
def on_button_add_clicked(self, widget): ''' Add a borrower to the database. ''' db_query = sql() logging.info("Added a borrower") logging.info(self.name.get_text()) if len(self.name.get_text()) > 0: if self.bid == 0: db_query.add_new_borrower(self.name.get_text(), self.contact.get_text(), self.notes.get_text()) else: db_query.update_borrower(self.name.get_text(), self.contact.get_text(), self.notes.get_text(), self.bid) self.status.set_text("Added a borrower.") else: logging.info("Nothing to add.") self.status.set_text("Nothing to add.") self.button_cancel.set_label(_("CLOSE"))
def on_button_add_clicked(self, widget): ''' Add a book, DVD or CD to the database. Arguably I could have used "ON DUPLICATE KEY", using the isbn as the key, here but it may happen that several books will have empty isbn values for instance, books printed before ISBN was invented. result = self.cur.execute ("SELECT count(isbn) as count FROM books WHERE isbn = %s;", str(self.abook.isbn)) TODO Move all DB stuff to db_queries.py ''' buff = self.text_view.get_buffer() db_query = sql() last_id = db_query.insert_book_object(self.abook) logging.debug(last_id); # We should check this for success if last_id == 0: print ("Failed to add book to database.") buff.insert_at_cursor (_( "\n\nCould add this book!")) self.text_view.set_buffer(buff) return # Get and insert the track listing # TODO: Move DB stuff to db_queries if str(self.abook.mtype) == 'Music': self.cur.execute("SELECT id FROM books WHERE title=%s AND author=%s LIMIT 1;",\ [str(self.abook.title), str(self.abook.authors)]) res = self.cur.fetchall() cdid = res[0][0] tracks = self.get_cd_tracks() for track in tracks: self.cur.execute("INSERT INTO cd_tracks(cdid,tracknum,trackname,tracklen) \ VALUES(%s,%s,%s,%s);", \ [cdid, track['index'],track['name'],str(track['length'])]) #self.db.commit() self.cur.execute("UPDATE books SET year = %s WHERE id = %s",[self.abook.year, cdid]) self.db.commit() buff = self.text_view.get_buffer() buff.insert_at_cursor(_( "\n\nYou added this " + str(self.abook.mtype) + ".\n")) self.text_view.set_buffer(buff) self.make_qr_code() print "You added this", str(self.abook.mtype)
def populate_borrowers(self): ''' Get borrowers and fill in the list''' db_query = sql() #Populate borrowers combo box etc. self.lentlist.clear() result = db_query.get_all_borrowers() for row in result: self.lentlist.append([row["id"], row["name"], row["contact"]]) #self.lent_select.append_text(row[1]) self.borrowers += 1 self.lentlist.prepend([0, "", ""]) #Get borrows for this book up to the # of copies result = db_query.get_borrows(self.orig_book.id,self.orig_book.copies) bid = 0 for row in result: bid = row["borrower"] book_id = row["book"] self.o_date = row["o_date"] logging.info(bid) if bid != 0: #logging.info(bid) if self.orig_book.id == book_id: self.orig_book.copies -=1 self.copies.set_text(str(self.orig_book.copies)) # Set active to current borrower. # FIXME: This get the first borrower of a copy. Normally not an issue # for personal libraries, it will be for lending libraries though. n = 0 for lender in self.lentlist: if lender[0] == bid: self.lent_select.set_active(n) self.lent_date.set_text(str(self.o_date)) self.lent.set_active(True) break n += 1 else: #self.lentlist.prepend([0, "", ""]) self.lent_select.set_active(0) self.lent.set_active(False) pass
def on_button_add_clicked(self, widget): ''' Add a book, DVD or CD to the database. Arguably I could have used "ON DUPLICATE KEY", using the isbn as the key, here but it may happen that several books will have empty isbn values for instance, books printed before ISBN was invented. result = self.cur.execute ("SELECT count(isbn) as count FROM books WHERE isbn = %s;", str(self.abook.isbn)) TODO Move all DB stuff to db_queries.py ''' buff = self.text_view.get_buffer() db_query = sql() last_id = db_query.insert_book_object(self.abook) DEBUG(last_id); # We should check this for success if last_id == 0: print ("Failed to add book to database.") buff.insert_at_cursor (_( "\n\nCould add this book!")) self.text_view.set_buffer(buff) return # Get and insert the track listing # TODO: Move DB stuff to db_queries if str(self.abook.mtype) == 'Music': self.cur.execute("SELECT id FROM books WHERE title=%s AND author=%s LIMIT 1;",\ [str(self.abook.title), str(self.abook.authors)]) res = self.cur.fetchall() cdid = res[0][0] tracks = self.get_cd_tracks() for track in tracks: self.cur.execute("INSERT INTO cd_tracks(cdid,tracknum,trackname,tracklen) \ VALUES(%s,%s,%s,%s);", \ [cdid, track['index'],track['name'],str(track['length'])]) #self.db.commit() self.cur.execute("UPDATE books SET year = %s WHERE id = %s",[self.abook.year, cdid]) self.db.commit() buff = self.text_view.get_buffer() buff.insert_at_cursor(_( "\n\nYou added this " + str(self.abook.mtype) + ".\n")) self.text_view.set_buffer(buff) self.make_qr_code() print ("You added this", str(self.abook.mtype))
def populate_borrowers(self): ''' Get borrowers and fill in the list''' db_query = sql() #Populate borrowers combo box etc. self.lentlist.clear() result = db_query.get_all_borrowers() for row in result: self.lentlist.append([row["id"], row["name"], row["contact"]]) self.borrowers += 1 self.lentlist.prepend([0, "", ""]) #Get borrows for this book up to the # of copies result = db_query.get_borrows(self.orig_book.id, self.orig_book.copies) bid = 0 for row in result: bid = row["borrower"] book_id = row["book"] self.o_date = row["o_date"] #logging.info(bid) if bid != 0: #logging.info(bid) if self.orig_book.id == book_id: self.orig_book.copies -= 1 self.copies.set_text(str(self.orig_book.copies)) # Set active to current borrower. # FIXME: This get the first borrower of a copy. Normally not an issue # for personal libraries, it will be for lending libraries though. n = 0 for lender in self.lentlist: if lender[0] == bid: self.lent_select.set_active(n) self.lent_date.set_text(str(self.o_date)) self.lent.set_active(True) break n += 1 else: self.lent_select.set_active(0) self.lent.set_active(False) pass
import gettext import sys count = 1 try: count = int(sys.argv[1]) except: pass _ = gettext.gettext logger = logging.getLogger("barscan") logging.basicConfig( format='%(module)s: LINE %(lineno)d: %(levelname)s: %(message)s', level=logging.DEBUG) DEBUG = logging.debug INFO = logging.info db_query = sql() of = open("eans.csv", "w") while count: ean = barcode.EAN8(str(randint(1000000, 9999999))).ean if len(str(ean)) != 8: continue if not db_query.insert_unique_isbn(ean): continue ## Insert if not existing print ean of.write(str(ean)) of.write(",\n") count = count - 1 of.close()
def on_button_remove_clicked(self, widget): ''' Remove selected book from database ''' db_query = sql() #logging.info(str(self.mybook.id) + " about to be removed.") db_query.remove_book(self.mybook.id) self.status.set_text (_(" Book has been removed."))
import logging from random import randint import gettext import sys count = 1 try: count = int(sys.argv[1]) except: pass _ = gettext.gettext logger = logging.getLogger("barscan") logging.basicConfig(format='%(module)s: LINE %(lineno)d: %(levelname)s: %(message)s', level=logging.DEBUG) DEBUG = logging.debug INFO = logging.info db_query = sql() of = open("eans.csv","w") while count: ean = barcode.EAN8(str(randint(1000000, 9999999))).ean if len(str(ean)) != 8: continue if not db_query.insert_unique_isbn(ean): continue ## Insert if not existing print ean of.write(str(ean)) of.write(",\n") count = count -1 of.close()
def on_button_scan_clicked(self, widget): ''' Do the scan, query the database and store the results. TODO: Need to find better way to enumerate cameras. TODO: Need to find how to do this on Windoze, gstreamer for both? TODO: If we already have a book display its location. ''' db_query = sql() device = None buff = self.text_view.get_buffer() buff.set_text(_("To begin press scan.")) self.text_view.set_buffer(buff) if system == "Linux": try: for i in self.getVideoDevices(): # Get the first found device. device = i[1] except: buff.set_text (_("Cannot find camera on this Operating system.")) self.text_view.set_buffer(buff) return ## No video device elif system == "Windows": # TODO: Windows camera stuff. pass else: # TODO: Write code for other systems. Others can do this perhaps. buff.set_text (_("Cannot find camera on this Operating system.")) self.text_view.set_buffer(buff) return # create a Processor proc = zbar.Processor() # configure the Processor proc.parse_config('enable') buff = self.text_view.get_buffer() # enable the preview window try: proc.init(device) except: buff.set_text (_("No camera present!")) self.text_view.set_buffer(buff) return proc.visible = True # read at least one barcode (or until window closed) proc.process_one() # hide the preview window proc.visible = False logging.info(proc.results) del proc for symbol in proc.results: bar = symbol.data logging.info(bar) # DONE Check if exists and increment book count if so. count = db_query.get_book_count_by_isbn(bar) logger.info(count) self.getBookLocation(bar) if count > 0: buff.insert_at_cursor (_("\n\nYou already have " + str(count) + " in the database!\n")) self.text_view.set_buffer(buff) if self.abook.webquery(bar) != 1: logging.info(self.abook.print_book()) buff.set_text(self.abook.print_book()) return else: # Try for a DVD lookup buff.set_text (_("No data returned, retry?")) self.text_view.set_buffer(buff) #logging.info(self.abook.print_book()) buff.set_text (_("Searching for DVDs\n")) self.text_view.set_buffer(buff) try: import amazonlookup dvd_search = amazonlookup.DVDlookup() if dvd_search.lookup(bar) != 1: buff.insert_at_cursor (_("Found DVD:\n")) buff.insert_at_cursor(str(dvd_search.Title) + "\n") buff.insert_at_cursor(str(dvd_search.Director)) self.text_view.set_buffer(buff) self.abook.isbn = bar self.abook.title = str(dvd_search.Title) self.abook.authors = str(dvd_search.Director) # This isn't perfect and maybe I should use K-V pairs? self.abook.mtype = str(dvd_search.ProductGroup) self.abook.id = str(bar) #self.abook.year = 0 # Should be available but ... self.abook.owner = self.owner self.abook.add_date = datetime.date.today() else: # Do a CD search buff.set_text (_("No DVDs.\n Searching for CDs\n")) self.text_view.set_buffer(buff) cd_search = amazonlookup.CDlookup() # Should be able to get more data from freedb.org if cd_search.lookup(bar) != 1 and cd_search.Title != '' : buff.insert_at_cursor(_("CD Found:\n")) self.text_view.set_buffer(buff) buff.insert_at_cursor(str(cd_search.Title) + "\n") buff.insert_at_cursor(str(cd_search.Artist)) self.abook.title = str(cd_search.Title) self.abook.authors = str(cd_search.Artist) self.abook.mtype = str(cd_search.ProductGroup) self.abook.id = str(bar) self.abook.year = 0 # Should be available but ... except: raise buff.set_text (_("Could not lookup DVD or CD on Amazon")) self.text_view.set_buffer(buff) #return del buff,proc