001package net.filebot.cli;
002
003import static java.awt.GraphicsEnvironment.*;
004import static java.util.Arrays.*;
005import static java.util.Collections.*;
006import static java.util.stream.Collectors.*;
007import static net.filebot.Logging.*;
008import static net.filebot.Settings.*;
009import static net.filebot.hash.VerificationUtilities.*;
010import static net.filebot.media.XattrMetaInfo.*;
011import static net.filebot.subtitle.SubtitleUtilities.*;
012import static net.filebot.util.FileUtilities.*;
013import static net.filebot.util.PGP.*;
014
015import java.io.File;
016import java.io.FileFilter;
017import java.io.StringWriter;
018import java.nio.charset.Charset;
019import java.nio.file.LinkOption;
020import java.util.ArrayList;
021import java.util.LinkedHashMap;
022import java.util.List;
023import java.util.Map;
024import java.util.Optional;
025import java.util.function.Supplier;
026import java.util.logging.Level;
027import java.util.regex.Pattern;
028
029import org.kohsuke.args4j.Argument;
030import org.kohsuke.args4j.CmdLineException;
031import org.kohsuke.args4j.CmdLineParser;
032import org.kohsuke.args4j.Option;
033import org.kohsuke.args4j.ParserProperties;
034import org.kohsuke.args4j.spi.ExplicitBooleanOptionHandler;
035import org.kohsuke.args4j.spi.RestOfArgumentsHandler;
036
037import net.filebot.ApplicationFolder;
038import net.filebot.Language;
039import net.filebot.RenameAction;
040import net.filebot.StandardRenameAction;
041import net.filebot.WebServices;
042import net.filebot.format.ExpressionFileFilter;
043import net.filebot.format.ExpressionFileFormat;
044import net.filebot.format.ExpressionFilter;
045import net.filebot.format.ExpressionFormat;
046import net.filebot.hash.HashType;
047import net.filebot.subtitle.SubtitleFormat;
048import net.filebot.subtitle.SubtitleNaming;
049import net.filebot.ui.PanelBuilder;
050import net.filebot.web.Datasource;
051import net.filebot.web.EpisodeListProvider;
052import net.filebot.web.SortOrder;
053
054public class ArgumentBean {
055
056        @Option(name = "--mode", usage = "Enable CLI interactive mode", metaVar = "[interactive]")
057        public String mode = null;
058
059        @Option(name = "-rename", usage = "Rename media files")
060        public boolean rename = false;
061
062        @Option(name = "--db", usage = "Database", metaVar = "[TheTVDB, AniDB, TheMovieDB::TV] or [TheMovieDB] or [AcoustID, ID3] or [xattr, exif, file]")
063        public String db;
064
065        @Option(name = "--order", usage = "Episode order", metaVar = "[Airdate, DVD, Absolute, AbsoluteAirdate]")
066        public String order = "Airdate";
067
068        @Option(name = "--action", usage = "Rename action", metaVar = "[move, copy, keeplink, symlink, hardlink, clone, test]")
069        public String action = "move";
070
071        @Option(name = "--conflict", usage = "Conflict resolution", metaVar = "[skip, override, auto, index, fail]")
072        public String conflict = "skip";
073
074        @Option(name = "--filter", usage = "Match filter expression", metaVar = "{expression}")
075        public String filter = null;
076
077        @Option(name = "--format", usage = "Format expression", metaVar = "{expression}")
078        public String format;
079
080        @Option(name = "-non-strict", usage = "Enable advanced matching and more aggressive guessing")
081        public boolean nonStrict = false;
082
083        @Option(name = "-get-subtitles", usage = "Fetch subtitles")
084        public boolean getSubtitles;
085
086        @Option(name = "--q", usage = "Force lookup query", metaVar = "series / movie query")
087        public String query;
088
089        @Option(name = "--lang", usage = "Language", metaVar = "language code")
090        public String lang = "en";
091
092        @Option(name = "-check", usage = "Create / Check verification files")
093        public boolean check;
094
095        @Option(name = "--output", usage = "Output path", metaVar = "path")
096        public String output;
097
098        @Option(name = "--encoding", usage = "Output character encoding", metaVar = "[UTF-8, Windows-1252]")
099        public String encoding;
100
101        @Option(name = "-list", usage = "Print episode list")
102        public boolean list = false;
103
104        @Option(name = "-mediainfo", usage = "Print media info")
105        public boolean mediaInfo = false;
106
107        @Option(name = "-revert", usage = "Revert files")
108        public boolean revert = false;
109
110        @Option(name = "-extract", usage = "Extract archives")
111        public boolean extract = false;
112
113        @Option(name = "-script", usage = "Run Groovy script", metaVar = "[fn:name] or [script.groovy]")
114        public String script = null;
115
116        @Option(name = "--def", usage = "Define script variables", handler = BindingsHandler.class)
117        public Map<String, String> defines = new LinkedHashMap<String, String>();
118
119        @Option(name = "-r", usage = "Recursively process folders")
120        public boolean recursive = false;
121
122        @Option(name = "--file-filter", usage = "Input file filter expression", metaVar = "{expression}")
123        public String inputFileFilter = null;
124
125        @Option(name = "-exec", usage = "Execute command", metaVar = "echo {f} [+]", handler = RestOfArgumentsHandler.class)
126        public List<String> exec = new ArrayList<String>();
127
128        @Option(name = "-unixfs", usage = "Allow special characters in file paths")
129        public boolean unixfs = false;
130
131        @Option(name = "-no-xattr", usage = "Disable extended attributes")
132        public boolean disableExtendedAttributes = false;
133
134        @Option(name = "--log", usage = "Log level", metaVar = "[all, fine, info, warning]")
135        public String log = "all";
136
137        @Option(name = "--log-file", usage = "Log file", metaVar = "log.txt")
138        public String logFile = null;
139
140        @Option(name = "--log-lock", usage = "Lock log file", metaVar = "[yes, no]", handler = ExplicitBooleanOptionHandler.class)
141        public boolean logLock = true;
142
143        @Option(name = "-clear-cache", usage = "Clear cached and temporary data")
144        public boolean clearCache = false;
145
146        @Option(name = "-clear-prefs", usage = "Clear application settings")
147        public boolean clearPrefs = false;
148
149        @Option(name = "-version", usage = "Print version identifier")
150        public boolean version = false;
151
152        @Option(name = "-help", usage = "Print this help message")
153        public boolean help = false;
154
155        @Option(name = "--license", usage = "Import license file", metaVar = "*.psm")
156        public String license = null;
157
158        @Argument
159        public List<String> arguments = new ArrayList<String>();
160
161        public boolean runCLI() {
162                return rename || getSubtitles || check || list || mediaInfo || revert || extract || script != null || (license != null && (isHeadless() || System.console() != null));
163        }
164
165        public boolean isInteractive() {
166                return "interactive".equalsIgnoreCase(mode) && System.console() != null;
167        }
168
169        public boolean printVersion() {
170                return version;
171        }
172
173        public boolean printHelp() {
174                return help;
175        }
176
177        public boolean clearCache() {
178                return clearCache;
179        }
180
181        public boolean clearUserData() {
182                return clearPrefs;
183        }
184
185        public List<File> getFiles(boolean resolveFolders) throws Exception {
186                if (arguments == null || arguments.isEmpty()) {
187                        return emptyList();
188                }
189
190                // resolve given paths
191                List<File> files = new ArrayList<File>();
192
193                for (String it : arguments) {
194                        // ignore empty arguments
195                        if (it.trim().isEmpty()) {
196                                continue;
197                        }
198
199                        // resolve relative paths
200                        File file = new File(it);
201
202                        // since we don't want to follow symlinks, we need to take the scenic route through the Path class
203                        try {
204                                file = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS).toFile();
205                        } catch (Exception e) {
206                                debug.warning(format("Illegal Argument: %s (%s)", e, file));
207                        }
208
209                        if (resolveFolders && file.isDirectory()) {
210                                if (recursive) {
211                                        files.addAll(listFiles(file, FILES, HUMAN_NAME_ORDER));
212                                } else {
213                                        files.addAll(getChildren(file, f -> f.isFile() && !f.isHidden(), HUMAN_NAME_ORDER));
214                                }
215                        } else {
216                                files.add(file);
217                        }
218                }
219
220                // input file filter (e.g. useful on Windows where find -exec is not an option)
221                if (inputFileFilter != null) {
222                        return filter(files, new ExpressionFileFilter(inputFileFilter, f -> f));
223                }
224
225                return files;
226        }
227
228        public RenameAction getRenameAction() {
229                // support custom executables (via absolute path)
230                if (action.startsWith("/")) {
231                        return new ExecutableRenameAction(action, getOutputPath());
232                }
233
234                // support custom groovy scripts (via closures)
235                if (action.startsWith("{")) {
236                        return new GroovyRenameAction(action);
237                }
238
239                return StandardRenameAction.forName(action);
240        }
241
242        public ConflictAction getConflictAction() {
243                return ConflictAction.forName(conflict);
244        }
245
246        public SortOrder getSortOrder() {
247                return SortOrder.forName(order);
248        }
249
250        public ExpressionFormat getExpressionFormat() throws Exception {
251                return format == null ? null : new ExpressionFormat(format);
252        }
253
254        public ExpressionFileFormat getExpressionFileFormat() throws Exception {
255                return format == null ? null : new ExpressionFileFormat(format);
256        }
257
258        public ExpressionFilter getExpressionFilter() throws Exception {
259                return filter == null ? null : new ExpressionFilter(filter);
260        }
261
262        public FileFilter getFileFilter() throws Exception {
263                return filter == null ? FILES : new ExpressionFileFilter(filter, xattr::getMetaInfo);
264        }
265
266        public Datasource getDatasource() {
267                return db == null ? null : WebServices.getService(db);
268        }
269
270        public EpisodeListProvider getEpisodeListProvider() {
271                return db == null ? WebServices.TheTVDB : WebServices.getEpisodeListProvider(db); // default to TheTVDB if --db is not set
272        }
273
274        public String getSearchQuery() {
275                return query == null || query.isEmpty() ? null : query;
276        }
277
278        public File getOutputPath() {
279                return output == null ? null : new File(output);
280        }
281
282        public File getAbsoluteOutputFolder() throws Exception {
283                return output == null ? null : new File(output).getCanonicalFile();
284        }
285
286        public SubtitleFormat getSubtitleOutputFormat() {
287                return output == null ? null : getSubtitleFormatByName(output);
288        }
289
290        public SubtitleNaming getSubtitleNamingFormat() {
291                return optional(format).map(SubtitleNaming::forName).orElse(SubtitleNaming.MATCH_VIDEO_ADD_LANGUAGE_TAG);
292        }
293
294        public HashType getOutputHashType() {
295                // support --output checksum.sfv
296                return optional(output).map(File::new).map(f -> getHashType(f)).orElseGet(() -> {
297                        // support --format SFV
298                        return optional(format).map(k -> getHashTypeByExtension(k)).orElse(HashType.SFV);
299                });
300        }
301
302        public Charset getEncoding() {
303                return encoding == null ? null : Charset.forName(encoding);
304        }
305
306        public Language getLanguage() {
307                // find language code for any input (en, eng, English, etc)
308                return optional(lang).map(Language::findLanguage).orElseThrow(error("Illegal language code", lang));
309        }
310
311        public File getLogFile() {
312                File file = new File(logFile);
313
314                if (file.isAbsolute()) {
315                        return file;
316                }
317
318                // by default resolve relative paths against {applicationFolder}/logs/{logFile}
319                return ApplicationFolder.AppData.resolve("logs/" + logFile);
320        }
321
322        public boolean isStrict() {
323                return !nonStrict;
324        }
325
326        public Level getLogLevel() {
327                return Level.parse(log.toUpperCase());
328        }
329
330        public ExecCommand getExecCommand() {
331                try {
332                        return exec == null || exec.isEmpty() ? null : ExecCommand.parse(exec, getOutputPath());
333                } catch (Exception e) {
334                        throw new CmdlineException("Illegal exec expression: " + exec);
335                }
336        }
337
338        public List<PanelBuilder> getPanelBuilders() {
339                if (mode == null) {
340                        // MAS does not allow subtitle applications
341                        if (isMacSandbox()) {
342                                return stream(PanelBuilder.defaultSequence()).filter(p -> !p.getName().equals("Subtitles")).collect(toList());
343                        }
344
345                        // default multi panel mode
346                        return asList(PanelBuilder.defaultSequence());
347                }
348
349                // only selected panels
350                return optional(mode).map(m -> {
351                        Pattern pattern = Pattern.compile(mode, Pattern.CASE_INSENSITIVE);
352                        List<PanelBuilder> panel = stream(PanelBuilder.defaultSequence()).filter(p -> pattern.matcher(p.getName()).matches()).collect(toList());
353
354                        // throw exception if illegal pattern was passed in
355                        if (panel.isEmpty()) {
356                                return null;
357                        }
358
359                        return panel;
360                }).orElseThrow(error("Illegal mode", mode));
361        }
362
363        public String getLicenseKey() {
364                try {
365                        return license == null || license.isEmpty() ? null : findClearSignMessage(readTextFile(new File(license)));
366                } catch (Exception e) {
367                        throw new CmdlineException("Invalid License File: " + e.getMessage(), e);
368                }
369        }
370
371        private final String[] args;
372
373        public ArgumentBean() {
374                this.args = new String[0];
375        }
376
377        public ArgumentBean(String[] args) throws CmdLineException {
378                this.args = args.clone();
379
380                CmdLineParser parser = new CmdLineParser(this);
381                parser.parseArgument(args);
382        }
383
384        public String[] getArgumentArray() {
385                return args.clone();
386        }
387
388        public String usage() {
389                StringWriter buffer = new StringWriter();
390                CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withShowDefaults(false).withOptionSorter(null));
391                parser.printUsage(buffer, null);
392                return buffer.toString();
393        }
394
395        private static <T> Optional<T> optional(T value) {
396                return Optional.ofNullable(value);
397        }
398
399        private static Supplier<CmdlineException> error(String message, Object value) {
400                return () -> new CmdlineException(message + ": " + value);
401        }
402
403        @Override
404        public String toString() {
405                return deepToString(args);
406        }
407
408        public static ArgumentBean parse(String... args) throws CmdLineException {
409                try {
410                        return new ArgumentBean(args);
411                } catch (CmdLineException e) {
412                        // MAS does not support or allow command-line applications and may run executables with strange arguments for no apparent reason (e.g. filebot.launcher -psn_0_774333) so we ignore arguments completely in this case
413                        if (Boolean.parseBoolean(System.getProperty("apple.app.launcher"))) {
414                                return new ArgumentBean();
415                        }
416
417                        // just throw exception as usual when called from command-line and display argument errors
418                        throw e;
419                }
420        }
421
422}