Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bosconian-dynamics/8447974 to your computer and use it in GitHub Desktop.
Save bosconian-dynamics/8447974 to your computer and use it in GitHub Desktop.
A couple functions using the LongURL API v2 to generate a regular expression string to match virtually any shortened URL, resulting in something similar to http://gist.github.com/KuroTsuto/8448070
// Grab the shortened URL services from api.longurl.org/v2/services, generate a regex pattern for all
function generateShortenedURLRegEx( fn_callback ) {
longURLAPICall( "services", {}, function( data ) {
var regExString = "(?:https?:\\/\\/)?(?:";
var serviceCount = 0;
var regExp;
for( var service in data ) {
if( data.hasOwnProperty( service ) ) {
if( service.charAt( service.length - 1 ) == '.' )
continue; // Ignore the weird domains that end with a dot and don't specify a TLD... @TODO: ask LongURL what these domains are supposed to imply
if( ++serviceCount > 1 )
regExString += "|";
if( data[ service ].regex == "" ) {
regExString += "(?:" + data[ service ].domain.replace( ".", "\\." ) + ")";
}
else
regExString += "(" + data[ service ].regex + ")";
}
}
regExString += ")\\/[a-z0-9]*";
fn_callback( regExString );
} );
};
function longURLAPICall( str_endpoint, ob_data, fn_callback ) {
var xhr = new XMLHttpRequest();
var url = "http://api.longurl.org/v2/" + str_endpoint;
var async = fn_callback != undefined && fn_callback instanceof Function;
var datastring = "";
var datacount = 0;
if( ob_data == undefined || typeof ob_data == "undefined" || ! ob_data instanceof Object )
ob_data == {};
ob_data.format = "json";
for( var key in ob_data ) {
if( ob_data.hasOwnProperty( key ) ) {
if( ++datacount > 1 )
datastring += "&";
else
datastring += "?";
datastring += key + "=" + encodeURIComponent( ob_data[ key ] );
}
}
url += datastring;
if( async ) {
xhr.responseType = "json";
xhr.onreadystatechange = function( e ) {
if( xhr.readyState == 4 ) {
if( xhr.status >= 200 && xhr.status < 300 ) {
fn_callback( xhr.response );
}
else {
console.log( "Error: LongURL API returned HTTP status code " + xhr.status + " with the text, \"" + xhr.statusText + "\"" );
}
}
};
}
xhr.open( "GET", url, async );
xhr.setRequestHeader( "user_agent", "GitHubGist8447974/0.0.3" );
xhr.send();
if( !async ) {
if( xhr.readyState == 4 ) {
if( xhr.status >= 200 && xhr.status < 300 ) {
return JSON.parse( xhr.response );
}
else {
console.log( "Error: LongURL API returned HTTP status code " + xhr.status + " with the text, \"" + xhr.statusText + "\"" );
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment