5
5
"errors"
6
6
"fmt"
7
7
"github.com/zcong1993/leetcode-tool/internal/config"
8
+ "io"
8
9
"io/ioutil"
9
10
"net/http"
10
11
"os"
@@ -13,6 +14,8 @@ import (
13
14
"github.com/tidwall/gjson"
14
15
)
15
16
17
+ const RemoteProblems = "https://raw.githubusercontent.com/PPsteven/leetcode-tool/master/data/problems.json"
18
+
16
19
type Meta struct {
17
20
Index string
18
21
Title string
@@ -47,10 +50,43 @@ func NewLeetcode(config *config.Config) *Leetcode {
47
50
return & Leetcode {Config : config }
48
51
}
49
52
53
+ func DownloadFile (remoteFile string ) error {
54
+ // Create the file
55
+ out , err := os .Create ("data/problems.json" )
56
+ if err != nil {
57
+ return err
58
+ }
59
+ defer out .Close ()
60
+
61
+ resp , err := http .Get (remoteFile )
62
+ if err != nil {
63
+ return err
64
+ }
65
+ defer resp .Body .Close ()
66
+
67
+ // Write the body to file
68
+ _ , err = io .Copy (out , resp .Body )
69
+ if err != nil {
70
+ return err
71
+ }
72
+
73
+ return nil
74
+ }
75
+
50
76
func (l * Leetcode ) getAllProblem () ([]byte , error ) {
51
- file , err := ioutil .ReadFile ("/Users/ppsteven/Projects/leetcode-tool/data/problems.json" )
52
- if err == os .ErrNotExist {
53
- return nil , errors .New ("234324" )
77
+ file , err := ioutil .ReadFile ("data/problems.json" )
78
+ if err != nil && errors .Is (err , os .ErrNotExist ) {
79
+ fmt .Println (fmt .Sprintf ("file problems.json not exists, start downloading from %s" , RemoteProblems ))
80
+ err = DownloadFile (RemoteProblems )
81
+
82
+ if err != nil {
83
+ return nil , fmt .Errorf ("download file failed: %v" , err )
84
+ }
85
+ file , err := ioutil .ReadFile ("data/problems.json" )
86
+ if err != nil {
87
+ return nil , fmt .Errorf ("read file failed: %v" , err )
88
+ }
89
+ return file , nil
54
90
}
55
91
return file , nil
56
92
}
@@ -97,16 +133,21 @@ func (l *Leetcode) GetMetaByNumber(number string) (*Meta, error) {
97
133
}
98
134
99
135
func (l * Leetcode ) GetTags () ([]Tag , error ) {
100
- resp , err := http .Get ("https://leetcode-cn.com/problems/api/tags/" )
101
- if err != nil {
102
- return nil , err
136
+ if l .Problems == nil {
137
+ l .Problems , _ = l .getAllProblem ()
103
138
}
104
- defer resp .Body .Close ()
105
- bt , err := ioutil .ReadAll (resp .Body )
106
- if err != nil {
107
- return nil , err
139
+
140
+ tags := make ([]Tag , 0 )
141
+ tagsMap := make (map [string ]Tag )
142
+ for _ , problem := range gjson .ParseBytes (l .Problems ).Map () {
143
+ _ = json .Unmarshal ([]byte (problem .Get ("topicTags" ).Raw ), & tags )
144
+ for _ , tag := range tags {
145
+ tagsMap [tag .Slug ] = tag
146
+ }
147
+ }
148
+ tags = make ([]Tag , 0 , len (tagsMap ))
149
+ for _ , tag := range tagsMap {
150
+ tags = append (tags , tag )
108
151
}
109
- res := make ([]Tag , 0 )
110
- err = json .Unmarshal ([]byte (gjson .GetBytes (bt , "topics" ).Raw ), & res )
111
- return res , err
152
+ return tags , nil
112
153
}
0 commit comments