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