~phablet-team/ciborium/trunk

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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*
 * Copyright 2014 Canonical Ltd.
 *
 * Authors:
 * Sergio Schvezov: sergio.schvezov@cannical.com
 *
 * ciborium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * nuntium 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 main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"syscall"
	"time"

	"launchpad.net/ciborium/gettext"
	"launchpad.net/ciborium/notifications"
	"launchpad.net/ciborium/udisks2"
	"launchpad.net/go-dbus/v1"
)

type message struct{ Summary, Body string }
type notifyFreeFunc func(mountpoint) error

type mountpoint string

func (m mountpoint) external() bool {
	return strings.HasPrefix(string(m), "/media")
}

type mountwatch struct {
	lock        sync.Mutex
	mountpoints map[mountpoint]bool
}

func (m *mountwatch) set(path mountpoint, state bool) {
	m.lock.Lock()
	defer m.lock.Unlock()

	m.mountpoints[path] = state
}

func (m *mountwatch) getMountpoints() []mountpoint {
	m.lock.Lock()
	defer m.lock.Unlock()

	mapLen := len(m.mountpoints)
	mountpoints := make([]mountpoint, 0, mapLen)
	for p := range m.mountpoints {
		mountpoints = append(mountpoints, p)
	}
	return mountpoints
}

func (m *mountwatch) warn(path mountpoint) bool {
	m.lock.Lock()
	defer m.lock.Unlock()

	return m.mountpoints[path]
}

func (m *mountwatch) remove(path mountpoint) {
	m.lock.Lock()
	defer m.lock.Unlock()

	delete(m.mountpoints, path)
}

func newMountwatch() *mountwatch {
	return &mountwatch{
		mountpoints: make(map[mountpoint]bool),
	}
}

const (
	sdCardIcon                = "media-memory-sd"
	errorIcon                 = "error"
	homeMountpoint mountpoint = "/home"
	freeThreshold             = 5
)

var (
	mw          *mountwatch
	supportedFS []string
)

func init() {
	mw = newMountwatch()
	mw.set(homeMountpoint, true)
	supportedFS = []string{"vfat"}
}

func main() {
	// set default logger flags to get more useful info
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	// Initialize i18n
	gettext.SetLocale(gettext.LC_ALL, "")
	gettext.Textdomain("ciborium")
	gettext.BindTextdomain("ciborium", "/usr/share/locale")

	var (
		msgStorageSuccess message = message{
			// TRANSLATORS: This is the summary of a notification bubble with a short message of
			// success when addding a storage device.
			Summary: gettext.Gettext("Storage device detected"),
			// TRANSLATORS: This is the body of a notification bubble with a short message about content
			// being scanned when addding a storage device.
			Body: gettext.Gettext("This device will be scanned for new content"),
		}

		msgStorageFail message = message{
			// TRANSLATORS: This is the summary of a notification bubble with a short message of
			// failure when adding a storage device.
			Summary: gettext.Gettext("Failed to add storage device"),
			// TRANSLATORS: This is the body of a notification bubble with a short message with hints
			// with regards to the failure when adding a storage device.
			Body: gettext.Gettext("Make sure the storage device is correctly formated"),
		}

		msgStorageRemoved message = message{
			// TRANSLATORS: This is the summary of a notification bubble with a short message of
			// a storage device being removed
			Summary: gettext.Gettext("Storage device has been removed"),
			// TRANSLATORS: This is the body of a notification bubble with a short message about content
			// from the removed device no longer being available
			Body: gettext.Gettext("Content previously available on this device will no longer be accessible"),
		}
	)

	var (
		systemBus, sessionBus *dbus.Connection
		err                   error
	)

	if systemBus, err = dbus.Connect(dbus.SystemBus); err != nil {
		log.Fatal("Connection error: ", err)
	}
	log.Print("Using system bus on ", systemBus.UniqueName)

	if sessionBus, err = dbus.Connect(dbus.SessionBus); err != nil {
		log.Fatal("Connection error: ", err)
	}
	log.Print("Using session bus on ", sessionBus.UniqueName)

	udisks2 := udisks2.NewStorageWatcher(systemBus, supportedFS...)

	notificationHandler := notifications.NewLegacyHandler(sessionBus, "ciborium")
	notifyFree := buildFreeNotify(notificationHandler)

	blockAdded, blockError := udisks2.SubscribeAddEvents()
	formatCompleted, formatErrors := udisks2.SubscribeFormatEvents()
	unmountCompleted, unmountErrors := udisks2.SubscribeUnmountEvents()
	mountCompleted, mountErrors := udisks2.SubscribeMountEvents()
	mountRemoved := udisks2.SubscribeRemoveEvents()

	// create a routine per couple of channels, the select algorithm will make use
	// ignore some events if more than one channels is being written to the algorithm
	// will pick one at random but we want to make sure that we always react, the pairs
	// are safe since the deal with complementary events

	// block additions
	go func() {
		log.Println("Listening for addition and removal events.")
		for {
			var n *notifications.PushMessage
			select {
			case a := <-blockAdded:
				udisks2.Mount(a)
			case e := <-blockError:
				log.Println("Issues in block for added drive:", e)
				n = notificationHandler.NewStandardPushMessage(
					msgStorageFail.Summary,
					msgStorageFail.Body,
					errorIcon,
				)
			case m := <-mountRemoved:
				log.Println("Path removed", m)
				n = notificationHandler.NewStandardPushMessage(
					msgStorageRemoved.Summary,
					msgStorageRemoved.Body,
					sdCardIcon,
				)
				mw.remove(mountpoint(m))
			case <-time.After(time.Minute):
				for _, m := range mw.getMountpoints() {
					err = notifyFree(m)
					if err != nil {
						log.Print("Error while querying free space for ", m, ": ", err)
					}
				}
			}
			if n != nil {
				if err := notificationHandler.Send(n); err != nil {
					log.Println(err)
				}
			}
		}
	}()

	// mount operations
	go func() {
		log.Println("Listening for mount and unmount events.")
		for {
			var n *notifications.PushMessage
			select {
			case m := <-mountCompleted:
				log.Println("Mounted", m)
				n = notificationHandler.NewStandardPushMessage(
					msgStorageSuccess.Summary,
					msgStorageSuccess.Body,
					sdCardIcon,
				)

				if err := createStandardHomeDirs(m.Mountpoint); err != nil {
					log.Println("Failed to create standard dir layout:", err)
				}

				mw.set(mountpoint(m.Mountpoint), true)
			case e := <-mountErrors:
				log.Println("Error while mounting device", e)

				n = notificationHandler.NewStandardPushMessage(
					msgStorageFail.Summary,
					msgStorageFail.Body,
					errorIcon,
				)
			case m := <-unmountCompleted:
				log.Println("Path removed", m)
				n = notificationHandler.NewStandardPushMessage(
					msgStorageRemoved.Summary,
					msgStorageRemoved.Body,
					sdCardIcon,
				)
				mw.remove(mountpoint(m))
			case e := <-unmountErrors:
				log.Println("Error while unmounting device", e)

				n = notificationHandler.NewStandardPushMessage(
					msgStorageFail.Summary,
					msgStorageFail.Body,
					errorIcon,
				)
			}

			if n != nil {
				if err := notificationHandler.Send(n); err != nil {
					log.Println(err)
				}
			}
		}
	}()

	// format operations
	go func() {
		log.Println("Listening for format events.")
		for {
			var n *notifications.PushMessage
			select {
			case f := <-formatCompleted:
				log.Println("Format done. Trying to mount.")
				udisks2.Mount(f)
			case e := <-formatErrors:
				log.Println("There was an error while formatting", e)
				n = notificationHandler.NewStandardPushMessage(
					msgStorageFail.Summary,
					msgStorageFail.Body,
					errorIcon,
				)
			}

			if n != nil {
				if err := notificationHandler.Send(n); err != nil {
					log.Println(err)
				}
			}
		}
	}()

	if err := udisks2.Init(); err != nil {
		log.Fatal("Cannot monitor storage devices:", err)
	}

	done := make(chan bool)
	<-done
}

