File: syncdir.go

package info (click to toggle)
golang-github-la5nta-wl2k-go 0.11.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,856 kB
  • sloc: ansic: 14; makefile: 2
file content (287 lines) | stat: -rw-r--r-- 7,166 bytes parent folder | download
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
// Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.

// Package mailbox provides mailbox handlers for a fbb.Session.
package mailbox

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/user"
	"path"
	"path/filepath"
	"strings"

	"github.com/la5nta/wl2k-go/fbb"
)

const (
	DIR_INBOX   = "/in/"
	DIR_OUTBOX  = "/out/"
	DIR_SENT    = "/sent/"
	DIR_ARCHIVE = "/archive/"
)

const Ext = ".b2f"

// NewDirHandler is a file system (directory) oriented mailbox handler.
type DirHandler struct {
	MBoxPath string
	deferred map[string]bool
	sendOnly bool
}

// NewDirHandler wraps the directory given by path as a DirHandler.
//
// If sendOnly is true, all inbound messages will be deferred.
func NewDirHandler(path string, sendOnly bool) *DirHandler {
	return &DirHandler{
		MBoxPath: path,
		sendOnly: sendOnly,
	}
}

func (h *DirHandler) Prepare() (err error) {
	h.deferred = make(map[string]bool)
	return ensureDirStructure(h.MBoxPath)
}

func (h *DirHandler) Inbox() ([]*fbb.Message, error) {
	return LoadMessageDir(path.Join(h.MBoxPath, DIR_INBOX))
}

func (h *DirHandler) Outbox() ([]*fbb.Message, error) {
	return LoadMessageDir(path.Join(h.MBoxPath, DIR_OUTBOX))
}

func (h *DirHandler) Sent() ([]*fbb.Message, error) {
	return LoadMessageDir(path.Join(h.MBoxPath, DIR_SENT))
}

func (h *DirHandler) Archive() ([]*fbb.Message, error) {
	return LoadMessageDir(path.Join(h.MBoxPath, DIR_ARCHIVE))
}

// InboxCount returns the number of messages in the inbox. -1 on error.
func (h *DirHandler) InboxCount() int   { return countFiles(path.Join(h.MBoxPath, DIR_INBOX)) }
func (h *DirHandler) OutboxCount() int  { return countFiles(path.Join(h.MBoxPath, DIR_OUTBOX)) }
func (h *DirHandler) SentCount() int    { return countFiles(path.Join(h.MBoxPath, DIR_SENT)) }
func (h *DirHandler) ArchiveCount() int { return countFiles(path.Join(h.MBoxPath, DIR_ARCHIVE)) }

func (h *DirHandler) AddOut(msg *fbb.Message) error {
	data, err := msg.Bytes()
	if err != nil {
		return err
	}

	return ioutil.WriteFile(path.Join(h.MBoxPath, DIR_OUTBOX, msg.MID()+Ext), data, 0644)
}

func (h *DirHandler) ProcessInbound(msgs ...*fbb.Message) (err error) {
	dir := path.Join(h.MBoxPath, DIR_INBOX)
	for _, m := range msgs {
		filename := path.Join(dir, m.MID()+Ext)

		m.Header.Set("X-Unread", "true")

		data, err := m.Bytes()
		if err != nil {
			return err
		}

		if err = ioutil.WriteFile(filename, data, 0664); err != nil {
			return fmt.Errorf("Unable to write received message (%s): %s", filename, err)
		}
	}
	return
}

func (h *DirHandler) GetInboundAnswer(p fbb.Proposal) fbb.ProposalAnswer {
	if h.sendOnly {
		return fbb.Defer
	}

	// Check if file exists
	f, err := os.Open(path.Join(h.MBoxPath, DIR_INBOX, p.MID()+Ext))
	if err == nil {
		f.Close()
		return fbb.Reject
	} else if os.IsNotExist(err) {
		return fbb.Accept
	} else if err != nil {
		log.Printf("Unable to determin if %s has been received: %s", p.MID(), err)
	}

	return fbb.Accept
}

func (h *DirHandler) SetSent(MID string, rejected bool) {
	oldPath := path.Join(h.MBoxPath, DIR_OUTBOX, MID+Ext)
	newPath := path.Join(h.MBoxPath, DIR_SENT, MID+Ext)

	if err := os.Rename(oldPath, newPath); err != nil {
		log.Fatalf("Unable to move %s to %s: %s", oldPath, newPath, err)
	}
}

func (h *DirHandler) SetDeferred(MID string) {
	h.deferred[MID] = true
}

func (h *DirHandler) GetOutbound(fws ...fbb.Address) []*fbb.Message {
	all, err := LoadMessageDir(path.Join(h.MBoxPath, DIR_OUTBOX))
	if err != nil {
		log.Println(err)
	}

	deliver := make([]*fbb.Message, 0, len(all))
	for _, m := range all {
		if h.deferred[m.MID()] {
			continue
		}

		// Check unsent messages that are addressed to one of the
		// forwarder addresses of the remote.
		if len(fws) > 0 {
			for _, fw := range fws {
				if m.IsOnlyReceiver(fw) {
					deliver = append(deliver, m)
					break
				}
			}
			continue
		}

		if len(fws) == 0 && m.Header.Get("X-P2POnly") == "true" {
			continue // The message is P2POnly and remote is CMS
		}

		// Remove private headers
		m.Header.Del("X-P2POnly")
		m.Header.Del("X-FilePath")
		m.Header.Del("X-Unread")

		deliver = append(deliver, m)
	}
	return deliver
}

// Deprecated: implementers should choose their own directories
func DefaultMailboxPath() (string, error) {
	appdir, err := DefaultAppDir()
	if err != nil {
		return "", fmt.Errorf("Unable to determine application directory: %s", err)
	}
	return path.Join(appdir, "mailbox"), nil
}

// Deprecated: implementers should choose their own directories
func DefaultAppDir() (string, error) {
	usr, err := user.Current()
	if err != nil {
		return "", fmt.Errorf("Unable to determine home directory: %s", err)
	}
	return path.Join(usr.HomeDir, ".wl2k"), nil
}

func ensureDirStructure(mboxPath string) (err error) {
	mode := os.ModeDir | os.ModePerm
	if err = os.MkdirAll(path.Join(mboxPath, DIR_INBOX), mode); err != nil {
		return
	} else if err = os.MkdirAll(path.Join(mboxPath, DIR_OUTBOX), mode); err != nil {
		return
	} else if err = os.MkdirAll(path.Join(mboxPath, DIR_SENT), mode); err != nil {
		return
	} else if err = os.MkdirAll(path.Join(mboxPath, DIR_ARCHIVE), mode); err != nil {
		return
	}
	return
}

func UserPath(root, callsign string) string {
	return path.Join(root, callsign)
}

func countFiles(dirPath string) int {
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return -1
	}

	return len(files)
}

func LoadMessageDir(dirPath string) ([]*fbb.Message, error) {
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return nil, fmt.Errorf("Unable to read dir (%s): %s", dirPath, err)
	}

	msgs := make([]*fbb.Message, 0, len(files))

	for _, file := range files {
		if file.IsDir() || file.Name()[0] == '.' {
			continue
		}

		if !strings.EqualFold(filepath.Ext(file.Name()), Ext) {
			continue
		}

		msg, err := OpenMessage(path.Join(dirPath, file.Name()))
		if err != nil {
			return nil, err
		}

		msgs = append(msgs, msg)
	}
	return msgs, nil
}

// OpenMessage opens a single a fbb.Message file.
func OpenMessage(path string) (*fbb.Message, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("Unable to open file (%s): %s", path, err)
	}
	defer f.Close()

	message := new(fbb.Message)
	if err := message.ReadFrom(f); err != nil {
		f.Close()
		return nil, fmt.Errorf("Unable to parse message (%s): %s", path, err)
	}

	message.Header.Set("X-FilePath", path)
	return message, nil
}

// IsUnread returns true if the given message is marked as unread.
func IsUnread(msg *fbb.Message) bool { return msg.Header.Get("X-Unread") == "true" }

// SetUnread marks the given message as read/unread and re-writes the file to disk.
func SetUnread(msg *fbb.Message, unread bool) error {
	if !unread && msg.Header.Get("X-Unread") == "" {
		return nil
	}

	if unread {
		msg.Header.Set("X-Unread", "true")
	} else {
		msg.Header.Del("X-Unread")
	}

	data, err := msg.Bytes()
	if err != nil {
		return err
	}

	filePath := msg.Header.Get("X-FilePath")
	if filePath == "" {
		return fmt.Errorf("Missing X-FilePath header")
	}
	return ioutil.WriteFile(filePath, data, 0644)
}