-
Notifications
You must be signed in to change notification settings - Fork 1
/
product.py
290 lines (244 loc) · 9.17 KB
/
product.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
__author__ = 'Emmanouil Samatas'
from gevent import monkey; monkey.patch_all()
from bottle import *
from bson.json_util import dumps, loads
from cStringIO import StringIO
from datetime import datetime
from time import gmtime, strftime
import random, string
import time
import gevent
import requests
import database
import cache
import apns
import base64
@hook('after_request')
def setHeaders():
response.content_type = "application/json"
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
@route('/')
def index():
return str(database.find_one(database="test", collection="test"))
def sendNotification(token=None, content=None) :
# build connection with notification servers
url = "http://ec2-54-217-229-240.eu-west-1.compute.amazonaws.com:8080/notification/addNotification"
timestamp = time.time()
timezones = strftime("%z", gmtime())
payload = {'token':token,
'content':content,
'timestamp':timestamp,
'timezones':timezones}
greenlet = gevent.spawn(requests.post, url, data=dumps(payload))
greenlet.ready()
greenlet.get()
return
@post('/token/registerDeviceToken')
def registerDeviceToken() :
requestBody = loads(request.body.read())
token = requestBody['token']
query = {'token' : token}
tokenID = database.find(database="brazaar2",
collection="devices",
query=query)
if not tokenID :
tokenID = database.insert(database="brazaar2",
collection="devices",
data=requestBody)
if tokenID :
return dumps(requestBody)
else :
response.status = 300
return {'error': 'register token error'}
return
@post('/product/getNearbyProducts')
def getNearbyProducts():
requestBody = loads(request.body.read())
token = requestBody['token']
location = requestBody['location']
# search in cache first
nearestProducts = None
# key = str(token + 'getNearbyProducts')
# nearestProducts = cache.get_cache(key)
if not nearestProducts :
# search in database
query = {'location': {'$nearSphere':{
'$geometry': { 'type' : 'Point' ,
'coordinates' : [location['longitude'],location['latitude']]}}}}
nearestProducts = database.find(database="brazaar2",
collection="products",
limit=10)
nearestProducts = dumps(nearestProducts)
# add to cache
# cache.set_cache(key, nearestProducts)
if nearestProducts :
return nearestProducts
else :
response.status = 300
return {'error': 'request collection error'}
def uploadImages(folderName, images) :
counter = 0
for image in images :
# decode base 64 data
fileItem = StringIO(base64.b64decode(image))
# Test if the file was uploaded
if fileItem:
filename = 'image' + str(counter) + '.jpg'
key_name = folderName + '/' + filename
database.upload_image(key_name=key_name, bucket="brazaar",
data=fileItem)
message = 'The file "' + filename + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print message
# increment image counter
counter += 1
@post('/product/addProduct')
def addProduct():
requestBody = loads(request.body.read())
token = requestBody['token']
product = requestBody['product']
name = product['name']
images = product['images']
product.setdefault('quantity', 1)
# delete images key
del product['images']
# # send notification to followers
# user = "Lunayo"
# content = user + " has posted new product : " + name + "!"
# # simulate 10 followers
# token = randomword(15)
# for i in range(1,10) :
# sendNotification(token=token, content=content)
productID = database.insert(database="brazaar2",
collection="products",
data=dict(product))
if productID :
greenlet = gevent.spawn(uploadImages, str(productID), images)
greenlet.ready()
greenlet.get()
return dumps(product)
else :
response.status = 300
return {'error': 'insert to collection error'}
@post('/product/getImages')
def getImages():
requestBody = loads(request.body.read())
token = requestBody['token']
product = requestBody['product']
productID = product['id']
images = []
if productID :
images = database.get_images(key_name=productID, bucket="brazaar")
# append images in to product json
product['images'] = images
return product
@post('/user/addFollowing')
def addFollowing():
requestBody = loads(request.body.read())
token = requestBody['token']
relationship = requestBody['relationship']
username = relationship['username']
following = relationship['following']
# check if user exists
query = {"username" : username}
user = database.find(database="brazaar2",
collection="users",
query=query)
if user :
followingID = database.insert(database="brazaar2",
collection="followings",
data=relationship)
if followingID :
return dumps(relationship)
else :
response.status = 300
return {'error': 'Relationship exists'}
else :
response.status = 300
return {'error': 'User not exists'}
@post('/user/getFollowers')
def getFollowers() :
requestBody = loads(request.body.read())
token = requestBody['token']
username = requestBody['username']
# check if user exists
query = {"username" : username}
user = database.find(database="brazaar2",
collection="users",
query=query)
if user :
# get followers with username
query = {'following' : username}
followings = list(database.find(database="brazaar2",
collection="followings",
query=query))
followingArray = []
for following in followings:
followingArray.append(following['username'])
# append to request body
requestBody['followings'] = followingArray
return dumps(requestBody)
else :
response.status = 300
return {'error': 'User not exists'}
# @post('/user/addFollower')
# def addFollower():
# relationship = {}
# session = {'username':"samatase"}
# requestBody = loads(request.body.read())
# token = requestBody['token']
# relationship['following'] = requestBody['username']
# relationship['user'] = session['username']
# userQuery = '{"username":' + relationship['following'] + '}'
# validate = list(database.find(database="brazaar2",
# collection="users",
# query=userQuery))
# if validate :
# relationshipID = database.insert(database="brazaar2",
# collection="relationships",
# data=dict(relationship))
# return dumps(relationship)
# else :
# response.status = 300
# return {'error': 'Invalid username'}
@post ('/user/createUser')
def createUser():
user = {}
requestBody = loads(request.body.read())
token = requestBody['token']
user['username'] = requestBody['username']
user['firstName'] = requestBody['firstName']
user['lastName'] = requestBody['lastName']
userID = database.insert(database="brazaar2",
collection="users",
data=dict(user))
if userID :
return dumps(user)
else :
response.status = 300
return {'error': 'insert to collection error'}
# @get ('/user/getFollowings')
# def getFollowing():
# session = {'username':"samatase"}
# followingUsers = []
# requestBody = loads(request.body.read())
# user = session['username']
# followingsQuery = '{"user":user},{"following":1,"_id":0}'
# followings = list(database.find(database="brazaar2",
# collection="relationships",
# query=followingsQuery))
# usersQuery = '{"username":' + following['following'] + '},{"firstName":1,"lastName":1,"_id":0}'
# for following in followings:
# user = database.find(database="brazaar2",
# collection="users",
# query=usersQuery,
# limit=1)
# if user :
# followingUsers.append(list(user))
# else :
# return {'error' : 'invalid user'}
# return dumps(followingUsers)
run(host='0.0.0.0', port=8080, debug=True, reloader=True, server="gevent")
# run(host='0.0.0.0', port=8082, debug=True)