1. gotamer
  2. Untitled project
  3. CitadelSync

Source

CitadelSync / sync.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// Sync local files such as vCard, vCalender, vNotes, and text
// files with a local or remote Citadel Mail Server
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	//"strconv"
	"strings"
	"time"

	"bitbucket.org/gotamer/cfg"
	"bitbucket.org/gotamer/citadel"
	"bitbucket.org/gotamer/errors"
	//"bitbucket.org/gotamer/tools"
)

const (
	VERSION      = 3
	VCARD_TIME   = "20060102T150405Z0700"
	DEFAULT_PORT = ":504"
)

var (
	name     = flag.String("n", "", "Name of the configuration contacts, notes, calender etc.")
	helpflag = flag.Bool("h", false, "Prints out this help text")
	username = flag.String("u", "", "Citadel Username")
	password = flag.String("p", "", "Citadel Password")
	purge    = flag.Bool("D", false, "Delete all items in the room!")
	version  = flag.Bool("v", false, "version")
)

var helpTop = `
  ****************************************
               Citadel Go Sync
  ****************************************

  Upload files to a Citadel Mail Server

 - Contacts from vCards ".vcf"
 - Notes from vNotes ".vnt"
 - Calendar from vCalendars ".vcs" or ".ics"
 - Task from vCalendars ".vcs" or ".ics"
 - Text from any text based files ".txt"

`

var helpButtom = `

  -n Based on the name flag a configuration template file will be created

  -u and -p / Username and Password for the Citadel Mail Server may be
  defined in the config file, or optionaly on the command line

  -D will delete all items in the given room WITHOUT WARNING

`

var (
	PS       string = string(os.PathSeparator)
	Cfg      *config
	FILE_DB  string
	FILE_CFG string
	FILE_LOG string
	DB       map[string]*database
)

type config struct {
	Version     int8
	Environment e.Env
	LocalDir    string
	Room        string
	Username    string
	Password    string
	Server      string
	Port        string
	Floor       string
	SSL_KEY     string
	SSL_CER     string
	citRoomType string
}

func init() {
	Cfg = new(config)
	Cfg.Version = VERSION
	Cfg.Environment = e.ENV_PROD
	Cfg.Username = "TaMeR"
	Cfg.Password = "God knows what"
	Cfg.Server = "localhost"
	Cfg.Port = DEFAULT_PORT
	Cfg.Room = "Contacts"
	Cfg.LocalDir = os.TempDir() + PS + "contacts"
	Cfg.Floor = "Not implemented"
	Cfg.SSL_CER = "Not implemented"
	Cfg.SSL_KEY = "Not implemented"

	DB = make(map[string]*database)
}

func main() {
	flag.Parse()
	if *version {
		fmt.Printf("\n\tCitadel Sync Version %v\n\n", VERSION)
		os.Exit(0)
	}
	if *helpflag || *name == "" {
		fmt.Println(helpTop)
		flag.PrintDefaults()
		fmt.Println(helpButtom)
		os.Exit(0)
	}
	FILE_DB = fmt.Sprintf("%s.db.json", *name)
	FILE_CFG = fmt.Sprintf("%s.cfg.json", *name)
	FILE_LOG = fmt.Sprintf("%s.log", *name)

	if err := cfg.Load(FILE_CFG, Cfg); err != nil {
		Cfg.LocalDir = os.Getenv("HOME") + PS + "PIM" + PS + *name
		if err = cfg.Save(FILE_CFG, Cfg); err != nil {
			fmt.Println("cfg.Save error: ", err.Error())
			os.Exit(1)
		} else {
			fmt.Printf("\nPlease edit your config file at:\n\n\t%s\n", FILE_CFG)
			os.Exit(0)
		}
	}

	if Cfg.Version != VERSION {
		fmt.Println("Please check and upgrade your config file version to the new version: ", VERSION)
		os.Exit(0)
	}

	LogFile()

	if len(*username) != 0 {
		Cfg.Username = *username
	}

	if len(*password) != 0 {
		Cfg.Password = *password
	}

	if *purge {
		CitadelDeleteAll()
		os.Exit(0)
	}

	if !checkRoom() {
		os.Exit(0)
	}
	if Cfg.Server != "" {
		DBLoad()
		FilesInfo()
		CitadelReceive()
		CitadelSend()
		DBSave()
	}
}

func (db *database) Set() {
	DB[db.FileName] = db
}

func (db *database) Del() {
	delete(DB, db.FileName)
}

func (db *database) Modified(fi os.FileInfo) bool {
	if db.FileName != "" {
		if db.FileModTime != fi.ModTime() {
			fmt.Println("FileModTime != fi.ModTime()")
			fmt.Println("FileModTime: ", db.FileModTime)
			fmt.Println("fi.ModTime() ", fi.ModTime())
			db.fileModified = true
		}
	} else {
		db.FileModTime = fi.ModTime()
		db.FileName = fi.Name()
		db.fileModified = true
		DB[db.FileName] = db
	}
	return db.fileModified
}

// TODO use linux "file -bip"
func (db *database) mimeType() (ok bool) {
	if db.FileName != "" {
		suffix := Suffix(db.FileName)
		switch suffix {
		case "vcf":
			db.MimeType = "text/vcard"
			ok = true
			if Cfg.citRoomType != citadel.VIEW_ADDRESSBOOK {
				e.Info("WARNING not a vCard Room. Is a: %v", Cfg.citRoomType)
			}
		case "vnt":
			db.MimeType = "text/vnote"
			ok = true
			if Cfg.citRoomType != citadel.VIEW_NOTES {
				e.Info("WARNING not a vNote Room. Is a: %v", Cfg.citRoomType)
			}
		case "vcs", "ics":
			db.MimeType = "text/calendar"
			ok = true
			if Cfg.citRoomType != citadel.VIEW_CALENDAR {
				e.Info("WARNING not a Calender Room. Is a: %v", Cfg.citRoomType)
			}
			if Cfg.citRoomType != citadel.VIEW_TASKS {
				e.Info("WARNING not a Task Room. Is a: %v", Cfg.citRoomType)
			}
		case "txt":
			db.MimeType = "text/text"
			ok = true
			if Cfg.citRoomType != citadel.VIEW_MAILBOX || Cfg.citRoomType != citadel.VIEW_BBS {
				e.Info("WARNING not a text Room. Is a: %v", Cfg.citRoomType)
			}
		default:
			db.MimeType = "text/text"
			e.Info("WARNING Can't determen file type, using text!")
		}
	} else {
		switch Cfg.citRoomType {
		case citadel.VIEW_ADDRESSBOOK:
			db.FileName = db.UID + ".vcf"
			db.MimeType = "text/vcard"
		case citadel.VIEW_NOTES:
			db.FileName = db.UID + ".vnt"
			db.MimeType = "text/vnote"
		case citadel.VIEW_CALENDAR:
			db.FileName = db.UID + ".vcs"
			db.MimeType = "text/calendar"
		case citadel.VIEW_TASKS:
			db.FileName = db.UID + ".vcs"
			db.MimeType = "text/calendar"
		default:
			db.MimeType = "text/text"
			db.FileName = db.UID + ".txt"
		}
		ok = true
	}
	return
}

func (db *database) CitadelEUID() {
	if db.CitEUID == "" {
		hostname, err := os.Hostname()
		if err != nil {
			hostname = "citadel.sync"
		}
		db.CitEUID = fmt.Sprintf("<%v@%v>", db.UID, hostname)
	}
}

func filenameToUID(name string) string {
	var i = strings.LastIndex(name, ".")
	if i > 0 {
		name = name[0:i]
	}
	return name
}

func FilesInfo() {
	fis := readDir(Cfg.LocalDir)
	no := len(fis)
	for i := 0; i < no; i++ {
		if fis[i].IsDir() {
			continue
		}

		uid := filenameToUID(fis[i].Name())
		dbitem, ok := DB[uid]
		if !ok {
			db := new(database)
			db.FileName = fis[i].Name()
			db.CitadelEUID()
			db.mimeType()
			db.CitadelSend()
			os.Remove(Cfg.LocalDir + PS + db.FileName)
			continue
		}
		dbitem.Modified(fis[i])
		dbitem.mimeType()
		dbitem.CitadelEUID()
		DB[uid] = dbitem
	}
}

func readDir(path string) (fis []os.FileInfo) {
	fi, err := os.Stat(path)
	if ok := e.Check(err); !ok {
		err := os.Mkdir(path, 0750)
		if ok := e.Check(err); ok {
			if fi, err = os.Stat(path); err != nil {
				fmt.Println("[ERROR] Something is very wrong, this should never happen ;)")
			}
		} else {
			fmt.Println("[ERROR] Could not make folder")
			os.Exit(0)
		}
	}
	if fi.IsDir() {
		f, err := os.Open(path)
		defer f.Close()
		e.Check(err)
		fis, err = f.Readdir(0) // 0 = All
		e.Check(err)
	}
	return
}

type database struct {
	UID          string
	CitEUID      string
	CitUxTime    int
	FileName     string
	MimeType     string
	FileModTime  time.Time
	fileModified bool
	citModified  bool
}

// Check which one is newer file or citadel
func modified(message *citadel.Message, dav *citadel.Dav) {
	if dbitem, ok := DB[dav.UID]; ok {
		fmt.Println("Found in db: ", dav.UID, "citModified is: ", dbitem.citModified, "fileModified is: ", dbitem.fileModified)
		if dbitem.CitUxTime > message.UxTime {
			fmt.Println("CitUx is bigger: ", dav.UID)
			dbitem.citModified = true
			if dbitem.fileModified {
				fmt.Println("fileModified is true ", dav.UID)
				if dbitem.FileModTime.Unix() > int64(message.UxTime) {
					fmt.Println("FileModTime >  ", dav.UID)
					dbitem.citModified = false
				} else {
					dbitem.fileModified = false
				}
			}
		}
	} else {
		dbitem = new(database)
		dbitem.UID = dav.UID
		dbitem.CitUxTime = message.UxTime
		dbitem.mimeType()
		dbitem.citModified = true
		dbitem.fileModified = false
		dbitem.CitadelEUID()
		DB[dav.UID] = dbitem
	}
}

func CitadelReceive() {
	c := citadel.New(Cfg.Server + Cfg.Port)
	defer c.Close()
	c.Login(Cfg.Username, Cfg.Password)
	c.Goto(Cfg.Room)
	db := new(database)
	db.mimeType()
	if list, ok := c.MsgListAll(); ok {
		for _, v := range list {
			if message, dav, ok := c.GetDav(v, db.MimeType); ok {
				modified(message, dav)
				if dbitem, ok := DB[dav.UID]; ok {
					if dbitem.citModified {
						ioutil.WriteFile(Cfg.LocalDir+PS+dbitem.FileName, []byte(dav.Object), 0640)
						dbitem.setDbFileModTime()
					}
				} else {
					// This should never happen
					err := e.New("Item should be in the database!")
					e.Check(err)
				}
			}
		}
	}
}

func (db *database) setDbFileModTime() {
	fi, err := os.Stat(Cfg.LocalDir + PS + db.FileName)
	e.Check(err)
	DB[db.UID].FileModTime = fi.ModTime()
}

func CitadelSend() {
	c := citadel.New(Cfg.Server + Cfg.Port)
	defer c.Close()
	c.Login(Cfg.Username, Cfg.Password)
	c.Goto(Cfg.Room)
	c.Info()

	for _, dbitem := range DB {
		if dbitem.fileModified == false {
			e.Info("File not modified; not sending! %v", dbitem.UID)
			fmt.Printf("Not Sending file %v\n", dbitem.UID)
			continue
		}
		e.Info("Sending file %v", dbitem.UID)
		fmt.Printf("Sending file %v\n", dbitem.UID)
		bytes, err := ioutil.ReadFile(Cfg.LocalDir + PS + dbitem.FileName)
		ok := e.Check(err)
		if ok {
			cmd := fmt.Sprintf("ENT0 1|||4||||||%s", dbitem.CitEUID)
			c.Request(cmd)
			if c.Code == citadel.CODE_SEND_LISTING {
				c.Error = c.Conn.PrintfLine("Content-type: " + dbitem.MimeType)
				c.Check()
				err = c.Conn.PrintfLine("%s", "\n")
				e.Check(err)
				err = c.Conn.PrintfLine("%s", bytes)
				e.Check(err)
				err = c.Conn.PrintfLine("%s", citadel.DE)
				e.Check(err)
				e.Info("%s", bytes)
				dbitem.setDbFileModTime()
			}
		}
	}
}

func (db *database) CitadelSend() {
	c := citadel.New(Cfg.Server + Cfg.Port)
	defer c.Close()
	c.Login(Cfg.Username, Cfg.Password)
	c.Goto(Cfg.Room)
	c.Info()

	bytes, err := ioutil.ReadFile(Cfg.LocalDir + PS + db.FileName)
	ok := e.Check(err)
	if ok {
		cmd := fmt.Sprintf("ENT0 1|||4||||||%s", db.CitEUID)
		c.Request(cmd)
		if c.Code == citadel.CODE_SEND_LISTING {
			c.Error = c.Conn.PrintfLine("Content-type: " + db.MimeType)
			c.Check()
			err = c.Conn.PrintfLine("%s", "\n")
			e.Check(err)
			err = c.Conn.PrintfLine("%s", bytes)
			e.Check(err)
			err = c.Conn.PrintfLine("%s", citadel.DE)
			e.Check(err)
			e.Info("%s", bytes)
		}
	}
}

func CitadelDeleteAll() {
	c := citadel.New(Cfg.Server + Cfg.Port)
	defer c.Close()
	c.Login(Cfg.Username, Cfg.Password)
	c.Goto(Cfg.Room)
	c.Info()
	list, ok := c.MsgListAll()
	if ok {
		c.MsgsDel(list)
	}
}

func checkRoom() (ok bool) {
	c := citadel.New(Cfg.Server + Cfg.Port)
	defer c.Close()
	c.Login(Cfg.Username, Cfg.Password)
	if ok = c.Goto(Cfg.Room); ok {
		Cfg.citRoomType = c.Resp[12]
	} else {
		e.Info("Room not availabe")
		c.Info()
	}
	return
}

func DBLoad() {
	if err := cfg.Load(FILE_DB, &DB); err != nil {
		e.Info("Will create new database at: %v", FILE_DB)
	}
}

func DBSave() {
	if err := cfg.Save(FILE_DB, DB); err != nil {
		e.Info("Could not create database at: ", FILE_DB)
		fmt.Println("Could not create database at: %v", FILE_DB)
	}
}

func LogFile() {
	e.ENVIRONMENT = Cfg.Environment
	if e.ENVIRONMENT != e.ENV_FAIL {
		f, err := os.OpenFile(FILE_LOG, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0664)
		e.Check(err)
		e.Logger(f)
	}
}

func Suffix(filename string) (suffix string) {
	no := strings.LastIndex(filename, ".")
	if no > 0 {
		suffix = filename[no+1:]
	}
	return
}