forked from niyazm524/arch_client_web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
259 lines (248 loc) · 8.68 KB
/
index.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
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<title>Хранилище данных</title>
</head>
<style>
/* Сброс стилей браузера */
html,
body {
margin: 0;
padding: 0;
}
/* Расположение двух блоков рядом по горизонтали */
body,
.container {
height: 100%;
width: 100%;
display: flex;
justify-content: space-around;
align-items: center;
}
.for-read,
.for-write {
width: 40%;
}
img {
position: absolute;
top: 20%;
height: 40%;
left: 50%;
}
</style>
<body>
<div class="container">
<form class="for-write" id="write-form">
<div>
<label for="text-input">Ввод</label>
<input id="text-input" type="text" />
</div>
<div>
<label for="file-input">Выбор файла</label>
<input id="file-input" type="file" />
<input type="submit" />
</div>
<div id="save-result"></div>
</form>
<div class="for-read">
<h2>Просмотр по категориям</h2>
<ul id="categories"></ul>
<h3>Сохраненный объект</h3>
<pre id="saved-object"></pre>
</div>
<button onClick="deleteCookie()">Выйти</button>
</div>
</body>
<script>
window.onload = function isToken() {
// При загрузке страницы проверять наличие токена
if (document.cookie === "") {
window.location.href = "auth.html";
}
};
function deleteCookie() {
// "Удалить" куки
document.cookie = "token= ; Max-Age=0";
window.location.href = "auth.html"; // Перейти на страницу авторизации
}
const API = "https://sadmadsoul.dev/api";
/**
* Фабрика методов апишки
* @param method HTTP метод
* @param endpoint
*/
function makeApiFunction(method, endpoint) {
return async function (data = null) {
try {
const response = await fetch(`${API}/${endpoint}`, {
method: method,
body: data != null ? JSON.stringify(data) : undefined,
headers: {
"Content-Type": "application/json",
Authorization: "Token " + document.cookie.split("=")[1],
},
});
if (response.ok) return await response.json();
} catch (error) {
console.error(error);
}
};
}
const api = {
user_input: makeApiFunction("POST", "data/"),
sendData: async function (data) {
var formData = new FormData(); // Создаем объект FormData
// Добавляем в него данные, введенные пользователем
formData.append("data", data);
const response = await fetch(`${API}/data/`, {
// Отправляем данные
method: "POST",
headers: {
Authorization: "Token " + document.cookie.split("=")[1],
},
body: formData,
});
return await response.json();
},
getCategories: makeApiFunction("GET", "category/"), // Поулучаем категории
getData: function (id) {
return fetch(`${API}/data/${id}`, {
// Отправляем запрос
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Token " + document.cookie.split("=")[1],
},
});
},
};
/**
* Отправляет строку данных на сервер, проверяя длину, и обновляет список категорий
*/
async function sendForm(event) {
// Знак браузеру, что не надо ничего делать, мы сами
event.preventDefault();
const inputElement = document.getElementById("text-input");
const input = inputElement.value;
let saveResult;
if (input.length === 0) {
// Если форма пустая
const fileInputElement = document.getElementById("file-input");
if (fileInputElement.files.length === 0) return; // Если нет файла, то выходим
saveResult = await api.sendData(fileInputElement.files[0]);
} else {
// Если файл есть
saveResult = await api.sendData(input);
inputElement.value = "";
}
if (saveResult.category != null) showSaveResult(saveResult.category);
await updateCategories();
}
function showSaveResult(objectType) {
const saveResultElement = document.getElementById("save-result");
saveResultElement.innerText = `Объект сохранен под категорией ${objectType}`;
setTimeout(function () {
saveResultElement.innerText = "";
}, 3500);
}
/**
* Запрашивает категории с сервера и рендерит их в список
*/
async function updateCategories() {
const categoriesElement = document.getElementById("categories");
const categories = await api.getCategories();
categoriesElement.innerHTML = "";
for (let category of categories) {
const newElement = document.createElement("li");
newElement.innerText = category.name;
newElement.dataset.id = category.id;
newElement.onclick = onCategoryClick;
categoriesElement.appendChild(newElement);
}
}
// Стратегия
class StrategyManager {
constructor() {
this._strategy = null;
}
set strategy(strategy) {
this._strategy = strategy;
}
doStrategy() {
this._strategy.doStrategy();
}
}
class ImgStrategy {
async doStrategy(buffer) {
document.getElementById("saved-object").innerText = " "; // "Убираем" текст
// Если категория Картинки, то отображаем картинку
const bytes = new Uint8Array(buffer);
const decoder = new TextDecoder("utf8");
var image = new Image();
image.src = "data:image/png;base64," + encode(bytes); // Устанавливаем ссылку на источник
document.body.appendChild(image); // Добавляем в DOM
}
}
class TextStrategy {
async doStrategy(savedObject) {
console.log(savedObject);
document.getElementById("saved-object").innerText = savedObject;
}
}
/**
* Функция, вызывающаяся по клику на категорию
* Получает данные и отображает их в виде текста
*/
async function onCategoryClick(event) {
const categoryId = event.target.dataset.id; // Получаем id
const categoryType = event.target.innerText; // Получаем категорию
const response = await api.getData(categoryId);
const strategyManager = new StrategyManager();
if (categoryType == "Картинки") {
const buffer = await response.arrayBuffer();
const imgStrategy = new ImgStrategy(buffer);
strategyManager.strategy = imgStrategy;
strategyManager.doStrategy();
} else {
// В остальных случаях выводим текст
const savedObject = await response.text();
console.log(savedObject);
const textStrategy = new TextStrategy(savedObject);
strategyManager.strategy = textStrategy;
strategyManager.doStrategy();
}
await updateCategories();
}
document.getElementById("write-form").onsubmit = sendForm;
updateCategories();
function encode(input) {
// Расшифровщик
var keyStr =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input[i++];
chr2 = i < input.length ? input[i++] : Number.NaN; // Not sure if the index
chr3 = i < input.length ? input[i++] : Number.NaN; // checks are needed here
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output +=
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
}
return output;
}
</script>
</html>