-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
142 lines (116 loc) · 4.65 KB
/
app.py
File metadata and controls
142 lines (116 loc) · 4.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import sqlite3
import random
import string
import datetime
import re
from flask import Flask, render_template, request, redirect, url_for, Response
from waitress import serve
app = Flask(__name__)
PORT = 5050
BASE_DIR = os.getcwd()
DB_FOLDER = os.path.join(BASE_DIR, 'database')
DB_PATH = os.path.join(DB_FOLDER, 'codes.db')
if not os.path.exists(DB_FOLDER):
os.makedirs(DB_FOLDER)
def clean_title(text):
text = text.replace(" ", "_")
text = re.sub(r'[^a-zA-Z0-9\-_]', '', text)
return text.strip('_')
def init_db():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS pastes
(id TEXT PRIMARY KEY, title TEXT, content TEXT, lang TEXT, created_at TEXT, expire_at TEXT)''')
try:
c.execute("ALTER TABLE pastes ADD COLUMN title TEXT")
except:
pass
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
c.execute("DELETE FROM pastes WHERE expire_at < ?", (now,))
conn.commit()
conn.close()
def generate_unique_id():
chars = string.ascii_letters + string.digits
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
while True:
new_id = ''.join(random.choice(chars) for _ in range(8))
c.execute("SELECT id FROM pastes WHERE id=?", (new_id,))
if not c.fetchone():
conn.close()
return new_id
init_db()
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
raw_title = request.form.get('title', '').strip()
content = request.form.get('content')
lang = request.form.get('lang')
duration = request.form.get('duration')
title = clean_title(raw_title)
if not title:
title = "Untitled_Code"
if not content or not content.strip():
return render_template('create.html', error="Kod alanı boş olamaz!")
short_id = generate_unique_id()
now = datetime.datetime.now()
if duration == "1":
expire_dt = now + datetime.timedelta(hours=1)
elif duration == "24":
expire_dt = now + datetime.timedelta(days=1)
else:
expire_dt = now + datetime.timedelta(days=7)
expire_db = expire_dt.strftime("%Y-%m-%d %H:%M")
created_db = now.strftime("%Y-%m-%d %H:%M")
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("INSERT INTO pastes (id, title, content, lang, created_at, expire_at) VALUES (?, ?, ?, ?, ?, ?)",
(short_id, title, content, lang, created_db, expire_db))
conn.commit()
conn.close()
return redirect(url_for('view_paste', short_id=short_id))
return render_template('create.html')
@app.route('/<short_id>')
def view_paste(short_id):
now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT title, content, lang, created_at, expire_at FROM pastes WHERE id=?", (short_id,))
data = c.fetchone()
conn.close()
if not data or data[4] < now_str:
return render_template('404.html'), 404
c_dt = datetime.datetime.strptime(data[3], "%Y-%m-%d %H:%M")
e_dt = datetime.datetime.strptime(data[4], "%Y-%m-%d %H:%M")
formatted_created = c_dt.strftime("%d.%m.%Y %H:%M")
formatted_expire = e_dt.strftime("%d.%m.%Y %H:%M")
return render_template('view.html',
short_id=short_id,
title=data[0],
content=data[1],
lang=data[2],
date=formatted_created,
expire=formatted_expire)
@app.route('/download/<short_id>')
def download_paste(short_id):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT content, lang, title FROM pastes WHERE id=?", (short_id,))
data = c.fetchone()
conn.close()
if not data: return render_template('404.html'), 404
extensions = {'python':'py', 'javascript':'js', 'html':'html', 'css':'css', 'sql':'sql', 'bash':'sh'}
ext = extensions.get(data[1], 'txt')
filename = f"{data[2]}_{short_id}.{ext}"
return Response(
data[0],
mimetype="text/plain",
headers={"Content-disposition": f"attachment; filename={filename}"}
)
if __name__ == '__main__':
print(f"Rapne - Code Başlatılıyor... Port: {PORT}")
serve(app, host='0.0.0.0', port=PORT)