deviceconfiguration.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (C) 2014 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 config
  7. import (
  8. "fmt"
  9. "sort"
  10. )
  11. func (cfg DeviceConfiguration) Copy() DeviceConfiguration {
  12. c := cfg
  13. c.Addresses = make([]string, len(cfg.Addresses))
  14. copy(c.Addresses, cfg.Addresses)
  15. c.AllowedNetworks = make([]string, len(cfg.AllowedNetworks))
  16. copy(c.AllowedNetworks, cfg.AllowedNetworks)
  17. c.IgnoredFolders = make([]ObservedFolder, len(cfg.IgnoredFolders))
  18. copy(c.IgnoredFolders, cfg.IgnoredFolders)
  19. return c
  20. }
  21. func (cfg *DeviceConfiguration) prepare(sharedFolders []string) {
  22. if len(cfg.Addresses) == 0 || len(cfg.Addresses) == 1 && cfg.Addresses[0] == "" {
  23. cfg.Addresses = []string{"dynamic"}
  24. }
  25. ignoredFolders := deduplicateObservedFoldersToMap(cfg.IgnoredFolders)
  26. for _, sharedFolder := range sharedFolders {
  27. delete(ignoredFolders, sharedFolder)
  28. }
  29. cfg.IgnoredFolders = sortedObservedFolderSlice(ignoredFolders)
  30. }
  31. func (cfg *DeviceConfiguration) IgnoredFolder(folder string) bool {
  32. for _, ignoredFolder := range cfg.IgnoredFolders {
  33. if ignoredFolder.ID == folder {
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. func sortedObservedFolderSlice(input map[string]ObservedFolder) []ObservedFolder {
  40. output := make([]ObservedFolder, 0, len(input))
  41. for _, folder := range input {
  42. output = append(output, folder)
  43. }
  44. sort.Slice(output, func(i, j int) bool {
  45. return output[i].Time.Before(output[j].Time)
  46. })
  47. return output
  48. }
  49. func deduplicateObservedFoldersToMap(input []ObservedFolder) map[string]ObservedFolder {
  50. output := make(map[string]ObservedFolder, len(input))
  51. for _, folder := range input {
  52. if existing, ok := output[folder.ID]; !ok || existing.Time.Before(folder.Time) {
  53. output[folder.ID] = folder
  54. }
  55. }
  56. return output
  57. }
  58. func (cfg *DeviceConfiguration) Description() string {
  59. if cfg.Name == "" {
  60. return cfg.DeviceID.Short().String()
  61. }
  62. return fmt.Sprintf("%s (%s)", cfg.Name, cfg.DeviceID.Short())
  63. }