Commit 5c663f26 authored by opelhoward's avatar opelhoward
Browse files

add logic to handler

parent 149b9fe9
This diff is collapsed.
......@@ -38,6 +38,6 @@ class Map:
Map.__maps.insert_one(_map)
if __name__ == '__main__':
# MongoClient('localhost', 27017)['sister'].create_collection('maps')
MongoClient('localhost', 27017)['sister'].create_collection('maps')
peta = Map.get_map('Bandar Behari')
print(peta.get_item(0, 0))
\ No newline at end of file
......@@ -4,27 +4,45 @@ from pymongo import MongoClient
from inventory import Inventory;
class Offer:
class OfferMarket:
def __init__(self, offer):
self.offered_id = offer[0]
self.offered_amount = offer[1]
self.demanded_id = offer[2]
self.demanded_amount = offer[3]
self.availability = offer[4]
self.token = offer[5]
self.offered_id = offer['offered_item']
self.offered_amount = offer['offered_amount']
self.demanded_id = offer['demanded_item']
self.demanded_amount = offer['demanded_amount']
self.availability = offer['availability']
self.offer_token = offer['offer_token']
self.ip = offer['ip']
self.port = offer['port']
class Market:
def __init__(self, index):
self.__market = MongoClient('localhost', 27017)['sister']\
.get_collection(Inventory.get_item_names()[index].lower()+".market")
self.offers = []
for offer in self.__market.find():
self.offers.append(Offer(offer))
def update(self, offers):
self.__market.delete_many()
self.__market.insert_many(offers)
self.offers = []
for offer in self.__market.find():
self.offers.append(Offer(offer))
\ No newline at end of file
__market = MongoClient('localhost', 27017)['sister']\
.get_collection("market")
@staticmethod
def get_offers(item):
result = []
offers = Market.__market.find({'offered_item': item})
for offer in offers:
result.append(OfferMarket(offer))
return result
@staticmethod
def add(item_id, raw_offers, ip, port):
for offer in raw_offers:
Market.__market.insert_one({'offered_item': offer[0], 'offered_amount': offer[1],
'demanded_item': offer[2], 'demanded_amount': offer[3],
'availability': offer[4], 'offer_token': offer[5],
'ip': ip, 'port': port})
@staticmethod
def clear(item_id):
Market.__market.delete_many({'offered_item': item_id})
@staticmethod
def find(token):
offer = OfferMarket(Market.__market.find_one({'offer_token': token}))
return offer
@staticmethod
def accept(token):
OfferMarket(Market.__market.find_one_and_replace({'offer_token': token}, {'availability': False}))
\ No newline at end of file
......@@ -15,68 +15,88 @@ def invoke(data):
s.close()
return json.loads(data.decode('utf-8'))
print('invoking signup')
response = invoke('{"method": "signup","username": "dummy","password": "dummy"}')
print(response)
# print('invoking signup')
# response = invoke('{"method": "signup","username": "dummy","password": "dummy"}')
# print(response)
print('')
print('invoking login')
response = invoke(json.dumps({'method':'login','username':'dummy','password':'dummy'}))
response = invoke(json.dumps({'method': 'login', 'username': 'dummy', 'password': 'dummy'}))
token = response.get('token')
print(response)
print('')
print('invoking map')
response = invoke(json.dumps({"method":"map","token":token}))
move_list = []
# for x in range(0,response.get('width')):
# for y in range(0,response.get('height')):
# PASSED
# print('')
# print('invoking map')
# response = invoke(json.dumps({"method": "map", "token": token}))
# move_list = []
# for x in range(0, response.get('width')):
# for y in range(0, response.get('height')):
# move_list.append((x,y))
# PASSED
# print('')
# print('invoking move')
# for move in move_list:
# x, y = move
# time.sleep(5)
# response = invoke(json.dumps({'method':'move','token':token,'x':x,'y':y}))
# response = invoke(json.dumps({'method': 'move', 'token': token,'x': x, 'y': y}))
# print(response)
# PASSED
print('')
print('invoking field')
response = invoke(json.dumps({"method": "field","token":token}))
response = invoke(json.dumps({"method": "field", "token":token}))
print(response)
response = invoke(json.dumps({"method": "field","token":token}))
print(response)
print('')
print('invoking sendfind')
response = invoke(json.dumps({"method": "sendfind","item": 2,"token":token}))
response = invoke(json.dumps({"method": "field", "token":token}))
print(response)
# PASSED
# print('')
# print('invoking findoffer')
# response = invoke(json.dumps({"method": "findoffer", "item": 2}))
# print(response)
print('')
print('invoking inventory')
response = invoke(json.dumps({"method": "inventory","token":token}))
print(response)
# PASSED
# print('')
# print('invoking canceloffer')
# response = invoke(json.dumps({"method": "canceloffer", "token": token, 'offer_token': '5537d6c431e9e71044eb21e5'}))
# print(response)
print('')
print('invoking tradebox')
response = invoke(json.dumps({"method": "tradebox","token":token}))
print(response)
# PASSED
# print('')
# print('invoking sendfind')
# response = invoke(json.dumps({"method": "sendfind","item": 2,"token":token}))
# print(response)
print('')
print('invoking offer')
response = invoke(json.dumps({"method": "offer","token": token,"offered_item": 2,"n1": 1,"demanded_item": 1,"n2": 1}))
print(response)
# PASSED
# print('')
# print('invoking inventory')
# response = invoke(json.dumps({"method": "inventory", "token":token}))
# print(response)
#invoke abusive client
print('')
print('invoke abusive')
s = Socket.socket()
host = Socket.gethostname()
port = 8000
s.connect((host, port))
time.sleep(10)
# PASSED
# print('')
# print('invoking tradebox')
# response = invoke(json.dumps({"method": "tradebox","token":token}))
# print(response)
# PASSED
# print('')
# print('invoking offer')
# response = invoke(json.dumps({'method': 'offer', 'token': token, 'offered_item': 2, 'n1': 1, 'demanded_item': 1, 'n2': 1}))
# print(response)
# print('')
# print('invoking accept')
# response = invoke(json.dumps({"method": "accept", "offer_token": token}))
# print(response)
#invoke abusive client
# print('')
# print('invoke abusive')
# s = Socket.socket()
# host = Socket.gethostname()
# port = 8000
# s.connect((host, port))
# time.sleep(10)
\ No newline at end of file
......@@ -6,6 +6,8 @@ import select
import codecs
from user import User
from map import Map
from tradebox import Tradebox
from market import Market
from ssocketio import SocketIO
......@@ -111,8 +113,8 @@ class ConnectionHandler:
# invoke controller signup
def handle_signup(self,username,password):
data = ""
if not User.is_exist(username):
data = json.dumps({'status': 'fail', 'description':'username exists'})
if User.is_exist(username):
data = json.dumps({'status': 'fail', 'description': 'username exists'})
else:
User.sign_up(username, password)
data = json.dumps({'status': 'ok'})
......@@ -128,11 +130,7 @@ class ConnectionHandler:
data = json.dumps({'status': 'fail','description': 'username/password combination is not found'})
else:
user = User.get_user(username)
print(user.id)
print(user.location.x)
print(user.location.y)
print(user.time)
data = json.dumps({'status': 'ok','token': str(user.id),
data = json.dumps({'status': 'ok', 'token': str(user.id),
'x': user.location.x, 'y': user.location.y,
'time': user.time})
try:
......@@ -142,8 +140,8 @@ class ConnectionHandler:
# invoke inventory
def handle_inventory(self,token):
# do something
data = json.dumps({'status':'ok','description':'stub inventory'})
user = User(token)
data = json.dumps({'status':'ok', 'inventory': user.inventory.items})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -151,7 +149,15 @@ class ConnectionHandler:
# invoke mix item
def handle_mixitem(self,token,item1,item2):
# do something
user = User(token)
if (user.inventory.items[item1] > 0) and (user.inventory.items[item2] > 0):
mixitem = -1
#remember to implement this
user.inventory.items[mixitem] += 1
user.inventory.items[item1] -= 1
user.inventory.items[item2] -= 1
else:
data = json.dumps({'status': 'fail', 'description': 'FAILURE MESSAGE HERE'})
data = json.dumps({'status':'ok','description':'stub mixitem'})
try:
self._socketio.write_to_socket(data.encode('ascii'))
......@@ -159,21 +165,23 @@ class ConnectionHandler:
print(msg)
# invoke map
def handle_map(self,token):
map = Map('Bandar Behari')
data = json.dumps({'status':'ok','name': map.name, 'width': map.width, 'height': map.height})
def handle_map(self, token):
map = Map.get_map('Bandar Behari')
data = json.dumps({'status': 'ok', 'name': map.name, 'width': int(map.width), 'height': int(map.height)})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
print(msg)
# invoke move
def handle_move(self,token,x,y):
def handle_move(self, token, x, y):
# do something
user = User(token)
(user.location.x, user.location.y) = (x, y);
user.time = time.time()
user.save()
data = json.dumps({'status':'ok','description':'stub move'})
data = json.dumps({'status': 'ok', 'time': user.time})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -181,17 +189,33 @@ class ConnectionHandler:
# invoke field
def handle_field(self,token):
# do something
data = json.dumps({'status':'ok','description':'stub field'})
data = ''
user = User(token)
map = Map.get_map('Bandar Behari')
if (user.location.x == user.prev_location.x) and (user.location.y == user.prev_location.y):
data = json.dumps({'status': 'fail','description': 'FAILURE MESSAGE HERE"'})
else:
new_item = map.get_item(user.location.x, user.location.y)
user.inventory.items[new_item] += 1;
(user.prev_location.x, user.prev_location.y) = (user.location.x, user.location.y)
user.save()
data = json.dumps({'status': 'ok', 'item': new_item})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
print(msg)
# invoke offer
def handle_offer(self,token,offered_item,n1,demanded_item,n2):
# do something
data = json.dumps({'status':'ok','description':'stub offer'})
def handle_offer(self, token, offered_item, n1, demanded_item, n2):
data = ''
user = User(token)
if user.inventory.items[offered_item] < n1:
data = json.dumps({'status': 'fail', 'description': 'insufficient"'})
else:
user.inventory.items[offered_item] -= n1;
user.save()
Tradebox.add_offer(token, offered_item, n1, demanded_item, n2);
data = json.dumps({'status': 'ok'})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -199,8 +223,13 @@ class ConnectionHandler:
# invoke tradebox
def handle_tradebox(self,token):
# do something
data = json.dumps({'status':'ok','description':'stub tradebox'})
offers = Tradebox.get_offers(token)
result = []
for offer in offers:
result.append((offer.offered_id, offer.offered_amount, offer.demanded_id, offer.demanded_amount,
offer.availability, str(offer.id)))
print(result);
data = json.dumps({'status':'ok', 'offers': result})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -209,6 +238,7 @@ class ConnectionHandler:
# invoke sendfind
def handle_sendfind(self,token,item):
#tambahin server abusive
Market.clear(item)
offer_list = []
# untuk setiap server lain
......@@ -246,13 +276,35 @@ class ConnectionHandler:
response = json.loads(data.decode('utf-8'))
server_offer_list = response.get('offers',[])
print('Result : ',end='')
Market.add(item, server_offer_list, host, port)
print(server_offer_list)
offer_list.extend(server_offer_list)
except ValueError as ve:
i = 1 # do nothing
print(offer_list)
offer_list = Market.get_offers(item)
my_offers = Tradebox.get_offers(token)
delete_list = []
count = -1
for offer in offer_list:
count += 1
for my_offer in my_offers:
if offer.offer_token == my_offer.id:
delete_list.append(count)
for index in delete_list:
delete_list.pop(index)
raw_offer_list = []
for offer in offer_list:
raw_offer_list.append([offer.offered_id, offer.offered_amount, offer.demanded_id, offer.demanded_amount,
offer.availability, offer.offer_token])
data = json.dumps({'status':'ok','offers':offer_list})
data = json.dumps({'status':'ok','offers': raw_offer_list})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -266,7 +318,12 @@ class ConnectionHandler:
time.sleep(SocketIO.TEST_ABUSIVE_SERVER_DELAY)
# lakukan query ke database untuk mendapatkan daftar offerings
data = json.dumps({'status':'ok','description':'stub findoffer'})
offers = Tradebox.find_offer_item(item)
raw_offers = []
for offer in offers:
raw_offers.append([offer.offered_id, offer.offered_amount, offer.demanded_id, offer.demanded_amount,
offer.availability, str(offer.id)])
data = json.dumps({'status': 'ok', 'offers': raw_offers})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -274,17 +331,52 @@ class ConnectionHandler:
# invoke accept
def handle_accept(self,offer_token):
# do something
data = json.dumps({'status':'ok','description':'stub accept'})
data = ''
offer = Tradebox.find_offer_id(offer_token)
if offer.availability:
offer.availability = False
offer.save()
data = json.dumps({'status': 'ok'})
else:
data = json.dumps({'status': 'fail','description': 'offer is not available'})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
print(msg)
# invoke send accept
def handle_sendaccept(self, token, offer_token):
data = ''
offer = Market.find(offer_token)
if offer.availability:
Market.accept(offer_token)
# ini bagian yafi
data = json.dumps({'status': 'ok'})
else:
data = json.dumps({'status': 'fail', 'description': 'offer is not available'})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
print(msg)
# invoke map
def handle_fetchitem(self,token,offer_token):
# do something
data = json.dumps({'status':'ok','description':'stub fetchitem'})
offer = Tradebox.find_offer_id(offer_token)
if (offer.user_id == token) and (offer.availability == True):
user = User(token)
user.inventory.items[offer.demanded_id] += offer.demanded_amount
user.save()
offer.availability = False
offer.save()
data = json.dumps({'status':'ok'})
else:
data = json.dumps({'status':'fail','description': 'FAILURE MESSAGE HERE'})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......@@ -292,8 +384,20 @@ class ConnectionHandler:
# invoke map
def handle_canceloffer(self,token,offer_token):
# do something
data = json.dumps({'status':'ok','description':'stub offertoken'})
data = ''
user = User(token)
offer = Tradebox.find_offer_id(offer_token)
if offer.availability:
offer.delete()
user.inventory.items[offer.offered_id] += offer.offered_amount
user.save()
data = json.dumps({'status': 'ok'})
else:
data = json.dumps({'status': 'fail', 'description': 'FAILURE MESSAGE HERE'})
try:
self._socketio.write_to_socket(data.encode('ascii'))
except Exception as msg:
......
__author__ = 'Willy'
from pymongo import MongoClient
import random
import string
import hashlib
from singleton import Singleton
from bson.objectid import ObjectId
class Offer:
def __init__(self, user_id, offer):
self.offered_id = offer["offered_item"]
self.offered_amount = offer["n1"]
self.demanded_id = offer["demanded_item"]
self.demanded_amount = offer["n2"]
self.availability = True
self.token = hashlib.md5(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)).
encode()).hexdigest()
self.user_id = user_id
__market = MongoClient('localhost', 27017)['sister'].get_collection('tradebox')
def __init__(self, _offer):
self.id = _offer["_id"]
self.offered_id = _offer["offered_item"]
self.offered_amount = _offer["n1"]
self.demanded_id = _offer["demanded_item"]
self.demanded_amount = _offer["n2"]
self.availability = _offer["availability"]
self.user_id = _offer["user_id"]
def save(self):
self.__market.find_one_and_replace({'_id': self.id},
{'_id': self.id,
'offered_item': self.offered_id, 'n1': self.offered_amount,
'demanded_item': self.demanded_id, 'n2': self.demanded_amount,
'availability': self.availability, 'user_id': self.user_id})
def delete(self):
self.__market.find_one_and_delete({'_id': self.id})
class Tradebox(object):
__singleton
class Tradebox():
def __init__(self):
__market = MongoClient('localhost', 27017)['sister'].get_collection('tradebox')
# self.__market = MongoClient('localhost', 27017)['sister'].get_collection('tradebox')
self.__offers = []
# for offer in self.__market.find():
# self.offers.append(Offer(offer))
@staticmethod
def add_offer(user_id, offered_item, n1, demanded_item, n2):
Tradebox.__market.insert({"user_id": user_id, 'offered_item': offered_item, 'n1': n1,
'demanded_item': demanded_item, 'n2': n2, 'availability': True})
def add_offer(self, user_id, raw_offer):
self.__offers.append(Offer(user_id, raw_offer))
@staticmethod
def get_offers(user_id):
result = []
for _offer in Tradebox.__market.find({'user_id': user_id}):
result.append(Offer(_offer))
return result
def get_offers(self, user_id):
@staticmethod
def find_offer_item(item_id):
result = []
for offer in self.__offers:
if offer.user_id == user_id:
result.append(offer)
for _offer in Tradebox.__market.find({'offered_item': item_id}):
result.append(Offer(_offer))
return result
def find_offer(self, token):
for offer in self.__offers:
if offer.token == token:
return offer
return None
@staticmethod
def find_offer_id(token):
_offer = Offer(Tradebox.__market.find_one({'_id': ObjectId(token)}))
return _offer
if __name__ == '__main__':
# MongoClient('localhost', 27017)['sister'].create_collection('tradebox')
......
......@@ -2,6 +2,7 @@ __author__ = 'Willy'
from pymongo import MongoClient
from inventory import Inventory
from bson.objectid import ObjectId
class Location:
......@@ -12,15 +13,17 @@ class Location:
(self.x, self.y) = (x, y)
class User:
__users = MongoClient('localhost', 27017)['sister'].get_collection('users')
def __init__(self, id):
_user = self.__users.find_one({"_id": id})
_user = self.__users.find_one({"_id": ObjectId(id)})
self.id = _user['_id']
self.username = _user['username']
self.password = _user['password']
self.location = Location(_user['location']['x'], _user['location']['y'])
self.prev_location = Location(_user['prev_location']['x'], _user['prev_location']['y'])
self.time = _user['time']
self.inventory = Inventory(_user['inventory'])