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