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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
|
2 |
+
from flask_login import UserMixin, LoginManager, login_user, login_required, logout_user, current_user
|
3 |
+
from flask_wtf.csrf import generate_csrf
|
4 |
+
from werkzeug.security import generate_password_hash, check_password_hash
|
5 |
+
from werkzeug.utils import secure_filename
|
6 |
+
from datetime import datetime
|
7 |
+
import sqlite3
|
8 |
+
import uuid
|
9 |
+
import os
|
10 |
+
import asyncio
|
11 |
+
from telethon import TelegramClient, events
|
12 |
+
from FastTelethonhelper import fast_download, fast_upload
|
13 |
+
|
14 |
+
# Configuration
|
15 |
+
app_id = os.getenv("APP_ID")
|
16 |
+
api_hash = os.getenv("API_HASH")
|
17 |
+
btoken = os.getenv("BOT")
|
18 |
+
chnl = os.getenv("CHN")
|
19 |
+
|
20 |
+
api_id = int(app_id)
|
21 |
+
bot_token = str(btoken)
|
22 |
+
channel = int(chnl)
|
23 |
+
|
24 |
+
app = Flask("Simplz")
|
25 |
+
app.config['SECRET_KEY'] = 'your_secret_key'
|
26 |
+
app.config['UPLOAD_FOLDER'] = 'static/users/uploaded_images'
|
27 |
+
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
|
28 |
+
|
29 |
+
login_manager = LoginManager(app)
|
30 |
+
login_manager.login_view = 'login'
|
31 |
+
|
32 |
+
# Database functions
|
33 |
+
def get_db():
|
34 |
+
conn = sqlite3.connect('instance/database.db')
|
35 |
+
conn.row_factory = sqlite3.Row
|
36 |
+
return conn
|
37 |
+
|
38 |
+
def close_db(conn):
|
39 |
+
conn.close()
|
40 |
+
|
41 |
+
# User model
|
42 |
+
class User(UserMixin):
|
43 |
+
def __init__(self, id, username, email, password):
|
44 |
+
self.id = id
|
45 |
+
self.username = username
|
46 |
+
self.email = email
|
47 |
+
self.password = password
|
48 |
+
|
49 |
+
@login_manager.user_loader
|
50 |
+
def load_user(user_id):
|
51 |
+
conn = get_db()
|
52 |
+
user_data = conn.execute('SELECT * FROM user WHERE id = ?', (user_id,)).fetchone()
|
53 |
+
close_db(conn)
|
54 |
+
if user_data:
|
55 |
+
return User(user_data['id'], user_data['username'], user_data['email'], user_data['password'])
|
56 |
+
return None
|
57 |
+
|
58 |
+
@app.route('/')
|
59 |
+
@login_required
|
60 |
+
def index():
|
61 |
+
conn = get_db()
|
62 |
+
posts = conn.execute('''
|
63 |
+
SELECT * FROM post WHERE user_id = ?
|
64 |
+
UNION ALL
|
65 |
+
SELECT * FROM post
|
66 |
+
WHERE user_id IN (SELECT followed_id FROM followers WHERE follower_id = ?)
|
67 |
+
ORDER BY created_at DESC
|
68 |
+
''', (current_user.id, current_user.id)).fetchall()
|
69 |
+
close_db(conn)
|
70 |
+
|
71 |
+
csrf_token = request.environ.get('HTTP_X_CSRFTOKEN')
|
72 |
+
return render_template('index.html', posts=posts, csrf_token=csrf_token)
|
73 |
+
|
74 |
+
@app.route('/register', methods=['GET', 'POST'])
|
75 |
+
def register():
|
76 |
+
if request.method == 'POST':
|
77 |
+
email = request.form['email']
|
78 |
+
username = request.form['username']
|
79 |
+
password = request.form['password']
|
80 |
+
password2 = request.form['password2']
|
81 |
+
|
82 |
+
if password != password2:
|
83 |
+
flash('Passwords do not match. Please try again.', 'error')
|
84 |
+
return render_template('register.html')
|
85 |
+
|
86 |
+
conn = get_db()
|
87 |
+
existing_user_with_username = conn.execute('SELECT * FROM user WHERE username = ?', (username,)).fetchone()
|
88 |
+
existing_user_with_email = conn.execute('SELECT * FROM user WHERE email = ?', (email,)).fetchone()
|
89 |
+
|
90 |
+
if existing_user_with_username:
|
91 |
+
flash('Username already exists. Please choose a different username.', 'error')
|
92 |
+
return render_template('register.html')
|
93 |
+
|
94 |
+
if existing_user_with_email:
|
95 |
+
flash('Email address already registered. Please use a different email.', 'error')
|
96 |
+
return render_template('register.html')
|
97 |
+
|
98 |
+
hashed_password = generate_password_hash(password, method='scrypt')
|
99 |
+
conn.execute('INSERT INTO user (username, email, password) VALUES (?, ?, ?)', (username, email, hashed_password))
|
100 |
+
conn.commit()
|
101 |
+
close_db(conn)
|
102 |
+
|
103 |
+
flash('Account created successfully! Please log in.', 'success')
|
104 |
+
return redirect(url_for('login'))
|
105 |
+
|
106 |
+
return render_template('register.html')
|
107 |
+
|
108 |
+
@app.route('/login', methods=['GET', 'POST'])
|
109 |
+
def login():
|
110 |
+
if request.method == 'POST':
|
111 |
+
username = request.form['username']
|
112 |
+
password = request.form['password']
|
113 |
+
conn = get_db()
|
114 |
+
user_data = conn.execute('SELECT * FROM user WHERE username = ?', (username,)).fetchone()
|
115 |
+
close_db(conn)
|
116 |
+
|
117 |
+
if user_data and check_password_hash(user_data['password'], password):
|
118 |
+
user = User(user_data['id'], user_data['username'], user_data['email'], user_data['password'])
|
119 |
+
login_user(user)
|
120 |
+
return redirect(url_for('index'))
|
121 |
+
else:
|
122 |
+
flash('Invalid username or password. Fields are case sensitive.', 'error')
|
123 |
+
return render_template('login.html')
|
124 |
+
|
125 |
+
@app.route('/logout')
|
126 |
+
@login_required
|
127 |
+
def logout():
|
128 |
+
logout_user()
|
129 |
+
return redirect(url_for('index'))
|
130 |
+
|
131 |
+
@app.route('/create_post', methods=['POST'])
|
132 |
+
@login_required
|
133 |
+
def create_post():
|
134 |
+
content = request.form['content']
|
135 |
+
image = request.files['image']
|
136 |
+
|
137 |
+
if image and allowed_file(image.filename):
|
138 |
+
filename = str(uuid.uuid4()) + secure_filename(image.filename)
|
139 |
+
image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
|
140 |
+
else:
|
141 |
+
filename = None
|
142 |
+
|
143 |
+
conn = get_db()
|
144 |
+
conn.execute('INSERT INTO post (content, user_id, filename) VALUES (?, ?, ?)', (content, current_user.id, filename))
|
145 |
+
conn.commit()
|
146 |
+
close_db(conn)
|
147 |
+
return redirect(url_for('index'))
|
148 |
+
|
149 |
+
@app.route('/delete_post/<int:post_id>', methods=['POST'])
|
150 |
+
@login_required
|
151 |
+
def delete_post(post_id):
|
152 |
+
conn = get_db()
|
153 |
+
post = conn.execute('SELECT * FROM post WHERE id = ?', (post_id,)).fetchone()
|
154 |
+
|
155 |
+
if post and post['user_id'] == current_user.id:
|
156 |
+
if post['filename']:
|
157 |
+
try:
|
158 |
+
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], post['filename']))
|
159 |
+
except Exception as e:
|
160 |
+
flash(f"Error deleting image file: {str(e)}", "error")
|
161 |
+
|
162 |
+
conn.execute('DELETE FROM post WHERE id = ?', (post_id,))
|
163 |
+
conn.execute('DELETE FROM like WHERE post_id = ?', (post_id,))
|
164 |
+
conn.commit()
|
165 |
+
close_db(conn)
|
166 |
+
return redirect(url_for('index'))
|
167 |
+
|
168 |
+
@app.route('/follow/<int:user_id>', methods=['POST'])
|
169 |
+
@login_required
|
170 |
+
def follow(user_id):
|
171 |
+
conn = get_db()
|
172 |
+
user_to_follow = conn.execute('SELECT * FROM user WHERE id = ?', (user_id,)).fetchone()
|
173 |
+
|
174 |
+
if user_to_follow is None:
|
175 |
+
flash('User not found.', 'error')
|
176 |
+
return redirect(url_for('explore'))
|
177 |
+
|
178 |
+
if current_user.is_following(user_to_follow):
|
179 |
+
flash('You are already following this user.', 'info')
|
180 |
+
return redirect(url_for('view_profile', user_id=user_id))
|
181 |
+
|
182 |
+
try:
|
183 |
+
conn.execute('INSERT INTO followers (follower_id, followed_id) VALUES (?, ?)', (current_user.id, user_id))
|
184 |
+
conn.commit()
|
185 |
+
except Exception as e:
|
186 |
+
flash('Failed to follow the user. Please try again.', 'error')
|
187 |
+
print(f"Error: {str(e)}")
|
188 |
+
return redirect(url_for('view_profile', user_id=user_id))
|
189 |
+
|
190 |
+
flash(f"You are now following {user_to_follow['username']}.", 'success')
|
191 |
+
close_db(conn)
|
192 |
+
return redirect(url_for('view_profile', user_id=user_id))
|
193 |
+
|
194 |
+
@app.route('/unfollow/<int:user_id>', methods=['POST'])
|
195 |
+
@login_required
|
196 |
+
def unfollow(user_id):
|
197 |
+
conn = get_db()
|
198 |
+
user_to_unfollow = conn.execute('SELECT * FROM user WHERE id = ?', (user_id,)).fetchone()
|
199 |
+
|
200 |
+
if user_to_unfollow is None:
|
201 |
+
flash('User not found.', 'danger')
|
202 |
+
return redirect(url_for('index'))
|
203 |
+
|
204 |
+
if current_user.is_following(user_to_unfollow):
|
205 |
+
conn.execute('DELETE FROM followers WHERE follower_id = ? AND followed_id = ?', (current_user.id, user_id))
|
206 |
+
conn.commit()
|
207 |
+
flash('You have unfollowed {}.'.format(user_to_unfollow['username']), 'success')
|
208 |
+
else:
|
209 |
+
flash('You are not following this user.', 'info')
|
210 |
+
|
211 |
+
close_db(conn)
|
212 |
+
return redirect(url_for('view_profile', user_id=user_id))
|
213 |
+
|
214 |
+
@app.route('/search_user', methods=['GET'])
|
215 |
+
def search_user():
|
216 |
+
search_query = request.args.get('search_query', '')
|
217 |
+
conn = get_db()
|
218 |
+
users = conn.execute('''
|
219 |
+
SELECT * FROM user
|
220 |
+
WHERE username LIKE ? OR first_name LIKE ? OR last_name LIKE ?
|
221 |
+
''', (f'%{search_query}%', f'%{search_query}%', f'%{search_query}%')).fetchall()
|
222 |
+
close_db(conn)
|
223 |
+
|
224 |
+
csrf_token = generate_csrf()
|
225 |
+
return render_template('search_results.html', users=users, csrf_token=csrf_token, searchq=search_query)
|
226 |
+
|
227 |
+
# Other routes and functions remain mostly unchanged
|
228 |
+
|
229 |
+
def start_flask_app():
|
230 |
+
with app.app_context():
|
231 |
+
# Ensure database and tables exist
|
232 |
+
conn = get_db()
|
233 |
+
conn.execute('''CREATE TABLE IF NOT EXISTS user (
|
234 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
235 |
+
username TEXT UNIQUE,
|
236 |
+
email TEXT UNIQUE,
|
237 |
+
password TEXT
|
238 |
+
)''')
|
239 |
+
|
240 |
+
conn.execute('''CREATE TABLE IF NOT EXISTS post (
|
241 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
242 |
+
content TEXT,
|
243 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
244 |
+
user_id INTEGER,
|
245 |
+
filename TEXT,
|
246 |
+
FOREIGN KEY (user_id) REFERENCES user (id)
|
247 |
+
)''')
|
248 |
+
|
249 |
+
conn.execute('''CREATE TABLE IF NOT EXISTS followers (
|
250 |
+
follower_id INTEGER,
|
251 |
+
followed_id INTEGER,
|
252 |
+
PRIMARY KEY (follower_id, followed_id),
|
253 |
+
FOREIGN KEY (follower_id) REFERENCES user (id),
|
254 |
+
FOREIGN KEY (followed_id) REFERENCES user (id)
|
255 |
+
)''')
|
256 |
+
|
257 |
+
close_db(conn)
|
258 |
+
|
259 |
+
app.run(debug=True)
|
260 |
+
|
261 |
+
if __name__ == '__main__':
|
262 |
+
start_flask_app()
|