import requests
import json
import urllib
import os
import glob
import tumblpy
import shutil
import re
import pysftp
import pyimgur
import cStringIO
from PIL import Image
import webbrowser
from IPython.display import display
from IPython.display import Image as imaged
import win32clipboard
def addToClipBoard(text):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
class Sharer(object):
def __init__(self):
self.site_url = ''
self.img_irl = ''
self.title = ''
self.comment = ''
self.platform = '' #########################
self.folder = ''
#for tumblr
self.tum = tumblpy.Tumblpy('TOKEN',
'TOKEN',
'TOKEN',
'TOKEN')
self.tumblogs = {'pr':'http://INSERT HERE.tumblr.com/',
'cc':'http://INSERT HERE.tumblr.com/',
'pv':'http://INSERT HERE.tumblr.com/',
'vs':'http://INSERT HERE.tumblr.com/'}
self.tumresp = ''
self.tumblog = ''
self.tumbltags = ''
#for sftp
self.sftpconn = pysftp.Connection('STFP SITE HERE',
username='INSERT HERE', password='INSERT HERE')
self.sftpconn.get('sked/sched.json', 'C:/api/sked/sched.json')
self.sftpconn.get('sked/thedict.json', 'C:/api/sked/thedict.json')
self.sftpconn.get('sked/errlog.txt', 'C:/api/sked/errlog.txt')
delete_globs()
def show_constants(self):
print 'image irl = ', self.img_irl
print 'title = ', self.title
print 'comment = ', self.comment
def change(self, what, to=''):
if what=='img_irl':
self.img_irl=to
elif what=='title':
self.title=to
elif what=='comment':
self.comment=to
else: print 'invalid change'
def tumblit(self, tblog = '', tumcomment='', tags='', state='queue', removal=True):
""" state=queue (default) or published. Caption can have html """
if tblog == '':
if self.tumblog == '':
self.tumblog = raw_input("Tumblr (pr, cc, pv, vs): ")
else:
self.tumblog = tblog
if tags != '':
self.tumbltags = tags
if self.platform == 'glob':
choice = 'f'
else:
choice='u'
if choice == "f":
photo = open(self.img_irl, 'rb')
if self.tumblog=='cc':
self.tumresp = self.tum.post('post', blog_url=self.tumblogs[self.tumblog],
params={'type':'photo',
'state':state,
'caption': tumcomment,
'tags':self.tumbltags,
'data': photo})
else:
self.tumresp = self.tum.post('post', blog_url=self.tumblogs[self.tumblog],
params={'type':'photo',
'state':state, 'tweet':'off',
'caption': tumcomment,
'tags':self.tumbltags,
'data': photo})
elif choice == "u":
if self.tumblog=='cc':
self.tumresp = self.tum.post('post', blog_url=self.tumblogs[self.tumblog],
params={'type':'photo',
'state':state,
'caption': tumcomment,
'tags':self.tumbltags,
'source': self.img_irl})
else:
self.tumresp = self.tum.post('post', blog_url=self.tumblogs[self.tumblog],
params={'type':'photo',
'state':state, 'tweet':'off',
'caption': tumcomment,
'tags':self.tumbltags,
'source': self.img_irl})
print "Tumblr response:", self.tumresp # returns id if posted successfully
if removal == True:
self.getridofit()
def redditit(self, title='', sub=[''], comment='', when='', removal=True, overrideurl=''):
subreddits = ["gifs", "comicbooks", "pics", "dataisbeautiful",
"montreal", "funny", "Art", "gifs", "woahdude",
"FullMovieGifs", "HistoryPorn", "MapPorn",
"canada"]
sched = json.loads( open('C:/api/sked/sched.json', 'r').read() )
thedict = json.loads( open('C:/api/sked/sched.json', 'r').read() )
tocontinue = False
tocontinue2 = True
print sub,
for subr in sub:
print subr,
if subr in subreddits:
print "!"
tocontinue = True
if tocontinue == False:
continuestr = raw_input('subreddit not in list. Continue? Y/n: ')
if continuestr in ['Y', 'y']:
tocontinue = True
if tocontinue == True and overrideurl == '':
resolution = ''
if self.platform == 'glob':
im = pyimgur.Imgur('TOKEN', 'TOKEN')
theupload = im.upload_image(path=self.img_irl)
url = theupload.link
pilimg=Image.open(self.img_irl)
resolution = ' [' + str(pilimg.size[0]) + 'x' + str(pilimg.size[1]) + ']'
else:
im = pyimgur.Imgur('TOKEN', 'TOKEN')
theupload = im.upload_image(url=self.img_irl)
url = theupload.link
if sub[-4:] == 'Porn':
if resolution == '':
pilfile = cStringIO.StringIO(urllib.urlopen('http://1.bp.blogspot.com/-RF8eKDAe6TQ/U9vivlxnmHI/AAAAAAAAAwE/lSmBjDLa3R4/s1600/CMQ6Zgm.jpg').read())
pilimg = Image.open(pilfile)
resolution = ' [' + str(pilimg.size[0]) + 'x' + str(pilimg.size[1]) + ']'
title += resolution
#check karma decay
imgur_suffix = url[7:]
kd_url = "http://www.karmadecay.com/" + imgur_suffix
import urllib2
kd_req = urllib2.Request(kd_url, headers={'User-Agent' : "Magic Browser"})
kd_conn = urllib2.urlopen( kd_req )
kd_html = kd_conn.read()
kd_found = kd_html.find("No very similar images were found.")
if kd_found == -1:
webbrowser.open(kd_url)
continuestr = raw_input('Karma Decay found image. Continue? Y/n: ')
if continuestr not in ['Y', 'y']:
tocontinue2 = False
if tocontinue == True and tocontinue2 == True:
td = {}
if overrideurl != '':
td['url'] = overrideurl
else:
td['url'] = url
td['title'] = title
td['comment']=comment
td['when']=when
td['sub']=sub
sched.append(td)
with open('C:/api/sked/sched.json', 'w+') as f: # write json to list of dicts
f.write(json.dumps(sched))
self.sftpconn.put('C:/api/sked/sched.json', 'sked/sched.json')
if removal == True:
self.getridofit()
def downloadit(self, fb=False):
filename = raw_input("Enter filename, or enter to use irl name:")
thepath = 'C:/api/'
if fb ==True:
thefolder = 'fb'
else:
thefolder = raw_input("Folder name, enter for root, any single char for same as last time")
if len(thefolder) == 1:
thefolder = self.folder
print 'Saving to ' + thepath + thefolder
if len(thefolder) > 0:
thepath = thepath + thefolder
self.folder = thefolder
if not os.path.isdir(thepath): # creates path if it does not exist
os.makedirs(thepath)
if filename == "":
filename = self.img_irl.rsplit('\\', 1)[-1]
filename = filename.rsplit('/', 1)[-1]
else:
filename = filename + self.img_irl[-4:]
print filename
print thepath
print thefolder
thepath = thepath + '/' + filename
print thepath
if self.platform == 'glob':
print self.img_irl, thepath
os.rename(self.img_irl, thepath)
else:
urllib.urlretrieve(self.img_irl, thepath)
self.nextit()
def googlit(self):
toclip = self.img_irl
if self.platform == 'glob':
toclip = toclip.rsplit('\\', 1)[-1]
toclip = toclip.rsplit('/', 1)[-1]
addToClipBoard(toclip)
webbrowser.open('https://images.google.com/')
def __str__(self):
return self.showconstants()
class Pocket(Sharer):
def __init__(self):
Sharer.__init__(self)
self.request = requests.post("https://getpocket.com/v3/get",
params={'consumer_key':'TOKEN',
'access_token':'TOKEN',
'state':'unread', 'sort':'newest',
'detailType':'complete'})
assert self.request.status_code == 200
self.json = json.loads(self.request.text)['list']
self.entry_ids = list(self.json.keys())
self.entry_ids_n = len(self.entry_ids)
self.entry_pos = 0
self.init_entry()
self.platform = 'pocket'
def init_entry(self):
self.entry_c = self.json[self.entry_ids[self.entry_pos]]
self.entry_c_imgs = []
dimens = []
if 'images' in self.entry_c.keys():
for key in self.entry_c['images'].keys():
self.entry_c_imgs.append(key)
dimens.append((int(self.entry_c['images'][key]['width'])+1) * (int(self.entry_c['images'][key]['height'])+1))
self.entry_c_img_pos = dimens.index(max(dimens))
self.entry_c_img_n = len(self.entry_c_imgs)
self.title = self.entry_c['resolved_title']
self.site_url = self.entry_c['resolved_url']
if len(self.entry_c_imgs) > 0:
self.img_irl = self.entry_c['images'][self.entry_c_imgs[self.entry_c_img_pos]]['src']
self.showit()
def showit(self):
print "Post {} of {}".format(self.entry_pos + 1, self.entry_ids_n)
print "[ %s ]" % (self.entry_c['resolved_title'])
self.show_constants()
if len(self.entry_c_imgs) == 0:
print "No images."
else:
print "Image: {} of {}: {}".format(self.entry_c_img_pos + 1, self.entry_c_img_n,
self.entry_c['images'][self.entry_c_imgs[self.entry_c_img_pos]]['src'])
display(imaged(url=self.entry_c['images'][self.entry_c_imgs[self.entry_c_img_pos]]['src']))
if len(self.entry_c_imgs) > 1:
print "Other images:"
for pos in range(self.entry_c_img_n):
if pos != self.entry_c_img_pos:
print self.entry_c['images'][self.entry_c_imgs[pos]]['src']
display(imaged(url=self.entry_c['images'][self.entry_c_imgs[pos]]['src']))
else:
print self.entry_c['images'][self.entry_c_imgs[pos]]['src']
print "[CURRENT IMAGE]"
def next_image(self):
if len(self.entry_c_imgs) > 1:
self.entry_c_img_pos = (self.entry_c_img_pos + 1) % self.entry_c_img_n
self.showit()
def previous_image(self):
if len(self.entry_c_imgs) > 1:
self.entry_c_img_pos = (self.entry_c_img_pos - 1) % self.entry_c_img_n
self.showit()
def nextit(self):
self.entry_pos = (self.entry_pos + 1) % self.entry_ids_n
self.init_entry()
def previt(self):
self.entry_pos = (elf.sentry_pos - 1) % self.entry_ids_n
self.init_entry()
def getridofit(self):
to_archive = self.entry_ids[self.entry_pos]
arch_json_text = "[{\"action\":\"archive\",\"item_id\":" + to_archive + "}]"
arch_request = requests.post("https://getpocket.com/v3/send",
params={'consumer_key':'TOKEN',
'access_token':'TOKEN',
'actions':arch_json_text})
assert arch_request.status_code == 200
self.nextit()
class Globit(Sharer):
def __init__(self):
Sharer.__init__(self)
self.pos_c = 0
self.globlist = glob.glob("C:/api/*.jpg") + glob.glob("C:/api/*.png") + glob.glob("C:/api/*.gif")
self.glob_n = len(self.globlist)
self.glob_pos = 0
self.showit()
self.platform = 'glob'
def showit(self):
self.img_irl = self.globlist[self.glob_pos]
print self.glob_pos, "of", self.glob_n
print self.globlist[self.glob_pos]
self.show_constants()
if self.globlist[self.glob_pos][:-4] == '.gif':
print '### opening in external applicatipn ###'
external()
nextit()
else:
try:
display(imaged(self.globlist[self.glob_pos]))
except:
print '\n##############################\nDisplay error\n##############################'
def external(self):
os.system("start \""+self.img_irl+"\"")
def rename(self):
newname = raw_input("Enter new name: ")
newname += self.globlist[self.glob_pos][-4:]
os.rename(self.globlist[self.glob_pos], newname)
self.nextit()
self.showit()
def getridofit(self):
os.close(os.open(self.img_irl, os.O_RDONLY))
del_dict = json.loads( open('C:/api/sked/thedict.json', 'r').read() )
del_list = del_dict['glob_to_delete']
del_list.append(self.img_irl)
del_dict['glob_to_delete'] = del_list
with open('C:/api/sked/thedict.json', 'w+') as f:
f.write(json.dumps(del_dict))
import pysftp
sftpconn = pysftp.Connection('STFP SITE HERE',
username='INSERT HERE', password='INSERT HERE')
sftpconn.put('C:/api/sked/thedict.json', 'sked/thedict.json')
delete_globs()
self.nextit()
def nextit(self):
self.glob_pos = (self.glob_pos + 1) % self.glob_n
self.showit()
def previt(self):
self.glob_pos = (self.glob_pos - 1) % self.glob_n
self.showit()
class Tumblit(Sharer):
def __init__(self):
Sharer.__init__(self)
self.tumlikes = self.tum.post('user/likes')['liked_posts']
self.n_entries = len(self.tumlikes)
self.entry_pos = 0
self.theid = ''
self.reblog = ''
self.platform = 'tumblr'
self.init_entry()
def init_entry(self):
self.entry_c = self.tumlikes[self.entry_pos]
self.entry_c_imgs = self.entry_c['photos']
self.entry_c_imgs_n = len(self.entry_c_imgs)
self.entry_c_imgs_pos = 0
if 2>1:
self.title = self.entry_c['caption']
self.title = re.sub('<.?>', '', self.title)
self.theid = self.entry_c['id']
self.reblog = self.entry_c['reblog_key']
if len(self.entry_c_imgs) > 0:
self.img_irl = self.entry_c_imgs[self.entry_c_imgs_pos]['original_size']['url']
else:
self.img_irl = ''
self.showit()
def showit(self):
print "Post {} of {}".format(self.entry_pos + 1, self.n_entries)
self.show_constants()
self.show_images()
def show_images(self):
if len(self.entry_c_imgs) == 0:
print "No images."
else:
print "Image: {} of {}: {}".format(self.entry_c_imgs_pos + 1, self.entry_c_imgs_n,
self.entry_c_imgs[self.entry_c_imgs_pos]['original_size']['url'])
display(imaged(url=self.entry_c_imgs[self.entry_c_imgs_pos]['original_size']['url']))
if 2>1:
print "Other images:"
for pos in range(self.entry_c_imgs_n):
if pos != self.entry_c_imgs_pos:
print self.entry_c_imgs[pos]['original_size']['url']
todisp = display(imaged(url=self.entry_c_imgs[pos]['original_size']['url']))
else:
print self.entry_c_imgs[pos]['original_size']['url']
print "[CURRENT IMAGE]"
def next_image(self):
if self.entry_c_imgs_n > 1:
self.entry_c_imgs_pos = (self.entry_c_imgs_pos + 1) % self.entry_c_imgs_n
self.show_images()
def previous_image(self):
if self.entry_c_imgs_n > 1:
self.entry_c_imgs_pos = (self.entry_c_imgs_pos - 1) % self.entry_c_imgs_n
self.show_images()
def nextit(self):
self.entry_pos = (self.entry_pos + 1) % self.n_entries
self.init_entry()
def previt(self):
self.entry_pos = (elf.sentry_pos - 1) % self.n_entries
self.init_entry()
def getridofit(self):
self.tum.post('user/unlike', params={'id': self.theid, 'reblog_key': self.reblog})
self.nextit()