Ejemplo n.º 1
0
  /**
   * Dial a list of multiaddrs on the given transport.
   *
   * @param {PeerId} peer
   * @param {SwarmTransport} transport
   * @param {Array<Multiaddr>} addrs
   * @param {function(Error, Connection)} callback
   * @returns {void}
   */
  dialMany (peer, transport, addrs, callback) {
    log('dialMany:start')
    // we use a token to track if we want to cancel following dials
    const token = { cancel: false }
    callback = once(callback) // only call callback once

    map(addrs, (m, cb) => {
      this.dialSingle(peer, transport, m, token, cb)
    }, (err, results) => {
      if (err) {
        return callback(err)
      }

      const success = results.filter((res) => res.conn)
      if (success.length > 0) {
        log('dialMany:success')
        return callback(null, success[0])
      }

      log('dialMany:error')
      const error = new Error('Failed to dial any provided address')
      error.errors = results
        .filter((res) => res.error)
        .map((res) => res.error)
      return callback(error)
    })
  }
Ejemplo n.º 2
0
      self.dag.get(cid, '', options, (err, res) => {
        if (err) { return callback(err) }

        mapAsync(res.value.links, (link, cb) => {
          self.dag._getRecursive(link.cid, options, cb)
        }, (err, nodes) => {
          // console.log('nodes:', nodes)
          if (err) return callback(err)
          callback(null, flattenDeep([res.value, nodes]))
        })
      })
Ejemplo n.º 3
0
  self._ready.await(function(){

    if (Array.isArray(payload)) {
      // handle batch
      map(payload, self._handleAsync.bind(self), cb)
    } else {
      // handle single
      self._handleAsync(payload, cb)
    }

  })
  archive.advancedSearch(params, function(err, results) {
    if (err) return next(err);

    map(results.response.docs, (doc, callback) => {
      const id = doc.identifier;

      archive.metadata(id, callback);
    }, function(err, results) {
      if (err) return next(err);

      console.log('Mapping feed onto xml');

      const items = results.map(result => {
        const mp3File = find(result.files, {format: 'VBR MP3'});

        const metadata = Object.assign({}, result.metadata, {
          length: mp3File.length,
          image: `(${env.image})`
        });

        return template(metadata);
      }).join('');

      req.feed =`<?xml version="1.0" encoding="UTF-8"?>
      <rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
      <channel>
        <title>${env.podcastTitle}</title>
        <link>${env.authorURL}</link>
        <language>${env.language}</language>
        <image>
          <title>${env.podcastTitle}</title>
          <url>${env.image}</url>
          <link>${env.authorURL}</link>
        </image>
        <itunes:author>${env.author}</itunes:author>
        <itunes:summary>${env.podcastDescription}</itunes:summary>
        <description>${env.podcastDescription}</description>
        <itunes:owner>
          <itunes:name>${env.author}</itunes:name>
          <itunes:email>${env.authorEmail}</itunes:email>
        </itunes:owner>
        <itunes:image href="${env.image}" />
        <itunes:category text="${env.parentCategory}">
          <itunes:category text="${env.category}" />
        </itunes:category>
        <itunes:explicit>${env.explicit}</itunes:explicit>`
      + items + '</channel></rss>';

      next();
    });
  });
Ejemplo n.º 5
0
Archivo: pin.js Proyecto: ipfs/js-ipfs
      resolvePath(self.object, paths, (err, mhs) => {
        if (err) { return callback(err) }

        // verify that each hash can be pinned
        map(mhs, (multihash, cb) => {
          const key = toB58String(multihash)
          if (recursive) {
            if (recursivePins.has(key)) {
              // it's already pinned recursively
              return cb(null, key)
            }

            // entire graph of nested links should be pinned,
            // so make sure we have all the objects
            dag._getRecursive(key, { preload: options.preload }, (err) => {
              if (err) { return cb(err) }
              // found all objects, we can add the pin
              return cb(null, key)
            })
          } else {
            if (recursivePins.has(key)) {
              // recursive supersedes direct, can't have both
              return cb(new Error(`${key} already pinned recursively`))
            }
            if (directPins.has(key)) {
              // already directly pinned
              return cb(null, key)
            }

            // make sure we have the object
            dag.get(new CID(multihash), { preload: options.preload }, (err) => {
              if (err) { return cb(err) }
              // found the object, we can add the pin
              return cb(null, key)
            })
          }
        }, (err, results) => {
          if (err) { return callback(err) }

          // update the pin sets in memory
          const pinset = recursive ? recursivePins : directPins
          results.forEach(key => pinset.add(key))

          // persist updated pin sets to datastore
          flushPins((err, root) => {
            if (err) { return callback(err) }
            callback(null, results.map(hash => ({ hash })))
          })
        })
      })
Ejemplo n.º 6
0
Archivo: pin.js Proyecto: ipfs/js-ipfs
      resolvePath(self.object, paths, (err, mhs) => {
        if (err) { return callback(err) }

        // verify that each hash can be unpinned
        map(mhs, (multihash, cb) => {
          pin._isPinnedWithType(multihash, types.all, (err, res) => {
            if (err) { return cb(err) }
            const { pinned, reason } = res
            const key = toB58String(multihash)
            if (!pinned) {
              return cb(new Error(`${key} is not pinned`))
            }

            switch (reason) {
              case (types.recursive):
                if (recursive) {
                  return cb(null, key)
                } else {
                  return cb(new Error(`${key} is pinned recursively`))
                }
              case (types.direct):
                return cb(null, key)
              default:
                return cb(new Error(
                  `${key} is pinned indirectly under ${reason}`
                ))
            }
          })
        }, (err, results) => {
          if (err) { return callback(err) }

          // update the pin sets in memory
          results.forEach(key => {
            if (recursive && recursivePins.has(key)) {
              recursivePins.delete(key)
            } else {
              directPins.delete(key)
            }
          })

          // persist updated pin sets to datastore
          flushPins((err, root) => {
            if (err) { return callback(err) }
            self.log(`Removed pins: ${results}`)
            callback(null, results.map(hash => ({ hash })))
          })
        })
      })
Ejemplo n.º 7
0
        .exec(function(err, days){
            if (err) {
                res.status(500).send({err: 'could not query database'});
                return console.error(err);
            }
            map(days, (day, eCb)=>{
                day.getEventCount((err, count)=>{
                    if(err) return eCb(err);
                    eCb(null, {...day.toJSON(), eventCount: count});
                });
            }, (err, results)=>{
                if(err) res.status(500).send({err: 'could not query database'});
                res.send(results);
            });

        });
Ejemplo n.º 8
0
  fs.readFile(pt.join(constants.packagesPrefix, 'package.json'), (err, data) => {
    if (err) {
      return dispatch(uiActions.addNotification({
        message: 'Could not read installed plugins.',
        level: 'error'
      }))
    }

    const packageDirs = _.map(_.keys(JSON.parse(data).dependencies), pkgName =>
      pt.join(constants.packagesPrefix, 'node_modules', pkgName, 'package.json')
    )

    asyncMap(packageDirs, fs.readFile, (err, resultStrs) => {
      const packages = _.map(resultStrs, JSON.parse)
      dispatch(setInstalledPlugins(packages))
      dispatch(installDependancies())
    })
  })
Ejemplo n.º 9
0
  self.emitPayload({ method: 'eth_blockNumber' }, function(err, res) {
    // FIXME: convert number using a bignum library
    var lastBlock = parseInt(res.result, 16)
    var blockNumbers = [ ]
    for (var i = 0; i < self.numberOfBlocks; i++) {
      blockNumbers.push('0x' + lastBlock.toString(16))
      lastBlock--
    }

    function getBlock(item, end) {
      self.emitPayload({ method: 'eth_getBlockByNumber', params: [ item, true ] }, function(err, res) {
        if (err) return end(err)
        end(null, res.result.transactions)
      })
    }

    // FIXME: this could be made much faster
    function calcPrice(err, transactions) {
      // flatten array
      transactions = transactions.reduce(function(a, b) { return a.concat(b) }, [])

      // leave only the gasprice
      // FIXME: convert number using a bignum library
      transactions = transactions.map(function(a) { return parseInt(a.gasPrice, 16) }, [])

      // order ascending
      transactions.sort(function(a, b) { return a - b })

      // ze median
      var half = Math.floor(transactions.length / 2)

      var median
      if (transactions.length % 2)
        median = transactions[half]
      else
        median = Math.floor((transactions[half - 1] + transactions[half]) / 2.0)

      end(null, median)
    }

    map(blockNumbers, getBlock, calcPrice)      
  })
      doc.constructor.find(objProperty(ancestors, doc[id])).exec(function(err, docs) {
        // update documents
        map(
          docs,
          function(childrenDoc, cbNext) {
            // Remove all the ancestors that now are not ancestors
            let newAncestors = _dropWhile(childrenDoc[ancestors], function(elementId) {
              return elementId.toString() !== doc[id].toString();
            });
            childrenDoc[ancestors] = _concat(doc[ancestors], newAncestors);

            childrenDoc.save(function(err, data) {
              cbNext(err, data);
            });
          },
          function(err) {
            next(err);
          }
        );
      });
Ejemplo n.º 11
0
Archivo: pin.js Proyecto: ipfs/js-ipfs
      dag._getRecursive(multihash, (err, nodes) => {
        if (err) {
          return cb(err)
        }

        map(nodes, (node, cb) => util.cid(util.serialize(node), {
          cidVersion: 0
        }).then(cid => cb(null, cid), cb), (err, cids) => {
          if (err) {
            return cb(err)
          }

          cids
            .map(cid => cid.toString())
            // recursive pins pre-empt indirect pins
            .filter(key => !recursivePins.has(key))
            .forEach(key => indirectKeys.add(key))

          cb()
        })
      })