hurr.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #!/usr/bin/python
  2. import ConfigParser
  3. import datetime
  4. import gntp.notifier
  5. import os
  6. import paramiko
  7. import pyperclip
  8. import random
  9. import re
  10. import string
  11. import sys
  12. import threading
  13. import time
  14. OLDFILES = OLDFILES_ALT = OLDFILES_DB = []
  15. AMOUNT = 0
  16. SSH = None
  17. GROWL = None
  18. MUHCONF = {
  19. 'growlname': None,
  20. 'icondir': None,
  21. 'sshdir': None,
  22. 'sshkey': 'id_rsa',
  23. 'remotebase': None,
  24. 'urlbase': None,
  25. 'scrotdir': None,
  26. 'scrotpattern': None,
  27. 'server': None,
  28. 'joeser': None,
  29. 'archivebase': '',
  30. 'archivecount': 0,
  31. 'archivewait': 0,
  32. 'archivetime': 0,
  33. 'scrotdir_alt': '',
  34. 'scrotpattern_alt': '',
  35. 'scrotdir_db': '',
  36. 'scrotpattern_db': ''
  37. }
  38. def getscrots():
  39. global MUHCONF
  40. p = re.compile(MUHCONF['scrotpattern'], re.I)
  41. return [f for f in os.listdir(MUHCONF['scrotdir']) if p.match(f)]
  42. def getscrots_alt():
  43. global MUHCONF
  44. if MUHCONF['scrotdir_alt'] == '' or MUHCONF['scrotpattern_alt'] == '':
  45. return []
  46. p = re.compile(MUHCONF['scrotpattern_alt'], re.I)
  47. return [f for f in os.listdir(MUHCONF['scrotdir_alt']) if p.match(f)]
  48. def getscrots_db():
  49. global MUHCONF
  50. if MUHCONF['scrotdir_db'] == '' or MUHCONF['scrotpattern_db'] == '':
  51. return []
  52. p = re.compile(MUHCONF['scrotpattern_db'], re.I)
  53. return [f for f in os.listdir(MUHCONF['scrotdir_db']) if p.match(f)]
  54. def growlnotif(ID, errorid=None, errormsg=None):
  55. global GROWL, MUHCONF
  56. growlnaem = MUHCONF['growlname']
  57. icondir = MUHCONF['icondir']
  58. if ID == 0:
  59. GROWL.notify(
  60. noteType='Uploading',
  61. title=growlnaem,
  62. description='Uploading image',
  63. icon=open('%s/UploadingIcon.png' % icondir, 'rb').read()
  64. )
  65. elif ID == 1:
  66. GROWL.notify(
  67. noteType='Complete',
  68. title=growlnaem,
  69. description='Upload complete',
  70. icon=open('%s/CompleteIcon.png' % icondir, 'rb').read()
  71. )
  72. elif ID == 2:
  73. GROWL.notify(
  74. noteType='Error',
  75. title=growlnaem,
  76. description='An error occured [%d]: %s' % (errorid, errormsg),
  77. icon=open('%s/ErrorIcon.png' % icondir, 'rb').read()
  78. )
  79. def upload(local, remote):
  80. global AMOUNT, MUHCONF
  81. try:
  82. SSH.connect(MUHCONF['server'], username=MUHCONF['joeser'], key_filename="%s/%s" % (MUHCONF['sshdir'], MUHCONF['sshkey']));
  83. sftp = SSH.open_sftp()
  84. sftp.put(local, '%s/%s' % (MUHCONF['remotebase'], remote))
  85. sftp.close()
  86. SSH.close()
  87. pyperclip.copy('%s/%s' % (MUHCONF['urlbase'], remote))
  88. AMOUNT += 1
  89. return 0
  90. except Exception as e:
  91. try:
  92. growlnotif(2, e.errno, e.strerror)
  93. except:
  94. growlnotif(2, -1, 'Something went wrong y0');
  95. return 1
  96. def archiver():
  97. global SSH, AMOUNT, MUHCONF
  98. while True:
  99. if AMOUNT >= MUHCONF['archivecount']:
  100. SSH.connect(MUHCONF['server'], username=MUHCONF['joeser'], key_filename="%s/%s" % (MUHCONF['sshdir'], MUHCONF['sshkey']));
  101. date = datetime.datetime.now()
  102. folder = "%d-%02d-%02d--%02d:%02d:%02d" % (date.year, date.month, date.day, date.hour, date.minute, date.second)
  103. print "Ayyy we archiving fam: %s/%s" % (MUHCONF['archivebase'], folder)
  104. SSH.exec_command('mkdir -p %s/%s' % (MUHCONF['archivebase'], folder))
  105. SSH.exec_command('find %s -type f -mmin +%d -exec mv "{}" "%s/%s" \;' % (MUHCONF['remotebase'], MUHCONF['archivetime'], MUHCONF['archivebase'], folder));
  106. checkamount = 'ls -1 %s | wc -l' % MUHCONF['remotebase']
  107. stdin, stdout, stderr = SSH.exec_command(checkamount)
  108. AMOUNT = int(stdout.read().strip())
  109. SSH.close()
  110. time.sleep(MUHCONF['archivewait'])
  111. def main(path):
  112. global OLDFILES, OLDFILES_ALT, OLDFILES_DB, MUHCONF
  113. if path != None:
  114. remotefile = ''.join([random.choice(string.ascii_letters + string.digits + '-_') for c in range(8)]) + os.path.splitext(path)[1]
  115. growlnotif(0)
  116. if upload(path, remotefile) == 0:
  117. growlnotif(1)
  118. sys.exit(0)
  119. while True:
  120. newfiles_mac = newfiles_alt = newfiles_db = []
  121. checkfiles = getscrots()
  122. newfiles_mac = list(set(checkfiles) - set(OLDFILES))
  123. checkfiles_alt = getscrots_alt()
  124. newfiles_alt = list(set(checkfiles_alt) - set(OLDFILES_ALT))
  125. checkfiles_db = getscrots_db()
  126. newfiles_db = list(set(checkfiles_db) - set(OLDFILES_DB))
  127. if len(newfiles_mac) > 0:
  128. runUpload(newfiles_mac, MUHCONF['scrotdir']);
  129. OLDFILES = checkfiles
  130. if len(newfiles_alt) > 0:
  131. runUpload(newfiles_alt, MUHCONF['scrotdir_alt'])
  132. OLDFILES_ALT = checkfiles_alt
  133. if len(newfiles_db) > 0:
  134. runUpload(newfiles_db, MUHCONF['scrotdir_db']);
  135. OLDFILES_DB = checkfiles_db
  136. time.sleep(3)
  137. def runUpload(newfiles, basepath):
  138. try:
  139. for file in newfiles:
  140. path = '%s/%s' % (basepath, file)
  141. remotefile = ''.join([random.choice(string.ascii_letters + string.digits + '-_') for c in range(8)]) + (os.path.splitext(file)[1])
  142. growlnotif(0)
  143. if upload(path, remotefile) == 0:
  144. growlnotif(1)
  145. time.sleep(5)
  146. except:
  147. return False
  148. return True
  149. if __name__ == "__main__":
  150. muhdir = os.path.dirname(os.path.realpath(__file__))
  151. Config = ConfigParser.ConfigParser()
  152. gottem = Config.read(muhdir + "/hurr.conf")
  153. print "Parsing config: %s/hurr.conf\r\n" % muhdir
  154. if gottem == []:
  155. print "Unable to read %s/hurr.conf" % muhdir
  156. sys.exit(1)
  157. for csect in Config.sections():
  158. for copt in Config.options(csect):
  159. try:
  160. if copt in MUHCONF:
  161. cval = None
  162. if copt in ["archivecount", "archivewait", "archivetime"]:
  163. cval = Config.getint(csect, copt)
  164. else:
  165. cval = (Config.get(csect, copt)).strip();
  166. if cval in MUHCONF.keys():
  167. cval = MUHCONF[cval]
  168. if cval[0] == '~':
  169. print "Expanding special path characters in %s" % cval
  170. cval = os.path.expanduser(cval)
  171. if copt in MUHCONF.keys() and not cval in [None, -1, '']:
  172. print "** %s = %s" % (copt, cval)
  173. MUHCONF[copt] = cval
  174. except:
  175. print "Invalid value '%s' for %s" % (cval, copt)
  176. sys.exit(1)
  177. if None in MUHCONF.values():
  178. print "Incomplete config file lol"
  179. sys.exit(1)
  180. print "\r\nGetting current directory contents"
  181. OLDFILES = getscrots()
  182. OLDFILES_ALT = getscrots_alt()
  183. OLDFILES_DB = getscrots_db()
  184. print "Setting up SSH using key pair: %s/%s" % (MUHCONF['sshdir'], MUHCONF['sshkey'])
  185. SSH = paramiko.SSHClient()
  186. SSH.known_hosts = None
  187. print "Loading known_hosts from %s/known_hosts" % MUHCONF['sshdir']
  188. SSH.load_host_keys(MUHCONF['sshdir'] + "/known_hosts")
  189. SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  190. print "Setting up Growl"
  191. GROWL = gntp.notifier.GrowlNotifier(
  192. applicationName = MUHCONF['growlname'],
  193. notifications = ['Uploading', 'Complete', 'Error'],
  194. defaultNotifications = ['Uploading', 'Complete', 'Error']
  195. )
  196. GROWL.register()
  197. print "Checking for daemon mode"
  198. if len(sys.argv) > 1:
  199. print "Seems to be a quick file upload, checking existence of %s" % sys.argv[1]
  200. if os.path.isfile(sys.argv[1]) == False:
  201. print "File doesn't exist lol"
  202. sys.exit(1)
  203. print "Calling main function"
  204. main(sys.argv[1])
  205. else:
  206. print "Setting up threads"
  207. run_event = threading.Event()
  208. run_event.set()
  209. threads = []
  210. args = []
  211. print "Getting current image count"
  212. SSH.connect(MUHCONF['server'], username=MUHCONF['joeser'], key_filename="%s/%s" % (MUHCONF['sshdir'], MUHCONF['sshkey']));
  213. checkamount = 'ls -1 %s | wc -l' % MUHCONF['remotebase']
  214. stdin, stdout, stderr = SSH.exec_command(checkamount)
  215. AMOUNT = int(stdout.read().strip())
  216. SSH.close()
  217. if MUHCONF['archivebase'] != '' and MUHCONF['archivecount'] > 0 and MUHCONF['archivewait'] > 0 and MUHCONF['archivetime'] > 0:
  218. tarchiver = threading.Thread(target=archiver)
  219. tarchiver.daemon = True
  220. tarchiver.start()
  221. print "Archiver thread created (folder: %s)" % MUHCONF['archivebase']
  222. else:
  223. print "Archiving disabled"
  224. args.append(None)
  225. tmain = threading.Thread(target=main, args=args)
  226. tmain.daemon = True
  227. tmain.start()
  228. threads.append(tmain)
  229. print "Started up, calling main function"
  230. try:
  231. while 1:
  232. time.sleep(.1)
  233. except KeyboardInterrupt:
  234. print "Attempting to close threads"
  235. run_event.clear()
  236. for thread in threads:
  237. thread.join(5)
  238. print "Threads successfully closed"