-
Notifications
You must be signed in to change notification settings - Fork 7
/
task.go
350 lines (327 loc) · 8.82 KB
/
task.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
package main
import (
"flag"
"fmt"
"os"
"runtime"
"strconv"
"strings"
"time"
"github.com/0xAX/notificator"
"github.com/ProtonMail/go-autostart"
"github.com/fatih/color"
"github.com/olebedev/when"
"github.com/olebedev/when/rules/common"
"github.com/olebedev/when/rules/en"
"github.com/olekukonko/tablewriter"
"github.com/segmentio/go-prompt"
"github.com/thedevsaddam/task/taskmanager"
)
const usage = `Usage:
Name:
Terminal Task
Description:
Your favorite terminal task manager and reminder!
Version:
1.0.0
$ task
Show all tasks
$ task p
Show all pending tasks
$ task a Watch Games of thrones
Add a new task [Watch Games of thrones] to list
$ task remind Meeting with John tomorrow at 10:30pm
This will send you a desktop notification
$ task del
Remove latest task from list
$ task rm ID
Remove task of ID from list
$ task s ID
Show detail view task of ID
$ task c ID
Mark task of ID as completed
$ task m ID Pirates of the Caribbean
Modify a task
$ task p ID
Mark task of ID as pending
$ task flush
Flush the database!
$ task service-start
Run task as service if you are using reminder
$ task service-stop
Unregister Task from service!
`
const (
completedSign = "\u2713"
pendingSign = "\u2613"
dateTimeLayout = "2006-01-02 15:04"
refreshRate = 40
)
var (
//task manager instance
tm = taskmanager.New()
//notifier
notify *notificator.Notificator
//run a service
service = autostart.App{
Name: "thedevsaddam_terminal_task",
DisplayName: "Task",
Exec: []string{"/usr/local/bin/task", "listen-reminder-queue"},
}
)
func main() {
flag.Usage = func() {
fmt.Fprint(os.Stderr, usage)
flag.PrintDefaults()
}
flag.Parse()
cmd, args, argsLen := flag.Arg(0), flag.Args(), len(flag.Args())
switch {
case cmd == "" || cmd == "l" || cmd == "ls" && argsLen == 1:
showTasksInTable(tm.GetAllTasks())
case cmd == "a" || cmd == "add" && argsLen >= 1:
if len(args[1:]) <= 0 {
warningText(" Task description can not be empty \n")
return
}
tm.Add(strings.Join(args[1:], " "), "", "")
successText(" Added to list: " + strings.Join(args[1:], " ") + " ")
case cmd == "reminder" || cmd == "remind" || cmd == "remind-me" && argsLen >= 1:
if len(args[1:]) <= 0 {
warningText(" Task/Reminder description can not be empty \n")
return
}
reminder := strings.Join(args[1:], " ")
action, actionWhen := parseReminder(reminder)
tm.Add(action, "", actionWhen)
successText(" Reminder Added: " + action + " ")
case cmd == "p" || cmd == "pending" && argsLen == 1:
showTasksInTable(tm.GetPendingTasks())
case cmd == "del" || cmd == "delete" && argsLen == 1:
p := prompt.Choose("Do you want to delete latest task?", []string{"yes", "no"})
if p == 1 {
warningText(" Task delete aboarted! ")
return
}
err := tm.RemoveTask(tm.GetLastId())
if err != nil {
errorText(err.Error())
return
}
successText(" Removed latest task ")
case cmd == "r" || cmd == "rm" && argsLen == 2:
id, _ := strconv.Atoi(flag.Arg(1))
p := prompt.Choose("Do you want to delete task of id "+flag.Arg(1)+" ?", []string{"yes", "no"})
if p == 1 {
warningText(" Task delete aboarted! ")
return
}
err := tm.RemoveTask(id)
if err != nil {
errorText(err.Error())
return
}
successText(" Task " + strconv.Itoa(id) + " removed! ")
case cmd == "e" || cmd == "m" || cmd == "u" && argsLen >= 2:
id, _ := strconv.Atoi(flag.Arg(1))
ok, _ := tm.UpdateTask(id, strings.Join(args[2:], " "))
successText(ok)
case cmd == "c" || cmd == "d" || cmd == "done" && argsLen >= 2:
id, _ := strconv.Atoi(flag.Arg(1))
task, err := tm.MarkAsCompleteTask(id)
if err != nil {
errorText(err.Error())
return
}
successText(" " + completedSign + " " + task.Description)
case cmd == "i" || cmd == "p" || cmd == "pending" && argsLen >= 2:
id, _ := strconv.Atoi(flag.Arg(1))
task, err := tm.MarkAsPendingTask(id)
if err != nil {
errorText(err.Error())
return
}
successText(" " + pendingMark() + " " + task.Description)
case cmd == "s" && argsLen == 2:
id, _ := strconv.Atoi(flag.Arg(1))
task, err := tm.GetTask(id)
if err != nil {
errorText(err.Error())
return
}
showTask(task)
case cmd == "flush":
p := prompt.Choose("Do you want to delete all tasks?", []string{"yes", "no"})
if p == 1 {
warningText(" Flush aborted! ")
return
}
err := tm.FlushDB()
if err != nil {
errorText(err.Error())
return
}
successText(" Database flushed successfully! ")
case cmd == "service-start" && argsLen == 1:
serviceStart()
case cmd == "service-force-start" && argsLen == 1:
serviceForceStart()
case cmd == "service-stop" && argsLen == 1:
serviceStop()
case cmd == "listen-reminder-queue" && argsLen == 1:
listenReminderQueue()
case cmd == "h" || cmd == "v":
fmt.Fprint(os.Stderr, usage)
default:
errorText(" [No command found by " + cmd + "] ")
fmt.Fprint(os.Stderr, "\n"+usage)
}
}
//show tasks list in table
func showTasksInTable(tasks taskmanager.Tasks) {
fmt.Fprintln(os.Stdout, "")
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ID", "Description", completedSign + "/" + pendingMark(), "Created"})
table.SetBorders(tablewriter.Border{Left: true, Top: true, Right: true, Bottom: false})
table.SetFooter([]string{"", "Total: " + strconv.Itoa(tm.TotalTask()), "", "Pending: " + strconv.Itoa(tm.PendingTask())})
table.SetCenterSeparator("|")
table.SetRowLine(true)
for _, task := range tasks {
//set completed icon
status := pendingSign
if task.Completed != "" {
status = completedSign
} else {
status = pendingMark()
}
table.Append([]string{
strconv.Itoa(task.Id),
task.Description,
status,
task.Created,
})
}
table.Render()
fmt.Fprintln(os.Stdout, "")
}
//show a single tasks
func showTask(task taskmanager.Task) {
fmt.Fprintln(os.Stdout, "")
printText("Task Details view")
printText("--------------------------------")
printText("ID: " + strconv.Itoa(task.Id))
printText("UID: " + task.UID)
printText("Description: " + task.Description)
printText("Tag: " + task.Tag)
printText("Created: " + task.Created)
printText("Updated: " + task.Updated)
fmt.Fprintln(os.Stdout, "")
}
func printText(str string) {
fmt.Fprintf(os.Stdout, str+"\n")
}
func printBoldText(str string) {
if runtime.GOOS == "windows" {
fmt.Fprintf(os.Stdout, str+"\n")
} else {
bold := color.New(color.Bold).FprintlnFunc()
bold(os.Stdout, str)
}
}
func successText(str string) {
if runtime.GOOS == "windows" {
fmt.Fprintf(color.Output, color.GreenString(str))
} else {
success := color.New(color.Bold, color.BgGreen, color.FgWhite).FprintlnFunc()
success(os.Stdout, str)
}
}
func warningText(str string) {
if runtime.GOOS == "windows" {
fmt.Fprintf(color.Output, color.YellowString(str))
} else {
warning := color.New(color.Bold, color.BgYellow, color.FgBlack).FprintlnFunc()
warning(os.Stdout, str)
}
}
func errorText(str string) {
if runtime.GOOS == "windows" {
fmt.Fprintf(color.Output, color.RedString(str))
} else {
errColor := color.New(color.Bold, color.BgRed, color.FgWhite).FprintlnFunc()
errColor(os.Stdout, str)
}
}
func pendingMark() string {
pending := pendingSign
if runtime.GOOS == "windows" {
pending = "x"
}
return pending
}
//parse reminder
func parseReminder(reminder string) (string, string) {
defer func() {
if r := recover(); r != nil {
errorText(" Your reminder does not contain any date time reference! ")
os.Exit(1)
}
}()
w := when.New(nil)
w.Add(en.All...)
w.Add(common.All...)
r, _ := w.Parse(reminder, time.Now())
action := strings.Replace(reminder, reminder[r.Index:r.Index+len(r.Text)], "", -1)
actionTime := r.Time.Format(dateTimeLayout)
return action, actionTime
}
//listen for reminder queue
func listenReminderQueue() {
for {
rm := taskmanager.New()
reminderList := rm.GetReminderTasks()
now := time.Now().Format(dateTimeLayout)
for _, r := range reminderList {
if r.RemindAt == now {
desktopNotifier("Task Reminder!", r.Description)
rm.MarkAsCompleteTask(r.Id)
}
}
time.Sleep(time.Second * refreshRate)
}
}
//send desktop notification
func desktopNotifier(title, body string) {
notify = notificator.New(notificator.Options{
DefaultIcon: "default.png",
AppName: "Terminal Task",
})
notify.Push(title, body, "default.png", notificator.UR_NORMAL)
}
//enable auto start
func serviceStart() {
if service.IsEnabled() {
warningText("Task is already enabled as service!")
} else {
if err := service.Enable(); err != nil {
errorText(err.Error())
}
successText("Task has been registered as service!")
}
}
//disable auto start
func serviceStop() {
if service.IsEnabled() {
if err := service.Disable(); err != nil {
errorText(err.Error())
}
successText("Task has been removed from service!")
} else {
warningText("Task was not registered as service!")
}
}
//force start
func serviceForceStart() {
serviceStop()
serviceStart()
}