models.py 54 KB

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