Django Library PyGal
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.

models.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import datetime
  2. from django.contrib.auth.models import User
  3. from django.db import models
  4. from django.utils import formats, timezone
  5. from django.urls import reverse
  6. import fstools
  7. import json
  8. import logging
  9. import media
  10. import os
  11. import pygal
  12. import subprocess
  13. import time
  14. DEBUG = False
  15. TYPE_FOLDER = 'folder'
  16. TYPE_IMAGE = 'image'
  17. TYPE_VIDEO = 'video'
  18. TYPE_AUDIO = 'audio'
  19. TYPE_OTHER = 'other'
  20. EXTENTIONS_IMAGE = ['.jpg', '.jpeg', '.jpe', '.png', '.tif', '.tiff', '.gif', ]
  21. EXTENTIONS_AUDIO = ['.mp3', ]
  22. EXTENTIONS_VIDEO = ['.avi', '.mpg', '.mpeg', '.mpe', '.mov', '.qt', '.mp4', '.webm', '.ogv', '.flv', '.3gp', ]
  23. # Get a logger instance
  24. logger = logging.getLogger("CACHING")
  25. def get_item_type(full_path):
  26. if os.path.isdir(full_path):
  27. return TYPE_FOLDER
  28. else:
  29. if os.path.splitext(full_path)[1].lower() in EXTENTIONS_IMAGE:
  30. return TYPE_IMAGE
  31. elif os.path.splitext(full_path)[1].lower() in EXTENTIONS_VIDEO:
  32. return TYPE_VIDEO
  33. elif os.path.splitext(full_path)[1].lower() in EXTENTIONS_AUDIO:
  34. return TYPE_AUDIO
  35. return TYPE_OTHER
  36. def supported_types():
  37. rv = []
  38. if pygal.show_audio():
  39. rv.append(TYPE_AUDIO)
  40. if pygal.show_image():
  41. rv.append(TYPE_IMAGE)
  42. if pygal.show_other():
  43. rv.append(TYPE_OTHER)
  44. if pygal.show_video():
  45. rv.append(TYPE_VIDEO)
  46. return rv
  47. def get_item_by_rel_path(rel_path):
  48. try:
  49. rv = Item.objects.get(rel_path=rel_path)
  50. except Item.DoesNotExist:
  51. rv = None
  52. if rv is not None:
  53. # return the existing item
  54. return rv
  55. else:
  56. # create new item, if rel_path exists in filesystem (folders needs to hold files)
  57. full_path = pygal.get_full_path(rel_path)
  58. if os.path.exists(full_path):
  59. # file exists or folder has files in substructure
  60. if get_item_type(full_path) != TYPE_FOLDER or len(fstools.filelist(full_path)) > 0:
  61. i = Item(rel_path=rel_path)
  62. i.save()
  63. logger.info('New Item created: %s', repr(rel_path))
  64. return i
  65. def is_valid_area(x1, y1, x2, y2):
  66. for p in [x1, y1, x2, y2]:
  67. if type(p) is not int:
  68. return False
  69. if (x1, y1) == (x2, y2):
  70. return False
  71. return True
  72. class ItemData(dict):
  73. DATA_FIELDS = [
  74. 'size',
  75. 'datetime',
  76. 'exposure_program',
  77. 'exposure_time',
  78. 'flash',
  79. 'f_number',
  80. 'focal_length',
  81. 'lon',
  82. 'lat',
  83. 'height',
  84. 'iso',
  85. 'camera',
  86. 'orientation',
  87. 'width',
  88. 'duration',
  89. 'ratio',
  90. 'album',
  91. 'artist',
  92. 'bitrate',
  93. 'genre',
  94. 'title',
  95. 'track',
  96. 'year',
  97. 'sil',
  98. 'num_audio',
  99. 'num_folders',
  100. 'num_images',
  101. 'num_other',
  102. 'num_videos',
  103. ]
  104. DEFAULT_VALUES = {
  105. 'size': 0,
  106. 'datetime': datetime.datetime(1900, 1, 1),
  107. 'exposure_program': '-',
  108. 'exposure_time': 0,
  109. 'flash': '-',
  110. 'f_number': 0,
  111. 'focal_length': 0,
  112. 'iso': 0,
  113. 'camera': '-',
  114. 'orientation': 1,
  115. 'duration': 3,
  116. 'ratio': 1,
  117. 'album': '-',
  118. 'artist': '-',
  119. 'bitrate': 0,
  120. 'genre': '-',
  121. 'title': '-',
  122. 'track': 0,
  123. 'year': 0,
  124. 'num_audio': 0,
  125. 'num_folders': 0,
  126. 'num_images': 0,
  127. 'num_other': 0,
  128. 'num_videos': 0,
  129. }
  130. def __init__(self, item):
  131. for key in self.DATA_FIELDS:
  132. value = getattr(item, key + '_c')
  133. if value is not None:
  134. self[key] = value
  135. setattr(self, key, value)
  136. else:
  137. if key in self.DEFAULT_VALUES:
  138. setattr(self, key, self.DEFAULT_VALUES[key])
  139. @property
  140. def formatted_datetime(self):
  141. try:
  142. return formats.date_format(self.get('datetime'), format="SHORT_DATE_FORMAT", use_l10n=True) + ' - ' + formats.time_format(self.get('datetime'), use_l10n=True)
  143. except AttributeError:
  144. return 'No Datetime available'
  145. @property
  146. def gps(self):
  147. if self.get('lon') and self.get('lat'):
  148. return {'lon': self.get('lon'), 'lat': self.get('lat')}
  149. else:
  150. return None
  151. class Item(models.Model):
  152. DATA_VERSION_NUMBER = 0
  153. #
  154. rel_path = models.TextField(unique=True)
  155. type = models.CharField(max_length=25, choices=((TYPE_AUDIO, 'Audio'), (TYPE_FOLDER, 'Folder'), (TYPE_IMAGE, 'Image'), (TYPE_OTHER, 'Other'), (TYPE_VIDEO, 'Video')))
  156. public_access = models.BooleanField(default=False)
  157. read_access = models.ManyToManyField(User, related_name="read_access", blank=True)
  158. modify_access = models.ManyToManyField(User, related_name="modify_access", blank=True)
  159. favourite_of = models.ManyToManyField(User, related_name="favourite_of", blank=True)
  160. #
  161. uid_c = models.CharField(max_length=50, null=True, blank=True)
  162. settings_c = models.IntegerField(null=True, blank=True)
  163. data_version_c = models.IntegerField(null=True, blank=True)
  164. # common
  165. size_c = models.IntegerField(null=True, blank=True)
  166. datetime_c = models.DateTimeField(null=True, blank=True)
  167. # image
  168. exposure_program_c = models.CharField(max_length=100, null=True, blank=True)
  169. exposure_time_c = models.FloatField(null=True, blank=True)
  170. flash_c = models.CharField(max_length=100, null=True, blank=True)
  171. f_number_c = models.FloatField(null=True, blank=True)
  172. focal_length_c = models.FloatField(null=True, blank=True)
  173. lon_c = models.FloatField(null=True, blank=True)
  174. lat_c = models.FloatField(null=True, blank=True)
  175. height_c = models.IntegerField(null=True, blank=True)
  176. iso_c = models.IntegerField(null=True, blank=True)
  177. camera_c = models.CharField(max_length=100, null=True, blank=True)
  178. orientation_c = models.IntegerField(null=True, blank=True)
  179. width_c = models.IntegerField(null=True, blank=True)
  180. # video
  181. duration_c = models.FloatField(null=True, blank=True)
  182. ratio_c = models.FloatField(null=True, blank=True)
  183. # audio
  184. album_c = models.CharField(max_length=100, null=True, blank=True)
  185. artist_c = models.CharField(max_length=100, null=True, blank=True)
  186. bitrate_c = models.IntegerField(null=True, blank=True)
  187. genre_c = models.CharField(max_length=100, null=True, blank=True)
  188. title_c = models.CharField(max_length=100, null=True, blank=True)
  189. track_c = models.IntegerField(null=True, blank=True)
  190. year_c = models.IntegerField(null=True, blank=True)
  191. # folder
  192. num_audio_c = models.IntegerField(null=True, blank=True)
  193. num_folders_c = models.IntegerField(null=True, blank=True)
  194. num_images_c = models.IntegerField(null=True, blank=True)
  195. num_other_c = models.IntegerField(null=True, blank=True)
  196. num_videos_c = models.IntegerField(null=True, blank=True)
  197. sil_c = models.TextField(null=True, blank=True)
  198. MODEL_TO_MEDIA_DATA = {
  199. media.metadata.KEY_SIZE: 'size_c',
  200. media.metadata.KEY_TIME: 'datetime_c',
  201. media.metadata.KEY_EXPOSURE_PROGRAM: 'exposure_program_c',
  202. media.metadata.KEY_EXPOSURE_TIME: 'exposure_time_c',
  203. media.metadata.KEY_FLASH: 'flash_c',
  204. media.metadata.KEY_APERTURE: 'f_number_c',
  205. media.metadata.KEY_FOCAL_LENGTH: 'focal_length_c',
  206. media.metadata.KEY_GPS: {'lon': 'lon_c', 'lat': 'lat_c'},
  207. media.metadata.KEY_HEIGHT: 'height_c',
  208. media.metadata.KEY_ISO: 'iso_c',
  209. media.metadata.KEY_CAMERA: 'camera_c',
  210. media.metadata.KEY_ORIENTATION: 'orientation_c',
  211. media.metadata.KEY_WIDTH: 'width_c',
  212. media.metadata.KEY_DURATION: 'duration_c',
  213. media.metadata.KEY_RATIO: 'ratio_c',
  214. media.metadata.KEY_ALBUM: 'album_c',
  215. media.metadata.KEY_ARTIST: 'artist_c',
  216. media.metadata.KEY_BITRATE: 'bitrate_c',
  217. media.metadata.KEY_GENRE: 'genre_c',
  218. media.metadata.KEY_TITLE: 'title_c',
  219. media.metadata.KEY_TRACK: 'track_c',
  220. media.metadata.KEY_YEAR: 'year_c',
  221. }
  222. def __init__(self, *args, **kwargs):
  223. self.__current_uid__ = None
  224. self.__current_settings__ = None
  225. models.Model.__init__(self, *args, **kwargs)
  226. @property
  227. def name(self):
  228. return os.path.splitext(os.path.basename(self.rel_path))[0]
  229. @property
  230. def item_data(self):
  231. if self.__cache_update_needed__():
  232. #
  233. self.__set_model_fields_from_file__()
  234. #
  235. self.save()
  236. return self.cached_item_data
  237. @property
  238. def cached_item_data(self):
  239. return ItemData(self)
  240. def get_admin_url(self):
  241. """the url to the Django admin interface for the model instance"""
  242. info = (self._meta.app_label, self._meta.model_name)
  243. return reverse('admin:%s_%s_change' % info, args=(self.pk,))
  244. def suspended(self, user):
  245. if pygal.suspend_public() and not user.is_authenticated:
  246. return True
  247. def may_read(self, user):
  248. if self.suspended(user):
  249. return False
  250. elif self.type == TYPE_FOLDER:
  251. return True
  252. else:
  253. parent = get_item_by_rel_path(os.path.dirname(self.rel_path))
  254. if parent.public_access is True:
  255. return True
  256. if user is None:
  257. return False
  258. if not user.is_authenticated:
  259. return False
  260. if user.is_superuser:
  261. return True
  262. return user in parent.read_access.all()
  263. def may_modify(self, user):
  264. if self.suspended(user):
  265. return False
  266. elif self.type == TYPE_FOLDER:
  267. return user in self.modify_access.all()
  268. else:
  269. if user is None:
  270. return False
  271. if not user.is_authenticated:
  272. return False
  273. if user.is_superuser:
  274. return True
  275. parent = get_item_by_rel_path(os.path.dirname(self.rel_path))
  276. return user in parent.modify_access.all()
  277. def sort_string(self):
  278. try:
  279. tm = int(self.item_data.datetime.strftime('%s'))
  280. except AttributeError:
  281. raise AttributeError('Unable to create a sortstring for %s. Used datetime was: %s' % (str(self), repr(self.item_data.datetime)))
  282. return '%012d_%s' % (tm, os.path.basename(self.rel_path))
  283. def sorted_itemlist(self):
  284. if self.type == TYPE_FOLDER:
  285. rv = []
  286. for rel_path in json.loads(self.item_data['sil']):
  287. try:
  288. rv.append(Item.objects.get(rel_path=rel_path))
  289. except Item.DoesNotExist:
  290. raise Item.DoesNotExist("%s: Item with rel_path=%s does not exist. in %s." % (str(self), rel_path))
  291. return rv
  292. else:
  293. return None
  294. def thumbnail_item(self):
  295. if self.type == TYPE_FOLDER:
  296. try:
  297. first_rel_path = json.loads(self.item_data['sil'])[0]
  298. return Item.objects.get(rel_path=first_rel_path).thumbnail_item()
  299. except IndexError:
  300. raise Item.DoesNotExist("%s: Tried to get the thumbnail_item for an empty list." % str(self))
  301. except Item.DoesNotExist:
  302. raise Item.DoesNotExist("%s: Item with rel_path=%s does not exist. in %s." % (str(self), first_rel_path))
  303. else:
  304. return self
  305. def all_itemslist(self):
  306. rv = []
  307. for i in self.sorted_itemlist():
  308. if i.type != TYPE_FOLDER:
  309. rv.append(i)
  310. else:
  311. rv.extend(i.all_itemslist())
  312. return rv
  313. def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
  314. if self.__cache_update_needed__():
  315. self.__set_model_fields_from_file__()
  316. return models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
  317. def current_uid(self):
  318. if self.__current_uid__ is None:
  319. self.__current_uid__ = fstools.uid(pygal.get_full_path(self.rel_path), None)
  320. return self.__current_uid__
  321. def current_settings(self):
  322. if self.__current_settings__ is None:
  323. self.__current_settings__ = pygal.show_audio() * 1 + pygal.show_image() * 2 + pygal.show_other() * 3 + pygal.show_video() * 4
  324. return self.__current_settings__
  325. def __cache_update_needed__(self):
  326. if self.type == TYPE_FOLDER:
  327. return DEBUG or self.settings_c != self.current_settings() or self.uid_c != self.current_uid() or self.data_version_c != self.DATA_VERSION_NUMBER
  328. else:
  329. return DEBUG or self.uid_c != self.current_uid() or self.data_version_c != self.DATA_VERSION_NUMBER
  330. def __set_model_fields_from_file__(self):
  331. logger.info('Updating cached data for Item: %s' % repr(self.rel_path))
  332. full_path = pygal.get_full_path(self.rel_path)
  333. self.type = get_item_type(full_path)
  334. self.uid_c = self.current_uid()
  335. self.settings_c = self.current_settings()
  336. self.data_version_c = self.DATA_VERSION_NUMBER
  337. if self.type == TYPE_FOLDER:
  338. self.__update_folder_file_data__(full_path)
  339. elif self.type == TYPE_OTHER:
  340. self.__update_other_file_data__(full_path)
  341. else:
  342. self.__update_media_file_data__(full_path)
  343. for key, value in self.cached_item_data.items():
  344. logger.debug(' - Adding %s=%s', key, repr(value))
  345. def __update_folder_file_data__(self, full_path):
  346. sil = []
  347. self.size_c = 0
  348. self.num_audio_c = 0
  349. self.num_folders_c = 1
  350. self.num_images_c = 0
  351. self.num_other_c = 0
  352. self.num_videos_c = 0
  353. for fn in os.listdir(full_path):
  354. sub_rel_path = pygal.get_rel_path(os.path.join(full_path, fn))
  355. sub_item = get_item_by_rel_path(sub_rel_path)
  356. # size, num_*
  357. if sub_item is not None: # Item does really exist / has sub-items
  358. if (sub_item.type == TYPE_FOLDER and len(json.loads(sub_item.item_data['sil']))) or sub_item.type in supported_types():
  359. self.size_c += sub_item.item_data.size
  360. if sub_item.type == TYPE_AUDIO:
  361. self.num_audio_c += 1
  362. elif sub_item.type == TYPE_FOLDER:
  363. self.num_audio_c += sub_item.item_data['num_audio']
  364. self.num_folders_c += sub_item.item_data['num_folders']
  365. self.num_images_c += sub_item.item_data['num_images']
  366. self.num_other_c += sub_item.item_data['num_other']
  367. self.num_videos_c += sub_item.item_data['num_videos']
  368. elif sub_item.type == TYPE_IMAGE:
  369. self.num_images_c += 1
  370. elif sub_item.type == TYPE_OTHER:
  371. self.num_other_c += 1
  372. elif sub_item.type == TYPE_VIDEO:
  373. self.num_videos_c += 1
  374. # sorted item list
  375. sil.append(sub_item)
  376. sil.sort(key=lambda entry: entry.sort_string(), reverse=True)
  377. self.sil_c = json.dumps([i.rel_path for i in sil], indent=4)
  378. # datetime
  379. if len(sil) > 0:
  380. self.datetime_c = sil[0].datetime_c
  381. def __update_media_file_data__(self, full_path):
  382. data = media.get_media_data(full_path) or {}
  383. for key in self.MODEL_TO_MEDIA_DATA:
  384. value = data.get(key)
  385. if key == media.metadata.KEY_GPS: # Split GPS data in lon and lat
  386. for k in self.MODEL_TO_MEDIA_DATA[key]:
  387. value_k = value[k] if value is not None else None
  388. setattr(self, self.MODEL_TO_MEDIA_DATA[key][k], value_k)
  389. else:
  390. if value is not None:
  391. if key == media.metadata.KEY_TIME: # convert time to datetime
  392. if data.get(media.metadata.KEY_TIME_IS_SUBSTITUTION) and self.type == TYPE_IMAGE: # don't use time substitution for images
  393. value = None
  394. else:
  395. value = datetime.datetime.fromtimestamp(value, tz=datetime.timezone.utc)
  396. setattr(self, self.MODEL_TO_MEDIA_DATA[key], value)
  397. def __update_other_file_data__(self, full_path):
  398. self.size_c = os.path.getsize(full_path)
  399. #
  400. self.datetime_c = datetime.datetime.fromtimestamp(os.path.getctime(full_path), tz=timezone.utc)
  401. def __str__(self):
  402. return 'Item: %s' % self.rel_path
  403. class Tag(models.Model):
  404. item = models.ForeignKey(Item, on_delete=models.CASCADE)
  405. text = models.CharField(max_length=100)
  406. topleft_x = models.IntegerField(null=True, blank=True)
  407. topleft_y = models.IntegerField(null=True, blank=True)
  408. bottomright_x = models.IntegerField(null=True, blank=True)
  409. bottomright_y = models.IntegerField(null=True, blank=True)
  410. def __init__(self, *args, **kwargs):
  411. self.__tm_start__ = time.time()
  412. models.Model.__init__(self, *args, **kwargs)
  413. logger.log(5, 'Initialising Tag Model object in %.02fs: %s', time.time() - self.__tm_start__, str(self))
  414. @property
  415. def has_valid_coordinates(self):
  416. return is_valid_area(self.topleft_x, self.topleft_y, self.bottomright_x, self.bottomright_y)
  417. def get_admin_url(self):
  418. """the url to the Django admin interface for the model instance"""
  419. info = (self._meta.app_label, self._meta.model_name)
  420. return reverse('admin:%s_%s_change' % info, args=(self.pk,))
  421. class Setting(models.Model):
  422. suspend_puplic = models.BooleanField(default=True)
  423. show_image = models.BooleanField(default=True)
  424. show_video = models.BooleanField(default=True)
  425. show_audio = models.BooleanField(default=False)
  426. show_other = models.BooleanField(default=False)