/** AKA scraping */ public TorrentStatus getStatus() throws IOException { if (!isGetStatusSupported()) { throw new IllegalStateException("Get status (scraping) not supported on this tracker"); } String path = announceUrl.getFile(); int i = path.lastIndexOf('/'); path = path.substring(0, i + 1) + "scrape" + path.substring(i + ANNOUNCE.length() + 1); GetMethod method = new GetMethod(path); method.setRequestHeader("User-Agent", "BlackBits/0.1"); StringBuffer queryString = new StringBuffer(announceUrl.getQuery() == null ? "" : announceUrl.getQuery()); queryString.append("info_hash=" + URLUtils.encode(infoHash.getBytes())); method.setQueryString(queryString.toString()); httpClient.executeMethod(method); BDecoder decoder = new BDecoder(method.getResponseBodyAsStream()); BDictionary dictionary = (BDictionary) decoder.decodeNext(); BDictionary files = (BDictionary) dictionary.get("files"); String key = (String) files.keySet().iterator().next(); BDictionary info = (BDictionary) files.get(key); BLong seeders = (BLong) info.get("complete"); BLong leechers = (BLong) info.get("incomplete"); BLong numberOfDownloads = (BLong) info.get("downloaded"); return new TorrentStatus(seeders.intValue(), leechers.intValue(), numberOfDownloads.intValue()); }
private TrackerResponse decodeResponse(GetMethod method) throws IOException, TrackerCommunicationException { BDecoder decoder = new BDecoder(method.getResponseBodyAsStream()); BDictionary dictionary = (BDictionary) decoder.decodeNext(); if (dictionary.get("failure reason") != null) { BString failureReason = (BString) dictionary.get("failure reason"); throw new TrackerCommunicationException(failureReason.getStringValue()); } int seeders = getInt(dictionary, "complete"); int leechers = getInt(dictionary, "incomplete"); int updateInterval = getInt(dictionary, "interval"); BList peersList = (BList) dictionary.get("peers"); List peers = new ArrayList(); for (Iterator i = peersList.iterator(); i.hasNext(); ) { BDictionary peerDictionary = (BDictionary) i.next(); peers.add( new Peer( ((BString) peerDictionary.get("peer id")).getStringValue(), ((BLong) peerDictionary.get("port")).intValue(), ((BString) peerDictionary.get("ip")).getStringValue())); } return new TrackerResponse(seeders, leechers, updateInterval, peers); }
private int getInt(BDictionary dictionary, String key) { BObject bObject = dictionary.get(key); if (!(bObject instanceof BLong)) { return 0; } return (int) ((BLong) bObject).longValue(); }