media.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. __filename__ = "media.py"
  2. __author__ = "Bob Mottram"
  3. __license__ = "AGPL3+"
  4. __version__ = "0.0.1"
  5. __maintainer__ = "Bob Mottram"
  6. __email__ = "bob@freedombone.net"
  7. __status__ = "Production"
  8. from blurhash import blurhash_encode as blurencode
  9. from PIL import Image
  10. import numpy
  11. import os
  12. import sys
  13. import json
  14. import commentjson
  15. import datetime
  16. from auth import createPassword
  17. from shutil import copyfile
  18. from shutil import rmtree
  19. from shutil import move
  20. def removeMetaData(imageFilename: str,outputFilename: str):
  21. imageFile = open(imageFilename)
  22. image = Image.open(imageFilename)
  23. data = list(image.getdata())
  24. imageWithoutExif = Image.new(image.mode, image.size)
  25. imageWithoutExif.putdata(data)
  26. imageWithoutExif.save(outputFilename)
  27. def getImageHash(imageFilename: str) -> str:
  28. return blurencode(numpy.array(Image.open(imageFilename).convert("RGB")))
  29. def isImage(imageFilename: str) -> bool:
  30. if imageFilename.endswith('.png') or \
  31. imageFilename.endswith('.jpg') or \
  32. imageFilename.endswith('.gif'):
  33. return True
  34. return False
  35. def createMediaDirs(baseDir: str,mediaPath: str) -> None:
  36. if not os.path.isdir(baseDir+'/media'):
  37. os.mkdir(baseDir+'/media')
  38. if not os.path.isdir(baseDir+'/'+mediaPath):
  39. os.mkdir(baseDir+'/'+mediaPath)
  40. def getMediaPath() -> str:
  41. currTime=datetime.datetime.utcnow()
  42. weeksSinceEpoch=int((currTime - datetime.datetime(1970,1,1)).days/7)
  43. return 'media/'+str(weeksSinceEpoch)
  44. def attachImage(baseDir: str,httpPrefix: str,domain: str,port: int, \
  45. postJson: {},imageFilename: str,description: str, \
  46. useBlurhash: bool) -> {}:
  47. """Attaches an image to a json object post
  48. The description can be None
  49. Blurhash is optional, since low power systems may take a long time to calculate it
  50. """
  51. if not isImage(imageFilename):
  52. return postJson
  53. mediaType='image/png'
  54. fileExtension='png'
  55. if imageFilename.endswith('.jpg'):
  56. mediaType='image/jpeg'
  57. fileExtension='jpg'
  58. if imageFilename.endswith('.gif'):
  59. mediaType='image/gif'
  60. fileExtension='gif'
  61. if port:
  62. if port!=80 and port!=443:
  63. if ':' not in domain:
  64. domain=domain+':'+str(port)
  65. mPath=getMediaPath()
  66. mediaPath=mPath+'/'+createPassword(32)+'.'+fileExtension
  67. if baseDir:
  68. createMediaDirs(baseDir,mPath)
  69. mediaFilename=baseDir+'/'+mediaPath
  70. attachmentJson={
  71. 'mediaType': mediaType,
  72. 'name': description,
  73. 'type': 'Document',
  74. 'url': httpPrefix+'://'+domain+'/'+mediaPath
  75. }
  76. if useBlurhash:
  77. attachmentJson['blurhash']=getImageHash(imageFilename)
  78. postJson['attachment']=[attachmentJson]
  79. if baseDir:
  80. removeMetaData(imageFilename,mediaFilename)
  81. #copyfile(imageFilename,mediaFilename)
  82. return postJson
  83. def archiveMedia(baseDir: str,archiveDirectory: str,maxWeeks=4) -> None:
  84. """Any media older than the given number of weeks gets archived
  85. """
  86. currTime=datetime.datetime.utcnow()
  87. weeksSinceEpoch=int((currTime - datetime.datetime(1970,1,1)).days/7)
  88. minWeek=weeksSinceEpoch-maxWeeks
  89. if archiveDirectory:
  90. if not os.path.isdir(archiveDirectory):
  91. os.mkdir(archiveDirectory)
  92. if not os.path.isdir(archiveDirectory+'/media'):
  93. os.mkdir(archiveDirectory+'/media')
  94. for subdir, dirs, files in os.walk(baseDir+'/media'):
  95. for weekDir in dirs:
  96. if int(weekDir)<minWeek:
  97. if archiveDirectory:
  98. move(os.path.join(baseDir+'/media', weekDir),archiveDirectory+'/media')
  99. else:
  100. # archive to /dev/null
  101. rmtree(os.path.join(baseDir+'/media', weekDir))