Only write config on change from the UI, not (say) from tests.
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "config.h"
21 #include "server.h"
22 #include "filter.h"
23 #include "ratio.h"
24 #include "dcp_content_type.h"
25 #include "cinema_sound_processor.h"
26 #include "colour_conversion.h"
27 #include "cinema.h"
28 #include "util.h"
29 #include "cross.h"
30 #include "raw_convert.h"
31 #include <dcp/colour_matrix.h>
32 #include <dcp/signer.h>
33 #include <dcp/certificate_chain.h>
34 #include <libcxml/cxml.h>
35 #include <glib.h>
36 #include <boost/filesystem.hpp>
37 #include <boost/algorithm/string.hpp>
38 #include <cstdlib>
39 #include <fstream>
40
41 #include "i18n.h"
42
43 using std::vector;
44 using std::cout;
45 using std::ifstream;
46 using std::string;
47 using std::list;
48 using std::max;
49 using std::remove;
50 using std::exception;
51 using std::cerr;
52 using boost::shared_ptr;
53 using boost::optional;
54 using boost::algorithm::trim;
55
56 Config* Config::_instance = 0;
57
58 /** Construct default configuration */
59 Config::Config ()
60 {
61         set_defaults ();
62 }
63
64 void
65 Config::set_defaults ()
66 {
67         _num_local_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
68         _server_port_base = 6192;
69         _use_any_servers = true;
70         _tms_path = ".";
71         _cinema_sound_processor = CinemaSoundProcessor::from_id (N_("dolby_cp750"));
72         _allow_any_dcp_frame_rate = false;
73         _default_still_length = 10;
74         _default_container = Ratio::from_id ("185");
75         _default_dcp_content_type = DCPContentType::from_isdcf_name ("FTR");
76         _default_j2k_bandwidth = 100000000;
77         _default_audio_delay = 0;
78         _check_for_updates = false;
79         _check_for_test_updates = false;
80         _maximum_j2k_bandwidth = 250000000;
81         _log_types = Log::TYPE_GENERAL | Log::TYPE_WARNING | Log::TYPE_ERROR | Log::TYPE_DEBUG;
82 #ifdef DCPOMATIC_WINDOWS          
83         _win32_console = false;
84 #endif    
85
86         _allowed_dcp_frame_rates.clear ();
87         _allowed_dcp_frame_rates.push_back (24);
88         _allowed_dcp_frame_rates.push_back (25);
89         _allowed_dcp_frame_rates.push_back (30);
90         _allowed_dcp_frame_rates.push_back (48);
91         _allowed_dcp_frame_rates.push_back (50);
92         _allowed_dcp_frame_rates.push_back (60);
93
94         _colour_conversions.clear ();
95         _colour_conversions.push_back (PresetColourConversion (_("sRGB"), dcp::ColourConversion::srgb_to_xyz ()));
96         _colour_conversions.push_back (PresetColourConversion (_("Rec. 601"), dcp::ColourConversion::rec601_to_xyz ()));
97         _colour_conversions.push_back (PresetColourConversion (_("Rec. 709"), dcp::ColourConversion::rec709_to_xyz ()));
98         _colour_conversions.push_back (PresetColourConversion (_("P3 (from SMPTE RP 431-2)"), dcp::ColourConversion::p3_to_xyz ()));
99
100         set_kdm_email_to_default ();
101 }
102
103 void
104 Config::restore_defaults ()
105 {
106         Config::instance()->set_defaults ();
107         Config::instance()->changed ();
108 }
109
110 void
111 Config::read ()
112 {
113         if (!boost::filesystem::exists (file ())) {
114                 /* Make a new set of signing certificates and key */
115                 _signer.reset (new dcp::Signer (openssl_path ()));
116                 /* And decryption keys */
117                 make_decryption_keys ();
118                 return;
119         }
120
121         cxml::Document f ("Config");
122         f.read_file (file ());
123         optional<string> c;
124
125         optional<int> version = f.optional_number_child<int> ("Version");
126
127         _num_local_encoding_threads = f.number_child<int> ("NumLocalEncodingThreads");
128         _default_directory = f.string_child ("DefaultDirectory");
129
130         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
131         if (!b) {
132                 b = f.optional_number_child<int> ("ServerPortBase");
133         }
134         _server_port_base = b.get ();
135
136         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
137         _use_any_servers = u.get_value_or (true);
138
139         list<cxml::NodePtr> servers = f.node_children ("Server");
140         for (list<cxml::NodePtr>::iterator i = servers.begin(); i != servers.end(); ++i) {
141                 if ((*i)->node_children("HostName").size() == 1) {
142                         _servers.push_back ((*i)->string_child ("HostName"));
143                 } else {
144                         _servers.push_back ((*i)->content ());
145                 }
146         }
147         
148         _tms_ip = f.string_child ("TMSIP");
149         _tms_path = f.string_child ("TMSPath");
150         _tms_user = f.string_child ("TMSUser");
151         _tms_password = f.string_child ("TMSPassword");
152
153         c = f.optional_string_child ("SoundProcessor");
154         if (c) {
155                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
156         }
157         c = f.optional_string_child ("CinemaSoundProcessor");
158         if (c) {
159                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
160         }
161
162         _language = f.optional_string_child ("Language");
163
164         c = f.optional_string_child ("DefaultContainer");
165         if (c) {
166                 _default_container = Ratio::from_id (c.get ());
167         }
168
169         c = f.optional_string_child ("DefaultDCPContentType");
170         if (c) {
171                 _default_dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
172         }
173
174         if (f.optional_string_child ("DCPMetadataIssuer")) {
175                 _dcp_issuer = f.string_child ("DCPMetadataIssuer");
176         } else if (f.optional_string_child ("DCPIssuer")) {
177                 _dcp_issuer = f.string_child ("DCPIssuer");
178         }
179         
180         if (version && version.get() >= 2) {
181                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
182         } else {
183                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
184         }
185         
186         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
187         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
188         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
189
190         list<cxml::NodePtr> cc = f.node_children ("ColourConversion");
191
192         if (!cc.empty ()) {
193                 _colour_conversions.clear ();
194         }
195
196         try {
197                 for (list<cxml::NodePtr>::iterator i = cc.begin(); i != cc.end(); ++i) {
198                         /* This is a bit of a hack; use 32 (the first Film state file version for the 2.x branch)
199                            for version 2 and 10 (the current Film state version for the 1.x branch) for version 1.
200                         */
201                         _colour_conversions.push_back (PresetColourConversion (*i, version == 2 ? 32 : 10));
202                 }
203         } catch (cxml::Error) {
204                 /* Probably failed to load an old-style ColourConversion tag; just give up */
205                 _colour_conversions.push_back (PresetColourConversion (_("sRGB"), dcp::ColourConversion::srgb_to_xyz ()));
206                 _colour_conversions.push_back (PresetColourConversion (_("Rec. 709"), dcp::ColourConversion::rec709_to_xyz ()));
207         }
208
209         list<cxml::NodePtr> cin = f.node_children ("Cinema");
210         for (list<cxml::NodePtr>::iterator i = cin.begin(); i != cin.end(); ++i) {
211                 /* Slightly grotty two-part construction of Cinema here so that we can use
212                    shared_from_this.
213                 */
214                 shared_ptr<Cinema> cinema (new Cinema (*i));
215                 cinema->read_screens (*i);
216                 _cinemas.push_back (cinema);
217         }
218
219         _mail_server = f.string_child ("MailServer");
220         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
221         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
222         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
223         _kdm_from = f.string_child ("KDMFrom");
224         _kdm_cc = f.optional_string_child ("KDMCC").get_value_or ("");
225         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
226         _kdm_email = f.string_child ("KDMEmail");
227
228         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
229         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
230
231         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
232         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate");
233
234         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (Log::TYPE_GENERAL | Log::TYPE_WARNING | Log::TYPE_ERROR);
235 #ifdef DCPOMATIC_WINDOWS        
236         _win32_console = f.optional_bool_child ("Win32Console").get_value_or (false);
237 #endif  
238
239         list<cxml::NodePtr> his = f.node_children ("History");
240         for (list<cxml::NodePtr>::const_iterator i = his.begin(); i != his.end(); ++i) {
241                 _history.push_back ((*i)->content ());
242         }
243
244         cxml::NodePtr signer = f.optional_node_child ("Signer");
245         dcp::CertificateChain signer_chain;
246         if (signer) {
247                 /* Read the signing certificates and private key in from the config file */
248                 list<cxml::NodePtr> certificates = signer->node_children ("Certificate");
249                 for (list<cxml::NodePtr>::const_iterator i = certificates.begin(); i != certificates.end(); ++i) {
250                         signer_chain.add (dcp::Certificate ((*i)->content ()));
251                 }
252
253                 _signer.reset (new dcp::Signer (signer_chain, signer->string_child ("PrivateKey")));
254         } else {
255                 /* Make a new set of signing certificates and key */
256                 _signer.reset (new dcp::Signer (openssl_path ()));
257         }
258
259         if (f.optional_string_child ("DecryptionCertificate")) {
260                 _decryption_certificate = dcp::Certificate (f.string_child ("DecryptionCertificate"));
261         }
262
263         if (f.optional_string_child ("DecryptionPrivateKey")) {
264                 _decryption_private_key = f.string_child ("DecryptionPrivateKey");
265         }
266
267         if (!f.optional_string_child ("DecryptionCertificate") || !f.optional_string_child ("DecryptionPrivateKey")) {
268                 /* Generate our own decryption certificate and key if either is not present in config */
269                 make_decryption_keys ();
270         }
271 }
272
273 void
274 Config::make_decryption_keys ()
275 {
276         boost::filesystem::path p = dcp::make_certificate_chain (openssl_path ());
277         _decryption_certificate = dcp::Certificate (dcp::file_to_string (p / "leaf.signed.pem"));
278         _decryption_private_key = dcp::file_to_string (p / "leaf.key");
279         boost::filesystem::remove_all (p);
280 }
281
282 /** @return Filename to write configuration to */
283 boost::filesystem::path
284 Config::file () const
285 {
286         boost::filesystem::path p;
287         p /= g_get_user_config_dir ();
288         boost::system::error_code ec;
289         boost::filesystem::create_directory (p, ec);
290         p /= "dcpomatic2";
291         boost::filesystem::create_directory (p, ec);
292         p /= "config.xml";
293         return p;
294 }
295
296 /** @return Singleton instance */
297 Config *
298 Config::instance ()
299 {
300         if (_instance == 0) {
301                 _instance = new Config;
302                 try {
303                         _instance->read ();
304                 } catch (exception& e) {
305                         /* configuration load failed; never mind, just
306                            stick with the default.
307                         */
308                         cerr << "dcpomatic: failed to load configuration (" << e.what() << ")\n";
309                 } catch (...) {
310                         cerr << "dcpomatic: failed to load configuration\n";
311                 }
312         }
313
314         return _instance;
315 }
316
317 /** Write our configuration to disk */
318 void
319 Config::write () const
320 {
321         xmlpp::Document doc;
322         xmlpp::Element* root = doc.create_root_node ("Config");
323
324         root->add_child("Version")->add_child_text ("2");
325         root->add_child("NumLocalEncodingThreads")->add_child_text (raw_convert<string> (_num_local_encoding_threads));
326         root->add_child("DefaultDirectory")->add_child_text (_default_directory.string ());
327         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
328         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
329         
330         for (vector<string>::const_iterator i = _servers.begin(); i != _servers.end(); ++i) {
331                 root->add_child("Server")->add_child_text (*i);
332         }
333
334         root->add_child("TMSIP")->add_child_text (_tms_ip);
335         root->add_child("TMSPath")->add_child_text (_tms_path);
336         root->add_child("TMSUser")->add_child_text (_tms_user);
337         root->add_child("TMSPassword")->add_child_text (_tms_password);
338         if (_cinema_sound_processor) {
339                 root->add_child("CinemaSoundProcessor")->add_child_text (_cinema_sound_processor->id ());
340         }
341         if (_language) {
342                 root->add_child("Language")->add_child_text (_language.get());
343         }
344         if (_default_container) {
345                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
346         }
347         if (_default_dcp_content_type) {
348                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
349         }
350         root->add_child("DCPIssuer")->add_child_text (_dcp_issuer);
351
352         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
353
354         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
355         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
356         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
357
358         for (vector<PresetColourConversion>::const_iterator i = _colour_conversions.begin(); i != _colour_conversions.end(); ++i) {
359                 i->as_xml (root->add_child ("ColourConversion"));
360         }
361
362         for (list<shared_ptr<Cinema> >::const_iterator i = _cinemas.begin(); i != _cinemas.end(); ++i) {
363                 (*i)->as_xml (root->add_child ("Cinema"));
364         }
365
366         root->add_child("MailServer")->add_child_text (_mail_server);
367         root->add_child("MailUser")->add_child_text (_mail_user);
368         root->add_child("MailPassword")->add_child_text (_mail_password);
369         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
370         root->add_child("KDMFrom")->add_child_text (_kdm_from);
371         root->add_child("KDMCC")->add_child_text (_kdm_cc);
372         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
373         root->add_child("KDMEmail")->add_child_text (_kdm_email);
374
375         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
376         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
377
378         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
379         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
380         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
381 #ifdef DCPOMATIC_WINDOWS        
382         root->add_child("Win32Console")->add_child_text (_win32_console ? "1" : "0");
383 #endif  
384
385         xmlpp::Element* signer = root->add_child ("Signer");
386         dcp::CertificateChain::List certs = _signer->certificates().root_to_leaf ();
387         for (dcp::CertificateChain::List::const_iterator i = certs.begin(); i != certs.end(); ++i) {
388                 signer->add_child("Certificate")->add_child_text (i->certificate (true));
389         }
390         signer->add_child("PrivateKey")->add_child_text (_signer->key ());
391
392         root->add_child("DecryptionCertificate")->add_child_text (_decryption_certificate.certificate (true));
393         root->add_child("DecryptionPrivateKey")->add_child_text (_decryption_private_key);
394
395         for (vector<boost::filesystem::path>::const_iterator i = _history.begin(); i != _history.end(); ++i) {
396                 root->add_child("History")->add_child_text (i->string ());
397         }
398
399         try {
400                 doc.write_to_file_formatted (file().string ());
401         } catch (xmlpp::exception& e) {
402                 string s = e.what ();
403                 trim (s);
404                 throw FileError (s, file ());
405         }
406 }
407
408 boost::filesystem::path
409 Config::default_directory_or (boost::filesystem::path a) const
410 {
411         if (_default_directory.empty()) {
412                 return a;
413         }
414
415         boost::system::error_code ec;
416         bool const e = boost::filesystem::exists (_default_directory, ec);
417         if (ec || !e) {
418                 return a;
419         }
420
421         return _default_directory;
422 }
423
424 void
425 Config::drop ()
426 {
427         delete _instance;
428         _instance = 0;
429 }
430
431 void
432 Config::changed ()
433 {
434         Changed ();
435 }
436
437 void
438 Config::set_kdm_email_to_default ()
439 {
440         _kdm_email = _(
441                 "Dear Projectionist\n\n"
442                 "Please find attached KDMs for $CPL_NAME.\n\n"
443                 "Cinema: $CINEMA_NAME\n"
444                 "Screen(s): $SCREENS\n\n"
445                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
446                 "Best regards,\nDCP-o-matic"
447                 );
448 }
449
450 void
451 Config::reset_kdm_email ()
452 {
453         set_kdm_email_to_default ();
454         changed ();
455 }
456
457 void
458 Config::add_to_history (boost::filesystem::path p)
459 {
460         /* Remove existing instances of this path in the history */
461         _history.erase (remove (_history.begin(), _history.end(), p), _history.end ());
462         
463         _history.insert (_history.begin (), p);
464         if (_history.size() > HISTORY_SIZE) {
465                 _history.pop_back ();
466         }
467
468         changed ();
469 }