-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.py
453 lines (385 loc) · 16.8 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import datetime
import json
from decimal import Decimal
import sqlalchemy
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Float, desc, ForeignKey, or_, exc
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
from cfg import *
class SQLiteNumeric(sqlalchemy.types.TypeDecorator):
impl = sqlalchemy.types.String
def load_dialect_impl(self, dialect):
return dialect.type_descriptor(sqlalchemy.types.VARCHAR(200))
def process_bind_param(self, value, dialect):
if value is None:
return None
return str(value)
def process_result_value(self, value, dialect):
if value is None:
return None
return Decimal(value)
Base = declarative_base()
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
username = Column(String)
first_name = Column(String)
lang = Column(String)
fiat = Column(String)
exchanges = Column(Integer)
sum_rate = Column(Integer)
def __init__(self, tg_id, username, lang, name):
self.id = tg_id
self.username = username.lower()
self.lang = lang
self.first_name = name
self.exchanges = 0
self.sum_rate = 0
def get_average_rate(self):
return f"{(self.sum_rate / self.exchanges):.1f}"
def balance_in(self, currency):
for balance in self.balance:
if balance.currency == currency:
return balance.amount
return 0
class Operation(Base):
__tablename__ = "operation"
id = Column(Integer, primary_key=True)
type_ = Column(String)
currency = Column(String)
amount = Column(SQLiteNumeric)
user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("User", backref="operations")
confirmed = Column(Boolean)
pseudo_uid = Column(String)
date = Column(DateTime)
address = Column(String)
linked_operation_id = Column(Integer)
linked_operation = None
frozen = Column(Boolean)
notification_id = Column(Integer)
def __init__(self, user_id, type_, currency, amount, pseudo_uid=None, address=None):
self.user_id = user_id
self.type_ = type_
self.currency = currency
self.amount = amount
self.pseudo_uid = pseudo_uid
self.confirmed = False
self.date = datetime.datetime.now()
self.address = address
self.frozen = False
self.notification_id = None
def link(self, session):
if self.linked_operation_id:
self.linked_operation = session.query(Operation).filter(Operation.id == self.linked_operation_id).one()
def __repr__(self):
if self.type_ == "EscrowSell":
badge_type = "EscrowExchange"
else:
badge_type = self.type_
r = f"{badge_type} #{self.id} от @{self.user.username}: {self.amount:.{SYMBOLS[self.currency]}f} {self.currency}\n"
if self.linked_operation:
r += f"за {self.linked_operation.amount:.{SYMBOLS[self.linked_operation.currency]}f} {self.linked_operation.currency}"
if self.address:
r += f"Реквезиты: {self.address}"
if (self.currency in CRYPTO_CURRENCIES and self.type_ == "Deposit") \
or self.type_ == "FastSell" and self.currency in CRYPTO_CURRENCIES and self.linked_operation.currency in CRYPTO_CURRENCIES:
r += "Эта операция будет совершена автоматически"
return r
def format(self, user=None, counterparty=False, lang=None, rate=False, op_name=None, **kwargs):
if not user:
user = self.user
if not lang:
lang = user.lang
if self.type_ in ["Deposit", "Withdraw"]:
return f"{self.amount:.{SYMBOLS[self.currency]}f} {self.currency} {MSGS[lang][self.type_]} #{self.id}"
else:
if self.type_ == "FastSell":
badge_type = "FastExchange"
elif self.type_ == "EscrowSell":
badge_type = "EscrowExchange"
else:
badge_type = self.type_
if not op_name is None:
if op_name:
msg = op_name
else:
msg = f"{badge_type}:\n"
else:
msg = ""
msg += f"{MSGS[lang]['Buy']} {self.linked_operation.amount:.{SYMBOLS[self.linked_operation.currency]}f} {self.linked_operation.currency} |" \
f"{MSGS[lang]['Sell']} {self.amount:.{SYMBOLS[self.currency]}f} {self.currency}"
if rate:
if self.user.exchanges:
msg += f"\n{MSGS[lang]['UserRate'].format(self.user.username, self.user.exchanges, self.user.get_average_rate())}"
else:
msg += f"\n{MSGS[lang]['FirstExchange']}"
if self.type_ == "EscrowSell" and counterparty:
msg += f"\n{MSGS[lang]['Counterparty']}: @{self.linked_operation.user.username}"
return msg
class Balance(Base):
__tablename__ = "balance"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("User", backref="balance")
currency = Column(String)
amount = Column(SQLiteNumeric)
def __init__(self, user_id, currency, amount: Decimal):
self.user_id = user_id
self.currency = currency
self.amount = amount
class Order(Base):
__tablename__ = "order"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("User", backref="orders")
sell_currency = Column(String)
sell_amount = Column(SQLiteNumeric)
buy_currency = Column(String)
min_trade_amount = Column(SQLiteNumeric)
rate = Column(SQLiteNumeric)
def __init__(self, user_id, sell_currency, buy_currency, min_trade_amount, sell_amount, rate):
self.user_id = user_id
self.sell_currency = sell_currency
self.buy_currency = buy_currency
self.min_trade_amount = min_trade_amount
self.sell_amount = sell_amount
self.rate = rate
def format(self, lang="en", user=None, status=True, to_me=False):
if not user:
f_user = self.user
else:
f_user = user
if to_me:
username = ""
else:
username = "@" + f_user.username
r = MSGS[lang]["OrderFormat"].format(username, self.min_trade_amount, self.sell_amount,
self.sell_currency, self.rate, self.buy_currency)
if status:
if f_user.exchanges:
r += f"\n{MSGS[lang]['UserRate'].format(f_user.username, f_user.exchanges, f_user.get_average_rate())}"
else:
r += f"\n{MSGS[lang]['FirstExchange']}"
return r
class Handler:
def __init__(self, database_path=None, base=Base):
if database_path:
self.database_path = database_path
engine = sqlalchemy.create_engine(DB_STRING + '?check_same_thread=False')
base.metadata.create_all(engine)
self.sessionmaker = sessionmaker(bind=engine, expire_on_commit=False)
print("База данных подключена.")
def create_user(self, tg_id, username, lang, first_name):
session = self.sessionmaker()
user = User(tg_id, username, lang, first_name)
session.add(user)
session.commit()
def get_user(self, tg_id=None, username=None):
session = self.sessionmaker()
if tg_id:
user = session.query(User).filter(User.id == tg_id).one()
else:
user = session.query(User).filter(User.username == username).one()
# session.close()
return user
def update_user(self, tg_id, **kwargs):
session = self.sessionmaker()
user = session.query(User).filter(User.id == tg_id).one()
for attr_name in kwargs:
value = kwargs[attr_name]
setattr(user, attr_name, value)
session.commit()
def create_operation(self, user_id, type_, currency, pre_amount, address=None):
if type_ == "Deposit" and currency in CRYPTO_CURRENCIES:
deadline = datetime.datetime.now() - datetime.timedelta(days=7)
session = self.sessionmaker()
ops = session.query(Operation).filter(Operation.date < deadline).all()
for op in ops:
op.pseudo_uid = None
session.commit()
session = self.sessionmaker()
if type_ == "Deposit" and currency in CRYPTO_CURRENCIES:
uid = get_uid(pre_amount, currency)
while session.query(Operation).filter(Operation.confirmed == False).filter(
Operation.pseudo_uid == uid).first():
pre_amount += Decimal(1) / Decimal(10 ** UID_DIVIDER[currency])
uid = get_uid(pre_amount, currency)
amount = pre_amount
else:
amount = pre_amount
uid = None
operation = Operation(user_id, type_, currency, amount, uid, address)
session.add(operation)
session.commit()
return operation
def create_linked_operations(self, type_, user1_id, user2_id=None, sell_cur=None, sell_amount=None, buy_cur=None,
buy_amount=None):
session = self.sessionmaker()
if type_ == "FastExchange":
op_sell = Operation(user1_id, "FastSell", sell_cur, sell_amount)
session.add(op_sell)
op_buy = Operation(user1_id, "FastBuy", buy_cur, buy_amount)
session.add(op_buy)
session.commit()
op_sell.linked_operation_id = op_buy.id
op_sell.link(session)
session.commit()
return op_sell
elif type_ == "EscrowExchange":
op_sell = Operation(user1_id, "EscrowSell", sell_cur, sell_amount)
session.add(op_sell)
op_buy = Operation(user2_id, "EscrowBuy", buy_cur, buy_amount)
session.add(op_buy)
session.commit()
op_sell.linked_operation_id = op_buy.id
op_sell.link(session)
op_buy.linked_operation_id = op_sell.id
session.commit()
return op_sell
def freeze_operation(self, operation_id, freeze=True):
session = self.sessionmaker()
operation = session.query(Operation).filter(Operation.id == operation_id).one()
bal = session.query(Balance).filter(Balance.user_id == operation.user_id).filter(
Balance.currency == operation.currency).one()
if freeze:
bal.amount = bal.amount - operation.amount
else:
bal.amount = bal.amount + operation.amount
operation.frozen = freeze
session.commit()
def update_operation(self, id_=None, uid=None, confirm=False, **kwargs):
session = self.sessionmaker()
if id_:
op = session.query(Operation).filter(Operation.id == id_).one()
else:
op = session.query(Operation).filter(Operation.pseudo_uid == uid).filter(Operation.confirmed == False).one()
op.link(session)
if confirm:
self.execute_operation(op, session)
op.confirmed = True
if op.linked_operation:
if op.type_ in ["FastSell"]:
self.execute_operation(op.linked_operation, session)
op.linked_operation.confirmed = True
for attr_name in kwargs:
value = kwargs[attr_name]
setattr(op, attr_name, value)
session.commit()
return op.id
def get_operation(self, id_=None, uid=None):
session = self.sessionmaker()
if id_:
op = session.query(Operation).filter(Operation.id == id_).one()
else:
op = session.query(Operation).filter(Operation.pseudo_uid == uid).filter(Operation.confirmed == False).one()
# session.close()
op.link(session)
return op
def delete_operation(self, id_):
session = self.sessionmaker()
op = session.query(Operation).filter(Operation.id == id_).one()
op.link(session)
if op.linked_operation:
session.delete(op.linked_operation)
session.delete(op)
session.commit()
def test(self):
session = self.sessionmaker()
user = session.query(User).filter(User.username == "bobaK00").one()
print(user)
def execute_operation(self, operation, session):
if operation.type_ in ["Deposit", "FastBuy"]:
try:
bal = session.query(Balance).filter(Balance.user_id == operation.user_id).filter(
Balance.currency == operation.currency).one()
bal.amount = bal.amount + operation.amount
except exc.NoResultFound:
bal = Balance(operation.user_id, operation.currency, operation.amount)
session.add(bal)
elif operation.type_ in ["Withdraw", "FastSell"]:
bal = session.query(Balance).filter(Balance.user_id == operation.user_id).filter(
Balance.currency == operation.currency).one()
bal.amount = bal.amount - operation.amount
elif operation.type_ in ["EscrowSell", "EscrowBuy"]:
l_op = session.query(Operation).filter(Operation.id == operation.linked_operation_id).one()
try:
bal = session.query(Balance).filter(Balance.user_id == l_op.user_id).filter(
Balance.currency == operation.currency).one()
bal.amount = bal.amount + operation.amount
except exc.NoResultFound:
bal = Balance(l_op.user_id, operation.currency, operation.amount)
session.add(bal)
session.commit()
def create_order(self, user_id, sell_currency, buy_currency, min_trade_amount, sell_amount, rate):
session = self.sessionmaker()
order = Order(user_id, sell_currency, buy_currency, min_trade_amount, sell_amount, rate)
session.add(order)
session.commit()
self.freeze_order(order.id)
def freeze_order(self, order_id, freeze=True):
session = self.sessionmaker()
order = session.query(Order).filter(Order.id == order_id).one()
bal = session.query(Balance).filter(Balance.user_id == order.user_id).filter(
Balance.currency == order.sell_currency).one()
if freeze:
bal.amount = bal.amount - order.sell_amount
else:
bal.amount = bal.amount + order.sell_amount
session.commit()
def update_order(self, order_id, **kwargs):
session = self.sessionmaker()
order = session.query(Order).filter(Order.id == order_id).one()
for attr_name in kwargs:
value = kwargs[attr_name]
setattr(order, attr_name, value)
if "sell_amount" in kwargs:
if order.sell_amount < order.min_trade_amount:
order.min_trade_amount = order.sell_amount
session.commit()
def get_orders(self, sell_cur, buy_cur, user_id, self_=False):
session = self.sessionmaker()
if self_:
orders = session.query(Order).filter(Order.user_id == user_id).all()
else:
orders = session.query(Order).filter(Order.sell_currency == sell_cur).filter(
Order.buy_currency == buy_cur).filter(Order.user_id != user_id).all()
orders += session.query(Order).filter(Order.sell_currency == buy_cur).filter(
Order.buy_currency == sell_cur).filter(Order.user_id != user_id).all()
return orders
def get_order(self, order_id):
session = self.sessionmaker()
return session.query(Order).filter(Order.id == order_id).one()
def delete_order(self, order_id):
session = self.sessionmaker()
session.delete(session.query(Order).filter(Order.id == order_id).one())
session.commit()
def count_system_balances(self):
session = self.sessionmaker()
bals = SYMBOLS
for key in bals:
bals[key] = 0
for balance in session.query(Balance).all():
bals[balance.currency] += balance.amount
session.close()
return bals
def get_users(self):
session = self.sessionmaker()
return session.query(User).all()
def get_escrows(self, user_id):
session = self.sessionmaker()
operations = session.query(Operation).filter(
Operation.user_id == user_id).filter(Operation.type_ == "EscrowSell").filter(
Operation.confirmed == 0).all()
for operation in operations:
operation.link(session)
return operations
def get_uid(amount, currency):
amount = f"{amount:.8f}"
amount = amount[amount.find(".") + 1:]
divider = UID_DIVIDER[currency]
uid = int(amount[divider - 2:divider])
return uid
if __name__ == '__main__':
h = Handler()
h.test()