server_controller.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import json
  2. from datetime import timedelta, datetime
  3. from math import ceil, floor
  4. from bottle import request, response
  5. from passlib.hash import sha256_crypt
  6. import model
  7. from debug import debug
  8. from util import salt
  9. def missing_attributes(attributes):
  10. for attr in attributes:
  11. if attr not in request.json or request.json[attr] == '' or request.json[attr] is None:
  12. if str(attr) == 'session_id':
  13. return 'You are not signed in.'
  14. return 'Missing value for attribute ' + str(attr)
  15. if str(attr) == 'session_id':
  16. if not model.valid_session_id(request.json['session_id']):
  17. return 'You are not signed in.'
  18. return False
  19. def login():
  20. if debug:
  21. missing = missing_attributes(['username'])
  22. else:
  23. missing = missing_attributes(['username', 'password'])
  24. if missing:
  25. return bad_request(missing)
  26. username = request.json['username']
  27. password = request.json['password']
  28. session_id = model.login(username, password)
  29. if session_id:
  30. return {'session_id': session_id}
  31. else:
  32. return forbidden('Invalid login data')
  33. def depot():
  34. missing = missing_attributes(['session_id'])
  35. if missing:
  36. return bad_request(missing)
  37. user_id = model.get_user_id_by_session_id(request.json['session_id'])
  38. return {'data': model.get_user_ownership(user_id),
  39. 'own_wealth': model.user_wealth(user_id)}
  40. def register():
  41. missing = missing_attributes(['username', 'password'])
  42. if missing:
  43. return bad_request(missing)
  44. username = request.json['username'].strip()
  45. if username == '':
  46. return bad_request('Username can not be empty.')
  47. hashed_password = sha256_crypt.encrypt(request.json['password'] + salt)
  48. if model.user_exists(username):
  49. return bad_request('User already exists.')
  50. game_key = ''
  51. if 'game_key' in request.json:
  52. game_key = request.json['game_key'].strip().upper()
  53. if game_key != '' and not model.valid_key(game_key):
  54. return bad_request('Game key is not valid.')
  55. if model.register(username, hashed_password, game_key):
  56. return {'message': "successfully registered user"}
  57. else:
  58. return bad_request('Registration not successful')
  59. def activate_key():
  60. missing = missing_attributes(['key', 'session_id'])
  61. if missing:
  62. return bad_request(missing)
  63. if model.valid_key(request.json['key']):
  64. user_id = model.get_user_id_by_session_id(request.json['session_id'])
  65. model.activate_key(request.json['key'], user_id)
  66. return {'message': "successfully activated key"}
  67. else:
  68. return bad_request('Invalid key.')
  69. def order():
  70. missing = missing_attributes(['buy', 'session_id', 'amount', 'ownable', 'time_until_expiration'])
  71. if missing:
  72. return bad_request(missing)
  73. if not model.ownable_name_exists(request.json['ownable']):
  74. return bad_request('This kind of object can not be ordered.')
  75. buy = request.json['buy']
  76. sell = not buy
  77. if not isinstance(buy, bool):
  78. return bad_request('`buy` must be a boolean')
  79. session_id = request.json['session_id']
  80. amount = request.json['amount']
  81. try:
  82. amount = int(amount)
  83. except ValueError:
  84. return bad_request('Invalid amount.')
  85. if amount < 0:
  86. return bad_request('You can not order a negative amount.')
  87. if amount < 1:
  88. return bad_request('The minimum order size is 1.')
  89. ownable_name = request.json['ownable']
  90. time_until_expiration = float(request.json['time_until_expiration'])
  91. if time_until_expiration < 0:
  92. return bad_request('Invalid expiration time.')
  93. ownable_id = model.ownable_id_by_name(ownable_name)
  94. user_id = model.get_user_id_by_session_id(session_id)
  95. model.own(user_id, ownable_name)
  96. ownership_id = model.get_ownership_id(ownable_id, user_id)
  97. try:
  98. if request.json['limit'] == '':
  99. limit = None
  100. elif request.json['limit'] is None:
  101. limit = None
  102. else:
  103. if buy:
  104. limit = floor(float(request.json['limit']) * 10000) / 10000
  105. else:
  106. limit = ceil(float(request.json['limit']) * 10000) / 10000
  107. except ValueError: # for example when float fails
  108. return bad_request('Invalid limit.')
  109. except KeyError: # for example when limit was not specified
  110. limit = None
  111. try:
  112. if request.json['stop_loss'] == '':
  113. stop_loss = None
  114. elif request.json['stop_loss'] is None:
  115. stop_loss = None
  116. else:
  117. stop_loss = 'stop_loss' in request.json and request.json['stop_loss']
  118. if stop_loss is not None and limit is None:
  119. return bad_request('Can only set stop-loss for limit orders')
  120. except KeyError: # for example when stop_loss was not specified
  121. stop_loss = None
  122. if sell:
  123. if not model.user_owns_at_least(amount, user_id, ownable_id):
  124. return bad_request('You can not sell more than you own.')
  125. try:
  126. expiry = datetime.strptime(model.current_db_time(), '%Y-%m-%d %H:%M:%S') + \
  127. timedelta(minutes=time_until_expiration)
  128. except OverflowError:
  129. return bad_request('The expiration time is too far in the future.')
  130. model.place_order(buy, ownership_id, limit, stop_loss, amount, expiry)
  131. return {'message': "Order placed."}
  132. def gift():
  133. missing = missing_attributes(['session_id', 'amount', 'object_name', 'username'])
  134. if missing:
  135. return bad_request(missing)
  136. if not model.ownable_name_exists(request.json['object_name']):
  137. return bad_request('This kind of object can not be given away.')
  138. if request.json['username'] == 'bank' or not model.user_exists(request.json['username']):
  139. return bad_request('There is no user with this name.')
  140. try:
  141. amount = float(request.json['amount'])
  142. except ValueError:
  143. return bad_request('Invalid amount.')
  144. ownable_id = model.ownable_id_by_name(request.json['object_name'])
  145. sender_id = model.get_user_id_by_session_id(request.json['session_id'])
  146. recipient_id = model.get_user_id_by_name(request.json['username'])
  147. if not model.user_owns_at_least(amount, sender_id, ownable_id):
  148. amount = model.available_amount(sender_id, ownable_id)
  149. model.send_ownable(sender_id,
  150. recipient_id,
  151. ownable_id,
  152. amount)
  153. return {'message': "Gift sent."}
  154. def orders():
  155. missing = missing_attributes(['session_id'])
  156. if missing:
  157. return bad_request(missing)
  158. data = model.get_user_orders(model.get_user_id_by_session_id(request.json['session_id']))
  159. return {'data': data}
  160. def orders_on():
  161. missing = missing_attributes(['session_id', 'ownable'])
  162. if missing:
  163. return bad_request(missing)
  164. if not model.ownable_name_exists(request.json['ownable']):
  165. return bad_request('This kind of object can not be ordered.')
  166. user_id = model.get_user_id_by_session_id(request.json['session_id'])
  167. ownable_id = model.ownable_id_by_name(request.json['ownable'])
  168. data = model.get_ownable_orders(user_id, ownable_id)
  169. return {'data': data}
  170. def old_orders():
  171. missing = missing_attributes(['session_id', 'include_canceled', 'include_executed', 'limit'])
  172. if missing:
  173. return bad_request(missing)
  174. include_executed = request.json['include_executed']
  175. include_canceled = request.json['include_canceled']
  176. user_id = model.get_user_id_by_session_id(request.json['session_id'])
  177. limit = request.json['limit']
  178. data = model.get_old_orders(user_id, include_executed, include_canceled, limit)
  179. return {'data': data}
  180. def cancel_order():
  181. missing = missing_attributes(['session_id', 'order_id'])
  182. if missing:
  183. return bad_request(missing)
  184. if not model.user_has_order_with_id(request.json['session_id'], request.json['order_id']):
  185. return bad_request('You do not have an order with that number.')
  186. model.delete_order(request.json['order_id'], 'Canceled')
  187. return {'message': "Successfully deleted order"}
  188. def change_password():
  189. missing = missing_attributes(['session_id', 'password'])
  190. if missing:
  191. return bad_request(missing)
  192. hashed_password = sha256_crypt.encrypt(request.json['password'] + salt)
  193. model.change_password(request.json['session_id'], hashed_password)
  194. model.sign_out_user(request.json['session_id'])
  195. return {'message': "Successfully changed password"}
  196. def news():
  197. return {'data': model.news()}
  198. def tradables():
  199. return {'data': model.ownables()}
  200. def trades():
  201. missing = missing_attributes(['session_id', 'limit'])
  202. if missing:
  203. return bad_request(missing)
  204. return {'data': model.trades(model.get_user_id_by_session_id(request.json['session_id']), request.json['limit'])}
  205. def trades_on():
  206. missing = missing_attributes(['session_id', 'ownable', 'limit'])
  207. if missing:
  208. return bad_request(missing)
  209. if not model.ownable_name_exists(request.json['ownable']):
  210. return bad_request('This kind of object can not have transactions.')
  211. return {'data': model.trades_on(model.ownable_id_by_name(request.json['ownable']), request.json['limit'])}
  212. def leaderboard():
  213. return {'data': model.leaderboard()}
  214. def not_found(msg=''):
  215. response.status = 404
  216. if debug:
  217. msg = str(response.status) + ': ' + msg
  218. response.content_type = 'application/json'
  219. return json.dumps({"error_message": msg})
  220. def forbidden(msg=''):
  221. response.status = 403
  222. if debug:
  223. msg = str(response.status) + ': ' + msg
  224. response.content_type = 'application/json'
  225. return json.dumps({"error_message": msg})
  226. def bad_request(msg=''):
  227. response.status = 400
  228. if debug:
  229. msg = str(response.status) + ': ' + msg
  230. response.content_type = 'application/json'
  231. return json.dumps({"error_message": msg})