hurr.py 7.5 KB

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