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