models.py 55 KB

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