Fixed bug with null messages

This commit is contained in:
Balazs Toldi 2019-11-26 12:52:03 +01:00
parent b71c4c7e4a
commit fae65b77d7
7 changed files with 108 additions and 100 deletions

View file

@ -0,0 +1,5 @@
.msg-box{
flex: 1 1 auto;
overflow-y: auto;
height: 32em;
}

View file

@ -1,4 +1,4 @@
String.prototype.replaceAll = function(search, replacement) {
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
@ -6,74 +6,70 @@ var submit = document.getElementById('s');
joypixels.ascii = true;
function encodeQueryData(data) {
const ret = [];
for (let d in data)
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
return ret.join('&');
const ret = [];
for (let d in data)
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
return ret.join('&');
}
function submitForm() {
var formElement = document.forms.namedItem("sendmsg")
var formElement = document.forms.namedItem("sendmsg")
var formData = new FormData(formElement);
if(formData.get("message") != "%0D%0A" && formData.get("message") != null ){
var data = {'id': formData.get("id"), 'message' : formData.get("message") }
var xhr = new XMLHttpRequest();
xhr.open('POST', window.location.href, true);
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(encodeQueryData(data));
}
$('#message').val('');
}
if (formData.get("message") != "%0D%0A" && formData.get("message") != null) {
var data = {'id': formData.get("id"), 'message': formData.get("message")}
var xhr = new XMLHttpRequest();
xhr.open('POST', window.location.href, true);
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(encodeQueryData(data));
}
$('#message').val('');
}
var fetch_messages = new XMLHttpRequest();
var url = "/peers/" +window.location.pathname+ ".txt";
var last_text ="";
setInterval(function(){
fetch_messages.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) loadMessages(this.responseText.split("\n"));
last_text = this.responseText;
var url = "/peers/" + window.location.pathname + ".txt";
var last_text = "";
setInterval(function () {
fetch_messages.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
loadMessages(this.responseText.split("\n"));
}
//$(".msg-box").animate({scrollTop: document.getElementById("msgs").offsetHeight }, "slow");
last_text = this.responseText;
};
fetch_messages.open("GET", url, true);
fetch_messages.send();
},1000);
function scrollSmoothToBottom (id) {
var div = document.getElementById(id);
$('#' + id).animate({
scrollTop: div.scrollHeight - div.clientHeight
}, 500);
}
}, 1000);
$(function () {
$("#message").keypress(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$("#s").trigger('click');
$('#message').val('');
$('#message').val('');
return true;
}
});
});
function loadMessages(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
if(arr[i] == '') continue;
if(arr[i].indexOf("Me:") == -1){
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2">'+window.location.pathname.replace("/","")+'<br></h6><p class="card-text">' + joypixels.toImage(decodeURIComponent(arr[i].replaceAll('+',' '))) + '</p></div></div>';
}else{
var msg = arr[i].replace("Me: ","");
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2" style="text-align:right;">You<br></h6><p class="card-text" style="text-align:right;">' + joypixels.toImage((decodeURIComponent(msg.replaceAll('+',' ')))) + '</p></div></div>';
}
for (i = 0; i < arr.length; i++) {
if (arr[i] == '') continue;
if (arr[i].indexOf("Me:") == -1) {
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2">' + window.location.pathname.replace("/", "") + '<br></h6><p class="card-text">' + joypixels.toImage(decodeURIComponent(arr[i].replaceAll('+', ' '))) + '</p></div></div>';
} else {
var msg = arr[i].replace("Me: ", "");
out += '<div class="card"><div class="card-body"><h6 class="text-muted card-subtitle mb-2" style="text-align:right;">You<br></h6><p class="card-text" style="text-align:right;">' + joypixels.toImage((decodeURIComponent(msg.replaceAll('+', ' ')))) + '</p></div></div>';
}
}
out += "<div id='endl'></div>";
var elem = document.getElementById("msgs");
elem.innerHTML = out;
document.getElementById('end').scrollIntoView();
elem.innerHTML = out;
document.getElementById('endl').scrollIntoView();
}

View file

@ -9,6 +9,7 @@
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/emoji-toolkit@5.0.5/extras/css/joypixels.min.css"/>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/styles.min.css">
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>

View file

