models.py 55 KB

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