Files
LNXSDK/leenkx/Sources/leenkx/network/torrent/TorrentClient.hx
2026-10-06 02:10:08 -07:00

408 lines
11 KiB
Haxe

package leenkx.network.torrent;
import haxe.io.Bytes;
import leenkx.network.torrent.storage.Storage;
import leenkx.network.torrent.storage.Storage.IStorage;
class TorrentClient {
public static var defaultTrackers:Array<String> = [];
public static var defaultDownloadDir:String = null;
public var downloadDir:String = null;
#if sys
static var mainQueue:sys.thread.Deque<Void -> Void> = null;
static var mainMutex:sys.thread.Mutex = null;
static var mainTimer:haxe.Timer = null;
#end
public static function initMain():Void {
#if sys
if (mainQueue != null) return;
mainQueue = new sys.thread.Deque();
mainMutex = new sys.thread.Mutex();
#end
}
public static function postMain(f:Void -> Void):Void {
#if sys
if (mainQueue == null) {
f();
return;
}
mainQueue.add(f);
mainMutex.acquire();
if (mainTimer == null) {
mainTimer = new haxe.Timer(5);
mainTimer.run = drainMain;
}
mainMutex.release();
#else
f();
#end
}
#if sys
static function drainMain():Void {
while (true) {
mainMutex.acquire();
var f = mainQueue.pop(false);
if (f == null) {
mainTimer.stop();
mainTimer = null;
mainMutex.release();
return;
}
mainMutex.release();
try {
f();
} catch(e:Dynamic) {}
}
}
#end
public var torrents:Map<String, Torrent> = [];
public var peerId:Bytes;
public var onError:String -> Void;
public var onTorrentAdded:Torrent -> Void;
public var onTorrentDone:Torrent -> Void;
public var listenPort:Int = 0;
var tcpListener:Dynamic = null;
public function new() {
initMain();
peerId = TorrentInfo.peerId();
}
public function listen(port:Int):Void {
#if (sys || kha_krom)
listenPort = port;
tcpListener = new leenkx.network.torrent.peer.TcpListener(port);
tcpListener.onPeer = function(ch, hex, key) {
var t = torrents.get(hex);
if (t == null) {
for (cand in torrents) {
if (cand.infoHashHex == hex) {
t = cand;
break;
}
}
}
if (t == null) {
ch.close();
return;
}
t.addIncomingPeer(key, ch);
};
tcpListener.onError = function(e) {
if (onError != null) onError(e);
};
tcpListener.start();
#end
}
public function add(torrentId:Dynamic, ?opts:Dynamic, ?cb:Torrent -> Void):Torrent {
if (opts != null && Reflect.isFunction(opts)) {
cb = opts;
opts = null;
}
var meta:MetaInfo = null;
var infoHash:Bytes = null;
var infoHashV2:Bytes = null;
var webSeeds:Array<String> = null;
var trackers = defaultTrackers.copy();
var name:String = null;
if (Std.isOfType(torrentId, Bytes)) {
meta = MetaInfo.fromTorrentBytes(torrentId);
infoHash = meta.infoHash;
infoHashV2 = meta.infoHashV2;
mergeTrackers(trackers, meta.announce);
} else {
var id = Std.string(torrentId);
var magnet = Magnet.parse(id);
if (magnet != null) {
infoHash = magnet.infoHash;
infoHashV2 = magnet.infoHashV2;
name = magnet.name;
webSeeds = magnet.webSeeds;
mergeTrackers(trackers, magnet.trackers);
} else if (id.length == 40 || id.length == 64) {
var bytes:Bytes = null;
try {
bytes = Bytes.ofHex(id);
} catch(e:Dynamic) {}
if (bytes == null) {
if (onError != null) {
onError("unrecognized torrent id: " + id);
}
return null;
}
if (bytes.length == 20) infoHash = bytes;
else infoHashV2 = bytes;
} else {
try {
meta = MetaInfo.fromTorrentBytes(Bytes.ofString(id));
infoHash = meta.infoHash;
infoHashV2 = meta.infoHashV2;
mergeTrackers(trackers, meta.announce);
} catch(e:Dynamic) {
if (onError != null) {
onError("unrecognized torrent id: " + id);
}
return null;
}
}
}
if (opts != null) {
var ann:Array<String> = Reflect.field(opts, "announce");
if (Reflect.field(opts, "announceOverride") == true) {
trackers = ann != null ? ann : [];
} else {
mergeTrackers(trackers, ann);
}
}
var key = infoHash != null ? Crypto.toHex(infoHash)
: (infoHashV2 != null ? "v2:" + Crypto.toHex(infoHashV2)
: null);
if (key == null) {
if (onError != null) onError("unrecognized torrent id");
return null;
}
var existing = torrents.get(key);
if (existing != null) {
if (cb != null) cb(existing);
return existing;
}
var wireHash = infoHash != null ? infoHash
: infoHashV2.sub(0, 20);
var t = new Torrent(wireHash, peerId, trackers, meta, null,
downloadDir != null ? downloadDir : defaultDownloadDir);
t.announcePort = listenPort > 0 ? listenPort
: 49152 + Std.random(16384);
t.infoHashV2 = infoHashV2;
if (infoHashV2 != null) {
t.infoHashV2Hex = Crypto.toHex(infoHashV2);
}
t.pendingWebSeeds = webSeeds;
if (name != null && meta == null) t.magnetURI = Magnet.build(
infoHash, name, trackers, webSeeds, infoHashV2);
t.on("error", function(e) {
if (onError != null) onError(e);
});
t.client = this;
torrents.set(key, t);
t.start();
if (onTorrentAdded != null) onTorrentAdded(t);
if (cb != null) cb(t);
return t;
}
public function seed(data:Dynamic, ?opts:Dynamic, ?cb:Torrent -> Void):Torrent {
if (opts != null && Reflect.isFunction(opts)) {
cb = opts;
opts = null;
}
var pair = buildPair(data, opts);
return seedMeta(pair.meta, pair.files, opts, cb);
}
public static function buildMeta(data:Dynamic, ?opts:Dynamic):MetaInfo {
return buildPair(data, opts).meta;
}
static function buildPair(data:Dynamic, ?opts:Dynamic):{
meta:MetaInfo, files:Array<{path:String, data:Bytes}>} {
var name = "leenkx";
var trackers = defaultTrackers.copy();
if (opts != null) {
var n = Reflect.field(opts, "name");
if (n != null) name = Std.string(n);
var ann:Array<String> = Reflect.field(opts, "announce");
mergeTrackers(trackers, ann);
}
var files:Array<{path:String, data:Bytes}> = [];
if (Std.isOfType(data, Bytes)) {
files.push({path: name, data: data});
} else if (Std.isOfType(data, Array)) {
for (f in (data:Array<Dynamic>)) {
var p = Reflect.field(f, "path");
var d:Bytes = Reflect.field(f, "data");
if (d == null && Reflect.field(f, "content") != null) {
d = Reflect.field(f, "content");
}
if (p != null && d != null) {
files.push({path: Std.string(p), data: d});
}
}
} else {
files.push({path: name, data: Bytes.ofString(Std.string(data))});
}
return {meta: MetaInfo.create(name, files, trackers, opts), files: files};
}
public static function readFolder(path:String, ?base:String):Array<{path:String, data:Bytes}> {
#if sys
var root = path;
while (root.length > 0 && (StringTools.endsWith(root, "/")
|| StringTools.endsWith(root, "\\"))) {
root = root.substr(0, root.length - 1);
}
if (base == null) {
var i = Std.int(Math.max(root.lastIndexOf("/"), root.lastIndexOf("\\")));
base = i >= 0 ? root.substr(i + 1) : root;
}
var files:Array<{path:String, data:Bytes}> = [];
readFolderInto(root, base, files);
return files;
#else
throw "readFolder requires a sys target";
#end
}
#if sys
static function readFolderInto(dir:String, prefix:String, files:Array<{path:String, data:Bytes}>):Void {
for (entry in sys.FileSystem.readDirectory(dir)) {
var p = dir + "/" + entry;
var rel = prefix + "/" + entry;
if (sys.FileSystem.isDirectory(p)) {
readFolderInto(p, rel, files);
} else {
files.push({path: rel, data: sys.io.File.getBytes(p)});
}
}
}
#end
public function seedMeta(meta:MetaInfo, files:Array<{path:String, data:Bytes}>, ?opts:Dynamic, ?cb:Torrent -> Void):Torrent {
var trackers = meta.announce.copy();
if (opts != null) {
var ann:Array<String> = Reflect.field(opts, "announce");
mergeTrackers(trackers, ann);
}
var ms = new MemoryStorage(meta.storageLength > 0
? meta.storageLength : meta.totalLength);
for (i in 0...files.length) {
ms.write(meta.files[i].offset, files[i].data);
}
var storage:IStorage = ms;
var wireHash = meta.infoHash != null ? meta.infoHash
: meta.infoHashV2.sub(0, 20);
var t = new Torrent(wireHash, peerId, trackers, meta, storage);
t.announcePort = listenPort > 0 ? listenPort
: 49152 + Std.random(16384);
t.markComplete();
t.on("error", function(e) {
if (onError != null) onError(e);
});
t.client = this;
torrents.set(meta.infoHashHex != null ? meta.infoHashHex
: "v2:" + meta.infoHashV2Hex, t);
t.start();
if (onTorrentAdded != null) onTorrentAdded(t);
if (onTorrentDone != null) onTorrentDone(t);
if (cb != null) cb(t);
return t;
}
public function get(id:Dynamic):Torrent {
if (Std.isOfType(id, Torrent)) return id;
if (id == null) return null;
var hex = Std.string(id);
if (StringTools.startsWith(hex, "v2:")) {
hex = hex.substr(3);
}
var t = torrents.get(hex);
if (t == null) t = torrents.get("v2:" + hex);
if (t == null) {
for (f in torrents) {
if (f.infoHashHex == hex || f.infoHashV2Hex == hex || (f.infoHash != null && Crypto.toHex(f.infoHash) == hex)) {
t = f;
break;
}
}
}
return t;
}
public static function torrentIdFor(v:Dynamic):Dynamic {
if (v == null) return null;
if (Std.isOfType(v, haxe.io.Bytes)) return v;
var s = Std.string(v);
if (s.indexOf("magnet:") == 0) return s;
if (s.indexOf("v2:") == 0) {
var h = s.substr(3);
return h.length == 64 ? "magnet:?xt=urn:btmh:1220" + h : s;
}
switch (s.length) {
case 40 | 32:
return "magnet:?xt=urn:btih:" + s;
case 64:
return "magnet:?xt=urn:btmh:1220" + s;
case 68:
return "magnet:?xt=urn:btmh:" + s;
default:
return s;
}
}
public static function trackerUrls(v:Dynamic):Array<String> {
if (v == null) return null;
var items:Array<Dynamic> = Std.isOfType(v, Array)
? (v:Array<Dynamic>) : [v];
var out:Array<String> = [];
for (item in items) {
var u:Dynamic = null;
if (!Std.isOfType(item, String)) {
try {
u = Reflect.field(item, "url");
} catch(e:Dynamic) {}
}
var s = u != null ? Std.string(u) : Std.string(item);
if (s != "" && s != "null") out.push(s);
}
return out.length > 0 ? out : null;
}
public function remove(infoHashHex:String, ?deleteData:Bool):Void {
var t = get(infoHashHex);
if (t != null) {
t.destroy();
if (deleteData) t.deleteData();
var key:String = null;
for (k in torrents.keys()) {
if (torrents.get(k) == t) { key = k; break; }
}
if (key != null) torrents.remove(key);
}
}
public static function mergeTrackers(trackers:Array<String>, urls:Array<String>):Void {
if (urls == null) return;
for (u in urls) {
if (u != null && Lambda.indexOf(trackers, u) < 0) {
trackers.push(u);
}
}
}
public function destroy():Void {
for (t in torrents) t.destroy();
torrents.clear();
#if (sys || kha_krom)
if (tcpListener != null) {
tcpListener.stop();
tcpListener = null;
}
#end
}
}