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.

339 lines
7.8 KiB

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