forked from kawalpemilu/kawalpemilu2019-extract
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sedot.go
113 lines (89 loc) · 1.66 KB
/
sedot.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"sync"
)
const (
ApiRoot = "https://kawal-c1.appspot.com/api/c/"
TpsDepth = 4
DataDir = "c"
)
func main() {
q := make([]int, 0)
q = append(q, 0)
for len(q) > 0 {
id := q[0]
q = q[1:]
node, err := readOrGetNode(id)
if err != nil {
log.Fatalf("Could not get the node %d: %v", id, err)
}
log.Printf("Node %d Depth %d", node.Id, node.Depth)
if node.Depth >= TpsDepth {
continue
}
var wg sync.WaitGroup
for _, ch := range node.Children {
cid := ch.Id()
q = append(q, cid)
wg.Add(1)
go func(id int) {
readOrGetNode(id)
wg.Done()
}(cid)
}
wg.Wait()
}
}
func readOrGet(id int) (io.ReadCloser, error) {
path := fmt.Sprintf("%s/%d.json", DataDir, id)
if _, err := os.Stat(path); os.IsNotExist(err) {
url := fmt.Sprintf("%s%d", ApiRoot, id)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
tmp := fmt.Sprintf("%s.tmp", path)
f, err := os.Create(tmp)
if err != nil {
return nil, err
}
_, err = io.Copy(f, resp.Body)
if err != nil {
return nil, err
}
f.Close()
err = os.Rename(tmp, path)
if err != nil {
return nil, err
}
}
return os.Open(path)
}
func readOrGetNode(id int) (Node, error) {
var node Node
b, err := readOrGet(id)
if err != nil {
return node, err
}
defer b.Close()
dec := json.NewDecoder(b)
err = dec.Decode(&node)
return node, err
}
type Node struct {
Id int `json:"id"`
Depth int `json:"depth"`
Children []Child `json:"children"`
}
type Child []interface{}
func (c Child) Id() int {
f := c[0].(float64)
return int(f)
}