/
api_themes.go
251 lines (225 loc) · 7.37 KB
/
api_themes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2020 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package daemon
import (
"context"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/overlord"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/strutil"
)
var (
themesCmd = &Command{
Path: "/v2/accessories/themes",
UserOK: true,
GET: checkThemes,
POST: installThemes,
}
)
type themeStatus string
const (
themeInstalled themeStatus = "installed"
themeAvailable themeStatus = "available"
themeUnavailable themeStatus = "unavailable"
)
type themeStatusResponse struct {
GtkThemes map[string]themeStatus `json:"gtk-themes"`
IconThemes map[string]themeStatus `json:"icon-themes"`
SoundThemes map[string]themeStatus `json:"sound-themes"`
}
func installedThemes(overlord *overlord.Overlord) (gtkThemes, iconThemes, soundThemes []string, err error) {
infos := overlord.InterfaceManager().Repository().Info(&interfaces.InfoOptions{
Names: []string{"content"},
Slots: true,
})
for _, info := range infos {
for _, slot := range info.Slots {
var content string
// The content interface ensures this attribute exists
if err := slot.Attr("content", &content); err != nil {
return nil, nil, nil, err
}
var themes *[]string
switch content {
case "gtk-3-themes":
themes = >kThemes
case "icon-themes":
themes = &iconThemes
case "sound-themes":
themes = &soundThemes
default:
continue
}
var sources []interface{}
if err := slot.Attr("source.read", &sources); err != nil {
continue
}
for _, s := range sources {
if path, ok := s.(string); ok {
*themes = append(*themes, filepath.Base(path))
}
}
}
}
sort.Strings(gtkThemes)
sort.Strings(iconThemes)
sort.Strings(soundThemes)
return gtkThemes, iconThemes, soundThemes, nil
}
var badPkgCharRegexp = regexp.MustCompile(`[^a-z0-9]+`)
func themePackageCandidates(prefix, themeName string) []string {
themeName = strings.ToLower(themeName)
themeName = badPkgCharRegexp.ReplaceAllString(themeName, "-")
themeName = strings.Trim(themeName, "-")
var packages []string
for themeName != "" {
packages = append(packages, prefix+themeName)
pos := strings.LastIndexByte(themeName, '-')
if pos < 0 {
break
}
themeName = themeName[:pos]
}
return packages
}
func collectThemeStatusForPrefix(ctx context.Context, theStore snapstate.StoreService, user *auth.UserState, prefix string, themes, installed []string, status map[string]themeStatus, candidateSnaps map[string]bool) error {
for _, theme := range themes {
// Skip duplicates
if _, ok := status[theme]; ok {
continue
}
if strutil.SortedListContains(installed, theme) {
status[theme] = themeInstalled
continue
}
status[theme] = themeUnavailable
for _, name := range themePackageCandidates(prefix, theme) {
var info *snap.Info
var err error
if info, err = theStore.SnapInfo(ctx, store.SnapSpec{Name: name}, user); err == store.ErrSnapNotFound {
continue
} else if err != nil {
return err
}
// Only mark the theme as available if it has
// been published to the stable channel.
if info.Channel == "stable" {
status[theme] = themeAvailable
candidateSnaps[name] = true
break
}
}
}
return nil
}
func themeStatusAndCandidateSnaps(ctx context.Context, c *Command, user *auth.UserState, gtkThemes, iconThemes, soundThemes []string) (status themeStatusResponse, candidateSnaps map[string]bool, err error) {
installedGtk, installedIcon, installedSound, err := installedThemes(c.d.overlord)
if err != nil {
return themeStatusResponse{}, nil, err
}
theStore := getStore(c)
status.GtkThemes = make(map[string]themeStatus, len(gtkThemes))
status.IconThemes = make(map[string]themeStatus, len(iconThemes))
status.SoundThemes = make(map[string]themeStatus, len(soundThemes))
candidateSnaps = make(map[string]bool)
if err = collectThemeStatusForPrefix(ctx, theStore, user, "gtk-theme-", gtkThemes, installedGtk, status.GtkThemes, candidateSnaps); err != nil {
return themeStatusResponse{}, nil, err
}
if err = collectThemeStatusForPrefix(ctx, theStore, user, "icon-theme-", iconThemes, installedIcon, status.IconThemes, candidateSnaps); err != nil {
return themeStatusResponse{}, nil, err
}
if err = collectThemeStatusForPrefix(ctx, theStore, user, "sound-theme-", soundThemes, installedSound, status.SoundThemes, candidateSnaps); err != nil {
return themeStatusResponse{}, nil, err
}
return status, candidateSnaps, nil
}
func checkThemes(c *Command, r *http.Request, user *auth.UserState) Response {
ctx := store.WithClientUserAgent(r.Context(), r)
q := r.URL.Query()
status, _, err := themeStatusAndCandidateSnaps(ctx, c, user, q["gtk-theme"], q["icon-theme"], q["sound-theme"])
if err != nil {
return InternalError("cannot get theme status: %s", err)
}
return SyncResponse(status, nil)
}
type themeInstallReq struct {
GtkThemes []string `json:"gtk-themes"`
IconThemes []string `json:"icon-themes"`
SoundThemes []string `json:"sound-themes"`
}
func installThemes(c *Command, r *http.Request, user *auth.UserState) Response {
decoder := json.NewDecoder(r.Body)
var req themeInstallReq
if err := decoder.Decode(&req); err != nil {
return BadRequest("cannot decode request body: %v", err)
}
ctx := store.WithClientUserAgent(r.Context(), r)
_, candidateSnaps, err := themeStatusAndCandidateSnaps(ctx, c, user, req.GtkThemes, req.IconThemes, req.SoundThemes)
if err != nil {
return InternalError("cannot get theme status: %s", err)
}
if len(candidateSnaps) == 0 {
return BadRequest("no snaps to install")
}
toInstall := make([]string, 0, len(candidateSnaps))
for pkg := range candidateSnaps {
toInstall = append(toInstall, pkg)
}
sort.Strings(toInstall)
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
userID := 0
if user != nil {
userID = user.ID
}
installed, tasksets, err := snapstateInstallMany(st, toInstall, userID)
if err != nil {
return InternalError("cannot install themes: %s", err)
}
var summary string
switch len(toInstall) {
case 1:
summary = fmt.Sprintf(i18n.G("Install snap %q"), toInstall)
default:
quoted := strutil.Quoted(toInstall)
summary = fmt.Sprintf(i18n.G("Install snaps %s"), quoted)
}
var chg *state.Change
if len(tasksets) == 0 {
chg = st.NewChange("install-themes", summary)
chg.SetStatus(state.DoneStatus)
} else {
chg = newChange(st, "install-themes", summary, tasksets, installed)
ensureStateSoon(st)
}
chg.Set("api-data", map[string]interface{}{"snap-names": installed})
return AsyncResponse(nil, &Meta{Change: chg.ID()})
}