2024-03-10 15:26:00 -05:00
|
|
|
package models
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
2024-03-11 16:04:29 -05:00
|
|
|
// A slice of Meta
|
2024-03-10 15:26:00 -05:00
|
|
|
type Metas []Meta
|
|
|
|
|
|
2024-03-11 16:04:29 -05:00
|
|
|
// Returns a single map containing all the Meta. Is useful when encoding to JSON
|
|
|
|
|
func (ms Metas) Map() map[string]any {
|
2024-03-10 15:26:00 -05:00
|
|
|
out := map[string]any{}
|
|
|
|
|
for _, f := range ms {
|
|
|
|
|
if _, found := out[f.Key]; found || f.Key == "title" || f.Key == "date" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if f.Key == "json" {
|
|
|
|
|
ob := map[string]any{}
|
|
|
|
|
if j, ok := f.Value.(json.RawMessage); ok {
|
|
|
|
|
json.Unmarshal(j, &ob)
|
|
|
|
|
}
|
|
|
|
|
// If we couldn't get valid data from there, this will just be empty
|
|
|
|
|
for k, v := range ob {
|
|
|
|
|
if k != "title" && k != "date" {
|
|
|
|
|
out[k] = v
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
out[f.Key] = f.Value
|
|
|
|
|
if vt, ok := f.Value.(time.Time); ok {
|
|
|
|
|
out[f.Key] = vt.Format(time.RFC3339)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-11 16:04:29 -05:00
|
|
|
// Implements json.Marshaler
|
2024-03-10 15:26:00 -05:00
|
|
|
func (ms Metas) MarshalJSON() ([]byte, error) {
|
2024-03-11 16:04:29 -05:00
|
|
|
return json.Marshal(ms.Map())
|
2024-03-10 15:26:00 -05:00
|
|
|
}
|
|
|
|
|
|
2024-03-11 16:04:29 -05:00
|
|
|
// Implements json.Unmarshaler
|
2024-03-10 15:26:00 -05:00
|
|
|
func (ms *Metas) UnmarshalJSON(in []byte) error {
|
2024-03-11 16:04:29 -05:00
|
|
|
old := (*ms).Map()
|
2024-03-10 15:26:00 -05:00
|
|
|
out := map[string]any{}
|
|
|
|
|
err := json.Unmarshal(in, &out)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
ret := *ms
|
|
|
|
|
for k, v := range out {
|
|
|
|
|
if _, found := old[k]; k != "title" && k != "date" && !found {
|
|
|
|
|
ret = append(ret, Meta{k, v})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
*ms = ret
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2024-03-11 16:04:29 -05:00
|
|
|
|
|
|
|
|
// Returns a new Metas with a new Meta appended
|
|
|
|
|
func (ms Metas) Append(k string, v any) Metas {
|
|
|
|
|
return append(ms, Meta{k, v})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Appends a new Meta to this Metas
|
|
|
|
|
func (ms *Metas) AppendTo(k string, v any) {
|
|
|
|
|
n := (*ms).Append(k, v)
|
|
|
|
|
*ms = n
|
|
|
|
|
}
|