models.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. import json
  2. import logging
  3. import os
  4. import random
  5. import re
  6. import tempfile
  7. import uuid
  8. import m3u8
  9. from django.conf import settings
  10. from django.contrib.postgres.indexes import GinIndex
  11. from django.contrib.postgres.search import SearchVectorField
  12. from django.core.exceptions import ValidationError
  13. from django.core.files import File
  14. from django.db import connection, models
  15. from django.db.models.signals import m2m_changed, post_delete, post_save, pre_delete
  16. from django.dispatch import receiver
  17. from django.template.defaultfilters import slugify
  18. from django.urls import reverse
  19. from django.utils import timezone
  20. from django.utils.html import strip_tags
  21. from imagekit.models import ProcessedImageField
  22. from imagekit.processors import ResizeToFit
  23. from mptt.models import MPTTModel, TreeForeignKey
  24. from . import helpers
  25. from .stop_words import STOP_WORDS
  26. logger = logging.getLogger(__name__)
  27. RE_TIMECODE = re.compile(r"(\d+:\d+:\d+.\d+)")
  28. # this is used by Media and Encoding models
  29. # reflects media encoding status for objects
  30. MEDIA_ENCODING_STATUS = (
  31. ("pending", "Pending"),
  32. ("running", "Running"),
  33. ("fail", "Fail"),
  34. ("success", "Success"),
  35. )
  36. # the media state of a Media object
  37. # this is set by default according to the portal workflow
  38. MEDIA_STATES = (
  39. ("private", "Private"),
  40. ("public", "Public"),
  41. ("unlisted", "Unlisted"),
  42. )
  43. # each uploaded Media gets a media_type hint
  44. # by helpers.get_file_type
  45. MEDIA_TYPES_SUPPORTED = (
  46. ("video", "Video"),
  47. ("image", "Image"),
  48. ("pdf", "Pdf"),
  49. ("audio", "Audio"),
  50. )
  51. ENCODE_EXTENSIONS = (
  52. ("mp4", "mp4"),
  53. ("webm", "webm"),
  54. ("gif", "gif"),
  55. )
  56. ENCODE_RESOLUTIONS = (
  57. (2160, "2160"),
  58. (1440, "1440"),
  59. (1080, "1080"),
  60. (720, "720"),
  61. (480, "480"),
  62. (360, "360"),
  63. (240, "240"),
  64. )
  65. CODECS = (
  66. ("h265", "h265"),
  67. ("h264", "h264"),
  68. ("vp9", "vp9"),
  69. )
  70. ENCODE_EXTENSIONS_KEYS = [extension for extension, name in ENCODE_EXTENSIONS]
  71. ENCODE_RESOLUTIONS_KEYS = [resolution for resolution, name in ENCODE_RESOLUTIONS]
  72. def original_media_file_path(instance, filename):
  73. """Helper function to place original media file"""
  74. file_name = "{0}.{1}".format(instance.uid.hex, helpers.get_file_name(filename))
  75. return settings.MEDIA_UPLOAD_DIR + "user/{0}/{1}".format(instance.user.username, file_name)
  76. def encoding_media_file_path(instance, filename):
  77. """Helper function to place encoded media file"""
  78. file_name = "{0}.{1}".format(instance.media.uid.hex, helpers.get_file_name(filename))
  79. return settings.MEDIA_ENCODING_DIR + "{0}/{1}/{2}".format(instance.profile.id, instance.media.user.username, file_name)
  80. def original_thumbnail_file_path(instance, filename):
  81. """Helper function to place original media thumbnail file"""
  82. return settings.THUMBNAIL_UPLOAD_DIR + "user/{0}/{1}".format(instance.user.username, filename)
  83. def subtitles_file_path(instance, filename):
  84. """Helper function to place subtitle file"""
  85. return settings.SUBTITLES_UPLOAD_DIR + "user/{0}/{1}".format(instance.media.user.username, filename)
  86. def category_thumb_path(instance, filename):
  87. """Helper function to place category thumbnail file"""
  88. file_name = "{0}.{1}".format(instance.uid.hex, helpers.get_file_name(filename))
  89. return settings.MEDIA_UPLOAD_DIR + "categories/{0}".format(file_name)
  90. class Media(models.Model):
  91. """The most important model for MediaCMS"""
  92. add_date = models.DateTimeField("Date produced", blank=True, null=True, db_index=True)
  93. allow_download = models.BooleanField(default=True, help_text="Whether option to download media is shown")
  94. category = models.ManyToManyField("Category", blank=True, help_text="Media can be part of one or more categories")
  95. channel = models.ForeignKey(
  96. "users.Channel",
  97. on_delete=models.CASCADE,
  98. blank=True,
  99. null=True,
  100. help_text="Media can exist in one or no Channels",
  101. )
  102. description = models.TextField(blank=True)
  103. dislikes = models.IntegerField(default=0)
  104. duration = models.IntegerField(default=0)
  105. edit_date = models.DateTimeField(auto_now=True)
  106. enable_comments = models.BooleanField(default=True, help_text="Whether comments will be allowed for this media")
  107. encoding_status = models.CharField(max_length=20, choices=MEDIA_ENCODING_STATUS, default="pending", db_index=True)
  108. featured = models.BooleanField(
  109. default=False,
  110. db_index=True,
  111. help_text="Whether media is globally featured by a MediaCMS editor",
  112. )
  113. friendly_token = models.CharField(blank=True, max_length=12, db_index=True, help_text="Identifier for the Media")
  114. hls_file = models.CharField(max_length=1000, blank=True, help_text="Path to HLS file for videos")
  115. is_reviewed = models.BooleanField(
  116. default=settings.MEDIA_IS_REVIEWED,
  117. db_index=True,
  118. help_text="Whether media is reviewed, so it can appear on public listings",
  119. )
  120. license = models.ForeignKey("License", on_delete=models.CASCADE, db_index=True, blank=True, null=True)
  121. likes = models.IntegerField(db_index=True, default=1)
  122. listable = models.BooleanField(default=False, help_text="Whether it will appear on listings")
  123. md5sum = models.CharField(max_length=50, blank=True, null=True, help_text="Not exposed, used internally")
  124. media_file = models.FileField(
  125. "media file",
  126. upload_to=original_media_file_path,
  127. max_length=500,
  128. help_text="media file",
  129. )
  130. media_info = models.TextField(blank=True, help_text="extracted media metadata info")
  131. media_type = models.CharField(
  132. max_length=20,
  133. blank=True,
  134. choices=MEDIA_TYPES_SUPPORTED,
  135. db_index=True,
  136. default="video",
  137. )
  138. password = models.CharField(max_length=100, blank=True, help_text="password for private media")
  139. preview_file_path = models.CharField(
  140. max_length=500,
  141. blank=True,
  142. help_text="preview gif for videos, path in filesystem",
  143. )
  144. poster = ProcessedImageField(
  145. upload_to=original_thumbnail_file_path,
  146. processors=[ResizeToFit(width=720, height=None)],
  147. format="JPEG",
  148. options={"quality": 95},
  149. blank=True,
  150. max_length=500,
  151. help_text="media extracted big thumbnail, shown on media page",
  152. )
  153. rating_category = models.ManyToManyField(
  154. "RatingCategory",
  155. blank=True,
  156. help_text="Rating category, if media Rating is allowed",
  157. )
  158. reported_times = models.IntegerField(default=0, help_text="how many time a media is reported")
  159. search = SearchVectorField(
  160. null=True,
  161. help_text="used to store all searchable info and metadata for a Media",
  162. )
  163. size = models.CharField(
  164. max_length=20,
  165. blank=True,
  166. null=True,
  167. help_text="media size in bytes, automatically calculated",
  168. )
  169. sprites = models.FileField(
  170. upload_to=original_thumbnail_file_path,
  171. blank=True,
  172. max_length=500,
  173. help_text="sprites file, only for videos, displayed on the video player",
  174. )
  175. state = models.CharField(
  176. max_length=20,
  177. choices=MEDIA_STATES,
  178. default=helpers.get_portal_workflow(),
  179. db_index=True,
  180. help_text="state of Media",
  181. )
  182. tags = models.ManyToManyField("Tag", blank=True, help_text="select one or more out of the existing tags")
  183. title = models.CharField(max_length=100, help_text="media title", blank=True, db_index=True)
  184. thumbnail = ProcessedImageField(
  185. upload_to=original_thumbnail_file_path,
  186. processors=[ResizeToFit(width=344, height=None)],
  187. format="JPEG",
  188. options={"quality": 95},
  189. blank=True,
  190. max_length=500,
  191. help_text="media extracted small thumbnail, shown on listings",
  192. )
  193. thumbnail_time = models.FloatField(blank=True, null=True, help_text="Time on video that a thumbnail will be taken")
  194. uid = models.UUIDField(unique=True, default=uuid.uuid4, help_text="A unique identifier for the Media")
  195. uploaded_thumbnail = ProcessedImageField(
  196. upload_to=original_thumbnail_file_path,
  197. processors=[ResizeToFit(width=344, height=None)],
  198. format="JPEG",
  199. options={"quality": 85},
  200. blank=True,
  201. max_length=500,
  202. help_text="thumbnail from uploaded_poster field",
  203. )
  204. uploaded_poster = ProcessedImageField(
  205. verbose_name="Upload image",
  206. help_text="This image will characterize the media",
  207. upload_to=original_thumbnail_file_path,
  208. processors=[ResizeToFit(width=720, height=None)],
  209. format="JPEG",
  210. options={"quality": 85},
  211. blank=True,
  212. max_length=500,
  213. )
  214. user = models.ForeignKey("users.User", on_delete=models.CASCADE, help_text="user that uploads the media")
  215. user_featured = models.BooleanField(default=False, help_text="Featured by the user")
  216. video_height = models.IntegerField(default=1)
  217. views = models.IntegerField(db_index=True, default=1)
  218. # keep track if media file has changed, on saves
  219. __original_media_file = None
  220. __original_thumbnail_time = None
  221. __original_uploaded_poster = None
  222. class Meta:
  223. ordering = ["-add_date"]
  224. indexes = [
  225. # TODO: check with pgdash.io or other tool what index need be
  226. # removed
  227. GinIndex(fields=["search"])
  228. ]
  229. def __str__(self):
  230. return self.title
  231. def __init__(self, *args, **kwargs):
  232. super(Media, self).__init__(*args, **kwargs)
  233. # keep track if media file has changed, on saves
  234. # thus know when another media was uploaded
  235. # or when thumbnail time change - for videos to
  236. # grep for thumbnail, or even when a new image
  237. # was added as the media poster
  238. self.__original_media_file = self.media_file
  239. self.__original_thumbnail_time = self.thumbnail_time
  240. self.__original_uploaded_poster = self.uploaded_poster
  241. def save(self, *args, **kwargs):
  242. if not self.title:
  243. self.title = self.media_file.path.split("/")[-1]
  244. strip_text_items = ["title", "description"]
  245. for item in strip_text_items:
  246. setattr(self, item, strip_tags(getattr(self, item, None)))
  247. self.title = self.title[:99]
  248. # if thumbnail_time specified, keep up to single digit
  249. if self.thumbnail_time:
  250. self.thumbnail_time = round(self.thumbnail_time, 1)
  251. # by default get an add_date of now
  252. if not self.add_date:
  253. self.add_date = timezone.now()
  254. if not self.friendly_token:
  255. # get a unique identifier
  256. while True:
  257. friendly_token = helpers.produce_friendly_token()
  258. if not Media.objects.filter(friendly_token=friendly_token):
  259. self.friendly_token = friendly_token
  260. break
  261. if self.pk:
  262. # media exists
  263. # check case where another media file was uploaded
  264. if self.media_file != self.__original_media_file:
  265. # set this otherwise gets to infinite loop
  266. self.__original_media_file = self.media_file
  267. self.media_init()
  268. # for video files, if user specified a different time
  269. # to automatically grub thumbnail
  270. if self.thumbnail_time != self.__original_thumbnail_time:
  271. self.__original_thumbnail_time = self.thumbnail_time
  272. self.set_thumbnail(force=True)
  273. else:
  274. # media is going to be created now
  275. # after media is saved, post_save signal will call media_init function
  276. # to take care of post save steps
  277. self.state = helpers.get_default_state(user=self.user)
  278. # condition to appear on listings
  279. if self.state == "public" and self.encoding_status == "success" and self.is_reviewed is True:
  280. self.listable = True
  281. else:
  282. self.listable = False
  283. super(Media, self).save(*args, **kwargs)
  284. # produce a thumbnail out of an uploaded poster
  285. # will run only when a poster is uploaded for the first time
  286. if self.uploaded_poster and self.uploaded_poster != self.__original_uploaded_poster:
  287. with open(self.uploaded_poster.path, "rb") as f:
  288. # set this otherwise gets to infinite loop
  289. self.__original_uploaded_poster = self.uploaded_poster
  290. myfile = File(f)
  291. thumbnail_name = helpers.get_file_name(self.uploaded_poster.path)
  292. self.uploaded_thumbnail.save(content=myfile, name=thumbnail_name)
  293. def update_search_vector(self):
  294. """
  295. Update SearchVector field of SearchModel using raw SQL
  296. search field is used to store SearchVector
  297. """
  298. db_table = self._meta.db_table
  299. # first get anything interesting out of the media
  300. # that needs to be search able
  301. a_tags = b_tags = ""
  302. if self.id:
  303. a_tags = " ".join([tag.title for tag in self.tags.all()])
  304. b_tags = " ".join([tag.title.replace("-", " ") for tag in self.tags.all()])
  305. items = [
  306. self.title,
  307. self.user.username,
  308. self.user.email,
  309. self.user.name,
  310. self.description,
  311. a_tags,
  312. b_tags,
  313. ]
  314. items = [item for item in items if item]
  315. text = " ".join(items)
  316. text = " ".join([token for token in text.lower().split(" ") if token not in STOP_WORDS])
  317. text = helpers.clean_query(text)
  318. sql_code = """
  319. UPDATE {db_table} SET search = to_tsvector(
  320. '{config}', '{text}'
  321. ) WHERE {db_table}.id = {id}
  322. """.format(
  323. db_table=db_table, config="simple", text=text, id=self.id
  324. )
  325. try:
  326. with connection.cursor() as cursor:
  327. cursor.execute(sql_code)
  328. except BaseException:
  329. pass # TODO:add log
  330. return True
  331. def media_init(self):
  332. """Normally this is called when a media is uploaded
  333. Performs all related tasks, as check for media type,
  334. video duration, encode
  335. """
  336. self.set_media_type()
  337. if self.media_type == "video":
  338. self.set_thumbnail(force=True)
  339. self.produce_sprite_from_video()
  340. self.encode()
  341. elif self.media_type == "image":
  342. self.set_thumbnail(force=True)
  343. return True
  344. def set_media_type(self, save=True):
  345. """Sets media type on Media
  346. Set encoding_status as success for non video
  347. content since all listings filter for encoding_status success
  348. """
  349. kind = helpers.get_file_type(self.media_file.path)
  350. if kind is not None:
  351. if kind == "image":
  352. self.media_type = "image"
  353. elif kind == "pdf":
  354. self.media_type = "pdf"
  355. if self.media_type in ["audio", "image", "pdf"]:
  356. self.encoding_status = "success"
  357. else:
  358. ret = helpers.media_file_info(self.media_file.path)
  359. if ret.get("fail"):
  360. self.media_type = ""
  361. self.encoding_status = "fail"
  362. elif ret.get("is_video") or ret.get("is_audio"):
  363. try:
  364. self.media_info = json.dumps(ret)
  365. except TypeError:
  366. self.media_info = ""
  367. self.md5sum = ret.get("md5sum")
  368. self.size = helpers.show_file_size(ret.get("file_size"))
  369. else:
  370. self.media_type = ""
  371. self.encoding_status = "fail"
  372. audio_file_with_thumb = False
  373. # handle case where a file identified as video is actually an
  374. # audio file with thumbnail
  375. if ret.get("is_video"):
  376. # case where Media is video. try to set useful
  377. # metadata as duration/height
  378. self.media_type = "video"
  379. self.duration = int(round(float(ret.get("video_duration", 0))))
  380. self.video_height = int(ret.get("video_height"))
  381. if ret.get("video_info", {}).get("codec_name", {}) in ["mjpeg"]:
  382. audio_file_with_thumb = True
  383. if ret.get("is_audio") or audio_file_with_thumb:
  384. self.media_type = "audio"
  385. self.duration = int(float(ret.get("audio_info", {}).get("duration", 0)))
  386. self.encoding_status = "success"
  387. if save:
  388. self.save(
  389. update_fields=[
  390. "listable",
  391. "media_type",
  392. "duration",
  393. "media_info",
  394. "video_height",
  395. "size",
  396. "md5sum",
  397. "encoding_status",
  398. ]
  399. )
  400. return True
  401. def set_thumbnail(self, force=False):
  402. """sets thumbnail for media
  403. For video call function to produce thumbnail and poster
  404. For image save thumbnail and poster, this will perform
  405. resize action
  406. """
  407. if force or (not self.thumbnail):
  408. if self.media_type == "video":
  409. self.produce_thumbnails_from_video()
  410. if self.media_type == "image":
  411. with open(self.media_file.path, "rb") as f:
  412. myfile = File(f)
  413. thumbnail_name = helpers.get_file_name(self.media_file.path) + ".jpg"
  414. self.thumbnail.save(content=myfile, name=thumbnail_name)
  415. self.poster.save(content=myfile, name=thumbnail_name)
  416. return True
  417. def produce_thumbnails_from_video(self):
  418. """Produce thumbnail and poster for media
  419. Only for video types. Uses ffmpeg
  420. """
  421. if not self.media_type == "video":
  422. return False
  423. if self.thumbnail_time and 0 <= self.thumbnail_time < self.duration:
  424. thumbnail_time = self.thumbnail_time
  425. else:
  426. thumbnail_time = round(random.uniform(0, self.duration - 0.1), 1)
  427. self.thumbnail_time = thumbnail_time # so that it gets saved
  428. tf = helpers.create_temp_file(suffix=".jpg")
  429. command = [
  430. settings.FFMPEG_COMMAND,
  431. "-ss",
  432. str(thumbnail_time), # -ss need to be firt here otherwise time taken is huge
  433. "-i",
  434. self.media_file.path,
  435. "-vframes",
  436. "1",
  437. "-y",
  438. tf,
  439. ]
  440. helpers.run_command(command)
  441. if os.path.exists(tf) and helpers.get_file_type(tf) == "image":
  442. with open(tf, "rb") as f:
  443. myfile = File(f)
  444. thumbnail_name = helpers.get_file_name(self.media_file.path) + ".jpg"
  445. self.thumbnail.save(content=myfile, name=thumbnail_name)
  446. self.poster.save(content=myfile, name=thumbnail_name)
  447. helpers.rm_file(tf)
  448. return True
  449. def produce_sprite_from_video(self):
  450. """Start a task that will produce a sprite file
  451. To be used on the video player
  452. """
  453. from . import tasks
  454. tasks.produce_sprite_from_video.delay(self.friendly_token)
  455. return True
  456. def encode(self, profiles=[], force=True, chunkize=True):
  457. """Start video encoding tasks
  458. Create a task per EncodeProfile object, after checking height
  459. so that no EncodeProfile for highter heights than the video
  460. are created
  461. """
  462. if not profiles:
  463. profiles = EncodeProfile.objects.filter(active=True)
  464. profiles = list(profiles)
  465. from . import tasks
  466. # attempt to break media file in chunks
  467. if self.duration > settings.CHUNKIZE_VIDEO_DURATION and chunkize:
  468. for profile in profiles:
  469. if profile.extension == "gif":
  470. profiles.remove(profile)
  471. encoding = Encoding(media=self, profile=profile)
  472. encoding.save()
  473. enc_url = settings.SSL_FRONTEND_HOST + encoding.get_absolute_url()
  474. tasks.encode_media.apply_async(
  475. args=[self.friendly_token, profile.id, encoding.id, enc_url],
  476. kwargs={"force": force},
  477. priority=0,
  478. )
  479. profiles = [p.id for p in profiles]
  480. tasks.chunkize_media.delay(self.friendly_token, profiles, force=force)
  481. else:
  482. for profile in profiles:
  483. if profile.extension != "gif":
  484. if self.video_height and self.video_height < profile.resolution:
  485. if profile.resolution not in settings.MINIMUM_RESOLUTIONS_TO_ENCODE:
  486. continue
  487. encoding = Encoding(media=self, profile=profile)
  488. encoding.save()
  489. enc_url = settings.SSL_FRONTEND_HOST + encoding.get_absolute_url()
  490. if profile.resolution in settings.MINIMUM_RESOLUTIONS_TO_ENCODE:
  491. priority = 9
  492. else:
  493. priority = 0
  494. tasks.encode_media.apply_async(
  495. args=[self.friendly_token, profile.id, encoding.id, enc_url],
  496. kwargs={"force": force},
  497. priority=priority,
  498. )
  499. return True
  500. def post_encode_actions(self, encoding=None, action=None):
  501. """perform things after encode has run
  502. whether it has failed or succeeded
  503. """
  504. self.set_encoding_status()
  505. # set a preview url
  506. if encoding:
  507. if self.media_type == "video" and encoding.profile.extension == "gif":
  508. if action == "delete":
  509. self.preview_file_path = ""
  510. else:
  511. self.preview_file_path = encoding.media_file.path
  512. self.save(update_fields=["listable", "preview_file_path"])
  513. self.save(update_fields=["encoding_status", "listable"])
  514. if encoding and encoding.status == "success" and encoding.profile.codec == "h264" and action == "add":
  515. from . import tasks
  516. tasks.create_hls(self.friendly_token)
  517. return True
  518. def set_encoding_status(self):
  519. """Set encoding_status for videos
  520. Set success if at least one mp4 or webm exists
  521. """
  522. mp4_statuses = set(encoding.status for encoding in self.encodings.filter(profile__extension="mp4", chunk=False))
  523. webm_statuses = set(encoding.status for encoding in self.encodings.filter(profile__extension="webm", chunk=False))
  524. if not mp4_statuses and not webm_statuses:
  525. encoding_status = "pending"
  526. elif "success" in mp4_statuses or "success" in webm_statuses:
  527. encoding_status = "success"
  528. elif "running" in mp4_statuses or "running" in webm_statuses:
  529. encoding_status = "running"
  530. else:
  531. encoding_status = "fail"
  532. self.encoding_status = encoding_status
  533. return True
  534. @property
  535. def encodings_info(self, full=False):
  536. """Property used on serializers"""
  537. ret = {}
  538. if self.media_type not in ["video"]:
  539. return ret
  540. for key in ENCODE_RESOLUTIONS_KEYS:
  541. ret[key] = {}
  542. for encoding in self.encodings.select_related("profile").filter(chunk=False):
  543. if encoding.profile.extension == "gif":
  544. continue
  545. enc = self.get_encoding_info(encoding, full=full)
  546. resolution = encoding.profile.resolution
  547. ret[resolution][encoding.profile.codec] = enc
  548. # TODO: the following code is untested/needs optimization
  549. # if a file is broken in chunks and they are being
  550. # encoded, the final encoding file won't appear until
  551. # they are finished. Thus, produce the info for these
  552. if full:
  553. extra = []
  554. for encoding in self.encodings.select_related("profile").filter(chunk=True):
  555. resolution = encoding.profile.resolution
  556. if not ret[resolution].get(encoding.profile.codec):
  557. extra.append(encoding.profile.codec)
  558. for codec in extra:
  559. ret[resolution][codec] = {}
  560. v = self.encodings.filter(chunk=True, profile__codec=codec).values("progress")
  561. ret[resolution][codec]["progress"] = sum([p["progress"] for p in v]) / v.count()
  562. # TODO; status/logs/errors
  563. return ret
  564. def get_encoding_info(self, encoding, full=False):
  565. """Property used on serializers"""
  566. ep = {}
  567. ep["title"] = encoding.profile.name
  568. ep["url"] = encoding.media_encoding_url
  569. ep["progress"] = encoding.progress
  570. ep["size"] = encoding.size
  571. ep["encoding_id"] = encoding.id
  572. ep["status"] = encoding.status
  573. if full:
  574. ep["logs"] = encoding.logs
  575. ep["worker"] = encoding.worker
  576. ep["retries"] = encoding.retries
  577. if encoding.total_run_time:
  578. ep["total_run_time"] = encoding.total_run_time
  579. if encoding.commands:
  580. ep["commands"] = encoding.commands
  581. ep["time_started"] = encoding.add_date
  582. ep["updated_time"] = encoding.update_date
  583. return ep
  584. @property
  585. def categories_info(self):
  586. """Property used on serializers"""
  587. ret = []
  588. for cat in self.category.all():
  589. ret.append({"title": cat.title, "url": cat.get_absolute_url()})
  590. return ret
  591. @property
  592. def tags_info(self):
  593. """Property used on serializers"""
  594. ret = []
  595. for tag in self.tags.all():
  596. ret.append({"title": tag.title, "url": tag.get_absolute_url()})
  597. return ret
  598. @property
  599. def original_media_url(self):
  600. """Property used on serializers"""
  601. if settings.SHOW_ORIGINAL_MEDIA:
  602. return helpers.url_from_path(self.media_file.path)
  603. else:
  604. return None
  605. @property
  606. def thumbnail_url(self):
  607. """Property used on serializers
  608. Prioritize uploaded_thumbnail, if exists, then thumbnail
  609. that is auto-generated
  610. """
  611. if self.uploaded_thumbnail:
  612. return helpers.url_from_path(self.uploaded_thumbnail.path)
  613. if self.thumbnail:
  614. return helpers.url_from_path(self.thumbnail.path)
  615. return None
  616. @property
  617. def poster_url(self):
  618. """Property used on serializers
  619. Prioritize uploaded_poster, if exists, then poster
  620. that is auto-generated
  621. """
  622. if self.uploaded_poster:
  623. return helpers.url_from_path(self.uploaded_poster.path)
  624. if self.poster:
  625. return helpers.url_from_path(self.poster.path)
  626. return None
  627. @property
  628. def subtitles_info(self):
  629. """Property used on serializers
  630. Returns subtitles info
  631. """
  632. ret = []
  633. for subtitle in self.subtitles.all():
  634. ret.append(
  635. {
  636. "src": helpers.url_from_path(subtitle.subtitle_file.path),
  637. "srclang": subtitle.language.code,
  638. "label": subtitle.language.title,
  639. }
  640. )
  641. return ret
  642. @property
  643. def sprites_url(self):
  644. """Property used on serializers
  645. Returns sprites url
  646. """
  647. if self.sprites:
  648. return helpers.url_from_path(self.sprites.path)
  649. return None
  650. @property
  651. def preview_url(self):
  652. """Property used on serializers
  653. Returns preview url
  654. """
  655. if self.preview_file_path:
  656. return helpers.url_from_path(self.preview_file_path)
  657. # get preview_file out of the encodings, since some times preview_file_path
  658. # is empty but there is the gif encoding!
  659. preview_media = self.encodings.filter(profile__extension="gif").first()
  660. if preview_media and preview_media.media_file:
  661. return helpers.url_from_path(preview_media.media_file.path)
  662. return None
  663. @property
  664. def hls_info(self):
  665. """Property used on serializers
  666. Returns hls info, curated to be read by video.js
  667. """
  668. res = {}
  669. if self.hls_file:
  670. if os.path.exists(self.hls_file):
  671. hls_file = self.hls_file
  672. p = os.path.dirname(hls_file)
  673. m3u8_obj = m3u8.load(hls_file)
  674. if os.path.exists(hls_file):
  675. res["master_file"] = helpers.url_from_path(hls_file)
  676. for iframe_playlist in m3u8_obj.iframe_playlists:
  677. uri = os.path.join(p, iframe_playlist.uri)
  678. if os.path.exists(uri):
  679. resolution = iframe_playlist.iframe_stream_info.resolution[1]
  680. res["{}_iframe".format(resolution)] = helpers.url_from_path(uri)
  681. for playlist in m3u8_obj.playlists:
  682. uri = os.path.join(p, playlist.uri)
  683. if os.path.exists(uri):
  684. resolution = playlist.stream_info.resolution[1]
  685. res["{}_playlist".format(resolution)] = helpers.url_from_path(uri)
  686. return res
  687. @property
  688. def author_name(self):
  689. return self.user.name
  690. @property
  691. def author_username(self):
  692. return self.user.username
  693. def author_profile(self):
  694. return self.user.get_absolute_url()
  695. def author_thumbnail(self):
  696. return helpers.url_from_path(self.user.logo.path)
  697. def get_absolute_url(self, api=False, edit=False):
  698. if edit:
  699. return reverse("edit_media") + "?m={0}".format(self.friendly_token)
  700. if api:
  701. return reverse("api_get_media", kwargs={"friendly_token": self.friendly_token})
  702. else:
  703. return reverse("get_media") + "?m={0}".format(self.friendly_token)
  704. @property
  705. def edit_url(self):
  706. return self.get_absolute_url(edit=True)
  707. @property
  708. def add_subtitle_url(self):
  709. return "/add_subtitle?m=%s" % self.friendly_token
  710. @property
  711. def ratings_info(self):
  712. """Property used on ratings
  713. If ratings functionality enabled
  714. """
  715. # to be used if user ratings are allowed
  716. ret = []
  717. if not settings.ALLOW_RATINGS:
  718. return []
  719. for category in self.rating_category.filter(enabled=True):
  720. ret.append(
  721. {
  722. "score": -1,
  723. # default score, means no score. In case user has already
  724. # rated for this media, it will be populated
  725. "category_id": category.id,
  726. "category_title": category.title,
  727. }
  728. )
  729. return ret
  730. class License(models.Model):
  731. """A Base license model to be used in Media"""
  732. title = models.CharField(max_length=100, unique=True)
  733. description = models.TextField(blank=True)
  734. def __str__(self):
  735. return self.title
  736. class Category(models.Model):
  737. """A Category base model"""
  738. uid = models.UUIDField(unique=True, default=uuid.uuid4)
  739. add_date = models.DateTimeField(auto_now_add=True)
  740. title = models.CharField(max_length=100, unique=True, db_index=True)
  741. description = models.TextField(blank=True)
  742. user = models.ForeignKey("users.User", on_delete=models.CASCADE, blank=True, null=True)
  743. is_global = models.BooleanField(default=False, help_text="global categories or user specific")
  744. media_count = models.IntegerField(default=0, help_text="number of media")
  745. thumbnail = ProcessedImageField(
  746. upload_to=category_thumb_path,
  747. processors=[ResizeToFit(width=344, height=None)],
  748. format="JPEG",
  749. options={"quality": 85},
  750. blank=True,
  751. )
  752. listings_thumbnail = models.CharField(max_length=400, blank=True, null=True, help_text="Thumbnail to show on listings")
  753. def __str__(self):
  754. return self.title
  755. class Meta:
  756. ordering = ["title"]
  757. verbose_name_plural = "Categories"
  758. def get_absolute_url(self):
  759. return reverse("search") + "?c={0}".format(self.title)
  760. def update_category_media(self):
  761. """Set media_count"""
  762. self.media_count = Media.objects.filter(listable=True, category=self).count()
  763. self.save(update_fields=["media_count"])
  764. return True
  765. @property
  766. def thumbnail_url(self):
  767. """Return thumbnail for category
  768. prioritize processed value of listings_thumbnail
  769. then thumbnail
  770. """
  771. if self.listings_thumbnail:
  772. return self.listings_thumbnail
  773. if self.thumbnail:
  774. return helpers.url_from_path(self.thumbnail.path)
  775. media = Media.objects.filter(category=self, state="public").order_by("-views").first()
  776. if media:
  777. return media.thumbnail_url
  778. return None
  779. def save(self, *args, **kwargs):
  780. strip_text_items = ["title", "description"]
  781. for item in strip_text_items:
  782. setattr(self, item, strip_tags(getattr(self, item, None)))
  783. super(Category, self).save(*args, **kwargs)
  784. class Tag(models.Model):
  785. """A Tag model"""
  786. title = models.CharField(max_length=100, unique=True, db_index=True)
  787. user = models.ForeignKey("users.User", on_delete=models.CASCADE, blank=True, null=True)
  788. media_count = models.IntegerField(default=0, help_text="number of media")
  789. listings_thumbnail = models.CharField(
  790. max_length=400,
  791. blank=True,
  792. null=True,
  793. help_text="Thumbnail to show on listings",
  794. db_index=True,
  795. )
  796. def __str__(self):
  797. return self.title
  798. class Meta:
  799. ordering = ["title"]
  800. def get_absolute_url(self):
  801. return reverse("search") + "?t={0}".format(self.title)
  802. def update_tag_media(self):
  803. self.media_count = Media.objects.filter(state="public", is_reviewed=True, tags=self).count()
  804. self.save(update_fields=["media_count"])
  805. return True
  806. def save(self, *args, **kwargs):
  807. self.title = slugify(self.title[:99])
  808. strip_text_items = ["title"]
  809. for item in strip_text_items:
  810. setattr(self, item, strip_tags(getattr(self, item, None)))
  811. super(Tag, self).save(*args, **kwargs)
  812. @property
  813. def thumbnail_url(self):
  814. if self.listings_thumbnail:
  815. return self.listings_thumbnail
  816. media = Media.objects.filter(tags=self, state="public").order_by("-views").first()
  817. if media:
  818. return media.thumbnail_url
  819. return None
  820. class EncodeProfile(models.Model):
  821. """Encode Profile model
  822. keeps information for each profile
  823. """
  824. name = models.CharField(max_length=90)
  825. extension = models.CharField(max_length=10, choices=ENCODE_EXTENSIONS)
  826. resolution = models.IntegerField(choices=ENCODE_RESOLUTIONS, blank=True, null=True)
  827. codec = models.CharField(max_length=10, choices=CODECS, blank=True, null=True)
  828. description = models.TextField(blank=True, help_text="description")
  829. active = models.BooleanField(default=True)
  830. def __str__(self):
  831. return self.name
  832. class Meta:
  833. ordering = ["resolution"]
  834. class Encoding(models.Model):
  835. """Encoding Media Instances"""
  836. add_date = models.DateTimeField(auto_now_add=True)
  837. commands = models.TextField(blank=True, help_text="commands run")
  838. chunk = models.BooleanField(default=False, db_index=True, help_text="is chunk?")
  839. chunk_file_path = models.CharField(max_length=400, blank=True)
  840. chunks_info = models.TextField(blank=True)
  841. logs = models.TextField(blank=True)
  842. md5sum = models.CharField(max_length=50, blank=True, null=True)
  843. media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name="encodings")
  844. media_file = models.FileField("encoding file", upload_to=encoding_media_file_path, blank=True, max_length=500)
  845. profile = models.ForeignKey(EncodeProfile, on_delete=models.CASCADE)
  846. progress = models.PositiveSmallIntegerField(default=0)
  847. update_date = models.DateTimeField(auto_now=True)
  848. retries = models.IntegerField(default=0)
  849. size = models.CharField(max_length=20, blank=True)
  850. status = models.CharField(max_length=20, choices=MEDIA_ENCODING_STATUS, default="pending")
  851. temp_file = models.CharField(max_length=400, blank=True)
  852. task_id = models.CharField(max_length=100, blank=True)
  853. total_run_time = models.IntegerField(default=0)
  854. worker = models.CharField(max_length=100, blank=True)
  855. @property
  856. def media_encoding_url(self):
  857. if self.media_file:
  858. return helpers.url_from_path(self.media_file.path)
  859. return None
  860. @property
  861. def media_chunk_url(self):
  862. if self.chunk_file_path:
  863. return helpers.url_from_path(self.chunk_file_path)
  864. return None
  865. def save(self, *args, **kwargs):
  866. if self.media_file:
  867. cmd = ["stat", "-c", "%s", self.media_file.path]
  868. stdout = helpers.run_command(cmd).get("out")
  869. if stdout:
  870. size = int(stdout.strip())
  871. self.size = helpers.show_file_size(size)
  872. if self.chunk_file_path and not self.md5sum:
  873. cmd = ["md5sum", self.chunk_file_path]
  874. stdout = helpers.run_command(cmd).get("out")
  875. if stdout:
  876. md5sum = stdout.strip().split()[0]
  877. self.md5sum = md5sum
  878. super(Encoding, self).save(*args, **kwargs)
  879. def set_progress(self, progress, commit=True):
  880. if isinstance(progress, int):
  881. if 0 <= progress <= 100:
  882. self.progress = progress
  883. self.save(update_fields=["progress"])
  884. return True
  885. return False
  886. def __str__(self):
  887. return "{0}-{1}".format(self.profile.name, self.media.title)
  888. def get_absolute_url(self):
  889. return reverse("api_get_encoding", kwargs={"encoding_id": self.id})
  890. class Language(models.Model):
  891. """Language model
  892. to be used with Subtitles
  893. """
  894. code = models.CharField(max_length=12, help_text="language code")
  895. title = models.CharField(max_length=100, help_text="language code")
  896. class Meta:
  897. ordering = ["id"]
  898. def __str__(self):
  899. return "{0}-{1}".format(self.code, self.title)
  900. class Subtitle(models.Model):
  901. """Subtitles model"""
  902. language = models.ForeignKey(Language, on_delete=models.CASCADE)
  903. media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name="subtitles")
  904. subtitle_file = models.FileField(
  905. "Subtitle/CC file",
  906. help_text="File has to be WebVTT format",
  907. upload_to=subtitles_file_path,
  908. max_length=500,
  909. )
  910. user = models.ForeignKey("users.User", on_delete=models.CASCADE)
  911. def __str__(self):
  912. return "{0}-{1}".format(self.media.title, self.language.title)
  913. class RatingCategory(models.Model):
  914. """Rating Category
  915. Facilitate user ratings.
  916. One or more rating categories per Category can exist
  917. will be shown to the media if they are enabled
  918. """
  919. description = models.TextField(blank=True)
  920. enabled = models.BooleanField(default=True)
  921. title = models.CharField(max_length=200, unique=True, db_index=True)
  922. class Meta:
  923. verbose_name_plural = "Rating Categories"
  924. def __str__(self):
  925. return "{0}".format(self.title)
  926. def validate_rating(value):
  927. if -1 >= value or value > 5:
  928. raise ValidationError("score has to be between 0 and 5")
  929. class Rating(models.Model):
  930. """User Rating"""
  931. add_date = models.DateTimeField(auto_now_add=True)
  932. media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name="ratings")
  933. rating_category = models.ForeignKey(RatingCategory, on_delete=models.CASCADE)
  934. score = models.IntegerField(validators=[validate_rating])
  935. user = models.ForeignKey("users.User", on_delete=models.CASCADE)
  936. class Meta:
  937. verbose_name_plural = "Ratings"
  938. indexes = [
  939. models.Index(fields=["user", "media"]),
  940. ]
  941. unique_together = ("user", "media", "rating_category")
  942. def __str__(self):
  943. return "{0}, rate for {1} for category {2}".format(self.user.username, self.media.title, self.rating_category.title)
  944. class Playlist(models.Model):
  945. """Playlists model"""
  946. add_date = models.DateTimeField(auto_now_add=True, db_index=True)
  947. description = models.TextField(blank=True, help_text="description")
  948. friendly_token = models.CharField(blank=True, max_length=12, db_index=True)
  949. media = models.ManyToManyField(Media, through="playlistmedia", blank=True)
  950. title = models.CharField(max_length=100, db_index=True)
  951. uid = models.UUIDField(unique=True, default=uuid.uuid4)
  952. user = models.ForeignKey("users.User", on_delete=models.CASCADE, db_index=True, related_name="playlists")
  953. def __str__(self):
  954. return self.title
  955. @property
  956. def media_count(self):
  957. return self.media.count()
  958. def get_absolute_url(self, api=False):
  959. if api:
  960. return reverse("api_get_playlist", kwargs={"friendly_token": self.friendly_token})
  961. else:
  962. return reverse("get_playlist", kwargs={"friendly_token": self.friendly_token})
  963. @property
  964. def url(self):
  965. return self.get_absolute_url()
  966. @property
  967. def api_url(self):
  968. return self.get_absolute_url(api=True)
  969. def user_thumbnail_url(self):
  970. if self.user.logo:
  971. return helpers.url_from_path(self.user.logo.path)
  972. return None
  973. def set_ordering(self, media, ordering):
  974. if media not in self.media.all():
  975. return False
  976. pm = PlaylistMedia.objects.filter(playlist=self, media=media).first()
  977. if pm and isinstance(ordering, int) and 0 < ordering:
  978. pm.ordering = ordering
  979. pm.save()
  980. return True
  981. return False
  982. def save(self, *args, **kwargs):
  983. strip_text_items = ["title", "description"]
  984. for item in strip_text_items:
  985. setattr(self, item, strip_tags(getattr(self, item, None)))
  986. self.title = self.title[:99]
  987. if not self.friendly_token:
  988. while True:
  989. friendly_token = helpers.produce_friendly_token()
  990. if not Playlist.objects.filter(friendly_token=friendly_token):
  991. self.friendly_token = friendly_token
  992. break
  993. super(Playlist, self).save(*args, **kwargs)
  994. @property
  995. def thumbnail_url(self):
  996. pm = self.playlistmedia_set.first()
  997. if pm and pm.media.thumbnail:
  998. return helpers.url_from_path(pm.media.thumbnail.path)
  999. return None
  1000. class PlaylistMedia(models.Model):
  1001. """Helper model to store playlist specific media"""
  1002. action_date = models.DateTimeField(auto_now=True)
  1003. media = models.ForeignKey(Media, on_delete=models.CASCADE)
  1004. playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE)
  1005. ordering = models.IntegerField(default=1)
  1006. class Meta:
  1007. ordering = ["ordering", "-action_date"]
  1008. class Comment(MPTTModel):
  1009. """Comments model"""
  1010. add_date = models.DateTimeField(auto_now_add=True)
  1011. media = models.ForeignKey(Media, on_delete=models.CASCADE, db_index=True, related_name="comments")
  1012. parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
  1013. text = models.TextField(help_text="text")
  1014. uid = models.UUIDField(unique=True, default=uuid.uuid4)
  1015. user = models.ForeignKey("users.User", on_delete=models.CASCADE, db_index=True)
  1016. class MPTTMeta:
  1017. order_insertion_by = ["add_date"]
  1018. def __str__(self):
  1019. return "On {0} by {1}".format(self.media.title, self.user.username)
  1020. def save(self, *args, **kwargs):
  1021. strip_text_items = ["text"]
  1022. for item in strip_text_items:
  1023. setattr(self, item, strip_tags(getattr(self, item, None)))
  1024. if self.text:
  1025. self.text = self.text[: settings.MAX_CHARS_FOR_COMMENT]
  1026. super(Comment, self).save(*args, **kwargs)
  1027. def get_absolute_url(self):
  1028. return reverse("get_media") + "?m={0}".format(self.media.friendly_token)
  1029. @property
  1030. def media_url(self):
  1031. return self.get_absolute_url()
  1032. @receiver(post_save, sender=Media)
  1033. def media_save(sender, instance, created, **kwargs):
  1034. # media_file path is not set correctly until mode is saved
  1035. # post_save signal will take care of calling a few functions
  1036. # once model is saved
  1037. # SOS: do not put anything here, as if more logic is added,
  1038. # we have to disconnect signal to avoid infinite recursion
  1039. if created:
  1040. from .methods import notify_users
  1041. instance.media_init()
  1042. notify_users(friendly_token=instance.friendly_token, action="media_added")
  1043. instance.user.update_user_media()
  1044. if instance.category.all():
  1045. # this won't catch when a category
  1046. # is removed from a media, which is what we want...
  1047. for category in instance.category.all():
  1048. category.update_category_media()
  1049. if instance.tags.all():
  1050. for tag in instance.tags.all():
  1051. tag.update_tag_media()
  1052. instance.update_search_vector()
  1053. @receiver(pre_delete, sender=Media)
  1054. def media_file_pre_delete(sender, instance, **kwargs):
  1055. if instance.category.all():
  1056. for category in instance.category.all():
  1057. instance.category.remove(category)
  1058. category.update_category_media()
  1059. if instance.tags.all():
  1060. for tag in instance.tags.all():
  1061. instance.tags.remove(tag)
  1062. tag.update_tag_media()
  1063. @receiver(post_delete, sender=Media)
  1064. def media_file_delete(sender, instance, **kwargs):
  1065. """
  1066. Deletes file from filesystem
  1067. when corresponding `Media` object is deleted.
  1068. """
  1069. if instance.media_file:
  1070. helpers.rm_file(instance.media_file.path)
  1071. if instance.thumbnail:
  1072. helpers.rm_file(instance.thumbnail.path)
  1073. if instance.poster:
  1074. helpers.rm_file(instance.poster.path)
  1075. if instance.uploaded_thumbnail:
  1076. helpers.rm_file(instance.uploaded_thumbnail.path)
  1077. if instance.uploaded_poster:
  1078. helpers.rm_file(instance.uploaded_poster.path)
  1079. if instance.sprites:
  1080. helpers.rm_file(instance.sprites.path)
  1081. if instance.hls_file:
  1082. p = os.path.dirname(instance.hls_file)
  1083. helpers.rm_dir(p)
  1084. instance.user.update_user_media()
  1085. @receiver(m2m_changed, sender=Media.category.through)
  1086. def media_m2m(sender, instance, **kwargs):
  1087. if instance.category.all():
  1088. for category in instance.category.all():
  1089. category.update_category_media()
  1090. if instance.tags.all():
  1091. for tag in instance.tags.all():
  1092. tag.update_tag_media()
  1093. @receiver(post_save, sender=Encoding)
  1094. def encoding_file_save(sender, instance, created, **kwargs):
  1095. """Performs actions on encoding file delete
  1096. For example, if encoding is a chunk file, with encoding_status success,
  1097. perform a check if this is the final chunk file of a media, then
  1098. concatenate chunks, create final encoding file and delete chunks
  1099. """
  1100. if instance.chunk and instance.status == "success":
  1101. # a chunk got completed
  1102. # check if all chunks are OK
  1103. # then concatenate to new Encoding - and remove chunks
  1104. # this should run only once!
  1105. if instance.media_file:
  1106. try:
  1107. orig_chunks = json.loads(instance.chunks_info).keys()
  1108. except BaseException:
  1109. instance.delete()
  1110. return False
  1111. chunks = Encoding.objects.filter(
  1112. media=instance.media,
  1113. profile=instance.profile,
  1114. chunks_info=instance.chunks_info,
  1115. chunk=True,
  1116. ).order_by("add_date")
  1117. complete = True
  1118. # perform validation, make sure everything is there
  1119. for chunk in orig_chunks:
  1120. if not chunks.filter(chunk_file_path=chunk):
  1121. complete = False
  1122. break
  1123. for chunk in chunks:
  1124. if not (chunk.media_file and chunk.media_file.path):
  1125. complete = False
  1126. break
  1127. if complete:
  1128. # concatenate chunks and create final encoding file
  1129. chunks_paths = [f.media_file.path for f in chunks]
  1130. with tempfile.TemporaryDirectory(dir=settings.TEMP_DIRECTORY) as temp_dir:
  1131. seg_file = helpers.create_temp_file(suffix=".txt", dir=temp_dir)
  1132. tf = helpers.create_temp_file(suffix=".{0}".format(instance.profile.extension), dir=temp_dir)
  1133. with open(seg_file, "w") as ff:
  1134. for f in chunks_paths:
  1135. ff.write("file {}\n".format(f))
  1136. cmd = [
  1137. settings.FFMPEG_COMMAND,
  1138. "-y",
  1139. "-f",
  1140. "concat",
  1141. "-safe",
  1142. "0",
  1143. "-i",
  1144. seg_file,
  1145. "-c",
  1146. "copy",
  1147. "-pix_fmt",
  1148. "yuv420p",
  1149. "-movflags",
  1150. "faststart",
  1151. tf,
  1152. ]
  1153. stdout = helpers.run_command(cmd)
  1154. encoding = Encoding(
  1155. media=instance.media,
  1156. profile=instance.profile,
  1157. status="success",
  1158. progress=100,
  1159. )
  1160. all_logs = "\n".join([st.logs for st in chunks])
  1161. encoding.logs = "{0}\n{1}\n{2}".format(chunks_paths, stdout, all_logs)
  1162. workers = list(set([st.worker for st in chunks]))
  1163. encoding.worker = json.dumps({"workers": workers})
  1164. start_date = min([st.add_date for st in chunks])
  1165. end_date = max([st.update_date for st in chunks])
  1166. encoding.total_run_time = (end_date - start_date).seconds
  1167. encoding.save()
  1168. with open(tf, "rb") as f:
  1169. myfile = File(f)
  1170. output_name = "{0}.{1}".format(
  1171. helpers.get_file_name(instance.media.media_file.path),
  1172. instance.profile.extension,
  1173. )
  1174. encoding.media_file.save(content=myfile, name=output_name)
  1175. # encoding is saved, deleting chunks
  1176. # and any other encoding that might exist
  1177. # first perform one last validation
  1178. # to avoid that this is run twice
  1179. if (
  1180. len(orig_chunks)
  1181. == Encoding.objects.filter( # noqa
  1182. media=instance.media,
  1183. profile=instance.profile,
  1184. chunks_info=instance.chunks_info,
  1185. ).count()
  1186. ):
  1187. # if two chunks are finished at the same time, this
  1188. # will be changed
  1189. who = Encoding.objects.filter(media=encoding.media, profile=encoding.profile).exclude(id=encoding.id)
  1190. who.delete()
  1191. else:
  1192. encoding.delete()
  1193. if not Encoding.objects.filter(chunks_info=instance.chunks_info):
  1194. # TODO: in case of remote workers, files should be deleted
  1195. # example
  1196. # for worker in workers:
  1197. # for chunk in json.loads(instance.chunks_info).keys():
  1198. # remove_media_file.delay(media_file=chunk)
  1199. for chunk in json.loads(instance.chunks_info).keys():
  1200. helpers.rm_file(chunk)
  1201. instance.media.post_encode_actions(encoding=instance, action="add")
  1202. elif instance.chunk and instance.status == "fail":
  1203. encoding = Encoding(media=instance.media, profile=instance.profile, status="fail", progress=100)
  1204. chunks = Encoding.objects.filter(media=instance.media, chunks_info=instance.chunks_info, chunk=True).order_by("add_date")
  1205. chunks_paths = [f.media_file.path for f in chunks]
  1206. all_logs = "\n".join([st.logs for st in chunks])
  1207. encoding.logs = "{0}\n{1}".format(chunks_paths, all_logs)
  1208. workers = list(set([st.worker for st in chunks]))
  1209. encoding.worker = json.dumps({"workers": workers})
  1210. start_date = min([st.add_date for st in chunks])
  1211. end_date = max([st.update_date for st in chunks])
  1212. encoding.total_run_time = (end_date - start_date).seconds
  1213. encoding.save()
  1214. who = Encoding.objects.filter(media=encoding.media, profile=encoding.profile).exclude(id=encoding.id)
  1215. who.delete()
  1216. # TODO: merge with above if, do not repeat code
  1217. else:
  1218. if instance.status in ["fail", "success"]:
  1219. instance.media.post_encode_actions(encoding=instance, action="add")
  1220. encodings = set([encoding.status for encoding in Encoding.objects.filter(media=instance.media)])
  1221. if ("running" in encodings) or ("pending" in encodings):
  1222. return
  1223. @receiver(post_delete, sender=Encoding)
  1224. def encoding_file_delete(sender, instance, **kwargs):
  1225. """
  1226. Deletes file from filesystem
  1227. when corresponding `Encoding` object is deleted.
  1228. """
  1229. if instance.media_file:
  1230. helpers.rm_file(instance.media_file.path)
  1231. if not instance.chunk:
  1232. instance.media.post_encode_actions(encoding=instance, action="delete")
  1233. # delete local chunks, and remote chunks + media file. Only when the
  1234. # last encoding of a media is complete