[Device] Several enhancement and bug fix

This commit is contained in:
Li Fanxi 2010-12-09 01:50:16 +08:00
parent 4d7ad09761
commit 345cd48a5b
2 changed files with 56 additions and 32 deletions

View File

@ -35,7 +35,6 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
CAN_SET_METADATA = False CAN_SET_METADATA = False
THUMBNAIL_HEIGHT = 155 THUMBNAIL_HEIGHT = 155
# path_sep = "/"
icon = I("devices/bambook.png") icon = I("devices/bambook.png")
# OPEN_FEEDBACK_MESSAGE = _( # OPEN_FEEDBACK_MESSAGE = _(
# 'Connecting to Bambook device, please wait ...') # 'Connecting to Bambook device, please wait ...')
@ -91,7 +90,6 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
deviceInfo = self.bambook.GetDeviceInfo() deviceInfo = self.bambook.GetDeviceInfo()
return (_("Bambook"), "SD928", deviceInfo.firmwareVersion, "MimeType") return (_("Bambook"), "SD928", deviceInfo.firmwareVersion, "MimeType")
def card_prefix(self, end_session=True): def card_prefix(self, end_session=True):
''' '''
Return a 2 element list of the prefix to paths on the cards. Return a 2 element list of the prefix to paths on the cards.
@ -149,10 +147,12 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
if oncard: if oncard:
return self.booklist_class(None, None, None) return self.booklist_class(None, None, None)
# Get metadata cache
prefix = '' prefix = ''
booklist = self.booklist_class(oncard, prefix, self.settings) booklist = self.booklist_class(oncard, prefix, self.settings)
need_sync = self.parse_metadata_cache(booklist) need_sync = self.parse_metadata_cache(booklist)
# Get book list from device
devicebooks = self.bambook.GetBookList() devicebooks = self.bambook.GetBookList()
books = [] books = []
for book in devicebooks: for book in devicebooks:
@ -163,7 +163,6 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
b.authors = [ book.bookAuthor.decode(text_encoding) ] b.authors = [ book.bookAuthor.decode(text_encoding) ]
b.size = 0 b.size = 0
b.datatime = time.gmtime() b.datatime = time.gmtime()
# b.path = book.bookGuid
b.lpath = book.bookGuid b.lpath = book.bookGuid
b.thumbnail = None b.thumbnail = None
b.tags = None b.tags = None
@ -172,16 +171,15 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
# make a dict cache of paths so the lookup in the loop below is faster. # make a dict cache of paths so the lookup in the loop below is faster.
bl_cache = {} bl_cache = {}
for idx, b in enumerate(booklist): for idx, b in enumerate(booklist):
bl_cache[b.lpath] = idx bl_cache[b.lpath] = idx
def update_booklist(book, prefix): def update_booklist(book, prefix):
changed = False changed = False
try: try:
idx = bl_cache.get(book.path, None) idx = bl_cache.get(book.lpath, None)
if idx is not None: if idx is not None:
bl_cache[book.path] = None bl_cache[book.lpath] = None
if self.update_metadata_item(book, booklist[idx]): if self.update_metadata_item(book, booklist[idx]):
changed = True changed = True
else: else:
@ -193,13 +191,15 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
traceback.print_exc() traceback.print_exc()
return changed return changed
# Check each book on device whether it has a correspondig item
# in metadata cache. If not, add it to cache.
for i, book in enumerate(books): for i, book in enumerate(books):
self.report_progress(i/float(len(books)), _('Getting list of books on device...')) self.report_progress(i/float(len(books)), _('Getting list of books on device...'))
changed = update_booklist(book, prefix) changed = update_booklist(book, prefix)
if changed: if changed:
need_sync = True need_sync = True
# Remove books that are no longer in the filesystem. Cache contains # Remove books that are no longer in the Bambook. Cache contains
# indices into the booklist if book not in filesystem, None otherwise # indices into the booklist if book not in filesystem, None otherwise
# Do the operation in reverse order so indices remain valid # Do the operation in reverse order so indices remain valid
for idx in sorted(bl_cache.itervalues(), reverse=True): for idx in sorted(bl_cache.itervalues(), reverse=True):
@ -361,13 +361,10 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
with TemporaryFile('.snb') as f: with TemporaryFile('.snb') as f:
if self.bambook.PackageSNB(f, tdir): if self.bambook.PackageSNB(f, tdir):
t = open('/tmp/abcd.snb', 'wb')
t2 = open(f, 'rb')
t.write(t2.read())
t.close()
t2.close()
if not self.bambook.SendFile(f, self.METADATA_FILE_GUID): if not self.bambook.SendFile(f, self.METADATA_FILE_GUID):
print "Upload failed" print "Upload failed"
else:
print "Package failed"
# Clear the _new_book indication, as we are supposed to be done with # Clear the _new_book indication, as we are supposed to be done with
# adding books at this point # adding books at this point
@ -388,11 +385,13 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
''' '''
if self.bambook: if self.bambook:
with TemporaryDirectory() as tdir: with TemporaryDirectory() as tdir:
self.bambook.GetFile(path, tdir) if self.bambook.GetFile(path, tdir):
filepath = os.path.join(tdir, path) filepath = os.path.join(tdir, path)
f = file(filepath, 'rb') f = file(filepath, 'rb')
outfile.write(f.read()) outfile.write(f.read())
f.close() f.close()
else:
print "Unable to get file from Bambook:", path
# @classmethod # @classmethod
# def config_widget(cls): # def config_widget(cls):
@ -418,7 +417,6 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
# raise NotImplementedError() # raise NotImplementedError()
def parse_metadata_cache(self, bl): def parse_metadata_cache(self, bl):
bl = []
need_sync = True need_sync = True
if not self.bambook: if not self.bambook:
return need_sync return need_sync
@ -444,13 +442,17 @@ class BAMBOOK(DeviceConfig, DevicePlugin):
@classmethod @classmethod
def update_metadata_item(cls, book, blb): def update_metadata_item(cls, book, blb):
changed = False # Currently, we do not have enough information
if book.bookName.decode(text_encoding) != blb.title: # from Bambook SDK to judge whether a book has
changed = True # been changed, we assume all books has been
if book.bookAuthor.decode(text_encoding) != blb.authors[0]: # changed.
changed = True
if book.bookAbstract.decode(text_encoding) != blb.comments:
changed = True changed = True
# if book.bookName.decode(text_encoding) != blb.title:
# changed = True
# if book.bookAuthor.decode(text_encoding) != blb.authors[0]:
# changed = True
# if book.bookAbstract.decode(text_encoding) != blb.comments:
# changed = True
return changed return changed
@staticmethod @staticmethod

