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