mautrix-whatsapp/database/puppet.go

100 lines
2.6 KiB
Go
Raw Normal View History

// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package database
import (
2018-08-26 21:53:13 +02:00
"database/sql"
2019-01-11 20:17:31 +01:00
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix-whatsapp/types"
)
type PuppetQuery struct {
db *Database
2018-08-16 18:20:07 +02:00
log log.Logger
}
func (pq *PuppetQuery) New() *Puppet {
return &Puppet{
db: pq.db,
log: pq.log,
}
}
func (pq *PuppetQuery) GetAll() (puppets []*Puppet) {
rows, err := pq.db.Query("SELECT * FROM puppet")
if err != nil || rows == nil {
return nil
}
defer rows.Close()
for rows.Next() {
puppets = append(puppets, pq.New().Scan(rows))
}
return
}
func (pq *PuppetQuery) Get(jid types.WhatsAppID) *Puppet {
2019-03-06 16:33:42 +01:00
row := pq.db.QueryRow("SELECT * FROM puppet WHERE jid=$1", jid)
if row == nil {
return nil
}
return pq.New().Scan(row)
}
type Puppet struct {
db *Database
2018-08-16 18:20:07 +02:00
log log.Logger
JID types.WhatsAppID
Avatar string
Displayname string
NameQuality int8
}
func (puppet *Puppet) Scan(row Scannable) *Puppet {
var displayname, avatar sql.NullString
2018-09-01 23:44:10 +02:00
var quality sql.NullInt64
err := row.Scan(&puppet.JID, &avatar, &displayname, &quality)
if err != nil {
if err != sql.ErrNoRows {
puppet.log.Errorln("Database scan failed:", err)
}
return nil
}
puppet.Displayname = displayname.String
puppet.Avatar = avatar.String
2018-09-01 23:44:10 +02:00
puppet.NameQuality = int8(quality.Int64)
return puppet
}
2019-01-21 22:55:16 +01:00
func (puppet *Puppet) Insert() {
2019-03-06 16:33:42 +01:00
_, err := puppet.db.Exec("INSERT INTO puppet VALUES ($1, $2, $3, $4)",
puppet.JID, puppet.Avatar, puppet.Displayname, puppet.NameQuality)
if err != nil {
puppet.log.Warnfln("Failed to insert %s: %v", puppet.JID, err)
}
}
2019-01-21 22:55:16 +01:00
func (puppet *Puppet) Update() {
2019-03-06 16:33:42 +01:00
_, err := puppet.db.Exec("UPDATE puppet SET displayname=$1, name_quality=$2, avatar=$3 WHERE jid=$4",
puppet.Displayname, puppet.NameQuality, puppet.Avatar, puppet.JID)
if err != nil {
puppet.log.Warnfln("Failed to update %s->%s: %v", puppet.JID, err)
}
}