Skip to content

Commit f3124a7

Browse files
committed
Add ability to update posts
Finishes issue #1
1 parent 8f7d273 commit f3124a7

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

writeas/cli.go

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,22 @@ func main() {
8181
},
8282
},
8383
},
84+
{
85+
Name: "update",
86+
Usage: "Update (overwrite) a post",
87+
Action: cmdUpdate,
88+
Flags: []cli.Flag{
89+
cli.BoolFlag{
90+
Name: "tor, t",
91+
Usage: "Update via Tor hidden service",
92+
},
93+
cli.IntFlag{
94+
Name: "tor-port",
95+
Usage: "Use a different port to connect to Tor",
96+
Value: 9150,
97+
},
98+
},
99+
},
84100
{
85101
Name: "get",
86102
Usage: "Read a raw post",
@@ -207,6 +223,35 @@ func cmdDelete(c *cli.Context) {
207223
DoDelete(friendlyId, token, tor)
208224
}
209225

226+
func cmdUpdate(c *cli.Context) {
227+
friendlyId := c.Args().Get(0)
228+
token := c.Args().Get(1)
229+
if friendlyId == "" {
230+
fmt.Println("usage: writeas update <postId> [<token>]")
231+
os.Exit(1)
232+
}
233+
234+
if token == "" {
235+
// Search for the token locally
236+
token = tokenFromID(friendlyId)
237+
if token == "" {
238+
fmt.Println("Couldn't find an edit token locally. Did you create this post here?")
239+
fmt.Printf("If you have an edit token, use: writeas update %s <token>\n", friendlyId)
240+
os.Exit(1)
241+
}
242+
}
243+
244+
// Read post body
245+
fullPost := readStdIn()
246+
247+
tor := c.Bool("tor") || c.Bool("t")
248+
if c.Int("tor-port") != 0 {
249+
torPort = c.Int("tor-port")
250+
}
251+
252+
DoUpdate(fullPost, friendlyId, token, tor)
253+
}
254+
210255
func cmdGet(c *cli.Context) {
211256
friendlyId := c.Args().Get(0)
212257
if friendlyId == "" {
@@ -340,6 +385,35 @@ func DoPost(post []byte, encrypt, tor bool) {
340385
}
341386
}
342387

388+
func DoUpdate(post []byte, friendlyId, token string, tor bool) {
389+
urlStr, client := client(false, tor, "", fmt.Sprintf("id=%s&t=%s", friendlyId, token))
390+
391+
data := url.Values{}
392+
data.Set("w", string(post))
393+
394+
r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
395+
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
396+
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
397+
398+
resp, err := client.Do(r)
399+
check(err)
400+
defer resp.Body.Close()
401+
402+
if resp.StatusCode == http.StatusOK {
403+
if tor {
404+
fmt.Println("Post updated via hidden service.")
405+
} else {
406+
fmt.Println("Post updated.")
407+
}
408+
} else {
409+
if DEBUG {
410+
fmt.Printf("Problem updating: %s\n", resp.Status)
411+
} else {
412+
fmt.Printf("Post doesn't exist, or bad edit token given.\n")
413+
}
414+
}
415+
}
416+
343417
func DoDelete(friendlyId, token string, tor bool) {
344418
urlStr, client := client(false, tor, "", fmt.Sprintf("id=%s&t=%s", friendlyId, token))
345419

0 commit comments

Comments
 (0)