models.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  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. helpers.clean_query(self.title),
  307. self.user.username,
  308. self.user.email,
  309. self.user.name,
  310. helpers.clean_query(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. sql_code = """
  318. UPDATE {db_table} SET search = to_tsvector(
  319. '{config}', '{text}'
  320. ) WHERE {db_table}.id = {id}
  321. """.format(
  322. db_table=db_table, config="simple", text=text, id=self.id
  323. )
  324. try:
  325. with connection.cursor() as cursor:
  326. cursor.execute(sql_code)
  327. except BaseException:
  328. pass # TODO:add log
  329. return True
  330. def media_init(self):
  331. """Normally this is called when a media is uploaded
  332. Performs all related tasks, as check for media type,
  333. video duration, encode
  334. """
  335. self.set_media_type()
  336. if self.media_type == "video":
  337. self.set_thumbnail(force=True)
  338. self.produce_sprite_from_video()
  339. self.encode()
  340. elif self.media_type == "image":
  341. self.set_thumbnail(force=True)
  342. return True
  343. def set_media_type(self, save=True):
  344. """Sets media type on Media
  345. Set encoding_status as success for non video
  346. content since all listings filter for encoding_status success
  347. """
  348. kind = helpers.get_file_type(self.media_file.path)
  349. if kind is not None:
  350. if kind == "image":
  351. self.media_type = "image"
  352. elif kind == "pdf":
  353. self.media_type = "pdf"
  354. if self.media_type in ["image", "pdf"]:
  355. self.encoding_status = "success"
  356. else:
  357. ret = helpers.media_file_info(self.media_file.path)
  358. if ret.get("fail"):
  359. self.media_type = ""
  360. self.encoding_status = "fail"
  361. elif ret.get("is_video") or ret.get("is_audio"):
  362. try:
  363. self.media_info = json.dumps(ret)
  364. except TypeError:
  365. self.media_info = ""
  366. self.md5sum = ret.get("md5sum")
  367. self.size = helpers.show_file_size(ret.get("file_size"))
  368. else:
  369. self.media_type = ""
  370. self.encoding_status = "fail"
  371. if ret.get("is_video"):
  372. # case where Media is video. try to set useful
  373. # metadata as duration/height
  374. self.media_type = "video"
  375. self.duration = int(round(float(ret.get("video_duration", 0))))
  376. self.video_height = int(ret.get("video_height"))
  377. elif ret.get("is_audio"):
  378. self.media_type = "audio"
  379. self.duration = int(float(ret.get("audio_info", {}).get("duration", 0)))
  380. self.encoding_status = "success"
  381. if save:
  382. self.save(
  383. update_fields=[
  384. "listable",
  385. "media_type",
  386. "duration",
  387. "media_info",
  388. "video_height",
  389. "size",
  390. "md5sum",
  391. "encoding_status",
  392. ]
  393. )
  394. return True
  395. def set_thumbnail(self, force=False):
  396. """sets thumbnail for media
  397. For video call function to produce thumbnail and poster
  398. For image save thumbnail and poster, this will perform
  399. resize action
  400. """
  401. if force or (not self.thumbnail):
  402. if self.media_type == "video":
  403. self.produce_thumbnails_from_video()
  404. if self.media_type == "image":
  405. with open(self.media_file.path, "rb") as f:
  406. myfile = File(f)
  407. thumbnail_name = helpers.get_file_name(self.media_file.path) + ".jpg"
  408. self.thumbnail.save(content=myfile, name=thumbnail_name)
  409. self.poster.save(content=myfile, name=thumbnail_name)
  410. return True
  411. def produce_thumbnails_from_video(self):
  412. """Produce thumbnail and poster for media
  413. Only for video types. Uses ffmpeg
  414. """
  415. if not self.media_type == "video":
  416. return False
  417. if self.thumbnail_time and 0 <= self.thumbnail_time < self.duration:
  418. thumbnail_time = self.thumbnail_time
  419. else:
  420. thumbnail_time = round(random.uniform(0, self.duration - 0.1), 1)
  421. self.thumbnail_time = thumbnail_time # so that it gets saved
  422. tf = helpers.create_temp_file(suffix=".jpg")
  423. command = [
  424. settings.FFMPEG_COMMAND,
  425. "-ss",
  426. str(thumbnail_time), # -ss need to be firt here otherwise time taken is huge
  427. "-i",
  428. self.media_file.path,
  429. "-vframes",
  430. "1",
  431. "-y",
  432. tf,
  433. ]
  434. helpers.run_command(command)
  435. if os.path.exists(tf) and helpers.get_file_type(tf) == "image":
  436. with open(tf, "rb") as f:
  437. myfile = File(f)
  438. thumbnail_name = helpers.get_file_name(self.media_file.path) + ".jpg"
  439. self.thumbnail.save(content=myfile, name=thumbnail_name)
  440. self.poster.save(content=myfile, name=thumbnail_name)
  441. helpers.rm_file(tf)
  442. return True
  443. def produce_sprite_from_video(self):
  444. """Start a task that will produce a sprite file
  445. To be used on the video player
  446. """
  447. from . import tasks
  448. tasks.produce_sprite_from_video.delay(self.friendly_token)
  449. return True
  450. def encode(self, profiles=[], force=True, chunkize=True):
  451. """Start video encoding tasks
  452. Create a task per EncodeProfile object, after checking height
  453. so that no EncodeProfile for highter heights than the video
  454. are created
  455. """
  456. if not profiles:
  457. profiles = EncodeProfile.objects.filter(active=True)
  458. profiles = list(profiles)
  459. from . import tasks
  460. # attempt to break media file in chunks
  461. if self.duration > settings.CHUNKIZE_VIDEO_DURATION and chunkize:
  462. for profile in profiles:
  463. if profile.extension == "gif":
  464. profiles.remove(profile)
  465. encoding = Encoding(media=self, profile=profile)
  466. encoding.save()
  467. enc_url = settings.SSL_FRONTEND_HOST + encoding.get_absolute_url()
  468. tasks.encode_media.apply_async(
  469. args=[self.friendly_token, profile.id, encoding.id, enc_url],
  470. kwargs={"force": force},
  471. priority=0,
  472. )
  473. profiles = [p.id for p in profiles]
  474. tasks.chunkize_media.delay(self.friendly_token, profiles, force=force)
  475. else:
  476. for profile in profiles:
  477. if profile.extension != "gif":
  478. if self.video_height and self.video_height < profile.resolution:
  479. if profile.resolution not in settings.MINIMUM_RESOLUTIONS_TO_ENCODE:
  480. continue
  481. encoding = Encoding(media=self, profile=profile)
  482. encoding.save()
  483. enc_url = settings.SSL_FRONTEND_HOST + encoding.get_absolute_url()
  484. if profile.resolution in settings.MINIMUM_RESOLUTIONS_TO_ENCODE:
  485. priority = 9
  486. else:
  487. priority = 0
  488. tasks.encode_media.apply_async(
  489. args=[self.friendly_token, profile.id, encoding.id, enc_url],
  490. kwargs={"force": force},
  491. priority=priority,
  492. )
  493. return True
  494. def post_encode_actions(self, encoding=None, action=None):
  495. """perform things after encode has run
  496. whether it has failed or succeeded
  497. """
  498. self.set_encoding_status()
  499. # set a preview url
  500. if encoding:
  501. if self.media_type == "video" and encoding.profile.extension == "gif":
  502. if action == "delete":
  503. self.preview_file_path = ""
  504. else:
  505. self.preview_file_path = encoding.media_file.path
  506. self.save(update_fields=["listable", "preview_file_path"])
  507. self.save(update_fields=["encoding_status", "listable"])
  508. if encoding and encoding.status == "success" and encoding.profile.codec == "h264" and action == "add":
  509. from . import tasks
  510. tasks.create_hls(self.friendly_token)
  511. return True
  512. def set_encoding_status(self):
  513. """Set encoding_status for videos
  514. Set success if at least one mp4 exists
  515. """
  516. mp4_statuses = set(encoding.status for encoding in self.encodings.filter(profile__extension="mp4", chunk=False))
  517. if not mp4_statuses:
  518. encoding_status = "pending"
  519. elif "success" in mp4_statuses:
  520. encoding_status = "success"
  521. elif "running" in mp4_statuses:
  522. encoding_status = "running"
  523. else:
  524. encoding_status = "fail"
  525. self.encoding_status = encoding_status
  526. return True
  527. @property
  528. def encodings_info(self, full=False):
  529. """Property used on serializers"""
  530. ret = {}
  531. if self.media_type not in ["video"]:
  532. return ret
  533. for key in ENCODE_RESOLUTIONS_KEYS:
  534. ret[key] = {}
  535. for encoding in self.encodings.select_related("profile").filter(chunk=False):
  536. if encoding.profile.extension == "gif":
  537. continue
  538. enc = self.get_encoding_info(encoding, full=full)
  539. resolution = encoding.profile.resolution
  540. ret[resolution][encoding.profile.codec] = enc
  541. # TODO: the following code is untested/needs optimization
  542. # if a file is broken in chunks and they are being
  543. # encoded, the final encoding file won't appear until
  544. # they are finished. Thus, produce the info for these
  545. if full:
  546. extra = []
  547. for encoding in self.encodings.select_related("profile").filter(chunk=True):
  548. resolution = encoding.profile.resolution
  549. if not ret[resolution].get(encoding.profile.codec):
  550. extra.append(encoding.profile.codec)
  551. for codec in extra:
  552. ret[resolution][codec] = {}
  553. v = self.encodings.filter(chunk=True, profile__codec=codec).values("progress")
  554. ret[resolution][codec]["progress"] = sum([p["progress"] for p in v]) / v.count()
  555. # TODO; status/logs/errors
  556. return ret
  557. def get_encoding_info(self, encoding, full=False):
  558. """Property used on serializers"""
  559. ep = {}
  560. ep["title"] = encoding.profile.name
  561. ep["url"] = encoding.media_encoding_url
  562. ep["progress"] = encoding.progress
  563. ep["size"] = encoding.size
  564. ep["encoding_id"] = encoding.id
  565. ep["status"] = encoding.status
  566. if full:
  567. ep["logs"] = encoding.logs
  568. ep["worker"] = encoding.worker
  569. ep["retries"] = encoding.retries
  570. if encoding.total_run_time:
  571. ep["total_run_time"] = encoding.total_run_time
  572. if encoding.commands:
  573. ep["commands"] = encoding.commands
  574. ep["time_started"] = encoding.add_date
  575. ep["updated_time"] = encoding.update_date
  576. return ep
  577. @property
  578. def categories_info(self):
  579. """Property used on serializers"""
  580. ret = []
  581. for cat in self.category.all():
  582. ret.append({"title": cat.title, "url": cat.get_absolute_url()})
  583. return ret
  584. @property
  585. def tags_info(self):
  586. """Property used on serializers"""
  587. ret = []
  588. for tag in self.tags.all():
  589. ret.append({"title": tag.title, "url": tag.get_absolute_url()})
  590. return ret
  591. @property
  592. def original_media_url(self):
  593. """Property used on serializers"""
  594. if settings.SHOW_ORIGINAL_MEDIA:
  595. return helpers.url_from_path(self.media_file.path)
  596. else:
  597. return None
  598. @property
  599. def thumbnail_url(self):
  600. """Property used on serializers
  601. Prioritize uploaded_thumbnail, if exists, then thumbnail
  602. that is auto-generated
  603. """
  604. if self.uploaded_thumbnail:
  605. return helpers.url_from_path(self.uploaded_thumbnail.path)
  606. if self.thumbnail:
  607. return helpers.url_from_path(self.thumbnail.path)
  608. return None
  609. @property
  610. def poster_url(self):
  611. """Property used on serializers
  612. Prioritize uploaded_poster, if exists, then poster
  613. that is auto-generated
  614. """
  615. if self.uploaded_poster:
  616. return helpers.url_from_path(self.uploaded_poster.path)
  617. if self.poster:
  618. return helpers.url_from_path(self.poster.path)
  619. return None
  620. @property
  621. def subtitles_info(self):
  622. """Property used on serializers
  623. Returns subtitles info
  624. """
  625. ret = []
  626. for subtitle in self.subtitles.all():
  627. ret.append(
  628. {
  629. "src": helpers.url_from_path(subtitle.subtitle_file.path),
  630. "srclang": subtitle.language.code,
  631. "label": subtitle.language.title,
  632. }
  633. )
  634. return ret
  635. @property
  636. def sprites_url(self):
  637. """Property used on serializers
  638. Returns sprites url
  639. """
  640. if self.sprites:
  641. return helpers.url_from_path(self.sprites.path)
  642. return None
  643. @property
  644. def preview_url(self):
  645. """Property used on serializers
  646. Returns preview url
  647. """
  648. if self.preview_file_path:
  649. return helpers.url_from_path(self.preview_file_path)
  650. # get preview_file out of the encodings, since some times preview_file_path
  651. # is empty but there is the gif encoding!
  652. preview_media = self.encodings.filter(profile__extension="gif").first()
  653. if preview_media and preview_media.media_file:
  654. return helpers.url_from_path(preview_media.media_file.path)
  655. return None
  656. @property
  657. def hls_info(self):
  658. """Property used on serializers
  659. Returns hls info, curated to be read by video.js
  660. """
  661. res = {}
  662. if self.hls_file:
  663. if os.path.exists(self.hls_file):
  664. hls_file = self.hls_file
  665. p = os.path.dirname(hls_file)
  666. m3u8_obj = m3u8.load(hls_file)
  667. if os.path.exists(hls_file):
  668. res["master_file"] = helpers.url_from_path(hls_file)
  669. for iframe_playlist in m3u8_obj.iframe_playlists:
  670. uri = os.path.join(p, iframe_playlist.uri)
  671. if os.path.exists(uri):
  672. resolution = iframe_playlist.iframe_stream_info.resolution[1]
  673. res["{}_iframe".format(resolution)] = helpers.url_from_path(uri)
  674. for playlist in m3u8_obj.playlists:
  675. uri = os.path.join(p, playlist.uri)
  676. if os.path.exists(uri):
  677. resolution = playlist.stream_info.resolution[1]
  678. res["{}_playlist".format(resolution)] = helpers.url_from_path(uri)
  679. return res
  680. @property
  681. def author_name(self):
  682. return self.user.name
  683. @property
  684. def author_username(self):
  685. return self.user.username
  686. def author_profile(self):
  687. return self.user.get_absolute_url()
  688. def author_thumbnail(self):
  689. return helpers.url_from_path(self.user.logo.path)
  690. def get_absolute_url(self, api=False, edit=False):
  691. if edit:
  692. return reverse("edit_media") + "?m={0}".format(self.friendly_token)
  693. if api:
  694. return reverse("api_get_media", kwargs={"friendly_token": self.friendly_token})
  695. else:
  696. return reverse("get_media") + "?m={0}".format(self.friendly_token)
  697. @property
  698. def edit_url(self):
  699. return self.get_absolute_url(edit=True)
  700. @property
  701. def add_subtitle_url(self):
  702. return "/add_subtitle?m=%s" % self.friendly_token
  703. @property
  704. def ratings_info(self):
  705. """Property used on ratings
  706. If ratings functionality enabled
  707. """
  708. # to be used if user ratings are allowed
  709. ret = []
  710. if not settings.ALLOW_RATINGS:
  711. return []
  712. for category in self.rating_category.filter(enabled=True):
  713. ret.append(
  714. {
  715. "score": -1,
  716. # default score, means no score. In case user has already
  717. # rated for this media, it will be populated
  718. "category_id": category.id,
  719. "category_title": category.title,
  720. }
  721. )
  722. return ret
  723. class License(models.Model):
  724. """A Base license model to be used in Media"""
  725. title = models.CharField(max_length=100, unique=True)
  726. description = models.TextField(blank=True)
  727. def __str__(self):
  728. return self.title
  729. class Category(models.Model):
  730. """A Category base model"""
  731. uid = models.UUIDField(unique=True, default=uuid.uuid4)
  732. add_date = models.DateTimeField(auto_now_add=True)
  733. title = models.CharField(max_length=100, unique=True, db_index=True)
  734. description = models.TextField(blank=True)
  735. user = models.ForeignKey("users.User", on_delete=models.CASCADE, blank=True, null=True)
  736. is_global = models.BooleanField(default=False, help_text="global categories or user specific")
  737. media_count = models.IntegerField(default=0, help_text="number of media")
  738. thumbnail = ProcessedImageField(
  739. upload_to=category_thumb_path,
  740. processors=[ResizeToFit(width=344, height=None)],
  741. format="JPEG",
  742. options={"quality": 85},
  743. blank=True,
  744. )
  745. listings_thumbnail = models.CharField(max_length=400, blank=True, null=True, help_text="Thumbnail to show on listings")
  746. def __str__(self):
  747. return self.title
  748. class Meta:
  749. ordering = ["title"]
  750. verbose_name_plural = "Categories"
  751. def get_absolute_url(self):
  752. return reverse("search") + "?c={0}".format(self.title)
  753. def update_category_media(self):
  754. """Set media_count"""
  755. self.media_count = Media.objects.filter(listable=True, category=self).count()
  756. self.save(update_fields=["media_count"])
  757. return True
  758. @property
  759. def thumbnail_url(self):
  760. """Return thumbnail for category
  761. prioritize processed value of listings_thumbnail
  762. then thumbnail
  763. """
  764. if self.listings_thumbnail:
  765. return self.listings_thumbnail
  766. if self.thumbnail:
  767. return helpers.url_from_path(self.thumbnail.path)
  768. media = Media.objects.filter(category=self, state="public").order_by("-views").first()
  769. if media:
  770. return media.thumbnail_url
  771. return None
  772. def save(self, *args, **kwargs):
  773. strip_text_items = ["title", "description"]
  774. for item in strip_text_items:
  775. setattr(self, item, strip_tags(getattr(self, item, None)))
  776. super(Category, self).save(*args, **kwargs)
  777. class Tag(models.Model):
  778. """A Tag model"""
  779. title = models.CharField(max_length=100, unique=True, db_index=True)
  780. user = models.ForeignKey("users.User", on_delete=models.CASCADE, blank=True, null=True)
  781. media_count = models.IntegerField(default=0, help_text="number of media")
  782. listings_thumbnail = models.CharField(
  783. max_length=400,
  784. blank=True,
  785. null=True,
  786. help_text="Thumbnail to show on listings",
  787. db_index=True,
  788. )
  789. def __str__(self):
  790. return self.title
  791. class Meta:
  792. ordering = ["title"]
  793. def get_absolute_url(self):
  794. return reverse("search") + "?t={0}".format(self.title)
  795. def update_tag_media(self):
  796. self.media_count = Media.objects.filter(state="public", is_reviewed=True, tags=self).count()
  797. self.save(update_fields=["media_count"])
  798. return True
  799. def save(self, *args, **kwargs):
  800. self.title = slugify(self.title[:99])
  801. strip_text_items = ["title"]
  802. for item in strip_text_items:
  803. setattr(self, item, strip_tags(getattr(self, item, None)))
  804. super(Tag, self).save(*args, **kwargs)
  805. @property
  806. def thumbnail_url(self):
  807. if self.listings_thumbnail:
  808. return self.listings_thumbnail
  809. media = Media.objects.filter(tags=self, state="public").order_by("-views").first()
  810. if media:
  811. return media.thumbnail_url
  812. return None
  813. class EncodeProfile(models.Model):
  814. """Encode Profile model
  815. keeps information for each profile
  816. """
  817. name = models.CharField(max_length=90)
  818. extension = models.CharField(max_length=10, choices=ENCODE_EXTENSIONS)
  819. resolution = models.IntegerField(choices=ENCODE_RESOLUTIONS, blank=True, null=True)
  820. codec = models.CharField(max_length=10, choices=CODECS, blank=True, null=True)
  821. description = models.TextField(blank=True, help_text="description")
  822. active = models.BooleanField(default=True)
  823. def __str__(self):
  824. return self.name
  825. class Meta:
  826. ordering = ["resolution"]
  827. class Encoding(models.Model):
  828. """Encoding Media Instances"""
  829. add_date = models.DateTimeField(auto_now_add=True)
  830. commands = models.TextField(blank=True, help_text="commands run")
  831. chunk = models.BooleanField(default=False, db_index=True, help_text="is chunk?")
  832. chunk_file_path = models.CharField(max_length=400, blank=True)
  833. chunks_info = models.TextField(blank=True)
  834. logs = models.TextField(blank=True)
  835. md5sum = models.CharField(max_length=50, blank=True, null=True)
  836. media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name="encodings")
  837. media_file = models.FileField("encoding file", upload_to=encoding_media_file_path, blank=True, max_length=500)
  838. profile = models.ForeignKey(EncodeProfile, on_delete=models.CASCADE)
  839. progress = models.PositiveSmallIntegerField(default=0)
  840. update_date = models.DateTimeField(auto_now=True)
  841. retries = models.IntegerField(default=0)
  842. size = models.CharField(max_length=20, blank=True)
  843. status = models.CharField(max_length=20, choices=MEDIA_ENCODING_STATUS, default="pending")
  844. temp_file = models.CharField(max_length=400, blank=True)
  845. task_id = models.CharField(max_length=100, blank=True)
  846. total_run_time = models.IntegerField(default=0)
  847. worker = models.CharField(max_length=100, blank=True)
  848. @property
  849. def media_encoding_url(self):
  850. if self.media_file:
  851. return helpers.url_from_path(self.media_file.path)
  852. return None
  853. @property
  854. def media_chunk_url(self):
  855. if self.chunk_file_path:
  856. return helpers.url_from_path(self.chunk_file_path)
  857. return None
  858. def save(self, *args, **kwargs):
  859. if self.media_file:
  860. cmd = ["stat", "-c", "%s", self.media_file.path]
  861. stdout = helpers.run_command(cmd).get("out")
  862. if stdout:
  863. size = int(stdout.strip())
  864. self.size = helpers.show_file_size(size)
  865. if self.chunk_file_path and not self.md5sum:
  866. cmd = ["md5sum", self.chunk_file_path]
  867. stdout = helpers.run_command(cmd).get("out")
  868. if stdout:
  869. md5sum = stdout.strip().split()[0]
  870. self.md5sum = md5sum
  871. super(Encoding, self).save(*args, **kwargs)
  872. def set_progress(self, progress, commit=True):
  873. if isinstance(progress, int):
  874. if 0 <= progress <= 100:
  875. self.progress = progress
  876. self.save(update_fields=["progress"])
  877. return True
  878. return False
  879. def __str__(self):
  880. return "{0}-{1}".format(self.profile.name, self.media.title)
  881. def get_absolute_url(self):
  882. return reverse("api_get_encoding", kwargs={"encoding_id": self.id})
  883. class Language(models.Model):
  884. """Language model
  885. to be used with Subtitles
  886. """
  887. code = models.CharField(max_length=12, help_text="language code")
  888. title = models.CharField(max_length=100, help_text="language code")
  889. class Meta:
  890. ordering = ["id"]
  891. def __str__(self):
  892. return "{0}-{1}".format(self.code, self.title)
  893. class Subtitle(models.Model):
  894. """Subtitles model"""
  895. language = models.ForeignKey(Language, on_delete=models.CASCADE)
  896. media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name="subtitles")
  897. subtitle_file = models.FileField(
  898. "Subtitle/CC file",
  899. help_text="File has to be WebVTT format",
  900. upload_to=subtitles_file_path,
  901. max_length=500,
  902. )
  903. user = models.ForeignKey("users.User", on_delete=models.CASCADE)
  904. def __str__(self):
  905. return "{0}-{1}".format(self.media.title, self.language.title)
  906. class RatingCategory(models.Model):
  907. """Rating Category
  908. Facilitate user ratings.
  909. One or more rating categories per Category can exist
  910. will be shown to the media if they are enabled
  911. """
  912. description = models.TextField(blank=True)
  913. enabled = models.BooleanField(default=True)
  914. title = models.CharField(max_length=200, unique=True, db_index=True)
  915. class Meta:
  916. verbose_name_plural = "Rating Categories"
  917. def __str__(self):
  918. return "{0}".format(self.title)
  919. def validate_rating(value):
  920. if -1 >= value or value > 5:
  921. raise ValidationError("score has to be between 0 and 5")
  922. class Rating(models.Model):
  923. """User Rating"""
  924. add_date = models.DateTimeField(auto_now_add=True)
  925. media = models.ForeignKey(Media, on_delete=models.CASCADE, related_name="ratings")
  926. rating_category = models.ForeignKey(RatingCategory, on_delete=models.CASCADE)
  927. score = models.IntegerField(validators=[validate_rating])
  928. user = models.ForeignKey("users.User", on_delete=models.CASCADE)
  929. class Meta:
  930. verbose_name_plural = "Ratings"
  931. indexes = [
  932. models.Index(fields=["user", "media"]),
  933. ]
  934. unique_together = ("user", "media", "rating_category")
  935. def __str__(self):
  936. return "{0}, rate for {1} for category {2}".format(self.user.username, self.media.title, self.rating_category.title)
  937. class Playlist(models.Model):
  938. """Playlists model"""
  939. add_date = models.DateTimeField(auto_now_add=True, db_index=True)
  940. description = models.TextField(blank=True, help_text="description")
  941. friendly_token = models.CharField(blank=True, max_length=12, db_index=True)
  942. media = models.ManyToManyField(Media, through="playlistmedia", blank=True)
  943. title = models.CharField(max_length=100, db_index=True)
  944. uid = models.UUIDField(unique=True, default=uuid.uuid4)
  945. user = models.ForeignKey("users.User", on_delete=models.CASCADE, db_index=True, related_name="playlists")
  946. def __str__(self):
  947. return self.title
  948. @property
  949. def media_count(self):
  950. return self.media.count()
  951. def get_absolute_url(self, api=False):
  952. if api:
  953. return reverse("api_get_playlist", kwargs={"friendly_token": self.friendly_token})
  954. else:
  955. return reverse("get_playlist", kwargs={"friendly_token": self.friendly_token})
  956. @property
  957. def url(self):
  958. return self.get_absolute_url()
  959. @property
  960. def api_url(self):
  961. return self.get_absolute_url(api=True)
  962. def user_thumbnail_url(self):
  963. if self.user.logo:
  964. return helpers.url_from_path(self.user.logo.path)
  965. return None
  966. def set_ordering(self, media, ordering):
  967. if media not in self.media.all():
  968. return False
  969. pm = PlaylistMedia.objects.filter(playlist=self, media=media).first()
  970. if pm and isinstance(ordering, int) and 0 < ordering:
  971. pm.ordering = ordering
  972. pm.save()
  973. return True
  974. return False
  975. def save(self, *args, **kwargs):
  976. strip_text_items = ["title", "description"]
  977. for item in strip_text_items:
  978. setattr(self, item, strip_tags(getattr(self, item, None)))
  979. self.title = self.title[:99]
  980. if not self.friendly_token:
  981. while True:
  982. friendly_token = helpers.produce_friendly_token()
  983. if not Playlist.objects.filter(friendly_token=friendly_token):
  984. self.friendly_token = friendly_token
  985. break
  986. super(Playlist, self).save(*args, **kwargs)
  987. @property
  988. def thumbnail_url(self):
  989. pm = self.playlistmedia_set.first()
  990. if pm and pm.media.thumbnail:
  991. return helpers.url_from_path(pm.media.thumbnail.path)
  992. return None
  993. class PlaylistMedia(models.Model):
  994. """Helper model to store playlist specific media"""
  995. action_date = models.DateTimeField(auto_now=True)
  996. media = models.ForeignKey(Media, on_delete=models.CASCADE)
  997. playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE)
  998. ordering = models.IntegerField(default=1)
  999. class Meta:
  1000. ordering = ["ordering", "-action_date"]
  1001. class Comment(MPTTModel):
  1002. """Comments model"""
  1003. add_date = models.DateTimeField(auto_now_add=True)
  1004. media = models.ForeignKey(Media, on_delete=models.CASCADE, db_index=True, related_name="comments")
  1005. parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
  1006. text = models.TextField(help_text="text")
  1007. uid = models.UUIDField(unique=True, default=uuid.uuid4)
  1008. user = models.ForeignKey("users.User", on_delete=models.CASCADE, db_index=True)
  1009. class MPTTMeta:
  1010. order_insertion_by = ["add_date"]
  1011. def __str__(self):
  1012. return "On {0} by {1}".format(self.media.title, self.user.username)
  1013. def save(self, *args, **kwargs):
  1014. strip_text_items = ["text"]
  1015. for item in strip_text_items:
  1016. setattr(self, item, strip_tags(getattr(self, item, None)))
  1017. if self.text:
  1018. self.text = self.text[: settings.MAX_CHARS_FOR_COMMENT]
  1019. super(Comment, self).save(*args, **kwargs)
  1020. def get_absolute_url(self):
  1021. return reverse("get_media") + "?m={0}".format(self.media.friendly_token)
  1022. @property
  1023. def media_url(self):
  1024. return self.get_absolute_url()
  1025. @receiver(post_save, sender=Media)
  1026. def media_save(sender, instance, created, **kwargs):
  1027. # media_file path is not set correctly until mode is saved
  1028. # post_save signal will take care of calling a few functions
  1029. # once model is saved
  1030. # SOS: do not put anything here, as if more logic is added,
  1031. # we have to disconnect signal to avoid infinite recursion
  1032. if created:
  1033. from .methods import notify_users
  1034. instance.media_init()
  1035. notify_users(friendly_token=instance.friendly_token, action="media_added")
  1036. instance.user.update_user_media()
  1037. if instance.category.all():
  1038. # this won't catch when a category
  1039. # is removed from a media, which is what we want...
  1040. for category in instance.category.all():
  1041. category.update_category_media()
  1042. if instance.tags.all():
  1043. for tag in instance.tags.all():
  1044. tag.update_tag_media()
  1045. instance.update_search_vector()
  1046. @receiver(pre_delete, sender=Media)
  1047. def media_file_pre_delete(sender, instance, **kwargs):
  1048. if instance.category.all():
  1049. for category in instance.category.all():
  1050. instance.category.remove(category)
  1051. category.update_category_media()
  1052. if instance.tags.all():
  1053. for tag in instance.tags.all():
  1054. instance.tags.remove(tag)
  1055. tag.update_tag_media()
  1056. @receiver(post_delete, sender=Media)
  1057. def media_file_delete(sender, instance, **kwargs):
  1058. """
  1059. Deletes file from filesystem
  1060. when corresponding `Media` object is deleted.
  1061. """
  1062. if instance.media_file:
  1063. helpers.rm_file(instance.media_file.path)
  1064. if instance.thumbnail:
  1065. helpers.rm_file(instance.thumbnail.path)
  1066. if instance.poster:
  1067. helpers.rm_file(instance.poster.path)
  1068. if instance.uploaded_thumbnail:
  1069. helpers.rm_file(instance.uploaded_thumbnail.path)
  1070. if instance.uploaded_poster:
  1071. helpers.rm_file(instance.uploaded_poster.path)
  1072. if instance.sprites:
  1073. helpers.rm_file(instance.sprites.path)
  1074. if instance.hls_file:
  1075. p = os.path.dirname(instance.hls_file)
  1076. helpers.rm_dir(p)
  1077. instance.user.update_user_media()
  1078. @receiver(m2m_changed, sender=Media.category.through)
  1079. def media_m2m(sender, instance, **kwargs):
  1080. if instance.category.all():
  1081. for category in instance.category.all():
  1082. category.update_category_media()
  1083. if instance.tags.all():
  1084. for tag in instance.tags.all():
  1085. tag.update_tag_media()
  1086. @receiver(post_save, sender=Encoding)
  1087. def encoding_file_save(sender, instance, created, **kwargs):
  1088. """Performs actions on encoding file delete
  1089. For example, if encoding is a chunk file, with encoding_status success,
  1090. perform a check if this is the final chunk file of a media, then
  1091. concatenate chunks, create final encoding file and delete chunks
  1092. """
  1093. if instance.chunk and instance.status == "success":
  1094. # a chunk got completed
  1095. # check if all chunks are OK
  1096. # then concatenate to new Encoding - and remove chunks
  1097. # this should run only once!
  1098. if instance.media_file:
  1099. try:
  1100. orig_chunks = json.loads(instance.chunks_info).keys()
  1101. except BaseException:
  1102. instance.delete()
  1103. return False
  1104. chunks = Encoding.objects.filter(
  1105. media=instance.media,
  1106. profile=instance.profile,
  1107. chunks_info=instance.chunks_info,
  1108. chunk=True,
  1109. ).order_by("add_date")
  1110. complete = True
  1111. # perform validation, make sure everything is there
  1112. for chunk in orig_chunks:
  1113. if not chunks.filter(chunk_file_path=chunk):
  1114. complete = False
  1115. break
  1116. for chunk in chunks:
  1117. if not (chunk.media_file and chunk.media_file.path):
  1118. complete = False
  1119. break
  1120. if complete:
  1121. # concatenate chunks and create final encoding file
  1122. chunks_paths = [f.media_file.path for f in chunks]
  1123. with tempfile.TemporaryDirectory(dir=settings.TEMP_DIRECTORY) as temp_dir:
  1124. seg_file = helpers.create_temp_file(suffix=".txt", dir=temp_dir)
  1125. tf = helpers.create_temp_file(suffix=".{0}".format(instance.profile.extension), dir=temp_dir)
  1126. with open(seg_file, "w") as ff:
  1127. for f in chunks_paths:
  1128. ff.write("file {}\n".format(f))
  1129. cmd = [
  1130. settings.FFMPEG_COMMAND,
  1131. "-y",
  1132. "-f",
  1133. "concat",
  1134. "-safe",
  1135. "0",
  1136. "-i",
  1137. seg_file,
  1138. "-c",
  1139. "copy",
  1140. "-pix_fmt",
  1141. "yuv420p",
  1142. "-movflags",
  1143. "faststart",
  1144. tf,
  1145. ]
  1146. stdout = helpers.run_command(cmd)
  1147. encoding = Encoding(
  1148. media=instance.media,
  1149. profile=instance.profile,
  1150. status="success",
  1151. progress=100,
  1152. )
  1153. all_logs = "\n".join([st.logs for st in chunks])
  1154. encoding.logs = "{0}\n{1}\n{2}".format(chunks_paths, stdout, all_logs)
  1155. workers = list(set([st.worker for st in chunks]))
  1156. encoding.worker = json.dumps({"workers": workers})
  1157. start_date = min([st.add_date for st in chunks])
  1158. end_date = max([st.update_date for st in chunks])
  1159. encoding.total_run_time = (end_date - start_date).seconds
  1160. encoding.save()
  1161. with open(tf, "rb") as f:
  1162. myfile = File(f)
  1163. output_name = "{0}.{1}".format(
  1164. helpers.get_file_name(instance.media.media_file.path),
  1165. instance.profile.extension,
  1166. )
  1167. encoding.media_file.save(content=myfile, name=output_name)
  1168. # encoding is saved, deleting chunks
  1169. # and any other encoding that might exist
  1170. # first perform one last validation
  1171. # to avoid that this is run twice
  1172. if (
  1173. len(orig_chunks)
  1174. == Encoding.objects.filter( # noqa
  1175. media=instance.media,
  1176. profile=instance.profile,
  1177. chunks_info=instance.chunks_info,
  1178. ).count()
  1179. ):
  1180. # if two chunks are finished at the same time, this
  1181. # will be changed
  1182. who = Encoding.objects.filter(media=encoding.media, profile=encoding.profile).exclude(id=encoding.id)
  1183. who.delete()
  1184. else:
  1185. encoding.delete()
  1186. if not Encoding.objects.filter(chunks_info=instance.chunks_info):
  1187. # TODO: in case of remote workers, files should be deleted
  1188. # example
  1189. # for worker in workers:
  1190. # for chunk in json.loads(instance.chunks_info).keys():
  1191. # remove_media_file.delay(media_file=chunk)
  1192. for chunk in json.loads(instance.chunks_info).keys():
  1193. helpers.rm_file(chunk)
  1194. instance.media.post_encode_actions(encoding=instance, action="add")
  1195. elif instance.chunk and instance.status == "fail":
  1196. encoding = Encoding(media=instance.media, profile=instance.profile, status="fail", progress=100)
  1197. chunks = Encoding.objects.filter(media=instance.media, chunks_info=instance.chunks_info, chunk=True).order_by("add_date")
  1198. chunks_paths = [f.media_file.path for f in chunks]
  1199. all_logs = "\n".join([st.logs for st in chunks])
  1200. encoding.logs = "{0}\n{1}".format(chunks_paths, all_logs)
  1201. workers = list(set([st.worker for st in chunks]))
  1202. encoding.worker = json.dumps({"workers": workers})
  1203. start_date = min([st.add_date for st in chunks])
  1204. end_date = max([st.update_date for st in chunks])
  1205. encoding.total_run_time = (end_date - start_date).seconds
  1206. encoding.save()
  1207. who = Encoding.objects.filter(media=encoding.media, profile=encoding.profile).exclude(id=encoding.id)
  1208. who.delete()
  1209. # TODO: merge with above if, do not repeat code
  1210. else:
  1211. if instance.status in ["fail", "success"]:
  1212. instance.media.post_encode_actions(encoding=instance, action="add")
  1213. encodings = set([encoding.status for encoding in Encoding.objects.filter(media=instance.media)])
  1214. if ("running" in encodings) or ("pending" in encodings):
  1215. return
  1216. @receiver(post_delete, sender=Encoding)
  1217. def encoding_file_delete(sender, instance, **kwargs):
  1218. """
  1219. Deletes file from filesystem
  1220. when corresponding `Encoding` object is deleted.
  1221. """
  1222. if instance.media_file:
  1223. helpers.rm_file(instance.media_file.path)
  1224. if not instance.chunk:
  1225. instance.media.post_encode_actions(encoding=instance, action="delete")
  1226. # delete local chunks, and remote chunks + media file. Only when the
  1227. # last encoding of a media is complete