from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Index, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relation, backref
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import and_
import settings, os, mimetypes
engine = create_engine(settings.db_path)
Base = declarative_base(bind = engine)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key = True)
username = Column(String, unique = True, index = True)
password = Column(String)
files = relation('File', backref = 'user', order_by = 'File.date.desc()')
def __init__(self, username, password):
self.username = username
self.password = password
class File(Base):
__tablename__ = 'files'
id = Column(Integer, primary_key = True)
hash = Column(String, unique = True, index = True)
file_hash = Column(String, unique = True, index = True)
filename = Column(String)
date = Column(DateTime)
user_id = Column(Integer, ForeignKey('users.id'), nullable = True)
def __init__(self, hash, file_hash, filename, date, user_id = None):
self.hash = hash
self.file_hash = file_hash
self.filename = filename
self.date = date
self.user_id = user_id
@staticmethod
def pretty_size(size):
suffixes = (('B', 2**10), ('KiB', 2**20), ('MiB', 2**30), ('GiB', 2**40), ('TiB', 2**50))
for suf, lim in suffixes:
if size > lim:
continue
else:
return '%s %s' % (str(round(size/float(lim/2**10), 2)), suf)
def get_path(self):
return os.path.join(settings.file_directory, self.hash + os.path.splitext(self.filename)[1])
def html(self):
return u'{filename} 1 2 ({size}) on {date}'.format(
hash = self.hash, filename = self.filename, ext = os.path.splitext(self.filename)[1],
size = self.pretty_size(os.path.getsize(self.get_path())), date = self.date.strftime('%Y-%m-%d %H:%M:%S UTC'))
def get_mime_type(self):
return mimetypes.guess_type(self.filename, strict = False)[0] or 'application/octet-stream'
def is_image(self):
return self.get_mime_type().startswith('image')
def image_html(self):
return u''.format(
hash = self.hash, filename = self.filename, ext = os.path.splitext(self.filename)[1])
Base.metadata.create_all()
Session = sessionmaker(bind = engine, autoflush = True, autocommit = False)