]> git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - webapp/backend/nopaste.py
4f877330cf25fd9d3c248b94e0a1139054fe2b02
[people/shoehn/ipfire.org.git] / webapp / backend / nopaste.py
1 #!/usr/bin/python
2
3 from misc import Object
4
5 class Nopaste(Object):
6 def create(self, subject, content, type="text", expires=None, account=None, address=None):
7 self._cleanup_database()
8
9 uid = None
10 if account:
11 uid = account.uid
12
13 # Escape any backslashes. PostgreSQL tends to think that they lead octal
14 # values or something that confuses the convertion from text to bytea.
15 if type == "text":
16 content = content.replace("\\", "\\\\")
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, uid) \
20 VALUES(random_slug(), %s, %s, (CASE WHEN %s = 0 THEN NULL ELSE NOW() + INTERVAL '%s seconds' END), \
21 %s, %s) RETURNING uuid", subject, content, expires, expires, address, uid)
22
23 if res:
24 return res.uuid
25
26 def get(self, uuid):
27 res = self.db.get("SELECT * FROM nopaste WHERE uuid = %s AND \
28 (CASE WHEN time_expires IS NULL THEN TRUE ELSE NOW() < time_expires END)", uuid)
29
30 if res:
31 # Convert the content to a byte string
32 res.content = "%s" % res.content
33
34 # Get the account that uploaded this if available
35 res.account = None
36 if res.uid:
37 res.account = self.backend.accounts.get_by_uid(res.uid)
38
39 # Touch the entry so it won't be deleted when it is still used
40 self._update_lastseen(uuid)
41
42 return res
43
44 def _update_lastseen(self, uuid):
45 self.db.execute("UPDATE nopaste SET time_lastseen = NOW() \
46 WHERE uuid = %s", uuid)
47
48 def _cleanup_database(self):
49 # Delete old pastes when they are expired or when they have not been
50 # accessed in a long time.
51 self.db.execute("DELETE FROM nopaste WHERE (CASE \
52 WHEN time_expires IS NULL \
53 THEN time_lastseen + INTERVAL '6 months' <= NOW() \
54 ELSE NOW() >= time_expires END)")