registry.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package upnp
  7. import (
  8. "sync"
  9. "time"
  10. "github.com/anacrolix/log"
  11. )
  12. type DiscoverFunc func(renewal, timeout time.Duration, _ log.Logger) []Device
  13. var providers []DiscoverFunc
  14. func Register(provider DiscoverFunc) {
  15. providers = append(providers, provider)
  16. }
  17. func discoverAll(renewal, timeout time.Duration, ll levelLogger) map[string]Device {
  18. wg := &sync.WaitGroup{}
  19. wg.Add(len(providers))
  20. c := make(chan Device)
  21. done := make(chan struct{})
  22. for _, discoverFunc := range providers {
  23. go func(f DiscoverFunc) {
  24. for _, dev := range f(renewal, timeout, ll.Logger) {
  25. c <- dev
  26. }
  27. wg.Done()
  28. }(discoverFunc)
  29. }
  30. nats := make(map[string]Device)
  31. go func() {
  32. for dev := range c {
  33. nats[dev.ID()] = dev
  34. }
  35. close(done)
  36. }()
  37. wg.Wait()
  38. close(c)
  39. <-done
  40. return nats
  41. }