summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/print_preview/print_preview_cloud.js
blob: 943f667c60ee2221ea7d2d6c8722e50480836ba3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('cloudprint', function() {

  // The URL to use to access the cloud print servers.
  // Set by a call to setBaseURL.
  var cloudPrintBaseURL = '';

  // Headers to set for most cloud print API calls.
  var xCloudPrintURLHeader = {'Content-Type':
                              'application/x-www-form-urlencoded',
                              'X-CloudPrint-Proxy': 'ChromePrintPreview'};

  // Headers to set when sending multipart data to cloud print APIs.
  // Currently only used when submitting a job.
  var xCloudPrintFormHeader = {'Content-Type':
        'multipart/form-data; boundary=----CloudPrintFormBoundaryjc9wuprokl8i',
        'X-CloudPrint-Proxy': 'ChromePrintPreview'};

  // The last received XSRF token.  This should be sent with each request
  // to prevent XSRF.
  var lastXSRFToken = '';

  /**
   * Sets the base URL to be used for communicating with cloud print
   * servers.
   * @param {string} cloudPrintURL The URL to use.
   */
  function setBaseURL(cloudPrintURL) {
    cloudPrintBaseURL = cloudPrintURL;
  }

  /**
   * Gets the base URL to be used for communicating with cloud print
   * servers.
   * @return {string} The URL.
   */
  function getBaseURL() {
    return cloudPrintBaseURL;
  }

  /**
   * Extracts the XSRF token from each response to be used in the next
   * request.
   * @param {XMLHttpRequest} xhr The object used to make the request.
   * @return {string} The extracted XSRF token.
   */
  function extractXSRFtoken(xhr) {
    if (xhr.status == 200) {
      var result = JSON.parse(xhr.responseText);
      return result['xsrf_token'];
    } else {
      return null;
    }
  }

  /**
   * Makes a request to cloud print servers.
   * @param {string} method The HTTP method to be used.
   * @param {string} action The cloud print API to call.
   * @param {Array} headers Headers to send with the request.
   * @param {string} body Body to be sent with POST requests.
   * @param {function} callback Function to be called to process response.
   * @param {boolean} async True if we want the request made asyncronously.
   */
  function sendCloudPrintRequest(method,
                                 action,
                                 headers,
                                 params,
                                 body,
                                 callback) {
    var xhr = new XMLHttpRequest();
    if (callback != null) {
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          var updatedXSRFToken = extractXSRFtoken(xhr);
          if (updatedXSRFToken != null) {
            lastXSRFToken = updatedXSRFToken;
          }
          callback.call(this, xhr);
        }
      };
    }
    var url = cloudPrintBaseURL + '/' + action;
    if (params == null) {
      params = new Array;
    }
    if (lastXSRFToken.length != 0) {
      params.push("xsrf=" + lastXSRFToken);
    }
    if (params.length != 0) {
      url = url + "?";
      for (param in params) {
        url = url + params[param] + "&";
      }
    }
    xhr.open(method, url, true);
    xhr.withCredentials = true;
    if (headers) {
      for (var header in headers) {
        if (headers.hasOwnProperty(header)) {
          xhr.setRequestHeader(header, headers[header]);
        }
      }
    }
    xhr.send(body);
    return xhr;
  }

  /**
   * Parse the response from the fetchPrinters call.
   * @param {function} callback Function to be called to process response.
   * @param {XMLHttpRequest} xhr The object used to make the request.
   */
  function fetchPrintersResponse(callback, xhr) {
    if (xhr.status == 200) {
      var searchResult = JSON.parse(xhr.responseText);
      if (searchResult['success']) {
        var printerList = searchResult['printers'];
        callback.call(this, printerList);
      } else {
        callback.call(this, null);
      }
    } else {
      callback.call(this, null);
    }
  }

  /**
   * Retrieve the list of printers available via cloud print.
   * @param {function} callback Function to be called to process response.
   */
  function fetchPrinters(callback, all) {
   var query = 'q=^recent';
   if (all) {
     query = '';
   }
   sendCloudPrintRequest('GET',
                         'search',
                         xCloudPrintURLHeader,
                         [query],
                         null,
                         fetchPrintersResponse.bind(this, callback));
  }

  /**
   * Handle the response from printing to cloud print.
   * @param {function} callback Function to be called to process response.
   * @param {XMLHttpRequest} xhr The object used to make the request.
   */
  function printToCloudResponse(callback, xhr) {
    if (xhr.status == 200) {
      var printResult = JSON.parse(xhr.responseText);
      if (printResult['success']) {
        callback.call();
      }
    }
    // TODO(abodenha@chromium.org) Catch and handle failures.
  }

  /**
   * Send the current document to cloud print.
   * @param {string} data The document to be printed.
   * @param {function} callback Function to be called to process response.
   */
  function printToCloud(data, callback) {
    // TODO(abodenha@chromium.org) Make sure we have an XSRF token before
    // sending a submit.  Right now if the user clicks print before we
    // complete any request we wont have an XSRF and the submit will fail.
    sendCloudPrintRequest('POST',
                          'submit',
                          xCloudPrintFormHeader,
                          null,
                          data,
                          printToCloudResponse.bind(this, callback));
  }

  /**
   * Gets the JSON string used to control the behavior of the current
   * print job.
   * @param {Object} printer The printer object to get the ticket for.
   * @return {string} The print ticket or null if not a cloud printer.
   */
  function getPrintTicketJSON(printer) {
    if (isCloudPrint(printer)) {
      return JSON.stringify({'capabilities':
                            [printer.cloudPrintOptions.colorOption]});
    } else {
      return null;
    }
  }

  /**
   * Process the response from cloud print containing the capabilities
   * for the printer.
   * @param {function} callback Function to be called to process response.
   * @param {Object} printer The printer object to get the capabilites for.
   * @param {XMLHttpRequest} xhr The object used to make the request.
   */
  function updatePrinterCapsResponse(callback, printer, xhr) {
    if (xhr.status == 200) {
      var printResult = JSON.parse(xhr.responseText);
      if (printResult['success']) {
        if (!printer.cloudPrintOptions)
          printer.cloudPrintOptions = new Object;
        printer.cloudPrintOptions.capsDownloaded = true;
        printer.cloudPrintOptions.colorOption = null;
        printer.cloudPrintOptions.colorIsDefault = false;
        var detailedCapabilities = printResult.printers[0].capabilities;
        for (var capability in detailedCapabilities) {
          var cap = detailedCapabilities[capability];
          if (cap.name == 'ns1:Colors') {
            printer.cloudPrintOptions.colorOption = new Object;
            printer.cloudPrintOptions.colorOption.name = cap.name;
            printer.cloudPrintOptions.colorOption.type = cap.type;
            for (var option in cap.options) {
              var opt = cap.options[option];
              if (opt.name == "Color") {
                printer.cloudPrintOptions.colorOnOption = opt;
              }
              if (opt.name == "Grey_K") {
                printer.cloudPrintOptions.colorOffOption = opt;
              }
              if (opt.default) {
                printer.cloudPrintOptions.colorOption.options = [opt];
                printer.cloudPrintOptions.colorIsDefault =
                    opt.name == printer.cloudPrintOptions.colorOnOption.name;
              }
            }
          }
        }
        callback.call(this, printer);
      }
    }
  }

  /**
   * Retrieve capabilities for a printer.
   * @param {Object} printer The printer object to get the capabilities for.
   * @param {function} callback Function to be called to process response.
   */
  function updatePrinterCaps(printer, callback) {
    if (isCloudPrint(printer) && !printer.cloudPrintOptions.capsDownloaded) {
      sendCloudPrintRequest('GET',
                            'printer?printerid=' +
                                printer.value +
                                '&output=json',
                            xCloudPrintURLHeader,
                            null,
                            null,
                            updatePrinterCapsResponse.bind(this,
                                                           callback,
                                                           printer));
    } else {
      callback.call(this, printer);
    }
  }

  /**
   * @param {Object} printer The printer object to get the data for.
   * @return {boolean} true if the printer supports color.
   */
  function supportsColor(printer) {
    return isCloudPrint(printer) &&
           printer.cloudPrintOptions.colorOption != null;
  }

  /**
   * @param {Object} printer The printer object to get the data for.
   * @return {boolean} true if the printer defaults to color.
   */
  function colorIsDefault(printer) {
    return isCloudPrint(printer) &&
           printer.cloudPrintOptions.colorIsDefault;
  }

  /**
   * Turn color on or off for the specified printer.
   * @param {Object} printer The printer object to turn color on/off for.
   * @param {boolean} color True to turn color on.
   */
  function setColor(printer, color) {
    if (isCloudPrint(printer) && supportsColor(printer)) {
      if (color) {
        printer.cloudPrintOptions.colorOption.options =
            [printer.cloudPrintOptions.colorOnOption];
      } else {
        printer.cloudPrintOptions.colorOption.options =
            [printer.cloudPrintOptions.colorOffOption];
      }
    }
  }

  /**
   * Creates a cloud print printer and sets it as the default printer.
   * @param {string} printer_name The name of the printer to create.
   * @param {Object} cloud_print_data Data to be stored in cloudPrintOptions.
   * @param {function} add_callback The callback to be called to add the new
   *     printer to the print preview UI.
   * @param {function} update_caps_callback The callback to be called to update
   *     capabilities on the new printer.
   */
  function setDefaultPrinter(printer_name,
                             cloud_print_data,
                             add_callback,
                             update_caps_callback) {
    var printer = add_callback([JSON.parse(cloud_print_data)]);
    if (printer)
      update_caps_callback(printer);
  }

  /**
   * Returns the data necessary to serialize a cloud print printer.
   * @param {Object} printer The printer object to get data for.
   * @return {string} A JSON string that can be used to recreate the
   *     cloud print portion of the printer object, or and empty string if
   *     there is no data to save.
   */
  function getData(printer) {
    if (isCloudPrint(printer)) {
      return JSON.stringify(printer.cloudPrintOptions);
    } else {
      return "";
    }
  }

  /**
   * Test if a printer is a cloud print printer.
   * @param {Object} printer The printer to test.
   * @return {boolean} true iff the printer is a cloud print printer.
   */
  function isCloudPrint(printer) {
    return printer && printer.cloudPrintOptions != null;
  }

  /**
   * Mark a printer as a cloud print printer and record its name and id.
   * @param {Object} printer The printer to mark.
   * @param {string} name The user visible name of the printer.
   * @param {string} id The id of the printer used by cloud print to
   *     identify it.
   */
  function setCloudPrint(printer, name, id) {
    if (!printer.cloudPrintOptions) {
      printer.cloudPrintOptions = new Object;
    }
    printer.cloudPrintOptions.name = name;
    printer.cloudPrintOptions.id = id;
  }

  return {
    colorIsDefault: colorIsDefault,
    fetchPrinters: fetchPrinters,
    getBaseURL: getBaseURL,
    getData: getData,
    getPrintTicketJSON: getPrintTicketJSON,
    isCloudPrint: isCloudPrint,
    printToCloud: printToCloud,
    setBaseURL: setBaseURL,
    setCloudPrint: setCloudPrint,
    setColor: setColor,
    setDefaultPrinter: setDefaultPrinter,
    supportsColor: supportsColor,
    updatePrinterCaps: updatePrinterCaps
  };
});