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