Possibly an odd question, but I'm sure someone has thought of it before :) I'm wondering if it's at all possible to verify a given string as being a theoretically valid Magnet link, using JS.
Not particularly bothered about opening the link etc. (That's done elsewhere), I'm more concerned here about weeding out broken/ truncated links.
The best I can come up with from the top of my head is a simple beginning of string match for the magnet:?xt=urn:
I suppose I could preface this with a length condition (20+ characters seems reasonable?), but does anyone have a 'better' solution?
I tried the above regular expression and it didn't work, so I created my own. I looked at the Wikipedia Magnet URI scheme which states that the magnet identifier is Base32, which means:
Base32 is a base-32 transfer encoding using the twenty-six letters A-Z and six digits 2-7. [Although my understanding is that these digits and letters can be interpolated at random].
As a result, we're looking for the following in a regex:
/magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32}/iThe beginning / and the ending / have to be there, because it's a regex, to denote the start and end, and the i at the end (/i) denotes a case-insensitive regex. If we didn't do the /i, we'd be having to check for [a-zA-Z0-9].
The final regex, which actually works, is as follows:
/magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32}/i
You can try this for yourself:
var torrent = "magnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C";
if (torrent.match(/magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32}/i) !== null)
{
console.log("It's valid, bloody fantastic!");
}
Obligatory JSFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With