Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {db} from './firebase.js';
- import { doc, setDoc } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js";
- import { getAuth, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js';
- import {app} from '../../js/firebase.js';
- let current_nickname = '';
- console.log(app);
- const auth = getAuth(app);
- onAuthStateChanged(auth, (user) => {
- if (user) {
- // User is signed in, see docs for a list of available properties
- // https://firebase.google.com/docs/reference/js/firebase.User
- const uid = user.uid;
- console.log('Текущий пользователь:', user);
- current_nickname = user.displayName;
- //document.getElementById("email").innerText += ' ' + user.displayName;
- // ...
- } else {
- // User is signed out
- // ...
- console.log("User not found")
- window.location.href = "/login";
- }
- });
- const blogTitleField = document.querySelector('.title');
- const articleField = document.querySelector('.article');
- // banner
- const bannerImage = document.querySelector('#banner-upload');
- const banner = document.querySelector('.banner');
- let bannerPath;
- const publishBtn = document.querySelector('.publish-btn');
- const uploadInput = document.querySelector('#image-upload');
- bannerImage.addEventListener('change', () => {
- uploadImage(bannerImage, "banner");
- })
- uploadInput.addEventListener('change', () => {
- uploadImage(uploadInput, "image");
- })
- const uploadImage = (uploadFile, uploadType) => {
- const [file] = uploadFile.files;
- if (file && file.type.includes("image")){
- const formdata = new FormData();
- formdata.append('image', file);
- console.log("Картинка выбрана");
- // Список пар ключ/значение
- for(let [name, value] of formdata) {
- console.log(`${name}`, value); // key1=value1, потом key2=value2
- }
- const csrfToken = getCookie('XSRF-TOKEN');
- console.log(csrfToken);
- const headers = new Headers({
- 'Content-Type': 'x-www-form-urlencoded',
- 'X-CSRF-Token': csrfToken
- });
- fetch('/upload', {
- method: 'post',
- headers: headers,
- credentials: 'include',
- body: formdata
- }).then(res => res.json())
- .then(data => {
- if (uploadType == 'image')
- {
- addImage(data, file.name);
- }
- else if (uploadType == 'banner')
- {
- bannerPath = `${location.origin}/${data}`;
- banner.style.backgroundImage = `url("${bannerPath}")`
- }
- else
- {
- console.error('Данный тип файла не поддерживается');
- }
- })
- } else
- {
- alert('Upload image only');
- }
- }
- // добавление ссылки на файл в записи
- const addImage = (imagepath, alt) => {
- let curPos = articleField.selectionStart;
- let textToInsert = `\r\r`;
- articleField.value = articleField.value.slice(0, curPos) + textToInsert + articleField.value.slice(curPos);
- }
- let mouths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- // Публикация записи
- publishBtn.addEventListener('click', () => {
- if(articleField.value.length && blogTitleField.value.length){ // если ввели название и содержание
- // генерация id
- let letters = 'abcdefghijklmnopqrstuvwxyz';
- let blogTitle = blogTitleField.value.split(" ").join("-");
- let id = '';
- for(let i = 0; i < 4; i++)
- {
- id += letters[Math.floor(Math.random() * letters.length)];
- }
- // Установка названия документа
- let docName = `${blogTitle}-${id}`;
- let date = new Date(); // для даты публикации
- console.log(db);
- // для доступа firestore переменной db
- /*db.collection("blogs").doc(docName).set({
- title: blogTitleField.value,
- article: articleField.value,
- bannerImage: bannerPath,
- publishedAt: `${date.getDate()} ${mouths[date.getMonth()]} ${date.getFullYear()}`
- })*/
- setDoc(doc(db, 'blogs', docName), {
- title: blogTitleField.value,
- article: articleField.value,
- bannerImage: bannerPath,
- publishedAt: `${date.getDate()} ${mouths[date.getMonth()]} ${date.getFullYear()}`,
- author: current_nickname
- })
- .then(() => {
- console.log('date entered');
- location.href = `/${docName}`;
- })
- .catch((err) => {
- console.error(err);
- })
- }
- })
- function getCookie(name) {
- if (!document.cookie) {
- return null;
- }
- const xsrfCookies = document.cookie.split(';')
- .map(c => c.trim())
- .filter(c => c.startsWith(name + '='));
- if (xsrfCookies.length === 0) {
- return null;
- }
- return decodeURIComponent(xsrfCookies[0].split('=')[1]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement