model.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. import random
  2. import re
  3. import sqlite3 as db
  4. import sys
  5. import uuid
  6. from datetime import timedelta, datetime
  7. from math import floor
  8. import db_setup
  9. from game import CURRENCY_NAME
  10. from util import random_chars
  11. from debug import debug
  12. # connection: db.Connection = None
  13. # cursor: db.Cursor = None
  14. connection = None # no type annotations in python 3.5
  15. cursor = None # no type annotations in python 3.5
  16. db_name = None
  17. def query_save_name():
  18. global db_name
  19. if debug:
  20. db_name = 'test.db'
  21. return
  22. while True:
  23. save_name = input('Name of the savegame: ')
  24. if re.match(r"[A-Za-z0-9.-]{0,50}", save_name):
  25. db_name = save_name + '.db'
  26. return
  27. else:
  28. print('Must match "[A-Za-z0-9.-]{0,50}"')
  29. def connect(reconnect=False):
  30. global connection
  31. global cursor
  32. global db_name
  33. if reconnect:
  34. connection.commit()
  35. connection.close()
  36. cursor = None
  37. connection = None
  38. db_name = None
  39. if connection is None or cursor is None:
  40. query_save_name()
  41. try:
  42. connection = db.connect(db_name)
  43. # connection.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')
  44. cursor = connection.cursor()
  45. except db.Error as e:
  46. print("Database error %s:" % e.args[0])
  47. sys.exit(1)
  48. # finally:
  49. # if con is not None:
  50. # con.close()
  51. def setup():
  52. connect()
  53. db_setup.setup(cursor)
  54. connection.commit()
  55. def used_key_count():
  56. connect()
  57. cursor.execute('''
  58. SELECT COUNT(*)
  59. FROM keys
  60. WHERE used_by_user_id IS NOT NULL
  61. ''')
  62. return cursor.fetchone()[0]
  63. def login(username, password):
  64. connect()
  65. # do not allow login as bank
  66. if password == '':
  67. return None
  68. cursor.execute('''
  69. SELECT rowid
  70. FROM users
  71. WHERE username = ?
  72. AND password = ?
  73. ''', (username, password))
  74. user_id = cursor.fetchone()
  75. if user_id:
  76. return new_session(user_id)
  77. else:
  78. return None
  79. def register(username, password, game_key):
  80. connect()
  81. if username == '':
  82. return False
  83. if password == '':
  84. return False
  85. cursor.execute('''
  86. INSERT INTO users
  87. (username, password)
  88. VALUES (? , ?)
  89. ''', (username, password))
  90. own(get_user_id_by_name(username), CURRENCY_NAME)
  91. if game_key != '':
  92. if valid_key(game_key):
  93. activate_key(game_key, get_user_id_by_name(username))
  94. return True
  95. def own(user_id, ownable_name):
  96. if not isinstance(ownable_name, str):
  97. return AssertionError('A name must be a string.')
  98. cursor.execute('''
  99. WITH one_ownable_id AS (SELECT rowid FROM ownables WHERE name = ?),
  100. one_user_id AS (SELECT ?)
  101. INSERT INTO ownership (user_id, ownable_id)
  102. SELECT *
  103. FROM one_user_id, one_ownable_id
  104. WHERE NOT EXISTS (
  105. SELECT * FROM ownership
  106. WHERE ownership.user_id IN one_user_id
  107. AND ownership.ownable_id IN one_ownable_id
  108. )
  109. ''', (ownable_name, user_id,))
  110. def send_ownable(from_user_id, to_user_id, ownable_name, amount):
  111. connect()
  112. if amount < 0:
  113. return False
  114. if from_user_id != bank_id():
  115. cursor.execute('''
  116. UPDATE ownership
  117. SET amount = amount - ?
  118. WHERE user_id = ?
  119. AND ownable_id = (SELECT rowid FROM ownables WHERE name = ?)
  120. ''', (amount, from_user_id, ownable_name,))
  121. cursor.execute('''
  122. UPDATE ownership
  123. SET amount = amount + ?
  124. WHERE user_id = ?
  125. AND ownable_id = (SELECT rowid FROM ownables WHERE name = ?)
  126. ''', (amount, to_user_id, ownable_name))
  127. return True
  128. def valid_key(key):
  129. connect()
  130. cursor.execute('''
  131. SELECT key
  132. FROM keys
  133. WHERE used_by_user_id IS NULL
  134. AND key = ?
  135. ''', (key,))
  136. if cursor.fetchone():
  137. return True
  138. else:
  139. return False
  140. def new_session(user_id):
  141. connect()
  142. session_id = str(uuid.uuid4())
  143. cursor.execute('''
  144. INSERT INTO SESSIONS
  145. (user_id, session_id)
  146. VALUES (? , ?)
  147. ''', (user_id[0], session_id))
  148. return session_id
  149. def save_key(key):
  150. connect()
  151. cursor.execute('''
  152. INSERT INTO keys
  153. (key)
  154. VALUES (?)
  155. ''', (key,))
  156. def drop_old_sessions():
  157. connect()
  158. cursor.execute('''
  159. DELETE FROM sessions
  160. WHERE
  161. (SELECT COUNT(*) as newer
  162. FROM sessions s2
  163. WHERE user_id = s2.user_id
  164. AND rowid < s2.rowid) >= 10
  165. ''')
  166. def user_exists(username):
  167. connect()
  168. cursor.execute('''
  169. SELECT rowid
  170. FROM users
  171. WHERE username = ?
  172. ''', (username,))
  173. if cursor.fetchone():
  174. return True
  175. else:
  176. return False
  177. def unused_keys():
  178. connect()
  179. cursor.execute('''
  180. SELECT key
  181. FROM keys
  182. WHERE used_by_user_id IS NULL
  183. ''')
  184. return [str(key[0]).strip().upper() for key in cursor.fetchall()]
  185. def get_user_id_by_session_id(session_id):
  186. connect()
  187. cursor.execute('''
  188. SELECT users.rowid
  189. FROM sessions, users
  190. WHERE sessions.session_id = ?
  191. AND users.rowid = sessions.user_id
  192. ''', (session_id,))
  193. ids = cursor.fetchone()
  194. if not ids:
  195. return False
  196. return ids[0]
  197. def get_user_id_by_name(username):
  198. connect()
  199. cursor.execute('''
  200. SELECT users.rowid
  201. FROM users
  202. WHERE username = ?
  203. ''', (username,))
  204. return cursor.fetchone()[0]
  205. def get_user_ownership(user_id):
  206. connect()
  207. cursor.execute('''
  208. SELECT
  209. ownables.name,
  210. ownership.amount,
  211. COALESCE (
  212. CASE -- sum score for each of the users ownables
  213. WHEN ownership.ownable_id = ? THEN 1
  214. ELSE (SELECT price
  215. FROM transactions
  216. WHERE ownable_id = ownership.ownable_id
  217. ORDER BY dt DESC
  218. LIMIT 1)
  219. END, 0) AS price,
  220. (SELECT MAX("limit")
  221. FROM orders, ownership o2
  222. WHERE o2.rowid = orders.ownership_id
  223. AND o2.ownable_id = ownership.ownable_id
  224. AND buy
  225. AND NOT stop_loss) AS bid,
  226. (SELECT MIN("limit")
  227. FROM orders, ownership o2
  228. WHERE o2.rowid = orders.ownership_id
  229. AND o2.ownable_id = ownership.ownable_id
  230. AND NOT buy
  231. AND NOT stop_loss) AS ask
  232. FROM ownership, ownables
  233. WHERE user_id = ?
  234. AND ownership.amount > 0
  235. AND ownership.ownable_id = ownables.rowid
  236. ''', (currency_id(), user_id,))
  237. return cursor.fetchall()
  238. def activate_key(key, user_id):
  239. connect()
  240. cursor.execute('''
  241. UPDATE keys
  242. SET used_by_user_id = ?
  243. WHERE used_by_user_id IS NULL
  244. AND key = ?
  245. ''', (user_id, key,))
  246. send_ownable(bank_id(), user_id, CURRENCY_NAME, 1000)
  247. def bank_id():
  248. connect()
  249. cursor.execute('''
  250. SELECT users.rowid
  251. FROM users
  252. WHERE username = 'bank'
  253. ''')
  254. return cursor.fetchone()[0]
  255. def valid_session_id(session_id):
  256. connect()
  257. cursor.execute('''
  258. SELECT rowid
  259. FROM sessions
  260. WHERE session_id = ?
  261. ''', (session_id,))
  262. if cursor.fetchone():
  263. return True
  264. else:
  265. return False
  266. def get_user_orders(user_id):
  267. connect()
  268. cursor.execute('''
  269. SELECT
  270. CASE
  271. WHEN orders.buy THEN 'Buy'
  272. ELSE 'Sell'
  273. END,
  274. ownables.name,
  275. orders.ordered_amount - orders.executed_amount,
  276. orders."limit",
  277. CASE
  278. WHEN orders."limit" IS NULL THEN NULL
  279. WHEN orders.stop_loss THEN 'Yes'
  280. ELSE 'No'
  281. END,
  282. orders.ordered_amount,
  283. datetime(orders.expiry_dt),
  284. orders.rowid
  285. FROM orders, ownables, ownership
  286. WHERE ownership.user_id = ?
  287. AND ownership.ownable_id = ownables.rowid
  288. AND orders.ownership_id = ownership.rowid
  289. ORDER BY ownables.name ASC, orders.stop_loss ASC, orders.buy DESC, orders."limit" ASC
  290. ''', (user_id,))
  291. return cursor.fetchall()
  292. def get_ownable_orders(ownable_id):
  293. connect()
  294. cursor.execute('''
  295. SELECT
  296. CASE
  297. WHEN orders.buy THEN 'Buy'
  298. ELSE 'Sell'
  299. END,
  300. ownables.name,
  301. orders.ordered_amount - orders.executed_amount,
  302. orders."limit",
  303. CASE
  304. WHEN orders."limit" IS NULL THEN NULL
  305. WHEN orders.stop_loss THEN 'Yes'
  306. ELSE 'No'
  307. END,
  308. datetime(orders.expiry_dt),
  309. orders.rowid
  310. FROM orders, ownables, ownership
  311. WHERE ownership.ownable_id = ?
  312. AND ownership.ownable_id = ownables.rowid
  313. AND orders.ownership_id = ownership.rowid
  314. ORDER BY ownables.name ASC, orders.stop_loss ASC, orders.buy DESC, orders."limit" ASC
  315. ''', (ownable_id,))
  316. return cursor.fetchall()
  317. def sell_ordered_amount(user_id, ownable_id):
  318. connect()
  319. # if ownable_id == currency_id():
  320. # return 0
  321. cursor.execute('''
  322. SELECT COALESCE(SUM(orders.ordered_amount - orders.executed_amount),0)
  323. FROM orders, ownership
  324. WHERE ownership.rowid = orders.ownership_id
  325. AND ownership.user_id = ?
  326. AND ownership.ownable_id = ?
  327. AND NOT orders.buy
  328. ''', (user_id, ownable_id))
  329. return cursor.fetchone()[0]
  330. def user_owns_at_least(amount, user_id, ownable_id):
  331. connect()
  332. if not isinstance(amount, float) and not isinstance(amount, int):
  333. # comparison of float with strings does not work so well in sql
  334. raise AssertionError()
  335. cursor.execute('''
  336. SELECT rowid
  337. FROM ownership
  338. WHERE user_id = ?
  339. AND ownable_id = ?
  340. AND amount - ? >= ?
  341. ''', (user_id, ownable_id, sell_ordered_amount(user_id, ownable_id), amount))
  342. if cursor.fetchone():
  343. return True
  344. else:
  345. return False
  346. def news():
  347. connect()
  348. cursor.execute('''
  349. SELECT * FROM
  350. (SELECT *
  351. FROM news
  352. ORDER BY dt DESC
  353. LIMIT 20) n
  354. ORDER BY dt ASC
  355. ''')
  356. return cursor.fetchall()
  357. def ownable_name_exists(name):
  358. connect()
  359. cursor.execute('''
  360. SELECT rowid
  361. FROM ownables
  362. WHERE name = ?
  363. ''', (name,))
  364. if cursor.fetchone():
  365. return True
  366. else:
  367. return False
  368. def new_stock(timeout=60, name=None):
  369. connect()
  370. while name is None:
  371. name = random_chars(6)
  372. if ownable_name_exists(name):
  373. name = None
  374. cursor.execute('''
  375. INSERT INTO ownables(name)
  376. VALUES (?)
  377. ''', (name,))
  378. cursor.execute('''
  379. INSERT INTO news(title)
  380. VALUES (?)
  381. ''', ('A new stock can now be bought: ' + name,))
  382. if random.getrandbits(1):
  383. cursor.execute('''
  384. INSERT INTO news(title)
  385. VALUES (?)
  386. ''', ('Experts expect the price of ' + name + ' to fall',))
  387. else:
  388. cursor.execute('''
  389. INSERT INTO news(title)
  390. VALUES (?)
  391. ''', ('Experts expect the price of ' + name + ' to rise',))
  392. amount = random.randrange(100, 10000)
  393. price = random.randrange(10000, 20000) / amount
  394. ownable_id = ownable_id_by_name(name)
  395. own(bank_id(), name)
  396. bank_order(False,
  397. ownable_id,
  398. price,
  399. amount,
  400. timeout)
  401. return name
  402. def new_stocks(timeout=60, count=1):
  403. return [new_stock(timeout=timeout) for _ in range(count)]
  404. def ownable_id_by_name(ownable_name):
  405. connect()
  406. cursor.execute('''
  407. SELECT rowid
  408. FROM ownables
  409. WHERE name = ?
  410. ''', (ownable_name,))
  411. return cursor.fetchone()[0]
  412. def get_ownership_id(ownable_id, user_id):
  413. connect()
  414. cursor.execute('''
  415. SELECT rowid
  416. FROM ownership
  417. WHERE ownable_id = ?
  418. AND user_id = ?
  419. ''', (ownable_id, user_id,))
  420. return cursor.fetchone()[0]
  421. def currency_id():
  422. connect()
  423. cursor.execute('''
  424. SELECT rowid
  425. FROM ownables
  426. WHERE name = ?
  427. ''', (CURRENCY_NAME,))
  428. return cursor.fetchone()[0]
  429. def user_money(user_id):
  430. connect()
  431. cursor.execute('''
  432. SELECT amount
  433. FROM ownership
  434. WHERE user_id = ?
  435. AND ownable_id = ?
  436. ''', (user_id, currency_id()))
  437. return cursor.fetchone()[0]
  438. def delete_order(order_id):
  439. connect()
  440. cursor.execute('''
  441. DELETE FROM orders
  442. WHERE rowid = ?
  443. ''', (order_id,))
  444. def current_value(ownable_id):
  445. connect()
  446. cursor.execute('''SELECT price
  447. FROM transactions
  448. WHERE ownable_id = ?
  449. ORDER BY dt DESC
  450. LIMIT 1
  451. ''', (ownable_id,))
  452. return cursor.fetchone()[0]
  453. def execute_orders(ownable_id):
  454. connect()
  455. while True:
  456. # find order to execute
  457. cursor.execute('''
  458. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  459. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  460. WHERE buy_order.buy AND NOT sell_order.buy
  461. AND buyer.rowid = buy_order.ownership_id
  462. AND seller.rowid = sell_order.ownership_id
  463. AND buyer.ownable_id = ?
  464. AND seller.ownable_id = ?
  465. AND (buy_order."limit" IS NULL
  466. OR sell_order."limit" IS NULL
  467. OR (sell_order."limit" <= buy_order."limit"
  468. AND NOT sell_order.stop_loss
  469. AND NOT buy_order.stop_loss))
  470. ORDER BY CASE WHEN sell_order."limit" IS NULL THEN 0 ELSE 1 END ASC,
  471. CASE WHEN buy_order."limit" IS NULL THEN 0 ELSE 1 END ASC,
  472. buy_order."limit" DESC,
  473. sell_order."limit" ASC,
  474. buy_order.ordered_amount - buy_order.executed_amount DESC,
  475. sell_order.ordered_amount - sell_order.executed_amount DESC
  476. LIMIT 1
  477. ''', (ownable_id, ownable_id,))
  478. matching_orders = cursor.fetchone()
  479. # return type: (ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  480. # ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  481. # user_id,user_id,rowid,rowid)
  482. if not matching_orders:
  483. break
  484. buy_ownership_id, _, buy_limit, _, buy_order_amount, buy_executed_amount, buy_expiry_dt, \
  485. sell_ownership_id, _, sell_limit, _, sell_order_amount, sell_executed_amount, sell_expiry_dt, \
  486. buyer_id, seller_id, buy_order_id, sell_order_id \
  487. = matching_orders
  488. if buy_limit is None and sell_limit is None:
  489. price = current_value(ownable_id)
  490. elif buy_limit is None:
  491. price = sell_limit
  492. elif sell_limit is None:
  493. price = buy_limit
  494. else: # both not NULL
  495. price = (float(sell_limit) + float(buy_limit)) / 2
  496. if price == 0:
  497. raise AssertionError()
  498. buyer_money = user_money(buyer_id)
  499. amount = min(buy_order_amount - buy_executed_amount,
  500. sell_order_amount - sell_executed_amount,
  501. floor(buyer_money / price))
  502. if amount == 0: # probable because buyer has not enough money
  503. delete_order(buy_order_id)
  504. continue
  505. buy_order_finished = (buy_order_amount - buy_executed_amount - amount <= 0) or (
  506. buyer_money - amount * price < price)
  507. sell_order_finished = (sell_order_amount - sell_executed_amount - amount <= 0)
  508. if price < 0 or amount <= 0:
  509. return AssertionError()
  510. # actually execute the order, but the bank does not send or receive anything
  511. if buyer_id != bank_id(): # buyer pays
  512. cursor.execute('''
  513. UPDATE ownership
  514. SET amount = amount - ?
  515. WHERE user_id = ?
  516. AND ownable_id = ?
  517. ''', (price * amount, buyer_id, currency_id()))
  518. if seller_id != bank_id(): # seller pays
  519. cursor.execute('''
  520. UPDATE ownership
  521. SET amount = amount - ?
  522. WHERE rowid = ?
  523. ''', (amount, sell_ownership_id))
  524. if buyer_id != bank_id(): # buyer receives
  525. cursor.execute('''
  526. UPDATE ownership
  527. SET amount = amount + ?
  528. WHERE rowid = ?
  529. ''', (amount, buy_ownership_id))
  530. if seller_id != bank_id(): # seller receives
  531. cursor.execute('''
  532. UPDATE ownership
  533. SET amount = amount + ?
  534. WHERE user_id = ?
  535. AND ownable_id = ?
  536. ''', (price * amount, seller_id, currency_id()))
  537. # update order execution state
  538. cursor.execute('''
  539. UPDATE orders
  540. SET executed_amount = executed_amount + ?
  541. WHERE rowid = ?
  542. OR rowid = ?
  543. ''', (amount, buy_order_id, sell_order_id))
  544. if buy_order_finished:
  545. delete_order(buy_order_id)
  546. if sell_order_finished:
  547. delete_order(sell_order_id)
  548. if seller_id != buyer_id: # prevent showing self-transactions
  549. cursor.execute('''
  550. INSERT INTO transactions
  551. (price, ownable_id, amount)
  552. VALUES(?, ?, ?)
  553. ''', (price, ownable_id, amount,))
  554. # trigger stop loss orders
  555. if buyer_id != seller_id:
  556. cursor.execute('''
  557. UPDATE orders
  558. SET stop_loss = NULL,
  559. "limit" = NULL
  560. WHERE stop_loss IS NOT NULL
  561. AND stop_loss
  562. AND ? IN (SELECT ownable_id FROM ownership WHERE rowid = ownership_id)
  563. AND ((buy AND "limit" < ?) OR (NOT buy AND "limit" > ?))
  564. ''', (ownable_id, price, price,))
  565. def ownable_id_by_ownership_id(ownership_id):
  566. connect()
  567. cursor.execute('''
  568. SELECT ownable_id
  569. FROM ownership
  570. WHERE rowid = ?
  571. ''', (ownership_id,))
  572. return cursor.fetchone()[0]
  573. def ownable_name_by_id(ownable_id):
  574. connect()
  575. cursor.execute('''
  576. SELECT name
  577. FROM ownables
  578. WHERE rowid = ?
  579. ''', (ownable_id,))
  580. return cursor.fetchone()[0]
  581. def bank_order(buy, ownable_id, limit, amount, time_until_expiration):
  582. if not limit:
  583. raise AssertionError('The bank does not give away anything.')
  584. place_order(buy,
  585. get_ownership_id(ownable_id, bank_id()),
  586. limit,
  587. False,
  588. amount,
  589. time_until_expiration)
  590. ownable_name = ownable_name_by_id(ownable_id)
  591. cursor.execute('''
  592. INSERT INTO news(title)
  593. VALUES (?)
  594. ''', ('External investors are selling ' + ownable_name + ' atm',))
  595. def current_time(): # might differ from datetime.datetime.now() for time zone reasons
  596. connect()
  597. cursor.execute('''
  598. SELECT datetime('now')
  599. ''')
  600. return cursor.fetchone()[0]
  601. def place_order(buy, ownership_id, limit, stop_loss, amount, time_until_expiration):
  602. connect()
  603. expiry = datetime.strptime(current_time(), '%Y-%m-%d %H:%M:%S') + timedelta(minutes=time_until_expiration)
  604. cursor.execute('''
  605. INSERT INTO orders
  606. (buy, ownership_id, "limit", stop_loss, ordered_amount, expiry_dt)
  607. VALUES (?, ?, ?, ?, ?, ?)
  608. ''', (buy, ownership_id, limit, stop_loss, amount, expiry))
  609. execute_orders(ownable_id_by_ownership_id(ownership_id))
  610. return True
  611. def transactions(ownable_id):
  612. connect()
  613. cursor.execute('''
  614. SELECT dt, amount, price
  615. FROM transactions
  616. WHERE ownable_id = ?
  617. ORDER BY dt DESC
  618. ''', (ownable_id,))
  619. return cursor.fetchall()
  620. def drop_expired_orders():
  621. connect()
  622. cursor.execute('''
  623. DELETE FROM orders
  624. WHERE expiry_dt < DATETIME('now')
  625. ''')
  626. return cursor.fetchall()
  627. def generate_keys(count=1):
  628. # source https://stackoverflow.com/questions/17049308/python-3-3-serial-key-generator-list-problems
  629. for i in range(count):
  630. key = '-'.join(random_chars(5) for _ in range(5))
  631. save_key(key)
  632. print(key)
  633. def user_has_order_with_id(session_id, order_id):
  634. connect()
  635. cursor.execute('''
  636. SELECT orders.rowid
  637. FROM orders, ownership, sessions
  638. WHERE orders.rowid = ?
  639. AND sessions.session_id = ?
  640. AND sessions.user_id = ownership.user_id
  641. AND ownership.rowid = orders.ownership_id
  642. ''', (order_id, session_id,))
  643. if cursor.fetchone():
  644. return True
  645. else:
  646. return False
  647. def leaderboard():
  648. connect()
  649. cursor.execute('''
  650. SELECT *
  651. FROM ( -- one score for each user
  652. SELECT
  653. username,
  654. SUM(CASE -- sum score for each of the users ownables
  655. WHEN ownership.ownable_id = ? THEN ownership.amount
  656. ELSE ownership.amount * (SELECT price
  657. FROM transactions
  658. WHERE ownable_id = ownership.ownable_id
  659. ORDER BY dt DESC
  660. LIMIT 1)
  661. END
  662. ) score
  663. FROM users, ownership
  664. WHERE ownership.user_id = users.rowid
  665. AND users.username != 'bank'
  666. GROUP BY users.rowid
  667. ) AS scores
  668. ORDER BY score DESC
  669. LIMIT 50
  670. ''', (currency_id(),))
  671. return cursor.fetchall()
  672. def user_wealth(user_id):
  673. connect()
  674. cursor.execute('''
  675. SELECT SUM(
  676. CASE -- sum score for each of the users ownables
  677. WHEN ownership.ownable_id = ? THEN ownership.amount
  678. ELSE ownership.amount * (SELECT price
  679. FROM transactions
  680. WHERE ownable_id = ownership.ownable_id
  681. ORDER BY dt DESC
  682. LIMIT 1)
  683. END
  684. ) score
  685. FROM ownership
  686. WHERE ownership.user_id = ?
  687. ''', (currency_id(), user_id,))
  688. return cursor.fetchone()[0]
  689. def change_password(session_id, password):
  690. connect()
  691. cursor.execute('''
  692. UPDATE users
  693. SET password = ?
  694. WHERE ? IN (SELECT session_id FROM sessions WHERE sessions.user_id = users.rowid)
  695. ''', (password, session_id,))
  696. def sign_out_user(session_id):
  697. connect()
  698. cursor.execute('''
  699. DELETE FROM sessions
  700. WHERE user_id = (SELECT user_id FROM sessions s2 WHERE s2.session_id = ?)
  701. ''', (session_id,))
  702. def delete_user(user_id):
  703. connect()
  704. cursor.execute('''
  705. DELETE FROM sessions
  706. WHERE user_id = ?
  707. ''', (user_id,))
  708. cursor.execute('''
  709. DELETE FROM orders
  710. WHERE ownership_id IN (
  711. SELECT rowid FROM ownership WHERE user_id = ?)
  712. ''', (user_id,))
  713. cursor.execute('''
  714. DELETE FROM ownership
  715. WHERE user_id = ?
  716. ''', (user_id,))
  717. cursor.execute('''
  718. DELETE FROM keys
  719. WHERE used_by_user_id = ?
  720. ''', (user_id,))
  721. cursor.execute('''
  722. INSERT INTO news(title)
  723. VALUES ((SELECT username FROM users WHERE rowid = ?) || ' retired.')
  724. ''', (user_id,))
  725. cursor.execute('''
  726. DELETE FROM users
  727. WHERE rowid = ?
  728. ''', (user_id,))
  729. def delete_ownable(ownable_id):
  730. connect()
  731. cursor.execute('''
  732. DELETE FROM transactions
  733. WHERE ownable_id = ?
  734. ''', (ownable_id,))
  735. cursor.execute('''
  736. DELETE FROM orders
  737. WHERE ownership_id IN (
  738. SELECT rowid FROM ownership WHERE ownable_id = ?)
  739. ''', (ownable_id,))
  740. # only delete empty ownerships
  741. cursor.execute('''
  742. DELETE FROM ownership
  743. WHERE ownable_id = ?
  744. AND amount = 0
  745. ''', (ownable_id,))
  746. cursor.execute('''
  747. INSERT INTO news(title)
  748. VALUES ((SELECT name FROM ownables WHERE rowid = ?) || ' can not be traded any more.')
  749. ''', (ownable_id,))
  750. cursor.execute('''
  751. DELETE FROM ownables
  752. WHERE rowid = ?
  753. ''', (ownable_id,))