@ -12,20 +12,20 @@ void map_init(Map *m) {
}
bool map_isFound(Map map, char *key) {
char* res = map_getValue(map,key);
char *res = map_getValue(map, key);
return (res == NULL) ? false : true;
}
char *map_getValue(Map m, char *key) {
int min = 0;
int max = m.length-1;
int kp = (min+max)/2;
while(min <= max && strcmp(m.pairs[kp].key,key) != 0){
if(strcmp(m.pairs[kp].key,key) < 0)
min = kp+1;
int max = m.length - 1;
int kp = (min + max) / 2;
while (min <= max && strcmp(m.pairs[kp].key, key) != 0) {
if (strcmp(m.pairs[kp].key, key) < 0)
min = kp + 1;
else
max = kp-1;
kp = (min+max)/2;
max = kp - 1;
kp = (min + max) / 2;
}
return min <= max ? m.pairs[kp].value : NULL;
}
@ -41,10 +41,10 @@ void map_addPair(Map *m, Pair p) {
assert(m->length == m->size);
size_t new_size = (m->size + 2) * 2;
m->pairs = realloc(m->pairs, new_size * sizeof(Pair));
if (m->pairs == NULL) {
printf("OUT OF MEMORY!");
abort();
}
if (m->pairs == NULL) {
printf("OUT OF MEMORY!");
abort();
}
m->size = new_size;
}
m->pairs[m->length++] = p;
@ -58,7 +58,7 @@ Pair map_make_pair(char *key, char *value) {
return result;
}
void map_sort(Map* m) {
void map_sort(Map *m) {
for (int i = m->length - 1; i > 0; --i) {
for (int j = 0; j < i; ++j) {

11
main.c
View file

@ -13,24 +13,22 @@
SOCKET listening;
SOCKET web_sock;
Map config;
PeerList peerList1;
void closeSocks(void){
logger_log("Closing socket...");
closesocket(listening);
closesocket(web_sock);
if(peerList1.size >0)free(peerList1.array);
if(config.size > 0) free(config.pairs);
}
void signalClose(int n){
closeSocks();
}
int main(void) {
PeerList peerList1;
atexit(closeSocks);
signal(SIGTERM,signalClose);
config = config_load();
Map config = config_load();
Node_data mynode = construct_Mynodedata(config);
logger_log("Initialising core...");
@ -83,6 +81,7 @@ int main(void) {
serverThread(listening,&master,webIo,&peerList1,mynode);
free(peerList1.array);
free(config.pairs);
return 0;
}

View file

@ -4,12 +4,13 @@
//
#include "server.h"
void getSeed(char*output){
void getSeed(char *output) {
FILE *seed_file;
seed_file = fopen("seed.txt", "r");
if (seed_file == NULL) {
logger_log("Seed not found! Generating a new one...");
char* string = generateSeed(16);
char *string = generateSeed(16);
strcpy(output, string);
free(string);
seed_file = fopen("seed.txt", "w");
@ -20,6 +21,7 @@ void getSeed(char*output){
}
fclose(seed_file);
}
Node_data construct_Mynodedata(Config cfg) {
Node_data result;
getSeed(result.id);
@ -37,12 +39,12 @@ Node_data construct_Mynodedata(Config cfg) {
return result;
}
void serverThread(SOCKET listening, fd_set *master, WebIO webIo, PeerList* list,Node_data mynode) {
void serverThread(SOCKET listening, fd_set *master, WebIO webIo, PeerList *list, Node_data mynode) {
bool run = true;
while (run) {
fd_set copy = *master;
SOCKET last = (list->length > 0) ? list->array[list->length - 1].socket : webIo.socket;
int count = select(((int)last)+1, &copy, NULL, NULL, NULL);
int count = select(((int) last) + 1, &copy, NULL, NULL, NULL);
if (FD_ISSET(listening, &copy)) {
if (peer_HandleConnection(listening, list, mynode, master) != 0)
@ -54,8 +56,8 @@ void serverThread(SOCKET listening, fd_set *master, WebIO webIo, PeerList* list,
}
} else {
for (int i = 0; i < (int) list->length; i++) {
SOCKET sock = list->array[i].socket;
if(!FD_ISSET(sock,&copy))
SOCKET sock = list->array[i].socket;
if (!FD_ISSET(sock, &copy))
continue;
char buf[DEFAULT_BUFLEN];
memset(buf, 0, DEFAULT_BUFLEN);
@ -75,22 +77,25 @@ void serverThread(SOCKET listening, fd_set *master, WebIO webIo, PeerList* list,
if (strlen(buf) == 0)
continue;
Map m = getPacketData(buf);
char file[64];
int k = peer_getPeer(*list, sock);
sprintf(file, "%speers/", webIo.folder);
if (map_getValue(m, "message") != NULL) {
printf("%s\n", buf);
char file[64];
int k = peer_getPeer(*list, sock);
sprintf(file, "%speers/", webIo.folder);
#if defined(_WIN32)
CreateDirectoryA(file,NULL);
CreateDirectoryA(file, NULL);
#else
mkdir(file, 0777);
mkdir(file, 0777);
#endif
sprintf(file, "%s%s.txt",file, list->array[k].peerData.id);
logger_log("Message received from %s", list->array[k].peerData.id);
FILE *fp;
fp = fopen(file, "a");
fprintf(fp, "%s\n", map_getValue(m, "message"));
fclose(fp);
free(m.pairs);
sprintf(file, "%s%s.txt", file, list->array[k].peerData.id);
logger_log("Message received from %s", list->array[k].peerData.id);
FILE *fp;
fp = fopen(file, "a");
fprintf(fp, "%s\n", map_getValue(m, "message"));
fclose(fp);
free(m.pairs);
}
}
}
}

View file

@ -45,9 +45,9 @@ int webio_handleRequest(WebIO wio) {
closesocket(client);
return -1;
}
char method[5],v_major[2],v_minor[3],file[50];
sscanf(buf, "%s %s %*[^/]/%[^.].%s",method,file,v_major,v_minor);
if(strcmp(v_major,"1") != 0){
char method[5], v_major[2], v_minor[3], file[50];
sscanf(buf, "%s %s %*[^/]/%[^.].%s", method, file, v_major, v_minor);
if (strcmp(v_major, "1") != 0) {
char *response = "HTTP/1.0 505 HTTP Version Not Supportedd"
"Content-Encoding: gzip\r\n"
"Content-Language: en\r\n"
@ -74,7 +74,7 @@ int webio_handleRequest(WebIO wio) {
res = webio_handlePOSTrequest(client, wio, post);
free(post.pairs);
} else{
} else {
char *response = "HTTP/1.0 501 Not Implemented"
"Content-Encoding: gzip\r\n"
"Content-Language: en\r\n"
@ -122,7 +122,7 @@ char *webio_getMIMEtype(char *filename) {
char *webio_getFiletype(char *filename) {
char *ext = (char *) malloc(sizeof(char) * 10);
strcpy(ext,"");
strcpy(ext, "");
char *tmp = strtok(filename, ".");
while (tmp != NULL) {
strncpy(ext, tmp, 10);
@ -206,12 +206,14 @@ static int webio_handlePOSTrequest(SOCKET client, WebIO wio, Map post) {
shutdown(client, SD_BOTH);
if (map_isFound(post, "id") && map_isFound(post, "message") &&
strcmp(map_getValue(post, "message"), "%0D%0A") != 0) {
(strcmp(map_getValue(post, "message"), "%0D%0A") != 0 &&
strcmp(map_getValue(post, "message"), "(null)") != 0)) {
char file[64];
char folder[72];
sprintf(folder, "%s/peers/", wio.folder);
#if defined(_WIN32)
CreateDirectoryA(folder,NULL);
CreateDirectoryA(folder, NULL);
#else
mkdir(folder, 0777);
#endif
@ -314,14 +316,14 @@ static void webio_getIndex(WebIO wio, char *outputBuffer) {
d = opendir(path);
int cnt = 0;
if (d != NULL){
if (d != NULL) {
strcat(content, "<ul>\n");
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if(strcmp(de->d_name,".") == 0 || strcmp(de->d_name,"..") == 0) continue;
if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue;
char peer[33];
sscanf(de->d_name,"%[^.]",peer);
if(!peer_ID_isFound(*wio.list,peer)) {
sscanf(de->d_name, "%[^.]", peer);
if (!peer_ID_isFound(*wio.list, peer)) {
cnt++;
sprintf(content, "%s<li><a href=\"%s\">%s</a></li>", content, peer, peer);
}
@ -329,7 +331,7 @@ static void webio_getIndex(WebIO wio, char *outputBuffer) {
closedir(d);
strcat(content, "</ul>\n");
}
if(d == NULL || cnt ==0){
if (d == NULL || cnt == 0) {
sprintf(content, "%s<div class=\"alert alert-warning\" role=\"alert\">\n"
" No offline messages!\n"
"</div>\n", content);
@ -352,14 +354,14 @@ static void webio_getPeerPage(WebIO wio, char *id, char *outputBuffer) {
webio_getHeader(wio.folder, header);
strcpy(content, header);
bool online = peer_ID_isFound(*wio.list,id);
bool online = peer_ID_isFound(*wio.list, id);
char *img = (online) ? "<img width=\"30\" height=\"30\" src=\"assets\\img\\on.svg\">"
: "<img width=\"30\" height=\"30\" src=\"assets\\img\\off.svg\">";
char *disabled = (online) ? "" : "disabled";
char *nickname = (online) ? wio.list->array[peer_ID_getPeer(*wio.list,id)].peerData.nick:"";
char *nickname = (online) ? wio.list->array[peer_ID_getPeer(*wio.list, id)].peerData.nick : "";
sprintf(content, "%s\n"
"<h1>%s%s %s</h1>\n"
"<div id=\"msgs\" style=\"margin-bottom:5em\"></div>\n"
"<div id=\"msgs\" class=\"msg-box\" style=\"margin-bottom:5em;\"></div>\n"
"<div id=\"end\"></div>\n"
" <form name=\"sendmsg\" class=\"form-inline\" style=\"margin: 7px;padding: 7px;position: fixed;bottom: 0;width: 100%%;\">"
"<textarea name=\"message\" id=\"message\" class=\"form-control\" style=\"width: 90%%;display: block;\" %s></textarea>"
@ -368,7 +370,7 @@ static void webio_getPeerPage(WebIO wio, char *id, char *outputBuffer) {
"<script src=\"assets/js/chat.js\"></script>"
"</body>\n"
"\n"
"</html>", header, img,nickname, id, disabled, id);
"</html>", header, img, nickname, id, disabled, id);
strcpy(outputBuffer, content);
}