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.
 
 
 
 
 

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