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