Commit 617b9f83 authored by Tony's avatar Tony
Browse files

Update pagi: Accept, rapihin serverStatus (struktur collection), update...

Update pagi: Accept, rapihin serverStatus (struktur collection), update offer_token ke 32-digit md5 random
parent 2fc7bb43
......@@ -10,9 +10,12 @@ from pymongo import MongoClient
import hashlib
from hashlib import md5
import random
import uuid
from bson.objectid import ObjectId
def getRandomMd5():
return str(uuid.uuid4().hex)
#md5 hash function
def md5(string):
......@@ -28,6 +31,54 @@ db = client.gamesister
user = db.user
map = db.map
offer = db.offer
server = db.server
PORT = 8000
#Join procedure
def join():
#Connect to tracker
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
except socket.error:
print ('Failed to create socket')
sys.exit()
print ('Socket Created')
host = '167.205.32.46';
port = 8000
sock.connect((host , port))
ip = socket.gethostbyname(socket.gethostname())
str_ip = str(ip)
message = {"method": "join", "ip": "167.205.71.13", "port": PORT}
#message = {"method": "join", "ip": "167.205.71.13", "port": PORT}
try :
#Set the whole string
sock.sendall(bytes(json.dumps(message), 'UTF-8'))
response = sock.recv(4096)
except socket.error:
#Send failed
print ('Send failed')
sys.exit()
print (response.decode('UTF-8'))
#Now receive data from tracker
decoded = json.loads(response.decode('UTF-8'))
#join reply
if (decoded['status'] == "ok"):
server.remove({})
print(server.find().count())
for serv in decoded['value']:
server.insert({"ip": str(serv['ip']), "port": str(serv['port'])}) #Insert to database
elif (decoded['status'] == "error"):
print (decoded['description'])
#Defining All Items in Inventory
honey = 0
......@@ -60,18 +111,24 @@ def clientThread(conn):
#Receiving from client
json_input = conn.recv(4096)
if not json_input: #no data received
if not json_input: #empty data
break
else:
else: #data not empty
decoded = json.loads(json_input.decode('UTF-8'))
print (decoded)
#ServerStatus(tracker)
#if (decoded['method'] == 'serverStatus'):
if (decoded['method'] == "serverStatus"):
server.remove({})
for serv in decoded['server']:
server.insert({"ip": str(serv['ip']), "port": str(serv['port'])}) #Insert to database
reply = {"status": "ok"}
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break
#Signup(client)
if (decoded['method'] == "signup"):
elif (decoded['method'] == "signup"):
userQuery = user.find_one({"username": decoded['username'].lower()})
if (userQuery == None): #user available
#Assign Map for new user
......@@ -222,7 +279,8 @@ def clientThread(conn):
#update inventory
user.update({"_id": userQuery['_id']}, {"$inc": {"inventory."+ str(decoded['offered_item']) : -decoded['n1']}})
#insert new offer
offer.insert({"user_token": str(userQuery['_id']),
offer.insert({ "offer_token": getRandomMd5(),
"user_token": str(userQuery['_id']),
"offered_item": decoded['offered_item'],
"n_offered_item": decoded['n1'],
"demanded_item": decoded['demanded_item'],
......@@ -239,7 +297,7 @@ def clientThread(conn):
allOffer = offer.find({"user_token": decoded['token']})
offers = []
for off in allOffer:
singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['_id'])]
singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
offers.append(singleOffer)
reply = {"status": "ok", "offers": offers}
......@@ -253,7 +311,7 @@ def clientThread(conn):
allOffer = offer.find({"user_token": {"$ne": decoded['token']}, "offered_item": decoded['item'], "availability": True})
offers = []
for off in allOffer:
singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['_id'])]
singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
offers.append(singleOffer)
reply = {"status": "ok", "offers": offers}
......@@ -262,9 +320,11 @@ def clientThread(conn):
allOffer = offer.find({"offered_item": decoded['item']})
offers = []
for off in allOffer:
singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['_id'])]
singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
offers.append(singleOffer)
reply = {"status": "ok", "offers": offers}
print(reply)
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break;
......@@ -274,24 +334,42 @@ def clientThread(conn):
if (userQuery == None): #Invalid Request, token mismatch
reply = {"status": "error"}
else: #valid request
off = offer.find_one({"_id": ObjectId(decoded['offer_token'])})
off = offer.find_one({"offer_token": decoded['offer_token']})
if (off == None): #offer token not found
reply = {"status": "fail", "description": "offer not found"}
else: #offer found
if (off['n_demanded_item'] > userQuery['inventory'][off['demanded_item']]): #insufficient item
reply = {"status": "fail", "description": "you have insufficient item"}
else: #sufficient item. Accept OK
#update inventory of acceptor
user.update({'_id': ObjectId(decoded['token'])},{"$inc": {'inventory.'+str(off['demanded_item']): -off['n_demanded_item'],
'inventory.'+str(off['offered_item']): off['n_offered_item']}})
#turn availability of offer to false
offer.update({'_id': ObjectId(decoded['offer_token'])}, {"$set": {'availability': False}})
reply = {"status": "ok"}
if (off['availability']): #offer still available
if (off['n_demanded_item'] > userQuery['inventory'][off['demanded_item']]): #insufficient item
reply = {"status": "fail", "description": "you have insufficient item"}
else: #sufficient item. Accept OK
#update inventory of acceptor
user.update({'_id': ObjectId(decoded['token'])},{"$inc": {'inventory.'+str(off['demanded_item']): -off['n_demanded_item'],
'inventory.'+str(off['offered_item']): off['n_offered_item']}})
#turn availability of offer to false
offer.update({'offer_token': decoded['offer_token']}, {"$set": {'availability': False}})
reply = {"status": "ok"}
else: #offer already taken
reply = {"status": "fail", "description": "offer is already taken"}
#Accept(server)
#elif (decoded['method'] == 'accept'):
elif (decoded['method'] == 'accept'):
off = offer.find_one({"offer_token": decoded['offer_token']})
if (offer == None) : #offer token not found
reply = {"status": "fail", "description": "offer not found"}
else: #offer found
if (off['availability']): #offer still available
#turn availability of offer to false
offer.update({'offer_token': decoded['offer_token']}, {"$set": {'availability': False}})
reply = {"status": "ok"}
else: #offer already taken
reply = {"status": "fail", "description": "offer is already taken"}
print(reply)
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break;
#FetchItem(client)
elif (decoded['method'] == 'fetchitem'):
......@@ -299,7 +377,7 @@ def clientThread(conn):
if (userQuery == None): #Invalid Request, token mismatch
reply = {"status": "error"}
else: #valid request
off = offer.find_one({"_id": ObjectId(decoded['offer_token'])})
off = offer.find_one({"offer_token": decoded['offer_token']})
if (off == None): #offer token not found
reply = {"status": "fail", "description": "offer not found"}
else: #offer found
......@@ -310,7 +388,7 @@ def clientThread(conn):
user.update({'_id': ObjectId(decoded['token'])},{"$inc": {'inventory.'+str(off['demanded_item']): off['n_demanded_item']}})
#remove offer
offer.remove({'_id': ObjectId(decoded['offer_token'])})
offer.remove({'offer_token': decoded['offer_token']})
reply = {"status": "ok"}
#CancelOffer(client)
......@@ -319,13 +397,13 @@ def clientThread(conn):
if (userQuery == None): #Invalid Request, token mismatch
reply = {"status": "error"}
else: #valid request
off = offer.find_one({'_id': ObjectId(decoded['offer_token'])})
off = offer.find_one({'offer_token': decoded['offer_token']})
if (off == None): #Offer not found
reply = {"status": "fail", "description": "Offer not found"}
else: # Offer found
if (off['availability']): #offer still available, cancel OK
user.update({"_id": userQuery['_id']},{"$inc": {"inventory."+str(off['offered_item']): off['n_offered_item']}})
offer.remove({"_id": off['_id']})
offer.remove({"offer_token": off['offer_token']})
reply = {"status": "ok"}
else: # not available, offer already accepted (taken)
reply = {"status": "fail", "description": "Offer already accepted / taken"}
......@@ -333,7 +411,6 @@ def clientThread(conn):
print(reply)
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
except Exception as e:
break
......@@ -344,6 +421,10 @@ def clientThread(conn):
### MAIN PROGRAM ###
if __name__ == '__main__':
nMap = 2
#Join
#join()
# LOAD MAP
mapQuery = list(map.find())
if (not mapQuery): # if map Database still empty
......@@ -367,17 +448,18 @@ if __name__ == '__main__':
map.insert(data)
# MAKING SOCKET CONNECTION #
HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
#HOST = socket.gethostbyname(socket.gethostname()) # Symbolic name meaning all available interfaces
HOST = 'localhost'
#PORT = 8000 # Arbitrary non-privileged port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
#Bind socket to local host and port
try:
sock.bind((HOST, PORT))
except (socket.error, msg):
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
except (socket.error):
print ('Bind failed')
sys.exit()
print ('Socket bind complete')
......@@ -395,4 +477,4 @@ if __name__ == '__main__':
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientThread ,(conn,))
s.close()
\ No newline at end of file
sock.close()
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment