Revert of Fix missing GN dependencies. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / cloud_print / service / service_state.cc
blob789d229a0e2591b3f94f35a3d64402026effbdb1
1 // Copyright (c) 2012 The Chromium 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.
5 #include "cloud_print/service/service_state.h"
7 #include "base/json/json_reader.h"
8 #include "base/json/json_writer.h"
9 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "net/base/elements_upload_data_stream.h"
14 #include "net/base/escape.h"
15 #include "net/base/io_buffer.h"
16 #include "net/base/load_flags.h"
17 #include "net/base/request_priority.h"
18 #include "net/base/upload_bytes_element_reader.h"
19 #include "net/url_request/url_request.h"
20 #include "net/url_request/url_request_context.h"
21 #include "net/url_request/url_request_context_builder.h"
23 namespace {
25 const char kCloudPrintJsonName[] = "cloud_print";
26 const char kEnabledOptionName[] = "enabled";
28 const char kEmailOptionName[] = "email";
29 const char kProxyIdOptionName[] = "proxy_id";
30 const char kRobotEmailOptionName[] = "robot_email";
31 const char kRobotTokenOptionName[] = "robot_refresh_token";
32 const char kAuthTokenOptionName[] = "auth_token";
33 const char kXmppAuthTokenOptionName[] = "xmpp_auth_token";
35 const char kClientLoginUrl[] = "https://www.google.com/accounts/ClientLogin";
37 const int64 kRequestTimeoutMs = 10 * 1000;
39 class ServiceStateURLRequestDelegate : public net::URLRequest::Delegate {
40 public:
41 void OnResponseStarted(net::URLRequest* request) override {
42 if (request->GetResponseCode() == 200) {
43 Read(request);
44 if (request->status().is_io_pending())
45 return;
47 request->Cancel();
50 void OnReadCompleted(net::URLRequest* request, int bytes_read) override {
51 Read(request);
52 if (!request->status().is_io_pending())
53 base::MessageLoop::current()->Quit();
56 const std::string& data() const {
57 return data_;
60 private:
61 void Read(net::URLRequest* request) {
62 // Read as many bytes as are available synchronously.
63 const int kBufSize = 100000;
64 scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(kBufSize));
65 int num_bytes = 0;
66 while (request->Read(buf.get(), kBufSize, &num_bytes)) {
67 data_.append(buf->data(), buf->data() + num_bytes);
70 std::string data_;
74 void SetNotEmptyJsonString(base::DictionaryValue* dictionary,
75 const std::string& name,
76 const std::string& value) {
77 if (!value.empty())
78 dictionary->SetString(name, value);
81 } // namespace
83 ServiceState::ServiceState() {
84 Reset();
87 ServiceState::~ServiceState() {
90 void ServiceState::Reset() {
91 email_.clear();
92 proxy_id_.clear();
93 robot_email_.clear();
94 robot_token_.clear();
95 auth_token_.clear();
96 xmpp_auth_token_.clear();
99 bool ServiceState::FromString(const std::string& json) {
100 Reset();
101 scoped_ptr<base::Value> data(base::JSONReader::Read(json));
102 if (!data.get())
103 return false;
105 const base::DictionaryValue* services = NULL;
106 if (!data->GetAsDictionary(&services))
107 return false;
109 const base::DictionaryValue* cloud_print = NULL;
110 if (!services->GetDictionary(kCloudPrintJsonName, &cloud_print))
111 return false;
113 bool valid_file = true;
114 // Don't exit on fail. Collect all data for re-use by user later.
115 if (!cloud_print->GetBoolean(kEnabledOptionName, &valid_file))
116 valid_file = false;
118 cloud_print->GetString(kEmailOptionName, &email_);
119 cloud_print->GetString(kProxyIdOptionName, &proxy_id_);
120 cloud_print->GetString(kRobotEmailOptionName, &robot_email_);
121 cloud_print->GetString(kRobotTokenOptionName, &robot_token_);
122 cloud_print->GetString(kAuthTokenOptionName, &auth_token_);
123 cloud_print->GetString(kXmppAuthTokenOptionName, &xmpp_auth_token_);
125 return valid_file && IsValid();
128 bool ServiceState::IsValid() const {
129 if (email_.empty() || proxy_id_.empty())
130 return false;
131 bool valid_robot = !robot_email_.empty() && !robot_token_.empty();
132 bool valid_auth = !auth_token_.empty() && !xmpp_auth_token_.empty();
133 return valid_robot || valid_auth;
136 std::string ServiceState::ToString() {
137 scoped_ptr<base::DictionaryValue> cloud_print(new base::DictionaryValue());
138 cloud_print->SetBoolean(kEnabledOptionName, true);
140 SetNotEmptyJsonString(cloud_print.get(), kEmailOptionName, email_);
141 SetNotEmptyJsonString(cloud_print.get(), kProxyIdOptionName, proxy_id_);
142 SetNotEmptyJsonString(cloud_print.get(), kRobotEmailOptionName, robot_email_);
143 SetNotEmptyJsonString(cloud_print.get(), kRobotTokenOptionName, robot_token_);
144 SetNotEmptyJsonString(cloud_print.get(), kAuthTokenOptionName, auth_token_);
145 SetNotEmptyJsonString(cloud_print.get(), kXmppAuthTokenOptionName,
146 xmpp_auth_token_);
148 base::DictionaryValue services;
149 services.Set(kCloudPrintJsonName, cloud_print.Pass());
151 std::string json;
152 base::JSONWriter::WriteWithOptions(
153 services, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json);
154 return json;
157 std::string ServiceState::LoginToGoogle(const std::string& service,
158 const std::string& email,
159 const std::string& password) {
160 base::MessageLoopForIO loop;
162 net::URLRequestContextBuilder builder;
163 scoped_ptr<net::URLRequestContext> context(builder.Build());
165 ServiceStateURLRequestDelegate fetcher_delegate;
166 GURL url(kClientLoginUrl);
168 std::string post_body;
169 post_body += "accountType=GOOGLE";
170 post_body += "&Email=" + net::EscapeUrlEncodedData(email, true);
171 post_body += "&Passwd=" + net::EscapeUrlEncodedData(password, true);
172 post_body += "&source=" + net::EscapeUrlEncodedData("CP-Service", true);
173 post_body += "&service=" + net::EscapeUrlEncodedData(service, true);
175 scoped_ptr<net::URLRequest> request(context->CreateRequest(
176 url, net::DEFAULT_PRIORITY, &fetcher_delegate));
177 int load_flags = request->load_flags();
178 load_flags = load_flags | net::LOAD_DO_NOT_SEND_COOKIES;
179 load_flags = load_flags | net::LOAD_DO_NOT_SAVE_COOKIES;
180 request->SetLoadFlags(load_flags);
182 scoped_ptr<net::UploadElementReader> reader(
183 net::UploadOwnedBytesElementReader::CreateWithString(post_body));
184 request->set_upload(
185 net::ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
186 request->SetExtraRequestHeaderByName(
187 "Content-Type", "application/x-www-form-urlencoded", true);
188 request->set_method("POST");
189 request->Start();
191 base::MessageLoop::current()->PostDelayedTask(
192 FROM_HERE,
193 base::MessageLoop::QuitClosure(),
194 base::TimeDelta::FromMilliseconds(kRequestTimeoutMs));
196 base::MessageLoop::current()->Run();
198 const char kAuthStart[] = "Auth=";
199 std::vector<std::string> lines;
200 Tokenize(fetcher_delegate.data(), "\r\n", &lines);
201 for (size_t i = 0; i < lines.size(); ++i) {
202 if (StartsWithASCII(lines[i], kAuthStart, false))
203 return lines[i].substr(arraysize(kAuthStart) - 1);
206 return std::string();
209 bool ServiceState::Configure(const std::string& email,
210 const std::string& password,
211 const std::string& proxy_id) {
212 robot_token_.clear();
213 robot_email_.clear();
214 email_ = email;
215 proxy_id_ = proxy_id;
216 auth_token_ = LoginToGoogle("cloudprint", email_, password);
217 xmpp_auth_token_ = LoginToGoogle("chromiumsync", email_, password);
218 return IsValid();