bridge.go 2.2 KB

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