]>
Commit | Line | Data |
---|---|---|
66862195 MT |
1 | #!/usr/bin/python |
2 | ||
3 | from misc import Object | |
4 | ||
5 | class Nopaste(Object): | |
6 | def create(self, subject, content, 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, uid) \ | |
15 | VALUES(random_slug(), %s, %s, (CASE WHEN %s = 0 THEN NULL ELSE NOW() + INTERVAL '%s seconds' END), \ | |
16 | %s, %s) RETURNING uuid", subject, content, expires, expires, address, uid) | |
17 | ||
18 | if res: | |
19 | return res.uuid | |
20 | ||
21 | def get(self, uuid): | |
22 | res = self.db.get("SELECT * FROM nopaste WHERE uuid = %s AND \ | |
23 | (CASE WHEN time_expires IS NULL THEN TRUE ELSE NOW() < time_expires END)", uuid) | |
24 | ||
25 | if res: | |
26 | # Convert the content to a byte string | |
27 | res.content = "%s" % res.content | |
28 | ||
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 _update_lastseen(self, uuid): | |
40 | self.db.execute("UPDATE nopaste SET time_lastseen = NOW() \ | |
41 | WHERE uuid = %s", uuid) | |
42 | ||
43 | def _cleanup_database(self): | |
44 | # Delete old pastes when they are expired or when they have not been | |
45 | # accessed in a long time. | |
46 | self.db.execute("DELETE FROM nopaste WHERE (CASE \ | |
47 | WHEN time_expires IS NULL \ | |
48 | THEN time_lastseen + INTERVAL '6 months' <= NOW() \ | |
49 | ELSE NOW() >= time_expires END)") |