Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to verifiy a magnet link (Javascript)

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?

like image 622
leezer3 Avatar asked Oct 24 '25 16:10

leezer3


1 Answers

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:

  • The word magnet followed by a semicolon, a questionmark and an "xt=urn:" string
    • /magnet:\?xt=urn:
  • Any number of letters/numbers up to the next colon (the question's regex fails this)
    • [a-z0-9]+:
  • From our research above, 32 characters (base32) of interpolated letters and numbers
    • [a-z0-9]{32}/i

The 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.

like image 69
Jimbo Avatar answered Oct 27 '25 05:10

Jimbo