Pull methods out of CinemaKDMs.
[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 = write_zip_files (
144                         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                                 dcp::NameFormat::Map name_values;
248                                 name_values['c'] = i->cinema->name;
249                                 name_values['s'] = i->name;
250
251                                 kdms.push_back (KDMWithMetadataPtr(new DCPKDMWithMetadata(name_values, i->cinema, kdm)));
252                         }
253                 }
254
255                 write_files (kdms, zip, output, container_name_format, filename_format, values, verbose);
256         } catch (FileError& e) {
257                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
258                 exit (EXIT_FAILURE);
259         } catch (KDMError& e) {
260                 cerr << program_name << ": " << e.what() << "\n";
261                 exit (EXIT_FAILURE);
262         } catch (runtime_error& e) {
263                 cerr << program_name << ": " << e.what() << "\n";
264                 exit (EXIT_FAILURE);
265         }
266 }
267
268 optional<dcp::EncryptedKDM>
269 sub_find_dkdm (shared_ptr<DKDMGroup> group, string cpl_id)
270 {
271         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
272                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
273                 if (g) {
274                         optional<dcp::EncryptedKDM> dkdm = sub_find_dkdm (g, cpl_id);
275                         if (dkdm) {
276                                 return dkdm;
277                         }
278                 } else {
279                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
280                         assert (d);
281                         if (d->dkdm().cpl_id() == cpl_id) {
282                                 return d->dkdm();
283                         }
284                 }
285         }
286
287         return optional<dcp::EncryptedKDM>();
288 }
289
290 optional<dcp::EncryptedKDM>
291 find_dkdm (string cpl_id)
292 {
293         return sub_find_dkdm (Config::instance()->dkdms(), cpl_id);
294 }
295
296 dcp::EncryptedKDM
297 kdm_from_dkdm (
298         dcp::DecryptedKDM dkdm,
299         dcp::Certificate target,
300         vector<string> trusted_devices,
301         dcp::LocalTime valid_from,
302         dcp::LocalTime valid_to,
303         dcp::Formulation formulation,
304         bool disable_forensic_marking_picture,
305         optional<int> disable_forensic_marking_audio
306         )
307 {
308         /* Signer for new KDM */
309         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
310         if (!signer->valid ()) {
311                 error ("signing certificate chain is invalid.");
312         }
313
314         /* Make a new empty KDM and add the keys from the DKDM to it */
315         dcp::DecryptedKDM kdm (
316                 valid_from,
317                 valid_to,
318                 dkdm.annotation_text().get_value_or(""),
319                 dkdm.content_title_text(),
320                 dcp::LocalTime().as_string()
321                 );
322
323         BOOST_FOREACH (dcp::DecryptedKDMKey const & j, dkdm.keys()) {
324                 kdm.add_key(j);
325         }
326
327         return kdm.encrypt (signer, target, trusted_devices, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
328 }
329
330 void
331 from_dkdm (
332         list<shared_ptr<Screen> > screens,
333         dcp::DecryptedKDM dkdm,
334         bool verbose,
335         boost::filesystem::path output,
336         dcp::NameFormat container_name_format,
337         dcp::NameFormat filename_format,
338         boost::posix_time::ptime valid_from,
339         boost::posix_time::ptime valid_to,
340         dcp::Formulation formulation,
341         bool disable_forensic_marking_picture,
342         optional<int> disable_forensic_marking_audio,
343         bool zip
344         )
345 {
346         dcp::NameFormat::Map values;
347         values['f'] = dkdm.annotation_text().get_value_or("");
348         values['b'] = dcp::LocalTime(valid_from).date() + " " + dcp::LocalTime(valid_from).time_of_day(true, false);
349         values['e'] = dcp::LocalTime(valid_to).date() + " " + dcp::LocalTime(valid_to).time_of_day(true, false);
350
351         try {
352                 list<KDMWithMetadataPtr> screen_kdms;
353                 BOOST_FOREACH (shared_ptr<Screen> i, screens) {
354                         if (!i->recipient) {
355                                 continue;
356                         }
357
358                         dcp::NameFormat::Map name_values;
359                         name_values['c'] = i->cinema->name;
360                         name_values['s'] = i->name;
361
362                         screen_kdms.push_back (
363                                 KDMWithMetadataPtr(
364                                         new DCPKDMWithMetadata(
365                                                 name_values,
366                                                 i->cinema,
367                                                 kdm_from_dkdm(
368                                                         dkdm,
369                                                         i->recipient.get(),
370                                                         i->trusted_device_thumbprints(),
371                                                         dcp::LocalTime(valid_from, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
372                                                         dcp::LocalTime(valid_to, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
373                                                         formulation,
374                                                         disable_forensic_marking_picture,
375                                                         disable_forensic_marking_audio
376                                                         )
377                                                 )
378                                         )
379                                 );
380                 }
381                 write_files (screen_kdms, zip, output, container_name_format, filename_format, values, verbose);
382         } catch (FileError& e) {
383                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
384                 exit (EXIT_FAILURE);
385         } catch (KDMError& e) {
386                 cerr << program_name << ": " << e.what() << "\n";
387                 exit (EXIT_FAILURE);
388         }
389 }
390
391 void
392 dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent)
393 {
394         if (indent > 0) {
395                 for (int i = 0; i < indent; ++i) {
396                         cout << " ";
397                 }
398                 cout << group->name() << "\n";
399         }
400         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
401                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
402                 if (g) {
403                         dump_dkdm_group (g, indent + 2);
404                 } else {
405                         for (int j = 0; j < indent; ++j) {
406                                 cout << " ";
407                         }
408                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
409                         assert(d);
410                         cout << d->dkdm().cpl_id() << "\n";
411                 }
412         }
413 }
414
415 int main (int argc, char* argv[])
416 {
417         boost::filesystem::path output = ".";
418         dcp::NameFormat container_name_format = Config::instance()->kdm_container_name_format();
419         dcp::NameFormat 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::MODIFIED_TRANSITIONAL_1;
433         bool disable_forensic_marking_picture = false;
434         optional<int> disable_forensic_marking_audio;
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                         { "zip", no_argument, 0, 'z' },
452                         { "verbose", no_argument, 0, 'v' },
453                         { "cinema", required_argument, 0, 'c' },
454                         { "screen", required_argument, 0, 'S' },
455                         { "certificate", required_argument, 0, 'C' },
456                         { "trusted-device", required_argument, 0, 'T' },
457                         { "list-cinemas", no_argument, 0, 'B' },
458                         { "list-dkdm-cpls", no_argument, 0, 'D' },
459                         { 0, 0, 0, 0 }
460                 };
461
462                 int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pa::zvc:S:C:T:BD", long_options, &option_index);
463
464                 if (c == -1) {
465                         break;
466                 }
467
468                 switch (c) {
469                 case 'h':
470                         help ();
471                         exit (EXIT_SUCCESS);
472                 case 'o':
473                         output = optarg;
474                         break;
475                 case 'K':
476                         filename_format = dcp::NameFormat (optarg);
477                         break;
478                 case 'Z':
479                         container_name_format = dcp::NameFormat (optarg);
480                         break;
481                 case 'f':
482                         valid_from = time_from_string (optarg);
483                         break;
484                 case 't':
485                         valid_to = time_from_string (optarg);
486                         break;
487                 case 'd':
488                         duration_string = optarg;
489                         break;
490                 case 'F':
491                         if (string (optarg) == "modified-transitional-1") {
492                                 formulation = dcp::MODIFIED_TRANSITIONAL_1;
493                         } else if (string (optarg) == "multiple-modified-transitional-1") {
494                                 formulation = dcp::MULTIPLE_MODIFIED_TRANSITIONAL_1;
495                         } else if (string (optarg) == "dci-any") {
496                                 formulation = dcp::DCI_ANY;
497                         } else if (string (optarg) == "dci-specific") {
498                                 formulation = dcp::DCI_SPECIFIC;
499                         } else {
500                                 error ("unrecognised KDM formulation " + string (optarg));
501                         }
502                         break;
503                 case 'p':
504                         disable_forensic_marking_picture = true;
505                         break;
506                 case 'a':
507                         disable_forensic_marking_audio = 0;
508                         if (optarg == 0 && argv[optind] != 0 && argv[optind][0] != '-') {
509                                 disable_forensic_marking_audio = atoi (argv[optind++]);
510                         } else if (optarg) {
511                                 disable_forensic_marking_audio = atoi (optarg);
512                         }
513                         break;
514                 case 'z':
515                         zip = true;
516                         break;
517                 case 'v':
518                         verbose = true;
519                         break;
520                 case 'c':
521                         /* This could be a cinema to search for in the configured list or the name of a cinema being
522                            built up on-the-fly in the option.  Cater for both possilibities here by storing the name
523                            (for lookup) and by creating a Cinema which the next Screen will be added to.
524                         */
525                         cinema_name = optarg;
526                         cinema = shared_ptr<Cinema> (new Cinema (optarg, list<string>(), "", 0, 0));
527                         break;
528                 case 'S':
529                         screen_description = optarg;
530                         break;
531                 case 'C':
532                 {
533                         /* Make a new screen and add it to the current cinema */
534                         dcp::CertificateChain chain (dcp::file_to_string(optarg));
535                         shared_ptr<Screen> screen (new Screen (screen_description, "", chain.leaf(), vector<TrustedDevice>()));
536                         if (cinema) {
537                                 cinema->add_screen (screen);
538                         }
539                         screens.push_back (screen);
540                         break;
541                 }
542                 case 'T':
543                         /* A trusted device ends up in the last screen we made */
544                         if (!screens.empty ()) {
545                                 screens.back()->trusted_devices.push_back(TrustedDevice(dcp::Certificate(dcp::file_to_string(optarg))));
546                         }
547                         break;
548                 case 'B':
549                         list_cinemas = true;
550                         break;
551                 case 'D':
552                         list_dkdm_cpls = true;
553                         break;
554                 }
555         }
556
557         if (list_cinemas) {
558                 list<boost::shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
559                 for (list<boost::shared_ptr<Cinema> >::const_iterator i = cinemas.begin(); i != cinemas.end(); ++i) {
560                         cout << (*i)->name << " (" << Emailer::address_list ((*i)->emails) << ")\n";
561                 }
562                 exit (EXIT_SUCCESS);
563         }
564
565         if (list_dkdm_cpls) {
566                 dump_dkdm_group (Config::instance()->dkdms(), 0);
567                 exit (EXIT_SUCCESS);
568         }
569
570         if (!duration_string && !valid_to) {
571                 error ("you must specify a --valid-duration or --valid-to");
572         }
573
574         if (!valid_from) {
575                 error ("you must specify --valid-from");
576                 exit (EXIT_FAILURE);
577         }
578
579         if (optind >= argc) {
580                 help ();
581                 exit (EXIT_FAILURE);
582         }
583
584         if (screens.empty()) {
585                 if (!cinema_name) {
586                         error ("you must specify either a cinema or one or more screens using certificate files");
587                 }
588
589                 screens = find_cinema (*cinema_name)->screens ();
590         }
591
592         if (duration_string) {
593                 valid_to = valid_from.get() + duration_from_string (*duration_string);
594         }
595
596         dcpomatic_setup_path_encoding ();
597         dcpomatic_setup ();
598
599         if (verbose) {
600                 cout << "Making KDMs valid from " << valid_from.get() << " to " << valid_to.get() << "\n";
601         }
602
603         string const thing = argv[optind];
604         if (boost::filesystem::is_directory(thing) && boost::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
605                 from_film (
606                         screens,
607                         thing,
608                         verbose,
609                         output,
610                         container_name_format,
611                         filename_format,
612                         *valid_from,
613                         *valid_to,
614                         formulation,
615                         disable_forensic_marking_picture,
616                         disable_forensic_marking_audio,
617                         zip
618                         );
619         } else {
620                 if (boost::filesystem::is_regular_file(thing)) {
621                         dkdm = dcp::EncryptedKDM (dcp::file_to_string (thing));
622                 } else {
623                         dkdm = find_dkdm (thing);
624                 }
625
626                 if (!dkdm) {
627                         error ("could not find film or CPL ID corresponding to " + thing);
628                 }
629
630                 from_dkdm (
631                         screens,
632                         dcp::DecryptedKDM (*dkdm, Config::instance()->decryption_chain()->key().get()),
633                         verbose,
634                         output,
635                         container_name_format,
636                         filename_format,
637                         *valid_from,
638                         *valid_to,
639                         formulation,
640                         disable_forensic_marking_picture,
641                         disable_forensic_marking_audio,
642                         zip
643                         );
644         }
645
646         return 0;
647 }