]>
git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - webapp/backend/nopaste.py
5 from misc
import Object
8 def create(self
, subject
, content
, type="text", expires
=None, account
=None, address
=None):
9 self
._cleanup
_database
()
15 # Escape any backslashes. PostgreSQL tends to think that they lead octal
16 # values or something that confuses the convertion from text to bytea.
18 content
= content
.replace("\\", "\\\\")
19 mimetype
= "text/plain"
22 content
= buffer(content
)
23 mimetype
= self
._guess
_mimetype
(content
)
25 # http://blog.00null.net/easily-generating-random-strings-in-postgresql/
26 res
= self
.db
.get("INSERT INTO nopaste(uuid, subject, content, time_expires, address, \
27 uid, mimetype, size) VALUES(random_slug(), %s, %s, \
28 (CASE WHEN %s = 0 THEN NULL ELSE NOW() + INTERVAL '%s seconds' END), \
29 %s, %s, %s, %s) RETURNING uuid",
30 subject
, content
, expires
, expires
, address
, uid
, mimetype
, len(content
))
35 def _guess_mimetype(self
, buf
):
36 ms
= magic
.open(magic
.NONE
)
39 # Return the mime type
40 ms
.setflags(magic
.MAGIC_MIME_TYPE
)
50 res
= self
.db
.get("SELECT uuid, subject, time_created, time_expires, address, uid, \
51 mimetype, views, size FROM nopaste WHERE uuid = %s AND (CASE WHEN time_expires \
52 IS NULL THEN TRUE ELSE NOW() < time_expires END)", uuid
)
55 # Get the account that uploaded this if available
58 res
.account
= self
.backend
.accounts
.get_by_uid(res
.uid
)
60 # Touch the entry so it won't be deleted when it is still used
61 self
._update
_lastseen
(uuid
)
65 def get_content(self
, uuid
):
66 # Try fetching the object from memcache. If found, we return it right away.
67 content
= self
.memcache
.get("nopaste-%s" % uuid
)
69 # If the object was not in the cache, we need to fetch it from the database.
71 res
= self
.db
.get("SELECT content FROM nopaste WHERE uuid = %s", uuid
)
73 # Convert the content to a byte string
74 content
= "%s" % res
.content
76 # Save it in the cache for later
77 self
.memcache
.set("nopaste-%s" % uuid
, content
, 6 * 3600)
81 def _update_lastseen(self
, uuid
):
82 self
.db
.execute("UPDATE nopaste SET time_lastseen = NOW(), views = views + 1 \
83 WHERE uuid = %s", uuid
)
85 def _cleanup_database(self
):
86 # Delete old pastes when they are expired or when they have not been
87 # accessed in a long time.
88 self
.db
.execute("DELETE FROM nopaste WHERE (CASE \
89 WHEN time_expires IS NULL \
90 THEN time_lastseen + INTERVAL '6 months' <= NOW() \
91 ELSE NOW() >= time_expires END)")