{"size": 1483, "ext": "js", "max_stars_repo_path": "lib/mediatypes/youtube.js", "max_stars_repo_name": "orktes/irc-watcher", "max_stars_repo_stars_event_min_datetime": "2015-04-29T02:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-29T02:30:10.000Z", "max_issues_repo_path": "lib/mediatypes/youtube.js", "max_issues_repo_name": "orktes/irc-watcher", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mediatypes/youtube.js", "max_forks_repo_name": "orktes/irc-watcher", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.5192307692, "max_line_length": 164, "alphanum_fraction": 0.6041807148}
var request = require('request');

function getIdFromUrl(url) {
  var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
	var match = url.match(regExp);
	if (match&&match[7].length==11){
	    return match[7];
	}else{
	    return null;
	}

}

function getVideoDataById(id, callback) {
  request('http://gdata.youtube.com/feeds/api/videos/' + id + '?alt=json&v=2', function (err, res, body) {
    if (err) {
      callback(err);
      return;
    }

    var data;

    try {
      data = JSON.parse(body);
    } catch (e) {
      callback(e);
      return;
    }

    var metadata = {};
    metadata.title = data.entry.title['$t'];
    metadata.author = data.entry.author[0].name['$t'];
    metadata.description = data.entry['media$group']['media$description']['$t'];
    metadata.id = id;
    metadata.published = new Date(data.entry.published['$t']);
    metadata.updated = new Date(data.entry.updated['$t']);
    metadata.content = {type: "iframe", src:'<iframe width="560" height="315" src="http://www.youtube.com/embed/'+id+'" frameborder="0" allowfullscreen></iframe>'};
    metadata.thumbnail = "http://i.ytimg.com/vi/" + id + "/hqdefault.jpg"
    callback(null, metadata);

  });
}


var type = exports = module.exports = {};
type.name = "youtube";
type.check = function (url, callback) {
  return callback(null, (getIdFromUrl(url) != null));
};
type.metadata = function (url, callback) {
  getVideoDataById(getIdFromUrl(url), callback);
};