-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfoldermon.py
More file actions
executable file
·191 lines (147 loc) · 3.56 KB
/
Copy pathfoldermon.py
File metadata and controls
executable file
·191 lines (147 loc) · 3.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python
import time
import os
import sys
import argparse
import json
import SocketServer
import urllib2
import subprocess
from dateutil import tz
from datetime import datetime, timedelta
from threading import Thread, Event
from CmdHttpServer import CmdHttpServer
from BaseHTTPServer import HTTPServer
#-------------------------------------------------------------------
# Globals
p = {}
#-------------------------------------------------------------------
# Web Commands
def cmdGetFiles(req, path, cmd, pd):
files = []
dir = req.ctx['folder']
if not len(dir):
dir = './'
sub = ''
if 'path' in cmd and len(cmd['path']) and 0 > cmd['path'].find('..'):
s = cmd['path']
while len(s) and ('/' == s[0] or '\\' == s[0]):
s = s[1:]
if len(s) and os.path.exists(os.path.join(dir, s)):
sub = s
dir = os.path.join(dir, s)
for fname in os.listdir(dir):
path = os.path.join(dir, fname)
si = os.stat(path)
isfile = os.path.isfile(path)
isdir = os.path.isdir(path)
if isdir:
link = ''
elif len(sub):
link = "/".join(['/files', sub, fname])
else:
link = "/".join(['/files', fname])
fi = {
'name': fname,
'isfile': isfile,
'isdir': isdir,
'size': si.st_size,
'atime': si.st_atime,
'mtime': si.st_mtime,
'ctime': si.st_ctime,
'link': link
}
files.append(fi)
return {'ok': 1, 'path': sub, 'files': files, 'root': req.ctx['folder'], 'absroot': os.path.abspath(req.ctx['folder'])}
#-------------------------------------------------------------------
# Main function
def main():
global p
print "Los geht's..."
scriptroot = os.path.dirname(__file__)
scriptname = os.path.basename(os.path.splitext(__file__)[0])
# Get user folder
userroot = os.path.expanduser("~")
if not os.path.exists(userroot):
userroot = './'
# Build a unique web link name
cachedir = os.path.join(userroot, '.cache', scriptname)
if not os.path.exists(cachedir):
os.makedirs(cachedir)
# Default web log name
weblog = os.path.join(cachedir, scriptname + '-web.log')
# Default html root
htmlroot = os.path.join(scriptroot, 'html')
# Command line arguments
ap = argparse.ArgumentParser(description='HTTP Server')
ap.add_argument('--port', '-p', default=8800, type=int, help='Server Port')
ap.add_argument('--html', '-m', default=htmlroot, type=str, help='Document root')
ap.add_argument('--logfile', '-l', default=weblog, type=str, help='Logfile')
ap.add_argument('--folder', '-f', default='./', type=str, help='Folder to monitor')
p = vars(ap.parse_args())
print "Parameters: " + str(p)
print 'Running at : http://localhost:%i/' % p['port']
# We must have an html folder
if not os.path.exists(p['html']):
print "Bad html path : " + p['html']
return;
# Create an exit event
p['exit'] = Event()
# Create web server thread
httpd = CmdHttpServer(p['port'], p)
# Request handler
httpd.req.handlers = {
'_':
{
'c':
{
'cmdGetFiles': cmdGetFiles
}
},
'html':
{
'f':
{
'path': p['html'],
'default': 'index.html'
}
},
'files':
{
'f':
{
'path': p['folder'],
'download': True
}
},
'':
{
'f':
{
'default': 'html/index.html'
}
}
}
# Log file
if len(p['logfile']):
httpd.req.logFile = open(p['logfile'], "a", 0)
# Start the server
httpd.start()
# Local cleanup
def cleanup():
p['exit'].set()
httpd.stop()
# Run the loop
try:
while not p['exit'].is_set():
p['exit'].wait(1)
except KeyboardInterrupt:
print " ~ KeyboardInterrupt ~ "
pass
except:
cleanup()
raise
cleanup()
print "Bye..."
if __name__ == '__main__':
main()