HTTP torrent tracker client (for an individual tracker)

@param {Client} client       parent bittorrent tracker client
@param {string} announceUrl  announce url of tracker
@param {Object} opts         options object
350265
function HTTPTracker (client, announceUrl, opts) {
  var self = this
  Tracker.call(self, client, announceUrl)
  debug('new http tracker %s', announceUrl)

  // Determine scrape url (if http tracker supports it)
  self.scrapeUrl = null

  var match = self.announceUrl.match(HTTP_SCRAPE_SUPPORT)
  if (match) {
    var pre = self.announceUrl.slice(0, match.index)
    var post = self.announceUrl.slice(match.index + 9)
    self.scrapeUrl = pre + '/scrape' + post
  }

  self.cleanupFns = []
  self.maybeDestroyCleanup = null
}
719379
function(callback) {
        var scarlet = new Scarlet(Math.min(opts.n, 100));

        function connect(taskObject) {
            var client = taskObject.task.client;
            var i = taskObject.task.idx;

            client.connect(function() {
                scarlet.taskDone(taskObject);
            });

            client.on("error", function(err) {
                console.log(err + ": Client " + i);
            });
        }

        console.time("Connect");

        // if mode is `clients`, we create (opts.complicating) clients,
        // otherwise we create only one.
        var max = opts["complicating-mode"] === "clients" ? opts.complicating : 1;
        for(var i = 0; i < max; i++) {
            var client = illyria2.createClient("127.0.0.1", SERVER_PORT, {
                runTimeout: 10000,
                retryInterval: 1000,
                reconnect: true
            });

            scarlet.push({ idx: i, client: client }, connect);

            clients.push(client);
        }

        scarlet.afterFinish(max, function() {
            console.timeEnd("Connect");
            callback();
        }, false);
    }
617517
function getDataTorrentFromFile(torrentFile) {
  if(!fs.existsSync(torrentFile)) {
    throw new Error(`This torrent file does not exists : ${torrentFile}`);
  }

  const torrent = parseTorrent(fs.readFileSync(torrentFile));
  torrent.path = torrentFile;
  torrent.hash = torrent.infoHash.toUpperCase();
  return torrent;
}
658217
function(opts) {

				// Remove from the store
				utils.store(p.name, null);

				// Emit events by default
				promise.fulfill(hello.utils.merge({network:p.name}, opts || {}));
			}
589222
function (opts, id) {
        let uri = this.classUrl
        if (id) {
          uri += '/' + id
        }

        if (typeof opts.data === 'function') {
          opts.next = opts.data
          opts.data = {}
        }

        // Reset payment sources
        this.payment_sources = null

        return new Promise(function (resolve, reject) {
          new Requestor({ api_version: instance.api_version }).request({
            method: 'get',
            url: [Conekta.api_base, uri].join(''),
            data: opts.data || {},
            next: function (error, response) {
              if (!error) {
                response = this.listObjectsToArray(response)
                this._json = response
                if (id) {
                  this._id = response.id
                } else {
                  _.each(response.data, (item) => {
                    const index = _.extend(
                      {
                        _json: item,
                        _id: item._id
                      },
                      this
                    )
                    this._items.push(index)
                  })
                }
                this.build_children()
              }
              if (opts.next !== undefined) {
                opts.next(error, this)
              } else {
                if (error) {
                  reject(error) 
                } else {
                  resolve(this)
                }
              }
            }.bind(this)
          })
        }.bind(this))

      }
