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