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
|
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'<a href="{root}f/{hash}/{filename}">{filename}</a> ' \
'<sup><a href="{root}f/{hash}">1</a> <a href="{root}f/{hash}{ext}">2</a></sup> ({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')
def image_html(self):
return u'<a href="{root}f/{hash}{ext}" title="{filename}"><img src="{root}t/{hash}" alt="{filename}" /></a>'.format(
root = settings.virtual_root, 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)
|