/
glass.py
242 lines (193 loc) · 7.67 KB
/
glass.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
__author__ = 'mookie'
import jinja2
import os
import webapp2
import urllib
import datetime
from google.appengine.api import app_identity
from google.appengine.api import channel
from google.appengine.api import users
from google.appengine.ext import ndb
"""Request Handler for /main endpoint."""
__author__ = 'charles.heath.berman@gmail.com (Charles Berman)'
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
PAGINATED_HTML = """
<article class='auto-paginate'>
<h2 class='blue text-large'>Did you know...?</h2>
<p>Cats are <em class='yellow'>solar-powered.</em> The time they spend
napping in direct sunlight is necessary to regenerate their internal
batteries. Cats that do not receive sufficient charge may exhibit the
following symptoms: lethargy, irritability, and disdainful glares. Cats
will reactivate on their own automatically after a complete charge
cycle; it is recommended that they be left undisturbed during this
process to maximize your enjoyment of your cat.</p><br/><p>
For more cat maintenance tips, tap to view the website!</p>
</article>
"""
#model for connected clients
class ChannelKey(ndb.Model):
ch_key = ndb.StringProperty()
token = ndb.StringProperty()
class LocationNDB(ndb.Model):
user = ndb.StringProperty()
trip_name=ndb.StringProperty(required=True)
date=ndb.DateTimeProperty(auto_now_add=True)
latitude=ndb.FloatProperty(required=True)
longitude=ndb.FloatProperty(required=True)
class Location(webapp2.RequestHandler):
def post(self):
#get the client_key from client
client_key=self.request.get('client_key')
#get location from client
location = self.request.get('m')
if location:
broadcast_location=client_key + " wrote: " + location
#check if client has previously being stored
ch_key = ChannelKey.query(ChannelKey.ch_key==client_key)
if ch_key.get() is None:
#send message to own client
channel.send_message(str(client_key),broadcast_location)
#save message on Message Kind (other name for tables in google app engine)
nosqlmessage = MessageNDB(user=client_key,message=broadcast_location)
nosqlmessage.put()
#send message to all connected clients
ch_keys = ChannelKey.query().fetch(1000)
for key in ch_keys:
channel.send_message(str(key.ch_key),broadcast_location)
class MessageNDB(ndb.Model):
user = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
message = ndb.StringProperty()
class Message(webapp2.RequestHandler):
def post(self):
#get the client_key from client
client_key = self.request.get('client_key')
#get message from client
message = self.request.get('m')
if message:
broadcast_message = client_key + " wrote: " + message
#check if client has previously being stored
ch_key = ChannelKey.query(ChannelKey.ch_key==client_key)
if ch_key.get() is None:
#send message to own client
channel.send_message(str(client_key),broadcast_message)
#save message on Message Kind (other name for tables in google app engine)
nosqlmessage = MessageNDB(user=client_key, message=broadcast_message)
nosqlmessage.put()
#send message to all connected clients
ch_keys = ChannelKey.query().fetch(1000)
for key in ch_keys:
channel.send_message(str(key.ch_key),broadcast_message)
class OpenedChannel(webapp2.RequestHandler):
def post(self):
#get the client_key from client
client_key = self.request.get('client_key')
if not client_key:
client_key = users.get_current_user().email()
#save Channel
new_key = ChannelKey(ch_key=str(client_key))
new_key.put()
#retrieve 7 days of messages from datastore
date1 = datetime.datetime.now() - datetime.timedelta(days=7)
m_history = MessageNDB.query(MessageNDB.date > date1)
m_history2 = m_history.order(MessageNDB.date)
result = m_history2.fetch(1000)
#send data to client
#Store log messages in one string
marray = "&log"
for m in result:
marray = marray+"&"+str(m.message)
#send via the channel
channel.send_message(str(client_key), marray)
class ClosedChannel(webapp2.RequestHandler):
def post(self):
#get the client_key from client
client_key = self.request.get('client_key')
#delete channel key from connected users
ndb.delete_multi(ChannelKey.query(ChannelKey.ch_key==str(client_key)).fetch(keys_only=True))
class DeleteMess(webapp2.RequestHandler):
def post(self):
ndb.delete_multi(ChannelKey.query().fetch(keys_only=True))
#ndb.delete_multi(MessageNDB.query().fetch(keys_only=True))
class MainPage(webapp2.RequestHandler):
def get(self):
#get user and login
usr = users.get_current_user()
if not usr:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
self.redirect(users.create_login_url(self.request.uri))
else:
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
#get the client key to start a channel
key = self.request.get('client_key')
if not key:
key = usr.email()
#create token to use on channel with client
token = channel.create_channel(str(key))
#send template values
template_values = {'user': usr,
'token': token,
'client_key': key,
'url': url,
'url_linktext': url_linktext,
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
class _BatchCallback(object):
"""Class used to track batch request response"""
def __init__(self):
"""Initialize a new _BatchCallback object."""
self.success = 0
self.failure = 0
def callback(self, request_id, response, exception):
"""Method called on each HTTP Response from a batch request.
For more information, see
https://developers.google.com/api-client-library/python/guide/batch
"""
if exception is None:
self.success += 1
else:
self.failure += 1
logging.error(
'Failed to insert item for user %s: %s', request_id, exception)
class MapHandler(webapp2.RequestHandler):
"""Request Handler for Map Activities"""
def _render_template(self,message=none):
user = users:get_current_user()
if not user:
url = users.create_login_url(self.request.uri))
url_linktext = 'Login'
self.redirect(users.create_login_url(self.request.uri))
else:
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
#get the client key to start a channel
key = self.request.get('client_key')
if not key:
key = user.email()
#create token to use on channel with client
token = channel.create_channel(str(key))
#send template values
template_values = {'user': usr,
'token': token,
'client_key': key,
'url': url,
'url_linktext': url_linktext,
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
application = webapp2.WSGIApplication([
('/', MainPage),
('/message', Message),
('/del', DeleteMess),
('/opened', OpenedChannel),
('/closed', ClosedChannel),
], debug=True)
MAP_ROUTES = [
('/',MapHandler)
]