108 lines
2.8 KiB
Go
108 lines
2.8 KiB
Go
package news
|
|
|
|
import (
|
|
"time"
|
|
"database/sql"
|
|
_ "github.com/lib/pq"
|
|
"fmt"
|
|
"github.com/dballard/transmet/categories"
|
|
|
|
)
|
|
|
|
type News struct {
|
|
news_id int
|
|
Url string
|
|
Title string
|
|
Category_id int
|
|
Date time.Time
|
|
Notes string
|
|
Expoerted bool
|
|
}
|
|
|
|
type NewsContainer struct {
|
|
Name string
|
|
News []News
|
|
Category *categories.Category
|
|
Children map[int]*NewsContainer
|
|
}
|
|
|
|
func (news *News) Insert(db *sql.DB) error {
|
|
_, err := db.Exec("INSERT INTO news (url, title, category_id, notes) VALUES($1, $2, $3, $4)", news.Url, news.Title, news.Category_id, news.Notes );
|
|
if err != nil {
|
|
fmt.Println("Error inserting news: ", err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func nullStringToString(str *sql.NullString) string {
|
|
if str.Valid {
|
|
return str.String
|
|
} else {
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func addContainer(category_id int, flat, tree map[int]*NewsContainer) {
|
|
container := &NewsContainer{ Category: categories.CategoriesFlat[category_id], Name: categories.CategoriesFlat[category_id].Name, News: []News{}, Children: map[int]*NewsContainer{} }
|
|
flat[category_id] = container
|
|
parent := categories.CategoriesFlat[category_id].Parent
|
|
if parent.Valid {
|
|
if _, ok := flat[int(parent.Int64)]; !ok {
|
|
addContainer(int(parent.Int64), flat, tree)
|
|
}
|
|
flat[int(parent.Int64)].Children[category_id] = container
|
|
} else {
|
|
tree[category_id] = container
|
|
}
|
|
}
|
|
|
|
func Unexported(db *sql.DB) (map[int]*NewsContainer, error) {
|
|
categories.LoadCategories(db)
|
|
|
|
rows, err := db.Query("SELECT url, title, category_id, timestamp, notes FROM news WHERE exported=false order by category_id ASC")
|
|
if err != nil {
|
|
fmt.Println("DB errpr reading unexported news: ", err)
|
|
return nil, err
|
|
}
|
|
newsTree := map[int]*NewsContainer{}
|
|
newsFlat := map[int]*NewsContainer{}
|
|
|
|
for rows.Next() {
|
|
news := News{}
|
|
var url, title, notes sql.NullString
|
|
var date, category_id sql.NullInt64
|
|
err := rows.Scan(&url, &title, &category_id, &news.Date, ¬es)
|
|
if err != nil {
|
|
fmt.Println("Error reading news from DB: " + err.Error())
|
|
return nil, err
|
|
}
|
|
|
|
news.Url = nullStringToString(&url)
|
|
news.Title = nullStringToString(&title)
|
|
news.Notes = nullStringToString(¬es)
|
|
|
|
if date.Valid {
|
|
news.Date = time.Unix(date.Int64, 0)
|
|
} else {
|
|
news.Date = time.Now()
|
|
}
|
|
|
|
cid := 1
|
|
if category_id.Valid {
|
|
cid = int(category_id.Int64)
|
|
}
|
|
|
|
if _, ok := newsFlat[cid]; !ok {
|
|
addContainer(cid, newsFlat, newsTree)
|
|
}
|
|
container := newsFlat[cid]
|
|
container.News = append(container.News, news)
|
|
}
|
|
|
|
return newsTree, nil
|
|
}
|
|
|
|
func (this *NewsContainer) HeaderDepth(start int) int {
|
|
return start + this.Category.Depth()
|
|
} |