f04c5ae04aa6d19b89f2de8f076feea4210b4325
[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::cout;
43 using std::dynamic_pointer_cast;
44 using std::list;
45 using std::make_shared;
46 using std::runtime_error;
47 using std::shared_ptr;
48 using std::string;
49 using std::vector;
50 using boost::optional;
51 using boost::bind;
52 #if BOOST_VERSION >= 106100
53 using namespace boost::placeholders;
54 #endif
55 using namespace dcpomatic;
56
57
58 static void
59 help ()
60 {
61         cout << "Syntax: " << program_name << " [OPTION] <FILM|CPL-ID|DKDM>\n"
62                 "  -h, --help                               show this help\n"
63                 "  -o, --output                             output file or directory\n"
64                 "  -K, --filename-format                    filename format for KDMs\n"
65                 "  -Z, --container-name-format              filename format for ZIP containers\n"
66                 "  -f, --valid-from                         valid from time (in local time zone of the cinema) (e.g. \"2013-09-28 01:41:51\") or \"now\"\n"
67                 "  -t, --valid-to                           valid to time (in local time zone of the cinema) (e.g. \"2014-09-28 01:41:51\")\n"
68                 "  -d, --valid-duration                     valid duration (e.g. \"1 day\", \"4 hours\", \"2 weeks\")\n"
69                 "  -F, --formulation                        modified-transitional-1, multiple-modified-transitional-1, dci-any or dci-specific [default modified-transitional-1]\n"
70                 "  -p, --disable-forensic-marking-picture   disable forensic marking of pictures essences\n"
71                 "  -a, --disable-forensic-marking-audio     disable forensic marking of audio essences (optionally above a given channel, e.g 12)\n"
72                 "  -e, --email                              email KDMs to cinemas\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 class KDMCLIError : public std::runtime_error
90 {
91 public:
92         KDMCLIError (std::string message)
93                 : std::runtime_error (String::compose("%1: %2", program_name, message).c_str())
94         {}
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                 throw KDMCLIError (String::compose("could not understand duration \"%1\"", d));
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         throw KDMCLIError (String::compose("could not understand duration \"%1\"", d));
132 }
133
134
135 static bool
136 always_overwrite ()
137 {
138         return true;
139 }
140
141
142 static
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 static
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                 throw KDMCLIError (String::compose("could not find cinema \"%1\"", cinema_name));
194         }
195
196         return *i;
197 }
198
199
200 static
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                 throw KDMCLIError (String::compose("error reading film \"%1\" (%2)", film_dir.string(), e.what()));
227         }
228
229         /* XXX: allow specification of this */
230         vector<CPLSummary> cpls = film->cpls ();
231         if (cpls.empty ()) {
232                 throw KDMCLIError ("no CPLs found in film");
233         } else if (cpls.size() > 1) {
234                 throw KDMCLIError ("more than one CPL found in film");
235         }
236
237         auto cpl = cpls.front().cpl_file;
238
239         try {
240                 list<KDMWithMetadataPtr> kdms;
241                 for (auto i: screens) {
242                         auto p = kdm_for_screen (film, cpl, i, valid_from, valid_to, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
243                         if (p) {
244                                 kdms.push_back (p);
245                         }
246                 }
247                 write_files (kdms, zip, output, container_name_format, filename_format, verbose);
248                 if (email) {
249                         send_emails ({kdms}, container_name_format, filename_format, film->dcp_name());
250                 }
251         } catch (FileError& e) {
252                 throw KDMCLIError (String::compose("%1 (%2)", e.what(), e.file().string()));
253         }
254 }
255
256
257 static
258 optional<dcp::EncryptedKDM>
259 sub_find_dkdm (shared_ptr<DKDMGroup> group, string cpl_id)
260 {
261         for (auto i: group->children()) {
262                 auto g = dynamic_pointer_cast<DKDMGroup>(i);
263                 if (g) {
264                         auto dkdm = sub_find_dkdm (g, cpl_id);
265                         if (dkdm) {
266                                 return dkdm;
267                         }
268                 } else {
269                         auto d = dynamic_pointer_cast<DKDM>(i);
270                         assert (d);
271                         if (d->dkdm().cpl_id() == cpl_id) {
272                                 return d->dkdm();
273                         }
274                 }
275         }
276
277         return {};
278 }
279
280
281 static
282 optional<dcp::EncryptedKDM>
283 find_dkdm (string cpl_id)
284 {
285         return sub_find_dkdm (Config::instance()->dkdms(), cpl_id);
286 }
287
288
289 static
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                 throw KDMCLIError ("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 static
326 void
327 from_dkdm (
328         list<shared_ptr<Screen>> screens,
329         dcp::DecryptedKDM dkdm,
330         bool verbose,
331         boost::filesystem::path output,
332         dcp::NameFormat container_name_format,
333         dcp::NameFormat filename_format,
334         boost::posix_time::ptime valid_from,
335         boost::posix_time::ptime valid_to,
336         dcp::Formulation formulation,
337         bool disable_forensic_marking_picture,
338         optional<int> disable_forensic_marking_audio,
339         bool email,
340         bool zip
341         )
342 {
343         dcp::NameFormat::Map values;
344
345         try {
346                 list<KDMWithMetadataPtr> kdms;
347                 for (auto i: screens) {
348                         if (!i->recipient) {
349                                 continue;
350                         }
351
352                         dcp::LocalTime begin(valid_from, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
353                         dcp::LocalTime end(valid_to, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
354
355                         auto const kdm = kdm_from_dkdm(
356                                                         dkdm,
357                                                         i->recipient.get(),
358                                                         i->trusted_device_thumbprints(),
359                                                         begin,
360                                                         end,
361                                                         formulation,
362                                                         disable_forensic_marking_picture,
363                                                         disable_forensic_marking_audio
364                                                         );
365
366                         dcp::NameFormat::Map name_values;
367                         name_values['c'] = i->cinema->name;
368                         name_values['s'] = i->name;
369                         name_values['f'] = dkdm.annotation_text().get_value_or("");
370                         name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
371                         name_values['e'] = end.date() + " " + end.time_of_day(true, false);
372                         name_values['i'] = kdm.cpl_id();
373
374                         kdms.push_back (make_shared<KDMWithMetadata>(name_values, i->cinema.get(), i->cinema->emails, kdm));
375                 }
376                 write_files (kdms, zip, output, container_name_format, filename_format, verbose);
377                 if (email) {
378                         send_emails ({kdms}, container_name_format, filename_format, dkdm.annotation_text().get_value_or(""));
379                 }
380         } catch (FileError& e) {
381                 throw KDMCLIError (String::compose("%1 (%2)", e.what(), e.file().string()));
382         }
383 }
384
385
386 static
387 void
388 dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent)
389 {
390         if (indent > 0) {
391                 for (int i = 0; i < indent; ++i) {
392                         cout << " ";
393                 }
394                 cout << group->name() << "\n";
395         }
396         for (auto i: group->children()) {
397                 auto g = dynamic_pointer_cast<DKDMGroup>(i);
398                 if (g) {
399                         dump_dkdm_group (g, indent + 2);
400                 } else {
401                         for (int j = 0; j < indent; ++j) {
402                                 cout << " ";
403                         }
404                         auto d = dynamic_pointer_cast<DKDM>(i);
405                         assert(d);
406                         cout << d->dkdm().cpl_id() << "\n";
407                 }
408         }
409 }
410
411
412 optional<string>
413 kdm_cli (int argc, char* argv[])
414 try
415 {
416         boost::filesystem::path output = ".";
417         auto container_name_format = Config::instance()->kdm_container_name_format();
418         auto filename_format = Config::instance()->kdm_filename_format();
419         optional<string> cinema_name;
420         shared_ptr<Cinema> cinema;
421         string screen_description;
422         list<shared_ptr<Screen>> screens;
423         optional<dcp::EncryptedKDM> dkdm;
424         optional<boost::posix_time::ptime> valid_from;
425         optional<boost::posix_time::ptime> valid_to;
426         bool zip = false;
427         bool list_cinemas = false;
428         bool list_dkdm_cpls = false;
429         optional<string> duration_string;
430         bool verbose = false;
431         dcp::Formulation formulation = dcp::Formulation::MODIFIED_TRANSITIONAL_1;
432         bool disable_forensic_marking_picture = false;
433         optional<int> disable_forensic_marking_audio;
434         bool email = false;
435
436         program_name = argv[0];
437
438         int option_index = 0;
439         while (true) {
440                 static struct option long_options[] = {
441                         { "help", no_argument, 0, 'h'},
442                         { "output", required_argument, 0, 'o'},
443                         { "filename-format", required_argument, 0, 'K'},
444                         { "container-name-format", required_argument, 0, 'Z'},
445                         { "valid-from", required_argument, 0, 'f'},
446                         { "valid-to", required_argument, 0, 't'},
447                         { "valid-duration", required_argument, 0, 'd'},
448                         { "formulation", required_argument, 0, 'F' },
449                         { "disable-forensic-marking-picture", no_argument, 0, 'p' },
450                         { "disable-forensic-marking-audio", optional_argument, 0, 'a' },
451                         { "email", no_argument, 0, 'e' },
452                         { "zip", no_argument, 0, 'z' },
453                         { "verbose", no_argument, 0, 'v' },
454                         { "cinema", required_argument, 0, 'c' },
455                         { "screen", required_argument, 0, 'S' },
456                         { "certificate", required_argument, 0, 'C' },
457                         { "trusted-device", required_argument, 0, 'T' },
458                         { "list-cinemas", no_argument, 0, 'B' },
459                         { "list-dkdm-cpls", no_argument, 0, 'D' },
460                         { 0, 0, 0, 0 }
461                 };
462
463                 int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pae::zvc:S:C:T:BD", long_options, &option_index);
464
465                 if (c == -1) {
466                         break;
467                 }
468
469                 switch (c) {
470                 case 'h':
471                         help ();
472                         exit (EXIT_SUCCESS);
473                 case 'o':
474                         output = optarg;
475                         break;
476                 case 'K':
477                         filename_format = dcp::NameFormat (optarg);
478                         break;
479                 case 'Z':
480                         container_name_format = dcp::NameFormat (optarg);
481                         break;
482                 case 'f':
483                         valid_from = time_from_string (optarg);
484                         break;
485                 case 't':
486                         valid_to = time_from_string (optarg);
487                         break;
488                 case 'd':
489                         duration_string = optarg;
490                         break;
491                 case 'F':
492                         if (string(optarg) == "modified-transitional-1") {
493                                 formulation = dcp::Formulation::MODIFIED_TRANSITIONAL_1;
494                         } else if (string(optarg) == "multiple-modified-transitional-1") {
495                                 formulation = dcp::Formulation::MULTIPLE_MODIFIED_TRANSITIONAL_1;
496                         } else if (string(optarg) == "dci-any") {
497                                 formulation = dcp::Formulation::DCI_ANY;
498                         } else if (string(optarg) == "dci-specific") {
499                                 formulation = dcp::Formulation::DCI_SPECIFIC;
500                         } else {
501                                 throw KDMCLIError ("unrecognised KDM formulation " + string (optarg));
502                         }
503                         break;
504                 case 'p':
505                         disable_forensic_marking_picture = true;
506                         break;
507                 case 'a':
508                         disable_forensic_marking_audio = 0;
509                         if (optarg == 0 && argv[optind] != 0 && argv[optind][0] != '-') {
510                                 disable_forensic_marking_audio = atoi (argv[optind++]);
511                         } else if (optarg) {
512                                 disable_forensic_marking_audio = atoi (optarg);
513                         }
514                         break;
515                 case 'e':
516                         email = true;
517                         break;
518                 case 'z':
519                         zip = true;
520                         break;
521                 case 'v':
522                         verbose = true;
523                         break;
524                 case 'c':
525                         /* This could be a cinema to search for in the configured list or the name of a cinema being
526                            built up on-the-fly in the option.  Cater for both possilibities here by storing the name
527                            (for lookup) and by creating a Cinema which the next Screen will be added to.
528                         */
529                         cinema_name = optarg;
530                         cinema = make_shared<Cinema>(optarg, list<string>(), "", 0, 0);
531                         break;
532                 case 'S':
533                         screen_description = optarg;
534                         break;
535                 case 'C':
536                 {
537                         /* Make a new screen and add it to the current cinema */
538                         dcp::CertificateChain chain (dcp::file_to_string(optarg));
539                         auto screen = make_shared<Screen>(screen_description, "", chain.leaf(), vector<TrustedDevice>());
540                         if (cinema) {
541                                 cinema->add_screen (screen);
542                         }
543                         screens.push_back (screen);
544                         break;
545                 }
546                 case 'T':
547                         /* A trusted device ends up in the last screen we made */
548                         if (!screens.empty ()) {
549                                 screens.back()->trusted_devices.push_back(TrustedDevice(dcp::Certificate(dcp::file_to_string(optarg))));
550                         }
551                         break;
552                 case 'B':
553                         list_cinemas = true;
554                         break;
555                 case 'D':
556                         list_dkdm_cpls = true;
557                         break;
558                 }
559         }
560
561         if (list_cinemas) {
562                 auto cinemas = Config::instance()->cinemas ();
563                 for (auto i: cinemas) {
564                         cout << i->name << " (" << Emailer::address_list (i->emails) << ")\n";
565                 }
566                 exit (EXIT_SUCCESS);
567         }
568
569         if (list_dkdm_cpls) {
570                 dump_dkdm_group (Config::instance()->dkdms(), 0);
571                 exit (EXIT_SUCCESS);
572         }
573
574         if (!duration_string && !valid_to) {
575                 throw KDMCLIError ("you must specify a --valid-duration or --valid-to");
576         }
577
578         if (!valid_from) {
579                 throw KDMCLIError ("you must specify --valid-from");
580         }
581
582         if (optind >= argc) {
583                 help ();
584                 exit (EXIT_FAILURE);
585         }
586
587         if (screens.empty()) {
588                 if (!cinema_name) {
589                         throw KDMCLIError ("you must specify either a cinema or one or more screens using certificate files");
590                 }
591
592                 screens = find_cinema (*cinema_name)->screens ();
593         }
594
595         if (duration_string) {
596                 valid_to = valid_from.get() + duration_from_string (*duration_string);
597         }
598
599         dcpomatic_setup_path_encoding ();
600         dcpomatic_setup ();
601
602         if (verbose) {
603                 cout << "Making KDMs valid from " << valid_from.get() << " to " << valid_to.get() << "\n";
604         }
605
606         string const thing = argv[optind];
607         if (boost::filesystem::is_directory(thing) && boost::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
608                 from_film (
609                         screens,
610                         thing,
611                         verbose,
612                         output,
613                         container_name_format,
614                         filename_format,
615                         *valid_from,
616                         *valid_to,
617                         formulation,
618                         disable_forensic_marking_picture,
619                         disable_forensic_marking_audio,
620                         email,
621                         zip
622                         );
623         } else {
624                 if (boost::filesystem::is_regular_file(thing)) {
625                         dkdm = dcp::EncryptedKDM (dcp::file_to_string (thing));
626                 } else {
627                         dkdm = find_dkdm (thing);
628                 }
629
630                 if (!dkdm) {
631                         throw KDMCLIError ("could not find film or CPL ID corresponding to " + thing);
632                 }
633
634                 from_dkdm (
635                         screens,
636                         dcp::DecryptedKDM (*dkdm, Config::instance()->decryption_chain()->key().get()),
637                         verbose,
638                         output,
639                         container_name_format,
640                         filename_format,
641                         *valid_from,
642                         *valid_to,
643                         formulation,
644                         disable_forensic_marking_picture,
645                         disable_forensic_marking_audio,
646                         email,
647                         zip
648                         );
649         }
650
651         return {};
652 } catch (std::exception& e) {
653         return string(e.what());
654 }
655