from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Index, ForeignKey, Boolean 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) jab_id = Column(String(12), unique = True, index = True) files = relation('File', backref = 'user', order_by = 'File.date.desc()') def __init__(self, username, jab_id): self.username = username self.jab_id = jab_id 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) ip = Column(String) accessed = Column(DateTime) def __init__(self, hash, file_hash, filename, date, user_id = None, ip = None): self.hash = hash self.file_hash = file_hash self.filename = filename self.date = date self.user_id = user_id self.ip = ip @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 get_size(self): return os.path.getsize(self.get_path()) def html(self): return u'{filename} ' \ '1 2 del ' \ '({size}) on {date}'.format( root = settings.virtual_root, hash = self.hash, filename = self.filename, ext = os.path.splitext(self.filename)[1], size = self.pretty_size(self.get_size()), 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') @property def ext(self): return os.path.splitext(self.filename)[1] Base.metadata.create_all() Session = sessionmaker(bind = engine, autoflush = True, autocommit = False) # vim: noet ts=4