bridge.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 config
  17. import (
  18. "bytes"
  19. "text/template"
  20. )
  21. type BridgeConfig struct {
  22. UsernameTemplate string `yaml:"username_template"`
  23. DisplaynameTemplate string `yaml:"displayname_template"`
  24. usernameTemplate *template.Template `yaml:"-"`
  25. displaynameTemplate *template.Template `yaml:"-"`
  26. }
  27. type umBridgeConfig BridgeConfig
  28. func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
  29. err := unmarshal((*umBridgeConfig)(bc))
  30. if err != nil {
  31. return err
  32. }
  33. bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
  34. if err != nil {
  35. return err
  36. }
  37. bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
  38. return err
  39. }
  40. type DisplaynameTemplateArgs struct {
  41. Displayname string
  42. }
  43. type UsernameTemplateArgs struct {
  44. Receiver string
  45. UserID string
  46. }
  47. func (bc BridgeConfig) FormatDisplayname(displayname string) string {
  48. var buf bytes.Buffer
  49. bc.displaynameTemplate.Execute(&buf, DisplaynameTemplateArgs{
  50. Displayname: displayname,
  51. })
  52. return buf.String()
  53. }
  54. func (bc BridgeConfig) FormatUsername(receiver, userID string) string {
  55. var buf bytes.Buffer
  56. bc.usernameTemplate.Execute(&buf, UsernameTemplateArgs{
  57. Receiver: receiver,
  58. UserID: userID,
  59. })
  60. return buf.String()
  61. }
  62. func (bc BridgeConfig) MarshalYAML() (interface{}, error) {
  63. bc.DisplaynameTemplate = bc.FormatDisplayname("{{.Displayname}}")
  64. bc.UsernameTemplate = bc.FormatUsername("{{.Receiver}}", "{{.UserID}}")
  65. return bc, nil
  66. }