package ctfc import ( "bytes" "os" "strings" "gitlab.com/Syndamia/ctfc/go-src/folderPaths" "gitlab.com/Syndamia/ctfc/go-src/utils" ) type ChatProp int const ( chatNameProp ChatProp = iota + 1 chatDescriptionProp ) type Chat struct { Name string Description string Owner User Messages []string } func (ch Chat) addMessage(value string, creatorUsername string) { value = creatorUsername + " : " + value ch.Messages = append(ch.Messages, value) utils.AppendToFile(folderPaths.FileAtChatsFolder(ch.Name), value+"\n") } func (ch Chat) updateProp(currentPassword string, newValue string, chatProp ChatProp) bool { if !loggedInUser.ValidatePassword(currentPassword) { return false } oldName, oldDesc := ch.Name, ch.Description chatFile := utils.GetFileContents(folderPaths.FileAtChatsFolder(ch.Name)) switch chatProp { case chatNameProp: chatFile[0] = newValue ch.Name = newValue case chatDescriptionProp: chatFile[1] = newValue ch.Description = newValue default: return false } os.WriteFile( folderPaths.FileAtChatsFolder(oldName), []byte(strings.Join(chatFile, "\n")), 0644) if oldName != ch.Name { os.Rename(folderPaths.FileAtChatsFolder(oldName), folderPaths.FileAtChatsFolder(ch.Name)) } allChatsFile, _ := os.ReadFile(folderPaths.AllChatsFilePath()) allChatsUpdatedFile := strings.Replace(string(allChatsFile), oldName+" : "+oldDesc, ch.Name+" : "+ch.Description, 1) os.WriteFile( folderPaths.AllChatsFilePath(), []byte(allChatsUpdatedFile), 0644, ) return true } func (ch Chat) UpdateName(password string, newName string) bool { return ch.updateProp(password, newName, chatNameProp) } func (ch Chat) UpdateDescription(password string, newDesc string) bool { return ch.updateProp(password, newDesc, chatDescriptionProp) } func createChat(data ...string) { chatFile, _ := os.Create(folderPaths.FileAtChatsFolder(data[0])) chatFile.WriteString(data[0] + "\n" + data[1] + "\n" + data[2] + "\n") chatFile.Close() utils.AppendToFile(folderPaths.AllChatsFilePath(), data[0]+" : "+data[1]+"\n") } func getChat(name string) Chat { f, _ := os.ReadFile(folderPaths.FileAtChatsFolder(name)) values := bytes.Split(f, []byte("\n")) return Chat{string(values[0]), string(values[1]), getUser(string(values[2])), utils.TwoDByteArrayToStringArray(values[3 : len(values)-1])} } func getAllChats() []string { f, _ := os.ReadFile(folderPaths.AllChatsFilePath()) values := bytes.Split(f, []byte("\n")) chats := utils.TwoDByteArrayToStringArray(values) return chats[:len(chats)-1] } func getOwnChats() (ownChats []string) { for _, v := range getAllChats() { f, _ := os.ReadFile(folderPaths.FileAtChatsFolder(strings.Split(v, " : ")[0])) if string(bytes.Split(f, []byte("\n"))[2]) == loggedInUser.Username { ownChats = append(ownChats, v) } } return }