Ejemplo n.º 1
0
func twitterImage(sess models.OAuthAuthorizedToken) string {
	query := url.Values{}
	query.Set("screen_name", sess.ScreenName)
	url := fmt.Sprintf("https://api.twitter.com/1.1/users/show.json?%v", query.Encode())

	req, e1 := http.NewRequest("GET", url, nil)
	if e1 != nil {
		logs.Error.Printf("Could not get new request: %v", e1)
		return ""
	}
	twitter.Sign(req, oauth1a.NewAuthorizedConfig(sess.AccessTokenKey, sess.AccessTokenSecret))

	client := &http.Client{}
	res, e2 := client.Do(req)
	if e2 != nil {
		logs.Error.Printf("Could not send HTTP request: %v", e2)
		return ""
	}
	defer res.Body.Close()

	body, e3 := ioutil.ReadAll(res.Body)
	if e3 != nil {
		logs.Error.Printf("Could not read HTTP response: %v", e3)
		return ""
	}
	type user struct {
		ProfileImageURL string `json:"profile_image_url"`
	}
	var u user
	if err := json.Unmarshal(body, &u); err != nil {
		logs.Error.Printf("Error: %v", err)
		return ""
	}
	return u.ProfileImageURL
}
Ejemplo n.º 2
0
func LoadCredentials() (client *twittergo.Client, err error) {
	credentials, err := ioutil.ReadFile("account.yaml")
	if err != nil {
		fmt.Println("There is no account.yaml")
		return nil, err
	}

	m := make(map[interface{}]interface{})

	err = yaml.Unmarshal([]byte(credentials), &m)

	if err != nil {
		log.Fatalf("error: %v", err)
	}

	twitter := m["twitter"].(map[interface{}]interface{})

	//fmt.Printf("%v\n", twitter)
	fmt.Printf("[%v]\n", twitter["consumerKey"])
	fmt.Printf("[%v]\n", twitter["consumerSecret"])
	fmt.Printf("[%v]\n", twitter["accessToken"])
	fmt.Printf("[%v]\n", twitter["accessTokenSecret"])

	config := &oauth1a.ClientConfig{
		ConsumerKey:    twitter["consumerKey"].(string),
		ConsumerSecret: twitter["consumerSecret"].(string),
	}

	user := oauth1a.NewAuthorizedConfig(twitter["accessToken"].(string), twitter["accessTokenSecret"].(string))
	client = twittergo.NewClient(config, user)

	return client, err
}
Ejemplo n.º 3
0
func LoadCredentials() (client *twittergo.Client, err error) {
	config := &oauth1a.ClientConfig{
		ConsumerKey:    os.Getenv("CONSUMER_KEY"),
		ConsumerSecret: os.Getenv("CONSUMER_SECRET"),
	}
	user := oauth1a.NewAuthorizedConfig(os.Getenv("API_KEY"), os.Getenv("API_SECRET"))
	client = twittergo.NewClient(config, user)
	return
}
Ejemplo n.º 4
0
func createClient() *twittergo.Client {
	a := services.Config.Twitter.Auth
	config := &oauth1a.ClientConfig{
		ConsumerKey:    a.Consumer_key,
		ConsumerSecret: a.Consumer_secret,
	}
	user := oauth1a.NewAuthorizedConfig(a.Token, a.Token_secret)
	return twittergo.NewClient(config, user)
}
Ejemplo n.º 5
0
func loadCredentials() (client *twittergo.Client) {
	config := &oauth1a.ClientConfig{
		ConsumerKey:    os.Getenv("twitter_ConsumerKey"),
		ConsumerSecret: os.Getenv("twitter_ConsumerSecret"),
	}
	user := oauth1a.NewAuthorizedConfig(
		os.Getenv("twitter_AccessToken"),
		os.Getenv("twitter_AcessTokenSecret"),
	)
	client = twittergo.NewClient(config, user)
	return
}
Ejemplo n.º 6
0
// The loading of credentials, the login, and tweeting functionality
// has been addapted from the example provided with github.com/kurrik/twittergo
func logIn(bot *TweetBot) (client *twittergo.Client, err error) {
	if len(bot.credentials) > 0 {
		lines := strings.Split(string(bot.credentials), "\n")
		config := &oauth1a.ClientConfig{
			ConsumerKey:    lines[0],
			ConsumerSecret: lines[1],
		}
		user := oauth1a.NewAuthorizedConfig(lines[2], lines[3])
		client = twittergo.NewClient(config, user)
	}
	return
}
Ejemplo n.º 7
0
func getTwitter(config Config) *twittergo.Client {
	twitterConfig := &oauth1a.ClientConfig{
		ConsumerKey:    config.Twitter.ConsumerKey,
		ConsumerSecret: config.Twitter.ConsumerSecret,
	}

	user := oauth1a.NewAuthorizedConfig(
		config.Twitter.AccessToken,
		config.Twitter.AccessTokenSecret,
	)

	return twittergo.NewClient(twitterConfig, user)
}
Ejemplo n.º 8
0
func NewTwitterUserClient() *twitterComm {
	config := &oauth1a.ClientConfig{
		ConsumerKey:    "my-api-key",
		ConsumerSecret: "my-api-secret",
	}

	user := oauth1a.NewAuthorizedConfig("oauth", "sucks")
	client := twittergo.NewClient(config, user)
	if err := client.FetchAppToken(); err != nil {
		fmt.Println("Error occured creating the client.", err)
		panic("ERROR CREATING USER CLIENT")
	}
	return &twitterComm{client}
}
Ejemplo n.º 9
0
func LoadCredentials() (client *twittergo.Client, err error) {
	credentials, err := ioutil.ReadFile("CREDENTIALS")
	if err != nil {
		return
	}
	lines := strings.Split(string(credentials), "\n")
	config := &oauth1a.ClientConfig{
		ConsumerKey:    lines[0],
		ConsumerSecret: lines[1],
	}
	user := oauth1a.NewAuthorizedConfig(lines[2], lines[3])
	client = twittergo.NewClient(config, user)
	return
}
Ejemplo n.º 10
0
//Initializes the TumblrRequest.
//consumerKey is the consumer key of your Tumblr Application.
//consumerSecret is the consumer secret of your Tumblr Application.
//callbackUrl is the callback URL of your Tumblr Application.
//oauthToken is the user specific token, received from the /access_token endpoint.
//oauthSecret is the user specific secret, received from the /access_token endpoint.
//host is the host that you are tryng to send information to (e.g. http://api.tumblr.com).
func NewTumblrRequest(consumerKey, consumerSecret, oauthToken, oauthSecret, callbackUrl, host string) *TumblrRequest {
	service := &oauth1a.Service{
		RequestURL:   "http://www.tumblr.com/oauth/request_token",
		AuthorizeURL: "http://www.tumblr.com/oauth/authorize",
		AccessURL:    "http://www.tumblr.com/oauth/access_token",
		ClientConfig: &oauth1a.ClientConfig{
			ConsumerKey:    consumerKey,
			ConsumerSecret: consumerSecret,
			CallbackURL:    callbackUrl,
		},
		Signer: new(oauth1a.HmacSha1Signer),
	}
	userConfig := oauth1a.NewAuthorizedConfig(oauthToken, oauthSecret)
	return &TumblrRequest{service, userConfig, host, consumerKey}
}
Ejemplo n.º 11
0
func LoadCredentials() (client *twittergo.Client, err error) {

	twitter, err := readYaml()

	if err != nil {
		return
	}

	config := &oauth1a.ClientConfig{
		ConsumerKey:    twitter["consumerKey"].(string),
		ConsumerSecret: twitter["consumerSecret"].(string),
	}

	user := oauth1a.NewAuthorizedConfig(twitter["accessToken"].(string), twitter["accessTokenSecret"].(string))
	client = twittergo.NewClient(config, user)

	return
}
Ejemplo n.º 12
0
// This is the initialization method.
// An easy way to get the credentials is to access the interactive console:
// https://api.tumblr.com/console
func New(consumerKey, consumerSecret, oauthKey, oauthSecret string) *Tumblr {
	service := &oauth1a.Service{
		RequestURL:   requestTokenUrl,
		AuthorizeURL: authorizeUrl,
		AccessURL:    accessTokenUrl,
		ClientConfig: &oauth1a.ClientConfig{
			ConsumerKey:    consumerKey,
			ConsumerSecret: consumerSecret,
		},
		Signer: new(oauth1a.HmacSha1Signer),
	}
	config := oauth1a.NewAuthorizedConfig(oauthKey, oauthSecret)
	return &Tumblr{
		oauthService: *service,
		config:       *config,
		apiKey:       consumerKey,
	}
}
Ejemplo n.º 13
0
func main() {
	config_file, err := ioutil.ReadFile("CREDENTIALS")

	if err != nil {
		return
	}
	lines := strings.Split(string(config_file), "\n")

	config := &oauth1a.ClientConfig{
		ConsumerKey:    lines[0],
		ConsumerSecret: lines[1],
	}

	user := oauth1a.NewAuthorizedConfig(lines[2], lines[3])
	client := twittergo.NewClient(config, user)
	fmt.Println(client)
	fmt.Println(&twittergo.Timeline{})
}
Ejemplo n.º 14
0
func loadCredentials() *twittergo.Client {
	err := godotenv.Load()
	if err != nil {
		log.Fatal(".env file missing")
	}

	consumerKey := os.Getenv("TWITTER_CONSUMER_KEY")
	consumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET")
	config := &oauth1a.ClientConfig{
		ConsumerKey:    consumerKey,
		ConsumerSecret: consumerSecret,
	}

	accessToken := os.Getenv("TWITTER_ACCESS_TOKEN")
	accessTokenSecret := os.Getenv("TWITTER_ACCESS_TOKEN_SECRET")
	user := oauth1a.NewAuthorizedConfig(accessToken, accessTokenSecret)

	return twittergo.NewClient(config, user)
}
Ejemplo n.º 15
0
func sync(name string, user *config.User) {
	if user.Enabled {
		weibo_account := user.GetAccount("tsina")
		twitter_account := user.GetAccount("twitter")
		posts := Timeline(weibo_account.Name, user.Last_weibo_id)

		oauth_user := oauth1a.NewAuthorizedConfig(twitter_account.Oauth_token_key, twitter_account.Oauth_token_secret)
		client := twittergo.NewClient(twitter_config, oauth_user)
		for i := len(posts) - 1; i >= 0; i-- {
			post := posts[i]
			if post.Id > user.Last_weibo_id {
				user.Last_weibo_id = post.Id
				tweet, err := Tweet(client, post.Text)
				log.Println(weibo_account.Name, post.Text, tweet)
				if err != nil {
					log.Println("[error]", tweet, err)
				}
			}
		}
	}
}
Ejemplo n.º 16
0
// New creates a new instance of the Twitter Social
func New(credentials *social.Credentials) (twitter *Twitter, err error) {

	log.Debugln("Creating a new Twitter Social")
	var user *oauth1a.UserConfig

	if !credentials.AppOnly() {
		log.Debugln("Application only authorization")
		user = oauth1a.NewAuthorizedConfig(credentials.Token, credentials.TokenSecret)
	}

	config := &oauth1a.ClientConfig{
		ConsumerKey:    credentials.Key,
		ConsumerSecret: credentials.Secret,
	}

	client := twittergo.NewClient(config, user)

	// Assign for return value
	twitter = &Twitter{
		api:         client,
		credentials: credentials,
	}
	return
}
Ejemplo n.º 17
0
func GetTwitterClient(ctx appengine.Context) (c *twittergo.Client, err error) {
	var (
		cred   *Credentials
		config *oauth1a.ClientConfig
		user   *oauth1a.UserConfig
	)
	if cred, err = LoadCredentials(ctx); err != nil {
		return
	}
	if cred.ConsumerKey == "" || cred.ConsumerSecret == "" {
		err = fmt.Errorf("Blank consumer secret and/or key")
		return
	}
	config = &oauth1a.ClientConfig{
		ConsumerKey:    cred.ConsumerKey,
		ConsumerSecret: cred.ConsumerSecret,
	}
	if cred.AccessToken != "" {
		user = oauth1a.NewAuthorizedConfig(cred.AccessToken, cred.AccessSecret)
	}
	c = twittergo.NewClient(config, user)
	c.HttpClient = urlfetch.Client(ctx)
	return
}
Ejemplo n.º 18
0
func HandleCreateUserByTwitter(r render.Render, bindErr binding.Errors, userForm models.UserForm, db *models.DB) {
	if bindErr.Count() > 0 {
		r.JSON(400, JsonErrBinding(bindErr))
		return
	}

	// Build Twitter client
	config := &oauth1a.ClientConfig{
		ConsumerKey:    TWITTER_CONSUMER_KEY,
		ConsumerSecret: TWITTER_CONSUMER_SECRET,
	}
	oauthUser := oauth1a.NewAuthorizedConfig(userForm.TwitterAccessToken,
		userForm.TwitterAccessSecret)
	client := twittergo.NewClient(config, oauthUser)

	// Build request to send to Twitter
	req, err := http.NewRequest("GET", "/1.1/account/verify_credentials.json", nil)
	if err != nil {
		log.Println("Could not build request for Twitter:", err.Error())
		r.JSON(500, JsonErr("Sorry, an internal server error has occurred."))
	}

	// Send it
	resp, err := client.SendRequest(req)
	if err != nil {
		log.Println("Error sending request to Twitter:", err.Error())
		r.JSON(504, JsonErr("Could not communicate properly with Twitter, "+
			"please try again soon."))
		return
	}

	// Parse the response
	var result = &twittergo.User{}
	if err = resp.Parse(result); err != nil {
		log.Println("Error parsing Twitter result:", err.Error(), "Response:",
			resp)
		r.JSON(504, JsonErr("Got a bad response from Twitter, please try "+
			"again soon."))
		return
	}

	user, err := db.GetUserWithId(result.IdStr())
	if err == nil {
		user, err = db.UpdateUserAuth(user.Id, userForm.TwitterAccessToken,
			userForm.TwitterAccessSecret)
		if err != nil {
			log.Println("Error updating user auth:", err.Error())
			r.JSON(500, JsonErr("Sorry, an internal server error has occurred."))
			return
		}
		r.JSON(200, map[string]*models.User{"user": user})
		return
	}

	// Now let's create that user, shall we?
	user, err = db.CreateUser(
		result.IdStr(),
		result.ScreenName(),
		(*result)["profile_image_url"].(string),
		userForm.TwitterAccessToken,
		userForm.TwitterAccessSecret,
	)
	if err != nil {
		log.Println("Error creating user:"******"Sorry, an internal server error has occurred."))
		return
	}

	r.JSON(200, map[string]*models.User{"user": user})
}
Ejemplo n.º 19
0
// Run executes the program.
func (m *Main) Run() error {
	logger := log.New(m.Stderr, "", log.LstdFlags)

	// Validate options.
	if m.DataDir == "" {
		return errors.New("data directory required")
	}

	// Create base directory, if not exists.
	if err := os.MkdirAll(m.DataDir, 0777); err != nil {
		return err
	}

	// Open data store.
	m.store = scuttlebutt.NewStore(filepath.Join(m.DataDir, "db"))
	m.store.RemoteStore = github.NewStore(m.Config.GitHub.Token)
	if err := m.store.Open(); err != nil {
		return fmt.Errorf("open store: %s", err)
	}

	// Initialize poller.
	m.poller = twitter.NewPoller()
	m.poller.Client = twittergo.NewClient(&oauth1a.ClientConfig{
		ConsumerKey:    m.Config.Twitter.Key,
		ConsumerSecret: m.Config.Twitter.Secret,
	}, nil)

	// Initialize notifiers for each account
	for _, acc := range m.Config.Accounts {
		client := twittergo.NewClient(
			&oauth1a.ClientConfig{
				ConsumerKey:    m.Config.Twitter.Key,
				ConsumerSecret: m.Config.Twitter.Secret,
			},
			oauth1a.NewAuthorizedConfig(acc.Key, acc.Secret),
		)

		n := twitter.NewNotifier()
		n.Username = acc.Username
		n.Language = acc.Language
		n.Client = client

		m.notifiers = append(m.notifiers, n)
	}

	// Open HTTP listener.
	ln, err := net.Listen("tcp", m.Addr)
	if err != nil {
		return err
	}
	m.Listener = ln
	m.Handler = &scuttlebutt.Handler{Store: m.store}

	// Run HTTP server is separate goroutine.
	logger.Printf("Listening on http://localhost%s", m.Addr)
	go http.Serve(m.Listener, m.Handler)

	// Create a poller & notify monitor.
	m.wg.Add(2)
	go m.runPoller()
	go m.runNotifier()

	return nil
}