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