By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 models.py

View raw Download
text/x-script.python • 11.54 kiB
Python script, ASCII text executable
        
            
1
from app import app, db
2
import git
3
from datetime import datetime
4
from enum import Enum
5
from PIL import Image
6
from cairosvg import svg2png
7
8
with app.app_context():
9
class RepoAccess(db.Model):
10
id = db.Column(db.Integer, primary_key=True)
11
userUsername = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
12
repoRoute = db.Column(db.String(98), db.ForeignKey("repo.route"), nullable=False)
13
accessLevel = db.Column(db.SmallInteger(), nullable=False) # 0 read-only, 1 read-write, 2 admin
14
15
user = db.relationship("User", back_populates="repoAccess")
16
repo = db.relationship("Repo", back_populates="repoAccess")
17
18
__table_args__ = (db.UniqueConstraint("userUsername", "repoRoute", name="_user_repo_uc"),)
19
20
def __init__(self, user, repo, level):
21
self.userUsername = user.username
22
self.repoRoute = repo.route
23
self.accessLevel = level
24
25
26
class RepoFavourite(db.Model):
27
id = db.Column(db.Integer, primary_key=True)
28
userUsername = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
29
repoRoute = db.Column(db.String(98), db.ForeignKey("repo.route"), nullable=False)
30
31
user = db.relationship("User", back_populates="favourites")
32
repo = db.relationship("Repo", back_populates="favourites")
33
34
__table_args__ = (db.UniqueConstraint("userUsername", "repoRoute", name="_user_repo_uc1"),)
35
36
def __init__(self, user, repo):
37
self.userUsername = user.username
38
self.repoRoute = repo.route
39
40
41
class PostVote(db.Model):
42
id = db.Column(db.Integer, primary_key=True)
43
userUsername = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
44
postIdentifier = db.Column(db.String(109), db.ForeignKey("post.identifier"), nullable=False)
45
voteScore = db.Column(db.SmallInteger(), nullable=False)
46
47
user = db.relationship("User", back_populates="votes")
48
post = db.relationship("Post", back_populates="votes")
49
50
__table_args__ = (db.UniqueConstraint("userUsername", "postIdentifier", name="_user_post_uc"),)
51
52
def __init__(self, user, post, score):
53
self.userUsername = user.username
54
self.postIdentifier = post.identifier
55
self.voteScore = score
56
57
58
class User(db.Model):
59
username = db.Column(db.String(32), unique=True, nullable=False, primary_key=True)
60
displayName = db.Column(db.Unicode(128), unique=False, nullable=True)
61
bio = db.Column(db.Unicode(512), unique=False, nullable=True)
62
passwordHashed = db.Column(db.String(60), nullable=False)
63
email = db.Column(db.String(254), nullable=True)
64
company = db.Column(db.Unicode(64), nullable=True)
65
companyURL = db.Column(db.String(256), nullable=True)
66
URL = db.Column(db.String(256), nullable=True)
67
showMail = db.Column(db.Boolean, default=False, nullable=False)
68
location = db.Column(db.Unicode(64), nullable=True)
69
creationDate = db.Column(db.DateTime, default=datetime.utcnow)
70
71
repositories = db.relationship("Repo", back_populates="owner")
72
followers = db.relationship("UserFollow", back_populates="followed", foreign_keys="[UserFollow.followedUsername]")
73
follows = db.relationship("UserFollow", back_populates="follower", foreign_keys="[UserFollow.followerUsername]")
74
repoAccess = db.relationship("RepoAccess", back_populates="user")
75
votes = db.relationship("PostVote", back_populates="user")
76
favourites = db.relationship("RepoFavourite", back_populates="user")
77
78
commits = db.relationship("Commit", back_populates="owner")
79
posts = db.relationship("Post", back_populates="owner")
80
notifications = db.relationship("UserNotification", back_populates="user")
81
82
def __init__(self, username, password, email=None, displayName=None):
83
self.username = username
84
self.passwordHashed = bcrypt.generate_password_hash(password, config.HASHING_ROUNDS).decode("utf-8")
85
self.email = email
86
self.displayName = displayName
87
88
# Create the user's directory
89
if not os.path.exists(os.path.join(config.REPOS_PATH, username)):
90
os.makedirs(os.path.join(config.REPOS_PATH, username))
91
if not os.path.exists(os.path.join(config.USERDATA_PATH, username)):
92
os.makedirs(os.path.join(config.USERDATA_PATH, username))
93
94
avatarName = random.choice(os.listdir(config.DEFAULT_AVATARS_PATH))
95
if os.path.join(config.DEFAULT_AVATARS_PATH, avatarName).endswith(".svg"):
96
cairosvg.svg2png(url=os.path.join(config.DEFAULT_AVATARS_PATH, avatarName),
97
write_to="/tmp/roundabout-avatar.png")
98
avatar = Image.open("/tmp/roundabout-avatar.png")
99
else:
100
avatar = Image.open(os.path.join(config.DEFAULT_AVATARS_PATH, avatarName))
101
avatar.thumbnail(config.AVATAR_SIZE)
102
avatar.save(os.path.join(config.USERDATA_PATH, username, "avatar.png"))
103
104
105
class Repo(db.Model):
106
route = db.Column(db.String(98), unique=True, nullable=False, primary_key=True)
107
ownerName = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
108
name = db.Column(db.String(64), nullable=False)
109
owner = db.relationship("User", back_populates="repositories")
110
visibility = db.Column(db.SmallInteger(), nullable=False)
111
info = db.Column(db.Unicode(512), nullable=True)
112
URL = db.Column(db.String(256), nullable=True)
113
creationDate = db.Column(db.DateTime, default=datetime.utcnow)
114
115
defaultBranch = db.Column(db.String(64), nullable=True, default="")
116
117
commits = db.relationship("Commit", back_populates="repo")
118
posts = db.relationship("Post", back_populates="repo")
119
repoAccess = db.relationship("RepoAccess", back_populates="repo")
120
favourites = db.relationship("RepoFavourite", back_populates="repo")
121
122
lastPostID = db.Column(db.Integer, nullable=False, default=0)
123
124
def __init__(self, owner, name, visibility):
125
self.route = f"/{owner.username}/{name}"
126
self.name = name
127
self.ownerName = owner.username
128
self.owner = owner
129
self.visibility = visibility
130
131
# Add the owner as an admin
132
repoAccess = RepoAccess(owner, self, 2)
133
db.session.add(repoAccess)
134
135
136
class Commit(db.Model):
137
identifier = db.Column(db.String(227), unique=True, nullable=False, primary_key=True)
138
sha = db.Column(db.String(128), nullable=False)
139
repoName = db.Column(db.String(98), db.ForeignKey("repo.route"), nullable=False)
140
ownerName = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
141
ownerIdentity = db.Column(db.String(321))
142
receiveDate = db.Column(db.DateTime, default=datetime.now)
143
authorDate = db.Column(db.DateTime)
144
message = db.Column(db.UnicodeText)
145
repo = db.relationship("Repo", back_populates="commits")
146
owner = db.relationship("User", back_populates="commits")
147
148
def __init__(self, sha, owner, repo, date, message, ownerIdentity):
149
self.identifier = f"{repo.route}/{sha}"
150
self.sha = sha
151
self.repoName = repo.route
152
self.repo = repo
153
self.ownerName = owner.username
154
self.owner = owner
155
self.authorDate = datetime.fromtimestamp(int(date))
156
self.message = message
157
self.ownerIdentity = ownerIdentity
158
159
160
class Post(db.Model):
161
identifier = db.Column(db.String(109), unique=True, nullable=False, primary_key=True)
162
number = db.Column(db.Integer, nullable=False)
163
repoName = db.Column(db.String(98), db.ForeignKey("repo.route"), nullable=False)
164
ownerName = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
165
votes = db.relationship("PostVote", back_populates="post")
166
voteSum = db.Column(db.Integer, nullable=False, default=0)
167
168
parentID = db.Column(db.String(109), db.ForeignKey("post.identifier"), nullable=True)
169
state = db.Column(db.SmallInteger, nullable=True, default=1)
170
171
date = db.Column(db.DateTime, default=datetime.now)
172
lastUpdated = db.Column(db.DateTime, default=datetime.now)
173
subject = db.Column(db.Unicode(384))
174
message = db.Column(db.UnicodeText)
175
repo = db.relationship("Repo", back_populates="posts")
176
owner = db.relationship("User", back_populates="posts")
177
parent = db.relationship("Post", back_populates="children", remote_side="Post.identifier")
178
children = db.relationship("Post", back_populates="parent", remote_side="Post.parentID")
179
180
def __init__(self, owner, repo, parent, subject, message):
181
self.identifier = f"{repo.route}/{repo.lastPostID}"
182
self.number = repo.lastPostID
183
self.repoName = repo.route
184
self.repo = repo
185
self.ownerName = owner.username
186
self.owner = owner
187
self.subject = subject
188
self.message = message
189
self.parent = parent
190
repo.lastPostID += 1
191
192
def updateDate(self):
193
self.lastUpdated = datetime.now()
194
with db.session.no_autoflush:
195
if self.parent is not None:
196
self.parent.updateDate()
197
198
199
class UserNotification(db.Model):
200
id = db.Column(db.Integer, primary_key=True)
201
userUsername = db.Column(db.String(32), db.ForeignKey("user.username"), nullable=False)
202
notificationID = db.Column(db.BigInteger, db.ForeignKey("notification.id"))
203
attentionLevel = db.Column(db.SmallInteger, nullable=False) # 0 is read
204
readTime = db.Column(db.DateTime, nullable=True)
205
206
user = db.relationship("User", back_populates="notifications")
207
notification = db.relationship("Notification", back_populates="notifications")
208
209
__table_args__ = (db.UniqueConstraint("userUsername", "notificationID", name="_user_notification_uc"),)
210
211
def __init__(self, user, notification, level):
212
self.userUsername = user.username
213
self.notificationID = notification.id
214
self.attentionLevel = level
215
216
def read(self):
217
self.readTime = datetime.utcnow
218
self.attentionLevel = 0
219
220
221
class UserFollow(db.Model):
222
id = db.Column(db.Integer, primary_key=True)
223
followerUsername = db.Column(db.String(32), db.ForeignKey("user.username", ondelete="CASCADE"), nullable=False)
224
followedUsername = db.Column(db.String(32), db.ForeignKey("user.username", ondelete="CASCADE"), nullable=False)
225
226
follower = db.relationship("User", back_populates="follows", foreign_keys=[followedUsername])
227
followed = db.relationship("User", back_populates="followers", foreign_keys=[followerUsername])
228
229
def __init__(self, followerUsername, followedUsername):
230
self.followerUsername = followerUsername
231
self.followedUsername = followedUsername
232
233
234
class Notification(db.Model):
235
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
236
data = db.Column(db.dialects.postgresql.JSONB, nullable=False, default={})
237
notifications = db.relationship("UserNotification", back_populates="notification")
238
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.now)
239
240
def __init__(self, json):
241
self.data = json
242
243
def sendTo(self, users, level):
244
for user in users:
245
db.session.add(UserNotification(user, self, level))
246
247