Tidy up option parsing a little.
[dcpomatic.git] / src / tools / dcpomatic_kdm_cli.cc
1 /*
2     Copyright (C) 2013-2017 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file  src/tools/dcpomatic_kdm_cli.cc
22  *  @brief Command-line program to generate KDMs.
23  */
24
25 #include "lib/film.h"
26 #include "lib/cinema.h"
27 #include "lib/screen_kdm.h"
28 #include "lib/cinema_kdms.h"
29 #include "lib/config.h"
30 #include "lib/exceptions.h"
31 #include "lib/emailer.h"
32 #include "lib/dkdm_wrapper.h"
33 #include "lib/screen.h"
34 #include <dcp/certificate.h>
35 #include <dcp/decrypted_kdm.h>
36 #include <dcp/encrypted_kdm.h>
37 #include <getopt.h>
38 #include <iostream>
39
40 using std::string;
41 using std::cout;
42 using std::cerr;
43 using std::list;
44 using std::vector;
45 using boost::shared_ptr;
46 using boost::optional;
47 using boost::bind;
48 using boost::dynamic_pointer_cast;
49
50 static void
51 help ()
52 {
53         cerr << "Syntax: " << program_name << " [OPTION] <FILM|CPL-ID|DKDM>\n"
54                 "  -h, --help                               show this help\n"
55                 "  -o, --output                             output file or directory\n"
56                 "  -K, --filename-format                    filename format for KDMs\n"
57                 "  -Z, --container-name-format              filename format for ZIP containers\n"
58                 "  -f, --valid-from                         valid from time (in local time zone of the cinema) (e.g. \"2013-09-28 01:41:51\") or \"now\"\n"
59                 "  -t, --valid-to                           valid to time (in local time zone of the cinema) (e.g. \"2014-09-28 01:41:51\")\n"
60                 "  -d, --valid-duration                     valid duration (e.g. \"1 day\", \"4 hours\", \"2 weeks\")\n"
61                 "  -F, --formulation                        modified-transitional-1, multiple-modified-transitional-1, dci-any or dci-specific [default modified-transitional-1]\n"
62                 "  -a, --disable-forensic-marking-picture   disable forensic of pictures essences\n"
63                 "  -a, --disable-forensic-marking-audio     disable forensic of audio essences (optionally above a given channel, e.g 12)\n"
64                 "  -z, --zip                                ZIP each cinema's KDMs into its own file\n"
65                 "  -v, --verbose                            be verbose\n"
66                 "  -c, --cinema                             specify a cinema, either by name or email address\n"
67                 "  -S, --screen                             screen description\n"
68                 "  -C, --certificate                        file containing projector certificate\n"
69                 "  -T, --trusted-device                     file containing a trusted device's certificate\n"
70                 "      --list-cinemas                       list known cinemas from the DCP-o-matic settings\n"
71                 "      --list-dkdm-cpls                     list CPLs for which DCP-o-matic has DKDMs\n\n"
72                 "CPL-ID must be the ID of a CPL that is mentioned in DCP-o-matic's DKDM list.\n\n"
73                 "For example:\n\n"
74                 "Create KDMs for my_great_movie to play in all of Fred's Cinema's screens for the next two weeks and zip them up.\n"
75                 "(Fred's Cinema must have been set up in DCP-o-matic's KDM window)\n\n"
76                 "\tdcpomatic_kdm -c \"Fred's Cinema\" -f now -d \"2 weeks\" -z my_great_movie\n\n";
77 }
78
79 static void
80 error (string m)
81 {
82         cerr << program_name << ": " << m << "\n";
83         exit (EXIT_FAILURE);
84 }
85
86 static boost::posix_time::ptime
87 time_from_string (string t)
88 {
89         if (t == "now") {
90                 return boost::posix_time::second_clock::local_time ();
91         }
92
93         return boost::posix_time::time_from_string (t);
94 }
95
96 static boost::posix_time::time_duration
97 duration_from_string (string d)
98 {
99         int N;
100         char unit_buf[64] = "\0";
101         sscanf (d.c_str(), "%d %63s", &N, unit_buf);
102         string const unit (unit_buf);
103
104         if (N == 0) {
105                 cerr << "Could not understand duration \"" << d << "\"\n";
106                 exit (EXIT_FAILURE);
107         }
108
109         if (unit == "year" || unit == "years") {
110                 return boost::posix_time::time_duration (N * 24 * 365, 0, 0, 0);
111         } else if (unit == "week" || unit == "weeks") {
112                 return boost::posix_time::time_duration (N * 24 * 7, 0, 0, 0);
113         } else if (unit == "day" || unit == "days") {
114                 return boost::posix_time::time_duration (N * 24, 0, 0, 0);
115         } else if (unit == "hour" || unit == "hours") {
116                 return boost::posix_time::time_duration (N, 0, 0, 0);
117         }
118
119         cerr << "Could not understand duration \"" << d << "\"\n";
120         exit (EXIT_FAILURE);
121 }
122
123 static bool
124 always_overwrite ()
125 {
126         return true;
127 }
128
129 void
130 write_files (
131         list<ScreenKDM> screen_kdms,
132         bool zip,
133         boost::filesystem::path output,
134         dcp::NameFormat container_name_format,
135         dcp::NameFormat filename_format,
136         dcp::NameFormat::Map values,
137         bool verbose
138         )
139 {
140         if (zip) {
141                 int const N = CinemaKDMs::write_zip_files (
142                         CinemaKDMs::collect (screen_kdms),
143                         output,
144                         container_name_format,
145                         filename_format,
146                         values,
147                         bind (&always_overwrite)
148                         );
149
150                 if (verbose) {
151                         cout << "Wrote " << N << " ZIP files to " << output << "\n";
152                 }
153         } else {
154                 int const N = ScreenKDM::write_files (
155                         screen_kdms, output, filename_format, values,
156                         bind (&always_overwrite)
157                         );
158
159                 if (verbose) {
160                         cout << "Wrote " << N << " KDM files to " << output << "\n";
161                 }
162         }
163 }
164
165 shared_ptr<Cinema>
166 find_cinema (string cinema_name)
167 {
168         list<shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
169         list<shared_ptr<Cinema> >::const_iterator i = cinemas.begin();
170         while (
171                 i != cinemas.end() &&
172                 (*i)->name != cinema_name &&
173                 find ((*i)->emails.begin(), (*i)->emails.end(), cinema_name) == (*i)->emails.end()) {
174
175                 ++i;
176         }
177
178         if (i == cinemas.end ()) {
179                 cerr << program_name << ": could not find cinema \"" << cinema_name << "\"\n";
180                 exit (EXIT_FAILURE);
181         }
182
183         return *i;
184 }
185
186 void
187 from_film (
188         list<shared_ptr<Screen> > screens,
189         boost::filesystem::path film_dir,
190         bool verbose,
191         boost::filesystem::path output,
192         dcp::NameFormat container_name_format,
193         dcp::NameFormat filename_format,
194         boost::posix_time::ptime valid_from,
195         boost::posix_time::ptime valid_to,
196         dcp::Formulation formulation,
197         int disable_forensic_marking_picture,
198         int disable_forensic_marking_audio,
199         bool zip
200         )
201 {
202         shared_ptr<Film> film;
203         try {
204                 film.reset (new Film (film_dir));
205                 film->read_metadata ();
206                 if (verbose) {
207                         cout << "Read film " << film->name () << "\n";
208                 }
209         } catch (std::exception& e) {
210                 cerr << program_name << ": error reading film `" << film_dir.string() << "' (" << e.what() << ")\n";
211                 exit (EXIT_FAILURE);
212         }
213
214         /* XXX: allow specification of this */
215         vector<CPLSummary> cpls = film->cpls ();
216         if (cpls.empty ()) {
217                 error ("no CPLs found in film");
218         } else if (cpls.size() > 1) {
219                 error ("more than one CPL found in film");
220         }
221
222         boost::filesystem::path cpl = cpls.front().cpl_file;
223
224         dcp::NameFormat::Map values;
225         values['f'] = film->name();
226         values['b'] = dcp::LocalTime(valid_from).date() + " " + dcp::LocalTime(valid_from).time_of_day(true, false);
227         values['e'] = dcp::LocalTime(valid_to).date() + " " + dcp::LocalTime(valid_to).time_of_day(true, false);
228
229         try {
230                 list<ScreenKDM> screen_kdms = film->make_kdms (
231                         screens, cpl, valid_from, valid_to, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio
232                         );
233
234                 write_files (screen_kdms, zip, output, container_name_format, filename_format, values, verbose);
235         } catch (FileError& e) {
236                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
237                 exit (EXIT_FAILURE);
238         } catch (KDMError& e) {
239                 cerr << program_name << ": " << e.what() << "\n";
240                 exit (EXIT_FAILURE);
241         }
242 }
243
244 optional<dcp::EncryptedKDM>
245 sub_find_dkdm (shared_ptr<DKDMGroup> group, string cpl_id)
246 {
247         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
248                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
249                 if (g) {
250                         optional<dcp::EncryptedKDM> dkdm = sub_find_dkdm (g, cpl_id);
251                         if (dkdm) {
252                                 return dkdm;
253                         }
254                 } else {
255                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
256                         assert (d);
257                         if (d->dkdm().cpl_id() == cpl_id) {
258                                 return d->dkdm();
259                         }
260                 }
261         }
262
263         return optional<dcp::EncryptedKDM>();
264 }
265
266 optional<dcp::EncryptedKDM>
267 find_dkdm (string cpl_id)
268 {
269         return sub_find_dkdm (Config::instance()->dkdms(), cpl_id);
270 }
271
272 dcp::EncryptedKDM
273 kdm_from_dkdm (
274         dcp::DecryptedKDM dkdm,
275         dcp::Certificate target,
276         vector<dcp::Certificate> trusted_devices,
277         dcp::LocalTime valid_from,
278         dcp::LocalTime valid_to,
279         dcp::Formulation formulation,
280         int disable_forensic_marking_picture,
281         int disable_forensic_marking_audio
282         )
283 {
284         /* Signer for new KDM */
285         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
286         if (!signer->valid ()) {
287                 error ("signing certificate chain is invalid.");
288         }
289
290         /* Make a new empty KDM and add the keys from the DKDM to it */
291         dcp::DecryptedKDM kdm (
292                 valid_from,
293                 valid_to,
294                 dkdm.annotation_text().get_value_or(""),
295                 dkdm.content_title_text(),
296                 dcp::LocalTime().as_string()
297                 );
298
299         BOOST_FOREACH (dcp::DecryptedKDMKey const & j, dkdm.keys()) {
300                 kdm.add_key(j);
301         }
302
303         return kdm.encrypt (signer, target, trusted_devices, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
304 }
305
306 void
307 from_dkdm (
308         list<shared_ptr<Screen> > screens,
309         dcp::DecryptedKDM dkdm,
310         bool verbose,
311         boost::filesystem::path output,
312         dcp::NameFormat container_name_format,
313         dcp::NameFormat filename_format,
314         boost::posix_time::ptime valid_from,
315         boost::posix_time::ptime valid_to,
316         dcp::Formulation formulation,
317         int disable_forensic_marking_picture,
318         int disable_forensic_marking_audio,
319         bool zip
320         )
321 {
322         dcp::NameFormat::Map values;
323         values['f'] = dkdm.annotation_text().get_value_or("");
324         values['b'] = dcp::LocalTime(valid_from).date() + " " + dcp::LocalTime(valid_from).time_of_day(true, false);
325         values['e'] = dcp::LocalTime(valid_to).date() + " " + dcp::LocalTime(valid_to).time_of_day(true, false);
326
327         try {
328                 list<ScreenKDM> screen_kdms;
329                 BOOST_FOREACH (shared_ptr<Screen> i, screens) {
330                         if (!i->recipient) {
331                                 continue;
332                         }
333
334                         screen_kdms.push_back (
335                                 ScreenKDM (
336                                         i,
337                                         kdm_from_dkdm (
338                                                 dkdm,
339                                                 i->recipient.get(),
340                                                 i->trusted_devices,
341                                                 dcp::LocalTime(valid_from, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
342                                                 dcp::LocalTime(valid_to, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
343                                                 formulation,
344                                                 disable_forensic_marking_picture,
345                                                 disable_forensic_marking_audio
346                                                 )
347                                         )
348                                 );
349                 }
350                 write_files (screen_kdms, zip, output, container_name_format, filename_format, values, verbose);
351         } catch (FileError& e) {
352                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
353                 exit (EXIT_FAILURE);
354         } catch (KDMError& e) {
355                 cerr << program_name << ": " << e.what() << "\n";
356                 exit (EXIT_FAILURE);
357         }
358 }
359
360 void
361 dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent)
362 {
363         if (indent > 0) {
364                 for (int i = 0; i < indent; ++i) {
365                         cout << " ";
366                 }
367                 cout << group->name() << "\n";
368         }
369         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
370                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
371                 if (g) {
372                         dump_dkdm_group (g, indent + 2);
373                 } else {
374                         for (int j = 0; j < indent; ++j) {
375                                 cout << " ";
376                         }
377                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
378                         assert(d);
379                         cout << d->dkdm().cpl_id() << "\n";
380                 }
381         }
382 }
383
384 int main (int argc, char* argv[])
385 {
386         boost::filesystem::path output = ".";
387         dcp::NameFormat container_name_format = Config::instance()->kdm_container_name_format();
388         dcp::NameFormat filename_format = Config::instance()->kdm_filename_format();
389         optional<string> cinema_name;
390         shared_ptr<Cinema> cinema;
391         string screen_description = "";
392         list<shared_ptr<Screen> > screens;
393         optional<dcp::EncryptedKDM> dkdm;
394         optional<boost::posix_time::ptime> valid_from;
395         optional<boost::posix_time::ptime> valid_to;
396         bool zip = false;
397         bool list_cinemas = false;
398         bool list_dkdm_cpls = false;
399         optional<string> duration_string;
400         bool verbose = false;
401         dcp::Formulation formulation = dcp::MODIFIED_TRANSITIONAL_1;
402         int disable_forensic_marking_picture = 0;
403         int disable_forensic_marking_audio = 0;
404
405         program_name = argv[0];
406
407         int option_index = 0;
408         while (true) {
409                 static struct option long_options[] = {
410                         { "help", no_argument, 0, 'h'},
411                         { "output", required_argument, 0, 'o'},
412                         { "filename-format", required_argument, 0, 'K'},
413                         { "container-name-format", required_argument, 0, 'Z'},
414                         { "valid-from", required_argument, 0, 'f'},
415                         { "valid-to", required_argument, 0, 't'},
416                         { "valid-duration", required_argument, 0, 'd'},
417                         { "formulation", required_argument, 0, 'F' },
418                         { "disable-forensic-marking-picture", no_argument, 0, 'p' },
419                         { "disable-forensic-marking-audio", optional_argument, 0, 'a' },
420                         { "zip", no_argument, 0, 'z' },
421                         { "verbose", no_argument, 0, 'v' },
422                         { "cinema", required_argument, 0, 'c' },
423                         { "screen", required_argument, 0, 'S' },
424                         { "certificate", required_argument, 0, 'C' },
425                         { "trusted-device", required_argument, 0, 'T' },
426                         { "list-cinemas", no_argument, 0, 'B' },
427                         { "list-dkdm-cpls", no_argument, 0, 'D' },
428                         { 0, 0, 0, 0 }
429                 };
430
431                 int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pa::zvc:S:C:T:BD", long_options, &option_index);
432
433                 if (c == -1) {
434                         break;
435                 }
436
437                 switch (c) {
438                 case 'h':
439                         help ();
440                         exit (EXIT_SUCCESS);
441                 case 'o':
442                         output = optarg;
443                         break;
444                 case 'K':
445                         filename_format = dcp::NameFormat (optarg);
446                         break;
447                 case 'Z':
448                         container_name_format = dcp::NameFormat (optarg);
449                         break;
450                 case 'f':
451                         valid_from = time_from_string (optarg);
452                         break;
453                 case 't':
454                         valid_to = time_from_string (optarg);
455                         break;
456                 case 'd':
457                         duration_string = optarg;
458                         break;
459                 case 'F':
460                         if (string (optarg) == "modified-transitional-1") {
461                                 formulation = dcp::MODIFIED_TRANSITIONAL_1;
462                         } else if (string (optarg) == "multiple-modified-transitional-1") {
463                                 formulation = dcp::MULTIPLE_MODIFIED_TRANSITIONAL_1;
464                         } else if (string (optarg) == "dci-any") {
465                                 formulation = dcp::DCI_ANY;
466                         } else if (string (optarg) == "dci-specific") {
467                                 formulation = dcp::DCI_SPECIFIC;
468                         } else {
469                                 error ("unrecognised KDM formulation " + string (optarg));
470                         }
471                         break;
472                 case 'p':
473                         disable_forensic_marking_picture = -1;
474                         break;
475                 case 'a':
476                         disable_forensic_marking_audio = -1;
477                         if (optarg == NULL && argv[optind] != NULL && argv[optind][0] != '-') {
478                                 disable_forensic_marking_audio = atoi (argv[optind++]);
479                         } else if (optarg != NULL) {
480                                 disable_forensic_marking_audio = atoi (optarg);
481                         }
482                         break;
483                 case 'z':
484                         zip = true;
485                         break;
486                 case 'v':
487                         verbose = true;
488                         break;
489                 case 'c':
490                         /* This could be a cinema to search for in the configured list or the name of a cinema being
491                            built up on-the-fly in the option.  Cater for both possilibities here by storing the name
492                            (for lookup) and by creating a Cinema which the next Screen will be added to.
493                         */
494                         cinema_name = optarg;
495                         cinema = shared_ptr<Cinema> (new Cinema (optarg, list<string>(), "", 0, 0));
496                         break;
497                 case 'S':
498                         screen_description = optarg;
499                         break;
500                 case 'C':
501                         /* Make a new screen and add it to the current cinema */
502                         shared_ptr<Screen> screen (new Screen (screen_description, dcp::Certificate (dcp::file_to_string (optarg)), vector<dcp::Certificate>()));
503                         if (cinema) {
504                                 cinema->add_screen (screen);
505                         }
506                         screens.push_back (screen);
507                         break;
508                 case 'T':
509                         /* A trusted device ends up in the last screen we made */
510                         if (!screens.empty ()) {
511                                 screens.back()->trusted_devices.push_back (dcp::Certificate (dcp::file_to_string (optarg)));
512                         }
513                         break;
514                 case 'B':
515                         list_cinemas = true;
516                         break;
517                 case 'D':
518                         list_dkdm_cpls = true;
519                         break;
520                 }
521         }
522
523         if (list_cinemas) {
524                 list<boost::shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
525                 for (list<boost::shared_ptr<Cinema> >::const_iterator i = cinemas.begin(); i != cinemas.end(); ++i) {
526                         cout << (*i)->name << " (" << Emailer::address_list ((*i)->emails) << ")\n";
527                 }
528                 exit (EXIT_SUCCESS);
529         }
530
531         if (list_dkdm_cpls) {
532                 dump_dkdm_group (Config::instance()->dkdms(), 0);
533                 exit (EXIT_SUCCESS);
534         }
535
536         if (!duration_string && !valid_to) {
537                 error ("you must specify a --valid-duration or --valid-to");
538         }
539
540         if (!valid_from) {
541                 error ("you must specify --valid-from");
542                 exit (EXIT_FAILURE);
543         }
544
545         if (optind >= argc) {
546                 help ();
547                 exit (EXIT_FAILURE);
548         }
549
550         if (screens.empty()) {
551                 if (!cinema_name) {
552                         error ("you must specify either a cinema or one or more screens using certificate files");
553                 }
554
555                 screens = find_cinema (*cinema_name)->screens ();
556         }
557
558         if (duration_string) {
559                 valid_to = valid_from.get() + duration_from_string (*duration_string);
560         }
561
562         dcpomatic_setup_path_encoding ();
563         dcpomatic_setup ();
564
565         if (verbose) {
566                 cout << "Making KDMs valid from " << valid_from.get() << " to " << valid_to.get() << "\n";
567         }
568
569         string const thing = argv[optind];
570         if (boost::filesystem::is_directory(thing) && boost::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
571                 from_film (
572                         screens,
573                         thing,
574                         verbose,
575                         output,
576                         container_name_format,
577                         filename_format,
578                         *valid_from,
579                         *valid_to,
580                         formulation,
581                         disable_forensic_marking_picture,
582                         disable_forensic_marking_audio,
583                         zip
584                         );
585         } else {
586                 if (boost::filesystem::is_regular_file(thing)) {
587                         dkdm = dcp::EncryptedKDM (dcp::file_to_string (thing));
588                 } else {
589                         dkdm = find_dkdm (thing);
590                 }
591
592                 if (!dkdm) {
593                         error ("could not find film or CPL ID corresponding to " + thing);
594                 }
595
596                 from_dkdm (
597                         screens,
598                         dcp::DecryptedKDM (*dkdm, Config::instance()->decryption_chain()->key().get()),
599                         verbose,
600                         output,
601                         container_name_format,
602                         filename_format,
603                         *valid_from,
604                         *valid_to,
605                         formulation,
606                         disable_forensic_marking_picture,
607                         disable_forensic_marking_audio,
608                         zip
609                         );
610         }
611
612         return 0;
613 }