├── .gitignore ├── icons ├── img │ ├── logo.png │ ├── darkBusy1.png │ ├── darkBusy2.png │ ├── darkBusy3.png │ ├── darkBusy4.png │ ├── darkBusy5.png │ ├── darkError.png │ ├── darkIdle.png │ ├── darkPause.png │ ├── lightIdle.png │ ├── lightBusy1.png │ ├── lightBusy2.png │ ├── lightBusy3.png │ ├── lightBusy4.png │ ├── lightBusy5.png │ ├── lightError.png │ ├── lightPause.png │ └── readme.md ├── icons_data_test.go ├── icons_data.go ├── icons_test.go └── icons.go ├── Screenshots └── indicator+menu.png ├── catalog_update.sh ├── go.mod ├── main_test.go ├── notify ├── notify_test.go └── notify.go ├── ydisk ├── check.go ├── ydisk_test.go ├── ydisk_bench_test.go └── ydisk.go ├── .github └── workflows │ └── go.yml ├── go.sum ├── README.md ├── catalog.go ├── tools ├── tools.go └── tools_test.go ├── locales ├── ru │ ├── out.gotext.json │ └── messages.gotext.json └── en-US │ └── out.gotext.json ├── yd.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | yd-go* 2 | icons/img/src 3 | icons/img/*_.png 4 | .vscode -------------------------------------------------------------------------------- /icons/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/logo.png -------------------------------------------------------------------------------- /icons/img/darkBusy1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkBusy1.png -------------------------------------------------------------------------------- /icons/img/darkBusy2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkBusy2.png -------------------------------------------------------------------------------- /icons/img/darkBusy3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkBusy3.png -------------------------------------------------------------------------------- /icons/img/darkBusy4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkBusy4.png -------------------------------------------------------------------------------- /icons/img/darkBusy5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkBusy5.png -------------------------------------------------------------------------------- /icons/img/darkError.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkError.png -------------------------------------------------------------------------------- /icons/img/darkIdle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkIdle.png -------------------------------------------------------------------------------- /icons/img/darkPause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/darkPause.png -------------------------------------------------------------------------------- /icons/img/lightIdle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightIdle.png -------------------------------------------------------------------------------- /icons/img/lightBusy1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightBusy1.png -------------------------------------------------------------------------------- /icons/img/lightBusy2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightBusy2.png -------------------------------------------------------------------------------- /icons/img/lightBusy3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightBusy3.png -------------------------------------------------------------------------------- /icons/img/lightBusy4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightBusy4.png -------------------------------------------------------------------------------- /icons/img/lightBusy5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightBusy5.png -------------------------------------------------------------------------------- /icons/img/lightError.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightError.png -------------------------------------------------------------------------------- /icons/img/lightPause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/icons/img/lightPause.png -------------------------------------------------------------------------------- /Screenshots/indicator+menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/slytomcat/yd-go/HEAD/Screenshots/indicator+menu.png -------------------------------------------------------------------------------- /catalog_update.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | go install golang.org/x/text/cmd/gotext@latest 4 | gotext update -out catalog.go 5 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/slytomcat/yd-go 2 | 3 | go 1.24.0 4 | 5 | require ( 6 | github.com/fsnotify/fsnotify v1.8.0 7 | github.com/godbus/dbus/v5 v5.1.0 8 | github.com/slytomcat/systray v1.10.5-0.20250611183948-9bd0132c1649 9 | github.com/stretchr/testify v1.8.4 10 | golang.org/x/text v0.21.0 11 | ) 12 | 13 | require ( 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/pmezard/go-difflib v1.0.0 // indirect 16 | golang.org/x/sys v0.28.0 // indirect 17 | gopkg.in/yaml.v3 v3.0.1 // indirect 18 | ) 19 | -------------------------------------------------------------------------------- /icons/icons_data_test.go: -------------------------------------------------------------------------------- 1 | package icons 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_Data(t *testing.T) { 10 | assert.NotEmpty(t, lightBusy1) 11 | assert.NotEmpty(t, lightBusy2) 12 | assert.NotEmpty(t, lightBusy3) 13 | assert.NotEmpty(t, lightBusy4) 14 | assert.NotEmpty(t, lightBusy5) 15 | assert.NotEmpty(t, lightError) 16 | assert.NotEmpty(t, lightIdle) 17 | assert.NotEmpty(t, lightPause) 18 | assert.NotEmpty(t, darkBusy1) 19 | assert.NotEmpty(t, darkBusy2) 20 | assert.NotEmpty(t, darkBusy3) 21 | assert.NotEmpty(t, darkBusy4) 22 | assert.NotEmpty(t, darkBusy5) 23 | assert.NotEmpty(t, darkError) 24 | assert.NotEmpty(t, darkIdle) 25 | assert.NotEmpty(t, darkPause) 26 | assert.NotEmpty(t, logo) 27 | } 28 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/slytomcat/yd-go/tools" 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestSetupLocalization(t *testing.T) { 11 | log := tools.SetupLogger(false) 12 | t.Run("en", func(t *testing.T) { 13 | t.Setenv("LANG", "en_US.UTF-8") 14 | p := SetupLocalization(log) 15 | require.Equal(t, "idle", p.Sprintf("idle")) 16 | }) 17 | t.Run("ru", func(t *testing.T) { 18 | t.Setenv("LANG", "ru_RU.UTF-8") 19 | p := SetupLocalization(log) 20 | require.Equal(t, "ожидание", p.Sprintf("idle")) 21 | }) 22 | } 23 | 24 | func TestJoinNonEmpty(t *testing.T) { 25 | require.Equal(t, "a b c", joinNonEmpty("", "a", "", "", "b", "", "c", "", "")) 26 | require.Equal(t, "", joinNonEmpty("", "", "")) 27 | } 28 | -------------------------------------------------------------------------------- /icons/img/readme.md: -------------------------------------------------------------------------------- 1 | Icons are used to display the indicator statuses. 2 | 3 | There are two icons themes: 4 | - `dark*` - for dark panel 5 | - `light*` - for light panel 6 | 7 | Each theme must support the following set of icons: 8 | - `*Idle.png` - displayed when Yandex.disk is synchronized 9 | - `*Pause.png` - displayed when Yandex.disk daemon not started or synchronization is paused 10 | - `*Error.png` - displayed when some error occurs in synchronization 11 | - `*Busy[1-5].png` - set of icons to indicate the synchronization process. 12 | 13 | Icons `*Busy[1-5].png` are displayed sequentially in the loop (to simulate animation): 14 | 15 | `*Busy1.png` -> `*Busy2.png` -> `*Busy3.png` -> `*Busy4.png` -> `*Busy5.png` -> `*Busy1.png` -> `*Busy2.png` ... 16 | 17 | The special icon `logo.png` is used into about and into other notifications. 18 | -------------------------------------------------------------------------------- /notify/notify_test.go: -------------------------------------------------------------------------------- 1 | package notify 2 | 3 | import ( 4 | "os" 5 | "path" 6 | "testing" 7 | "time" 8 | 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestDBusNotify(t *testing.T) { 13 | if os.Getenv("CI") != "" { 14 | t.Skip("Skipping testing in CI environment") 15 | } 16 | // read icon 17 | p, err := os.Getwd() 18 | require.NoError(t, err) 19 | p, _ = path.Split(p) 20 | p += "/icons/img/logo.png" 21 | icon, err := os.ReadFile(p) 22 | require.NoError(t, err) 23 | 24 | n, err := New("appName", icon, true, -1) 25 | require.NoError(t, err) 26 | require.NotNil(t, n) 27 | defer n.Close() 28 | 29 | cap, err := n.Cap() 30 | require.NoError(t, err) 31 | require.NotEmpty(t, cap) 32 | 33 | n.Send("title", "message") 34 | time.Sleep(time.Second) 35 | n.Send("title1", "message1") 36 | time.Sleep(time.Second) 37 | n.Send("title2", "message2") 38 | time.Sleep(time.Second) 39 | n.replace = false 40 | n.Send("title3", "message3") 41 | time.Sleep(time.Second) 42 | n.Send("title4", "message4") 43 | time.Sleep(time.Second) 44 | } 45 | -------------------------------------------------------------------------------- /icons/icons_data.go: -------------------------------------------------------------------------------- 1 | package icons 2 | 3 | import ( 4 | _ "embed" // embed is used only here 5 | ) 6 | 7 | var ( 8 | //go:embed img/darkBusy1.png 9 | darkBusy1 []byte 10 | 11 | //go:embed img/darkBusy2.png 12 | darkBusy2 []byte 13 | 14 | //go:embed img/darkBusy3.png 15 | darkBusy3 []byte 16 | 17 | //go:embed img/darkBusy4.png 18 | darkBusy4 []byte 19 | 20 | //go:embed img/darkBusy5.png 21 | darkBusy5 []byte 22 | 23 | //go:embed img/darkError.png 24 | darkError []byte 25 | 26 | //go:embed img/darkIdle.png 27 | darkIdle []byte 28 | 29 | //go:embed img/darkPause.png 30 | darkPause []byte 31 | 32 | //go:embed img/lightBusy1.png 33 | lightBusy1 []byte 34 | 35 | //go:embed img/lightBusy2.png 36 | lightBusy2 []byte 37 | 38 | //go:embed img/lightBusy3.png 39 | lightBusy3 []byte 40 | 41 | //go:embed img/lightBusy4.png 42 | lightBusy4 []byte 43 | 44 | //go:embed img/lightBusy5.png 45 | lightBusy5 []byte 46 | 47 | //go:embed img/lightError.png 48 | lightError []byte 49 | 50 | //go:embed img/lightIdle.png 51 | lightIdle []byte 52 | 53 | //go:embed img/lightPause.png 54 | lightPause []byte 55 | 56 | //go:embed img/logo.png 57 | logo []byte 58 | ) 59 | -------------------------------------------------------------------------------- /ydisk/check.go: -------------------------------------------------------------------------------- 1 | package ydisk 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "os" 8 | "os/exec" 9 | "strings" 10 | ) 11 | 12 | func notExists(path string) bool { 13 | _, err := os.Stat(path) 14 | if err != nil { 15 | return os.IsNotExist(err) 16 | } 17 | return false 18 | } 19 | 20 | // checkDaemon checks that yandex-disk daemon is installed. 21 | // It reads the provided daemon configuration file and checks existence of synchronized folder 22 | // and authorization file ('passwd' file). If one of them is not exists then checkDaemon exits 23 | // from program. 24 | // It returns the user catalogue that is synchronized by daemon in case of success check. 25 | func checkDaemon(conf string) (string, string, error) { 26 | exe, err := exec.LookPath("yandex-disk") 27 | if err != nil { 28 | msg := "Yandex.Disk CLI utility is not installed. Install it first" 29 | return "", "", fmt.Errorf("%s", msg) 30 | } 31 | f, err := os.Open(conf) 32 | if err != nil { 33 | return "", "", fmt.Errorf("daemon configuration file open error: %v", err) 34 | } 35 | defer f.Close() 36 | reader := bufio.NewReader(f) 37 | var line, dir, auth string 38 | for { 39 | line, err = reader.ReadString('\n') 40 | if err != nil { 41 | break 42 | } 43 | if strings.HasPrefix(line, "dir") { 44 | dir = line[5 : len(line)-2] 45 | } 46 | if strings.HasPrefix(line, "auth") { 47 | auth = line[6 : len(line)-2] 48 | } 49 | if dir != "" && auth != "" { 50 | break 51 | } 52 | } 53 | if err != nil && err != io.EOF { 54 | return "", "", err 55 | } 56 | if notExists(dir) || notExists(auth) { 57 | msg := "Daemon is not configured. First run: `yandex-disk setup`" 58 | return "", "", fmt.Errorf("%s", msg) 59 | } 60 | return exe, dir, nil 61 | } 62 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - name: Set up Go 15 | uses: actions/setup-go@v5 16 | with: 17 | go-version-file: './go.mod' 18 | - name: Prepare simulator 19 | run: | 20 | curl -L https://github.com/slytomcat/yandex-disk-simulator/releases/latest/download/yandex-disk-simulator > yandex-disk 21 | chmod a+x yandex-disk 22 | - name: Test 23 | run: | 24 | export PATH=$(pwd):$PATH 25 | go test -v --race -coverprofile cover.out ./... 26 | - name: Format coverage 27 | run: go tool cover -html=cover.out -o coverage.html 28 | - name: Upload coverage to Artifacts 29 | uses: actions/upload-artifact@v4 30 | with: 31 | name: coverage_artifacts 32 | path: coverage.html 33 | build: 34 | runs-on: ubuntu-latest 35 | steps: 36 | - uses: actions/checkout@v4 37 | - name: Set up Go 38 | uses: actions/setup-go@v5 39 | with: 40 | go-version-file: './go.mod' 41 | - name: Requirements 42 | run: sudo apt-get install upx-ucl 43 | - name: Build amd64 44 | run: | 45 | GOOS=linux GOARCH=amd64 ./build.sh 46 | - name: Upload a Build Artifacts 47 | uses: actions/upload-artifact@v4 48 | with: 49 | name: build_artifacts 50 | path: | 51 | yd-go 52 | push: 53 | needs: [build, test] 54 | if: github.ref == 'refs/heads/master' 55 | runs-on: ubuntu-latest 56 | steps: 57 | - uses: actions/checkout@v4 58 | - name: Download Artifacts 59 | uses: actions/download-artifact@v4.1.7 60 | with: 61 | name: build_artifacts 62 | - name: draft new release and upload assets 63 | env: 64 | GH_TOKEN: ${{ secrets.TOKEN }} 65 | run: | 66 | gh release create "$(git branch --show-current)-$(git rev-parse --short HEAD)" ./yd-go 67 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= 4 | github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= 5 | github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= 6 | github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 7 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 8 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 9 | github.com/slytomcat/systray v1.10.3 h1:av8XasQcCBUmK67pP6fsjG65GbtpQ6Py8uccgfDSKr4= 10 | github.com/slytomcat/systray v1.10.3/go.mod h1:3bQ/lBgh62qi5WgCNSv+cq/xTii1LfP35mGH9w7vFG8= 11 | github.com/slytomcat/systray v1.10.4 h1:ZMhgn86+DAySosrC3zsn5TW8CpMt/3VZuIy9ISznWuU= 12 | github.com/slytomcat/systray v1.10.4/go.mod h1:3bQ/lBgh62qi5WgCNSv+cq/xTii1LfP35mGH9w7vFG8= 13 | github.com/slytomcat/systray v1.10.5-0.20250606215122-e06e650379f7 h1:vldgJbxDHHKkhg0gjwCczWQ9XLiZRGWSjKND25lrpZM= 14 | github.com/slytomcat/systray v1.10.5-0.20250606215122-e06e650379f7/go.mod h1:3bQ/lBgh62qi5WgCNSv+cq/xTii1LfP35mGH9w7vFG8= 15 | github.com/slytomcat/systray v1.10.5-0.20250607081031-c46e47fac446 h1:ySQi7W40AeBtAx+JGX7ynIizIIY27XxJgevlIqdu+Ns= 16 | github.com/slytomcat/systray v1.10.5-0.20250607081031-c46e47fac446/go.mod h1:3bQ/lBgh62qi5WgCNSv+cq/xTii1LfP35mGH9w7vFG8= 17 | github.com/slytomcat/systray v1.10.5-0.20250611183948-9bd0132c1649 h1:Z6b9yf7MvIy7zkulNHhnHARTrw9YCuyXVZDEzvShh/8= 18 | github.com/slytomcat/systray v1.10.5-0.20250611183948-9bd0132c1649/go.mod h1:3bQ/lBgh62qi5WgCNSv+cq/xTii1LfP35mGH9w7vFG8= 19 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 20 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 21 | golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= 22 | golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 23 | golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= 24 | golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= 25 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 26 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 27 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 28 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 29 | -------------------------------------------------------------------------------- /icons/icons_test.go: -------------------------------------------------------------------------------- 1 | package icons 2 | 3 | import ( 4 | "bytes" 5 | "sync" 6 | "testing" 7 | "time" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | type mockIcon struct { 14 | icon []byte 15 | mu sync.Mutex 16 | } 17 | 18 | func (m *mockIcon) set(icon []byte) { 19 | m.mu.Lock() 20 | defer m.mu.Unlock() 21 | m.icon = icon 22 | } 23 | 24 | func (m *mockIcon) get() []byte { 25 | m.mu.Lock() 26 | defer m.mu.Unlock() 27 | return m.icon 28 | } 29 | 30 | var mi mockIcon 31 | 32 | func TestNewIcon(t *testing.T) { 33 | i := NewIcon("dark", mi.set) 34 | require.NotNil(t, i) 35 | defer i.Close() 36 | assert.Equal(t, darkPause, mi.get()) 37 | assert.Equal(t, darkError, i.errorIcon) 38 | assert.Equal(t, darkIdle, i.idleIcon) 39 | assert.Equal(t, darkPause, i.pauseIcon) 40 | assert.Equal(t, [5][]byte{darkBusy1, darkBusy2, darkBusy3, darkBusy4, darkBusy5}, i.busyIcons) 41 | } 42 | 43 | func TestSetTheme(t *testing.T) { 44 | i := NewIcon("dark", mi.set) 45 | defer i.Close() 46 | assert.Equal(t, darkPause, mi.get()) 47 | i.SetTheme("light") 48 | assert.Equal(t, lightPause, mi.get()) 49 | assert.Equal(t, lightError, i.errorIcon) 50 | assert.Equal(t, lightIdle, i.idleIcon) 51 | assert.Equal(t, lightPause, i.pauseIcon) 52 | assert.Equal(t, [5][]byte{lightBusy1, lightBusy2, lightBusy3, lightBusy4, lightBusy5}, i.busyIcons) 53 | i.Set("idle") 54 | assert.Equal(t, lightIdle, mi.get()) 55 | i.SetTheme("dark") 56 | assert.Equal(t, darkIdle, mi.get()) // after a call of Set(), the SetTheme() should change current icon 57 | } 58 | 59 | func TestSet(t *testing.T) { 60 | i := NewIcon("dark", mi.set) 61 | require.NotNil(t, i) 62 | defer i.Close() 63 | i.Set("error") 64 | assert.Equal(t, darkError, mi.get()) 65 | i.Set("idle") 66 | assert.Equal(t, darkIdle, mi.get()) 67 | i.Set("busy") 68 | assert.Equal(t, darkBusy1, mi.get()) 69 | i.Set("paused") 70 | assert.Equal(t, darkPause, mi.get()) 71 | i.SetTheme("light") 72 | assert.Equal(t, lightPause, mi.get()) 73 | i.Set("idle") 74 | assert.Equal(t, lightIdle, mi.get()) 75 | i.Set("error") 76 | assert.Equal(t, lightError, mi.get()) 77 | } 78 | 79 | func TestAnimation(t *testing.T) { 80 | interval = 10 * time.Millisecond 81 | tick := time.Millisecond 82 | waitFor := interval + 5*tick 83 | event := func(i []byte) func() bool { 84 | return func() bool { return bytes.Equal(mi.get(), i) } 85 | } 86 | 87 | i := NewIcon("dark", mi.set) 88 | require.NotNil(t, i) 89 | defer i.Close() 90 | i.Set("busy") 91 | assert.Equal(t, darkBusy1, mi.get()) 92 | assert.Eventually(t, event(darkBusy2), waitFor, tick) 93 | assert.Eventually(t, event(darkBusy3), waitFor, tick) 94 | assert.Eventually(t, event(darkBusy4), waitFor, tick) 95 | assert.Eventually(t, event(darkBusy5), waitFor, tick) 96 | assert.Eventually(t, event(darkBusy1), waitFor, tick) 97 | } 98 | -------------------------------------------------------------------------------- /notify/notify.go: -------------------------------------------------------------------------------- 1 | package notify 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "image" 7 | _ "image/png" 8 | "sync/atomic" 9 | 10 | "github.com/godbus/dbus/v5" 11 | ) 12 | 13 | // Notify holds D-Bus connection and defaults for the notifications. 14 | type Notify struct { 15 | ctx context.Context 16 | cancel func() 17 | app string 18 | iconHints map[string]dbus.Variant 19 | replace bool 20 | time int 21 | conn *dbus.Conn 22 | connObj dbus.BusObject 23 | lastID atomic.Uint32 24 | } 25 | 26 | const ( 27 | dBusDest = "org.freedesktop.Notifications" 28 | dBusPath = "/org/freedesktop/Notifications" 29 | ) 30 | 31 | // New creates new Notify component. 32 | // The application is the name of application. 33 | // The icon is png/ico image data to use in Send as notify message icon. 34 | // True value of replace means that a new notification will replace the previous one if it is still displayed. 35 | // The time sets the time in milliseconds after which the notification will disappear. Set it to -1 to use Desktop default settings. 36 | // It returns error in cases of D-BUS connection error or error of getting the notification server capabilities. 37 | func New(application string, icon []byte, replace bool, time int) (*Notify, error) { 38 | conn, err := dbus.ConnectSessionBus() 39 | if err != nil { 40 | return nil, err 41 | } 42 | ctx, cancel := context.WithCancel(context.Background()) 43 | notify := &Notify{ 44 | ctx: ctx, 45 | cancel: cancel, 46 | app: application, 47 | replace: replace, 48 | time: time, 49 | conn: conn, 50 | connObj: conn.Object(dBusDest, dBusPath), 51 | } 52 | if _, err = notify.Cap(); err != nil { 53 | return nil, err 54 | } 55 | // perform heavy staff only when service is available 56 | notify.iconHints = map[string]dbus.Variant{"image-data": dbus.MakeVariant(convertToPixels(icon))} 57 | return notify, nil 58 | } 59 | 60 | // Close closes D-BUS connection. Call it on app exit or similar cases. 61 | func (n *Notify) Close() { 62 | n.cancel() 63 | n.conn.Close() 64 | } 65 | 66 | // Send sends the desktop notification. 67 | func (n *Notify) Send(title, message string) { 68 | var last uint32 69 | if n.replace { 70 | last = n.lastID.Load() 71 | } 72 | call := n.connObj.CallWithContext(n.ctx, dBusDest+".Notify", dbus.Flags(0), n.app, last, "", title, message, []string{}, n.iconHints, n.time) 73 | if call.Err == nil && n.replace { 74 | n.lastID.Store(call.Body[0].(uint32)) 75 | } 76 | // ignore the rest possible errors 77 | } 78 | 79 | // ImageData is struct to hold image data into pix-buffer format as it declared into D-BUS specs. 80 | type ImageData struct { 81 | Width, Height, RowStride int32 82 | HasAlpha bool 83 | BitsPerSample, Channels int32 84 | ImageData []byte 85 | } 86 | 87 | // convertToPixels is used to convert png/ico format into pix-buffer as it declared into D-BUS specs. 88 | func convertToPixels(data []byte) ImageData { 89 | src, _, err := image.Decode(bytes.NewReader(data)) 90 | if err != nil { 91 | panic(err) 92 | } 93 | img := image.NewRGBA(src.Bounds()) 94 | for x := range src.Bounds().Dx() { 95 | for y := range src.Bounds().Dy() { 96 | img.Set(x, y, src.At(x, y)) 97 | } 98 | } 99 | return ImageData{ 100 | Width: int32(img.Bounds().Dx()), 101 | Height: int32(img.Bounds().Dy()), 102 | RowStride: int32(img.Stride), 103 | HasAlpha: true, 104 | BitsPerSample: 8, 105 | Channels: 4, 106 | ImageData: img.Pix, 107 | } 108 | } 109 | 110 | // Cap returns the notification server capabilities 111 | func (n *Notify) Cap() ([]string, error) { 112 | call := n.connObj.CallWithContext(n.ctx, dBusDest+".GetCapabilities", dbus.Flags(0)) 113 | if call.Err != nil { 114 | return nil, call.Err 115 | } 116 | return call.Body[0].([]string), nil 117 | } 118 | -------------------------------------------------------------------------------- /icons/icons.go: -------------------------------------------------------------------------------- 1 | package icons 2 | 3 | import ( 4 | "context" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | const busyIconsCnt = 5 10 | 11 | var interval = time.Millisecond * 333 12 | 13 | // iconSet is set of one theme icons 14 | type iconsSet struct { 15 | busyIcons [busyIconsCnt][]byte // busy icons set for icon animation for index and busy statuses 16 | idleIcon []byte // idle icon data 17 | pauseIcon []byte // pause icon data 18 | errorIcon []byte // error icon data 19 | } 20 | 21 | var ( 22 | lightSet = &iconsSet{ 23 | busyIcons: [busyIconsCnt][]byte{lightBusy1, lightBusy2, lightBusy3, lightBusy4, lightBusy5}, 24 | idleIcon: lightIdle, 25 | pauseIcon: lightPause, 26 | errorIcon: lightError, 27 | } 28 | darkSet = &iconsSet{ 29 | busyIcons: [busyIconsCnt][]byte{darkBusy1, darkBusy2, darkBusy3, darkBusy4, darkBusy5}, 30 | idleIcon: darkIdle, 31 | pauseIcon: darkPause, 32 | errorIcon: darkError, 33 | } 34 | ) 35 | 36 | // Icon is the icon helper 37 | type Icon struct { 38 | *iconsSet // current theme icons set 39 | LogoIcon []byte // bytes of logo icon 40 | lock sync.Mutex // data protection lock 41 | currentStatus string // current icon status 42 | currentBusyIcon int // current icon number for busy animation 43 | setFunc func([]byte) // function to set icon 44 | ticker *time.Ticker // ticker for icon animation 45 | stopper func() // helper stop function 46 | } 47 | 48 | // NewIcon initializes the icon helper, sets 'paused' icon ac initial and returns the helper. 49 | // Use icon.Close() for properly utilization of the icon helper resources. 50 | // The helper provides 'paused' 'idle' 'error' icons and animated 'busy' icon. In additional it provides LogoIcon. 51 | // Icons 'paused' 'idle' 'error' and 'busy' are provided in one of two themes: "light" or "dark" for light or dark DE themes. 52 | func NewIcon(theme string, setFunc func([]byte)) *Icon { 53 | ctx, cancel := context.WithCancel(context.Background()) 54 | i := &Icon{ 55 | currentStatus: "paused", 56 | currentBusyIcon: 0, 57 | LogoIcon: logo, 58 | setFunc: setFunc, 59 | ticker: time.NewTicker(time.Hour), 60 | stopper: cancel, 61 | } 62 | i.ticker.Stop() 63 | i.SetTheme(theme) 64 | go i.loop(ctx) 65 | return i 66 | } 67 | 68 | // SetTheme select one of the icons' themes: "light" or "dark" and update icon from new theme via setFunc. 69 | func (i *Icon) SetTheme(theme string) { 70 | i.lock.Lock() 71 | defer i.lock.Unlock() 72 | switch theme { 73 | case "light": 74 | i.iconsSet = lightSet 75 | case "dark": 76 | i.iconsSet = darkSet 77 | } 78 | i.setIcon() 79 | } 80 | 81 | // setIcon sets the current icon image via i.SetFunc 82 | func (i *Icon) setIcon() { 83 | switch i.currentStatus { 84 | case "busy": 85 | i.setFunc(i.busyIcons[i.currentBusyIcon]) 86 | case "idle": 87 | i.setFunc(i.idleIcon) 88 | case "paused": 89 | i.setFunc(i.pauseIcon) 90 | case "error": 91 | i.setFunc(i.errorIcon) 92 | } 93 | } 94 | 95 | // Set sets the icon for status "busy" (animated), "idle", "paused" and "error" 96 | func (i *Icon) Set(status string) { 97 | i.lock.Lock() 98 | defer i.lock.Unlock() 99 | if i.currentStatus != "busy" && status == "busy" { // not busy -> busy 100 | i.ticker.Reset(interval) 101 | } 102 | if status != "busy" && i.currentStatus == "busy" { // busy -> not busy 103 | i.ticker.Stop() 104 | } 105 | i.currentStatus = status 106 | i.setIcon() 107 | } 108 | 109 | func (i *Icon) loop(ctx context.Context) { 110 | for { 111 | select { 112 | case <-i.ticker.C: 113 | i.lock.Lock() 114 | i.currentBusyIcon = (i.currentBusyIcon + 1) % busyIconsCnt 115 | i.setIcon() 116 | i.lock.Unlock() 117 | case <-ctx.Done(): 118 | return 119 | } 120 | } 121 | } 122 | 123 | // Close stops internal loop 124 | func (i *Icon) Close() { 125 | i.ticker.Stop() 126 | i.stopper() 127 | } 128 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # yd-go 2 | [![Go](https://github.com/slytomcat/yd-go/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/slytomcat/yd-go/actions/workflows/go.yml) 3 | ## Panel indicator for Yandex-disk CLI daemon (linux) 4 | 5 | [![Screenshot](https://github.com/slytomcat/yd-go/blob/master/Screenshots/indicator%2Bmenu.png)](https://github.com/slytomcat/yd-go/blob/master/Screenshots/indicator%2Bmenu.png) 6 | 7 | This version of indicator uses B-Bus for communication to the status notification plugin. Therefore it's fully independent of the desktop environment of Linux distribution. 8 | 9 | IMPORTANT: 10 | 11 | Indicator responsible only for showing the synchronization status in the desktop panel. All the synchronization operations are performed by [yandex-disk utility from Yandex](https://yandex.ru/support/disk-desktop-linux/index.html). 12 | 13 | WIKI: 14 | 15 | Russian wiki: https://github.com/slytomcat/yd-go/wiki 16 | 17 | STORY: 18 | 19 | I've made it as it is rather well-known task for me: I've made the similar indicator (GTK+ version) in [YD-tools project in Python language](https://github.com/slytomcat/yandex-disk-indicator). And when I started to learn golang the rewriting the indicator were rather obvious task to practice a new language. Initially there was two versions of golang indicators: for GTK+ and for QT. But later I've adopted new version of indicator library that uses D-Bus for organizing user interface. 20 | 21 | DESCRIPTION: 22 | 23 | Indicator shows current status by different icons in the status notification area. During synchronization the icon is animated. Indicator supports dark and light themes. The current theme can be changed via menu. 24 | 25 | Desktop notifications inform user when daemon started/stopped or synchronization started/stopped. Notifications can be switched off. 26 | 27 | The status notification icon has a menu that allows to: 28 | - see the current daemon status and cloud-disk properties (Used/Total/Free/Trash) 29 | - see paths of the last synchronized files and open them (in default program) 30 | - start/stop daemon 31 | - see the original output of daemon in the current user language 32 | - open local synchronized path into the default file-manager 33 | - open Yandex.Disk in the default browser 34 | - open help/support page 35 | - change the indicator settings (see `"Theme"`, `"Notifications"`, `"StartDaemon"` and `"StopDaemon"` settings below) 36 | 37 | 38 | Application uses settings from the configuration file. The default path to configuration file is `~/.config/yd-go/default.cfg`. The path can be changed by the `-config` application option. The file is in JSON format and it contain following options: 39 | - `"Conf"` - Path to daemon config file (default `"~/.config/yandex-disk/config.cfg"`). 40 | - `"Theme"` - Icons theme name (default `"dark"`, may be set to `"dark"` or `"light"`). This setting can be changed via indicator menu. 41 | - `"Notifications"` - Display or not the desktop notifications (default `true`). This setting can be changed via indicator menu. 42 | - `"StartDaemon"` - Flag that shows that the daemon should be started on app start (default `true`). This setting can be changed via indicator menu. 43 | - `"StopDaemon"` - Flag that shows that the daemon should be stopped on app closure (default `false`). This setting can be changed via indicator menu. 44 | 45 | ## Get 46 | Download linux-amd64 binary from [releases](https://github.com/slytomcat/yd-go/releases), copy it to path in PATH (/usr/local/bin for example) and make it executable. 47 | 48 | OR 49 | 50 | Get source from master branch and unzip it or just clone repository build it and install as described below. 51 | 52 | ## Build 53 | You must have Golang v1.24+ installed to build the binary. There is no additional libraries/packages required for building except the optional `upx` utility. Just jump into project directory and run: 54 | 55 | ```bash 56 | ./build.sh 57 | ``` 58 | When `upx` is available then the binary will be additionally compressed. If `upx` is not installed then the binary will be uncompressed and a warning appears abut it. You can use both compressed and not compressed binary, the only difference is the used space on disk for binary (not soo much in both cases). 59 | ## Installation 60 | Run 61 | ```bash 62 | sudo cp yd-go /usr/local/bin/ 63 | ``` 64 | 65 | ## Usage 66 | yd-go [-debug] [-config=] 67 | 68 | -config string 69 | Path to the indicator configuration file (default "~/.config/yd.go/default.cfg") 70 | -debug 71 | Alow debugging messages to be sent to stderr 72 | -version 73 | Print out version information and exit 74 | 75 | 76 | NOTE: the yandex-disk CLI utility must be installed and configured before starting of the yd-go. 77 | 78 | ## Icons 79 | 80 | All the indicator icons are embedded into binary during the build time. But You can change them and rebuild the indicator. See more details about icons into [icons/img/readme.md](icons/img/readme.md) 81 | -------------------------------------------------------------------------------- /catalog.go: -------------------------------------------------------------------------------- 1 | // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. 2 | 3 | package main 4 | 5 | import ( 6 | "golang.org/x/text/language" 7 | "golang.org/x/text/message" 8 | "golang.org/x/text/message/catalog" 9 | ) 10 | 11 | type dictionary struct { 12 | index []uint32 13 | data string 14 | } 15 | 16 | func (d *dictionary) Lookup(key string) (data string, ok bool) { 17 | p, ok := messageKeyToIndex[key] 18 | if !ok { 19 | return "", false 20 | } 21 | start, end := d.index[p], d.index[p+1] 22 | if start == end { 23 | return "", false 24 | } 25 | return d.data[start:end], true 26 | } 27 | 28 | func init() { 29 | dict := map[string]catalog.Dictionary{ 30 | "en_US": &dictionary{index: en_USIndex, data: en_USData}, 31 | "ru": &dictionary{index: ruIndex, data: ruData}, 32 | } 33 | fallback := language.MustParse("en-US") 34 | cat, err := catalog.NewFromMap(dict, catalog.Fallback(fallback)) 35 | if err != nil { 36 | panic(err) 37 | } 38 | message.DefaultCatalog = cat 39 | } 40 | 41 | var messageKeyToIndex = map[string]int{ 42 | "About": 18, 43 | "Daemon started": 28, 44 | "Daemon stopped": 27, 45 | "Donations": 19, 46 | "Free: %s Trash: %s": 26, 47 | "Help": 17, 48 | "Last synchronized": 6, 49 | "Light theme": 13, 50 | "Notification service unavailable!": 21, 51 | "Notifications": 14, 52 | "Open Yandex.Disk folder": 10, 53 | "Open Yandex.Disk in browser": 11, 54 | "Quit": 20, 55 | "Settings": 12, 56 | "Show daemon output": 9, 57 | "Start daemon": 7, 58 | "Start on start": 15, 59 | "Status: %s": 24, 60 | "Stop daemon": 8, 61 | "Stop on exit": 16, 62 | "Synchronization finished": 30, 63 | "Synchronization started": 29, 64 | "Used: %s/%s": 25, 65 | "Yandex.Disk daemon output": 22, 66 | "Yandex.Disk indicator": 0, 67 | "busy": 3, 68 | "idle": 1, 69 | "index": 2, 70 | "none": 4, 71 | "paused": 5, 72 | "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: %s\n\nCopyleft 2017-%s Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3\n\n": 23, 73 | } 74 | 75 | var en_USIndex = []uint32{ // 32 elements 76 | 0x00000000, 0x00000016, 0x0000001b, 0x00000021, 77 | 0x00000026, 0x0000002b, 0x00000032, 0x00000044, 78 | 0x00000051, 0x0000005d, 0x00000070, 0x00000088, 79 | 0x000000a4, 0x000000ad, 0x000000b9, 0x000000c7, 80 | 0x000000d6, 0x000000e3, 0x000000e8, 0x000000ee, 81 | 0x000000f8, 0x000000fd, 0x0000011f, 0x00000139, 82 | 0x000001ce, 0x000001dc, 0x000001ee, 0x00000207, 83 | 0x00000216, 0x00000225, 0x0000023d, 0x00000256, 84 | } // Size: 152 bytes 85 | 86 | const en_USData string = "" + // Size: 598 bytes 87 | "\x02Yandex.Disk indicator\x02idle\x02index\x02busy\x02none\x02paused\x02" + 88 | "Last synchronized\x02Start daemon\x02Stop daemon\x02Show daemon output" + 89 | "\x02Open Yandex.Disk folder\x02Open Yandex.Disk in browser\x02Settings" + 90 | "\x02Light theme\x02Notifications\x02Start on start\x02Stop on exit\x02He" + 91 | "lp\x02About\x02Donations\x02Quit\x02Notification service unavailable!" + 92 | "\x02Yandex.Disk daemon output\x04\x00\x02\x0a\x0a\x8e\x01\x02yd-go is th" + 93 | "e panel indicator for Yandex.Disk daemon.\x0a\x0a\x09Version: %[1]s\x0a" + 94 | "\x0aCopyleft 2017-%[2]s Sly_tom_cat (slytomcat@mail.ru)\x0a\x0a\x09Licen" + 95 | "se: GPL v.3\x02Status: %[1]s\x02Used: %[1]s/%[2]s\x02Free: %[1]s Trash: " + 96 | "%[2]s\x02Daemon stopped\x02Daemon started\x02Synchronization started\x02" + 97 | "Synchronization finished" 98 | 99 | var ruIndex = []uint32{ // 32 elements 100 | 0x00000000, 0x0000001f, 0x00000030, 0x00000045, 101 | 0x00000060, 0x00000075, 0x00000080, 0x000000b8, 102 | 0x000000da, 0x000000fe, 0x00000129, 0x00000153, 103 | 0x00000182, 0x00000195, 0x000001ad, 0x000001c4, 104 | 0x000001e9, 0x00000212, 0x0000021f, 0x00000239, 105 | 0x00000254, 0x0000025f, 0x00000299, 0x000002bf, 106 | 0x0000037d, 0x00000391, 0x000003b7, 0x000003e5, 107 | 0x0000040b, 0x0000042b, 0x00000453, 0x00000481, 108 | } // Size: 152 bytes 109 | 110 | const ruData string = "" + // Size: 1153 bytes 111 | "\x02Индикатор Yandex.Disk\x02ожидание\x02индексация\x02синхронизация\x02" + 112 | "остановлен\x02пауза\x02Последние синхронизированные\x02Запустить утилит" + 113 | "у\x02Остановить утилиту\x02Показать вывод утилиты\x02Открыть каталог Ya" + 114 | "ndex.Disk\x02Открыть Yandex.Disk в браузере\x02Настройки\x02Светлая тема" + 115 | "\x02Уведомления\x02Запускать на старте\x02Остановить при выходе\x02Помощ" + 116 | "ь\x02Об индикаторе\x02Пожертвования\x02Выход\x02Сервис уведомлений недо" + 117 | "ступен!\x02Вывод утилиты Yandex.Disk\x04\x00\x02\x0a\x0a\xb7\x01\x02yd-" + 118 | "go это индикатор панели для утилиты Yandex.Disk.\x0a\x0a\x09Версия: %[1]" + 119 | "s\x0a\x0aCopyleft 2017-%[2]s Sly_tom_cat (slytomcat@mail.ru)\x0a\x0a\x09" + 120 | "Лицензия: GPL v.3\x02Статус: %[1]s\x02Использовано: %[1]s/%[2]s\x02Своб" + 121 | "одно: %[1]s Корзина: %[2]s\x02Утилита остановлена\x02Утилита запущена" + 122 | "\x02Синхронизация начата\x02Синхронизация закончена" 123 | 124 | // Total table size 2055 bytes (2KiB); checksum: E6D66B0E 125 | -------------------------------------------------------------------------------- /tools/tools.go: -------------------------------------------------------------------------------- 1 | // Package tools contains commonly used functions for yd-go and yd-qgo projects 2 | package tools 3 | 4 | import ( 5 | "encoding/json" 6 | "errors" 7 | "flag" 8 | "fmt" 9 | "io/fs" 10 | "log/slog" 11 | "os" 12 | "os/exec" 13 | "path" 14 | "strings" 15 | ) 16 | 17 | var llog *slog.Logger 18 | 19 | // NotExists returns true when specified path does not exists 20 | func NotExists(path string) bool { 21 | if _, err := os.Stat(path); err != nil { 22 | return errors.Is(err, fs.ErrNotExist) 23 | } 24 | return false 25 | } 26 | 27 | // XdgOpen opens the uri via xdg-open command 28 | func XdgOpen(uri string) error { 29 | return exec.Command("xdg-open", uri).Start() 30 | } 31 | 32 | // MakeTitle returns the shorten version of its first parameter. The second parameter specifies 33 | // the maximum number of symbols (runes) in returned string. It also replaces underscore symbol with 34 | // the special unicode symbols sequence that looks very similar to the original underscore 35 | func MakeTitle(s string, l int) string { 36 | r := []rune(s) 37 | if len(r) < l { 38 | return replaceUnderscore(s) 39 | } 40 | b := (l - 3) / 2 41 | return replaceUnderscore(string(r[:b])) + "..." + replaceUnderscore(string(r[len(r)-(l-3-b):])) 42 | } 43 | 44 | // replaceUnderscore replaces underscore (special symbol for menu shortcut) to special unicode symbols which looks like original underscore 45 | func replaceUnderscore(s string) string { 46 | return strings.ReplaceAll(s, "_", "\u2009\u0332\u2009") // thin space + combining low line + thin space 47 | } 48 | 49 | // Config is application configuration 50 | type Config struct { 51 | path string // config file path 52 | Conf string // path to daemon config file 53 | Theme string // icons theme name 54 | Notifications bool // display desktop notification 55 | StartDaemon bool // start daemon on app start 56 | StopDaemon bool // stop daemon on app exit 57 | } 58 | 59 | // NewConfig returns the application configuration 60 | func NewConfig(cfgFilePath string) (*Config, error) { 61 | cfg := &Config{ 62 | path: cfgFilePath, // store path for Save method 63 | // fill it with default values 64 | Conf: os.ExpandEnv("$HOME/.config/yandex-disk/config.cfg"), // path to daemon config file 65 | Theme: "dark", // icons theme name 66 | Notifications: true, // display desktop notification 67 | StartDaemon: true, // start daemon on app start 68 | StopDaemon: false, // stop daemon on app closure 69 | } 70 | 71 | cfgPath, _ := path.Split(cfgFilePath) 72 | // Check that the configuration file path is exists 73 | if NotExists(cfgPath) { 74 | if err := os.MkdirAll(cfgPath, 0700); err != nil { 75 | return nil, fmt.Errorf("can't create application configuration path: %v", err) 76 | } 77 | } 78 | // Check that the configuration file is exists 79 | if NotExists(cfgFilePath) { 80 | // Create and save new configuration file with default values 81 | err := cfg.Save() 82 | if err != nil { 83 | return nil, fmt.Errorf("default config saving error: %v", err) 84 | } 85 | } else { 86 | // Read the configuration file 87 | data, err := os.ReadFile(cfgFilePath) 88 | if err != nil { 89 | return nil, fmt.Errorf("reading config file error: %v", err) 90 | } 91 | err = json.Unmarshal(data, cfg) 92 | if err != nil { 93 | return nil, fmt.Errorf("parsing config file error: %v", err) 94 | } 95 | if cfg.Theme != "dark" && cfg.Theme != "light" { 96 | return nil, fmt.Errorf("wrong theme name: '%s' (should be 'dark' or 'light')", cfg.Theme) 97 | } 98 | } 99 | return cfg, nil 100 | } 101 | 102 | // Save stores application configuration to the disk 103 | func (c *Config) Save() error { 104 | data, _ := json.Marshal(c) 105 | err := os.WriteFile(c.path, data, 0664) 106 | if err != nil { 107 | return fmt.Errorf("can't save configuration file: %v", err) 108 | } 109 | return nil 110 | } 111 | 112 | // SetupLogger initializes the logger for application 113 | func SetupLogger(debug bool) *slog.Logger { 114 | // set logging level 115 | logLevel := new(slog.LevelVar) 116 | if debug { 117 | logLevel.Set(slog.LevelDebug) 118 | } else { 119 | logLevel.Set(slog.LevelInfo) 120 | } 121 | return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})) 122 | } 123 | 124 | // GetParams read the command line parameters and returns configuration file path and boolean value for debug logging activation. 125 | // When app is called with -h or -version or with wrong option it will call os.Exit(). 126 | func GetParams(appName string, args []string, version string) (string, bool) { 127 | var pv bool 128 | var debug bool 129 | var config string 130 | f := flag.NewFlagSet(appName, flag.ExitOnError) 131 | f.BoolVar(&debug, "debug", false, "Allow debugging messages to be sent to stdout") 132 | f.StringVar(&config, "config", "$HOME/.config/"+appName+"/default.cfg", "Path to the indicator configuration file") 133 | f.BoolVar(&pv, "version", false, "Print out version information and exit") 134 | f.Usage = func() { 135 | _, _ = fmt.Fprintf(f.Output(), "%s\nUsage:\n\n\t\t%q [-debug] [-config=] [-version]\n\n", getVersion(appName, version), appName) 136 | f.PrintDefaults() 137 | } 138 | _ = f.Parse(args[1:]) 139 | if pv { 140 | fmt.Print(getVersion(appName, version)) 141 | os.Exit(0) 142 | } 143 | return os.ExpandEnv(config), debug 144 | } 145 | 146 | func getVersion(appName, version string) string { 147 | return fmt.Sprintf("%s ver.: %s\n", appName, version) 148 | } 149 | -------------------------------------------------------------------------------- /tools/tools_test.go: -------------------------------------------------------------------------------- 1 | package tools 2 | 3 | import ( 4 | "io" 5 | "os" 6 | "path" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | func TestMakeTitle(t *testing.T) { 14 | tests := []struct { 15 | in string 16 | out string 17 | l int 18 | }{ 19 | {in: "1234567890", out: "1234567890", l: 20}, 20 | {in: "1234567890", out: "12...890", l: 8}, 21 | {in: "1234567890123", out: "12...123", l: 8}, 22 | {in: "русский текст", out: "русский текст", l: 20}, 23 | {in: "русский текст дада", out: "рус...дада", l: 10}, 24 | {in: "one_two", out: "one\u2009\u0332\u2009two", l: 10}, 25 | } 26 | for _, tc := range tests { 27 | assert.Equal(t, tc.out, MakeTitle(tc.in, tc.l)) 28 | } 29 | } 30 | 31 | func TestNotExists(t *testing.T) { 32 | wd, err := os.Getwd() 33 | require.NoError(t, err) 34 | require.False(t, NotExists(wd)) 35 | require.True(t, NotExists("/Unreal path+*$")) 36 | } 37 | 38 | func makeTempCfgFile(t *testing.T, content string) string { 39 | file := path.Join(t.TempDir(), "default.cfg") 40 | if err := os.WriteFile(file, []byte(content), 0766); err != nil { 41 | panic(err) 42 | } 43 | return file 44 | } 45 | 46 | func TestConfig(t *testing.T) { 47 | t.Run("no config file", func(t *testing.T) { 48 | testFile := makeTempCfgFile(t, "") 49 | os.Remove(testFile) 50 | cfg, err := NewConfig(testFile) 51 | require.NoError(t, err) 52 | require.NotNil(t, cfg) 53 | require.Equal(t, &Config{ 54 | path: testFile, 55 | Conf: os.ExpandEnv("$HOME/.config/yandex-disk/config.cfg"), 56 | Theme: "dark", 57 | Notifications: true, 58 | StartDaemon: true, 59 | StopDaemon: false, 60 | }, cfg) 61 | }) 62 | 63 | t.Run("config file exists", func(t *testing.T) { 64 | testFile := makeTempCfgFile(t, `{"Conf":"config.cfg","Theme":"dark","Notifications":false,"StartDaemon":false,"StopDaemon":true}`) 65 | defer os.Remove(testFile) 66 | cfg, err := NewConfig(testFile) 67 | require.NoError(t, err) 68 | require.NotNil(t, cfg) 69 | require.Equal(t, &Config{ 70 | path: testFile, 71 | Conf: "config.cfg", 72 | Theme: "dark", 73 | Notifications: false, 74 | StartDaemon: false, 75 | StopDaemon: true, 76 | }, cfg) 77 | }) 78 | 79 | t.Run("empty config file", func(t *testing.T) { 80 | testFile := makeTempCfgFile(t, `{}`) 81 | defer os.Remove(testFile) 82 | cfg, err := NewConfig(testFile) 83 | require.NoError(t, err) 84 | require.NotNil(t, cfg) 85 | require.Equal(t, &Config{ 86 | path: testFile, 87 | Conf: os.ExpandEnv("$HOME/.config/yandex-disk/config.cfg"), 88 | Theme: "dark", 89 | Notifications: true, 90 | StartDaemon: true, 91 | StopDaemon: false, 92 | }, cfg) 93 | }) 94 | 95 | t.Run("partial config file", func(t *testing.T) { 96 | testFile := makeTempCfgFile(t, `{"Theme":"dark","Notifications":false,"StopDaemon":true}`) 97 | defer os.Remove(testFile) 98 | cfg, err := NewConfig(testFile) 99 | require.NoError(t, err) 100 | require.NotNil(t, cfg) 101 | require.Equal(t, &Config{ 102 | path: testFile, 103 | Conf: os.ExpandEnv("$HOME/.config/yandex-disk/config.cfg"), // default 104 | Theme: "dark", // config 105 | Notifications: false, // config 106 | StartDaemon: true, // default 107 | StopDaemon: true, // config 108 | }, cfg) 109 | }) 110 | 111 | t.Run("incorrect theme", func(t *testing.T) { 112 | testFile := makeTempCfgFile(t, `{"Theme":"incorrect"}`) 113 | defer os.Remove(testFile) 114 | cfg, err := NewConfig(testFile) 115 | require.Error(t, err) 116 | require.Nil(t, cfg) 117 | }) 118 | 119 | t.Run("bad config file", func(t *testing.T) { 120 | testFile := makeTempCfgFile(t, `bad,bad,bad`) 121 | defer os.Remove(testFile) 122 | cfg, err := NewConfig(testFile) 123 | require.Error(t, err) 124 | require.Nil(t, cfg) 125 | }) 126 | 127 | t.Run("config file cat't be read", func(t *testing.T) { 128 | cfg, err := NewConfig("/dev/") 129 | require.Error(t, err) 130 | require.Nil(t, cfg) 131 | }) 132 | 133 | t.Run("config file cat't be written", func(t *testing.T) { 134 | cfg, err := NewConfig("/dev/non_existing_device") 135 | require.Error(t, err) 136 | require.Nil(t, cfg) 137 | }) 138 | 139 | t.Run("config file path cat't be created", func(t *testing.T) { 140 | cfg, err := NewConfig("/dev/non_existing_device/file") 141 | require.Error(t, err) 142 | require.Nil(t, cfg) 143 | }) 144 | 145 | // 100% coverage for Config !!! 146 | } 147 | 148 | func readStd(f **os.File) func() string { 149 | r, w, err := os.Pipe() 150 | if err != nil { 151 | panic(err) 152 | } 153 | out := *f 154 | *f = w 155 | return func() string { 156 | *f = out 157 | w.Close() 158 | b, err := io.ReadAll(r) 159 | if err != nil { 160 | panic(err) 161 | } 162 | return string(b) 163 | } 164 | } 165 | 166 | func TestGetParams(t *testing.T) { 167 | tAppName := "testApp" 168 | tVersion := "test" 169 | t.Run("wo_params", func(t *testing.T) { 170 | cfgPath, debug := GetParams(tAppName, []string{tAppName}, tVersion) 171 | require.Equal(t, os.ExpandEnv("$HOME/.config/"+tAppName+"/default.cfg"), cfgPath) 172 | require.False(t, debug) 173 | }) 174 | t.Run("with_debug", func(t *testing.T) { 175 | cfgPath, debug := GetParams(tAppName, []string{tAppName, "-debug"}, tVersion) 176 | require.Equal(t, os.ExpandEnv("$HOME/.config/"+tAppName+"/default.cfg"), cfgPath) 177 | require.True(t, debug) 178 | }) 179 | t.Run("with_cfg", func(t *testing.T) { 180 | cfgFile := makeTempCfgFile(t, "{}") 181 | defer os.Remove(cfgFile) 182 | cfgPath, debug := GetParams(tAppName, []string{tAppName, "-config=" + cfgFile}, tVersion) 183 | require.Equal(t, cfgFile, cfgPath) 184 | require.False(t, debug) 185 | }) 186 | t.Run("with_-h", func(t *testing.T) { 187 | getOut := readStd(&os.Stderr) 188 | // help request will call os.Exit(0) that panics the testing 189 | require.Panics(t, func() { GetParams(tAppName, []string{tAppName, "-h"}, tVersion) }) 190 | out := getOut() 191 | require.Contains(t, out, "Usage") 192 | }) 193 | t.Run("with_-version", func(t *testing.T) { 194 | getOut := readStd(&os.Stdout) 195 | // version request will call os.Exit(0) that panics the testing 196 | require.Panics(t, func() { GetParams(tAppName, []string{tAppName, "-version"}, tVersion) }) 197 | out := getOut() 198 | require.Contains(t, out, tVersion) 199 | }) 200 | } 201 | 202 | func TestSetupLogger(t *testing.T) { 203 | infoMsg := "info_msg" 204 | debugMsg := "debug_msg" 205 | t.Run("info", func(t *testing.T) { 206 | getOut := readStd(&os.Stdout) 207 | l := SetupLogger(false) 208 | l.Debug(debugMsg) 209 | l.Info(infoMsg) 210 | out := getOut() 211 | require.Contains(t, out, infoMsg) 212 | require.NotContains(t, out, debugMsg) 213 | }) 214 | t.Run("debug", func(t *testing.T) { 215 | getOut := readStd(&os.Stdout) 216 | l := SetupLogger(true) 217 | l.Debug(debugMsg) 218 | l.Info(infoMsg) 219 | out := getOut() 220 | require.Contains(t, out, infoMsg) 221 | require.Contains(t, out, debugMsg) 222 | }) 223 | } 224 | 225 | // I have no idea how to test XdgOpen... 226 | -------------------------------------------------------------------------------- /locales/ru/out.gotext.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "ru", 3 | "messages": [ 4 | { 5 | "id": "Yandex.Disk indicator", 6 | "message": "Yandex.Disk indicator", 7 | "translation": "Индикатор Yandex.Disk" 8 | }, 9 | { 10 | "id": "idle", 11 | "message": "idle", 12 | "translation": "ожидание" 13 | }, 14 | { 15 | "id": "index", 16 | "message": "index", 17 | "translation": "индексация" 18 | }, 19 | { 20 | "id": "busy", 21 | "message": "busy", 22 | "translation": "синхронизация" 23 | }, 24 | { 25 | "id": "none", 26 | "message": "none", 27 | "translation": "остановлен" 28 | }, 29 | { 30 | "id": "paused", 31 | "message": "paused", 32 | "translation": "пауза" 33 | }, 34 | { 35 | "id": "Last synchronized", 36 | "message": "Last synchronized", 37 | "translation": "Последние синхронизированные" 38 | }, 39 | { 40 | "id": "Start daemon", 41 | "message": "Start daemon", 42 | "translation": "Запустить утилиту" 43 | }, 44 | { 45 | "id": "Stop daemon", 46 | "message": "Stop daemon", 47 | "translation": "Остановить утилиту" 48 | }, 49 | { 50 | "id": "Show daemon output", 51 | "message": "Show daemon output", 52 | "translation": "Показать вывод утилиты" 53 | }, 54 | { 55 | "id": "Open Yandex.Disk folder", 56 | "message": "Open Yandex.Disk folder", 57 | "translation": "Открыть каталог Yandex.Disk" 58 | }, 59 | { 60 | "id": "Open Yandex.Disk in browser", 61 | "message": "Open Yandex.Disk in browser", 62 | "translation": "Открыть Yandex.Disk в браузере" 63 | }, 64 | { 65 | "id": "Settings", 66 | "message": "Settings", 67 | "translation": "Настройки" 68 | }, 69 | { 70 | "id": "Light theme", 71 | "message": "Light theme", 72 | "translation": "Светлая тема" 73 | }, 74 | { 75 | "id": "Notifications", 76 | "message": "Notifications", 77 | "translation": "Уведомления" 78 | }, 79 | { 80 | "id": "Start on start", 81 | "message": "Start on start", 82 | "translation": "Запускать на старте" 83 | }, 84 | { 85 | "id": "Stop on exit", 86 | "message": "Stop on exit", 87 | "translation": "Остановить при выходе" 88 | }, 89 | { 90 | "id": "Help", 91 | "message": "Help", 92 | "translation": "Помощь" 93 | }, 94 | { 95 | "id": "About", 96 | "message": "About", 97 | "translation": "Об индикаторе" 98 | }, 99 | { 100 | "id": "Donations", 101 | "message": "Donations", 102 | "translation": "Пожертвования" 103 | }, 104 | { 105 | "id": "Quit", 106 | "message": "Quit", 107 | "translation": "Выход" 108 | }, 109 | { 110 | "id": "Notification service unavailable!", 111 | "message": "Notification service unavailable!", 112 | "translation": "Сервис уведомлений недоступен!" 113 | }, 114 | { 115 | "id": "Yandex.Disk daemon output", 116 | "message": "Yandex.Disk daemon output", 117 | "translation": "Вывод утилиты Yandex.Disk" 118 | }, 119 | { 120 | "id": [ 121 | "about", 122 | "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3" 123 | ], 124 | "message": "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3", 125 | "translation": "yd-go это индикатор панели для утилиты Yandex.Disk.\n\n\tВерсия: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tЛицензия: GPL v.3", 126 | "placeholders": [ 127 | { 128 | "id": "Version", 129 | "string": "%[1]s", 130 | "type": "string", 131 | "underlyingType": "string", 132 | "argNum": 1, 133 | "expr": "version" 134 | }, 135 | { 136 | "id": "Format2006", 137 | "string": "%[2]s", 138 | "type": "string", 139 | "underlyingType": "string", 140 | "argNum": 2, 141 | "expr": "time.Now().Format(\"2006\")" 142 | } 143 | ] 144 | }, 145 | { 146 | "id": "Status: {St}", 147 | "message": "Status: {St}", 148 | "translation": "Статус: %[1]s", 149 | "placeholders": [ 150 | { 151 | "id": "St", 152 | "string": "%[1]s", 153 | "type": "string", 154 | "underlyingType": "string", 155 | "argNum": 1, 156 | "expr": "st" 157 | } 158 | ] 159 | }, 160 | { 161 | "id": "Used: {Used}/{Total}", 162 | "message": "Used: {Used}/{Total}", 163 | "translation": "Использовано: %[1]s/%[2]s", 164 | "placeholders": [ 165 | { 166 | "id": "Used", 167 | "string": "%[1]s", 168 | "type": "string", 169 | "underlyingType": "string", 170 | "argNum": 1, 171 | "expr": "yds.Used" 172 | }, 173 | { 174 | "id": "Total", 175 | "string": "%[2]s", 176 | "type": "string", 177 | "underlyingType": "string", 178 | "argNum": 2, 179 | "expr": "yds.Total" 180 | } 181 | ] 182 | }, 183 | { 184 | "id": "Free: {Free} Trash: {Trash}", 185 | "message": "Free: {Free} Trash: {Trash}", 186 | "translation": "Свободно: %[1]s Корзина: %[2]s", 187 | "placeholders": [ 188 | { 189 | "id": "Free", 190 | "string": "%[1]s", 191 | "type": "string", 192 | "underlyingType": "string", 193 | "argNum": 1, 194 | "expr": "yds.Free" 195 | }, 196 | { 197 | "id": "Trash", 198 | "string": "%[2]s", 199 | "type": "string", 200 | "underlyingType": "string", 201 | "argNum": 2, 202 | "expr": "yds.Trash" 203 | } 204 | ] 205 | }, 206 | { 207 | "id": "Daemon stopped", 208 | "message": "Daemon stopped", 209 | "translation": "Утилита остановлена" 210 | }, 211 | { 212 | "id": "Daemon started", 213 | "message": "Daemon started", 214 | "translation": "Утилита запущена" 215 | }, 216 | { 217 | "id": "Synchronization started", 218 | "message": "Synchronization started", 219 | "translation": "Синхронизация начата" 220 | }, 221 | { 222 | "id": "Synchronization finished", 223 | "message": "Synchronization finished", 224 | "translation": "Синхронизация закончена" 225 | } 226 | ] 227 | } -------------------------------------------------------------------------------- /locales/ru/messages.gotext.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "ru", 3 | "messages": [ 4 | { 5 | "id": "Yandex.Disk indicator", 6 | "message": "Yandex.Disk indicator", 7 | "translation": "Индикатор Yandex.Disk" 8 | }, 9 | { 10 | "id": "idle", 11 | "message": "idle", 12 | "translation": "ожидание" 13 | }, 14 | { 15 | "id": "index", 16 | "message": "index", 17 | "translation": "индексация" 18 | }, 19 | { 20 | "id": "busy", 21 | "message": "busy", 22 | "translation": "синхронизация" 23 | }, 24 | { 25 | "id": "none", 26 | "message": "none", 27 | "translation": "остановлен" 28 | }, 29 | { 30 | "id": "paused", 31 | "message": "paused", 32 | "translation": "пауза" 33 | }, 34 | { 35 | "id": "Last synchronized", 36 | "message": "Last synchronized", 37 | "translation": "Последние синхронизированные" 38 | }, 39 | { 40 | "id": "Start daemon", 41 | "message": "Start daemon", 42 | "translation": "Запустить утилиту" 43 | }, 44 | { 45 | "id": "Stop daemon", 46 | "message": "Stop daemon", 47 | "translation": "Остановить утилиту" 48 | }, 49 | { 50 | "id": "Show daemon output", 51 | "message": "Show daemon output", 52 | "translation": "Показать вывод утилиты" 53 | }, 54 | { 55 | "id": "Open Yandex.Disk folder", 56 | "message": "Open Yandex.Disk folder", 57 | "translation": "Открыть каталог Yandex.Disk" 58 | }, 59 | { 60 | "id": "Open Yandex.Disk in browser", 61 | "message": "Open Yandex.Disk in browser", 62 | "translation": "Открыть Yandex.Disk в браузере" 63 | }, 64 | { 65 | "id": "Settings", 66 | "message": "Settings", 67 | "translation": "Настройки" 68 | }, 69 | { 70 | "id": "Light theme", 71 | "message": "Light theme", 72 | "translation": "Светлая тема" 73 | }, 74 | { 75 | "id": "Notifications", 76 | "message": "Notifications", 77 | "translation": "Уведомления" 78 | }, 79 | { 80 | "id": "Start on start", 81 | "message": "Start on start", 82 | "translation": "Запускать на старте" 83 | }, 84 | { 85 | "id": "Stop on exit", 86 | "message": "Stop on exit", 87 | "translation": "Остановить при выходе" 88 | }, 89 | { 90 | "id": "Help", 91 | "message": "Help", 92 | "translation": "Помощь" 93 | }, 94 | { 95 | "id": "About", 96 | "message": "About", 97 | "translation": "Об индикаторе" 98 | }, 99 | { 100 | "id": "Donations", 101 | "message": "Donations", 102 | "translation": "Пожертвования" 103 | }, 104 | { 105 | "id": "Quit", 106 | "message": "Quit", 107 | "translation": "Выход" 108 | }, 109 | { 110 | "id": "Notification service unavailable!", 111 | "message": "Notification service unavailable!", 112 | "translation": "Сервис уведомлений недоступен!" 113 | }, 114 | { 115 | "id": "Yandex.Disk daemon output", 116 | "message": "Yandex.Disk daemon output", 117 | "translation": "Вывод утилиты Yandex.Disk" 118 | }, 119 | { 120 | "id": [ 121 | "about", 122 | "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3" 123 | ], 124 | "message": "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3", 125 | "translation": "yd-go это индикатор панели для утилиты Yandex.Disk.\n\n\tВерсия: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tЛицензия: GPL v.3", 126 | "placeholders": [ 127 | { 128 | "id": "Version", 129 | "string": "%[1]s", 130 | "type": "string", 131 | "underlyingType": "string", 132 | "argNum": 1, 133 | "expr": "version" 134 | }, 135 | { 136 | "id": "Format2006", 137 | "string": "%[2]s", 138 | "type": "string", 139 | "underlyingType": "string", 140 | "argNum": 2, 141 | "expr": "time.Now().Format(\"2006\")" 142 | } 143 | ] 144 | }, 145 | { 146 | "id": "Status: {St}", 147 | "message": "Status: {St}", 148 | "translation": "Статус: %[1]s", 149 | "placeholders": [ 150 | { 151 | "id": "St", 152 | "string": "%[1]s", 153 | "type": "string", 154 | "underlyingType": "string", 155 | "argNum": 1, 156 | "expr": "st" 157 | } 158 | ] 159 | }, 160 | { 161 | "id": "Used: {Used}/{Total}", 162 | "message": "Used: {Used}/{Total}", 163 | "translation": "Использовано: %[1]s/%[2]s", 164 | "placeholders": [ 165 | { 166 | "id": "Used", 167 | "string": "%[1]s", 168 | "type": "string", 169 | "underlyingType": "string", 170 | "argNum": 1, 171 | "expr": "yds.Used" 172 | }, 173 | { 174 | "id": "Total", 175 | "string": "%[2]s", 176 | "type": "string", 177 | "underlyingType": "string", 178 | "argNum": 2, 179 | "expr": "yds.Total" 180 | } 181 | ] 182 | }, 183 | { 184 | "id": "Free: {Free} Trash: {Trash}", 185 | "message": "Free: {Free} Trash: {Trash}", 186 | "translation": "Свободно: %[1]s Корзина: %[2]s", 187 | "placeholders": [ 188 | { 189 | "id": "Free", 190 | "string": "%[1]s", 191 | "type": "string", 192 | "underlyingType": "string", 193 | "argNum": 1, 194 | "expr": "yds.Free" 195 | }, 196 | { 197 | "id": "Trash", 198 | "string": "%[2]s", 199 | "type": "string", 200 | "underlyingType": "string", 201 | "argNum": 2, 202 | "expr": "yds.Trash" 203 | } 204 | ] 205 | }, 206 | { 207 | "id": "Daemon stopped", 208 | "message": "Daemon stopped", 209 | "translation": "Утилита остановлена" 210 | }, 211 | { 212 | "id": "Daemon started", 213 | "message": "Daemon started", 214 | "translation": "Утилита запущена" 215 | }, 216 | { 217 | "id": "Synchronization started", 218 | "message": "Synchronization started", 219 | "translation": "Синхронизация начата" 220 | }, 221 | { 222 | "id": "Synchronization finished", 223 | "message": "Synchronization finished", 224 | "translation": "Синхронизация закончена" 225 | } 226 | ] 227 | } 228 | -------------------------------------------------------------------------------- /ydisk/ydisk_test.go: -------------------------------------------------------------------------------- 1 | package ydisk 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log/slog" 7 | "os" 8 | "os/exec" 9 | "path" 10 | "path/filepath" 11 | "testing" 12 | "time" 13 | 14 | "github.com/stretchr/testify/require" 15 | ) 16 | 17 | var ( 18 | Cfg, CfgPath, SyncDir, SymExe string 19 | YD *YDisk 20 | ) 21 | 22 | const ( 23 | SyncDirPath = "$HOME/TeSt_Yandex.Disk_TeSt" 24 | ConfigFilePath = "$HOME/.config/TeSt_Yandex.Disk_TeSt" 25 | ) 26 | 27 | func TestMain(m *testing.M) { 28 | flag.Parse() 29 | 30 | // Initialization 31 | CfgPath = os.ExpandEnv(ConfigFilePath) 32 | Cfg = filepath.Join(CfgPath, "config.cfg") 33 | SyncDir = os.ExpandEnv(SyncDirPath) 34 | os.Setenv("Sim_SyncDir", SyncDir) 35 | os.Setenv("Sim_ConfDir", CfgPath) 36 | err := os.MkdirAll(CfgPath, 0755) 37 | if err != nil { 38 | fmt.Printf("Path '%s' creation error: %v\n", CfgPath, err) 39 | os.Exit(1) 40 | } 41 | 42 | SymExe, err = exec.LookPath("yandex-disk") 43 | if err != nil { 44 | fmt.Printf("yandex-disk utility lookup error: %v\n", err) 45 | os.Exit(1) 46 | } 47 | 48 | exec.Command(SymExe, "stop").Run() 49 | os.RemoveAll(path.Join(os.TempDir(), "yandexdisksimulator.socket")) 50 | fmt.Printf("Tests init completed: yd exe: %v\n", SymExe) 51 | 52 | // Run tests 53 | e := m.Run() 54 | 55 | // Clearance 56 | exec.Command(SymExe, "stop").Run() 57 | os.RemoveAll(path.Join(os.TempDir(), "yandexdisksimulator.socket")) 58 | os.RemoveAll(CfgPath) 59 | os.RemoveAll(SyncDir) 60 | fmt.Println("Tests clearance completed") 61 | os.Exit(e) 62 | } 63 | 64 | func TestNotInstalled(t *testing.T) { 65 | t.Setenv("PATH", "") 66 | // test not_installed case 67 | yd, err := NewYDisk(Cfg, slog.Default()) 68 | require.Error(t, err) 69 | require.Nil(t, yd) 70 | } 71 | 72 | func TestWrongConf(t *testing.T) { 73 | // test initialization with wrong/not-existing config 74 | yd, err := NewYDisk(Cfg+"_bad", slog.Default()) 75 | require.Error(t, err) 76 | require.Nil(t, yd) 77 | } 78 | 79 | func TestEmptyConf(t *testing.T) { 80 | // test initialization with empty config 81 | file, err := os.OpenFile(Cfg, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0666) 82 | require.NoError(t, err) 83 | defer file.Close() 84 | _, err = file.Write([]byte("Dir=\"no_dir\"\n\nproxy=\"no\"\n")) 85 | require.NoError(t, err) 86 | file.Close() 87 | defer os.Remove(Cfg) 88 | _, err = NewYDisk(Cfg, slog.Default()) 89 | require.Error(t, err) 90 | } 91 | 92 | func TestFull(t *testing.T) { 93 | // prepare for simulation 94 | err := exec.Command(SymExe, "setup").Run() 95 | require.NoError(t, err) 96 | var yds YDvals 97 | log := slog.Default() 98 | // logLevel := new(slog.LevelVar) 99 | // logLevel.Set(slog.LevelDebug) 100 | // log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})) 101 | YD, err = NewYDisk(Cfg, log) 102 | require.NoError(t, err) 103 | 104 | t.Run("NotStartedOutput", func(t *testing.T) { 105 | output := YD.Output() 106 | require.Empty(t, output) 107 | }) 108 | 109 | t.Run("InitialEvent", func(t *testing.T) { 110 | require.Eventually(t, func() bool { 111 | select { 112 | case yds = <-YD.Changes: 113 | require.Equal(t, "{none unknown [] true }", fmt.Sprintf("%v", yds)) 114 | return true 115 | default: 116 | return false 117 | } 118 | }, time.Second, 100*time.Millisecond) 119 | }) 120 | 121 | t.Run("Start", func(t *testing.T) { 122 | err = YD.Start() 123 | require.NoError(t, err) 124 | require.Eventually(t, func() bool { 125 | select { 126 | case yds = <-YD.Changes: 127 | require.Equal(t, "{paused none [File.ods downloads/file.deb downloads/setup download down do_it very_very_long_long_file_with_underscore o w n] true }", fmt.Sprintf("%v", yds)) 128 | return true 129 | default: 130 | return false 131 | } 132 | }, time.Second*3, 300*time.Microsecond) 133 | }) 134 | 135 | t.Run("OutputStarted", func(t *testing.T) { 136 | output := YD.Output() 137 | require.NotEmpty(t, output) 138 | }) 139 | 140 | t.Run("Start2Idle", func(t *testing.T) { 141 | require.Eventually(t, func() bool { 142 | select { 143 | case yds = <-YD.Changes: 144 | if yds.Stat != "idle" { 145 | return false 146 | } 147 | require.Equal(t, "{idle index 43.50 GB 2.89 GB 40.61 GB 0 B [File.ods downloads/file.deb downloads/setup download down do_it very_very_long_long_file_with_underscore o w n] false }", fmt.Sprintf("%v", yds)) 148 | return true 149 | default: 150 | return false 151 | } 152 | }, 30*time.Second, time.Second) 153 | }) 154 | 155 | t.Run("SecondaryStart", func(t *testing.T) { 156 | err := YD.Start() 157 | require.NoError(t, err) 158 | select { 159 | case <-YD.Changes: 160 | t.Error("Event received within 3 sec interval after secondary start of daemon") 161 | case <-time.After(time.Second * 3): 162 | } 163 | }) 164 | 165 | t.Run("Sync", func(t *testing.T) { 166 | err = exec.Command("yandex-disk", "sync").Run() 167 | require.NoError(t, err) 168 | select { 169 | case yds = <-YD.Changes: 170 | require.Equal(t, 171 | "{index idle 43.50 GB 2.89 GB 40.61 GB 0 B [File.ods downloads/file.deb downloads/setup download down do_it very_very_long_long_file_with_underscore o w n] false }", 172 | fmt.Sprintf("%v", yds)) 173 | case <-time.After(2 * time.Second): 174 | t.Fatal("no event for 2 seconds after sync command") 175 | } 176 | }) 177 | 178 | t.Run("Busy2Idle", func(t *testing.T) { 179 | require.Eventually(t, func() bool { 180 | select { 181 | case yds = <-YD.Changes: 182 | if yds.Stat != "idle" { 183 | return false 184 | } 185 | require.Equal(t, 186 | "{idle index 43.50 GB 2.89 GB 40.61 GB 0 B [File.ods downloads/file.deb downloads/setup download down do_it very_very_long_long_file_with_underscore o w n] true }", 187 | fmt.Sprintf("%v", yds)) 188 | return true 189 | } 190 | }, 10*time.Second, time.Second) 191 | }) 192 | 193 | t.Run("Error", func(t *testing.T) { 194 | require.NoError(t, exec.Command("yandex-disk", "error").Run()) 195 | require.Eventually(t, func() bool { 196 | select { 197 | case yds = <-YD.Changes: 198 | if yds.Stat != "error" { 199 | return false 200 | } 201 | require.Equal(t, 202 | "{error idle 43.50 GB 2.88 GB 40.62 GB 654.48 MB [File.ods downloads/file.deb downloads/setup download down do_it very_very_long_long_file_with_underscore o w n] false access error downloads/test1 }", 203 | fmt.Sprintf("%v", yds)) 204 | return true 205 | default: 206 | return false 207 | } 208 | 209 | }, 2*time.Second, 200*time.Millisecond) 210 | }) 211 | t.Run("Error2Idle", func(t *testing.T) { 212 | require.Eventually(t, func() bool { 213 | select { 214 | case yds = <-YD.Changes: 215 | if yds.Stat != "idle" { 216 | return false 217 | } 218 | require.Equal(t, 219 | "{idle error 43.50 GB 2.89 GB 40.61 GB 0 B [File.ods downloads/file.deb downloads/setup download down do_it very_very_long_long_file_with_underscore o w n] false }", 220 | fmt.Sprintf("%v", yds)) 221 | return true 222 | } 223 | }, 10*time.Second, time.Second) 224 | }) 225 | 226 | t.Run("Stop", func(t *testing.T) { 227 | require.NoError(t, YD.Stop()) 228 | require.Eventually(t, func() bool { 229 | select { 230 | case yds = <-YD.Changes: 231 | if yds.Stat != "none" { 232 | return false 233 | } 234 | require.Equal(t, "{none idle [] true }", fmt.Sprintf("%v", yds)) 235 | return true 236 | default: 237 | return false 238 | } 239 | }, 3*time.Second, 300*time.Millisecond) 240 | }) 241 | 242 | t.Run("SecondaryStop", func(t *testing.T) { 243 | require.NoError(t, YD.Stop()) 244 | require.Never(t, func() bool { 245 | select { 246 | case <-YD.Changes: 247 | return true 248 | default: 249 | return false 250 | } 251 | }, 3*time.Second, 300*time.Millisecond) 252 | }) 253 | 254 | t.Run("Close", func(t *testing.T) { 255 | YD.Close() 256 | require.Eventually(t, func() bool { 257 | select { 258 | case _, ok := <-YD.Changes: 259 | require.False(t, ok) 260 | return true 261 | default: 262 | return false 263 | } 264 | }, time.Second, 100*time.Millisecond) 265 | }) 266 | } 267 | -------------------------------------------------------------------------------- /ydisk/ydisk_bench_test.go: -------------------------------------------------------------------------------- 1 | package ydisk 2 | 3 | import ( 4 | "bytes" 5 | "os/exec" 6 | "regexp" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | var ( 14 | rPar = regexp.MustCompile(`\s*(.*): '?(.*?)'?\n`) 15 | rList = regexp.MustCompile(`: '(.*)'\n`) 16 | st1 = "Sync progress: 139.38 MB/ 139.38 MB (100 %)\nSynchronization core status: index\nPath to Yandex.Disk directory: '/home/stc/Yandex.Disk'\n\tTotal: 43.50 GB\n\tUsed: 2.89 GB\n\tAvailable: 40.61 GB\n\tMax file size: 50 GB\n\tTrash size: 0 B\n\nLast synchronized items:\n\tfile: 'NewFile'\n\tfile: 'File.ods'\n\tfile: 'downloads/file.deb'\n\tfile: 'downloads/setup'\n\tfile: 'download'\n\tfile: 'down'\n\tfile: 'do'\n\tfile: 'd'\n\tfile: 'o'\n\tfile: 'w'\n\n" 17 | st2 = "Synchronization core status: idle\nPath to Yandex.Disk directory: '/home/stc/Yandex.Disk'\n\tTotal: 43.50 GB\n\tUsed: 2.89 GB\n\tAvailable: 40.61 GB\n\tMax file size: 50 GB\n\tTrash size: 0 B\n\nLast synchronized items:\n\tfile: 'File.ods'\n\tfile: 'downloads/file.deb'\n\tfile: 'downloads/setup'\n\tfile: 'download'\n\tfile: 'down'\n\tfile: 'do'\n\tfile: 'd'\n\tfile: 'o'\n\tfile: 'w'\n\tfile: 'n'\n\n" 18 | ) 19 | 20 | func BenchmarkYDvalUpdateString(b *testing.B) { 21 | yd := newYDvals() 22 | for b.Loop() { 23 | yd.update(st1) 24 | yd.update(st2) 25 | } 26 | } 27 | func BenchmarkYDvalUpdatePreComp(b *testing.B) { 28 | yd := newYDvals() 29 | for b.Loop() { 30 | yd.update1(st1) 31 | yd.update1(st2) 32 | } 33 | } 34 | 35 | func BenchmarkYDvalUpdateOrig(b *testing.B) { 36 | yd := newYDvals() 37 | for b.Loop() { 38 | yd.update2(st1) 39 | yd.update2(st2) 40 | } 41 | } 42 | 43 | // func BenchmarkYDiskGetOutput(b *testing.B) { 44 | // // prepare for simulation 45 | // err := exec.Command(SymExe, "setup").Run() 46 | // if err != nil { 47 | // b.Fatal("simulation prepare error") 48 | // } 49 | // out, err := exec.Command(SymExe, "start").Output() 50 | // if err != nil { 51 | // b.Fatal("simulation prepare error " + SymExe + err.Error() + string(out)) 52 | // } 53 | // <-time.After(time.Second) 54 | // defer func() { 55 | // err := exec.Command(SymExe, "stop").Run() 56 | // if err != nil { 57 | // b.Fatal("simulation prepare error " + SymExe + err.Error() + string(out)) 58 | // } 59 | // }() 60 | 61 | // for range b.N { 62 | // st, err := exec.Command(SymExe, "status").Output() 63 | // if err != nil { 64 | // b.Fatal("simulation prepare error " + SymExe + err.Error()) 65 | // } 66 | // if len(st) == 0 { 67 | // b.Fatal("simulation error: empty output") 68 | // } 69 | 70 | // } 71 | // } 72 | 73 | // func BenchmarkYDiskGetOutput2(b *testing.B) { 74 | // // prepare for simulation 75 | // err := exec.Command(SymExe, "setup").Run() 76 | // if err != nil { 77 | // b.Fatal("simulation prepare error") 78 | // } 79 | // out, err := exec.Command(SymExe, "start").Output() 80 | // if err != nil { 81 | // b.Fatal("simulation prepare error " + SymExe + err.Error() + string(out)) 82 | // } 83 | // defer func() { 84 | // err := exec.Command(SymExe, "stop").Run() 85 | // if err != nil { 86 | // b.Fatal("simulation stop error " + err.Error()) 87 | // } 88 | // }() 89 | 90 | // for range b.N { 91 | // c := exec.Command(SymExe, "status") 92 | // var stdout bytes.Buffer 93 | // //stdout.Grow(256) 94 | // c.Stdout = &stdout 95 | // err := c.Run() 96 | // st := stdout.Bytes() 97 | // if err != nil || len(st) == 0 { 98 | // b.Error(err) 99 | // } 100 | // } 101 | // } 102 | 103 | func BenchmarkEchoCmdOutput(b *testing.B) { 104 | for b.Loop() { 105 | st, err := exec.Command("echo", "test").Output() 106 | if err != nil || len(st) == 0 { 107 | b.Error(err) 108 | } 109 | } 110 | } 111 | 112 | func BenchmarkEchoCmdOutput2(b *testing.B) { 113 | for b.Loop() { 114 | c := exec.Command("echo", "test") 115 | var stdout bytes.Buffer 116 | c.Stdout = &stdout 117 | err := c.Run() 118 | st := stdout.Bytes() 119 | if err != nil || len(st) == 0 { 120 | b.Error(err) 121 | } 122 | } 123 | } 124 | 125 | func setChanged1(v *string, val string, c *bool) { 126 | *c = *c || *v != val 127 | *v = val 128 | } 129 | 130 | func TestSetChanged1(t *testing.T) { 131 | a := "none" 132 | c := false 133 | setChanged(&a, "idle", &c) 134 | require.True(t, c) 135 | require.Equal(t, "idle", a) 136 | b := "none" 137 | d := false 138 | setChanged1(&b, "idle", &d) 139 | require.Equal(t, a, b) 140 | require.Equal(t, c, d) 141 | c = false 142 | d = false 143 | setChanged(&a, "idle", &c) 144 | setChanged1(&b, "idle", &d) 145 | require.False(t, c) 146 | require.Equal(t, a, b) 147 | require.Equal(t, c, d) 148 | } 149 | 150 | func testChangedFunc(f func(v *string, val string, c *bool)) { 151 | a := "none" 152 | c := false 153 | f(&a, "idle", &c) 154 | f(&a, "idle", &c) 155 | f(&a, "none", &c) 156 | f(&a, "none", &c) 157 | f(&a, "idle", &c) 158 | f(&a, "idle", &c) 159 | f(&a, "none", &c) 160 | f(&a, "none", &c) 161 | f(&a, "idle", &c) 162 | f(&a, "idle", &c) 163 | } 164 | 165 | func BenchmarkSetChanged(b *testing.B) { 166 | for b.Loop() { 167 | testChangedFunc(setChanged) 168 | } 169 | } 170 | 171 | func BenchmarkSetChanged1(b *testing.B) { 172 | for b.Loop() { 173 | testChangedFunc(setChanged1) 174 | } 175 | } 176 | 177 | // update2 is original version with strings and not compiled regexp 178 | func (val *YDvals) update2(out string) bool { 179 | val.Prev = val.Stat // store previous status but don't track changes of val.Prev 180 | changed := false // track changes for values 181 | if out == "" { 182 | setChanged(&val.Stat, "none", &changed) 183 | if changed { 184 | val.Total, val.Used, val.Trash, val.Free = "", "", "", "" 185 | val.Prog, val.Err, val.ErrP, val.ChLast = "", "", "", true 186 | val.Last = []string{} 187 | } 188 | return changed 189 | } 190 | split := strings.Split(out, "Last synchronized items:") 191 | // Need to remove "Path to " as another "Path:" exists in case of access error 192 | split[0] = strings.Replace(split[0], "Path to ", "", 1) 193 | // Initialize map with keys that can be missed 194 | keys := map[string]string{"Sync": "", "Error": "", "Path": ""} 195 | // Take only first word in the phrase before ":" 196 | for _, s := range regexp.MustCompile(`\s*([^ ]+).*: (.*)`).FindAllStringSubmatch(split[0], -1) { 197 | if s[2][0] == byte('\'') { 198 | s[2] = s[2][1 : len(s[2])-1] // remove ' in the begging and at end 199 | } 200 | keys[s[1]] = s[2] 201 | } 202 | // map representation of switch_case clause 203 | for k, v := range map[string]*string{ 204 | "Synchronization": &val.Stat, 205 | "Total": &val.Total, 206 | "Used": &val.Used, 207 | "Available": &val.Free, 208 | "Trash": &val.Trash, 209 | "Error": &val.Err, 210 | "Path": &val.ErrP, 211 | "Sync": &val.Prog, 212 | } { 213 | setChanged(v, keys[k], &changed) 214 | } 215 | // Parse the "Last synchronized items" section (list of paths and files) 216 | val.ChLast = false // track last list changes separately 217 | if len(split) > 1 { 218 | f := regexp.MustCompile(`: '(.*)'\n`).FindAllStringSubmatch(split[1], -1) 219 | if len(f) != len(val.Last) { 220 | val.ChLast = true 221 | val.Last = []string{} 222 | for _, p := range f { 223 | val.Last = append(val.Last, p[1]) 224 | } 225 | } else { 226 | for i, p := range f { 227 | setChanged(&val.Last[i], p[1], &val.ChLast) 228 | } 229 | } 230 | } else { // len(split) = 1 - there is no section with last sync. paths 231 | if len(val.Last) > 0 { 232 | val.Last = []string{} 233 | val.ChLast = true 234 | } 235 | } 236 | return changed || val.ChLast 237 | } 238 | 239 | // update1 used precompiled regexps 240 | func (val *YDvals) update1(out string) bool { 241 | val.Prev = val.Stat // store previous status but don't track changes of val.Prev 242 | changed := false // track changes for values 243 | if out == "" { 244 | setChanged(&val.Stat, "none", &changed) 245 | if changed { 246 | val.Total, val.Used, val.Trash, val.Free = "", "", "", "" 247 | val.Prog, val.Err, val.ErrP, val.ChLast = "", "", "", true 248 | val.Last = []string{} 249 | } 250 | return changed 251 | } 252 | split := strings.Split(out, "Last synchronized items:") 253 | // Initialize map with keys that can be missed 254 | keys := map[string]string{"Sync progress": "", "Error": "", "Path": ""} 255 | for _, s := range rPar.FindAllStringSubmatch(split[0], -1) { 256 | keys[s[1]] = s[2] 257 | } 258 | for k, v := range keys { 259 | switch k { 260 | case "Synchronization core status": 261 | setChanged(&val.Stat, v, &changed) 262 | case "Total": 263 | setChanged(&val.Total, v, &changed) 264 | case "Used": 265 | setChanged(&val.Used, v, &changed) 266 | case "Available": 267 | setChanged(&val.Free, v, &changed) 268 | case "Trash size": 269 | setChanged(&val.Trash, v, &changed) 270 | case "Error": 271 | setChanged(&val.Err, v, &changed) 272 | case "Path": 273 | if v != "" { 274 | setChanged(&val.ErrP, v[1:len(v)-1], &changed) 275 | } else { 276 | setChanged(&val.ErrP, "", &changed) 277 | } 278 | case "Sync progress": 279 | setChanged(&val.Prog, v, &changed) 280 | } 281 | } 282 | // Parse the "Last synchronized items" section (list of paths and files) 283 | val.ChLast = false // track last list changes separately 284 | if len(split) > 1 { 285 | f := rList.FindAllStringSubmatch(split[1], -1) 286 | if len(f) != len(val.Last) { 287 | val.ChLast = true 288 | val.Last = []string{} 289 | for _, p := range f { 290 | val.Last = append(val.Last, p[1]) 291 | } 292 | } else { 293 | for i, p := range f { 294 | setChanged(&val.Last[i], p[1], &val.ChLast) 295 | } 296 | } 297 | } else { // len(split) = 1 - there is no section with last sync. paths 298 | if len(val.Last) > 0 { 299 | val.Last = []string{} 300 | val.ChLast = true 301 | } 302 | } 303 | return changed || val.ChLast 304 | } 305 | -------------------------------------------------------------------------------- /locales/en-US/out.gotext.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "en-US", 3 | "messages": [ 4 | { 5 | "id": "Yandex.Disk indicator", 6 | "message": "Yandex.Disk indicator", 7 | "translation": "Yandex.Disk indicator", 8 | "translatorComment": "Copied from source.", 9 | "fuzzy": true 10 | }, 11 | { 12 | "id": "idle", 13 | "message": "idle", 14 | "translation": "idle", 15 | "translatorComment": "Copied from source.", 16 | "fuzzy": true 17 | }, 18 | { 19 | "id": "index", 20 | "message": "index", 21 | "translation": "index", 22 | "translatorComment": "Copied from source.", 23 | "fuzzy": true 24 | }, 25 | { 26 | "id": "busy", 27 | "message": "busy", 28 | "translation": "busy", 29 | "translatorComment": "Copied from source.", 30 | "fuzzy": true 31 | }, 32 | { 33 | "id": "none", 34 | "message": "none", 35 | "translation": "none", 36 | "translatorComment": "Copied from source.", 37 | "fuzzy": true 38 | }, 39 | { 40 | "id": "paused", 41 | "message": "paused", 42 | "translation": "paused", 43 | "translatorComment": "Copied from source.", 44 | "fuzzy": true 45 | }, 46 | { 47 | "id": "Last synchronized", 48 | "message": "Last synchronized", 49 | "translation": "Last synchronized", 50 | "translatorComment": "Copied from source.", 51 | "fuzzy": true 52 | }, 53 | { 54 | "id": "Start daemon", 55 | "message": "Start daemon", 56 | "translation": "Start daemon", 57 | "translatorComment": "Copied from source.", 58 | "fuzzy": true 59 | }, 60 | { 61 | "id": "Stop daemon", 62 | "message": "Stop daemon", 63 | "translation": "Stop daemon", 64 | "translatorComment": "Copied from source.", 65 | "fuzzy": true 66 | }, 67 | { 68 | "id": "Show daemon output", 69 | "message": "Show daemon output", 70 | "translation": "Show daemon output", 71 | "translatorComment": "Copied from source.", 72 | "fuzzy": true 73 | }, 74 | { 75 | "id": "Open Yandex.Disk folder", 76 | "message": "Open Yandex.Disk folder", 77 | "translation": "Open Yandex.Disk folder", 78 | "translatorComment": "Copied from source.", 79 | "fuzzy": true 80 | }, 81 | { 82 | "id": "Open Yandex.Disk in browser", 83 | "message": "Open Yandex.Disk in browser", 84 | "translation": "Open Yandex.Disk in browser", 85 | "translatorComment": "Copied from source.", 86 | "fuzzy": true 87 | }, 88 | { 89 | "id": "Settings", 90 | "message": "Settings", 91 | "translation": "Settings", 92 | "translatorComment": "Copied from source.", 93 | "fuzzy": true 94 | }, 95 | { 96 | "id": "Light theme", 97 | "message": "Light theme", 98 | "translation": "Light theme", 99 | "translatorComment": "Copied from source.", 100 | "fuzzy": true 101 | }, 102 | { 103 | "id": "Notifications", 104 | "message": "Notifications", 105 | "translation": "Notifications", 106 | "translatorComment": "Copied from source.", 107 | "fuzzy": true 108 | }, 109 | { 110 | "id": "Start on start", 111 | "message": "Start on start", 112 | "translation": "Start on start", 113 | "translatorComment": "Copied from source.", 114 | "fuzzy": true 115 | }, 116 | { 117 | "id": "Stop on exit", 118 | "message": "Stop on exit", 119 | "translation": "Stop on exit", 120 | "translatorComment": "Copied from source.", 121 | "fuzzy": true 122 | }, 123 | { 124 | "id": "Help", 125 | "message": "Help", 126 | "translation": "Help", 127 | "translatorComment": "Copied from source.", 128 | "fuzzy": true 129 | }, 130 | { 131 | "id": "About", 132 | "message": "About", 133 | "translation": "About", 134 | "translatorComment": "Copied from source.", 135 | "fuzzy": true 136 | }, 137 | { 138 | "id": "Donations", 139 | "message": "Donations", 140 | "translation": "Donations", 141 | "translatorComment": "Copied from source.", 142 | "fuzzy": true 143 | }, 144 | { 145 | "id": "Quit", 146 | "message": "Quit", 147 | "translation": "Quit", 148 | "translatorComment": "Copied from source.", 149 | "fuzzy": true 150 | }, 151 | { 152 | "id": "Notification service unavailable!", 153 | "message": "Notification service unavailable!", 154 | "translation": "Notification service unavailable!", 155 | "translatorComment": "Copied from source.", 156 | "fuzzy": true 157 | }, 158 | { 159 | "id": "Yandex.Disk daemon output", 160 | "message": "Yandex.Disk daemon output", 161 | "translation": "Yandex.Disk daemon output", 162 | "translatorComment": "Copied from source.", 163 | "fuzzy": true 164 | }, 165 | { 166 | "id": [ 167 | "about", 168 | "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3" 169 | ], 170 | "message": "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3", 171 | "translation": "yd-go is the panel indicator for Yandex.Disk daemon.\n\n\tVersion: {Version}\n\nCopyleft 2017-{Format2006} Sly_tom_cat (slytomcat@mail.ru)\n\n\tLicense: GPL v.3", 172 | "translatorComment": "Copied from source.", 173 | "placeholders": [ 174 | { 175 | "id": "Version", 176 | "string": "%[1]s", 177 | "type": "string", 178 | "underlyingType": "string", 179 | "argNum": 1, 180 | "expr": "version" 181 | }, 182 | { 183 | "id": "Format2006", 184 | "string": "%[2]s", 185 | "type": "string", 186 | "underlyingType": "string", 187 | "argNum": 2, 188 | "expr": "time.Now().Format(\"2006\")" 189 | } 190 | ], 191 | "fuzzy": true 192 | }, 193 | { 194 | "id": "Status: {St}", 195 | "message": "Status: {St}", 196 | "translation": "Status: {St}", 197 | "translatorComment": "Copied from source.", 198 | "placeholders": [ 199 | { 200 | "id": "St", 201 | "string": "%[1]s", 202 | "type": "string", 203 | "underlyingType": "string", 204 | "argNum": 1, 205 | "expr": "st" 206 | } 207 | ], 208 | "fuzzy": true 209 | }, 210 | { 211 | "id": "Used: {Used}/{Total}", 212 | "message": "Used: {Used}/{Total}", 213 | "translation": "Used: {Used}/{Total}", 214 | "translatorComment": "Copied from source.", 215 | "placeholders": [ 216 | { 217 | "id": "Used", 218 | "string": "%[1]s", 219 | "type": "string", 220 | "underlyingType": "string", 221 | "argNum": 1, 222 | "expr": "yds.Used" 223 | }, 224 | { 225 | "id": "Total", 226 | "string": "%[2]s", 227 | "type": "string", 228 | "underlyingType": "string", 229 | "argNum": 2, 230 | "expr": "yds.Total" 231 | } 232 | ], 233 | "fuzzy": true 234 | }, 235 | { 236 | "id": "Free: {Free} Trash: {Trash}", 237 | "message": "Free: {Free} Trash: {Trash}", 238 | "translation": "Free: {Free} Trash: {Trash}", 239 | "translatorComment": "Copied from source.", 240 | "placeholders": [ 241 | { 242 | "id": "Free", 243 | "string": "%[1]s", 244 | "type": "string", 245 | "underlyingType": "string", 246 | "argNum": 1, 247 | "expr": "yds.Free" 248 | }, 249 | { 250 | "id": "Trash", 251 | "string": "%[2]s", 252 | "type": "string", 253 | "underlyingType": "string", 254 | "argNum": 2, 255 | "expr": "yds.Trash" 256 | } 257 | ], 258 | "fuzzy": true 259 | }, 260 | { 261 | "id": "Daemon stopped", 262 | "message": "Daemon stopped", 263 | "translation": "Daemon stopped", 264 | "translatorComment": "Copied from source.", 265 | "fuzzy": true 266 | }, 267 | { 268 | "id": "Daemon started", 269 | "message": "Daemon started", 270 | "translation": "Daemon started", 271 | "translatorComment": "Copied from source.", 272 | "fuzzy": true 273 | }, 274 | { 275 | "id": "Synchronization started", 276 | "message": "Synchronization started", 277 | "translation": "Synchronization started", 278 | "translatorComment": "Copied from source.", 279 | "fuzzy": true 280 | }, 281 | { 282 | "id": "Synchronization finished", 283 | "message": "Synchronization finished", 284 | "translation": "Synchronization finished", 285 | "translatorComment": "Copied from source.", 286 | "fuzzy": true 287 | } 288 | ] 289 | } -------------------------------------------------------------------------------- /ydisk/ydisk.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package ydisk implements API for yandex-disk daemon. Logging is organized 3 | via github.com/slytomcat/llog package. 4 | */ 5 | package ydisk 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "log/slog" 11 | "os" 12 | "os/exec" 13 | "path/filepath" 14 | "strings" 15 | "time" 16 | "unicode" 17 | 18 | "github.com/fsnotify/fsnotify" 19 | ) 20 | 21 | var log *slog.Logger 22 | 23 | // YDvals - Daemon Status structure 24 | type YDvals struct { 25 | Stat string // Current Status 26 | Prev string // Previous Status 27 | Total string // Total space available 28 | Used string // Used space 29 | Free string // Free space 30 | Trash string // Trash size 31 | Last []string // Last-updated files/folders list (10 or less items) 32 | ChLast bool // Indicator that Last was changed 33 | Err string // Error status message 34 | ErrP string // Error path 35 | Prog string // Synchronization progress (when in busy status) 36 | } 37 | 38 | // A new YDvals constructor 39 | func newYDvals() YDvals { 40 | return YDvals{ 41 | Stat: "unknown", 42 | Prev: "unknown", 43 | Total: "", 44 | Used: "", 45 | Free: "", 46 | Trash: "", 47 | Last: []string{}, 48 | ChLast: true, 49 | Err: "", 50 | ErrP: "", 51 | Prog: "", 52 | } 53 | } 54 | 55 | // Tool function that controls the change of value in variable 56 | func setChanged(v *string, val string, c *bool) { 57 | if *v != val { 58 | *v = val 59 | *c = true 60 | } 61 | } 62 | 63 | // update - Updates Daemon status values from the daemon output string. 64 | // Returns true if a change detected in any value, otherwise returns false. 65 | // It uses only strings operation for parsing. 66 | func (val *YDvals) update(out string) bool { 67 | val.Prev = val.Stat // store previous status but don't track changes of val.Prev 68 | changed := false // track changes for values 69 | if out == "" { 70 | if setChanged(&val.Stat, "none", &changed); changed { 71 | val.Total, val.Used, val.Trash, val.Free = "", "", "", "" 72 | val.Prog, val.Err, val.ErrP, val.ChLast = "", "", "", true 73 | val.Last = []string{} 74 | } 75 | return changed 76 | } 77 | n := strings.Index(out, "Last synchronized items:") 78 | val.ChLast = false // track last list changes separately 79 | if n > 0 { 80 | // Parse the "Last synchronized items" section (list of paths and files) 81 | f := make([]string, 0, 10) 82 | files := out[n+24:] 83 | for { 84 | if p := strings.Index(files, "\n"); p < 0 { 85 | break 86 | } else { 87 | if p > 8 { 88 | f = append(f, files[strings.Index(files, ":")+3:p-1]) 89 | } 90 | files = files[p+len("\n"):] 91 | } 92 | } 93 | if len(f) != len(val.Last) { 94 | val.ChLast = true 95 | val.Last = f 96 | } else { 97 | for i, p := range f { 98 | setChanged(&val.Last[i], p, &val.ChLast) 99 | } 100 | } 101 | } else { // There is no "Last synchronized items" section 102 | n = len(out) 103 | if len(val.Last) > 0 { 104 | val.Last = []string{} 105 | val.ChLast = true 106 | } 107 | } 108 | // Parse disk values and status 109 | // Initialize map with keys that can be missed 110 | keys := make(map[string]string, 11) 111 | keys["Sync progress"] = "" 112 | keys["Error"] = "" 113 | keys["Path"] = "" 114 | vals := out[:n] 115 | for { 116 | if p := strings.Index(vals, "\n"); p < 0 { 117 | break 118 | } else { 119 | if n := strings.Index(vals[:p], ":"); n > 0 { 120 | keys[strings.TrimLeftFunc(vals[:n], unicode.IsSpace)] = vals[n+2 : p] 121 | } 122 | vals = vals[p+1:] 123 | } 124 | } 125 | for k, v := range keys { 126 | switch k { 127 | case "Synchronization core status": 128 | setChanged(&val.Stat, v, &changed) 129 | case "Total": 130 | setChanged(&val.Total, v, &changed) 131 | case "Used": 132 | setChanged(&val.Used, v, &changed) 133 | case "Available": 134 | setChanged(&val.Free, v, &changed) 135 | case "Trash size": 136 | setChanged(&val.Trash, v, &changed) 137 | case "Sync progress": 138 | setChanged(&val.Prog, v, &changed) 139 | case "Error": 140 | setChanged(&val.Err, v, &changed) 141 | case "Path": 142 | if v != "" { 143 | setChanged(&val.ErrP, v[1:len(v)-1], &changed) 144 | } else { 145 | setChanged(&val.ErrP, "", &changed) 146 | } 147 | } 148 | } 149 | return changed || val.ChLast 150 | } 151 | 152 | type watcher struct { 153 | *fsnotify.Watcher 154 | active bool // Flag that means that watching path was successfully added 155 | } 156 | 157 | func newWatcher() watcher { 158 | watch, err := fsnotify.NewWatcher() 159 | if err != nil { 160 | log.Error("file_watcher", "error", err) 161 | os.Exit(1) 162 | } 163 | return watcher{ 164 | Watcher: watch, 165 | active: false, 166 | } 167 | } 168 | 169 | func (w *watcher) activate(path string) { 170 | if !w.active { 171 | path := filepath.Join(path, ".sync/cli.log") 172 | err := w.Add(path) 173 | if err != nil { 174 | log.Debug("file_watcher", "path", path, "error", err) 175 | return 176 | } 177 | log.Debug("file_watcher", "status", "added") 178 | w.active = true 179 | } 180 | } 181 | 182 | // YDisk provides methods to interact with yandex-disk (methods: Start, Stop, Output), path 183 | // of synchronized catalogue (property Path) and channel for receiving yandex-disk status 184 | // changes (property Changes). 185 | type YDisk struct { 186 | Path string // Path to synchronized folder (obtained from yandex-disk conf. file) 187 | Changes chan YDvals // Output channel for detected changes in daemon status 188 | conf string // Path to yandex-disc configuration file 189 | exe string // Path to yandex-disk executable 190 | exit chan struct{} // Stop signal/replay channel for Event handler routine 191 | activate func() // Function to activate watcher after daemon creation 192 | } 193 | 194 | // NewYDisk creates new YDisk structure for communication with yandex-disk daemon 195 | // Parameter: 196 | // 197 | // conf - full path to yandex-disk daemon configuration file 198 | // 199 | // Checks performed in the beginning: 200 | // 201 | // - check that yandex-disk was installed 202 | // - check that yandex-disk was properly configured 203 | // 204 | // When something not good NewYDisk returns not nil error 205 | func NewYDisk(conf string, logger *slog.Logger) (*YDisk, error) { 206 | log = logger 207 | exe, path, err := checkDaemon(conf) 208 | if err != nil { 209 | return nil, err 210 | } 211 | watch := newWatcher() 212 | log.Debug("yandex-disk", "executable", exe) 213 | yd := YDisk{ 214 | Path: path, 215 | Changes: make(chan YDvals, 1), // Output should be buffered 216 | conf: conf, 217 | exe: exe, 218 | exit: make(chan struct{}), 219 | activate: func() { watch.activate(path) }, 220 | } 221 | // start event handler in separate goroutine 222 | go yd.eventHandler(watch) 223 | // Try to activate watching at the beginning. It may fail but it is not a problem 224 | // as it can be activated later (on Start of daemon). 225 | yd.activate() 226 | log.Debug("YDisk", "status", "initialized", "path", path) 227 | return &yd, nil 228 | } 229 | 230 | // eventHandler works in separate goroutine until YDisk.exit channel receives a bool value (any). 231 | func (yd *YDisk) eventHandler(watch watcher) { 232 | log.Debug("daemon_event_handler", "status", "started") 233 | yds := newYDvals() 234 | interval := 1 235 | tick := time.NewTimer(time.Millisecond * 100) // First time trigger it quickly to update the current status 236 | defer func() { 237 | watch.Close() 238 | tick.Stop() 239 | close(yd.Changes) 240 | log.Debug("daemon_event_handler", "status", "exited") 241 | yd.exit <- struct{}{} // Report exit completion 242 | }() 243 | var source string 244 | for { 245 | select { 246 | case err := <-watch.Errors: 247 | log.Error("file_watcher", "error", err) 248 | return 249 | case <-yd.exit: 250 | return 251 | case <-watch.Events: 252 | source = "watcher" 253 | interval = 1 254 | case <-tick.C: 255 | source = fmt.Sprintf("timer%ds", interval) 256 | if yds.Stat == "busy" || yds.Stat == "index" { 257 | interval = 2 // keep 2s interval in busy mode 258 | } else { 259 | if interval < 32 { 260 | interval <<= 1 // continuously increase timer interval: 2s, 4s, 8s. 261 | } 262 | } 263 | } 264 | // in both cases (Timer or Watcher events): 265 | // - check for daemon changes and send changed values in case of change 266 | if yds.update(yd.getOutput(false)) { 267 | log.Debug("change", "source", source, "prev", yds.Prev, "new", yds.Stat, 268 | "S", len(yds.Total) > 0, "L", len(yds.Last), "E", len(yds.Err) > 0) 269 | yd.Changes <- yds 270 | // in case of any change reset the timer interval 271 | interval = 1 272 | } 273 | // - restart timer when daemon is running 274 | if yds.Stat != "none" { 275 | tick.Reset(time.Duration(interval) * time.Second) 276 | } else { 277 | tick.Stop() 278 | } 279 | } 280 | } 281 | 282 | func (yd YDisk) getOutput(userLang bool) string { 283 | cmd := []string{yd.exe, "status", "-c", yd.conf} 284 | if !userLang { 285 | cmd = append([]string{"env", "-i", "TEMP=" + os.TempDir()}, cmd...) 286 | } 287 | out, err := exec.Command(cmd[0], cmd[1:]...).Output() 288 | if err != nil { 289 | if message := strings.TrimSuffix(string(out), "\n"); message != "Error: daemon not started" { 290 | log.Error("daemon_status", "error", err.Error(), "message", message) 291 | } 292 | return "" 293 | } 294 | return string(out) 295 | } 296 | 297 | // Close deactivates the daemon connection: stops event handler that closes file watcher 298 | // and Changes channel. 299 | func (yd *YDisk) Close() { 300 | yd.exit <- struct{}{} 301 | <-yd.exit // Wait for the event handler completion 302 | } 303 | 304 | // Output returns the output string of `yandex-disk status` command in the current user language. 305 | func (yd *YDisk) Output() string { 306 | return yd.getOutput(true) 307 | } 308 | 309 | // Start runs `yandex-disk start` if daemon was not started before. 310 | func (yd *YDisk) Start() error { 311 | if yd.getOutput(true) == "" { 312 | out, err := exec.Command(yd.exe, "start", "-c", yd.conf).Output() 313 | if err != nil { 314 | log.Error("daemon_start", "error", err) 315 | return err 316 | } 317 | log.Debug("daemon_start", "message", string(bytes.TrimRight(out, " \n"))) 318 | } else { 319 | log.Debug("daemon_start", "status", "already_started") 320 | } 321 | yd.activate() // try to activate watching after daemon start. It shouldn't fail on started daemon 322 | return nil 323 | } 324 | 325 | // Stop runs `yandex-disk stop` if daemon was not stopped before. 326 | func (yd *YDisk) Stop() error { 327 | if yd.getOutput(true) != "" { 328 | out, err := exec.Command(yd.exe, "stop", "-c", yd.conf).Output() 329 | if err != nil { 330 | log.Error("daemon stop", "error", err) 331 | return err 332 | } 333 | log.Debug("daemon_stop", "message", string(bytes.TrimRight(out, " \n"))) 334 | } else { 335 | log.Debug("daemon_stop", "status", "already_stopped") 336 | } 337 | return nil 338 | } 339 | -------------------------------------------------------------------------------- /yd.go: -------------------------------------------------------------------------------- 1 | // Copyleft 2017 - +Inf Sly_tom_cat (slytomcat@mail.ru) 2 | // License: GPL v.3 3 | 4 | //go:generate gotext update -out catalog.go 5 | 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "log/slog" 11 | "os" 12 | "os/signal" 13 | "path" 14 | "syscall" 15 | 16 | "path/filepath" 17 | "strings" 18 | "time" 19 | 20 | "github.com/slytomcat/systray" 21 | "github.com/slytomcat/yd-go/icons" 22 | "github.com/slytomcat/yd-go/notify" 23 | "github.com/slytomcat/yd-go/tools" 24 | "github.com/slytomcat/yd-go/ydisk" 25 | "golang.org/x/text/message" 26 | ) 27 | 28 | var ( 29 | version = "local build" 30 | ) 31 | 32 | const ( 33 | appName = "yd-go" // app name for systray ID 34 | appTitle = "Yandex.Disk indicator" // human readable application title for icon and notifications 35 | about = appName + ` is the panel indicator for Yandex.Disk daemon. 36 | 37 | Version: %s 38 | 39 | Copyleft 2017-%s Sly_tom_cat (slytomcat@mail.ru) 40 | 41 | License: GPL v.3 42 | 43 | ` 44 | ydURL = "https://disk.yandex.ru" 45 | faqURL = "https://github.com/slytomcat/yd-go/wiki/FAQ" 46 | helpURL = "https://github.com/slytomcat/yd-go/wiki/FAQ&SUPPORT" 47 | donateUrl = "https://github.com/slytomcat/yd-go/wiki/Donations" 48 | lastLen = 10 49 | ) 50 | 51 | type indicator struct { 52 | cfg *tools.Config // app config 53 | msg func(message.Reference, ...any) string // msg is the Localization printer func 54 | icon *icons.Icon // icon helper 55 | notifySend func(title, msg string) // function to send notification, nil means that notifications are not available 56 | log *slog.Logger // logger 57 | menu *menu // app menu 58 | } 59 | 60 | type menu struct { 61 | status *systray.MenuItem // menu item to show current status 62 | size1 *systray.MenuItem // menu item to show used/total sizes 63 | size2 *systray.MenuItem // menu item to show free anf trash sizes 64 | last *systray.MenuItem // Sub-menu with last synchronized 65 | lastMItem [lastLen]*systray.MenuItem // last synchronized menu items 66 | lastPath [lastLen]string // paths to last synchronized 67 | start *systray.MenuItem // start daemon item 68 | stop *systray.MenuItem // stop daemon item 69 | out *systray.MenuItem 70 | path *systray.MenuItem 71 | notes *systray.MenuItem 72 | theme *systray.MenuItem 73 | daemonStart *systray.MenuItem 74 | daemonStop *systray.MenuItem 75 | site *systray.MenuItem 76 | help *systray.MenuItem 77 | about *systray.MenuItem 78 | donate *systray.MenuItem 79 | quit *systray.MenuItem 80 | warning *systray.MenuItem 81 | } 82 | 83 | func (i *indicator) makeMenu() { 84 | i.menu = new(menu) 85 | i.menu.status = systray.AddMenuItem("", "") 86 | i.menu.size1 = systray.AddMenuItem("", "") 87 | i.menu.size2 = systray.AddMenuItem("", "") 88 | systray.AddSeparator() 89 | i.menu.last = systray.AddMenuItem(i.msg("Last synchronized"), "") 90 | for j := range lastLen { 91 | l := i.menu.last.AddSubMenuItem("", "") 92 | l.Hide() 93 | i.menu.lastMItem[j] = l 94 | } 95 | systray.AddSeparator() 96 | i.menu.start = systray.AddMenuItem(i.msg("Start daemon"), "") 97 | i.menu.stop = systray.AddMenuItem(i.msg("Stop daemon"), "") 98 | systray.AddSeparator() 99 | i.menu.out = systray.AddMenuItem(i.msg("Show daemon output"), "") 100 | i.menu.path = systray.AddMenuItem(i.msg("Open Yandex.Disk folder"), "") 101 | i.menu.site = systray.AddMenuItem(i.msg("Open Yandex.Disk in browser"), "") 102 | setup := systray.AddMenuItem(i.msg("Settings"), "") 103 | i.menu.theme = setup.AddSubMenuItemCheckbox(i.msg("Light theme"), "", i.cfg.Theme == "light") 104 | i.menu.notes = setup.AddSubMenuItemCheckbox(i.msg("Notifications"), "", i.cfg.Notifications) 105 | i.menu.daemonStart = setup.AddSubMenuItemCheckbox(i.msg("Start on start"), "", i.cfg.StartDaemon) 106 | i.menu.daemonStop = setup.AddSubMenuItemCheckbox(i.msg("Stop on exit"), "", i.cfg.StopDaemon) 107 | systray.AddSeparator() 108 | i.menu.help = systray.AddMenuItem(i.msg("Help"), "") 109 | i.menu.about = systray.AddMenuItem(i.msg("About"), "") 110 | i.menu.donate = systray.AddMenuItem(i.msg("Donations"), "") 111 | systray.AddSeparator() 112 | i.menu.quit = systray.AddMenuItem(i.msg("Quit"), "") 113 | i.menu.status.Disable() 114 | i.menu.size1.Disable() 115 | i.menu.size2.Disable() 116 | i.menu.last.Disable() 117 | i.menu.start.Hide() 118 | i.menu.stop.Hide() 119 | if i.notifySend == nil { // disable all menu items that are dependant on notification service 120 | i.menu.about.Disable() 121 | i.menu.out.Disable() 122 | i.menu.notes.Disable() 123 | // add menu warning 124 | systray.AddSeparator() 125 | i.menu.warning = systray.AddMenuItem(i.msg("Notification service unavailable!"), "") 126 | } else { 127 | i.menu.warning = systray.AddMenuItem("", "") 128 | i.menu.warning.Hide() 129 | } 130 | } 131 | 132 | // SetupLocalization initializes translations 133 | func SetupLocalization(logger *slog.Logger) *message.Printer { 134 | lng := os.Getenv("LANG") 135 | if len(lng) > 2 { 136 | lng = lng[:2] 137 | } 138 | logger.Debug("language", "LANG", lng) 139 | return message.NewPrinter(message.MatchLanguage(lng)) 140 | } 141 | 142 | func main() { 143 | cfgPath, debug := tools.GetParams(appName, os.Args, version) 144 | _, id := path.Split(cfgPath) 145 | systray.SetID(fmt.Sprintf("%s_%s", appName, id)) 146 | systray.Run(func() { 147 | defer systray.Quit() // it releases systray.Run in main() 148 | log := tools.SetupLogger(debug) 149 | cfg, err := tools.NewConfig(cfgPath) 150 | if err != nil { 151 | log.Error("config_error", "error", err) 152 | os.Exit(1) 153 | } 154 | defer cfg.Save() 155 | i := &indicator{ 156 | cfg: cfg, 157 | msg: SetupLocalization(log).Sprintf, 158 | log: log, 159 | } 160 | // create new YDisk instance 161 | YD, err := ydisk.NewYDisk(i.cfg.Conf, i.log) 162 | if err != nil { 163 | i.log.Error("daemon_initialization", "error", err) 164 | os.Exit(1) 165 | } 166 | defer YD.Close() 167 | // handle starting/stopping daemon 168 | if i.cfg.StartDaemon { 169 | go YD.Start() 170 | } 171 | defer func() { 172 | if i.cfg.StopDaemon { 173 | YD.Stop() 174 | } 175 | }() 176 | // register interrupt signals chan 177 | canceled := make(chan os.Signal, 1) 178 | signal.Notify(canceled, syscall.SIGINT, syscall.SIGTERM) 179 | // set systray title 180 | systray.SetTitle(i.msg(appTitle)) 181 | // initialize icon helper 182 | i.icon = icons.NewIcon(cfg.Theme, systray.SetIcon) 183 | defer i.icon.Close() 184 | // Initialize notifications 185 | if notifyHandler, err := notify.New(appName, i.icon.LogoIcon, false, -1); err != nil { 186 | i.notifySend = nil 187 | cfg.Notifications = false // disable notifications into configuration 188 | i.log.Warn("notifications", "status", "not_available", "error", err) 189 | } else { 190 | i.notifySend = func(title, msg string) { 191 | i.log.Debug("sending_message", "title", title, "message", msg) 192 | notifyHandler.Send(title, msg) 193 | } 194 | defer notifyHandler.Close() 195 | } 196 | // Initialize systray menu 197 | i.makeMenu() 198 | // Start events handler 199 | i.log.Debug("ui_event_handler", "status", "started") 200 | defer i.log.Debug("ui_event_handler", "status", "exited") 201 | for { 202 | select { 203 | case <-i.menu.lastMItem[0].ClickedCh: 204 | i.openPath(i.menu.lastPath[0]) 205 | case <-i.menu.lastMItem[1].ClickedCh: 206 | i.openPath(i.menu.lastPath[1]) 207 | case <-i.menu.lastMItem[2].ClickedCh: 208 | i.openPath(i.menu.lastPath[2]) 209 | case <-i.menu.lastMItem[3].ClickedCh: 210 | i.openPath(i.menu.lastPath[3]) 211 | case <-i.menu.lastMItem[4].ClickedCh: 212 | i.openPath(i.menu.lastPath[4]) 213 | case <-i.menu.lastMItem[5].ClickedCh: 214 | i.openPath(i.menu.lastPath[5]) 215 | case <-i.menu.lastMItem[6].ClickedCh: 216 | i.openPath(i.menu.lastPath[6]) 217 | case <-i.menu.lastMItem[7].ClickedCh: 218 | i.openPath(i.menu.lastPath[7]) 219 | case <-i.menu.lastMItem[8].ClickedCh: 220 | i.openPath(i.menu.lastPath[8]) 221 | case <-i.menu.lastMItem[9].ClickedCh: 222 | i.openPath(i.menu.lastPath[9]) 223 | case <-i.menu.start.ClickedCh: 224 | go YD.Start() 225 | case <-i.menu.stop.ClickedCh: 226 | go YD.Stop() 227 | case <-i.menu.out.ClickedCh: 228 | i.notifySend(i.msg("Yandex.Disk daemon output"), YD.Output()) 229 | case <-i.menu.path.ClickedCh: 230 | i.openPath(YD.Path) 231 | case <-i.menu.site.ClickedCh: 232 | i.openPath(ydURL) 233 | case <-i.menu.theme.ClickedCh: 234 | i.cfg.Theme = i.handleThemeClick(i.menu.theme) 235 | case <-i.menu.notes.ClickedCh: 236 | i.cfg.Notifications = handleCheck(i.menu.notes) 237 | case <-i.menu.daemonStart.ClickedCh: 238 | i.cfg.StartDaemon = handleCheck(i.menu.daemonStart) 239 | case <-i.menu.daemonStop.ClickedCh: 240 | i.cfg.StopDaemon = handleCheck(i.menu.daemonStop) 241 | case <-i.menu.help.ClickedCh: 242 | i.openPath(helpURL) 243 | case <-i.menu.about.ClickedCh: 244 | i.notifySend(i.msg(appTitle), i.msg(about, version, time.Now().Format("2006"))) 245 | case <-i.menu.donate.ClickedCh: 246 | i.openPath(donateUrl) 247 | case <-i.menu.warning.ClickedCh: 248 | i.openPath(faqURL) 249 | case yds := <-YD.Changes: // YDisk change event 250 | i.handleUpdate(&yds, YD.Path) 251 | case sig := <-canceled: // SIGINT or SIGTERM signal received 252 | fmt.Println() // to leave ^C on previous line 253 | i.log.Warn("exit", "signal", sig) 254 | return 255 | case <-i.menu.quit.ClickedCh: 256 | i.log.Debug("exit", "status", "requested") 257 | return 258 | } 259 | } 260 | }, nil) 261 | } 262 | 263 | func (i *indicator) openPath(path string) { 264 | if err := tools.XdgOpen(path); err != nil { 265 | i.log.Error("opening", "path", path, "error", err) 266 | } 267 | } 268 | 269 | func handleCheck(mi *systray.MenuItem) bool { 270 | if mi.Checked() { 271 | mi.Uncheck() 272 | return false 273 | } 274 | mi.Check() 275 | return true 276 | } 277 | 278 | func (i *indicator) handleThemeClick(mi *systray.MenuItem) (theme string) { 279 | if handleCheck(mi) { 280 | theme = "light" 281 | } else { 282 | theme = "dark" 283 | } 284 | i.icon.SetTheme(theme) 285 | return 286 | } 287 | 288 | func joinNonEmpty(items ...string) string { 289 | s := strings.Builder{} 290 | for _, i := range items { 291 | if len(i) > 0 { 292 | s.WriteString(i) 293 | s.WriteString(" ") 294 | } 295 | } 296 | if s.Len() > 0 { 297 | return s.String()[:s.Len()-1] 298 | } 299 | return "" 300 | } 301 | 302 | // handleUpdate changes icon/menu and sends notifications if they are enabled 303 | func (i *indicator) handleUpdate(yds *ydisk.YDvals, path string) { 304 | st := joinNonEmpty(i.msg(yds.Stat), yds.Prog, yds.Err, tools.MakeTitle(yds.ErrP, 30)) 305 | i.menu.status.SetTitle(i.msg("Status: %s", st)) 306 | i.menu.size1.SetTitle(i.msg("Used: %s/%s", yds.Used, yds.Total)) 307 | i.menu.size2.SetTitle(i.msg("Free: %s Trash: %s", yds.Free, yds.Trash)) 308 | if yds.ChLast { // last synchronized list changed 309 | for l := range lastLen { 310 | if l < len(yds.Last) { 311 | p := yds.Last[l] 312 | i.menu.lastPath[l] = filepath.Join(path, p) 313 | i.menu.lastMItem[l].SetTitle(tools.MakeTitle(p, 40)) 314 | if tools.NotExists(i.menu.lastPath[l]) { 315 | i.menu.lastMItem[l].Disable() 316 | } else { 317 | i.menu.lastMItem[l].Enable() 318 | } 319 | i.menu.lastMItem[l].Show() // show list items 320 | } else { 321 | i.menu.lastMItem[l].Hide() // hide the rest of list 322 | } 323 | } 324 | if len(yds.Last) == 0 { 325 | i.menu.last.Disable() 326 | } else { 327 | i.menu.last.Enable() 328 | } 329 | i.menu.last.Show() // to update parent item view 330 | } 331 | yds.Stat = index2Busy(yds.Stat) // index and busy statuses are equal in terms of icons and notifications 332 | yds.Prev = index2Busy(yds.Prev) 333 | if yds.Stat != yds.Prev { // status changed 334 | // change indicator icon 335 | i.icon.Set(none2Paused(yds.Stat)) // index were converted to busy earlier 336 | // handle Start/Stop menu items 337 | if yds.Stat == "none" || yds.Prev == "none" || yds.Prev == "unknown" { 338 | if yds.Stat == "none" { 339 | i.menu.start.Show() 340 | i.menu.stop.Hide() 341 | i.menu.out.Disable() 342 | } else { 343 | i.menu.stop.Show() 344 | i.menu.start.Hide() 345 | if i.notifySend != nil { 346 | i.menu.out.Enable() 347 | } 348 | } 349 | } 350 | if i.cfg.Notifications && i.notifySend != nil { 351 | go i.handleNotifications(yds) 352 | } 353 | } 354 | i.log.Debug("ui_change", "status", "handled", "last", len(yds.Last)) 355 | } 356 | 357 | // index2Busy converts index to busy 358 | func index2Busy(status string) string { 359 | if status == "index" { 360 | return "busy" 361 | } 362 | return status 363 | } 364 | 365 | // none2Paused converts none to paused 366 | func none2Paused(status string) string { 367 | if status == "none" { 368 | return "paused" 369 | } 370 | return status 371 | } 372 | 373 | func (i *indicator) handleNotifications(yds *ydisk.YDvals) { 374 | switch { 375 | case yds.Stat == "none" && yds.Prev != "unknown": 376 | i.notifySend(i.msg(appTitle), i.msg("Daemon stopped")) 377 | case yds.Prev == "none": 378 | i.notifySend(i.msg(appTitle), i.msg("Daemon started")) 379 | case yds.Prev != "busy" && yds.Stat == "busy": 380 | i.notifySend(i.msg(appTitle), i.msg("Synchronization started")) 381 | case yds.Prev == "busy" && yds.Stat != "busy": 382 | i.notifySend(i.msg(appTitle), i.msg("Synchronization finished")) 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------