1 // Copyright 2015 The Weave Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "examples/provider/file_config_store.h"
6
7 #include <sys/stat.h>
8 #include <sys/utsname.h>
9
10 #include <fstream>
11 #include <map>
12 #include <string>
13 #include <vector>
14
15 #include <base/bind.h>
16
17 namespace weave {
18 namespace examples {
19
20 const char kSettingsDir[] = "/var/lib/weave/";
21
FileConfigStore(const std::string & model_id,provider::TaskRunner * task_runner)22 FileConfigStore::FileConfigStore(const std::string& model_id,
23 provider::TaskRunner* task_runner)
24 : model_id_{model_id},
25 task_runner_{task_runner} {}
26
GetPath(const std::string & name) const27 std::string FileConfigStore::GetPath(const std::string& name) const {
28 std::string path{kSettingsDir};
29 path += "weave_settings_" + model_id_;
30 if (!name.empty())
31 path += "_" + name;
32 return path + ".json";
33 }
34
LoadDefaults(Settings * settings)35 bool FileConfigStore::LoadDefaults(Settings* settings) {
36 char host_name[HOST_NAME_MAX] = {};
37 gethostname(host_name, HOST_NAME_MAX);
38
39 settings->name = host_name;
40 settings->description = "";
41
42 utsname uname_data;
43 uname(&uname_data);
44
45 settings->firmware_version = uname_data.sysname;
46 settings->oem_name = "Unknown";
47 settings->model_name = "Unknown";
48 settings->model_id = model_id_;
49 settings->pairing_modes = {PairingType::kEmbeddedCode};
50 settings->embedded_code = "0000";
51
52 // Keys owners:
53 // avakulenko@google.com
54 // gene@chromium.org
55 // vitalybuka@chromium.org
56 settings->client_id =
57 "338428340000-vkb4p6h40c7kja1k3l70kke8t615cjit.apps.googleusercontent."
58 "com";
59 settings->client_secret = "LS_iPYo_WIOE0m2VnLdduhnx";
60 settings->api_key = "AIzaSyACK3oZtmIylUKXiTMqkZqfuRiCgQmQSAQ";
61
62 return true;
63 }
64
LoadSettings()65 std::string FileConfigStore::LoadSettings() {
66 return LoadSettings("");
67 }
68
LoadSettings(const std::string & name)69 std::string FileConfigStore::LoadSettings(const std::string& name) {
70 LOG(INFO) << "Loading settings from " << GetPath(name);
71 std::ifstream str(GetPath(name));
72 return std::string(std::istreambuf_iterator<char>(str),
73 std::istreambuf_iterator<char>());
74 }
75
SaveSettings(const std::string & name,const std::string & settings,const DoneCallback & callback)76 void FileConfigStore::SaveSettings(const std::string& name,
77 const std::string& settings,
78 const DoneCallback& callback) {
79 CHECK(mkdir(kSettingsDir, S_IRWXU) == 0 || errno == EEXIST);
80 LOG(INFO) << "Saving settings to " << GetPath(name);
81 std::ofstream str(GetPath(name));
82 str << settings;
83 if (!callback.is_null())
84 task_runner_->PostDelayedTask(FROM_HERE, base::Bind(callback, nullptr), {});
85 }
86
87 } // namespace examples
88 } // namespace weave
89