Browse Source

Initial commit

Ian Adam Naval 5 years ago
commit
fe20833928
7 changed files with 324 additions and 0 deletions
  1. 2
    0
      .gitignore
  2. 1
    0
      README.md
  3. 129
    0
      daemon.py
  4. 93
    0
      filesd.py
  5. 93
    0
      main.py
  6. 3
    0
      shutdown.sh
  7. 3
    0
      startup.sh

+ 2
- 0
.gitignore View File

@@ -0,0 +1,2 @@
1
+screenshots/
2
+*.pyc

+ 1
- 0
README.md View File

@@ -0,0 +1 @@
1
+This is a place for me to make my screenshots public.

+ 129
- 0
daemon.py View File

@@ -0,0 +1,129 @@
1
+#!/usr/bin/env python
2
+
3
+import sys, os, time, atexit
4
+from signal import SIGTERM 
5
+
6
+class Daemon:
7
+	"""
8
+	A generic daemon class.
9
+	
10
+	Usage: subclass the Daemon class and override the run() method
11
+	"""
12
+	def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
13
+		self.stdin = stdin
14
+		self.stdout = stdout
15
+		self.stderr = stderr
16
+		self.pidfile = pidfile
17
+	
18
+	def daemonize(self):
19
+		"""
20
+		do the UNIX double-fork magic, see Stevens' "Advanced 
21
+		Programming in the UNIX Environment" for details (ISBN 0201563177)
22
+		http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
23
+		"""
24
+		try: 
25
+			pid = os.fork() 
26
+			if pid > 0:
27
+				# exit first parent
28
+				sys.exit(0) 
29
+		except OSError, e: 
30
+			sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
31
+			sys.exit(1)
32
+	
33
+		# decouple from parent environment
34
+		os.chdir("/") 
35
+		os.setsid() 
36
+		os.umask(0) 
37
+	
38
+		# do second fork
39
+		try: 
40
+			pid = os.fork() 
41
+			if pid > 0:
42
+				# exit from second parent
43
+				sys.exit(0) 
44
+		except OSError, e: 
45
+			sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
46
+			sys.exit(1) 
47
+	
48
+		# redirect standard file descriptors
49
+		sys.stdout.flush()
50
+		sys.stderr.flush()
51
+		si = file(self.stdin, 'r')
52
+		so = file(self.stdout, 'a+')
53
+		se = file(self.stderr, 'a+', 0)
54
+		os.dup2(si.fileno(), sys.stdin.fileno())
55
+		os.dup2(so.fileno(), sys.stdout.fileno())
56
+		os.dup2(se.fileno(), sys.stderr.fileno())
57
+	
58
+		# write pidfile
59
+		atexit.register(self.delpid)
60
+		pid = str(os.getpid())
61
+		file(self.pidfile,'w+').write("%s\n" % pid)
62
+	
63
+	def delpid(self):
64
+		os.remove(self.pidfile)
65
+
66
+	def start(self):
67
+		"""
68
+		Start the daemon
69
+		"""
70
+		# Check for a pidfile to see if the daemon already runs
71
+		try:
72
+			pf = file(self.pidfile,'r')
73
+			pid = int(pf.read().strip())
74
+			pf.close()
75
+		except IOError:
76
+			pid = None
77
+	
78
+		if pid:
79
+			message = "pidfile %s already exist. Daemon already running?\n"
80
+			sys.stderr.write(message % self.pidfile)
81
+			sys.exit(1)
82
+		
83
+		# Start the daemon
84
+		self.daemonize()
85
+		self.run()
86
+
87
+	def stop(self):
88
+		"""
89
+		Stop the daemon
90
+		"""
91
+		# Get the pid from the pidfile
92
+		try:
93
+			pf = file(self.pidfile,'r')
94
+			pid = int(pf.read().strip())
95
+			pf.close()
96
+		except IOError:
97
+			pid = None
98
+	
99
+		if not pid:
100
+			message = "pidfile %s does not exist. Daemon not running?\n"
101
+			sys.stderr.write(message % self.pidfile)
102
+			return # not an error in a restart
103
+
104
+		# Try killing the daemon process	
105
+		try:
106
+			while 1:
107
+				os.kill(pid, SIGTERM)
108
+				time.sleep(0.1)
109
+		except OSError, err:
110
+			err = str(err)
111
+			if err.find("No such process") > 0:
112
+				if os.path.exists(self.pidfile):
113
+					os.remove(self.pidfile)
114
+			else:
115
+				print str(err)
116
+				sys.exit(1)
117
+
118
+	def restart(self):
119
+		"""
120
+		Restart the daemon
121
+		"""
122
+		self.stop()
123
+		self.start()
124
+
125
+	def run(self):
126
+		"""
127
+		You should override this method when you subclass Daemon. It will be called after the process has been
128
+		daemonized by start() or restart().
129
+		"""

