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