main.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. }
  63. func NewBridge() *Bridge {
  64. bridge := &Bridge{}
  65. var err error
  66. bridge.Config, err = config.Load(*configPath)
  67. if err != nil {
  68. fmt.Fprintln(os.Stderr, "Failed to load config:", err)
  69. os.Exit(10)
  70. }
  71. return bridge
  72. }
  73. func (bridge *Bridge) Init() {
  74. var err error
  75. bridge.AppService, err = bridge.Config.MakeAppService()
  76. if err != nil {
  77. fmt.Fprintln(os.Stderr, "Failed to initialize AppService:", err)
  78. os.Exit(11)
  79. }
  80. bridge.AppService.Init()
  81. bridge.Log = bridge.AppService.Log.Parent
  82. log.DefaultLogger = bridge.Log
  83. bridge.AppService.Log = log.CreateSublogger("Matrix", log.LevelDebug)
  84. bridge.DB, err = database.New(bridge.Config.AppService.Database.URI)
  85. if err != nil {
  86. bridge.Log.Fatalln("Failed to initialize database:", err)
  87. os.Exit(12)
  88. }
  89. bridge.MatrixListener = NewMatrixListener(bridge)
  90. }
  91. func (bridge *Bridge) Start() {
  92. bridge.AppService.Start()
  93. bridge.MatrixListener.Start()
  94. }
  95. func (bridge *Bridge) Stop() {
  96. bridge.AppService.Stop()
  97. bridge.MatrixListener.Stop()
  98. }
  99. func (bridge *Bridge) Main() {
  100. if *generateRegistration {
  101. bridge.GenerateRegistration()
  102. return
  103. }
  104. bridge.Init()
  105. bridge.Log.Infoln("Bridge initialization complete, starting...")
  106. bridge.Start()
  107. bridge.Log.Infoln("Bridge started!")
  108. c := make(chan os.Signal)
  109. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  110. <-c
  111. bridge.Log.Infoln("Interrupt received, stopping...")
  112. bridge.Stop()
  113. bridge.Log.Infoln("Bridge stopped.")
  114. os.Exit(0)
  115. }
  116. func main() {
  117. flag.SetHelpTitles("mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.", "[-h] [-c <path>] [-r <path>] [-g]")
  118. err := flag.Parse()
  119. if err != nil {
  120. fmt.Fprintln(os.Stderr, err)
  121. flag.PrintHelp()
  122. os.Exit(1)
  123. } else if *wantHelp {
  124. flag.PrintHelp()
  125. os.Exit(0)
  126. }
  127. NewBridge().Main()
  128. }
  129. func temp() {
  130. wac, err := whatsapp.NewConn(20 * time.Second)
  131. if err != nil {
  132. panic(err)
  133. }
  134. wac.AddHandler(myHandler{})
  135. sess, err := LoadSession("whatsapp.session")
  136. if err != nil {
  137. fmt.Println(err)
  138. sess, err = Login(wac)
  139. } else {
  140. sess, err = wac.RestoreSession(sess)
  141. }
  142. if err != nil {
  143. panic(err)
  144. }
  145. SaveSession(sess, "whatsapp.session")
  146. reader := bufio.NewReader(os.Stdin)
  147. for {
  148. fmt.Print("receiver> ")
  149. receiver, _ := reader.ReadString('\n')
  150. fmt.Print("message> ")
  151. message, _ := reader.ReadString('\n')
  152. wac.Send(whatsapp.TextMessage{
  153. Info: whatsapp.MessageInfo{
  154. RemoteJid: fmt.Sprintf("%s@s.whatsapp.net", receiver),
  155. },
  156. Text: message,
  157. })
  158. fmt.Println(receiver, message)
  159. }
  160. }
  161. func Login(wac *whatsapp.Conn) (whatsapp.Session, error) {
  162. qrChan := make(chan string)
  163. go func() {
  164. qrterminal.Generate(<-qrChan, qrterminal.L, os.Stdout)
  165. }()
  166. return wac.Login(qrChan)
  167. }
  168. func SaveSession(session whatsapp.Session, fileName string) {
  169. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0600)
  170. if err != nil {
  171. panic(err)
  172. }
  173. enc := gob.NewEncoder(file)
  174. enc.Encode(session)
  175. }
  176. func LoadSession(fileName string) (sess whatsapp.Session, err error) {
  177. file, err := os.OpenFile(fileName, os.O_RDONLY, 0600)
  178. if err != nil {
  179. return sess, err
  180. }
  181. dec := gob.NewDecoder(file)
  182. dec.Decode(sess)
  183. return
  184. }
  185. type myHandler struct{}
  186. func (myHandler) HandleError(err error) {
  187. fmt.Fprintf(os.Stderr, "%v", err)
  188. }
  189. func (myHandler) HandleTextMessage(message whatsapp.TextMessage) {
  190. fmt.Println(message)
  191. }
  192. func (myHandler) HandleImageMessage(message whatsapp.ImageMessage) {
  193. fmt.Println(message)
  194. }
  195. func (myHandler) HandleVideoMessage(message whatsapp.VideoMessage) {
  196. fmt.Println(message)
  197. }
  198. func (myHandler) HandleJsonMessage(message string) {
  199. fmt.Println(message)
  200. }