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.
 
 
 
 
 

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