Spaces:
Zeuscloud
/
m
Sleeping

Eluza133 commited on
Commit
c3cabdb
·
verified ·
1 Parent(s): 0be21c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +286 -47
app.py CHANGED
@@ -27,16 +27,18 @@ def load_data():
27
  data = json.load(file)
28
  if not isinstance(data, dict):
29
  logging.warning("Data is not in dict format, initializing empty database")
30
- return {'posts': [], 'users': {}}
31
  if 'posts' not in data:
32
  data['posts'] = []
33
  if 'users' not in data:
34
  data['users'] = {}
 
 
35
  logging.info("Data loaded successfully")
36
  return data
37
  except Exception as e:
38
  logging.error(f"Error loading data: {e}")
39
- return {'posts': [], 'users': {}}
40
 
41
  def save_data(data):
42
  try:
@@ -78,7 +80,7 @@ def download_db_from_hf():
78
  logging.error(f"Error downloading database: {e}")
79
  if not os.path.exists(DATA_FILE):
80
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
81
- json.dump({'posts': [], 'users': {}}, f)
82
 
83
  def periodic_backup():
84
  while True:
@@ -175,7 +177,7 @@ BASE_STYLE = '''
175
  color: white;
176
  }
177
  .logout-btn:hover {
178
- background: #45b7b0; /* Исправлена синтаксическая ошибка */
179
  }
180
  .menu-btn {
181
  display: none;
@@ -303,6 +305,7 @@ NAV_HTML = '''
303
  {% if is_authenticated %}
304
  <a href="{{ url_for('profile') }}" class="nav-link"><span>👤</span> Profile ({{ username }})</a>
305
  <a href="{{ url_for('upload') }}" class="nav-link"><span>⬆️</span> Upload</a>
 
306
  <a href="{{ url_for('logout') }}" class="nav-link logout-btn"><span>🚪</span> Logout</a>
307
  {% else %}
308
  <a href="{{ url_for('login') }}" class="nav-link"><span>🔑</span> Login</a>
@@ -529,7 +532,7 @@ def logout():
529
  session.pop('username', None)
530
  return redirect(url_for('feed'))
531
 
532
- # Новый маршрут для увеличения просмотров
533
  @app.route('/increment_view/<post_id>', methods=['POST'])
534
  def increment_view(post_id):
535
  data = load_data()
@@ -537,7 +540,7 @@ def increment_view(post_id):
537
  if post:
538
  post['views'] = post.get('views', 0) + 1
539
  save_data(data)
540
- return '', 204 # Пустой ответ с кодом 204 (No Content)
541
  return 'Post not found', 404
542
 
543
  # Feed
@@ -701,16 +704,7 @@ def feed():
701
  const modalImg = document.getElementById('modalImage');
702
  modal.style.display = 'flex';
703
  modalImg.src = src;
704
-
705
- // Увеличиваем счетчик просмотров
706
- fetch('/increment_view/' + postId, {
707
- method: 'POST',
708
- headers: {
709
- 'Content-Type': 'application/json',
710
- }
711
- }).then(response => {
712
- if (!response.ok) console.error('Error incrementing view');
713
- });
714
  }
715
  function closeModal(event) {
716
  if (event.target.tagName !== 'IMG') {
@@ -1120,16 +1114,7 @@ def profile():
1120
  const modalImg = document.getElementById('modalImage');
1121
  modal.style.display = 'flex';
1122
  modalImg.src = src;
1123
-
1124
- // Увеличиваем счетчик просмотров
1125
- fetch('/increment_view/' + postId, {
1126
- method: 'POST',
1127
- headers: {
1128
- 'Content-Type': 'application/json',
1129
- }
1130
- }).then(response => {
1131
- if (!response.ok) console.error('Error incrementing view');
1132
- });
1133
  }
1134
  function closeModal(event) {
1135
  if (event.target.tagName !== 'IMG') {
@@ -1326,16 +1311,7 @@ def user_profile(username):
1326
  const modalImg = document.getElementById('modalImage');
1327
  modal.style.display = 'flex';
1328
  modalImg.src = src;
1329
-
1330
- // Увеличиваем счетчик просмотров
1331
- fetch('/increment_view/' + postId, {
1332
- method: 'POST',
1333
- headers: {
1334
- 'Content-Type': 'application/json',
1335
- }
1336
- }).then(response => {
1337
- if (!response.ok) console.error('Error incrementing view');
1338
- });
1339
  }
1340
  function closeModal(event) {
1341
  if (event.target.tagName !== 'IMG') {
@@ -1523,6 +1499,278 @@ def upload():
1523
  '''
1524
  return render_template_string(html, username=username, is_authenticated=is_authenticated)
1525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1526
  # Admin panel
1527
  @app.route('/admhosto', methods=['GET', 'POST'])
1528
  def admin_panel():
@@ -1695,16 +1943,7 @@ def admin_panel():
1695
  const modalImg = document.getElementById('modalImage');
1696
  modal.style.display = 'flex';
1697
  modalImg.src = src;
1698
-
1699
- // Увеличиваем счетчик просмотров
1700
- fetch('/increment_view/' + postId, {
1701
- method: 'POST',
1702
- headers: {
1703
- 'Content-Type': 'application/json',
1704
- }
1705
- }).then(response => {
1706
- if (!response.ok) console.error('Error incrementing view');
1707
- });
1708
  }
1709
  function closeModal(event) {
1710
  if (event.target.tagName !== 'IMG') {
@@ -1731,4 +1970,4 @@ def admin_panel():
1731
  if __name__ == '__main__':
1732
  backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1733
  backup_thread.start()
1734
- app.run(debug=True, host='0.0.0.0', port=7860),
 
27
  data = json.load(file)
28
  if not isinstance(data, dict):
29
  logging.warning("Data is not in dict format, initializing empty database")
30
+ return {'posts': [], 'users': {}, 'chats': {}}
31
  if 'posts' not in data:
32
  data['posts'] = []
33
  if 'users' not in data:
34
  data['users'] = {}
35
+ if 'chats' not in data:
36
+ data['chats'] = {}
37
  logging.info("Data loaded successfully")
38
  return data
39
  except Exception as e:
40
  logging.error(f"Error loading data: {e}")
41
+ return {'posts': [], 'users': {}, 'chats': {}}
42
 
43
  def save_data(data):
44
  try:
 
80
  logging.error(f"Error downloading database: {e}")
81
  if not os.path.exists(DATA_FILE):
82
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
83
+ json.dump({'posts': [], 'users': {}, 'chats': {}}, f)
84
 
85
  def periodic_backup():
86
  while True:
 
177
  color: white;
178
  }
179
  .logout-btn:hover {
180
+ background: #45b7b0;
181
  }
182
  .menu-btn {
183
  display: none;
 
305
  {% if is_authenticated %}
306
  <a href="{{ url_for('profile') }}" class="nav-link"><span>👤</span> Profile ({{ username }})</a>
307
  <a href="{{ url_for('upload') }}" class="nav-link"><span>⬆️</span> Upload</a>
308
+ <a href="{{ url_for('chat') }}" class="nav-link"><span>💬</span> Chat</a>
309
  <a href="{{ url_for('logout') }}" class="nav-link logout-btn"><span>🚪</span> Logout</a>
310
  {% else %}
311
  <a href="{{ url_for('login') }}" class="nav-link"><span>🔑</span> Login</a>
 
532
  session.pop('username', None)
533
  return redirect(url_for('feed'))
534
 
535
+ # Increment view count
536
  @app.route('/increment_view/<post_id>', methods=['POST'])
537
  def increment_view(post_id):
538
  data = load_data()
 
540
  if post:
541
  post['views'] = post.get('views', 0) + 1
542
  save_data(data)
543
+ return '', 204 # Empty response with code 204 (No Content)
544
  return 'Post not found', 404
545
 
546
  # Feed
 
704
  const modalImg = document.getElementById('modalImage');
705
  modal.style.display = 'flex';
706
  modalImg.src = src;
707
+ fetch('/increment_view/' + postId, { method: 'POST' });
 
 
 
 
 
 
 
 
 
708
  }
709
  function closeModal(event) {
710
  if (event.target.tagName !== 'IMG') {
 
1114
  const modalImg = document.getElementById('modalImage');
1115
  modal.style.display = 'flex';
1116
  modalImg.src = src;
1117
+ fetch('/increment_view/' + postId, { method: 'POST' });
 
 
 
 
 
 
 
 
 
1118
  }
1119
  function closeModal(event) {
1120
  if (event.target.tagName !== 'IMG') {
 
1311
  const modalImg = document.getElementById('modalImage');
1312
  modal.style.display = 'flex';
1313
  modalImg.src = src;
1314
+ fetch('/increment_view/' + postId, { method: 'POST' });
 
 
 
 
 
 
 
 
 
1315
  }
1316
  function closeModal(event) {
1317
  if (event.target.tagName !== 'IMG') {
 
1499
  '''
1500
  return render_template_string(html, username=username, is_authenticated=is_authenticated)
1501
 
1502
+ # Chat
1503
+ @app.route('/chat', methods=['GET', 'POST'])
1504
+ def chat():
1505
+ if 'username' not in session:
1506
+ flash('Login to use chat!')
1507
+ return redirect(url_for('login'))
1508
+
1509
+ data = load_data()
1510
+ username = session['username']
1511
+ is_authenticated = 'username' in session
1512
+
1513
+ # Get user's chats
1514
+ user_chats = {chat_id: chat for chat_id, chat in data['chats'].items()
1515
+ if username in chat['participants']}
1516
+
1517
+ if request.method == 'POST':
1518
+ if 'new_chat' in request.form:
1519
+ recipient = request.form.get('recipient')
1520
+ if recipient and recipient in data['users'] and recipient != username:
1521
+ chat_id = f"chat_{len(data['chats']) + 1}_{int(time.time())}"
1522
+ data['chats'][chat_id] = {
1523
+ 'participants': [username, recipient],
1524
+ 'messages': []
1525
+ }
1526
+ save_data(data)
1527
+ return redirect(url_for('chat', chat_id=chat_id))
1528
+
1529
+ elif 'send_message' in request.form:
1530
+ chat_id = request.form.get('chat_id')
1531
+ message = request.form.get('message')
1532
+ file = request.files.get('file')
1533
+ post_id = request.form.get('post_id')
1534
+
1535
+ if chat_id in user_chats:
1536
+ message_data = {
1537
+ 'sender': username,
1538
+ 'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
1539
+ }
1540
+
1541
+ if message:
1542
+ message_data['text'] = message
1543
+
1544
+ if file and file.filename:
1545
+ filename = secure_filename(file.filename)
1546
+ temp_path = os.path.join('uploads', filename)
1547
+ os.makedirs('uploads', exist_ok=True)
1548
+ file.save(temp_path)
1549
+
1550
+ file_type = 'video' if filename.lower().endswith(('.mp4', '.mov', '.avi')) else 'photo'
1551
+ api = HfApi()
1552
+ file_path = f"chat_files/{chat_id}/{filename}"
1553
+ api.upload_file(
1554
+ path_or_fileobj=temp_path,
1555
+ path_in_repo=file_path,
1556
+ repo_id=REPO_ID,
1557
+ repo_type="dataset",
1558
+ token=HF_TOKEN_WRITE,
1559
+ commit_message=f"Uploaded chat file by {username}"
1560
+ )
1561
+ message_data['file'] = file_path
1562
+ message_data['file_type'] = file_type
1563
+ if os.path.exists(temp_path):
1564
+ os.remove(temp_path)
1565
+
1566
+ if post_id:
1567
+ post = next((p for p in data['posts'] if p['id'] == post_id and p['uploader'] == username), None)
1568
+ if post:
1569
+ message_data['post_id'] = post_id
1570
+
1571
+ if 'text' in message_data or 'file' in message_data or 'post_id' in message_data:
1572
+ data['chats'][chat_id]['messages'].append(message_data)
1573
+ save_data(data)
1574
+
1575
+ return redirect(url_for('chat', chat_id=chat_id))
1576
+
1577
+ selected_chat_id = request.args.get('chat_id')
1578
+ selected_chat = user_chats.get(selected_chat_id, None)
1579
+
1580
+ html = '''
1581
+ <!DOCTYPE html>
1582
+ <html lang="en">
1583
+ <head>
1584
+ <meta charset="UTF-8">
1585
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1586
+ <meta name="keywords" content="interracial porn, bbc porn, qos, queen of spades, big black cock">
1587
+ <title>Chat - Content Hub</title>
1588
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap" rel="stylesheet">
1589
+ <style>
1590
+ ''' + BASE_STYLE + '''
1591
+ .container {
1592
+ display: flex;
1593
+ max-width: 1200px;
1594
+ gap: 30px;
1595
+ }
1596
+ .chat-list {
1597
+ width: 300px;
1598
+ background: var(--card-bg-light);
1599
+ backdrop-filter: blur(20px);
1600
+ padding: 25px;
1601
+ border-radius: 20px;
1602
+ box-shadow: var(--shadow);
1603
+ }
1604
+ body.dark .chat-list {
1605
+ background: var(--card-bg-dark);
1606
+ }
1607
+ .chat-area {
1608
+ flex: 1;
1609
+ background: var(--card-bg-light);
1610
+ backdrop-filter: blur(20px);
1611
+ padding: 25px;
1612
+ border-radius: 20px;
1613
+ box-shadow: var(--shadow);
1614
+ }
1615
+ body.dark .chat-area {
1616
+ background: var(--card-bg-dark);
1617
+ }
1618
+ h1 {
1619
+ font-size: 2.2em;
1620
+ margin-bottom: 30px;
1621
+ background: linear-gradient(45deg, var(--primary), var(--secondary));
1622
+ -webkit-background-clip: text;
1623
+ color: transparent;
1624
+ }
1625
+ .chat-item {
1626
+ padding: 15px;
1627
+ background: var(--glass-bg);
1628
+ border-radius: 15px;
1629
+ margin-bottom: 15px;
1630
+ cursor: pointer;
1631
+ transition: var(--transition);
1632
+ }
1633
+ .chat-item:hover {
1634
+ background: var(--primary);
1635
+ color: white;
1636
+ }
1637
+ .message {
1638
+ padding: 15px;
1639
+ background: var(--glass-bg);
1640
+ border-radius: 15px;
1641
+ margin-bottom: 15px;
1642
+ }
1643
+ .message img, .message video {
1644
+ max-width: 300px;
1645
+ max-height: 300px;
1646
+ border-radius: 10px;
1647
+ margin-top: 10px;
1648
+ }
1649
+ .message a {
1650
+ color: var(--primary);
1651
+ text-decoration: none;
1652
+ }
1653
+ .message a:hover {
1654
+ text-decoration: underline;
1655
+ }
1656
+ .message-form {
1657
+ margin-top: 20px;
1658
+ }
1659
+ .post-select {
1660
+ margin: 15px 0;
1661
+ padding: 14px;
1662
+ width: 100%;
1663
+ border-radius: 15px;
1664
+ background: var(--glass-bg);
1665
+ color: var(--text-light);
1666
+ }
1667
+ body.dark .post-select {
1668
+ color: var(--text-dark);
1669
+ }
1670
+ </style>
1671
+ </head>
1672
+ <body>
1673
+ <button class="menu-btn" onclick="toggleSidebar()">☰</button>
1674
+ ''' + NAV_HTML + '''
1675
+ <button class="theme-toggle" onclick="toggleTheme()">🌙</button>
1676
+ <div class="container">
1677
+ <div class="chat-list">
1678
+ <h1>Chats</h1>
1679
+ <form method="POST">
1680
+ <input type="text" name="recipient" placeholder="Enter username" required>
1681
+ <button type="submit" name="new_chat" class="btn">New Chat</button>
1682
+ </form>
1683
+ {% for chat_id, chat in user_chats.items() %}
1684
+ <div class="chat-item" onclick="window.location='{{ url_for('chat', chat_id=chat_id) }}'">
1685
+ {% for participant in chat['participants'] if participant != username %}
1686
+ {{ participant }}
1687
+ {% endfor %}
1688
+ </div>
1689
+ {% endfor %}
1690
+ </div>
1691
+ <div class="chat-area">
1692
+ {% if selected_chat %}
1693
+ <h1>Chat with {% for participant in selected_chat['participants'] if participant != username %}{{ participant }}{% endfor %}</h1>
1694
+ <div class="messages">
1695
+ {% for message in selected_chat['messages'] %}
1696
+ <div class="message">
1697
+ <strong>{{ message['sender'] }}</strong> ({{ message['time'] }}):
1698
+ {% if 'text' in message %}
1699
+ <p>{{ message['text'] }}</p>
1700
+ {% endif %}
1701
+ {% if 'file' in message %}
1702
+ {% if message['file_type'] == 'video' %}
1703
+ <video controls>
1704
+ <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ message['file'] }}" type="video/mp4">
1705
+ </video>
1706
+ {% else %}
1707
+ <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ message['file'] }}" alt="Chat file" onclick="openModal(this.src)">
1708
+ {% endif %}
1709
+ {% endif %}
1710
+ {% if 'post_id' in message %}
1711
+ {% set post = [p for p in posts if p['id'] == message['post_id']][0] %}
1712
+ <p>Shared post: <a href="{{ url_for('post_page', post_id=message['post_id']) }}">{{ post['title'] }}</a></p>
1713
+ {% endif %}
1714
+ </div>
1715
+ {% endfor %}
1716
+ </div>
1717
+ <form method="POST" enctype="multipart/form-data" class="message-form">
1718
+ <input type="hidden" name="chat_id" value="{{ selected_chat_id }}">
1719
+ <textarea name="message" placeholder="Type a message" rows="3"></textarea>
1720
+ <input type="file" name="file" accept="video/*,image/*">
1721
+ <select name="post_id" class="post-select">
1722
+ <option value="">Share a post (optional)</option>
1723
+ {% for post in user_posts %}
1724
+ <option value="{{ post['id'] }}">{{ post['title'] }}</option>
1725
+ {% endfor %}
1726
+ </select>
1727
+ <button type="submit" name="send_message" class="btn">Send</button>
1728
+ </form>
1729
+ {% else %}
1730
+ <h1>Select a chat to start messaging</h1>
1731
+ {% endif %}
1732
+ </div>
1733
+ </div>
1734
+ <div class="modal" id="imageModal" onclick="closeModal(event)">
1735
+ <img id="modalImage" src="">
1736
+ </div>
1737
+ <script>
1738
+ function toggleSidebar() {
1739
+ document.getElementById('sidebar').classList.toggle('active');
1740
+ }
1741
+ function toggleTheme() {
1742
+ document.body.classList.toggle('dark');
1743
+ localStorage.setItem('theme', document.body.classList.contains('dark') ? 'dark' : 'light');
1744
+ }
1745
+ function openModal(src) {
1746
+ const modal = document.getElementById('imageModal');
1747
+ const modalImg = document.getElementById('modalImage');
1748
+ modal.style.display = 'flex';
1749
+ modalImg.src = src;
1750
+ }
1751
+ function closeModal(event) {
1752
+ if (event.target.tagName !== 'IMG') {
1753
+ document.getElementById('imageModal').style.display = 'none';
1754
+ }
1755
+ }
1756
+ window.onload = () => {
1757
+ if (localStorage.getItem('theme') === 'dark') document.body.classList.add('dark');
1758
+ };
1759
+ </script>
1760
+ </body>
1761
+ </html>
1762
+ '''
1763
+ user_posts = [p for p in data['posts'] if p['uploader'] == username]
1764
+ return render_template_string(html,
1765
+ user_chats=user_chats,
1766
+ selected_chat=selected_chat,
1767
+ selected_chat_id=selected_chat_id,
1768
+ username=username,
1769
+ is_authenticated=is_authenticated,
1770
+ repo_id=REPO_ID,
1771
+ posts=data['posts'],
1772
+ user_posts=user_posts)
1773
+
1774
  # Admin panel
1775
  @app.route('/admhosto', methods=['GET', 'POST'])
1776
  def admin_panel():
 
1943
  const modalImg = document.getElementById('modalImage');
1944
  modal.style.display = 'flex';
1945
  modalImg.src = src;
1946
+ fetch('/increment_view/' + postId, { method: 'POST' });
 
 
 
 
 
 
 
 
 
1947
  }
1948
  function closeModal(event) {
1949
  if (event.target.tagName !== 'IMG') {
 
1970
  if __name__ == '__main__':
1971
  backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1972
  backup_thread.start()
1973
+ app.run(debug=True, host='0.0.0.0', port=7860)