use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class LWSDiskManager method start.
@Override
public void start() {
try {
TOTorrent torrent = lws.getTOTorrent(false);
internal_name = ByteFormatter.nicePrint(torrent.getHash(), true);
LocaleUtilDecoder locale_decoder = LocaleTorrentUtil.getTorrentEncoding(torrent);
piece_mapper = DMPieceMapperFactory.create(torrent);
piece_mapper.construct(locale_decoder, save_file.getName());
files = getFileInfo(piece_mapper.getFiles(), save_file);
reader = DMAccessFactory.createReader(this);
reader.start();
if (state != DiskManager.FAULTY) {
started = true;
state = DiskManager.READY;
}
} catch (Throwable e) {
setFailed("start failed - " + Debug.getNestedExceptionMessage(e));
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class HTTPNetworkConnectionFile method decodeHeader.
@Override
protected void decodeHeader(HTTPMessageDecoder decoder, final String header) throws IOException {
if (switching) {
Debug.out("new header received while paused");
throw (new IOException("Bork"));
}
if (!isSeed()) {
return;
}
PEPeerControl control = getPeerControl();
DiskManager dm = control.getDiskManager();
if (dm == null) {
Debug.out("Disk manager is null");
throw (new IOException("Disk manager unavailable"));
}
TOTorrent to_torrent = dm.getTorrent();
char[] chars = header.toCharArray();
int last_pos = 0;
int line_num = 0;
String target_str = null;
DiskManagerFileInfo target_file = null;
long file_offset = 0;
List<long[]> ranges = new ArrayList<>();
boolean keep_alive = false;
for (int i = 1; i < chars.length; i++) {
if (chars[i - 1] == '\r' && chars[i] == '\n') {
String line = new String(chars, last_pos, i - last_pos).trim();
last_pos = i;
line_num++;
if (line_num == 1) {
line = line.substring(line.indexOf("files/") + 6);
int hash_end = line.indexOf("/");
final byte[] old_hash = control.getHash();
final byte[] new_hash = URLDecoder.decode(line.substring(0, hash_end), "ISO-8859-1").getBytes("ISO-8859-1");
if (!Arrays.equals(new_hash, old_hash)) {
switching = true;
decoder.pauseInternally();
flushRequests(new flushListener() {
private boolean triggered;
@Override
public void flushed() {
synchronized (this) {
if (triggered) {
return;
}
triggered = true;
}
getManager().reRoute(HTTPNetworkConnectionFile.this, old_hash, new_hash, header);
}
});
return;
}
line = line.substring(hash_end + 1);
line = line.substring(0, line.lastIndexOf(' '));
String file = line;
if (to_torrent.isSimpleTorrent()) {
// optimise for simple torrents. also support the case where
// client has the hash but doesn't know the file name
target_file = dm.getFiles()[0];
} else {
target_str = file;
StringTokenizer tok = new StringTokenizer(file, "/");
List<byte[]> bits = new ArrayList<>();
while (tok.hasMoreTokens()) {
bits.add(URLDecoder.decode(tok.nextToken(), "ISO-8859-1").getBytes("ISO-8859-1"));
}
if (!to_torrent.isSimpleTorrent() && bits.size() > 1) {
if (Arrays.equals(to_torrent.getName(), (byte[]) bits.get(0))) {
bits.remove(0);
}
}
DiskManagerFileInfo[] files = dm.getFiles();
file_offset = 0;
for (int j = 0; j < files.length; j++) {
TOTorrentFile torrent_file = files[j].getTorrentFile();
byte[][] comps = torrent_file.getPathComponents();
if (comps.length == bits.size()) {
boolean match = true;
for (int k = 0; k < comps.length; k++) {
if (!Arrays.equals(comps[k], (byte[]) bits.get(k))) {
match = false;
break;
}
}
if (match) {
target_file = files[j];
break;
}
}
file_offset += torrent_file.getLength();
}
}
} else {
line = line.toLowerCase(MessageText.LOCALE_ENGLISH);
if (line.startsWith("range") && target_file != null) {
line = line.substring(5).trim();
if (line.startsWith(":")) {
String range_str = line.substring(1).trim();
if (range_str.startsWith("bytes=")) {
long file_length = target_file.getLength();
StringTokenizer tok2 = new StringTokenizer(range_str.substring(6), ",");
while (tok2.hasMoreTokens()) {
String range = tok2.nextToken();
try {
int pos = range.indexOf('-');
if (pos != -1) {
String lhs = range.substring(0, pos);
String rhs = range.substring(pos + 1);
long start;
long end;
if (lhs.length() == 0) {
// -222 is last 222 bytes of file
end = file_length - 1;
start = file_length - Long.parseLong(rhs);
} else if (rhs.length() == 0) {
end = file_length - 1;
start = Long.parseLong(lhs);
} else {
start = Long.parseLong(lhs);
end = Long.parseLong(rhs);
}
ranges.add(new long[] { start, end });
}
} catch (Throwable e) {
}
}
}
if (ranges.size() == 0) {
log("Invalid range specification: '" + line + "'");
sendAndClose(getManager().getRangeNotSatisfiable());
return;
}
}
} else if (line.contains("keep-alive")) {
keep_alive = true;
}
}
}
}
if (target_file == null) {
log("Failed to find file '" + target_str + "'");
sendAndClose(getManager().getNotFound());
return;
}
try {
String name = target_file.getFile(true).getName();
int pos = name.lastIndexOf(".");
if (pos != -1) {
setContentType(HTTPUtils.guessContentTypeFromFileType(name.substring(pos + 1)));
}
} catch (Throwable e) {
}
long file_length = target_file.getLength();
boolean partial_content = ranges.size() > 0;
if (!partial_content) {
ranges.add(new long[] { 0, file_length - 1 });
}
long[] offsets = new long[ranges.size()];
long[] lengths = new long[ranges.size()];
for (int i = 0; i < ranges.size(); i++) {
long[] range = (long[]) ranges.get(i);
long start = range[0];
long end = range[1];
if (start < 0 || start >= file_length || end < 0 || end >= file_length || start > end) {
log("Invalid range specification: '" + start + "-" + end + "'");
sendAndClose(getManager().getRangeNotSatisfiable());
return;
}
offsets[i] = file_offset + start;
lengths[i] = (end - start) + 1;
}
addRequest(new httpRequest(offsets, lengths, file_length, partial_content, keep_alive));
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class CLCacheDiscovery method main.
public static void main(String[] args) {
try {
TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedFile(new File("C:\\temp\\test.torrent"));
CachePeer[] peers = new CLCacheDiscovery().lookup(torrent);
System.out.println("peers=" + peers.length);
for (int i = 0; i < peers.length; i++) {
System.out.println(" cache: " + peers[i].getAddress() + ":" + peers[i].getPort());
}
} catch (Throwable e) {
e.printStackTrace();
}
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class DeviceManagerRSSFeed method generate.
@Override
public boolean generate(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException {
InetSocketAddress local_address = request.getLocalAddress();
if (local_address == null) {
return (false);
}
URL url = request.getAbsoluteURL();
String path = url.getPath();
path = path.substring(PROVIDER.length() + 1);
DeviceImpl[] devices = manager.getDevices();
OutputStream os = response.getOutputStream();
XMLEscapeWriter pw = new XMLEscapeWriter(new PrintWriter(new OutputStreamWriter(os, "UTF-8")));
pw.setEnabled(false);
boolean hide_generic = COConfigurationManager.getBooleanParameter(DeviceManager.CONFIG_VIEW_HIDE_REND_GENERIC, true);
boolean show_only_tagged = COConfigurationManager.getBooleanParameter(DeviceManager.CONFIG_VIEW_SHOW_ONLY_TAGGED, false);
if (path.length() <= 1) {
response.setContentType("text/html; charset=UTF-8");
pw.println("<HTML><HEAD><TITLE>" + Constants.APP_NAME + " Device Feeds</TITLE></HEAD><BODY>");
for (DeviceImpl d : devices) {
if (d.getType() != Device.DT_MEDIA_RENDERER || d.isHidden() || !d.isRSSPublishEnabled() || (hide_generic && d.isNonSimple()) || (show_only_tagged && !d.isTagged())) {
continue;
}
String name = d.getName();
String device_url = PROVIDER + "/" + URLEncoder.encode(name, "UTF-8");
pw.println("<LI><A href=\"" + device_url + "\">" + name + "</A> - <font size=\"-1\"><a href=\"" + device_url + "?format=html\">html</a></font></LI>");
}
pw.println("</BODY></HTML>");
} else {
String device_name = URLDecoder.decode(path.substring(1), "UTF-8");
DeviceImpl device = null;
for (DeviceImpl d : devices) {
if (d.getName().equals(device_name) && d.isRSSPublishEnabled()) {
device = d;
break;
}
}
if (device == null) {
response.setReplyStatus(404);
return (true);
}
TranscodeFileImpl[] _files = device.getFiles();
List<TranscodeFileImpl> files = new ArrayList<>(_files.length);
files.addAll(Arrays.asList(_files));
Collections.sort(files, new Comparator<TranscodeFileImpl>() {
@Override
public int compare(TranscodeFileImpl f1, TranscodeFileImpl f2) {
long added1 = f1.getCreationDateMillis() / 1000;
long added2 = f2.getCreationDateMillis() / 1000;
return ((int) (added2 - added1));
}
});
URL feed_url = url;
// absolute url is borked as it doesn't set the host properly. hack
String host = (String) request.getHeaders().get("host");
if (host != null) {
int pos = host.indexOf(':');
if (pos != -1) {
host = host.substring(0, pos);
}
feed_url = UrlUtils.setHost(url, host);
}
if (device instanceof DeviceMediaRendererImpl) {
((DeviceMediaRendererImpl) device).browseReceived();
}
String channel_title = "Vuze Device: " + escape(device.getName());
boolean html = request.getURL().contains("format=html");
if (html) {
response.setContentType("text/html; charset=UTF-8");
pw.println("<HTML><HEAD><TITLE>" + channel_title + "</TITLE></HEAD><BODY>");
for (TranscodeFileImpl file : files) {
if (!file.isComplete()) {
if (!file.isTemplate()) {
continue;
}
}
URL stream_url = file.getStreamURL(feed_url.getHost());
if (stream_url != null) {
String url_ext = stream_url.toExternalForm();
pw.println("<p>");
pw.println("<a href=\"" + url_ext + "\">" + escape(file.getName()) + "</a>");
url_ext += url_ext.indexOf('?') == -1 ? "?" : "&";
url_ext += "action=download";
pw.println(" - <font size=\"-1\"><a href=\"" + url_ext + "\">save</a></font>");
}
}
pw.println("</BODY></HTML>");
} else {
boolean debug = request.getURL().contains("format=debug");
if (debug) {
response.setContentType("text/html; charset=UTF-8");
pw.println("<HTML><HEAD><TITLE>" + channel_title + "</TITLE></HEAD><BODY>");
pw.println("<pre>");
pw.setEnabled(true);
} else {
response.setContentType("application/xml; charset=UTF-8");
}
try {
pw.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
pw.println("<rss version=\"2.0\" " + "xmlns:vuze=\"http://www.vuze.com\" " + "xmlns:media=\"http://search.yahoo.com/mrss/\" " + "xmlns:atom=\"http://www.w3.org/2005/Atom\" " + "xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\">");
pw.println("<channel>");
pw.println("<title>" + channel_title + "</title>");
pw.println("<link>http://vuze.com</link>");
pw.println("<atom:link href=\"" + feed_url.toExternalForm() + "\" rel=\"self\" type=\"application/rss+xml\" />");
pw.println("<description>" + Constants.APP_NAME + " RSS Feed for device " + escape(device.getName()) + "</description>");
pw.println("<itunes:image href=\"http://www.vuze.com/img/vuze_icon_128.png\"/>");
pw.println("<image><url>http://www.vuze.com/img/vuze_icon_128.png</url><title>" + channel_title + "</title><link>http://vuze.com</link></image>");
String feed_date_key = "devices.feed_date." + device.getID();
long feed_date = COConfigurationManager.getLongParameter(feed_date_key);
boolean new_date = false;
for (TranscodeFileImpl file : files) {
long file_date = file.getCreationDateMillis();
if (file_date > feed_date) {
new_date = true;
feed_date = file_date;
}
}
if (new_date) {
COConfigurationManager.setParameter(feed_date_key, feed_date);
}
pw.println("<pubDate>" + TimeFormatter.getHTTPDate(feed_date) + "</pubDate>");
for (TranscodeFileImpl file : files) {
if (!file.isComplete()) {
if (!file.isTemplate()) {
continue;
}
}
try {
pw.println("<item>");
pw.println("<title>" + escape(file.getName()) + "</title>");
pw.println("<pubDate>" + TimeFormatter.getHTTPDate(file.getCreationDateMillis()) + "</pubDate>");
pw.println("<guid isPermaLink=\"false\">" + escape(file.getKey()) + "</guid>");
String[] categories = file.getCategories();
for (String category : categories) {
pw.println("<category>" + escape(category) + "</category>");
}
String[] tags = file.getTags(true);
for (String tag : tags) {
pw.println("<tag>" + escape(tag) + "</tag>");
}
String mediaContent = "";
URL stream_url = file.getStreamURL(feed_url.getHost());
if (stream_url != null) {
String url_ext = escape(stream_url.toExternalForm());
long fileSize = file.getTargetFile().getLength();
pw.println("<link>" + url_ext + "</link>");
mediaContent = "<media:content medium=\"video\" fileSize=\"" + fileSize + "\" url=\"" + url_ext + "\"";
String mime_type = file.getMimeType();
if (mime_type != null) {
mediaContent += " type=\"" + mime_type + "\"";
}
pw.println("<enclosure url=\"" + url_ext + "\" length=\"" + fileSize + (mime_type == null ? "" : "\" type=\"" + mime_type) + "\"></enclosure>");
}
String thumb_url = null;
String author = null;
String description = null;
try {
Torrent torrent = file.getSourceFile().getDownload().getTorrent();
TOTorrent toTorrent = PluginCoreUtils.unwrap(torrent);
long duration_secs = PlatformTorrentUtils.getContentVideoRunningTime(toTorrent);
if (mediaContent.length() > 0 && duration_secs > 0) {
mediaContent += " duration=\"" + duration_secs + "\"";
}
thumb_url = PlatformTorrentUtils.getContentThumbnailUrl(toTorrent);
author = PlatformTorrentUtils.getContentAuthor(toTorrent);
description = PlatformTorrentUtils.getContentDescription(toTorrent);
if (description != null) {
description = escapeMultiline(description);
/*
if ( thumb_url != null ){
pw.println( "<description type=\"text/html\">" +
escape( "<div style=\"text-align: justify;padding: 5px;\"><img style=\"float: left;margin-right: 15px;margin-bottom: 15px;\" src=\"" + thumb_url + "\"/>" ) +
description +
escape( "</div>" ) +
"</description>" );
}else{
*/
pw.println("<description>" + description + "</description>");
// }
}
} catch (Throwable e) {
}
if (mediaContent.length() > 0) {
pw.println(mediaContent += "></media:content>");
}
pw.println("<media:title>" + escape(file.getName()) + "</media:title>");
if (description != null) {
pw.println("<media:description>" + description + "</media:description>");
}
if (thumb_url != null) {
pw.println("<media:thumbnail url=\"" + thumb_url + "\"/>");
}
if (thumb_url != null) {
pw.println("<itunes:image href=\"" + thumb_url + "\"/>");
}
if (author != null) {
pw.println("<itunes:author>" + escape(author) + "</itunees:author>");
}
pw.println("<itunes:summary>" + escape(file.getName()) + "</itunes:summary>");
pw.println("<itunes:duration>" + TimeFormatter.formatColon(file.getDurationMillis() / 1000) + "</itunes:duration>");
pw.println("</item>");
} catch (Throwable e) {
Debug.out(e);
}
}
pw.println("</channel>");
pw.println("</rss>");
} finally {
if (debug) {
pw.setEnabled(false);
pw.println("</pre>");
pw.println("</BODY></HTML>");
}
}
}
}
pw.flush();
return (true);
}
use of com.biglybt.core.torrent.TOTorrent in project BiglyBT by BiglySoftware.
the class NetworkAdminSpeedTesterBTImpl method start.
/**
* The downloads have been stopped just need to do the testing.
* @param tot - Torrent recieved from testing service.
*/
public synchronized void start(TOTorrent tot) {
if (test_started) {
Debug.out("Test already started!");
return;
}
test_started = true;
// OK lets start the test.
try {
TorrentUtils.setFlag(tot, TorrentUtils.TORRENT_FLAG_LOW_NOISE, true);
Torrent torrent = new TorrentImpl(tot);
String fileName = torrent.getName();
sendStageUpdateToListeners(MessageText.getString("SpeedTestWizard.stage.message.preparing"));
// create a blank file of specified size. (using the temporary name.)
File saveLocation = AETemporaryFileHandler.createTempFile();
File baseDir = saveLocation.getParentFile();
File blankFile = new File(baseDir, fileName);
File blankTorrentFile = new File(baseDir, "speedTestTorrent.torrent");
torrent.writeToFile(blankTorrentFile);
URL announce_url = torrent.getAnnounceURL();
if (announce_url.getProtocol().equalsIgnoreCase("https")) {
SESecurityManager.setCertificateHandler(announce_url, new SECertificateListener() {
@Override
public boolean trustCertificate(String resource, X509Certificate cert) {
return (true);
}
});
}
Download speed_download = plugin.getDownloadManager().addDownloadStopped(torrent, blankTorrentFile, blankFile);
speed_download.setBooleanAttribute(speedTestAttrib, true);
DownloadManager core_download = PluginCoreUtils.unwrap(speed_download);
core_download.setPieceCheckingEnabled(false);
// make sure we've got a bunch of upload slots
core_download.getDownloadState().setIntParameter(DownloadManagerState.PARAM_MAX_UPLOADS, 32);
core_download.getDownloadState().setIntParameter(DownloadManagerState.PARAM_MAX_UPLOADS_WHEN_SEEDING, 32);
if (use_crypto) {
core_download.setCryptoLevel(NetworkManager.CRYPTO_OVERRIDE_REQUIRED);
}
core_download.addPeerListener(new DownloadManagerPeerListener() {
@Override
public void peerManagerWillBeAdded(PEPeerManager peer_manager) {
DiskManager disk_manager = peer_manager.getDiskManager();
DiskManagerPiece[] pieces = disk_manager.getPieces();
int startPiece = setStartPieceBasedOnMode(testMode, pieces.length);
for (int i = startPiece; i < pieces.length; i++) {
pieces[i].setDone(true);
}
}
@Override
public void peerManagerAdded(PEPeerManager peer_manager) {
}
@Override
public void peerManagerRemoved(PEPeerManager manager) {
}
@Override
public void peerAdded(PEPeer peer) {
}
@Override
public void peerRemoved(PEPeer peer) {
}
});
speed_download.moveTo(1);
speed_download.setFlag(Download.FLAG_DISABLE_AUTO_FILE_MOVE, true);
core_download.initialize();
core_download.setForceStart(true);
TorrentSpeedTestMonitorThread monitor = new TorrentSpeedTestMonitorThread(speed_download);
monitor.start();
// The test has now started!!
} catch (Throwable e) {
test_completed = true;
abort("Could not start test", e);
}
}
Aggregations