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