-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcross-posts.html
387 lines (354 loc) · 18.2 KB
/
cross-posts.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
387
<!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="#cfec66">
<script>
if (window.innerWidth < 550) {
document.querySelector('meta[name="viewport"]').setAttribute('content', 'width=550, initial-scale=1.0');
}
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = "https://oldemmi.vercel.app/css/dark.css?nocache=" + new Date().getTime();
document.head.appendChild(link);
</script>
</head>
<body>
<div class="navbar">
<div onclick="goToHome()" 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 class="normal">
<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>
<div style="display: inline;" class="neP"><div style="display: none;" class="profileInBar"></div></div>
</div>
</div>
<div id="post">
<!-- сюда будут добавляться посты через js -->
</div>
<hr width="93%" size="2" color="#c4db53">
<div id="posts">
<!-- сюда будут добавляться комментарии через js -->
</div>
<div class="load-more">
<button>more</button>
</div>
<script src="https://oldemmi.vercel.app/js/needScript.js"></script>
<script src="https://oldemmi.vercel.app/js/markdown.js"></script>
<script src="https://oldemmi.vercel.app/js/actions.js"></script>
<script defer>
const urlParams = new URLSearchParams(window.location.search);
const server = urlParams.get('server') || "lemmy.world";
const post = urlParams.get('post') || "826753";
let page = 1; // текущая страница для загрузки
const limit = 9; // количество постов на одну загрузку
const api = `https://${server}/api/v3`
const lemmyToken = localStorage.getItem("lemmyToken");
function instanceapply() {
const instdiv = document.querySelector(".navbar .oldemmi .text .instance");
instdiv.innerHTML = `
${server}
`;
}
function goToComments(postoid) {
window.location.href = `https://oldemmi.vercel.app/comments?server=${server}&post=${postoid}`
}
// функция для получения постов
async function fetchPost() {
try {
const response = await fetch(`${api}/post?id=${post}`, {
method: "GET",
headers: { "Content-Type": "application/json", "authorization": `Bearer ${localStorage.getItem("lemmyToken")}` }
});
const data = await response.json();
return data.post_view;
} catch (error) {
alert(`error while loading post: ${error}`);
}
}
async function fetchCross() {
try {
const response = await fetch(`${api}/post?id=${post}`, {
method: "GET",
headers: { "Content-Type": "application/json", "authorization": `Bearer ${localStorage.getItem("lemmyToken")}` }
});
const data = await response.json();
return data.cross_posts;
} catch (error) {
alert(`error while loading comments: ${error}`);
}
}
async function getLoggined() {
try {
const response = await fetch(`https://${localStorage.getItem("accountServer")}/api/v3/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://${localStorage.getItem("accountServer")}/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 goToCommunity(comname, servecom) {
window.location.href = `https://oldemmi.vercel.app/community?server=${servecom}&community=${comname}`
}
// функция для отображения постов
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 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 is cross-post')" class="nsfw">
🔄
</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})">💬</button>
<span>${post.counts.comments}</span>
</div>
</div>
`;
postsContainer.appendChild(postElement);
});
} catch (error) {
alert(`error while rendering posts: ${error}`);
}
}
// функция для отображения постов
function renderPost(post_view) {
try {
const postContainer = document.getElementById("post");
const locked = post_view.post.locked === true ? '🔒' : '';
const deleted = post_view.post.deleted === true ? '🗑️' : '';
const nsfw = post_view.post.nsfw === true ? '🔞' : '';
const postotourl = post_view.post.url && post_view.post.url !== post_view.post.thumbnail_url ? post_view.post.url : null;
const postElement = document.createElement("div");
postElement.classList.add("post");
postElement.innerHTML = `
<div class="post-header">
<img onclick="goToProfile('${post_view.creator.name}', '${getInstanceFromActorId(post_view.creator.actor_id)}')" src="${post_view.creator.avatar || 'https://oldemmi.vercel.app/resources/user.png'}" alt="avatar">
<div class="author">
${post_view.creator.display_name || post_view.creator.name}
<div onclick="goToCommunity('${post_view.community.name}', '${getInstanceFromActorId(post_view.community.actor_id)}')" class="community">
${post_view.community.name}
@
${getInstanceFromActorId(post_view.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>
</div>
<div class="post-name">${post_view.post.name}</div>
<div class="post-text">${parseMarkdown(post_view.post.body || "")}</div>
${post_view.post.thumbnail_url ? `<img src="${post_view.post.thumbnail_url}" class="post-image" alt="image">` : ""}
${postotourl ? `<div class="post-link"><a rel="noopener noreferrer" href="${postotourl}">${postotourl}</a></div>` : ""}
<div class="post-footer">
<div class="counter">
<button>👍</button>
<span>${post_view.counts.upvotes}</span>
</div>
<div class="counter">
<button>👎</button>
<span>${post_view.counts.downvotes}</span>
</div>
<div class="answer">
<button>💬</button>
<span>${post_view.counts.comments}</span>
</div>
</div>
`;
postContainer.appendChild(postElement);
} catch (error) {
alert(`error while rendering post: ${error}`);
}
}
// функция для загрузки комментариев
async function loadMoreCross() {
const cross = await fetchCross();
renderPosts(cross);
page++; // увеличиваем номер страницы
}
async function loadPost() {
const post_view = await fetchPost();
renderPost(post_view);
}
async function loginedornot() {
try {
const profileInBar = document.querySelector(".navbar .normal .neP .profileInBar");
const login = document.getElementById("login");
const logout = document.getElementById("logout");
if (lemmyToken) {
const lemmyTokenValid = await validateToken();
if (lemmyTokenValid) {
profileInBar.style.display = "flex";
logout.style.display = "flex";
login.style.display = "none";
const user = await getLoggined();
profileInBar.innerHTML = `
<img onclick="goToProfile('${user.name}', '${localStorage.getItem("accountServer")}')" 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}`);
}
}
// функция для входа
function login() {
window.location.href = `https://oldemmi.vercel.app/login`;
}
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}`);
}
}
function goToHome() {
window.location.href = `https://oldemmi.vercel.app/home?server=${server}`
}
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`;
}
// загружаем пост и комментарии при загрузке страницы
loginedornot();
loadPost();
loadMoreCross();
// вставляем название сервера в заголовок
instanceapply();
</script>
</body>
</html>