View File

@ -108,6 +108,8 @@ class PrivBookInfo(ctypes.Structure):
# extern "C"_declspec(dllexport) BB_RESULT BambookConnect(const char* lpszIP, int timeOut, BB_HANDLE* hConn); # extern "C"_declspec(dllexport) BB_RESULT BambookConnect(const char* lpszIP, int timeOut, BB_HANDLE* hConn);
def BambookConnect(ip = DEFAULT_BAMBOOK_IP, timeout = 0): def BambookConnect(ip = DEFAULT_BAMBOOK_IP, timeout = 0):
if isinstance(ip, unicode):
ip = ip.encode('ascii')
handle = ctypes.c_int(0) handle = ctypes.c_int(0)
if lib_handle == None: if lib_handle == None:
raise Exception(_('Bambook SDK has not been installed.')) raise Exception(_('Bambook SDK has not been installed.'))
@ -187,6 +189,8 @@ def BambookGetNextPrivBookInfo(handle, bookInfo):
# extern "C" BB_RESULT BambookDeletePrivBook(BB_HANDLE hConn, const char * lpszBookID); # extern "C" BB_RESULT BambookDeletePrivBook(BB_HANDLE hConn, const char * lpszBookID);
def BambookDeletePrivBook(handle, guid): def BambookDeletePrivBook(handle, guid):
if isinstance(guid, unicode):
guid = guid.encode('ascii')
ret = lib_handle.BambookDeletePrivBook(handle, guid) ret = lib_handle.BambookDeletePrivBook(handle, guid)
if ret == BR_SUCC: if ret == BR_SUCC:
return True return True
@ -210,8 +214,8 @@ class JobQueue:
return maxid return maxid
def FinishJob(self, jobID, status): def FinishJob(self, jobID, status):
self.jobs[jobID][0].set()
self.jobs[jobID] = (self.jobs[jobID][0], status) self.jobs[jobID] = (self.jobs[jobID][0], status)
self.jobs[jobID][0].set()
def WaitJob(self, jobID): def WaitJob(self, jobID):
self.jobs[jobID][0].wait() self.jobs[jobID][0].wait()
@ -247,6 +251,8 @@ def BambookAddPrivBook(handle, filename, callback, userData):
def BambookReplacePrivBook(handle, filename, bookID, callback, userData): def BambookReplacePrivBook(handle, filename, bookID, callback, userData):
if isinstance(filename, unicode): if isinstance(filename, unicode):
filename = filename.encode('ascii') filename = filename.encode('ascii')
if isinstance(bookID, unicode):
bookID = bookID.encode('ascii')
ret = lib_handle.BambookReplacePrivBook(handle, filename, bookID, callback, userData) ret = lib_handle.BambookReplacePrivBook(handle, filename, bookID, callback, userData)
if ret == BR_SUCC: if ret == BR_SUCC:
return True return True
@ -258,6 +264,8 @@ def BambookReplacePrivBook(handle, filename, bookID, callback, userData):
def BambookFetchPrivBook(handle, bookID, filename, callback, userData): def BambookFetchPrivBook(handle, bookID, filename, callback, userData):
if isinstance(filename, unicode): if isinstance(filename, unicode):
filename = filename.encode('ascii') filename = filename.encode('ascii')
if isinstance(bookID, unicode):
bookID = bookID.encode('ascii')
ret = lib_handle.BambookFetchPrivBook(handle, bookID, filename, bambookTransferCallback, userData) ret = lib_handle.BambookFetchPrivBook(handle, bookID, filename, bambookTransferCallback, userData)
if ret == BR_SUCC: if ret == BR_SUCC:
return True return True
@ -275,6 +283,10 @@ def BambookVerifySnbFile(filename):
# BB_RESULT BambookPackSnbFromDir ( const char * snbName,, const char * rootDir ); # BB_RESULT BambookPackSnbFromDir ( const char * snbName,, const char * rootDir );
def BambookPackSnbFromDir(snbFileName, rootDir): def BambookPackSnbFromDir(snbFileName, rootDir):
if isinstance(snbFileName, unicode):
snbFileName = snbFileName.encode('ascii')
if isinstance(rootDir, unicode):
rootDir = rootDir.encode('ascii')
ret = lib_handle.BambookPackSnbFromDir(snbFileName, rootDir) ret = lib_handle.BambookPackSnbFromDir(snbFileName, rootDir)
if ret == BR_SUCC: if ret == BR_SUCC:
return True return True
@ -283,6 +295,12 @@ def BambookPackSnbFromDir(snbFileName, rootDir):
# BB_RESULT BambookUnpackFileFromSnb ( const char * snbName,, const char * relativePath, const char * outfname ); # BB_RESULT BambookUnpackFileFromSnb ( const char * snbName,, const char * relativePath, const char * outfname );
def BambookUnpackFileFromSnb(snbFileName, relPath, outFileName): def BambookUnpackFileFromSnb(snbFileName, relPath, outFileName):
if isinstance(snbFileName, unicode):
snbFileName = snbFileName.encode('ascii')
if isinstance(relPath, unicode):
relPath = relPath.encode('ascii')
if isinstance(outFileName, unicode):
outFileName = outFileName.encode('ascii')
ret = lib_handle.BambookUnpackFileFromSnb(snbFileName, relPath, outFileName) ret = lib_handle.BambookUnpackFileFromSnb(snbFileName, relPath, outFileName)
if ret == BR_SUCC: if ret == BR_SUCC:
return True return True
@ -426,19 +444,20 @@ if __name__ == "__main__":
else: else:
failed() failed()
print "Verify SNB File" print "Verify good SNB File"
if bb.VerifySNB(u'/tmp/f2pioq3qf68h475.snb'): if bb.VerifySNB(u'/tmp/f8268e6c1f4e78c.snb'):
passed() passed()
else: else:
failed() failed()
print "Verify bad SNB File"
if not bb.VerifySNB('./libwrapper.py'): if not bb.VerifySNB('./libwrapper.py'):
passed() passed()
else: else:
failed() failed()
print "Extract SNB File" print "Extract SNB File"
if bb.ExtractSNB('./test.snb', '/tmp'): if bb.ExtractSNB('./test.snb', '/tmp/test'):
passed() passed()
else: else:
failed() failed()
@ -469,7 +488,10 @@ if __name__ == "__main__":
failed() failed()
print "Send file" print "Send file"
bb.SendFile('./test.snb') if bb.SendFile('/tmp/tmp.snb'):
passed()
else:
failed()
print "Get book list" print "Get book list"
books = bb.GetBookList() books = bb.GetBookList()
@ -479,7 +501,7 @@ if __name__ == "__main__":
failed() failed()
print "Get book" print "Get book"
if bb.GetFile('f2pioq3qf68h475.snb', '/tmp') and bb.VerifySNB('/tmp/f2pioq3qf68h475.snb'): if bb.GetFile('f8268e6c1f4e78c.snb', '/tmp') and bb.VerifySNB('/tmp/f8268e6c1f4e78c.snb'):
passed() passed()
else: else:
failed() failed()