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