// createStandardHomeDirs creates directories reflecting a standard home, these
// directories are Documents, Downloads, Music, Pictures and Videos
func createStandardHomeDirs(mountpoint string) error {
	log.Println("createStandardHomeDirs(", mountpoint, ")")
	for _, node := range []string{"Documents", "Downloads", "Music", "Pictures", "Videos"} {
		dir := filepath.Join(mountpoint, node)

		if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
			if err := os.MkdirAll(dir, 755); err != nil {
				return err
			}
		} else if err != nil {
			return err
		}
	}

	return nil
}

// notify only notifies if a notification is actually needed
// depending on freeThreshold and on warningSent's status
func buildFreeNotify(nh *notifications.NotificationHandler) notifyFreeFunc {
	// TRANSLATORS: This is the summary of a notification bubble with a short message warning on
	// low space
	summary := gettext.Gettext("Low on disk space")
	// TRANSLATORS: This is the body of a notification bubble with a short message about content
	// reamining available space, %d is the remaining percentage of space available on internal
	// storage
	bodyInternal := gettext.Gettext("Only %d%% is available on the internal storage device")
	// TRANSLATORS: This is the body of a notification bubble with a short message about content
	// reamining available space, %d is the remaining percentage of space available on a given
	// external storage device
	bodyExternal := gettext.Gettext("Only %d%% is available on the external storage device")

	var body string

	return func(path mountpoint) error {
		if path.external() {
			body = bodyExternal
		} else {
			body = bodyInternal
		}

		availPercentage, err := queryFreePercentage(path)
		if err != nil {
			return err
		}

		if mw.warn(path) && availPercentage <= freeThreshold {
			n := nh.NewStandardPushMessage(
				summary,
				fmt.Sprintf(body, availPercentage),
				errorIcon,
			)
			log.Println("Warning for", path, "available percentage", availPercentage)
			if err := nh.Send(n); err != nil {
				return err
			}
			mw.set(path, false)
		}

		if availPercentage > freeThreshold {
			mw.set(path, true)
		}
		return nil
	}
}

func queryFreePercentage(path mountpoint) (uint64, error) {
	s := syscall.Statfs_t{}
	if err := syscall.Statfs(string(path), &s); err != nil {
		return 0, err
	}
	if s.Blocks == 0 {
		return 0, errors.New("statfs call returned 0 blocks available")
	}
	return uint64(s.Bavail) * 100 / uint64(s.Blocks), nil
}