filesd/filesd.py
2014-05-22 04:34:23 -07:00

94 lines
2.8 KiB
Python
Executable File

#!/usr/bin/env python2
import gtk
import pygtk
import time
import sys
from os import listdir as ls, rename
from os.path import exists, isfile, join, splitext
from random import choice
from string import ascii_letters, digits
from subprocess import call
from daemon import Daemon
pygtk.require('2.0')
# Config
SSH_PORT = 22
PATH = "/home/ian/Pictures"
BASE_URL = "http://files.ianonavy.com/"
SCP_PATH = "files.ianonavy.com:sites/ianonavy.com/files"
WAIT_INTERVAL = 1
class FilesDaemon(Daemon):
def run(self):
"""
Constantly loops checking for a new file. It's not very efficient, but
it gets the job done.
"""
print "Loading list of all files..."
# Get list of all files.
files = [f for f in ls(PATH) if isfile(join(PATH, f))]
print "Done! Waiting for some new files."
while 1:
for f in ls(PATH):
filename = join(PATH, f) # Get the full file path.
if isfile(filename):
if f not in files:
#print f, files
base, extension = splitext(f)
new_filename = self.random_filename(extension=extension)
rename(filename, join(PATH, new_filename))
files.append(new_filename)
self.upload(join(PATH, new_filename))
image_url = "%s%s" % (BASE_URL, new_filename)
self.copy_to_clipboard(image_url)
time.sleep(WAIT_INTERVAL)
def upload(self, filename):
""" Uploads a file to the remote host. """
print "scp -P %d %s %s" % (SSH_PORT, filename, SCP_PATH)
call("scp -P %d %s %s" % (SSH_PORT, filename, SCP_PATH), shell=True)
def copy_to_clipboard(self, text):
""" Copies the passed argument to the clipboard. """
clipboard = gtk.clipboard_get()
clipboard.set_text(text)
clipboard.store() # Let other programs use it.
def random_filename(self, length=4, extension='', attempts=10):
""" Generates a random filename and verifies that it doesn't exist. """
chars = ''.join([ascii_letters, digits])
for attempt in range(attempts):
filename = ''.join([choice(chars) for i in range(length)])
filename = filename + extension
if not exists(filename):
return filename
if __name__ == "__main__":
daemon = FilesDaemon('/tmp/filesd.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s {start|stop|restart}" % sys.argv[0]
sys.exit(2)