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