formatting

This commit is contained in:
Tomáš Mládek 2018-10-17 13:37:53 +02:00
parent 1688d04646
commit b19ed3cade
5 changed files with 58 additions and 60 deletions

24
api.php
View file

@ -4,20 +4,20 @@ $database = new SQLite3('outchat.db');
$action = $_GET['action']; $action = $_GET['action'];
if($action === 'getMessages'){ if ($action === 'getMessages') {
$timestamp = $database->escapeString(htmlspecialchars($_GET['timestamp'])); $timestamp = $database->escapeString(htmlspecialchars($_GET['timestamp']));
$timestamp = ($timestamp == 0) ? strtotime('-6 hours') : $timestamp; $timestamp = ($timestamp == 0) ? strtotime('-6 hours') : $timestamp;
$results = $database->query('SELECT * FROM messages WHERE timestamp > '.$timestamp); $results = $database->query('SELECT * FROM messages WHERE timestamp > ' . $timestamp);
$messageArray = []; $messageArray = [];
while($row = $results->fetchArray(SQLITE3_ASSOC)) { while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
$row['datetime'] = date('d/m H:i', $row['timestamp']); $row['datetime'] = date('d/m H:i', $row['timestamp']);
$image_search = preg_match('/(http|https):\/\/[^ ]+(\.gif|\.jpg|\.jpeg|\.png)/', $row['text'], $out); $image_search = preg_match('/(http|https):\/\/[^ ]+(\.gif|\.jpg|\.jpeg|\.png)/', $row['text'], $out);
if($image_search > 0){ if ($image_search > 0) {
$row['text_processed'] = str_replace($out[0], '<p><img src="'.$out[0].'" /></p>', $row['text']); $row['text_processed'] = str_replace($out[0], '<p><img src="' . $out[0] . '" /></p>', $row['text']);
} else { } else {
$row['text_processed'] = $row['text']; $row['text_processed'] = $row['text'];
} }
@ -27,17 +27,17 @@ if($action === 'getMessages'){
echo json_encode($messageArray); echo json_encode($messageArray);
} }
if($action === 'createMessage'){ if ($action === 'createMessage') {
$timestamp = time(); $timestamp = time();
$name = $database->escapeString(htmlspecialchars($_POST['name'])); $name = $database->escapeString(htmlspecialchars($_POST['name']));
$text = $database->escapeString(htmlspecialchars($_POST['text'])); $text = $database->escapeString(htmlspecialchars($_POST['text']));
/* /*
$payload = file_get_contents('php://input'); $payload = file_get_contents('php://input');
$data = json_decode($payload); $data = json_decode($payload);
var_dump($data); var_dump($data);
*/ */
$database->query('INSERT INTO messages (name, text, timestamp) VALUES ("'.$name.'", "'.$text.'", "'.$timestamp.'")'); $database->query('INSERT INTO messages (name, text, timestamp) VALUES ("' . $name . '", "' . $text . '", "' . $timestamp . '")');
} }
?> ?>

View file

@ -7,12 +7,12 @@ function htmlToElements(html) {
function hashCode(str) { // java String#hashCode function hashCode(str) { // java String#hashCode
var hash = 0; var hash = 0;
for (var i = 0; i < str.length; i++) { for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash); hash = str.charCodeAt(i) + ((hash << 5) - hash);
} }
return hash; return hash;
} }
function intToRGB(i){ function intToRGB(i) {
const c = (i & 0x00FFFFFF) const c = (i & 0x00FFFFFF)
.toString(16) .toString(16)
.toUpperCase(); .toUpperCase();
@ -26,7 +26,7 @@ function getCookie(name) {
if (parts.length == 2) return parts.pop().split(";").shift(); if (parts.length == 2) return parts.pop().split(";").shift();
} }
function nl2br(str, is_xhtml){ function nl2br(str, is_xhtml) {
if (typeof str === 'undefined' || str === null) { if (typeof str === 'undefined' || str === null) {
return ''; return '';
} }
@ -34,6 +34,6 @@ function nl2br(str, is_xhtml){
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
} }
function scrollWindowDown(){ function scrollWindowDown() {
window.scrollTo(0, document.body.scrollHeight) window.scrollTo(0, document.body.scrollHeight)
} }

View file

@ -4,15 +4,15 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>sermon</title> <title>sermon</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="main.css">
</head> </head>
<body> <body>
<?php <?php
if(!isset($_COOKIE['outchat_name'])){ if (!isset($_COOKIE['outchat_name'])) {
echo ' echo '
<div class="modal"> <div class="modal">
<form action="" method="post" class="modal__form"> <form action="" method="post" class="modal__form">
<input type="text" name="name" placeholder="name" minLength="3" maxLength="20" class="modal__form-input"> <input type="text" name="name" placeholder="name" minLength="3" maxLength="20" class="modal__form-input">
@ -20,7 +20,7 @@
</form> </form>
</div> </div>
'; ';
} }
?> ?>
<div class="chat"> <div class="chat">
@ -34,6 +34,6 @@
<script src="helpers.js"></script> <script src="helpers.js"></script>
<script src="main.js"></script> <script src="main.js"></script>
</body> </body>
</html> </html>

View file

@ -112,7 +112,7 @@ body {
} }
.modal__form-input { .modal__form-input {
padding: 0 90px 0 30px; padding: 0 90px 0 30px;
width: 100%; width: 100%;
height: 100%; height: 100%;
border: 0; border: 0;
@ -134,8 +134,6 @@ body {
background: none; background: none;
} }
@media (max-width: 640px) { @media (max-width: 640px) {
.chat { .chat {
padding: 10px 10px 50px 10px; padding: 10px 10px 50px 10px;

70
main.js
View file

@ -1,26 +1,26 @@
// modal form handle // modal form handle
if(document.querySelector('.modal__form-submit')){ if (document.querySelector('.modal__form-submit')) {
document.querySelector('.modal__form-submit').addEventListener('click', function(e){ document.querySelector('.modal__form-submit').addEventListener('click', function (e) {
e.preventDefault() e.preventDefault()
const value = document.querySelector('.modal__form-input').value const value = document.querySelector('.modal__form-input').value
if(value.length >= 3){ if (value.length >= 3) {
var date = new Date(Date.now()) var date = new Date(Date.now())
date = date.setTime(date.getTime() + (90*24*60*60*1000)) date = date.setTime(date.getTime() + (90 * 24 * 60 * 60 * 1000))
date = new Date(date) date = new Date(date)
const expires = '; expires=' + date.toUTCString() const expires = '; expires=' + date.toUTCString()
document.cookie = 'outchat_name=' + (value || '') + expires + '; path=/' document.cookie = 'outchat_name=' + (value || '') + expires + '; path=/'
window.location.href = '' window.location.href = ''
} }
}) })
} }
document.querySelector('.form__input-message').addEventListener('keydown', function(e){ document.querySelector('.form__input-message').addEventListener('keydown', function (e) {
if(e.ctrlKey && e.keyCode == 13){ if (e.ctrlKey && e.keyCode == 13) {
document.querySelector('.form__input-submit').click() document.querySelector('.form__input-submit').click()
} }
}) })
document.querySelector('.form__input-submit').addEventListener('click', function(e){ document.querySelector('.form__input-submit').addEventListener('click', function (e) {
e.preventDefault() e.preventDefault()
const name = getCookie('outchat_name') const name = getCookie('outchat_name')
@ -31,52 +31,52 @@ document.querySelector('.form__input-submit').addEventListener('click', function
formData.append(name, text) formData.append(name, text)
fetch('api.php?action=createMessage', { fetch('api.php?action=createMessage', {
method: 'post', method: 'post',
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded" "Content-Type": "application/x-www-form-urlencoded"
}, },
body: 'name='+name+'&text='+text body: 'name=' + name + '&text=' + text
}) })
.then(function(data){ .then(function (data) {
getMessages() getMessages()
}) })
.catch(function(error){ .catch(function (error) {
console.log(error) console.log(error)
}) })
}) })
function getMessages(){ function getMessages() {
const timestamp = (document.querySelector('.chat').lastElementChild) ? document.querySelector('.chat').lastElementChild.getAttribute('data-timestamp') : 0 const timestamp = (document.querySelector('.chat').lastElementChild) ? document.querySelector('.chat').lastElementChild.getAttribute('data-timestamp') : 0
fetch('api.php?action=getMessages&timestamp='+timestamp) fetch('api.php?action=getMessages&timestamp=' + timestamp)
.then(function(data){ .then(function (data) {
return data.json() return data.json()
}) })
.then(function(data){ .then(function (data) {
if(data.length > 0){ if (data.length > 0) {
if((window.scrollY + window.innerHeight) == document.body.scrollHeight){ if ((window.scrollY + window.innerHeight) == document.body.scrollHeight) {
setTimeout(function(){ setTimeout(function () {
scrollWindowDown() scrollWindowDown()
}, 100) }, 100)
} }
for(message of data){ for (message of data) {
createMessageNode(message.name, message.text_processed, message.timestamp, message.datetime) createMessageNode(message.name, message.text_processed, message.timestamp, message.datetime)
} }
} }
}) })
.catch(function(error){ .catch(function (error) {
console.log(error) console.log(error)
}) })
} }
function createMessageNode(name, text, timestamp, datetime){ function createMessageNode(name, text, timestamp, datetime) {
const elementMain = document.createElement('div', { class: 'message' }) const elementMain = document.createElement('div', {class: 'message'})
const elementText = document.createElement('div', { class: 'message__text'}) const elementText = document.createElement('div', {class: 'message__text'})
const elementInfo = document.createElement('div', { class: 'message__info'}) const elementInfo = document.createElement('div', {class: 'message__info'})
const elementName = document.createElement('div', { id: 'message__info-name'}) const elementName = document.createElement('div', {id: 'message__info-name'})
const elementDatetime = document.createElement('div', { id: 'message__info-datetime'}) const elementDatetime = document.createElement('div', {id: 'message__info-datetime'})
const contentName = document.createTextNode(name) const contentName = document.createTextNode(name)
const contentDatetime = document.createTextNode('['+datetime+']') const contentDatetime = document.createTextNode('[' + datetime + ']')
//const contentText = document.createTextNode(text) //const contentText = document.createTextNode(text)
// element creation // element creation
@ -87,7 +87,7 @@ function createMessageNode(name, text, timestamp, datetime){
elementName.classList.add('message__info-name') elementName.classList.add('message__info-name')
// "hash" name color // "hash" name color
elementName.style.color = "#"+intToRGB(hashCode(name)) elementName.style.color = "#" + intToRGB(hashCode(name))
// append everything to chat // append everything to chat
elementName.appendChild(contentName) elementName.appendChild(contentName)
@ -100,13 +100,13 @@ function createMessageNode(name, text, timestamp, datetime){
elementMain.appendChild(elementInfo) elementMain.appendChild(elementInfo)
elementMain.appendChild(elementText) elementMain.appendChild(elementText)
elementMain.setAttribute('data-timestamp', timestamp) elementMain.setAttribute('data-timestamp', timestamp)
document.querySelector('.chat').appendChild(elementMain) document.querySelector('.chat').appendChild(elementMain)
return true return true
} }
getMessages() getMessages()
setInterval(function(){ setInterval(function () {
getMessages() getMessages()
}, 2000) }, 2000)