Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a URL regex to get the link #6

Merged
merged 2 commits into from
Oct 7, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
82 changes: 46 additions & 36 deletions githubOneboxer.user.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
/** @preserve
// ==UserScript==
// @name SE Chat Github Oneboxer
// @namespace http://stackexchange.com/users/4337810/
// @version 1.1.2
// @description Oneboxes links to Github repos, issues, or pull requests in Chat
// @author ᔕᖺᘎᕊ (http://stackexchange.com/users/4337810/)
// @match *://chat.stackoverfow.com/*
// @match *://chat.meta.stackexchange.com/*
// @match *://chat.stackexchange.com/*
// @require http://timeago.yarp.com/jquery.timeago.js
// @grant none
// ==/UserScript==
*/
// ==UserScript==
// @name SE Chat Github Oneboxer
// @namespace http://stackexchange.com/users/4337810/
// @version 1.1.2
// @description Oneboxes links to Github repos, issues, or pull requests in Chat
// @author ᔕᖺᘎᕊ (http://stackexchange.com/users/4337810/)
// @match *://chat.stackoverfow.com/*
// @match *://chat.meta.stackexchange.com/*
// @match *://chat.stackexchange.com/*
// @require http://timeago.yarp.com/jquery.timeago.js
// @grant none
// ==/UserScript==
*/
$('head').append('<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/shu8/SEChat-githubOneboxer/master/style.css">'); //add stylesheet to head (CSS from http://meta.stackexchange.com/q/243259/260841)

var urlRegex = /^(?:([^:\/?\#]+):)?(?:\/\/([^\/?\#]*))?([^?\#]*)(?:\?([^\#]*))?(?:\#(.*))?/

function replaceVars(url, details) { //Replace the {placeholders} with their actual values from the details array
return url.replace(/{username}/, details.username).replace(/{repo_name}/, details.repo_name).replace(/{issue_number}/, details.issue_number).replace(/{pull_number}/, details.pull_number);
return url.replace(/\{username}/, details.username).replace(/\{repo_name}/, details.repo_name).replace(/\{issue_number}/, details.issue_number).replace(/\{pull_number}/, details.pull_number);
}

function useApi(url, details, callback) { //use the Github API to get the info
Expand All @@ -25,27 +27,31 @@ function useApi(url, details, callback) { //use the Github API to get the info
"Accept": "application/vnd.github.VERSION.html", //to get HTML versions of body, and not markdown
"User-Agent": "shu8" //https://developer.github.com/v3/#user-agent-required
},
success: function(data) {
success: function (data) {
callback(data);
}
});
}

function extractFromUrlAndGetInfo(link, $obj) { //to avoid repetition (for existing/new messages), a function to call getInfo with correct parameters
var info = link.split('github.com')[1];
function extractFromUrlAndGetInfo(link, $obj) { //to avoid repetition (for existing/new messages), a function to call getInfo with correct parameters
var info = link.split(urlRegex)[3];
var username = info.split('/')[1],
repo_name = info.split('/')[2],
type = info.split('/')[3],
issue_number, pull_number;

if (link.indexOf('issues') > -1) { //for issues
if (type === "issues") { //for issues
issue_number = info.split('/')[4];
if (issue_number === undefined)
return;
getInfo('issue', { //get issue info via the API
username: username, //with the variables
repo_name: repo_name,
issue_number: issue_number
}, $obj); //pass on the jQuery element we need to onebox
} else if (link.indexOf('pull') > -1) { //for pull requests
} else if (type === "pull") { //for pull requests
pull_number = info.split('/')[4];
if (pull_number === undefined)
return;
getInfo('pull', { //get pull info via the API
username: username, //with the variables
repo_name: repo_name,
Expand All @@ -62,7 +68,7 @@ function extractFromUrlAndGetInfo(link, $obj) { //to avoid repetition (for exist
function getInfo(type, details, $element) {
switch (type) {
case 'issue': //for issues
useApi("https://api.github.com/repos/{username}/{repo_name}/issues/{issue_number}", details, function(data) { //sends URL with placeholders to useApi and a callback follows:
useApi("https://api.github.com/repos/{username}/{repo_name}/issues/{issue_number}", details, function (data) { //sends URL with placeholders to useApi and a callback follows:
var body = $(data.body_html).find('img').remove().end().text(), //remove images from the body
title = data.title,
number = data.number,
Expand All @@ -77,7 +83,7 @@ function getInfo(type, details, $element) {

var labelSpan = ''; //get labels and suround them with spans for their own colour
if (labels != '') {
$.each(labels, function(i, o) {
$.each(labels, function (i, o) {
labelSpan += "<span class='label' style='background-color:#" + o.color + ";'>" + o.name + "</span>";
});
}
Expand All @@ -100,7 +106,7 @@ function getInfo(type, details, $element) {
});
break;
case 'repo': //for repos
useApi("https://api.github.com/repos/{username}/{repo_name}", details, function(data) {
useApi("https://api.github.com/repos/{username}/{repo_name}", details, function (data) {
var owner = data.owner.login,
name = data.name,
description = data.description,
Expand All @@ -120,7 +126,7 @@ function getInfo(type, details, $element) {
});
break;
case 'pull': //for pull requests
useApi("https://api.github.com/repos/{username}/{repo_name}/pulls/{pull_number}", details, function(data) {
useApi("https://api.github.com/repos/{username}/{repo_name}/pulls/{pull_number}", details, function (data) {
var title = data.title,
body = $(data.body_html).find('img').remove().end().text(), //remove images from the body
number = data.number,
Expand All @@ -146,34 +152,38 @@ function getInfo(type, details, $element) {
}
}

var observer = new MutationObserver(function(mutations) { //MutationObserver; reviewed @ CR: http://codereview.stackexchange.com/a/101207/41415!
mutations.forEach(function(mutation) {
var length = mutation.addedNodes.length;
var observer = new MutationObserver(function (mutations) { //MutationObserver; reviewed @ CR: http://codereview.stackexchange.com/a/101207/41415!
mutations.forEach(function (mutation) {
var length = mutation.addedNodes.length;
for (var i = 0; i < length; i++) {
var $addedNode = $(mutation.addedNodes[i]);
if (!$addedNode.hasClass('message')) { return; } //don't run if new node is NOT a .message
if (!$addedNode.hasClass('message')) {
return;
} //don't run if new node is NOT a .message

var $lastanchor = $addedNode.find('a').last();
if (!$lastanchor) { return; } //don't run if there is no link
if (!$lastanchor) {
return;
} //don't run if there is no link

var lastanchorHref = $lastanchor.attr('href');
var lastanchorHref = $lastanchor.attr('href');
if ($addedNode.text().trim().indexOf(' ') == -1 && lastanchorHref.indexOf('github.com') > -1) { //if there are no spaces (ie. only one word) and if the link is to github...
extractFromUrlAndGetInfo(lastanchorHref, $addedNode); //pass URL and added node to the function which will go on to call useApi and add the onebox
}
}
});
});

setTimeout(function() {
$('.message').each(function() { //loop through EXISTING messages to find oneboxable messages
var link = $(this).find('a[href*="github.com"]');
setTimeout(function () {
$('.message').each(function () { //loop through EXISTING messages to find oneboxable messages
var link = $(this).find('a[href*="github.com"]');
if (!link.length || $(this).text().trim().indexOf(' ') > -1) { //if there is a link to github AND if there is no space (ie. nothing other than the link)
return;
}
}
extractFromUrlAndGetInfo(link.attr('href'), $(this)); //pass URL and message to the function which will go on to call useApi and add the onebox
});
setTimeout(function() { //use the timeago plugin to add relative times to the onebox for EXISTING messages

setTimeout(function () { //use the timeago plugin to add relative times to the onebox for EXISTING messages
$("time.timeago").timeago();
}, 1000);

Expand Down