-
Notifications
You must be signed in to change notification settings - Fork 3
/
models.py
97 lines (74 loc) · 2.55 KB
/
models.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
from flask_login import UserMixin
from passlib.handlers.sha2_crypt import sha256_crypt
from peewee import Model, OperationalError, CharField, BooleanField, ForeignKeyField, IntegerField
from redis import StrictRedis
from config import DB
redis = StrictRedis(decode_responses=True)
def db_init():
DB.connect()
try:
DB.create_tables([User])
print('Creating tables...')
except OperationalError:
pass
DB.close()
redis.delete('chatcount')
class BaseModel(Model):
class Meta:
database = DB
class User(BaseModel, UserMixin):
username = CharField(unique=True)
password = CharField(null=True)
admin = BooleanField(default=False)
ldap = BooleanField(default=False)
def check_password(self, password: str) -> bool:
if self.ldap:
from utils import ldap_auth
return ldap_auth(self.username, password)
return sha256_crypt.verify(password, self.password)
def set_password(self, password: str) -> None:
self.password = sha256_crypt.encrypt(password)
def unplayed_requests(self):
return self.requests.filter(done=False)
class SongRequest:
def __init__(self, uri: str):
self.uri = uri
self.data = redis.hgetall('request:' + uri)
def _vote(self, direction: int, user_id: str) -> None:
redis.set('vote:{}:{}'.format(self.uri, user_id), direction)
def vote_up(self, user_id: str) -> None:
redis.incr('votes:' + self.uri)
self._vote(1, user_id)
def vote_down(self, user_id: str) -> None:
redis.decr('votes:' + self.uri)
self._vote(-1, user_id)
@property
def user(self) -> str:
return str(self.data['user'])
@property
def title(self):
return self.data['title']
@property
def artist(self):
return self.data['artist']
@property
def votes(self) -> int:
try:
return int(redis.get('votes:' + self.uri))
except (ValueError, TypeError):
return 0
def get_user_vote(self, user_id: str) -> int:
try:
return int(redis.get('vote:{}:{}'.format(self.uri, user_id)))
except (ValueError, TypeError):
return 0
def delete(self) -> None:
redis.delete('votes:' + self.uri)
redis.srem('requests', self.uri)
redis.srem('user:' + self.user, self.uri)
def to_dict(self):
return {'title': self.data['title'],
'artist': self.data['artist'],
'uri': self.uri,
'votes': self.votes
}