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