anacondaaaa

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 16, 2019 License: MIT Imports: 7 Imported by: 4

README

anacondaaaa - anaconda support library for Twitter Account Activity API

Installation

$ go get github.com/mpppk/anacondaaaa

Usage

Echo example
func main() {
	consumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET")

	e := echo.New()
	e.GET("/", generateCRCTestHandler(consumerSecret))
	e.POST("/", accountActivityEventHandler)
	e.Logger.Fatal(e.Start(":1323"))
}

func generateCRCTestHandler(twitterConsumerSecret string) func(c echo.Context) error {
	return func(c echo.Context) error {
		req := new(anacondaaaa.CRCRequest)
		if err := c.Bind(req); err != nil {
			return err
		}

		response := &anacondaaaa.CRCResponse{
			ResponseToken: anacondaaaa.CreateCRCToken(req.CRCToken, twitterConsumerSecret),
		}
		return c.JSON(http.StatusOK, response)
	}
}

func accountActivityEventHandler(c echo.Context) error {
	events := new(anacondaaaa.AccountActivityEvent)
	if err := c.Bind(events); err != nil {
		return err
	}

	if events.GetEventName() == anacondaaaa.TweetCreateEventsEventName {
		return c.String(http.StatusOK, fmt.Sprintf(
			"tweet event is arrived. first tweet content: %#v", events.TweetCreateEvents[0]))
	}

	return c.NoContent(http.StatusNoContent)
}
net/http example
func main() {
	http.HandleFunc("/", httpHandler)
	log.Fatal(http.ListenAndServe(":1323", nil))
}

func httpHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method == "GET" {
		query := req.URL.Query()
		parameters, ok := query["crc_token"]
		if !ok || len(parameters) == 0 {
			http.Error(w, "invalid query parameters", http.StatusInternalServerError)
			return
		}

		crcToken := parameters[0]
		twitterConsumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET")
		response := &anacondaaaa.CRCResponse{
			ResponseToken: anacondaaaa.CreateCRCToken(crcToken, twitterConsumerSecret),
		}

		res, err := json.Marshal(response)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(res)
		return
	}

	if req.Method != "POST" {
		http.Error(w, "invalid HTTP Method", http.StatusBadRequest)
		return
	}

	if req.Header.Get("Content-Type") != "application/json" {
		http.Error(w, "invalid Content-Type", http.StatusBadRequest)
		return
	}

	events, err := parseJsonBody(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if events.GetEventName() == anacondaaaa.TweetCreateEventsEventName {
		w.WriteHeader(http.StatusOK)
		retText := fmt.Sprintf("tweet event is arrived. first tweet content: %#v", events.TweetCreateEvents[0])
		_, _ = w.Write([]byte(retText))
		return
	}

	w.WriteHeader(http.StatusNoContent)
	return
}

func parseJsonBody(req *http.Request) (*anacondaaaa.AccountActivityEvent, error) {
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		return nil, xerrors.Errorf("failed to read request body")
	}
	var accountActivityEvent anacondaaaa.AccountActivityEvent
	err = json.Unmarshal(body, &accountActivityEvent)
	if err != nil {
		return nil, xerrors.Errorf("failed to unmarshal request body to json: %w", err)
	}
	return &accountActivityEvent, nil
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateCRCToken

func CreateCRCToken(crcToken, consumerSecret string) string

Types

type AccountActivityEvent

type AccountActivityEvent struct {
	ForUserId                         string                              `json:"for_user_id"`
	TweetCreateEvents                 []*anaconda.Tweet                   `json:"tweet_create_events"`
	FavoriteEvents                    []*FavoriteEvent                    `json:"favorite_events"`
	FollowEvents                      []*UserRelationEvent                `json:"follow_events"`
	BlockEvents                       []*UserRelationEvent                `json:"block_events"`
	MuteEvents                        []*UserRelationEvent                `json:"mute_events"`
	UserEvent                         *UserEvent                          `json:"user_event"`
	DirectMessageEvents               []*DirectMessageEvent               `json:"direct_message_events"`
	DirectMessageIndicateTypingEvents []*DirectMessageIndicateTypingEvent `json:"direct_message_indicate_typing_events"`
	DirectMessageMarkReadEvents       []*DirectMessageMarkReadEvent       `json:"direct_message_mark_read_events"`
	TweetDeleteEvents                 []*TweetDeleteEvent                 `json:"tweet_delete_events"`
	Apps                              map[string]interface{}
	Users                             map[string]interface{}
}

func (*AccountActivityEvent) GetApps

func (a *AccountActivityEvent) GetApps() (*Apps, error)

func (*AccountActivityEvent) GetEventName

func (a *AccountActivityEvent) GetEventName() EventName

func (*AccountActivityEvent) GetUsers

func (a *AccountActivityEvent) GetUsers() (users []*AppUser, err error)

type AppUser

