server_controller.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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_has_at_least_available(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. if model.available_amount(sender_id, ownable_id) == 0:
  147. return bad_request('You do not own any of these.')
  148. if not model.user_has_at_least_available(amount, sender_id, ownable_id):
  149. # for example if you have a 1.23532143213 Kollar and want to give them all away
  150. amount = model.available_amount(sender_id, ownable_id)
  151. recipient_id = model.get_user_id_by_name(request.json['username'])
  152. model.send_ownable(sender_id,
  153. recipient_id,
  154. ownable_id,
  155. amount)
  156. return {'message': "Gift sent."}
  157. def orders():
  158. missing = missing_attributes(['session_id'])
  159. if missing:
  160. return bad_request(missing)
  161. data = model.get_user_orders(model.get_user_id_by_session_id(request.json['session_id']))
  162. return {'data': data}
  163. def orders_on():
  164. missing = missing_attributes(['session_id', 'ownable'])
  165. if missing:
  166. return bad_request(missing)
  167. if not model.ownable_name_exists(request.json['ownable']):
  168. return bad_request('This kind of object can not be ordered.')
  169. user_id = model.get_user_id_by_session_id(request.json['session_id'])
  170. ownable_id = model.ownable_id_by_name(request.json['ownable'])
  171. data = model.get_ownable_orders(user_id, ownable_id)
  172. return {'data': data}
  173. def old_orders():
  174. missing = missing_attributes(['session_id', 'include_canceled', 'include_executed', 'limit'])
  175. if missing:
  176. return bad_request(missing)
  177. include_executed = request.json['include_executed']
  178. include_canceled = request.json['include_canceled']
  179. user_id = model.get_user_id_by_session_id(request.json['session_id'])
  180. limit = request.json['limit']
  181. data = model.get_old_orders(user_id, include_executed, include_canceled, limit)
  182. return {'data': data}
  183. def cancel_order():
  184. missing = missing_attributes(['session_id', 'order_id'])
  185. if missing:
  186. return bad_request(missing)
  187. if not model.user_has_order_with_id(request.json['session_id'], request.json['order_id']):
  188. return bad_request('You do not have an order with that number.')
  189. model.delete_order(request.json['order_id'], 'Canceled')
  190. return {'message': "Successfully deleted order"}
  191. def change_password():
  192. missing = missing_attributes(['session_id', 'password'])
  193. if missing:
  194. return bad_request(missing)
  195. hashed_password = sha256_crypt.encrypt(request.json['password'] + salt)
  196. model.change_password(request.json['session_id'], hashed_password)
  197. model.sign_out_user(request.json['session_id'])
  198. return {'message': "Successfully changed password"}
  199. def news():
  200. return {'data': model.news()}
  201. def tradables():
  202. return {'data': model.ownables()}
  203. def trades():
  204. missing = missing_attributes(['session_id', 'limit'])
  205. if missing:
  206. return bad_request(missing)
  207. return {'data': model.trades(model.get_user_id_by_session_id(request.json['session_id']), request.json['limit'])}
  208. def trades_on():
  209. missing = missing_attributes(['session_id', 'ownable', 'limit'])
  210. if missing:
  211. return bad_request(missing)
  212. if not model.ownable_name_exists(request.json['ownable']):
  213. return bad_request('This kind of object can not have transactions.')
  214. return {'data': model.trades_on(model.ownable_id_by_name(request.json['ownable']), request.json['limit'])}
  215. def leaderboard():
  216. return {'data': model.leaderboard()}
  217. def not_found(msg=''):
  218. response.status = 404
  219. if debug:
  220. msg = str(response.status) + ': ' + msg
  221. response.content_type = 'application/json'
  222. return json.dumps({"error_message": msg})
  223. def forbidden(msg=''):
  224. response.status = 403
  225. if debug:
  226. msg = str(response.status) + ': ' + msg
  227. response.content_type = 'application/json'
  228. return json.dumps({"error_message": msg})
  229. def bad_request(msg=''):
  230. response.status = 400
  231. if debug:
  232. msg = str(response.status) + ': ' + msg
  233. response.content_type = 'application/json'
  234. return json.dumps({"error_message": msg})