219341
function Courier(opts) {
  stream.Transform.call(this, { objectMode: true });

  this.options = merge(Object.create(Courier.DEFAULTS), opts || {});
}
91435
function addWebRoutes(opts) {
    var server = opts.server;
    var socialProviders = opts.config && opts.config.security && opts.config.security.social;
    var me = this;

    // first add social auth routes
    _.each(socialProviders, function (provider, providerName) {
        server.route({
            method:     ['GET', 'POST'],
            path:       '/auth/' + providerName,
            handler:    me.getWebRouteHandler(opts),
            config:     { auth: providerName }
        });
    });

    routeHandler = this.getWebRouteHandler(opts);

    // all other URLs checked against app config files for dymanic web routes
    server.route({
        method:     '*',
        path:       '/{p*}',
        handler:    routeHandler,
        config: {
            state: {
                parse:      true,
                failAction: 'log'
            }
        }
    });

    // for now simple access logging for errors
    server.on('response', function (request) {
        var resp = request.response || {};
        var statusCode = resp.statusCode || 0;
        var method = (request.method || '').toUpperCase();
        var reqInfo = request.info || {};
        var referrer = reqInfo.referrer || '';
        var host = reqInfo.hostname || '';
        var url = request.url || {};
        var urlPath = url.path || '';

        if (statusCode > 399 && method.toUpperCase && host && urlPath) {

            var lapse = -1;
            if (reqInfo.responded && reqInfo.received) {
                lapse = reqInfo.responded - reqInfo.received;
            }

            var msg = method + ' ' + host + urlPath + ' -> ' + statusCode + ' ' + '(' + lapse + 'ms)';
            if (referrer) {
                msg += ' ref: ' + request.info.referrer;
            }

            console.log(msg);
        }
    });
}
10715
function (opts, candidate) {
        this._log('info', 'Discovered new ICE candidate', candidate.jingle);
        this.send('transport-info', candidate.jingle);
        if (opts.signalEndOfCandidates) {
            this.lastCandidate = candidate;
        }
    }
332339
@Override
  public void handleDiscoveredPeers(List<Peer> peers, String hexInfoHash) {

    if (peers.size() == 0) return;

    SharedTorrent torrent = torrentsStorage.getTorrent(hexInfoHash);

    if (torrent != null && torrent.isFinished()) return;

    final LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(hexInfoHash);
    if (announceableTorrent == null) {
      logger.info("announceable torrent {} is not found in storage. Maybe it was removed", hexInfoHash);
      return;
    }

    if (announceableTorrent.getPieceStorage().isFinished()) return;

    logger.debug("Got {} peer(s) ({}) for {} in tracker response", new Object[]{peers.size(),
            Arrays.toString(peers.toArray()), hexInfoHash});

    Map<PeerUID, Peer> uniquePeers = new HashMap<PeerUID, Peer>();
    for (Peer peer : peers) {
      final PeerUID peerUID = new PeerUID(peer.getAddress(), hexInfoHash);
      if (uniquePeers.containsKey(peerUID)) continue;
      uniquePeers.put(peerUID, peer);
    }

    for (Map.Entry<PeerUID, Peer> e : uniquePeers.entrySet()) {

      PeerUID peerUID = e.getKey();
      Peer peer = e.getValue();
      boolean alreadyConnectedToThisPeer = peersStorage.getSharingPeer(peerUID) != null;

      if (alreadyConnectedToThisPeer) {
        logger.debug("skipping peer {}, because we already connected to this peer", peer);
        continue;
      }

      ConnectionListener connectionListener = new OutgoingConnectionListener(
              this,
              announceableTorrent.getTorrentHash(),
              peer.getIp(),
              peer.getPort());

      logger.debug("trying to connect to the peer {}", peer);

      boolean connectTaskAdded = this.myConnectionManager.offerConnect(
              new ConnectTask(peer.getIp(),
                      peer.getPort(),
                      connectionListener,
                      new SystemTimeService().now(),
                      Constants.DEFAULT_CONNECTION_TIMEOUT_MILLIS), 1, TimeUnit.SECONDS);
      if (!connectTaskAdded) {
        logger.info("can not connect to peer {}. Unable to add connect task to connection manager", peer);
      }
    }
  }
