github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/server/camlistored/ui/server_connection.js (about)

     1  /*
     2  Copyright 2013 Google Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  goog.provide('cam.ServerConnection');
    18  
    19  goog.require('goog.string');
    20  goog.require('goog.net.XhrIo');
    21  goog.require('goog.Uri'); // because goog.net.XhrIo forgot to include it.
    22  goog.require('goog.debug.ErrorHandler'); // because goog.net.Xhrio forgot to include it.
    23  goog.require('goog.uri.utils');
    24  
    25  goog.require('cam.blob');
    26  goog.require('cam.ServerType');
    27  goog.require('cam.WorkerMessageRouter');
    28  
    29  // @fileoverview Connection to the blob server and API for the RPCs it provides. All blob index UI code should use this connection to contact the server.
    30  // @param {cam.ServerType.DiscoveryDocument} config Discovery document for the current server.
    31  // @param {Function=} opt_sendXhr Function for sending XHRs for testing.
    32  // @constructor
    33  cam.ServerConnection = function(config, opt_sendXhr) {
    34  	this.config_ = config;
    35  	this.sendXhr_ = opt_sendXhr || goog.net.XhrIo.send;
    36  	this.worker_ = null;
    37  };
    38  
    39  cam.ServerConnection.prototype.getWorker_ = function() {
    40  	if (!this.worker_) {
    41  		var r = new Date().getTime(); // For cachebusting the worker. Sigh. We need content stamping.
    42  		this.worker_ = new cam.WorkerMessageRouter(new Worker('hash_worker.js?r=' + r));
    43  	}
    44  	return this.worker_;
    45  };
    46  
    47  cam.ServerConnection.prototype.getConfig = function() {
    48  	return this.config_;
    49  };
    50  
    51  // @param {?Function|undefined} fail Fail func to call if exists.
    52  // @return {Function}
    53  cam.ServerConnection.prototype.safeFail_ = function(fail) {
    54  	return fail || function(msg) {
    55  		throw new Error(msg);
    56  	};
    57  };
    58  
    59  // @param {Function} success Success callback.
    60  // @param {?Function} fail Optional fail callback.
    61  // @param {goog.events.Event} e Event that triggered this
    62  cam.ServerConnection.prototype.handleXhrResponseText_ = function(success, fail, e) {
    63  	var xhr = e.target;
    64  	var error = !xhr.isSuccess();
    65  	var result = null;
    66  	if (!error) {
    67  		result = xhr.getResponseText();
    68  		error = !result;
    69  	}
    70  	if (error) {
    71  		if (fail) {
    72  			fail(xhr.getLastError())
    73  		} else {
    74  			// TODO(bslatkin): Add a default failure event handler to this class.
    75  			console.log('Failed XHR (text) in ServerConnection');
    76  		}
    77  		return;
    78  	}
    79  	success(result);
    80  };
    81  
    82  // @param {string} blobref blobref whose contents we want.
    83  // @param {Function} success callback with data.
    84  // @param {?Function} opt_fail optional failure calback
    85  cam.ServerConnection.prototype.getBlobContents = function(blobref, success, opt_fail) {
    86  	var path = goog.uri.utils.appendPath(
    87  		this.config_.blobRoot, 'camli/' + blobref
    88  	);
    89  
    90  	this.sendXhr_(path,
    91  		goog.bind(this.handleXhrResponseText_, this,
    92  			success, this.safeFail_(opt_fail)
    93  		)
    94  	);
    95  };
    96  
    97  // TODO(mpl): set a global timeout ?
    98  // Brett, would it be worth to use the XhrIo send instance method, with listeners,
    99  // instead of the send() utility function ?
   100  // @param {Function} success Success callback.
   101  // @param {?Function} fail Optional fail callback.
   102  // @param {goog.events.Event} e Event that triggered this
   103  cam.ServerConnection.prototype.handleXhrResponseJson_ = function(success, fail, e) {
   104  	var xhr = e.target;
   105  	var error = !xhr.isSuccess();
   106  	var result = null;
   107  
   108  	try {
   109  		result = xhr.getResponseJson();
   110  	} catch(err) {
   111  		result = "Response was not valid JSON: " + xhr.getResponseText();
   112  	}
   113  
   114  	if (error) {
   115  		fail(result.error || result);
   116  	} else {
   117  		success(result);
   118  	}
   119  };
   120  
   121  // @param {Function} success callback with data.
   122  // @param {?Function} opt_fail optional failure calback
   123  cam.ServerConnection.prototype.discoSignRoot = function(success, opt_fail) {
   124  	var path = goog.uri.utils.appendPath(this.config_.jsonSignRoot, '/camli/sig/discovery');
   125  	this.sendXhr_(path, goog.bind(this.handleXhrResponseJson_, this, success, this.safeFail_(opt_fail)));
   126  };
   127  
   128  // @param {function(cam.ServerType.StatusResponse)} success.
   129  // @param {?Function} opt_fail optional failure calback
   130  cam.ServerConnection.prototype.serverStatus = function(success, opt_fail) {
   131  	var path = goog.uri.utils.appendPath(this.config_.statusRoot, 'status.json');
   132  
   133  	this.sendXhr_(path,
   134  		goog.bind(this.handleXhrResponseJson_, this, success, function(msg) {
   135  			console.log("serverStatus error: " + msg);
   136  		}));
   137  };
   138  
   139  // @param {Function} success Success callback.
   140  // @param {?Function} opt_fail Optional fail callback.
   141  // @param {goog.events.Event} e Event that triggered this
   142  cam.ServerConnection.prototype.genericHandleSearch_ = function(success, opt_fail, e) {
   143  	this.handleXhrResponseJson_(success, this.safeFail_(opt_fail), e);
   144  };
   145  
   146  // @param {string} blobref root of the tree
   147  // @param {Function} success callback with data.
   148  // @param {?Function} opt_fail optional failure calback
   149  cam.ServerConnection.prototype.getFileTree = function(blobref, success, opt_fail) {
   150  
   151  	// TODO(mpl): do it relatively to a discovered root?
   152  	var path = "./tree/" + blobref;
   153  	this.sendXhr_(path, goog.bind(this.genericHandleSearch_, this, success, this.safeFail_(opt_fail)));
   154  };
   155  
   156  
   157  // @param {string} blobref Permanode blobref.
   158  // @param {number} thumbnailSize
   159  // @param {function(cam.ServerType.DescribeResponse)} success.
   160  // @param {Function=} opt_fail Optional fail callback.
   161  cam.ServerConnection.prototype.describeWithThumbnails = function(blobref, thumbnailSize, success, opt_fail) {
   162  	var path = goog.uri.utils.appendPath(
   163  		this.config_.searchRoot, 'camli/search/describe?blobref=' + blobref);
   164  
   165  	// TODO(mpl): should we URI encode the value? doc does not say...
   166  	path = goog.uri.utils.appendParam(path, 'thumbnails', thumbnailSize);
   167  	this.sendXhr_(path, goog.bind(this.genericHandleSearch_, this, success, this.safeFail_(opt_fail)));
   168  };
   169  
   170  // @param {string} signer permanode must belong to signer.
   171  // @param {string} attr searched attribute.
   172  // @param {string} value value of the searched attribute.
   173  // @param {Function} success.
   174  // @param {Function=} opt_fail Optional fail callback.
   175  cam.ServerConnection.prototype.permanodeOfSignerAttrValue = function(signer, attr, value, success, opt_fail) {
   176  	var path = goog.uri.utils.appendPath(this.config_.searchRoot, 'camli/search/signerattrvalue');
   177  	path = goog.uri.utils.appendParams(path,
   178  		'signer', signer, 'attr', attr, 'value', value
   179  	);
   180  
   181  	this.sendXhr_(
   182  		path,
   183  		goog.bind(this.genericHandleSearch_, this,
   184  			success, this.safeFail_(opt_fail)
   185  		)
   186  	);
   187  };
   188  
   189  // @param {string|object} query If string, will be sent as 'expression', otherwise will be sent as 'constraint'.
   190  // @param {?object} opt_describe The describe property to send for the query
   191  cam.ServerConnection.prototype.buildQuery = function(callerQuery, opt_describe, opt_limit, opt_continuationToken) {
   192  	var query = {
   193  		sort: "-mod"
   194  	};
   195  
   196  	if (goog.isString(callerQuery)) {
   197  		query.expression = callerQuery;
   198  	} else {
   199  		query.constraint = callerQuery;
   200  	}
   201  
   202  	if (opt_describe) {
   203  		query.describe = opt_describe;
   204  	}
   205  	if (opt_limit) {
   206  		query.limit = opt_limit;
   207  	}
   208  	if (opt_continuationToken) {
   209  		query.continue = opt_continuationToken;
   210  	}
   211  
   212  	return query;
   213  }
   214  
   215  // @param {string|object} query If string, will be sent as 'expression', otherwise will be sent as 'constraint'.
   216  // @param {?object} opt_describe The describe property to send for the query
   217  cam.ServerConnection.prototype.search = function(query, opt_describe, opt_limit, opt_continuationToken, callback) {
   218  	var path = goog.uri.utils.appendPath(this.config_.searchRoot, 'camli/search/query');
   219  	this.sendXhr_(path,
   220  		goog.bind(this.genericHandleSearch_, this, callback, this.safeFail_()),
   221  		"POST", JSON.stringify(this.buildQuery(query, opt_describe, opt_limit, opt_continuationToken)));
   222  };
   223  
   224  // Where is the target accessed via? (paths it's at)
   225  // @param {string} signer owner of permanode.
   226  // @param {string} target blobref of permanode we want to find paths to
   227  // @param {Function} success.
   228  // @param {Function=} opt_fail Optional fail callback.
   229  cam.ServerConnection.prototype.pathsOfSignerTarget = function(signer, target, success, opt_fail) {
   230  	var path = goog.uri.utils.appendPath(
   231  		this.config_.searchRoot, 'camli/search/signerpaths'
   232  	);
   233  	path = goog.uri.utils.appendParams(path, 'signer', signer, 'target', target);
   234  	this.sendXhr_(path,
   235  		goog.bind(this.genericHandleSearch_, this, success, this.safeFail_(opt_fail)));
   236  };
   237  
   238  // @param {string} permanode Permanode blobref.
   239  // @param {Function} success.
   240  // @param {Function=} opt_fail Optional fail callback.
   241  cam.ServerConnection.prototype.permanodeClaims = function(permanode, success, opt_fail) {
   242  	var path = goog.uri.utils.appendPath(
   243  		this.config_.searchRoot, 'camli/search/claims?permanode=' + permanode
   244  	);
   245  
   246  	this.sendXhr_(
   247  		path,
   248  		goog.bind(this.genericHandleSearch_, this,
   249  			success, this.safeFail_(opt_fail)
   250  		)
   251  	);
   252  };
   253  
   254  // @param {Object} clearObj Unsigned object.
   255  // @param {Function} success Success callback.
   256  // @param {?Function} opt_fail Optional fail callback.
   257  cam.ServerConnection.prototype.sign_ = function(clearObj, success, opt_fail) {
   258  	var sigConf = this.config_.signing;
   259  	if (!sigConf || !sigConf.publicKeyBlobRef) {
   260  		this.safeFail_(opt_fail)("Missing Camli.config.signing.publicKeyBlobRef");
   261  		return;
   262  	}
   263  
   264  		clearObj.camliSigner = sigConf.publicKeyBlobRef;
   265  		var camVersion = clearObj.camliVersion;
   266  		if (camVersion) {
   267  			 delete clearObj.camliVersion;
   268  		}
   269  		var clearText = JSON.stringify(clearObj, null, "	");
   270  		if (camVersion) {
   271  			 clearText = "{\"camliVersion\":" + camVersion + ",\n" + clearText.substr("{\n".length);
   272  		}
   273  
   274  	this.sendXhr_(
   275  		sigConf.signHandler,
   276  		goog.bind(this.handlePost_, this,
   277  			success, this.safeFail_(opt_fail)),
   278  		"POST",
   279  		"json=" + encodeURIComponent(clearText),
   280  		{"Content-Type": "application/x-www-form-urlencoded"}
   281  	);
   282  };
   283  
   284  // @param {Object} signed Signed JSON blob (string) to verify.
   285  // @param {Function} success Success callback.
   286  // @param {?Function} opt_fail Optional fail callback.
   287  cam.ServerConnection.prototype.verify_ = function(signed, success, opt_fail) {
   288  	var sigConf = this.config_.signing;
   289  	if (!sigConf || !sigConf.publicKeyBlobRef) {
   290  		this.safeFail_(opt_fail)("Missing Camli.config.signing.publicKeyBlobRef");
   291  		return;
   292  	}
   293  	this.sendXhr_(
   294  		sigConf.verifyHandler,
   295  		goog.bind(this.handlePost_, this,
   296  			success, this.safeFail_(opt_fail)),
   297  		"POST",
   298  		"sjson=" + encodeURIComponent(signed),
   299  		{"Content-Type": "application/x-www-form-urlencoded"}
   300  	);
   301  };
   302  
   303  // @param {Function} success Success callback.
   304  // @param {?Function} opt_fail Optional fail callback.
   305  // @param {goog.events.Event} e Event that triggered this
   306  cam.ServerConnection.prototype.handlePost_ = function(success, opt_fail, e) {
   307  	this.handleXhrResponseText_(success, opt_fail, e);
   308  };
   309  
   310  
   311  // @param {string} s String to upload.
   312  // @param {Function} success Success callback.
   313  // @param {?Function} opt_fail Optional fail callback.
   314  cam.ServerConnection.prototype.uploadString_ = function(s, success, opt_fail) {
   315  	var blobref = cam.blob.refFromString(s);
   316  	var parts = [s];
   317  	var bb = new Blob(parts);
   318  	var fd = new FormData();
   319  	fd.append(blobref, bb);
   320  
   321  	// TODO: hack, hard-coding the upload URL here.
   322  	// Change the spec now that App Engine permits 32 MB requests
   323  	// and permit a PUT request on the sha1?	Or at least let us
   324  	// specify the well-known upload URL?	In cases like this, uploading
   325  	// a new permanode, it's silly to even stat.
   326  	this.sendXhr_(
   327  		this.config_.blobRoot + "camli/upload",
   328  		goog.bind(this.handleUploadString_, this,
   329  			blobref,
   330  			success,
   331  			this.safeFail_(opt_fail)
   332  		),
   333  		"POST",
   334  		fd
   335  	);
   336  };
   337  
   338  // @param {string} blobref Uploaded blobRef.
   339  // @param {Function} success Success callback.
   340  // @param {?Function} opt_fail Optional fail callback.
   341  // @param {goog.events.Event} e Event that triggered this
   342  cam.ServerConnection.prototype.handleUploadString_ = function(blobref, success, opt_fail, e) {
   343  	this.handlePost_(
   344  		function(resj) {
   345  			if (!resj) {
   346  				alert("upload permanode fail; no response");
   347  				return;
   348  			}
   349  			var resObj = JSON.parse(resj);
   350  			if (!resObj.received || !resObj.received[0] || !resObj.received[0].blobRef) {
   351  				alert("upload permanode fail, expected blobRef not in response");
   352  				return;
   353  			}
   354  			if (success) {
   355  				success(blobref);
   356  			}
   357  		},
   358  		this.safeFail_(opt_fail),
   359  		e
   360  	)
   361  };
   362  
   363  // @param {Function} success Success callback.
   364  // @param {?Function} opt_fail Optional fail callback.
   365  cam.ServerConnection.prototype.createPermanode = function(success, opt_fail) {
   366  	var json = {
   367  		"camliVersion": 1,
   368  		"camliType": "permanode",
   369  		"random": ""+Math.random()
   370  	};
   371  	this.sign_(json,
   372  		goog.bind(this.handleSignPermanode_, this, success, this.safeFail_(opt_fail)),
   373  		function(msg) {
   374  			this.safeFail_(opt_fail)("sign permanode fail: " + msg);
   375  		}
   376  	);
   377  };
   378  
   379  // @param {Function} success Success callback.
   380  // @param {?Function} opt_fail Optional fail callback.
   381  // @param {string} signed Signed string to upload
   382  cam.ServerConnection.prototype.handleSignPermanode_ = function(success, opt_fail, signed) {
   383  	this.uploadString_(
   384  		signed,
   385  		success,
   386  		function(msg) {
   387  			this.safeFail_(opt_fail)("upload permanode fail: " + msg);
   388  		}
   389  	)
   390  };
   391  
   392  
   393  // @param {string} permanode Permanode to change.
   394  // @param {string} claimType What kind of claim: "add-attribute", "set-attribute"...
   395  // @param {string} attribute What attribute the claim applies to.
   396  // @param {string} value Attribute value.
   397  // @param {Function} success Success callback.
   398  // @param {?Function} opt_fail Optional fail callback.
   399  cam.ServerConnection.prototype.changeAttribute_ = function(permanode, claimType, attribute, value, success, opt_fail) {
   400  	var json = {
   401  		"camliVersion": 1,
   402  		"camliType": "claim",
   403  		"permaNode": permanode,
   404  		"claimType": claimType,
   405  		// TODO(mpl): to (im)port.
   406  		"claimDate": dateToRfc3339String(new Date()),
   407  		"attribute": attribute,
   408  		"value": value
   409  	};
   410  	this.sign_(json,
   411  		goog.bind(this.handleSignClaim_, this, success, this.safeFail_(opt_fail)),
   412  		function(msg) {
   413  			this.safeFail_(opt_fail)("sign " + claimType + " fail: " + msg);
   414  		}
   415  	);
   416  };
   417  
   418  // @param {Function} success Success callback.
   419  // @param {?Function} opt_fail Optional fail callback.
   420  // @param {string} signed Signed string to upload
   421  cam.ServerConnection.prototype.handleSignClaim_ = function(success, opt_fail, signed) {
   422  	this.uploadString_(
   423  		signed,
   424  		success,
   425  		function(msg) {
   426  			this.safeFail_(opt_fail)("upload " + claimType + " fail: " + msg);
   427  		}
   428  	)
   429  };
   430  
   431  // @param {string} permanode Permanode blobref.
   432  // @param {string} attribute Name of the attribute to set.
   433  // @param {string} value Value to set the attribute to.
   434  // @param {function(string)} success Success callback, called with blobref of uploaded file.
   435  // @param {?Function} opt_fail Optional fail callback.
   436  cam.ServerConnection.prototype.newSetAttributeClaim = function(permanode, attribute, value, success, opt_fail) {
   437  	this.changeAttribute_(permanode, "set-attribute", attribute, value,
   438  		success, this.safeFail_(opt_fail)
   439  	);
   440  };
   441  
   442  
   443  // @param {string} permanode Permanode blobref.
   444  // @param {string} attribute Name of the attribute to add.
   445  // @param {string} value Value of the added attribute.
   446  // @param {function(string)} success Success callback, called with blobref of uploaded file.
   447  // @param {?Function} opt_fail Optional fail callback.
   448  cam.ServerConnection.prototype.newAddAttributeClaim = function(permanode, attribute, value, success, opt_fail) {
   449  	this.changeAttribute_(permanode, "add-attribute", attribute, value,
   450  		success, this.safeFail_(opt_fail)
   451  	);
   452  };
   453  
   454  // @param {string} permanode Permanode blobref.
   455  // @param {string} attribute Name of the attribute to delete.
   456  // @param {string} value Value of the attribute to delete.
   457  // @param {function(string)} success Success callback, called with blobref of uploaded file.
   458  // @param {?Function} opt_fail Optional fail callback.
   459  cam.ServerConnection.prototype.newDelAttributeClaim = function(permanode, attribute, value, success, opt_fail) {
   460  	this.changeAttribute_(permanode, "del-attribute", attribute, value,
   461  		success, this.safeFail_(opt_fail)
   462  	);
   463  };
   464  
   465  
   466  // @param {File} file File to be uploaded.
   467  // @param {function(string)} success Success callback, called with blobref of
   468  // uploaded file.
   469  // @param {?Function} opt_fail Optional fail callback.
   470  // @param {?Function} opt_onContentsRef Optional callback to set contents during upload.
   471  cam.ServerConnection.prototype.uploadFile = function(file, success, opt_fail, opt_onContentsRef) {
   472  	this.getWorker_().sendMessage('ref', file, function(ref) {
   473  		if (opt_onContentsRef) {
   474  			opt_onContentsRef(ref);
   475  		}
   476  		this.camliUploadFileHelper_(file, ref, success, this.safeFail_(opt_fail));
   477  	}.bind(this));
   478  };
   479  
   480  // camliUploadFileHelper uploads the provided file with contents blobref contentsBlobRef
   481  // and returns a blobref of a file blob.	It does not create any permanodes.
   482  // Most callers will use camliUploadFile instead of this helper.
   483  //
   484  // camliUploadFileHelper only uploads chunks of the file if they don't already exist
   485  // on the server. It starts by assuming the file might already exist on the server
   486  // and, if so, uses an existing (but re-verified) file schema ref instead.
   487  // @param {File} file File to be uploaded.
   488  // @param {string} contentsBlobRef Blob ref of file as sha1'd locally.
   489  // @param {function(string)} success function(fileBlobRef) of the
   490  // server-validated or just-uploaded file schema blob.
   491  // @param {?Function} opt_fail Optional fail callback.
   492  cam.ServerConnection.prototype.camliUploadFileHelper_ = function(file, contentsBlobRef, success, opt_fail) {
   493  	if (!this.config_.uploadHelper) {
   494  		this.safeFail_(opt_fail)("no uploadHelper available");
   495  		return;
   496  	}
   497  
   498  	var doUpload = goog.bind(function() {
   499  		var fd = new FormData();
   500  		fd.append("TODO-some-uploadHelper-form-name", file);
   501  		this.sendXhr_(
   502  			this.config_.uploadHelper,
   503  			goog.bind(this.handleUpload_, this,
   504  				file, contentsBlobRef, success, this.safeFail_(opt_fail)
   505  			),
   506  			"POST",
   507  			fd
   508  		);
   509  	}, this);
   510  
   511  	this.findExistingFileSchemas_(
   512  		contentsBlobRef,
   513  		goog.bind(this.dupCheck_, this,
   514  			doUpload, contentsBlobRef, success
   515  		),
   516  		this.safeFail_(opt_fail)
   517  	)
   518  }
   519  
   520  // @param {File} file File to be uploaded.
   521  // @param {string} contentsBlobRef Blob ref of file as sha1'd locally.
   522  // @param {Function} success Success callback.
   523  // @param {?Function} opt_fail Optional fail callback.
   524  // @param {goog.events.Event} e Event that triggered this
   525  cam.ServerConnection.prototype.handleUpload_ = function(file, contentsBlobRef, success, opt_fail, e) {
   526  	this.handlePost_(
   527  		goog.bind(function(res) {
   528  			var resObj = JSON.parse(res);
   529  			if (resObj.got && resObj.got.length == 1 && resObj.got[0].fileref) {
   530  				var fileblob = resObj.got[0].fileref;
   531  				console.log("uploaded " + contentsBlobRef + " => file blob " + fileblob);
   532  				success(fileblob);
   533  			} else {
   534  				this.safeFail_(opt_fail)("failed to upload " + file.name + ": " + contentsBlobRef + ": " + JSON.stringify(res, null, 2))
   535  			}
   536  		}, this),
   537  		this.safeFail_(opt_fail),
   538  		e
   539  	)
   540  };
   541  
   542  
   543  // @param {string} wholeDigestRef file digest.
   544  // @param {Function} success callback with data.
   545  // @param {?Function} opt_fail optional failure calback
   546  cam.ServerConnection.prototype.findExistingFileSchemas_ = function(wholeDigestRef, success, opt_fail) {
   547  	var path = goog.uri.utils.appendPath(this.config_.searchRoot, 'camli/search/files');
   548  	path = goog.uri.utils.appendParam(path, 'wholedigest', wholeDigestRef);
   549  
   550  	this.sendXhr_(
   551  		path,
   552  		goog.bind(this.genericHandleSearch_, this,
   553  			success, this.safeFail_(opt_fail)
   554  		)
   555  	);
   556  };
   557  
   558  
   559  // @param {Function} doUpload fun that takes care of uploading.
   560  // @param {string} contentsBlobRef Blob ref of file as sha1'd locally.
   561  // @param {Function} success Success callback.
   562  // @param {Object} res result from the wholedigest search.
   563  cam.ServerConnection.prototype.dupCheck_ = function(doUpload, contentsBlobRef, success, res) {
   564  	var remain = res.files;
   565  	var checkNext = goog.bind(function(files) {
   566  		if (files.length == 0) {
   567  			doUpload();
   568  			return;
   569  		}
   570  		// TODO: verify filename and other file metadata in the
   571  		// file json schema match too, not just the contents
   572  		var checkFile = files[0];
   573  		console.log("integrity checking the reported dup " + checkFile);
   574  
   575  		// TODO(mpl): see about passing directly a ref of files maybe instead of a copy?
   576  		// just being careful for now.
   577  		this.sendXhr_(
   578  			this.config_.downloadHelper + checkFile + "/?verifycontents=" + contentsBlobRef,
   579  			goog.bind(this.handleVerifycontents_, this,
   580  				contentsBlobRef, files.slice(), checkNext, success),
   581  			"HEAD"
   582  		);
   583  	}, this);
   584  	checkNext(remain);
   585  }
   586  
   587  // @param {string} contentsBlobRef Blob ref of file as sha1'd locally.
   588  // @param {Array.<string>} files files to check.
   589  // @param {Function} checkNext fun, recursive call.
   590  // @param {Function} success Success callback.
   591  // @param {goog.events.Event} e Event that triggered this
   592  cam.ServerConnection.prototype.handleVerifycontents_ = function(contentsBlobRef, files, checkNext, success, e) {
   593  	var xhr = e.target;
   594  	var error = !(xhr.isComplete() && xhr.getStatus() == 200);
   595  	var checkFile = files.shift();
   596  
   597  	if (error) {
   598  		console.log("integrity check failed on " + checkFile);
   599  		checkNext(files);
   600  		return;
   601  	}
   602  	if (xhr.getResponseHeader("X-Camli-Contents") == contentsBlobRef) {
   603  		console.log("integrity check passed on " + checkFile + "; using it.");
   604  		success(checkFile);
   605  	} else {
   606  		checkNext(files);
   607  	}
   608  };
   609  
   610  // Format |dateVal| as specified by RFC 3339.
   611  function dateToRfc3339String(dateVal) {
   612  	// Return a string containing |num| zero-padded to |length| digits.
   613  	var pad = function(num, length) {
   614  		var numStr = "" + num;
   615  		while (numStr.length < length) {
   616  			numStr = "0" + numStr;
   617  		}
   618  		return numStr;
   619  	};
   620  
   621  	return goog.string.subs("%s-%s-%sT%s:%s:%sZ",
   622  		dateVal.getUTCFullYear(), pad(dateVal.getUTCMonth() + 1, 2), pad(dateVal.getUTCDate(), 2),
   623  		pad(dateVal.getUTCHours(), 2), pad(dateVal.getUTCMinutes(), 2), pad(dateVal.getUTCSeconds(), 2));
   624  };