]>
Commit | Line | Data |
---|---|---|
66862195 MT |
1 | #!/usr/bin/python |
2 | ||
11347e46 | 3 | from .misc import Object |
66862195 MT |
4 | |
5 | class Nopaste(Object): | |
bed82f3e | 6 | def create(self, subject, content, mimetype="text", expires=None, account=None, address=None): |
66862195 MT |
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/ | |
b0b3e3e7 MT |
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)) | |
66862195 MT |
19 | |
20 | if res: | |
21 | return res.uuid | |
22 | ||
23 | def get(self, uuid): | |
0de07bc3 MT |
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) | |
66862195 MT |
27 | |
28 | if res: | |
66862195 MT |
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 | ||
0de07bc3 | 39 | def get_content(self, uuid): |
09fa25a8 MT |
40 | res = self.db.get("SELECT content FROM nopaste \ |
41 | WHERE uuid = %s", uuid) | |
0de07bc3 | 42 | |
09fa25a8 | 43 | if res: |
a41085fb | 44 | return bytes(res.content) |
0de07bc3 | 45 | |
66862195 | 46 | def _update_lastseen(self, uuid): |
bfbf061b | 47 | self.db.execute("UPDATE nopaste SET time_lastseen = NOW(), views = views + 1 \ |
66862195 MT |
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)") |