]>
Commit | Line | Data |
---|---|---|
8b82926a MT |
1 | #!/usr/bin/python3 |
2 | ||
3 | import datetime | |
66862195 | 4 | |
11347e46 | 5 | from .misc import Object |
66862195 MT |
6 | |
7 | class Nopaste(Object): | |
bed82f3e | 8 | def create(self, subject, content, mimetype="text", expires=None, account=None, address=None): |
66862195 MT |
9 | self._cleanup_database() |
10 | ||
11 | uid = None | |
12 | if account: | |
13 | uid = account.uid | |
14 | ||
8b82926a MT |
15 | if expires: |
16 | expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=expires) | |
17 | ||
66862195 | 18 | # http://blog.00null.net/easily-generating-random-strings-in-postgresql/ |
b0b3e3e7 | 19 | res = self.db.get("INSERT INTO nopaste(uuid, subject, content, time_expires, address, \ |
8b82926a MT |
20 | uid, mimetype, size) VALUES(random_slug(), %s, %s, %s, %s, %s, %s, %s) RETURNING uuid", |
21 | subject, content, expires, address, uid, mimetype, len(content)) | |
66862195 MT |
22 | |
23 | if res: | |
24 | return res.uuid | |
25 | ||
26 | def get(self, uuid): | |
0de07bc3 MT |
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) | |
66862195 MT |
30 | |
31 | if res: | |
66862195 MT |
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 | ||
0de07bc3 | 42 | def get_content(self, uuid): |
09fa25a8 MT |
43 | res = self.db.get("SELECT content FROM nopaste \ |
44 | WHERE uuid = %s", uuid) | |
0de07bc3 | 45 | |
09fa25a8 | 46 | if res: |
a41085fb | 47 | return bytes(res.content) |
0de07bc3 | 48 | |
66862195 | 49 | def _update_lastseen(self, uuid): |
bfbf061b | 50 | self.db.execute("UPDATE nopaste SET time_lastseen = NOW(), views = views + 1 \ |
66862195 MT |
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)") |