Compare commits

..

1 Commits

Author SHA1 Message Date
15770f58c1 changes 2025-01-20 21:10:18 -06:00
5 changed files with 64 additions and 79 deletions

View File

@ -1,7 +1,8 @@
{
"server": {
"ipAddress": "192.168.1.222",
"port": 8080
"port": 8080,
"messageMaxAge": 259200
},
"paths": {
"databasePath": "/home/radon/Documents/chattest.db",
@ -9,9 +10,5 @@
"indexCssPath": "./content/root.css",
"indexHtmlPath": "./content/root.html",
"messagesHtmlPath": "./content/messages.html"
},
"options": {
"messageMaxAge": 259200,
"nameMaxLength": 32
}
}

View File

@ -255,14 +255,14 @@ body {
gap: 10px;
}
.video-embed {
.youtube-embed {
position: inline;
padding-top: 10px;
width: 100%;
max-width: 560px; /* Standard YouTube width */
}
.video-embed iframe {
.youtube-embed iframe {
border-radius: 4px;
}

View File

@ -39,7 +39,9 @@ async function deleteMessage(messageId) {
});
if (response.ok) {
updateMessagesInPlace();
// Refresh messages
console.log("Message deleted successfully");
location.reload();
} else {
console.error("Failed to delete message");
}
@ -49,22 +51,6 @@ async function deleteMessage(messageId) {
}
}
async function updateMessagesInPlace() {
const currenteScrollLocation = getScrollLocation();
await loadMessages(true);
setScrollLocation(currenteScrollLocation);
}
function getScrollLocation() {
const messagesDiv = document.getElementById("messages");
return messagesDiv.scrollTop;
}
function setScrollLocation(height) {
const messagesDiv = document.getElementById("messages");
messagesDiv.scrollTop = height;
}
document.addEventListener("click", function (event) {
const settingsPanel = document.getElementById("settings-panel");
const settingsButton = document.querySelector(".settings-button");
@ -131,7 +117,7 @@ async function loadUsers() {
}
let lastMessageCount = 0;
async function loadMessages(forceUpdate = false) {
async function loadMessages() {
try {
let messagesDiv = document.getElementById("messages");
const response = await fetch("/messages");
@ -166,10 +152,10 @@ async function loadMessages(forceUpdate = false) {
const newMessageCount = messages.length;
const update = newMessageCount != lastMessageCount ||
lastMessageCount === 0 || forceUpdate;
if (update) {
if (
newMessageCount > lastMessageCount ||
lastMessageCount === 0
) {
messagesDiv.innerHTML = "";
Array.from(messages).forEach((msg) => {
const messageDiv = document.createElement(
@ -186,16 +172,49 @@ async function loadMessages(forceUpdate = false) {
"<br>",
);
const linkedContent = content.replace(
/(?![^<]*>)(https?:\/\/[^\s<]+)/g,
function (url) {
console.log(
"Processing URL:",
url,
); // Debug log
const videoId = getYouTubeID(
url,
);
if (videoId) {
return `<div class="youtube-embed"><iframe
width="100%"
height="315"
src="https://www.youtube.com/embed/${videoId}"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe></div>`;
} else if (isImageUrl(url)) {
console.log(
"Attempting to embed image:",
url,
);
return `<div class="image-embed"><img
src="${url}"
alt="Embedded image"
loading="lazy"
onerror="console.log('Image failed to load:', this.src); this.style.display='none'"
onload="console.log('Image loaded successfully:', this.src)"></div>`;
}
return `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`;
},
);
let deleteHtml = "";
const usernameDiv = document.createElement(
"div",
);
usernameDiv.innerHTML = username;
compareUsername = usernameDiv.textContent;
let deleteHtml = "";
const embeddedContent = contentEmbedding(
content,
);
if (
compareUsername ===
@ -210,7 +229,7 @@ async function loadMessages(forceUpdate = false) {
<div class="message-header">
<div class="username">${username} ${timestamp} ${deleteHtml}</div>
</div>
<div class="content">${embeddedContent}</div>`;
<div class="content">${linkedContent}</div>`;
messagesDiv.appendChild(messageDiv);
});
@ -222,36 +241,6 @@ async function loadMessages(forceUpdate = false) {
}
}
function contentEmbedding(content) {
return content.replace(
/(?![^<]*>)(https?:\/\/[^\s<]+)/g,
function (url) {
const videoId = getYouTubeID(
url,
);
if (videoId) {
return `<div class="video-embed"><iframe
width="100%"
height="315"
src="https://www.youtube.com/embed/${videoId}"
frameborder="0"
onerror="console.log('Video failed to load:', this.src); this.style.display='none'"
onload="console.log('Video loaded successfully:', this.src)"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe></div>`;
} else if (isImageUrl(url)) {
return `<div class="image-embed"><img
src="${url}"
alt="Embedded image"
loading="lazy"
onerror="console.log('Image failed to load:', this.src); this.style.display='none'"
onload="console.log('Image loaded successfully:', this.src)"></div>`;
}
return `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`;
},
);
}
function isImageUrl(url) {
return url.match(/\.(jpeg|jpg|gif|png|webp|bmp)($|\?)/i) != null;
}
@ -338,8 +327,8 @@ async function setUsername() {
setTimeout(() => {
document.getElementById("settings-panel").style
.display = "none";
}, 750);
updateMessagesInPlace();
}, 500);
location.reload();
} else {
showUsernameStatus(
data.error || "Failed to set username",
@ -374,7 +363,7 @@ async function sendMessage() {
if (response.ok) {
messageInput.value = "";
messageInput.style.height = "auto";
loadMessages(true);
loadMessages();
} else {
showStatus(
data.error || "Failed to send message",
@ -481,7 +470,7 @@ async function initialize() {
setInterval(loadMessages, 1000);
setInterval(loadUsers, 1000);
setInterval(pingCheck, 3000);
await loadMessages(true);
await loadMessages();
scrollToBottom();
}

17
main.go
View File

@ -438,8 +438,8 @@ func (s *Server) handleUsername(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
if len(req.Username) > s.Config.Options.NameMaxLength {
http.Error(w, fmt.Sprintf(`{"error": "Username too long (%v out of %v characters maximum)"}`, len(req.Username), s.Config.Options.NameMaxLength), http.StatusRequestEntityTooLarge)
if len(req.Username) > 64 {
http.Error(w, fmt.Sprintf(`{"error": "Username too long (must be less than 64 characters)"}`), http.StatusRequestEntityTooLarge)
s.mu.Unlock()
return
}
@ -451,8 +451,8 @@ func (s *Server) handleUsername(w http.ResponseWriter, r *http.Request) {
}
if s.Database.UserNameExists(req.Username) {
http.Error(w, fmt.Sprintf(`{"error": "Username already exists"}`), http.StatusConflict)
s.mu.Unlock()
http.Error(w, fmt.Sprintf(`{"error": "Username already exists"}`), http.StatusConflict)
return
}
@ -659,7 +659,7 @@ func (s *Server) handleCss(w http.ResponseWriter, r *http.Request) {
func (s *Server) Run() {
s.Database.DbCreateTableMessages()
s.Database.DbCreateTableUsers()
s.Database.DeleteOldMessages(s.Config.Options.MessageMaxAge)
s.Database.DeleteOldMessages(s.Config.Server.MessageMaxAge)
handler := http.NewServeMux()
handler.HandleFunc("/ping", s.handlePing)
handler.HandleFunc("/username", s.handleUsername)
@ -699,8 +699,9 @@ func main() {
type Config struct {
Server struct {
IpAddress string `json:"ipAddress"`
Port int `json:"port"`
IpAddress string `json:"ipAddress"`
Port int `json:"port"`
MessageMaxAge int `json:"messageMaxAge"`
} `json:"server"`
Paths struct {
DatabasePath string `json:"databasePath"`
@ -709,10 +710,6 @@ type Config struct {
IndexHtmlPath string `json:"indexHtmlPath"`
MessagesHtmlPath string `json:"messagesHtmlPath"`
} `json:"paths"`
Options struct {
MessageMaxAge int `json:"messageMaxAge"`
NameMaxLength int `json:"nameMaxLength"`
} `json:"options"`
}
func LoadConfig(filepath string) Config {

View File

@ -2,6 +2,8 @@
## Frontend
### High Priority
- Nothing yet
- Fix scroll to bottom on initial load?
- Add delete button tooltip
### Mid Priority
- Other embeds (Twitter posts, spotify tracks, soundcloud, github repos, instagram posts, other video platforms)
### Low Priority