Update newweb.py
Browse files
newweb.py
CHANGED
@@ -1,49 +1,61 @@
|
|
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
|
8 |
import uuid
|
9 |
import os
|
|
|
|
|
|
|
|
|
10 |
import asyncio
|
11 |
-
|
12 |
-
|
|
|
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
|
23 |
|
24 |
-
|
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 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
# Database functions
|
33 |
-
def get_db():
|
34 |
-
conn = sqlite3.connect('database.db')
|
35 |
-
conn.row_factory = sqlite3.Row
|
36 |
-
return conn
|
37 |
|
38 |
-
def close_db(conn):
|
39 |
-
conn.close()
|
40 |
|
41 |
|
42 |
async def updb():
|
43 |
client = TelegramClient(None, api_id, api_hash)
|
44 |
await client.start(bot_token=bot_token)
|
45 |
-
|
46 |
-
path = 'database.db'
|
47 |
fle = await fast_upload(client, file_location=path)
|
48 |
entity = await client.get_entity(channel)
|
49 |
|
@@ -51,39 +63,180 @@ async def updb():
|
|
51 |
await client.disconnect()
|
52 |
return '2'
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
@login_manager.user_loader
|
63 |
def load_user(user_id):
|
64 |
-
|
65 |
-
|
66 |
-
close_db(conn)
|
67 |
-
if user_data:
|
68 |
-
return User(user_data['id'], user_data['username'], user_data['email'], user_data['password'])
|
69 |
-
return None
|
70 |
|
71 |
@app.route('/')
|
72 |
@login_required
|
73 |
def index():
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
UNION ALL
|
78 |
-
SELECT * FROM post
|
79 |
-
WHERE user_id IN (SELECT followed_id FROM followers WHERE follower_id = ?)
|
80 |
-
ORDER BY created_at DESC
|
81 |
-
''', (current_user.id, current_user.id)).fetchall()
|
82 |
-
close_db(conn)
|
83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
csrf_token = request.environ.get('HTTP_X_CSRFTOKEN')
|
|
|
85 |
return render_template('index.html', posts=posts, csrf_token=csrf_token)
|
86 |
|
|
|
|
|
87 |
@app.route('/register', methods=['GET', 'POST'])
|
88 |
def register():
|
89 |
if request.method == 'POST':
|
@@ -96,9 +249,8 @@ def register():
|
|
96 |
flash('Passwords do not match. Please try again.', 'error')
|
97 |
return render_template('register.html')
|
98 |
|
99 |
-
|
100 |
-
|
101 |
-
existing_user_with_email = conn.execute('SELECT * FROM user WHERE email = ?', (email,)).fetchone()
|
102 |
|
103 |
if existing_user_with_username:
|
104 |
flash('Username already exists. Please choose a different username.', 'error')
|
@@ -109,9 +261,9 @@ def register():
|
|
109 |
return render_template('register.html')
|
110 |
|
111 |
hashed_password = generate_password_hash(password, method='scrypt')
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
|
116 |
flash('Account created successfully! Please log in.', 'success')
|
117 |
return redirect(url_for('login'))
|
@@ -123,12 +275,8 @@ def login():
|
|
123 |
if request.method == 'POST':
|
124 |
username = request.form['username']
|
125 |
password = request.form['password']
|
126 |
-
|
127 |
-
|
128 |
-
close_db(conn)
|
129 |
-
|
130 |
-
if user_data and check_password_hash(user_data['password'], password):
|
131 |
-
user = User(user_data['id'], user_data['username'], user_data['email'], user_data['password'])
|
132 |
login_user(user)
|
133 |
return redirect(url_for('index'))
|
134 |
else:
|
@@ -153,37 +301,37 @@ def create_post():
|
|
153 |
else:
|
154 |
filename = None
|
155 |
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
close_db(conn)
|
160 |
return redirect(url_for('index'))
|
161 |
|
162 |
@app.route('/delete_post/<int:post_id>', methods=['POST'])
|
163 |
@login_required
|
164 |
def delete_post(post_id):
|
165 |
-
|
166 |
-
post
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
conn.commit()
|
178 |
-
close_db(conn)
|
179 |
return redirect(url_for('index'))
|
180 |
|
|
|
|
|
|
|
|
|
181 |
@app.route('/follow/<int:user_id>', methods=['POST'])
|
182 |
@login_required
|
183 |
def follow(user_id):
|
184 |
-
|
185 |
-
user_to_follow =
|
186 |
-
|
187 |
if user_to_follow is None:
|
188 |
flash('User not found.', 'error')
|
189 |
return redirect(url_for('explore'))
|
@@ -193,36 +341,175 @@ def follow(user_id):
|
|
193 |
return redirect(url_for('view_profile', user_id=user_id))
|
194 |
|
195 |
try:
|
196 |
-
|
197 |
-
conn.commit()
|
198 |
except Exception as e:
|
199 |
flash('Failed to follow the user. Please try again.', 'error')
|
200 |
print(f"Error: {str(e)}")
|
201 |
return redirect(url_for('view_profile', user_id=user_id))
|
202 |
|
203 |
-
flash(f"You are now following {user_to_follow
|
204 |
-
close_db(conn)
|
205 |
return redirect(url_for('view_profile', user_id=user_id))
|
206 |
|
|
|
207 |
@app.route('/unfollow/<int:user_id>', methods=['POST'])
|
208 |
@login_required
|
209 |
-
def unfollow(user_id):
|
210 |
-
|
211 |
-
user_to_unfollow = conn.execute('SELECT * FROM user WHERE id = ?', (user_id,)).fetchone()
|
212 |
-
|
213 |
if user_to_unfollow is None:
|
214 |
flash('User not found.', 'danger')
|
215 |
return redirect(url_for('index'))
|
216 |
|
217 |
if current_user.is_following(user_to_unfollow):
|
218 |
-
|
219 |
-
|
220 |
-
flash('You have unfollowed {}.'.format(user_to_unfollow['username']), 'success')
|
221 |
else:
|
222 |
flash('You are not following this user.', 'info')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
|
224 |
-
close_db(conn)
|
225 |
-
return redirect(url_for('view_profile', user_id=user_id))
|
226 |
|
227 |
|
228 |
@app.route('/updb', methods=['GET'])
|
@@ -233,7 +520,7 @@ def updbur():
|
|
233 |
asyncio.set_event_loop(loop)
|
234 |
|
235 |
# Run the async function
|
236 |
-
|
237 |
rp = loop.run_until_complete(updb())
|
238 |
loop.close() # Close the loop when done
|
239 |
|
@@ -242,53 +529,39 @@ def updbur():
|
|
242 |
return 'no'
|
243 |
|
244 |
|
245 |
-
@app.route('/search_user', methods=['GET'])
|
246 |
-
def search_user():
|
247 |
-
search_query = request.args.get('search_query', '')
|
248 |
-
conn = get_db()
|
249 |
-
users = conn.execute('''
|
250 |
-
SELECT * FROM user
|
251 |
-
WHERE username LIKE ? OR first_name LIKE ? OR last_name LIKE ?
|
252 |
-
''', (f'%{search_query}%', f'%{search_query}%', f'%{search_query}%')).fetchall()
|
253 |
-
close_db(conn)
|
254 |
|
255 |
-
csrf_token = generate_csrf()
|
256 |
-
return render_template('search_results.html', users=users, csrf_token=csrf_token, searchq=search_query)
|
257 |
|
258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
259 |
|
260 |
def start_flask_app():
|
261 |
with app.app_context():
|
262 |
-
|
263 |
-
conn = get_db()
|
264 |
-
conn.execute('''CREATE TABLE IF NOT EXISTS user (
|
265 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
266 |
-
username TEXT UNIQUE,
|
267 |
-
email TEXT UNIQUE,
|
268 |
-
password TEXT
|
269 |
-
)''')
|
270 |
-
|
271 |
-
conn.execute('''CREATE TABLE IF NOT EXISTS post (
|
272 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
273 |
-
content TEXT,
|
274 |
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
275 |
-
user_id INTEGER,
|
276 |
-
filename TEXT,
|
277 |
-
FOREIGN KEY (user_id) REFERENCES user (id)
|
278 |
-
)''')
|
279 |
-
|
280 |
-
conn.execute('''CREATE TABLE IF NOT EXISTS followers (
|
281 |
-
follower_id INTEGER,
|
282 |
-
followed_id INTEGER,
|
283 |
-
PRIMARY KEY (follower_id, followed_id),
|
284 |
-
FOREIGN KEY (follower_id) REFERENCES user (id),
|
285 |
-
FOREIGN KEY (followed_id) REFERENCES user (id)
|
286 |
-
)''')
|
287 |
-
|
288 |
-
close_db(conn)
|
289 |
-
|
290 |
app.run(debug=True, use_reloader=False, host="0.0.0.0", port=7860)
|
291 |
|
292 |
-
|
293 |
if __name__ == '__main__':
|
294 |
-
start_flask_app()
|
|
|
1 |
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
|
2 |
+
from flask_sqlalchemy import SQLAlchemy
|
3 |
+
from sqlalchemy import select, Column, exists, or_, Table, ForeignKey, Integer, String, DateTime, Text, and_, alias
|
4 |
+
from sqlalchemy.orm import aliased, relationship
|
5 |
from flask_login import UserMixin, LoginManager, login_user, login_required, logout_user, current_user
|
6 |
from flask_wtf.csrf import generate_csrf
|
7 |
from werkzeug.security import generate_password_hash, check_password_hash
|
8 |
from werkzeug.utils import secure_filename
|
9 |
from datetime import datetime
|
10 |
+
from flask_migrate import Migrate
|
11 |
import uuid
|
12 |
import os
|
13 |
+
from sqlalchemy import or_, func
|
14 |
+
from FastTelethonhelper import fast_download
|
15 |
+
from FastTelethonhelper import fast_upload
|
16 |
+
from telethon import TelegramClient, events,sync
|
17 |
import asyncio
|
18 |
+
import time
|
19 |
+
|
20 |
+
|
21 |
|
|
|
22 |
app_id = os.getenv("APP_ID")
|
23 |
api_hash = os.getenv("API_HASH")
|
24 |
btoken = os.getenv("BOT")
|
25 |
chnl = os.getenv("CHN")
|
26 |
|
27 |
+
|
28 |
api_id = int(app_id)
|
29 |
+
api_hash = str(api_hash)
|
30 |
bot_token = str(btoken)
|
31 |
+
channel= int(chnl)
|
32 |
|
33 |
+
print('dl sec')
|
|
|
|
|
|
|
34 |
|
35 |
+
###DB BACKUP##
|
36 |
+
|
37 |
+
async def downdb():
|
38 |
+
client = TelegramClient(None, api_id, api_hash)
|
39 |
+
await client.start(bot_token=bot_token)
|
40 |
+
|
41 |
+
os.remove('instance/database.db')
|
42 |
+
@client.on(events.NewMessage)
|
43 |
+
async def handler(event):
|
44 |
+
last_message = event.message
|
45 |
+
await fast_download(client,last_message)
|
46 |
+
await asyncio.sleep(10)
|
47 |
+
await client.disconnect()
|
48 |
+
|
49 |
+
|
50 |
+
return '2'
|
51 |
|
|
|
|
|
|
|
|
|
|
|
52 |
|
|
|
|
|
53 |
|
54 |
|
55 |
async def updb():
|
56 |
client = TelegramClient(None, api_id, api_hash)
|
57 |
await client.start(bot_token=bot_token)
|
58 |
+
path = 'instance/database.db'
|
|
|
59 |
fle = await fast_upload(client, file_location=path)
|
60 |
entity = await client.get_entity(channel)
|
61 |
|
|
|
63 |
await client.disconnect()
|
64 |
return '2'
|
65 |
|
66 |
+
app = Flask("Simplz")
|
67 |
+
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
|
68 |
+
app.config['SECRET_KEY'] = 'your_secret_key'
|
69 |
+
db = SQLAlchemy(app)
|
70 |
+
migrate = Migrate(app, db)
|
71 |
+
|
72 |
+
app.config['UPLOAD_FOLDER'] = 'static/users/uploaded_images'
|
73 |
+
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
|
74 |
+
|
75 |
+
followers = db.Table(
|
76 |
+
'followers',
|
77 |
+
db.Column('follower_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
|
78 |
+
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
|
79 |
+
extend_existing=True
|
80 |
+
)
|
81 |
+
|
82 |
+
class Comment(db.Model):
|
83 |
+
id = db.Column(db.Integer, primary_key=True)
|
84 |
+
content = db.Column(db.Text, nullable=False)
|
85 |
+
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
|
86 |
+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
87 |
+
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
|
88 |
+
author = db.relationship('User', backref='comments', lazy=True)
|
89 |
+
|
90 |
+
|
91 |
+
class Like(db.Model):
|
92 |
+
id = db.Column(db.Integer, primary_key=True)
|
93 |
+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
94 |
+
post_id = db.Column(db.Integer, db.ForeignKey('post.id', ondelete='CASCADE'), nullable=False)
|
95 |
+
liked_at = db.Column(db.DateTime, default=datetime.utcnow)
|
96 |
+
|
97 |
+
|
98 |
+
class Follow(db.Model):
|
99 |
+
__tablename__ = 'followers'
|
100 |
+
follower_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
|
101 |
+
followed_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
|
102 |
+
|
103 |
+
follower = db.relationship('User', foreign_keys=[follower_id], backref='following')
|
104 |
+
followed = db.relationship('User', foreign_keys=[followed_id], backref='followers')
|
105 |
+
|
106 |
+
__table_args__ = {'extend_existing': True}
|
107 |
+
|
108 |
+
class Message(db.Model):
|
109 |
+
id = db.Column(db.Integer, primary_key=True)
|
110 |
+
sender_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
111 |
+
recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
112 |
+
content = db.Column(db.Text, nullable=False)
|
113 |
+
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
|
114 |
+
sender = db.relationship('User', foreign_keys=[sender_id], backref='sent_messages')
|
115 |
+
recipient = db.relationship('User', foreign_keys=[recipient_id], backref='received_messages')
|
116 |
+
|
117 |
+
|
118 |
+
|
119 |
+
class User(UserMixin, db.Model):
|
120 |
+
id = db.Column(db.Integer, primary_key=True)
|
121 |
+
username = db.Column(db.String(100), unique=True, nullable=False)
|
122 |
+
email = db.Column(db.String(100), unique=True, nullable=False)
|
123 |
+
password = db.Column(db.String(100), nullable=False)
|
124 |
+
first_name = db.Column(db.String(50), default="Per")
|
125 |
+
last_name = db.Column(db.String(50), default="Son")
|
126 |
+
profession = db.Column(db.String(100), default="Person")
|
127 |
+
location = db.Column(db.String(100), default="Earth")
|
128 |
+
bio = db.Column(db.Text, default="Hello there...")
|
129 |
+
profile_pic = db.Column(db.String(100), default='default.jpg')
|
130 |
+
posts = db.relationship('Post', backref='author', lazy=True)
|
131 |
+
|
132 |
+
following_list = db.relationship(
|
133 |
+
'User',
|
134 |
+
secondary=followers,
|
135 |
+
primaryjoin=(followers.c.follower_id == id),
|
136 |
+
secondaryjoin=(followers.c.followed_id == id),
|
137 |
+
backref=db.backref('followers_of', lazy='dynamic'),
|
138 |
+
lazy='dynamic',
|
139 |
+
overlaps="follower,followers_of,following,following_list"
|
140 |
+
)
|
141 |
+
|
142 |
+
followers_list = db.relationship(
|
143 |
+
'User',
|
144 |
+
secondary=followers,
|
145 |
+
primaryjoin=(followers.c.followed_id == id),
|
146 |
+
secondaryjoin=(followers.c.follower_id == id),
|
147 |
+
backref=db.backref('following_by', lazy='dynamic'),
|
148 |
+
lazy='dynamic',
|
149 |
+
overlaps="followed,followers,followers_of,following_list"
|
150 |
+
)
|
151 |
+
|
152 |
+
def is_following(self, user):
|
153 |
+
return self.following_list.filter_by(id=user.id).first() is not None
|
154 |
+
|
155 |
+
def follow(self, user):
|
156 |
+
if not self.is_following(user) and self.id != user.id:
|
157 |
+
self.following_list.append(user)
|
158 |
+
db.session.commit()
|
159 |
+
|
160 |
+
def unfollow(self, user):
|
161 |
+
if self.is_following(user):
|
162 |
+
self.following_list.remove(user)
|
163 |
+
db.session.commit()
|
164 |
+
|
165 |
+
def like_post(self, post):
|
166 |
+
if not self.has_liked_post(post):
|
167 |
+
like = Like(user_id=self.id, post_id=post.id)
|
168 |
+
db.session.add(like)
|
169 |
+
db.session.commit()
|
170 |
+
|
171 |
+
def unlike_post(self, post):
|
172 |
+
like = Like.query.filter_by(user_id=self.id, post_id=post.id).first()
|
173 |
+
if like:
|
174 |
+
db.session.delete(like)
|
175 |
+
db.session.commit()
|
176 |
+
|
177 |
+
def has_liked_post(self, post):
|
178 |
+
return Like.query.filter_by(user_id=self.id, post_id=post.id).count() > 0
|
179 |
+
|
180 |
+
def add_comment(self, post, content):
|
181 |
+
comment = Comment(user_id=self.id, post_id=post.id, content=content)
|
182 |
+
db.session.add(comment)
|
183 |
+
db.session.commit()
|
184 |
+
|
185 |
+
def delete_comment(self, comment):
|
186 |
+
if comment.user_id == self.id:
|
187 |
+
db.session.delete(comment)
|
188 |
+
db.session.commit()
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
class Post(db.Model):
|
193 |
+
id = db.Column(db.Integer, primary_key=True)
|
194 |
+
content = db.Column(db.Text, nullable=False)
|
195 |
+
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
196 |
+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
197 |
+
filename = db.Column(db.String(100))
|
198 |
+
comments = db.relationship('Comment', backref='post', lazy=True, cascade='all, delete-orphan')
|
199 |
+
likes = db.relationship('Like', backref='post', lazy=True)
|
200 |
+
@property
|
201 |
+
def likes_count(self):
|
202 |
+
return Like.query.filter_by(post_id=self.id).count()
|
203 |
+
|
204 |
+
|
205 |
+
login_manager = LoginManager(app)
|
206 |
+
login_manager.login_view = 'login'
|
207 |
+
|
208 |
+
def allowed_file(filename):
|
209 |
+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
|
210 |
|
211 |
@login_manager.user_loader
|
212 |
def load_user(user_id):
|
213 |
+
return db.session.get(User, int(user_id))
|
214 |
+
|
|
|
|
|
|
|
|
|
215 |
|
216 |
@app.route('/')
|
217 |
@login_required
|
218 |
def index():
|
219 |
+
followed_user = aliased(User, name='followed_user')
|
220 |
+
|
221 |
+
own_posts_query = Post.query.filter_by(user_id=current_user.id)
|
|
|
|
|
|
|
|
|
|
|
|
|
222 |
|
223 |
+
followed_posts_query = Post.query.join(
|
224 |
+
Follow,
|
225 |
+
or_(
|
226 |
+
and_(Post.user_id == Follow.followed_id, Follow.follower_id == current_user.id),
|
227 |
+
and_(Post.user_id == Follow.follower_id, Follow.followed_id == current_user.id)
|
228 |
+
)
|
229 |
+
)
|
230 |
+
|
231 |
+
combined_posts_query = own_posts_query.union_all(followed_posts_query)
|
232 |
+
posts = combined_posts_query.order_by(Post.created_at.desc()).all()
|
233 |
+
|
234 |
csrf_token = request.environ.get('HTTP_X_CSRFTOKEN')
|
235 |
+
|
236 |
return render_template('index.html', posts=posts, csrf_token=csrf_token)
|
237 |
|
238 |
+
|
239 |
+
|
240 |
@app.route('/register', methods=['GET', 'POST'])
|
241 |
def register():
|
242 |
if request.method == 'POST':
|
|
|
249 |
flash('Passwords do not match. Please try again.', 'error')
|
250 |
return render_template('register.html')
|
251 |
|
252 |
+
existing_user_with_username = User.query.filter_by(username=username).first()
|
253 |
+
existing_user_with_email = User.query.filter_by(email=email).first()
|
|
|
254 |
|
255 |
if existing_user_with_username:
|
256 |
flash('Username already exists. Please choose a different username.', 'error')
|
|
|
261 |
return render_template('register.html')
|
262 |
|
263 |
hashed_password = generate_password_hash(password, method='scrypt')
|
264 |
+
new_user = User(username=username, email=email, password=hashed_password)
|
265 |
+
db.session.add(new_user)
|
266 |
+
db.session.commit()
|
267 |
|
268 |
flash('Account created successfully! Please log in.', 'success')
|
269 |
return redirect(url_for('login'))
|
|
|
275 |
if request.method == 'POST':
|
276 |
username = request.form['username']
|
277 |
password = request.form['password']
|
278 |
+
user = User.query.filter_by(username=username).first()
|
279 |
+
if user and check_password_hash(user.password, password):
|
|
|
|
|
|
|
|
|
280 |
login_user(user)
|
281 |
return redirect(url_for('index'))
|
282 |
else:
|
|
|
301 |
else:
|
302 |
filename = None
|
303 |
|
304 |
+
new_post = Post(content=content, author=current_user, filename=filename)
|
305 |
+
db.session.add(new_post)
|
306 |
+
db.session.commit()
|
|
|
307 |
return redirect(url_for('index'))
|
308 |
|
309 |
@app.route('/delete_post/<int:post_id>', methods=['POST'])
|
310 |
@login_required
|
311 |
def delete_post(post_id):
|
312 |
+
post = db.session.get(Post, post_id)
|
313 |
+
if post and post.author == current_user:
|
314 |
+
if post.filename:
|
315 |
+
try:
|
316 |
+
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], post.filename))
|
317 |
+
except Exception as e:
|
318 |
+
flash(f"Error deleting image file: {str(e)}", "error")
|
319 |
+
|
320 |
+
|
321 |
+
Like.query.filter_by(post_id=post_id).delete()
|
322 |
+
db.session.delete(post)
|
323 |
+
db.session.commit()
|
|
|
|
|
324 |
return redirect(url_for('index'))
|
325 |
|
326 |
+
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
@app.route('/follow/<int:user_id>', methods=['POST'])
|
331 |
@login_required
|
332 |
def follow(user_id):
|
333 |
+
|
334 |
+
user_to_follow = User.query.get(user_id)
|
|
|
335 |
if user_to_follow is None:
|
336 |
flash('User not found.', 'error')
|
337 |
return redirect(url_for('explore'))
|
|
|
341 |
return redirect(url_for('view_profile', user_id=user_id))
|
342 |
|
343 |
try:
|
344 |
+
current_user.follow(user_to_follow)
|
|
|
345 |
except Exception as e:
|
346 |
flash('Failed to follow the user. Please try again.', 'error')
|
347 |
print(f"Error: {str(e)}")
|
348 |
return redirect(url_for('view_profile', user_id=user_id))
|
349 |
|
350 |
+
flash(f"You are now following {user_to_follow.username}.", 'success')
|
|
|
351 |
return redirect(url_for('view_profile', user_id=user_id))
|
352 |
|
353 |
+
|
354 |
@app.route('/unfollow/<int:user_id>', methods=['POST'])
|
355 |
@login_required
|
356 |
+
def unfollow(user_id, page):
|
357 |
+
user_to_unfollow = User.query.get(user_id)
|
|
|
|
|
358 |
if user_to_unfollow is None:
|
359 |
flash('User not found.', 'danger')
|
360 |
return redirect(url_for('index'))
|
361 |
|
362 |
if current_user.is_following(user_to_unfollow):
|
363 |
+
current_user.unfollow(user_to_unfollow)
|
364 |
+
flash('You have unfollowed {}.'.format(user_to_unfollow.username), 'success')
|
|
|
365 |
else:
|
366 |
flash('You are not following this user.', 'info')
|
367 |
+
if page == 'profile':
|
368 |
+
return redirect(url_for('view_profile', user_id=user_id))
|
369 |
+
elif page == 'search':
|
370 |
+
return redirect(url_for('search_results', query=request.form['query']))
|
371 |
+
else:
|
372 |
+
return redirect(url_for('view_profile', user_id=user_id))
|
373 |
+
|
374 |
+
|
375 |
+
@app.route('/account', methods=['GET', 'POST'])
|
376 |
+
@login_required
|
377 |
+
def account():
|
378 |
+
if request.method == 'POST':
|
379 |
+
current_user.username = request.form['username']
|
380 |
+
current_user.email = request.form['email']
|
381 |
+
current_user.first_name = request.form['first_name']
|
382 |
+
current_user.last_name = request.form['last_name']
|
383 |
+
current_user.bio = request.form['bio']
|
384 |
+
current_user.location = request.form['location']
|
385 |
+
current_user.profession = request.form['profession']
|
386 |
+
|
387 |
+
profile_picture = request.files['profile_picture']
|
388 |
+
if profile_picture and allowed_file(profile_picture.filename):
|
389 |
+
filename = str(uuid.uuid4()) + secure_filename(profile_picture.filename)
|
390 |
+
profile_picture.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
|
391 |
+
|
392 |
+
if current_user.profile_pic is not None and current_user.profile_pic != 'default.jpg':
|
393 |
+
old_profile_picture_path = os.path.join(app.config['UPLOAD_FOLDER'], current_user.profile_pic)
|
394 |
+
os.remove(old_profile_picture_path)
|
395 |
+
|
396 |
+
current_user.profile_pic = filename
|
397 |
+
|
398 |
+
new_password = request.form['new_password']
|
399 |
+
if new_password:
|
400 |
+
current_user.password = generate_password_hash(new_password, method='scrypt')
|
401 |
+
|
402 |
+
db.session.commit()
|
403 |
+
flash('Profile updated successfully!', 'success')
|
404 |
+
return redirect(url_for('account'))
|
405 |
+
|
406 |
+
return render_template('account.html')
|
407 |
+
|
408 |
+
@app.route('/search_user', methods=['GET'])
|
409 |
+
def search_user():
|
410 |
+
search_query = request.args.get('search_query', '')
|
411 |
+
users = User.query.filter(
|
412 |
+
|
413 |
+
or_(
|
414 |
+
User.username.ilike(f'%{search_query}%'),
|
415 |
+
User.first_name.ilike(f'%{search_query}%'),
|
416 |
+
User.last_name.ilike(f'%{search_query}%'),
|
417 |
+
(User.first_name + User.last_name).like(f'%{search_query}%')
|
418 |
+
)
|
419 |
+
).all()
|
420 |
+
|
421 |
+
|
422 |
+
#users = User.query.filter(User.username.ilike(f'%{search_query}%')).all()
|
423 |
+
csrf_token = generate_csrf() # Generate CSRF token
|
424 |
+
return render_template('search_results.html', users=users, csrf_token=csrf_token, searchq=search_query )
|
425 |
+
|
426 |
+
@app.route('/user/<int:user_id>')
|
427 |
+
@login_required
|
428 |
+
def view_profile(user_id):
|
429 |
+
user = User.query.get(user_id)
|
430 |
+
if not user:
|
431 |
+
flash('User not found.', 'error')
|
432 |
+
return redirect(url_for('search_user'))
|
433 |
+
|
434 |
+
posts = Post.query.filter_by(user_id=user.id).order_by(Post.created_at.desc()).all()
|
435 |
+
csrf_token = generate_csrf()
|
436 |
+
return render_template('user_profile.html', user=user, posts=posts, csrf_token=csrf_token, profile_user_id=user_id)
|
437 |
+
|
438 |
+
@app.route('/add_comment/<int:post_id>', methods=['POST'])
|
439 |
+
@login_required
|
440 |
+
def add_comment(post_id):
|
441 |
+
content = request.form['content']
|
442 |
+
post = Post.query.get(post_id)
|
443 |
+
if not post:
|
444 |
+
flash('Post not found.', 'error')
|
445 |
+
return redirect(url_for('index'))
|
446 |
+
current_user.add_comment(post, content)
|
447 |
+
|
448 |
+
flash('Comment added successfully.', 'success')
|
449 |
+
return redirect(url_for('index'))
|
450 |
+
|
451 |
+
@login_required
|
452 |
+
@app.route('/like_post/<int:post_id>', methods=['POST'])
|
453 |
+
def like_post(post_id):
|
454 |
+
post = Post.query.get(post_id)
|
455 |
+
if not post:
|
456 |
+
flash('Post not found.', 'error')
|
457 |
+
return redirect(url_for('index'))
|
458 |
+
|
459 |
+
if current_user.has_liked_post(post):
|
460 |
+
current_user.unlike_post(post)
|
461 |
+
db.session.commit()
|
462 |
+
liked = False
|
463 |
+
else:
|
464 |
+
current_user.like_post(post)
|
465 |
+
db.session.commit()
|
466 |
+
liked = True
|
467 |
+
|
468 |
+
likes_count = post.likes_count
|
469 |
+
response_data = {'likes_count': likes_count, 'liked': liked}
|
470 |
+
return jsonify(response_data)
|
471 |
+
|
472 |
+
|
473 |
+
@app.route('/send_message', methods=['POST'])
|
474 |
+
@login_required
|
475 |
+
def send_message():
|
476 |
+
recipient_username = request.form['recipient_username']
|
477 |
+
message_content = request.form['message_content']
|
478 |
+
|
479 |
+
recipient = User.query.filter_by(username=recipient_username).first()
|
480 |
+
if not recipient:
|
481 |
+
flash('Recipient not found.', 'error')
|
482 |
+
return redirect(url_for('conversations'))
|
483 |
+
|
484 |
+
new_message = Message(sender_id=current_user.id, recipient_id=recipient.id, content=message_content)
|
485 |
+
db.session.add(new_message)
|
486 |
+
db.session.commit()
|
487 |
+
|
488 |
+
flash('Message sent successfully!', 'success')
|
489 |
+
return redirect(url_for('conversation', recipient_id=recipient.id))
|
490 |
+
|
491 |
+
|
492 |
+
@app.route('/conversations')
|
493 |
+
@login_required
|
494 |
+
def conversations():
|
495 |
+
conversations = db.session.query(User).join(
|
496 |
+
Message, or_(
|
497 |
+
and_(Message.sender_id == current_user.id, Message.recipient_id == User.id),
|
498 |
+
and_(Message.sender_id == User.id, Message.recipient_id == current_user.id)
|
499 |
+
)
|
500 |
+
).distinct(User.id).all()
|
501 |
+
|
502 |
+
return render_template('conversations.html', conversations=conversations)
|
503 |
+
|
504 |
+
@app.route('/new_conversation', methods=['GET'])
|
505 |
+
@login_required
|
506 |
+
def new_conversation():
|
507 |
+
return render_template('new_conversation.html')
|
508 |
+
|
509 |
+
|
510 |
+
|
511 |
+
|
512 |
|
|
|
|
|
513 |
|
514 |
|
515 |
@app.route('/updb', methods=['GET'])
|
|
|
520 |
asyncio.set_event_loop(loop)
|
521 |
|
522 |
# Run the async function
|
523 |
+
session.close()
|
524 |
rp = loop.run_until_complete(updb())
|
525 |
loop.close() # Close the loop when done
|
526 |
|
|
|
529 |
return 'no'
|
530 |
|
531 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
532 |
|
|
|
|
|
533 |
|
534 |
+
@app.route('/conversation/<int:recipient_id>', methods=['GET', 'POST'])
|
535 |
+
@login_required
|
536 |
+
def conversation(recipient_id):
|
537 |
+
recipient = User.query.get(recipient_id)
|
538 |
+
if not recipient:
|
539 |
+
flash('Recipient not found.', 'error')
|
540 |
+
return redirect(url_for('conversations'))
|
541 |
+
|
542 |
+
if request.method == 'POST':
|
543 |
+
message_content = request.form['message_content']
|
544 |
+
|
545 |
+
new_message = Message(sender_id=current_user.id, recipient_id=recipient.id, content=message_content)
|
546 |
+
db.session.add(new_message)
|
547 |
+
db.session.commit()
|
548 |
+
|
549 |
+
flash('Message sent successfully!', 'success')
|
550 |
+
return redirect(url_for('conversation', recipient_id=recipient_id))
|
551 |
+
|
552 |
+
messages = Message.query.filter(or_(
|
553 |
+
and_(Message.sender_id == current_user.id, Message.recipient_id == recipient_id),
|
554 |
+
and_(Message.sender_id == recipient_id, Message.recipient_id == current_user.id)
|
555 |
+
)).order_by(Message.timestamp).all()
|
556 |
+
|
557 |
+
return render_template('conversation.html', recipient=recipient, messages=messages)
|
558 |
+
|
559 |
+
|
560 |
|
561 |
def start_flask_app():
|
562 |
with app.app_context():
|
563 |
+
db.create_all()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
564 |
app.run(debug=True, use_reloader=False, host="0.0.0.0", port=7860)
|
565 |
|
|
|
566 |
if __name__ == '__main__':
|
567 |
+
start_flask_app()
|