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