A Python UPnP Media Server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
6.9 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2006 John-Mark Gurney <gurney_j@resnet.uroegon.edu>
  3. #
  4. # $Id$
  5. #
  6. import itertools
  7. import os.path
  8. import sets
  9. import time
  10. import iterzipfile
  11. zipfile = iterzipfile
  12. import itertarfile
  13. tarfile = itertarfile
  14. import FileDIDL
  15. from DIDLLite import StorageFolder, Item, VideoItem, AudioItem, TextItem, ImageItem, Resource
  16. from FSStorage import FSObject, registerklassfun
  17. from twisted.python import threadable, log
  18. from twisted.spread import pb
  19. from twisted.web import http
  20. from twisted.web import server
  21. from twisted.web import resource
  22. def inserthierdict(d, name, obj):
  23. if not name:
  24. return
  25. i = name.find('/')
  26. if i == -1:
  27. d[name] = obj
  28. return
  29. dname = name[:i]
  30. rname = name[i + 1:]
  31. # remaining path components
  32. try:
  33. inserthierdict(d[dname], rname, obj)
  34. except KeyError:
  35. d[dname] = {}
  36. inserthierdict(d[dname], rname, obj)
  37. def buildNameHier(names, objs):
  38. ret = {}
  39. for n, o in itertools.izip(names, objs):
  40. inserthierdict(ret, n, o)
  41. return ret
  42. class ZipFileTransfer(pb.Viewable):
  43. def __init__(self, zf, name, request):
  44. self.zf = zf
  45. self.size = zf.getinfo(name).file_size
  46. self.iter = zf.readiter(name)
  47. self.request = request
  48. self.written = 0
  49. request.registerProducer(self, 0)
  50. def resumeProducing(self):
  51. if not self.request:
  52. return
  53. # get data and write to request.
  54. try:
  55. data = self.iter.next()
  56. if data:
  57. self.written += len(data)
  58. # this .write will spin the reactor, calling
  59. # .doWrite and then .resumeProducing again, so
  60. # be prepared for a re-entrant call
  61. self.request.write(data)
  62. except StopIteration:
  63. if self.request:
  64. self.request.unregisterProducer()
  65. self.request.finish()
  66. self.request = None
  67. def pauseProducing(self):
  68. pass
  69. def stopProducing(self):
  70. # close zipfile
  71. self.request = None
  72. # Remotely relay producer interface.
  73. def view_resumeProducing(self, issuer):
  74. self.resumeProducing()
  75. def view_pauseProducing(self, issuer):
  76. self.pauseProducing()
  77. def view_stopProducing(self, issuer):
  78. self.stopProducing()
  79. synchronized = ['resumeProducing', 'stopProducing']
  80. threadable.synchronize(ZipFileTransfer)
  81. class ZipResource(resource.Resource):
  82. # processors = {}
  83. isLeaf = True
  84. def __init__(self, zf, name, mt):
  85. resource.Resource.__init__(self)
  86. self.zf = zf
  87. self.zi = zf.getinfo(name)
  88. self.name = name
  89. self.mt = mt
  90. def getFileSize(self):
  91. return self.zi.file_size
  92. def render(self, request):
  93. request.setHeader('content-type', self.mt)
  94. # We could possibly send the deflate data directly!
  95. if None and self.encoding:
  96. request.setHeader('content-encoding', self.encoding)
  97. if request.setLastModified(time.mktime(list(self.zi.date_time) +
  98. [ 0, 0, -1])) is http.CACHED:
  99. return ''
  100. request.setHeader('content-length', str(self.getFileSize()))
  101. if request.method == 'HEAD':
  102. return ''
  103. # return data
  104. ZipFileTransfer(self.zf, self.name, request)
  105. # and make sure the connection doesn't get closed
  106. return server.NOT_DONE_YET
  107. class ZipItem:
  108. '''Basic zip stuff initalization'''
  109. def __init__(self, *args, **kwargs):
  110. self.zo = kwargs['zo']
  111. del kwargs['zo']
  112. self.zf = kwargs['zf']
  113. del kwargs['zf']
  114. self.name = kwargs['name']
  115. del kwargs['name']
  116. def checkUpdate(self):
  117. self.doUpdate()
  118. return self.zo.checkUpdate()
  119. class ZipFile(ZipItem, Item):
  120. def __init__(self, *args, **kwargs):
  121. self.mimetype = kwargs['mimetype']
  122. del kwargs['mimetype']
  123. ZipItem.__init__(self, *args, **kwargs)
  124. self.zi = self.zf.getinfo(self.name)
  125. kwargs['content'] = ZipResource(self.zf, self.name,
  126. self.mimetype)
  127. Item.__init__(self, *args, **kwargs)
  128. self.url = '%s/%s' % (self.cd.urlbase, self.id)
  129. def doUpdate(self):
  130. self.res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
  131. self.res.size = self.zi.file_size
  132. Item.doUpdate(self)
  133. class ZipChildDir(ZipItem, StorageFolder):
  134. '''This is to represent a child dir of the zip file.'''
  135. def __init__(self, *args, **kwargs):
  136. self.hier = kwargs['hier']
  137. del kwargs['hier']
  138. ZipItem.__init__(self, *args, **kwargs)
  139. del kwargs['zf'], kwargs['zo'], kwargs['name']
  140. StorageFolder.__init__(self, *args, **kwargs)
  141. # mapping from path to objectID
  142. self.pathObjmap = {}
  143. def doUpdate(self):
  144. children = sets.Set(self.hier.keys())
  145. for i in self.pathObjmap.keys():
  146. if i not in children:
  147. # delete
  148. self.cd.delItem(self.pathObjmap[i])
  149. del self.pathObjmap[i]
  150. for i in children:
  151. if i in self.pathObjmap:
  152. continue
  153. # new object
  154. pathname = os.path.join(self.name, i)
  155. if isinstance(self.hier[i], dict):
  156. # must be a dir
  157. self.pathObjmap[i] = self.cd.addItem(self.id,
  158. ZipChildDir, i, zf = self.zf, zo = self,
  159. name = pathname, hier = self.hier[i])
  160. else:
  161. klass, mt = FileDIDL.buildClassMT(ZipFile, i)
  162. if klass is None:
  163. continue
  164. self.pathObjmap[i] = self.cd.addItem(self.id,
  165. klass, i, zf = self.zf, zo = self,
  166. name = pathname, mimetype = mt)
  167. # sort our children
  168. self.sort(lambda x, y: cmp(x.title, y.title))
  169. def __repr__(self):
  170. return '<ZipChildDir: len: %d>' % len(self.pathObjmap)
  171. def genZipFile(path):
  172. try:
  173. return zipfile.ZipFile(path)
  174. except:
  175. import traceback
  176. traceback.print_exc(file=log.logfile)
  177. pass
  178. log.msg('trying tar now:', `path`)
  179. try:
  180. # Try to see if it's a tar file
  181. if path[-2:] == 'gz':
  182. comp = tarfile.TAR_GZIPPED
  183. elif path[-3:] == 'bz2':
  184. comp = tarfile.TAR_BZ2
  185. else:
  186. comp = tarfile.TAR_PLAIN
  187. return tarfile.TarFileCompat(path, compression=comp)
  188. except:
  189. import traceback
  190. traceback.print_exc(file=log.logfile)
  191. raise
  192. class ZipObject(FSObject, StorageFolder):
  193. def __init__(self, *args, **kwargs):
  194. '''If a zip argument is passed it, use that as the zip archive.'''
  195. path = kwargs['path']
  196. del kwargs['path']
  197. StorageFolder.__init__(self, *args, **kwargs)
  198. FSObject.__init__(self, path)
  199. # mapping from path to objectID
  200. self.pathObjmap = {}
  201. def doUpdate(self):
  202. # open the zipfile as necessary.
  203. self.zip = genZipFile(self.FSpath)
  204. hier = buildNameHier(self.zip.namelist(), self.zip.infolist())
  205. children = sets.Set(hier.keys())
  206. for i in self.pathObjmap.keys():
  207. if i not in children:
  208. # delete
  209. self.cd.delItem(self.pathObjmap[i])
  210. del self.pathObjmap[i]
  211. for i in children:
  212. if i in self.pathObjmap:
  213. continue
  214. # new object
  215. if isinstance(hier[i], dict):
  216. # must be a dir
  217. self.pathObjmap[i] = self.cd.addItem(self.id,
  218. ZipChildDir, i, zf = self.zip, zo = self,
  219. name = i, hier = hier[i])
  220. else:
  221. klass, mt = FileDIDL.buildClassMT(ZipFile, i)
  222. if klass is None:
  223. continue
  224. self.pathObjmap[i] = self.cd.addItem(self.id,
  225. klass, i, zf = self.zip, zo = self,
  226. name = i, mimetype = mt)
  227. # sort our children
  228. self.sort(lambda x, y: cmp(x.title, y.title))
  229. def __repr__(self):
  230. return '<ZipObject: path: %s>' % len(self.path)
  231. def detectzipfile(path, fobj):
  232. try:
  233. genZipFile(path)
  234. except:
  235. return None, None
  236. return ZipObject, { 'path': path }
  237. registerklassfun(detectzipfile)