Raising pylint scores for libprs500/*.py

This commit is contained in:
Kovid Goyal 2006-12-19 01:50:00 +00:00
parent 3d7d6a862a
commit 6010e9b2ca
6 changed files with 1691 additions and 1639 deletions

View File

@ -12,152 +12,200 @@
## You should have received a copy of the GNU General Public License along ## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
""" This module contains the logic for dealing with XML book lists found in the reader cache """ """
This module contains the logic for dealing with XML book lists found
in the reader cache.
"""
from xml.dom.ext import PrettyPrint from xml.dom.ext import PrettyPrint
import xml.dom.minidom as dom import xml.dom.minidom as dom
from base64 import b64decode as decode from base64 import b64decode as decode
from base64 import b64encode as encode from base64 import b64encode as encode
import time import time
MIME_MAP = { "lrf":"application/x-sony-bbeb", "rtf":"application/rtf", "pdf":"application/pdf", "txt":"text/plain" } MIME_MAP = { \
"lrf":"application/x-sony-bbeb", \
"rtf":"application/rtf", \
"pdf":"application/pdf", \
"txt":"text/plain" \
}
class book_metadata_field(object): class book_metadata_field(object):
def __init__(self, attr, formatter=None, setter=None): """ Represents metadata stored as an attribute """
self.attr = attr def __init__(self, attr, formatter=None, setter=None):
self.formatter = formatter self.attr = attr
self.setter = setter self.formatter = formatter
self.setter = setter
def __get__(self, obj, typ=None):
""" Return a string. String may be empty if self.attr is absent """ def __get__(self, obj, typ=None):
return self.formatter(obj.elem.getAttribute(self.attr)) if self.formatter else obj.elem.getAttribute(self.attr).strip() """ Return a string. String may be empty if self.attr is absent """
return self.formatter(obj.elem.getAttribute(self.attr)) if \
def __set__(self, obj, val): self.formatter else obj.elem.getAttribute(self.attr).strip()
val = self.setter(val) if self.setter else val
obj.elem.setAttribute(self.attr, str(val)) def __set__(self, obj, val):
""" Set the attribute """
val = self.setter(val) if self.setter else val
obj.elem.setAttribute(self.attr, str(val))
class Book(object): class Book(object):
""" Provides a view onto the XML element that represents a book """
title = book_metadata_field("title") title = book_metadata_field("title")
author = book_metadata_field("author", formatter=lambda x: x if x.strip() else "Unknown") author = book_metadata_field("author", \
formatter=lambda x: x if x.strip() else "Unknown")
mime = book_metadata_field("mime") mime = book_metadata_field("mime")
rpath = book_metadata_field("path") rpath = book_metadata_field("path")
id = book_metadata_field("id", formatter=int) id = book_metadata_field("id", formatter=int)
sourceid = book_metadata_field("sourceid", formatter=int) sourceid = book_metadata_field("sourceid", formatter=int)
size = book_metadata_field("size", formatter=int) size = book_metadata_field("size", formatter=int)
# When setting this attribute you must use an epoch # When setting this attribute you must use an epoch
datetime = book_metadata_field("date", formatter=lambda x: time.strptime(x, "%a, %d %b %Y %H:%M:%S %Z"), setter=lambda x: time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(x))) datetime = book_metadata_field("date", \
formatter=lambda x: time.strptime(x, "%a, %d %b %Y %H:%M:%S %Z"),
setter=lambda x: time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(x)))
@apply @apply
def thumbnail(): def thumbnail():
def fget(self): doc = \
th = self.elem.getElementsByTagName(self.prefix + "thumbnail") """
if len(th): The thumbnail. Should be a height 68 image.
for n in th[0].childNodes: Setting is not supported.
if n.nodeType == n.ELEMENT_NODE: """
th = n def fget(self):
break th = self.elem.getElementsByTagName(self.prefix + "thumbnail")
rc = "" if len(th):
for node in th.childNodes: for n in th[0].childNodes:
if node.nodeType == node.TEXT_NODE: rc += node.data if n.nodeType == n.ELEMENT_NODE:
return decode(rc) th = n
return property(**locals()) break
rc = ""
for node in th.childNodes:
if node.nodeType == node.TEXT_NODE:
rc += node.data
return decode(rc)
return property(fget=fget, doc=doc)
@apply @apply
def path(): def path():
def fget(self): return self.root + self.rpath doc = """ Absolute path to book on device. Setting not supported. """
return property(**locals()) def fget(self):
return self.root + self.rpath
return property(fget=fget, doc=doc)
def __init__(self, node, prefix="xs1:", root="/Data/media/"): def __init__(self, node, prefix="xs1:", root="/Data/media/"):
self.elem = node self.elem = node
self.prefix = prefix self.prefix = prefix
self.root = root self.root = root
def __repr__(self): def __repr__(self):
return self.title + " by " + self.author+ " at " + self.path return self.title + " by " + self.author+ " at " + self.path
def __str__(self): def __str__(self):
return self.__repr__() return self.__repr__()
def fix_ids(media, cache): def fix_ids(media, cache):
id = 0 """
for child in media.root.childNodes: Update ids in media, cache to be consistent with their
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("id"): current structure
child.setAttribute("id", str(id)) """
id += 1 cid = 0
mmaxid = id - 1 for child in media.root.childNodes:
id = mmaxid + 2 if child.nodeType == child.ELEMENT_NODE and \
if len(cache): child.hasAttribute("id"):
for child in cache.root.childNodes: child.setAttribute("id", str(cid))
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("sourceid"): cid += 1
child.setAttribute("sourceid", str(mmaxid+1)) mmaxid = cid - 1
child.setAttribute("id", str(id)) cid = mmaxid + 2
id += 1 if len(cache):
media.document.documentElement.setAttribute("nextID", str(id)) for child in cache.root.childNodes:
if child.nodeType == child.ELEMENT_NODE and \
child.hasAttribute("sourceid"):
child.setAttribute("sourceid", str(mmaxid+1))
child.setAttribute("id", str(cid))
cid += 1
media.document.documentElement.setAttribute("nextID", str(cid))
class BookList(list): class BookList(list):
__getslice__ = None """
__setslice__ = None A list of L{Book}s. Created from an XML file. Can write list
to an XML file.
def __init__(self, prefix="xs1:", root="/Data/media/", file=None): """
list.__init__(self) __getslice__ = None
if file: __setslice__ = None
self.prefix = prefix
self.proot = root
file.seek(0)
self.document = dom.parse(file)
self.root = self.document.documentElement #: The root element containing all records
if prefix == "xs1:": self.root = self.root.getElementsByTagName("records")[0]
for book in self.document.getElementsByTagName(self.prefix + "text"): self.append(Book(book, root=root, prefix=prefix))
def max_id(self):
id = -1
for child in self.root.childNodes:
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("id"):
c = int(child.getAttribute("id"))
if c > id: id = c
return id
def has_id(self, id):
""" Check if a book with id C{ == id} exists already. This *does not* check if id exists in the underlying XML file """
ans = False
for book in self:
if book.id == id:
ans = True
break
return ans
def delete_book(self, id):
node = None
for book in self:
if book.id == id:
node = book
self.remove(book)
break
node.elem.parentNode.removeChild(node.elem)
node.elem.unlink()
def add_book(self, info, name, size, ctime):
node = self.document.createElement(self.prefix + "text")
mime = MIME_MAP[name[name.rfind(".")+1:]]
id = self.max_id()+1
sourceid = str(self[0].sourceid) if len(self) else "1"
attrs = { "title":info["title"], "author":info["authors"], "page":"0", "part":"0", "scale":"0", "sourceid":sourceid, "id":str(id), "date":"", "mime":mime, "path":name, "size":str(size)}
for attr in attrs.keys():
node.setAttributeNode(self.document.createAttribute(attr))
node.setAttribute(attr, attrs[attr])
w, h, data = info["cover"]
if data:
th = self.document.createElement(self.prefix + "thumbnail")
th.setAttribute("width", str(w))
th.setAttribute("height", str(h))
jpeg = self.document.createElement(self.prefix + "jpeg")
jpeg.appendChild(self.document.createTextNode(encode(data)))
th.appendChild(jpeg)
node.appendChild(th)
self.root.appendChild(node)
book = Book(node, root=self.proot, prefix=self.prefix)
book.datetime = ctime
self.append(book)
def write(self, stream): def __init__(self, prefix="xs1:", root="/Data/media/", sfile=None):
PrettyPrint(self.document, stream) list.__init__(self)
if sfile:
self.prefix = prefix
self.proot = root
sfile.seek(0)
self.document = dom.parse(sfile)
# The root element containing all records
self.root = self.document.documentElement
if prefix == "xs1:":
self.root = self.root.getElementsByTagName("records")[0]
for book in self.document.getElementsByTagName(self.prefix + "text"):
self.append(Book(book, root=root, prefix=prefix))
def max_id(self):
""" Highest id in underlying XML file """
cid = -1
for child in self.root.childNodes:
if child.nodeType == child.ELEMENT_NODE and \
child.hasAttribute("id"):
c = int(child.getAttribute("id"))
if c > cid:
cid = c
return cid
def has_id(self, cid):
"""
Check if a book with id C{ == cid} exists already.
This *does not* check if id exists in the underlying XML file
"""
ans = False
for book in self:
if book.id == cid:
ans = True
break
return ans
def delete_book(self, cid):
""" Remove DOM node corresponding to book with C{id == cid}."""
node = None
for book in self:
if book.id == cid:
node = book
self.remove(book)
break
node.elem.parentNode.removeChild(node.elem)
node.elem.unlink()
def add_book(self, info, name, size, ctime):
""" Add a node into DOM tree representing a book """
node = self.document.createElement(self.prefix + "text")
mime = MIME_MAP[name[name.rfind(".")+1:]]
cid = self.max_id()+1
sourceid = str(self[0].sourceid) if len(self) else "1"
attrs = { "title":info["title"], "author":info["authors"], \
"page":"0", "part":"0", "scale":"0", \
"sourceid":sourceid, "id":str(cid), "date":"", \
"mime":mime, "path":name, "size":str(size)}
for attr in attrs.keys():
node.setAttributeNode(self.document.createAttribute(attr))
node.setAttribute(attr, attrs[attr])
w, h, data = info["cover"]
if data:
th = self.document.createElement(self.prefix + "thumbnail")
th.setAttribute("width", str(w))
th.setAttribute("height", str(h))
jpeg = self.document.createElement(self.prefix + "jpeg")
jpeg.appendChild(self.document.createTextNode(encode(data)))
th.appendChild(jpeg)
node.appendChild(th)
self.root.appendChild(node)
book = Book(node, root=self.proot, prefix=self.prefix)
book.datetime = ctime
self.append(book)
def write(self, stream):
""" Write XML representation of DOM tree to C{stream} """
PrettyPrint(self.document, stream)

File diff suppressed because it is too large Load Diff

View File

@ -17,53 +17,55 @@ Defines the errors that libprs500 generates.
G{classtree ProtocolError} G{classtree ProtocolError}
""" """
from exceptions import Exception
class ProtocolError(Exception): class ProtocolError(Exception):
""" The base class for all exceptions in this package """ """ The base class for all exceptions in this package """
def __init__(self, msg): def __init__(self, msg):
Exception.__init__(self, msg) Exception.__init__(self, msg)
class TimeoutError(ProtocolError): class TimeoutError(ProtocolError):
""" There was a timeout during communication """ """ There was a timeout during communication """
def __init__(self, func_name): def __init__(self, func_name):
ProtocolError.__init__(self, "There was a timeout while communicating with the device in function: "+func_name) ProtocolError.__init__(self, \
"There was a timeout while communicating with the device in function: "\
+func_name)
class DeviceError(ProtocolError): class DeviceError(ProtocolError):
""" Raised when device is not found """ """ Raised when device is not found """
def __init__(self): def __init__(self):
ProtocolError.__init__(self, "Unable to find SONY Reader. Is it connected?") ProtocolError.__init__(self, \
"Unable to find SONY Reader. Is it connected?")
class DeviceBusy(ProtocolError): class DeviceBusy(ProtocolError):
""" Raised when device is busy """ """ Raised when device is busy """
def __init__(self): def __init__(self):
ProtocolError.__init__(self, "Device is in use by another application") ProtocolError.__init__(self, "Device is in use by another application")
class PacketError(ProtocolError): class PacketError(ProtocolError):
""" Errors with creating/interpreting packets """ """ Errors with creating/interpreting packets """
class FreeSpaceError(ProtocolError): class FreeSpaceError(ProtocolError):
""" Errors caused when trying to put files onto an overcrowded device """ """ Errors caused when trying to put files onto an overcrowded device """
class ArgumentError(ProtocolError): class ArgumentError(ProtocolError):
""" Errors caused by invalid arguments to a public interface function """ """ Errors caused by invalid arguments to a public interface function """
class PathError(ArgumentError): class PathError(ArgumentError):
""" When a user supplies an incorrect/invalid path """ """ When a user supplies an incorrect/invalid path """
class ControlError(ProtocolError): class ControlError(ProtocolError):
""" Errors in Command/Response pairs while communicating with the device """ """ Errors in Command/Response pairs while communicating with the device """
def __init__(self, query=None, response=None, desc=None): def __init__(self, query=None, response=None, desc=None):
self.query = query self.query = query
self.response = response self.response = response
Exception.__init__(self, desc) ProtocolError.__init__(self, desc)
def __str__(self): def __str__(self):
if self.query and self.response: if self.query and self.response:
return "Got unexpected response:\n" + \ return "Got unexpected response:\n" + \
"query:\n"+str(self.query.query)+"\n"+\ "query:\n"+str(self.query.query)+"\n"+\
"expected:\n"+str(self.query.response)+"\n" +\ "expected:\n"+str(self.query.response)+"\n" +\
"actual:\n"+str(self.response) "actual:\n"+str(self.response)
if self.desc: if self.desc:
return self.desc return self.desc
return "Unknown control error occurred" return "Unknown control error occurred"

View File

@ -487,4 +487,5 @@ def main():
lock = LockFile(lock) lock = LockFile(lock)
return app.exec_() return app.exec_()
if __name__ == "__main__": sys.exit(main()) if __name__ == "__main__":
sys.exit(main())

File diff suppressed because it is too large Load Diff

View File

@ -1,239 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Project SYSTEM "Project-4.0.dtd">
<!-- eric4 project file for project prs-500 -->
<!-- Saved: 2006-12-08, 23:24:29 -->
<!-- Copyright (C) 2006 Kovid Goyal, kovid@kovidgoyal.net -->
<Project version="4.0">
<ProgLanguage mixed="0">Python</ProgLanguage>
<UIType>Qt4</UIType>
<Description>Library to communicate with the Sony Reader PRS-500 via USB</Description>
<Version></Version>
<Author>Kovid Goyal</Author>
<Email>kovid@kovidgoyal.net</Email>
<Sources>
<Source>
<Dir>libprs500</Dir>
<Name>communicate.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Name>prstypes.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Name>errors.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Name>__init__.py</Name>
</Source>
<Source>
<Name>setup.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>cli</Dir>
<Name>terminfo.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>cli</Dir>
<Name>main.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>cli</Dir>
<Name>__init__.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>main.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>__init__.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>lrf</Dir>
<Name>meta.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>lrf</Dir>
<Name>__init__.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>database.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>editbook.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Name>books.py</Name>
</Source>
<Source>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>widgets.py</Name>
</Source>
</Sources>
<Forms>
<Form>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>main.ui</Name>
</Form>
<Form>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>editbook.ui</Name>
</Form>
</Forms>
<Translations>
</Translations>
<Resources>
</Resources>
<Interfaces>
</Interfaces>
<Others>
<Other>
<Name>epydoc.conf</Name>
</Other>
<Other>
<Name>epydoc-pdf.conf</Name>
</Other>
</Others>
<MainScript>
<Dir>libprs500</Dir>
<Dir>gui</Dir>
<Name>main.py</Name>
</MainScript>
<Vcs>
<VcsType>Subversion</VcsType>
<VcsOptions>
<dict>
<key>
<string>status</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>log</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>global</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>update</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>remove</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>add</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>tag</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>export</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>commit</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>diff</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>checkout</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
<key>
<string>history</string>
</key>
<value>
<list>
<string></string>
</list>
</value>
</dict>
</VcsOptions>
<VcsOtherData>
<dict>
<key>
<string>standardLayout</string>
</key>
<value>
<bool>True</bool>
</value>
</dict>
</VcsOtherData>
</Vcs>
<FiletypeAssociations>
<FiletypeAssociation pattern="*.py" type="SOURCES" />
<FiletypeAssociation pattern="*.ui.h" type="FORMS" />
<FiletypeAssociation pattern="*.idl" type="INTERFACES" />
<FiletypeAssociation pattern="*.ui" type="FORMS" />
<FiletypeAssociation pattern="*.ptl" type="SOURCES" />
</FiletypeAssociations>
</Project>