-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtalk_controller.go
73 lines (60 loc) · 1.32 KB
/
talk_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"github.com/ChimeraCoder/anaconda"
"runtime"
"github.com/jinzhu/gorm"
)
// TalkController is controller of talk.
type TalkController struct {
Talk Talk
Seq int
db *gorm.DB
}
// NewTalkController is constructor of TalkController.
func NewTalkController(talk Talk, db *gorm.DB)*TalkController{
return &TalkController{
Talk:talk,
Seq:0,
db:db,
}
}
// PostOne posts one tweet and inclement sequence.
func (tc *TalkController) PostOne() (Tweets, error){
numTweet := len(tc.Talk.Tweets[tc.Seq])
resultCh := make(chan Tweet, numTweet)
errCh := make(chan error, runtime.NumCPU())
for _,v := range tc.Talk.Tweets[tc.Seq]{
go postTweet(v, resultCh, errCh)
}
count := 0
var err error
L1:
for{
select {
case result := <-resultCh:
tc.db.Save(result)
count++
if count == numTweet {
break L1
}
case err = <-errCh:
break L1
default:
}
}
// Increment sequence
tc.Seq++
return tc.Talk.Tweets[tc.Seq-1], err
}
func postTweet(tweet Tweet, resultCh chan Tweet, errCh chan error) {
// This function is for posting tweet asynchronously
api := anaconda.NewTwitterApi(tweet.Bot.AccessToken, tweet.Bot.AccessTokenSecret)
result, err := api.PostTweet(tweet.Text, nil)
if err != nil {
errCh <- err
return
}
tweet.TweetIdStr = result.IdStr
tweet.Bot = Bot{}
resultCh <- tweet
}