-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.html
386 lines (352 loc) · 18.1 KB
/
main.html
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>oldemmi</title>
<link rel="apple-touch-icon" sizes="180x180" href="https://oldemmi.vercel.app/resources/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://oldemmi.vercel.app/resources/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://oldemmi.vercel.app/resources/favicon/favicon-16x16.png">
<link rel="manifest" href="https://oldemmi.vercel.app/resources/favicon/site.webmanifest">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#303030">
<script>
let bebra = window.innerWidth < 550 ? 550 : window.innerWidth;
let conebebra = bebra / 1300;
document.querySelector('meta[name="viewport"]').setAttribute('content', `width=${bebra}, initial-scale=${conebebra}`);
const colorned = localStorage.getItem("theme") || "green";
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = `https://oldemmi.vercel.app/css/${colorned}/dark.css?nocache=` + new Date().getTime();
document.head.appendChild(link);
</script>
</head>
<body>
<div class="navbar">
<div class="oldemmi">
<img src="https://oldemmi.vercel.app/resources/logo.png" alt="oldemmi logo">
<div class="text">
oldemmi
<div class="instance">
<!-- тут будет сервер -->
</div>
</div>
</div>
<div style="justify-content: normal;">
<select onchange="filters()" name="filter" id="filter">
<option value="Hot">hot</option>
<option value="New">new</option>
<option value="Old">old</option>
<option value="Controversial">controversial</option>
</select>
<select onchange="fromFilters()" name="fromSelect" id="fromSelect">
<option value="All">all posts</option>
<option value="Local">local</option>
<option value="Subscribed">subscribed</option>
</select>
</div>
<div class="normal">
<button id="ccom" style="display: none;" onclick="window.location.href = 'https://oldemmi.vercel.app/create-community.html';">➕</button>
<button id="settings" style="display: none;" onclick="goToSettings()">⚙️</button>
<button onclick="goToSearch()">🔎</button>
<button id="logout" style="display: none;" onclick="logout('userlogout')">logout</button>
<button style="display: inline;" id="login" class="login" onclick="login()">login</button>
<button style="display: inline;" id="changeServer" onclick="change_server()">change the instance</button>
<div style="display: inline;" class="neP"><div style="display: none;" class="profileInBar"></div></div>
</div>
</div>
<div id="posts">
<!-- сюда будут добавляться посты через js -->
</div>
<div class="load-more">
<button onclick="loadMorePosts()">more</button>
</div>
<script src="https://oldemmi.vercel.app/js/markdown.js"></script>
<script src="https://oldemmi.vercel.app/js/needScript.js"></script>
<script src="https://oldemmi.vercel.app/js/actions.js"></script>
<script defer>
let usernamentu = null;
const urlParams = new URLSearchParams(window.location.search);
let filter = urlParams.get('filter') || "New";
let fromFilter = localStorage.getItem("fromFilter") || urlParams.get('from') || "All";
let page = 1; // текущая страница для загрузки
const limit = 9; // количество постов на одну загрузку
const server = localStorage.getItem("accountServer") || urlParams.get('server') || "lemmy.world";
const api = `https://${server}/api/v3`
let fSelect = document.querySelector(".navbar #filter");
fSelect.value = filter;
let fromSelect = document.querySelector(".navbar #fromSelect");
fromSelect.value = fromFilter;
const lemmyToken = localStorage.getItem("lemmyToken");
function instanceapply() {
const instdiv = document.querySelector(".navbar .oldemmi .text .instance");
instdiv.innerHTML = `
${server}
`;
}
// функция для получения постов
async function fetchPosts() {
try {
const response = await fetch(`${api}/post/list?page=${page}&limit=${limit}&sort=${filter}&type_=${fromFilter}`, {
method: "GET",
headers: { "Content-Type": "application/json", "authorization": `Bearer ${localStorage.getItem("lemmyToken")}` }
});
const data = await response.json();
return data.posts;
} catch (error) {
alert(`error while loading posts: ${error}`);
}
}
async function getLoggined() {
try {
const response = await fetch(`${api}/site`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${lemmyToken}`
}
});
const data = await response.json();
return data.my_user.local_user_view.person;
} catch (error) {
alert(`error while loading profile: ${error}`);
}
}
async function validateToken() {
const serverUrl = `https://${server}/api/v3/user/validate_auth`;
try {
const response = await fetch(serverUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${lemmyToken}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("token is valid:", data);
return true; // токен валидный
} catch (error) {
console.error("token validation failed:", error);
return false; // токен не валидный
}
}
function getInstanceFromActorId(actorId) {
const url = new URL(actorId);
return url.hostname; // возвращает домен, например, "lemmy.world"
}
function goToComments(postoid, serveromo) {
window.location.href = `https://oldemmi.vercel.app/comments?server=${server}&post=${postoid}`
}
function goToCommunity(comname, servecom) {
window.location.href = `https://oldemmi.vercel.app/community?server=${servecom}&community=${comname}`
}
async function loginedornot() {
try {
const profileInBar = document.querySelector(".navbar .normal .neP .profileInBar");
const changeServer = document.getElementById("changeServer");
const login = document.getElementById("login");
const logout = document.getElementById("logout");
const settings = document.getElementById("settings");
const ccom = document.getElementById("ccom");
if (lemmyToken) {
const lemmyTokenValid = await validateToken();
if (lemmyTokenValid) {
profileInBar.style.display = "flex";
settings.style.display = "flex";
ccom.style.display = "flex";
logout.style.display = "flex";
changeServer.style.display = "none";
login.style.display = "none";
const user = await getLoggined();
usernamentu = user.name;
profileInBar.innerHTML = `
<img onclick="goToProfile('${user.name}', '${server}')" src="${user.avatar || 'https://lgor360.github.io/oldemmi/user.png'}">
<div class="text">
${user.display_name || user.name}
</div>
`;
} else {
logout("notvalid");
}
}
return;
} catch (error) {
alert(`error while account login check: ${error}`);
}
}
// функция для отображения постов
async function renderPosts(posts) {
try {
const postsContainer = document.getElementById("posts");
posts.forEach(post => {
const locked = post.post.locked === true ? '🔒' : '';
const deleted = post.post.deleted === true ? '🗑️' : '';
const pinned_community = post.post.featured_community === true ? '📍' : '';
const blocked = post.post.removed === true ? '🚫' : '';
const pinned_local = post.post.featured_local === true ? '📌' : '';
const edited = post.post.updated ? '✏️' : '';
const nsfw = post.post.nsfw === true ? '🔞' : '';
const postotourl = post.post.url && post.post.url !== post.post.thumbnail_url ? post.post.url : null;
const postElement = document.createElement("div");
postElement.classList.add("post");
const likecolor = post.my_vote === 1 ? "#b3c46d" : "#ffffff";
const dislikecolor = post.my_vote === -1 ? "#b3c46d" : "#ffffff";
postElement.innerHTML = `
<div class="post-header">
<img onclick="goToProfile('${post.creator.name}', '${getInstanceFromActorId(post.creator.actor_id)}')" src="${post.creator.avatar || 'https://oldemmi.vercel.app/resources/user.png'}" alt="avatar">
<div class="author">
${post.creator.display_name || post.creator.name}
<div onclick="goToCommunity('${post.community.name}', '${getInstanceFromActorId(post.community.actor_id)}')" class="community">
${post.community.name}
@
${getInstanceFromActorId(post.community.actor_id)}
</div>
</div>
<div class="post-status">
<div onclick="alert('this post is locked')" class="locked">
${locked}
</div>
<div onclick="alert('this post is deleted')" class="deleted">
${deleted}
</div>
<div onclick="alert('this post is nsfw (18+)')" class="nsfw">
${nsfw}
</div>
<div onclick="alert('this post is edited')" class="edited">
${edited}
</div>
<div onclick="alert('this post is pinned in community')" class="pincom">
${pinned_community}
</div>
<div onclick="alert('this post is pinned in instance')" class="pininstance">
${pinned_local}
</div>
<div onclick="alert('this post is removed by community moderator')" class="blocked">
${blocked}
</div>
</div>
</div>
<div class="post-name">${post.post.name}</div>
<div class="post-text">${parseMarkdown(post.post.body || "")}</div>
${post.post.thumbnail_url ? `<img src="${post.post.thumbnail_url}" class="post-image" alt="image">` : ""}
${postotourl ? `<div class="post-link"><a rel="noopener noreferrer" href="${postotourl}">${linkMax(postotourl)}</a></div>` : ""}
<div class="post-footer">
<div class="counter">
<button onclick="voteContent(1, 'post', ${post.post.id}, ${post.my_vote})">👍</button>
<span style="color: ${likecolor};" id="vote${post.post.id}">${post.counts.upvotes}</span>
</div>
<div class="counter">
<button onclick="voteContent(-1, 'post', ${post.post.id}, ${post.my_vote})">👎</button>
<span style="color: ${dislikecolor};" id="down${post.post.id}">${post.counts.downvotes}</span>
</div>
<div class="counter">
<button onclick="goToComments(${post.post.id}, '${server}')">💬</button>
<span>${post.counts.comments}</span>
</div>
</div>
`;
postsContainer.appendChild(postElement);
});
} catch (error) {
alert(`error while rendering posts: ${error}`);
}
}
// функция для загрузки постов
async function loadMorePosts() {
const posts = await fetchPosts();
await renderPosts(posts);
page++; // увеличиваем номер страницы
}
// функция для входа
function login() {
window.location.href = `https://oldemmi.vercel.app/login.html`;
}
function goToSettings() {
window.location.href = `https://oldemmi.vercel.app/settings?user=${usernamentu}`;
}
// функция для изменения инстанса
function change_server() {
const prompto = prompt("enter instance url. example: lemmy.world");
if (prompto) {
window.location.href = `https://oldemmi.vercel.app/home?server=${prompto}`
}
}
async function filters() {
filter = fSelect.value;
page = 1;
document.getElementById("posts").innerHTML = "";
const url = new URL(window.location);
url.searchParams.set("filter", filter);
window.history.replaceState({}, '', url);
await loadMorePosts();
}
async function fromFilters() {
fromFilter = fromSelect.value;
localStorage.setItem("fromFilter", fromFilter);
page = 1;
document.getElementById("posts").innerHTML = "";
const url = new URL(window.location);
url.searchParams.set("from", fromFilter);
window.history.replaceState({}, '', url);
await loadMorePosts();
}
function goToProfile(id, servero) {
window.location.href = `https://oldemmi.vercel.app/profile?server=${servero}&user=${id}`
}
function goToSearch() {
window.location.href = `https://oldemmi.vercel.app/search?server=${server}&filter=Posts`;
}
async function logout(option) {
const confirmation = confirm("are you sure want to logout?");
if (!confirmation) {
return; // если пользователь нажал "нет", ничего не делаем
}
const proxyUrl = "https://oldemmi.vercel.app/api/server.js";
const logoutData = {
url: `https://${localStorage.getItem("accountServer")}/api/v3/user/logout`,
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${lemmyToken}`
},
body: {}
};
try {
if (option === "userlogout") {
// выполняем запрос на выход через прокси
const response = await fetch(proxyUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(logoutData)
});
if (!response.ok) {
throw new Error(`logout failed: ${response.status} ${response.statusText}`);
}
}
// удаляем токен и сервер из LocalStorage
localStorage.removeItem("lemmyToken");
localStorage.removeItem("accountServer");
// перезапускаем текущую страницу
location.reload();
} catch (error) {
alert(`error during logout: ${error}`);
}
}
async function initPage() {
try {
await loginedornot();
// загружаем первые посты при загрузке страницы
await loadMorePosts();
// вставляем название сервера в заголовок
instanceapply();
} catch (error) {
alert(`error while initialization page: ${error}`);
}
}
initPage();
</script>
</body>
</html>