Browse Source

Open sauced this shit, also made it use a conf file =]

Wazakindjes 6 years ago
parent
commit
97bb10e601
1 changed files with 284 additions and 0 deletions
  1. 284 0
      hurr.py

+ 284 - 0
hurr.py

@@ -0,0 +1,284 @@
+#!/usr/bin/python
+import ConfigParser
+import datetime
+import gntp.notifier
+import os
+import paramiko
+import pyperclip
+import random
+import re
+import string
+import sys
+import threading
+import time
+
+OLDFILES = OLDFILES_ALT = OLDFILES_DB = []
+AMOUNT = 0
+SSH = None
+GROWL = None
+MUHCONF = {
+	'growlname': None,
+	'icondir': None,
+	'sshdir': None,
+	'remotebase': None,
+	'urlbase': None,
+	'scrotdir': None,
+	'scrotpattern': None,
+	'server': None,
+	'joeser': None,
+	'archivebase': '',
+	'archivecount': 0,
+	'archivewait': 0,
+	'archivetime': 0,
+	'scrotdir_alt': '',
+	'scrotpattern_alt': '',
+	'scrotdir_db': '',
+	'scrotpattern_db': ''
+}
+
+def getscrots():
+	global MUHCONF
+	p = re.compile(MUHCONF['scrotpattern'], re.I)
+	return [f for f in os.listdir(MUHCONF['scrotdir']) if p.match(f)]
+
+def getscrots_alt():
+	global MUHCONF
+	if MUHCONF['scrotdir_alt'] == '' or MUHCONF['scrotpattern_alt'] == '':
+		return []
+
+	p = re.compile(MUHCONF['scrotpattern_alt'], re.I)
+	return [f for f in os.listdir(MUHCONF['scrotdir_alt']) if p.match(f)]
+
+def getscrots_db():
+	global MUHCONF
+	if MUHCONF['scrotdir_db'] == '' or MUHCONF['scrotpattern_db'] == '':
+		return []
+
+	p = re.compile(MUHCONF['scrotpattern_db'], re.I)
+	return [f for f in os.listdir(MUHCONF['scrotdir_db']) if p.match(f)]
+
+def growlnotif(ID, errorid=None, errormsg=None):
+	global GROWL, MUHCONF
+	growlnaem = MUHCONF['growlname']
+	icondir = MUHCONF['icondir']
+	if ID == 0:
+		GROWL.notify(
+			noteType='Uploading',
+			title=growlnaem,
+			description='Uploading image',
+			icon=open('%s/UploadingIcon.png' % icondir, 'rb').read()
+		)
+
+	elif ID == 1:
+		GROWL.notify(
+			noteType='Complete',
+			title=growlnaem,
+			description='Upload complete',
+			icon=open('%s/CompleteIcon.png' % icondir, 'rb').read()
+		)
+
+	elif ID == 2:
+		GROWL.notify(
+			noteType='Error',
+			title=growlnaem,
+			description='An error occured [%d]: %s' % (errorid, errormsg),
+			icon=open('%s/ErrorIcon.png' % icondir, 'rb').read()
+		)
+
+def upload(local, remote):
+	global AMOUNT, MUHCONF
+	try:
+		SSH.connect(MUHCONF['server'], username=MUHCONF['joeser']);
+		sftp = SSH.open_sftp()
+		sftp.put(local, '%s/%s' % (MUHCONF['remotebase'], remote))
+		sftp.close()
+		SSH.close()
+		pyperclip.copy('%s/%s' % (MUHCONF['urlbase'], remote))
+		AMOUNT += 1
+		return 0
+	except Exception as e:
+		try:
+			growlnotif(2, e.errno, e.strerror)
+		except:
+			growlnotif(2, -1, 'Something went wrong y0');
+		return 1
+
+def archiver():
+	global SSH, AMOUNT, MUHCONF
+	while True:
+		if AMOUNT >= MUHCONF['archivecount']:
+			SSH.connect(MUHCONF['server'], username=MUHCONF['joeser']);
+			date = datetime.datetime.now()
+			folder = "%d-%02d-%02d--%02d:%02d:%02d" % (date.year, date.month, date.day, date.hour, date.minute, date.second)
+
+			print "Ayyy we archiving fam: %s/%s" % (MUHCONF['archivebase'], folder)
+
+			SSH.exec_command('mkdir -p %s/%s' % (MUHCONF['archivebase'], folder))
+			SSH.exec_command('find %s -type f -mmin +%d -exec mv "{}" "%s/%s" \;' % (MUHCONF['remotebase'], MUHCONF['archivetime'], MUHCONF['archivebase'], folder));
+
+			checkamount = 'ls -1 %s | wc -l' % MUHCONF['remotebase']
+			stdin, stdout, stderr = SSH.exec_command(checkamount)
+			AMOUNT = int(stdout.read().strip())
+
+			SSH.close()
+			time.sleep(MUHCONF['archivewait'])
+
+def main(path):
+	global OLDFILES, OLDFILES_ALT, OLDFILES_DB, MUHCONF
+
+	if path != None:
+		remotefile = ''.join([random.choice(string.ascii_letters + string.digits + '-_') for c in range(8)]) + os.path.splitext(path)[1]
+		growlnotif(0)
+		if upload(path, remotefile) == 0:
+			growlnotif(1)
+		sys.exit(0)
+
+	while True:
+		newfiles_mac = newfiles_alt = newfiles_db = []
+
+		checkfiles = getscrots()
+		newfiles_mac = list(set(checkfiles) - set(OLDFILES))
+
+		checkfiles_alt = getscrots_alt()
+		newfiles_alt = list(set(checkfiles_alt) - set(OLDFILES_ALT))
+
+		checkfiles_db = getscrots_db()
+		newfiles_db = list(set(checkfiles_db) - set(OLDFILES_DB))
+
+		if len(newfiles_mac) > 0:
+			runUpload(newfiles_mac, MUHCONF['scrotdir']);
+			OLDFILES = checkfiles
+
+		if len(newfiles_alt) > 0:
+			runUpload(newfiles_alt, MUHCONF['scrotdir_alt'])
+			OLDFILES_ALT = checkfiles_alt
+
+		if len(newfiles_db) > 0:
+			runUpload(newfiles_db, MUHCONF['scrotdir_db']);
+			OLDFILES_DB = checkfiles_db
+
+		time.sleep(3)
+
+def runUpload(newfiles, basepath):
+	try:
+		for file in newfiles:
+			path = '%s/%s' % (basepath, file)
+			remotefile = ''.join([random.choice(string.ascii_letters + string.digits + '-_') for c in range(8)]) + (os.path.splitext(file)[1])
+			growlnotif(0)
+
+			if upload(path, remotefile) == 0:
+				growlnotif(1)
+
+			time.sleep(5)
+	except:
+		return False
+
+	return True
+
+if __name__ == "__main__":
+	muhdir = os.path.dirname(os.path.realpath(__file__))
+	Config = ConfigParser.ConfigParser()
+	gottem = Config.read(muhdir + "/hurr.conf")
+	print "Parsing config: %s/hurr.conf\r\n" % muhdir
+
+	if gottem == []:
+		print "Unable to read %s/hurr.conf" % muhdir
+		sys.exit(1)
+
+	for csect in Config.sections():
+		for copt in Config.options(csect):
+			try:
+				if copt in MUHCONF:
+					cval = None
+					if copt in ["archivecount", "archivewait", "archivetime"]:
+						cval = Config.getint(csect, copt)
+					else:
+						cval = (Config.get(csect, copt)).strip();
+						if cval in MUHCONF.keys():
+							cval = MUHCONF[cval]
+
+						if cval[0] == '~':
+							print "Expanding special path characters in %s" % cval
+							cval = os.path.expanduser(cval)
+
+					if copt in MUHCONF.keys() and not cval in [None, -1, '']:
+						print "** %s = %s" % (copt, cval)
+						MUHCONF[copt] = cval
+			except:
+				print "Invalid value '%s' for %s" % (cval, copt)
+				sys.exit(1)
+
+	if None in MUHCONF.values():
+		print "Incomplete config file lol"
+		sys.exit(1)
+
+	print "\r\nGetting current directory contents"
+	OLDFILES = getscrots()
+	OLDFILES_ALT = getscrots_alt()
+	OLDFILES_DB = getscrots_db()
+
+	print "Setting up SSH"
+	SSH = paramiko.SSHClient()
+	SSH.known_hosts = None
+
+	print "Loading known_hosts from %s/known_hosts" % MUHCONF['sshdir']
+	SSH.load_host_keys(MUHCONF['sshdir'] + "/known_hosts")
+	SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+
+	print "Setting up Growl"
+	GROWL = gntp.notifier.GrowlNotifier(
+		applicationName = MUHCONF['growlname'],
+		notifications = ['Uploading', 'Complete', 'Error'],
+		defaultNotifications = ['Uploading', 'Complete', 'Error']
+	)
+	GROWL.register()
+
+	print "Checking for daemon mode"
+	if len(sys.argv) > 1:
+		print "Seems to be a quick file upload, checking existence of %s" % sys.argv[1]
+		if os.path.isfile(sys.argv[1]) == False:
+			print "File doesn't exist lol"
+			sys.exit(1)
+
+		print "Calling main function"
+		main(sys.argv[1])
+	else:
+		print "Setting up threads"
+		run_event = threading.Event()
+		run_event.set()
+		threads = []
+		args = []
+
+		print "Getting current image count"
+		SSH.connect(MUHCONF['server'], username=MUHCONF['joeser']);
+		checkamount = 'ls -1 %s | wc -l' % MUHCONF['remotebase']
+		stdin, stdout, stderr = SSH.exec_command(checkamount)
+		AMOUNT = int(stdout.read().strip())
+		SSH.close()
+
+		if MUHCONF['archivebase'] != '' and MUHCONF['archivecount'] > 0 and MUHCONF['archivewait'] > 0 and MUHCONF['archivetime'] > 0:
+			tarchiver = threading.Thread(target=archiver)
+			tarchiver.daemon = True
+			tarchiver.start()
+			print "Archiver thread created (folder: %s)" % MUHCONF['archivebase']
+		else:
+			print "Archiving disabled"
+
+		args.append(None)
+		tmain = threading.Thread(target=main, args=args)
+		tmain.daemon = True
+		tmain.start()
+		threads.append(tmain)
+
+		print "Started up, calling main function"
+
+		try:
+			while 1:
+				time.sleep(.1)
+		except KeyboardInterrupt:
+			print "Attempting to close threads"
+			run_event.clear()
+			for thread in threads:
+				thread.join(5)
+			print "Threads successfully closed"
+