type AppUser struct {
	Id                   string `mapstructure:"id"`
	CreatedTimestamp     string `mapstructure:"created_timestamp"`
	Name                 string `mapstructure:"name"`
	ScreenName           string `mapstructure:"screen_name"`
	Location             string `mapstructure:"location"`
	Description          string `mapstructure:"description"`
	URL                  string `mapstructure:"url"`
	Protected            bool   `mapstructure:"protected"`
	Verified             bool   `mapstructure:"verified"`
	FollowersCount       int    `mapstructure:"followers_count"`
	FriendsCount         int    `mapstructure:"friends_count"`
	StatusesCount        int    `mapstructure:"statuses_count"`
	ProfileImageURL      string `mapstructure:"profile_image_url"`
	ProfileImageURLHTTPS string `mapstructure:"profile_image_url_https"`
}

type Apps

type Apps struct {
	SourceApp *SourceApp
	Sender    *AppUser
	Recipient *AppUser
}

type CRCRequest

type CRCRequest struct {
	CRCToken string `query:"crc_token" mapstructure:"crc_token"`
}

type CRCResponse

type CRCResponse struct {
	ResponseToken string `json:"response_token"`
}

type DirectMessageEvent

type DirectMessageEvent struct {
	Type             EventType      `json:"type"`
	Id               string         `json:"id"`
	CreatedTimestamp string         `json:"created_timestamp"`
	MessageCreate    *MessageCreate `json:"message_create"`
}

type DirectMessageIndicateTypingEvent

type DirectMessageIndicateTypingEvent struct {
	CreatedTimestamp string `json:"created_timestamp"`
	SenderId         string `json:"sender_id"`
	Target           struct {
		RecipientId string `json:"recipient_id"`
	} `json:"target"`
}

type DirectMessageMarkReadEvent

type DirectMessageMarkReadEvent struct {
	CreatedTimestamp string `json:"created_timestamp"`
	SenderId         string `json:"sender_id"`
	Target           struct {
		RecipientId string `json:"recipient_id"`
	} `json:"target"`
	LastReadEventId string `json:"last_read_event_id"`
}

type Entities

type Entities struct {
	Hashtags     []interface{} `json:"hashtags"`
	Symbols      []interface{} `json:"symbols"`
	UserMentions []interface{} `json:"user_mentions"`
	Urls         []interface{} `json:"urls"`
}

type EventName

type EventName string
const (
	TweetCreateEventsEventName                 EventName = "tweet_create_events"
	FavoriteEventsEventName                    EventName = "favorite_events"
	FollowEventsEventName                      EventName = "follow_events"
	BlockEventsEventName                       EventName = "block_events"
	MuteEventsEventName                        EventName = "mute_events"
	UserEventEventName                         EventName = "user_event"
	DirectMessageEventsEventName               EventName = "direct_message_events"
	DirectMessageIndicateTypingEventsEventName EventName = "direct_message_indicate_typing_events"
	DirectMessageMarkReadEventsEventName       EventName = "direct_message_mark_read_events"
	TweetDeleteEventsEventName                 EventName = "tweet_delete_events"
)

type EventType

type EventType string
const (
	FollowEventType        EventType = "follow"
	UnfollowEventType      EventType = "unfollow"
	BlockEventType         EventType = "block"
	UnblockEventType       EventType = "unblock"
	MuteEventType          EventType = "mute"
	UnmuteEventType        EventType = "unmute"
	MessageCreateEventType EventType = "message_create"
)

type FavoriteEvent

type FavoriteEvent struct {
	Id              string         `json:"id"`
	CreatedAt       string         `json:"created_at"`
	TimestampMs     int            `json:"timestamp_ms"`
	FavoritedStatus anaconda.Tweet `json:"favorited_status"`
	User            anaconda.User  `json:"user"`
}

type MessageCreate

type MessageCreate struct {
	Target struct {
		RecipientId string `json:"recipient_id"`
	} `json:"target"`
	SenderId    string      `json:"sender_id"`
	SourceAppId string      `json:"source_app_id"`
	MessageData MessageData `json:"message_data"`
}

type MessageData

type MessageData struct {
	Text     string    `json:"text"`
	Entities *Entities `json:"entities"`
}

type Revoke

type Revoke struct {
	DateTime string `json:"date_time"`
	Target   struct {
		AppId string `json:"app_id"`
	}
	Source struct {
		UserId string `json:"user_id"`
	}
}

type SourceApp

type SourceApp struct {
	Id   string `mapstructure:"id"`
	Name string `mapstructure:"name"`
	URL  string `mapstructure:"url"`
}

type TweetDeleteEvent

type TweetDeleteEvent struct {
	Status struct {
		Id     string `json:"id"`
		UserId string `json:"user_id"`
	} `json:"status"`
	TimestampMs string `json:"timestamp_ms"`
}

type UserEvent

type UserEvent struct {
	Revoke *Revoke `json:"revoke"`
}

type UserRelationEvent

type UserRelationEvent struct {
	Type             EventType      `json:"type"`
	CreatedTimestamp string         `json:"created_timestamp"`
	Target           *anaconda.User `json:"target"`
	Source           *anaconda.User `json:"source"`
}

Directories

Path Synopsis
examples
echo Module
http Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL