Created
August 28, 2011 01:02
-
-
Save mrdaemon/1176091 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# Copyright (c) 2010, mr_daemon | |
# All rights reserved. | |
# | |
# Redistribution and use in source and binary forms, with or without | |
# modification, are permitted provided that the following conditions are met: | |
# | |
# * Redistributions of source code must retain the above copyright notice, | |
# this list of conditions, and the following disclaimer. | |
# * Redistributions in binary form must reproduce the above copyright notice, | |
# this list of conditions, and the following disclaimer in the | |
# documentation and/or other materials provided with the distribution. | |
# * Neither the name of the author of this software nor the name of | |
# contributors to this software may be used to endorse or promote products | |
# derived from this software without specific prior written consent. | |
# | |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
# POSSIBILITY OF SUCH DAMAGE. | |
### | |
import supybot.utils as utils | |
from supybot.commands import * | |
import supybot.plugins as plugins | |
import supybot.ircutils as ircutils | |
import supybot.ircmsgs as ircmsgs | |
import supybot.callbacks as callbacks | |
from poster.encode import multipart_encode, MultipartParam | |
from poster.streaminghttp import register_openers | |
import urllib2 | |
from BeautifulSoup import BeautifulSoup as bs | |
from tempfile import NamedTemporaryFile | |
import mimetypes | |
IMAGEBOARD_POST = 'http://glasnost.underwares.org/imageboard.php?stage=2' | |
IMAGEBOARD_GET = 'http://glasnost.underwares.org/imageboard.php?search=iwakura' | |
IMAGEBOARD_URLBASE = 'http://glasnost.underwares.org/images/' | |
USER_AGENT = "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 " \ | |
"(KHTML, like Gecko) Ubuntu/10.10 Chromium/8.0.552.28" | |
def get_image(url, handle): | |
""" Fetch URL and write to handle """ | |
request = urllib2.Request(url) | |
request.add_header('User-Agent', USER_AGENT) | |
opener = urllib2.build_opener() | |
image = opener.open(request).read() | |
handle.write(image) | |
handle.flush() # Actually necessary | |
def post_image(fname, imagefilehandle): | |
"""Post image to imageboard""" | |
register_openers() | |
# The doc for poster says that if you don't set 'filetype', | |
# a default one will be set -- and the default one will *not* | |
# be liked by anyone. It's basically plain text. | |
ftype = mimetypes.guess_type(imagefilehandle.name)[0] | |
imagedata = MultipartParam('file', filename=fname, | |
filetype=ftype, | |
fileobj=imagefilehandle) | |
params = [ | |
('username','iwakura'), | |
('MAX_FILE_SIZE','52428800'), # Knifa is a butt | |
imagedata, | |
('tags','imagecache nsfw'), | |
('submit','Upload!'), # Double-butt, even | |
] | |
datagen, headers = multipart_encode(params) | |
request = urllib2.Request(IMAGEBOARD_POST, datagen, headers) | |
# This is the buttiest. I'm sorry. Feel free to rewrite. | |
try: | |
result = urllib2.urlopen(request) | |
if result.geturl() == IMAGEBOARD_POST: | |
''' | |
Damn you Knifa! | |
On POST failure, the board will redirect to the | |
action form. On success, to imageboard.php. | |
So this the only way to figure out if that actually | |
worked. | |
''' | |
print result.read() | |
return False | |
else: | |
return True | |
except Exception as excinst: | |
#FIXME: Move all of this as class methods | |
# and then log the exception using | |
# self.log.warning(excinst) | |
return False | |
def get_board_url(original_filename): | |
scraped = bs(urllib2.urlopen(IMAGEBOARD_GET)) | |
for postedimage in scraped.findAll("img"): | |
imgtitle = "%(alt)s" % postedimage | |
if imgtitle == original_filename: | |
new_filename = postedimage['src'].split("/")[-1] | |
return IMAGEBOARD_URLBASE + new_filename | |
return None | |
class GlasnostImgCache(callbacks.Plugin): | |
"""Add the help for "@plugin help GlasnostImgCache" here | |
This should describe *how* to use this plugin.""" | |
threaded = True | |
def doPrivmsg(self, irc, msg): | |
channel = msg.args[0] | |
if irc.isChannel(channel): | |
if ircmsgs.isAction(msg): | |
text = ircmsgs.unAction(msg) | |
else: | |
text = msg.args[1] | |
fileexts = ('.jpg','.jpeg','.gif','.png') | |
for url in utils.web.urlRe.findall(text): | |
if url.lower().endswith(fileexts): | |
original_filename = url.split('/')[-1] | |
# Split name and extension for temporary file | |
# This serves no real purpose other than identifying the | |
# temp file should something go horribly wrong. | |
ofile = original_filename.split('.')[-2] | |
oext = "." + original_filename.split('.')[-1] | |
# Temporary file | |
f = NamedTemporaryFile('r+b', prefix=ofile, suffix=oext) | |
try: | |
get_image(url, f) | |
if post_image(original_filename, f): | |
# Image URL is located and constructed using a | |
# metric fuckton of voodoo and WTF inducing checks | |
# based on the uploaded filename. | |
cachedurl = get_board_url(original_filename) | |
if cachedurl: | |
irc.reply("Posted to imageboard: %s" % | |
(cachedurl), prefixNick=False) | |
else: | |
irc.reply("I posted %s to the imageboard," \ | |
" but it sounds like Knifa's shit" \ | |
" ate it :( -- Sorry." % | |
(original_filename), prefixNick=False) | |
except Exception as excinst: | |
irc.reply("I couldn't cache %s because: %s" % | |
(original_filename, excinst), | |
prefixNick=False) | |
finally: | |
# Tempfile gets wiped on close. | |
f.close() | |
Class = GlasnostImgCache | |
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment