vlozit.py 2.12 KB
Newer Older
Mindiell's avatar
Mindiell committed
1
2
3
4
5
6
7
8
9
#encoding: utf-8

from Crypto.Hash import SHA
import os
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer, TextLexer
import time

Mindiell's avatar
Mindiell committed
10
11
import config

Mindiell's avatar
Mindiell committed
12
13
class Vlozit():
    def get_template(self, filename):
Mindiell's avatar
Mindiell committed
14
15
16
        path = (os.path.sep).join(("pastes",filename[0:2],filename[2:4],filename[4:6],filename))
        if os.path.exists(path):
            return path
Mindiell's avatar
Mindiell committed
17
18

    def get_path(self, filename):
Mindiell's avatar
Mindiell committed
19
        return (os.path.sep).join(("templates/pastes",filename[0:2],filename[2:4],filename[4:6],filename))
Mindiell's avatar
Mindiell committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

    def create_paste(self, data):
        # Idées possibles :
        #
        # * Chiffrer le contenu, la clef est dans l'url (c'est donc plutôt pour le serveur)
        #       Utilisation de pycrypto (https://pypi.python.org/pypi/pycrypto)
        # * Permettre de discuter du contenu
        # * Permettre de modifier le contenu (en-dessous) et donc d'en reposter un facilement
        while True:
            filename = SHA.new(bytes(str(time.perf_counter()),"utf-8")).hexdigest()
            path = self.get_path(filename)
            if not os.path.exists(path):
                break
        # Create path if not yet existing
        os.makedirs(os.path.dirname(path))
        # Format url to return
Mindiell's avatar
Mindiell committed
36
        url = "%sp?%s" % (config.WEBSITE, filename)
Mindiell's avatar
Mindiell committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        # Guessing which lexer to use
        try:
            lexer = guess_lexer(data)
        except:
            lexer = TextLexer()
        # Converting data via pygments
        colored = highlight(data, lexer, HtmlFormatter(linenos=True))
        # Replace specific characters in order to keep clean
        data = data.replace("#", "&num;").replace("%", "&percnt;").replace("<", "&lt;").replace(">", "&gt;")
        colored = colored.replace("#", "&num;").replace("%", "&percnt;")
        # Write file based on skeleton
        with open("templates/skeleton.html") as f:
            html = f.read()
        html = html.replace("##FORMATTED##", colored)
        html = html.replace("##RAW##", data)
        html = html.replace("##URL##", url)
        with open(path, "w") as f:
            f.write(html)
        return bytes(url, "utf-8")