mixin.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. # GNU MediaGoblin -- federated, autonomous media hosting
  2. # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. This module contains some Mixin classes for the db objects.
  18. A bunch of functions on the db objects are really more like
  19. "utility functions": They could live outside the classes
  20. and be called "by hand" passing the appropiate reference.
  21. They usually only use the public API of the object and
  22. rarely use database related stuff.
  23. These functions now live here and get "mixed in" into the
  24. real objects.
  25. """
  26. import uuid
  27. import re
  28. from datetime import datetime
  29. from pytz import UTC
  30. from werkzeug.utils import cached_property
  31. from mediagoblin.media_types import FileTypeNotSupported
  32. from mediagoblin.tools import common, licenses
  33. from mediagoblin.tools.pluginapi import hook_handle
  34. from mediagoblin.tools.text import cleaned_markdown_conversion
  35. from mediagoblin.tools.url import slugify
  36. from mediagoblin.tools.translate import pass_to_ugettext as _
  37. class UserMixin(object):
  38. object_type = "person"
  39. @property
  40. def bio_html(self):
  41. return cleaned_markdown_conversion(self.bio)
  42. def url_for_self(self, urlgen, **kwargs):
  43. """Generate a URL for this User's home page."""
  44. return urlgen('mediagoblin.user_pages.user_home',
  45. user=self.username, **kwargs)
  46. class GenerateSlugMixin(object):
  47. """
  48. Mixin to add a generate_slug method to objects.
  49. Depends on:
  50. - self.slug
  51. - self.title
  52. - self.check_slug_used(new_slug)
  53. """
  54. def generate_slug(self):
  55. """
  56. Generate a unique slug for this object.
  57. This one does not *force* slugs, but usually it will probably result
  58. in a niceish one.
  59. The end *result* of the algorithm will result in these resolutions for
  60. these situations:
  61. - If we have a slug, make sure it's clean and sanitized, and if it's
  62. unique, we'll use that.
  63. - If we have a title, slugify it, and if it's unique, we'll use that.
  64. - If we can't get any sort of thing that looks like it'll be a useful
  65. slug out of a title or an existing slug, bail, and don't set the
  66. slug at all. Don't try to create something just because. Make
  67. sure we have a reasonable basis for a slug first.
  68. - If we have a reasonable basis for a slug (either based on existing
  69. slug or slugified title) but it's not unique, first try appending
  70. the entry's id, if that exists
  71. - If that doesn't result in something unique, tack on some randomly
  72. generated bits until it's unique. That'll be a little bit of junk,
  73. but at least it has the basis of a nice slug.
  74. """
  75. #Is already a slug assigned? Check if it is valid
  76. if self.slug:
  77. slug = slugify(self.slug)
  78. # otherwise, try to use the title.
  79. elif self.title:
  80. # assign slug based on title
  81. slug = slugify(self.title)
  82. else:
  83. # We don't have any information to set a slug
  84. return
  85. # We don't want any empty string slugs
  86. if slug == u"":
  87. return
  88. # Otherwise, let's see if this is unique.
  89. if self.check_slug_used(slug):
  90. # It looks like it's being used... lame.
  91. # Can we just append the object's id to the end?
  92. if self.id:
  93. slug_with_id = u"%s-%s" % (slug, self.id)
  94. if not self.check_slug_used(slug_with_id):
  95. self.slug = slug_with_id
  96. return # success!
  97. # okay, still no success;
  98. # let's whack junk on there till it's unique.
  99. slug += '-' + uuid.uuid4().hex[:4]
  100. # keep going if necessary!
  101. while self.check_slug_used(slug):
  102. slug += uuid.uuid4().hex[:4]
  103. # self.check_slug_used(slug) must be False now so we have a slug that
  104. # we can use now.
  105. self.slug = slug
  106. class MediaEntryMixin(GenerateSlugMixin):
  107. def check_slug_used(self, slug):
  108. # import this here due to a cyclic import issue
  109. # (db.models -> db.mixin -> db.util -> db.models)
  110. from mediagoblin.db.util import check_media_slug_used
  111. return check_media_slug_used(self.uploader, slug, self.id)
  112. @property
  113. def object_type(self):
  114. """ Converts media_type to pump-like type - don't use internally """
  115. return self.media_type.split(".")[-1]
  116. @property
  117. def description_html(self):
  118. """
  119. Rendered version of the description, run through
  120. Markdown and cleaned with our cleaning tool.
  121. """
  122. return cleaned_markdown_conversion(self.description)
  123. def get_display_media(self):
  124. """Find the best media for display.
  125. We try checking self.media_manager.fetching_order if it exists to
  126. pull down the order.
  127. Returns:
  128. (media_size, media_path)
  129. or, if not found, None.
  130. """
  131. fetch_order = self.media_manager.media_fetch_order
  132. # No fetching order found? well, give up!
  133. if not fetch_order:
  134. return None
  135. media_sizes = self.media_files.keys()
  136. for media_size in fetch_order:
  137. if media_size in media_sizes:
  138. return media_size, self.media_files[media_size]
  139. def main_mediafile(self):
  140. pass
  141. @property
  142. def slug_or_id(self):
  143. if self.slug:
  144. return self.slug
  145. else:
  146. return u'id:%s' % self.id
  147. def url_for_self(self, urlgen, **extra_args):
  148. """
  149. Generate an appropriate url for ourselves
  150. Use a slug if we have one, else use our 'id'.
  151. """
  152. uploader = self.get_uploader
  153. return urlgen(
  154. 'mediagoblin.user_pages.media_home',
  155. user=uploader.username,
  156. media=self.slug_or_id,
  157. **extra_args)
  158. @property
  159. def thumb_url(self):
  160. """Return the thumbnail URL (for usage in templates)
  161. Will return either the real thumbnail or a default fallback icon."""
  162. # TODO: implement generic fallback in case MEDIA_MANAGER does
  163. # not specify one?
  164. if u'thumb' in self.media_files:
  165. thumb_url = self._app.public_store.file_url(
  166. self.media_files[u'thumb'])
  167. else:
  168. # No thumbnail in media available. Get the media's
  169. # MEDIA_MANAGER for the fallback icon and return static URL
  170. # Raises FileTypeNotSupported in case no such manager is enabled
  171. manager = self.media_manager
  172. thumb_url = self._app.staticdirector(manager[u'default_thumb'])
  173. return thumb_url
  174. @property
  175. def original_url(self):
  176. """ Returns the URL for the original image
  177. will return self.thumb_url if original url doesn't exist"""
  178. if u"original" not in self.media_files:
  179. return self.thumb_url
  180. return self._app.public_store.file_url(
  181. self.media_files[u"original"]
  182. )
  183. @cached_property
  184. def media_manager(self):
  185. """Returns the MEDIA_MANAGER of the media's media_type
  186. Raises FileTypeNotSupported in case no such manager is enabled
  187. """
  188. manager = hook_handle(('media_manager', self.media_type))
  189. if manager:
  190. return manager(self)
  191. # Not found? Then raise an error
  192. raise FileTypeNotSupported(
  193. "MediaManager not in enabled types. Check media_type plugins are"
  194. " enabled in config?")
  195. def get_fail_exception(self):
  196. """
  197. Get the exception that's appropriate for this error
  198. """
  199. if self.fail_error:
  200. return common.import_component(self.fail_error)
  201. def get_license_data(self):
  202. """Return license dict for requested license"""
  203. return licenses.get_license_by_url(self.license or "")
  204. def exif_display_iter(self):
  205. if not self.media_data:
  206. return
  207. exif_all = self.media_data.get("exif_all")
  208. for key in exif_all:
  209. label = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', key)
  210. yield label.replace('EXIF', '').replace('Image', ''), exif_all[key]
  211. def exif_display_data_short(self):
  212. """Display a very short practical version of exif info"""
  213. if not self.media_data:
  214. return
  215. exif_all = self.media_data.get("exif_all")
  216. exif_short = {}
  217. if 'Image DateTimeOriginal' in exif_all:
  218. # format date taken
  219. takendate = datetime.strptime(
  220. exif_all['Image DateTimeOriginal']['printable'],
  221. '%Y:%m:%d %H:%M:%S').date()
  222. taken = takendate.strftime('%B %d %Y')
  223. exif_short.update({'Date Taken': taken})
  224. aperture = None
  225. if 'EXIF FNumber' in exif_all:
  226. fnum = str(exif_all['EXIF FNumber']['printable']).split('/')
  227. # calculate aperture
  228. if len(fnum) == 2:
  229. aperture = "f/%.1f" % (float(fnum[0])/float(fnum[1]))
  230. elif fnum[0] != 'None':
  231. aperture = "f/%s" % (fnum[0])
  232. if aperture:
  233. exif_short.update({'Aperture': aperture})
  234. short_keys = [
  235. ('Camera', 'Image Model', None),
  236. ('Exposure', 'EXIF ExposureTime', lambda x: '%s sec' % x),
  237. ('ISO Speed', 'EXIF ISOSpeedRatings', None),
  238. ('Focal Length', 'EXIF FocalLength', lambda x: '%s mm' % x)]
  239. for label, key, fmt_func in short_keys:
  240. try:
  241. val = fmt_func(exif_all[key]['printable']) if fmt_func \
  242. else exif_all[key]['printable']
  243. exif_short.update({label: val})
  244. except KeyError:
  245. pass
  246. return exif_short
  247. class MediaCommentMixin(object):
  248. object_type = "comment"
  249. @property
  250. def content_html(self):
  251. """
  252. the actual html-rendered version of the comment displayed.
  253. Run through Markdown and the HTML cleaner.
  254. """
  255. return cleaned_markdown_conversion(self.content)
  256. def __unicode__(self):
  257. return u'<{klass} #{id} {author} "{comment}">'.format(
  258. klass=self.__class__.__name__,
  259. id=self.id,
  260. author=self.get_author,
  261. comment=self.content)
  262. def __repr__(self):
  263. return '<{klass} #{id} {author} "{comment}">'.format(
  264. klass=self.__class__.__name__,
  265. id=self.id,
  266. author=self.get_author,
  267. comment=self.content)
  268. class CollectionMixin(GenerateSlugMixin):
  269. object_type = "collection"
  270. def check_slug_used(self, slug):
  271. # import this here due to a cyclic import issue
  272. # (db.models -> db.mixin -> db.util -> db.models)
  273. from mediagoblin.db.util import check_collection_slug_used
  274. return check_collection_slug_used(self.creator, slug, self.id)
  275. @property
  276. def description_html(self):
  277. """
  278. Rendered version of the description, run through
  279. Markdown and cleaned with our cleaning tool.
  280. """
  281. return cleaned_markdown_conversion(self.description)
  282. @property
  283. def slug_or_id(self):
  284. return (self.slug or self.id)
  285. def url_for_self(self, urlgen, **extra_args):
  286. """
  287. Generate an appropriate url for ourselves
  288. Use a slug if we have one, else use our 'id'.
  289. """
  290. creator = self.get_creator
  291. return urlgen(
  292. 'mediagoblin.user_pages.user_collection',
  293. user=creator.username,
  294. collection=self.slug_or_id,
  295. **extra_args)
  296. class CollectionItemMixin(object):
  297. @property
  298. def note_html(self):
  299. """
  300. the actual html-rendered version of the note displayed.
  301. Run through Markdown and the HTML cleaner.
  302. """
  303. return cleaned_markdown_conversion(self.note)
  304. class ActivityMixin(object):
  305. object_type = "activity"
  306. VALID_VERBS = ["add", "author", "create", "delete", "dislike", "favorite",
  307. "follow", "like", "post", "share", "unfavorite", "unfollow",
  308. "unlike", "unshare", "update", "tag"]
  309. def get_url(self, request):
  310. return request.urlgen(
  311. "mediagoblin.user_pages.activity_view",
  312. username=self.get_actor.username,
  313. id=self.id,
  314. qualified=True
  315. )
  316. def generate_content(self):
  317. """ Produces a HTML content for object """
  318. # some of these have simple and targetted. If self.target it set
  319. # it will pick the targetted. If they DON'T have a targetted version
  320. # the information in targetted won't be added to the content.
  321. verb_to_content = {
  322. "add": {
  323. "simple" : _("{username} added {object}"),
  324. "targetted": _("{username} added {object} to {target}"),
  325. },
  326. "author": {"simple": _("{username} authored {object}")},
  327. "create": {"simple": _("{username} created {object}")},
  328. "delete": {"simple": _("{username} deleted {object}")},
  329. "dislike": {"simple": _("{username} disliked {object}")},
  330. "favorite": {"simple": _("{username} favorited {object}")},
  331. "follow": {"simple": _("{username} followed {object}")},
  332. "like": {"simple": _("{username} liked {object}")},
  333. "post": {
  334. "simple": _("{username} posted {object}"),
  335. "targetted": _("{username} posted {object} to {target}"),
  336. },
  337. "share": {"simple": _("{username} shared {object}")},
  338. "unfavorite": {"simple": _("{username} unfavorited {object}")},
  339. "unfollow": {"simple": _("{username} stopped following {object}")},
  340. "unlike": {"simple": _("{username} unliked {object}")},
  341. "unshare": {"simple": _("{username} unshared {object}")},
  342. "update": {"simple": _("{username} updated {object}")},
  343. "tag": {"simple": _("{username} tagged {object}")},
  344. }
  345. object_map = {
  346. "image": _("an image"),
  347. "comment": _("a comment"),
  348. "collection": _("a collection"),
  349. "video": _("a video"),
  350. "audio": _("audio"),
  351. "person": _("a person"),
  352. }
  353. obj = self.object_helper.get_object()
  354. target = None if self.target_helper is None else self.target_helper.get_object()
  355. actor = self.get_actor
  356. content = verb_to_content.get(self.verb, None)
  357. if content is None or self.object is None:
  358. return
  359. # Decide what to fill the object with
  360. if hasattr(obj, "title") and obj.title.strip(" "):
  361. object_value = obj.title
  362. elif obj.object_type in object_map:
  363. object_value = object_map[obj.object_type]
  364. else:
  365. object_value = _("an object")
  366. # Do we want to add a target (indirect object) to content?
  367. if target is not None and "targetted" in content:
  368. if hasattr(target, "title") and target.title.strip(" "):
  369. target_value = terget.title
  370. elif target.object_type in object_map:
  371. target_value = object_map[target.object_type]
  372. else:
  373. target_value = _("an object")
  374. self.content = content["targetted"].format(
  375. username=actor.username,
  376. object=object_value,
  377. target=target_value
  378. )
  379. else:
  380. self.content = content["simple"].format(
  381. username=actor.username,
  382. object=object_value
  383. )
  384. return self.content
  385. def serialize(self, request):
  386. href = request.urlgen(
  387. "mediagoblin.api.object",
  388. object_type=self.object_type,
  389. id=self.id,
  390. qualified=True
  391. )
  392. published = UTC.localize(self.published)
  393. updated = UTC.localize(self.updated)
  394. obj = {
  395. "id": href,
  396. "actor": self.get_actor.serialize(request),
  397. "verb": self.verb,
  398. "published": published.isoformat(),
  399. "updated": updated.isoformat(),
  400. "content": self.content,
  401. "url": self.get_url(request),
  402. "object": self.get_object.serialize(request),
  403. "objectType": self.object_type,
  404. "links": {
  405. "self": {
  406. "href": href,
  407. },
  408. },
  409. }
  410. if self.generator:
  411. obj["generator"] = self.get_generator.serialize(request)
  412. if self.title:
  413. obj["title"] = self.title
  414. target = self.get_target
  415. if target is not None:
  416. obj["target"] = target.serialize(request)
  417. return obj
  418. def unseralize(self, data):
  419. """
  420. Takes data given and set it on this activity.
  421. Several pieces of data are not written on because of security
  422. reasons. For example changing the author or id of an activity.
  423. """
  424. if "verb" in data:
  425. self.verb = data["verb"]
  426. if "title" in data:
  427. self.title = data["title"]
  428. if "content" in data:
  429. self.content = data["content"]