-
Notifications
You must be signed in to change notification settings - Fork 1
/
autorip
executable file
·203 lines (178 loc) · 6.1 KB
/
autorip
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
# Copyright 2022 by Chris Osborn <[email protected]>
#
# This file is part of viddin.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License at <http://www.gnu.org/licenses/> for
# more details.
import argparse
import os, sys
from viddin import viddin
import subprocess
import time
from pytimeparse.timeparse import timeparse
VIDEO_EXT = [".mkv", ".mp4", ".webm"]
LOCK_DIR = "/var/lock"
RIPPED_DIR = "ripped"
AUTOFLAGS = "autorip-flags"
AUTOCMD = "autorip-cmd"
def build_argparser():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("directory", help="directory to scan and rip")
parser.add_argument("--check", action="store_true", help="check if there's anything to rip and exit with 0 if there is")
# parser.add_argument("--flags", default=FLAGS, help="flags to pass to rip-video")
parser.add_argument("--outtype", default=".mkv", help="file type to rip to")
parser.add_argument("--ripdir", default=RIPPED_DIR,
help="directory to put ripped files into")
parser.add_argument("--minage", help="file must be at least this old to rip")
parser.add_argument("--debug", action="store_true", help="pass debug flag")
return parser
def create_lock():
lock_file = os.path.basename(__file__) + ".pid"
lock_path = os.path.join(LOCK_DIR, lock_file)
if os.path.exists(lock_path):
with open(lock_path, "r") as f:
pid = f.readline()
try:
pid = int(pid)
except ValueError:
pid = None
pidpath = '/proc/{}'.format(pid)
if pid and os.path.isdir(pidpath):
return None
with open(lock_path, "w") as f:
f.write(str(os.getpid()))
f.write("\n")
return lock_path
def get_videos(path, minage, ignore):
result = []
now = time.time()
ignore = os.path.commonpath([ignore])
for root, dirs, files in os.walk(path):
if ignore == os.path.commonpath([ignore, root]):
print("Ignoring", root)
continue
for file in files:
base, ext = os.path.splitext(file)
if base[0] == '.' or ext not in VIDEO_EXT:
print("Not a video", base)
continue
fpath = os.path.join(root, file)
st = os.stat(fpath)
if now - st.st_mtime < minage:
print("Skipping", fpath, "age:", now - st.st_mtime)
continue
result.append(fpath)
result.sort()
return result
def find_flags(path, basedir, flags_file=AUTOFLAGS):
pathdir = os.path.dirname(path)
check_dirs = os.path.split(os.path.relpath(pathdir, basedir))
for idx in range(len(check_dirs), 0, -1):
subdir = os.path.join(*check_dirs[:idx])
flags_path = os.path.join(basedir, subdir, flags_file)
if os.path.isfile(flags_path) and os.access(flags_path, os.R_OK):
return flags_path
return None
def rip_video(path, basedir, ripdir, outtype, debugFlag=False):
subdir = os.path.relpath(os.path.dirname(path), basedir)
subdir = os.path.join(basedir, ripdir, subdir)
output = os.path.join(subdir, os.path.basename(path))
p, e = os.path.splitext(output)
output = p + outtype
log = p + ".autolog"
resolution = viddin.getResolution(path, debugFlag)
bluray = False
if resolution[0] > 1000 or resolution[1] >= 700:
bluray = True
flags_path = find_flags(path, basedir)
if flags_path is not None:
with open(flags_path) as f:
flags = f.read()
flags = flags.split()
else:
flags = ["--lang=eng"]
if bluray:
flags.extend(["--bluray"])
else:
# FIXME - detect telecine and choose between --tv and --film
flags.extend(["--tv"])
cmd = ["rip-video"]
cmd_file = find_flags(path, basedir, flags_file=AUTOCMD)
if cmd_file is not None:
with open(cmd_file) as f:
cmd = f.read()
cmd = cmd.split()
cmd.extend(flags)
if debugFlag:
flags.append("--debug")
cmd.extend([path, output])
os.makedirs(subdir, exist_ok=True)
if debugFlag:
print(cmd)
if not sys.stdout.isatty():
with open(log, "w") as logf:
p = subprocess.run(cmd, stdout=logf, stderr=subprocess.STDOUT)
else:
print("Ripping", path)
print("Flags", flags)
p = subprocess.run(cmd)
return p.returncode == 0
def delete_empty_dirs(path):
folders = list(os.walk(path))
for d, b, c in folders[::-1]:
flags = os.path.join(d, AUTOFLAGS)
existing = os.listdir(d)
if len(existing) == 1 and AUTOFLAGS in existing:
os.unlink(os.path.join(d, AUTOFLAGS))
existing.remove(AUTOFLAGS)
if len(existing) == 0:
os.rmdir(d)
return
def main():
args = build_argparser().parse_args()
minage = 0
if args.minage:
minage = timeparse(args.minage)
exit_code = 0
lock = create_lock()
if not lock:
# FIXME - check how long pid has been running and print message if more than several hours
exit_code = -1
if exit_code == 0:
if os.path.isabs(args.ripdir):
parent = os.path.abspath(args.directory)
if os.path.commonpath([parent]) != os.path.commonpath([parent, args.ripdir]):
print("ripdir must be in directory")
exit_code = -2
else:
args.ripdir = os.path.relpath(ripdir, parent)
if args.outtype[0] != '.':
args.outtype = "." + args.outtype
if exit_code == 0:
videos = get_videos(args.directory, minage, os.path.join(args.directory, args.ripdir))
if args.check:
exit_code = len(videos) == 0
else:
for v in videos:
ripped = rip_video(v, args.directory, args.ripdir, args.outtype, debugFlag=args.debug)
if ripped:
print("Ripped", v)
os.unlink(v)
else:
print("FAILED", v)
exit_code += 1
delete_empty_dirs(args.directory)
if lock:
os.unlink(lock)
return exit_code
if __name__ == '__main__':
exit(main() or 0)