main.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2018 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "github.com/Rhymen/go-whatsapp"
  19. "time"
  20. "fmt"
  21. "os"
  22. "bufio"
  23. "encoding/gob"
  24. "github.com/mdp/qrterminal"
  25. "maunium.net/go/mautrix-whatsapp/config"
  26. flag "maunium.net/go/mauflag"
  27. "os/signal"
  28. "syscall"
  29. "maunium.net/go/mautrix-appservice"
  30. log "maunium.net/go/maulogger"
  31. "maunium.net/go/mautrix-whatsapp/database"
  32. )
  33. var configPath = flag.MakeFull("c", "config", "The path to your config file.", "config.yaml").String()
  34. var registrationPath = flag.MakeFull("r", "registration", "The path where to save the appservice registration.", "registration.yaml").String()
  35. var generateRegistration = flag.MakeFull("g", "generate-registration", "Generate registration and quit.", "false").Bool()
  36. var wantHelp, _ = flag.MakeHelpFlag()
  37. func (bridge *Bridge) GenerateRegistration() {
  38. reg, err := bridge.Config.NewRegistration()
  39. if err != nil {
  40. fmt.Fprintln(os.Stderr, "Failed to generate registration:", err)
  41. os.Exit(20)
  42. }
  43. err = reg.Save(*registrationPath)
  44. if err != nil {
  45. fmt.Fprintln(os.Stderr, "Failed to save registration:", err)
  46. os.Exit(21)
  47. }
  48. err = bridge.Config.Save(*configPath)
  49. if err != nil {
  50. fmt.Fprintln(os.Stderr, "Failed to save config:", err)
  51. os.Exit(22)
  52. }
  53. fmt.Println("Registration generated. Add the path to the registration to your Synapse config restart it, then start the bridge.")
  54. os.Exit(0)
  55. }
  56. type Bridge struct {
  57. AppService *appservice.AppService
  58. Config *config.Config
  59. DB *database.Database
  60. Log *log.Logger
  61. MatrixListener *MatrixListener
  62. users map[string]*User
  63. }
  64. func NewBridge() *Bridge {
  65. bridge := &Bridge{}
  66. var err error
  67. bridge.Config, err = config.Load(*configPath)
  68. if err != nil {
  69. fmt.Fprintln(os.Stderr, "Failed to load config:", err)
  70. os.Exit(10)
  71. }
  72. return bridge
  73. }
  74. func (bridge *Bridge) Init() {
  75. var err error
  76. bridge.AppService, err = bridge.Config.MakeAppService()
  77. if err != nil {
  78. fmt.Fprintln(os.Stderr, "Failed to initialize AppService:", err)
  79. os.Exit(11)
  80. }
  81. bridge.AppService.Init()
  82. bridge.Log = bridge.AppService.Log.Parent
  83. log.DefaultLogger = bridge.Log
  84. bridge.AppService.Log = log.CreateSublogger("Matrix", log.LevelDebug)
  85. bridge.DB, err = database.New(bridge.Config.AppService.Database.URI)
  86. if err != nil {
  87. bridge.Log.Fatalln("Failed to initialize database:", err)
  88. os.Exit(12)
  89. }
  90. bridge.MatrixListener = NewMatrixListener(bridge)
  91. }
  92. func (bridge *Bridge) Start() {
  93. bridge.AppService.Start()
  94. bridge.MatrixListener.Start()
  95. }
  96. func (bridge *Bridge) Stop() {
  97. bridge.AppService.Stop()
  98. bridge.MatrixListener.Stop()
  99. }
  100. func (bridge *Bridge) Main() {
  101. if *generateRegistration {
  102. bridge.GenerateRegistration()
  103. return
  104. }
  105. bridge.Init()
  106. bridge.Log.Infoln("Bridge initialization complete, starting...")
  107. bridge.Start()
  108. bridge.Log.Infoln("Bridge started!")
  109. c := make(chan os.Signal)
  110. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  111. <-c
  112. bridge.Log.Infoln("Interrupt received, stopping...")
  113. bridge.Stop()
  114. bridge.Log.Infoln("Bridge stopped.")
  115. os.Exit(0)
  116. }
  117. func main() {
  118. flag.SetHelpTitles(
  119. "mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.",
  120. "mautrix-whatsapp [-h] [-c <path>] [-r <path>] [-g]")
  121. err := flag.Parse()
  122. if err != nil {
  123. fmt.Fprintln(os.Stderr, err)
  124. flag.PrintHelp()
  125. os.Exit(1)
  126. } else if *wantHelp {
  127. flag.PrintHelp()
  128. os.Exit(0)
  129. }
  130. NewBridge().Main()
  131. }
  132. func temp() {
  133. wac, err := whatsapp.NewConn(20 * time.Second)
  134. if err != nil {
  135. panic(err)
  136. }
  137. wac.AddHandler(myHandler{})
  138. sess, err := LoadSession("whatsapp.session")
  139. if err != nil {
  140. fmt.Println(err)
  141. sess, err = Login(wac)
  142. } else {
  143. sess, err = wac.RestoreSession(sess)
  144. }
  145. if err != nil {
  146. panic(err)
  147. }
  148. SaveSession(sess, "whatsapp.session")
  149. reader := bufio.NewReader(os.Stdin)
  150. for {
  151. fmt.Print("receiver> ")
  152. receiver, _ := reader.ReadString('\n')
  153. fmt.Print("message> ")
  154. message, _ := reader.ReadString('\n')
  155. wac.Send(whatsapp.TextMessage{
  156. Info: whatsapp.MessageInfo{
  157. RemoteJid: fmt.Sprintf("%s@s.whatsapp.net", receiver),
  158. },
  159. Text: message,
  160. })
  161. fmt.Println(receiver, message)
  162. }
  163. }
  164. func Login(wac *whatsapp.Conn) (whatsapp.Session, error) {
  165. qrChan := make(chan string)
  166. go func() {
  167. qrterminal.Generate(<-qrChan, qrterminal.L, os.Stdout)
  168. }()
  169. return wac.Login(qrChan)
  170. }
  171. func SaveSession(session whatsapp.Session, fileName string) {
  172. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0600)
  173. if err != nil {
  174. panic(err)
  175. }
  176. enc := gob.NewEncoder(file)
  177. enc.Encode(session)
  178. }
  179. func LoadSession(fileName string) (sess whatsapp.Session, err error) {
  180. file, err := os.OpenFile(fileName, os.O_RDONLY, 0600)
  181. if err != nil {
  182. return sess, err
  183. }
  184. dec := gob.NewDecoder(file)
  185. dec.Decode(sess)
  186. return
  187. }
  188. type myHandler struct{}
  189. func (myHandler) HandleError(err error) {
  190. fmt.Fprintf(os.Stderr, "%v", err)
  191. }
  192. func (myHandler) HandleTextMessage(message whatsapp.TextMessage) {
  193. fmt.Println(message)
  194. }
  195. func (myHandler) HandleImageMessage(message whatsapp.ImageMessage) {
  196. fmt.Println(message)
  197. }
  198. func (myHandler) HandleVideoMessage(message whatsapp.VideoMessage) {
  199. fmt.Println(message)
  200. }
  201. func (myHandler) HandleJsonMessage(message string) {
  202. fmt.Println(message)
  203. }