intake/cmd/itemAdd.go

101 lines
2.5 KiB
Go

package cmd
import (
"encoding/json"
"log"
"github.com/Jaculabilis/intake/core"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/cobra"
)
var itemAddCmd = &cobra.Command{
Use: "add",
Short: "Add an item",
Long: `Create an ad-hoc item in a source.
By default, the item is created in the "default" source, which is created
if it doesn't exist, with a random id.`,
Run: func(cmd *cobra.Command, args []string) {
itemAdd(
stringArg(cmd, "source"),
stringArg(cmd, "id"),
stringArg(cmd, "title"),
stringArg(cmd, "author"),
stringArg(cmd, "body"),
stringArg(cmd, "link"),
intArg(cmd, "time"),
intArg(cmd, "ttl"),
intArg(cmd, "ttd"),
intArg(cmd, "tts"),
stringArg(cmd, "action"),
)
},
}
func init() {
itemCmd.AddCommand(itemAddCmd)
itemAddCmd.Flags().StringP("source", "s", "", "Source in which to create the item (default: default)")
itemAddCmd.Flags().StringP("id", "i", "", "Item id (default: random hex)")
itemAddCmd.Flags().StringP("title", "t", "", "Item title")
itemAddCmd.Flags().StringP("author", "a", "", "Item author")
itemAddCmd.Flags().StringP("body", "b", "", "Item body")
itemAddCmd.Flags().StringP("link", "l", "", "Item link")
itemAddCmd.Flags().IntP("time", "m", 0, "Item time as a Unix timestamp")
itemAddCmd.Flags().Int("ttl", 0, "Item time-to-live in seconds, relative to item creation date")
itemAddCmd.Flags().Int("ttd", 0, "Item time-to-die in seconds, relative to item creation date")
itemAddCmd.Flags().Int("tts", 0, "Item time-to-show in seconds, relative to item creation date")
itemAddCmd.Flags().StringP("action", "x", "", "Item action data as JSON")
}
func itemAdd(
source string,
id string,
title string,
author string,
body string,
link string,
time int,
ttl int,
ttd int,
tts int,
actions string,
) {
// Default to "default" source
if source == "" {
source = "default"
}
// Default id to random hex string
if id == "" {
id = core.RandomHex(16)
}
var itemActions core.Actions
if actions != "" {
if err := json.Unmarshal([]byte(actions), &itemActions); err != nil {
log.Fatalf("error: could not parse actions: %v", err)
}
}
db := openAndMigrateDb()
if err := core.AddItems(db, []core.Item{{
Source: source,
Id: id,
Title: title,
Author: author,
Body: body,
Link: link,
Time: time,
Ttl: ttl,
Ttd: ttd,
Tts: tts,
Action: itemActions,
}}); err != nil {
log.Fatalf("error: failed to add item: %s", err)
}
log.Printf("Added %s/%s\n", source, id)
}