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
## with this program; if not, write to the Free Software Foundation, Inc.,
## 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
import xml.dom.minidom as dom
from base64 import b64decode as decode
from base64 import b64encode as encode
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):
def __init__(self, attr, formatter=None, setter=None):
self.attr = attr
self.formatter = formatter
self.setter = setter
""" Represents metadata stored as an attribute """
def __init__(self, attr, formatter=None, setter=None):
self.attr = attr
self.formatter = formatter
self.setter = setter
def __get__(self, obj, typ=None):
""" Return a string. String may be empty if self.attr is absent """
return self.formatter(obj.elem.getAttribute(self.attr)) if self.formatter else obj.elem.getAttribute(self.attr).strip()
def __get__(self, obj, typ=None):
""" Return a string. String may be empty if self.attr is absent """
return self.formatter(obj.elem.getAttribute(self.attr)) if \
self.formatter else obj.elem.getAttribute(self.attr).strip()
def __set__(self, obj, val):
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):
""" Provides a view onto the XML element that represents a book """
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")
rpath = book_metadata_field("path")
id = book_metadata_field("id", formatter=int)
sourceid = book_metadata_field("sourceid", formatter=int)
size = book_metadata_field("size", formatter=int)
# 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
def thumbnail():
def fget(self):
th = self.elem.getElementsByTagName(self.prefix + "thumbnail")
if len(th):
for n in th[0].childNodes:
if n.nodeType == n.ELEMENT_NODE:
th = n
break
rc = ""
for node in th.childNodes:
if node.nodeType == node.TEXT_NODE: rc += node.data
return decode(rc)
return property(**locals())
doc = \
"""
The thumbnail. Should be a height 68 image.
Setting is not supported.
"""
def fget(self):
th = self.elem.getElementsByTagName(self.prefix + "thumbnail")
if len(th):
for n in th[0].childNodes:
if n.nodeType == n.ELEMENT_NODE:
th = n
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
def path():
def fget(self): return self.root + self.rpath
return property(**locals())
doc = """ Absolute path to book on device. Setting not supported. """
def fget(self):
return self.root + self.rpath
return property(fget=fget, doc=doc)
def __init__(self, node, prefix="xs1:", root="/Data/media/"):
self.elem = node
self.prefix = prefix
self.root = root
self.elem = node
self.prefix = prefix
self.root = root
def __repr__(self):
return self.title + " by " + self.author+ " at " + self.path
return self.title + " by " + self.author+ " at " + self.path
def __str__(self):
return self.__repr__()
return self.__repr__()
def fix_ids(media, cache):
id = 0
for child in media.root.childNodes:
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("id"):
child.setAttribute("id", str(id))
id += 1
mmaxid = id - 1
id = mmaxid + 2
if len(cache):
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(id))
id += 1
media.document.documentElement.setAttribute("nextID", str(id))
"""
Update ids in media, cache to be consistent with their
current structure
"""
cid = 0
for child in media.root.childNodes:
if child.nodeType == child.ELEMENT_NODE and \
child.hasAttribute("id"):
child.setAttribute("id", str(cid))
cid += 1
mmaxid = cid - 1
cid = mmaxid + 2
if len(cache):
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):
__getslice__ = None
__setslice__ = None
"""
A list of L{Book}s. Created from an XML file. Can write list
to an XML file.
"""
__getslice__ = None
__setslice__ = None
def __init__(self, prefix="xs1:", root="/Data/media/", file=None):
list.__init__(self)
if file:
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 __init__(self, prefix="xs1:", root="/Data/media/", sfile=None):
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):
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 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, 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 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, 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 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):
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 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):
PrettyPrint(self.document, stream)
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}
"""
from exceptions import Exception
class ProtocolError(Exception):
""" The base class for all exceptions in this package """
def __init__(self, msg):
Exception.__init__(self, msg)
""" The base class for all exceptions in this package """
def __init__(self, msg):
Exception.__init__(self, msg)
class TimeoutError(ProtocolError):
""" There was a timeout during communication """
def __init__(self, func_name):
ProtocolError.__init__(self, "There was a timeout while communicating with the device in function: "+func_name)
""" There was a timeout during communication """
def __init__(self, func_name):
ProtocolError.__init__(self, \
"There was a timeout while communicating with the device in function: "\
+func_name)
class DeviceError(ProtocolError):
""" Raised when device is not found """
def __init__(self):
ProtocolError.__init__(self, "Unable to find SONY Reader. Is it connected?")
""" Raised when device is not found """
def __init__(self):
ProtocolError.__init__(self, \
"Unable to find SONY Reader. Is it connected?")
class DeviceBusy(ProtocolError):
""" Raised when device is busy """
def __init__(self):
ProtocolError.__init__(self, "Device is in use by another application")
""" Raised when device is busy """
def __init__(self):
ProtocolError.__init__(self, "Device is in use by another application")
class PacketError(ProtocolError):
""" Errors with creating/interpreting packets """
""" Errors with creating/interpreting packets """
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):
""" Errors caused by invalid arguments to a public interface function """
""" Errors caused by invalid arguments to a public interface function """
class PathError(ArgumentError):
""" When a user supplies an incorrect/invalid path """
""" When a user supplies an incorrect/invalid path """
class ControlError(ProtocolError):
""" Errors in Command/Response pairs while communicating with the device """
def __init__(self, query=None, response=None, desc=None):
self.query = query
self.response = response
Exception.__init__(self, desc)
""" Errors in Command/Response pairs while communicating with the device """
def __init__(self, query=None, response=None, desc=None):
self.query = query
self.response = response
ProtocolError.__init__(self, desc)
def __str__(self):
if self.query and self.response:
return "Got unexpected response:\n" + \
def __str__(self):
if self.query and self.response:
return "Got unexpected response:\n" + \
"query:\n"+str(self.query.query)+"\n"+\
"expected:\n"+str(self.query.response)+"\n" +\
"actual:\n"+str(self.response)
if self.desc:
return self.desc
return "Unknown control error occurred"
if self.desc:
return self.desc
return "Unknown control error occurred"

View File

@ -487,4 +487,5 @@ def main():
lock = LockFile(lock)
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>