Skip to content

Instantly share code, notes, and snippets.

@Jhawins

Jhawins/autobin.js

Forked from rlemon/autobin.js
Last active Aug 29, 2015
Embed
What would you like to do?
// ==UserScript==
// @name SO Chat room gif autobinner
// @author Robert Lemon
// @version 0.0.31
// @namespace
// @description make rooms not suffer gifs
// @include http://chat.stackoverflow.com/rooms/*
// ==/UserScript==
(function(global) {
"use strict";
var socket, roomid, destinationid, url, timeout, timeouts;
timeout = 30000; // ms before binning.
destinationid = 61037; // gif bin
roomid = Number(/\d+/.exec(location)[0]);
timeouts = [];
connect();
function connect() {
$.post('/ws-auth', fkey({
roomid: roomid
})).done(function(data) {
url = data.url;
poll();
});
}
function poll() {
socket = new WebSocket(url + '?l=' + Date.now());
socket.onmessage = ondata;
socket.onclose = onclose;
}
function ondata(data) {
var frame = JSON.parse(data.data);
for (var room in frame) {
if ('e' in frame[room]) {
processevent(frame[room].e[0]);
}
}
}
function onclose() {
socket.close();
socket = null;
setTimeout(poll, 1000 * 10);
}
function processevent(evt) {
if (evt.room_id === roomid && (evt.event_type === 1 || evt.event_type === 2)) {
// sorry not sorry jQuery
// if there's already a timeout return that timeout otherwise false
var existing = ($.inArray(evt.message_id, timeouts) > -1 && timeouts[evt.message_id]);
var tmp = document.createElement('div');
// check for gif true or false
var hasGif = tmp.querySelectorAll('.ob-image').length && tmp.querySelector('img').src.slice(-3).toLowerCase() === 'gif';
tmp.innerHTML = evt.content;
// rather weird seeing Gif capitalized?
if (hasGif && !existing) {
console.log('found gif', evt);
var oUrl = tmp.querySelector('img').src;
// store timeout in case we need to cancel
timeouts[evt.message_id] = setTimeout(function sendmessage() {
$.post("/admin/movePosts/" + roomid, fkey({
ids: [evt.message_id],
to: destinationid
})).fail(function() { // sometimes we 409.
setTimeout(sendmessage, 3000);
}).done(function() {
setTimeout(function() { // nasty -- we have to wait for the latest ID to make it back to the DOM
var id = [].slice.call(document.querySelectorAll('.user-container.mine .messages .message')).pop().id.match(/(\d+)/)[0];
if (!id) return; // so I don't blow up. this should never fail tho.
$.post('/messages/' + id, {
text: evt.user_name + ' posted ' + oUrl + ' but it was moved to http://chat.stackoverflow.com/rooms/' + destinationid + ' because gifs get annoying fast.',
fkey: fkey().fkey
});
}, 2000);
});
}, timeout);
} else if (existing && !hasGif) { // that makes sense, right?
clearTimeout(existing);
return; // done
}
}
}
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.