33313
function sendAnalyticsDataToServer(eventParams) {
        var result = new $.Deferred();

        var analyticsData = getAnalyticsData(eventParams);
        $.ajax({
            url: brackets.config.analyticsDataServerURL,
            type: "POST",
            data: JSON.stringify({events: [analyticsData]}),
            headers: {
                "Content-Type": "application/json",
                "x-api-key": brackets.config.serviceKey
            }
        })
            .done(function () {
                result.resolve();
            })
            .fail(function (jqXHR, status, errorThrown) {
                console.error("Error in sending Adobe Analytics Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown);
                result.reject();
            });

        return result.promise();
    }
679043
function (opts, cb) {
            var self = this;
            cb = cb || function () {
                };
            opts = opts || {};
            var url = this._getlisturi(opts);
            this.client.get({
                uri: url,
                data:opts
            }, cb);
        }
624690
function Aliyun_Push(opts) {
  opts = opts || {};

  this.AccessKeyId = opts.AccessKeyId;
  this.AccessKeySecret = opts.AccessKeySecret;
  this.AccountName = opts.AccountName;
  this.dmHost = 'https://dm.aliyuncs.com/';
  this.smsHost = 'https://sms.aliyuncs.com/';

  this.publicParams = {
    Format: 'JSON',
    AccessKeyId: opts.AccessKeyId,
    SignatureMethod: 'HMAC-SHA1',
    Timestamp: '',
    SignatureVersion: '1.0',
    SignatureNonce: '',
  };
  this.singleOptions = {
    Action: 'SingleSendMail',
    AccountName: opts.AccountName,
    ReplyToAddress: true,
    AddressType: 1
  }
  this.batchOptions = {
    Action: 'BatchSendMail',
    AccountName: opts.AccountName,
    ReplyToAddress: true,
    AddressType: 1
  }
  this.smsOptions = {
    Action: 'SingleSendSms'
  }
}
1226406
public void start(final URI defaultTrackerURI, final AnnounceResponseListener listener, final Peer[] peers, final int announceInterval) {
    myAnnounceInterval = announceInterval;
    myPeers.addAll(Arrays.asList(peers));
    if (defaultTrackerURI != null) {
      try {
        myDefaultTracker = myTrackerClientFactory.createTrackerClient(myPeers, defaultTrackerURI);
        myDefaultTracker.register(listener);
        this.clients.put(defaultTrackerURI.toString(), myDefaultTracker);
      } catch (Exception e) {
      }
    } else {
      myDefaultTracker = null;
    }

    this.stop = false;
    this.forceStop = false;

    if (this.thread == null || !this.thread.isAlive()) {
      this.thread = new Thread(this);
      this.thread.setName("torrent tracker announce thread");
      this.thread.start();
    }
  }
1044498
function(gitStashLocation, indexMessage, workingDirectoryMessage, includeUntracked){
			var service = this;
			
			var payload = {};
			if(indexMessage != null) /* note that undefined == null */
				payload.IndexMessage = indexMessage;
			
			if(workingDirectoryMessage != null) /* note that undefined == null */
				payload.WorkingDirectoryMessage = workingDirectoryMessage;
			
			if(includeUntracked === true)
				payload.IncludeUntracked = true;
			
			var clientDeferred = new Deferred();
			xhr("POST", gitStashLocation, {
				headers : { 
					"Orion-Version" : "1",
					"Content-Type" : contentType
				},
				timeout : GIT_TIMEOUT,
				data: JSON.stringify(payload)
			}).then(function(result) {
				service._getGitServiceResponse(clientDeferred, result);
			}, function(error){
				service._handleGitServiceResponseError(clientDeferred, error);
			});
			
			return clientDeferred;
		}
1252717
function EventTransmitter(opts) {
  var hash;

  PassThrough.call(this);

  opts = opts || {};

  hash = crypto.createHash('sha1', opts.delimeter || 'jambalaya');
  hash.setEncoding('hex');
  hash.end();

  this.delimiter = '<' + hash.read().substr(0, 10) + '>';
  this.opts = opts;
}
1146773
function updatePersistentPath(client, path, data, callback) {
  debug('updatePersistentPath: "%s" "%s"', path, data);

  data = ensureBuffer(data);

  client.setData(path, data, function (err) {
    if (err) {
      if (err.code !== NO_NODE)
        return callback(err);

      createParentPath(client, path, function(err) {
        if (err) return callback(err);

        client.create(path, data, function(err) {
          if (err) {
            if (err.code !== NODE_EXISTS)
              return callback(err);
            client.setData(path, data, callback);
          } else
            callback(null);
        });
      });
    } else
      callback(null);
  });
}
956881
function createClient(url, opts) {
  // Attempt to get Url from this instance.
  url = url || this.url || (this.opts || {}).url || (opts || {}).url;
  if (! url) {
    throw 'No url specified for ActiveDirectory client.';
  }
  log.trace('createClient(%s)', url);

  var opts = getLdapClientOpts(_.defaults({}, { url: url }, opts, this.opts));
  log.debug('Creating ldapjs client for %s. Opts: %j', opts.url, _.omit(opts, 'url', 'bindDN', 'bindCredentials'));
  var client = ldap.createClient(opts);
  return(client);
}