Skip to content

Instantly share code, notes, and snippets.

@stephenplusplus
Created March 3, 2015 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenplusplus/66bfc7ba04ba97a8a15a to your computer and use it in GitHub Desktop.
Save stephenplusplus/66bfc7ba04ba97a8a15a to your computer and use it in GitHub Desktop.
Make public / private
Bucket.prototype.makePublic = function(options, callback) {
var self = this;
if (util.is(options, 'function')) {
callback = options;
options = {};
}
// Allow public to read bucket contents while preserving original permissions.
this.acl.add({
entity: 'allUsers',
role: 'READER'
}, function(err) {
if (err) {
callback(err);
return;
}
if (options.recursive) {
options.public = true;
self._makeAllFilesPublicPrivate(options, callback);
return;
}
callback();
});
};
Bucket.prototype.makePrivate = function(options, callback) {
var self = this;
if (util.is(options, 'function')) {
callback = options;
options = {};
}
var query = {
predefinedAcl: options.strict ? 'private' : 'projectPrivate'
};
// You aren't allowed to set both predefinedAcl & acl properties on a bucket
// so acl must explicitly be nullified.
var metadata = { acl: null };
this.makeReq_('PATCH', '', query, metadata, function(err, resp) {
if (err) {
callback(err);
return;
}
self.metadata = resp;
if (options.recursive) {
options.private = true;
self._makeAllFilesPublicPrivate(options, callback);
return;
}
callback();
});
};
Bucket.prototype._makeAllFilesPublicPrivate = function(options, callback) {
var self = this;
var MAX_PARALLEL_LIMIT = 10;
var errors = [];
var filesProcessed = [];
// Start processing files, iteratively fetching more as necessary.
processFiles({}, function (err) {
if (err || errors.length > 0) {
callback(err || errors, filesProcessed);
return;
}
callback(null, filesProcessed);
});
function processFiles(query, callback) {
self.getFiles(query, function(err, files, nextQuery) {
if (err) {
callback(err);
return;
}
// Iterate through each file and make it public/private.
async.eachLimit(files, MAX_PARALLEL_LIMIT, processFile, function(err) {
if (err) {
callback(err);
return;
}
if (nextQuery) {
processFiles(nextQuery, callback);
return;
}
callback();
});
}
}
function processFile(file, callback) {
if (options.public) {
file.makePublic(processedCallback);
} else if (options.private) {
file.makePrivate({ strict: options.strict }, processedCallback);
}
function processedCallback(err) {
if (err) {
if (!options.force) {
callback(err);
} else {
errors.push(err);
callback();
}
return;
}
filesProcessed.push(file);
callback();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment