openfree commited on
Commit
19af799
ยท
verified ยท
1 Parent(s): 857f721

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +453 -83
app.py CHANGED
@@ -3,7 +3,17 @@ import os, re, json
3
 
4
  app = Flask(__name__)
5
 
6
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 1. CURATED CATEGORIES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
7
  CATEGORIES = {
8
  "Productivity": [
9
  "https://huggingface.co/spaces/ginigen/perflexity-clone",
@@ -61,20 +71,67 @@ CATEGORIES = {
61
  ],
62
  }
63
 
64
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 2. URL HELPERS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
65
- def direct_url(hf_url: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  m = re.match(r"https?://huggingface\.co/spaces/([^/]+)/([^/?#]+)", hf_url)
67
  if not m:
68
  return hf_url
69
  owner, name = m.groups()
70
  owner = owner.lower()
71
- name = name.replace('.', '-').replace('_', '-').lower()
72
  return f"https://{owner}-{name}.hf.space"
73
 
74
- def screenshot_url(hf_url: str) -> str:
75
- return f"https://image.thum.io/get/fullpage/{direct_url(hf_url)}"
76
 
77
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 3. API FOR TABS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  @app.route('/api/category')
79
  def api_category():
80
  cat = request.args.get('name', '')
@@ -84,105 +141,418 @@ def api_category():
84
  "title": url.split('/')[-1],
85
  "owner": url.split('/')[-2] if '/spaces/' in url else '',
86
  "iframe": direct_url(url),
87
- "shot": screenshot_url(url),
88
- "hf": url
89
  } for url in urls
90
  ])
91
 
92
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 4. ROUTES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  @app.route('/')
94
  def home():
95
- return render_template('index.html', cats=list(CATEGORIES.keys()))
96
-
97
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 5. CREATE TEMPLATE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
98
- os.makedirs('templates', exist_ok=True)
99
- with open('templates/index.html', 'w', encoding='utf-8') as fp:
100
- fp.write(r'''<!DOCTYPE html>
101
- <html><head><meta charset="utf-8"><meta name="viewport"content="width=device-width,initial-scale=1">
102
- <title>Dynamic HF Spaces Gallery</title>
 
103
  <style>
104
  @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;600&display=swap');
105
- body{margin:0;font-family:Nunito,sans-serif;background:#f6f8fb}
106
- .tabs{display:flex;flex-wrap:wrap;gap:8px;padding:16px}
107
- .tab{padding:6px 14px;border:none;border-radius:18px;background:#e2e8f0;font-weight:600;cursor:pointer}
108
- .tab.active{background:#a78bfa;color:#1a202c}
109
- .grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;padding:0 16px 60px}
110
- @media(max-width:800px){.grid{grid-template-columns:1fr}}
111
- .card{background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);overflow:hidden;height:420px;display:flex;flex-direction:column;position:relative}
112
- .frame{flex:1;position:relative;overflow:hidden}
113
- .frame iframe,.frame img{position:absolute;width:166.667%;height:166.667%;transform:scale(.6);transform-origin:top left;border:0}
114
- .err{display:none;align-items:center;justify-content:center;width:100%;height:100%;background:#fafafa;text-align:center;padding:10px;color:#666;font-size:.9rem}
115
- .foot{height:44px;background:#fafafa;display:flex;align-items:center;justify-content:center;border-top:1px solid #eee}
116
- .foot a{font-size:.82rem;font-weight:700;color:#4a6dd8;text-decoration:none}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  </style>
118
  </head>
119
  <body>
120
  <div class="tabs" id="tabs"></div>
121
- <div class="grid" id="grid"></div>
122
 
123
  <script>
124
- const cats={{cats|tojson}};
125
- const tabs=document.getElementById('tabs');
126
- const grid=document.getElementById('grid');
127
- let active="";
128
-
129
- /* ---------- card builder (dynamic + fallback) ---------- */
130
- function createCard(sp){
131
- const card=document.createElement('div');card.className='card';
132
-
133
- const frameBox=document.createElement('div');frameBox.className='frame';
134
- const ifr=document.createElement('iframe');
135
- ifr.src=sp.iframe; ifr.loading='lazy';
136
- frameBox.appendChild(ifr);
137
-
138
- const err=document.createElement('div');err.className='err';
139
- err.innerHTML=`Preview blocked.<br><a href="${sp.hf}" target="_blank">Open on HF โ†—</a>`;
140
- frameBox.appendChild(err);
141
-
142
- let loaded=false;
143
- ifr.onload = ()=>{ loaded=true; }; // success
144
- ifr.onerror= fallback; // immediate fail
145
- setTimeout(()=>{ if(!loaded) fallback(); },10000); // watchdog
146
-
147
- function fallback(){
148
- ifr.remove();
149
- const img=new Image(); img.src=sp.shot; img.loading='lazy';
150
- img.onerror=()=>{ err.style.display='flex'; };
151
- frameBox.prepend(img);
 
 
 
152
  }
 
 
 
 
 
 
 
153
 
154
- const foot=document.createElement('div');foot.className='foot';
155
- foot.innerHTML=`<a href="${sp.iframe}" target="_blank">${sp.title}</a>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
- card.appendChild(frameBox);
158
- card.appendChild(foot);
159
- return card;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  }
161
 
162
- /* ---------- load tab ---------- */
163
- function load(cat){
164
- if(cat===active) return;
165
- active=cat;
166
- [...tabs.children].forEach(b=>b.classList.toggle('active',b.dataset.c===cat));
167
- grid.innerHTML='<p style="grid-column:1/-1;text-align:center;padding:40px">Loadingโ€ฆ</p>';
168
- fetch('/api/category?name='+encodeURIComponent(cat))
169
- .then(r=>r.json()).then(arr=>{
170
- grid.innerHTML='';
171
- arr.forEach(sp=>grid.appendChild(createCard(sp)));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  }
174
 
175
- /* ---------- init tabs ---------- */
176
- cats.forEach((c,i)=>{
177
- const b=document.createElement('button');
178
- b.className='tab'; b.textContent=c; b.dataset.c=c;
179
- b.onclick=()=>load(c);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  tabs.appendChild(b);
181
- if(i===0) load(c);
182
  });
 
 
 
 
 
 
 
 
 
 
 
183
  </script>
184
- </body></html>''')
 
 
 
 
 
 
 
185
 
186
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 6. RUN โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
187
  if __name__ == '__main__':
188
- app.run(host='0.0.0.0', port=7860)
 
3
 
4
  app = Flask(__name__)
5
 
6
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 1. CONFIGURATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
7
+ DB_FILE = "favorite_sites.json" # Database file for user-saved sites
8
+
9
+ # Domains that commonly block iframes
10
+ BLOCKED_DOMAINS = [
11
+ "naver.com", "daum.net", "google.com",
12
+ "facebook.com", "instagram.com", "kakao.com",
13
+ "ycombinator.com"
14
+ ]
15
+
16
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 2. CURATED CATEGORIES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
17
  CATEGORIES = {
18
  "Productivity": [
19
  "https://huggingface.co/spaces/ginigen/perflexity-clone",
 
71
  ],
72
  }
73
 
74
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 3. DATABASE FUNCTIONS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
75
+ def init_db():
76
+ if not os.path.exists(DB_FILE):
77
+ with open(DB_FILE, "w", encoding="utf-8") as f:
78
+ json.dump([], f, ensure_ascii=False)
79
+
80
+ def load_db():
81
+ try:
82
+ with open(DB_FILE, "r", encoding="utf-8") as f:
83
+ raw = json.load(f)
84
+ return raw if isinstance(raw, list) else []
85
+ except Exception:
86
+ return []
87
+
88
+ def save_db(lst):
89
+ try:
90
+ with open(DB_FILE, "w", encoding="utf-8") as f:
91
+ json.dump(lst, f, ensure_ascii=False, indent=2)
92
+ return True
93
+ except Exception:
94
+ return False
95
+
96
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 4. URL HELPERS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
97
+ def direct_url(hf_url):
98
  m = re.match(r"https?://huggingface\.co/spaces/([^/]+)/([^/?#]+)", hf_url)
99
  if not m:
100
  return hf_url
101
  owner, name = m.groups()
102
  owner = owner.lower()
103
+ name = name.replace('.', '-').replace('_', '-').lower()
104
  return f"https://{owner}-{name}.hf.space"
105
 
106
+ def screenshot_url(url):
107
+ return f"https://image.thum.io/get/fullpage/{url}"
108
 
109
+ def process_url_for_preview(url):
110
+ """Returns (preview_url, mode)"""
111
+ # Handle blocked domains first
112
+ if any(d for d in BLOCKED_DOMAINS if d in url):
113
+ return screenshot_url(url), "snapshot"
114
+
115
+ # Special case handling for problematic URLs
116
+ if "vibe-coding-tetris" in url or "World-of-Tank-GAME" in url or "Minesweeper-Game" in url:
117
+ return screenshot_url(url), "snapshot"
118
+
119
+ # General HF space handling
120
+ try:
121
+ if "huggingface.co/spaces" in url:
122
+ parts = url.rstrip("/").split("/")
123
+ if len(parts) >= 5:
124
+ owner = parts[-2]
125
+ name = parts[-1]
126
+ embed_url = f"https://huggingface.co/spaces/{owner}/{name}/embed"
127
+ return embed_url, "iframe"
128
+ except Exception:
129
+ return screenshot_url(url), "snapshot"
130
+
131
+ # Default handling
132
+ return url, "iframe"
133
+
134
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 5. API ROUTES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
135
  @app.route('/api/category')
136
  def api_category():
137
  cat = request.args.get('name', '')
 
141
  "title": url.split('/')[-1],
142
  "owner": url.split('/')[-2] if '/spaces/' in url else '',
143
  "iframe": direct_url(url),
144
+ "shot": screenshot_url(url),
145
+ "hf": url
146
  } for url in urls
147
  ])
148
 
