Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(215)

Side by Side Diff: chrome/browser/resources/print_preview/cloud_print_interface.js

Issue 10108001: Refactor print preview web ui (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Resolve conflicts Created 8 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | chrome/browser/resources/print_preview/color_settings.html » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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.
4
5 cr.define('cloudprint', function() {
6 'use strict';
7
8 /**
9 * API to the Google Cloud Print service.
10 * @param {string} baseUrl Base part of the Google Cloud Print service URL
11 * with no trailing slash. For example,
12 * 'https://www.google.com/cloudprint'.
13 * @constructor
14 * @extends {cr.EventTarget}
15 */
16 function CloudPrintInterface(baseUrl) {
17 /**
18 * The base URL of the Google Cloud Print API.
19 * @type {string}
20 * @private
21 */
22 this.baseURL_ = baseUrl;
23
24 /**
25 * Last received XSRF token. Sent as a parameter in every request.
26 * @type {string}
27 * @private
28 */
29 this.xsrfToken_ = '';
30 };
31
32 /**
33 * Event types dispatched by the interface.
34 * @enum {string}
35 */
36 CloudPrintInterface.EventType = {
37 ERROR: 'cloudprint.CloudPrintInterface.ERROR',
38 PRINTER_DONE: 'cloudprint.CloudPrintInterface.PRINTER_DONE',
39 SEARCH_DONE: 'cloudprint.CloudPrintInterface.SEARCH_DONE',
40 SUBMIT_DONE: 'cloudprint.CloudPrintInterface.SUBMIT_DONE'
41 };
42
43 /**
44 * Content type header value for a URL encoded HTTP request.
45 * @type {string}
46 * @private
47 */
48 CloudPrintInterface.URL_ENCODED_CONTENT_TYPE_ =
49 'application/x-www-form-urlencoded';
50
51 /**
52 * Content type header value for a multipart HTTP request.
53 * @type {string}
54 * @private
55 */
56 CloudPrintInterface.MULTIPART_CONTENT_TYPE_ =
57 'multipart/form-data; boundary=----CloudPrintFormBoundaryjc9wuprokl8i';
58
59 /**
60 * Enumeration of JSON response fields from Google Cloud Print API.
61 * @enum {string}
62 * @private
63 */
64 CloudPrintInterface.JsonFields_ = {
65 PRINTER: 'printer'
66 };
67
68 CloudPrintInterface.prototype = {
69 __proto__: cr.EventTarget.prototype,
70
71 /**
72 * Sends a Google Cloud Print search API request.
73 * @param {boolean} isRecent Whether to search for only recently used
74 * printers.
75 */
76 search: function(isRecent) {
77 var params = {};
78 if (isRecent) {
79 params['q'] = '^recent';
80 }
81 this.sendRequest_('GET', 'search', params, null, this.onSearchDone_);
82 },
83
84 /**
85 * Sends a Google Cloud Print submit API request.
86 * @param {string} body Body of the HTTP post request to send.
87 */
88 submit: function(body) {
89 this.sendRequest_('POST', 'submit', null, body, this.onSubmitDone_);
90 },
91
92 /**
93 * Sends a Google Cloud Print printer API request.
94 * @param {string} printerId ID of the printer to lookup.
95 */
96 printer: function(printerId) {
97 var params = {'printerid': printerId};
98 this.sendRequest_('GET', 'printer', params, null, this.onPrinterDone_);
99 },
100
101 /**
102 * Creates an object that represents a Google Cloud Print print ticket.
103 * @param {!print_preview.Destination} destination Destination to print to.
104 * @param {!print_preview.PrintTicketStore} printTicketStore Used to create
105 * the state of the print ticket.
106 * @return {object} Google Cloud Print print ticket.
107 */
108 createPrintTicket: function(destination, printTicketStore) {
109 assert(!destination.isLocal,
110 'Trying to create a Google Cloud Print print ticket for a local ' +
111 'destination');
112 assert(destination.capabilities,
113 'Trying to create a Google Cloud Print print ticket for a ' +
114 'destination with no print capabilities');
115
116 var ticketItems = [];
117
118 if (destination.capabilities.collateCapability) {
119 var collateCap = destination.capabilities.collateCapability;
120 var ticketItem = {
121 'name': collateCap.id,
122 'type': collateCap.type,
123 'options': [{'name': printTicketStore.isCollateEnabled() ?
124 collateCap.collateOption : collateCap.noCollateOption}]
125 };
126 ticketItems.push(ticketItem);
127 }
128
129 if (destination.capabilities.colorCapability) {
130 var colorCap = destination.capabilities.colorCapability;
131 var ticketItem = {
132 'name': colorCap.id,
133 'type': colorCap.type,
134 'options': [{'name': printTicketStore.isColorEnabled() ?
135 colorCap.colorOption : colorCap.bwOption}]
136 };
137 ticketItems.push(ticketItem);
138 }
139
140 if (destination.capabilities.copiesCapability) {
141 var copiesCap = destination.capabilities.copiesCapability;
142 var ticketItem = {
143 'name': copiesCap.id,
144 'type': copiesCap.type,
145 'value': printTicketStore.getCopies()
146 };
147 ticketItems.push(ticketItem);
148 }
149
150 if (destination.capabilities.duplexCapability) {
151 var duplexCap = destination.capabilities.duplexCapability;
152 var ticketItem = {
153 'name': duplexCap.id,
154 'type': duplexCap.type,
155 'options': [{'name': printTicketStore.isDuplexEnabled() ?
156 duplexCap.longEdgeOption : duplexCap.simplexOption}]
157 };
158 ticketItems.push(ticketItem);
159 }
160
161 return {
162 'capabilities': ticketItems
163 };
164 },
165
166 /**
167 * Sends a request to the Google Cloud Print API.
168 * @param {string} method HTTP method of the request.
169 * @param {string} action Google Cloud Print action to perform.
170 * @param {Object} params HTTP parameters to include in the request.
171 * @param {string} body HTTP multi-part encoded body.
172 * @param {function(Object)} successCallback Callback to invoke when request
173 * completes successfully.
174 */
175 sendRequest_: function(method, action, params, body, successCallback) {
176 if (!this.xsrfToken_) {
177 // TODO(rltoscano): Should throw an error if not a read-only action or
178 // issue an xsrf token request.
179 }
180 var url = this.baseURL_ + '/' + action + '?xsrf=' + this.xsrfToken_;
181
182 if (params) {
183 for (var paramName in params) {
184 url += '&' + paramName + '=' + encodeURIComponent(params[paramName]);
185 }
186 }
187
188 var headers = {};
189 headers['X-CloudPrint-Proxy'] = 'ChromePrintPreview';
190 if (method == 'GET') {
191 headers['Content-Type'] = CloudPrintInterface.URL_ENCODED_CONTENT_TYPE_;
192 } else if (method == 'POST') {
193 headers['Content-Type'] = CloudPrintInterface.MULTIPART_CONTENT_TYPE_;
194 }
195
196 var xhr = new XMLHttpRequest();
197 xhr.onreadystatechange = this.onReadyStateChange_.bind(
198 this, xhr, successCallback.bind(this));
199 xhr.open(method, url, true);
200 xhr.withCredentials = true;
201 for (var header in headers) {
202 xhr.setRequestHeader(header, headers[header]);
203 }
204 xhr.send(body);
205 },
206
207 /**
208 * Dispatches an ERROR event with the given error message.
209 * @param {string} message Error message to include in the ERROR event.
210 * @private
211 */
212 dispatchErrorEvent_: function(message) {
213 var errorEvent = new cr.Event(CloudPrintInterface.EventType.ERROR);
214 errorEvent.message = message;
215 this.dispatchEvent(errorEvent);
216 },
217
218 /**
219 * Called when the ready-state of a XML http request changes.
220 * Calls the successCallback with the result or dispatches an ERROR event.
221 * @param {XMLHttpRequest} xhr XML http request that changed.
222 * @param {function(Object)} successCallback Callback to call if the request
223 * was successful.
224 * @private
225 */
226 onReadyStateChange_: function(xhr, successCallback) {
227 if (xhr.readyState == 4) {
228 if (xhr.status == 200) {
229 var result = JSON.parse(xhr.responseText);
230 if (result['success']) {
231 this.xsrfToken_ = result['xsrf_token'];
232 successCallback(result);
233 } else {
234 this.dispatchErrorEvent_(result['message']);
235 }
236 } else {
237 this.dispatchErrorEvent_(xhr.status + '');
238 }
239 }
240 },
241
242 /**
243 * Called when the search request completes successfully.
244 * @param {Object} result JSON response.
245 * @private
246 */
247 onSearchDone_: function(result) {
248 var printerListJson = result['printers'] || [];
249 var printerList = [];
250 for (var printerJson, i = 0; printerJson = printerListJson[i]; i++) {
251 try {
252 printerList.push(
253 cloudprint.CloudDestinationParser.parse(printerJson));
254 } catch (err) {
255 console.error('Unable to parse cloud print destination: ' + err);
256 }
257 }
258 var isRecent = result['request']['params']['q'] == '^recent';
259 var searchDoneEvent =
260 new cr.Event(CloudPrintInterface.EventType.SEARCH_DONE);
261 searchDoneEvent.printers = printerList;
262 searchDoneEvent.isRecent = isRecent;
263 searchDoneEvent.email = result['request']['user'];
264 this.dispatchEvent(searchDoneEvent);
265 },
266
267 /**
268 * Called when the submit request completes successfully.
269 * @param {Object} result JSON response.
270 * @private
271 */
272 onSubmitDone_: function(result) {
273 this.dispatchEvent(
274 new cr.Event(CloudPrintInterface.EventType.SUBMIT_DONE));
275 },
276
277 /**
278 * Called when the printer request completes successfully.
279 * @param {Object} result JSON response.
280 * @private
281 */
282 onPrinterDone_: function(result) {
283 // TODO(rltoscano): Better error handling here.
284 var printerJson = result['printers'][0];
285 var printer;
286 try {
287 printer = cloudprint.CloudDestinationParser.parse(printerJson);
288 } catch (err) {
289 console.error('Failed to parse cloud print destination: ' +
290 JSON.stringify(printerJson));
291 return;
292 }
293 var printerDoneEvent =
294 new cr.Event(CloudPrintInterface.EventType.PRINTER_DONE);
295 printerDoneEvent.printer = printer;
296 this.dispatchEvent(printerDoneEvent);
297 }
298 };
299
300 // Export
301 return {
302 CloudPrintInterface: CloudPrintInterface
303 };
304 });
OLDNEW
« no previous file with comments | « no previous file | chrome/browser/resources/print_preview/color_settings.html » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698