upgrade to .todo. inbox

This commit is contained in:
Bel LaPointe
2023-11-09 08:24:08 -07:00
parent 6a70c6d2ac
commit e3d821e219
6 changed files with 69 additions and 163 deletions

View File

@@ -1,27 +1,20 @@
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"gogs.inhome.blapointe.com/local/oauth2"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
"github.com/google/uuid"
)
func Upload(config Config, transaction *Transaction) error {
switch config.Uploader {
case UploaderTodo:
return uploadTodo(config, transaction)
panic("DEAD")
case UploaderLedger:
return uploadLedger(config, transaction)
case UploaderPTTodo:
@@ -31,67 +24,14 @@ func Upload(config Config, transaction *Transaction) error {
}
}
func uploadTodo(config Config, transaction *Transaction) error {
params := url.Values{
"list": {config.TodoList},
"title": {transaction.Format()},
"tag": {config.TodoTag},
}
req, err := http.NewRequest("POST", config.TodoAddr+"/ajax.php?newTask", strings.NewReader(params.Encode()))
if err != nil {
return err
}
req.Header.Set("Cookie", oauth2.COOKIE+"="+config.TodoToken)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("bad status from todo: %v: %s", resp.StatusCode, b)
}
return nil
}
func uploadPTTodo(config Config, transaction *Transaction) error {
b, err := ioutil.ReadFile(config.TodoAddr)
if os.IsNotExist(err) {
b = []byte("todo:\n")
} else if err != nil {
return err
} else if len(b) == 0 {
b = []byte("todo:\n")
}
f, err := ioutil.TempFile(path.Dir(config.TodoAddr), path.Base("."+config.TodoAddr))
f, err := os.Create(fmt.Sprintf("%s.todo.%s", config.TodoAddr, uuid.New().String()))
if err != nil {
return err
}
defer f.Close()
sep := []byte{'\n'}
seek := []byte("todo:")
for len(b) > 0 {
idx := bytes.Index(b, sep)
if idx == -1 {
idx = len(b) - 1
}
fmt.Fprintf(f, "%s\n", b[:idx])
if bytes.Equal(bytes.TrimSpace(b[:idx]), seek) {
fmt.Fprintf(f, `- {"todo":%q, "tags":%q}%s`, transaction.Format(), config.TodoTag, "\n")
}
b = b[idx+1:]
}
f.Close()
var v interface{}
b, err = ioutil.ReadFile(f.Name())
if err != nil {
return err
}
if err := yaml.Unmarshal(b, &v); err != nil {
return err
}
return os.Rename(f.Name(), config.TodoAddr)
fmt.Fprintf(f, `- {"todo":%q, "tags":%q}%s`, transaction.Format(), config.TodoTag, "\n")
return f.Close()
}
func uploadLedger(config Config, transaction *Transaction) error {