+ 93
- 0
filesd.py View File

@@ -0,0 +1,93 @@
1
+#!/usr/bin/env python2
2
+
3
+import gtk
4
+import pygtk
5
+import time
6
+import sys
7
+from os import listdir as ls, rename
8
+from os.path import exists, isfile, join, splitext
9
+from random import choice
10
+from string import ascii_letters, digits
11
+from subprocess import call
12
+from daemon import Daemon
13
+pygtk.require('2.0')
14
+
15
+
16
+# Config
17
+SSH_PORT = 22
18
+PATH = "/home/ian/Pictures"
19
+BASE_URL = "http://files.ianonavy.com/"
20
+SCP_PATH = "files.ianonavy.com:sites/ianonavy.com/files"
21
+WAIT_INTERVAL = 1
22
+
23
+
24
+class FilesDaemon(Daemon):
25
+
26
+    def run(self):
27
+        """
28
+        Constantly loops checking for a new file. It's not very efficient, but
29
+        it gets the job done.
30
+
31
+        """
32
+
33
+        print "Loading list of all files..."
34
+        # Get list of all files.
35
+        files = [f for f in ls(PATH) if isfile(join(PATH, f))]
36
+        print "Done! Waiting for some new files."
37
+
38
+        while 1:
39
+            for f in ls(PATH):
40
+                filename = join(PATH, f)  # Get the full file path.
41
+
42
+                if isfile(filename):
43
+                    if f not in files:
44
+                        #print f, files
45
+
46
+                        base, extension = splitext(f)
47
+                        new_filename = self.random_filename(extension=extension)
48
+                        rename(filename, join(PATH, new_filename))
49
+                        files.append(new_filename)
50
+
51
+                        self.upload(join(PATH, new_filename))
52
+                        image_url = "%s%s" % (BASE_URL, new_filename)
53
+                        self.copy_to_clipboard(image_url)
54
+
55
+            time.sleep(WAIT_INTERVAL)
56
+
57
+    def upload(self, filename):
58
+        """ Uploads a file to the remote host. """
59
+        print "scp -P %d %s %s" % (SSH_PORT, filename, SCP_PATH)
60
+        call("scp -P %d %s %s" % (SSH_PORT, filename, SCP_PATH), shell=True)
61
+
62
+    def copy_to_clipboard(self, text):
63
+        """ Copies the passed argument to the clipboard. """
64
+        clipboard = gtk.clipboard_get()
65
+        clipboard.set_text(text)
66
+        clipboard.store()  # Let other programs use it.
67
+
68
+    def random_filename(self, length=4, extension='', attempts=10):
69
+        """ Generates a random filename and verifies that it doesn't exist. """
70
+        chars = ''.join([ascii_letters, digits])
71
+        for attempt in range(attempts):
72
+            filename = ''.join([choice(chars) for i in range(length)])
73
+            filename = filename + extension
74
+            if not exists(filename):
75
+                return filename
76
+
77
+
78
+if __name__ == "__main__":
79
+    daemon = FilesDaemon('/tmp/filesd.pid')
80
+    if len(sys.argv) == 2:
81
+        if 'start' == sys.argv[1]:
82
+            daemon.start()
83
+        elif 'stop' == sys.argv[1]:
84
+            daemon.stop()
85
+        elif 'restart' == sys.argv[1]:
86
+            daemon.restart()
87
+        else:
88
+            print "Unknown command"
89
+            sys.exit(2)
90
+        sys.exit(0)
91
+    else:
92
+        print "usage: %s {start|stop|restart}" % sys.argv[0]
93
+        sys.exit(2)

+ 93
- 0
main.py View File

@@ -0,0 +1,93 @@
1
+#!/usr/bin/env python
2
+
3
+import gtk
4
+import pygtk
5
+import time
6
+import sys
7
+from daemon import Daemon
8
+from subprocess import call
9
+from random import choice
10
+from string import ascii_letters, digits
11
+from os import listdir as ls, rename
12
+from os.path import exists, isfile, join, splitext
13
+pygtk.require('2.0')
14
+
15
+
16
+# Config
17
+SSH_PORT = 1337
18
+PATH = "/home/ian/Dropbox/projects/files/screenshots"
19
+BASE_URL = "http://files.ianonavy.com/"
20
+SCP_PATH = "vpn.ianonavy.com:sites/ianonavy.com/files"
21
+WAIT_INTERVAL = 1
22
+
23
+
24
+class FilesDaemon(Daemon):
25
+
26
+    def run(self):
27
+        """
28
+        Constantly loops checking for a new file. It's not very efficient, but
29
+        it gets the job done.
30
+
31
+        """
32
+
33
+        print "Loading list of all files..."
34
+        # Get list of all files.
35
+        files = [f for f in ls(PATH) if isfile(join(PATH, f))]
36
+        print "Done! Waiting for some new files."
37
+
38
+        while 1:
39
+            for f in ls(PATH):
40
+                filename = join(PATH, f)  # Get the full file path.
41
+
42
+                if isfile(filename):
43
+                    if f not in files:
44
+                        #print f, files
45
+
46
+                        base, extension = splitext(f)
47
+                        new_filename = self.random_filename(extension=extension)
48
+                        rename(filename, join(PATH, new_filename))
49
+                        files.append(new_filename)
50
+
51
+                        self.upload(join(PATH, new_filename))
52
+                        image_url = "%s%s" % (BASE_URL, new_filename)
53
+                        self.copy_to_clipboard(image_url)
54
+
55
+            time.sleep(WAIT_INTERVAL)
56
+
57
+    def upload(self, filename):
58
+        """ Uploads a file to the remote host. """
59
+        print "scp -P %d %s %s" % (SSH_PORT, filename, SCP_PATH)
60
+        call("scp -P %d %s %s" % (SSH_PORT, filename, SCP_PATH), shell=True)
61
+
62
+    def copy_to_clipboard(self, text):
63
+        """ Copies the passed argument to the clipboard. """
64
+        clipboard = gtk.clipboard_get()
65
+        clipboard.set_text(text)
66
+        clipboard.store()  # Let other programs use it.
67
+
68
+    def random_filename(self, length=4, extension='', attempts=10):
69
+        """ Generates a random filename and verifies that it doesn't exist. """
70
+        chars = ''.join([ascii_letters, digits])
71
+        for attempt in range(attempts):
72
+            filename = ''.join([choice(chars) for i in range(length)])
73
+            filename = filename + extension
74
+            if not exists(filename):
75
+                return filename
76
+
77
+
78
+if __name__ == "__main__":
79
+    daemon = FilesDaemon('/tmp/filesd.pid')
80
+    if len(sys.argv) == 2:
81
+        if 'start' == sys.argv[1]:
82
+            daemon.start()
83
+        elif 'stop' == sys.argv[1]:
84
+            daemon.stop()
85
+        elif 'restart' == sys.argv[1]:
86
+            daemon.restart()
87
+        else:
88
+            print "Unknown command"
89
+            sys.exit(2)
90
+        sys.exit(0)
91
+    else:
92
+        print "usage: %s {start|stop|restart}" % sys.argv[0]
93
+        sys.exit(2)

+ 3
- 0
shutdown.sh View File

@@ -0,0 +1,3 @@
1
+#/bin/bash
2
+kill `pgrep -f "python main.py"`
3
+kill `pgrep -f "ssh -nNR 52398:localhost:52398 -p 1337 ian@208.110.86.98"`

+ 3
- 0
startup.sh View File

@@ -0,0 +1,3 @@
1
+#!/bin/bash
2
+cd "$( dirname "${BASH_SOURCE[0]}" )"
3
+python main.py >/dev/null &

Loading…
Cancel
Save