149
+ @app.route('/api/favorites')
150
+ def api_favorites():
151
+ urls = load_db()
152
+ page = int(request.args.get('page', 1))
153
+ per_page = int(request.args.get('per_page', 9))
154
+
155
+ total_pages = max(1, (len(urls) + per_page - 1) // per_page)
156
+ start = (page - 1) * per_page
157
+ end = min(start + per_page, len(urls))
158
+
159
+ urls_page = urls[start:end]
160
+
161
+ result = []
162
+ for url in urls_page:
163
+ try:
164
+ preview_url, mode = process_url_for_preview(url)
165
+ result.append({
166
+ "title": url.split('/')[-1],
167
+ "url": url,
168
+ "preview_url": preview_url,
169
+ "mode": mode
170
+ })
171
+ except Exception:
172
+ # Fallback to screenshot mode
173
+ result.append({
174
+ "title": url.split('/')[-1],
175
+ "url": url,
176
+ "preview_url": screenshot_url(url),
177
+ "mode": "snapshot"
178
+ })
179
+
180
+ return jsonify({
181
+ "items": result,
182
+ "page": page,
183
+ "total_pages": total_pages
184
+ })
185
+
186
+ @app.route('/api/url/add', methods=['POST'])
187
+ def add_url():
188
+ url = request.form.get('url', '').strip()
189
+ if not url:
190
+ return jsonify({"success": False, "message": "URL is required"})
191
+
192
+ data = load_db()
193
+ if url in data:
194
+ return jsonify({"success": False, "message": "URL already exists"})
195
+
196
+ data.insert(0, url)
197
+ save_db(data)
198
+ return jsonify({"success": True, "message": "URL added successfully"})
199
+
200
+ @app.route('/api/url/update', methods=['POST'])
201
+ def update_url():
202
+ old = request.form.get('old', '')
203
+ new = request.form.get('new', '').strip()
204
+
205
+ if not new:
206
+ return jsonify({"success": False, "message": "New URL is required"})
207
+
208
+ data = load_db()
209
+ try:
210
+ idx = data.index(old)
211
+ data[idx] = new
212
+ save_db(data)
213
+ return jsonify({"success": True, "message": "URL updated successfully"})
214
+ except ValueError:
215
+ return jsonify({"success": False, "message": "URL not found"})
216
+
217
+ @app.route('/api/url/delete', methods=['POST'])
218
+ def delete_url():
219
+ url = request.form.get('url', '')
220
+ data = load_db()
221
+ try:
222
+ data.remove(url)
223
+ save_db(data)
224
+ return jsonify({"success": True, "message": "URL deleted successfully"})
225
+ except ValueError:
226
+ return jsonify({"success": False, "message": "URL not found"})
227
+
228
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 6. MAIN ROUTES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
229
  @app.route('/')
230
  def home():
231
+ os.makedirs('templates', exist_ok=True)
232
+
233
+ with open('templates/index.html', 'w', encoding='utf-8') as fp:
234
+ fp.write(r'''<!DOCTYPE html>
235
+ <html>
236
+ <head>
237
+ <meta charset="utf-8">
238
+ <meta name="viewport" content="width=device-width, initial-scale=1">
239
+ <title>Web Gallery</title>
240
  <style>
241
  @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;600&display=swap');
242
+ body{margin:0;font-family:Nunito,sans-serif;background:#f6f8fb;}
243
+ .tabs{display:flex;flex-wrap:wrap;gap:8px;padding:16px;}
244
+ .tab{padding:6px 14px;border:none;border-radius:18px;background:#e2e8f0;font-weight:600;cursor:pointer;}
245
+ .tab.active{background:#a78bfa;color:#1a202c;}
246
+ .tab.manage{background:#ff6e91;color:white;}
247
+ .tab.manage.active{background:#ff2d62;color:white;}
248
+ .grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;padding:0 16px 60px;}
249
+ @media(max-width:800px){.grid{grid-template-columns:1fr;}}
250
+ .card{background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);overflow:hidden;height:420px;display:flex;flex-direction:column;position:relative;}
251
+ .frame{flex:1;position:relative;overflow:hidden;}
252
+ .frame iframe{position:absolute;width:166.667%;height:166.667%;transform:scale(.6);transform-origin:top left;border:0;}
253
+ .frame img{width:100%;height:100%;object-fit:cover;}
254
+ .foot{height:44px;background:#fafafa;display:flex;align-items:center;justify-content:center;border-top:1px solid #eee;}
255
+ .foot a{font-size:.82rem;font-weight:700;color:#4a6dd8;text-decoration:none;}
256
+ .pagination{display:flex;justify-content:center;margin:20px 0;gap:10px;}
257
+ .pagination button{padding:5px 15px;border:none;border-radius:20px;background:#e2e8f0;cursor:pointer;}
258
+ .pagination button:disabled{opacity:0.5;cursor:not-allowed;}
259
+ .manage-panel{background:white;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);margin:16px;padding:20px;}
260
+ .form-group{margin-bottom:15px;}
261
+ .form-group label{display:block;margin-bottom:5px;font-weight:600;}
262
+ .form-control{width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;}
263
+ .btn{padding:8px 15px;border:none;border-radius:4px;cursor:pointer;font-weight:600;}
264
+ .btn-primary{background:#4a6dd8;color:white;}
265
+ .btn-danger{background:#e53e3e;color:white;}
266
+ .btn-success{background:#38a169;color:white;}
267
+ .status{padding:10px;margin:10px 0;border-radius:4px;display:none;}
268
+ .status.success{display:block;background:#c6f6d5;color:#22543d;}
269
+ .status.error{display:block;background:#fed7d7;color:#822727;}
270
+ .url-list{margin:20px 0;border:1px solid #eee;border-radius:4px;max-height:300px;overflow-y:auto;}
271
+ .url-item{padding:10px;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center;}
272
+ .url-item:last-child{border-bottom:none;}
273
+ .url-controls{display:flex;gap:5px;}
274
  </style>
275
  </head>
276
  <body>
277
  <div class="tabs" id="tabs"></div>
278
+ <div id="content"></div>
279
 
280
  <script>
281
+ // Basic configuration
282
+ const cats = {{cats|tojson}};
283
+ const tabs = document.getElementById('tabs');
284
+ const content = document.getElementById('content');
285
+ let active = "";
286
+ let currentPage = 1;
287
+
288
+ // Simple utility functions
289
+ function loadHTML(url, callback) {
290
+ const xhr = new XMLHttpRequest();
291
+ xhr.open('GET', url, true);
292
+ xhr.onreadystatechange = function() {
293
+ if (xhr.readyState === 4 && xhr.status === 200) {
294
+ callback(xhr.responseText);
295
+ }
296
+ };
297
+ xhr.send();
298
+ }
299
+
300
+ function makeRequest(url, method, data, callback) {
301
+ const xhr = new XMLHttpRequest();
302
+ xhr.open(method, url, true);
303
+ xhr.onreadystatechange = function() {
304
+ if (xhr.readyState === 4 && xhr.status === 200) {
305
+ callback(JSON.parse(xhr.responseText));
306
+ }
307
+ };
308
+ if (method === 'POST') {
309
+ xhr.send(data);
310
+ } else {
311
+ xhr.send();
312
  }
313
+ }
314
+
315
+ function updateTabs() {
316
+ Array.from(tabs.children).forEach(b => {
317
+ b.classList.toggle('active', b.dataset.c === active);
318
+ });
319
+ }
320
 
321
+ // Tab handlers
322
+ function loadCategory(cat) {
323
+ if(cat === active) return;
324
+ active = cat;
325
+ updateTabs();
326
+
327
+ content.innerHTML = '<p style="text-align:center;padding:40px">Loadingโ€ฆ</p>';
328
+
329
+ makeRequest('/api/category?name=' + encodeURIComponent(cat), 'GET', null, function(data) {
330
+ let html = '<div class="grid">';
331
+
332
+ data.forEach(item => {
333
+ html += `
334
+ <div class="card">
335
+ <div class="frame">
336
+ <iframe src="${item.iframe}" loading="lazy" sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts allow-downloads"></iframe>
337
+ </div>
338
+ <div class="foot">
339
+ <a href="${item.hf}" target="_blank">${item.title}</a>
340
+ </div>
341
+ </div>
342
+ `;
343
+ });
344
+
345
+ html += '</div>';
346
+ content.innerHTML = html;
347
+ });
348
+ }
349
 
350
+ function loadFavorites(page) {
351
+ if(active === 'Favorites' && currentPage === page) return;
352
+ active = 'Favorites';
353
+ currentPage = page || 1;
354
+ updateTabs();
355
+
356
+ content.innerHTML = '<p style="text-align:center;padding:40px">Loadingโ€ฆ</p>';
357
+
358
+ makeRequest('/api/favorites?page=' + currentPage, 'GET', null, function(data) {
359
+ let html = '<div class="grid">';
360
+
361
+ if(data.items.length === 0) {
362
+ html += '<p style="grid-column:1/-1;text-align:center;padding:40px">No favorites saved yet.</p>';
363
+ } else {
364
+ data.items.forEach(item => {
365
+ if(item.mode === 'snapshot') {
366
+ html += `
367
+ <div class="card">
368
+ <div class="frame">
369
+ <img src="${item.preview_url}" loading="lazy">
370
+ </div>
371
+ <div class="foot">
372
+ <a href="${item.url}" target="_blank">${item.title}</a>
373
+ </div>
374
+ </div>
375
+ `;
376
+ } else {
377
+ html += `
378
+ <div class="card">
379
+ <div class="frame">
380
+ <iframe src="${item.preview_url}" loading="lazy" sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts allow-downloads"></iframe>
381
+ </div>
382
+ <div class="foot">
383
+ <a href="${item.url}" target="_blank">${item.title}</a>
384
+ </div>
385
+ </div>
386
+ `;
387
+ }
388
+ });
389
+ }
390
+
391
+ html += '</div>';
392
+
393
+ // Add pagination
394
+ html += `
395
+ <div class="pagination">
396
+ <button ${currentPage <= 1 ? 'disabled' : ''} onclick="loadFavorites(${currentPage-1})">ยซ Previous</button>
397
+ <span>Page ${currentPage} of ${data.total_pages}</span>
398
+ <button ${currentPage >= data.total_pages ? 'disabled' : ''} onclick="loadFavorites(${currentPage+1})">Next ยป</button>
399
+ </div>
400
+ `;
401
+
402
+ content.innerHTML = html;
403
+ });
404
  }
405
 
406
+ function loadManage() {
407
+ if(active === 'Manage') return;
408
+ active = 'Manage';
409
+ updateTabs();
410
+
411
+ content.innerHTML = `
412
+ <div class="manage-panel">
413
+ <h2>Add New URL</h2>
414
+ <div class="form-group">
415
+ <label for="new-url">URL</label>
416
+ <input type="text" id="new-url" class="form-control" placeholder="https://example.com">
417
+ </div>
418
+ <button onclick="addUrl()" class="btn btn-primary">Add URL</button>
419
+ <div id="add-status" class="status"></div>
420
+
421
+ <h2>Manage Saved URLs</h2>
422
+ <div id="url-list" class="url-list">Loading...</div>
423
+ </div>
424
+ `;
425
+
426
+ loadUrlList();
427
+ }
428
+
429
+ // URL management functions
430
+ function loadUrlList() {
431
+ makeRequest('/api/favorites?per_page=100', 'GET', null, function(data) {
432
+ const urlList = document.getElementById('url-list');
433
+
434
+ if(data.items.length === 0) {
435
+ urlList.innerHTML = '<p style="text-align:center;padding:20px">No URLs saved yet.</p>';
436
+ return;
437
+ }
438
+
439
+ let html = '';
440
+ data.items.forEach(item => {
441
+ html += `
442
+ <div class="url-item">
443
+ <div>${item.url}</div>
444
+ <div class="url-controls">
445
+ <button class="btn" onclick="editUrl('${item.url}')">Edit</button>
446
+ <button class="btn btn-danger" onclick="deleteUrl('${item.url}')">Delete</button>
447
+ </div>
448
+ </div>
449
+ `;
450
  });
451
+
452
+ urlList.innerHTML = html;
453
+ });
454
+ }
455
+
456
+ function addUrl() {
457
+ const url = document.getElementById('new-url').value.trim();
458
+
459
+ if(!url) {
460
+ showStatus('add-status', 'Please enter a URL', false);
461
+ return;
462
+ }
463
+
464
+ const formData = new FormData();
465
+ formData.append('url', url);
466
+
467
+ makeRequest('/api/url/add', 'POST', formData, function(data) {
468
+ showStatus('add-status', data.message, data.success);
469
+ if(data.success) {
470
+ document.getElementById('new-url').value = '';
471
+ loadUrlList();
472
+ }
473
+ });
474
+ }
475
+
476
+ function editUrl(url) {
477
+ const newUrl = prompt('Edit URL:', url);
478
+
479
+ if(!newUrl || newUrl === url) return;
480
+
481
+ const formData = new FormData();
482
+ formData.append('old', url);
483
+ formData.append('new', newUrl);
484
+
485
+ makeRequest('/api/url/update', 'POST', formData, function(data) {
486
+ if(data.success) {
487
+ loadUrlList();
488
+ } else {
489
+ alert(data.message);
490
+ }
491
+ });
492
  }
493
 
494
+ function deleteUrl(url) {
495
+ if(!confirm('Are you sure you want to delete this URL?')) return;
496
+
497
+ const formData = new FormData();
498
+ formData.append('url', url);
499
+
500
+ makeRequest('/api/url/delete', 'POST', formData, function(data) {
501
+ if(data.success) {
502
+ loadUrlList();
503
+ } else {
504
+ alert(data.message);
505
+ }
506
+ });
507
+ }
508
+
509
+ function showStatus(id, message, success) {
510
+ const status = document.getElementById(id);
511
+ status.textContent = message;
512
+ status.className = success ? 'status success' : 'status error';
513
+ setTimeout(() => {
514
+ status.className = 'status';
515
+ }, 3000);
516
+ }
517
+
518
+ // Create tabs
519
+ // Favorites tab first
520
+ const favTab = document.createElement('button');
521
+ favTab.className = 'tab';
522
+ favTab.textContent = 'Favorites';
523
+ favTab.dataset.c = 'Favorites';
524
+ favTab.onclick = function() { loadFavorites(1); };
525
+ tabs.appendChild(favTab);
526
+
527
+ // Category tabs
528
+ cats.forEach(c => {
529
+ const b = document.createElement('button');
530
+ b.className = 'tab';
531
+ b.textContent = c;
532
+ b.dataset.c = c;
533
+ b.onclick = function() { loadCategory(c); };
534
  tabs.appendChild(b);
 
535
  });
536
+
537
+ // Manage tab last
538
+ const manageTab = document.createElement('button');
539
+ manageTab.className = 'tab manage';
540
+ manageTab.textContent = 'Manage';
541
+ manageTab.dataset.c = 'Manage';
542
+ manageTab.onclick = function() { loadManage(); };
543
+ tabs.appendChild(manageTab);
544
+
545
+ // Start with Favorites tab
546
+ loadFavorites(1);
547
  </script>
548
+ </body>
549
+ </html>''')
550
+
551
+ # Return the rendered template
552
+ return render_template('index.html', cats=list(CATEGORIES.keys()))
553
+
554
+ # Initialize database on startup
555
+ init_db()
556
 
 
557
  if __name__ == '__main__':
558
+ app.run(host='0.0.0.0', port=7860)