contentdb/app/models.py

408 lines
12 KiB
Python
Raw Normal View History

2018-03-18 18:43:30 +01:00
from flask import Flask, url_for
2018-03-18 19:05:53 +01:00
from flask_sqlalchemy import SQLAlchemy
2018-03-18 18:43:30 +01:00
from app import app
from datetime import datetime
from sqlalchemy.orm import validates
from flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter
2018-03-20 01:44:47 +01:00
import enum
2018-03-18 18:43:30 +01:00
# Initialise database
db = SQLAlchemy(app)
2018-03-20 04:16:46 +01:00
class UserRank(enum.Enum):
2018-03-20 05:03:13 +01:00
NOT_JOINED = 0
NEW_MEMBER = 1
MEMBER = 2
EDITOR = 3
MODERATOR = 4
ADMIN = 5
2018-03-20 04:16:46 +01:00
def atLeast(self, min):
return self.value >= min.value
2018-03-20 04:32:14 +01:00
def getTitle(self):
return self.name.replace("_", " ").title()
2018-03-24 20:37:33 +01:00
def toName(self):
return self.name.lower()
def __str__(self):
return self.name
@classmethod
def choices(cls):
return [(choice, choice.getTitle()) for choice in cls]
@classmethod
def coerce(cls, item):
return item if type(item) == UserRank else UserRank[item]
2018-03-20 05:11:50 +01:00
class Permission(enum.Enum):
EDIT_PACKAGE = "EDIT_PACKAGE"
APPROVE_CHANGES = "APPROVE_CHANGES"
DELETE_PACKAGE = "DELETE_PACKAGE"
CHANGE_AUTHOR = "CHANGE_AUTHOR"
MAKE_RELEASE = "MAKE_RELEASE"
APPROVE_RELEASE = "APPROVE_RELEASE"
APPROVE_NEW = "APPROVE_NEW"
CHANGE_RELEASE_URL = "CHANGE_RELEASE_URL"
2018-03-24 20:37:33 +01:00
CHANGE_RANK = "CHANGE_RANK"
2018-03-20 05:11:50 +01:00
# Only return true if the permission is valid for *all* contexts
# See Package.checkPerm for package-specific contexts
2018-03-21 20:03:14 +01:00
def check(self, user):
2018-03-21 20:24:45 +01:00
if not user.is_authenticated:
return False
if self == Permission.APPROVE_NEW or \
self == Permission.APPROVE_CHANGES or \
self == Permission.APPROVE_RELEASE:
2018-03-21 20:03:14 +01:00
return user.rank.atLeast(UserRank.EDITOR)
else:
raise Exception("Non-global permission checked globally. Use Package.checkPerm or User.checkPerm instead.")
2018-03-20 05:11:50 +01:00
2018-03-18 18:43:30 +01:00
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
# User authentication information
username = db.Column(db.String(50), nullable=False, unique=True)
2018-03-21 23:03:37 +01:00
password = db.Column(db.String(255), nullable=False, server_default="")
reset_password_token = db.Column(db.String(100), nullable=False, server_default="")
2018-03-18 18:43:30 +01:00
2018-03-20 04:16:46 +01:00
rank = db.Column(db.Enum(UserRank))
2018-03-18 19:05:53 +01:00
# Account linking
github_username = db.Column(db.String(50), nullable=True, unique=True)
forums_username = db.Column(db.String(50), nullable=True, unique=True)
2018-03-18 18:43:30 +01:00
# User email information
email = db.Column(db.String(255), nullable=True, unique=True)
confirmed_at = db.Column(db.DateTime())
# User information
2018-03-21 23:03:37 +01:00
active = db.Column("is_active", db.Boolean, nullable=False, server_default="0")
display_name = db.Column(db.String(100), nullable=False, server_default="")
2018-03-18 18:43:30 +01:00
# Content
2018-03-21 23:03:37 +01:00
packages = db.relationship("Package", backref="author", lazy="dynamic")
2018-03-23 20:08:55 +01:00
requests = db.relationship("EditRequest", backref="author", lazy="dynamic")
2018-03-18 18:43:30 +01:00
def __init__(self, username):
import datetime
self.username = username
self.confirmed_at = datetime.datetime.now() - datetime.timedelta(days=6000)
2018-03-18 19:05:53 +01:00
self.display_name = username
2018-03-20 05:03:13 +01:00
self.rank = UserRank.NOT_JOINED
2018-03-18 18:43:30 +01:00
def isClaimed(self):
return self.rank.atLeast(UserRank.NEW_MEMBER)
2018-03-18 18:43:30 +01:00
2018-03-24 20:37:33 +01:00
def checkPerm(self, user, perm):
if not user.is_authenticated:
return False
if type(perm) == str:
perm = Permission[perm]
elif type(perm) != Permission:
raise Exception("Unknown permission given to User.checkPerm()")
# Members can edit their own packages, and editors can edit any packages
if perm == Permission.CHANGE_AUTHOR:
return user.rank.atLeast(UserRank.EDITOR)
elif perm == Permission.CHANGE_RANK:
2018-03-24 20:37:33 +01:00
return user.rank.atLeast(UserRank.MODERATOR)
else:
raise Exception("Permission {} is not related to users".format(perm.name))
2018-04-03 15:13:11 +02:00
class License(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False, unique=True)
packages = db.relationship("Package", backref="license", lazy="dynamic")
def __init__(self, v):
self.name = v
def __str__(self):
return self.name
2018-03-20 01:44:47 +01:00
class PackageType(enum.Enum):
MOD = "Mod"
GAME = "Game"
TXP = "Texture Pack"
2018-03-20 04:32:14 +01:00
def toName(self):
2018-03-20 05:11:50 +01:00
return self.name.lower()
def __str__(self):
return self.name
2018-03-20 03:58:31 +01:00
@classmethod
def choices(cls):
return [(choice, choice.value) for choice in cls]
@classmethod
def coerce(cls, item):
2018-03-20 05:11:50 +01:00
return item if type(item) == PackageType else PackageType[item]
2018-03-20 03:58:31 +01:00
2018-03-23 20:08:55 +01:00
class PackagePropertyKey(enum.Enum):
2018-03-23 20:25:48 +01:00
name = "Name"
title = "Title"
shortDesc = "Short Description"
desc = "Description"
type = "Type"
2018-04-03 15:13:11 +02:00
license = "License"
tags = "Tags"
2018-03-23 20:25:48 +01:00
repo = "Repository"
website = "Website"
issueTracker = "Issue Tracker"
forums = "Forum Topic ID"
2018-03-23 20:08:55 +01:00
def convert(self, value):
if self == PackagePropertyKey.tags:
return ','.join([t.title for t in value])
else:
return str(value)
2018-03-26 12:28:34 +02:00
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
db.Column('package_id', db.Integer, db.ForeignKey('package.id'), primary_key=True)
)
2018-03-23 20:08:55 +01:00
2018-03-19 19:25:13 +01:00
class Package(db.Model):
2018-03-20 01:44:47 +01:00
id = db.Column(db.Integer, primary_key=True)
2018-03-18 18:43:30 +01:00
# Basic details
2018-03-21 23:03:37 +01:00
author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
2018-03-20 01:44:47 +01:00
name = db.Column(db.String(100), nullable=False)
title = db.Column(db.String(100), nullable=False)
2018-03-21 18:42:43 +01:00
shortDesc = db.Column(db.String(200), nullable=False)
2018-03-20 01:44:47 +01:00
desc = db.Column(db.Text, nullable=True)
type = db.Column(db.Enum(PackageType))
2018-03-18 18:43:30 +01:00
2018-04-03 15:13:11 +02:00
license_id = db.Column(db.Integer, db.ForeignKey("license.id"))
2018-03-21 20:03:14 +01:00
approved = db.Column(db.Boolean, nullable=False, default=False)
2018-03-18 18:43:30 +01:00
# Downloads
2018-03-20 01:44:47 +01:00
repo = db.Column(db.String(200), nullable=True)
website = db.Column(db.String(200), nullable=True)
2018-03-18 18:43:30 +01:00
issueTracker = db.Column(db.String(200), nullable=True)
2018-03-21 18:42:43 +01:00
forums = db.Column(db.Integer, nullable=False)
2018-03-18 18:43:30 +01:00
2018-03-26 12:28:34 +02:00
tags = db.relationship('Tag', secondary=tags, lazy='subquery',
backref=db.backref('packages', lazy=True))
2018-03-21 23:03:37 +01:00
releases = db.relationship("PackageRelease", backref="package",
lazy="dynamic", order_by=db.desc("package_release_releaseDate"))
2018-03-20 19:20:30 +01:00
2018-03-26 11:52:25 +02:00
screenshots = db.relationship("PackageScreenshot", backref="package",
lazy="dynamic")
2018-03-23 20:08:55 +01:00
requests = db.relationship("EditRequest", backref="package",
lazy="dynamic")
2018-03-23 18:33:34 +01:00
def getAsDictionary(self, base_url):
return {
"name": self.name,
"title": self.title,
"author": self.author.display_name,
"shortDesc": self.shortDesc,
"type": self.type.toName(),
2018-04-03 15:13:11 +02:00
"license": self.license.name,
2018-03-23 18:33:34 +01:00
"repo": self.repo,
"url": base_url + self.getDownloadURL(),
2018-04-19 21:20:05 +02:00
"release": self.getDownloadRelease().id if self.getDownloadRelease() is not None else None,
2018-03-26 11:52:25 +02:00
"screenshots": [base_url + ss.url for ss in self.screenshots]
2018-03-23 18:33:34 +01:00
}
2018-03-20 03:58:31 +01:00
def getDetailsURL(self):
return url_for("package_page",
2018-03-20 04:32:14 +01:00
type=self.type.toName(),
2018-03-20 03:58:31 +01:00
author=self.author.username, name=self.name)
def getEditURL(self):
2018-03-21 18:03:14 +01:00
return url_for("create_edit_package_page",
2018-03-20 04:32:14 +01:00
type=self.type.toName(),
2018-03-20 03:58:31 +01:00
author=self.author.username, name=self.name)
2018-03-21 20:03:14 +01:00
def getApproveURL(self):
return url_for("approve_package_page",
type=self.type.toName(),
author=self.author.username, name=self.name)
2018-03-26 11:52:25 +02:00
def getNewScreenshotURL(self):
return url_for("create_screenshot_page",
type=self.type.toName(),
author=self.author.username, name=self.name)
2018-03-20 19:40:19 +01:00
def getCreateReleaseURL(self):
return url_for("create_release_page",
type=self.type.toName(),
author=self.author.username, name=self.name)
2018-03-24 03:49:30 +01:00
def getCreateEditRequestURL(self):
return url_for("create_editrequest_page",
ptype=self.type.toName(),
author=self.author.username, name=self.name)
2018-03-23 17:20:56 +01:00
def getDownloadURL(self):
return url_for("package_download_page",
type=self.type.toName(),
author=self.author.username, name=self.name)
def getMainScreenshotURL(self):
2018-03-26 11:52:25 +02:00
return self.screenshots[0].url if len(self.screenshots) > 0 else None
2018-03-23 17:20:56 +01:00
def getDownloadRelease(self):
for rel in self.releases:
if rel.approved:
return rel
return None
2018-03-20 03:58:31 +01:00
def checkPerm(self, user, perm):
2018-03-20 04:45:01 +01:00
if not user.is_authenticated:
return False
2018-03-20 04:16:46 +01:00
if type(perm) == str:
perm = Permission[perm]
elif type(perm) != Permission:
raise Exception("Unknown permission given to Package.checkPerm()")
2018-03-20 04:16:46 +01:00
isOwner = user == self.author
2018-03-20 04:45:01 +01:00
# Members can edit their own packages, and editors can edit any packages
2018-03-20 19:20:30 +01:00
if perm == Permission.MAKE_RELEASE:
return isOwner or user.rank.atLeast(UserRank.EDITOR)
2018-03-20 04:45:01 +01:00
if perm == Permission.EDIT_PACKAGE or perm == Permission.APPROVE_CHANGES:
2018-03-20 04:16:46 +01:00
return user.rank.atLeast(UserRank.MEMBER if isOwner else UserRank.EDITOR)
2018-03-20 04:45:01 +01:00
# Editors can change authors, approve new packages, and approve releases
elif perm == Permission.CHANGE_AUTHOR or perm == Permission.APPROVE_NEW \
or perm == Permission.APPROVE_RELEASE:
2018-03-20 04:16:46 +01:00
return user.rank.atLeast(UserRank.EDITOR)
2018-03-20 04:45:01 +01:00
# Moderators can delete packages
elif perm == Permission.DELETE_PACKAGE or perm == Permission.CHANGE_RELEASE_URL:
2018-03-20 04:45:01 +01:00
return user.rank.atLeast(UserRank.MODERATOR)
2018-03-20 04:16:46 +01:00
else:
raise Exception("Permission {} is not related to packages".format(perm.name))
2018-03-20 03:58:31 +01:00
2018-03-26 12:28:34 +02:00
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
2018-03-26 12:28:34 +02:00
title = db.Column(db.String(100), nullable=False)
backgroundColor = db.Column(db.String(6), nullable=False)
textColor = db.Column(db.String(6), nullable=False)
def __init__(self, title, backgroundColor="000000", textColor="ffffff"):
self.title = title
self.backgroundColor = backgroundColor
self.textColor = textColor
import re
regex = re.compile('[^a-z_]')
self.name = regex.sub("", self.title.lower().replace(" ", "_"))
2018-03-26 12:28:34 +02:00
2018-03-20 19:20:30 +01:00
class PackageRelease(db.Model):
id = db.Column(db.Integer, primary_key=True)
2018-03-21 23:03:37 +01:00
package_id = db.Column(db.Integer, db.ForeignKey("package.id"))
2018-03-20 19:20:30 +01:00
title = db.Column(db.String(100), nullable=False)
releaseDate = db.Column(db.DateTime, nullable=False)
2018-03-20 19:20:30 +01:00
url = db.Column(db.String(100), nullable=False)
approved = db.Column(db.Boolean, nullable=False, default=False)
def getEditURL(self):
return url_for("edit_release_page",
type=self.package.type.toName(),
author=self.package.author.username,
name=self.package.name,
id=self.id)
2018-03-20 19:20:30 +01:00
def __init__(self):
self.releaseDate = datetime.now()
2018-03-26 11:52:25 +02:00
class PackageScreenshot(db.Model):
id = db.Column(db.Integer, primary_key=True)
package_id = db.Column(db.Integer, db.ForeignKey("package.id"))
title = db.Column(db.String(100), nullable=False)
url = db.Column(db.String(100), nullable=False)
def getThumbnailURL(self):
return self.url # TODO
2018-03-23 20:08:55 +01:00
class EditRequest(db.Model):
id = db.Column(db.Integer, primary_key=True)
package_id = db.Column(db.Integer, db.ForeignKey("package.id"))
author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
2018-03-23 20:25:48 +01:00
title = db.Column(db.String(100), nullable=False)
2018-03-23 20:08:55 +01:00
desc = db.Column(db.String(1000), nullable=True)
2018-03-23 20:49:57 +01:00
status = db.Column(db.Integer, nullable=False, default=0)
2018-03-23 20:08:55 +01:00
changes = db.relationship("EditRequestChange", backref="request",
lazy="dynamic")
2018-03-23 20:25:48 +01:00
def getURL(self):
return url_for("view_editrequest_page",
ptype=self.package.type.toName(),
author=self.package.author.username,
name=self.package.name,
id=self.id)
2018-03-23 20:49:57 +01:00
def getApproveURL(self):
return url_for("approve_editrequest_page",
ptype=self.package.type.toName(),
author=self.package.author.username,
name=self.package.name,
id=self.id)
def getRejectURL(self):
return url_for("reject_editrequest_page",
ptype=self.package.type.toName(),
author=self.package.author.username,
name=self.package.name,
id=self.id)
2018-03-23 20:08:55 +01:00
def applyAll(self, package):
for change in self.changes:
change.apply(package)
2018-03-23 20:25:48 +01:00
2018-03-23 20:08:55 +01:00
class EditRequestChange(db.Model):
id = db.Column(db.Integer, primary_key=True)
request_id = db.Column(db.Integer, db.ForeignKey("edit_request.id"))
key = db.Column(db.Enum(PackagePropertyKey), nullable=False)
# TODO: make diff instead
2018-03-23 20:49:57 +01:00
oldValue = db.Column(db.Text, nullable=True)
newValue = db.Column(db.Text, nullable=True)
2018-03-23 20:08:55 +01:00
def apply(self, package):
if self.key == PackagePropertyKey.tags:
package.tags.clear()
for tagTitle in self.newValue.split(","):
tag = Tag.query.filter_by(title=tagTitle.strip()).first()
package.tags.append(tag)
else:
setattr(package, self.key.name, self.newValue)
2018-03-23 20:08:55 +01:00
2018-03-18 18:43:30 +01:00
# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db, User) # Register the User model
user_manager = UserManager(db_adapter, app) # Initialize Flask-User