-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloco.go
84 lines (73 loc) · 2.14 KB
/
loco.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package loco
import (
"context"
"errors"
"log"
"github.com/lucasmdrs/ctxpoller"
)
const baseURL = "https://localise.biz/api/"
const authEndpoint = "auth/verify"
const filenameTemplate = "%s.json"
const endpointTemplate = "export/" + filenameTemplate
const authParameter = "?key=%s"
// goloco is a structure that holds the required information and implements the GoLoco service interface
type goloco struct {
notifier chan interface{}
poller ctxpoller.Poller
projects map[uint]*project
}
// GoLoco defines the service interface
type GoLoco interface {
AddProject(key, assetsPath string) error
StartPoller() (chan interface{}, error)
StopPoller()
FetchTranslations(context.Context)
}
// Init initializes the service
func Init() GoLoco {
return &goloco{
notifier: make(chan interface{}),
projects: make(map[uint]*project, 0),
}
}
// AddProject includes a new Loco project from a API Key
// and sets the assets destination.
func (g *goloco) AddProject(key string, assetsDestinationPath string) error {
p, err := getProjectInformation(key)
if err != nil {
return err
}
if _, exists := g.projects[p.ID]; exists {
return errors.New("Duplicated project")
}
p.assetsPath = assetsDestinationPath
g.projects[p.ID] = &p
g.notifier = make(chan interface{}, len(g.projects))
return nil
}
// StartPoller keep a poller for any changes in the projects translations
// notifying it in the returned channel whenever the assets changed
func (g *goloco) StartPoller() (chan interface{}, error) {
g.poller = ctxpoller.DefaultPoller(g.FetchTranslations)
return g.notifier, g.poller.Start()
}
// StopPoller stops looking for changes in the translations
func (g *goloco) StopPoller() {
g.poller.Stop()
}
// FetchTranslations fetches the translations from Loco and save it assets
func (g *goloco) FetchTranslations(context.Context) {
for _, p := range g.projects {
if err := p.fetchProjectTranslations(g.notifier); err != nil {
log.Fatalf("Failed to retrieve translations for %s: %s", p.Name, err.Error())
}
}
if g.poller == nil || !g.poller.IsActive() {
emptyChannel(g.notifier)
}
}
func emptyChannel(ch chan interface{}) {
for len(ch) > 0 {
<-ch
}
}