a85624c82cc64fab1dd83d5cfeb907e686df6231
[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         dcp::NameFormat::Map values,
138         bool verbose
139         )
140 {
141         if (zip) {
142                 int const N = write_zip_files (
143                         collect (kdms),
144                         output,
145                         container_name_format,
146                         filename_format,
147                         values,
148                         bind (&always_overwrite)
149                         );
150
151                 if (verbose) {
152                         cout << "Wrote " << N << " ZIP files to " << output << "\n";
153                 }
154         } else {
155                 int const N = write_files (
156                         kdms, output, filename_format, values,
157                         bind (&always_overwrite)
158                         );
159
160                 if (verbose) {
161                         cout << "Wrote " << N << " KDM files to " << output << "\n";
162                 }
163         }
164 }
165
166 shared_ptr<Cinema>
167 find_cinema (string cinema_name)
168 {
169         list<shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
170         list<shared_ptr<Cinema> >::const_iterator i = cinemas.begin();
171         while (
172                 i != cinemas.end() &&
173                 (*i)->name != cinema_name &&
174                 find ((*i)->emails.begin(), (*i)->emails.end(), cinema_name) == (*i)->emails.end()) {
175
176                 ++i;
177         }
178
179         if (i == cinemas.end ()) {
180                 cerr << program_name << ": could not find cinema \"" << cinema_name << "\"\n";
181                 exit (EXIT_FAILURE);
182         }
183
184         return *i;
185 }
186
187 void
188 from_film (
189         list<shared_ptr<Screen> > screens,
190         boost::filesystem::path film_dir,
191         bool verbose,
192         boost::filesystem::path output,
193         dcp::NameFormat container_name_format,
194         dcp::NameFormat filename_format,
195         boost::posix_time::ptime valid_from,
196         boost::posix_time::ptime valid_to,
197         dcp::Formulation formulation,
198         bool disable_forensic_marking_picture,
199         optional<int> disable_forensic_marking_audio,
200         bool zip
201         )
202 {
203         shared_ptr<Film> film;
204         try {
205                 film.reset (new Film (film_dir));
206                 film->read_metadata ();
207                 if (verbose) {
208                         cout << "Read film " << film->name () << "\n";
209                 }
210         } catch (std::exception& e) {
211                 cerr << program_name << ": error reading film `" << film_dir.string() << "' (" << e.what() << ")\n";
212                 exit (EXIT_FAILURE);
213         }
214
215         /* XXX: allow specification of this */
216         vector<CPLSummary> cpls = film->cpls ();
217         if (cpls.empty ()) {
218                 error ("no CPLs found in film");
219         } else if (cpls.size() > 1) {
220                 error ("more than one CPL found in film");
221         }
222
223         boost::filesystem::path cpl = cpls.front().cpl_file;
224
225         dcp::NameFormat::Map values;
226
227         try {
228                 list<KDMWithMetadataPtr> kdms;
229
230                 BOOST_FOREACH (shared_ptr<Screen> i, screens) {
231                         if (i->recipient) {
232
233                                 dcp::LocalTime const begin(valid_from, i->cinema ? i->cinema->utc_offset_hour() : 0, i->cinema ? i->cinema->utc_offset_minute() : 0);
234                                 dcp::LocalTime const end(valid_to,   i->cinema ? i->cinema->utc_offset_hour() : 0, i->cinema ? i->cinema->utc_offset_minute() : 0);
235
236                                 dcp::EncryptedKDM const kdm = film->make_kdm (
237                                                 i->recipient.get(),
238                                                 i->trusted_device_thumbprints(),
239                                                 cpl,
240                                                 begin,
241                                                 end,
242                                                 formulation,
243                                                 disable_forensic_marking_picture,
244                                                 disable_forensic_marking_audio
245                                                 );
246
247                                 dcp::NameFormat::Map name_values;
248                                 name_values['c'] = i->cinema->name;
249                                 name_values['s'] = i->name;
250                                 name_values['f'] = film->name();
251                                 name_values['b'] = dcp::LocalTime(begin).date() + " " + dcp::LocalTime(begin).time_of_day(true, false);
252                                 name_values['e'] = dcp::LocalTime(end).date() + " " + dcp::LocalTime(end).time_of_day(true, false);
253
254                                 kdms.push_back (KDMWithMetadataPtr(new DCPKDMWithMetadata(name_values, i->cinema, kdm)));
255                         }
256                 }
257
258                 write_files (kdms, zip, output, container_name_format, filename_format, values, verbose);
259         } catch (FileError& e) {
260                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
261                 exit (EXIT_FAILURE);
262         } catch (KDMError& e) {
263                 cerr << program_name << ": " << e.what() << "\n";
264                 exit (EXIT_FAILURE);
265         } catch (runtime_error& e) {
266                 cerr << program_name << ": " << e.what() << "\n";
267                 exit (EXIT_FAILURE);
268         }
269 }
270
271 optional<dcp::EncryptedKDM>
272 sub_find_dkdm (shared_ptr<DKDMGroup> group, string cpl_id)
273 {
274         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
275                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
276                 if (g) {
277                         optional<dcp::EncryptedKDM> dkdm = sub_find_dkdm (g, cpl_id);
278                         if (dkdm) {
279                                 return dkdm;
280                         }
281                 } else {
282                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
283                         assert (d);
284                         if (d->dkdm().cpl_id() == cpl_id) {
285                                 return d->dkdm();
286                         }
287                 }
288         }
289
290         return optional<dcp::EncryptedKDM>();
291 }
292
293 optional<dcp::EncryptedKDM>
294 find_dkdm (string cpl_id)
295 {
296         return sub_find_dkdm (Config::instance()->dkdms(), cpl_id);
297 }
298
299 dcp::EncryptedKDM
300 kdm_from_dkdm (
301         dcp::DecryptedKDM dkdm,
302         dcp::Certificate target,
303         vector<string> trusted_devices,
304         dcp::LocalTime valid_from,
305         dcp::LocalTime valid_to,
306         dcp::Formulation formulation,
307         bool disable_forensic_marking_picture,
308         optional<int> disable_forensic_marking_audio
309         )
310 {
311         /* Signer for new KDM */
312         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
313         if (!signer->valid ()) {
314                 error ("signing certificate chain is invalid.");
315         }
316
317         /* Make a new empty KDM and add the keys from the DKDM to it */
318         dcp::DecryptedKDM kdm (
319                 valid_from,
320                 valid_to,
321                 dkdm.annotation_text().get_value_or(""),
322                 dkdm.content_title_text(),
323                 dcp::LocalTime().as_string()
324                 );
325
326         BOOST_FOREACH (dcp::DecryptedKDMKey const & j, dkdm.keys()) {
327                 kdm.add_key(j);
328         }
329
330         return kdm.encrypt (signer, target, trusted_devices, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
331 }
332
333 void
334 from_dkdm (
335         list<shared_ptr<Screen> > screens,
336         dcp::DecryptedKDM dkdm,
337         bool verbose,
338         boost::filesystem::path output,
339         dcp::NameFormat container_name_format,
340         dcp::NameFormat filename_format,
341         boost::posix_time::ptime valid_from,
342         boost::posix_time::ptime valid_to,
343         dcp::Formulation formulation,
344         bool disable_forensic_marking_picture,
345         optional<int> disable_forensic_marking_audio,
346         bool zip
347         )
348 {
349         dcp::NameFormat::Map values;
350
351         try {
352                 list<KDMWithMetadataPtr> kdms;
353                 BOOST_FOREACH (shared_ptr<Screen> i, screens) {
354                         if (!i->recipient) {
355                                 continue;
356                         }
357
358                         dcp::LocalTime begin(valid_from, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
359                         dcp::LocalTime end(valid_to, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
360
361                         dcp::NameFormat::Map name_values;
362                         name_values['c'] = i->cinema->name;
363                         name_values['s'] = i->name;
364                         name_values['f'] = dkdm.annotation_text().get_value_or("");
365                         name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
366                         name_values['e'] = end.date() + " " + end.time_of_day(true, false);
367
368                         kdms.push_back (
369                                 KDMWithMetadataPtr(
370                                         new DCPKDMWithMetadata(
371                                                 name_values,
372                                                 i->cinema,
373                                                 kdm_from_dkdm(
374                                                         dkdm,
375                                                         i->recipient.get(),
376                                                         i->trusted_device_thumbprints(),
377                                                         begin,
378                                                         end,
379                                                         formulation,
380                                                         disable_forensic_marking_picture,
381                                                         disable_forensic_marking_audio
382                                                         )
383                                                 )
384                                         )
385                                 );
386                 }
387                 write_files (kdms, zip, output, container_name_format, filename_format, values, verbose);
388         } catch (FileError& e) {
389                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
390                 exit (EXIT_FAILURE);
391         } catch (KDMError& e) {
392                 cerr << program_name << ": " << e.what() << "\n";
393                 exit (EXIT_FAILURE);
394         }
395 }
396
397 void
398 dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent)
399 {
400         if (indent > 0) {
401                 for (int i = 0; i < indent; ++i) {
402                         cout << " ";
403                 }
404                 cout << group->name() << "\n";
405         }
406         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
407                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
408                 if (g) {
409                         dump_dkdm_group (g, indent + 2);
410                 } else {
411                         for (int j = 0; j < indent; ++j) {
412                                 cout << " ";
413                         }
414                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
415                         assert(d);
416                         cout << d->dkdm().cpl_id() << "\n";
417                 }
418         }
419 }
420
421 int main (int argc, char* argv[])
422 {
423         boost::filesystem::path output = ".";
424         dcp::NameFormat container_name_format = Config::instance()->kdm_container_name_format();
425         dcp::NameFormat filename_format = Config::instance()->kdm_filename_format();
426         optional<string> cinema_name;
427         shared_ptr<Cinema> cinema;
428         string screen_description = "";
429         list<shared_ptr<Screen> > screens;
430         optional<dcp::EncryptedKDM> dkdm;
431         optional<boost::posix_time::ptime> valid_from;
432         optional<boost::posix_time::ptime> valid_to;
433         bool zip = false;
434         bool list_cinemas = false;
435         bool list_dkdm_cpls = false;
436         optional<string> duration_string;
437         bool verbose = false;
438         dcp::Formulation formulation = dcp::MODIFIED_TRANSITIONAL_1;
439         bool disable_forensic_marking_picture = false;
440         optional<int> disable_forensic_marking_audio;
441
442         program_name = argv[0];
443
444         int option_index = 0;
445         while (true) {
446                 static struct option long_options[] = {
447                         { "help", no_argument, 0, 'h'},
448                         { "output", required_argument, 0, 'o'},
449                         { "filename-format", required_argument, 0, 'K'},
450                         { "container-name-format", required_argument, 0, 'Z'},
451                         { "valid-from", required_argument, 0, 'f'},
452                         { "valid-to", required_argument, 0, 't'},
453                         { "valid-duration", required_argument, 0, 'd'},
454                         { "formulation", required_argument, 0, 'F' },
455                         { "disable-forensic-marking-picture", no_argument, 0, 'p' },
456                         { "disable-forensic-marking-audio", optional_argument, 0, 'a' },
457                         { "zip", no_argument, 0, 'z' },
458                         { "verbose", no_argument, 0, 'v' },
459                         { "cinema", required_argument, 0, 'c' },
460                         { "screen", required_argument, 0, 'S' },
461                         { "certificate", required_argument, 0, 'C' },
462                         { "trusted-device", required_argument, 0, 'T' },
463                         { "list-cinemas", no_argument, 0, 'B' },
464                         { "list-dkdm-cpls", no_argument, 0, 'D' },
465                         { 0, 0, 0, 0 }
466                 };
467
468                 int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pa::zvc:S:C:T:BD", long_options, &option_index);
469
470                 if (c == -1) {
471                         break;
472                 }
473
474                 switch (c) {
475                 case 'h':
476                         help ();
477                         exit (EXIT_SUCCESS);
478                 case 'o':
479                         output = optarg;
480                         break;
481                 case 'K':
482                         filename_format = dcp::NameFormat (optarg);
483                         break;
484                 case 'Z':
485                         container_name_format = dcp::NameFormat (optarg);
486                         break;
487                 case 'f':
488                         valid_from = time_from_string (optarg);
489                         break;
490                 case 't':
491                         valid_to = time_from_string (optarg);
492                         break;
493                 case 'd':
494                         duration_string = optarg;
495                         break;
496                 case 'F':
497                         if (string (optarg) == "modified-transitional-1") {
498                                 formulation = dcp::MODIFIED_TRANSITIONAL_1;
499                         } else if (string (optarg) == "multiple-modified-transitional-1") {
500                                 formulation = dcp::MULTIPLE_MODIFIED_TRANSITIONAL_1;
501                         } else if (string (optarg) == "dci-any") {
502                                 formulation = dcp::DCI_ANY;
503                         } else if (string (optarg) == "dci-specific") {
504                                 formulation = dcp::DCI_SPECIFIC;
505                         } else {
506                                 error ("unrecognised KDM formulation " + string (optarg));
507                         }
508                         break;
509                 case 'p':
510                         disable_forensic_marking_picture = true;
511                         break;
512                 case 'a':
513                         disable_forensic_marking_audio = 0;
514                         if (optarg == 0 && argv[optind] != 0 && argv[optind][0] != '-') {
515                                 disable_forensic_marking_audio = atoi (argv[optind++]);
516                         } else if (optarg) {
517                                 disable_forensic_marking_audio = atoi (optarg);
518                         }
519                         break;
520                 case 'z':
521                         zip = true;
522                         break;
523                 case 'v':
524                         verbose = true;
525                         break;
526                 case 'c':
527                         /* This could be a cinema to search for in the configured list or the name of a cinema being
528                            built up on-the-fly in the option.  Cater for both possilibities here by storing the name
529                            (for lookup) and by creating a Cinema which the next Screen will be added to.
530                         */
531                         cinema_name = optarg;
532                         cinema = shared_ptr<Cinema> (new Cinema (optarg, list<string>(), "", 0, 0));
533                         break;
534                 case 'S':
535                         screen_description = optarg;
536                         break;
537                 case 'C':
538                 {
539                         /* Make a new screen and add it to the current cinema */
540                         dcp::CertificateChain chain (dcp::file_to_string(optarg));
541                         shared_ptr<Screen> screen (new Screen (screen_description, "", chain.leaf(), vector<TrustedDevice>()));
542                         if (cinema) {
543                                 cinema->add_screen (screen);
544                         }
545                         screens.push_back (screen);
546                         break;
547                 }
548                 case 'T':
549                         /* A trusted device ends up in the last screen we made */
550                         if (!screens.empty ()) {
551                                 screens.back()->trusted_devices.push_back(TrustedDevice(dcp::Certificate(dcp::file_to_string(optarg))));
552                         }
553                         break;
554                 case 'B':
555                         list_cinemas = true;
556                         break;
557                 case 'D':
558                         list_dkdm_cpls = true;
559                         break;
560                 }
561         }
562
563         if (list_cinemas) {
564                 list<boost::shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
565                 for (list<boost::shared_ptr<Cinema> >::const_iterator i = cinemas.begin(); i != cinemas.end(); ++i) {
566                         cout << (*i)->name << " (" << Emailer::address_list ((*i)->emails) << ")\n";
567                 }
568                 exit (EXIT_SUCCESS);
569         }
570
571         if (list_dkdm_cpls) {
572                 dump_dkdm_group (Config::instance()->dkdms(), 0);
573                 exit (EXIT_SUCCESS);
574         }
575
576         if (!duration_string && !valid_to) {
577                 error ("you must specify a --valid-duration or --valid-to");
578         }
579
580         if (!valid_from) {
581                 error ("you must specify --valid-from");
582                 exit (EXIT_FAILURE);
583         }
584
585         if (optind >= argc) {
586                 help ();
587                 exit (EXIT_FAILURE);
588         }
589
590         if (screens.empty()) {
591                 if (!cinema_name) {
592                         error ("you must specify either a cinema or one or more screens using certificate files");
593                 }
594
595                 screens = find_cinema (*cinema_name)->screens ();
596         }
597
598         if (duration_string) {
599                 valid_to = valid_from.get() + duration_from_string (*duration_string);
600         }
601
602         dcpomatic_setup_path_encoding ();
603         dcpomatic_setup ();
604
605         if (verbose) {
606                 cout << "Making KDMs valid from " << valid_from.get() << " to " << valid_to.get() << "\n";
607         }
608
609         string const thing = argv[optind];
610         if (boost::filesystem::is_directory(thing) && boost::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
611                 from_film (
612                         screens,
613                         thing,
614                         verbose,
615                         output,
616                         container_name_format,
617                         filename_format,
618                         *valid_from,
619                         *valid_to,
620                         formulation,
621                         disable_forensic_marking_picture,
622                         disable_forensic_marking_audio,
623                         zip
624                         );
625         } else {
626                 if (boost::filesystem::is_regular_file(thing)) {
627                         dkdm = dcp::EncryptedKDM (dcp::file_to_string (thing));
628                 } else {
629                         dkdm = find_dkdm (thing);
630                 }
631
632                 if (!dkdm) {
633                         error ("could not find film or CPL ID corresponding to " + thing);
634                 }
635
636                 from_dkdm (
637                         screens,
638                         dcp::DecryptedKDM (*dkdm, Config::instance()->decryption_chain()->key().get()),
639                         verbose,
640                         output,
641                         container_name_format,
642                         filename_format,
643                         *valid_from,
644                         *valid_to,
645                         formulation,
646                         disable_forensic_marking_picture,
647                         disable_forensic_marking_audio,
648                         zip
649                         );
650         }
651
652         return 0;
653 }