DynamoTable.get = function (key) { var promise = vow.promise(); var options = { TableName: this.name }; try { options.Key = this.createKey(key); } catch (err) { promise.reject(err); } var self = this; this.db.getItem(options, function (err, res) { if (err) { // console.error(err); promise.reject(new Error(err.message)); } else { if (res && 'Item' in res) { promise.fulfill(parse(res.Item, self.schema)); } else { promise.fulfill(); } } }); return promise; }
.each (function (item) { var venueId = item.venue.id, promise = Promises.promise (); api.list ('venues/' + venueId + '/tips') .each (function (item) { item.venue = { id: venueId }; return Promises.when ( normalize (item, 'tip') ) .then (function (entry) { if ((task ['previous-poll'] || task ['scrape-start']) && entry.created_at) { if ((task ['previous-poll'] || task ['scrape-start']) > entry.created_at * 1000) { return false; } } return emit (entry); }); }) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)); return promise; })
function getUserInfo (vk, user_id, callback) { var promise = Promises.promise(); var params = { fields: 'nickname,screen_name,sex,bdate,city,country,timezone,photo_50,photo_100,photo_200_orig,has_mobile,contacts,education,online,counters,relation,last_seen,status,can_write_private_message,can_see_all_posts,can_post,universities,schools' }; if (user_id) { params.user_ids = user_id; } vk ('users.get', params, function (error, result) { var response; if(error) { response = callback(error); } else { response = callback(null, result [0]); } promise.fulfill (response); }); return promise; };
.use ('urn:fos:sync:feature/6ffa51e02f7211e399f5c5b42f4313e0', function fetchVenueTips (task) { var token = task._prefetch.token, emit = this.emitter (task), api = getAPI (token), venueId = task.url.match (/\/([a-z0-9]+)\/?$/) [1], promise = Promises.promise (); api.list ('venues/' + venueId + '/tips') .each (function (item) { item.venue = { id: venueId }; return Promises.when ( normalize (item, 'tip') ) .then (function (entry) { if ((task ['previous-poll'] || task ['scrape-start']) && entry.created_at) { if ((task ['previous-poll'] || task ['scrape-start']) > entry.created_at * 1000) { return false; } } return emit (entry); }); }) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)); return promise; })
.then(function(res){ // save res to file if (typeof output === 'string') { return VOWFS.write(output, res); } // write res to writable stream of opened file var defer = VOW.promise(); // output res to stdout if (output === process.stdout) { output.write(res); return defer.fulfill(); } output.on('error', function(err) { defer.reject(err); }); output.once('close', function() { defer.fulfill(); }); output.once('end', function() { defer.fulfill(); }); output.write(res); output.end(); return defer; });
.use ('urn:fos:sync:feature/1f1d48152476612c3d5931cb9239fc2a', function searchAllNews (task) { var token = task._prefetch.token, emit = this.emitter (task), vk = getVKontakte (token), promise = Promises.promise(), query = Url.parse (task.url, true).query, keywords = query.q || query ['c[q]']; return iterate (vk, 'newsfeed.search', {q: keywords, start_time: (task ['previous-poll'] || task ['scrape-start'])/1000}, function (row) { return (row.date * 1000) >= (task ['previous-poll'] || task ['scrape-start']); }, function (error, row) { if (error) { return promise.reject (error); } if (typeof row == 'object') { return normalize (row, null, vk) .then(function (entry) { Promises.when (emit (entry)) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)) .done (); }) /*.fail (function (error) { return promise.reject (error); })*/; //return getComments(vk, emit, row); } }); })
.builder(function (sourceFiles) { var _this = this, promise = Vow.promise(); var css = sourceFiles.map(function(file) { var path = file.fullname; if (file.name.indexOf('.styl') !== -1) { return '/* ' + path + ':begin */\n' + '@import "' + path + '";\n' + '/* ' + path + ':end */\n'; } else { return '@import "' + path + '";'; } }).join('\n'); var targetName = _this._target; var renderer = stylus(css) .define('url', function(url){ return new stylus.nodes.Literal('url(' + _this._resolveCssUrl(url.val, url.filename) + ')'); }) .set('filename', _this.node.resolvePath(targetName)); _this._configureRenderer(renderer) .render(function(err, css) { if (err) promise.reject(err); promise.fulfill(css); }); return promise.then(function(css) { return _this._processIncludes(css, _this.node.resolvePath(targetName)); }); })
function urlResolve (vk, url) { if (url.match (/vk.com\/id(\d+)$/) || url.match (/vk.com\/club(\d+)$/) || url.match (/vk.com\/wall/) || url.match (/vk.com\/topic/) || url.match (/vk.com\/board/)) { return Promises.fulfill (url); } else if (tmp = url.match(/vk.com\/(public|event)(\d+)$/)) { url = 'http://vk.com/club' + tmp [2]; return Promises.fulfill (url); } else if (tmp = url.match(/vk.com\/(.+)/)) { var promise = Promises.promise (); getGroupInfo (vk, tmp [1], function (error, result) { if (error) { return getUserInfo (vk, tmp [1], function (error, result) { if (error) { promise.reject ('Url resolving error'); } else { promise.fulfill ('http://vk.com/id' + tmp [1]); } }); } else { promise.fulfill ('http://vk.com/club' + tmp [1]); } }); return promise; } };
function(path) { var promise = Vow.promise(); fs.stat(path, function(err) { promise.fulfill(!err); }); return promise; },
.then (function (client) { console.log ('connected with', bridge.host); var promise = Promises.promise (); self.onCancel (task._id, function () { promise.fulfill (); client.disconnect (); }); console.log ('trying to join', '#' + channel); client.on ('join', function handleJoin () { console.log ('joined ', '#' + channel); client.on ('message', function handleMessage (from, to, message, info) { emit ( normalize (info, bridge.host) ); }); }); client.on ('error', function (error) { promise.reject (_.last (error.args)); client.disconnect (); }); client.join ('#' + channel + ' ' + token.password); return promise; });
watchDB: function () { var promise = Promises.promise (), database = this.database, self = this, cache = this.cache; database.info (function (error, result) { if (error) { promise.reject (error); } else { var feed = database.changes ({since: result.update_seq, include_docs: true}); feed.on ('change', function (event) { if (!self.pulling && !self.pushing && self.cache [event.id]) { cache [event.id] = event.seq; var promise = self.pullDoc (event.doc); if (promise) { promise .fail (console.error) .done (); } } }); promise.fulfill (); } }); return promise; },
exports.start = function () { var Express = require('express'); var Db = require('./db'); var Routes = require('./routes/routes'); var app = Express(); app.configure(function () { app.use(Express.compress()); app.use(Express.cookieParser()); app.use(Express.session({ secret:'iuBviX21'})); }); var promise = Vow.promise(); var errorHandler = function (err) { promise.reject(err); }; Db.init(Db.DEVELOP) .then(function () { Routes.init(app); app.listen(8080); promise.fulfill(); }, errorHandler); return promise; };
it('should not be callable after intercept called', function () { var debugCtx = new DebugCtx(TestTools.getCollection()); debugCtx.intercept('count', [], Vow.promise()); assert.throws(function () { debugCtx.intercept('find', {id: 123}, Vow.promise()); }); });
module.exports = function (zipUrl, path) { var promise = vow.promise(); var unzip = new Extract({ path: path }); unzip.on('close', function () { promise.fulfill(path); }); unzip.on('error', promise.reject.bind(promise)); notifyNextTick(promise, 'Downloading zip ' + zipUrl); var zip = request(zipUrl); var length = 0; zip.on('data', function (chunk) { length += chunk.length; promise.notify('Downloading zip ' + (length / 1024 / 1024).toFixed(2) + 'Mb'); }); zip.on('end', function () { promise.notify('Extracting zip'); }); zip.pipe(unzip); return promise; };
start: function(enbTask, config) { var promise = Vow.promise(); var _this = this; this._init(enbTask).then(function() { enbTask.log('Start watch ' + _this._levels.join(', ')); var watcher = chokidar.watch(_this._levels, {ignored: /^\./, persistent: true}); watcher .on('add', function(path) { _this._handleChanges(path); }) .on('change', function(path) { _this._handleChanges(path); }) .on('unlink', function(path) { _this._handleChanges(path); }) .on('error', function(error) { _this._logger.logErrorAction('Error happened', error); }); }); return promise; }
.use ('urn:fos:sync:feature/28c886a4cc8e209253a03ee4f682728e', function (task) { var token = task._prefetch.token, emit = this.emitter (task), twitter = getTwitter (token), promise = Promises.promise (); twitter.getDirectMessages ({}, function (data) { if (data instanceof Error) { promise.reject (data.message); } else { Promises.all ( _.map (data, function (data) { return Promises.when ( emit (normalize (data)) ); }) ) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)) .done (); } }); return promise; })
.use ('urn:fos:sync:feature/28c886a4cc8e209253a03ee4f684a19d', function resolveToken (task) { var token = task._prefetch.token, emit = this.emitter (task), twitter = getTwitter (token), promise = Promises.promise (); twitter.verifyCredentials (function (profile) { if (!profile) { promise.reject ('could not verify token credentials'); return null; } var entry = normalize (profile); if (entry) { entry.tokens = [token._id]; } Promises.when (emit (entry)) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)) .done (); }); return promise; })
build: function (targets) { targets = this._fixPath(targets); var promise = Vow.promise(); var startTime = new Date(); var _this = this; var targetTask; try { this._logger.log('build started'); if (targets.length && this._projectConfig.getTaskConfig(targets[0])) { targetTask = this.buildTask(targets[0], targets.slice(1)); } else { targetTask = this.buildTargets(targets); } targetTask.then(function () { _this._logger.log('build finished - ' + colors.red((new Date() - startTime) + 'ms')); Object.keys(_this._nodes).forEach(function (nodeName) { _this._nodes[nodeName].getLogger().setEnabled(false); }); promise.fulfill(); }, function (err) { _this._logger.log('build failed'); promise.reject(err); }); } catch (err) { promise.reject(err); } return promise; },
isFileExists: function(filePath) { var promise = vow.promise(); fs.exists(filePath, function(exists) { promise[exists ? 'fulfill' : 'reject'](); }); return promise; },
map: function(modelName, source) { var _this = this, promise = Vow.isPromise(source) ? source : Vow.promise(source), schema = require('../../models/' + modelName + '/' + modelName + '.map.js'), result = {}; return promise.then(function(data) { Object.keys(schema).forEach(function(field) { var rule = schema[field], ctxType = typeof rule, val; if ((ctxType === 'string') || (ctxType === 'function')) { rule = { type: 'simple', ctx: rule }; } else { ctxType = typeof rule.ctx; } val = ctxType === 'string' ? data[rule.ctx] : rule.ctx(data); if (rule.type === 'model') { result[field] = _this.map(rule.model, val); } else if (rule.type === 'collection' && val instanceof Array) { result[field] = Vow.all(val.map(function(item) { return _this.map(rule.model, item); })); } else { result[field] = val; } }); return Vow.all(result); }); }
getJSDocTag: function(tag, value) { var promise = vow.promise(), before = ' * @' + tag + ' ', standard = before + value; if(tag === 'date' && value === true) { promise.fulfill(before + moment().lang('en').format('D MMMM YYYY')); return promise; } this.openExistsFile(value).then( function(data) { try { var jsonValue = JSON.parse(data)[tag]; } catch(error) { this.console.warn({ operation: 'jsdoc', path: value, description: '@' + tag + ' file must be JSON' }); return promise.fulfill(standard); } promise.fulfill(before + jsonValue); }.bind(this), function() { promise.fulfill(standard); } ); return promise; }
function(path) { var promise = Vow.promise(); fs.exists(path, function(exists) { promise.fulfill(exists); }); return promise; } :
.use ('urn:fos:sync:feature/01bdf56a3837bfd6afa8bf69b54f70e3', function getMentions (task) { var token = task._prefetch.token, emit = this.emitter (task), vk = getVKontakte (token), promise = Promises.promise (), user_id = task.url.match(/vk.com\/id(\d+)$/) [1]; return iterate (vk, 'newsfeed.getMentions', {uid: user_id, limit: 50}, function (row) { return (row.date * 1000) >= (task ['previous-poll'] || task ['scrape-start']); }, function (error, row) { if (error) { return promise.reject (error); } if (typeof row == 'object') { return normalize (row, null, vk) .then (function (entry) { Promises.when (emit (entry)) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)) .done (); }) /*.fail (function (error) { return promise.reject (error); })*/; } }); })
return this.isFile(sourcePath).then(function(isFile) { if(!isFile) { var err = Error(); err.errno = 28; err.code = 'EISDIR'; err.path = sourcePath; throw err; } var promise = Vow.promise(), sourceStream = fs.createReadStream(sourcePath), errFn = function(err) { promise.reject(err); }; sourceStream .on('error', errFn) .on('open', function() { var targetStream = fs.createWriteStream(targetPath); sourceStream.pipe( targetStream .on('error', errFn) .on('close', function() { promise.fulfill(); })); }); return promise; });
.use ('urn:fos:sync:feature/70a3d7202f5811e3be4b27b4e33fefff', function fetchUserTips (task) { var token = task._prefetch.token, emit = this.emitter (task), api = getAPI (token), userId = task.url.match (/\/user\/(\d+)(\/|$)/) [1], promise = Promises.promise (); api.list ('lists/' + userId + '/tips') .each (function (item) { return Promises.when ( normalize (item, 'tip') ) .then (function (entry) { if ((task ['previous-poll'] || task ['scrape-start']) && entry.created_at) { if ((task ['previous-poll'] || task ['scrape-start']) > entry.created_at * 1000) { return false; } } return emit (entry); }); }) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)); return promise; })
.then (function (client) { var promise = Promises.promise (); client.on ('error', function (error) { promise.reject (_.last (error.args)); client.disconnect (); }); if (/,isnick$/.test (task.url)) { // private message // 'irc://chat.freenode.net/not_a_lyxsus,isnick' var nickname = task.url.match (/\/([^,\/]+),isnick$/) [1]; client.say (nickname, task.content); //todo: emit and fulfill } else { // public message // 'irc://chat.freenode.net/ccprivatechannel/1376933059886' var channel = '#' + task.url.match (/\/([^\/]+)\/\d+$/) [1]; client.on ('join', function () { client.say (channel, task.content); //todo: emit and fulfill }); client.join ('#' + channel + ' ' + token.password); } return promise; });
.use ('urn:fos:sync:feature/29e5fa0b4e79c2412525bcdc576a92a2', function resolveToken (task) { var token = task._prefetch.token, emit = this.emitter (task), promise = Promises.promise(), vk = getVKontakte (token); getUserInfo (vk, null, function (error, result) { if (error) { return promise.reject (error); } if (result.deactivated) { return promise.reject ('User deactivated'); } return normalize (result, 'profile', vk) .then(function (entry) { Promises.when (entry) .then (function (entry) { entry.tokens = [token._id]; return emit (entry); }) .then (_.bind (promise.fulfill, promise)) .fail (_.bind (promise.reject, promise)) .done (); }) /*.fail (function (error) { return emit (error); })*/; }); return promise; })
build: function () { var _this = this; var options = this._options; var promise = Vow.promise(); var source = this.node.unmaskTargetName(this._sourceTarget); var sourcePath = this.node.resolvePath(source); var target = this.node.unmaskTargetName(this._destTarget); var targetPath = this.node.resolvePath(target); var cache = this.node.getNodeCache(target); var sources = [source]; var xslFile = options.xslFile; this.node.getLogger().logTechIsDeprecated( target, 'xslt', 'enb', 'xslt', 'enb-lego-xml' ); if (options.xslSource) { var xslSource = options.xslSource; xslSource = this.node.unmaskTargetName(xslSource); xslFile = this.node.resolvePath(xslSource); sources.push(xslSource); } this.node.requireSources(sources).then(function () { var args = (options.args || []).concat([xslFile, sourcePath]); // TODO: XSL Include deps tree. if (cache.needRebuildFile('target-file', targetPath) || cache.needRebuildFile('source-file', sourcePath) || cache.needRebuildFile('xsl-file', xslFile) ) { fs.open(targetPath, 'w', function (err, fd) { if (err) { return promise.reject(err); } childProcess.spawn('/usr/bin/xsltproc', args, { stdio: [null, fd, null] }) .on('error', function (err) { promise.reject(err); }) .on('close', function () { cache.cacheFileInfo('target-file', targetPath); cache.cacheFileInfo('source-file', sourcePath); cache.cacheFileInfo('xsl-file', xslFile); _this.node.resolveTarget(target); promise.fulfill(); }); }); } else { _this.node.isValidTarget(target); _this.node.resolveTarget(target); promise.fulfill(); } }); return promise; }
build: function() { var _this = this, promise = Vow.promise(); try { var target = this._target, levelList = [], levelsToCache = [], levelsIndex = {}, cache = this.node.getNodeCache(target); for (var i = 0, l = this._levelConfig.length; i < l; i++) { var levelInfo = this._levelConfig[i]; levelInfo = typeof levelInfo === 'object' ? levelInfo : {path: levelInfo}; var levelPath = levelInfo.path, levelKey = 'level:' + levelPath; if (levelsIndex[levelPath]) continue; levelsIndex[levelPath] = true; if (!this.node.buildState[levelKey]) { var level = new Level(levelPath, this.node.getLevelNamingScheme(levelPath)); if (levelInfo.check === false) { var blocks = cache.get(levelPath); if (blocks) { level.loadFromCache(blocks); } else { levelsToCache.push(level); } } this.node.buildState[levelKey] = level; } levelList.push(this.node.buildState[levelKey]); } var pageBlocksPath = this.node.resolvePath('blocks'); fs.exists(pageBlocksPath, function(res) { try { if (res && !levelsIndex[pageBlocksPath]) { levelsIndex[pageBlocksPath] = true; levelList.push(new Level(pageBlocksPath)); } return Vow.all(levelList.map(function(level) { return level.load(); })).then((function() { levelsToCache.forEach(function(level) { cache.set(level.getPath(), level.getBlocks()); }); _this.node.resolveTarget(target, new Levels(levelList)); return promise.fulfill(); }), function(err) { return promise.reject(err); }); } catch (err) { return promise.reject(err); } }); } catch (err) { promise.reject(err); } return promise; },
.then(function(server) { var promise = Vow.promise(); testFn(function() { server.close(mochaDone); }, server); return promise; })