pre-commit: add configuration and did some cleanup

Signed-off-by: Sumner Evans <sumner@beeper.com>
This commit is contained in:
Sumner Evans 2022-10-21 09:35:03 -05:00
parent 93b8a88726
commit 9bed215ffa
No known key found for this signature in database
GPG Key ID: 8904527AB50022FD
18 changed files with 73 additions and 77 deletions

20
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,20 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
hooks:
- id: trailing-whitespace
exclude_types: [markdown]
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/tekwizely/pre-commit-golang
rev: v1.0.0-beta.5
hooks:
- id: go-imports-repo
args:
- "-local"
- "github.com/beeper/hungryserv"
- "-w"
- id: go-vet-repo-mod
# - id: go-staticcheck-repo-mod

View File

@ -17,14 +17,10 @@
package main package main
import ( import (
// "errors"
"fmt" "fmt"
"math" "math"
"sort" "sort"
// "math"
"strconv" "strconv"
"strings" "strings"
@ -879,12 +875,11 @@ func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
const cmdPMHelp = `pm - To direct message someone already in a shared group start a direct chat with them in Matrix` const cmdPMHelp = `pm - To direct message someone already in a shared group start a direct chat with them in Matrix`
func (handler *CommandHandler) CommandPM(ce *CommandEvent) { func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
ce.Reply(fmt.Sprintf("**DEPRECATED COMMAND:** `%s`", cmdPMHelp)) // ce.Reply(fmt.Sprintf("**DEPRECATED COMMAND:** `%s`", cmdPMHelp))
return // if len(ce.Args) == 0 {
if len(ce.Args) == 0 { // ce.Reply(fmt.Sprintf("**DEPRECATED COMMAND:** `%s`", cmdPMHelp))
ce.Reply(fmt.Sprintf("**DEPRECATED COMMAND:** `%s`", cmdPMHelp)) // return
return // }
}
// force := ce.Args[0] == "--force" // force := ce.Args[0] == "--force"
// if force { // if force {

View File

@ -68,8 +68,8 @@ type Config struct {
} `yaml:"metrics"` } `yaml:"metrics"`
GroupMe struct { GroupMe struct {
OSName string `yaml:"os_name"` OSName string `yaml:"os_name"`
BrowserName string `yaml:"browser_name"` BrowserName string `yaml:"browser_name"`
} `yaml:"groupme"` } `yaml:"groupme"`
Bridge BridgeConfig `yaml:"bridge"` Bridge BridgeConfig `yaml:"bridge"`

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU Affero General Public License // 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/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
//go:build cgo && !nocrypto
// +build cgo,!nocrypto // +build cgo,!nocrypto
package main package main

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU Affero General Public License // 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/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
//go:build cgo && !nocrypto
// +build cgo,!nocrypto // +build cgo,!nocrypto
package database package database

View File

@ -92,8 +92,9 @@ package database
// } // }
func Migrate(old *Database, new *Database) { func Migrate(old *Database, new *Database) {
print("skipping migration because test") print("skipping migration because test")
} }
// err := migrateTable(old, new, "portal", "jid", "receiver", "mxid", "name", "topic", "avatar", "avatar_url", "encrypted") // err := migrateTable(old, new, "portal", "jid", "receiver", "mxid", "name", "topic", "avatar", "avatar_url", "encrypted")
// if err != nil { // if err != nil {
// panic(err) // panic(err)

View File

@ -157,7 +157,7 @@ type Portal struct {
Name string Name string
Topic string Topic string
Avatar string Avatar string
AvatarURL types.ContentURI AvatarURL id.ContentURI
Encrypted bool `gorm:"notNull;default:false"` Encrypted bool `gorm:"notNull;default:false"`
} }

View File

@ -97,8 +97,7 @@ func NewFormatter(bridge *Bridge) *Formatter {
return fmt.Sprintf("<code>%s</code>", str) return fmt.Sprintf("<code>%s</code>", str)
}, },
} }
formatter.waReplFuncText = map[*regexp.Regexp]func(string) string{ formatter.waReplFuncText = map[*regexp.Regexp]func(string) string{}
}
return formatter return formatter
} }

2
go.mod
View File

@ -25,4 +25,4 @@ require (
maunium.net/go/mautrix v0.9.24 maunium.net/go/mautrix v0.9.24
) )
replace github.com/karmanyaahm/groupme => ./groupme replace github.com/karmanyaahm/groupme => ../groupme-lib

View File

@ -36,7 +36,7 @@ func (m *Message) Value() (driver.Value, error) {
return e, nil return e, nil
} }
//DownloadImage helper function to download image from groupme; // DownloadImage helper function to download image from groupme;
// append .large/.preview/.avatar to get various sizes // append .large/.preview/.avatar to get various sizes
func DownloadImage(URL string) (bytes *[]byte, mime string, err error) { func DownloadImage(URL string) (bytes *[]byte, mime string, err error) {
//TODO check its actually groupme? //TODO check its actually groupme?
@ -70,7 +70,11 @@ func DownloadFile(RoomJID types.GroupMeID, FileID string, token string) (content
req, _ := http.NewRequest("POST", fmt.Sprintf("https://file.groupme.com/v1/%s/fileData", RoomJID), bytes.NewReader(b)) req, _ := http.NewRequest("POST", fmt.Sprintf("https://file.groupme.com/v1/%s/fileData", RoomJID), bytes.NewReader(b))
req.Header.Add("X-Access-Token", token) req.Header.Add("X-Access-Token", token)
req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Type", "application/json")
resp, _ := client.Do(req) resp, err := client.Do(req)
if err != nil {
// TODO: FIX
panic(err)
}
defer resp.Body.Close() defer resp.Body.Close()
data := []ImgData{} data := []ImgData{}
@ -83,7 +87,11 @@ func DownloadFile(RoomJID types.GroupMeID, FileID string, token string) (content
req, _ = http.NewRequest("POST", fmt.Sprintf("https://file.groupme.com/v1/%s/files/%s", RoomJID, FileID), nil) req, _ = http.NewRequest("POST", fmt.Sprintf("https://file.groupme.com/v1/%s/files/%s", RoomJID, FileID), nil)
req.URL.Query().Add("token", token) req.URL.Query().Add("token", token)
req.Header.Add("X-Access-Token", token) req.Header.Add("X-Access-Token", token)
resp, _ = client.Do(req) resp, err = client.Do(req)
if err != nil {
// TODO: FIX
panic(err)
}
defer resp.Body.Close() defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body) bytes, _ := ioutil.ReadAll(resp.Body)

View File

@ -426,7 +426,7 @@ func (bridge *Bridge) Main() {
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
c := make(chan os.Signal) c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM) signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c <-c

View File

@ -31,7 +31,6 @@ import (
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"github.com/karmanyaahm/matrix-groupme-go/database" "github.com/karmanyaahm/matrix-groupme-go/database"
"github.com/karmanyaahm/matrix-groupme-go/types"
) )
type MatrixHandler struct { type MatrixHandler struct {
@ -165,17 +164,17 @@ func (mx *MatrixHandler) handlePrivatePortal(roomID id.RoomID, inviter *User, pu
func (mx *MatrixHandler) createPrivatePortalFromInvite(roomID id.RoomID, inviter *User, puppet *Puppet, portal *Portal) { func (mx *MatrixHandler) createPrivatePortalFromInvite(roomID id.RoomID, inviter *User, puppet *Puppet, portal *Portal) {
portal.MXID = roomID portal.MXID = roomID
portal.Topic = "WhatsApp private chat" portal.Topic = "WhatsApp private chat"
portal.Key = database.PortalKey{puppet.JID, inviter.JID} portal.Key = database.PortalKey{JID: puppet.JID, Receiver: inviter.JID}
_, _ = portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic) _, _ = portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic)
if portal.bridge.Config.Bridge.PrivateChatPortalMeta { if portal.bridge.Config.Bridge.PrivateChatPortalMeta {
m, _ := mx.bridge.StateStore.TryGetMemberRaw(portal.MXID, puppet.MXID) m, _ := mx.bridge.StateStore.TryGetMemberRaw(portal.MXID, puppet.MXID)
portal.Name = m.DisplayName portal.Name = m.DisplayName
portal.AvatarURL = types.ContentURI{id.MustParseContentURI(m.AvatarURL)} portal.AvatarURL = id.MustParseContentURI(m.AvatarURL)
print("possible bug with pointer above") print("possible bug with pointer above")
portal.Avatar = m.Avatar portal.Avatar = m.Avatar
_, _ = portal.MainIntent().SetRoomName(portal.MXID, portal.Name) _, _ = portal.MainIntent().SetRoomName(portal.MXID, portal.Name)
_, _ = portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL.ContentURI) _, _ = portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
} else { } else {
portal.Name = "" portal.Name = ""
} }

View File

@ -1,3 +1,4 @@
//go:build !cgo || nocrypto
// +build !cgo nocrypto // +build !cgo nocrypto
package main package main

View File

@ -196,7 +196,7 @@ func (portal *Portal) handleMessageLoop() {
if msg.timestamp+MaxMessageAgeToCreatePortal < uint64(time.Now().Unix()) { if msg.timestamp+MaxMessageAgeToCreatePortal < uint64(time.Now().Unix()) {
portal.log.Debugln("Not creating portal room for incoming message: message is too old") portal.log.Debugln("Not creating portal room for incoming message: message is too old")
continue continue
} }
portal.log.Debugln("Creating Matrix room from incoming message") portal.log.Debugln("Creating Matrix room from incoming message")
err := portal.CreateMatrixRoom(msg.source) err := portal.CreateMatrixRoom(msg.source)
if err != nil { if err != nil {
@ -392,7 +392,7 @@ func (portal *Portal) UpdateAvatar(user *User, avatar string, updateInfo bool) b
if err != nil { if err != nil {
portal.log.Warnln("Failed to remove avatar:", err) portal.log.Warnln("Failed to remove avatar:", err)
} }
portal.AvatarURL = types.ContentURI{} portal.AvatarURL = id.ContentURI{}
portal.Avatar = avatar portal.Avatar = avatar
return true return true
} }
@ -425,7 +425,7 @@ func (portal *Portal) UpdateAvatar(user *User, avatar string, updateInfo bool) b
return false return false
} }
portal.AvatarURL = types.ContentURI{resp.ContentURI} portal.AvatarURL = resp.ContentURI
if len(portal.MXID) > 0 { if len(portal.MXID) > 0 {
_, err = portal.MainIntent().SetRoomAvatar(portal.MXID, resp.ContentURI) _, err = portal.MainIntent().SetRoomAvatar(portal.MXID, resp.ContentURI)
if err != nil { if err != nil {
@ -951,7 +951,7 @@ func (portal *Portal) CreateMatrixRoom(user *User) error {
//m, _ := portal.bridge.StateStore.TryGetMemberRaw(portal.MXID, puppet.MXID) //m, _ := portal.bridge.StateStore.TryGetMemberRaw(portal.MXID, puppet.MXID)
if portal.bridge.Config.Bridge.PrivateChatPortalMeta { if portal.bridge.Config.Bridge.PrivateChatPortalMeta {
portal.Name = meta.DisplayName portal.Name = meta.DisplayName
portal.AvatarURL = types.ContentURI{id.MustParseContentURI(meta.AvatarURL)} portal.AvatarURL = id.MustParseContentURI(meta.AvatarURL)
portal.Avatar = meta.Avatar portal.Avatar = meta.Avatar
} else { } else {
portal.Name = "" portal.Name = ""
@ -992,7 +992,7 @@ func (portal *Portal) CreateMatrixRoom(user *User) error {
initialState = append(initialState, &event.Event{ initialState = append(initialState, &event.Event{
Type: event.StateRoomAvatar, Type: event.StateRoomAvatar,
Content: event.Content{ Content: event.Content{
Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL.ContentURI}, Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL},
}, },
}) })
} }
@ -1414,7 +1414,7 @@ func (portal *Portal) handleAttachment(intent *appservice.IntentAPI, attachment
portal.log.Warnln("Unable to handle groupme attachment type", attachment.Type) portal.log.Warnln("Unable to handle groupme attachment type", attachment.Type)
return nil, true, fmt.Errorf("Unable to handle groupme attachment type %s", attachment.Type) return nil, true, fmt.Errorf("Unable to handle groupme attachment type %s", attachment.Type)
} }
return nil, true, errors.New("Unknown type") // return nil, true, errors.New("Unknown type")
} }
func (portal *Portal) HandleMediaMessage(source *User, msg mediaMessage) { func (portal *Portal) HandleMediaMessage(source *User, msg mediaMessage) {
// intent := portal.startHandling(source, msg.info) // intent := portal.startHandling(source, msg.info)

View File

@ -336,20 +336,20 @@ var upgrader = websocket.Upgrader{
} }
func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) { func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("user_id") // userID := r.URL.Query().Get("user_id")
user := prov.bridge.GetUserByMXID(id.UserID(userID)) // user := prov.bridge.GetUserByMXID(id.UserID(userID))
if len(ce.Args) < 1 { // if len(ce.Args) < 1 {
// Return error that the token needs to be longer than 0 length // // Return error that the token needs to be longer than 0 length
// ce.Reply(`Get your access token from https://dev.groupme.com/ which should be the first argument to login`) // // ce.Reply(`Get your access token from https://dev.groupme.com/ which should be the first argument to login`)
return // return
} // }
user.Token = ce.Args[0] // user.Token = ce.Args[0]
user.addToJIDMap() // user.addToJIDMap()
// ce.Reply("Successfully logged in, synchronizing chats...") // // ce.Reply("Successfully logged in, synchronizing chats...")
user.PostLogin() // user.PostLogin()
user.Connect() // user.Connect()
// c, err := upgrader.Upgrade(w, r, nil) // c, err := upgrader.Upgrade(w, r, nil)
// if err != nil { // if err != nil {

View File

@ -237,10 +237,9 @@ func (puppet *Puppet) UpdateAvatar(source *User, portalMXID id.RoomID, avatar st
} }
func (puppet *Puppet) UpdateName(source *User, portalMXID id.RoomID, contact groupme.Member) bool { func (puppet *Puppet) UpdateName(source *User, portalMXID id.RoomID, contact groupme.Member) bool {
newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(contact) newName, _ := puppet.bridge.Config.Bridge.FormatDisplayname(contact)
memberRaw, _ := puppet.bridge.StateStore.TryGetMemberRaw(portalMXID, puppet.MXID) //TODO Handle memberRaw, _ := puppet.bridge.StateStore.TryGetMemberRaw(portalMXID, puppet.MXID) //TODO Handle
quality = quality //quality not used
if memberRaw.DisplayName != newName { //&& quality >= puppet.NameQuality[portalMXID] { if memberRaw.DisplayName != newName { //&& quality >= puppet.NameQuality[portalMXID] {
var err error var err error
@ -278,7 +277,7 @@ func (puppet *Puppet) updatePortalAvatar() {
portal.log.Warnln("Failed to set avatar:", err) portal.log.Warnln("Failed to set avatar:", err)
} }
} }
portal.AvatarURL = types.ContentURI{id.MustParseContentURI(m.AvatarURL)} portal.AvatarURL = id.MustParseContentURI(m.AvatarURL)
portal.Avatar = m.Avatar portal.Avatar = m.Avatar
portal.Update() portal.Update()
}) })

View File

@ -1,28 +0,0 @@
package types
import (
"database/sql/driver"
"maunium.net/go/mautrix/id"
)
type ContentURI struct {
id.ContentURI
}
func (m *ContentURI) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
//return errors.New(fmt.Sprint("Failed to unmarshal value:", value))
}
if len(bytes) == 0 {
uri, _ := id.ParseContentURI("")
*m = ContentURI{uri}
return nil
}
return m.UnmarshalText(bytes)
}
func (m ContentURI) Value() (driver.Value, error) {
return m.String(), nil
}

View File

@ -363,7 +363,7 @@ func (user *User) Login(ce *CommandEvent) {
// // Also between the two logout methods (commands.go and provisioning.go) // // Also between the two logout methods (commands.go and provisioning.go)
// user.ConnectionErrors = 0 // user.ConnectionErrors = 0
// user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1) // user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
if len(ce.Args) < 1 { if len(ce.Args) < 1 {
ce.Reply(`Get your access token from https://dev.groupme.com/ which should be the first argument to login`) ce.Reply(`Get your access token from https://dev.groupme.com/ which should be the first argument to login`)
return return
@ -643,7 +643,7 @@ func (user *User) syncPortals(createAll bool) {
break break
} }
wg.Add(1) wg.Add(1)
go func(chat Chat) { go func(chat Chat, i int) {
create := (chat.LastMessageTime >= user.LastConnection && user.LastConnection > 0) || i < limit create := (chat.LastMessageTime >= user.LastConnection && user.LastConnection > 0) || i < limit
if len(chat.Portal.MXID) > 0 || create || createAll { if len(chat.Portal.MXID) > 0 || create || createAll {
chat.Portal.Sync(user, chat.Group) chat.Portal.Sync(user, chat.Group)
@ -654,7 +654,7 @@ func (user *User) syncPortals(createAll bool) {
} }
wg.Done() wg.Done()
}(chat) }(chat, i)
} }
wg.Wait() wg.Wait()