bridge.go 2.3 KB

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