Skip to content

Instantly share code, notes, and snippets.

@rlemon

rlemon/autobin.js

Last active Aug 29, 2015
Embed
What would you like to do?
auto bin gifs.
// ==UserScript==
// @name SO Chat room gif autobinner
// @author Robert Lemon
// @version 0.0.32
// @namespace
// @description make rooms not suffer gifs
// @include http://chat.stackoverflow.com/rooms/*
// ==/UserScript==
(function(global) {
"use strict";
var socket, roomid, destinationid, url, timeout;
timeout = 30000; // ms before binning.
destinationid = 61037; // gif bin
roomid = Number(/\d+/.exec(location)[0]);
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)) {
var tmp = document.createElement('div');
tmp.innerHTML = evt.content;
if (tmp.querySelectorAll('.ob-image').length && tmp.querySelector('img').src.slice(-3).toLowerCase() === 'gif') {
console.log('found gif', evt);
var oUrl = tmp.querySelector('img').src;
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: '[gif](' + oUrl + ') from ' + evt.user_name + ' was [moved](http://chat.stackoverflow.com/rooms/' + destinationid +')',
fkey: fkey().fkey
});
}, 2000);
});
}, timeout);
}
}
}
}(window));
@darkyen

This comment has been minimized.

Copy link

@darkyen darkyen commented Jan 14, 2015

+1

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.