~psic4t/qcard

ref: 85dd70da644380a0a96770d6379b4e4e480d2279 qcard/helpers.go -rw-r--r-- 8.1 KiB
85dd70dapsic4t enable sorting by last name in configuration 4 months ago
                                                                                
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
package main

import (
	"bufio"
	"crypto/rand"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
)

func getConf() *configStruct {
	configData, err := ioutil.ReadFile(configLocation)
	if err != nil {
		fmt.Print("Config not found. \n\nPlease copy config-sample.json to ~/.config/qcard/config.json and modify it accordingly.\n\n")
		log.Fatal(err)
	}

	conf := configStruct{}
	err = json.Unmarshal(configData, &conf)
	//fmt.Println(conf)
	if err != nil {
		log.Fatal(err)
	}

	return &conf
}

func getAbProps(calNo int, p *[]calProps, wg *sync.WaitGroup) {
	req, err := http.NewRequest("PROPFIND", config.Addressbooks[calNo].Url, nil)
	req.SetBasicAuth(config.Addressbooks[calNo].Username, config.Addressbooks[calNo].Password)

	/*tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	cli := &http.Client{Transport: tr}*/
	cli := &http.Client{}
	resp, err := cli.Do(req)

	if err != nil {
		log.Fatal(err)
	}

	xmlContent, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	xmlProps := xmlProps{}
	err = xml.Unmarshal(xmlContent, &xmlProps)
	if err != nil {
		log.Fatal(err)
	}
	displayName := xmlProps.DisplayName

	thisCal := calProps{
		calNo:       calNo,
		displayName: displayName,
		url:         config.Addressbooks[calNo].Url,
	}
	*p = append(*p, thisCal)

	wg.Done()
}

func getAbList() {
	p := []calProps{}

	var wg sync.WaitGroup
	wg.Add(len(config.Addressbooks)) // waitgroup length = num calendars

	for i := range config.Addressbooks {
		go getAbProps(i, &p, &wg)
	}
	wg.Wait()

	sort.Slice(p, func(i, j int) bool {
		return p[i].calNo < (p[j].calNo)
	})

	for i := range p {
		u, err := url.Parse(config.Addressbooks[i].Url)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(`[` + fmt.Sprintf("%v", i) + `] - ` + Colors[i] + colorBlock + ColDefault +
			` ` + p[i].displayName + ` (` + u.Hostname() + `)`)
	}
}

func checkError(e error) {
	if e != nil {
		fmt.Println(e)
	}
}

func splitAfter(s string, re *regexp.Regexp) (r []string) {
	re.ReplaceAllStringFunc(s, func(x string) string {
		s = strings.Replace(s, x, "::"+x, -1)
		return s
	})
	for _, x := range strings.Split(s, "::") {
		if x != "" {
			r = append(r, x)
		}
	}
	return
}

func (e contactStruct) fancyOutput() {
	//fmt.Println(e.name)
	//fmt.Printf(`%5s`, ` `)
	//fmt.Println(` M: ` + e.phoneCell)
	if *showEmailOnly {
		showDetails = false

		if e.emailHome != "" {
			fmt.Printf("%s\t%s\tHOME\n", e.emailHome, e.fullName)
		}
		if e.emailWork != "" {
			fmt.Printf("%s\t%s\tWORK\n", e.emailWork, e.fullName)
		}
	} else {
		if showColor {
			fmt.Print(e.Color + colorBlock + ColDefault + ` `)
		}
		if config.SortByLastname {
			fmt.Println(e.name)
		} else {
			fmt.Println(e.fullName)
		}
	}

	if showDetails {
		if e.title != "" {
			fmt.Println(`  T: ` + e.title)
		}
		if e.organisation != "" {
			fmt.Println(`  O: ` + e.organisation)
		}
		if e.phoneCell != "" {
			//fmt.Printf(`%2s`, ` `)
			//fmt.Printf("%2s%s\n", " ", "M: "+e.phoneCell)
			fmt.Println("  M: " + e.phoneCell)
			//fmt.Println(`M: ` + e.phoneCell)
		}
		if e.phoneHome != "" {
			fmt.Println(`  P: ` + e.phoneHome)
		}
		if e.phoneWork != "" {
			fmt.Println(`  p: ` + e.phoneWork)
		}
		if e.emailHome != "" {
			fmt.Println(`  E: ` + e.emailHome)
		}
		if e.emailWork != "" {
			fmt.Println(`  e: ` + e.emailWork)
		}
		if e.addressHome != "" {
			fmt.Println(`  A: ` + e.addressHome)
		}
		if e.addressWork != "" {
			fmt.Println(`  a: ` + e.addressWork)
		}
		if e.birthday != "" {
			fmt.Println(`  B: ` + e.birthday)
		}
		if e.name != "" {
			fmt.Println(`  N: ` + e.name)
		}
		if e.note != "" {
			fmt.Println(`  n: ` + e.note)
		}
	}

	if showFilename {
		if e.Href != "" {
			fmt.Println(path.Base(e.Href))
		}
	}
	//fmt.Println()
}
func (e contactStruct) vcfOutput() {
	// whole day or greater
	fmt.Println(`Contact
=======`)
	//fmt.Printf(`Summary:%6s`, ` `)
	fmt.Printf("Full Name:\t%s\n", e.fullName)
	fmt.Printf("Cell:\t\t%s\n", e.phoneCell)
}

func genUUID() (uuid string) {
	b := make([]byte, 16)
	_, err := rand.Read(b)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}
	uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

	return
}

func strToInt(str string) (int, error) {
	nonFractionalPart := strings.Split(str, ".")
	return strconv.Atoi(nonFractionalPart[0])
}

func isNumeric(s string) bool {
	_, err := strconv.ParseFloat(s, 64)
	return err == nil
}

func filterMatch(fullName string) bool {
	re, _ := regexp.Compile(`(?i)` + filter)
	return re.FindString(fullName) != ""
}

func deleteContact(abNo int, contactFilename string) (status string) {
	if contactFilename == "" {
		log.Fatal("No contact filename given")
	}

	req, _ := http.NewRequest("DELETE", config.Addressbooks[abNo].Url+contactFilename, nil)
	req.SetBasicAuth(config.Addressbooks[abNo].Username, config.Addressbooks[abNo].Password)

	cli := &http.Client{}
	resp, err := cli.Do(req)
	defer resp.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Status)

	return
}

func dumpContact(abNo int, contactFilename string, toFile bool) (status string) {
	//fmt.Println(config.Addressbooks[calNo].Url + eventFilename)
	if abNo == 1000 {
		abNo = 0 // use first addressbook if not set
	}

	req, _ := http.NewRequest("GET", config.Addressbooks[abNo].Url+contactFilename, nil)
	req.SetBasicAuth(config.Addressbooks[abNo].Username, config.Addressbooks[abNo].Password)

	cli := &http.Client{}
	resp, err := cli.Do(req)
	defer resp.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	//fmt.Println(resp.Status)
	xmlContent, _ := ioutil.ReadAll(resp.Body)

	if toFile {
		// create cache dir if not exists
		os.MkdirAll(cacheLocation, os.ModePerm)
		err := ioutil.WriteFile(cacheLocation+"/"+contactFilename, xmlContent, 0644)
		if err != nil {
			log.Fatal(err)
		}
		return contactFilename + " written"
	} else {
		fmt.Println(string(xmlContent))
		return
	}
}

func uploadVCF(abNo int, contactFilePath string, contactEdit bool) (status string) {
	//fmt.Println(config.Calendars[calNo].Url + eventFilePath)

	var vcfData string
	var contactVCF string
	var contactFileName string

	if contactFilePath == "-" {
		scanner := bufio.NewScanner(os.Stdin)

		for scanner.Scan() {
			vcfData += scanner.Text() + "\n"
		}
		//eventICS, _ = explodeEvent(&icsData)
		contactVCF = vcfData
		contactFileName = genUUID() + `.ics`
		fmt.Println(contactVCF)

	} else {
		//eventICS, err := ioutil.ReadFile(cacheLocation + "/" + eventFilename)
		contactVCFByte, err := ioutil.ReadFile(contactFilePath)
		if err != nil {
			log.Fatal(err)
		}

		contactVCF = string(contactVCFByte)
		if contactEdit == true {
			contactFileName = path.Base(contactFilePath) // use old filename again
		} else {
			contactFileName = genUUID() + `.ics` // no edit, so new filename
		}
	}
	req, _ := http.NewRequest("PUT", config.Addressbooks[abNo].Url+contactFileName, strings.NewReader(contactVCF))
	req.SetBasicAuth(config.Addressbooks[abNo].Username, config.Addressbooks[abNo].Password)
	req.Header.Add("Content-Type", "text/calendar; charset=utf-8")

	cli := &http.Client{}
	resp, err := cli.Do(req)
	defer resp.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Status)

	return
}

func displayVCF() {
	scanner := bufio.NewScanner(os.Stdin)

	var vcfData string

	for scanner.Scan() {
		vcfData += scanner.Text() + "\n"
	}

	parseMain(&vcfData, &contactsSlice, "none", "none")
	for _, e := range contactsSlice {
		e.vcfOutput()
	}

	if err := scanner.Err(); err != nil {
		log.Println(err)
	}

}

func editContact(abNo int, contactFilename string) (status string) {
	toFile = true
	contactEdit := true
	dumpContact(abNo, contactFilename, toFile)
	//fmt.Println(appointmentEdit)
	filePath := cacheLocation + "/" + contactFilename
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		log.Fatal(err)
	}
	beforeMTime := fileInfo.ModTime()

	shell := exec.Command(editor, filePath)
	shell.Stdout = os.Stdin
	shell.Stdin = os.Stdin
	shell.Stderr = os.Stderr
	shell.Run()

	fileInfo, err = os.Stat(filePath)
	if err != nil {
		log.Fatal(err)
	}
	afterMTime := fileInfo.ModTime()

	if beforeMTime.Before(afterMTime) {
		uploadVCF(abNo, filePath, contactEdit)
	} else {
		log.Fatal("no changes")
	}

	return
}