messages.go (2441B)
1 // Copyright © 2018 MTRNord <info@nordgedanken.de> 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package sqlite 16 17 import ( 18 "encoding/json" 19 "github.com/Nordgedanken/Morpheusv2/pkg/matrix" 20 "github.com/Nordgedanken/Morpheusv2/pkg/matrix/messages" 21 "github.com/matrix-org/gomatrix" 22 "time" 23 ) 24 25 // SaveMessage saves message Events to the DB 26 func (s *SQLite) SaveMessage(message matrix.Message) error { 27 if s.db == nil { 28 s.db = s.Open() 29 } 30 31 tx, err := s.db.Begin() 32 if err != nil { 33 return err 34 } 35 36 stmt, err := tx.Prepare("INSERT INTO messages (id, author_id, message, timestamp, pure_event) VALUES (?, ?, ?, ?, ?)") 37 if err != nil { 38 return err 39 } 40 defer stmt.Close() 41 42 id := message.GetEventID() 43 authorID := message.GetAuthorMXID() 44 messageS := message.GetMessage() 45 timestampR := message.GetTimestamp() 46 timestamp := timestampR.Format("2006-01-02 15:04:05") 47 pureEvent := message.GetEvent() 48 _, err = stmt.Exec(id, authorID, messageS, timestamp, pureEvent) 49 if err != nil { 50 return err 51 } 52 53 return tx.Commit() 54 } 55 56 // GetMessage returns the Message where the id matches the eventID 57 func (s *SQLite) GetMessage(eventID string) (messageR matrix.Message, err error) { 58 if s.db == nil { 59 s.db = s.Open() 60 } 61 62 stmt, err := s.db.Prepare(`SELECT author_id, message, timestamp, pure_event FROM messages WHERE id=$1`) 63 if err != nil { 64 return 65 } 66 defer stmt.Close() 67 68 row := stmt.QueryRow(eventID) 69 70 var authorID string 71 var messageS string 72 var timestamp time.Time 73 var pureEvent string 74 err = row.Scan(&authorID, &messageS, ×tamp, &pureEvent) 75 if err != nil { 76 return 77 } 78 79 messageI := &messages.Message{} 80 messageI.SetEventID(eventID) 81 messageI.SetAuthorMXID(authorID) 82 messageI.SetMessage(messageS) 83 messageI.SetTimestamp(×tamp) 84 var gomatrixEvent gomatrix.Event 85 err = json.Unmarshal([]byte(pureEvent), &gomatrixEvent) 86 if err != nil { 87 return 88 } 89 messageI.SetEvent(&gomatrixEvent) 90 91 messageR = messageI 92 return 93 }