transmet/news/news.go

102 lines
2.6 KiB
Go
Raw Normal View History

package news
import (
"time"
"database/sql"
_ "github.com/lib/pq"
"fmt"
2015-05-13 06:21:06 +00:00
"github.com/dballard/transmet/categories"
)
type News struct {
news_id int
Url string
Title string
2015-05-12 05:06:28 +00:00
Category_id int
Date time.Time
2015-05-12 05:06:28 +00:00
Notes string
2015-05-12 05:50:09 +00:00
Expoerted bool
}
type NewsContainer struct {
Name string
News []News
Children map[int]*NewsContainer
}
func (news *News) Insert(db *sql.DB) error {
2015-05-12 05:06:28 +00:00
_, 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
2015-05-12 05:50:09 +00:00
}
2015-05-13 06:21:06 +00:00
func nullStringToString(str *sql.NullString) string {
if str.Valid {
return str.String
} else {
return ""
}
}
func Unexported(db *sql.DB) (map[int]*NewsContainer, error) {
2015-05-13 06:21:06 +00:00
categories.LoadCategories(db)
rows, err := db.Query("SELECT url, title, category_id, timestamp, notes FROM news WHERE exported=false order by category_id ASC")
2015-05-12 05:50:09 +00:00
if err != nil {
fmt.Println("DB errpr reading unexported news: ", err)
return nil, err
}
newsTree := map[int]*NewsContainer{}
newsFlat := map[int]*NewsContainer{}
2015-05-12 05:50:09 +00:00
for rows.Next() {
news := News{}
2015-05-13 06:21:06 +00:00
var url, title, notes sql.NullString
var date, category_id sql.NullInt64
err := rows.Scan(&url, &title, &category_id, &news.Date, &notes)
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(&notes)
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)
}
var container *NewsContainer
var ok bool
fmt.Println("cid: ", cid)
if container, ok = newsFlat[cid]; !ok {
fmt.Println("ADDING")
// need new container for new cid
container = &NewsContainer{ Name: categories.CategoriesFlat[cid].Name, News: []News{}, Children: map[int]*NewsContainer{} }
newsFlat[cid] = container
parent := categories.CategoriesFlat[cid].Parent
if parent.Valid {
fmt.Println("parent: ", parent.Int64)
newsFlat[int(parent.Int64)].Children[cid] = container
} else {
fmt.Println("no parent")
newsTree[cid] = container
}
}
container.News = append(container.News, news)
}
2015-05-12 05:50:09 +00:00
return newsTree, nil
}