Skip to content

Instantly share code, notes, and snippets.

@yssk22
Created October 12, 2010 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yssk22/622432 to your computer and use it in GitHub Desktop.
Save yssk22/622432 to your computer and use it in GitHub Desktop.
function copy(fileUrl, docUrl, event, trace){
if( !trace ){
trace = 0;
}
if( !trace ){
event = new EventEmitter();
}
if( trace == MAX_TRACE ){
logger.error('Max trace exceeded. ({fileUrl} -> {docUrl})'.format({fileUrl: fileUrl, docUrl: docUrl}));
return undefined;
}
logger.info('copy {fileUrl} to {docUrl}'.format({fileUrl: fileUrl, docUrl: docUrl}));
var src = httpUtil.parseUrl(fileUrl);
var dst = httpUtil.parseUrl(docUrl);
var srcReq = src.client.request('GET', src.path,
src.headers);
srcReq.on('response', function(srcRes){
if( srcRes.statusCode >= 300 && srcRes.statusCode < 400 &&
srcRes.headers.location ){
logger.info('changed url {fileUrl} to {newUrl}'.format({fileUrl: fileUrl, newUrl: srcRes.headers.location}));
copy(srcRes.headers.location, docUrl, event, trace + 1);
return;
}
logger.debug(sys.inspect(srcRes.headers));
dst.headers['content-type'] = srcRes.headers['content-type'];
dst.headers['content-length'] = srcRes.headers['content-length'];
var dstReq = dst.client.request('PUT', dst.path, dst.headers);
dstReq.on('response', function(dstRes){
logger.debug('CouchDB repsonse: ' + dstRes.statusCode);
var buff = '';
dstRes.on('data', function(chunk){
buff += chunk;
});
dstRes.on('end', function(){
logger.info('ends with ' + buff);
var obj;
try{
obj = JSON.parse(buff);
}catch(e){
logger.error('CouchDB returns invalid JSON: ' + buff);
}
event.emit('end', obj);
});
});
var buff = '';
var progress = 0;
var size = 0;
var totalSize = srcRes.headers['content-length'];
srcRes.on('data', function(chunk){
if(srcRes.statusCode == 200 ){
dstReq.write(chunk);
size = size + chunk.length;
event.emit('progress', size, totalSize);
}else{
buff += chunk;
}
});
srcRes.on('end', function(){
dstReq.end();
if(srcRes.statusCode != 200 ){
logger.error('postAttachmentFailed with {status} ({url})'.format({status: srcRes.statusCode, url: fileUrl}));
logger.error("{data} ({url})".format({url:fileUrl, data:buff}));
}
});
});
srcReq.end();
return event;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment