-
Notifications
You must be signed in to change notification settings - Fork 0
/
calendarReciever.py
177 lines (149 loc) · 5.25 KB
/
calendarReciever.py
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
import os
import posixpath
import BaseHTTPServer
import urllib
# import cgi
import shutil
# import mimetypes
# import re
import icalendar
import utils
import pytz
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import calendarParser
from Monitor import Monitor
from datetime import datetime
# from datetime import timedelta
# import icalendar
def calChangedCB(gcal):
'''Callback for calendar change from reciever'''
print("Detected calendar changed.")
mo_temp = []
for component in gcal.walk():
if component.name == "VEVENT":
summary = component.get('summary')
start_time = component.get('dtstart').dt
end_time = component.get('dtend').dt
time_delta = end_time - start_time
# Create Cron Job base on schedule
seconds = time_delta.total_seconds()
comm0 = calendarParser.COMM + " " + summary + " " + str(seconds)
# create new Monitor
job = Monitor(0, comm0, start_time)
mo_temp.append(job)
print(utils.MONITORS)
for mo in utils.MONITORS:
mo.stop()
utils.MONITORS = []
timezone = pytz.timezone("US/Eastern")
print mo_temp
for mo in mo_temp:
if mo.dt < timezone.localize(datetime.now()):
continue
utils.MONITORS.append(mo)
for mo in utils.MONITORS:
mo.start()
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# Simple HTTP request handler with POST commands.
def do_POST(self):
"""Serve a POST request."""
r, info = self.deal_post_data()
print r, info, "by: ", self.client_address
f = StringIO()
if r:
f.write("<strong>Success:</strong>")
else:
f.write("<strong>Failed:</strong>")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
if f:
self.copyfile(f, self.wfile)
f.close()
def deal_post_data(self):
print self.headers
boundary = self.headers.plisttext.split("=")[1]
print 'Boundary %s' % boundary
remainbytes = int(self.headers['content-length'])
print "Remain Bytes %s" % remainbytes
line = self.rfile.readline()
remainbytes -= len(line)
if boundary not in line:
return (False, "Content NOT begin with boundary")
line = self.rfile.readline()
remainbytes -= len(line)
fn = "ICS/Calendar.ics"
line = self.rfile.readline()
remainbytes -= len(line)
line = self.rfile.readline()
remainbytes -= len(line)
try:
out = open(fn, 'wb')
except IOError:
return (False, "No Write Permission")
if line.strip():
preline = line
else:
preline = self.rfile.readline()
remainbytes -= len(preline)
while 1:
line = self.rfile.readline()
# print(line)
remainbytes -= len(line)
if boundary in line:
preline = preline[0:-1]
if preline.endswith('\r'):
preline = preline[0:-1]
out.write(preline)
out.close()
g = open(fn, 'rb')
gcal = icalendar.Calendar.from_ical(g.read())
calChangedCB(gcal)
return (True, "File '%s' upload success!" % fn)
else:
out.write(preline)
preline = line
return (False, "Unexpect Ends of data.")
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = path.split('?', 1)[0]
path = path.split('#', 1)[0]
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = os.getcwd()
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir):
continue
path = os.path.join(path, word)
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
shutil.copyfileobj(source, outputfile)
def start_server(HandlerClass=SimpleHTTPRequestHandler,
ServerClass=BaseHTTPServer.HTTPServer):
BaseHTTPServer.test(HandlerClass, ServerClass)
if __name__ == '__main__':
start_server()