forked from talkkonnect/talkkonnect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
344 lines (292 loc) · 8.4 KB
/
utils.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
/*
* talkkonnect headless mumble client/gateway with lcd screen and channel control
* Copyright (C) 2018-2019, Suvir Kumar <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* talkkonnect is the based on talkiepi and barnard by Daniel Chote and Tim Cooper
*
* The Initial Developer of the Original Code is
* Suvir Kumar <[email protected]>
* Portions created by the Initial Developer are Copyright (C) Suvir Kumar. All Rights Reserved.
*
* Code Copied from https://www.socketloop.com/tutorials/golang-convert-seconds-to-human-readable-time-format-example
*
* Contributor(s):
*
* Suvir Kumar <[email protected]>
*
* My Blog is at www.talkkonnect.com
* The source code is hosted at github.com/talkkonnect
*
*
*/
package talkkonnect
import (
"archive/zip"
"fmt"
"io"
"log"
"math"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
externalip "github.com/glendc/go-external-ip"
"github.com/kennygrant/sanitize"
"github.com/talkkonnect/gumble/gumble"
term "github.com/talkkonnect/termbox-go"
"github.com/xackery/gomail"
)
func reset() {
term.Sync()
}
func esc(str string) string {
return sanitize.HTML(str)
}
func cleanstring(str string) string {
return sanitize.Name(str)
}
func plural(count int, singular string) (result string) {
if (count == 1) || (count == 0) {
result = strconv.Itoa(count) + " " + singular + " "
} else {
result = strconv.Itoa(count) + " " + singular + "s "
}
return
}
func secondsToHuman(input int) (result string) {
years := math.Floor(float64(input) / 60 / 60 / 24 / 7 / 30 / 12)
seconds := input % (60 * 60 * 24 * 7 * 30 * 12)
months := math.Floor(float64(seconds) / 60 / 60 / 24 / 7 / 30)
seconds = input % (60 * 60 * 24 * 7 * 30)
weeks := math.Floor(float64(seconds) / 60 / 60 / 24 / 7)
seconds = input % (60 * 60 * 24 * 7)
days := math.Floor(float64(seconds) / 60 / 60 / 24)
seconds = input % (60 * 60 * 24)
hours := math.Floor(float64(seconds) / 60 / 60)
seconds = input % (60 * 60)
minutes := math.Floor(float64(seconds) / 60)
seconds = input % 60
if years > 0 {
result = plural(int(years), "year") + plural(int(months), "month") + plural(int(weeks), "week") + plural(int(days), "day") + plural(int(hours), "hour") + plural(int(minutes), "minute") + plural(int(seconds), "second")
} else if months > 0 {
result = plural(int(months), "month") + plural(int(weeks), "week") + plural(int(days), "day") + plural(int(hours), "hour") + plural(int(minutes), "minute") + plural(int(seconds), "second")
} else if weeks > 0 {
result = plural(int(weeks), "week") + plural(int(days), "day") + plural(int(hours), "hour") + plural(int(minutes), "minute") + plural(int(seconds), "second")
} else if days > 0 {
result = plural(int(days), "day") + plural(int(hours), "hour") + plural(int(minutes), "minute") + plural(int(seconds), "second")
} else if hours > 0 {
result = plural(int(hours), "hour") + plural(int(minutes), "minute") + plural(int(seconds), "second")
} else if minutes > 0 {
result = plural(int(minutes), "minute") + plural(int(seconds), "second")
} else {
result = plural(int(seconds), "second")
}
return
}
func localAddresses() {
ifaces, err := net.Interfaces()
if err != nil {
log.Print(fmt.Sprintf("error: localAddresses %v", err.Error()))
return
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
log.Print(fmt.Sprintf("error: localAddresses %v", err.Error()))
continue
}
for _, a := range addrs {
if i.Name != "lo" {
log.Printf("info: %v %v\n", i.Name, a)
}
}
}
}
func (b *Talkkonnect) pingconnectedserver() {
resp, err := gumble.Ping(b.Address, time.Second*1, time.Second*5)
if err != nil {
log.Println(fmt.Sprintf("error: Ping Error %s", err))
return
}
major, minor, patch := resp.Version.SemanticVersion()
log.Println("info: Server Address: ", resp.Address)
log.Println("info: Current Channel: ", b.Client.Self.Channel.Name)
log.Println("info: Server Ping: ", resp.Ping)
log.Println("info: Server Version: ", major, ".", minor, ".", patch)
log.Println("info: Server Users: ", resp.ConnectedUsers, "/", resp.MaximumUsers)
log.Println("info: Server Maximum Bitrate: ", resp.MaximumBitrate)
}
func sendviagmail(username string, password string, receiver string, subject string, message string) error {
err := gomail.Send(username, password, []string{receiver}, subject, message)
if err != nil {
return fmt.Errorf("sending Email Via GMAIL Error")
}
go LcdDisplay(LcdText, LCDRSPin, LCDEPin, LCDD4Pin, LCDD5Pin, LCDD6Pin, LCDD7Pin, LCDInterfaceType, LCDI2CAddress)
return nil
}
func zipit(source, target string) error {
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
info, err := os.Stat(source)
if err != nil {
return nil
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
return err
}
func createDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0777)
if err != nil {
panic(err)
}
}
}
func cleardir(dir string) {
// The target directory.
//directory := CamImageSavePath // path must end on "/"... fix for no "/"?
directory := dir + "/" // path with "/"
// Open the directory and read all its files.
dirRead, _ := os.Open(directory)
dirFiles, _ := dirRead.Readdir(0)
// Loop over the directory's files.
for index := range dirFiles {
fileHere := dirFiles[index]
// Get name of file and its full path.
nameHere := fileHere.Name()
fullPath := directory + nameHere
// Remove the files.
os.Remove(fullPath)
log.Println("info: Removed file", fullPath)
}
}
func dirIsEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
log.Println("debug: Dir is Not Empty")
return false, err // Not Empty
}
defer f.Close()
_, err = f.Readdirnames(1) // Or f.Readdir(1) // empty
if err == io.EOF {
log.Println("debug: Dir is Empty")
return true, nil
}
return false, err // Either not empty or error, suits both cases
}
func isCommandAvailable(name string) bool {
cmd := exec.Command("/bin/sh", "-c", "command -v "+name)
if err := cmd.Run(); err != nil {
return false
}
return true
}
func check(err error) {
if err != nil {
FatalCleanUp(err.Error())
}
}
func fmtDuration(d time.Duration) string {
d = d.Round(time.Minute)
//d = d.Round(time.Second)
h := d / time.Hour
d -= h * time.Hour
m := d / time.Minute
//s := m / time.Second
return fmt.Sprintf("%02d:%02d", h, m) // show sec’s also?
}
func before(value string, a string) string { // used for sox time
// Get substring before a string.
pos := strings.Index(value, a)
if pos == -1 {
return ""
}
return value[0:pos]
}
func getMacAddr() ([]string, error) {
ifas, err := net.Interfaces()
if err != nil {
return nil, err
}
var as []string
for _, ifa := range ifas {
a := ifa.HardwareAddr.String()
if a != "" {
as = append(as, a)
}
}
return as, nil
}
func getOutboundIP() string {
consensus := externalip.DefaultConsensus(nil, nil)
ip, err := consensus.ExternalIP()
if err == nil {
return ip.String()
}
return "Could Not Get Public WAN IP"
}
func FileExists(filepath string) bool {
fileinfo, err := os.Stat(filepath)
if os.IsNotExist(err) {
return false
}
return !fileinfo.IsDir()
}
func restart() {
time.Sleep(2 * time.Second)
c := exec.Command("reset")
c.Stdout = os.Stdout
c.Run()
os.Exit(0)
}