glowingbear-mainbox/js/imgur.js

79 lines
1.7 KiB
JavaScript
Raw Normal View History

2015-10-09 13:59:34 +02:00
(function() {
'use strict';
var weechat = angular.module('weechat');
weechat.factory('imgur', ['$rootScope', function($rootScope) {
2015-11-07 12:32:25 +01:00
var process = function(image, callback) {
2015-10-09 13:59:34 +02:00
// Is it an image?
if (!image || !image.type.match(/image.*/)) return;
// New file reader
var reader = new FileReader();
// When image is read
reader.onload = function (event) {
var image = event.target.result.split(',')[1];
2015-11-07 12:32:25 +01:00
upload(image, callback);
2015-10-09 13:59:34 +02:00
};
// Read image as data url
reader.readAsDataURL(image);
};
// Upload image to imgur from base64
2015-11-07 12:32:25 +01:00
var upload = function( base64img, callback ) {
2015-10-09 13:59:34 +02:00
// Set client ID (Glowing Bear)
var clientId = "164efef8979cd4b";
// Create new form data
var fd = new FormData();
fd.append("image", base64img); // Append the file
fd.append("type", "base64"); // Set image type to base64
// Create new XMLHttpRequest
var xhttp = new XMLHttpRequest();
// Post request to imgur api
xhttp.open("POST", "https://api.imgur.com/3/image", true);
// Set headers
xhttp.setRequestHeader("Authorization", "Client-ID " + clientId);
xhttp.setRequestHeader("Accept", "application/json");
// Handler for response
xhttp.onreadystatechange = function() {
// Check state and response status
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Get response text
var response = JSON.parse(xhttp.responseText);
2015-11-07 12:32:25 +01:00
// Send link as message
if( response.data && response.data.link ) {
if (callback && typeof(callback) === "function") {
callback(response.data.link);
}
}
2015-10-09 13:59:34 +02:00
}
};
// Send request with form data
xhttp.send(fd);
};
return {
process: process
};
}]);
})();