Skip to content

Instantly share code, notes, and snippets.

@Swader
Last active December 30, 2015 13:08
Show Gist options
  • Save Swader/7833383 to your computer and use it in GitHub Desktop.
Save Swader/7833383 to your computer and use it in GitHub Desktop.
Background.js part 2
"use strict";
var Base64 = {_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (r) {
var t, e, a, o, h, n, C, c = "", i = 0;
for (r = Base64._utf8_encode(r); i < r.length;)t = r.charCodeAt(i++), e = r.charCodeAt(i++), a = r.charCodeAt(i++), o = t >> 2, h = (3 & t) << 4 | e >> 4, n = (15 & e) << 2 | a >> 6, C = 63 & a, isNaN(e) ? n = C = 64 : isNaN(a) && (C = 64), c = c + this._keyStr.charAt(o) + this._keyStr.charAt(h) + this._keyStr.charAt(n) + this._keyStr.charAt(C);
return c
}, _utf8_encode: function (r) {
r = r.replace(/\r\n/g, "\n");
for (var t = "", e = 0; e < r.length; e++) {
var a = r.charCodeAt(e);
128 > a ? t += String.fromCharCode(a) : a > 127 && 2048 > a ? (t += String.fromCharCode(192 | a >> 6), t += String.fromCharCode(128 | 63 & a)) : (t += String.fromCharCode(224 | a >> 12), t += String.fromCharCode(128 | 63 & a >> 6), t += String.fromCharCode(128 | 63 & a))
}
return t
}};
/**
* Flag to define whether or not logging is active
* @type {boolean}
*/
const CONSOLE_LOGGING = false;
/**
* Logging function that replaces console.log
* @param val
*/
function clog(val) {
if (CONSOLE_LOGGING) {
console.log(val);
}
}
/**
* Returns an array of common elements from both arrays
* @param array
* @returns {Array}
*/
Array.prototype.intersect = function (array) {
return this.filter(function (n) {
return array.indexOf(n) != -1
});
};
/**
* Removes duplicate elements from the array
*/
Array.prototype.unique = function () {
var result = [];
var len = this.length;
while (len--) {
if (result.indexOf(this[len]) == -1) {
result.push(this[len]);
}
}
this.length = 0;
len = result.length;
while (len--) {
this.push(result[len]);
}
};
/**
* Returns an array - the difference between the two provided arrays.
* If the mirror parameter is undefined or true, returns only left-to-right difference.
* Otherwise, returns a merge of left-to-right and right-to-left difference.
* @param array {Array}
* @param mirror
* @returns {Array}
*/
Array.prototype.diff = function (array, mirror) {
var current = this;
mirror = (mirror === undefined);
var a = current.filter(function (n) {
return array.indexOf(n) == -1
});
if (mirror) {
return a.concat(array.filter(function (n) {
return current.indexOf(n) == -1
}));
}
return a;
};
/**
* Iterates through children of the item with ID: {id} and calls callback with
* first child of a matching title, or false.
* @param id
* @param title
* @param callback
*/
chrome.bookmarks.getFirstChildByTitle = function (id, title, callback) {
chrome.bookmarks.getChildren(id, function (children) {
var iLength = children.length;
while (iLength--) {
var item = children[iLength];
if (item.title == title) {
return callback(item);
}
}
return callback(false);
});
};
/**
* Iterates through children of the item with ID: {id} and calls callback with
* first child of a matching URL, or false
* @param id
* @param url
* @param callback
*/
chrome.bookmarks.getFirstChildByUrl = function (id, url, callback) {
chrome.bookmarks.getChildren(id, function (children) {
var iLength = children.length;
while (iLength--) {
var item = children[iLength];
if (item.hasOwnProperty('url') && item.url == url) {
return callback(item);
}
}
return callback(false);
});
};
/**
* Makes a basic Base64 encoded auth header for basic HTTP authentication requests
* @param user
* @param password
* @returns {string}
*/
function make_basic_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
var user = 'user';
var password = 'pass';
var auth = make_basic_auth(user, password);
var rootUrl = "https://secure.diigo.com/api/v2/bookmarks?key=KEY&";
var possibleErrors = {
400: 'Bad Request: Some request parameters are invalid or the API rate limit is exceeded.',
401: 'Not Authorized: Authentication credentials are missing or invalid.',
403: 'Forbidden: The request has been refused because of the lack of proper permission.',
404: 'Not Found: Either you\'re requesting an invalid URI or the resource in question doesn\'t exist (e.g. no such user).',
500: 'Internal Server Error: Something is broken.',
502: 'Bad Gateway: Diigo is down or being upgraded.',
503: 'Service Unavailable: The Diigo servers are too busy to server your request. Please try again later.',
other: 'Unknown error. Something went wrong.'
};
var doRequest = function () {
var xml = new XMLHttpRequest();
xml.open('GET', rootUrl + "&count=100&filter=all&user=" + user);
xml.setRequestHeader('Authorization', auth);
xml.send();
xml.onreadystatechange = function () {
if (xml.readyState === 4) {
if (xml.status === 200) {
process(JSON.parse(xml.responseText));
} else {
if (possibleErrors[xml.status] !== undefined) {
console.error(xml.status + ' ' + possibleErrors[xml.status]);
} else {
console.error(possibleErrors.other);
console.error(xml.status);
}
}
}
};
};
var process = function(response) {
var iLength = response.length;
var allTags = [];
var rootBookmarks = [];
if (iLength) {
console.info(iLength + " bookmarks were found.");
var i = iLength;
while (i--) {
var item = response[i];
if (item.tags !== undefined && item.tags != "") {
var tags = item.tags.split(',');
if (tags.indexOf('bbs-root') > -1) {
rootBookmarks.push(item);
}
allTags = allTags.concat(tags);
}
}
allTags.unique();
allTags.sort();
var folderName = 'Diigo #BBS';
chrome.bookmarks.getFirstChildByTitle("1", folderName, function(value) {
if (value === false) {
chrome.bookmarks.create({
parentId: "1",
title: folderName
}, function (folder) {
console.log(folderName + " not found and has been created at ID " + folder.id);
});
}
});
} else {
console.info("Response is empty - there are no bookmarks?");
}
};
doRequest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment