-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
87 lines (71 loc) · 1.38 KB
/
app.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
package main
import (
"fmt"
"net/url"
"strings"
)
type App struct {
hosts *Hosts
storage *Storage
}
func NewApp(
hosts *Hosts,
storage *Storage,
) *App {
return &App{
hosts: hosts,
storage: storage,
}
}
type Cmd struct {
Unblock bool
Block bool
Website string
}
func (app *App) Handle(cmd Cmd) error {
switch {
case cmd.Website != "": // Banning a website
return app.banWebsite(cmd.Website)
case cmd.Unblock:
return app.unblock()
case cmd.Block:
return app.block()
default:
if isPaused, err := app.storage.IsStatus(StatusPaused); err != nil {
return err
} else if isPaused {
fmt.Println("Application in paused state. Doing nothing")
return nil // Do nothing
}
return app.block()
}
}
func (app *App) banWebsite(website string) error {
if !strings.HasPrefix(website, "http") {
website = "http://" + website
}
u, err := url.ParseRequestURI(website)
if err != nil {
return fmt.Errorf("%w", err)
}
web := strings.ToLower(u.Hostname())
fmt.Printf("Banning %q...\n", web)
return app.storage.BanWebsite(web)
}
func (app *App) block() error {
if err := app.storage.Resume(); err != nil {
return err
}
webs, err := app.storage.Websites()
if err != nil {
return err
}
return app.hosts.Block(webs)
}
func (app *App) unblock() error {
webs, err := app.storage.Websites()
if err != nil {
return err
}
return app.hosts.Block(webs)
}