meowlib/client/storage.go

83 lines
2.1 KiB
Go

package client
import (
"database/sql"
"os"
"path/filepath"
"forge.redroom.link/yves/meowlib"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
)
func StoreMessage(peer *Peer, usermessage *meowlib.UserMessage, password string) error {
var dbid string
// If no db/no ID create DB + Tablz
if len(peer.DbIds) == 0 {
dbid = uuid.NewString()
file, err := os.Create(filepath.Join(GetConfig().StoragePath, dbid))
if err != nil {
return err
}
file.Close()
peer.DbIds = append(peer.DbIds, dbid)
sqliteDatabase, _ := sql.Open("sqlite3", filepath.Join(GetConfig().StoragePath, dbid)) // Open the created SQLite File
err = createTable(sqliteDatabase)
if err != nil {
return err
}
sqliteDatabase.Close()
GetConfig().me.Save()
} else {
dbid = peer.DbIds[len(peer.DbIds)-1]
}
// Open Db
db, _ := sql.Open("sqlite3", filepath.Join(GetConfig().StoragePath, dbid)) // Open the created SQLite File
defer db.Close()
// TODO Detach Files
if len(usermessage.Files) > 0 {
for _, f := range usermessage.Files {
hiddenFilename := uuid.NewString()
// TODO cypher file
encData, err := meowlib.SymEncrypt(password, f.Data)
if err != nil {
return err
}
os.WriteFile(hiddenFilename, encData, 0600)
// replace f.Data by uuid filename
f.Data = []byte(hiddenFilename)
}
}
// TODO Encrypt message
// Inser message
insertMessageSQL := `INSERT INTO message(m) VALUES (?)`
statement, err := db.Prepare(insertMessageSQL) // Prepare statement.
if err != nil {
return err
}
_, err = statement.Exec(usermessage)
if err != nil {
return err
}
return nil
}
// Get last messages from a peer
func GetLastMessages(peer *Peer, lastIdx int, count int, gotUuid string) {
// TODO Try to get count from last DB
// TODO Get missing from previous DB
}
func createTable(db *sql.DB) error {
createMessageTableSQL := `CREATE TABLE message (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"m" BLOB,
);` // SQL Statement for Create Table
statement, err := db.Prepare(createMessageTableSQL) // Prepare SQL Statement
if err != nil {
return err
}
statement.Exec() // Execute SQL Statements
return nil
}