Le repo des sources pour le site web des JM2L
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.
 
 
 
 
 

599 lines
25 KiB

  1. # -*- coding: utf8 -*-
  2. from pyramid.view import view_config, view_defaults
  3. from pyramid.response import Response
  4. from pyramid.exceptions import NotFound
  5. from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest
  6. from PIL import Image
  7. import re, os, shutil
  8. from os import path
  9. import mimetypes
  10. import magic
  11. import subprocess
  12. try:
  13. from StringIO import StringIO
  14. except ImportError:
  15. from io import StringIO
  16. # Database access imports
  17. from .models import User, Place, Tiers, Event, SallePhy
  18. from .blenderthumbnailer import blend_extract_thumb, write_png
  19. from jm2l.const import CurrentYear
  20. from slugify import slugify
  21. MIN_FILE_SIZE = 1 # bytes
  22. MAX_FILE_SIZE = 500000000 # bytes
  23. IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)')
  24. ACCEPTED_MIMES = ['application/pdf',
  25. 'application/vnd.oasis.opendocument.text',
  26. 'application/vnd.oasis.opendocument.text-template',
  27. 'application/vnd.oasis.opendocument.graphics',
  28. 'application/vnd.oasis.opendocument.graphics-template',
  29. 'application/vnd.oasis.opendocument.presentation',
  30. 'application/vnd.oasis.opendocument.presentation-template',
  31. 'application/vnd.oasis.opendocument.spreadsheet',
  32. 'application/vnd.oasis.opendocument.spreadsheet-template',
  33. 'image/svg+xml',
  34. 'application/x-blender'
  35. ]
  36. ACCEPT_FILE_TYPES = IMAGE_TYPES
  37. THUMBNAIL_SIZE = 80
  38. EXPIRATION_TIME = 300 # seconds
  39. IMAGEPATH = ['images']
  40. DOCPATH = ['document']
  41. THUMBNAILPATH = ['images', 'thumbnails']
  42. # change the following to POST if DELETE isn't supported by the webserver
  43. DELETEMETHOD = "DELETE"
  44. mimetypes.init()
  45. class MediaPath():
  46. def get_all(self, media_table, linked_id, MediaType=None):
  47. filelist = list()
  48. curpath = self.get_mediapath(media_table, linked_id, None)
  49. thumbpath = os.path.join(curpath, 'thumbnails')
  50. if not os.path.isdir(curpath) or not os.path.isdir(thumbpath):
  51. return list()
  52. for f in os.listdir(curpath):
  53. filename, ext = os.path.splitext(f)
  54. if os.path.isdir(os.path.join(curpath, f)):
  55. continue
  56. if f.endswith('.type'):
  57. continue
  58. if f:
  59. ress_url = '/image/%s/%d/%s' % (media_table, linked_id, f.replace(" ", "%20"))
  60. thumb_url = '/image/%s/%d/thumbnails/%s' % (media_table, linked_id, f.replace(" ", "%20"))
  61. if MediaType is None:
  62. if os.path.exists(os.path.join(thumbpath, f + ".jpg")):
  63. filelist.append((ress_url, thumb_url + ".jpg"))
  64. else:
  65. filelist.append((ress_url, thumb_url))
  66. elif MediaType == 'Image' and len(os.path.splitext(filename)[1]) == 0:
  67. filelist.append((ress_url, thumb_url))
  68. elif MediaType == 'Other' and len(os.path.splitext(filename)[1]):
  69. filelist.append((ress_url, thumb_url))
  70. return filelist
  71. def get_list(self, media_table, linked_id, MediaType=None):
  72. filelist = list()
  73. curpath = self.get_mediapath(media_table, linked_id, None)
  74. if not os.path.isdir(curpath):
  75. return list()
  76. for f in os.listdir(curpath):
  77. if os.path.isdir(os.path.join(curpath, f)):
  78. continue
  79. if f.endswith('.type'):
  80. continue
  81. if f:
  82. filename, ext = os.path.splitext(f)
  83. tmpurl = '/image/%s/%d/%s' % (media_table, linked_id, f.replace(" ", "%20"))
  84. if MediaType is None:
  85. filelist.append(tmpurl)
  86. elif MediaType == 'Image' and ext.lower() in ['.gif', '.jpg', '.png', '.svg', '.jpeg']:
  87. filelist.append(tmpurl)
  88. elif MediaType == 'Other' and ext.lower() not in ['.gif', '.jpg', '.png', '.svg', '.jpeg']:
  89. filelist.append(tmpurl)
  90. return filelist
  91. def get_thumb(self, media_table, linked_id, MediaType=None):
  92. filelist = list()
  93. curpath = self.get_mediapath(media_table, linked_id, None)
  94. curpath = os.path.join(curpath, 'thumbnails')
  95. if not os.path.isdir(curpath):
  96. return list()
  97. for f in os.listdir(curpath):
  98. filename, ext = os.path.splitext(f)
  99. if os.path.isdir(os.path.join(curpath, f)):
  100. continue
  101. if f.endswith('.type'):
  102. continue
  103. if f:
  104. tmpurl = '/image/%s/%d/thumbnails/%s' % (media_table, linked_id, f.replace(" ", "%20"))
  105. if MediaType is None:
  106. filelist.append(tmpurl)
  107. elif MediaType == 'Image' and len(os.path.splitext(filename)[1]) == 0:
  108. filelist.append(tmpurl)
  109. elif MediaType == 'Other' and len(os.path.splitext(filename)[1]):
  110. filelist.append(tmpurl)
  111. return filelist
  112. def move_mediapath(self, media_table, from_id, to_id):
  113. """
  114. Move target media folder to follow database
  115. :param media_table: type of media
  116. :param from_id: source
  117. :param to_id: destination
  118. :return: Error if any
  119. """
  120. if media_table in ['tiers', 'place', 'salle', 'users']:
  121. src = IMAGEPATH + [media_table, from_id]
  122. dst = IMAGEPATH + [media_table, to_id]
  123. else:
  124. raise RuntimeError("Sorry, Media '%s' not supported yet for move." % media_table)
  125. src_path = os.path.join('jm2l/upload', *src)
  126. dst_path = os.path.join('jm2l/upload', *dst)
  127. if not os.path.isdir(src_path):
  128. # Nothing to do ...
  129. return False
  130. if os.path.isdir(dst_path):
  131. raise RuntimeError('Destination path already exist')
  132. shutil.move(src_path, dst_path)
  133. return True
  134. def get_mediapath(self, media_table, linked_id, name):
  135. """
  136. :param media_table: type of media
  137. :param linked_id: id of media
  138. :param name: filename
  139. :return: full relative path on server side
  140. """
  141. linked_id = str(linked_id)
  142. if media_table in ['tiers', 'place', 'salle']:
  143. # Retrieve Slug
  144. if media_table == 'tiers':
  145. slug = Tiers.by_id(linked_id).slug
  146. if media_table == 'place':
  147. slug = Place.by_id(linked_id).slug or slugify(Place.by_id(linked_id).name)
  148. if media_table == 'salle':
  149. slug = SallePhy.by_id(linked_id).slug
  150. p = IMAGEPATH + [media_table, slug]
  151. elif media_table == 'presse':
  152. # Use Year in linked_id
  153. p = IMAGEPATH + [media_table, linked_id]
  154. elif media_table == 'tasks':
  155. # Use Current Year
  156. p = IMAGEPATH + [str(CurrentYear), media_table, linked_id]
  157. elif media_table == 'poles':
  158. # Use Current Year
  159. p = IMAGEPATH + [str(CurrentYear), media_table, linked_id]
  160. elif media_table in ['RIB', 'Justif']:
  161. slug = User.by_id(linked_id).slug
  162. p = IMAGEPATH + ['users', slug, media_table]
  163. elif media_table in ['users', 'badge']:
  164. user = User.by_id(linked_id)
  165. if not user:
  166. raise HTTPNotFound()
  167. else:
  168. slug = user.slug
  169. p = IMAGEPATH + [media_table, slug]
  170. elif media_table == 'event':
  171. ev = Event.by_id(linked_id)
  172. slug = ev.slug
  173. year = ev.for_year
  174. p = IMAGEPATH + ['event', str(year), slug]
  175. if name:
  176. p += [name]
  177. TargetPath = os.path.join('jm2l/upload', *p)
  178. if not os.path.isdir(os.path.dirname(TargetPath)):
  179. try:
  180. os.makedirs(os.path.dirname(TargetPath))
  181. except OSError as e:
  182. if e.errno != 17:
  183. raise e
  184. return os.path.join('jm2l/upload', *p)
  185. def ExtMimeIcon(self, mime):
  186. if mime == 'application/pdf':
  187. return "/img/PDF.png"
  188. def check_blend_file(self, fileobj):
  189. head = fileobj.read(12)
  190. fileobj.seek(0)
  191. if head[:2] == b'\x1f\x8b': # gzip magic
  192. import zlib
  193. head = zlib.decompress(fileobj.read(), 31)[:12]
  194. fileobj.seek(0)
  195. if head.startswith(b'BLENDER'):
  196. return True
  197. def get_mimetype_from_file(self, fileobj):
  198. mimetype = magic.from_buffer(fileobj.read(1024), mime=True)
  199. fileobj.seek(0)
  200. # Check if the binary file is a blender file
  201. if (mimetype == "application/octet-stream" or mimetype == "application/x-gzip") and self.check_blend_file(
  202. fileobj):
  203. return "application/x-blender", True
  204. else:
  205. return mimetype, False
  206. def get_mimetype(self, name):
  207. """ This function return the mime-type based on .type file """
  208. try:
  209. with open(self.mediapath(name) + '.type', 'r', 16) as f:
  210. mime = f.read()
  211. return mime
  212. except IOError:
  213. return None
  214. @view_defaults(route_name='media_upload')
  215. class MediaUpload(MediaPath):
  216. def __init__(self, request):
  217. self.request = request
  218. self.media_table = self.request.matchdict.get('media_table')
  219. self.display_only = False
  220. if self.media_table.startswith('_'):
  221. self.display_only = True
  222. self.media_table = self.media_table[1:]
  223. self.linked_id = self.request.matchdict.get('uid')
  224. if not self.linked_id.isdigit():
  225. raise HTTPBadRequest('Wrong Parameter')
  226. request.response.headers['Access-Control-Allow-Origin'] = '*'
  227. request.response.headers['Access-Control-Allow-Methods'] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE'
  228. def mediapath(self, name):
  229. return self.get_mediapath(self.media_table, self.linked_id, name)
  230. def validate(self, result, filecontent):
  231. """ Do some basic check to the uploaded file before to accept it """
  232. # Try to determine mime type from content uploaded
  233. found_mime = magic.from_buffer(filecontent.read(1024), mime=True)
  234. filecontent.seek(0)
  235. # Do a special statement for specific detected mime type
  236. if found_mime in ["application/octet-stream", "application/x-gzip"]:
  237. # Lets see if it's a bender file
  238. if self.check_blend_file(filecontent):
  239. found_mime = "application/x-blender"
  240. # MonKey Patch of content type
  241. result['type'] = found_mime
  242. # Reject mime type that don't match
  243. if found_mime != result['type']:
  244. result['error'] = 'L\'extension du fichier ne correspond pas à son contenu - '
  245. result['error'] += "( %s vs %s )" % (found_mime, result['type'])
  246. return False
  247. # Accept images and mime types listed
  248. if not found_mime in ACCEPTED_MIMES:
  249. if not (IMAGE_TYPES.match(found_mime)):
  250. result['error'] = 'Ce type fichier n\'est malheureusement pas supporté. '
  251. return False
  252. if result['size'] < MIN_FILE_SIZE:
  253. result['error'] = 'le fichier est trop petit'
  254. elif result['size'] > MAX_FILE_SIZE:
  255. result['error'] = 'le fichier est trop voluminueux'
  256. # elif not ACCEPT_FILE_TYPES.match(file['type']):
  257. # file['error'] = u'les type de fichiers acceptés sont png, jpg et gif'
  258. else:
  259. return True
  260. return False
  261. def get_file_size(self, fileobj):
  262. fileobj.seek(0, 2) # Seek to the end of the file
  263. size = fileobj.tell() # Get the position of EOF
  264. fileobj.seek(0) # Reset the file position to the beginning
  265. return size
  266. def thumbnailurl(self, name):
  267. return self.request.route_url('media_view', name='thumbnails',
  268. media_table=self.media_table,
  269. uid=self.linked_id) + '/' + name
  270. def thumbnailpath(self, name):
  271. origin = self.mediapath(name)
  272. TargetPath = os.path.join(os.path.dirname(origin), 'thumbnails', name)
  273. if not os.path.isdir(os.path.dirname(TargetPath)):
  274. os.makedirs(os.path.dirname(TargetPath))
  275. return TargetPath
  276. def createthumbnail(self, filename):
  277. image = Image.open(self.mediapath(filename))
  278. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  279. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  280. timage.paste(
  281. image,
  282. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  283. TargetFileName = self.thumbnailpath(filename)
  284. timage.save(TargetFileName)
  285. return self.thumbnailurl(os.path.basename(TargetFileName))
  286. def pdfthumbnail(self, filename):
  287. TargetFileName = self.thumbnailpath(filename)
  288. Command = ["convert", "./%s[0]" % self.mediapath(filename), "./%s_.jpg" % TargetFileName]
  289. Result = subprocess.call(Command)
  290. if Result == 0:
  291. image = Image.open(TargetFileName + "_.jpg")
  292. pdf_indicator = Image.open("jm2l/static/img/PDF_Thumb_Stamp.png")
  293. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  294. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  295. # Add thumbnail
  296. timage.paste(
  297. image,
  298. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  299. # Stamp with PDF file type
  300. timage.paste(
  301. pdf_indicator,
  302. (timage.size[0] - 30, timage.size[1] - 30),
  303. pdf_indicator,
  304. )
  305. timage.convert('RGB').save(TargetFileName + ".jpg", 'JPEG')
  306. os.unlink(TargetFileName + "_.jpg")
  307. return self.thumbnailurl(os.path.basename(TargetFileName + ".jpg"))
  308. return self.ExtMimeIcon('application/pdf')
  309. def svgthumbnail(self, filename):
  310. TargetFileName = self.thumbnailpath(filename)
  311. Command = ["convert", "./%s[0]" % self.mediapath(filename), "./%s_.jpg" % TargetFileName]
  312. Result = subprocess.call(Command)
  313. if Result == 0:
  314. image = Image.open(TargetFileName + "_.jpg")
  315. pdf_indicator = Image.open("jm2l/static/img/svg-icon.png")
  316. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  317. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  318. # Add thumbnail
  319. timage.paste(
  320. image,
  321. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  322. # Stamp with PDF file type
  323. timage.paste(
  324. pdf_indicator,
  325. (timage.size[0] - 30, timage.size[1] - 30),
  326. pdf_indicator,
  327. )
  328. timage.convert('RGB').save(TargetFileName + ".jpg", 'JPEG')
  329. os.unlink(TargetFileName + "_.jpg")
  330. return self.thumbnailurl(os.path.basename(TargetFileName + ".jpg"))
  331. return self.ExtMimeIcon('image/svg+xml')
  332. def docthumbnail(self, filename):
  333. TargetFileName = self.thumbnailpath(filename)
  334. # let's take the thumbnail generated inside the document
  335. Command = ["unzip", "-p", self.mediapath(filename), "Thumbnails/thumbnail.png"]
  336. ThumbBytes = subprocess.check_output(Command)
  337. image = Image.open(StringIO.StringIO(ThumbBytes))
  338. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  339. # Use the correct stamp
  340. f, ext = os.path.splitext(filename)
  341. istamp = [('Writer', 'odt'),
  342. ('Impress', 'odp'),
  343. ('Calc', 'ods'),
  344. ('Draw', 'odg')]
  345. stampfilename = filter(lambda x, y: ext.endswith(y), istamp)
  346. stamp = Image.open("jm2l/static/img/%s-icon.png" % stampfilename[0][0])
  347. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  348. # Add thumbnail
  349. timage.paste(
  350. image,
  351. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  352. # Stamp with PDF file type
  353. timage.paste(
  354. stamp,
  355. (timage.size[0] - 30, timage.size[1] - 30),
  356. stamp,
  357. )
  358. timage.convert('RGB').save(TargetFileName + ".jpg", 'JPEG')
  359. return self.thumbnailurl(os.path.basename(TargetFileName + ".jpg"))
  360. def blendthumbnail(self, filename):
  361. blendfile = self.mediapath(filename)
  362. # Extract Thumb
  363. if 0:
  364. head = fileobj.read(12)
  365. fileobj.seek(0)
  366. if head[:2] == b'\x1f\x8b': # gzip magic
  367. import zlib
  368. head = zlib.decompress(fileobj.read(), 31)[:12]
  369. fileobj.seek(0)
  370. buf, width, height = blend_extract_thumb(blendfile)
  371. if buf:
  372. png = write_png(buf, width, height)
  373. TargetFileName = self.thumbnailpath(filename)
  374. image = Image.open(StringIO.StringIO(png))
  375. blender_indicator = Image.open("jm2l/static/img/Blender_Thumb_Stamp.png")
  376. image.thumbnail((THUMBNAIL_SIZE, THUMBNAIL_SIZE), Image.ANTIALIAS)
  377. timage = Image.new('RGBA', (THUMBNAIL_SIZE, THUMBNAIL_SIZE), (255, 255, 255, 0))
  378. # Add thumbnail
  379. timage.paste(
  380. image,
  381. ((THUMBNAIL_SIZE - image.size[0]) / 2, (THUMBNAIL_SIZE - image.size[1]) / 2))
  382. # Stamp with Blender file type
  383. timage.paste(
  384. blender_indicator,
  385. (timage.size[0] - 30, timage.size[1] - 30),
  386. blender_indicator,
  387. )
  388. timage.save(TargetFileName + ".png")
  389. return self.thumbnailurl(os.path.basename(TargetFileName + ".png"))
  390. return self.ExtMimeIcon('application/x-blender')
  391. def fileinfo(self, name):
  392. filename = self.mediapath(name)
  393. f, ext = os.path.splitext(name)
  394. if ext != '.type' and os.path.isfile(filename):
  395. info = {}
  396. info['name'] = name
  397. info['size'] = os.path.getsize(filename)
  398. info['url'] = self.request.route_url('media_view',
  399. name=name,
  400. media_table=self.media_table,
  401. uid=self.linked_id)
  402. mime = self.get_mimetype(name)
  403. if IMAGE_TYPES.match(mime):
  404. info['thumbnailUrl'] = self.thumbnailurl(name)
  405. elif mime in ACCEPTED_MIMES:
  406. thumb = self.thumbnailpath("%s%s" % (f, ext))
  407. thumbext = ".jpg"
  408. if mime == "application/x-blender":
  409. thumbext = ".png"
  410. if os.path.exists(thumb + thumbext):
  411. info['thumbnailUrl'] = self.thumbnailurl(name) + thumbext
  412. else:
  413. info['thumbnailUrl'] = self.ExtMimeIcon(mime)
  414. else:
  415. info['thumbnailUrl'] = self.ExtMimeIcon(mime)
  416. if not self.display_only:
  417. info['deleteType'] = DELETEMETHOD
  418. info['deleteUrl'] = self.request.route_url('media_upload',
  419. sep='',
  420. name='',
  421. media_table=self.media_table,
  422. uid=self.linked_id) + '/' + name
  423. if DELETEMETHOD != 'DELETE':
  424. info['deleteUrl'] += '&_method=DELETE'
  425. return info
  426. else:
  427. return None
  428. @view_config(request_method='OPTIONS')
  429. def options(self):
  430. return Response(body='')
  431. @view_config(request_method='HEAD')
  432. def options(self):
  433. return Response(body='')
  434. @view_config(request_method='GET', renderer="json")
  435. def get(self):
  436. p = self.request.matchdict.get('name')
  437. if p:
  438. return self.fileinfo(p)
  439. else:
  440. filelist = []
  441. content = self.mediapath('')
  442. if content and path.exists(content):
  443. for f in os.listdir(content):
  444. n = self.fileinfo(f)
  445. if n:
  446. filelist.append(n)
  447. return {"files": filelist}
  448. @view_config(request_method='DELETE', xhr=True, accept="application/json", renderer='json')
  449. def delete(self):
  450. filename = self.request.matchdict.get('name')
  451. try:
  452. os.remove(self.mediapath(filename) + '.type')
  453. except IOError:
  454. pass
  455. except OSError:
  456. pass
  457. try:
  458. os.remove(self.thumbnailpath(filename))
  459. except IOError:
  460. pass
  461. except OSError:
  462. pass
  463. try:
  464. os.remove(self.thumbnailpath(filename + ".jpg"))
  465. except IOError:
  466. pass
  467. except OSError:
  468. pass
  469. try:
  470. os.remove(self.mediapath(filename))
  471. except IOError:
  472. return False
  473. return True
  474. @view_config(request_method='POST', xhr=True, accept="application/json", renderer='json')
  475. def post(self):
  476. if self.request.matchdict.get('_method') == "DELETE":
  477. return self.delete()
  478. results = []
  479. for name, fieldStorage in self.request.POST.items():
  480. if isinstance(fieldStorage, unicode):
  481. continue
  482. result = {}
  483. result['name'] = os.path.basename(fieldStorage.filename)
  484. result['type'] = fieldStorage.type
  485. result['size'] = self.get_file_size(fieldStorage.file)
  486. if self.validate(result, fieldStorage.file):
  487. filename, file_extension = os.path.splitext(result['name'])
  488. local_filename = slugify(filename) + file_extension
  489. # Keep mime-type in .type file
  490. with open(self.mediapath(local_filename) + '.type', 'w') as f:
  491. f.write(result['type'])
  492. # Store uploaded file
  493. fieldStorage.file.seek(0)
  494. with open(self.mediapath(local_filename), 'wb') as f:
  495. shutil.copyfileobj(fieldStorage.file, f)
  496. if re.match(IMAGE_TYPES, result['type']):
  497. result['thumbnailUrl'] = self.createthumbnail(local_filename)
  498. elif result['type'] == 'application/pdf':
  499. result['thumbnailUrl'] = self.pdfthumbnail(local_filename)
  500. elif result['type'] == 'image/svg+xml':
  501. result['thumbnailUrl'] = self.svgthumbnail(local_filename)
  502. elif result['type'].startswith('application/vnd'):
  503. result['thumbnailUrl'] = self.docthumbnail(local_filename)
  504. elif result['type'] == 'application/x-blender':
  505. result['thumbnailUrl'] = self.blendthumbnail(local_filename)
  506. else:
  507. result['thumbnailUrl'] = self.ExtMimeIcon(result['type'])
  508. result['deleteType'] = DELETEMETHOD
  509. result['deleteUrl'] = self.request.route_url('media_upload',
  510. sep='',
  511. name='',
  512. media_table=self.media_table,
  513. uid=self.linked_id) + '/' + local_filename
  514. result['url'] = self.request.route_url('media_view',
  515. media_table=self.media_table,
  516. uid=self.linked_id,
  517. name=local_filename)
  518. if DELETEMETHOD != 'DELETE':
  519. result['deleteUrl'] += '&_method=DELETE'
  520. results.append(result)
  521. return {"files": results}
  522. @view_defaults(route_name='media_view')
  523. class MediaView(MediaPath):
  524. def __init__(self, request):
  525. self.request = request
  526. self.media_table = self.request.matchdict.get('media_table')
  527. self.linked_id = self.request.matchdict.get('uid')
  528. def mediapath(self, name):
  529. return self.get_mediapath(self.media_table, self.linked_id, name)
  530. @view_config(request_method='GET', http_cache=(EXPIRATION_TIME, {'public': True}))
  531. def get(self):
  532. name = self.request.matchdict.get('name')
  533. self.request.response.content_type = self.get_mimetype(name)
  534. try:
  535. self.request.response.body_file = open(self.mediapath(name), 'rb', 10000)
  536. except IOError:
  537. raise NotFound
  538. return self.request.response
  539. ##return Response(app_iter=ImgHandle, content_type = 'image/png')