-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.py
104 lines (90 loc) · 3.3 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import datetime
import logging
import re
from django_ffmpeg.models import Video, ConvertingCommand
from pytz import timezone
logger = logging.getLogger(__name__)
class Converter(object):
def convert(self):
# Choosing one unconverted video
try:
video = Video.objects.filter(convert_status='pending')[0]
except IndexError:
logger.info('No video found. Bypassing call...')
return
video.convert_status = 'started'
video.save()
# Choosing converting command
filepath = video.video.path
full_name = filepath.split('/')[-1]
video_info = {
'name': full_name,
'extension': full_name.split('.')[-1],
}
cmds = ConvertingCommand.objects.filter(is_enabled=True)
cmd = None
for c in cmds:
data = video_info.get(c.match_by)
if not data:
continue
if re.match(c.match_regex, data):
cmd = c
break
if not cmd:
logger.error('Conversion command not found...')
video.convert_status = 'error'
video.last_convert_msg = 'Conversion command not found'
video.save()
return
# Convert video
video.convert_extension = cmd.convert_extension
try:
c = cmd.command % {
'input_file': filepath,
'output_file': video.converted_path,
}
logger.info('Converting video command: %s' % c)
output = self._cli(c)
logger.info('Converting video result: %s' % output)
except Exception as e:
logger.error('Converting video error', exc_info=True)
video.convert_status = 'error'
video.last_convert_msg = 'Exception while converting'
video.save()
raise
# Convert thumb
try:
if not video.thumb:
cmd = cmd.thumb_command % {
'in_file' : filepath,
'out_file' : video.thumb_video_path,
'thumb_frame' : video.thumb_frame,
}
self._cli(cmd, True)
logger.info('Creating thumbnail command: %s' % cmd)
except:
logger.error('Converting thumb error', exc_info=True)
video.convert_status = 'error' \
if output and output.find('Conversion failed') != -1 \
else 'converted'
video.last_convert_msg = repr(output).replace('\\n', '\n').strip('\'')
video.converted_at = datetime.datetime.now(tz=timezone('UTC'))
video.save()
def _cli(self, cmd, without_output=False):
import os
import subprocess
import sys
if sys.version_info[0] > 2:
res = subprocess.getstatusoutput(cmd)
if not without_output and res and len(res):
return res[1]
elif os.name == 'posix':
import commands
return commands.getoutput(cmd)
else:
if without_output:
DEVNULL = open(os.devnull, 'wb')
subprocess.Popen(cmd, stdout=DEVNULL, stderr=DEVNULL)
else:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return p.stdout.read()