Skip to content

Commit

Permalink
gophernews, no subcomments support...
Browse files Browse the repository at this point in the history
Squashed commit of the following:

commit 908dabb
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 23:23:26 2022 -0300

    take width from opts

commit b045b41
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 22:39:45 2022 -0300

    wg wait before sending the work

    possible fixing some race condition that caused comments not being displayed

commit 4e96c1d
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 21:23:46 2022 -0300

    cleanup

commit 8008c5d
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 21:20:21 2022 -0300

    skip deleted(? messages, add date of comments

commit 394bf4d
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 21:03:31 2022 -0300

    comments fetch working, only for the first level of comments

commit 8045e55
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 07:46:33 2022 -0300

    minor cleanup

commit 46f8ac5
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 07:26:23 2022 -0300

    add selfurl to op

commit a7e5ba4
Author: azimut <azimut.github@protonmail.com>
Date:   Tue Jul 26 07:19:02 2022 -0300

    just return story
  • Loading branch information
azimut committed Jul 27, 2022
1 parent ea2fee7 commit c48f0ad
Show file tree
Hide file tree
Showing 10 changed files with 164 additions and 142 deletions.
7 changes: 4 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ TW_URL := 'https://twitter.com/TwitterDev/status/1443269993676763138'
.PHONY: all test build clean install

all: test build
build: ; go build -x -v ./...
build: ; go build -race -x -v ./...
clean: ; go clean -x ./...
install: ; go install ./...
test:
go vet ./...
go test ./...
# go run cmd/hackerview/main.go -t 20s $(HN_URL)
go run cmd/twitterview/main.go -t 20s $(TW_URL)
testrun:
go run cmd/hackerview/main.go -t 20s $(HN_URL)
# go run cmd/twitterview/main.go -t 20s $(TW_URL)
4 changes: 2 additions & 2 deletions cmd/hackerview/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@ func run(args []string, stdout io.Writer) error {
return errors.New("missing URL argument")
}
url = flag.Args()[0]
doc, err := hackernews.Fetch(url, opt.userAgent, opt.timeout)
op, comments, err := hackernews.Fetch(url, opt.userAgent, opt.timeout)
if err != nil {
return errors.New("could not fetch url")
}
hackernews.PrintDoc(doc)
hackernews.Format(opt.width, op, comments)
return nil
}

Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (

require (
github.com/andybalholm/cascadia v1.2.0 // indirect
github.com/caser/gophernews v0.0.0-20150107061403-f17255d5b792
github.com/containerd/console v1.0.2 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.13 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ github.com/PuerkitoBio/goquery v1.7.1/go.mod h1:XY0pP4kfraEmmV1O7Uf6XyjoslwsneBb
github.com/andybalholm/cascadia v1.2.0 h1:vuRCkM5Ozh/BfmsaTm26kbjm0mIOM3yS5Ek/F5h18aE=
github.com/andybalholm/cascadia v1.2.0/go.mod h1:YCyR8vOZT9aZ1CHEd8ap0gMVm2aFgxBp0T0eFw1RUQY=
github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/caser/gophernews v0.0.0-20150107061403-f17255d5b792 h1:yWTZbMC92aSFyZm+f7iJTrLdV2Q3eEIreRoYmJE86lk=
github.com/caser/gophernews v0.0.0-20150107061403-f17255d5b792/go.mod h1:XAJyumv6flVGfp36Ii0+4mjkLLHZYlu+osSOpgsLHLs=
github.com/charmbracelet/bubbles v0.9.0 h1:lqJ8FXwoLceQF2J0A+dWo1Cuu1dNyjbW4Opgdi2vkhw=
github.com/charmbracelet/bubbles v0.9.0/go.mod h1:NWT/c+0rYEnYChz5qCyX4Lj6fDw9gGToh9EFJPajghU=
github.com/charmbracelet/bubbletea v0.14.1/go.mod h1:b5lOf5mLjMg1tRn1HVla54guZB+jvsyV0yYAQja95zE=
Expand Down
123 changes: 114 additions & 9 deletions internal/hackernews/fetch.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,130 @@
package hackernews

import (
"strings"
"errors"
"sync"
"time"

"github.com/PuerkitoBio/goquery"
"github.com/azimut/cli-view/internal/fetch"
"github.com/caser/gophernews"
)

func Fetch(url, ua string, timeout time.Duration) (doc *goquery.Document, err error) {
url, err = effectiveUrl(url)
const NUM_OF_WORKERS = 3

func unix2time(t int) time.Time {
return time.Unix(int64(t), 0)
}

func newOp(story *gophernews.Story, selfUrl string) Op {
return Op{
url: story.URL,
title: story.Title,
score: story.Score,
user: story.By,
date: unix2time(story.Time),
ncomments: len(story.Kids), // ?
selfUrl: selfUrl,
}
}

func Fetch(rawUrl, ua string, timeout time.Duration) (doc *Op, c *[]Comment, err error) {
url, storyId, err := effectiveUrl(rawUrl)
if err != nil {
return nil, err
return nil, nil, err
}
res, err := fetch.Fetch(url, ua, timeout)
client := gophernews.NewClient()
story, err := fetchStory(client, storyId)
if err != nil {
return nil, err
return nil, nil, err
}
doc, err = goquery.NewDocumentFromReader(strings.NewReader(res))
op := newOp(story, url)
comments := fetchComments(story.Kids) // TODO: error
return &op, &comments, nil
}

func fetchStory(client *gophernews.Client, id int) (*gophernews.Story, error) {
story, err := client.GetStory(id)
if err != nil {
return nil, err
}
if story.Type != "story" {
return nil, errors.New("is not a story")
}
return &story, nil
}

func fetchComments(comments []int) []Comment {
idsChan := make(chan int, 5)
commentsCh := make(chan result, 5)
var wg sync.WaitGroup
wg.Add(len(comments))
go sendWork(comments, idsChan)
go closeAfterWait(&wg, commentsCh)
spawnWorkers(&wg, idsChan, commentsCh)
return collector(&wg, idsChan, commentsCh)
}

func closeAfterWait(wg *sync.WaitGroup, commentsCh chan<- result) {
wg.Wait()
close(commentsCh)
}

func sendWork(ids []int, input chan<- int) {
for _, id := range ids {
input <- id
}
close(input)
}

func spawnWorkers(wg *sync.WaitGroup, in <-chan int, out chan<- result) {
for i := 0; i < NUM_OF_WORKERS; i++ {
go worker(wg, in, out)
}
}

type result struct {
comment gophernews.Comment
err error
}

func worker(wg *sync.WaitGroup, commentsChan <-chan int, output chan<- result) {
client := gophernews.NewClient()
for commentId := range commentsChan {
comment, err := client.GetComment(commentId)
if err != nil {
output <- result{err: err}
}
output <- result{comment: comment}
wg.Done()
}
}

func collector(
wg *sync.WaitGroup,
commentsCh chan<- int,
responseCh <-chan result,

) (state []Comment) {
for response := range responseCh {
if response.err != nil {
continue
}

c := response.comment

if c.Text == "" && len(c.Kids) == 0 {
continue
}

state = append(state, Comment{
id: c.ID,
msg: c.Text,
user: c.By,
kids: c.Kids,
date: unix2time(c.Time),
})
// for _, id := range c.Kids {
// commentsCh <- id
// }
}
return
}
82 changes: 0 additions & 82 deletions internal/hackernews/header.go

This file was deleted.

31 changes: 0 additions & 31 deletions internal/hackernews/header_test.go

This file was deleted.

28 changes: 20 additions & 8 deletions internal/hackernews/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@ import (
"strings"

text "github.com/MichaelMure/go-term-text"
"github.com/PuerkitoBio/goquery"
"github.com/dustin/go-humanize"
"github.com/jaytaylor/html2text"
)

func PrintDoc(doc *goquery.Document) {
fmt.Println(NewHeader(doc))
printChilds(NewComments(doc))
const SPACES_PER_INDENT = 5

var max_width int

func Format(width int, op *Op, comments *[]Comment) {
max_width = width
fmt.Println(op)
for _, comment := range *comments {
fmt.Println(comment)
}
}

func printChilds(c []*Comment) {
Expand All @@ -24,18 +30,24 @@ func printChilds(c []*Comment) {

func (o *Op) String() (ret string) {
ret += "title: " + o.title + "\n"
ret += "url: " + o.url + "\n"
if o.url != "" {
ret += "url: " + o.url + "\n"
}
ret += "self: " + o.selfUrl + "\n"
ret += fmt.Sprintf("%s(%d) - %s\n", o.user, o.score, humanize.Time(o.date))
return
}

func (c *Comment) String() (ret string) {
indent := c.indent * 5
msg, err := html2text.FromString(c.msg, html2text.Options{OmitLinks: false, PrettyTables: true, CitationStyleLinks: true})
indent := c.indent * SPACES_PER_INDENT
msg, err := html2text.FromString(
c.msg,
html2text.Options{OmitLinks: false, PrettyTables: true, CitationStyleLinks: true},
)
if err != nil {
panic(err)
}
wrapped, _ := text.WrapLeftPadded(msg, 120, indent+1)
wrapped, _ := text.WrapLeftPadded(msg, max_width, indent+1)
ret += "\n" + wrapped + "\n"
arrow := ">>> "
if c.indent > 0 {
Expand Down
6 changes: 5 additions & 1 deletion internal/hackernews/type.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package hackernews

import "time"
import (
"time"
)

type Op struct {
url string
Expand All @@ -9,12 +11,14 @@ type Op struct {
ncomments int
user string
date time.Time
selfUrl string
}

type Comment struct {
id int
msg string
Childs []*Comment
kids []int
indent int
user string
date time.Time
Expand Down
Loading

0 comments on commit c48f0ad

Please sign in to comment.