]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/nopaste.py
Use Python's internal asyncio stuff instead of Tornado's
[ipfire.org.git] / src / backend / nopaste.py
1 #!/usr/bin/python3
2
3 import datetime
4
5 from .misc import Object
6
7 class Nopaste(Object):
8 def create(self, subject, content, mimetype="text", expires=None, account=None, address=None):
9 self._cleanup_database()
10
11 uid = None
12 if account:
13 uid = account.uid
14
15 if expires:
16 expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=expires)
17
18 # http://blog.00null.net/easily-generating-random-strings-in-postgresql/
19 res = self.db.get("INSERT INTO nopaste(uuid, subject, content, time_expires, address, \
20 uid, mimetype, size) VALUES(random_slug(), %s, %s, %s, %s, %s, %s, %s) RETURNING uuid",
21 subject, content, expires or None, address, uid, mimetype, len(content))
22
23 if res:
24 return res.uuid
25
26 def get(self, uuid):
27 res = self.db.get("SELECT uuid, subject, time_created, time_expires, address, uid, \
28 mimetype, views, size FROM nopaste WHERE uuid = %s AND (CASE WHEN time_expires \
29 IS NULL THEN TRUE ELSE NOW() < time_expires END)", uuid)
30
31 if res:
32 # Get the account that uploaded this if available
33 res.account = None
34 if res.uid:
35 res.account = self.backend.accounts.get_by_uid(res.uid)
36
37 # Touch the entry so it won't be deleted when it is still used
38 self._update_lastseen(uuid)
39
40 return res
41
42 def get_content(self, uuid):
43 res = self.db.get("SELECT content FROM nopaste \
44 WHERE uuid = %s", uuid)
45
46 if res:
47 return bytes(res.content)
48
49 def _update_lastseen(self, uuid):
50 self.db.execute("UPDATE nopaste SET time_lastseen = NOW(), views = views + 1 \
51 WHERE uuid = %s", uuid)
52
53 def _cleanup_database(self):
54 # Delete old pastes when they are expired or when they have not been
55 # accessed in a long time.
56 self.db.execute("DELETE FROM nopaste WHERE (CASE \
57 WHEN time_expires IS NULL \
58 THEN time_lastseen + INTERVAL '6 months' <= NOW() \
59 ELSE NOW() >= time_expires END)")