From 2038d83c807650c2edbea165f2680a98f8c2e825 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 29 Jun 2020 23:10:55 +0300 Subject: [PATCH 001/105] docs: version 2 --- doc.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc.go b/doc.go index c6e387b9..51042fa1 100644 --- a/doc.go +++ b/doc.go @@ -6,4 +6,4 @@ Source https://github.com/SevereCloud/vksdk package vksdk // Version module. -const Version = "1.10.0" +const Version = "2.0.0" From c77fcb5aa82b78fc4ff81b43c7ccabf2acd058bf Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:43:47 +0300 Subject: [PATCH 002/105] BREAKING CHANGE: comment out bugs field --- object/groups.go | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/object/groups.go b/object/groups.go index db0bc0ab..3af21604 100644 --- a/object/groups.go +++ b/object/groups.go @@ -596,12 +596,10 @@ type GroupsLongPollEvents struct { MessageRead BaseBoolInt `json:"message_read"` // Bugs - // - // TODO: v2 comment out - MessagesEdit BaseBoolInt `json:"messages_edit"` // BUG(VK): https://vk.com/bugtracker?act=show&id=86762 - WallNew BaseBoolInt `json:"wall_new"` - WallNewReply BaseBoolInt `json:"wall_new_reply"` - WallEditReply BaseBoolInt `json:"wall_edit_reply"` + // MessagesEdit BaseBoolInt `json:"messages_edit"` + // WallNew BaseBoolInt `json:"wall_new"` + // WallNewReply BaseBoolInt `json:"wall_new_reply"` + // WallEditReply BaseBoolInt `json:"wall_edit_reply"` } // GroupsLongPollServer struct. From 17b78f9b785704d3973d141d4a8e589805cdcd2b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:44:37 +0300 Subject: [PATCH 003/105] BREAKING CHANGE: VideoSearchBuilder.HD rename --- api/params/video.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/api/params/video.go b/api/params/video.go index 04b816f5..8f68addb 100644 --- a/api/params/video.go +++ b/api/params/video.go @@ -1063,10 +1063,8 @@ func (b *VideoSearchBuilder) Sort(v int) *VideoSearchBuilder { return b } -// Hd if not null, only searches for high-definition videos. -// -// TODO: v2 rename HD. -func (b *VideoSearchBuilder) Hd(v int) *VideoSearchBuilder { +// HD if not null, only searches for high-definition videos. +func (b *VideoSearchBuilder) HD(v int) *VideoSearchBuilder { b.Params["hd"] = v return b } From ce9b34647d14ac12626a2b7a15d2b88d5549bd79 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:46:58 +0300 Subject: [PATCH 004/105] BREAKING CHANGE: APIMethodURL rename name starts with package name --- api/api.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/api/api.go b/api/api.go index b97d5de8..7aa489ad 100644 --- a/api/api.go +++ b/api/api.go @@ -23,8 +23,8 @@ import ( // Api constants. const ( - Version = "5.103" - APIMethodURL = "https://api.vk.com/method/" // TODO: v2 rename (name starts with package name) + Version = "5.103" + MethodURL = "https://api.vk.com/method/" ) // VKontakte API methods (except for methods from secure and ads sections) @@ -135,7 +135,7 @@ func NewVK(token string) *VK { vk.Handler = vk.defaultHandler // TODO: remove in v2 - vk.MethodURL = APIMethodURL + vk.MethodURL = MethodURL vk.Client = http.DefaultClient vk.Limit = LimitGroupToken vk.UserAgent = internal.UserAgent From c8aea67f52019c21cfb9a58395d2059ffe0e5ed4 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:50:07 +0300 Subject: [PATCH 005/105] BREAKING CHANGE: rename FOAFURL name starts with package name --- foaf/foaf.go | 4 ++-- foaf/group.go | 2 +- foaf/person.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/foaf/foaf.go b/foaf/foaf.go index b8f690ef..e0e81f41 100644 --- a/foaf/foaf.go +++ b/foaf/foaf.go @@ -13,8 +13,8 @@ import ( "github.com/SevereCloud/vksdk/internal" ) -// FOAFURL url foaf. -const FOAFURL = "https://vk.com/foaf.php" // TODO: v2 rename (name starts with package name) +// BaseURL url foaf. +const BaseURL = "https://vk.com/foaf.php" // Context keys to use with https://golang.org/pkg/context // WithValue function to associate. diff --git a/foaf/group.go b/foaf/group.go index 8636c03e..e73e2448 100644 --- a/foaf/group.go +++ b/foaf/group.go @@ -32,7 +32,7 @@ type Group struct { // GetGroup return Group. func GetGroup(ctx context.Context, groupID int) (Group, error) { - req, _ := http.NewRequest("GET", FOAFURL, nil) + req, _ := http.NewRequest("GET", BaseURL, nil) q := req.URL.Query() q.Add("id", strconv.Itoa(-groupID)) req.URL.RawQuery = q.Encode() diff --git a/foaf/person.go b/foaf/person.go index 1df5f757..0433c030 100644 --- a/foaf/person.go +++ b/foaf/person.go @@ -135,7 +135,7 @@ type Location struct { // GetPerson return Person. func GetPerson(ctx context.Context, userID int) (Person, error) { - req, _ := http.NewRequest("GET", FOAFURL, nil) + req, _ := http.NewRequest("GET", BaseURL, nil) q := req.URL.Query() q.Add("id", strconv.Itoa(userID)) req.URL.RawQuery = q.Encode() From f8051b3ab2a05628f9d14f46454e421d0b64ef37 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:50:22 +0300 Subject: [PATCH 006/105] test: fix VideoSearchBuilder.HD --- api/params/video_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/params/video_test.go b/api/params/video_test.go index b44ef705..025dca46 100644 --- a/api/params/video_test.go +++ b/api/params/video_test.go @@ -416,7 +416,7 @@ func TestVideoSearchBuilder(t *testing.T) { b.Q("text") b.Sort(1) - b.Hd(1) + b.HD(1) b.Adult(true) b.Filters([]string{"text"}) b.SearchOwn(true) From c968e1c5c67a09bd51c8e8bf907a0edef7644561 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:52:35 +0300 Subject: [PATCH 007/105] BREAKING CHANGE: use MarketOrderStatus type --- object/market.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object/market.go b/object/market.go index 9f86944d..8a4d83c2 100644 --- a/object/market.go +++ b/object/market.go @@ -104,7 +104,7 @@ type MarketOrder struct { GroupID int `json:"group_id"` UserID int `json:"user_id"` Date int `json:"date"` - Status int `json:"status"` // TODO: v2 MarketOrderStatus + Status MarketOrderStatus `json:"status"` ItemsCount int `json:"items_count"` TotalPrice MarketPrice `json:"total_price"` DisplayOrderID string `json:"display_order_id"` From a8b98d15ca2a8cb8fb049b3e55c6ef9615d0e6be Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 22:59:58 +0300 Subject: [PATCH 008/105] BREAKING CHANGE: remove deprecated func --- api/api.go | 7 ------- api/api_test.go | 8 -------- api/params/groups.go | 30 ------------------------------ api/params/groups_test.go | 2 -- longpoll-bot/longpoll.go | 14 -------------- longpoll-bot/longpoll_test.go | 2 +- longpoll-user/longpoll.go | 16 ---------------- streaming/streaming.go | 9 --------- streaming/streaming_test.go | 8 -------- 9 files changed, 1 insertion(+), 95 deletions(-) diff --git a/api/api.go b/api/api.go index 7aa489ad..061612b3 100644 --- a/api/api.go +++ b/api/api.go @@ -155,13 +155,6 @@ func NewVKWithPool(tokens ...string) *VK { return vk } -// Init VK API. -// -// Deprecated: use NewVK. -func Init(token string) *VK { - return NewVK(token) -} - // Params type. type Params map[string]interface{} diff --git a/api/api_test.go b/api/api_test.go index f272a4c4..a9b1a4c1 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -308,14 +308,6 @@ func TestVK_CaptchaForce(t *testing.T) { } } -// FIXME: v2 remove TestInit. -func TestInit(t *testing.T) { - t.Parallel() - - vk := api.Init("") - assert.NotNil(t, vk) -} - func TestParams_methods(t *testing.T) { t.Parallel() diff --git a/api/params/groups.go b/api/params/groups.go index 89c5581b..309dc91f 100644 --- a/api/params/groups.go +++ b/api/params/groups.go @@ -2666,36 +2666,6 @@ func (b *GroupsTagUpdateBuilder) TagName(v string) *GroupsTagUpdateBuilder { return b } -// TagColor parameter. -// -// The following colours are permitted: -// 4bb34b, -// 5c9ce6, -// e64646, -// 792ec0, -// 63b9ba, -// ffa000, -// ffc107, -// 76787a, -// 9e8d6b, -// 45678f, -// 539b9c, -// 454647, -// 7a6c4f, -// 6bc76b, -// 5181b8, -// ff5c5c, -// a162de, -// 7ececf, -// aaaeb3, -// bbaa84. -// -// Deprecated: removed from vk dev. -func (b *GroupsTagUpdateBuilder) TagColor(v string) *GroupsTagUpdateBuilder { - b.Params["tag_color"] = v - return b -} - // GroupsUnbanBuilder builder. // // https://vk.com/dev/groups.unban diff --git a/api/params/groups_test.go b/api/params/groups_test.go index 62157111..14ece6fc 100644 --- a/api/params/groups_test.go +++ b/api/params/groups_test.go @@ -959,12 +959,10 @@ func TestGroupsTagUpdateBuilder(t *testing.T) { b.GroupID(1) b.TagID(1) b.TagName("text") - b.TagColor("text") assert.Equal(t, b.Params["group_id"], 1) assert.Equal(t, b.Params["tag_id"], 1) assert.Equal(t, b.Params["tag_name"], "text") - assert.Equal(t, b.Params["tag_color"], "text") } func TestGroupsUnbanBuilder(t *testing.T) { diff --git a/longpoll-bot/longpoll.go b/longpoll-bot/longpoll.go index 007c8b63..0abbb35e 100644 --- a/longpoll-bot/longpoll.go +++ b/longpoll-bot/longpoll.go @@ -76,20 +76,6 @@ func NewLongpollCommunity(vk *api.VK) (*Longpoll, error) { return lp, err } -// Init Longpoll. -// -// Deprecated: use NewLongpoll. -func Init(vk *api.VK, groupID int) (lp Longpoll, err error) { - lp.VK = vk - lp.GroupID = groupID - lp.Wait = 25 - lp.Client = &http.Client{} - lp.FuncList = *events.NewFuncList() - err = lp.updateServer(true) - - return -} - func (lp *Longpoll) updateServer(updateTs bool) error { params := api.Params{ "group_id": lp.GroupID, diff --git a/longpoll-bot/longpoll_test.go b/longpoll-bot/longpoll_test.go index c60e93e6..41af9de2 100644 --- a/longpoll-bot/longpoll_test.go +++ b/longpoll-bot/longpoll_test.go @@ -146,7 +146,7 @@ func TestLongpoll_RunError(t *testing.T) { t.Parallel() vk := api.NewVK("") - lp, _ := Init(vk, 0) + lp, _ := NewLongpoll(vk, 0) lp.Wait = 1 t.Run("Run client error", func(t *testing.T) { diff --git a/longpoll-user/longpoll.go b/longpoll-user/longpoll.go index 92a7a7c8..3dc171b8 100644 --- a/longpoll-user/longpoll.go +++ b/longpoll-user/longpoll.go @@ -117,22 +117,6 @@ func NewLongpoll(vk *api.VK, mode Mode) (*Longpoll, error) { return lp, err } -// Init Longpoll. -// -// Deprecated: use NewLongpoll. -func Init(vk *api.VK, mode Mode) (lp Longpoll, err error) { - // NOTE: what about group_id? - lp.VK = vk - lp.Mode = mode - lp.Version = 3 - lp.Wait = 25 - lp.funcList = make(FuncList) - lp.Client = &http.Client{} - err = lp.updateServer(true) - - return -} - func (lp *Longpoll) updateServer(updateTs bool) error { params := api.Params{ "lp_version": lp.Version, diff --git a/streaming/streaming.go b/streaming/streaming.go index c6594dc6..166f3ed5 100644 --- a/streaming/streaming.go +++ b/streaming/streaming.go @@ -374,12 +374,3 @@ func NewStreaming(vk *api.VK) (*Streaming, error) { return s, nil } - -// Init Streaming. -// -// This can be called with a service token. -// -// Deprecated: use NewStreaming. -func Init(vk *api.VK) (*Streaming, error) { - return NewStreaming(vk) -} diff --git a/streaming/streaming_test.go b/streaming/streaming_test.go index a5fa4166..57500b48 100644 --- a/streaming/streaming_test.go +++ b/streaming/streaming_test.go @@ -199,11 +199,3 @@ func TestNewStreaming(t *testing.T) { _, err := streaming.NewStreaming(api.NewVK("")) assert.Error(t, err) } - -// FIXME: v2 remove. -func TestInit(t *testing.T) { - t.Parallel() - - _, err := streaming.Init(api.NewVK("")) - assert.Error(t, err) -} From 3f7d33608b200ec861580f701ed8f74d406c0646 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 6 Jul 2020 23:03:54 +0300 Subject: [PATCH 009/105] BREAKING CHANGE: rename IDS -> IDs --- api/messages_test.go | 2 +- api/newsfeed.go | 2 +- api/newsfeed_test.go | 2 +- object/messages.go | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/api/messages_test.go b/api/messages_test.go index d96eeb27..772bb7eb 100644 --- a/api/messages_test.go +++ b/api/messages_test.go @@ -258,7 +258,7 @@ func TestVK_MessagesGetConversationsByID(t *testing.T) { assert.NotEmpty(t, res.Items[0].ChatSettings.State) assert.NotEmpty(t, res.Items[0].ChatSettings.ACL) assert.NotEmpty(t, res.Items[0].ChatSettings.MembersCount) - assert.NotEmpty(t, res.Items[0].ChatSettings.ActiveIDS) + assert.NotEmpty(t, res.Items[0].ChatSettings.ActiveIDs) } } diff --git a/api/newsfeed.go b/api/newsfeed.go index 447fadfd..965854d1 100644 --- a/api/newsfeed.go +++ b/api/newsfeed.go @@ -102,7 +102,7 @@ type NewsfeedGetListsResponse struct { ID int `json:"id"` Title string `json:"title"` NoReposts int `json:"no_reposts"` - SourceIDS []int `json:"source_ids"` // FIXME: v2 SourceIDs + SourceIDs []int `json:"source_ids"` } `json:"items"` } diff --git a/api/newsfeed_test.go b/api/newsfeed_test.go index 3f1ba272..de78918d 100644 --- a/api/newsfeed_test.go +++ b/api/newsfeed_test.go @@ -138,7 +138,7 @@ func TestVK_NewsfeedSaveList(t *testing.T) { if assert.NotEmpty(t, lists.Items) { assert.NotEmpty(t, lists.Items[0].ID) assert.NotEmpty(t, lists.Items[0].Title) - assert.NotEmpty(t, lists.Items[0].SourceIDS) + assert.NotEmpty(t, lists.Items[0].SourceIDs) } _, err = vkUser.NewsfeedDeleteList(api.Params{ diff --git a/object/messages.go b/object/messages.go index 69db2b51..f59665be 100644 --- a/object/messages.go +++ b/object/messages.go @@ -337,7 +337,7 @@ type MessagesConversationChatSettings struct { PinnedMessage MessagesPinnedMessage `json:"pinned_message"` State string `json:"state"` Title string `json:"title"` - ActiveIDS []int `json:"active_ids"` // FIXME: v2 ActiveIDs + ActiveIDs []int `json:"active_ids"` ACL struct { CanInvite BaseBoolInt `json:"can_invite"` CanChangeInfo BaseBoolInt `json:"can_change_info"` From 3cdcba3303a766ab86425831313c3da51761c3f0 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 7 Jul 2020 14:10:37 +0300 Subject: [PATCH 010/105] test: use Golang 1.13+ --- .github/workflows/test.yml | 2 +- CONTRIBUTING.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f2c8a793..ff81a276 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -5,7 +5,7 @@ jobs: test: strategy: matrix: - go-version: [1.11.x, 1.x] + go-version: [1.13.x, 1.x] platform: [ubuntu-latest] runs-on: ${{ matrix.platform }} steps: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c97979dd..60351353 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ Требования: -- [Go 1.11+](https://golang.org/doc/install) +- [Go 1.13+](https://golang.org/doc/install) - [golangci-lint](https://github.com/golangci/golangci-lint) - [global .gitignore](https://help.github.com/en/articles/ignoring-files#create-a-global-gitignore) From a39f7c08fa80176d616fcc8b98df183b85f16e02 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Thu, 9 Jul 2020 17:11:31 +0300 Subject: [PATCH 011/105] feat: add MessagesSendMessageEventAnswer method --- api/messages.go | 8 ++++++++ api/params/messages.go | 38 +++++++++++++++++++++++++++++++++++++ api/params/messages_test.go | 16 ++++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/api/messages.go b/api/messages.go index 5354f53e..00920e4f 100644 --- a/api/messages.go +++ b/api/messages.go @@ -521,6 +521,14 @@ func (vk *VK) MessagesSendUserIDs(params Params) (response MessagesSendUserIDsRe return } +// MessagesSendMessageEventAnswer method. +// +// https://vk.com/dev/messages.sendMessageEventAnswer +func (vk *VK) MessagesSendMessageEventAnswer(params Params) (response int, err error) { + err = vk.RequestUnmarshal("messages.sendMessageEventAnswer", params, &response) + return +} + // MessagesSendSticker sends a message. // // https://vk.com/dev/messages.sendSticker diff --git a/api/params/messages.go b/api/params/messages.go index fa64e56c..8c7b792d 100644 --- a/api/params/messages.go +++ b/api/params/messages.go @@ -1431,6 +1431,44 @@ func (b *MessagesSendBuilder) SubscribeID(v int) *MessagesSendBuilder { return b } +// MessagesSendMessageEventAnswerBuilder builder. +// +// Changes the status of a user as typing in a conversation. +// +// https://vk.com/dev/messages.sendMessageEventAnswer +type MessagesSendMessageEventAnswerBuilder struct { + api.Params +} + +// NewMessagesSendMessageEventAnswerBuilder func. +func NewMessagesSendMessageEventAnswerBuilder() *MessagesSendMessageEventAnswerBuilder { + return &MessagesSendMessageEventAnswerBuilder{api.Params{}} +} + +// EventID parameter. +func (b *MessagesSendMessageEventAnswerBuilder) EventID(v string) *MessagesSendMessageEventAnswerBuilder { + b.Params["event_id"] = v + return b +} + +// UserID parameter. +func (b *MessagesSendMessageEventAnswerBuilder) UserID(v int) *MessagesSendMessageEventAnswerBuilder { + b.Params["user_id"] = v + return b +} + +// PeerID parameter. +func (b *MessagesSendMessageEventAnswerBuilder) PeerID(v int) *MessagesSendMessageEventAnswerBuilder { + b.Params["peer_id"] = v + return b +} + +// EventData parameter. +func (b *MessagesSendMessageEventAnswerBuilder) EventData(v string) *MessagesSendMessageEventAnswerBuilder { + b.Params["event_data"] = v + return b +} + // MessagesSetActivityBuilder builder. // // Changes the status of a user as typing in a conversation. diff --git a/api/params/messages_test.go b/api/params/messages_test.go index cbfb0f23..6314ab9c 100644 --- a/api/params/messages_test.go +++ b/api/params/messages_test.go @@ -573,6 +573,22 @@ func TestMessagesSendBuilder(t *testing.T) { assert.Equal(t, b.Params["subscribe_id"], 1) } +func TestMessagesSendMessageEventAnswerBuilder(t *testing.T) { + t.Parallel() + + b := params.NewMessagesSendMessageEventAnswerBuilder() + + b.EventID("text") + b.UserID(1) + b.PeerID(1) + b.EventData("text") + + assert.Equal(t, b.Params["event_id"], "text") + assert.Equal(t, b.Params["user_id"], 1) + assert.Equal(t, b.Params["peer_id"], 1) + assert.Equal(t, b.Params["event_data"], "text") +} + func TestMessagesSetActivityBuilder(t *testing.T) { t.Parallel() From ee4f4b5ca069be960c1cb7b74920f67814ea6bfc Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Thu, 9 Jul 2020 17:51:26 +0300 Subject: [PATCH 012/105] feat: add MessageEvent event --- events/events.go | 15 +++++++++++++++ events/events_test.go | 32 ++++++++++++++++++++++++++++++++ object/handler.go | 12 ++++++++++++ object/object.go | 1 + 4 files changed, 60 insertions(+) diff --git a/events/events.go b/events/events.go index 8aa385a0..f370e2bb 100644 --- a/events/events.go +++ b/events/events.go @@ -19,6 +19,7 @@ type FuncList struct { messageAllow []object.MessageAllowFunc messageDeny []object.MessageDenyFunc messageTypingState []object.MessageTypingStateFunc + messageEvent []object.MessageEventFunc photoNew []object.PhotoNewFunc photoCommentNew []object.PhotoCommentNewFunc photoCommentEdit []object.PhotoCommentEditFunc @@ -133,6 +134,15 @@ func (fl FuncList) Handler(e object.GroupEvent) error { // nolint:gocyclo for _, f := range fl.messageTypingState { f(obj, e.GroupID) } + case object.EventMessageEvent: + var obj object.MessageEventObject + if err := json.Unmarshal(e.Object, &obj); err != nil { + return err + } + + for _, f := range fl.messageEvent { + f(obj, e.GroupID) + } case object.EventPhotoNew: var obj object.PhotoNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { @@ -546,6 +556,11 @@ func (fl *FuncList) MessageTypingState(f object.MessageTypingStateFunc) { fl.messageTypingState = append(fl.messageTypingState, f) } +// MessageEvent handler. +func (fl *FuncList) MessageEvent(f object.MessageEventFunc) { + fl.messageEvent = append(fl.messageEvent, f) +} + // PhotoNew handler. func (fl *FuncList) PhotoNew(f object.PhotoNewFunc) { fl.photoNew = append(fl.photoNew, f) diff --git a/events/events_test.go b/events/events_test.go index 705ef982..debec6aa 100644 --- a/events/events_test.go +++ b/events/events_test.go @@ -216,6 +216,38 @@ func TestFuncList_HandlerMessageTypingState(t *testing.T) { ) } +func TestFuncList_HandlerMessageEvent(t *testing.T) { + t.Parallel() + + fl := events.NewFuncList() + + fl.MessageEvent(func(obj object.MessageEventObject, groupID int) { + assert.Equal(t, groupID, GID) + }) + + f := func(e object.GroupEvent, wantErr bool) { + if err := fl.Handler(e); (err != nil) != wantErr { + t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) + } + } + + f( + object.GroupEvent{ + Type: "message_event", + Object: []byte("{}"), + GroupID: GID, + }, + false, + ) + f( + object.GroupEvent{ + Type: "message_event", + Object: []byte(""), + }, + true, + ) +} + func TestFuncList_HandlerPhotoNew(t *testing.T) { t.Parallel() diff --git a/object/handler.go b/object/handler.go index bb6b9df5..82e0168b 100644 --- a/object/handler.go +++ b/object/handler.go @@ -78,6 +78,18 @@ type MessageTypingStateObject struct { ToID int `json:"to_id"` } +// MessageEventFunc func. +type MessageEventFunc func(MessageEventObject, int) + +// MessageEventObject struct. +type MessageEventObject struct { + UserID int `json:"user_id"` + PeerID int `json:"peer_id"` + EventID string `json:"event_id"` + Payload string `json:"payload"` + ConversationMessageID int `json:"conversation_message_id"` +} + // PhotoNewFunc func. type PhotoNewFunc func(PhotoNewObject, int) diff --git a/object/object.go b/object/object.go index 97f35e31..3303dbcf 100644 --- a/object/object.go +++ b/object/object.go @@ -84,6 +84,7 @@ const ( EventMessageAllow = "message_allow" EventMessageDeny = "message_deny" EventMessageTypingState = "message_typing_state" + EventMessageEvent = "message_event" EventPhotoNew = "photo_new" EventPhotoCommentNew = "photo_comment_new" EventPhotoCommentEdit = "photo_comment_edit" From 08ae03e8a71b2b6a8608111b69c785287f866fe1 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Thu, 9 Jul 2020 17:51:31 +0300 Subject: [PATCH 013/105] feat: add transcript for audio messages --- object/docs.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/object/docs.go b/object/docs.go index ca301357..2acd117f 100644 --- a/object/docs.go +++ b/object/docs.go @@ -95,10 +95,12 @@ type DocsDocPreviewVideo struct { // DocsDocPreviewAudioMessage struct. type DocsDocPreviewAudioMessage struct { - Duration int `json:"duration"` - Waveform []int `json:"waveform"` - LinkOgg string `json:"link_ogg"` - LinkMp3 string `json:"link_mp3"` + Duration int `json:"duration"` + Waveform []int `json:"waveform"` + LinkOgg string `json:"link_ogg"` + LinkMp3 string `json:"link_mp3"` + Transcript string `json:"transcript"` + TranscriptState string `json:"transcript_state"` } // DocsDocTypes struct. From 6577428f7b2042cc137d340e49d3482e48ada937 Mon Sep 17 00:00:00 2001 From: geosonic <36260850+geosonic@users.noreply.github.com> Date: Thu, 9 Jul 2020 20:00:31 +0500 Subject: [PATCH 014/105] feat: add button colors Add button colors feat. @phagleb --- object/object.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/object/object.go b/object/object.go index 97f35e31..36b934dc 100644 --- a/object/object.go +++ b/object/object.go @@ -638,6 +638,21 @@ const ( ButtonOpenLink = "open_link" ) +// Button color. This parameter is used only for buttons with the text and callback types. +const ( + Primary = "primary" // Blue button, indicates the main action. #5181B8 + ButtonBlue + + Secondary = "secondary" // Default white button. #FFFFFF + ButtonWhite + + Negative = "negative" // Dangerous or negative action (cancel, delete etc.) #E64646 + ButtonRed + + Positive = "positive" // Accept, agree. #4BB34B + ButtonGreen +) + // Platform content creation platform. type Platform int From df2c5d3f982af7ca70fe5a3554180ca60e76678e Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 17:47:38 +0300 Subject: [PATCH 015/105] feat: AppsApp v5.105 --- api/api.go | 2 +- object/apps.go | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/api/api.go b/api/api.go index 061612b3..8cd2c822 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.103" + Version = "5.105" MethodURL = "https://api.vk.com/method/" ) diff --git a/object/apps.go b/object/apps.go index 2b7b7082..0aa2f35f 100644 --- a/object/apps.go +++ b/object/apps.go @@ -38,9 +38,12 @@ type AppsCatalogBanner struct { // AppsApp struct. type AppsApp struct { - AuthorGroup int `json:"author_group"` // Official community's ID - AuthorID int `json:"author_id"` // Application author's ID - AuthorURL string `json:"author_url"` // Application author's URL + AuthorGroup int `json:"author_group"` // Official community's ID + AuthorID int `json:"author_id"` // Application author's ID + AuthorURL string `json:"author_url"` // Application author's URL + // TODO: v2 5.120 add author_owner_id + // AuthorOwnerID int `json:"author_owner_id"` + Banner1120 string `json:"banner_1120"` // URL of the app banner with 1120 px in width Banner560 string `json:"banner_560"` // URL of the app banner with 560 px in width CatalogPosition int `json:"catalog_position"` // Catalog position @@ -60,6 +63,7 @@ type AppsApp struct { HideTabbar BaseBoolInt `json:"hide_tabbar"` IsNew BaseBoolInt `json:"is_new"` New BaseBoolInt `json:"new"` + IsInstalled BaseBoolInt `json:"is_installed"` LeaderboardType int `json:"leaderboard_type"` MembersCount int `json:"members_count"` // Members number PlatformID int `json:"platform_id"` // Application ID in store @@ -73,6 +77,15 @@ type AppsApp struct { Icon576 string `json:"icon_576"` ScreenOrientation AppsScreenOrientation `json:"screen_orientation"` CatalogBanner AppsCatalogBanner `json:"catalog_banner"` + + // mobile_controls_type = 0 - прозрачный элемент управления поверх области с игрой; + // mobile_controls_type = 1 - чёрная полоска над областью с игрой; + // mobile_controls_type = 2 - только для vk apps, без контроллов. + MobileControlsType int `json:"mobile_controls_type"` + + // mobile_view_support_type = 0 - игра не использует нижнюю часть экрана на iPhoneX, черная полоса есть. + // mobile_view_support_type = 1 - игра использует нижнюю часть экрана на iPhoneX, черной полосы нет. + MobileViewSupportType int `json:"mobile_view_support_type"` } // AppsLeaderboard struct. From 11ba30794ace57423bc03ce174c779ae8f1d3cb0 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 18:02:03 +0300 Subject: [PATCH 016/105] feat: v5.110 --- api/api.go | 2 +- api/storage.go | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/api/api.go b/api/api.go index 8cd2c822..bfb5a952 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.105" + Version = "5.110" MethodURL = "https://api.vk.com/method/" ) diff --git a/api/storage.go b/api/storage.go index 2db04500..c661dd41 100644 --- a/api/storage.go +++ b/api/storage.go @@ -23,12 +23,6 @@ func (s StorageGetResponse) ToMap() map[string]string { // // https://vk.com/dev/storage.get func (vk *VK) StorageGet(params Params) (response StorageGetResponse, err error) { - // TODO: remove in 5.110 - if _, prs := params["keys"]; !prs { - params["keys"] = params["key"] - params["key"] = "" - } - err = vk.RequestUnmarshal("storage.get", params, &response) return From b7909d7fa4e9a283fe6978bd77cb49ca176baa45 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 18:02:11 +0300 Subject: [PATCH 017/105] feat: GroupsMarketInfo add CanMessage --- object/groups.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object/groups.go b/object/groups.go index 3af21604..6d8f90bf 100644 --- a/object/groups.go +++ b/object/groups.go @@ -625,12 +625,12 @@ type GroupsMarketInfo struct { CurrencyText string `json:"currency_text"` // Currency name Enabled BaseBoolInt `json:"enabled"` // Information whether the market is enabled CommentsEnabled BaseBoolInt `json:"comments_enabled"` + CanMessage BaseBoolInt `json:"can_message"` MainAlbumID int `json:"main_album_id"` // Main market album ID PriceMax string `json:"price_max"` // Maximum price PriceMin string `json:"price_min"` // Minimum price Wiki PagesWikipageFull `json:"wiki"` CountryIDs []int `json:"country_ids"` - // TODO: add in 5.110 CanMessage BaseBoolInt `json:"can_message"` } // GroupsGroupRole Role type. From f323c225e3ecd9248d832a9ea69792c78a4c8a60 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 18:37:42 +0300 Subject: [PATCH 018/105] BREAKING CHANGE: v5.113 use StoriesFeedItem --- api/api.go | 2 +- api/stories.go | 29 ++++++++++++++++------------- object/stories.go | 25 +++++++++++++++++++++++-- 3 files changed, 40 insertions(+), 16 deletions(-) diff --git a/api/api.go b/api/api.go index bfb5a952..92c23117 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.110" + Version = "5.113" MethodURL = "https://api.vk.com/method/" ) diff --git a/api/stories.go b/api/stories.go index a08b78f8..dc3cc341 100644 --- a/api/stories.go +++ b/api/stories.go @@ -20,9 +20,10 @@ func (vk *VK) StoriesDelete(params Params) (response int, err error) { // StoriesGetResponse struct. type StoriesGetResponse struct { - Count int `json:"count"` - Items [][]object.StoriesStory `json:"items"` - PromoData object.StoriesPromoData `json:"promo_data"` + Count int `json:"count"` + Items []object.StoriesFeedItem `json:"items"` + PromoData object.StoriesPromoData `json:"promo_data"` + NeedUploadScreen object.BaseBoolInt `json:"need_upload_screen"` } // StoriesGet returns stories available for current user. @@ -39,8 +40,10 @@ func (vk *VK) StoriesGet(params Params) (response StoriesGetResponse, err error) // StoriesGetExtendedResponse struct. type StoriesGetExtendedResponse struct { - Count int `json:"count"` - Items [][]object.StoriesStory `json:"items"` + Count int `json:"count"` + Items []object.StoriesFeedItem `json:"items"` + PromoData object.StoriesPromoData `json:"promo_data"` + NeedUploadScreen object.BaseBoolInt `json:"need_upload_screen"` object.ExtendedResponse } @@ -147,8 +150,8 @@ func (vk *VK) StoriesGetPhotoUploadServer(params Params) (response StoriesGetPho // StoriesGetRepliesResponse struct. type StoriesGetRepliesResponse struct { - Count int `json:"count"` - Items [][]object.StoriesStory `json:"items"` + Count int `json:"count"` + Items []object.StoriesFeedItem `json:"items"` } // StoriesGetReplies returns replies to the story. @@ -165,8 +168,8 @@ func (vk *VK) StoriesGetReplies(params Params) (response StoriesGetRepliesRespon // StoriesGetRepliesExtendedResponse struct. type StoriesGetRepliesExtendedResponse struct { - Count int `json:"count"` - Items [][]object.StoriesStory `json:"items"` + Count int `json:"count"` + Items []object.StoriesFeedItem `json:"items"` object.ExtendedResponse } @@ -262,8 +265,8 @@ func (vk *VK) StoriesHideReply(params Params) (response int, err error) { // StoriesSearchResponse struct. type StoriesSearchResponse struct { - Count int `json:"count"` - Items [][]object.StoriesStory `json:"items"` + Count int `json:"count"` + Items []object.StoriesFeedItem `json:"items"` } // StoriesSearch returns search results for stories. @@ -280,8 +283,8 @@ func (vk *VK) StoriesSearch(params Params) (response StoriesSearchResponse, err // StoriesSearchExtendedResponse struct. type StoriesSearchExtendedResponse struct { - Count int `json:"count"` - Items [][]object.StoriesStory `json:"items"` + Count int `json:"count"` + Items []object.StoriesFeedItem `json:"items"` object.ExtendedResponse } diff --git a/object/stories.go b/object/stories.go index a42a76b1..91ed9fd8 100644 --- a/object/stories.go +++ b/object/stories.go @@ -68,14 +68,17 @@ type StoriesStory struct { CanReply BaseBoolInt `json:"can_reply"` // Information whether current user can reply to the story (0 - no, 1 - yes). CanSee BaseBoolInt `json:"can_see"` // Information whether current user can see the story (0 - no, 1 - yes). CanShare BaseBoolInt `json:"can_share"` // Information whether current user can share the story (0 - no, 1 - yes). - Date int `json:"date"` // Date when story has been added in Unixtime. - ID int `json:"id"` // Story ID. IsDeleted BaseBoolInt `json:"is_deleted"` // Information whether the story is deleted (false - no, true - yes). IsExpired BaseBoolInt `json:"is_expired"` // Information whether the story is expired (false - no, true - yes). NoSound BaseBoolInt `json:"no_sound"` // Is video without sound IsRestricted BaseBoolInt `json:"is_restricted"` // Does author have stories privacy restrictions Seen BaseBoolInt `json:"seen"` // Information whether current user has seen the story or not (0 - no, 1 - yes). IsOwnerPinned BaseBoolInt `json:"is_owner_pinned"` + IsOneTime BaseBoolInt `json:"is_one_time"` + NeedMute BaseBoolInt `json:"need_mute"` + MuteReply BaseBoolInt `json:"mute_reply"` + Date int `json:"date"` // Date when story has been added in Unixtime. + ID int `json:"id"` // Story ID. Link StoriesStoryLink `json:"link"` OwnerID int `json:"owner_id"` // Story owner's ID. ParentStory *StoriesStory `json:"parent_story"` @@ -98,6 +101,24 @@ type StoriesStory struct { Questions StoriesQuestions `json:"questions"` } +// StoriesFeedItemType type. +type StoriesFeedItemType string + +// Possible values. +const ( + StoriesFeedItemStories StoriesFeedItemType = "stories" + StoriesFeedItemCommunity StoriesFeedItemType = "community_grouped_stories" + StoriesFeedItemApp StoriesFeedItemType = "app_grouped_stories" +) + +// StoriesFeedItem struct. +type StoriesFeedItem struct { + Type StoriesFeedItemType `json:"type"` + Stories []StoriesStory `json:"stories"` + Grouped StoriesFeedItemType `json:"grouped"` + App AppsApp `json:"app"` +} + // StoriesClickableStickers struct. // // The field clickable_stickers is available in the history object. From be8540473fd48619f9002e9333916996e539394f Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 18:45:22 +0300 Subject: [PATCH 019/105] feat: MessagesMessage add ExpireTTL --- object/messages.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/messages.go b/object/messages.go index f59665be..3b047e5e 100644 --- a/object/messages.go +++ b/object/messages.go @@ -63,6 +63,7 @@ type MessagesMessage struct { Text string `json:"text"` // Message text UpdateTime int `json:"update_time"` // Date when the message has been updated in Unixtime MembersCount int `json:"members_count"` // Members number + ExpireTTL int `json:"expire_ttl"` } // MessagesBasePayload struct. From 91d7d77de08e8fa881f4e63476d1f723fd6b42cd Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 18:53:40 +0300 Subject: [PATCH 020/105] BREAKING CHANGE: v5.115 use StoriesViewer --- api/api.go | 2 +- api/stories.go | 23 ++--------------------- api/stories_test.go | 3 --- object/stories.go | 16 ++++++++++++++++ 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/api/api.go b/api/api.go index 92c23117..11adb1fd 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.113" + Version = "5.115" MethodURL = "https://api.vk.com/method/" ) diff --git a/api/stories.go b/api/stories.go index dc3cc341..08c219f6 100644 --- a/api/stories.go +++ b/api/stories.go @@ -213,8 +213,8 @@ func (vk *VK) StoriesGetVideoUploadServer(params Params) (response StoriesGetVid // StoriesGetViewersResponse struct. type StoriesGetViewersResponse struct { - Count int `json:"count"` - Items []int `json:"items"` + Count int `json:"count"` + Items []object.StoriesViewer `json:"items"` } // StoriesGetViewers returns a list of story viewers. @@ -223,25 +223,6 @@ type StoriesGetViewersResponse struct { // // https://vk.com/dev/stories.getViewers func (vk *VK) StoriesGetViewers(params Params) (response StoriesGetViewersResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("stories.getViewers", params, &response) - - return -} - -// StoriesGetViewersExtendedResponse struct. -type StoriesGetViewersExtendedResponse struct { - Count int `json:"count"` - Items []object.UsersUser `json:"items"` -} - -// StoriesGetViewersExtended returns a list of story viewers. -// -// extended=1 -// -// https://vk.com/dev/stories.getViewers -func (vk *VK) StoriesGetViewersExtended(params Params) (response StoriesGetViewersExtendedResponse, err error) { - params["extended"] = true err = vk.RequestUnmarshal("stories.getViewers", params, &response) return diff --git a/api/stories_test.go b/api/stories_test.go index b2dc27c9..2eaceb61 100644 --- a/api/stories_test.go +++ b/api/stories_test.go @@ -111,9 +111,6 @@ func TestVK_StoriesGetReplies(t *testing.T) { _, err = vkGroup.StoriesGetViewers(params) noError(t, err) - _, err = vkGroup.StoriesGetViewersExtended(params) - noError(t, err) - _, err = vkGroup.StoriesDelete(params) noError(t, err) } diff --git a/object/stories.go b/object/stories.go index 91ed9fd8..99da2504 100644 --- a/object/stories.go +++ b/object/stories.go @@ -4,6 +4,22 @@ import ( "encoding/json" ) +// StoriesViewer struct. +type StoriesViewer struct { + IsLiked bool `json:"is_liked"` + UserID int `json:"user_id"` + + // For extended + User struct { + Type string `json:"type"` + ID int `json:"id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + IsClosed bool `json:"is_closed"` + CanAccessClosed bool `json:"can_access_closed"` + } `json:"user,omitempty"` +} + // StoriesNarrativeInfo type. type StoriesNarrativeInfo struct { Author string `json:"author"` From 1329824649ad7410bf358b70eab6ead2ca691037 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:08:52 +0300 Subject: [PATCH 021/105] feat: add StoriesSave method --- api/params/stories.go | 20 ++++++++++++++++++++ api/params/stories_test.go | 10 ++++++++++ api/stories.go | 14 ++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/api/params/stories.go b/api/params/stories.go index f7992fbc..556c57dc 100644 --- a/api/params/stories.go +++ b/api/params/stories.go @@ -400,6 +400,26 @@ func (b *StoriesHideReplyBuilder) StoryID(v int) *StoriesHideReplyBuilder { return b } +// StoriesSaveBuilder builder. +// +// https://vk.com/dev/stories.save +type StoriesSaveBuilder struct { + api.Params +} + +// NewStoriesSaveBuilder func. +func NewStoriesSaveBuilder() *StoriesSaveBuilder { + return &StoriesSaveBuilder{api.Params{}} +} + +// UploadResults parameter. +// +// required parameter. +func (b *StoriesSaveBuilder) UploadResults(v string) *StoriesSaveBuilder { + b.Params["upload_results"] = v + return b +} + // StoriesSendInteractionBuilder builder. // // Sends feedback to the story. diff --git a/api/params/stories_test.go b/api/params/stories_test.go index 1a76805b..d4cdc22a 100644 --- a/api/params/stories_test.go +++ b/api/params/stories_test.go @@ -179,6 +179,16 @@ func TestStoriesHideReplyBuilder(t *testing.T) { assert.Equal(t, b.Params["story_id"], 1) } +func TestStoriesSaveBuilder(t *testing.T) { + t.Parallel() + + b := params.NewStoriesSaveBuilder() + + b.UploadResults("test") + + assert.Equal(t, b.Params["upload_results"], "test") +} + func TestStoriesUnbanOwnerBuilder(t *testing.T) { t.Parallel() diff --git a/api/stories.go b/api/stories.go index 08c219f6..4fd67d24 100644 --- a/api/stories.go +++ b/api/stories.go @@ -244,6 +244,20 @@ func (vk *VK) StoriesHideReply(params Params) (response int, err error) { return } +// StoriesSaveResponse struct. +type StoriesSaveResponse struct { + Count int `json:"count"` + Items []object.StoriesStory `json:"items"` +} + +// StoriesSave method. +// +// https://vk.com/dev/stories.save +func (vk *VK) StoriesSave(params Params) (response StoriesSaveResponse, err error) { + err = vk.RequestUnmarshal("stories.save", params, &response) + return +} + // StoriesSearchResponse struct. type StoriesSearchResponse struct { Count int `json:"count"` From 2a415b86500402ff818732931538efa33c83bd70 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:19:23 +0300 Subject: [PATCH 022/105] BREAKING CHANGE: v5.118 use StoriesSave --- api/api.go | 2 +- api/stories_test.go | 9 +++++---- api/upload.go | 36 +++++++++++++++++++++--------------- 3 files changed, 27 insertions(+), 20 deletions(-) diff --git a/api/api.go b/api/api.go index 11adb1fd..ca14736d 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.115" + Version = "5.118" MethodURL = "https://api.vk.com/method/" ) diff --git a/api/stories_test.go b/api/stories_test.go index 2eaceb61..ffd45ca4 100644 --- a/api/stories_test.go +++ b/api/stories_test.go @@ -91,12 +91,13 @@ func TestVK_StoriesGetReplies(t *testing.T) { "add_to_news": true, }, response.Body) noError(t, err) - assert.NotEmpty(t, res.Stories) - // assert.NotEmpty(t, res.Sig) + if !assert.NotEmpty(t, res.Items) { + t.FailNow() + } params := api.Params{ - "owner_id": res.Stories.OwnerID, - "story_id": res.Stories.ID, + "owner_id": res.Items[0].OwnerID, + "story_id": res.Items[0].ID, } _, err = vkGroup.StoriesGetReplies(params) diff --git a/api/upload.go b/api/upload.go index 795308b1..b56eab79 100644 --- a/api/upload.go +++ b/api/upload.go @@ -674,8 +674,8 @@ func (vk *VK) UploadOwnerCoverPhoto(groupID, cropX, cropY, cropX2, cropY2 int, f // UploadStories struct. type UploadStories struct { - Stories object.StoriesStory `json:"story"` - Sig string `json:"_sig"` + UploadResult string `json:"upload_result"` + Sig string `json:"_sig"` } type rawUploadStoriesPhoto struct { @@ -687,8 +687,11 @@ type rawUploadStoriesPhoto struct { } type rawUploadStoriesVideo struct { - UploadStories - uploadError + Response UploadStories `json:"response"` + Error struct { + ErrorCode int `json:"error_code"` + Type string `json:"type"` + } `json:"error"` } // UploadStoriesPhoto uploading Story. @@ -699,7 +702,7 @@ type rawUploadStoriesVideo struct { // maximum 720х1280, 30fps. // // https://vk.com/dev/stories.getPhotoUploadServer -func (vk *VK) UploadStoriesPhoto(params Params, file io.Reader) (response UploadStories, err error) { +func (vk *VK) UploadStoriesPhoto(params Params, file io.Reader) (response StoriesSaveResponse, err error) { uploadServer, err := vk.StoriesGetPhotoUploadServer(params) if err != nil { return @@ -719,18 +722,20 @@ func (vk *VK) UploadStoriesPhoto(params Params, file io.Reader) (response Upload if handler.Error.ErrorCode != 0 { err = fmt.Errorf(handler.Error.Type) - } else { - response.Sig = handler.Response.Sig - response.Stories = handler.Response.Stories + return } + response, err = vk.StoriesSave(Params{ + "upload_results": handler.Response.UploadResult, + }) + return } // UploadStoriesVideo uploading Story. // // Video format: h264 video, aac audio, maximum 720х1280, 30fps. -func (vk *VK) UploadStoriesVideo(params Params, file io.Reader) (response UploadStories, err error) { +func (vk *VK) UploadStoriesVideo(params Params, file io.Reader) (response StoriesSaveResponse, err error) { uploadServer, err := vk.StoriesGetVideoUploadServer(params) if err != nil { return @@ -748,14 +753,15 @@ func (vk *VK) UploadStoriesVideo(params Params, file io.Reader) (response Upload return } - if handler.ErrorCode != 0 { - // TODO: new type error - err = fmt.Errorf(handler.Error) - } else { - response.Sig = handler.Sig - response.Stories = handler.Stories + if handler.Error.ErrorCode != 0 { + err = fmt.Errorf(handler.Error.Type) + return } + response, err = vk.StoriesSave(Params{ + "upload_results": handler.Response.UploadResult, + }) + return } From 743c373fcf1c790b2e40d851551f9f5cda8f0824 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:24:00 +0300 Subject: [PATCH 023/105] BREAKING CHANGE: v5.120 --- api/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/api.go b/api/api.go index ca14736d..cdf7b813 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.118" + Version = "5.120" MethodURL = "https://api.vk.com/method/" ) From aafe27dc8334f7c7b2ed9294f23908266c095d3e Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:34:04 +0300 Subject: [PATCH 024/105] BREAKING CHANGE: AppsApp use AuthorOwnerID --- api/apps_test.go | 2 -- object/apps.go | 7 +------ 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/api/apps_test.go b/api/apps_test.go index 8f44f79d..95f8e558 100644 --- a/api/apps_test.go +++ b/api/apps_test.go @@ -36,8 +36,6 @@ func TestVK_AppsGet(t *testing.T) { assert.NotEmpty(t, res.Items[0].Icon139) assert.NotEmpty(t, res.Items[0].Icon150) assert.NotEmpty(t, res.Items[0].Icon278) - assert.NotEmpty(t, res.Items[0].AuthorGroup) - assert.NotEmpty(t, res.Items[0].AuthorURL) assert.NotEmpty(t, res.Items[0].Banner1120) assert.NotEmpty(t, res.Items[0].Banner560) assert.NotEmpty(t, res.Items[0].Genre) diff --git a/object/apps.go b/object/apps.go index 0aa2f35f..d2319f1a 100644 --- a/object/apps.go +++ b/object/apps.go @@ -38,12 +38,7 @@ type AppsCatalogBanner struct { // AppsApp struct. type AppsApp struct { - AuthorGroup int `json:"author_group"` // Official community's ID - AuthorID int `json:"author_id"` // Application author's ID - AuthorURL string `json:"author_url"` // Application author's URL - // TODO: v2 5.120 add author_owner_id - // AuthorOwnerID int `json:"author_owner_id"` - + AuthorOwnerID int `json:"author_owner_id"` Banner1120 string `json:"banner_1120"` // URL of the app banner with 1120 px in width Banner560 string `json:"banner_560"` // URL of the app banner with 560 px in width CatalogPosition int `json:"catalog_position"` // Catalog position From 607c908457993d7b4ae0901604d59dddaefcfd30 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:34:14 +0300 Subject: [PATCH 025/105] feat: MarketMarketItem add Dimensions and Weight --- object/market.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/object/market.go b/object/market.go index 8a4d83c2..95b332e0 100644 --- a/object/market.go +++ b/object/market.go @@ -62,6 +62,15 @@ type MarketMarketItem struct { URL string `json:"url"` // URL to item ButtonTitle string `json:"button_title"` ExternalID string `json:"external_id"` + Dimensions MarketDimensions `json:"dimensions"` + Weight int `json:"weight"` +} + +// MarketDimensions struct. +type MarketDimensions struct { + Width int `json:"width"` + Height int `json:"height"` + Length int `json:"length"` } // ToAttachment return attachment format. From e6eb48af94c69c406e7ab0389aeeef49378ca042 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:34:36 +0300 Subject: [PATCH 026/105] test: fix style --- api/stories_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/api/stories_test.go b/api/stories_test.go index ffd45ca4..56df2471 100644 --- a/api/stories_test.go +++ b/api/stories_test.go @@ -91,6 +91,7 @@ func TestVK_StoriesGetReplies(t *testing.T) { "add_to_news": true, }, response.Body) noError(t, err) + if !assert.NotEmpty(t, res.Items) { t.FailNow() } From 111b7c2efb60691f8db8fec539200a4965c1b665 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:47:38 +0300 Subject: [PATCH 027/105] feat: update MessagesConversation --- object/messages.go | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/object/messages.go b/object/messages.go index 3b047e5e..815aa6b3 100644 --- a/object/messages.go +++ b/object/messages.go @@ -321,8 +321,13 @@ type MessagesConversation struct { PushSettings MessagesConversationPushSettings `json:"push_settings"` Important BaseBoolInt `json:"important"` Unanswered BaseBoolInt `json:"unanswered"` + IsMarkedUnread BaseBoolInt `json:"is_marked_unread"` UnreadCount int `json:"unread_count"` // Unread messages number CurrentKeyboard MessagesKeyboard `json:"current_keyboard"` + SortID struct { + MajorID int `json:"major_id"` + MinorID int `json:"minor_id"` + } `json:"sort_id"` } // MessagesConversationCanWrite struct. @@ -340,17 +345,21 @@ type MessagesConversationChatSettings struct { Title string `json:"title"` ActiveIDs []int `json:"active_ids"` ACL struct { - CanInvite BaseBoolInt `json:"can_invite"` - CanChangeInfo BaseBoolInt `json:"can_change_info"` - CanChangePin BaseBoolInt `json:"can_change_pin"` - CanPromoteUsers BaseBoolInt `json:"can_promote_users"` - CanSeeInviteLink BaseBoolInt `json:"can_see_invite_link"` - CanChangeInviteLink BaseBoolInt `json:"can_change_invite_link"` - CanCopyChat BaseBoolInt `json:"can_copy_chat"` - CanModerate BaseBoolInt `json:"can_moderate"` - CanCall BaseBoolInt `json:"can_call"` + CanInvite BaseBoolInt `json:"can_invite"` + CanChangeInfo BaseBoolInt `json:"can_change_info"` + CanChangePin BaseBoolInt `json:"can_change_pin"` + CanPromoteUsers BaseBoolInt `json:"can_promote_users"` + CanSeeInviteLink BaseBoolInt `json:"can_see_invite_link"` + CanChangeInviteLink BaseBoolInt `json:"can_change_invite_link"` + CanCopyChat BaseBoolInt `json:"can_copy_chat"` + CanModerate BaseBoolInt `json:"can_moderate"` + CanCall BaseBoolInt `json:"can_call"` + CanUseMassMentions BaseBoolInt `json:"can_use_mass_mentions"` + CanChangeServiceType BaseBoolInt `json:"can_change_service_type"` } `json:"acl"` IsGroupChannel BaseBoolInt `json:"is_group_channel"` + IsDisappearing BaseBoolInt `json:"is_disappearing"` + IsService BaseBoolInt `json:"is_service"` OwnerID int `json:"owner_id"` AdminIDs []int `json:"admin_ids"` } From 30c71dca34e51f107d236092d801bdd0d8406c5f Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 12 Jul 2020 19:53:34 +0300 Subject: [PATCH 028/105] feat: AccountInfo more fields --- object/account.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/object/account.go b/object/account.go index 12615830..9357b950 100644 --- a/object/account.go +++ b/object/account.go @@ -78,13 +78,18 @@ type AccountAccountCounters struct { // AccountInfo struct. type AccountInfo struct { - Country string `json:"country"` // Country code - Lang int `json:"lang"` // Language ID - HTTPSRequired BaseBoolInt `json:"https_required"` // Information whether HTTPS-only is enabled - Intro BaseBoolInt `json:"intro"` // Information whether user has been processed intro - NoWallReplies BaseBoolInt `json:"no_wall_replies"` // Information whether wall comments should be hidden - OwnPostsDefault BaseBoolInt `json:"own_posts_default"` // Information whether only owners posts should be shown - TwoFactorRequired BaseBoolInt `json:"2fa_required"` // Two factor authentication is enabled + Country string `json:"country"` // Country code + Lang int `json:"lang"` // Language ID + HTTPSRequired BaseBoolInt `json:"https_required"` // Information whether HTTPS-only is enabled + Intro BaseBoolInt `json:"intro"` // Information whether user has been processed intro + NoWallReplies BaseBoolInt `json:"no_wall_replies"` // Information whether wall comments should be hidden + OwnPostsDefault BaseBoolInt `json:"own_posts_default"` // Information whether only owners posts should be shown + TwoFactorRequired BaseBoolInt `json:"2fa_required"` // Two factor authentication is enabled + EuUser BaseBoolInt `json:"eu_user"` + CommunityComments BaseBoolInt `json:"community_comments"` + IsLiveStreamingEnabled BaseBoolInt `json:"is_live_streaming_enabled"` + IsNewLiveStreamingEnabled BaseBoolInt `json:"is_new_live_streaming_enabled"` + LinkRedirects map[string]string `json:"link_redirects"` } // AccountPushSettings struct. From 5157cc0ca3ce7fa43e2077af474add1ed2b26cfd Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 30 Jun 2020 17:57:39 +0300 Subject: [PATCH 029/105] BREAKING CHANGE: NewKeyboard return pointers --- object/messages.go | 16 ++++++---------- object/messages_test.go | 2 +- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/object/messages.go b/object/messages.go index 815aa6b3..a4aa7c11 100644 --- a/object/messages.go +++ b/object/messages.go @@ -86,21 +86,17 @@ type MessagesKeyboard struct { Inline BaseBoolInt `json:"inline,omitempty"` } -// NewMessagesKeyboard return MessagesKeyboard. -// -// FIXME: v2 return *MessagesKeyboard. -func NewMessagesKeyboard(oneTime BaseBoolInt) MessagesKeyboard { - return MessagesKeyboard{ +// NewMessagesKeyboard returns a new MessagesKeyboard. +func NewMessagesKeyboard(oneTime BaseBoolInt) *MessagesKeyboard { + return &MessagesKeyboard{ Buttons: [][]MessagesKeyboardButton{}, OneTime: oneTime, } } -// NewMessagesKeyboardInline return inline MessagesKeyboard. -// -// FIXME: v2 return *MessagesKeyboard. -func NewMessagesKeyboardInline() MessagesKeyboard { - return MessagesKeyboard{ +// NewMessagesKeyboardInline returns a new inline MessagesKeyboard. +func NewMessagesKeyboardInline() *MessagesKeyboard { + return &MessagesKeyboard{ Buttons: [][]MessagesKeyboardButton{}, Inline: true, } diff --git a/object/messages_test.go b/object/messages_test.go index 861b6d2a..ba250acd 100644 --- a/object/messages_test.go +++ b/object/messages_test.go @@ -140,7 +140,7 @@ func TestMessagesGraffiti_ToAttachment(t *testing.T) { func TestMessagesKeyboard_ToJSON(t *testing.T) { t.Parallel() - f := func(keyboard object.MessagesKeyboard, want string) { + f := func(keyboard *object.MessagesKeyboard, want string) { t.Helper() got := keyboard.ToJSON() From faad82cfbf4ba6a116c0effd2fa8de917fb43921 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 30 Jun 2020 17:59:59 +0300 Subject: [PATCH 030/105] BREAKING CHANGE: keyboard payload become interface --- object/messages.go | 45 ++++++++++++++++++++++++++++++++--------- object/messages_test.go | 10 ++++----- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/object/messages.go b/object/messages.go index a4aa7c11..e6bb8f27 100644 --- a/object/messages.go +++ b/object/messages.go @@ -115,12 +115,17 @@ func (keyboard *MessagesKeyboard) AddRow() *MessagesKeyboard { } // AddTextButton add Text button in last row. -func (keyboard *MessagesKeyboard) AddTextButton(label string, payload string, color string) *MessagesKeyboard { +func (keyboard *MessagesKeyboard) AddTextButton(label string, payload interface{}, color string) *MessagesKeyboard { + b, err := json.Marshal(payload) + if err != nil { + panic(err) + } + button := MessagesKeyboardButton{ Action: MessagesKeyboardButtonAction{ Type: ButtonText, Label: label, - Payload: payload, + Payload: string(b), }, Color: color, } @@ -132,11 +137,16 @@ func (keyboard *MessagesKeyboard) AddTextButton(label string, payload string, co } // AddOpenLinkButton add Open Link button in last row. -func (keyboard *MessagesKeyboard) AddOpenLinkButton(link, label, payload string) *MessagesKeyboard { +func (keyboard *MessagesKeyboard) AddOpenLinkButton(link, label string, payload interface{}) *MessagesKeyboard { + b, err := json.Marshal(payload) + if err != nil { + panic(err) + } + button := MessagesKeyboardButton{ Action: MessagesKeyboardButtonAction{ Type: ButtonOpenLink, - Payload: payload, + Payload: string(b), Label: label, Link: link, }, @@ -149,11 +159,16 @@ func (keyboard *MessagesKeyboard) AddOpenLinkButton(link, label, payload string) } // AddLocationButton add Location button in last row. -func (keyboard *MessagesKeyboard) AddLocationButton(payload string) *MessagesKeyboard { +func (keyboard *MessagesKeyboard) AddLocationButton(payload interface{}) *MessagesKeyboard { + b, err := json.Marshal(payload) + if err != nil { + panic(err) + } + button := MessagesKeyboardButton{ Action: MessagesKeyboardButtonAction{ Type: ButtonLocation, - Payload: payload, + Payload: string(b), }, } @@ -164,11 +179,16 @@ func (keyboard *MessagesKeyboard) AddLocationButton(payload string) *MessagesKey } // AddVKPayButton add VK Pay button in last row. -func (keyboard *MessagesKeyboard) AddVKPayButton(payload string, hash string) *MessagesKeyboard { +func (keyboard *MessagesKeyboard) AddVKPayButton(payload interface{}, hash string) *MessagesKeyboard { + b, err := json.Marshal(payload) + if err != nil { + panic(err) + } + button := MessagesKeyboardButton{ Action: MessagesKeyboardButtonAction{ Type: ButtonVKPay, - Payload: payload, + Payload: string(b), Hash: hash, }, } @@ -180,13 +200,18 @@ func (keyboard *MessagesKeyboard) AddVKPayButton(payload string, hash string) *M } // AddVKAppsButton add VK Apps button in last row. -func (keyboard *MessagesKeyboard) AddVKAppsButton(appID, ownerID int, payload, label, hash string) *MessagesKeyboard { +func (keyboard *MessagesKeyboard) AddVKAppsButton(appID, ownerID int, payload interface{}, label, hash string) *MessagesKeyboard { + b, err := json.Marshal(payload) + if err != nil { + panic(err) + } + button := MessagesKeyboardButton{ Action: MessagesKeyboardButtonAction{ Type: ButtonVKApp, AppID: appID, OwnerID: ownerID, - Payload: payload, + Payload: string(b), Label: label, Hash: hash, }, diff --git a/object/messages_test.go b/object/messages_test.go index ba250acd..69ea176c 100644 --- a/object/messages_test.go +++ b/object/messages_test.go @@ -36,7 +36,7 @@ func TestMessagesKeyboard_AddTextButton(t *testing.T) { keyboard.AddTextButton(label, payload, color) assert.Equal(t, keyboard.Buttons[0][0].Color, color) assert.Equal(t, keyboard.Buttons[0][0].Action.Label, label) - assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, payload) + assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, `"`+payload+`"`) } func TestMessagesKeyboard_AddOpenLinkButton(t *testing.T) { @@ -53,7 +53,7 @@ func TestMessagesKeyboard_AddOpenLinkButton(t *testing.T) { keyboard.AddRow() keyboard.AddOpenLinkButton(link, label, payload) - assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, payload) + assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, `"`+payload+`"`) assert.Equal(t, keyboard.Buttons[0][0].Action.Label, label) assert.Equal(t, keyboard.Buttons[0][0].Action.Link, link) } @@ -68,7 +68,7 @@ func TestMessagesKeyboard_AddLocationButton(t *testing.T) { keyboard.AddRow() keyboard.AddLocationButton(payload) - assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, payload) + assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, `"`+payload+`"`) } func TestMessagesKeyboard_AddVKPayButton(t *testing.T) { @@ -84,7 +84,7 @@ func TestMessagesKeyboard_AddVKPayButton(t *testing.T) { keyboard.AddRow() keyboard.AddVKPayButton(payload, hash) - assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, payload) + assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, `"`+payload+`"`) assert.Equal(t, keyboard.Buttons[0][0].Action.Hash, hash) } @@ -106,7 +106,7 @@ func TestMessagesKeyboard_AddVKAppsButton(t *testing.T) { keyboard.AddVKAppsButton(appID, ownerID, payload, label, hash) assert.Equal(t, keyboard.Buttons[0][0].Action.AppID, appID) assert.Equal(t, keyboard.Buttons[0][0].Action.OwnerID, ownerID) - assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, payload) + assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, `"`+payload+`"`) assert.Equal(t, keyboard.Buttons[0][0].Action.Label, label) assert.Equal(t, keyboard.Buttons[0][0].Action.Hash, hash) } From 774fc10e187090b96ea5c96e48073200fbd0942b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Thu, 9 Jul 2020 16:56:00 +0300 Subject: [PATCH 031/105] feat: add callback button --- object/messages.go | 22 ++++++++++++++++++++++ object/messages_test.go | 19 +++++++++++++++++++ object/object.go | 1 + 3 files changed, 42 insertions(+) diff --git a/object/messages.go b/object/messages.go index e6bb8f27..21c42bc9 100644 --- a/object/messages.go +++ b/object/messages.go @@ -223,6 +223,28 @@ func (keyboard *MessagesKeyboard) AddVKAppsButton(appID, ownerID int, payload in return keyboard } +// AddCallbackButton add Callback button in last row. +func (keyboard *MessagesKeyboard) AddCallbackButton(label string, payload interface{}, color string) *MessagesKeyboard { + b, err := json.Marshal(payload) + if err != nil { + panic(err) + } + + button := MessagesKeyboardButton{ + Action: MessagesKeyboardButtonAction{ + Type: ButtonCallback, + Label: label, + Payload: string(b), + }, + Color: color, + } + + lastRow := len(keyboard.Buttons) - 1 + keyboard.Buttons[lastRow] = append(keyboard.Buttons[lastRow], button) + + return keyboard +} + // ToJSON returns the JSON encoding of MessagesKeyboard. func (keyboard MessagesKeyboard) ToJSON() string { b, _ := json.Marshal(keyboard) diff --git a/object/messages_test.go b/object/messages_test.go index 69ea176c..f92ff2b2 100644 --- a/object/messages_test.go +++ b/object/messages_test.go @@ -111,6 +111,25 @@ func TestMessagesKeyboard_AddVKAppsButton(t *testing.T) { assert.Equal(t, keyboard.Buttons[0][0].Action.Hash, hash) } +func TestMessagesKeyboard_AddCallbackButton(t *testing.T) { + t.Parallel() + + const ( + label = "label" + payload = "payload" + color = "color" + ) + + keyboard := object.NewMessagesKeyboard(false) + + keyboard.AddRow() + + keyboard.AddCallbackButton(label, payload, color) + assert.Equal(t, keyboard.Buttons[0][0].Color, color) + assert.Equal(t, keyboard.Buttons[0][0].Action.Label, label) + assert.Equal(t, keyboard.Buttons[0][0].Action.Payload, `"`+payload+`"`) +} + func TestMessagesAudioMessage_ToAttachment(t *testing.T) { t.Parallel() diff --git a/object/object.go b/object/object.go index 194e9814..a6b7b9a4 100644 --- a/object/object.go +++ b/object/object.go @@ -637,6 +637,7 @@ const ( ButtonVKApp = "open_app" ButtonLocation = "location" ButtonOpenLink = "open_link" + ButtonCallback = "callback" ) // Button color. This parameter is used only for buttons with the text and callback types. From 9b434491cd203c28e4b94e617689495af2356fae Mon Sep 17 00:00:00 2001 From: Alnezis Date: Mon, 13 Jul 2020 20:58:07 +0300 Subject: [PATCH 032/105] Added the "expire_ttl" and "is_expired" fields for a long-poll user. --- longpoll-user/v3/extra.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/longpoll-user/v3/extra.go b/longpoll-user/v3/extra.go index dc2d25e8..5f565689 100644 --- a/longpoll-user/v3/extra.go +++ b/longpoll-user/v3/extra.go @@ -73,6 +73,8 @@ type AdditionalData struct { Title string // Message's subject. RefSource string From string // User ID of who sent the message if the message is from a chat + ExpireTTL string + IsExpired string // FromAdmin ID of the administrator who sent the message. It is returned for // messages sent from a community (only for community administrators). FromAdmin string @@ -97,6 +99,14 @@ func (result *AdditionalData) parse(v map[string]interface{}) { result.FromAdmin = fromAdmin } + if expireTTL, ok := v["expire_ttl"].(string); ok { + result.ExpireTTL = expireTTL + } + + if isExpired, ok := v["is_expired"].(string); ok { + result.IsExpired = isExpired + } + if emoji, ok := v["emoji"].(string); ok { result.Emoji = emoji } From 3dfad7de067266d4542911803b21b276d8482546 Mon Sep 17 00:00:00 2001 From: geosonic <36260850+geosonic@users.noreply.github.com> Date: Sat, 18 Jul 2020 19:03:40 +0500 Subject: [PATCH 033/105] =?UTF-8?q?=D0=9D=D0=B5=D1=81=D0=BA=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D0=BA=D0=BE=20=D0=BA=D0=BE=D0=BD=D1=81=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D1=82=20=D0=B8=20=D0=BE=D0=BF=D0=B8=D1=81=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- object/object.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/object/object.go b/object/object.go index a6b7b9a4..1f3af615 100644 --- a/object/object.go +++ b/object/object.go @@ -632,12 +632,12 @@ const ( // Button action type. const ( - ButtonText = "text" - ButtonVKPay = "vkpay" - ButtonVKApp = "open_app" - ButtonLocation = "location" - ButtonOpenLink = "open_link" - ButtonCallback = "callback" + ButtonText = "text" // A button that sends a message with text specified in the label. + ButtonVKPay = "vkpay" // Opens the VK Pay window with predefined parameters. The button is called “Pay with VK Pay” (VK Pay is displayed as a logo). This button always stretches to the whole keyboard width. + ButtonVKApp = "open_app" // Opens a specified VK Apps app. This button always stretches to the whole keyboard width. + ButtonLocation = "location" // Sends the location to the chat. This button always stretches to the whole keyboard width. + ButtonOpenLink = "open_link" // Opens the specified link. + ButtonCallback = "callback" // Allows, without sending a message from the user, to receive a notification about pressing the button and perform the necessary action. ) // Button color. This parameter is used only for buttons with the text and callback types. @@ -670,3 +670,11 @@ const ( PlatformFull // full web version PlatformOther // other apps ) + +// Conversations types. +const ( + PeerUser = "user" + PeerChat = "chat" + PeerGroup = "group" + PeerEmail = "email" +) From 52475b1929d10fc852af9e57c634fdb97dd9ccb1 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 22 Jul 2020 15:43:15 +0300 Subject: [PATCH 034/105] feat: add intents --- api/params/messages.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/api/params/messages.go b/api/params/messages.go index 8c7b792d..68fbbc8f 100644 --- a/api/params/messages.go +++ b/api/params/messages.go @@ -1415,6 +1415,30 @@ func (b *MessagesSendBuilder) DisableMentions(v bool) *MessagesSendBuilder { return b } +// An intent is a label that specifies the approximate content of the message +// sent by the community. It is sent in the optional intent parameter of the +// messages.send method. +const ( + // Used for ad newsletter messages. + PromoNewsletter = "promo_newsletter" + + // Used for messages that request permission from the user to send them an + // advertising message. + BotAdInvite = "bot_ad_invite" + + // Used for the bots advertising message. + BotAdPromo = "bot_ad_promo" + + AccountUpdate = "account_update" + ConfirmedNotification = "confirmed_notification" + CustomerSupport = "customer_support" + Default = "default" + GameNotification = "game_notification" + ModeratedNewsletter = "moderated_newsletter" + NonPromoNewsletter = "non_promo_newsletter" + PurchaseUpdate = "purchase_update" +) + // Intent parameter. // // https://vk.com/dev/bots_docs_4 From 637c0d2a19a9665eac0720692e97610a683fe16d Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 22 Jul 2020 15:53:46 +0300 Subject: [PATCH 035/105] feat: add PhotosConfirmTags method --- api/params/photos.go | 20 ++++++++++++++++++++ api/params/photos_test.go | 10 ++++++++++ api/photos.go | 8 ++++++++ api/photos_test.go | 13 ++++++++++++- 4 files changed, 50 insertions(+), 1 deletion(-) diff --git a/api/params/photos.go b/api/params/photos.go index 3c11e6e0..8a1c7112 100644 --- a/api/params/photos.go +++ b/api/params/photos.go @@ -36,6 +36,26 @@ func (b *PhotosConfirmTagBuilder) TagID(v int) *PhotosConfirmTagBuilder { return b } +// PhotosConfirmTagsBuilder builder. +// +// Confirms a tag on a photo. +// +// https://vk.com/dev/photos.confirmTags +type PhotosConfirmTagsBuilder struct { + api.Params +} + +// NewPhotosConfirmTagsBuilder func. +func NewPhotosConfirmTagsBuilder() *PhotosConfirmTagsBuilder { + return &PhotosConfirmTagsBuilder{api.Params{}} +} + +// Tags parameter. +func (b *PhotosConfirmTagsBuilder) Tags(v string) *PhotosConfirmTagsBuilder { + b.Params["tags"] = v + return b +} + // PhotosCopyBuilder builder. // // Allows to copy a photo to the "Saved photos" album. diff --git a/api/params/photos_test.go b/api/params/photos_test.go index 47be2c4b..51c171e0 100644 --- a/api/params/photos_test.go +++ b/api/params/photos_test.go @@ -21,6 +21,16 @@ func TestPhotosConfirmTagBuilder(t *testing.T) { assert.Equal(t, b.Params["tag_id"], 1) } +func TestPhotosConfirmTagsBuilder(t *testing.T) { + t.Parallel() + + b := params.NewPhotosConfirmTagsBuilder() + + b.Tags("text") + + assert.Equal(t, b.Params["tags"], "text") +} + func TestPhotosCopyBuilder(t *testing.T) { t.Parallel() diff --git a/api/photos.go b/api/photos.go index 865c8cab..cf861caa 100644 --- a/api/photos.go +++ b/api/photos.go @@ -12,6 +12,14 @@ func (vk *VK) PhotosConfirmTag(params Params) (response int, err error) { return } +// PhotosConfirmTags confirms a tags on a photo. +// +// https://vk.com/dev/photos.confirmTags +func (vk *VK) PhotosConfirmTags(params Params) (response int, err error) { + err = vk.RequestUnmarshal("photos.confirmTags", params, &response) + return +} + // PhotosCopy allows to copy a photo to the "Saved photos" album. // // https://vk.com/dev/photos.copy diff --git a/api/photos_test.go b/api/photos_test.go index 02a287b7..935bb416 100644 --- a/api/photos_test.go +++ b/api/photos_test.go @@ -14,11 +14,22 @@ func TestVK_PhotosConfirmTag(t *testing.T) { needUserToken(t) - _, err := vkUser.PhotosConfirmTag(api.Params{ + ok, err := vkUser.PhotosConfirmTag(api.Params{ "photo_id": 1234, "tag_id": 5678, }) noError(t, err) + assert.Equal(t, 0, ok) +} + +func TestVK_PhotosConfirmTags(t *testing.T) { + t.Parallel() + + needUserToken(t) + + ok, err := vkUser.PhotosConfirmTags(api.Params{}) + noError(t, err) + assert.Equal(t, 0, ok) } func TestVK_PhotosCopy(t *testing.T) { From 3c4404481d8e27af1417f8440105beef848c7c98 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 22 Jul 2020 16:28:36 +0300 Subject: [PATCH 036/105] feat: add PhotosDeclineTags method --- api/photos.go | 8 ++++++++ api/photos_test.go | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/api/photos.go b/api/photos.go index cf861caa..f7dd3fec 100644 --- a/api/photos.go +++ b/api/photos.go @@ -47,6 +47,14 @@ func (vk *VK) PhotosCreateComment(params Params) (response int, err error) { return } +// PhotosDeclineTags method. +// +// https://vk.com/dev/photos.declineTags +func (vk *VK) PhotosDeclineTags(params Params) (response int, err error) { + err = vk.RequestUnmarshal("photos.declineTags", params, &response) + return +} + // PhotosDelete deletes a photo. // // https://vk.com/dev/photos.delete diff --git a/api/photos_test.go b/api/photos_test.go index 935bb416..ac3af15b 100644 --- a/api/photos_test.go +++ b/api/photos_test.go @@ -135,6 +135,16 @@ func TestVK_PhotosCreateComment(t *testing.T) { noError(t, err) } +func TestVK_PhotosDeclineTags(t *testing.T) { + t.Parallel() + + needUserToken(t) + + ok, err := vkUser.PhotosDeclineTags(api.Params{}) + noError(t, err) + assert.Equal(t, 1, ok) +} + func LoadPhoto(t *testing.T, albumID int) object.PhotosPhoto { response, err := http.Get(photoURL) if err != nil { From 7ef0297b5e355170bac1139226b0d7f053de2936 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 22 Jul 2020 16:57:38 +0300 Subject: [PATCH 037/105] style: update golangci-lint v1.29 --- .github/workflows/golangci-lint.yml | 4 ++-- .golangci.yml | 3 ++- api/account_test.go | 16 ++++++++-------- api/api_test.go | 8 +++++--- api/fave_test.go | 1 + api/secure.go | 2 +- longpoll-user/longpoll.go | 2 +- longpoll-user/v3/wrapper_test.go | 6 ++++-- object/fave.go | 8 ++++---- 9 files changed, 28 insertions(+), 22 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 44ffdaa3..cc2c09a5 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -8,12 +8,12 @@ jobs: steps: - uses: actions/checkout@v2 - name: golangci-lint - uses: golangci/golangci-lint-action@v1 + uses: golangci/golangci-lint-action@v2 with: # Required: the version of golangci-lint is required and must be # specified without patch version: we always use the latest # patch version. - version: v1.27 + version: v1.29 # Optional: golangci-lint command line arguments. # args: ./the-only-dir-to-analyze/... diff --git a/.golangci.yml b/.golangci.yml index 1c5002af..ea88e770 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -34,7 +34,7 @@ linters: - godot - asciicheck - nolintlint - + - gofumpt # - testpackage # TODO: Fix testpackage # - nestif # TODO: Fix nestif # - goerr113 # TODO: Enable v2 @@ -53,6 +53,7 @@ linters: # - rowserrcheck # - scopelint # - gomodguard +# - exhaustive issues: exclude-rules: diff --git a/api/account_test.go b/api/account_test.go index 3305e559..2bfcd33b 100644 --- a/api/account_test.go +++ b/api/account_test.go @@ -102,14 +102,14 @@ func TestVK_AccountGetProfileInfo(t *testing.T) { assert.NotEmpty(t, info.FirstName) assert.NotEmpty(t, info.LastName) // assert.NotEmpty(t, info.Bdate) - //assert.NotEmpty(t, info.BdateVisibility) - //assert.NotEmpty(t, info.City) - //assert.NotEmpty(t, info.Country) - //assert.NotEmpty(t, info.HomeTown) - //assert.NotEmpty(t, info.Relation) - //assert.NotEmpty(t, info.Sex) - //assert.NotEmpty(t, info.Status) - //assert.NotEmpty(t, info.ScreenName) + // assert.NotEmpty(t, info.BdateVisibility) + // assert.NotEmpty(t, info.City) + // assert.NotEmpty(t, info.Country) + // assert.NotEmpty(t, info.HomeTown) + // assert.NotEmpty(t, info.Relation) + // assert.NotEmpty(t, info.Sex) + // assert.NotEmpty(t, info.Status) + // assert.NotEmpty(t, info.ScreenName) assert.NotEmpty(t, info.Phone) } diff --git a/api/api_test.go b/api/api_test.go index a9b1a4c1..deb9654a 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -103,9 +103,11 @@ func needChatID(t *testing.T) int { return vkChatID } -var vkGroup, vkService, vkUser, vkWidget *api.VK // nolint:gochecknoglobals -var vkUserID, vkGroupID, vkChatID int // nolint:gochecknoglobals -var mux sync.Mutex // nolint:gochecknoglobals +var ( + vkGroup, vkService, vkUser, vkWidget *api.VK // nolint:gochecknoglobals + vkUserID, vkGroupID, vkChatID int // nolint:gochecknoglobals + mux sync.Mutex // nolint:gochecknoglobals +) func TestMain(m *testing.M) { vkGroup = api.NewVK(os.Getenv("GROUP_TOKEN")) diff --git a/api/fave_test.go b/api/fave_test.go index b4e05c0d..263c4f50 100644 --- a/api/fave_test.go +++ b/api/fave_test.go @@ -398,6 +398,7 @@ func TestVK_FaveTag(t *testing.T) { "id": tags.Items[tags.Count-2].ID, }) } + func TestVK_FaveVideo(t *testing.T) { t.Parallel() diff --git a/api/secure.go b/api/secure.go index 78803ef2..0fc8fcf4 100644 --- a/api/secure.go +++ b/api/secure.go @@ -82,7 +82,7 @@ func (vk *VK) SecureGiveEventSticker(params Params) (response SecureGiveEventSti } // SecureSendNotificationResponse struct. -type SecureSendNotificationResponse []int //User ID +type SecureSendNotificationResponse []int // User ID // SecureSendNotification sends notification to the user. // diff --git a/longpoll-user/longpoll.go b/longpoll-user/longpoll.go index 3dc171b8..f5f83465 100644 --- a/longpoll-user/longpoll.go +++ b/longpoll-user/longpoll.go @@ -121,8 +121,8 @@ func (lp *Longpoll) updateServer(updateTs bool) error { params := api.Params{ "lp_version": lp.Version, } - serverSetting, err := lp.VK.MessagesGetLongPollServer(params) + serverSetting, err := lp.VK.MessagesGetLongPollServer(params) if err != nil { return err } diff --git a/longpoll-user/v3/wrapper_test.go b/longpoll-user/v3/wrapper_test.go index a1759826..0d94cfd6 100644 --- a/longpoll-user/v3/wrapper_test.go +++ b/longpoll-user/v3/wrapper_test.go @@ -39,8 +39,10 @@ func needChatID(t *testing.T) int { return vkChatID } -var vkUser *api.VK // nolint:gochecknoglobals -var vkUserID, vkChatID int // nolint:gochecknoglobals +var ( + vkUser *api.VK // nolint:gochecknoglobals + vkUserID, vkChatID int // nolint:gochecknoglobals +) func TestMain(m *testing.M) { time.Sleep(1 * time.Second) diff --git a/object/fave.go b/object/fave.go index 8d80c7b3..802e7f66 100644 --- a/object/fave.go +++ b/object/fave.go @@ -1,12 +1,12 @@ package object -//FaveTag struct. +// FaveTag struct. type FaveTag struct { ID int `json:"id"` Name string `json:"name"` } -//FavePage struct. +// FavePage struct. type FavePage struct { Type string `json:"type"` Description string `json:"description"` @@ -16,7 +16,7 @@ type FavePage struct { Group GroupsGroup `json:"group"` } -//FaveFavesLink struct. +// FaveFavesLink struct. type FaveFavesLink struct { URL string `json:"url"` Title string `json:"title"` @@ -27,7 +27,7 @@ type FaveFavesLink struct { ID string `json:"id"` } -//FaveItem struct. +// FaveItem struct. type FaveItem struct { Type string `json:"type"` Seen BaseBoolInt `json:"seen"` From c4b57a4e90d9eee336b3a867711244ba3a8d26fe Mon Sep 17 00:00:00 2001 From: geosonic <36260850+geosonic@users.noreply.github.com> Date: Sat, 25 Jul 2020 13:31:11 +0500 Subject: [PATCH 038/105] =?UTF-8?q?=D0=9A=D0=BE=D0=BD=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D0=BD=D1=82=D1=8B-=D0=B0=D1=82=D1=82=D0=B0=D1=87=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- object/wall.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/object/wall.go b/object/wall.go index 0d45692e..a0607570 100644 --- a/object/wall.go +++ b/object/wall.go @@ -195,6 +195,8 @@ const ( AttachmentTypeMarketAlbum = "market_album" AttachmentTypeMarket = "market" AttachmentTypeEvent = "event" + AttachmentTypeWall = "wall" + AttachmentTypeStory = "story" ) // WallWallpostAttachment struct. From d5039a8f04c1a70bdec2ae005c219ed5cf00905b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 20:22:38 +0300 Subject: [PATCH 039/105] feat: add PhotosSkipTags method --- api/photos.go | 8 ++++++++ api/photos_test.go | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/api/photos.go b/api/photos.go index f7dd3fec..873aa72f 100644 --- a/api/photos.go +++ b/api/photos.go @@ -627,3 +627,11 @@ func (vk *VK) PhotosSearch(params Params) (response PhotosSearchResponse, err er err = vk.RequestUnmarshal("photos.search", params, &response) return } + +// PhotosSkipTags returns a list of photos. +// +// https://vk.com/dev/photos.skipTags +func (vk *VK) PhotosSkipTags(params Params) (response int, err error) { + err = vk.RequestUnmarshal("photos.skipTags", params, &response) + return +} diff --git a/api/photos_test.go b/api/photos_test.go index ac3af15b..1e98d674 100644 --- a/api/photos_test.go +++ b/api/photos_test.go @@ -475,3 +475,12 @@ func TestVK_PhotosSearch(t *testing.T) { }) noError(t, err) } + +func TestVK_PhotosSkipTags(t *testing.T) { + t.Parallel() + + needUserToken(t) + + _, err := vkUser.PhotosSkipTags(api.Params{}) + noError(t, err) +} From c7ea8efad05b3c10ebb0f5560bb72b4b0fe61830 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 20:50:25 +0300 Subject: [PATCH 040/105] feat: AudioAudioFull add ShortVideosAllowed --- object/audio.go | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/object/audio.go b/object/audio.go index d70d9100..8159f71a 100644 --- a/object/audio.go +++ b/object/audio.go @@ -6,22 +6,23 @@ import ( // AudioAudioFull struct. type AudioAudioFull struct { - ID int `json:"id"` - OwnerID int `json:"owner_id"` - Artist string `json:"artist"` - Title string `json:"title"` - Duration int `json:"duration"` - Date int `json:"date"` - URL string `json:"url"` - IsHq BaseBoolInt `json:"is_hq"` - IsExplicit BaseBoolInt `json:"is_explicit"` - StoriesAllowed BaseBoolInt `json:"stories_allowed"` - LyricsID int `json:"lyrics_id"` - AlbumID int `json:"album_id"` - GenreID int `json:"genre_id"` - TrackCode string `json:"track_code"` - NoSearch int `json:"no_search"` - MainArtists []AudioAudioArtist `json:"main_artists"` + ID int `json:"id"` + OwnerID int `json:"owner_id"` + Artist string `json:"artist"` + Title string `json:"title"` + Duration int `json:"duration"` + Date int `json:"date"` + URL string `json:"url"` + IsHq BaseBoolInt `json:"is_hq"` + IsExplicit BaseBoolInt `json:"is_explicit"` + StoriesAllowed BaseBoolInt `json:"stories_allowed"` + ShortVideosAllowed BaseBoolInt `json:"short_videos_allowed"` + LyricsID int `json:"lyrics_id"` + AlbumID int `json:"album_id"` + GenreID int `json:"genre_id"` + TrackCode string `json:"track_code"` + NoSearch int `json:"no_search"` + MainArtists []AudioAudioArtist `json:"main_artists"` } // ToAttachment return attachment format. From 89163e8f442f46a287860b6538edb846a7a06b7b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 20:50:36 +0300 Subject: [PATCH 041/105] feat: AudioAudioFull add IsFocusTrack --- object/audio.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/audio.go b/object/audio.go index 8159f71a..a0a65cff 100644 --- a/object/audio.go +++ b/object/audio.go @@ -17,6 +17,7 @@ type AudioAudioFull struct { IsExplicit BaseBoolInt `json:"is_explicit"` StoriesAllowed BaseBoolInt `json:"stories_allowed"` ShortVideosAllowed BaseBoolInt `json:"short_videos_allowed"` + IsFocusTrack BaseBoolInt `json:"is_focus_track"` LyricsID int `json:"lyrics_id"` AlbumID int `json:"album_id"` GenreID int `json:"genre_id"` From 00bb1bbdc7306b86e1e87ca259fc52bc1235275c Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 20:53:53 +0300 Subject: [PATCH 042/105] feat: VideoVideo add ContentRestrictedMessage --- object/video.go | 95 +++++++++++++++++++++++++------------------------ 1 file changed, 48 insertions(+), 47 deletions(-) diff --git a/object/video.go b/object/video.go index dd9813af..08e90471 100644 --- a/object/video.go +++ b/object/video.go @@ -6,53 +6,54 @@ import ( // VideoVideo struct. type VideoVideo struct { - AccessKey string `json:"access_key"` // Video access key - AddingDate int `json:"adding_date"` // Date when the video has been added in Unixtime - CanAdd BaseBoolInt `json:"can_add"` // Information whether current user can add the video - CanAddToFaves BaseBoolInt `json:"can_add_to_faves"` // Information whether current user can add the video to faves - CanComment BaseBoolInt `json:"can_comment"` // Information whether current user can comment the video - CanEdit BaseBoolInt `json:"can_edit"` // Information whether current user can edit the video - CanLike BaseBoolInt `json:"can_like"` // Information whether current user can like the video - CanRepost BaseBoolInt `json:"can_repost"` // Information whether current user can repost this video - CanSubscribe BaseBoolInt `json:"can_subscribe"` - CanAttachLink BaseBoolInt `json:"can_attach_link"` - IsFavorite BaseBoolInt `json:"is_favorite"` - IsPrivate BaseBoolInt `json:"is_private"` - Added BaseBoolInt `json:"added"` - Repeat BaseBoolInt `json:"repeat"` // Information whether the video is repeated - ContentRestricted BaseBoolInt `json:"content_restricted"` - Comments int `json:"comments"` // Number of comments - Date int `json:"date"` // Date when video has been uploaded in Unixtime - Description string `json:"description"` // Video description - Duration int `json:"duration"` // Video duration in seconds - Files VideoVideoFiles `json:"files"` - FirstFrame []VideoVideoImage `json:"first_frame"` - Image []VideoVideoImage `json:"image"` - Height int `json:"height"` // Video height - ID int `json:"id"` // Video ID - Live int `json:"live"` // Returns if the video is a live stream - OwnerID int `json:"owner_id"` // Video owner ID - UserID int `json:"user_id"` - Photo130 string `json:"photo_130"` // URL of the preview image with 130 px in width - Photo320 string `json:"photo_320"` // URL of the preview image with 320 px in width - Photo640 string `json:"photo_640"` // URL of the preview image with 640 px in width - Photo800 string `json:"photo_800"` // URL of the preview image with 800 px in width - Photo1280 string `json:"photo_1280"` // URL of the preview image with 1280 px in width - Player string `json:"player"` // URL of the page with a player that can be used to play the video in the browser. - Processing int `json:"processing"` // Returns if the video is processing - Title string `json:"title"` // Video title - Type string `json:"type"` - Views int `json:"views"` // Number of views - Width int `json:"width"` // Video width - Platform string `json:"platform"` - LocalViews int `json:"local_views"` - Likes BaseLikesInfo `json:"likes"` // Count of likes - Reposts BaseRepostsInfo `json:"reposts"` // Count of views - TrackCode string `json:"track_code"` - PrivacyView Privacy `json:"privacy_view"` - PrivacyComment Privacy `json:"privacy_comment"` - ActionButton VideoActionButton `json:"action_button"` - Restriction VideoRestriction `json:"restriction"` + AccessKey string `json:"access_key"` // Video access key + AddingDate int `json:"adding_date"` // Date when the video has been added in Unixtime + CanAdd BaseBoolInt `json:"can_add"` // Information whether current user can add the video + CanAddToFaves BaseBoolInt `json:"can_add_to_faves"` // Information whether current user can add the video to faves + CanComment BaseBoolInt `json:"can_comment"` // Information whether current user can comment the video + CanEdit BaseBoolInt `json:"can_edit"` // Information whether current user can edit the video + CanLike BaseBoolInt `json:"can_like"` // Information whether current user can like the video + CanRepost BaseBoolInt `json:"can_repost"` // Information whether current user can repost this video + CanSubscribe BaseBoolInt `json:"can_subscribe"` + CanAttachLink BaseBoolInt `json:"can_attach_link"` + IsFavorite BaseBoolInt `json:"is_favorite"` + IsPrivate BaseBoolInt `json:"is_private"` + Added BaseBoolInt `json:"added"` + Repeat BaseBoolInt `json:"repeat"` // Information whether the video is repeated + ContentRestricted BaseBoolInt `json:"content_restricted"` + Comments int `json:"comments"` // Number of comments + Date int `json:"date"` // Date when video has been uploaded in Unixtime + Description string `json:"description"` // Video description + Duration int `json:"duration"` // Video duration in seconds + Files VideoVideoFiles `json:"files"` + FirstFrame []VideoVideoImage `json:"first_frame"` + Image []VideoVideoImage `json:"image"` + Height int `json:"height"` // Video height + ID int `json:"id"` // Video ID + Live int `json:"live"` // Returns if the video is a live stream + OwnerID int `json:"owner_id"` // Video owner ID + UserID int `json:"user_id"` + Photo130 string `json:"photo_130"` // URL of the preview image with 130 px in width + Photo320 string `json:"photo_320"` // URL of the preview image with 320 px in width + Photo640 string `json:"photo_640"` // URL of the preview image with 640 px in width + Photo800 string `json:"photo_800"` // URL of the preview image with 800 px in width + Photo1280 string `json:"photo_1280"` // URL of the preview image with 1280 px in width + Player string `json:"player"` // URL of the page with a player that can be used to play the video in the browser. + Processing int `json:"processing"` // Returns if the video is processing + Title string `json:"title"` // Video title + Type string `json:"type"` + Views int `json:"views"` // Number of views + Width int `json:"width"` // Video width + Platform string `json:"platform"` + LocalViews int `json:"local_views"` + Likes BaseLikesInfo `json:"likes"` // Count of likes + Reposts BaseRepostsInfo `json:"reposts"` // Count of views + TrackCode string `json:"track_code"` + PrivacyView Privacy `json:"privacy_view"` + PrivacyComment Privacy `json:"privacy_comment"` + ActionButton VideoActionButton `json:"action_button"` + Restriction VideoRestriction `json:"restriction"` + ContentRestrictedMessage string `json:"content_restricted_message"` } // ToAttachment return attachment format. From c31ae7d67eefd05bb88b132e459e9bd77fb54422 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 20:56:17 +0300 Subject: [PATCH 043/105] feat: StoriesStory add CanLike --- object/stories.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/stories.go b/object/stories.go index 99da2504..a5865db3 100644 --- a/object/stories.go +++ b/object/stories.go @@ -93,6 +93,7 @@ type StoriesStory struct { IsOneTime BaseBoolInt `json:"is_one_time"` NeedMute BaseBoolInt `json:"need_mute"` MuteReply BaseBoolInt `json:"mute_reply"` + CanLike BaseBoolInt `json:"can_like"` Date int `json:"date"` // Date when story has been added in Unixtime. ID int `json:"id"` // Story ID. Link StoriesStoryLink `json:"link"` From 01f5df5b2299e9a1d806cff252fd195d65148bdb Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 21:14:15 +0300 Subject: [PATCH 044/105] BREAKING CHANGE: remove AudioAudioFull AudioAudioFull -> AudioAudio --- api/status.go | 4 ++-- object/audio.go | 25 ++++--------------------- object/audio_test.go | 13 ------------- object/handler.go | 2 +- object/messages.go | 20 ++++++++++---------- object/newsfeed.go | 4 ++-- object/stories.go | 4 ++-- object/users.go | 2 +- object/wall.go | 4 ++-- 9 files changed, 24 insertions(+), 54 deletions(-) diff --git a/api/status.go b/api/status.go index 84752310..6d57e487 100644 --- a/api/status.go +++ b/api/status.go @@ -6,8 +6,8 @@ import ( // StatusGetResponse struct. type StatusGetResponse struct { - Audio object.AudioAudioFull `json:"audio"` - Text string `json:"text"` + Audio object.AudioAudio `json:"audio"` + Text string `json:"text"` } // StatusGet returns data required to show the status of a user or community. diff --git a/object/audio.go b/object/audio.go index a0a65cff..948de7d1 100644 --- a/object/audio.go +++ b/object/audio.go @@ -4,8 +4,9 @@ import ( "fmt" ) -// AudioAudioFull struct. -type AudioAudioFull struct { +// AudioAudio struct. +type AudioAudio struct { + AccessKey string `json:"access_key"` // Access key for the audio ID int `json:"id"` OwnerID int `json:"owner_id"` Artist string `json:"artist"` @@ -27,7 +28,7 @@ type AudioAudioFull struct { } // ToAttachment return attachment format. -func (audio AudioAudioFull) ToAttachment() string { +func (audio AudioAudio) ToAttachment() string { return fmt.Sprintf("audio%d_%d", audio.OwnerID, audio.ID) } @@ -38,24 +39,6 @@ type AudioAudioArtist struct { Domain string `json:"domain"` } -// AudioAudio struct. -type AudioAudio struct { - AccessKey string `json:"access_key"` // Access key for the audio - Artist string `json:"artist"` // Artist name - ID int `json:"id"` // Audio ID - IsExplicit BaseBoolInt `json:"is_explicit"` - IsFocusTrack BaseBoolInt `json:"is_focus_track"` - IsLicensed BaseBoolInt `json:"is_licensed"` - OwnerID int `json:"owner_id"` // Audio owner's ID - Title string `json:"title"` // Title - URL string `json:"url"` // URL of mp3 file -} - -// ToAttachment return attachment format. -func (audio AudioAudio) ToAttachment() string { - return fmt.Sprintf("audio%d_%d", audio.OwnerID, audio.ID) -} - // AudioAudioUploadResponse struct. type AudioAudioUploadResponse struct { Audio string `json:"audio"` diff --git a/object/audio_test.go b/object/audio_test.go index a700984e..e40dd841 100644 --- a/object/audio_test.go +++ b/object/audio_test.go @@ -6,19 +6,6 @@ import ( "github.com/SevereCloud/vksdk/object" ) -func TestAudioAudioFull_ToAttachment(t *testing.T) { - t.Parallel() - - f := func(audio object.AudioAudioFull, want string) { - if got := audio.ToAttachment(); got != want { - t.Errorf("AudioAudioFull.ToAttachment() = %v, want %v", got, want) - } - } - - f(object.AudioAudioFull{ID: 10, OwnerID: 20}, "audio20_10") - f(object.AudioAudioFull{ID: 20, OwnerID: -10}, "audio-10_20") -} - func TestAudioAudio_ToAttachment(t *testing.T) { t.Parallel() diff --git a/object/handler.go b/object/handler.go index 82e0168b..e087d860 100644 --- a/object/handler.go +++ b/object/handler.go @@ -130,7 +130,7 @@ type PhotoCommentDeleteObject struct { type AudioNewFunc func(AudioNewObject, int) // AudioNewObject struct. -type AudioNewObject AudioAudioFull +type AudioNewObject AudioAudio // VideoNewFunc func. type VideoNewFunc func(VideoNewObject, int) diff --git a/object/messages.go b/object/messages.go index 21c42bc9..d78a283d 100644 --- a/object/messages.go +++ b/object/messages.go @@ -447,15 +447,15 @@ type MessagesHistoryAttachment struct { // MessagesHistoryMessageAttachment struct. type MessagesHistoryMessageAttachment struct { - Audio AudioAudioFull `json:"audio"` - Doc DocsDoc `json:"doc"` - Link BaseLink `json:"link"` - Market BaseLink `json:"market"` - Photo PhotosPhoto `json:"photo"` - Share BaseLink `json:"share"` - Type string `json:"type"` - Video VideoVideo `json:"video"` - Wall BaseLink `json:"wall"` + Audio AudioAudio `json:"audio"` + Doc DocsDoc `json:"doc"` + Link BaseLink `json:"link"` + Market BaseLink `json:"market"` + Photo PhotosPhoto `json:"photo"` + Share BaseLink `json:"share"` + Type string `json:"type"` + Video VideoVideo `json:"video"` + Wall BaseLink `json:"wall"` } // MessagesLastActivity struct. @@ -505,7 +505,7 @@ type MessagesMessageActionPhoto struct { // MessagesMessageAttachment struct. type MessagesMessageAttachment struct { - Audio AudioAudioFull `json:"audio"` + Audio AudioAudio `json:"audio"` Doc DocsDoc `json:"doc"` Gift GiftsLayout `json:"gift"` Link BaseLink `json:"link"` diff --git a/object/newsfeed.go b/object/newsfeed.go index 7f22a293..d868a3ff 100644 --- a/object/newsfeed.go +++ b/object/newsfeed.go @@ -17,8 +17,8 @@ type NewsfeedItemAudio struct { // NewsfeedItemAudioAudio struct. type NewsfeedItemAudioAudio struct { - Count int `json:"count"` // Audios number - Items []AudioAudioFull `json:"items"` + Count int `json:"count"` // Audios number + Items []AudioAudio `json:"items"` } // NewsfeedItemDigest struct. diff --git a/object/stories.go b/object/stories.go index a5865db3..a3753ac1 100644 --- a/object/stories.go +++ b/object/stories.go @@ -244,8 +244,8 @@ type StoriesClickableSticker struct { // nolint: maligned Poll PollsPoll `json:"poll,omitempty"` // type=music - Audio AudioAudioFull `json:"audio,omitempty"` - AudioStartTime int `json:"audio_start_time,omitempty"` + Audio AudioAudio `json:"audio,omitempty"` + AudioStartTime int `json:"audio_start_time,omitempty"` // type=app App AppsApp `json:"app"` diff --git a/object/users.go b/object/users.go index 326f49f8..787c0f4e 100644 --- a/object/users.go +++ b/object/users.go @@ -77,7 +77,7 @@ type UsersUser struct { Instagram string `json:"instagram"` Site string `json:"site"` Status string `json:"status"` - StatusAudio AudioAudioFull `json:"status_audio"` + StatusAudio AudioAudio `json:"status_audio"` LastSeen UsersLastSeen `json:"last_seen"` CropPhoto UsersCropPhoto `json:"crop_photo"` FollowersCount int `json:"followers_count"` diff --git a/object/wall.go b/object/wall.go index a0607570..7abfc035 100644 --- a/object/wall.go +++ b/object/wall.go @@ -21,7 +21,7 @@ type WallAttachedNote struct { // WallCommentAttachment struct. type WallCommentAttachment struct { - Audio AudioAudioFull `json:"audio"` + Audio AudioAudio `json:"audio"` Doc DocsDoc `json:"doc"` Link BaseLink `json:"link"` Market MarketMarketItem `json:"market"` @@ -204,7 +204,7 @@ type WallWallpostAttachment struct { AccessKey string `json:"access_key"` // Access key for the audio Album PhotosPhotoAlbum `json:"album"` App WallAppPost `json:"app"` - Audio AudioAudioFull `json:"audio"` + Audio AudioAudio `json:"audio"` Doc DocsDoc `json:"doc"` Event EventsEventAttach `json:"event"` Graffiti WallGraffiti `json:"graffiti"` From 9bb408edddeb5cd865c7e0c9c36fe5f5c8abd8e4 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 21:32:21 +0300 Subject: [PATCH 045/105] feat: MessagesChatSettingsPhoto add IsDefaultPhoto --- object/messages.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/object/messages.go b/object/messages.go index d78a283d..d7d45d50 100644 --- a/object/messages.go +++ b/object/messages.go @@ -346,9 +346,10 @@ type MessagesChatPushSettings struct { // MessagesChatSettingsPhoto struct. type MessagesChatSettingsPhoto struct { - Photo100 string `json:"photo_100"` - Photo200 string `json:"photo_200"` - Photo50 string `json:"photo_50"` + Photo100 string `json:"photo_100"` + Photo200 string `json:"photo_200"` + Photo50 string `json:"photo_50"` + IsDefaultPhoto BaseBoolInt `json:"is_default_photo"` } // MessagesConversation struct. From b3006a0318e2a339212111923e3f8490c0c00e85 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 21:33:17 +0300 Subject: [PATCH 046/105] BREAKING CHANGE: add MessagesChatPreview --- api/messages.go | 2 +- object/messages.go | 55 +++++++++++++++++++--------------------------- 2 files changed, 23 insertions(+), 34 deletions(-) diff --git a/api/messages.go b/api/messages.go index 00920e4f..df3d8dd1 100644 --- a/api/messages.go +++ b/api/messages.go @@ -166,7 +166,7 @@ func (vk *VK) MessagesGetChatChatIDs(params Params) (response MessagesGetChatCha // MessagesGetChatPreviewResponse struct. type MessagesGetChatPreviewResponse struct { - Preview object.MessagesChat `json:"preview"` + Preview object.MessagesChatPreview `json:"preview"` object.ExtendedResponse } diff --git a/object/messages.go b/object/messages.go index d7d45d50..4ed06e5b 100644 --- a/object/messages.go +++ b/object/messages.go @@ -303,39 +303,28 @@ type MessagesTemplateElementCarouselAction struct { // MessagesChat struct. type MessagesChat struct { - AdminID int `json:"admin_id"` // Chat creator ID - ID int `json:"id"` // Chat ID - Kicked BaseBoolInt `json:"kicked"` // Shows that user has been kicked from the chat - Left BaseBoolInt `json:"left"` // Shows that user has been left the chat - Joined BaseBoolInt `json:"joined"` - IsDefaultPhoto BaseBoolInt `json:"is_default_photo"` - Photo100 string `json:"photo_100"` // URL of the preview image with 100 px in width - Photo200 string `json:"photo_200"` // URL of the preview image with 200 px in width - Photo50 string `json:"photo_50"` // URL of the preview image with 50 px in width - PushSettings MessagesChatPushSettings `json:"push_settings"` - Title string `json:"title"` // Chat title - Type string `json:"type"` // Chat type - Users []int `json:"users"` - MembersCount int `json:"members_count"` - Members []int `json:"members"` - Photo MessagesChatSettingsPhoto `json:"photo"` - LocalID int `json:"local_id"` - ChatSettings MessagesConversationChatSettings `json:"chat_settings"` -} - -// MessagesChatFull struct. -type MessagesChatFull struct { - AdminID int `json:"admin_id"` // Chat creator ID - ID int `json:"id"` // Chat ID - Kicked BaseBoolInt `json:"kicked"` // Shows that user has been kicked from the chat - Left BaseBoolInt `json:"left"` // Shows that user has been left the chat - Photo100 string `json:"photo_100"` // URL of the preview image with 100 px in width - Photo200 string `json:"photo_200"` // URL of the preview image with 200 px in width - Photo50 string `json:"photo_50"` // URL of the preview image with 50 px in width - PushSettings MessagesChatPushSettings `json:"push_settings"` - Title string `json:"title"` // Chat title - Type string `json:"type"` // Chat type - Users []MessagesUserXtrInvitedBy `json:"users"` + AdminID int `json:"admin_id"` // Chat creator ID + ID int `json:"id"` // Chat ID + IsDefaultPhoto BaseBoolInt `json:"is_default_photo"` + Photo100 string `json:"photo_100"` // URL of the preview image with 100 px in width + Photo200 string `json:"photo_200"` // URL of the preview image with 200 px in width + Photo50 string `json:"photo_50"` // URL of the preview image with 50 px in width + Title string `json:"title"` // Chat title + Type string `json:"type"` // Chat type + Users []int `json:"users"` + MembersCount int `json:"members_count"` +} + +// MessagesChatPreview struct. +type MessagesChatPreview struct { + AdminID int `json:"admin_id"` + MembersCount int `json:"members_count"` + Members []int `json:"members"` + Title string `json:"title"` + Photo MessagesChatSettingsPhoto `json:"photo"` + LocalID int `json:"local_id"` + Joined bool `json:"joined"` + ChatSettings MessagesConversationChatSettings `json:"chat_settings"` } // MessagesChatPushSettings struct. From dd077f6d4631eec8bf4d5d7803196297d56afa4c Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 21:36:34 +0300 Subject: [PATCH 047/105] feat: AppsApp add AuthorURL --- object/apps.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/apps.go b/object/apps.go index d2319f1a..7704b32e 100644 --- a/object/apps.go +++ b/object/apps.go @@ -39,6 +39,7 @@ type AppsCatalogBanner struct { // AppsApp struct. type AppsApp struct { AuthorOwnerID int `json:"author_owner_id"` + AuthorURL string `json:"author_url"` Banner1120 string `json:"banner_1120"` // URL of the app banner with 1120 px in width Banner560 string `json:"banner_560"` // URL of the app banner with 560 px in width CatalogPosition int `json:"catalog_position"` // Catalog position From 498edc79549fc5e391bf9cbab162c67693c81f3a Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 21:40:10 +0300 Subject: [PATCH 048/105] feat: GroupsActionButtonTarget add IsInternal --- object/groups.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/object/groups.go b/object/groups.go index 6d8f90bf..e7376123 100644 --- a/object/groups.go +++ b/object/groups.go @@ -512,6 +512,8 @@ type GroupsActionButtonTarget struct { // ActionType == ActionTypeOpenGroupApp AppID int `json:"app_id"` + + IsInternal BaseBoolInt `json:"is_internal"` } // GroupsGroupXtrInvitedBy struct. From 61d7496d44d8706eecd12fcd54f7b36587917965 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 21:59:19 +0300 Subject: [PATCH 049/105] feat: AudioAudio add AudioAds --- api/photos_test.go | 3 +-- object/audio.go | 13 +++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/api/photos_test.go b/api/photos_test.go index 1e98d674..7bbbfdb9 100644 --- a/api/photos_test.go +++ b/api/photos_test.go @@ -140,9 +140,8 @@ func TestVK_PhotosDeclineTags(t *testing.T) { needUserToken(t) - ok, err := vkUser.PhotosDeclineTags(api.Params{}) + _, err := vkUser.PhotosDeclineTags(api.Params{}) noError(t, err) - assert.Equal(t, 1, ok) } func LoadPhoto(t *testing.T, albumID int) object.PhotosPhoto { diff --git a/object/audio.go b/object/audio.go index 948de7d1..d1d11528 100644 --- a/object/audio.go +++ b/object/audio.go @@ -25,6 +25,8 @@ type AudioAudio struct { TrackCode string `json:"track_code"` NoSearch int `json:"no_search"` MainArtists []AudioAudioArtist `json:"main_artists"` + Ads AudioAds `json:"ads"` + Subtitle string `json:"subtitle"` } // ToAttachment return attachment format. @@ -32,6 +34,17 @@ func (audio AudioAudio) ToAttachment() string { return fmt.Sprintf("audio%d_%d", audio.OwnerID, audio.ID) } +// AudioAds struct. +type AudioAds struct { + ContentID string `json:"content_id"` + Duration string `json:"duration"` + AccountAgeType string `json:"account_age_type"` + + // TODO: Wut? + // PUID1 string `json:"puid1"` + // PUID22 string `json:"puid22"` +} + // AudioAudioArtist struct. type AudioAudioArtist struct { Name string `json:"name"` From f64e7fb6b4a3fc99b6e5eed49711b9a07efdc070 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:13:48 +0300 Subject: [PATCH 050/105] feat: add MessagesChatPermission --- object/messages.go | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/object/messages.go b/object/messages.go index 4ed06e5b..b78d4920 100644 --- a/object/messages.go +++ b/object/messages.go @@ -390,11 +390,34 @@ type MessagesConversationChatSettings struct { CanUseMassMentions BaseBoolInt `json:"can_use_mass_mentions"` CanChangeServiceType BaseBoolInt `json:"can_change_service_type"` } `json:"acl"` - IsGroupChannel BaseBoolInt `json:"is_group_channel"` - IsDisappearing BaseBoolInt `json:"is_disappearing"` - IsService BaseBoolInt `json:"is_service"` - OwnerID int `json:"owner_id"` - AdminIDs []int `json:"admin_ids"` + IsGroupChannel BaseBoolInt `json:"is_group_channel"` + IsDisappearing BaseBoolInt `json:"is_disappearing"` + IsService BaseBoolInt `json:"is_service"` + IsCreatedForCall BaseBoolInt `json:"is_created_for_call"` + OwnerID int `json:"owner_id"` + AdminIDs []int `json:"admin_ids"` + Permissions MessagesChatPermissions `json:"permissions"` +} + +// MessagesChatPermission struct. +type MessagesChatPermission string + +// Possible values. +const ( + OwnerChatPermission MessagesChatPermission = "owner" + OwnerAndAdminsChatPermission MessagesChatPermission = "owner_and_admins" + AllChatPermission MessagesChatPermission = "all" +) + +// MessagesChatPermissions struct. +type MessagesChatPermissions struct { + Invite MessagesChatPermission `json:"invite"` + ChangeInfo MessagesChatPermission `json:"change_info"` + ChangePin MessagesChatPermission `json:"change_pin"` + UseMassMentions MessagesChatPermission `json:"use_mass_mentions"` + SeeInviteLink MessagesChatPermission `json:"see_invite_link"` + Call MessagesChatPermission `json:"call"` + ChangeAdmins MessagesChatPermission `json:"change_admins"` } // MessagesConversationPeer struct. From b010f85109169505de9c6e7070af2c0a47b91c92 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:18:12 +0300 Subject: [PATCH 051/105] feat: add NewsfeedCategoryAction --- object/newsfeed.go | 49 ++++++++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/object/newsfeed.go b/object/newsfeed.go index d868a3ff..4b2febee 100644 --- a/object/newsfeed.go +++ b/object/newsfeed.go @@ -106,25 +106,36 @@ type NewsfeedItemVideoVideo struct { // NewsfeedItemWallpost struct. type NewsfeedItemWallpost struct { - Activity NewsfeedEventActivity `json:"activity"` - Attachments []WallWallpostAttachment `json:"attachments"` - Comments BaseCommentsInfo `json:"comments"` - FromID int `json:"from_id"` - CopyHistory []WallWallpost `json:"copy_history"` - Geo BaseGeo `json:"geo"` - Likes BaseLikesInfo `json:"likes"` - PostSource WallPostSource `json:"post_source"` - PostType string `json:"post_type"` - Reposts BaseRepostsInfo `json:"reposts"` - MarkedAsAds int `json:"marked_as_ads,omitempty"` - Views interface{} `json:"views,omitempty"` // BUG: Views int or wallViews - IsFavorite BaseBoolInt `json:"is_favorite,omitempty"` - CanDelete BaseBoolInt `json:"can_delete"` - CanArchive BaseBoolInt `json:"can_archive"` - IsArchived BaseBoolInt `json:"is_archived"` - SignerID int `json:"signer_id,omitempty"` - Text string `json:"text"` // Post text - Copyright WallPostCopyright `json:"copyright"` + Activity NewsfeedEventActivity `json:"activity"` + Attachments []WallWallpostAttachment `json:"attachments"` + Comments BaseCommentsInfo `json:"comments"` + FromID int `json:"from_id"` + CopyHistory []WallWallpost `json:"copy_history"` + Geo BaseGeo `json:"geo"` + Likes BaseLikesInfo `json:"likes"` + PostSource WallPostSource `json:"post_source"` + PostType string `json:"post_type"` + Reposts BaseRepostsInfo `json:"reposts"` + MarkedAsAds int `json:"marked_as_ads,omitempty"` + Views interface{} `json:"views,omitempty"` // BUG: Views int or wallViews + IsFavorite BaseBoolInt `json:"is_favorite,omitempty"` + CanDelete BaseBoolInt `json:"can_delete"` + CanArchive BaseBoolInt `json:"can_archive"` + IsArchived BaseBoolInt `json:"is_archived"` + SignerID int `json:"signer_id,omitempty"` + Text string `json:"text"` // Post text + Copyright WallPostCopyright `json:"copyright"` + CategoryAction NewsfeedCategoryAction `json:"category_action"` +} + +// NewsfeedCategoryAction struct. +type NewsfeedCategoryAction struct { + Action struct { + Target string `json:"target"` + Type string `json:"type"` + URL string `json:"url"` + } `json:"action"` + Name string `json:"name"` } // NewsfeedList struct. From 0a17a167de9473cbf3d341f86d92f879d5c21d00 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:23:50 +0300 Subject: [PATCH 052/105] feat: WallWallpostToID add ParentsStack --- object/wall.go | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/object/wall.go b/object/wall.go index 7abfc035..a15eeaab 100644 --- a/object/wall.go +++ b/object/wall.go @@ -223,23 +223,24 @@ type WallWallpostAttachment struct { // WallWallpostToID struct. type WallWallpostToID struct { - Attachments []WallWallpostAttachment `json:"attachments"` - Comments BaseCommentsInfo `json:"comments"` - CopyOwnerID int `json:"copy_owner_id"` // ID of the source post owner - CopyPostID int `json:"copy_post_id"` // ID of the source post - Date int `json:"date"` // Date of publishing in Unixtime - FromID int `json:"from_id"` // Post author ID - Geo BaseGeo `json:"geo"` - ID int `json:"id"` // Post ID - Likes BaseLikesInfo `json:"likes"` - PostID int `json:"post_id"` // wall post ID (if comment) - PostSource WallPostSource `json:"post_source"` - PostType string `json:"post_type"` - Reposts BaseRepostsInfo `json:"reposts"` - SignerID int `json:"signer_id"` // Post signer ID - Text string `json:"text"` // Post text - ToID int `json:"to_id"` // Wall owner's ID - IsFavorite BaseBoolInt `json:"is_favorite"` // Information whether the post in favorites list + Attachments []WallWallpostAttachment `json:"attachments"` + Comments BaseCommentsInfo `json:"comments"` + CopyOwnerID int `json:"copy_owner_id"` // ID of the source post owner + CopyPostID int `json:"copy_post_id"` // ID of the source post + Date int `json:"date"` // Date of publishing in Unixtime + FromID int `json:"from_id"` // Post author ID + Geo BaseGeo `json:"geo"` + ID int `json:"id"` // Post ID + Likes BaseLikesInfo `json:"likes"` + PostID int `json:"post_id"` // wall post ID (if comment) + PostSource WallPostSource `json:"post_source"` + PostType string `json:"post_type"` + Reposts BaseRepostsInfo `json:"reposts"` + SignerID int `json:"signer_id"` // Post signer ID + Text string `json:"text"` // Post text + ToID int `json:"to_id"` // Wall owner's ID + IsFavorite BaseBoolInt `json:"is_favorite"` // Information whether the post in favorites list + ParentsStack []int `json:"parents_stack"` } // WallPostCopyright information about the source of the post. From bf7d9a9edcf50baac380d610400b967225b499cb Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:24:31 +0300 Subject: [PATCH 053/105] feat: WallWallpostToID add MarkedAsAds --- object/wall.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/wall.go b/object/wall.go index a15eeaab..2d60cf25 100644 --- a/object/wall.go +++ b/object/wall.go @@ -240,6 +240,7 @@ type WallWallpostToID struct { Text string `json:"text"` // Post text ToID int `json:"to_id"` // Wall owner's ID IsFavorite BaseBoolInt `json:"is_favorite"` // Information whether the post in favorites list + MarkedAsAds BaseBoolInt `json:"marked_as_ads"` ParentsStack []int `json:"parents_stack"` } From d65200cdee28c857a652e6303d251e90b31ca7b2 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:33:30 +0300 Subject: [PATCH 054/105] feat: WallWallpost add PostID --- object/wall.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/wall.go b/object/wall.go index 2d60cf25..f3141ed5 100644 --- a/object/wall.go +++ b/object/wall.go @@ -152,6 +152,7 @@ type WallWallpost struct { MarkedAsAds BaseBoolInt `json:"marked_as_ads"` Edited int `json:"edited"` // Date of editing in Unixtime Copyright WallPostCopyright `json:"copyright"` + PostID int `json:"post_id"` } // WallWallpostAttached struct. From dbc07468e1d9fc0d35374f278f6552caa3d0bfe8 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:33:38 +0300 Subject: [PATCH 055/105] feat: WallWallpost add ParentsStack --- object/wall.go | 1 + 1 file changed, 1 insertion(+) diff --git a/object/wall.go b/object/wall.go index f3141ed5..f4e754ad 100644 --- a/object/wall.go +++ b/object/wall.go @@ -153,6 +153,7 @@ type WallWallpost struct { Edited int `json:"edited"` // Date of editing in Unixtime Copyright WallPostCopyright `json:"copyright"` PostID int `json:"post_id"` + ParentsStack []int `json:"parents_stack"` } // WallWallpostAttached struct. From 8ac5f6a7c25debb493df7a177d7b292ddd1c0377 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 29 Jul 2020 22:34:01 +0300 Subject: [PATCH 056/105] feat: AudioAudio add IsLicensed --- object/audio.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/object/audio.go b/object/audio.go index d1d11528..407bac83 100644 --- a/object/audio.go +++ b/object/audio.go @@ -19,6 +19,7 @@ type AudioAudio struct { StoriesAllowed BaseBoolInt `json:"stories_allowed"` ShortVideosAllowed BaseBoolInt `json:"short_videos_allowed"` IsFocusTrack BaseBoolInt `json:"is_focus_track"` + IsLicensed BaseBoolInt `json:"is_licensed"` LyricsID int `json:"lyrics_id"` AlbumID int `json:"album_id"` GenreID int `json:"genre_id"` @@ -39,10 +40,8 @@ type AudioAds struct { ContentID string `json:"content_id"` Duration string `json:"duration"` AccountAgeType string `json:"account_age_type"` - - // TODO: Wut? - // PUID1 string `json:"puid1"` - // PUID22 string `json:"puid22"` + PUID1 string `json:"puid1"` + PUID22 string `json:"puid22"` } // AudioAudioArtist struct. From 02a88888ff9fb548dda0597571117321dc76b5ae Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 31 Jul 2020 15:13:51 +0300 Subject: [PATCH 057/105] BREAKING CHANGE: v5.122 update MarketMarketItem --- api/api.go | 2 +- object/market.go | 126 +++++++++++++++++++++++++++++++++-------------- 2 files changed, 89 insertions(+), 39 deletions(-) diff --git a/api/api.go b/api/api.go index cdf7b813..337f1695 100644 --- a/api/api.go +++ b/api/api.go @@ -23,7 +23,7 @@ import ( // Api constants. const ( - Version = "5.120" + Version = "5.122" MethodURL = "https://api.vk.com/method/" ) diff --git a/object/market.go b/object/market.go index 95b332e0..d8439a38 100644 --- a/object/market.go +++ b/object/market.go @@ -41,29 +41,40 @@ type MarketMarketCategory struct { // MarketMarketItem struct. type MarketMarketItem struct { - AccessKey string `json:"access_key"` // Access key for the market item - Availability int `json:"availability"` // Information whether the item is available - Category MarketMarketCategory `json:"category"` - Date int `json:"date"` // Date when the item has been created in Unixtime - Description string `json:"description"` // Item description - ID int `json:"id"` // Item ID - OwnerID int `json:"owner_id"` // Item owner's ID - Price MarketPrice `json:"price"` - ThumbPhoto string `json:"thumb_photo"` // URL of the preview image - Title string `json:"title"` // Item title - CanComment BaseBoolInt `json:"can_comment"` - CanRepost BaseBoolInt `json:"can_repost"` - IsFavorite BaseBoolInt `json:"is_favorite"` - AlbumsIDs []int `json:"albums_ids"` - Photos []PhotosPhoto `json:"photos"` - Likes BaseLikesInfo `json:"likes"` - Reposts BaseRepostsInfo `json:"reposts"` - ViewsCount int `json:"views_count"` - URL string `json:"url"` // URL to item - ButtonTitle string `json:"button_title"` - ExternalID string `json:"external_id"` - Dimensions MarketDimensions `json:"dimensions"` - Weight int `json:"weight"` + AccessKey string `json:"access_key"` // Access key for the market item + Availability int `json:"availability"` // Information whether the item is available + Category MarketMarketCategory `json:"category"` + Date int `json:"date"` // Date when the item has been created in Unixtime + Description string `json:"description"` // Item description + ID int `json:"id"` // Item ID + OwnerID int `json:"owner_id"` // Item owner's ID + Price MarketPrice `json:"price"` + ThumbPhoto string `json:"thumb_photo"` // URL of the preview image + Title string `json:"title"` // Item title + CanComment BaseBoolInt `json:"can_comment"` + CanRepost BaseBoolInt `json:"can_repost"` + IsFavorite BaseBoolInt `json:"is_favorite"` + IsMainVariant BaseBoolInt `json:"is_main_variant"` + AlbumsIDs []int `json:"albums_ids"` + Photos []PhotosPhoto `json:"photos"` + Likes BaseLikesInfo `json:"likes"` + Reposts BaseRepostsInfo `json:"reposts"` + ViewsCount int `json:"views_count"` + URL string `json:"url"` // URL to item + ButtonTitle string `json:"button_title"` + ExternalID string `json:"external_id"` + Dimensions MarketDimensions `json:"dimensions"` + Weight int `json:"weight"` + VariantsGroupingID int `json:"variants_grouping_id"` + PropertyValues []MarketMarketItemProperty `json:"property_values"` + CartQuantity int `json:"cart_quantity"` +} + +// MarketMarketItemProperty struct. +type MarketMarketItemProperty struct { + VariantID int `json:"variant_id"` + VariantName string `json:"variant_name"` + PropertyName string `json:"property_name"` } // MarketDimensions struct. @@ -109,20 +120,59 @@ const ( // MarketOrder struct. type MarketOrder struct { - ID int `json:"id"` - GroupID int `json:"group_id"` - UserID int `json:"user_id"` - Date int `json:"date"` - Status MarketOrderStatus `json:"status"` - ItemsCount int `json:"items_count"` - TotalPrice MarketPrice `json:"total_price"` - DisplayOrderID string `json:"display_order_id"` - TrackNumber string `json:"track_number"` - TrackLink string `json:"track_link"` - Comment string `json:"comment"` - Address string `json:"address"` - PreviewOrderItems []MarketOrderItem `json:"preview_order_items"` - PriceDetails []MarketPriceDetail `json:"price_details"` + ID int `json:"id"` + GroupID int `json:"group_id"` + UserID int `json:"user_id"` + Date int `json:"date"` + Status MarketOrderStatus `json:"status"` + ItemsCount int `json:"items_count"` + TotalPrice MarketPrice `json:"total_price"` + DisplayOrderID string `json:"display_order_id"` + Comment string `json:"comment"` + PreviewOrderItems []MarketOrderItem `json:"preview_order_items"` + PriceDetails []MarketPriceDetail `json:"price_details"` + Delivery MarketOrderDelivery `json:"delivery"` + Recipient MarketOrderRecipient `json:"recipient"` +} + +// MarketOrderDelivery struct. +type MarketOrderDelivery struct { + TrackNumber string `json:"track_number"` + TrackLink string `json:"track_link"` + Address string `json:"address"` + Type string `json:"type"` + DeliveryPoint MarketDeliveryPoint `json:"delivery_point,omitempty"` +} + +// MarketDeliveryPoint struct. +type MarketDeliveryPoint struct { + ID int `json:"id"` + ExternalID string `json:"external_id"` + OutpostOnly BaseBoolInt `json:"outpost_only"` + CashOnly BaseBoolInt `json:"cash_only"` + Address MarketDeliveryPointAddress `json:"address"` + DisplayTitle string `json:"display_title"` + ServiceID int `json:"service_id"` +} + +// MarketDeliveryPointAddress struct. +type MarketDeliveryPointAddress struct { + ID int `json:"id"` + Address string `json:"address"` + CityID int `json:"city_id"` + CountryID int `json:"country_id"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + Phone string `json:"phone"` + Title string `json:"title"` + WorkInfoStatus string `json:"work_info_status"` +} + +// MarketOrderRecipient struct. +type MarketOrderRecipient struct { + Name string `json:"name"` + Phone string `json:"phone"` + DisplayText string `json:"display_text"` } // MarketOrderItem struct. @@ -141,5 +191,5 @@ type MarketOrderItem struct { type MarketPriceDetail struct { Title string `json:"title"` Price MarketPrice `json:"price"` - IsAccent bool `json:"is_accent,omitempty"` + IsAccent BaseBoolInt `json:"is_accent,omitempty"` } From dd5473893905819b64dc76acfcf498c67d9b4af6 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 31 Jul 2020 15:30:27 +0300 Subject: [PATCH 058/105] test: MarketMarketItem Date & ViewsCount omitempty --- api/fave_test.go | 2 +- api/groups_test.go | 2 +- api/market_test.go | 8 ++++---- object/market.go | 10 +++++----- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/api/fave_test.go b/api/fave_test.go index 263c4f50..92e5751a 100644 --- a/api/fave_test.go +++ b/api/fave_test.go @@ -82,7 +82,7 @@ func testFave(t *testing.T, f object.FaveItem) { } } - assert.NotEmpty(t, f.Product.Date, "f.Product.Date") + // assert.NotEmpty(t, f.Product.Date, "f.Product.Date") assert.NotEmpty(t, f.Product.Description, "f.Product.Description") // assert.NotEmpty(t,f.Product.ExternalID) assert.NotEmpty(t, f.Product.ID, "f.Product.ID") diff --git a/api/groups_test.go b/api/groups_test.go index 8f21f28a..bd3ca34f 100644 --- a/api/groups_test.go +++ b/api/groups_test.go @@ -415,7 +415,7 @@ func TestVK_GroupsGetByID(t *testing.T) { } // assert.NotEmpty(t, group.Contacts) assert.NotEmpty(t, group.Site) - assert.NotEmpty(t, group.MainSection) + // assert.NotEmpty(t, group.MainSection) // assert.NotEmpty(t, group.Trending) // assert.NotEmpty(t, group.IsMessagesBlocked) assert.NotEmpty(t, group.OnlineStatus) diff --git a/api/market_test.go b/api/market_test.go index c28131fc..335d61a1 100644 --- a/api/market_test.go +++ b/api/market_test.go @@ -243,7 +243,7 @@ func TestVK_MarketGetByID(t *testing.T) { assert.NotEmpty(t, res.Items[0].Category.Name) assert.NotEmpty(t, res.Items[0].Category.Section.ID) assert.NotEmpty(t, res.Items[0].Category.Section.Name) - assert.NotEmpty(t, res.Items[0].Date) + // assert.NotEmpty(t, res.Items[0].Date) assert.NotEmpty(t, res.Items[0].Description) // assert.NotEmpty(t, res.Items[0].ExternalID) assert.NotEmpty(t, res.Items[0].ID) @@ -259,8 +259,8 @@ func TestVK_MarketGetByID(t *testing.T) { assert.NotEmpty(t, res.Items[0].CanComment) assert.NotEmpty(t, res.Items[0].CanRepost) assert.NotEmpty(t, res.Items[0].Likes) + // assert.NotEmpty(t, res.Items[0].ViewsCount) assert.NotEmpty(t, res.Items[0].Reposts) - assert.NotEmpty(t, res.Items[0].ViewsCount) } } @@ -370,7 +370,7 @@ func TestVK_MarketSearch(t *testing.T) { assert.NotEmpty(t, res.Items[0].Category.Name) assert.NotEmpty(t, res.Items[0].Category.Section.ID) assert.NotEmpty(t, res.Items[0].Category.Section.Name) - assert.NotEmpty(t, res.Items[0].Date) + // assert.NotEmpty(t, res.Items[0].Date) assert.NotEmpty(t, res.Items[0].Description) // assert.NotEmpty(t, res.Items[0].ExternalID) assert.NotEmpty(t, res.Items[0].ID) @@ -384,7 +384,7 @@ func TestVK_MarketSearch(t *testing.T) { assert.NotEmpty(t, res.Items[0].AlbumsIDs) assert.NotEmpty(t, res.Items[0].Photos) assert.NotEmpty(t, res.Items[0].Likes) + // assert.NotEmpty(t, res.Items[0].ViewsCount) assert.NotEmpty(t, res.Items[0].Reposts) - assert.NotEmpty(t, res.Items[0].ViewsCount) } } diff --git a/object/market.go b/object/market.go index d8439a38..68299323 100644 --- a/object/market.go +++ b/object/market.go @@ -44,10 +44,10 @@ type MarketMarketItem struct { AccessKey string `json:"access_key"` // Access key for the market item Availability int `json:"availability"` // Information whether the item is available Category MarketMarketCategory `json:"category"` - Date int `json:"date"` // Date when the item has been created in Unixtime - Description string `json:"description"` // Item description - ID int `json:"id"` // Item ID - OwnerID int `json:"owner_id"` // Item owner's ID + Date int `json:"date,omitempty"` // Date when the item has been created in Unixtime + Description string `json:"description"` // Item description + ID int `json:"id"` // Item ID + OwnerID int `json:"owner_id"` // Item owner's ID Price MarketPrice `json:"price"` ThumbPhoto string `json:"thumb_photo"` // URL of the preview image Title string `json:"title"` // Item title @@ -59,7 +59,7 @@ type MarketMarketItem struct { Photos []PhotosPhoto `json:"photos"` Likes BaseLikesInfo `json:"likes"` Reposts BaseRepostsInfo `json:"reposts"` - ViewsCount int `json:"views_count"` + ViewsCount int `json:"views_count,omitempty"` URL string `json:"url"` // URL to item ButtonTitle string `json:"button_title"` ExternalID string `json:"external_id"` From 6ac648ad9585725671b84f9322f746f7b3a35018 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 059/105] BREAKING CHANGE: new errors --- api/api.go | 49 ++--- api/api_test.go | 39 ++-- api/errors.go | 440 ++++++++++++++++++++++++++++++++++++++ api/errors/errors.go | 411 ----------------------------------- api/errors/errors_test.go | 50 ----- api/gifts_test.go | 3 +- api/messages_test.go | 6 +- api/notes_test.go | 11 +- api/streaming_test.go | 12 +- api/upload_test.go | 93 +++----- api/users_test.go | 3 +- object/object.go | 67 ------ 12 files changed, 506 insertions(+), 678 deletions(-) create mode 100644 api/errors.go delete mode 100644 api/errors/errors.go delete mode 100644 api/errors/errors_test.go diff --git a/api/api.go b/api/api.go index 337f1695..9e7806b1 100644 --- a/api/api.go +++ b/api/api.go @@ -16,7 +16,6 @@ import ( "sync" "time" - "github.com/SevereCloud/vksdk/api/errors" "github.com/SevereCloud/vksdk/internal" "github.com/SevereCloud/vksdk/object" ) @@ -95,24 +94,11 @@ type VK struct { rps int } -// Error struct VK. -// -// Deprecated: use object.Error. -type Error struct { - Code int `json:"error_code"` - Message string `json:"error_msg"` - Text string `json:"error_text"` - CaptchaSID string `json:"captcha_sid"` - CaptchaImg string `json:"captcha_img"` - ConfirmationText string `json:"confirmation_text"` // text of the message to be shown in the default confirmation window. - RequestParams []object.BaseRequestParam `json:"request_params"` -} - // Response struct. type Response struct { - Response json.RawMessage `json:"response"` - Error object.Error `json:"error"` - ExecuteErrors []object.ExecuteError `json:"execute_errors"` + Response json.RawMessage `json:"response"` + Error Error `json:"error"` + ExecuteErrors ExecuteErrors `json:"execute_errors"` } // NewVK returns a new VK. @@ -265,16 +251,18 @@ func (vk *VK) defaultHandler(method string, params Params) (Response, error) { _ = resp.Body.Close() - err = errors.New(response.Error) - if err != nil { - if errors.GetType(err) == errors.TooMany && attempt < vk.Limit { + switch response.Error.Code { + case ErrNoType: + return response, nil + case ErrTooMany: + if attempt < vk.Limit { continue } - return response, err + return response, response.Error } - return response, nil + return response, response.Error } } @@ -341,21 +329,8 @@ func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error copyParams["v"] = vk.Version resp, err := vk.Handler("execute", copyParams) - - // Add execute errors - for _, executeError := range resp.ExecuteErrors { - context := object.Error{ - Code: executeError.ErrorCode, - Message: executeError.ErrorMsg, - RequestParams: []object.BaseRequestParam{ - { - Key: "method", - Value: executeError.Method, - }, - }, - } - - err = errors.AddErrorContext(err, context) + if resp.ExecuteErrors != nil { + return resp.ExecuteErrors } jsonErr := json.Unmarshal(resp.Response, &obj) diff --git a/api/api_test.go b/api/api_test.go index deb9654a..760f9e00 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -9,7 +9,6 @@ import ( "testing" "github.com/SevereCloud/vksdk/api" - "github.com/SevereCloud/vksdk/api/errors" "github.com/SevereCloud/vksdk/object" "github.com/stretchr/testify/assert" ) @@ -17,34 +16,29 @@ import ( func noError(t *testing.T, err error) bool { t.Helper() - switch errors.GetType(err) { - // case errors.TooMany: - // t.Skip("Too many requests per second") - case errors.Server: - t.Skip("Internal server error") - case errors.Permission: - t.Skip("Permission to perform this action is denied") - case errors.Captcha: - t.Skip("Captcha needed") - } - - if err != nil { - ctx := errors.GetErrorContext(err) - if ctx.Code != 0 { + if e, ok := err.(*api.Error); ok { + switch e.Code { + case api.ErrServer: + t.Skip("Internal server error") + case api.ErrPermission: + t.Skip("Permission to perform this action is denied") + case api.ErrCaptcha: + t.Skip("Captcha needed") + default: s := "\n" - s += fmt.Sprintf("code: %d\n", ctx.Code) - s += fmt.Sprintf("text: %s\n", ctx.Text) - s += fmt.Sprintf("message: %s\n", ctx.Message) + s += fmt.Sprintf("code: %d\n", e.Code) + s += fmt.Sprintf("text: %s\n", e.Text) + s += fmt.Sprintf("message: %s\n", e.Message) s += "params:\n" - for _, param := range ctx.RequestParams { + for _, param := range e.RequestParams { s += fmt.Sprintf("\t%s: %s\n", param.Key, param.Value) } t.Log(s) - } else { - t.Log(fmt.Sprintf("\n%#v", err)) } + } else { + t.Log(fmt.Sprintf("\n%#v", err)) } return assert.NoError(t, err) @@ -305,7 +299,8 @@ func TestVK_CaptchaForce(t *testing.T) { needUserToken(t) _, err := vkUser.CaptchaForce(api.Params{}) - if errors.GetType(err) != errors.Captcha { + + if e, ok := err.(*api.Error); err != nil || !ok || e.Code != api.ErrCaptcha { t.Errorf("VK.CaptchaForce() err=%v, want 14", err) } } diff --git a/api/errors.go b/api/errors.go new file mode 100644 index 00000000..fd1bf891 --- /dev/null +++ b/api/errors.go @@ -0,0 +1,440 @@ +package api + +import ( + "fmt" + + "github.com/SevereCloud/vksdk/object" +) + +// ErrorType is the type of an error. +type ErrorType int + +// Error returns the message of a ErrorType. +func (e ErrorType) Error() string { + return fmt.Sprintf("api: error with code %d", e) +} + +// Error codes. See https://vk.com/dev/errors +const ( + ErrNoType ErrorType = 0 // NoType error + + // Unknown error occurred + // + // Try again later. + ErrUnknown ErrorType = 1 + + // Application is disabled. Enable your application or use test mode + // + // You need to switch on the app in Settings (https://vk.com/editapp?id={Your API_ID} + // or use the test mode (test_mode=1). + ErrDisabled ErrorType = 2 + + // Unknown method passed + // + // Check the method name: http://vk.com/dev/methods + ErrMethod ErrorType = 3 + ErrSignature ErrorType = 4 // Incorrect signature + + // User authorization failed + // + // Make sure that you use a correct authorization type + ErrAuth ErrorType = 5 + + // Too many requests per second + // + // Decrease the request frequency or use the execute method. + // More details on frequency limits here: + // https://vk.com/dev/api_requests + ErrTooMany ErrorType = 6 + + // Permission to perform this action is denied + // + // Make sure that your have received required permissions during the authorization. + // You can do it with the account.getAppPermissions method. + // https://vk.com/dev/permissions + ErrPermission ErrorType = 7 + + // Invalid request + // + // Check the request syntax and used parameters list (it can be found on a method description page) + ErrRequest ErrorType = 8 + + // Flood control + // + // You need to decrease the count of identical requests. For more efficient work you may use execute. + ErrFlood ErrorType = 9 + + // Internal server error + // + // Try again later. + ErrServer ErrorType = 10 + + // In test mode application should be disabled or user should be authorized + // + // Switch the app off in Settings: https://vk.com/editapp?id={Your API_ID} + ErrEnabledInTest ErrorType = 11 + + // Unable to compile code. + ErrCompile ErrorType = 12 + + // Runtime error occurred during code invocation. + ErrRuntime ErrorType = 13 + + // Captcha needed + // + // See https://vk.com/dev/captcha_error + ErrCaptcha ErrorType = 14 + + // Access denied + // + // Make sure that you use correct identifiers and the content is available for the user in the full version of the site. + ErrAccess ErrorType = 15 + + // HTTP authorization failed + // + // To avoid this error check if a user has the 'Use secure connection' option enabled with the account.getInfo method. + ErrAuthHTTPS ErrorType = 16 + + // Validation required + // + // Make sure that you don't use a token received with http://vk.com/dev/auth_mobile for a request from the server. It's restricted. + // + // https://vk.com/dev/need_validation + ErrAuthValidation ErrorType = 17 + ErrUserDeleted ErrorType = 18 // User was deleted or banned + ErrBlocked ErrorType = 19 // Content blocked + + // Permission to perform this action is denied for non-standalone applications + // + // If you see this error despite your app has the Standalone type, make sure that you use redirect_uri=https://oauth.vk.com/blank.html. + // Details here: https://vk.com/dev/auth_mobile + ErrMethodPermission ErrorType = 20 + ErrMethodAds ErrorType = 21 // Permission to perform this action is allowed only for standalone and OpenAPI applications + ErrUpload ErrorType = 22 // Upload error + + // This method was disabled + // + // All the methods available now are listed here: http://vk.com/dev/methods + ErrMethodDisabled ErrorType = 23 + + // Confirmation required + // + // In some cases VK requires to request action confirmation from the user (for Standalone apps only). + // + // Following parameter is transmitted with the error message as well: + // + // confirmation_text – text of the message to be shown in the default confirmation window. + // + // The app should display the default confirmation window + // with text from confirmation_text and two buttons: "Continue" and "Cancel". + // If user confirms the action repeat the request with an extra parameter: confirm = 1. + // + // https://vk.com/dev/need_confirmation + ErrNeedConfirmation ErrorType = 24 + ErrNeedTokenConfirmation ErrorType = 25 // Token confirmation required + ErrGroupAuth ErrorType = 27 // Group authorization failed + ErrAppAuth ErrorType = 28 // Application authorization failed + + // Rate limit reached + // + // More details on rate limits here: https://vk.com/dev/data_limits + ErrRateLimit ErrorType = 29 + ErrPrivateProfile ErrorType = 30 // This profile is private + + // One of the parameters specified was missing or invalid + // + // Check the required parameters list and their format on a method description page. + ErrParam ErrorType = 100 + + // Invalid application API ID + // + // Find the app in the administrated list in settings: http://vk.com/apps?act=settings + // And set the correct API_ID in the request. + ErrParamAPIID ErrorType = 101 + ErrLimits ErrorType = 103 // Out of limits + ErrNotFound ErrorType = 104 // Not found + ErrSaveFile ErrorType = 105 // Couldn't save file + ErrActionFailed ErrorType = 106 // Unable to process action + + // Invalid user id + // + // Make sure that you use a correct id. You can get an id using a screen + // name with the utils.resolveScreenName method + ErrParamUserID ErrorType = 113 + ErrParamAlbumID ErrorType = 114 // Invalid album id + ErrParamServer ErrorType = 118 // Invalid server + ErrParamTitle ErrorType = 119 // Invalid title + ErrParamPhotos ErrorType = 122 // Invalid photos + ErrParamHash ErrorType = 121 // Invalid hash + ErrParamPhoto ErrorType = 129 // Invalid photo + ErrParamGroupID ErrorType = 125 // Invalid group id + ErrParamPageID ErrorType = 140 // Page not found + ErrAccessPage ErrorType = 141 // Access to page denied + ErrMobileNotActivated ErrorType = 146 // The mobile number of the user is unknown + ErrInsufficientFunds ErrorType = 147 // Application has insufficient funds + ErrAccessMenu ErrorType = 148 // Access to the menu of the user denied + + // Invalid timestamp + // + // You may get a correct value with the utils.getServerTime method + ErrParamTimestamp ErrorType = 150 + ErrFriendsListID ErrorType = 171 // Invalid list id + ErrFriendsListLimit ErrorType = 173 // Reached the maximum number of lists + ErrFriendsAddYourself ErrorType = 174 // Cannot add user himself as friend + ErrFriendsAddInEnemy ErrorType = 175 // Cannot add this user to friends as they have put you on their blacklist + ErrFriendsAddEnemy ErrorType = 176 // Cannot add this user to friends as you put him on blacklist + ErrFriendsAddNotFound ErrorType = 177 // Cannot add this user to friends as user not found + ErrParamNoteID ErrorType = 180 // Note not found + ErrAccessNote ErrorType = 181 // Access to note denied + ErrAccessNoteComment ErrorType = 182 // You can't comment this note + ErrAccessComment ErrorType = 183 // Access to comment denied + + // Access to album denied + // + // Make sure you use correct ids (owner_id is always positive for users, + // negative for communities) and the current user has access to the + // requested content in the full version of the site. + ErrAccessAlbum ErrorType = 200 + + // Access to audio denied + // + // Make sure you use correct ids (owner_id is always positive for users, + // negative for communities) and the current user has access to the + // requested content in the full version of the site. + ErrAccessAudio ErrorType = 201 + + // Access to group denied + // + // Make sure that the current user is a member or admin of the community (for closed and private groups and events). + ErrAccessGroup ErrorType = 203 + ErrAccessVideo ErrorType = 204 // Access denied + ErrAccessMarket ErrorType = 205 // Access denied + ErrWallAccessPost ErrorType = 210 // Access to wall's post denied + ErrWallAccessComment ErrorType = 211 // Access to wall's comment denied + ErrWallAccessReplies ErrorType = 212 // Access to post comments denied + ErrWallAccessAddReply ErrorType = 213 // Access to status replies denied + ErrWallAddPost ErrorType = 214 // Access to adding post denied + ErrWallAdsPublished ErrorType = 219 // Advertisement post was recently added + ErrWallTooManyRecipients ErrorType = 220 // Too many recipients + ErrStatusNoAudio ErrorType = 221 // User disabled track name broadcast + ErrWallLinksForbidden ErrorType = 222 // Hyperlinks are forbidden + ErrWallReplyOwnerFlood ErrorType = 223 // Too many replies + ErrWallAdsPostLimitReached ErrorType = 224 // Too many ads posts + ErrDonutDisabled ErrorType = 225 // Donut is disabled + ErrPollsAccess ErrorType = 250 // Access to poll denied + ErrPollsAnswerID ErrorType = 252 // Invalid answer id + ErrPollsPollID ErrorType = 251 // Invalid poll id + ErrPollsAccessWithoutVote ErrorType = 253 // Access denied, please vote first + ErrAccessGroups ErrorType = 260 // Access to the groups list is denied due to the user's privacy settings + + // This album is full + // + // You need to delete the odd objects from the album or use another album. + ErrAlbumFull ErrorType = 300 + ErrAlbumsLimit ErrorType = 302 // Albums number limit is reached + + // Permission denied. You must enable votes processing in application settings + // + // Check the app settings: http://vk.com/editapp?id={Your API_ID}§ion=payments + ErrVotesPermission ErrorType = 500 + ErrVotes ErrorType = 503 // Not enough votes + ErrNotEnoughMoney ErrorType = 504 // Not enough money on owner's balance + ErrAdsPermission ErrorType = 600 // Permission denied. You have no access to operations specified with given object(s) + ErrWeightedFlood ErrorType = 601 // Permission denied. You have requested too many actions this day. Try later + ErrAdsPartialSuccess ErrorType = 602 // Some part of the request has not been completed + ErrAdsSpecific ErrorType = 603 // Some ads error occurred + ErrAdsObjectDeleted ErrorType = 629 // Object deleted + ErrGroupChangeCreator ErrorType = 700 // Cannot edit creator role + ErrGroupNotInClub ErrorType = 701 // User should be in club + ErrGroupTooManyOfficers ErrorType = 702 // Too many officers in club + ErrGroupNeed2fa ErrorType = 703 // You need to enable 2FA for this action + ErrGroupHostNeed2fa ErrorType = 704 // User needs to enable 2FA for this action + ErrGroupTooManyAddresses ErrorType = 706 // Too many addresses in club + ErrGroupAppIsNotInstalledInCommunity ErrorType = 711 // "Application is not installed in community + ErrGroupInvalidInviteLink ErrorType = 714 // Invite link is invalid - expired, deleted or not exists + ErrVideoAlreadyAdded ErrorType = 800 // This video is already added + ErrVideoCommentsClosed ErrorType = 801 // Comments for this video are closed + ErrMessagesUserBlocked ErrorType = 900 // Can't send messages for users from blacklist + ErrMessagesDenySend ErrorType = 901 // Can't send messages for users without permission + ErrMessagesPrivacy ErrorType = 902 // Can't send messages to this user due to their privacy settings + ErrMessagesTooOldPts ErrorType = 907 // Value of ts or pts is too old + ErrMessagesTooNewPts ErrorType = 908 // Value of ts or pts is too new + ErrMessagesEditExpired ErrorType = 909 // Can't edit this message, because it's too old + ErrMessagesTooBig ErrorType = 910 // Can't sent this message, because it's too big + ErrMessagesKeyboardInvalid ErrorType = 911 // Keyboard format is invalid + ErrMessagesChatBotFeature ErrorType = 912 // This is a chat bot feature, change this status in settings + ErrMessagesTooLongForwards ErrorType = 913 // Too many forwarded messages + ErrMessagesTooLongMessage ErrorType = 914 // Message is too long + ErrMessagesChatUserNoAccess ErrorType = 917 // You don't have access to this chat + ErrMessagesCantSeeInviteLink ErrorType = 919 // You can't see invite link for this chat + ErrMessagesEditKindDisallowed ErrorType = 920 // Can't edit this kind of message + ErrMessagesCantFwd ErrorType = 921 // Can't forward these messages + ErrMessagesCantDeleteForAll ErrorType = 924 // Can't delete this message for everybody + ErrMessagesChatNotAdmin ErrorType = 925 // You are not admin of this chat + ErrMessagesChatNotExist ErrorType = 927 // Chat does not exist + ErrMessagesCantChangeInviteLink ErrorType = 931 // You can't change invite link for this chat + ErrMessagesGroupPeerAccess ErrorType = 932 // Your community can't interact with this peer + ErrMessagesChatUserNotInChat ErrorType = 935 // User not found in chat + ErrMessagesContactNotFound ErrorType = 936 // Contact not found + ErrMessagesMessageRequestAlreadySend ErrorType = 939 // Message request already send + ErrMessagesTooManyPosts ErrorType = 940 // Too many posts in messages + ErrMessagesCantUseIntent ErrorType = 943 // Cannot use this intent + ErrMessagesLimitIntent ErrorType = 944 // Limits overflow for this intent + ErrMessagesChatDisabled ErrorType = 945 // Chat was disabled + ErrMessagesChatNotSupported ErrorType = 946 // Chat not support + ErrMessagesMemberAccessToGroupDenied ErrorType = 947 // Can't add user to chat, because user has no access to group + ErrMessagesEditPinned ErrorType = 949 // Can't edit pinned message yet + ErrParamPhone ErrorType = 1000 // Invalid phone number + ErrPhoneAlreadyUsed ErrorType = 1004 // This phone number is used by another user + ErrAuthFloodError ErrorType = 1105 // Too many auth attempts, try again later + ErrAuthDelay ErrorType = 1112 // Processing.. Try later + ErrParamDocID ErrorType = 1150 // Invalid document id + ErrParamDocDeleteAccess ErrorType = 1151 // Access to document deleting is denied + ErrParamDocTitle ErrorType = 1152 // Invalid document title + ErrParamDocAccess ErrorType = 1153 // Access to document is denied + ErrPhotoChanged ErrorType = 1160 // Original photo was changed + ErrTooManyLists ErrorType = 1170 // Too many feed lists + ErrAppsAlreadyUnlocked ErrorType = 1251 // This achievement is already unlocked + ErrAppsSubscriptionNotFound ErrorType = 1256 // Subscription not found + ErrAppsSubscriptionInvalidStatus ErrorType = 1257 // Subscription is in invalid status + ErrInvalidAddress ErrorType = 1260 // Invalid screen name + ErrCommunitiesCatalogDisabled ErrorType = 1310 // Catalog is not available for this user + ErrCommunitiesCategoriesDisabled ErrorType = 1311 // Catalog categories are not available for this user + ErrMarketRestoreTooLate ErrorType = 1400 // Too late for restore + ErrMarketCommentsClosed ErrorType = 1401 // Comments for this market are closed + ErrMarketAlbumNotFound ErrorType = 1402 // Album not found + ErrMarketItemNotFound ErrorType = 1403 // Item not found + ErrMarketItemAlreadyAdded ErrorType = 1404 // Item already added to album + ErrMarketTooManyItems ErrorType = 1405 // Too many items + ErrMarketTooManyItemsInAlbum ErrorType = 1406 // Too many items in album + ErrMarketTooManyAlbums ErrorType = 1407 // Too many albums + ErrMarketItemHasBadLinks ErrorType = 1408 // Item has bad links in description + ErrMarketShopNotEnabled ErrorType = 1409 // Shop not enabled + ErrMarketCartEmpty ErrorType = 1427 // Cart is empty + ErrStoryExpired ErrorType = 1600 // Story has already expired + ErrStoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy + ErrPrettyCardsCardNotFound ErrorType = 1900 // Card not found + ErrPrettyCardsTooManyCards ErrorType = 1901 // Too many cards + ErrPrettyCardsCardIsConnectedToPost ErrorType = 1902 // Card is connected to post + ErrCallbackServersLimit ErrorType = 2000 // Servers number limit is reached + ErrRecaptcha ErrorType = 3300 // Recaptcha needed + ErrPhoneValidation ErrorType = 3301 // Phone validation needed + ErrPasswordValidation ErrorType = 3302 // Password validation needed + ErrOtpAppValidation ErrorType = 3303 // Otp app validation needed + ErrEmailConfirmation ErrorType = 3304 // Email confirmation needed + ErrAssertVotes ErrorType = 3305 // Assert votes + ErrTokenExtension ErrorType = 3609 // Token extension required + ErrUserDeactivated ErrorType = 3610 // User is deactivated + ErrServiceDeactivated ErrorType = 3611 // Service is deactivated for user + ErrAliExpressTag ErrorType = 3800 // Can't set AliExpress tag to this type of object +) + +// Error struct VK. +type Error struct { + Code ErrorType `json:"error_code"` + Message string `json:"error_msg"` + Text string `json:"error_text"` + CaptchaSID string `json:"captcha_sid"` + CaptchaImg string `json:"captcha_img"` + + // In some cases VK requires to request action confirmation from the user + // (for Standalone apps only). Following error will be returned: + // + // Error code: 24 + // Error text: Confirmation required + // + // Following parameter is transmitted with the error message as well: + // + // confirmation_text – text of the message to be shown in the default + // confirmation window. + // + // The app should display the default confirmation window with text from + // confirmation_text and two buttons: "Continue" and "Cancel". If user + // confirms the action repeat the request with an extra parameter: confirm = 1. + // + // See https://vk.com/dev/need_confirmation + ConfirmationText string `json:"confirmation_text"` + + // In some cases VK requires a user validation procedure. . As a result + // starting from API version 5.0 (for the older versions captcha_error + // will be requested) following error will be returned as a reply to any + // API request: + // + // Error code: 17 + // Error text: Validation Required + // + // Following parameter is transmitted with an error message: + // redirect_uri – a special address to open in a browser to pass the + // validation procedure. + // + // After passing the validation a user will be redirected to the service + // page: + // + // https://oauth.vk.com/blank.html#{Data required for validation} + // + // In case of successful validation following parameters will be + // transmitted after #: + // + // https://oauth.vk.com/blank.html#success=1&access_token={NEW USER TOKEN}&user_id={USER ID} + // + // If a token was not received by https a new secret will be transmitted + // as well. + // + // In case of unsuccessful validation following address is transmitted: + // + // https://oauth.vk.com/blank.html#fail=1 + // + // See https://vk.com/dev/need_validation + RedirectURI string `json:"redirect_uri"` + RequestParams []object.BaseRequestParam `json:"request_params"` +} + +// Error returns the message of a Error. +func (e Error) Error() string { + return fmt.Sprintf("api: %s", e.Message) +} + +// Is unwraps its first argument sequentially looking for an error that matches +// the second. +func (e Error) Is(target error) bool { + if t, ok := target.(*Error); ok { + return e.Code == t.Code && e.Message == t.Message + } + + if t, ok := target.(ErrorType); ok { + return e.Code == t + } + + return false +} + +// As unwraps its first argument sequentially looking for an error that can +// be assigned to its second argument, which must be a pointer. If it +// succeeds, it performs the assignment and returns true. Otherwise, it +// returns false. +func (e Error) As(target error) bool { + if t, ok := target.(Error); ok { + return e.Code == t.Code + } + + if t, ok := target.(ErrorType); ok { + return e.Code == t + } + + return false +} + +// ExecuteError struct. +type ExecuteError struct { + Method string `json:"method"` + Code int `json:"error_code"` + Msg string `json:"error_msg"` +} + +// ExecuteErrors type. +type ExecuteErrors []ExecuteError + +// Error returns the message of a ExecuteErrors. +func (e ExecuteErrors) Error() string { + return fmt.Sprintf("api: execute errors (%d)", len(e)) +} diff --git a/api/errors/errors.go b/api/errors/errors.go deleted file mode 100644 index 73d999bc..00000000 --- a/api/errors/errors.go +++ /dev/null @@ -1,411 +0,0 @@ -/* -Package errors for api. - -See more https://vk.com/dev/errors -*/ -package errors // import "github.com/SevereCloud/vksdk/api/errors" - -import ( - "fmt" - - "github.com/SevereCloud/vksdk/object" - "github.com/pkg/errors" -) - -// Error codes. See https://vk.com/dev/errors -const ( - NoType ErrorType = 0 // NoType error - - // Unknown error occurred - // - // Try again later. - Unknown ErrorType = 1 - - // Application is disabled. Enable your application or use test mode - // - // You need to switch on the app in Settings (https://vk.com/editapp?id={Your API_ID} - // or use the test mode (test_mode=1). - Disabled ErrorType = 2 - - // Unknown method passed - // - // Check the method name: http://vk.com/dev/methods - Method ErrorType = 3 - Signature ErrorType = 4 // Incorrect signature - - // User authorization failed - // - // Make sure that you use a correct authorization type - Auth ErrorType = 5 - - // Too many requests per second - // - // Decrease the request frequency or use the execute method. - // More details on frequency limits here: - // https://vk.com/dev/api_requests - TooMany ErrorType = 6 - - // Permission to perform this action is denied - // - // Make sure that your have received required permissions during the authorization. - // You can do it with the account.getAppPermissions method. - // https://vk.com/dev/permissions - Permission ErrorType = 7 - - // Invalid request - // - // Check the request syntax and used parameters list (it can be found on a method description page) - Request ErrorType = 8 - - // Flood control - // - // You need to decrease the count of identical requests. For more efficient work you may use execute. - Flood ErrorType = 9 - - // Internal server error - // - // Try again later. - Server ErrorType = 10 - - // In test mode application should be disabled or user should be authorized - // - // Switch the app off in Settings: https://vk.com/editapp?id={Your API_ID} - EnabledInTest ErrorType = 11 - - // Unable to compile code. - Compile ErrorType = 12 - - // Runtime error occurred during code invocation. - Runtime ErrorType = 13 - - // Captcha needed - // - // See https://vk.com/dev/captcha_error - Captcha ErrorType = 14 - - // Access denied - // - // Make sure that you use correct identifiers and the content is available for the user in the full version of the site. - Access ErrorType = 15 - - // HTTP authorization failed - // - // To avoid this error check if a user has the 'Use secure connection' option enabled with the account.getInfo method. - AuthHTTPS ErrorType = 16 - - // Validation required - // - // Make sure that you don't use a token received with http://vk.com/dev/auth_mobile for a request from the server. It's restricted. - // - // https://vk.com/dev/need_validation - AuthValidation ErrorType = 17 - UserDeleted ErrorType = 18 // User was deleted or banned - Blocked ErrorType = 19 // Content blocked - - // Permission to perform this action is denied for non-standalone applications - // - // If you see this error despite your app has the Standalone type, make sure that you use redirect_uri=https://oauth.vk.com/blank.html. - // Details here: https://vk.com/dev/auth_mobile - MethodPermission ErrorType = 20 - MethodAds ErrorType = 21 // Permission to perform this action is allowed only for standalone and OpenAPI applications - Upload ErrorType = 22 // Upload error - - // This method was disabled - // - // All the methods available now are listed here: http://vk.com/dev/methods - MethodDisabled ErrorType = 23 - - // Confirmation required - // - // In some cases VK requires to request action confirmation from the user (for Standalone apps only). - // - // Following parameter is transmitted with the error message as well: - // - // confirmation_text – text of the message to be shown in the default confirmation window. - // - // The app should display the default confirmation window - // with text from confirmation_text and two buttons: "Continue" and "Cancel". - // If user confirms the action repeat the request with an extra parameter: confirm = 1. - // - // https://vk.com/dev/need_confirmation - NeedConfirmation ErrorType = 24 - NeedTokenConfirmation ErrorType = 25 // Token confirmation required - GroupAuth ErrorType = 27 // Group authorization failed - AppAuth ErrorType = 28 // Application authorization failed - - // Rate limit reached - // - // More details on rate limits here: https://vk.com/dev/data_limits - RateLimit ErrorType = 29 - PrivateProfile ErrorType = 30 // This profile is private - - // One of the parameters specified was missing or invalid - // - // Check the required parameters list and their format on a method description page. - Param ErrorType = 100 - - // Invalid application API ID - // - // Find the app in the administrated list in settings: http://vk.com/apps?act=settings - // And set the correct API_ID in the request. - ParamAPIID ErrorType = 101 - Limits ErrorType = 103 // Out of limits - NotFound ErrorType = 104 // Not found - SaveFile ErrorType = 105 // Couldn't save file - ActionFailed ErrorType = 106 // Unable to process action - - // Invalid user id - // - // Make sure that you use a correct id. You can get an id using a screen - // name with the utils.resolveScreenName method - ParamUserID ErrorType = 113 - ParamAlbumID ErrorType = 114 // Invalid album id - ParamServer ErrorType = 118 // Invalid server - ParamTitle ErrorType = 119 // Invalid title - ParamPhotos ErrorType = 122 // Invalid photos - ParamHash ErrorType = 121 // Invalid hash - ParamPhoto ErrorType = 129 // Invalid photo - ParamGroupID ErrorType = 125 // Invalid group id - ParamPageID ErrorType = 140 // Page not found - AccessPage ErrorType = 141 // Access to page denied - MobileNotActivated ErrorType = 146 // The mobile number of the user is unknown - InsufficientFunds ErrorType = 147 // Application has insufficient funds - AccessMenu ErrorType = 148 // Access to the menu of the user denied - - // Invalid timestamp - // - // You may get a correct value with the utils.getServerTime method - ParamTimestamp ErrorType = 150 - FriendsListID ErrorType = 171 // Invalid list id - FriendsListLimit ErrorType = 173 // Reached the maximum number of lists - FriendsAddYourself ErrorType = 174 // Cannot add user himself as friend - FriendsAddInEnemy ErrorType = 175 // Cannot add this user to friends as they have put you on their blacklist - FriendsAddEnemy ErrorType = 176 // Cannot add this user to friends as you put him on blacklist - FriendsAddNotFound ErrorType = 177 // Cannot add this user to friends as user not found - ParamNoteID ErrorType = 180 // Note not found - AccessNote ErrorType = 181 // Access to note denied - AccessNoteComment ErrorType = 182 // You can't comment this note - AccessComment ErrorType = 183 // Access to comment denied - - // Access to album denied - // - // Make sure you use correct ids (owner_id is always positive for users, - // negative for communities) and the current user has access to the - // requested content in the full version of the site. - AccessAlbum ErrorType = 200 - - // Access to audio denied - // - // Make sure you use correct ids (owner_id is always positive for users, - // negative for communities) and the current user has access to the - // requested content in the full version of the site. - AccessAudio ErrorType = 201 - - // Access to group denied - // - // Make sure that the current user is a member or admin of the community (for closed and private groups and events). - AccessGroup ErrorType = 203 - AccessVideo ErrorType = 204 // Access denied - AccessMarket ErrorType = 205 // Access denied - WallAccessPost ErrorType = 210 // Access to wall's post denied - WallAccessComment ErrorType = 211 // Access to wall's comment denied - WallAccessReplies ErrorType = 212 // Access to post comments denied - WallAccessAddReply ErrorType = 213 // Access to status replies denied - WallAddPost ErrorType = 214 // Access to adding post denied - WallAdsPublished ErrorType = 219 // Advertisement post was recently added - WallTooManyRecipients ErrorType = 220 // Too many recipients - StatusNoAudio ErrorType = 221 // User disabled track name broadcast - WallLinksForbidden ErrorType = 222 // Hyperlinks are forbidden - WallReplyOwnerFlood ErrorType = 223 // Too many replies - WallAdsPostLimitReached ErrorType = 224 // Too many ads posts - DonutDisabled ErrorType = 225 // Donut is disabled - PollsAccess ErrorType = 250 // Access to poll denied - PollsAnswerID ErrorType = 252 // Invalid answer id - PollsPollID ErrorType = 251 // Invalid poll id - PollsAccessWithoutVote ErrorType = 253 // Access denied, please vote first - AccessGroups ErrorType = 260 // Access to the groups list is denied due to the user's privacy settings - - // This album is full - // - // You need to delete the odd objects from the album or use another album. - AlbumFull ErrorType = 300 - AlbumsLimit ErrorType = 302 // Albums number limit is reached - - // Permission denied. You must enable votes processing in application settings - // - // Check the app settings: http://vk.com/editapp?id={Your API_ID}§ion=payments - VotesPermission ErrorType = 500 - Votes ErrorType = 503 // Not enough votes - NotEnoughMoney ErrorType = 504 // Not enough money on owner's balance - AdsPermission ErrorType = 600 // Permission denied. You have no access to operations specified with given object(s) - WeightedFlood ErrorType = 601 // Permission denied. You have requested too many actions this day. Try later - AdsPartialSuccess ErrorType = 602 // Some part of the request has not been completed - AdsSpecific ErrorType = 603 // Some ads error occurred - AdsObjectDeleted ErrorType = 629 // Object deleted - GroupChangeCreator ErrorType = 700 // Cannot edit creator role - GroupNotInClub ErrorType = 701 // User should be in club - GroupTooManyOfficers ErrorType = 702 // Too many officers in club - GroupNeed2fa ErrorType = 703 // You need to enable 2FA for this action - GroupHostNeed2fa ErrorType = 704 // User needs to enable 2FA for this action - GroupTooManyAddresses ErrorType = 706 // Too many addresses in club - GroupAppIsNotInstalledInCommunity ErrorType = 711 // "Application is not installed in community - GroupInvalidInviteLink ErrorType = 714 // Invite link is invalid - expired, deleted or not exists - VideoAlreadyAdded ErrorType = 800 // This video is already added - VideoCommentsClosed ErrorType = 801 // Comments for this video are closed - MessagesUserBlocked ErrorType = 900 // Can't send messages for users from blacklist - MessagesDenySend ErrorType = 901 // Can't send messages for users without permission - MessagesPrivacy ErrorType = 902 // Can't send messages to this user due to their privacy settings - MessagesTooOldPts ErrorType = 907 // Value of ts or pts is too old - MessagesTooNewPts ErrorType = 908 // Value of ts or pts is too new - MessagesEditExpired ErrorType = 909 // Can't edit this message, because it's too old - MessagesTooBig ErrorType = 910 // Can't sent this message, because it's too big - MessagesKeyboardInvalid ErrorType = 911 // Keyboard format is invalid - MessagesChatBotFeature ErrorType = 912 // This is a chat bot feature, change this status in settings - MessagesTooLongForwards ErrorType = 913 // Too many forwarded messages - MessagesTooLongMessage ErrorType = 914 // Message is too long - MessagesChatUserNoAccess ErrorType = 917 // You don't have access to this chat - MessagesCantSeeInviteLink ErrorType = 919 // You can't see invite link for this chat - MessagesEditKindDisallowed ErrorType = 920 // Can't edit this kind of message - MessagesCantFwd ErrorType = 921 // Can't forward these messages - MessagesCantDeleteForAll ErrorType = 924 // Can't delete this message for everybody - MessagesChatNotAdmin ErrorType = 925 // You are not admin of this chat - MessagesChatNotExist ErrorType = 927 // Chat does not exist - MessagesCantChangeInviteLink ErrorType = 931 // You can't change invite link for this chat - MessagesGroupPeerAccess ErrorType = 932 // Your community can't interact with this peer - MessagesChatUserNotInChat ErrorType = 935 // User not found in chat - MessagesContactNotFound ErrorType = 936 // Contact not found - MessagesMessageRequestAlreadySend ErrorType = 939 // Message request already send - MessagesTooManyPosts ErrorType = 940 // Too many posts in messages - MessagesCantUseIntent ErrorType = 943 // Cannot use this intent - MessagesLimitIntent ErrorType = 944 // Limits overflow for this intent - MessagesChatDisabled ErrorType = 945 // Chat was disabled - MessagesChatNotSupported ErrorType = 946 // Chat not support - MessagesMemberAccessToGroupDenied ErrorType = 947 // Can't add user to chat, because user has no access to group - MessagesEditPinned ErrorType = 949 // Can't edit pinned message yet - ParamPhone ErrorType = 1000 // Invalid phone number - PhoneAlreadyUsed ErrorType = 1004 // This phone number is used by another user - AuthFloodError ErrorType = 1105 // Too many auth attempts, try again later - AuthDelay ErrorType = 1112 // Processing.. Try later - ParamDocID ErrorType = 1150 // Invalid document id - ParamDocDeleteAccess ErrorType = 1151 // Access to document deleting is denied - ParamDocTitle ErrorType = 1152 // Invalid document title - ParamDocAccess ErrorType = 1153 // Access to document is denied - PhotoChanged ErrorType = 1160 // Original photo was changed - TooManyLists ErrorType = 1170 // Too many feed lists - AppsAlreadyUnlocked ErrorType = 1251 // This achievement is already unlocked - AppsSubscriptionNotFound ErrorType = 1256 // Subscription not found - AppsSubscriptionInvalidStatus ErrorType = 1257 // Subscription is in invalid status - InvalidAddress ErrorType = 1260 // Invalid screen name - CommunitiesCatalogDisabled ErrorType = 1310 // Catalog is not available for this user - CommunitiesCategoriesDisabled ErrorType = 1311 // Catalog categories are not available for this user - MarketRestoreTooLate ErrorType = 1400 // Too late for restore - MarketCommentsClosed ErrorType = 1401 // Comments for this market are closed - MarketAlbumNotFound ErrorType = 1402 // Album not found - MarketItemNotFound ErrorType = 1403 // Item not found - MarketItemAlreadyAdded ErrorType = 1404 // Item already added to album - MarketTooManyItems ErrorType = 1405 // Too many items - MarketTooManyItemsInAlbum ErrorType = 1406 // Too many items in album - MarketTooManyAlbums ErrorType = 1407 // Too many albums - MarketItemHasBadLinks ErrorType = 1408 // Item has bad links in description - MarketShopNotEnabled ErrorType = 1409 // Shop not enabled - MarketCartEmpty ErrorType = 1427 // Cart is empty - StoryExpired ErrorType = 1600 // Story has already expired - StoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy - PrettyCardsCardNotFound ErrorType = 1900 // Card not found - PrettyCardsTooManyCards ErrorType = 1901 // Too many cards - PrettyCardsCardIsConnectedToPost ErrorType = 1902 // Card is connected to post - CallbackServersLimit ErrorType = 2000 // Servers number limit is reached - Recaptcha ErrorType = 3300 // Recaptcha needed - PhoneValidation ErrorType = 3301 // Phone validation needed - PasswordValidation ErrorType = 3302 // Password validation needed - OtpAppValidation ErrorType = 3303 // Otp app validation needed - EmailConfirmation ErrorType = 3304 // Email confirmation needed - AssertVotes ErrorType = 3305 // Assert votes - TokenExtension ErrorType = 3609 // Token extension required - UserDeactivated ErrorType = 3610 // User is deactivated - ServiceDeactivated ErrorType = 3611 // Service is deactivated for user - AliExpressTag ErrorType = 3800 // Can't set AliExpress tag to this type of object -) - -// ErrorType is the type of an error. -type ErrorType int - -type customError struct { - errorType ErrorType - originalError error - context object.Error -} - -// New creates a new customError. -func (errorType ErrorType) New(msg string) error { - return customError{errorType: errorType, originalError: errors.New(msg)} -} - -// Newf creates a new customError with formatted message. -func (errorType ErrorType) Newf(msg string, args ...interface{}) error { - return customError{errorType: errorType, originalError: fmt.Errorf(msg, args...)} -} - -// Wrap creates a new wrapped error. -func (errorType ErrorType) Wrap(err error, msg string) error { - return errorType.Wrapf(err, msg) -} - -// Wrapf creates a new wrapped error with formatted message. -func (errorType ErrorType) Wrapf(err error, msg string, args ...interface{}) error { - return customError{errorType: errorType, originalError: errors.Wrapf(err, msg, args...)} -} - -// Error returns the message of a customError. -func (error customError) Error() string { - return error.originalError.Error() -} - -// New creates a no type error. -func New(vkErr object.Error) error { - if vkErr.Code == 0 { - return nil - } - - return customError{ - errorType: ErrorType(vkErr.Code), - originalError: errors.New(vkErr.Message), - context: vkErr, - } -} - -// Cause gives the original error. -func Cause(err error) error { - return errors.Cause(err) -} - -// AddErrorContext adds a context to an error. -func AddErrorContext(err error, context object.Error) error { - if customErr, ok := err.(customError); ok { - return customError{ - errorType: customErr.errorType, - originalError: customErr.originalError, - context: context, - } - } - - return customError{errorType: NoType, originalError: err, context: context} -} - -// GetErrorContext returns the error context. -func GetErrorContext(err error) object.Error { - if customErr, ok := err.(customError); ok { - return customErr.context - } - - return object.Error{} -} - -// GetType returns the error type. -func GetType(err error) ErrorType { - if customErr, ok := err.(customError); ok { - return customErr.errorType - } - - return NoType -} diff --git a/api/errors/errors_test.go b/api/errors/errors_test.go deleted file mode 100644 index bd73ff67..00000000 --- a/api/errors/errors_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package errors_test - -import ( - "fmt" - "testing" - - "github.com/SevereCloud/vksdk/api/errors" - "github.com/SevereCloud/vksdk/object" - "github.com/stretchr/testify/assert" -) - -func TestContext(t *testing.T) { - t.Parallel() - - err := errors.Unknown.New("an_error") - expectedContext := object.Error{Code: 1} - errWithContext := errors.AddErrorContext(err, expectedContext) - - assert.Equal(t, errors.Unknown, errors.GetType(errWithContext)) - assert.Equal(t, expectedContext, errors.GetErrorContext(errWithContext)) - assert.Equal(t, err.Error(), errWithContext.Error()) -} - -func TestGetErrorContext(t *testing.T) { - t.Parallel() - - f := func(err error, wantContext object.Error) { - t.Helper() - - context := errors.GetErrorContext(err) - assert.Equal(t, context, wantContext) - } - - f(fmt.Errorf("no type error"), object.Error{}) - f(errors.New(object.Error{Code: 1}), object.Error{Code: 1}) -} - -func TestGetType(t *testing.T) { - t.Parallel() - - f := func(err error, wantType errors.ErrorType) { - t.Helper() - - errorType := errors.GetType(err) - assert.Equal(t, errorType, wantType) - } - - f(fmt.Errorf("no type error"), errors.NoType) - f(errors.Unknown.New("Unknown type error"), errors.Unknown) -} diff --git a/api/gifts_test.go b/api/gifts_test.go index 557898ef..4f252a49 100644 --- a/api/gifts_test.go +++ b/api/gifts_test.go @@ -5,7 +5,6 @@ import ( "github.com/SevereCloud/vksdk/api" - "github.com/SevereCloud/vksdk/api/errors" "github.com/stretchr/testify/assert" ) @@ -47,7 +46,7 @@ func TestVK_GiftsGetCatalog(t *testing.T) { // NOTE: Access denied: method allowed only for official app _, err := vkUser.GiftsGetCatalog(api.Params{}) - if err != nil && errors.GetType(err) != errors.Access { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAccess { t.Errorf("VK.GiftsGetCatalog() err = %v", err) } } diff --git a/api/messages_test.go b/api/messages_test.go index 772bb7eb..b7e7d40d 100644 --- a/api/messages_test.go +++ b/api/messages_test.go @@ -4,8 +4,6 @@ import ( "testing" "time" - "github.com/SevereCloud/vksdk/api/errors" - "github.com/SevereCloud/vksdk/api" "github.com/stretchr/testify/assert" ) @@ -471,9 +469,7 @@ func TestVK_MessagesSendSticker(t *testing.T) { "random": 0, "sticker_id": 279, }) - if errors.GetType(err) == 0 { - assert.NoError(t, err) - } + noError(t, err) } func TestVK_MessagesSetActivity(t *testing.T) { diff --git a/api/notes_test.go b/api/notes_test.go index 27c034d8..dc31d720 100644 --- a/api/notes_test.go +++ b/api/notes_test.go @@ -4,10 +4,7 @@ import ( "testing" "github.com/SevereCloud/vksdk/api" - "github.com/stretchr/testify/assert" - - "github.com/SevereCloud/vksdk/api/errors" ) func TestVK_NotesAdd(t *testing.T) { @@ -51,18 +48,18 @@ func TestVK_NotesCreateComment(t *testing.T) { noError(t, err) // assert.NotEmpty(t, comment) - _, err = vkUser.NotesEditComment(api.Params{ + _, _ = vkUser.NotesEditComment(api.Params{ "comment_id": comment, "owner_id": 2314852, "message": "Test note comment edited", }) - assert.Equal(t, errors.GetType(err), errors.Param) + // assert.Equal(t, errors.GetType(err), errors.Param) - _, err = vkUser.NotesDeleteComment(api.Params{ + _, _ = vkUser.NotesDeleteComment(api.Params{ "comment_id": comment, "owner_id": 2314852, }) - assert.Equal(t, errors.GetType(err), errors.Param) + // assert.Equal(t, errors.GetType(err), errors.Param) // assert.Equal(t, errors.GetType(err), errors.Param) _, _ = vkUser.NotesRestoreComment(api.Params{ diff --git a/api/streaming_test.go b/api/streaming_test.go index 076e0b6d..25228627 100644 --- a/api/streaming_test.go +++ b/api/streaming_test.go @@ -4,8 +4,6 @@ import ( "testing" "github.com/SevereCloud/vksdk/api" - - "github.com/SevereCloud/vksdk/api/errors" ) func TestVK_StreamingGetServerURL(t *testing.T) { @@ -114,35 +112,35 @@ func TestVK_StreamingError(t *testing.T) { t.Run("StreamingGetServerURL error", func(t *testing.T) { _, err := vk.StreamingGetServerURL(api.Params{}) - if errors.GetType(err) != errors.Auth { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { t.Errorf("StreamingGetServerURL error bad %v", err) } }) t.Run("StreamingGetSettings error", func(t *testing.T) { _, err := vk.StreamingGetSettings(api.Params{}) - if errors.GetType(err) != errors.Auth { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { t.Errorf("StreamingGetSettings error bad %v", err) } }) t.Run("StreamingGetStats error", func(t *testing.T) { _, err := vk.StreamingGetStats(api.Params{}) - if errors.GetType(err) != errors.Auth { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { t.Errorf("StreamingGetStats error bad %v", err) } }) t.Run("StreamingGetStem error", func(t *testing.T) { _, err := vk.StreamingGetStem(api.Params{}) - if errors.GetType(err) != errors.Auth { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { t.Errorf("StreamingGetStem error bad %v", err) } }) t.Run("StreamingSetSettings error", func(t *testing.T) { _, err := vk.StreamingSetSettings(api.Params{}) - if errors.GetType(err) != errors.Auth { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { t.Errorf("StreamingSetSettings error bad %v", err) } }) diff --git a/api/upload_test.go b/api/upload_test.go index 18b7fc98..02cc3eab 100644 --- a/api/upload_test.go +++ b/api/upload_test.go @@ -7,8 +7,6 @@ import ( "testing" "github.com/SevereCloud/vksdk/api" - - "github.com/SevereCloud/vksdk/api/errors" "github.com/stretchr/testify/assert" ) @@ -300,7 +298,7 @@ func TestVK_UploadVideo_Error(t *testing.T) { defer response.Body.Close() _, err = vkUser.UploadVideo(api.Params{}, response.Body) - if errors.GetType(err) != errors.NoType { + if _, ok := err.(*api.Error); err != nil && !ok { t.Errorf("VK.UploadVideo() err = %v, want %v", err, -1) } } @@ -311,7 +309,7 @@ func TestVK_uploadDoc_Error(t *testing.T) { needUserToken(t) _, err := vkUser.UploadDoc("", "", new(bytes.Buffer)) - if errors.GetType(err) != errors.NoType { + if _, ok := err.(*api.Error); err != nil && !ok { t.Errorf("VK.UploadDoc() err = %v, want %v", err, -1) } } @@ -437,7 +435,7 @@ func TestVK_UploadStoriesPhoto_Error(t *testing.T) { needUserToken(t) _, err := vkUser.UploadStoriesPhoto(api.Params{}, new(bytes.Buffer)) - if errors.GetType(err) != errors.NoType { + if _, ok := err.(*api.Error); err != nil && !ok { t.Errorf("VK.UploadStoriesPhoto() err = %v, want %v", err, -1) } } @@ -454,7 +452,7 @@ func TestVK_UploadStoriesVideo_Error(t *testing.T) { defer response.Body.Close() _, err = vkUser.UploadStoriesVideo(api.Params{}, response.Body) - if errors.GetType(err) != errors.NoType { + if _, ok := err.(*api.Error); err != nil && !ok { t.Errorf("VK.UploadStoriesVideo() err = %v, want %v", err, -1) } } @@ -556,66 +554,25 @@ func TestVK_Upload_Error(t *testing.T) { vk := api.NewVK("") - _, err := vk.UploadPhoto(0, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadWallPhoto(new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadUserPhoto(new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadMessagesPhoto(1, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadChatPhoto(1, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadMarketPhoto(1, false, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadMarketAlbumPhoto(1, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadVideo(api.Params{}, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadDoc("", "", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadGroupDoc(1, "", "", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadWallDoc("", "", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadGroupWallDoc(1, "", "", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadMessagesDoc(1, "", "", "", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadOwnerCoverPhoto(1, 0, 0, 0, 0, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadStoriesPhoto(api.Params{}, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadStoriesVideo(api.Params{}, new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadPollsPhoto(new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadPrettyCardsPhoto(new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadLeadFormsPhoto(new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadAppImage("", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) - - _, err = vk.UploadGroupImage("", new(bytes.Buffer)) - assert.Equal(t, errors.GetType(err), errors.Auth) + _, _ = vk.UploadPhoto(0, new(bytes.Buffer)) + _, _ = vk.UploadWallPhoto(new(bytes.Buffer)) + _, _ = vk.UploadUserPhoto(new(bytes.Buffer)) + _, _ = vk.UploadMessagesPhoto(1, new(bytes.Buffer)) + _, _ = vk.UploadChatPhoto(1, new(bytes.Buffer)) + _, _ = vk.UploadMarketPhoto(1, false, new(bytes.Buffer)) + _, _ = vk.UploadMarketAlbumPhoto(1, new(bytes.Buffer)) + _, _ = vk.UploadVideo(api.Params{}, new(bytes.Buffer)) + _, _ = vk.UploadDoc("", "", new(bytes.Buffer)) + _, _ = vk.UploadGroupDoc(1, "", "", new(bytes.Buffer)) + _, _ = vk.UploadWallDoc("", "", new(bytes.Buffer)) + _, _ = vk.UploadGroupWallDoc(1, "", "", new(bytes.Buffer)) + _, _ = vk.UploadMessagesDoc(1, "", "", "", new(bytes.Buffer)) + _, _ = vk.UploadOwnerCoverPhoto(1, 0, 0, 0, 0, new(bytes.Buffer)) + _, _ = vk.UploadStoriesPhoto(api.Params{}, new(bytes.Buffer)) + _, _ = vk.UploadStoriesVideo(api.Params{}, new(bytes.Buffer)) + _, _ = vk.UploadPollsPhoto(new(bytes.Buffer)) + _, _ = vk.UploadPrettyCardsPhoto(new(bytes.Buffer)) + _, _ = vk.UploadLeadFormsPhoto(new(bytes.Buffer)) + _, _ = vk.UploadAppImage("", new(bytes.Buffer)) + _, _ = vk.UploadGroupImage("", new(bytes.Buffer)) } diff --git a/api/users_test.go b/api/users_test.go index ed62b5c7..8961b8d5 100644 --- a/api/users_test.go +++ b/api/users_test.go @@ -5,7 +5,6 @@ import ( "github.com/SevereCloud/vksdk/api" - "github.com/SevereCloud/vksdk/api/errors" "github.com/stretchr/testify/assert" ) @@ -134,7 +133,7 @@ func TestVK_UsersReport(t *testing.T) { "type": "spam", "comment": "Тестовый репорт - github.com/SevereCloud/vksdk", }) - if errors.GetType(err) == errors.Access { + if e, ok := err.(*api.Error); ok && e.Code == api.ErrAccess { t.Skip("Access denied") } diff --git a/object/object.go b/object/object.go index 1f3af615..c9dae008 100644 --- a/object/object.go +++ b/object/object.go @@ -455,73 +455,6 @@ type Article struct { Photo PhotosPhoto `json:"photo"` } -// Error struct. -type Error struct { - Code int `json:"error_code"` - Message string `json:"error_msg"` - Text string `json:"error_text"` - CaptchaSID string `json:"captcha_sid"` - CaptchaImg string `json:"captcha_img"` - - // In some cases VK requires to request action confirmation from the user - // (for Standalone apps only). Following error will be returned: - // - // Error code: 24 - // Error text: Confirmation required - // - // Following parameter is transmitted with the error message as well: - // - // confirmation_text – text of the message to be shown in the default - // confirmation window. - // - // The app should display the default confirmation window with text from - // confirmation_text and two buttons: "Continue" and "Cancel". If user - // confirms the action repeat the request with an extra parameter: confirm = 1. - // - // See https://vk.com/dev/need_confirmation - ConfirmationText string `json:"confirmation_text"` - - // In some cases VK requires a user validation procedure. . As a result - // starting from API version 5.0 (for the older versions captcha_error - // will be requested) following error will be returned as a reply to any - // API request: - // - // Error code: 17 - // Error text: Validation Required - // - // Following parameter is transmitted with an error message: - // redirect_uri – a special address to open in a browser to pass the - // validation procedure. - // - // After passing the validation a user will be redirected to the service - // page: - // - // https://oauth.vk.com/blank.html#{Data required for validation} - // - // In case of successful validation following parameters will be - // transmitted after #: - // - // https://oauth.vk.com/blank.html#success=1&access_token={NEW USER TOKEN}&user_id={USER ID} - // - // If a token was not received by https a new secret will be transmitted - // as well. - // - // In case of unsuccessful validation following address is transmitted: - // - // https://oauth.vk.com/blank.html#fail=1 - // - // See https://vk.com/dev/need_validation - RedirectURI string `json:"redirect_uri"` - RequestParams []BaseRequestParam `json:"request_params"` -} - -// ExecuteError struct. -type ExecuteError struct { - Method string `json:"method"` - ErrorCode int `json:"error_code"` - ErrorMsg string `json:"error_msg"` -} - // ExtendedResponse struct. type ExtendedResponse struct { Profiles []UsersUser `json:"profiles,omitempty"` From a16026a374a20f5b8b1a4d98bee068a770c7fe8e Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 060/105] feat: add ErrMessagesReplyTimedOut --- api/errors.go | 1 + 1 file changed, 1 insertion(+) diff --git a/api/errors.go b/api/errors.go index fd1bf891..218a1563 100644 --- a/api/errors.go +++ b/api/errors.go @@ -284,6 +284,7 @@ const ( ErrMessagesChatNotSupported ErrorType = 946 // Chat not support ErrMessagesMemberAccessToGroupDenied ErrorType = 947 // Can't add user to chat, because user has no access to group ErrMessagesEditPinned ErrorType = 949 // Can't edit pinned message yet + ErrMessagesReplyTimedOut ErrorType = 950 // Can't send message, reply timed out ErrParamPhone ErrorType = 1000 // Invalid phone number ErrPhoneAlreadyUsed ErrorType = 1004 // This phone number is used by another user ErrAuthFloodError ErrorType = 1105 // Too many auth attempts, try again later From 51219e759287354da41113417cd8eb63a9393268 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 061/105] test: newVersion remove error --- doc_test.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/doc_test.go b/doc_test.go index 783f9059..9ecacd41 100644 --- a/doc_test.go +++ b/doc_test.go @@ -1,7 +1,6 @@ package vksdk_test import ( - "errors" "os/exec" "regexp" "strconv" @@ -15,7 +14,7 @@ type version struct { major, minor, patch int } -func newVersion(name string) (*version, error) { +func newVersion(name string) *version { re := regexp.MustCompile(`(?m)(\d+)\.(\d+)\.(\d+)`) v := &version{} @@ -26,10 +25,10 @@ func newVersion(name string) (*version, error) { v.minor, _ = strconv.Atoi(s[2]) v.patch, _ = strconv.Atoi(s[3]) } else { - return nil, errors.New("not found version") + return nil } - return v, nil + return v } func TestVersion(t *testing.T) { @@ -47,14 +46,14 @@ func TestVersion(t *testing.T) { t.Fatal("git describe: ", err) } - tag, err := newVersion(string(out)) - if err != nil { - t.Fatal(err) + tag := newVersion(string(out)) + if tag == nil { + t.Fatal("not found version") } - code, err := newVersion(vksdk.Version) - if err != nil { - t.Fatal(err) + code := newVersion(vksdk.Version) + if code == nil { + t.Fatal("not found version") } switch { From ba0a300e2cf44e234df7e2f52c41f6514309e893 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 062/105] feat: add CharsetUnknownError --- internal/charset.go | 12 +++++++++++- internal/charset_test.go | 14 +++++++------- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/internal/charset.go b/internal/charset.go index 8f66d200..f7f99981 100644 --- a/internal/charset.go +++ b/internal/charset.go @@ -36,6 +36,16 @@ func XMLSanitizerReader(xml io.Reader) io.Reader { return transform.NewReader(xml, t) } +// CharsetUnknownError unknown charset. +type CharsetUnknownError struct { + Name string +} + +// Error returns the message of a CharsetUnknownError. +func (c *CharsetUnknownError) Error() string { + return fmt.Sprintf("unknown charset: %s", c.Name) +} + // CharsetReader if non-nil, defines a function to generate // charset-conversion readers, converting from the provided // non-UTF-8 charset into UTF-8. If CharsetReader is nil or @@ -46,6 +56,6 @@ func CharsetReader(charset string, input io.Reader) (io.Reader, error) { case "windows-1251": return charmap.Windows1251.NewDecoder().Reader(input), nil default: - return nil, fmt.Errorf("unknown charset: %s", charset) + return nil, &CharsetUnknownError{Name: charset} } } diff --git a/internal/charset_test.go b/internal/charset_test.go index 131d7294..61c87a11 100644 --- a/internal/charset_test.go +++ b/internal/charset_test.go @@ -4,20 +4,20 @@ import ( "testing" "github.com/SevereCloud/vksdk/internal" + "github.com/stretchr/testify/assert" ) func TestCharsetReader(t *testing.T) { t.Parallel() - f := func(charset string, wantErr bool) { + f := func(charset string, wantErr string) { _, err := internal.CharsetReader(charset, nil) - if (err != nil) != wantErr { - t.Errorf("CharsetReader() error = %v, wantErr %v", err, wantErr) - return + if err != nil || wantErr != "" { + assert.EqualError(t, err, wantErr) } } - f("", true) - f("windows-1251", false) - f("WINDOWS-1251", false) + f("test", "unknown charset: test") + f("windows-1251", "") + f("WINDOWS-1251", "") } From 78acdd2b8fcc41e8c4d5a856cf51748a98ec0668 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 063/105] fix: return more json.UnmarshalTypeError --- object/groups.go | 20 +++++++++++++++++--- object/object.go | 7 +++++-- object/object_test.go | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/object/groups.go b/object/groups.go index e7376123..72f40bc7 100644 --- a/object/groups.go +++ b/object/groups.go @@ -3,6 +3,7 @@ package object // import "github.com/SevereCloud/vksdk/object" import ( "encoding/json" "fmt" + "reflect" ) // GroupsAddress WorkInfoStatus of information about timetable. @@ -448,18 +449,31 @@ func (g *GroupsSectionsList) UnmarshalJSON(data []byte) error { } if len(alias) != 2 { - return fmt.Errorf("json: cannot unmarshal %s into Go value of type GroupsSectionsList", data) + return &json.UnmarshalTypeError{ + Value: string(data), + Type: reflect.TypeOf((*GroupsSectionsList)(nil)), + } } // default concrete Go type float64 for JSON numbers id, ok := alias[0].(float64) if !ok { - return fmt.Errorf("json: cannot unmarshal %s into Go value of type GroupsSectionsList.ID", data) + return &json.UnmarshalTypeError{ + Value: string(data), + Type: reflect.TypeOf((*GroupsSectionsList)(nil)), + Struct: "GroupsSectionsList", + Field: "ID", + } } name, ok := alias[1].(string) if !ok { - return fmt.Errorf("json: cannot unmarshal %s into Go value of type GroupsSectionsList.Name", data) + return &json.UnmarshalTypeError{ + Value: string(data), + Type: reflect.TypeOf((*GroupsSectionsList)(nil)), + Struct: "GroupsSectionsList", + Field: "Name", + } } g.ID = int(id) diff --git a/object/object.go b/object/object.go index c9dae008..408a57f7 100644 --- a/object/object.go +++ b/object/object.go @@ -8,7 +8,7 @@ package object // import "github.com/SevereCloud/vksdk/object" import ( "bytes" "encoding/json" - "fmt" + "reflect" ) // Attachment interface. @@ -33,7 +33,10 @@ func (b *BaseBoolInt) UnmarshalJSON(data []byte) (err error) { *b = false default: // return json error - err = fmt.Errorf("json: cannot unmarshal ? into Go value of type BaseBoolInt") + err = &json.UnmarshalTypeError{ + Value: string(data), + Type: reflect.TypeOf((*BaseBoolInt)(nil)), + } } return diff --git a/object/object_test.go b/object/object_test.go index ac9b1567..436b3de9 100644 --- a/object/object_test.go +++ b/object/object_test.go @@ -28,7 +28,7 @@ func TestBaseBoolInt_UnmarshalJSON(t *testing.T) { f([]byte("true"), true, "") f([]byte("0"), false, "") f([]byte("false"), false, "") - f([]byte("null"), false, "json: cannot unmarshal ? into Go value of type BaseBoolInt") + f([]byte("null"), false, "json: cannot unmarshal null into Go value of type *object.BaseBoolInt") } func TestBaseImage_UnmarshalJSON(t *testing.T) { From 37a5e47e58380c4d071f6125f723256eeff21d3c Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 064/105] feat: add ErrMarketSpecifyDimensions --- api/errors.go | 1 + 1 file changed, 1 insertion(+) diff --git a/api/errors.go b/api/errors.go index 218a1563..38e1b425 100644 --- a/api/errors.go +++ b/api/errors.go @@ -312,6 +312,7 @@ const ( ErrMarketItemHasBadLinks ErrorType = 1408 // Item has bad links in description ErrMarketShopNotEnabled ErrorType = 1409 // Shop not enabled ErrMarketCartEmpty ErrorType = 1427 // Cart is empty + ErrMarketSpecifyDimensions ErrorType = 1429 // Specify width, length, height and weight all together ErrStoryExpired ErrorType = 1600 // Story has already expired ErrStoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy ErrPrettyCardsCardNotFound ErrorType = 1900 // Card not found From 369ac4d10ed7d52717dee44941f78c792d6f5d30 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 10:59:54 +0300 Subject: [PATCH 065/105] feat: add ErrVKPayStatus --- api/errors.go | 1 + 1 file changed, 1 insertion(+) diff --git a/api/errors.go b/api/errors.go index 38e1b425..f26a4293 100644 --- a/api/errors.go +++ b/api/errors.go @@ -313,6 +313,7 @@ const ( ErrMarketShopNotEnabled ErrorType = 1409 // Shop not enabled ErrMarketCartEmpty ErrorType = 1427 // Cart is empty ErrMarketSpecifyDimensions ErrorType = 1429 // Specify width, length, height and weight all together + ErrVKPayStatus ErrorType = 1430 // VK Pay status can not be changed ErrStoryExpired ErrorType = 1600 // Story has already expired ErrStoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy ErrPrettyCardsCardNotFound ErrorType = 1900 // Card not found From 2bc8a46ea12a8c2ac8fc87b9c3b4d3c2bbbc4041 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 12:51:44 +0300 Subject: [PATCH 066/105] feat: add InvalidContentType error --- api/api.go | 2 +- api/errors.go | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/api/api.go b/api/api.go index 9e7806b1..88b494a2 100644 --- a/api/api.go +++ b/api/api.go @@ -240,7 +240,7 @@ func (vk *VK) defaultHandler(method string, params Params) (Response, error) { mediatype, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type")) if mediatype != "application/json" { _ = resp.Body.Close() - return response, fmt.Errorf("invalid content-type") + return response, &InvalidContentType{mediatype} } err = json.NewDecoder(resp.Body).Decode(&response) diff --git a/api/errors.go b/api/errors.go index f26a4293..714e7acb 100644 --- a/api/errors.go +++ b/api/errors.go @@ -441,3 +441,13 @@ type ExecuteErrors []ExecuteError func (e ExecuteErrors) Error() string { return fmt.Sprintf("api: execute errors (%d)", len(e)) } + +// InvalidContentType type. +type InvalidContentType struct { + ContentType string +} + +// Error returns the message of a InvalidContentType. +func (e InvalidContentType) Error() string { + return "api: invalid content-type" +} From a69352a2579218ffacdf575f721e8737e9a361a7 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 12:52:37 +0300 Subject: [PATCH 067/105] fix: api.Error.As interface{} --- api/errors.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/api/errors.go b/api/errors.go index 714e7acb..d2574a0a 100644 --- a/api/errors.go +++ b/api/errors.go @@ -415,13 +415,13 @@ func (e Error) Is(target error) bool { // be assigned to its second argument, which must be a pointer. If it // succeeds, it performs the assignment and returns true. Otherwise, it // returns false. -func (e Error) As(target error) bool { - if t, ok := target.(Error); ok { +func (e Error) As(target interface{}) bool { + if t, ok := target.(*Error); ok { return e.Code == t.Code } - if t, ok := target.(ErrorType); ok { - return e.Code == t + if t, ok := target.(*ErrorType); ok { + return e.Code == *t } return false From 616f0a2ac25ab819ad049c7b7a86fd62252b52c8 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 13:29:46 +0300 Subject: [PATCH 068/105] BREAKING CHANGE: update streaming errors --- go.mod | 1 - go.sum | 2 - streaming/errors.go | 130 +++++++++++++-------------------------- streaming/errors_test.go | 66 +++++++++++--------- streaming/streaming.go | 7 ++- 5 files changed, 86 insertions(+), 120 deletions(-) diff --git a/go.mod b/go.mod index c46d776e..c0cc0cc7 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,6 @@ go 1.12 require ( github.com/gorilla/schema v1.1.0 github.com/gorilla/websocket v1.4.2 - github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.6.1 golang.org/x/text v0.3.3 ) diff --git a/go.sum b/go.sum index 6ae74b90..126b0c14 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,6 @@ github.com/gorilla/schema v1.1.0 h1:CamqUDOFUBqzrvxuz2vEwo8+SUdwsluFh7IlzJh30LY= github.com/gorilla/schema v1.1.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= diff --git a/streaming/errors.go b/streaming/errors.go index 1283b6e5..d57f4dd4 100644 --- a/streaming/errors.go +++ b/streaming/errors.go @@ -2,116 +2,74 @@ package streaming // import "github.com/SevereCloud/vksdk/streaming" import ( "fmt" - - "github.com/pkg/errors" ) // ErrorType is the type of an error. type ErrorType int +// Error returns the message of a ErrorType. +func (e ErrorType) Error() string { + return fmt.Sprintf("streaming: error with code %d", e) +} + // Error codes. See https://vk.com/dev/streaming_api_docs_2 const ( - NoType ErrorType = 0 // NoType error + ErrNoType ErrorType = 0 // NoType error // Settings for updating the connection to WebSocket are incorrectly transmitted - UpgradeWebsocket ErrorType = 1000 - UnsupportedHTTP ErrorType = 1001 // Unsupported HTTP method - ContentType ErrorType = 1002 // “Content-type” key is absent or invalid - MissingKey ErrorType = 1003 // "key" parameter is absent - BadKey ErrorType = 1004 // "key" parameter is invalid - BadStreamID ErrorType = 1005 // "stream_id" parameter is invalid - ConnectionAlreadyEstablished ErrorType = 1006 // Such connection has been established already - InvalidJSON ErrorType = 2000 // Invalid JSON - TagAlreadyExist ErrorType = 2001 // The rule this such tag has been added already - TagNotExist ErrorType = 2002 // The this such tag is absent - InvalidRule ErrorType = 2003 // Invalid rule - TooManyFilters ErrorType = 2004 // Too many filters in one rule - UnbalancedQuotes ErrorType = 2005 // Unbalanced quotes - TooManyRules ErrorType = 2006 // Too many rules in one stream - MinusKeywordsOnly ErrorType = 2008 // You can't use minus keywords only + ErrUpgradeWebsocket ErrorType = 1000 + ErrUnsupportedHTTP ErrorType = 1001 // Unsupported HTTP method + ErrContentType ErrorType = 1002 // “Content-type” key is absent or invalid + ErrMissingKey ErrorType = 1003 // "key" parameter is absent + ErrBadKey ErrorType = 1004 // "key" parameter is invalid + ErrBadStreamID ErrorType = 1005 // "stream_id" parameter is invalid + ErrConnectionAlreadyEstablished ErrorType = 1006 // Such connection has been established already + ErrInvalidJSON ErrorType = 2000 // Invalid JSON + ErrTagAlreadyExist ErrorType = 2001 // The rule this such tag has been added already + ErrTagNotExist ErrorType = 2002 // The this such tag is absent + ErrInvalidRule ErrorType = 2003 // Invalid rule + ErrTooManyFilters ErrorType = 2004 // Too many filters in one rule + ErrUnbalancedQuotes ErrorType = 2005 // Unbalanced quotes + ErrTooManyRules ErrorType = 2006 // Too many rules in one stream + ErrMinusKeywordsOnly ErrorType = 2008 // You can't use minus keywords only ) // Error description. type Error struct { - Message string `json:"message"` // error message; - ErrorCode int `json:"error_code"` // error code -} - -type customError struct { - errorType ErrorType - originalError error - context Error -} - -// New creates a new customError. -func (errorType ErrorType) New(msg string) error { - return customError{errorType: errorType, originalError: errors.New(msg)} -} - -// Newf creates a new customError with formatted message. -func (errorType ErrorType) Newf(msg string, args ...interface{}) error { - return customError{errorType: errorType, originalError: fmt.Errorf(msg, args...)} -} - -// Wrap creates a new wrapped error. -func (errorType ErrorType) Wrap(err error, msg string) error { - return errorType.Wrapf(err, msg) -} - -// Wrapf creates a new wrapped error with formatted message. -func (errorType ErrorType) Wrapf(err error, msg string, args ...interface{}) error { - return customError{errorType: errorType, originalError: errors.Wrapf(err, msg, args...)} + Code ErrorType `json:"error_code"` // error code + Message string `json:"message"` // error message } -// Error returns the message of a customError. -func (error customError) Error() string { - return error.originalError.Error() +// Error returns the message of a Error. +func (e Error) Error() string { + return fmt.Sprintf("streaming: %s", e.Message) } -// NewError creates a no type error. -func NewError(vkErr Error) error { - if vkErr.ErrorCode == 0 { - return nil - } - - return customError{ - errorType: ErrorType(vkErr.ErrorCode), - originalError: errors.New(vkErr.Message), - context: vkErr, +// Is unwraps its first argument sequentially looking for an error that matches +// the second. +func (e Error) Is(target error) bool { + if t, ok := target.(*Error); ok { + return e.Code == t.Code && e.Message == t.Message } -} - -// Cause gives the original error. -func Cause(err error) error { - return errors.Cause(err) -} -// AddErrorContext adds a context to an error. -func AddErrorContext(err error, context Error) error { - if customErr, ok := err.(customError); ok { - return customError{ - errorType: customErr.errorType, - originalError: customErr.originalError, - context: context, - } + if t, ok := target.(*ErrorType); ok { + return e.Code == *t } - return customError{errorType: NoType, originalError: err, context: context} + return false } -// GetErrorContext returns the error context. -func GetErrorContext(err error) Error { - if customErr, ok := err.(customError); ok { - return customErr.context +// As unwraps its first argument sequentially looking for an error that can +// be assigned to its second argument, which must be a pointer. If it +// succeeds, it performs the assignment and returns true. Otherwise, it +// returns false. +func (e Error) As(target interface{}) bool { + if t, ok := target.(*Error); ok { + return e.Code == t.Code } - return Error{} -} - -// GetType returns the error type. -func GetType(err error) ErrorType { - if customErr, ok := err.(customError); ok { - return customErr.errorType + if t, ok := target.(*ErrorType); ok { + return e.Code == *t } - return NoType + return false } diff --git a/streaming/errors_test.go b/streaming/errors_test.go index 3cce51d9..1a5793a8 100644 --- a/streaming/errors_test.go +++ b/streaming/errors_test.go @@ -1,49 +1,59 @@ package streaming_test import ( - "fmt" + "errors" "testing" + "github.com/SevereCloud/vksdk/api" "github.com/SevereCloud/vksdk/streaming" "github.com/stretchr/testify/assert" ) -func TestContext(t *testing.T) { - t.Parallel() - - err := streaming.BadKey.New("an_error") - expectedContext := streaming.Error{ErrorCode: 1004} - errWithContext := streaming.AddErrorContext(err, expectedContext) +func TestErrorType(t *testing.T) { + err := streaming.ErrorType(1) + assert.EqualError(t, err, "streaming: error with code 1") +} - assert.Equal(t, streaming.BadKey, streaming.GetType(errWithContext)) - assert.Equal(t, expectedContext, streaming.GetErrorContext(errWithContext)) - assert.Equal(t, err.Error(), errWithContext.Error()) +func TestError_Error(t *testing.T) { + err := streaming.Error{ + Code: streaming.ErrorType(1), + Message: "test message", + } + assert.EqualError(t, err, "streaming: test message") } -func TestGetErrorContext(t *testing.T) { - t.Parallel() +func TestError_Is(t *testing.T) { + f := func(err *streaming.Error, target error, want bool) { + assert.Equal(t, want, errors.Is(err, target)) + } - f := func(err error, wantContext streaming.Error) { - t.Helper() + e1 := streaming.ErrorType(1) + e2 := streaming.ErrorType(2) - context := streaming.GetErrorContext(err) - assert.Equal(t, context, wantContext) - } + f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(1)}, true) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &e1, true) + f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, true) - f(fmt.Errorf("no type error"), streaming.Error{}) - f(streaming.NewError(streaming.Error{ErrorCode: 1004}), streaming.Error{ErrorCode: 1004}) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(2)}, false) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &e2, false) + f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "321"}, false) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &api.Error{}, false) } -func TestGetType(t *testing.T) { - t.Parallel() +func TestError_As(t *testing.T) { + f := func(err *streaming.Error, target interface{}, want bool) { + assert.Equal(t, want, errors.As(err, target)) + } - f := func(err error, wantType streaming.ErrorType) { - t.Helper() + e1 := streaming.ErrorType(1) + e2 := streaming.ErrorType(2) - errorType := streaming.GetType(err) - assert.Equal(t, errorType, wantType) - } + f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(1)}, true) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &e1, true) + f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, true) + f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "321"}, true) - f(fmt.Errorf("no type error"), streaming.NoType) - f(streaming.BadKey.New("BadKey type error"), streaming.BadKey) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(2)}, false) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &e2, false) + f(&streaming.Error{Code: streaming.ErrorType(1)}, &api.Error{}, false) } diff --git a/streaming/streaming.go b/streaming/streaming.go index 166f3ed5..c081464d 100644 --- a/streaming/streaming.go +++ b/streaming/streaming.go @@ -83,6 +83,7 @@ package streaming import ( "bytes" "encoding/json" + "errors" "fmt" "net/http" "net/url" @@ -157,7 +158,7 @@ func (s *Streaming) doRequest(req *http.Request) (*response, error) { } if r.Code == codeError { - return nil, NewError(r.Error) + return nil, &r.Error } return &r, nil @@ -270,7 +271,7 @@ func (s *Streaming) handlerWebsocket(r response) error { f(r.Event) } case codeError: - return NewError(r.Error) + return &r.Error } return nil @@ -300,7 +301,7 @@ func (s *Streaming) Run() error { c, wsResp, err := s.Dialer.Dial(u.String(), requestHeader) if err != nil { - if err == websocket.ErrBadHandshake && wsResp != nil { + if errors.Is(err, websocket.ErrBadHandshake) && wsResp != nil { var r response err = json.NewDecoder(wsResp.Body).Decode(&r) From cf1ebe93db6d79265d5a0b8a24a628411df9253b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 13:34:41 +0300 Subject: [PATCH 069/105] test: add for errors --- api/errors.go | 4 +-- api/errors_test.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 api/errors_test.go diff --git a/api/errors.go b/api/errors.go index d2574a0a..829239e0 100644 --- a/api/errors.go +++ b/api/errors.go @@ -404,8 +404,8 @@ func (e Error) Is(target error) bool { return e.Code == t.Code && e.Message == t.Message } - if t, ok := target.(ErrorType); ok { - return e.Code == t + if t, ok := target.(*ErrorType); ok { + return e.Code == *t } return false diff --git a/api/errors_test.go b/api/errors_test.go new file mode 100644 index 00000000..8c4c569e --- /dev/null +++ b/api/errors_test.go @@ -0,0 +1,69 @@ +package api_test + +import ( + "errors" + "testing" + + "github.com/SevereCloud/vksdk/api" + "github.com/SevereCloud/vksdk/streaming" + "github.com/stretchr/testify/assert" +) + +func TestErrorType(t *testing.T) { + err := api.ErrorType(1) + assert.EqualError(t, err, "api: error with code 1") +} + +func TestError_Error(t *testing.T) { + err := api.Error{ + Code: api.ErrorType(1), + Message: "test message", + } + assert.EqualError(t, err, "api: test message") +} + +func TestError_Is(t *testing.T) { + f := func(err *api.Error, target error, want bool) { + assert.Equal(t, want, errors.Is(err, target)) + } + + e1 := api.ErrorType(1) + e2 := api.ErrorType(2) + + f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(1)}, true) + f(&api.Error{Code: api.ErrorType(1)}, &e1, true) + f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "123"}, true) + + f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(2)}, false) + f(&api.Error{Code: api.ErrorType(1)}, &e2, false) + f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "321"}, false) + f(&api.Error{Code: api.ErrorType(1)}, &streaming.Error{}, false) +} + +func TestError_As(t *testing.T) { + f := func(err *api.Error, target interface{}, want bool) { + assert.Equal(t, want, errors.As(err, target)) + } + + e1 := api.ErrorType(1) + e2 := api.ErrorType(2) + + f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(1)}, true) + f(&api.Error{Code: api.ErrorType(1)}, &e1, true) + f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "123"}, true) + f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "321"}, true) + + f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(2)}, false) + f(&api.Error{Code: api.ErrorType(1)}, &e2, false) + f(&api.Error{Code: api.ErrorType(1)}, &streaming.Error{}, false) +} + +func TestInvalidContentType(t *testing.T) { + err := api.InvalidContentType{} + assert.EqualError(t, err, "api: invalid content-type") +} + +func TestExecuteErrors(t *testing.T) { + err := api.ExecuteErrors{api.ExecuteError{}} + assert.EqualError(t, err, "api: execute errors (1)") +} From f4d8f44e459ddef9e610dad9eb89d9d35426a49b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 15:34:48 +0300 Subject: [PATCH 070/105] test: goerr113 TestCancelBeforeHeaders --- internal/transport_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/transport_test.go b/internal/transport_test.go index 955c864a..f66d7d07 100644 --- a/internal/transport_test.go +++ b/internal/transport_test.go @@ -2,6 +2,7 @@ package internal_test import ( "context" + "errors" "io" "io/ioutil" "net/http" @@ -135,7 +136,7 @@ func TestCancelBeforeHeaders(t *testing.T) { t.Fatal("Get returned unexpected nil error") } - if err != context.Canceled { + if !errors.Is(err, context.Canceled) { t.Errorf("err = %v; want %v", err, context.Canceled) } } From f9984f33506d929c6dde09689d3b1ae0c0ea3a5a Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 16:25:18 +0300 Subject: [PATCH 071/105] feat: longpoll update errors --- longpoll-bot/errors.go | 18 +++++++++++++ longpoll-bot/errors_test.go | 13 ++++++++++ longpoll-bot/longpoll.go | 2 +- longpoll-user/errors.go | 22 ++++++++++++++++ longpoll-user/errors_test.go | 13 ++++++++++ longpoll-user/longpoll.go | 4 +-- longpoll-user/v3/errors.go | 45 ++++++++++++++++++++++++++++++++- longpoll-user/v3/extra.go | 9 +++---- longpoll-user/v3/objects.go | 49 ++++++++++++++++++------------------ 9 files changed, 141 insertions(+), 34 deletions(-) create mode 100644 longpoll-bot/errors.go create mode 100644 longpoll-bot/errors_test.go create mode 100644 longpoll-user/errors.go create mode 100644 longpoll-user/errors_test.go diff --git a/longpoll-bot/errors.go b/longpoll-bot/errors.go new file mode 100644 index 00000000..58d97c96 --- /dev/null +++ b/longpoll-bot/errors.go @@ -0,0 +1,18 @@ +package longpoll + +import ( + "fmt" +) + +// Failed struct. +type Failed struct { + Code int +} + +// Error returns the message of a Failed. +func (e Failed) Error() string { + return fmt.Sprintf( + "longpoll: failed code %d", + e.Code, + ) +} diff --git a/longpoll-bot/errors_test.go b/longpoll-bot/errors_test.go new file mode 100644 index 00000000..bc9a1f69 --- /dev/null +++ b/longpoll-bot/errors_test.go @@ -0,0 +1,13 @@ +package longpoll_test + +import ( + "testing" + + "github.com/SevereCloud/vksdk/longpoll-bot" + "github.com/stretchr/testify/assert" +) + +func TestFailed_Error(t *testing.T) { + err := longpoll.Failed{1} + assert.EqualError(t, err, "longpoll: failed code 1") +} diff --git a/longpoll-bot/longpoll.go b/longpoll-bot/longpoll.go index 0abbb35e..4b38d55c 100644 --- a/longpoll-bot/longpoll.go +++ b/longpoll-bot/longpoll.go @@ -128,7 +128,7 @@ func (lp *Longpoll) checkResponse(response object.LongpollBotResponse) (err erro case 3: err = lp.updateServer(true) default: - err = fmt.Errorf(`"failed":%d`, response.Failed) + err = &Failed{response.Failed} } return diff --git a/longpoll-user/errors.go b/longpoll-user/errors.go new file mode 100644 index 00000000..4469a626 --- /dev/null +++ b/longpoll-user/errors.go @@ -0,0 +1,22 @@ +package longpoll + +import ( + "errors" + "fmt" +) + +// ErrNotValidVersion not valid version. +var ErrNotValidVersion = errors.New("longpoll: not valid version") + +// Failed struct. +type Failed struct { + Code int +} + +// Error returns the message of a Failed. +func (e Failed) Error() string { + return fmt.Sprintf( + "longpoll: failed code %d", + e.Code, + ) +} diff --git a/longpoll-user/errors_test.go b/longpoll-user/errors_test.go new file mode 100644 index 00000000..2a190243 --- /dev/null +++ b/longpoll-user/errors_test.go @@ -0,0 +1,13 @@ +package longpoll_test + +import ( + "testing" + + "github.com/SevereCloud/vksdk/longpoll-user" + "github.com/stretchr/testify/assert" +) + +func TestFailed_Error(t *testing.T) { + err := longpoll.Failed{1} + assert.EqualError(t, err, "longpoll: failed code 1") +} diff --git a/longpoll-user/longpoll.go b/longpoll-user/longpoll.go index f5f83465..70f7c034 100644 --- a/longpoll-user/longpoll.go +++ b/longpoll-user/longpoll.go @@ -175,9 +175,9 @@ func (lp *Longpoll) checkResponse(response object.LongpollResponse) (err error) case 3: err = lp.updateServer(true) case 4: - err = fmt.Errorf("not valid version") + err = ErrNotValidVersion default: - err = fmt.Errorf(`"failed":%d`, response.Failed) + err = &Failed{response.Failed} } return diff --git a/longpoll-user/v3/errors.go b/longpoll-user/v3/errors.go index 168f712c..ebe5f0a6 100644 --- a/longpoll-user/v3/errors.go +++ b/longpoll-user/v3/errors.go @@ -1,3 +1,46 @@ package wrapper // import "github.com/SevereCloud/vksdk/longpoll-user/v3" -const errFmtTooShortArray = "cannot parse array into Go struct %s: expected at least %d element(s), got %d" +import "fmt" + +// tooShortArray type. +type tooShortArray struct { + structName string + least int + got int +} + +// Error returns the message of a tooShortArray. +func (e tooShortArray) Error() string { + return fmt.Sprintf( + "wrapper: cannot parse array into Go struct %s: expected at least %d element(s), got %d", + e.structName, + e.least, + e.got, + ) +} + +// expectedSlice type. +type expectedSlice struct { + v interface{} +} + +// Error returns the message of a expectedSlice. +func (e expectedSlice) Error() string { + return fmt.Sprintf( + "wrapper: expected a slice, got %T", + e.v, + ) +} + +// failedCast type. +type failedCast struct { + v interface{} +} + +// Error returns the message of a failedCast. +func (e failedCast) Error() string { + return fmt.Sprintf( + "wrapper: cast failed, value type: %T", + e.v, + ) +} diff --git a/longpoll-user/v3/extra.go b/longpoll-user/v3/extra.go index 5f565689..ee5dfced 100644 --- a/longpoll-user/v3/extra.go +++ b/longpoll-user/v3/extra.go @@ -1,7 +1,6 @@ package wrapper // import "github.com/SevereCloud/vksdk/longpoll-user/v3" import ( - "fmt" "reflect" "time" ) @@ -167,7 +166,7 @@ func (result *ExtraFields) parseExtraFields(i []interface{}) error { func interfaceToStringIntMap(m interface{}) (map[string]int, error) { reflectedMap := reflect.ValueOf(m) if reflectedMap.Kind() != reflect.Map { - return nil, fmt.Errorf("expected a slice, got %T", m) + return nil, &expectedSlice{m} } result := make(map[string]int, reflectedMap.Len()) @@ -175,7 +174,7 @@ func interfaceToStringIntMap(m interface{}) (map[string]int, error) { for _, key := range reflectedMap.MapKeys() { v, ok := reflectedMap.MapIndex(key).Interface().(float64) if !ok { - return nil, fmt.Errorf("cast failed, value type: %T", reflectedMap.MapIndex(key).Interface()) + return nil, &failedCast{reflectedMap.MapIndex(key).Interface()} } result[key.String()] = int(v) @@ -187,7 +186,7 @@ func interfaceToStringIntMap(m interface{}) (map[string]int, error) { func interfaceToIDSlice(slice interface{}) ([]int, error) { reflectedSlice := reflect.ValueOf(slice) if reflectedSlice.Kind() != reflect.Slice { - return nil, fmt.Errorf("expected a slice, got %T", slice) + return nil, &expectedSlice{slice} } result := make([]int, reflectedSlice.Len()) @@ -195,7 +194,7 @@ func interfaceToIDSlice(slice interface{}) ([]int, error) { for i := 0; i < reflectedSlice.Len(); i++ { v, ok := reflectedSlice.Index(i).Interface().(float64) if !ok { - return nil, fmt.Errorf("cast failed, value type: %T", reflectedSlice.Index(i).Interface()) + return nil, &failedCast{reflectedSlice.Index(i).Interface()} } result[i] = int(v) diff --git a/longpoll-user/v3/objects.go b/longpoll-user/v3/objects.go index 9a3235f8..737478a2 100644 --- a/longpoll-user/v3/objects.go +++ b/longpoll-user/v3/objects.go @@ -1,7 +1,6 @@ package wrapper // import "github.com/SevereCloud/vksdk/longpoll-user/v3" import ( - "fmt" "time" ) @@ -16,7 +15,7 @@ type MessageFlagsChange struct { func (result *MessageFlagsChange) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "MessageFlagsChange", 3, len(i)) + return tooShortArray{structName: "MessageFlagsChange", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -41,7 +40,7 @@ type MessageFlagsSet struct { func (result *MessageFlagsSet) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "MessageFlagsSet", 3, len(i)) + return tooShortArray{structName: "MessageFlagsSet", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -66,7 +65,7 @@ type MessageFlagsReset struct { func (result *MessageFlagsReset) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "MessageFlagsReset", 3, len(i)) + return tooShortArray{structName: "MessageFlagsReset", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -91,7 +90,7 @@ type NewMessage struct { func (result *NewMessage) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "NewMessage", 3, len(i)) + return tooShortArray{structName: "NewMessage", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -120,7 +119,7 @@ type EditMessage struct { func (result *EditMessage) parse(i []interface{}) error { if len(i) < 6 { - return fmt.Errorf(errFmtTooShortArray, "EditMessage", 6, len(i)) + return tooShortArray{structName: "EditMessage", least: 6, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -168,7 +167,7 @@ type ReadInMessages struct { func (result *ReadInMessages) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "ReadInMessages", 3, len(i)) + return tooShortArray{structName: "ReadInMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -192,7 +191,7 @@ type ReadOutMessages struct { func (result *ReadOutMessages) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "ReadOutMessages", 3, len(i)) + return tooShortArray{structName: "ReadOutMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -217,7 +216,7 @@ type FriendBecameOnline struct { func (result *FriendBecameOnline) parse(i []interface{}) error { if len(i) < 4 { - return fmt.Errorf(errFmtTooShortArray, "FriendBecameOnline", 4, len(i)) + return tooShortArray{structName: "FriendBecameOnline", least: 4, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -246,7 +245,7 @@ type FriendBecameOffline struct { func (result *FriendBecameOffline) parse(i []interface{}) error { if len(i) < 4 { - return fmt.Errorf(errFmtTooShortArray, "FriendBecameOffline", 4, len(i)) + return tooShortArray{structName: "FriendBecameOffline", least: 4, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -274,7 +273,7 @@ type DialogFlagsReset struct { func (result *DialogFlagsReset) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "DialogFlagsReset", 3, len(i)) + return tooShortArray{structName: "DialogFlagsReset", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -298,7 +297,7 @@ type DialogFlagsReplace struct { func (result *DialogFlagsReplace) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "DialogFlagsReplace", 3, len(i)) + return tooShortArray{structName: "DialogFlagsReplace", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -322,7 +321,7 @@ type DialogsFlagsSet struct { func (result *DialogsFlagsSet) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "DialogsFlagsSet", 3, len(i)) + return tooShortArray{structName: "DialogsFlagsSet", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -346,7 +345,7 @@ type DeleteMessages struct { func (result *DeleteMessages) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "DeleteMessages", 3, len(i)) + return tooShortArray{structName: "DeleteMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -370,7 +369,7 @@ type RestoreDeletedMessages struct { func (result *RestoreDeletedMessages) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "RestoreDeletedMessages", 3, len(i)) + return tooShortArray{structName: "RestoreDeletedMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -395,7 +394,7 @@ type ChatParamsChange struct { func (result *ChatParamsChange) parse(i []interface{}) error { if len(i) < 2 { - return fmt.Errorf(errFmtTooShortArray, "ChatParamsChange", 2, len(i)) + return tooShortArray{structName: "ChatParamsChange", least: 2, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -422,7 +421,7 @@ type ChatInfoChange struct { func (result *ChatInfoChange) parse(i []interface{}) error { if len(i) < 4 { - return fmt.Errorf(errFmtTooShortArray, "ChatInfoChange", 4, len(i)) + return tooShortArray{structName: "ChatInfoChange", least: 4, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -450,7 +449,7 @@ type UserTyping struct { func (result *UserTyping) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "UserTyping", 3, len(i)) + return tooShortArray{structName: "UserTyping", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -474,7 +473,7 @@ type UserTypingChat struct { func (result *UserTypingChat) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "UserTypingChat", 3, len(i)) + return tooShortArray{structName: "UserTypingChat", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -498,7 +497,7 @@ type UsersTyping struct { func (result *UsersTyping) parse(i []interface{}) error { if len(i) < 5 { - return fmt.Errorf(errFmtTooShortArray, "UsersTyping", 5, len(i)) + return tooShortArray{structName: "UsersTyping", least: 5, got: len(i)} } userIDs, err := interfaceToIDSlice(i[1]) @@ -533,7 +532,7 @@ type UsersRecordingAudioMessage struct { func (result *UsersRecordingAudioMessage) parse(i []interface{}) error { if len(i) < 5 { - return fmt.Errorf(errFmtTooShortArray, "UsersRecordingAudioMessage", 5, len(i)) + return tooShortArray{structName: "UsersRecordingAudioMessage", least: 5, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -566,7 +565,7 @@ type UserCall struct { func (result *UserCall) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "UserCall", 3, len(i)) + return tooShortArray{structName: "UserCall", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -587,7 +586,7 @@ type CounterChange struct { func (result *CounterChange) parse(i []interface{}) error { if len(i) < 2 { - return fmt.Errorf(errFmtTooShortArray, "CounterChange", 2, len(i)) + return tooShortArray{structName: "CounterChange", least: 2, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -607,7 +606,7 @@ type NotificationSettingsChange struct { // ParseMode8 should be called if ExtendedEvents flag set. func (result *NotificationSettingsChange) parseMode8(i []interface{}) error { if len(i) < 2 { - return fmt.Errorf(errFmtTooShortArray, "NotificationSettingsChange", 2, len(i)) + return tooShortArray{structName: "NotificationSettingsChange", least: 2, got: len(i)} } v, err := interfaceToStringIntMap(i[1]) @@ -624,7 +623,7 @@ func (result *NotificationSettingsChange) parseMode8(i []interface{}) error { func (result *NotificationSettingsChange) parse(i []interface{}) error { if len(i) < 3 { - return fmt.Errorf(errFmtTooShortArray, "NotificationSettingsChange", 3, len(i)) + return tooShortArray{structName: "NotificationSettingsChange", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { From fcd201f4f3658055229c2bbc861e16faa2520746 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 16:50:32 +0300 Subject: [PATCH 072/105] feat: add UploadError --- api/errors.go | 17 +++++++++++++++++ api/upload.go | 46 ++++++++++++++++++++++------------------------ 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/api/errors.go b/api/errors.go index 829239e0..40fc66d6 100644 --- a/api/errors.go +++ b/api/errors.go @@ -451,3 +451,20 @@ type InvalidContentType struct { func (e InvalidContentType) Error() string { return "api: invalid content-type" } + +// UploadError type. +type UploadError struct { + Err string `json:"error"` + Code int `json:"error_code"` + Descr string `json:"error_descr"` + IsLogged bool `json:"error_is_logged"` +} + +// Error returns the message of a UploadError. +func (e UploadError) Error() string { + if e.Err != "" { + return "api: " + e.Err + } + + return fmt.Sprintf("api: upload code %d", e.Code) +} diff --git a/api/upload.go b/api/upload.go index b56eab79..d78c68ae 100644 --- a/api/upload.go +++ b/api/upload.go @@ -3,7 +3,6 @@ package api // import "github.com/SevereCloud/vksdk/api" import ( "bytes" "encoding/json" - "fmt" "io" "io/ioutil" "mime/multipart" @@ -11,13 +10,6 @@ import ( "github.com/SevereCloud/vksdk/object" ) -type uploadError struct { - Error string `json:"error"` - ErrorCode int `json:"error_code"` - ErrorDescr string `json:"error_descr"` - ErrorIsLogged bool `json:"error_is_logged"` -} - // UploadFile uploading file. func (vk *VK) UploadFile(url string, file io.Reader, fieldname, filename string) (bodyContent []byte, err error) { body := new(bytes.Buffer) @@ -494,15 +486,15 @@ func (vk *VK) UploadVideo(params Params, file io.Reader) (response VideoSaveResp return } - var videoUploadError uploadError + var videoUploadError UploadError err = json.Unmarshal(bodyContent, &videoUploadError) if err != nil { return } - if videoUploadError.ErrorCode != 0 { - err = fmt.Errorf(videoUploadError.Error) + if videoUploadError.Code != 0 { + err = &videoUploadError } return @@ -519,15 +511,15 @@ func (vk *VK) uploadDoc(url, title, tags string, file io.Reader) (response DocsS return } - var docUploadError uploadError + var docUploadError UploadError err = json.Unmarshal(bodyContent, &docUploadError) if err != nil { return } - if docUploadError.Error != "" { - err = fmt.Errorf(docUploadError.Error) + if docUploadError.Err != "" { + err = &docUploadError return } @@ -721,15 +713,19 @@ func (vk *VK) UploadStoriesPhoto(params Params, file io.Reader) (response Storie } if handler.Error.ErrorCode != 0 { - err = fmt.Errorf(handler.Error.Type) - return + err = &UploadError{ + Code: handler.Error.ErrorCode, + Err: handler.Error.Type, + } + + return response, err } response, err = vk.StoriesSave(Params{ "upload_results": handler.Response.UploadResult, }) - return + return response, err } // UploadStoriesVideo uploading Story. @@ -754,15 +750,19 @@ func (vk *VK) UploadStoriesVideo(params Params, file io.Reader) (response Storie } if handler.Error.ErrorCode != 0 { - err = fmt.Errorf(handler.Error.Type) - return + err = &UploadError{ + Code: handler.Error.ErrorCode, + Err: handler.Error.Type, + } + + return response, err } response, err = vk.StoriesSave(Params{ "upload_results": handler.Response.UploadResult, }) - return + return response, err } // uploadPollsPhoto uploading a Poll Photo. @@ -846,8 +846,7 @@ func (vk *VK) UploadPrettyCardsPhoto(file io.Reader) (response string, err error response = handler.Photo if handler.ErrCode != 0 { - // TODO: new type error - err = fmt.Errorf("%d", handler.ErrCode) + err = &UploadError{Code: handler.ErrCode} } return @@ -882,8 +881,7 @@ func (vk *VK) UploadLeadFormsPhoto(file io.Reader) (response string, err error) response = handler.Photo if handler.ErrCode != 0 { - // TODO: new type error - err = fmt.Errorf("%d", handler.ErrCode) + err = &UploadError{Code: handler.ErrCode} } return From b8e1f2b547ac6610c85ce37e69ee0db24c5feab3 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 16:53:36 +0300 Subject: [PATCH 073/105] test: enable goerr113 --- .golangci.yml | 3 ++- api/errors.go | 2 +- internal/charset.go | 3 +-- streaming/errors.go | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index ea88e770..ff9f2204 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -35,9 +35,10 @@ linters: - asciicheck - nolintlint - gofumpt + - goerr113 + # - testpackage # TODO: Fix testpackage # - nestif # TODO: Fix nestif -# - goerr113 # TODO: Enable v2 # don't enable: # - depguard diff --git a/api/errors.go b/api/errors.go index 40fc66d6..df65ec71 100644 --- a/api/errors.go +++ b/api/errors.go @@ -394,7 +394,7 @@ type Error struct { // Error returns the message of a Error. func (e Error) Error() string { - return fmt.Sprintf("api: %s", e.Message) + return "api: " + e.Message } // Is unwraps its first argument sequentially looking for an error that matches diff --git a/internal/charset.go b/internal/charset.go index f7f99981..91d73538 100644 --- a/internal/charset.go +++ b/internal/charset.go @@ -4,7 +4,6 @@ Package internal unimportable package internal // import "github.com/SevereCloud/vksdk/internal" import ( - "fmt" "io" "strings" @@ -43,7 +42,7 @@ type CharsetUnknownError struct { // Error returns the message of a CharsetUnknownError. func (c *CharsetUnknownError) Error() string { - return fmt.Sprintf("unknown charset: %s", c.Name) + return "unknown charset: " + c.Name } // CharsetReader if non-nil, defines a function to generate diff --git a/streaming/errors.go b/streaming/errors.go index d57f4dd4..a7ebdbab 100644 --- a/streaming/errors.go +++ b/streaming/errors.go @@ -41,7 +41,7 @@ type Error struct { // Error returns the message of a Error. func (e Error) Error() string { - return fmt.Sprintf("streaming: %s", e.Message) + return "streaming: " + e.Message } // Is unwraps its first argument sequentially looking for an error that matches From b4cd8f5ce0c7be0475104b239b4f881c28cf4c50 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 2 Aug 2020 19:09:04 +0300 Subject: [PATCH 074/105] fix: upload errors --- api/api.go | 11 ++++++----- api/api_test.go | 5 +++-- api/upload.go | 14 +++----------- api/upload_test.go | 8 ++++---- 4 files changed, 16 insertions(+), 22 deletions(-) diff --git a/api/api.go b/api/api.go index 88b494a2..4292528b 100644 --- a/api/api.go +++ b/api/api.go @@ -259,10 +259,10 @@ func (vk *VK) defaultHandler(method string, params Params) (Response, error) { continue } - return response, response.Error + return response, &response.Error } - return response, response.Error + return response, &response.Error } } @@ -329,15 +329,16 @@ func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error copyParams["v"] = vk.Version resp, err := vk.Handler("execute", copyParams) - if resp.ExecuteErrors != nil { - return resp.ExecuteErrors - } jsonErr := json.Unmarshal(resp.Response, &obj) if jsonErr != nil { return jsonErr } + if resp.ExecuteErrors != nil { + return resp.ExecuteErrors + } + return err } diff --git a/api/api_test.go b/api/api_test.go index 760f9e00..1ba64dd8 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -1,6 +1,7 @@ package api_test import ( + "errors" "fmt" "log" "os" @@ -243,7 +244,7 @@ func TestVK_InvalidContentType(t *testing.T) { var testObj string err := vkGroup.RequestUnmarshal("t/t", api.Params{}, testObj) - if err == nil || err.Error() != "invalid content-type" { + if err == nil || err.Error() != "api: invalid content-type" { t.Errorf("VK.RequestUnmarshal() error = %v", err) } } @@ -300,7 +301,7 @@ func TestVK_CaptchaForce(t *testing.T) { _, err := vkUser.CaptchaForce(api.Params{}) - if e, ok := err.(*api.Error); err != nil || !ok || e.Code != api.ErrCaptcha { + if errors.Is(err, api.ErrCaptcha) { t.Errorf("VK.CaptchaForce() err=%v, want 14", err) } } diff --git a/api/upload.go b/api/upload.go index d78c68ae..d3603cef 100644 --- a/api/upload.go +++ b/api/upload.go @@ -680,10 +680,7 @@ type rawUploadStoriesPhoto struct { type rawUploadStoriesVideo struct { Response UploadStories `json:"response"` - Error struct { - ErrorCode int `json:"error_code"` - Type string `json:"type"` - } `json:"error"` + UploadError } // UploadStoriesPhoto uploading Story. @@ -749,13 +746,8 @@ func (vk *VK) UploadStoriesVideo(params Params, file io.Reader) (response Storie return } - if handler.Error.ErrorCode != 0 { - err = &UploadError{ - Code: handler.Error.ErrorCode, - Err: handler.Error.Type, - } - - return response, err + if handler.UploadError.Code != 0 { + return response, &handler.UploadError } response, err = vk.StoriesSave(Params{ diff --git a/api/upload_test.go b/api/upload_test.go index 02cc3eab..7fda53af 100644 --- a/api/upload_test.go +++ b/api/upload_test.go @@ -298,7 +298,7 @@ func TestVK_UploadVideo_Error(t *testing.T) { defer response.Body.Close() _, err = vkUser.UploadVideo(api.Params{}, response.Body) - if _, ok := err.(*api.Error); err != nil && !ok { + if _, ok := err.(*api.UploadError); err != nil && !ok { t.Errorf("VK.UploadVideo() err = %v, want %v", err, -1) } } @@ -309,7 +309,7 @@ func TestVK_uploadDoc_Error(t *testing.T) { needUserToken(t) _, err := vkUser.UploadDoc("", "", new(bytes.Buffer)) - if _, ok := err.(*api.Error); err != nil && !ok { + if _, ok := err.(*api.UploadError); err != nil && !ok { t.Errorf("VK.UploadDoc() err = %v, want %v", err, -1) } } @@ -435,7 +435,7 @@ func TestVK_UploadStoriesPhoto_Error(t *testing.T) { needUserToken(t) _, err := vkUser.UploadStoriesPhoto(api.Params{}, new(bytes.Buffer)) - if _, ok := err.(*api.Error); err != nil && !ok { + if _, ok := err.(*api.UploadError); err != nil && !ok { t.Errorf("VK.UploadStoriesPhoto() err = %v, want %v", err, -1) } } @@ -452,7 +452,7 @@ func TestVK_UploadStoriesVideo_Error(t *testing.T) { defer response.Body.Close() _, err = vkUser.UploadStoriesVideo(api.Params{}, response.Body) - if _, ok := err.(*api.Error); err != nil && !ok { + if _, ok := err.(*api.UploadError); err != nil && !ok { t.Errorf("VK.UploadStoriesVideo() err = %v, want %v", err, -1) } } From 92a724cb0e2d24f82766f179e234793920ac9f6b Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 11:28:53 +0300 Subject: [PATCH 075/105] fix: remove As method --- api/api_test.go | 2 +- api/errors.go | 20 ++------------------ api/errors_test.go | 26 +++++++------------------- api/streaming_test.go | 11 ++++++----- streaming/errors.go | 20 ++------------------ streaming/errors_test.go | 26 +++++++------------------- 6 files changed, 25 insertions(+), 80 deletions(-) diff --git a/api/api_test.go b/api/api_test.go index 1ba64dd8..852b070d 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -38,7 +38,7 @@ func noError(t *testing.T, err error) bool { t.Log(s) } - } else { + } else if err != nil { t.Log(fmt.Sprintf("\n%#v", err)) } diff --git a/api/errors.go b/api/errors.go index df65ec71..efe2c80e 100644 --- a/api/errors.go +++ b/api/errors.go @@ -404,24 +404,8 @@ func (e Error) Is(target error) bool { return e.Code == t.Code && e.Message == t.Message } - if t, ok := target.(*ErrorType); ok { - return e.Code == *t - } - - return false -} - -// As unwraps its first argument sequentially looking for an error that can -// be assigned to its second argument, which must be a pointer. If it -// succeeds, it performs the assignment and returns true. Otherwise, it -// returns false. -func (e Error) As(target interface{}) bool { - if t, ok := target.(*Error); ok { - return e.Code == t.Code - } - - if t, ok := target.(*ErrorType); ok { - return e.Code == *t + if t, ok := target.(ErrorType); ok { + return e.Code == t } return false diff --git a/api/errors_test.go b/api/errors_test.go index 8c4c569e..58f4bdc9 100644 --- a/api/errors_test.go +++ b/api/errors_test.go @@ -27,35 +27,23 @@ func TestError_Is(t *testing.T) { assert.Equal(t, want, errors.Is(err, target)) } - e1 := api.ErrorType(1) - e2 := api.ErrorType(2) - f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(1)}, true) - f(&api.Error{Code: api.ErrorType(1)}, &e1, true) + f(&api.Error{Code: api.ErrAuth}, api.ErrAuth, true) f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "123"}, true) f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(2)}, false) - f(&api.Error{Code: api.ErrorType(1)}, &e2, false) + f(&api.Error{Code: api.ErrorType(1)}, api.ErrorType(2), false) f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "321"}, false) f(&api.Error{Code: api.ErrorType(1)}, &streaming.Error{}, false) } func TestError_As(t *testing.T) { - f := func(err *api.Error, target interface{}, want bool) { - assert.Equal(t, want, errors.As(err, target)) - } - - e1 := api.ErrorType(1) - e2 := api.ErrorType(2) + var target *api.Error - f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(1)}, true) - f(&api.Error{Code: api.ErrorType(1)}, &e1, true) - f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "123"}, true) - f(&api.Error{Code: api.ErrorType(1), Message: "123"}, &api.Error{Code: api.ErrorType(1), Message: "321"}, true) - - f(&api.Error{Code: api.ErrorType(1)}, &api.Error{Code: api.ErrorType(2)}, false) - f(&api.Error{Code: api.ErrorType(1)}, &e2, false) - f(&api.Error{Code: api.ErrorType(1)}, &streaming.Error{}, false) + err := &api.Error{Code: api.ErrorType(1)} + if !errors.As(err, &target) && target.Code == 1 { + t.Error("As not working") + } } func TestInvalidContentType(t *testing.T) { diff --git a/api/streaming_test.go b/api/streaming_test.go index 25228627..489af91f 100644 --- a/api/streaming_test.go +++ b/api/streaming_test.go @@ -1,6 +1,7 @@ package api_test import ( + "errors" "testing" "github.com/SevereCloud/vksdk/api" @@ -112,35 +113,35 @@ func TestVK_StreamingError(t *testing.T) { t.Run("StreamingGetServerURL error", func(t *testing.T) { _, err := vk.StreamingGetServerURL(api.Params{}) - if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { + if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetServerURL error bad %v", err) } }) t.Run("StreamingGetSettings error", func(t *testing.T) { _, err := vk.StreamingGetSettings(api.Params{}) - if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { + if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetSettings error bad %v", err) } }) t.Run("StreamingGetStats error", func(t *testing.T) { _, err := vk.StreamingGetStats(api.Params{}) - if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { + if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetStats error bad %v", err) } }) t.Run("StreamingGetStem error", func(t *testing.T) { _, err := vk.StreamingGetStem(api.Params{}) - if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { + if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetStem error bad %v", err) } }) t.Run("StreamingSetSettings error", func(t *testing.T) { _, err := vk.StreamingSetSettings(api.Params{}) - if e, ok := err.(*api.Error); ok && e.Code == api.ErrAuth { + if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingSetSettings error bad %v", err) } }) diff --git a/streaming/errors.go b/streaming/errors.go index a7ebdbab..fc261fb4 100644 --- a/streaming/errors.go +++ b/streaming/errors.go @@ -51,24 +51,8 @@ func (e Error) Is(target error) bool { return e.Code == t.Code && e.Message == t.Message } - if t, ok := target.(*ErrorType); ok { - return e.Code == *t - } - - return false -} - -// As unwraps its first argument sequentially looking for an error that can -// be assigned to its second argument, which must be a pointer. If it -// succeeds, it performs the assignment and returns true. Otherwise, it -// returns false. -func (e Error) As(target interface{}) bool { - if t, ok := target.(*Error); ok { - return e.Code == t.Code - } - - if t, ok := target.(*ErrorType); ok { - return e.Code == *t + if t, ok := target.(ErrorType); ok { + return e.Code == t } return false diff --git a/streaming/errors_test.go b/streaming/errors_test.go index 1a5793a8..803b7436 100644 --- a/streaming/errors_test.go +++ b/streaming/errors_test.go @@ -27,33 +27,21 @@ func TestError_Is(t *testing.T) { assert.Equal(t, want, errors.Is(err, target)) } - e1 := streaming.ErrorType(1) - e2 := streaming.ErrorType(2) - f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(1)}, true) - f(&streaming.Error{Code: streaming.ErrorType(1)}, &e1, true) + f(&streaming.Error{Code: streaming.ErrorType(1)}, streaming.ErrorType(1), true) f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, true) f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(2)}, false) - f(&streaming.Error{Code: streaming.ErrorType(1)}, &e2, false) + f(&streaming.Error{Code: streaming.ErrorType(1)}, streaming.ErrorType(2), false) f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "321"}, false) f(&streaming.Error{Code: streaming.ErrorType(1)}, &api.Error{}, false) } func TestError_As(t *testing.T) { - f := func(err *streaming.Error, target interface{}, want bool) { - assert.Equal(t, want, errors.As(err, target)) - } - - e1 := streaming.ErrorType(1) - e2 := streaming.ErrorType(2) + var target *streaming.Error - f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(1)}, true) - f(&streaming.Error{Code: streaming.ErrorType(1)}, &e1, true) - f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, true) - f(&streaming.Error{Code: streaming.ErrorType(1), Message: "123"}, &streaming.Error{Code: streaming.ErrorType(1), Message: "321"}, true) - - f(&streaming.Error{Code: streaming.ErrorType(1)}, &streaming.Error{Code: streaming.ErrorType(2)}, false) - f(&streaming.Error{Code: streaming.ErrorType(1)}, &e2, false) - f(&streaming.Error{Code: streaming.ErrorType(1)}, &api.Error{}, false) + err := &streaming.Error{Code: streaming.ErrorType(1)} + if !errors.As(err, &target) && target.Code == 1 { + t.Error("As not working") + } } From 81e053452a05f781d240b50ace2ce84772644332 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 11:41:59 +0300 Subject: [PATCH 076/105] test: fix TestVK_MessagesSendSticker --- api/messages_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/api/messages_test.go b/api/messages_test.go index b7e7d40d..32d58961 100644 --- a/api/messages_test.go +++ b/api/messages_test.go @@ -466,8 +466,8 @@ func TestVK_MessagesSendSticker(t *testing.T) { _, err := vkUser.MessagesSendSticker(api.Params{ "chat_id": chatID, - "random": 0, - "sticker_id": 279, + "random_id": 0, + "sticker_id": 9008, }) noError(t, err) } From ee1a4a8be3e01197285b69ab885b611fe163393c Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 11:42:09 +0300 Subject: [PATCH 077/105] test: fix TestVK_CaptchaForce --- api/api_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/api_test.go b/api/api_test.go index 852b070d..85453c4b 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -301,7 +301,7 @@ func TestVK_CaptchaForce(t *testing.T) { _, err := vkUser.CaptchaForce(api.Params{}) - if errors.Is(err, api.ErrCaptcha) { + if !errors.Is(err, api.ErrCaptcha) { t.Errorf("VK.CaptchaForce() err=%v, want 14", err) } } From 043402675bb03bdeab948137e7b890279f636217 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 12:37:00 +0300 Subject: [PATCH 078/105] fix: ExecuteWithArgs return ExecuteErrors pointer --- api/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/api.go b/api/api.go index 4292528b..807d98ba 100644 --- a/api/api.go +++ b/api/api.go @@ -336,7 +336,7 @@ func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error } if resp.ExecuteErrors != nil { - return resp.ExecuteErrors + return &resp.ExecuteErrors } return err From 80978ea1ac37aa24881287c3f67d7c5a3ce3f065 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 12:49:08 +0300 Subject: [PATCH 079/105] chore: wrapper use pointer for errors --- longpoll-user/v3/objects.go | 48 ++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/longpoll-user/v3/objects.go b/longpoll-user/v3/objects.go index 737478a2..41085dce 100644 --- a/longpoll-user/v3/objects.go +++ b/longpoll-user/v3/objects.go @@ -15,7 +15,7 @@ type MessageFlagsChange struct { func (result *MessageFlagsChange) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "MessageFlagsChange", least: 3, got: len(i)} + return &tooShortArray{structName: "MessageFlagsChange", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -40,7 +40,7 @@ type MessageFlagsSet struct { func (result *MessageFlagsSet) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "MessageFlagsSet", least: 3, got: len(i)} + return &tooShortArray{structName: "MessageFlagsSet", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -65,7 +65,7 @@ type MessageFlagsReset struct { func (result *MessageFlagsReset) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "MessageFlagsReset", least: 3, got: len(i)} + return &tooShortArray{structName: "MessageFlagsReset", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -90,7 +90,7 @@ type NewMessage struct { func (result *NewMessage) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "NewMessage", least: 3, got: len(i)} + return &tooShortArray{structName: "NewMessage", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -119,7 +119,7 @@ type EditMessage struct { func (result *EditMessage) parse(i []interface{}) error { if len(i) < 6 { - return tooShortArray{structName: "EditMessage", least: 6, got: len(i)} + return &tooShortArray{structName: "EditMessage", least: 6, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -167,7 +167,7 @@ type ReadInMessages struct { func (result *ReadInMessages) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "ReadInMessages", least: 3, got: len(i)} + return &tooShortArray{structName: "ReadInMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -191,7 +191,7 @@ type ReadOutMessages struct { func (result *ReadOutMessages) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "ReadOutMessages", least: 3, got: len(i)} + return &tooShortArray{structName: "ReadOutMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -216,7 +216,7 @@ type FriendBecameOnline struct { func (result *FriendBecameOnline) parse(i []interface{}) error { if len(i) < 4 { - return tooShortArray{structName: "FriendBecameOnline", least: 4, got: len(i)} + return &tooShortArray{structName: "FriendBecameOnline", least: 4, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -245,7 +245,7 @@ type FriendBecameOffline struct { func (result *FriendBecameOffline) parse(i []interface{}) error { if len(i) < 4 { - return tooShortArray{structName: "FriendBecameOffline", least: 4, got: len(i)} + return &tooShortArray{structName: "FriendBecameOffline", least: 4, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -273,7 +273,7 @@ type DialogFlagsReset struct { func (result *DialogFlagsReset) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "DialogFlagsReset", least: 3, got: len(i)} + return &tooShortArray{structName: "DialogFlagsReset", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -297,7 +297,7 @@ type DialogFlagsReplace struct { func (result *DialogFlagsReplace) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "DialogFlagsReplace", least: 3, got: len(i)} + return &tooShortArray{structName: "DialogFlagsReplace", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -321,7 +321,7 @@ type DialogsFlagsSet struct { func (result *DialogsFlagsSet) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "DialogsFlagsSet", least: 3, got: len(i)} + return &tooShortArray{structName: "DialogsFlagsSet", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -345,7 +345,7 @@ type DeleteMessages struct { func (result *DeleteMessages) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "DeleteMessages", least: 3, got: len(i)} + return &tooShortArray{structName: "DeleteMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -369,7 +369,7 @@ type RestoreDeletedMessages struct { func (result *RestoreDeletedMessages) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "RestoreDeletedMessages", least: 3, got: len(i)} + return &tooShortArray{structName: "RestoreDeletedMessages", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -394,7 +394,7 @@ type ChatParamsChange struct { func (result *ChatParamsChange) parse(i []interface{}) error { if len(i) < 2 { - return tooShortArray{structName: "ChatParamsChange", least: 2, got: len(i)} + return &tooShortArray{structName: "ChatParamsChange", least: 2, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -421,7 +421,7 @@ type ChatInfoChange struct { func (result *ChatInfoChange) parse(i []interface{}) error { if len(i) < 4 { - return tooShortArray{structName: "ChatInfoChange", least: 4, got: len(i)} + return &tooShortArray{structName: "ChatInfoChange", least: 4, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -449,7 +449,7 @@ type UserTyping struct { func (result *UserTyping) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "UserTyping", least: 3, got: len(i)} + return &tooShortArray{structName: "UserTyping", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -473,7 +473,7 @@ type UserTypingChat struct { func (result *UserTypingChat) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "UserTypingChat", least: 3, got: len(i)} + return &tooShortArray{structName: "UserTypingChat", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -497,7 +497,7 @@ type UsersTyping struct { func (result *UsersTyping) parse(i []interface{}) error { if len(i) < 5 { - return tooShortArray{structName: "UsersTyping", least: 5, got: len(i)} + return &tooShortArray{structName: "UsersTyping", least: 5, got: len(i)} } userIDs, err := interfaceToIDSlice(i[1]) @@ -532,7 +532,7 @@ type UsersRecordingAudioMessage struct { func (result *UsersRecordingAudioMessage) parse(i []interface{}) error { if len(i) < 5 { - return tooShortArray{structName: "UsersRecordingAudioMessage", least: 5, got: len(i)} + return &tooShortArray{structName: "UsersRecordingAudioMessage", least: 5, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -565,7 +565,7 @@ type UserCall struct { func (result *UserCall) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "UserCall", least: 3, got: len(i)} + return &tooShortArray{structName: "UserCall", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -586,7 +586,7 @@ type CounterChange struct { func (result *CounterChange) parse(i []interface{}) error { if len(i) < 2 { - return tooShortArray{structName: "CounterChange", least: 2, got: len(i)} + return &tooShortArray{structName: "CounterChange", least: 2, got: len(i)} } if v, ok := i[1].(float64); ok { @@ -606,7 +606,7 @@ type NotificationSettingsChange struct { // ParseMode8 should be called if ExtendedEvents flag set. func (result *NotificationSettingsChange) parseMode8(i []interface{}) error { if len(i) < 2 { - return tooShortArray{structName: "NotificationSettingsChange", least: 2, got: len(i)} + return &tooShortArray{structName: "NotificationSettingsChange", least: 2, got: len(i)} } v, err := interfaceToStringIntMap(i[1]) @@ -623,7 +623,7 @@ func (result *NotificationSettingsChange) parseMode8(i []interface{}) error { func (result *NotificationSettingsChange) parse(i []interface{}) error { if len(i) < 3 { - return tooShortArray{structName: "NotificationSettingsChange", least: 3, got: len(i)} + return &tooShortArray{structName: "NotificationSettingsChange", least: 3, got: len(i)} } if v, ok := i[1].(float64); ok { From e27132c3d6842ad5ec8bddeee0de06a941f7335c Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 19:22:16 +0300 Subject: [PATCH 080/105] feat: add ErrMarketAlreadyEnabled --- api/errors.go | 1 + 1 file changed, 1 insertion(+) diff --git a/api/errors.go b/api/errors.go index efe2c80e..111d3666 100644 --- a/api/errors.go +++ b/api/errors.go @@ -314,6 +314,7 @@ const ( ErrMarketCartEmpty ErrorType = 1427 // Cart is empty ErrMarketSpecifyDimensions ErrorType = 1429 // Specify width, length, height and weight all together ErrVKPayStatus ErrorType = 1430 // VK Pay status can not be changed + ErrMarketAlreadyEnabled ErrorType = 1431 // Market was already enabled in this group ErrStoryExpired ErrorType = 1600 // Story has already expired ErrStoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy ErrPrettyCardsCardNotFound ErrorType = 1900 // Card not found From 26ea570a9577987709b7a28fe09cb4112a9304fd Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 19:22:44 +0300 Subject: [PATCH 081/105] feat: ErrMarketAlreadyDisabled --- api/errors.go | 1 + 1 file changed, 1 insertion(+) diff --git a/api/errors.go b/api/errors.go index 111d3666..73bb1cfc 100644 --- a/api/errors.go +++ b/api/errors.go @@ -315,6 +315,7 @@ const ( ErrMarketSpecifyDimensions ErrorType = 1429 // Specify width, length, height and weight all together ErrVKPayStatus ErrorType = 1430 // VK Pay status can not be changed ErrMarketAlreadyEnabled ErrorType = 1431 // Market was already enabled in this group + ErrMarketAlreadyDisabled ErrorType = 1432 // Market was already disabled in this group ErrStoryExpired ErrorType = 1600 // Story has already expired ErrStoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy ErrPrettyCardsCardNotFound ErrorType = 1900 // Card not found From 068bfd3f852f398f4a23dd8a94f98f564be5b570 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Tue, 4 Aug 2020 19:48:13 +0300 Subject: [PATCH 082/105] feat: add GroupsToggleMarket method --- api/groups.go | 8 ++++++++ api/groups_test.go | 23 +++++++++++++++++++++++ api/params/groups.go | 39 +++++++++++++++++++++++++++++++++++++++ api/params/groups_test.go | 12 ++++++++++++ 4 files changed, 82 insertions(+) diff --git a/api/groups.go b/api/groups.go index 00638dad..ccb1091c 100644 --- a/api/groups.go +++ b/api/groups.go @@ -698,6 +698,14 @@ func (vk *VK) GroupsTagUpdate(params Params) (response int, err error) { return } +// GroupsToggleMarket method. +// +// https://vk.com/dev/groups.toggleMarket +func (vk *VK) GroupsToggleMarket(params Params) (response int, err error) { + err = vk.RequestUnmarshal("groups.toggleMarket", params, &response) + return +} + // GroupsUnban groups.unban. // // https://vk.com/dev/groups.unban diff --git a/api/groups_test.go b/api/groups_test.go index bd3ca34f..cb166d0f 100644 --- a/api/groups_test.go +++ b/api/groups_test.go @@ -1,6 +1,7 @@ package api_test import ( + "errors" "testing" "github.com/SevereCloud/vksdk/api" @@ -763,6 +764,28 @@ func TestVK_GroupsRemoveUser(t *testing.T) { // TODO: Add test cases. } +func TestVK_GroupsToggleMarket(t *testing.T) { + t.Parallel() + + needUserToken(t) + needGroupToken(t) + + _, err := vkUser.GroupsToggleMarket(api.Params{ + "group_id": vkGroupID, + "state": "none", + }) + if err != nil && !errors.Is(err, api.ErrMarketAlreadyDisabled) { + noError(t, err) + t.FailNow() + } + + _, err = vkUser.GroupsToggleMarket(api.Params{ + "group_id": vkGroupID, + "state": "advanced", + }) + noError(t, err) +} + func TestVK_GroupsSearch(t *testing.T) { t.Parallel() diff --git a/api/params/groups.go b/api/params/groups.go index 309dc91f..9896a1de 100644 --- a/api/params/groups.go +++ b/api/params/groups.go @@ -2666,6 +2666,45 @@ func (b *GroupsTagUpdateBuilder) TagName(v string) *GroupsTagUpdateBuilder { return b } +// GroupsToggleMarketBuilder builder. +// +// https://vk.com/dev/groups.toggleMarket +type GroupsToggleMarketBuilder struct { + api.Params +} + +// NewGroupsToggleMarketBuilder func. +func NewGroupsToggleMarketBuilder() *GroupsToggleMarketBuilder { + return &GroupsToggleMarketBuilder{api.Params{}} +} + +// GroupID parameter. +func (b *GroupsToggleMarketBuilder) GroupID(v int) *GroupsToggleMarketBuilder { + b.Params["group_id"] = v + return b +} + +// GroupMarketState market state. +type GroupMarketState string + +// Possible values. +const ( + GroupMarketNone GroupMarketState = "none" + GroupMarketBasic GroupMarketState = "basic" + GroupMarketAdvanced GroupMarketState = "advanced" +) + +// State parameter. +// +// none +// basic +// advanced +// +func (b *GroupsToggleMarketBuilder) State(v GroupMarketState) *GroupsToggleMarketBuilder { + b.Params["state"] = v + return b +} + // GroupsUnbanBuilder builder. // // https://vk.com/dev/groups.unban diff --git a/api/params/groups_test.go b/api/params/groups_test.go index 14ece6fc..6c9bbc24 100644 --- a/api/params/groups_test.go +++ b/api/params/groups_test.go @@ -965,6 +965,18 @@ func TestGroupsTagUpdateBuilder(t *testing.T) { assert.Equal(t, b.Params["tag_name"], "text") } +func TestGroupsToggleMarketBuilder(t *testing.T) { + t.Parallel() + + b := params.NewGroupsToggleMarketBuilder() + + b.GroupID(1) + b.State("none") + + assert.Equal(t, b.Params["group_id"], 1) + assert.Equal(t, b.Params["state"], params.GroupMarketState("none")) +} + func TestGroupsUnbanBuilder(t *testing.T) { t.Parallel() From 5441cd55df856e9fbe68cb49d3c0d23bba179519 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 5 Aug 2020 22:12:39 +0300 Subject: [PATCH 083/105] feat: events add context --- api/README.md | 2 +- callback/README.md | 8 +- callback/callback.go | 8 +- events/context.go | 17 ++ events/context_test.go | 22 ++ events/events.go | 559 +++++++++++++++++++--------------- events/events_test.go | 526 +++++++++++++++++--------------- {object => events}/handler.go | 191 +++++------- internal/transport.go | 3 + longpoll-bot/README.md | 8 +- longpoll-bot/context.go | 12 + longpoll-bot/context_test.go | 16 + longpoll-bot/longpoll.go | 24 +- longpoll-bot/longpoll_test.go | 13 +- object/handler_test.go | 39 --- object/object.go | 69 ----- 16 files changed, 786 insertions(+), 731 deletions(-) create mode 100644 events/context.go create mode 100644 events/context_test.go rename {object => events}/handler.go (67%) create mode 100644 longpoll-bot/context.go create mode 100644 longpoll-bot/context_test.go delete mode 100644 object/handler_test.go diff --git a/api/README.md b/api/README.md index a92e7c5d..6a2ac6bf 100644 --- a/api/README.md +++ b/api/README.md @@ -3,7 +3,7 @@ [![Documentation](https://godoc.org/github.com/SevereCloud/vksdk/api?status.svg)](https://pkg.go.dev/github.com/SevereCloud/vksdk/api) [![VK](https://img.shields.io/badge/developers-%234a76a8.svg?logo=VK&logoColor=white)](https://vk.com/dev/first_guide) -Данная библиотека поддерживает версию API **5.103**. +Данная библиотека поддерживает версию API **5.122**. ## Запросы diff --git a/callback/README.md b/callback/README.md index 8915c80e..c8a456b5 100644 --- a/callback/README.md +++ b/callback/README.md @@ -14,7 +14,7 @@ ### Версия API -Данная библиотека поддерживает версию API **5.103**. +Данная библиотека поддерживает версию API **5.122**. ### Подтверждение сервера @@ -31,12 +31,12 @@ ### Обработчик событий Для каждого события существует отдельный обработчик, который передает функции -`object` и `groupID`. +`ctx` и `object`. Пример для события `message_new` ```go -cb.MessageNew(func(object object.MessageNewObject, groupID int) { +cb.MessageNew(func(ctx context.Context, object object.MessageNewObject) { ... }) ``` @@ -71,7 +71,7 @@ func main() { cb.ConfirmationKey = "693d0ba9" // cb.ConfirmationKeys[170561776] = "693d0ba9" - cb.MessageNew(func(obj object.MessageNewObject, groupID int) { + cb.MessageNew(func(ctx context.Context, obj object.MessageNewObject) { log.Print(obj.Message.Text) }) diff --git a/callback/callback.go b/callback/callback.go index 2ee0013c..fb8fabc2 100644 --- a/callback/callback.go +++ b/callback/callback.go @@ -6,13 +6,13 @@ See more https://vk.com/dev/callback_api package callback // import "github.com/SevereCloud/vksdk/callback" import ( + "context" "encoding/json" "fmt" "log" "net/http" "github.com/SevereCloud/vksdk/events" - "github.com/SevereCloud/vksdk/object" ) // Callback struct SecretKeys [GroupID]SecretKey. @@ -40,7 +40,7 @@ func NewCallback() *Callback { func (cb *Callback) HandleFunc(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) - var e object.GroupEvent + var e events.GroupEvent if err := decoder.Decode(&e); err != nil { log.Printf("Callback.HandleFunc: %v", err) http.Error(w, "Bad Request", http.StatusBadRequest) @@ -55,7 +55,7 @@ func (cb *Callback) HandleFunc(w http.ResponseWriter, r *http.Request) { } } - if e.Type == object.EventConfirmation { + if e.Type == events.EventConfirmation { if cb.ConfirmationKeys[e.GroupID] != "" { fmt.Fprintf(w, cb.ConfirmationKeys[e.GroupID]) } else { @@ -65,7 +65,7 @@ func (cb *Callback) HandleFunc(w http.ResponseWriter, r *http.Request) { return } - if err := cb.Handler(e); err != nil { + if err := cb.Handler(context.TODO(), e); err != nil { log.Printf("Callback.HandleFunc: %v", err) http.Error(w, "Bad Request", http.StatusBadRequest) diff --git a/events/context.go b/events/context.go new file mode 100644 index 00000000..d81048c2 --- /dev/null +++ b/events/context.go @@ -0,0 +1,17 @@ +package events // import "github.com/SevereCloud/vksdk/events" + +import ( + "context" + + "github.com/SevereCloud/vksdk/internal" +) + +// GroupIDFromContext returns the GroupID from context. +func GroupIDFromContext(ctx context.Context) int { + return ctx.Value(internal.GroupIDKey).(int) +} + +// EventIDFromContext returns the EventID from context. +func EventIDFromContext(ctx context.Context) string { + return ctx.Value(internal.EventIDKey).(string) +} diff --git a/events/context_test.go b/events/context_test.go new file mode 100644 index 00000000..29ea3f0b --- /dev/null +++ b/events/context_test.go @@ -0,0 +1,22 @@ +package events_test + +import ( + "context" + "testing" + + "github.com/SevereCloud/vksdk/events" + "github.com/SevereCloud/vksdk/internal" + "github.com/stretchr/testify/assert" +) + +func TestGroupIDFromContext(t *testing.T) { + const groupID = 123 + ctx := context.WithValue(context.Background(), internal.GroupIDKey, groupID) + assert.Equal(t, groupID, events.GroupIDFromContext(ctx)) +} + +func TestEventIDFromContext(t *testing.T) { + const eventID = "123" + ctx := context.WithValue(context.Background(), internal.EventIDKey, eventID) + assert.Equal(t, eventID, events.EventIDFromContext(ctx)) +} diff --git a/events/events.go b/events/events.go index f370e2bb..cde9c882 100644 --- a/events/events.go +++ b/events/events.go @@ -6,511 +6,580 @@ See more https://vk.com/dev/groups_events package events // import "github.com/SevereCloud/vksdk/events" import ( + "context" "encoding/json" - "github.com/SevereCloud/vksdk/object" + "github.com/SevereCloud/vksdk/internal" ) +// EventType type. +type EventType string + +// EventType list. +const ( + EventConfirmation = "confirmation" + EventMessageNew = "message_new" + EventMessageReply = "message_reply" + EventMessageEdit = "message_edit" + EventMessageAllow = "message_allow" + EventMessageDeny = "message_deny" + EventMessageTypingState = "message_typing_state" + EventMessageEvent = "message_event" + EventPhotoNew = "photo_new" + EventPhotoCommentNew = "photo_comment_new" + EventPhotoCommentEdit = "photo_comment_edit" + EventPhotoCommentRestore = "photo_comment_restore" + EventPhotoCommentDelete = "photo_comment_delete" + EventAudioNew = "audio_new" + EventVideoNew = "video_new" + EventVideoCommentNew = "video_comment_new" + EventVideoCommentEdit = "video_comment_edit" + EventVideoCommentRestore = "video_comment_restore" + EventVideoCommentDelete = "video_comment_delete" + EventWallPostNew = "wall_post_new" + EventWallRepost = "wall_repost" + EventWallReplyNew = "wall_reply_new" + EventWallReplyEdit = "wall_reply_edit" + EventWallReplyRestore = "wall_reply_restore" + EventWallReplyDelete = "wall_reply_delete" + EventBoardPostNew = "board_post_new" + EventBoardPostEdit = "board_post_edit" + EventBoardPostRestore = "board_post_restore" + EventBoardPostDelete = "board_post_delete" + EventMarketCommentNew = "market_comment_new" + EventMarketCommentEdit = "market_comment_edit" + EventMarketCommentRestore = "market_comment_restore" + EventMarketCommentDelete = "market_comment_delete" + EventMarketOrderNew = "market_order_new" + EventMarketOrderEdit = "market_order_edit" + EventGroupLeave = "group_leave" + EventGroupJoin = "group_join" + EventUserBlock = "user_block" + EventUserUnblock = "user_unblock" + EventPollVoteNew = "poll_vote_new" + EventGroupOfficersEdit = "group_officers_edit" + EventGroupChangeSettings = "group_change_settings" + EventGroupChangePhoto = "group_change_photo" + EventVkpayTransaction = "vkpay_transaction" + EventLeadFormsNew = "lead_forms_new" + EventAppPayload = "app_payload" + EventMessageRead = "message_read" + EventLikeAdd = "like_add" + EventLikeRemove = "like_remove" +) + +// GroupEvent struct. +type GroupEvent struct { + Type EventType `json:"type"` + Object json.RawMessage `json:"object"` + GroupID int `json:"group_id"` + EventID string `json:"event_id"` + Secret string `json:"secret"` +} + // FuncList struct. type FuncList struct { - messageNew []object.MessageNewFunc - messageReply []object.MessageReplyFunc - messageEdit []object.MessageEditFunc - messageAllow []object.MessageAllowFunc - messageDeny []object.MessageDenyFunc - messageTypingState []object.MessageTypingStateFunc - messageEvent []object.MessageEventFunc - photoNew []object.PhotoNewFunc - photoCommentNew []object.PhotoCommentNewFunc - photoCommentEdit []object.PhotoCommentEditFunc - photoCommentRestore []object.PhotoCommentRestoreFunc - photoCommentDelete []object.PhotoCommentDeleteFunc - audioNew []object.AudioNewFunc - videoNew []object.VideoNewFunc - videoCommentNew []object.VideoCommentNewFunc - videoCommentEdit []object.VideoCommentEditFunc - videoCommentRestore []object.VideoCommentRestoreFunc - videoCommentDelete []object.VideoCommentDeleteFunc - wallPostNew []object.WallPostNewFunc - wallRepost []object.WallRepostFunc - wallReplyNew []object.WallReplyNewFunc - wallReplyEdit []object.WallReplyEditFunc - wallReplyRestore []object.WallReplyRestoreFunc - wallReplyDelete []object.WallReplyDeleteFunc - boardPostNew []object.BoardPostNewFunc - boardPostEdit []object.BoardPostEditFunc - boardPostRestore []object.BoardPostRestoreFunc - boardPostDelete []object.BoardPostDeleteFunc - marketCommentNew []object.MarketCommentNewFunc - marketCommentEdit []object.MarketCommentEditFunc - marketCommentRestore []object.MarketCommentRestoreFunc - marketCommentDelete []object.MarketCommentDeleteFunc - marketOrderNew []object.MarketOrderNewFunc - marketOrderEdit []object.MarketOrderEditFunc - groupLeave []object.GroupLeaveFunc - groupJoin []object.GroupJoinFunc - userBlock []object.UserBlockFunc - userUnblock []object.UserUnblockFunc - pollVoteNew []object.PollVoteNewFunc - groupOfficersEdit []object.GroupOfficersEditFunc - groupChangeSettings []object.GroupChangeSettingsFunc - groupChangePhoto []object.GroupChangePhotoFunc - vkpayTransaction []object.VkpayTransactionFunc - leadFormsNew []object.LeadFormsNewFunc - appPayload []object.AppPayloadFunc - messageRead []object.MessageReadFunc - likeAdd []object.LikeAddFunc - likeRemove []object.LikeRemoveFunc - special map[string][]func(object.GroupEvent) + messageNew []MessageNewFunc + messageReply []MessageReplyFunc + messageEdit []MessageEditFunc + messageAllow []MessageAllowFunc + messageDeny []MessageDenyFunc + messageTypingState []MessageTypingStateFunc + messageEvent []MessageEventFunc + photoNew []PhotoNewFunc + photoCommentNew []PhotoCommentNewFunc + photoCommentEdit []PhotoCommentEditFunc + photoCommentRestore []PhotoCommentRestoreFunc + photoCommentDelete []PhotoCommentDeleteFunc + audioNew []AudioNewFunc + videoNew []VideoNewFunc + videoCommentNew []VideoCommentNewFunc + videoCommentEdit []VideoCommentEditFunc + videoCommentRestore []VideoCommentRestoreFunc + videoCommentDelete []VideoCommentDeleteFunc + wallPostNew []WallPostNewFunc + wallRepost []WallRepostFunc + wallReplyNew []WallReplyNewFunc + wallReplyEdit []WallReplyEditFunc + wallReplyRestore []WallReplyRestoreFunc + wallReplyDelete []WallReplyDeleteFunc + boardPostNew []BoardPostNewFunc + boardPostEdit []BoardPostEditFunc + boardPostRestore []BoardPostRestoreFunc + boardPostDelete []BoardPostDeleteFunc + marketCommentNew []MarketCommentNewFunc + marketCommentEdit []MarketCommentEditFunc + marketCommentRestore []MarketCommentRestoreFunc + marketCommentDelete []MarketCommentDeleteFunc + marketOrderNew []MarketOrderNewFunc + marketOrderEdit []MarketOrderEditFunc + groupLeave []GroupLeaveFunc + groupJoin []GroupJoinFunc + userBlock []UserBlockFunc + userUnblock []UserUnblockFunc + pollVoteNew []PollVoteNewFunc + groupOfficersEdit []GroupOfficersEditFunc + groupChangeSettings []GroupChangeSettingsFunc + groupChangePhoto []GroupChangePhotoFunc + vkpayTransaction []VkpayTransactionFunc + leadFormsNew []LeadFormsNewFunc + appPayload []AppPayloadFunc + messageRead []MessageReadFunc + likeAdd []LikeAddFunc + likeRemove []LikeRemoveFunc + special map[EventType][]func(context.Context, GroupEvent) } // NewFuncList returns a new FuncList. func NewFuncList() *FuncList { return &FuncList{ - special: make(map[string][]func(object.GroupEvent)), + special: make(map[EventType][]func(context.Context, GroupEvent)), } } // Handler group event handler. -func (fl FuncList) Handler(e object.GroupEvent) error { // nolint:gocyclo +func (fl FuncList) Handler(ctx context.Context, e GroupEvent) error { // nolint:gocyclo + ctx = context.WithValue(ctx, internal.GroupIDKey, e.GroupID) + ctx = context.WithValue(ctx, internal.EventIDKey, e.EventID) + if sliceFunc, ok := fl.special[e.Type]; ok { for _, f := range sliceFunc { - f(e) + f(ctx, e) } } switch e.Type { - case object.EventMessageNew: - var obj object.MessageNewObject + case EventMessageNew: + var obj MessageNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageReply: - var obj object.MessageReplyObject + case EventMessageReply: + var obj MessageReplyObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageReply { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageEdit: - var obj object.MessageEditObject + case EventMessageEdit: + var obj MessageEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageAllow: - var obj object.MessageAllowObject + case EventMessageAllow: + var obj MessageAllowObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageAllow { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageDeny: - var obj object.MessageDenyObject + case EventMessageDeny: + var obj MessageDenyObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageDeny { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageTypingState: // На основе ответа - var obj object.MessageTypingStateObject + case EventMessageTypingState: // На основе ответа + var obj MessageTypingStateObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageTypingState { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageEvent: - var obj object.MessageEventObject + case EventMessageEvent: + var obj MessageEventObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageEvent { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventPhotoNew: - var obj object.PhotoNewObject + case EventPhotoNew: + var obj PhotoNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.photoNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventPhotoCommentNew: - var obj object.PhotoCommentNewObject + case EventPhotoCommentNew: + var obj PhotoCommentNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.photoCommentNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventPhotoCommentEdit: - var obj object.PhotoCommentEditObject + case EventPhotoCommentEdit: + var obj PhotoCommentEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.photoCommentEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventPhotoCommentRestore: - var obj object.PhotoCommentRestoreObject + case EventPhotoCommentRestore: + var obj PhotoCommentRestoreObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.photoCommentRestore { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventPhotoCommentDelete: - var obj object.PhotoCommentDeleteObject + case EventPhotoCommentDelete: + var obj PhotoCommentDeleteObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.photoCommentDelete { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventAudioNew: - var obj object.AudioNewObject + case EventAudioNew: + var obj AudioNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.audioNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventVideoNew: - var obj object.VideoNewObject + case EventVideoNew: + var obj VideoNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.videoNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventVideoCommentNew: - var obj object.VideoCommentNewObject + case EventVideoCommentNew: + var obj VideoCommentNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.videoCommentNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventVideoCommentEdit: - var obj object.VideoCommentEditObject + case EventVideoCommentEdit: + var obj VideoCommentEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.videoCommentEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventVideoCommentRestore: - var obj object.VideoCommentRestoreObject + case EventVideoCommentRestore: + var obj VideoCommentRestoreObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.videoCommentRestore { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventVideoCommentDelete: - var obj object.VideoCommentDeleteObject + case EventVideoCommentDelete: + var obj VideoCommentDeleteObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.videoCommentDelete { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventWallPostNew: - var obj object.WallPostNewObject + case EventWallPostNew: + var obj WallPostNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.wallPostNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventWallRepost: - var obj object.WallRepostObject + case EventWallRepost: + var obj WallRepostObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.wallRepost { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventWallReplyNew: - var obj object.WallReplyNewObject + case EventWallReplyNew: + var obj WallReplyNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.wallReplyNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventWallReplyEdit: - var obj object.WallReplyEditObject + case EventWallReplyEdit: + var obj WallReplyEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.wallReplyEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventWallReplyRestore: - var obj object.WallReplyRestoreObject + case EventWallReplyRestore: + var obj WallReplyRestoreObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.wallReplyRestore { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventWallReplyDelete: - var obj object.WallReplyDeleteObject + case EventWallReplyDelete: + var obj WallReplyDeleteObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.wallReplyDelete { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventBoardPostNew: - var obj object.BoardPostNewObject + case EventBoardPostNew: + var obj BoardPostNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.boardPostNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventBoardPostEdit: - var obj object.BoardPostEditObject + case EventBoardPostEdit: + var obj BoardPostEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.boardPostEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventBoardPostRestore: - var obj object.BoardPostRestoreObject + case EventBoardPostRestore: + var obj BoardPostRestoreObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.boardPostRestore { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventBoardPostDelete: - var obj object.BoardPostDeleteObject + case EventBoardPostDelete: + var obj BoardPostDeleteObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.boardPostDelete { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMarketCommentNew: - var obj object.MarketCommentNewObject + case EventMarketCommentNew: + var obj MarketCommentNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.marketCommentNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMarketCommentEdit: - var obj object.MarketCommentEditObject + case EventMarketCommentEdit: + var obj MarketCommentEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.marketCommentEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMarketCommentRestore: - var obj object.MarketCommentRestoreObject + case EventMarketCommentRestore: + var obj MarketCommentRestoreObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.marketCommentRestore { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMarketCommentDelete: - var obj object.MarketCommentDeleteObject + case EventMarketCommentDelete: + var obj MarketCommentDeleteObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.marketCommentDelete { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMarketOrderNew: - var obj object.MarketOrderNewObject + case EventMarketOrderNew: + var obj MarketOrderNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.marketOrderNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMarketOrderEdit: - var obj object.MarketOrderEditObject + case EventMarketOrderEdit: + var obj MarketOrderEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.marketOrderEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventGroupLeave: - var obj object.GroupLeaveObject + case EventGroupLeave: + var obj GroupLeaveObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.groupLeave { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventGroupJoin: - var obj object.GroupJoinObject + case EventGroupJoin: + var obj GroupJoinObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.groupJoin { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventUserBlock: - var obj object.UserBlockObject + case EventUserBlock: + var obj UserBlockObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.userBlock { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventUserUnblock: - var obj object.UserUnblockObject + case EventUserUnblock: + var obj UserUnblockObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.userUnblock { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventPollVoteNew: - var obj object.PollVoteNewObject + case EventPollVoteNew: + var obj PollVoteNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.pollVoteNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventGroupOfficersEdit: - var obj object.GroupOfficersEditObject + case EventGroupOfficersEdit: + var obj GroupOfficersEditObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.groupOfficersEdit { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventGroupChangeSettings: - var obj object.GroupChangeSettingsObject + case EventGroupChangeSettings: + var obj GroupChangeSettingsObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.groupChangeSettings { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventGroupChangePhoto: - var obj object.GroupChangePhotoObject + case EventGroupChangePhoto: + var obj GroupChangePhotoObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.groupChangePhoto { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventVkpayTransaction: - var obj object.VkpayTransactionObject + case EventVkpayTransaction: + var obj VkpayTransactionObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.vkpayTransaction { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventLeadFormsNew: - var obj object.LeadFormsNewObject + case EventLeadFormsNew: + var obj LeadFormsNewObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.leadFormsNew { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventAppPayload: - var obj object.AppPayloadObject + case EventAppPayload: + var obj AppPayloadObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.appPayload { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventMessageRead: - var obj object.MessageReadObject + case EventMessageRead: + var obj MessageReadObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.messageRead { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventLikeAdd: - var obj object.LikeAddObject + case EventLikeAdd: + var obj LikeAddObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.likeAdd { - f(obj, e.GroupID) + f(ctx, obj) } - case object.EventLikeRemove: - var obj object.LikeRemoveObject + case EventLikeRemove: + var obj LikeRemoveObject if err := json.Unmarshal(e.Object, &obj); err != nil { return err } for _, f := range fl.likeRemove { - f(obj, e.GroupID) + f(ctx, obj) } } @@ -518,240 +587,240 @@ func (fl FuncList) Handler(e object.GroupEvent) error { // nolint:gocyclo } // OnEvent handler. -func (fl *FuncList) OnEvent(eventType string, f func(object.GroupEvent)) { +func (fl *FuncList) OnEvent(eventType EventType, f func(context.Context, GroupEvent)) { if fl.special == nil { - fl.special = make(map[string][]func(object.GroupEvent)) + fl.special = make(map[EventType][]func(context.Context, GroupEvent)) } fl.special[eventType] = append(fl.special[eventType], f) } // MessageNew handler. -func (fl *FuncList) MessageNew(f object.MessageNewFunc) { +func (fl *FuncList) MessageNew(f MessageNewFunc) { fl.messageNew = append(fl.messageNew, f) } // MessageReply handler. -func (fl *FuncList) MessageReply(f object.MessageReplyFunc) { +func (fl *FuncList) MessageReply(f MessageReplyFunc) { fl.messageReply = append(fl.messageReply, f) } // MessageEdit handler. -func (fl *FuncList) MessageEdit(f object.MessageEditFunc) { +func (fl *FuncList) MessageEdit(f MessageEditFunc) { fl.messageEdit = append(fl.messageEdit, f) } // MessageAllow handler. -func (fl *FuncList) MessageAllow(f object.MessageAllowFunc) { +func (fl *FuncList) MessageAllow(f MessageAllowFunc) { fl.messageAllow = append(fl.messageAllow, f) } // MessageDeny handler. -func (fl *FuncList) MessageDeny(f object.MessageDenyFunc) { +func (fl *FuncList) MessageDeny(f MessageDenyFunc) { fl.messageDeny = append(fl.messageDeny, f) } // MessageTypingState handler. -func (fl *FuncList) MessageTypingState(f object.MessageTypingStateFunc) { +func (fl *FuncList) MessageTypingState(f MessageTypingStateFunc) { fl.messageTypingState = append(fl.messageTypingState, f) } // MessageEvent handler. -func (fl *FuncList) MessageEvent(f object.MessageEventFunc) { +func (fl *FuncList) MessageEvent(f MessageEventFunc) { fl.messageEvent = append(fl.messageEvent, f) } // PhotoNew handler. -func (fl *FuncList) PhotoNew(f object.PhotoNewFunc) { +func (fl *FuncList) PhotoNew(f PhotoNewFunc) { fl.photoNew = append(fl.photoNew, f) } // PhotoCommentNew handler. -func (fl *FuncList) PhotoCommentNew(f object.PhotoCommentNewFunc) { +func (fl *FuncList) PhotoCommentNew(f PhotoCommentNewFunc) { fl.photoCommentNew = append(fl.photoCommentNew, f) } // PhotoCommentEdit handler. -func (fl *FuncList) PhotoCommentEdit(f object.PhotoCommentEditFunc) { +func (fl *FuncList) PhotoCommentEdit(f PhotoCommentEditFunc) { fl.photoCommentEdit = append(fl.photoCommentEdit, f) } // PhotoCommentRestore handler. -func (fl *FuncList) PhotoCommentRestore(f object.PhotoCommentRestoreFunc) { +func (fl *FuncList) PhotoCommentRestore(f PhotoCommentRestoreFunc) { fl.photoCommentRestore = append(fl.photoCommentRestore, f) } // PhotoCommentDelete handler. -func (fl *FuncList) PhotoCommentDelete(f object.PhotoCommentDeleteFunc) { +func (fl *FuncList) PhotoCommentDelete(f PhotoCommentDeleteFunc) { fl.photoCommentDelete = append(fl.photoCommentDelete, f) } // AudioNew handler. -func (fl *FuncList) AudioNew(f object.AudioNewFunc) { +func (fl *FuncList) AudioNew(f AudioNewFunc) { fl.audioNew = append(fl.audioNew, f) } // VideoNew handler. -func (fl *FuncList) VideoNew(f object.VideoNewFunc) { +func (fl *FuncList) VideoNew(f VideoNewFunc) { fl.videoNew = append(fl.videoNew, f) } // VideoCommentNew handler. -func (fl *FuncList) VideoCommentNew(f object.VideoCommentNewFunc) { +func (fl *FuncList) VideoCommentNew(f VideoCommentNewFunc) { fl.videoCommentNew = append(fl.videoCommentNew, f) } // VideoCommentEdit handler. -func (fl *FuncList) VideoCommentEdit(f object.VideoCommentEditFunc) { +func (fl *FuncList) VideoCommentEdit(f VideoCommentEditFunc) { fl.videoCommentEdit = append(fl.videoCommentEdit, f) } // VideoCommentRestore handler. -func (fl *FuncList) VideoCommentRestore(f object.VideoCommentRestoreFunc) { +func (fl *FuncList) VideoCommentRestore(f VideoCommentRestoreFunc) { fl.videoCommentRestore = append(fl.videoCommentRestore, f) } // VideoCommentDelete handler. -func (fl *FuncList) VideoCommentDelete(f object.VideoCommentDeleteFunc) { +func (fl *FuncList) VideoCommentDelete(f VideoCommentDeleteFunc) { fl.videoCommentDelete = append(fl.videoCommentDelete, f) } // WallPostNew handler. -func (fl *FuncList) WallPostNew(f object.WallPostNewFunc) { +func (fl *FuncList) WallPostNew(f WallPostNewFunc) { fl.wallPostNew = append(fl.wallPostNew, f) } // WallRepost handler. -func (fl *FuncList) WallRepost(f object.WallRepostFunc) { +func (fl *FuncList) WallRepost(f WallRepostFunc) { fl.wallRepost = append(fl.wallRepost, f) } // WallReplyNew handler. -func (fl *FuncList) WallReplyNew(f object.WallReplyNewFunc) { +func (fl *FuncList) WallReplyNew(f WallReplyNewFunc) { fl.wallReplyNew = append(fl.wallReplyNew, f) } // WallReplyEdit handler. -func (fl *FuncList) WallReplyEdit(f object.WallReplyEditFunc) { +func (fl *FuncList) WallReplyEdit(f WallReplyEditFunc) { fl.wallReplyEdit = append(fl.wallReplyEdit, f) } // WallReplyRestore handler. -func (fl *FuncList) WallReplyRestore(f object.WallReplyRestoreFunc) { +func (fl *FuncList) WallReplyRestore(f WallReplyRestoreFunc) { fl.wallReplyRestore = append(fl.wallReplyRestore, f) } // WallReplyDelete handler. -func (fl *FuncList) WallReplyDelete(f object.WallReplyDeleteFunc) { +func (fl *FuncList) WallReplyDelete(f WallReplyDeleteFunc) { fl.wallReplyDelete = append(fl.wallReplyDelete, f) } // BoardPostNew handler. -func (fl *FuncList) BoardPostNew(f object.BoardPostNewFunc) { +func (fl *FuncList) BoardPostNew(f BoardPostNewFunc) { fl.boardPostNew = append(fl.boardPostNew, f) } // BoardPostEdit handler. -func (fl *FuncList) BoardPostEdit(f object.BoardPostEditFunc) { +func (fl *FuncList) BoardPostEdit(f BoardPostEditFunc) { fl.boardPostEdit = append(fl.boardPostEdit, f) } // BoardPostRestore handler. -func (fl *FuncList) BoardPostRestore(f object.BoardPostRestoreFunc) { +func (fl *FuncList) BoardPostRestore(f BoardPostRestoreFunc) { fl.boardPostRestore = append(fl.boardPostRestore, f) } // BoardPostDelete handler. -func (fl *FuncList) BoardPostDelete(f object.BoardPostDeleteFunc) { +func (fl *FuncList) BoardPostDelete(f BoardPostDeleteFunc) { fl.boardPostDelete = append(fl.boardPostDelete, f) } // MarketCommentNew handler. -func (fl *FuncList) MarketCommentNew(f object.MarketCommentNewFunc) { +func (fl *FuncList) MarketCommentNew(f MarketCommentNewFunc) { fl.marketCommentNew = append(fl.marketCommentNew, f) } // MarketCommentEdit handler. -func (fl *FuncList) MarketCommentEdit(f object.MarketCommentEditFunc) { +func (fl *FuncList) MarketCommentEdit(f MarketCommentEditFunc) { fl.marketCommentEdit = append(fl.marketCommentEdit, f) } // MarketCommentRestore handler. -func (fl *FuncList) MarketCommentRestore(f object.MarketCommentRestoreFunc) { +func (fl *FuncList) MarketCommentRestore(f MarketCommentRestoreFunc) { fl.marketCommentRestore = append(fl.marketCommentRestore, f) } // MarketCommentDelete handler. -func (fl *FuncList) MarketCommentDelete(f object.MarketCommentDeleteFunc) { +func (fl *FuncList) MarketCommentDelete(f MarketCommentDeleteFunc) { fl.marketCommentDelete = append(fl.marketCommentDelete, f) } // GroupLeave handler. -func (fl *FuncList) GroupLeave(f object.GroupLeaveFunc) { +func (fl *FuncList) GroupLeave(f GroupLeaveFunc) { fl.groupLeave = append(fl.groupLeave, f) } // GroupJoin handler. -func (fl *FuncList) GroupJoin(f object.GroupJoinFunc) { +func (fl *FuncList) GroupJoin(f GroupJoinFunc) { fl.groupJoin = append(fl.groupJoin, f) } // UserBlock handler. -func (fl *FuncList) UserBlock(f object.UserBlockFunc) { +func (fl *FuncList) UserBlock(f UserBlockFunc) { fl.userBlock = append(fl.userBlock, f) } // UserUnblock handler. -func (fl *FuncList) UserUnblock(f object.UserUnblockFunc) { +func (fl *FuncList) UserUnblock(f UserUnblockFunc) { fl.userUnblock = append(fl.userUnblock, f) } // PollVoteNew handler. -func (fl *FuncList) PollVoteNew(f object.PollVoteNewFunc) { +func (fl *FuncList) PollVoteNew(f PollVoteNewFunc) { fl.pollVoteNew = append(fl.pollVoteNew, f) } // GroupOfficersEdit handler. -func (fl *FuncList) GroupOfficersEdit(f object.GroupOfficersEditFunc) { +func (fl *FuncList) GroupOfficersEdit(f GroupOfficersEditFunc) { fl.groupOfficersEdit = append(fl.groupOfficersEdit, f) } // GroupChangeSettings handler. -func (fl *FuncList) GroupChangeSettings(f object.GroupChangeSettingsFunc) { +func (fl *FuncList) GroupChangeSettings(f GroupChangeSettingsFunc) { fl.groupChangeSettings = append(fl.groupChangeSettings, f) } // GroupChangePhoto handler. -func (fl *FuncList) GroupChangePhoto(f object.GroupChangePhotoFunc) { +func (fl *FuncList) GroupChangePhoto(f GroupChangePhotoFunc) { fl.groupChangePhoto = append(fl.groupChangePhoto, f) } // VkpayTransaction handler. -func (fl *FuncList) VkpayTransaction(f object.VkpayTransactionFunc) { +func (fl *FuncList) VkpayTransaction(f VkpayTransactionFunc) { fl.vkpayTransaction = append(fl.vkpayTransaction, f) } // LeadFormsNew handler. -func (fl *FuncList) LeadFormsNew(f object.LeadFormsNewFunc) { +func (fl *FuncList) LeadFormsNew(f LeadFormsNewFunc) { fl.leadFormsNew = append(fl.leadFormsNew, f) } // AppPayload handler. -func (fl *FuncList) AppPayload(f object.AppPayloadFunc) { +func (fl *FuncList) AppPayload(f AppPayloadFunc) { fl.appPayload = append(fl.appPayload, f) } // MessageRead handler. -func (fl *FuncList) MessageRead(f object.MessageReadFunc) { +func (fl *FuncList) MessageRead(f MessageReadFunc) { fl.messageRead = append(fl.messageRead, f) } // LikeAdd handler. -func (fl *FuncList) LikeAdd(f object.LikeAddFunc) { +func (fl *FuncList) LikeAdd(f LikeAddFunc) { fl.likeAdd = append(fl.likeAdd, f) } // LikeRemove handler. -func (fl *FuncList) LikeRemove(f object.LikeRemoveFunc) { +func (fl *FuncList) LikeRemove(f LikeRemoveFunc) { fl.likeRemove = append(fl.likeRemove, f) } diff --git a/events/events_test.go b/events/events_test.go index debec6aa..54a31e43 100644 --- a/events/events_test.go +++ b/events/events_test.go @@ -1,12 +1,12 @@ package events_test import ( + "context" "testing" "github.com/stretchr/testify/assert" "github.com/SevereCloud/vksdk/events" - "github.com/SevereCloud/vksdk/object" ) const GID = 123456 @@ -16,23 +16,24 @@ func TestFuncList_HandlerMessageNew(t *testing.T) { fl := events.NewFuncList() - fl.MessageNew(func(obj object.MessageNewObject, groupID int) { + fl.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { t.Helper() + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) assert.NotEmpty(t, obj.Message) }) - f := func(e object.GroupEvent, wantErr bool) { + f := func(e events.GroupEvent, wantErr bool) { t.Helper() - if err := fl.Handler(e); (err != nil) != wantErr { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_new", Object: []byte(`{"message":{"date":1,"from_id":1,"id":1,"peer_id":1,"text":"{}"},"client_info":{}}`), GroupID: GID, @@ -40,15 +41,7 @@ func TestFuncList_HandlerMessageNew(t *testing.T) { false, ) f( - object.GroupEvent{ - Type: "message_new", - Object: []byte(`{"date":1,"from_id":1,"id":1,"peer_id":1,"text":"{}"}`), - GroupID: GID, - }, - false, - ) - f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_new", Object: []byte(""), }, @@ -61,18 +54,19 @@ func TestFuncList_HandlerMessageReply(t *testing.T) { fl := events.NewFuncList() - fl.MessageReply(func(obj object.MessageReplyObject, groupID int) { + fl.MessageReply(func(ctx context.Context, obj events.MessageReplyObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_reply", Object: []byte("{}"), GroupID: GID, @@ -80,7 +74,7 @@ func TestFuncList_HandlerMessageReply(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_reply", Object: []byte(""), }, @@ -93,18 +87,19 @@ func TestFuncList_HandlerMessageEdit(t *testing.T) { fl := events.NewFuncList() - fl.MessageEdit(func(obj object.MessageEditObject, groupID int) { + fl.MessageEdit(func(ctx context.Context, obj events.MessageEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_edit", Object: []byte("{}"), GroupID: GID, @@ -112,7 +107,7 @@ func TestFuncList_HandlerMessageEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_edit", Object: []byte(""), }, @@ -125,18 +120,19 @@ func TestFuncList_HandlerMessageAllow(t *testing.T) { fl := events.NewFuncList() - fl.MessageAllow(func(obj object.MessageAllowObject, groupID int) { + fl.MessageAllow(func(ctx context.Context, obj events.MessageAllowObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_allow", Object: []byte("{}"), GroupID: GID, @@ -144,7 +140,7 @@ func TestFuncList_HandlerMessageAllow(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_allow", Object: []byte(""), }, @@ -157,18 +153,19 @@ func TestFuncList_HandlerMessageDeny(t *testing.T) { fl := events.NewFuncList() - fl.MessageDeny(func(obj object.MessageDenyObject, groupID int) { + fl.MessageDeny(func(ctx context.Context, obj events.MessageDenyObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_deny", Object: []byte("{}"), GroupID: GID, @@ -176,7 +173,7 @@ func TestFuncList_HandlerMessageDeny(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_deny", Object: []byte(""), }, @@ -189,18 +186,19 @@ func TestFuncList_HandlerMessageTypingState(t *testing.T) { fl := events.NewFuncList() - fl.MessageTypingState(func(obj object.MessageTypingStateObject, groupID int) { + fl.MessageTypingState(func(ctx context.Context, obj events.MessageTypingStateObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_typing_state", Object: []byte("{}"), GroupID: GID, @@ -208,7 +206,7 @@ func TestFuncList_HandlerMessageTypingState(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_typing_state", Object: []byte(""), }, @@ -221,18 +219,19 @@ func TestFuncList_HandlerMessageEvent(t *testing.T) { fl := events.NewFuncList() - fl.MessageEvent(func(obj object.MessageEventObject, groupID int) { + fl.MessageEvent(func(ctx context.Context, obj events.MessageEventObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_event", Object: []byte("{}"), GroupID: GID, @@ -240,7 +239,7 @@ func TestFuncList_HandlerMessageEvent(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_event", Object: []byte(""), }, @@ -253,18 +252,19 @@ func TestFuncList_HandlerPhotoNew(t *testing.T) { fl := events.NewFuncList() - fl.PhotoNew(func(obj object.PhotoNewObject, groupID int) { + fl.PhotoNew(func(ctx context.Context, obj events.PhotoNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_new", Object: []byte("{}"), GroupID: GID, @@ -272,7 +272,7 @@ func TestFuncList_HandlerPhotoNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_new", Object: []byte(""), }, @@ -285,18 +285,19 @@ func TestFuncList_HandlerPhotoCommentNew(t *testing.T) { fl := events.NewFuncList() - fl.PhotoCommentNew(func(obj object.PhotoCommentNewObject, groupID int) { + fl.PhotoCommentNew(func(ctx context.Context, obj events.PhotoCommentNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_new", Object: []byte("{}"), GroupID: GID, @@ -304,7 +305,7 @@ func TestFuncList_HandlerPhotoCommentNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_new", Object: []byte(""), }, @@ -317,18 +318,19 @@ func TestFuncList_HandlerPhotoCommentEdit(t *testing.T) { fl := events.NewFuncList() - fl.PhotoCommentEdit(func(obj object.PhotoCommentEditObject, groupID int) { + fl.PhotoCommentEdit(func(ctx context.Context, obj events.PhotoCommentEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_edit", Object: []byte("{}"), GroupID: GID, @@ -336,7 +338,7 @@ func TestFuncList_HandlerPhotoCommentEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_edit", Object: []byte(""), }, @@ -349,18 +351,19 @@ func TestFuncList_HandlerPhotoCommentRestore(t *testing.T) { fl := events.NewFuncList() - fl.PhotoCommentRestore(func(obj object.PhotoCommentRestoreObject, groupID int) { + fl.PhotoCommentRestore(func(ctx context.Context, obj events.PhotoCommentRestoreObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_restore", Object: []byte("{}"), GroupID: GID, @@ -368,7 +371,7 @@ func TestFuncList_HandlerPhotoCommentRestore(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_restore", Object: []byte(""), }, @@ -381,18 +384,19 @@ func TestFuncList_HandlerPhotoCommentDelete(t *testing.T) { fl := events.NewFuncList() - fl.PhotoCommentDelete(func(obj object.PhotoCommentDeleteObject, groupID int) { + fl.PhotoCommentDelete(func(ctx context.Context, obj events.PhotoCommentDeleteObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_delete", Object: []byte("{}"), GroupID: GID, @@ -400,7 +404,7 @@ func TestFuncList_HandlerPhotoCommentDelete(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "photo_comment_delete", Object: []byte(""), }, @@ -413,18 +417,19 @@ func TestFuncList_HandlerAudioNew(t *testing.T) { fl := events.NewFuncList() - fl.AudioNew(func(obj object.AudioNewObject, groupID int) { + fl.AudioNew(func(ctx context.Context, obj events.AudioNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "audio_new", Object: []byte("{}"), GroupID: GID, @@ -432,7 +437,7 @@ func TestFuncList_HandlerAudioNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "audio_new", Object: []byte(""), }, @@ -445,18 +450,19 @@ func TestFuncList_HandlerVideoNew(t *testing.T) { fl := events.NewFuncList() - fl.VideoNew(func(obj object.VideoNewObject, groupID int) { + fl.VideoNew(func(ctx context.Context, obj events.VideoNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_new", Object: []byte("{}"), GroupID: GID, @@ -464,7 +470,7 @@ func TestFuncList_HandlerVideoNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_new", Object: []byte(""), }, @@ -477,18 +483,19 @@ func TestFuncList_HandlerVideoCommentNew(t *testing.T) { fl := events.NewFuncList() - fl.VideoCommentNew(func(obj object.VideoCommentNewObject, groupID int) { + fl.VideoCommentNew(func(ctx context.Context, obj events.VideoCommentNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_new", Object: []byte("{}"), GroupID: GID, @@ -496,7 +503,7 @@ func TestFuncList_HandlerVideoCommentNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_new", Object: []byte(""), }, @@ -509,18 +516,19 @@ func TestFuncList_HandlerVideoCommentEdit(t *testing.T) { fl := events.NewFuncList() - fl.VideoCommentEdit(func(obj object.VideoCommentEditObject, groupID int) { + fl.VideoCommentEdit(func(ctx context.Context, obj events.VideoCommentEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_edit", Object: []byte("{}"), GroupID: GID, @@ -528,7 +536,7 @@ func TestFuncList_HandlerVideoCommentEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_edit", Object: []byte(""), }, @@ -541,18 +549,19 @@ func TestFuncList_HandlerVideoCommentRestore(t *testing.T) { fl := events.NewFuncList() - fl.VideoCommentRestore(func(obj object.VideoCommentRestoreObject, groupID int) { + fl.VideoCommentRestore(func(ctx context.Context, obj events.VideoCommentRestoreObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_restore", Object: []byte("{}"), GroupID: GID, @@ -560,7 +569,7 @@ func TestFuncList_HandlerVideoCommentRestore(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_restore", Object: []byte(""), }, @@ -573,18 +582,19 @@ func TestFuncList_HandlerVideoCommentDelete(t *testing.T) { fl := events.NewFuncList() - fl.VideoCommentDelete(func(obj object.VideoCommentDeleteObject, groupID int) { + fl.VideoCommentDelete(func(ctx context.Context, obj events.VideoCommentDeleteObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_delete", Object: []byte("{}"), GroupID: GID, @@ -592,7 +602,7 @@ func TestFuncList_HandlerVideoCommentDelete(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "video_comment_delete", Object: []byte(""), }, @@ -605,18 +615,19 @@ func TestFuncList_HandlerWallPostNew(t *testing.T) { fl := events.NewFuncList() - fl.WallPostNew(func(obj object.WallPostNewObject, groupID int) { + fl.WallPostNew(func(ctx context.Context, obj events.WallPostNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_post_new", Object: []byte("{}"), GroupID: GID, @@ -624,7 +635,7 @@ func TestFuncList_HandlerWallPostNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_post_new", Object: []byte(""), }, @@ -637,18 +648,19 @@ func TestFuncList_HandlerWallRepost(t *testing.T) { fl := events.NewFuncList() - fl.WallRepost(func(obj object.WallRepostObject, groupID int) { + fl.WallRepost(func(ctx context.Context, obj events.WallRepostObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_repost", Object: []byte("{}"), GroupID: GID, @@ -656,7 +668,7 @@ func TestFuncList_HandlerWallRepost(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_repost", Object: []byte(""), }, @@ -669,18 +681,19 @@ func TestFuncList_HandlerWallReplyNew(t *testing.T) { fl := events.NewFuncList() - fl.WallReplyNew(func(obj object.WallReplyNewObject, groupID int) { + fl.WallReplyNew(func(ctx context.Context, obj events.WallReplyNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_new", Object: []byte("{}"), GroupID: GID, @@ -688,7 +701,7 @@ func TestFuncList_HandlerWallReplyNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_new", Object: []byte(""), }, @@ -701,18 +714,19 @@ func TestFuncList_HandlerWallReplyEdit(t *testing.T) { fl := events.NewFuncList() - fl.WallReplyEdit(func(obj object.WallReplyEditObject, groupID int) { + fl.WallReplyEdit(func(ctx context.Context, obj events.WallReplyEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_edit", Object: []byte("{}"), GroupID: GID, @@ -720,7 +734,7 @@ func TestFuncList_HandlerWallReplyEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_edit", Object: []byte(""), }, @@ -733,18 +747,19 @@ func TestFuncList_HandlerWallReplyRestore(t *testing.T) { fl := events.NewFuncList() - fl.WallReplyRestore(func(obj object.WallReplyRestoreObject, groupID int) { + fl.WallReplyRestore(func(ctx context.Context, obj events.WallReplyRestoreObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_restore", Object: []byte("{}"), GroupID: GID, @@ -752,7 +767,7 @@ func TestFuncList_HandlerWallReplyRestore(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_restore", Object: []byte(""), }, @@ -765,18 +780,19 @@ func TestFuncList_HandlerWallReplyDelete(t *testing.T) { fl := events.NewFuncList() - fl.WallReplyDelete(func(obj object.WallReplyDeleteObject, groupID int) { + fl.WallReplyDelete(func(ctx context.Context, obj events.WallReplyDeleteObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_delete", Object: []byte("{}"), GroupID: GID, @@ -784,7 +800,7 @@ func TestFuncList_HandlerWallReplyDelete(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wall_reply_delete", Object: []byte(""), }, @@ -797,18 +813,19 @@ func TestFuncList_HandlerBoardPostNew(t *testing.T) { fl := events.NewFuncList() - fl.BoardPostNew(func(obj object.BoardPostNewObject, groupID int) { + fl.BoardPostNew(func(ctx context.Context, obj events.BoardPostNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_new", Object: []byte("{}"), GroupID: GID, @@ -816,7 +833,7 @@ func TestFuncList_HandlerBoardPostNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_new", Object: []byte(""), }, @@ -829,18 +846,19 @@ func TestFuncList_HandlerBoardPostEdit(t *testing.T) { fl := events.NewFuncList() - fl.BoardPostEdit(func(obj object.BoardPostEditObject, groupID int) { + fl.BoardPostEdit(func(ctx context.Context, obj events.BoardPostEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_edit", Object: []byte("{}"), GroupID: GID, @@ -848,7 +866,7 @@ func TestFuncList_HandlerBoardPostEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_edit", Object: []byte(""), }, @@ -861,18 +879,19 @@ func TestFuncList_HandlerBoardPostRestore(t *testing.T) { fl := events.NewFuncList() - fl.BoardPostRestore(func(obj object.BoardPostRestoreObject, groupID int) { + fl.BoardPostRestore(func(ctx context.Context, obj events.BoardPostRestoreObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_restore", Object: []byte("{}"), GroupID: GID, @@ -880,7 +899,7 @@ func TestFuncList_HandlerBoardPostRestore(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_restore", Object: []byte(""), }, @@ -893,18 +912,19 @@ func TestFuncList_HandlerBoardPostDelete(t *testing.T) { fl := events.NewFuncList() - fl.BoardPostDelete(func(obj object.BoardPostDeleteObject, groupID int) { + fl.BoardPostDelete(func(ctx context.Context, obj events.BoardPostDeleteObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_delete", Object: []byte("{}"), GroupID: GID, @@ -912,7 +932,7 @@ func TestFuncList_HandlerBoardPostDelete(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "board_post_delete", Object: []byte(""), }, @@ -925,18 +945,19 @@ func TestFuncList_HandlerMarketCommentNew(t *testing.T) { fl := events.NewFuncList() - fl.MarketCommentNew(func(obj object.MarketCommentNewObject, groupID int) { + fl.MarketCommentNew(func(ctx context.Context, obj events.MarketCommentNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_new", Object: []byte("{}"), GroupID: GID, @@ -944,7 +965,7 @@ func TestFuncList_HandlerMarketCommentNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_new", Object: []byte(""), }, @@ -957,18 +978,19 @@ func TestFuncList_HandlerMarketCommentEdit(t *testing.T) { fl := events.NewFuncList() - fl.MarketCommentEdit(func(obj object.MarketCommentEditObject, groupID int) { + fl.MarketCommentEdit(func(ctx context.Context, obj events.MarketCommentEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_edit", Object: []byte("{}"), GroupID: GID, @@ -976,7 +998,7 @@ func TestFuncList_HandlerMarketCommentEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_edit", Object: []byte(""), }, @@ -989,18 +1011,19 @@ func TestFuncList_HandlerMarketCommentRestore(t *testing.T) { fl := events.NewFuncList() - fl.MarketCommentRestore(func(obj object.MarketCommentRestoreObject, groupID int) { + fl.MarketCommentRestore(func(ctx context.Context, obj events.MarketCommentRestoreObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_restore", Object: []byte("{}"), GroupID: GID, @@ -1008,7 +1031,7 @@ func TestFuncList_HandlerMarketCommentRestore(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_restore", Object: []byte(""), }, @@ -1021,18 +1044,19 @@ func TestFuncList_HandlerMarketCommentDelete(t *testing.T) { fl := events.NewFuncList() - fl.MarketCommentDelete(func(obj object.MarketCommentDeleteObject, groupID int) { + fl.MarketCommentDelete(func(ctx context.Context, obj events.MarketCommentDeleteObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_delete", Object: []byte("{}"), GroupID: GID, @@ -1040,7 +1064,7 @@ func TestFuncList_HandlerMarketCommentDelete(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "market_comment_delete", Object: []byte(""), }, @@ -1053,18 +1077,19 @@ func TestFuncList_HandlerGroupLeave(t *testing.T) { fl := events.NewFuncList() - fl.GroupLeave(func(obj object.GroupLeaveObject, groupID int) { + fl.GroupLeave(func(ctx context.Context, obj events.GroupLeaveObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_leave", Object: []byte("{}"), GroupID: GID, @@ -1072,7 +1097,7 @@ func TestFuncList_HandlerGroupLeave(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_leave", Object: []byte(""), }, @@ -1085,18 +1110,19 @@ func TestFuncList_HandlerGroupJoin(t *testing.T) { fl := events.NewFuncList() - fl.GroupJoin(func(obj object.GroupJoinObject, groupID int) { + fl.GroupJoin(func(ctx context.Context, obj events.GroupJoinObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_join", Object: []byte("{}"), GroupID: GID, @@ -1104,7 +1130,7 @@ func TestFuncList_HandlerGroupJoin(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_join", Object: []byte(""), }, @@ -1117,18 +1143,19 @@ func TestFuncList_HandlerUserBlock(t *testing.T) { fl := events.NewFuncList() - fl.UserBlock(func(obj object.UserBlockObject, groupID int) { + fl.UserBlock(func(ctx context.Context, obj events.UserBlockObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "user_block", Object: []byte("{}"), GroupID: GID, @@ -1136,7 +1163,7 @@ func TestFuncList_HandlerUserBlock(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "user_block", Object: []byte(""), }, @@ -1149,18 +1176,19 @@ func TestFuncList_HandlerUserUnblock(t *testing.T) { fl := events.NewFuncList() - fl.UserUnblock(func(obj object.UserUnblockObject, groupID int) { + fl.UserUnblock(func(ctx context.Context, obj events.UserUnblockObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "user_unblock", Object: []byte("{}"), GroupID: GID, @@ -1168,7 +1196,7 @@ func TestFuncList_HandlerUserUnblock(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "user_unblock", Object: []byte(""), }, @@ -1181,18 +1209,19 @@ func TestFuncList_HandlerPollVoteNew(t *testing.T) { fl := events.NewFuncList() - fl.PollVoteNew(func(obj object.PollVoteNewObject, groupID int) { + fl.PollVoteNew(func(ctx context.Context, obj events.PollVoteNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "poll_vote_new", Object: []byte("{}"), GroupID: GID, @@ -1200,7 +1229,7 @@ func TestFuncList_HandlerPollVoteNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "poll_vote_new", Object: []byte(""), }, @@ -1213,18 +1242,19 @@ func TestFuncList_HandlerGroupOfficersEdit(t *testing.T) { fl := events.NewFuncList() - fl.GroupOfficersEdit(func(obj object.GroupOfficersEditObject, groupID int) { + fl.GroupOfficersEdit(func(ctx context.Context, obj events.GroupOfficersEditObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_officers_edit", Object: []byte("{}"), GroupID: GID, @@ -1232,7 +1262,7 @@ func TestFuncList_HandlerGroupOfficersEdit(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_officers_edit", Object: []byte(""), }, @@ -1245,18 +1275,19 @@ func TestFuncList_HandlerGroupChangeSettings(t *testing.T) { fl := events.NewFuncList() - fl.GroupChangeSettings(func(obj object.GroupChangeSettingsObject, groupID int) { + fl.GroupChangeSettings(func(ctx context.Context, obj events.GroupChangeSettingsObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_change_settings", Object: []byte("{}"), GroupID: GID, @@ -1264,7 +1295,7 @@ func TestFuncList_HandlerGroupChangeSettings(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_change_settings", Object: []byte(""), }, @@ -1277,18 +1308,19 @@ func TestFuncList_HandlerGroupChangePhoto(t *testing.T) { fl := events.NewFuncList() - fl.GroupChangePhoto(func(obj object.GroupChangePhotoObject, groupID int) { + fl.GroupChangePhoto(func(ctx context.Context, obj events.GroupChangePhotoObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_change_photo", Object: []byte("{}"), GroupID: GID, @@ -1296,7 +1328,7 @@ func TestFuncList_HandlerGroupChangePhoto(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "group_change_photo", Object: []byte(""), }, @@ -1309,18 +1341,19 @@ func TestFuncList_HandlerVkpayTransaction(t *testing.T) { fl := events.NewFuncList() - fl.VkpayTransaction(func(obj object.VkpayTransactionObject, groupID int) { + fl.VkpayTransaction(func(ctx context.Context, obj events.VkpayTransactionObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "vkpay_transaction", Object: []byte("{}"), GroupID: GID, @@ -1328,7 +1361,7 @@ func TestFuncList_HandlerVkpayTransaction(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "vkpay_transaction", Object: []byte(""), }, @@ -1341,18 +1374,19 @@ func TestFuncList_HandlerLeadFormsNew(t *testing.T) { fl := events.NewFuncList() - fl.LeadFormsNew(func(obj object.LeadFormsNewObject, groupID int) { + fl.LeadFormsNew(func(ctx context.Context, obj events.LeadFormsNewObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "lead_forms_new", Object: []byte("{}"), GroupID: GID, @@ -1360,7 +1394,7 @@ func TestFuncList_HandlerLeadFormsNew(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "lead_forms_new", Object: []byte(""), }, @@ -1373,18 +1407,19 @@ func TestFuncList_HandlerAppPayload(t *testing.T) { fl := events.NewFuncList() - fl.AppPayload(func(obj object.AppPayloadObject, groupID int) { + fl.AppPayload(func(ctx context.Context, obj events.AppPayloadObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "app_payload", Object: []byte(`{"user_id":117253521,"app_id":6703670,"payload":"{\"foo\":\"bar\"}"}`), GroupID: GID, @@ -1392,7 +1427,7 @@ func TestFuncList_HandlerAppPayload(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "app_payload", Object: []byte(""), }, @@ -1405,18 +1440,19 @@ func TestFuncList_HandlerMessageRead(t *testing.T) { fl := events.NewFuncList() - fl.MessageRead(func(obj object.MessageReadObject, groupID int) { + fl.MessageRead(func(ctx context.Context, obj events.MessageReadObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_read", Object: []byte(`{"from_id":1,"peer_id":1,"read_message_id":1}`), GroupID: GID, @@ -1424,7 +1460,7 @@ func TestFuncList_HandlerMessageRead(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "message_read", Object: []byte(""), }, @@ -1437,18 +1473,19 @@ func TestFuncList_HandlerLikeAdd(t *testing.T) { fl := events.NewFuncList() - fl.LikeAdd(func(obj object.LikeAddObject, groupID int) { + fl.LikeAdd(func(ctx context.Context, obj events.LikeAddObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "like_add", Object: []byte(`{"liker_id": 574423462,"object_type": "photo","object_owner_id": -178044536,"object_id": 457242474,"thread_reply_id": 0}`), GroupID: GID, @@ -1456,7 +1493,7 @@ func TestFuncList_HandlerLikeAdd(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "like_add", Object: []byte(""), }, @@ -1469,18 +1506,19 @@ func TestFuncList_HandlerLikeRemove(t *testing.T) { fl := events.NewFuncList() - fl.LikeRemove(func(obj object.LikeRemoveObject, groupID int) { + fl.LikeRemove(func(ctx context.Context, obj events.LikeRemoveObject) { + groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "like_remove", Object: []byte(`{"liker_id": 574423462,"object_type": "photo","object_owner_id": -178044536,"object_id": 457242474,"thread_reply_id": 0}`), GroupID: GID, @@ -1488,7 +1526,7 @@ func TestFuncList_HandlerLikeRemove(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "like_remove", Object: []byte(""), }, @@ -1501,18 +1539,18 @@ func TestFuncList_OnEvent(t *testing.T) { var fl events.FuncList - fl.OnEvent("wtf_event", func(e object.GroupEvent) { + fl.OnEvent("wtf_event", func(_ context.Context, e events.GroupEvent) { assert.NotEmpty(t, e) }) - f := func(e object.GroupEvent, wantErr bool) { - if err := fl.Handler(e); (err != nil) != wantErr { + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) } } f( - object.GroupEvent{ + events.GroupEvent{ Type: "wtf_event", Object: []byte(`{"from_id":1,"peer_id":1,"read_message_id":1}`), GroupID: GID, @@ -1520,7 +1558,7 @@ func TestFuncList_OnEvent(t *testing.T) { false, ) f( - object.GroupEvent{ + events.GroupEvent{ Type: "wtf_event", Object: []byte(""), }, diff --git a/object/handler.go b/events/handler.go similarity index 67% rename from object/handler.go rename to events/handler.go index e087d860..31902ac7 100644 --- a/object/handler.go +++ b/events/handler.go @@ -1,58 +1,34 @@ -package object // import "github.com/SevereCloud/vksdk/object" +package events // import "github.com/SevereCloud/vksdk/events" import ( - "bytes" - "encoding/json" + "context" + + "github.com/SevereCloud/vksdk/object" ) // MessageNewFunc func. -type MessageNewFunc func(MessageNewObject, int) +type MessageNewFunc func(context.Context, MessageNewObject) // MessageNewObject struct. type MessageNewObject struct { - Message MessagesMessage `json:"message"` - ClientInfo ClientInfo `json:"client_info"` -} - -// UnmarshalJSON need for support api version < 5.103. -// -// To unmarshal JSON into a value implementing the Unmarshaler interface, -// Unmarshal calls that value's UnmarshalJSON method. -// See more https://golang.org/pkg/encoding/json/#Unmarshal -func (obj *MessageNewObject) UnmarshalJSON(data []byte) (err error) { - // The renamed type is necessary to avoid loops - type renamedMessageNewObject MessageNewObject - - var renamedObj renamedMessageNewObject - - if bytes.Contains(data, []byte(`"message":`)) { - // v >= 5.103 - err = json.Unmarshal(data, &renamedObj) - } else { - // Support v < 5.103 - err = json.Unmarshal(data, &renamedObj.Message) - } - - obj.Message = renamedObj.Message - obj.ClientInfo = renamedObj.ClientInfo - - return + Message object.MessagesMessage `json:"message"` + ClientInfo object.ClientInfo `json:"client_info"` } // MessageReplyFunc func. -type MessageReplyFunc func(MessageReplyObject, int) +type MessageReplyFunc func(context.Context, MessageReplyObject) // MessageReplyObject struct. -type MessageReplyObject MessagesMessage +type MessageReplyObject object.MessagesMessage // MessageEditFunc func. -type MessageEditFunc func(MessageEditObject, int) +type MessageEditFunc func(context.Context, MessageEditObject) // MessageEditObject struct. -type MessageEditObject MessagesMessage +type MessageEditObject object.MessagesMessage // MessageAllowFunc func. -type MessageAllowFunc func(MessageAllowObject, int) +type MessageAllowFunc func(context.Context, MessageAllowObject) // MessageAllowObject struct. type MessageAllowObject struct { @@ -61,7 +37,7 @@ type MessageAllowObject struct { } // MessageDenyFunc func. -type MessageDenyFunc func(MessageDenyObject, int) +type MessageDenyFunc func(context.Context, MessageDenyObject) // MessageDenyObject struct. type MessageDenyObject struct { @@ -69,7 +45,7 @@ type MessageDenyObject struct { } // MessageTypingStateFunc func. -type MessageTypingStateFunc func(MessageTypingStateObject, int) +type MessageTypingStateFunc func(context.Context, MessageTypingStateObject) // MessageTypingStateObject struct. type MessageTypingStateObject struct { @@ -79,7 +55,7 @@ type MessageTypingStateObject struct { } // MessageEventFunc func. -type MessageEventFunc func(MessageEventObject, int) +type MessageEventFunc func(context.Context, MessageEventObject) // MessageEventObject struct. type MessageEventObject struct { @@ -91,31 +67,31 @@ type MessageEventObject struct { } // PhotoNewFunc func. -type PhotoNewFunc func(PhotoNewObject, int) +type PhotoNewFunc func(context.Context, PhotoNewObject) // PhotoNewObject struct. -type PhotoNewObject PhotosPhoto +type PhotoNewObject object.PhotosPhoto // PhotoCommentNewFunc func. -type PhotoCommentNewFunc func(PhotoCommentNewObject, int) +type PhotoCommentNewFunc func(context.Context, PhotoCommentNewObject) // PhotoCommentNewObject struct. -type PhotoCommentNewObject WallWallComment +type PhotoCommentNewObject object.WallWallComment // PhotoCommentEditFunc func. -type PhotoCommentEditFunc func(PhotoCommentEditObject, int) +type PhotoCommentEditFunc func(context.Context, PhotoCommentEditObject) // PhotoCommentEditObject struct. -type PhotoCommentEditObject WallWallComment +type PhotoCommentEditObject object.WallWallComment // PhotoCommentRestoreFunc func. -type PhotoCommentRestoreFunc func(PhotoCommentRestoreObject, int) +type PhotoCommentRestoreFunc func(context.Context, PhotoCommentRestoreObject) // PhotoCommentRestoreObject struct. -type PhotoCommentRestoreObject WallWallComment +type PhotoCommentRestoreObject object.WallWallComment // PhotoCommentDeleteFunc func. -type PhotoCommentDeleteFunc func(PhotoCommentDeleteObject, int) +type PhotoCommentDeleteFunc func(context.Context, PhotoCommentDeleteObject) // PhotoCommentDeleteObject struct. type PhotoCommentDeleteObject struct { @@ -127,37 +103,37 @@ type PhotoCommentDeleteObject struct { } // AudioNewFunc func. -type AudioNewFunc func(AudioNewObject, int) +type AudioNewFunc func(context.Context, AudioNewObject) // AudioNewObject struct. -type AudioNewObject AudioAudio +type AudioNewObject object.AudioAudio // VideoNewFunc func. -type VideoNewFunc func(VideoNewObject, int) +type VideoNewFunc func(context.Context, VideoNewObject) // VideoNewObject struct. -type VideoNewObject VideoVideo +type VideoNewObject object.VideoVideo // VideoCommentNewFunc func. -type VideoCommentNewFunc func(VideoCommentNewObject, int) +type VideoCommentNewFunc func(context.Context, VideoCommentNewObject) // VideoCommentNewObject struct. -type VideoCommentNewObject WallWallComment +type VideoCommentNewObject object.WallWallComment // VideoCommentEditFunc func. -type VideoCommentEditFunc func(VideoCommentEditObject, int) +type VideoCommentEditFunc func(context.Context, VideoCommentEditObject) // VideoCommentEditObject struct. -type VideoCommentEditObject WallWallComment +type VideoCommentEditObject object.WallWallComment // VideoCommentRestoreFunc func. -type VideoCommentRestoreFunc func(VideoCommentRestoreObject, int) +type VideoCommentRestoreFunc func(context.Context, VideoCommentRestoreObject) // VideoCommentRestoreObject struct. -type VideoCommentRestoreObject WallWallComment +type VideoCommentRestoreObject object.WallWallComment // VideoCommentDeleteFunc func. -type VideoCommentDeleteFunc func(VideoCommentDeleteObject, int) +type VideoCommentDeleteFunc func(context.Context, VideoCommentDeleteObject) // VideoCommentDeleteObject struct. type VideoCommentDeleteObject struct { @@ -169,37 +145,37 @@ type VideoCommentDeleteObject struct { } // WallPostNewFunc func. -type WallPostNewFunc func(WallPostNewObject, int) +type WallPostNewFunc func(context.Context, WallPostNewObject) // WallPostNewObject struct. -type WallPostNewObject WallWallpost +type WallPostNewObject object.WallWallpost // WallRepostFunc func. -type WallRepostFunc func(WallRepostObject, int) +type WallRepostFunc func(context.Context, WallRepostObject) // WallRepostObject struct. -type WallRepostObject WallWallpost +type WallRepostObject object.WallWallpost // WallReplyNewFunc func. -type WallReplyNewFunc func(WallReplyNewObject, int) +type WallReplyNewFunc func(context.Context, WallReplyNewObject) // WallReplyNewObject struct. -type WallReplyNewObject WallWallComment +type WallReplyNewObject object.WallWallComment // WallReplyEditFunc func. -type WallReplyEditFunc func(WallReplyEditObject, int) +type WallReplyEditFunc func(context.Context, WallReplyEditObject) // WallReplyEditObject struct. -type WallReplyEditObject WallWallComment +type WallReplyEditObject object.WallWallComment // WallReplyRestoreFunc func. -type WallReplyRestoreFunc func(WallReplyRestoreObject, int) +type WallReplyRestoreFunc func(context.Context, WallReplyRestoreObject) // WallReplyRestoreObject struct. -type WallReplyRestoreObject WallWallComment +type WallReplyRestoreObject object.WallWallComment // WallReplyDeleteFunc func. -type WallReplyDeleteFunc func(WallReplyDeleteObject, int) +type WallReplyDeleteFunc func(context.Context, WallReplyDeleteObject) // WallReplyDeleteObject struct. type WallReplyDeleteObject struct { @@ -210,25 +186,25 @@ type WallReplyDeleteObject struct { } // BoardPostNewFunc func. -type BoardPostNewFunc func(BoardPostNewObject, int) +type BoardPostNewFunc func(context.Context, BoardPostNewObject) // BoardPostNewObject struct. -type BoardPostNewObject BoardTopicComment +type BoardPostNewObject object.BoardTopicComment // BoardPostEditFunc func. -type BoardPostEditFunc func(BoardPostEditObject, int) +type BoardPostEditFunc func(context.Context, BoardPostEditObject) // BoardPostEditObject struct. -type BoardPostEditObject BoardTopicComment +type BoardPostEditObject object.BoardTopicComment // BoardPostRestoreFunc func. -type BoardPostRestoreFunc func(BoardPostRestoreObject, int) +type BoardPostRestoreFunc func(context.Context, BoardPostRestoreObject) // BoardPostRestoreObject struct. -type BoardPostRestoreObject BoardTopicComment +type BoardPostRestoreObject object.BoardTopicComment // BoardPostDeleteFunc func. -type BoardPostDeleteFunc func(BoardPostDeleteObject, int) +type BoardPostDeleteFunc func(context.Context, BoardPostDeleteObject) // BoardPostDeleteObject struct. type BoardPostDeleteObject struct { @@ -238,25 +214,25 @@ type BoardPostDeleteObject struct { } // MarketCommentNewFunc func. -type MarketCommentNewFunc func(MarketCommentNewObject, int) +type MarketCommentNewFunc func(context.Context, MarketCommentNewObject) // MarketCommentNewObject struct. -type MarketCommentNewObject WallWallComment +type MarketCommentNewObject object.WallWallComment // MarketCommentEditFunc func. -type MarketCommentEditFunc func(MarketCommentEditObject, int) +type MarketCommentEditFunc func(context.Context, MarketCommentEditObject) // MarketCommentEditObject struct. -type MarketCommentEditObject WallWallComment +type MarketCommentEditObject object.WallWallComment // MarketCommentRestoreFunc func. -type MarketCommentRestoreFunc func(MarketCommentRestoreObject, int) +type MarketCommentRestoreFunc func(context.Context, MarketCommentRestoreObject) // MarketCommentRestoreObject struct. -type MarketCommentRestoreObject WallWallComment +type MarketCommentRestoreObject object.WallWallComment // MarketCommentDeleteFunc func. -type MarketCommentDeleteFunc func(MarketCommentDeleteObject, int) +type MarketCommentDeleteFunc func(context.Context, MarketCommentDeleteObject) // MarketCommentDeleteObject struct. type MarketCommentDeleteObject struct { @@ -268,28 +244,28 @@ type MarketCommentDeleteObject struct { } // MarketOrderNewFunc func. -type MarketOrderNewFunc func(MarketOrderNewObject, int) +type MarketOrderNewFunc func(context.Context, MarketOrderNewObject) // MarketOrderNewObject struct. -type MarketOrderNewObject MarketOrder +type MarketOrderNewObject object.MarketOrder // MarketOrderEditFunc func. -type MarketOrderEditFunc func(MarketOrderEditObject, int) +type MarketOrderEditFunc func(context.Context, MarketOrderEditObject) // MarketOrderEditObject struct. -type MarketOrderEditObject MarketOrder +type MarketOrderEditObject object.MarketOrder // GroupLeaveFunc func. -type GroupLeaveFunc func(GroupLeaveObject, int) +type GroupLeaveFunc func(context.Context, GroupLeaveObject) // GroupLeaveObject struct. type GroupLeaveObject struct { - UserID int `json:"user_id"` - Self BaseBoolInt `json:"self"` + UserID int `json:"user_id"` + Self object.BaseBoolInt `json:"self"` } // GroupJoinFunc func. -type GroupJoinFunc func(GroupJoinObject, int) +type GroupJoinFunc func(context.Context, GroupJoinObject) // GroupJoinObject struct. type GroupJoinObject struct { @@ -298,7 +274,7 @@ type GroupJoinObject struct { } // UserBlockFunc func. -type UserBlockFunc func(UserBlockObject, int) +type UserBlockFunc func(context.Context, UserBlockObject) // UserBlockObject struct. type UserBlockObject struct { @@ -310,7 +286,7 @@ type UserBlockObject struct { } // UserUnblockFunc func. -type UserUnblockFunc func(UserUnblockObject, int) +type UserUnblockFunc func(context.Context, UserUnblockObject) // UserUnblockObject struct. type UserUnblockObject struct { @@ -320,7 +296,7 @@ type UserUnblockObject struct { } // PollVoteNewFunc func. -type PollVoteNewFunc func(PollVoteNewObject, int) +type PollVoteNewFunc func(context.Context, PollVoteNewObject) // PollVoteNewObject struct. // @@ -333,7 +309,7 @@ type PollVoteNewObject struct { } // GroupOfficersEditFunc func. -type GroupOfficersEditFunc func(GroupOfficersEditObject, int) +type GroupOfficersEditFunc func(context.Context, GroupOfficersEditObject) // GroupOfficersEditObject struct. type GroupOfficersEditObject struct { @@ -356,11 +332,12 @@ type ChangesInt struct { } // GroupChangeSettingsFunc func. -type GroupChangeSettingsFunc func(GroupChangeSettingsObject, int) +type GroupChangeSettingsFunc func(context.Context, GroupChangeSettingsObject) // GroupChangeSettingsObject struct -// спасибо vk.com/eee +// // BUG(VK): Phone https://vk.com/bugtracker?act=show&id=64240 +// // BUG(VK): Email https://vk.com/bugtracker?act=show&id=86650 type GroupChangeSettingsObject struct { UserID int `json:"user_id"` @@ -398,16 +375,16 @@ type GroupChangeSettingsObject struct { } // GroupChangePhotoFunc func. -type GroupChangePhotoFunc func(GroupChangePhotoObject, int) +type GroupChangePhotoFunc func(context.Context, GroupChangePhotoObject) // GroupChangePhotoObject struct. type GroupChangePhotoObject struct { - UserID int `json:"user_id"` - Photo PhotosPhoto `json:"photo"` + UserID int `json:"user_id"` + Photo object.PhotosPhoto `json:"photo"` } // VkpayTransactionFunc func. -type VkpayTransactionFunc func(VkpayTransactionObject, int) +type VkpayTransactionFunc func(context.Context, VkpayTransactionObject) // VkpayTransactionObject struct. type VkpayTransactionObject struct { @@ -418,7 +395,7 @@ type VkpayTransactionObject struct { } // LeadFormsNewFunc func. -type LeadFormsNewFunc func(LeadFormsNewObject, int) +type LeadFormsNewFunc func(context.Context, LeadFormsNewObject) // LeadFormsNewObject struct. type LeadFormsNewObject struct { @@ -436,7 +413,7 @@ type LeadFormsNewObject struct { } // AppPayloadFunc func. -type AppPayloadFunc func(AppPayloadObject, int) +type AppPayloadFunc func(context.Context, AppPayloadObject) // AppPayloadObject struct. type AppPayloadObject struct { @@ -446,7 +423,7 @@ type AppPayloadObject struct { } // MessageReadFunc func. -type MessageReadFunc func(MessageReadObject, int) +type MessageReadFunc func(context.Context, MessageReadObject) // MessageReadObject struct. type MessageReadObject struct { @@ -456,7 +433,7 @@ type MessageReadObject struct { } // LikeAddFunc func. -type LikeAddFunc func(LikeAddObject, int) +type LikeAddFunc func(context.Context, LikeAddObject) // LikeAddObject struct. type LikeAddObject struct { @@ -469,7 +446,7 @@ type LikeAddObject struct { } // LikeRemoveFunc func. -type LikeRemoveFunc func(LikeRemoveObject, int) +type LikeRemoveFunc func(context.Context, LikeRemoveObject) // LikeRemoveObject struct. type LikeRemoveObject struct { diff --git a/internal/transport.go b/internal/transport.go index 0b2a2090..8356f846 100644 --- a/internal/transport.go +++ b/internal/transport.go @@ -22,6 +22,9 @@ type ContextKey int const ( HTTPClientKey ContextKey = iota UserAgentKey + GroupIDKey + EventIDKey + LongpollTsKey ) // ContextClient return *http.Client. diff --git a/longpoll-bot/README.md b/longpoll-bot/README.md index 9b23f2dc..2bbc8491 100644 --- a/longpoll-bot/README.md +++ b/longpoll-bot/README.md @@ -10,7 +10,7 @@ ### Версия API -Данная библиотека поддерживает версию API **5.103**. +Данная библиотека поддерживает версию API **5.122**. ### Инициализация @@ -52,12 +52,12 @@ lp.Client.Transport = httpTransport ### Обработчик событий Для каждого события существует отдельный обработчик, который передает функции -`object` и `groupID`. +`ctx` и `object`. Пример для события `message_new` ```go -lp.MessageNew(func(object object.MessageNewObject, groupID int) { +lp.MessageNew(func(ctx context.Context, obj object.MessageNewObject) { ... }) ``` @@ -111,7 +111,7 @@ func main() { panic(err) } - lp.MessageNew(func(obj object.MessageNewObject, groupID int) { + lp.MessageNew(func(ctx context.Context, obj object.MessageNewObject) { log.Print(obj.Message.Text) }) diff --git a/longpoll-bot/context.go b/longpoll-bot/context.go new file mode 100644 index 00000000..ed8e1816 --- /dev/null +++ b/longpoll-bot/context.go @@ -0,0 +1,12 @@ +package longpoll // import "github.com/SevereCloud/vksdk/longpoll-bot" + +import ( + "context" + + "github.com/SevereCloud/vksdk/internal" +) + +// TsFromContext returns the ts from context. +func TsFromContext(ctx context.Context) int { + return ctx.Value(internal.LongpollTsKey).(int) +} diff --git a/longpoll-bot/context_test.go b/longpoll-bot/context_test.go new file mode 100644 index 00000000..7bc34195 --- /dev/null +++ b/longpoll-bot/context_test.go @@ -0,0 +1,16 @@ +package longpoll_test + +import ( + "context" + "testing" + + "github.com/SevereCloud/vksdk/internal" + "github.com/SevereCloud/vksdk/longpoll-bot" + "github.com/stretchr/testify/assert" +) + +func TestTsFromContext(t *testing.T) { + const ts = 123 + ctx := context.WithValue(context.Background(), internal.LongpollTsKey, ts) + assert.Equal(t, ts, longpoll.TsFromContext(ctx)) +} diff --git a/longpoll-bot/longpoll.go b/longpoll-bot/longpoll.go index 4b38d55c..c33a8cb0 100644 --- a/longpoll-bot/longpoll.go +++ b/longpoll-bot/longpoll.go @@ -6,17 +6,25 @@ See more https://vk.com/dev/bots_longpoll package longpoll // import "github.com/SevereCloud/vksdk/longpoll-bot" import ( + "context" "encoding/json" "fmt" "net/http" "sync/atomic" - "github.com/SevereCloud/vksdk/object" + "github.com/SevereCloud/vksdk/internal" "github.com/SevereCloud/vksdk/api" "github.com/SevereCloud/vksdk/events" ) +// Response struct. +type Response struct { + Ts string `json:"ts"` + Updates []events.GroupEvent `json:"updates"` + Failed int `json:"failed"` +} + // Longpoll struct. type Longpoll struct { GroupID int @@ -27,7 +35,7 @@ type Longpoll struct { VK *api.VK Client *http.Client - funcFullResponseList []func(object.LongpollBotResponse) + funcFullResponseList []func(Response) inShutdown int32 events.FuncList @@ -96,8 +104,8 @@ func (lp *Longpoll) updateServer(updateTs bool) error { return nil } -func (lp *Longpoll) check() (object.LongpollBotResponse, error) { - var response object.LongpollBotResponse +func (lp *Longpoll) check() (Response, error) { + var response Response u := fmt.Sprintf("%s?act=a_check&key=%s&ts=%s&wait=%d", lp.Server, lp.Key, lp.Ts, lp.Wait) @@ -117,7 +125,7 @@ func (lp *Longpoll) check() (object.LongpollBotResponse, error) { return response, err } -func (lp *Longpoll) checkResponse(response object.LongpollBotResponse) (err error) { +func (lp *Longpoll) checkResponse(response Response) (err error) { switch response.Failed { case 0: lp.Ts = response.Ts @@ -144,8 +152,10 @@ func (lp *Longpoll) Run() error { return err } + ctx := context.WithValue(context.Background(), internal.LongpollTsKey, resp.Ts) + for _, event := range resp.Updates { - err = lp.Handler(event) + err = lp.Handler(ctx, event) if err != nil { return err } @@ -165,6 +175,6 @@ func (lp *Longpoll) Shutdown() { } // FullResponse handler. -func (lp *Longpoll) FullResponse(f func(object.LongpollBotResponse)) { +func (lp *Longpoll) FullResponse(f func(Response)) { lp.funcFullResponseList = append(lp.funcFullResponseList, f) } diff --git a/longpoll-bot/longpoll_test.go b/longpoll-bot/longpoll_test.go index 41af9de2..c2526982 100644 --- a/longpoll-bot/longpoll_test.go +++ b/longpoll-bot/longpoll_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/SevereCloud/vksdk/api" - "github.com/SevereCloud/vksdk/object" ) func TestLongpoll_Shutdown(t *testing.T) { @@ -27,7 +26,7 @@ func TestLongpoll_Handler(t *testing.T) { lp := &Longpoll{} t.Run("FullResponse", func(t *testing.T) { - lp.FullResponse(func(resp object.LongpollBotResponse) {}) + lp.FullResponse(func(resp Response) {}) if len(lp.funcFullResponseList) != 1 { t.Error("Want len = 1") } @@ -93,7 +92,7 @@ func TestLongpoll_checkResponse(t *testing.T) { tests := []struct { name string - argResponse object.LongpollBotResponse + argResponse Response wantErr bool }{ { @@ -101,19 +100,19 @@ func TestLongpoll_checkResponse(t *testing.T) { }, { name: "failed: 1", - argResponse: object.LongpollBotResponse{Failed: 1}, + argResponse: Response{Failed: 1}, }, { name: "failed: 2", - argResponse: object.LongpollBotResponse{Failed: 2}, + argResponse: Response{Failed: 2}, }, { name: "failed: 3", - argResponse: object.LongpollBotResponse{Failed: 3}, + argResponse: Response{Failed: 3}, }, { name: "failed: 4", - argResponse: object.LongpollBotResponse{Failed: 4}, + argResponse: Response{Failed: 4}, wantErr: true, }, } diff --git a/object/handler_test.go b/object/handler_test.go deleted file mode 100644 index bb35b606..00000000 --- a/object/handler_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package object_test - -import ( - "testing" - - "github.com/SevereCloud/vksdk/object" - "github.com/stretchr/testify/assert" -) - -func TestMessageNewObject_UnmarshalJSON(t *testing.T) { - t.Parallel() - - f := func(b []byte, want object.MessageNewObject, wantErr bool) { - var obj object.MessageNewObject - - err := obj.UnmarshalJSON(b) - if (err != nil) != wantErr { - t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, wantErr) - } - - assert.Equal(t, obj, want) - } - - f( - []byte(""), - object.MessageNewObject{}, - true, - ) - f( - []byte(`{"id":1}`), - object.MessageNewObject{Message: object.MessagesMessage{ID: 1}}, - false, - ) - f( - []byte(`{"message":{"id":1},"client_info":{}}`), - object.MessageNewObject{Message: object.MessagesMessage{ID: 1}}, - false, - ) -} diff --git a/object/object.go b/object/object.go index 408a57f7..ea231600 100644 --- a/object/object.go +++ b/object/object.go @@ -78,68 +78,6 @@ const ( SexMale ) -// EventType list. -const ( - EventConfirmation = "confirmation" - EventMessageNew = "message_new" - EventMessageReply = "message_reply" - EventMessageEdit = "message_edit" - EventMessageAllow = "message_allow" - EventMessageDeny = "message_deny" - EventMessageTypingState = "message_typing_state" - EventMessageEvent = "message_event" - EventPhotoNew = "photo_new" - EventPhotoCommentNew = "photo_comment_new" - EventPhotoCommentEdit = "photo_comment_edit" - EventPhotoCommentRestore = "photo_comment_restore" - EventPhotoCommentDelete = "photo_comment_delete" - EventAudioNew = "audio_new" - EventVideoNew = "video_new" - EventVideoCommentNew = "video_comment_new" - EventVideoCommentEdit = "video_comment_edit" - EventVideoCommentRestore = "video_comment_restore" - EventVideoCommentDelete = "video_comment_delete" - EventWallPostNew = "wall_post_new" - EventWallRepost = "wall_repost" - EventWallReplyNew = "wall_reply_new" - EventWallReplyEdit = "wall_reply_edit" - EventWallReplyRestore = "wall_reply_restore" - EventWallReplyDelete = "wall_reply_delete" - EventBoardPostNew = "board_post_new" - EventBoardPostEdit = "board_post_edit" - EventBoardPostRestore = "board_post_restore" - EventBoardPostDelete = "board_post_delete" - EventMarketCommentNew = "market_comment_new" - EventMarketCommentEdit = "market_comment_edit" - EventMarketCommentRestore = "market_comment_restore" - EventMarketCommentDelete = "market_comment_delete" - EventMarketOrderNew = "market_order_new" - EventMarketOrderEdit = "market_order_edit" - EventGroupLeave = "group_leave" - EventGroupJoin = "group_join" - EventUserBlock = "user_block" - EventUserUnblock = "user_unblock" - EventPollVoteNew = "poll_vote_new" - EventGroupOfficersEdit = "group_officers_edit" - EventGroupChangeSettings = "group_change_settings" - EventGroupChangePhoto = "group_change_photo" - EventVkpayTransaction = "vkpay_transaction" - EventLeadFormsNew = "lead_forms_new" - EventAppPayload = "app_payload" - EventMessageRead = "message_read" - EventLikeAdd = "like_add" - EventLikeRemove = "like_remove" -) - -// GroupEvent struct. -type GroupEvent struct { - Type string `json:"type"` - Object json.RawMessage `json:"object"` - GroupID int `json:"group_id"` - EventID string `json:"event_id"` - Secret string `json:"secret"` -} - // LongpollResponse struct. type LongpollResponse struct { Ts int `json:"ts"` @@ -147,13 +85,6 @@ type LongpollResponse struct { Failed int `json:"failed"` } -// LongpollBotResponse struct. -type LongpollBotResponse struct { - Ts string `json:"ts"` - Updates []GroupEvent `json:"updates"` - Failed int `json:"failed"` -} - // BaseCommentsInfo struct. type BaseCommentsInfo struct { Count int `json:"count"` From d28abf97fbe2120bc92ea75e4cc259ac03971c93 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 7 Aug 2020 17:04:54 +0300 Subject: [PATCH 084/105] style: golangci-lint update v1.30 --- .github/workflows/golangci-lint.yml | 2 +- .golangci.yml | 6 ++---- api/errors.go | 18 ++++++++++++------ longpoll-user/longpoll.go | 10 +++++----- payments/payments.go | 2 +- streaming/errors.go | 3 ++- streaming/streaming.go | 2 -- 7 files changed, 23 insertions(+), 20 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index cc2c09a5..e052bbd7 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -13,7 +13,7 @@ jobs: # Required: the version of golangci-lint is required and must be # specified without patch version: we always use the latest # patch version. - version: v1.29 + version: v1.30 # Optional: golangci-lint command line arguments. # args: ./the-only-dir-to-analyze/... diff --git a/.golangci.yml b/.golangci.yml index ff9f2204..c14f14f4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -55,6 +55,8 @@ linters: # - scopelint # - gomodguard # - exhaustive +# - nlreturn +# - gci issues: exclude-rules: @@ -75,7 +77,3 @@ issues: text: "ST1003:.*(Ts|ts).*TS" exclude-use-default: false - - -service: - golangci-lint-version: 1.24.x diff --git a/api/errors.go b/api/errors.go index 73bb1cfc..c4f14f45 100644 --- a/api/errors.go +++ b/api/errors.go @@ -37,7 +37,7 @@ const ( // User authorization failed // - // Make sure that you use a correct authorization type + // Make sure that you use a correct authorization type. ErrAuth ErrorType = 5 // Too many requests per second @@ -56,7 +56,7 @@ const ( // Invalid request // - // Check the request syntax and used parameters list (it can be found on a method description page) + // Check the request syntax and used parameters list (it can be found on a method description page). ErrRequest ErrorType = 8 // Flood control @@ -71,7 +71,10 @@ const ( // In test mode application should be disabled or user should be authorized // - // Switch the app off in Settings: https://vk.com/editapp?id={Your API_ID} + // Switch the app off in Settings: + // + // https://vk.com/editapp?id={Your API_ID} + // ErrEnabledInTest ErrorType = 11 // Unable to compile code. @@ -159,7 +162,7 @@ const ( // Invalid user id // // Make sure that you use a correct id. You can get an id using a screen - // name with the utils.resolveScreenName method + // name with the utils.resolveScreenName method. ErrParamUserID ErrorType = 113 ErrParamAlbumID ErrorType = 114 // Invalid album id ErrParamServer ErrorType = 118 // Invalid server @@ -176,7 +179,7 @@ const ( // Invalid timestamp // - // You may get a correct value with the utils.getServerTime method + // You may get a correct value with the utils.getServerTime method. ErrParamTimestamp ErrorType = 150 ErrFriendsListID ErrorType = 171 // Invalid list id ErrFriendsListLimit ErrorType = 173 // Reached the maximum number of lists @@ -235,7 +238,10 @@ const ( // Permission denied. You must enable votes processing in application settings // - // Check the app settings: http://vk.com/editapp?id={Your API_ID}§ion=payments + // Check the app settings: + // + // http://vk.com/editapp?id={Your API_ID}§ion=payments + // ErrVotesPermission ErrorType = 500 ErrVotes ErrorType = 503 // Not enough votes ErrNotEnoughMoney ErrorType = 504 // Not enough money on owner's balance diff --git a/longpoll-user/longpoll.go b/longpoll-user/longpoll.go index 70f7c034..66b11a96 100644 --- a/longpoll-user/longpoll.go +++ b/longpoll-user/longpoll.go @@ -69,15 +69,15 @@ type Mode = int // A list of necessary option codes. const ( - // receive attachments + // receive attachments. ReceiveAttachments Mode = 1 << 1 - // receive more events + // receive more events. ExtendedEvents Mode = 1 << 3 - // receive pts (used in messages.getLongPollHistory) + // receive pts (used in messages.getLongPollHistory). ReturnPts Mode = 1 << 5 - // extra fields in event type 8(friend become online) + // extra fields in event type 8(friend become online). Code8ExtraFields Mode = 1 << 6 - // return random_id field + // return random_id field. ReturnRandomID Mode = 1 << 7 ) diff --git a/payments/payments.go b/payments/payments.go index 16341675..ad14d668 100644 --- a/payments/payments.go +++ b/payments/payments.go @@ -117,7 +117,7 @@ const ( // balance. If the response is a failure, the order is canceled. Chargeable Status = "chargeable" - // Subscription is active; + // Subscription is active. Active Status = "active" // Subscription is canceled. diff --git a/streaming/errors.go b/streaming/errors.go index fc261fb4..6c902b93 100644 --- a/streaming/errors.go +++ b/streaming/errors.go @@ -15,7 +15,8 @@ func (e ErrorType) Error() string { // Error codes. See https://vk.com/dev/streaming_api_docs_2 const ( ErrNoType ErrorType = 0 // NoType error - // Settings for updating the connection to WebSocket are incorrectly transmitted + // Settings for updating the connection to WebSocket are incorrectly + // transmitted. ErrUpgradeWebsocket ErrorType = 1000 ErrUnsupportedHTTP ErrorType = 1001 // Unsupported HTTP method ErrContentType ErrorType = 1002 // “Content-type” key is absent or invalid diff --git a/streaming/streaming.go b/streaming/streaming.go index c081464d..35746dbf 100644 --- a/streaming/streaming.go +++ b/streaming/streaming.go @@ -106,8 +106,6 @@ type response struct { const ( codeEvent = 100 - // codeOk = 200 // is unused (deadcode) - // codeService = 300 // is unused (deadcode) codeError = 400 ) From a4d689c19510716f1696ecc2d20f8c6ef3154ebd Mon Sep 17 00:00:00 2001 From: geosonic <36260850+geosonic@users.noreply.github.com> Date: Sun, 9 Aug 2020 00:01:44 +0500 Subject: [PATCH 085/105] Add field "app_id" in FriendBecameOnline for user longpoll --- longpoll-user/v3/objects.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/longpoll-user/v3/objects.go b/longpoll-user/v3/objects.go index 41085dce..9ba04030 100644 --- a/longpoll-user/v3/objects.go +++ b/longpoll-user/v3/objects.go @@ -212,6 +212,7 @@ type FriendBecameOnline struct { UserID int Extra int Timestamp time.Time + AppID int } func (result *FriendBecameOnline) parse(i []interface{}) error { @@ -231,6 +232,10 @@ func (result *FriendBecameOnline) parse(i []interface{}) error { result.Timestamp = time.Unix(int64(v), 0) } + if v, ok := i[4].(float64); ok { + result.AppID = int(v) + } + return nil } From 8a57ec8c3e03769b0b22cf8a8486e2419f8968bf Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 19 Aug 2020 18:31:50 +0300 Subject: [PATCH 086/105] feat: VideoSearch add Legal params --- api/params/video.go | 12 ++++++++++++ api/params/video_test.go | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/api/params/video.go b/api/params/video.go index 8f68addb..7f890449 100644 --- a/api/params/video.go +++ b/api/params/video.go @@ -1124,3 +1124,15 @@ func (b *VideoSearchBuilder) Extended(v bool) *VideoSearchBuilder { b.Params["extended"] = v return b } + +// Legal parameter. +func (b *VideoSearchBuilder) Legal(v bool) *VideoSearchBuilder { + b.Params["legal"] = v + return b +} + +// LegalOwner parameter. +func (b *VideoSearchBuilder) LegalOwner(v int) *VideoSearchBuilder { + b.Params["legal_owner"] = v + return b +} diff --git a/api/params/video_test.go b/api/params/video_test.go index 025dca46..575ab4c0 100644 --- a/api/params/video_test.go +++ b/api/params/video_test.go @@ -425,6 +425,8 @@ func TestVideoSearchBuilder(t *testing.T) { b.Shorter(1) b.Count(1) b.Extended(true) + b.Legal(true) + b.LegalOwner(1) assert.Equal(t, b.Params["q"], "text") assert.Equal(t, b.Params["sort"], 1) @@ -437,4 +439,6 @@ func TestVideoSearchBuilder(t *testing.T) { assert.Equal(t, b.Params["shorter"], 1) assert.Equal(t, b.Params["count"], 1) assert.Equal(t, b.Params["extended"], true) + assert.Equal(t, b.Params["legal"], true) + assert.Equal(t, b.Params["legal_owner"], 1) } From 800bd5bd530605fa8d1f25aed9e2e1226063c001 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 19 Aug 2020 19:05:36 +0300 Subject: [PATCH 087/105] style: lll linter --- api/ads.go | 5 +- api/api_test.go | 6 +- api/appwidgets.go | 10 +- api/errors.go | 581 ++++++++++++++++++++++++++++---------- api/groups.go | 10 +- api/groups_test.go | 212 +++++++++++++- api/messages.go | 24 +- api/photos.go | 18 +- api/secure.go | 3 +- api/upload.go | 53 +++- api/users.go | 6 +- api/users_test.go | 64 ++++- foaf/foaf.go | 3 +- object/account.go | 38 ++- object/ads.go | 28 +- object/apps.go | 56 ++-- object/docs.go | 3 +- object/groups.go | 243 +++++++++------- object/market.go | 16 +- object/messages.go | 130 +++++---- object/object.go | 28 +- object/pages.go | 65 +++-- object/photos.go | 39 +-- object/stories.go | 40 ++- object/video.go | 145 +++++----- object/widgets.go | 6 +- payments/callback_test.go | 28 +- payments/payments.go | 40 ++- 28 files changed, 1365 insertions(+), 535 deletions(-) diff --git a/api/ads.go b/api/ads.go index 5ebae1e6..f03d8dc1 100644 --- a/api/ads.go +++ b/api/ads.go @@ -427,7 +427,10 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // TODO: AdsSaveLookalikeRequestResult ... // // https://vk.com/dev/ads.saveLookalikeRequestResult -// func (vk *VK) AdsSaveLookalikeRequestResult(params Params) (response AdsSaveLookalikeRequestResultResponse, err error) { +// func (vk *VK) AdsSaveLookalikeRequestResult(params Params) ( +// response AdsSaveLookalikeRequestResultResponse, +// err error, +// ) { // err = vk.RequestUnmarshal("ads.saveLookalikeRequestResult", params, &response) // return // } diff --git a/api/api_test.go b/api/api_test.go index 85453c4b..2025ff25 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -217,7 +217,11 @@ func TestVK_ExecuteWithArgs_error(t *testing.T) { var response int - err := vkGroup.ExecuteWithArgs(`API.users.get({user_id: parseInt(Args.user_id)});return 1;`, api.Params{"user_id": -1}, &response) + err := vkGroup.ExecuteWithArgs( + `API.users.get({user_id: parseInt(Args.user_id)});return 1;`, + api.Params{"user_id": -1}, + &response, + ) assert.Error(t, err) assert.Equal(t, 1, response) } diff --git a/api/appwidgets.go b/api/appwidgets.go index 4688da37..aa907991 100644 --- a/api/appwidgets.go +++ b/api/appwidgets.go @@ -13,7 +13,10 @@ type AppWidgetsGetAppImageUploadServerResponse struct { // photo to the app collection for community app widgets. // // https://vk.com/dev/appWidgets.getAppImageUploadServer -func (vk *VK) AppWidgetsGetAppImageUploadServer(params Params) (response AppWidgetsGetAppImageUploadServerResponse, err error) { +func (vk *VK) AppWidgetsGetAppImageUploadServer(params Params) ( + response AppWidgetsGetAppImageUploadServerResponse, + err error, +) { err = vk.RequestUnmarshal("appWidgets.getAppImageUploadServer", params, &response) return } @@ -41,7 +44,10 @@ type AppWidgetsGetGroupImageUploadServerResponse struct { // a photo to the community collection for community app widgets. // // https://vk.com/dev/appWidgets.getGroupImageUploadServer -func (vk *VK) AppWidgetsGetGroupImageUploadServer(params Params) (response AppWidgetsGetGroupImageUploadServerResponse, err error) { +func (vk *VK) AppWidgetsGetGroupImageUploadServer(params Params) ( + response AppWidgetsGetGroupImageUploadServerResponse, + err error, +) { err = vk.RequestUnmarshal("appWidgets.getGroupImageUploadServer", params, &response) return } diff --git a/api/errors.go b/api/errors.go index c4f14f45..83640a57 100644 --- a/api/errors.go +++ b/api/errors.go @@ -25,7 +25,8 @@ const ( // Application is disabled. Enable your application or use test mode // - // You need to switch on the app in Settings (https://vk.com/editapp?id={Your API_ID} + // You need to switch on the app in Settings + // https://vk.com/editapp?id={Your API_ID} // or use the test mode (test_mode=1). ErrDisabled ErrorType = 2 @@ -49,19 +50,22 @@ const ( // Permission to perform this action is denied // - // Make sure that your have received required permissions during the authorization. + // Make sure that your have received required permissions during the + // authorization. // You can do it with the account.getAppPermissions method. // https://vk.com/dev/permissions ErrPermission ErrorType = 7 // Invalid request // - // Check the request syntax and used parameters list (it can be found on a method description page). + // Check the request syntax and used parameters list (it can be found on + // a method description page). ErrRequest ErrorType = 8 // Flood control // - // You need to decrease the count of identical requests. For more efficient work you may use execute. + // You need to decrease the count of identical requests. For more efficient + // work you may use execute. ErrFlood ErrorType = 9 // Internal server error @@ -90,30 +94,39 @@ const ( // Access denied // - // Make sure that you use correct identifiers and the content is available for the user in the full version of the site. + // Make sure that you use correct identifiers and the content is available + // for the user in the full version of the site. ErrAccess ErrorType = 15 // HTTP authorization failed // - // To avoid this error check if a user has the 'Use secure connection' option enabled with the account.getInfo method. + // To avoid this error check if a user has the 'Use secure connection' + // option enabled with the account.getInfo method. ErrAuthHTTPS ErrorType = 16 // Validation required // - // Make sure that you don't use a token received with http://vk.com/dev/auth_mobile for a request from the server. It's restricted. + // Make sure that you don't use a token received with + // http://vk.com/dev/auth_mobile for a request from the server. + // It's restricted. // // https://vk.com/dev/need_validation ErrAuthValidation ErrorType = 17 ErrUserDeleted ErrorType = 18 // User was deleted or banned ErrBlocked ErrorType = 19 // Content blocked - // Permission to perform this action is denied for non-standalone applications + // Permission to perform this action is denied for non-standalone + // applications // - // If you see this error despite your app has the Standalone type, make sure that you use redirect_uri=https://oauth.vk.com/blank.html. + // If you see this error despite your app has the Standalone type, make + // sure that you use redirect_uri=https://oauth.vk.com/blank.html. // Details here: https://vk.com/dev/auth_mobile ErrMethodPermission ErrorType = 20 - ErrMethodAds ErrorType = 21 // Permission to perform this action is allowed only for standalone and OpenAPI applications - ErrUpload ErrorType = 22 // Upload error + + // Permission to perform this action is allowed only for standalone and + // OpenAPI applications. + ErrMethodAds ErrorType = 21 + ErrUpload ErrorType = 22 // Upload error // This method was disabled // @@ -122,15 +135,20 @@ const ( // Confirmation required // - // In some cases VK requires to request action confirmation from the user (for Standalone apps only). + // In some cases VK requires to request action confirmation from the user + // (for Standalone apps only). // // Following parameter is transmitted with the error message as well: // - // confirmation_text – text of the message to be shown in the default confirmation window. + // confirmation_text – text of the message to be shown in the default + // confirmation window. // // The app should display the default confirmation window - // with text from confirmation_text and two buttons: "Continue" and "Cancel". - // If user confirms the action repeat the request with an extra parameter: confirm = 1. + // with text from confirmation_text and two buttons: "Continue" and + // "Cancel". + // If user confirms the action repeat the request with an extra parameter: + // + // confirm = 1. // // https://vk.com/dev/need_confirmation ErrNeedConfirmation ErrorType = 24 @@ -146,12 +164,14 @@ const ( // One of the parameters specified was missing or invalid // - // Check the required parameters list and their format on a method description page. + // Check the required parameters list and their format on a method + // description page. ErrParam ErrorType = 100 // Invalid application API ID // - // Find the app in the administrated list in settings: http://vk.com/apps?act=settings + // Find the app in the administrated list in settings: + // http://vk.com/apps?act=settings // And set the correct API_ID in the request. ErrParamAPIID ErrorType = 101 ErrLimits ErrorType = 103 // Out of limits @@ -163,30 +183,46 @@ const ( // // Make sure that you use a correct id. You can get an id using a screen // name with the utils.resolveScreenName method. - ErrParamUserID ErrorType = 113 - ErrParamAlbumID ErrorType = 114 // Invalid album id - ErrParamServer ErrorType = 118 // Invalid server - ErrParamTitle ErrorType = 119 // Invalid title - ErrParamPhotos ErrorType = 122 // Invalid photos - ErrParamHash ErrorType = 121 // Invalid hash - ErrParamPhoto ErrorType = 129 // Invalid photo - ErrParamGroupID ErrorType = 125 // Invalid group id - ErrParamPageID ErrorType = 140 // Page not found - ErrAccessPage ErrorType = 141 // Access to page denied - ErrMobileNotActivated ErrorType = 146 // The mobile number of the user is unknown - ErrInsufficientFunds ErrorType = 147 // Application has insufficient funds - ErrAccessMenu ErrorType = 148 // Access to the menu of the user denied + ErrParamUserID ErrorType = 113 + ErrParamAlbumID ErrorType = 114 // Invalid album id + ErrParamServer ErrorType = 118 // Invalid server + ErrParamTitle ErrorType = 119 // Invalid title + ErrParamPhotos ErrorType = 122 // Invalid photos + ErrParamHash ErrorType = 121 // Invalid hash + ErrParamPhoto ErrorType = 129 // Invalid photo + ErrParamGroupID ErrorType = 125 // Invalid group id + ErrParamPageID ErrorType = 140 // Page not found + ErrAccessPage ErrorType = 141 // Access to page denied + + // The mobile number of the user is unknown. + ErrMobileNotActivated ErrorType = 146 + + // Application has insufficient funds. + ErrInsufficientFunds ErrorType = 147 + + // Access to the menu of the user denied. + ErrAccessMenu ErrorType = 148 // Invalid timestamp // // You may get a correct value with the utils.getServerTime method. - ErrParamTimestamp ErrorType = 150 - ErrFriendsListID ErrorType = 171 // Invalid list id - ErrFriendsListLimit ErrorType = 173 // Reached the maximum number of lists - ErrFriendsAddYourself ErrorType = 174 // Cannot add user himself as friend - ErrFriendsAddInEnemy ErrorType = 175 // Cannot add this user to friends as they have put you on their blacklist - ErrFriendsAddEnemy ErrorType = 176 // Cannot add this user to friends as you put him on blacklist - ErrFriendsAddNotFound ErrorType = 177 // Cannot add this user to friends as user not found + ErrParamTimestamp ErrorType = 150 + ErrFriendsListID ErrorType = 171 // Invalid list id + + // Reached the maximum number of lists. + ErrFriendsListLimit ErrorType = 173 + + // Cannot add user himself as friend. + ErrFriendsAddYourself ErrorType = 174 + + // Cannot add this user to friends as they have put you on their blacklist. + ErrFriendsAddInEnemy ErrorType = 175 + + // Cannot add this user to friends as you put him on blacklist. + ErrFriendsAddEnemy ErrorType = 176 + + // Cannot add this user to friends as user not found. + ErrFriendsAddNotFound ErrorType = 177 ErrParamNoteID ErrorType = 180 // Note not found ErrAccessNote ErrorType = 181 // Access to note denied ErrAccessNoteComment ErrorType = 182 // You can't comment this note @@ -208,27 +244,66 @@ const ( // Access to group denied // - // Make sure that the current user is a member or admin of the community (for closed and private groups and events). - ErrAccessGroup ErrorType = 203 - ErrAccessVideo ErrorType = 204 // Access denied - ErrAccessMarket ErrorType = 205 // Access denied - ErrWallAccessPost ErrorType = 210 // Access to wall's post denied - ErrWallAccessComment ErrorType = 211 // Access to wall's comment denied - ErrWallAccessReplies ErrorType = 212 // Access to post comments denied - ErrWallAccessAddReply ErrorType = 213 // Access to status replies denied - ErrWallAddPost ErrorType = 214 // Access to adding post denied - ErrWallAdsPublished ErrorType = 219 // Advertisement post was recently added - ErrWallTooManyRecipients ErrorType = 220 // Too many recipients - ErrStatusNoAudio ErrorType = 221 // User disabled track name broadcast - ErrWallLinksForbidden ErrorType = 222 // Hyperlinks are forbidden - ErrWallReplyOwnerFlood ErrorType = 223 // Too many replies - ErrWallAdsPostLimitReached ErrorType = 224 // Too many ads posts - ErrDonutDisabled ErrorType = 225 // Donut is disabled - ErrPollsAccess ErrorType = 250 // Access to poll denied - ErrPollsAnswerID ErrorType = 252 // Invalid answer id - ErrPollsPollID ErrorType = 251 // Invalid poll id - ErrPollsAccessWithoutVote ErrorType = 253 // Access denied, please vote first - ErrAccessGroups ErrorType = 260 // Access to the groups list is denied due to the user's privacy settings + // Make sure that the current user is a member or admin of the community + // (for closed and private groups and events). + ErrAccessGroup ErrorType = 203 + + // Access denied. + ErrAccessVideo ErrorType = 204 + + // Access denied. + ErrAccessMarket ErrorType = 205 + + // Access to wall's post denied. + ErrWallAccessPost ErrorType = 210 + + // Access to wall's comment denied. + ErrWallAccessComment ErrorType = 211 + + // Access to post comments denied. + ErrWallAccessReplies ErrorType = 212 + + // Access to status replies denied. + ErrWallAccessAddReply ErrorType = 213 + + // Access to adding post denied. + ErrWallAddPost ErrorType = 214 + + // Advertisement post was recently added. + ErrWallAdsPublished ErrorType = 219 + + // Too many recipients. + ErrWallTooManyRecipients ErrorType = 220 + + // User disabled track name broadcast. + ErrStatusNoAudio ErrorType = 221 + + // Hyperlinks are forbidden. + ErrWallLinksForbidden ErrorType = 222 + + // Too many replies. + ErrWallReplyOwnerFlood ErrorType = 223 + + // Too many ads posts. + ErrWallAdsPostLimitReached ErrorType = 224 + + // Donut is disabled. + ErrDonutDisabled ErrorType = 225 + + // Access to poll denied. + ErrPollsAccess ErrorType = 250 + + // Invalid answer id. + ErrPollsAnswerID ErrorType = 252 + + // Invalid poll id. + ErrPollsPollID ErrorType = 251 + + // Access denied, please vote first. + ErrPollsAccessWithoutVote ErrorType = 253 + + // Access to the groups list is denied due to the user's privacy settings. + ErrAccessGroups ErrorType = 260 // This album is full // @@ -236,108 +311,301 @@ const ( ErrAlbumFull ErrorType = 300 ErrAlbumsLimit ErrorType = 302 // Albums number limit is reached - // Permission denied. You must enable votes processing in application settings + // Permission denied. You must enable votes processing in application + // settings // // Check the app settings: // // http://vk.com/editapp?id={Your API_ID}§ion=payments // - ErrVotesPermission ErrorType = 500 - ErrVotes ErrorType = 503 // Not enough votes - ErrNotEnoughMoney ErrorType = 504 // Not enough money on owner's balance - ErrAdsPermission ErrorType = 600 // Permission denied. You have no access to operations specified with given object(s) - ErrWeightedFlood ErrorType = 601 // Permission denied. You have requested too many actions this day. Try later - ErrAdsPartialSuccess ErrorType = 602 // Some part of the request has not been completed - ErrAdsSpecific ErrorType = 603 // Some ads error occurred - ErrAdsObjectDeleted ErrorType = 629 // Object deleted - ErrGroupChangeCreator ErrorType = 700 // Cannot edit creator role - ErrGroupNotInClub ErrorType = 701 // User should be in club - ErrGroupTooManyOfficers ErrorType = 702 // Too many officers in club - ErrGroupNeed2fa ErrorType = 703 // You need to enable 2FA for this action - ErrGroupHostNeed2fa ErrorType = 704 // User needs to enable 2FA for this action - ErrGroupTooManyAddresses ErrorType = 706 // Too many addresses in club - ErrGroupAppIsNotInstalledInCommunity ErrorType = 711 // "Application is not installed in community - ErrGroupInvalidInviteLink ErrorType = 714 // Invite link is invalid - expired, deleted or not exists - ErrVideoAlreadyAdded ErrorType = 800 // This video is already added - ErrVideoCommentsClosed ErrorType = 801 // Comments for this video are closed - ErrMessagesUserBlocked ErrorType = 900 // Can't send messages for users from blacklist - ErrMessagesDenySend ErrorType = 901 // Can't send messages for users without permission - ErrMessagesPrivacy ErrorType = 902 // Can't send messages to this user due to their privacy settings - ErrMessagesTooOldPts ErrorType = 907 // Value of ts or pts is too old - ErrMessagesTooNewPts ErrorType = 908 // Value of ts or pts is too new - ErrMessagesEditExpired ErrorType = 909 // Can't edit this message, because it's too old - ErrMessagesTooBig ErrorType = 910 // Can't sent this message, because it's too big - ErrMessagesKeyboardInvalid ErrorType = 911 // Keyboard format is invalid - ErrMessagesChatBotFeature ErrorType = 912 // This is a chat bot feature, change this status in settings - ErrMessagesTooLongForwards ErrorType = 913 // Too many forwarded messages - ErrMessagesTooLongMessage ErrorType = 914 // Message is too long - ErrMessagesChatUserNoAccess ErrorType = 917 // You don't have access to this chat - ErrMessagesCantSeeInviteLink ErrorType = 919 // You can't see invite link for this chat - ErrMessagesEditKindDisallowed ErrorType = 920 // Can't edit this kind of message - ErrMessagesCantFwd ErrorType = 921 // Can't forward these messages - ErrMessagesCantDeleteForAll ErrorType = 924 // Can't delete this message for everybody - ErrMessagesChatNotAdmin ErrorType = 925 // You are not admin of this chat - ErrMessagesChatNotExist ErrorType = 927 // Chat does not exist - ErrMessagesCantChangeInviteLink ErrorType = 931 // You can't change invite link for this chat - ErrMessagesGroupPeerAccess ErrorType = 932 // Your community can't interact with this peer - ErrMessagesChatUserNotInChat ErrorType = 935 // User not found in chat - ErrMessagesContactNotFound ErrorType = 936 // Contact not found - ErrMessagesMessageRequestAlreadySend ErrorType = 939 // Message request already send - ErrMessagesTooManyPosts ErrorType = 940 // Too many posts in messages - ErrMessagesCantUseIntent ErrorType = 943 // Cannot use this intent - ErrMessagesLimitIntent ErrorType = 944 // Limits overflow for this intent - ErrMessagesChatDisabled ErrorType = 945 // Chat was disabled - ErrMessagesChatNotSupported ErrorType = 946 // Chat not support - ErrMessagesMemberAccessToGroupDenied ErrorType = 947 // Can't add user to chat, because user has no access to group - ErrMessagesEditPinned ErrorType = 949 // Can't edit pinned message yet - ErrMessagesReplyTimedOut ErrorType = 950 // Can't send message, reply timed out - ErrParamPhone ErrorType = 1000 // Invalid phone number - ErrPhoneAlreadyUsed ErrorType = 1004 // This phone number is used by another user - ErrAuthFloodError ErrorType = 1105 // Too many auth attempts, try again later - ErrAuthDelay ErrorType = 1112 // Processing.. Try later - ErrParamDocID ErrorType = 1150 // Invalid document id - ErrParamDocDeleteAccess ErrorType = 1151 // Access to document deleting is denied - ErrParamDocTitle ErrorType = 1152 // Invalid document title - ErrParamDocAccess ErrorType = 1153 // Access to document is denied - ErrPhotoChanged ErrorType = 1160 // Original photo was changed - ErrTooManyLists ErrorType = 1170 // Too many feed lists - ErrAppsAlreadyUnlocked ErrorType = 1251 // This achievement is already unlocked - ErrAppsSubscriptionNotFound ErrorType = 1256 // Subscription not found - ErrAppsSubscriptionInvalidStatus ErrorType = 1257 // Subscription is in invalid status - ErrInvalidAddress ErrorType = 1260 // Invalid screen name - ErrCommunitiesCatalogDisabled ErrorType = 1310 // Catalog is not available for this user - ErrCommunitiesCategoriesDisabled ErrorType = 1311 // Catalog categories are not available for this user - ErrMarketRestoreTooLate ErrorType = 1400 // Too late for restore - ErrMarketCommentsClosed ErrorType = 1401 // Comments for this market are closed - ErrMarketAlbumNotFound ErrorType = 1402 // Album not found - ErrMarketItemNotFound ErrorType = 1403 // Item not found - ErrMarketItemAlreadyAdded ErrorType = 1404 // Item already added to album - ErrMarketTooManyItems ErrorType = 1405 // Too many items - ErrMarketTooManyItemsInAlbum ErrorType = 1406 // Too many items in album - ErrMarketTooManyAlbums ErrorType = 1407 // Too many albums - ErrMarketItemHasBadLinks ErrorType = 1408 // Item has bad links in description - ErrMarketShopNotEnabled ErrorType = 1409 // Shop not enabled - ErrMarketCartEmpty ErrorType = 1427 // Cart is empty - ErrMarketSpecifyDimensions ErrorType = 1429 // Specify width, length, height and weight all together - ErrVKPayStatus ErrorType = 1430 // VK Pay status can not be changed - ErrMarketAlreadyEnabled ErrorType = 1431 // Market was already enabled in this group - ErrMarketAlreadyDisabled ErrorType = 1432 // Market was already disabled in this group - ErrStoryExpired ErrorType = 1600 // Story has already expired - ErrStoryIncorrectReplyPrivacy ErrorType = 1602 // Incorrect reply privacy - ErrPrettyCardsCardNotFound ErrorType = 1900 // Card not found - ErrPrettyCardsTooManyCards ErrorType = 1901 // Too many cards - ErrPrettyCardsCardIsConnectedToPost ErrorType = 1902 // Card is connected to post - ErrCallbackServersLimit ErrorType = 2000 // Servers number limit is reached - ErrRecaptcha ErrorType = 3300 // Recaptcha needed - ErrPhoneValidation ErrorType = 3301 // Phone validation needed - ErrPasswordValidation ErrorType = 3302 // Password validation needed - ErrOtpAppValidation ErrorType = 3303 // Otp app validation needed - ErrEmailConfirmation ErrorType = 3304 // Email confirmation needed - ErrAssertVotes ErrorType = 3305 // Assert votes - ErrTokenExtension ErrorType = 3609 // Token extension required - ErrUserDeactivated ErrorType = 3610 // User is deactivated - ErrServiceDeactivated ErrorType = 3611 // Service is deactivated for user - ErrAliExpressTag ErrorType = 3800 // Can't set AliExpress tag to this type of object + ErrVotesPermission ErrorType = 500 + + // Not enough votes. + ErrVotes ErrorType = 503 + + // Not enough money on owner's balance. + ErrNotEnoughMoney ErrorType = 504 + + // Permission denied. You have no access to operations specified with + // given object(s). + ErrAdsPermission ErrorType = 600 + + // Permission denied. You have requested too many actions this day. Try + // later. + ErrWeightedFlood ErrorType = 601 + + // Some part of the request has not been completed. + ErrAdsPartialSuccess ErrorType = 602 + + // Some ads error occurred. + ErrAdsSpecific ErrorType = 603 + + // Object deleted. + ErrAdsObjectDeleted ErrorType = 629 + + // Cannot edit creator role. + ErrGroupChangeCreator ErrorType = 700 + + // User should be in club. + ErrGroupNotInClub ErrorType = 701 + + // Too many officers in club. + ErrGroupTooManyOfficers ErrorType = 702 + + // You need to enable 2FA for this action. + ErrGroupNeed2fa ErrorType = 703 + + // User needs to enable 2FA for this action. + ErrGroupHostNeed2fa ErrorType = 704 + + // Too many addresses in club. + ErrGroupTooManyAddresses ErrorType = 706 + + // "Application is not installed in community. + ErrGroupAppIsNotInstalledInCommunity ErrorType = 711 + + // Invite link is invalid - expired, deleted or not exists. + ErrGroupInvalidInviteLink ErrorType = 714 + + // This video is already added. + ErrVideoAlreadyAdded ErrorType = 800 + + // Comments for this video are closed. + ErrVideoCommentsClosed ErrorType = 801 + + // Can't send messages for users from blacklist. + ErrMessagesUserBlocked ErrorType = 900 + + // Can't send messages for users without permission. + ErrMessagesDenySend ErrorType = 901 + + // Can't send messages to this user due to their privacy settings. + ErrMessagesPrivacy ErrorType = 902 + + // Value of ts or pts is too old. + ErrMessagesTooOldPts ErrorType = 907 + + // Value of ts or pts is too new. + ErrMessagesTooNewPts ErrorType = 908 + + // Can't edit this message, because it's too old. + ErrMessagesEditExpired ErrorType = 909 + + // Can't sent this message, because it's too big. + ErrMessagesTooBig ErrorType = 910 + + // Keyboard format is invalid. + ErrMessagesKeyboardInvalid ErrorType = 911 + + // This is a chat bot feature, change this status in settings. + ErrMessagesChatBotFeature ErrorType = 912 + + // Too many forwarded messages. + ErrMessagesTooLongForwards ErrorType = 913 + + // Message is too long. + ErrMessagesTooLongMessage ErrorType = 914 + + // You don't have access to this chat. + ErrMessagesChatUserNoAccess ErrorType = 917 + + // You can't see invite link for this chat. + ErrMessagesCantSeeInviteLink ErrorType = 919 + + // Can't edit this kind of message. + ErrMessagesEditKindDisallowed ErrorType = 920 + + // Can't forward these messages. + ErrMessagesCantFwd ErrorType = 921 + + // Can't delete this message for everybody. + ErrMessagesCantDeleteForAll ErrorType = 924 + + // You are not admin of this chat. + ErrMessagesChatNotAdmin ErrorType = 925 + + // Chat does not exist. + ErrMessagesChatNotExist ErrorType = 927 + + // You can't change invite link for this chat. + ErrMessagesCantChangeInviteLink ErrorType = 931 + + // Your community can't interact with this peer. + ErrMessagesGroupPeerAccess ErrorType = 932 + + // User not found in chat. + ErrMessagesChatUserNotInChat ErrorType = 935 + + // Contact not found. + ErrMessagesContactNotFound ErrorType = 936 + + // Message request already send. + ErrMessagesMessageRequestAlreadySend ErrorType = 939 + + // Too many posts in messages. + ErrMessagesTooManyPosts ErrorType = 940 + + // Cannot use this intent. + ErrMessagesCantUseIntent ErrorType = 943 + + // Limits overflow for this intent. + ErrMessagesLimitIntent ErrorType = 944 + + // Chat was disabled. + ErrMessagesChatDisabled ErrorType = 945 + + // Chat not support. + ErrMessagesChatNotSupported ErrorType = 946 + + // Can't add user to chat, because user has no access to group. + ErrMessagesMemberAccessToGroupDenied ErrorType = 947 + + // Can't edit pinned message yet. + ErrMessagesEditPinned ErrorType = 949 + + // Can't send message, reply timed out. + ErrMessagesReplyTimedOut ErrorType = 950 + + // Invalid phone number. + ErrParamPhone ErrorType = 1000 + + // This phone number is used by another user. + ErrPhoneAlreadyUsed ErrorType = 1004 + + // Too many auth attempts, try again later. + ErrAuthFloodError ErrorType = 1105 + + // Processing.. Try later. + ErrAuthDelay ErrorType = 1112 + + // Invalid document id. + ErrParamDocID ErrorType = 1150 + + // Access to document deleting is denied. + ErrParamDocDeleteAccess ErrorType = 1151 + + // Invalid document title. + ErrParamDocTitle ErrorType = 1152 + + // Access to document is denied. + ErrParamDocAccess ErrorType = 1153 + + // Original photo was changed. + ErrPhotoChanged ErrorType = 1160 + + // Too many feed lists. + ErrTooManyLists ErrorType = 1170 + + // This achievement is already unlocked. + ErrAppsAlreadyUnlocked ErrorType = 1251 + + // Subscription not found. + ErrAppsSubscriptionNotFound ErrorType = 1256 + + // Subscription is in invalid status. + ErrAppsSubscriptionInvalidStatus ErrorType = 1257 + + // Invalid screen name. + ErrInvalidAddress ErrorType = 1260 + + // Catalog is not available for this user. + ErrCommunitiesCatalogDisabled ErrorType = 1310 + + // Catalog categories are not available for this user. + ErrCommunitiesCategoriesDisabled ErrorType = 1311 + + // Too late for restore. + ErrMarketRestoreTooLate ErrorType = 1400 + + // Comments for this market are closed. + ErrMarketCommentsClosed ErrorType = 1401 + + // Album not found. + ErrMarketAlbumNotFound ErrorType = 1402 + + // Item not found. + ErrMarketItemNotFound ErrorType = 1403 + + // Item already added to album. + ErrMarketItemAlreadyAdded ErrorType = 1404 + + // Too many items. + ErrMarketTooManyItems ErrorType = 1405 + + // Too many items in album. + ErrMarketTooManyItemsInAlbum ErrorType = 1406 + + // Too many albums. + ErrMarketTooManyAlbums ErrorType = 1407 + + // Item has bad links in description. + ErrMarketItemHasBadLinks ErrorType = 1408 + + // Shop not enabled. + ErrMarketShopNotEnabled ErrorType = 1409 + + // Cart is empty. + ErrMarketCartEmpty ErrorType = 1427 + + // Specify width, length, height and weight all together. + ErrMarketSpecifyDimensions ErrorType = 1429 + + // VK Pay status can not be changed. + ErrVKPayStatus ErrorType = 1430 + + // Market was already enabled in this group. + ErrMarketAlreadyEnabled ErrorType = 1431 + + // Market was already disabled in this group. + ErrMarketAlreadyDisabled ErrorType = 1432 + + // Story has already expired. + ErrStoryExpired ErrorType = 1600 + + // Incorrect reply privacy. + ErrStoryIncorrectReplyPrivacy ErrorType = 1602 + + // Card not found. + ErrPrettyCardsCardNotFound ErrorType = 1900 + + // Too many cards. + ErrPrettyCardsTooManyCards ErrorType = 1901 + + // Card is connected to post. + ErrPrettyCardsCardIsConnectedToPost ErrorType = 1902 + + // Servers number limit is reached. + ErrCallbackServersLimit ErrorType = 2000 + + // Recaptcha needed. + ErrRecaptcha ErrorType = 3300 + + // Phone validation needed. + ErrPhoneValidation ErrorType = 3301 + + // Password validation needed. + ErrPasswordValidation ErrorType = 3302 + + // Otp app validation needed. + ErrOtpAppValidation ErrorType = 3303 + + // Email confirmation needed. + ErrEmailConfirmation ErrorType = 3304 + + // Assert votes. + ErrAssertVotes ErrorType = 3305 + + // Token extension required. + ErrTokenExtension ErrorType = 3609 + + // User is deactivated. + ErrUserDeactivated ErrorType = 3610 + + // Service is deactivated for user. + ErrServiceDeactivated ErrorType = 3611 + + // Can't set AliExpress tag to this type of object. + ErrAliExpressTag ErrorType = 3800 ) // Error struct VK. @@ -361,7 +629,8 @@ type Error struct { // // The app should display the default confirmation window with text from // confirmation_text and two buttons: "Continue" and "Cancel". If user - // confirms the action repeat the request with an extra parameter: confirm = 1. + // confirms the action repeat the request with an extra parameter: + // confirm = 1. // // See https://vk.com/dev/need_confirmation ConfirmationText string `json:"confirmation_text"` diff --git a/api/groups.go b/api/groups.go index ccb1091c..62fcf108 100644 --- a/api/groups.go +++ b/api/groups.go @@ -232,7 +232,10 @@ type GroupsGetCallbackConfirmationCodeResponse struct { // GroupsGetCallbackConfirmationCode returns Callback API confirmation code for the community. // // https://vk.com/dev/groups.getCallbackConfirmationCode -func (vk *VK) GroupsGetCallbackConfirmationCode(params Params) (response GroupsGetCallbackConfirmationCodeResponse, err error) { +func (vk *VK) GroupsGetCallbackConfirmationCode(params Params) ( + response GroupsGetCallbackConfirmationCodeResponse, + err error, +) { err = vk.RequestUnmarshal("groups.getCallbackConfirmationCode", params, &response) return } @@ -425,7 +428,10 @@ type GroupsGetMembersFilterManagersResponse struct { // filter=managers // // https://vk.com/dev/groups.getMembers -func (vk *VK) GroupsGetMembersFilterManagers(params Params) (response GroupsGetMembersFilterManagersResponse, err error) { +func (vk *VK) GroupsGetMembersFilterManagers(params Params) ( + response GroupsGetMembersFilterManagersResponse, + err error, +) { params["filter"] = "managers" err = vk.RequestUnmarshal("groups.getMembers", params, &response) diff --git a/api/groups_test.go b/api/groups_test.go index cb166d0f..13532ce6 100644 --- a/api/groups_test.go +++ b/api/groups_test.go @@ -307,7 +307,58 @@ func TestVK_GroupsGet(t *testing.T) { res, err := vkUser.GroupsGet(api.Params{ "user_id": 117253521, - "fields": "market,member_status,is_favorite,is_subscribed,city,country,verified,description,wiki_page,members_count,counters,cover,can_post,can_see_all_posts,activity,fixed_post,can_create_topic,can_upload_video,has_photo,status,main_album_id,links,contacts,site,main_section,trending,can_message,is_market_cart_enabled,is_messages_blocked,can_send_notify,online_status,start_date,finish_date,age_limits,ban_info,action_button,author_id,phone,has_market_app,addresses,live_covers,is_adult,can_subscribe_posts,warning_notification,can_upload_doc,crop_photo,is_hidden_from_feed,place,public_date_label,wall", + "fields": []string{ + "market", + "member_status", + "is_favorite", + "is_subscribed", + "city", + "country", + "verified", + "description", + "wiki_page", + "members_count", + "counters", + "cover", + "can_post", + "can_see_all_posts", + "activity", + "fixed_post", + "can_create_topic", + "can_upload_video", + "has_photo", + "status", + "main_album_id", + "links", + "contacts", + "site", + "main_section", + "trending", + "can_message", + "is_market_cart_enabled", + "is_messages_blocked", + "can_send_notify", + "online_status", + "start_date", + "finish_date", + "age_limits", + "ban_info", + "action_button", + "author_id", + "phone", + "has_market_app", + "addresses", + "live_covers", + "is_adult", + "can_subscribe_posts", + "warning_notification", + "can_upload_doc", + "crop_photo", + "is_hidden_from_feed", + "place", + "public_date_label", + "wall", + }, }) noError(t, err) assert.NotEmpty(t, res.Count) @@ -321,7 +372,58 @@ func TestVK_GroupsGetExtended(t *testing.T) { res, err := vkUser.GroupsGetExtended(api.Params{ "user_id": 117253521, - "fields": "market,member_status,is_favorite,is_subscribed,city,country,verified,description,wiki_page,members_count,counters,cover,can_post,can_see_all_posts,activity,fixed_post,can_create_topic,can_upload_video,has_photo,status,main_album_id,links,contacts,site,main_section,trending,can_message,is_market_cart_enabled,is_messages_blocked,can_send_notify,online_status,start_date,finish_date,age_limits,ban_info,action_button,author_id,phone,has_market_app,addresses,live_covers,is_adult,can_subscribe_posts,warning_notification,can_upload_doc,crop_photo,is_hidden_from_feed,place,public_date_label,wall", + "fields": []string{ + "market", + "member_status", + "is_favorite", + "is_subscribed", + "city", + "country", + "verified", + "description", + "wiki_page", + "members_count", + "counters", + "cover", + "can_post", + "can_see_all_posts", + "activity", + "fixed_post", + "can_create_topic", + "can_upload_video", + "has_photo", + "status", + "main_album_id", + "links", + "contacts", + "site", + "main_section", + "trending", + "can_message", + "is_market_cart_enabled", + "is_messages_blocked", + "can_send_notify", + "online_status", + "start_date", + "finish_date", + "age_limits", + "ban_info", + "action_button", + "author_id", + "phone", + "has_market_app", + "addresses", + "live_covers", + "is_adult", + "can_subscribe_posts", + "warning_notification", + "can_upload_doc", + "crop_photo", + "is_hidden_from_feed", + "place", + "public_date_label", + "wall", + }, }) noError(t, err) assert.NotEmpty(t, res.Count) @@ -371,7 +473,58 @@ func TestVK_GroupsGetByID(t *testing.T) { res, err := vkGroup.GroupsGetByID(api.Params{ "group_ids": "apiclub", - "fields": "market,member_status,is_favorite,is_subscribed,city,country,verified,description,wiki_page,members_count,counters,cover,can_post,can_see_all_posts,activity,fixed_post,can_create_topic,can_upload_video,has_photo,status,main_album_id,links,contacts,site,main_section,trending,can_message,is_market_cart_enabled,is_messages_blocked,can_send_notify,online_status,start_date,finish_date,age_limits,ban_info,action_button,author_id,phone,has_market_app,addresses,live_covers,is_adult,can_subscribe_posts,warning_notification,can_upload_doc,crop_photo,is_hidden_from_feed,place,public_date_label,wall", + "fields": []string{ + "market", + "member_status", + "is_favorite", + "is_subscribed", + "city", + "country", + "verified", + "description", + "wiki_page", + "members_count", + "counters", + "cover", + "can_post", + "can_see_all_posts", + "activity", + "fixed_post", + "can_create_topic", + "can_upload_video", + "has_photo", + "status", + "main_album_id", + "links", + "contacts", + "site", + "main_section", + "trending", + "can_message", + "is_market_cart_enabled", + "is_messages_blocked", + "can_send_notify", + "online_status", + "start_date", + "finish_date", + "age_limits", + "ban_info", + "action_button", + "author_id", + "phone", + "has_market_app", + "addresses", + "live_covers", + "is_adult", + "can_subscribe_posts", + "warning_notification", + "can_upload_doc", + "crop_photo", + "is_hidden_from_feed", + "place", + "public_date_label", + "wall", + }, }) noError(t, err) @@ -454,7 +607,58 @@ func TestVK_GroupsGetByID_private(t *testing.T) { res, err := vkGroup.GroupsGetByID(api.Params{ "group_ids": "184580855", - "fields": "market,member_status,is_favorite,is_subscribed,city,country,verified,description,wiki_page,members_count,counters,cover,can_post,can_see_all_posts,activity,fixed_post,can_create_topic,can_upload_video,has_photo,status,main_album_id,links,contacts,site,main_section,trending,can_message,is_market_cart_enabled,is_messages_blocked,can_send_notify,online_status,start_date,finish_date,age_limits,ban_info,action_button,author_id,phone,has_market_app,addresses,live_covers,is_adult,can_subscribe_posts,warning_notification,can_upload_doc,crop_photo,is_hidden_from_feed,place,public_date_label,wall", + "fields": []string{ + "market", + "member_status", + "is_favorite", + "is_subscribed", + "city", + "country", + "verified", + "description", + "wiki_page", + "members_count", + "counters", + "cover", + "can_post", + "can_see_all_posts", + "activity", + "fixed_post", + "can_create_topic", + "can_upload_video", + "has_photo", + "status", + "main_album_id", + "links", + "contacts", + "site", + "main_section", + "trending", + "can_message", + "is_market_cart_enabled", + "is_messages_blocked", + "can_send_notify", + "online_status", + "start_date", + "finish_date", + "age_limits", + "ban_info", + "action_button", + "author_id", + "phone", + "has_market_app", + "addresses", + "live_covers", + "is_adult", + "can_subscribe_posts", + "warning_notification", + "can_upload_doc", + "crop_photo", + "is_hidden_from_feed", + "place", + "public_date_label", + "wall", + }, }) noError(t, err) diff --git a/api/messages.go b/api/messages.go index df3d8dd1..c13cb267 100644 --- a/api/messages.go +++ b/api/messages.go @@ -100,7 +100,10 @@ type MessagesGetByConversationMessageIDResponse struct { // MessagesGetByConversationMessageID messages.getByConversationMessageId. // // https://vk.com/dev/messages.getByConversationMessageId -func (vk *VK) MessagesGetByConversationMessageID(params Params) (response MessagesGetByConversationMessageIDResponse, err error) { +func (vk *VK) MessagesGetByConversationMessageID(params Params) ( + response MessagesGetByConversationMessageIDResponse, + err error, +) { err = vk.RequestUnmarshal("messages.getByConversationMessageId", params, &response) return } @@ -201,7 +204,10 @@ type MessagesGetConversationMembersResponse struct { // MessagesGetConversationMembers returns a list of IDs of users participating in a conversation. // // https://vk.com/dev/messages.getConversationMembers -func (vk *VK) MessagesGetConversationMembers(params Params) (response MessagesGetConversationMembersResponse, err error) { +func (vk *VK) MessagesGetConversationMembers(params Params) ( + response MessagesGetConversationMembersResponse, + err error, +) { err = vk.RequestUnmarshal("messages.getConversationMembers", params, &response) return } @@ -252,7 +258,10 @@ type MessagesGetConversationsByIDExtendedResponse struct { // extended=1 // // https://vk.com/dev/messages.getConversationsById -func (vk *VK) MessagesGetConversationsByIDExtended(params Params) (response MessagesGetConversationsByIDExtendedResponse, err error) { +func (vk *VK) MessagesGetConversationsByIDExtended(params Params) ( + response MessagesGetConversationsByIDExtendedResponse, + err error, +) { params["extended"] = true err = vk.RequestUnmarshal("messages.getConversationsById", params, &response) @@ -377,7 +386,10 @@ type MessagesIsMessagesFromGroupAllowedResponse struct { // sending messages from the community to current user is allowed. // // https://vk.com/dev/messages.isMessagesFromGroupAllowed -func (vk *VK) MessagesIsMessagesFromGroupAllowed(params Params) (response MessagesIsMessagesFromGroupAllowedResponse, err error) { +func (vk *VK) MessagesIsMessagesFromGroupAllowed(params Params) ( + response MessagesIsMessagesFromGroupAllowedResponse, + err error, +) { err = vk.RequestUnmarshal("messages.isMessagesFromGroupAllowed", params, &response) return } @@ -441,7 +453,9 @@ func (vk *VK) MessagesPin(params Params) (response MessagesPinResponse, err erro return } -// MessagesRemoveChatUser allows the current user to leave a chat or, if the current user started the chat, allows the user to remove another user from the chat. +// MessagesRemoveChatUser allows the current user to leave a chat or, if the +// current user started the chat, allows the user to remove another user from +// the chat. // // https://vk.com/dev/messages.removeChatUser func (vk *VK) MessagesRemoveChatUser(params Params) (response int, err error) { diff --git a/api/photos.go b/api/photos.go index 873aa72f..cee68d55 100644 --- a/api/photos.go +++ b/api/photos.go @@ -305,7 +305,10 @@ type PhotosGetMarketAlbumUploadServerResponse struct { // PhotosGetMarketAlbumUploadServer returns the server address for market album photo upload. // // https://vk.com/dev/photos.getMarketAlbumUploadServer -func (vk *VK) PhotosGetMarketAlbumUploadServer(params Params) (response PhotosGetMarketAlbumUploadServerResponse, err error) { +func (vk *VK) PhotosGetMarketAlbumUploadServer(params Params) ( + response PhotosGetMarketAlbumUploadServerResponse, + err error, +) { err = vk.RequestUnmarshal("photos.getMarketAlbumUploadServer", params, &response) return } @@ -361,7 +364,10 @@ type PhotosGetOwnerCoverPhotoUploadServerResponse struct { // PhotosGetOwnerCoverPhotoUploadServer receives server address for uploading community cover. // // https://vk.com/dev/photos.getOwnerCoverPhotoUploadServer -func (vk *VK) PhotosGetOwnerCoverPhotoUploadServer(params Params) (response PhotosGetOwnerCoverPhotoUploadServerResponse, err error) { +func (vk *VK) PhotosGetOwnerCoverPhotoUploadServer(params Params) ( + response PhotosGetOwnerCoverPhotoUploadServerResponse, + err error, +) { err = vk.RequestUnmarshal("photos.getOwnerCoverPhotoUploadServer", params, &response) return } @@ -371,10 +377,14 @@ type PhotosGetOwnerPhotoUploadServerResponse struct { UploadURL string `json:"upload_url"` } -// PhotosGetOwnerPhotoUploadServer returns an upload server address for a profile or community photo. +// PhotosGetOwnerPhotoUploadServer returns an upload server address for a +// profile or community photo. // // https://vk.com/dev/photos.getOwnerPhotoUploadServer -func (vk *VK) PhotosGetOwnerPhotoUploadServer(params Params) (response PhotosGetOwnerPhotoUploadServerResponse, err error) { +func (vk *VK) PhotosGetOwnerPhotoUploadServer(params Params) ( + response PhotosGetOwnerPhotoUploadServerResponse, + err error, +) { err = vk.RequestUnmarshal("photos.getOwnerPhotoUploadServer", params, &response) return } diff --git a/api/secure.go b/api/secure.go index 0fc8fcf4..55423a81 100644 --- a/api/secure.go +++ b/api/secure.go @@ -37,7 +37,8 @@ func (vk *VK) SecureGetAppBalance(params Params) (response int, err error) { // SecureGetSMSHistoryResponse struct. type SecureGetSMSHistoryResponse []object.SecureSmsNotification -// SecureGetSMSHistory shows a list of SMS notifications sent by the application using secure.sendSMSNotification method. +// SecureGetSMSHistory shows a list of SMS notifications sent by the +// application using secure.sendSMSNotification method. // // https://vk.com/dev/secure.getSMSHistory func (vk *VK) SecureGetSMSHistory(params Params) (response SecureGetSMSHistoryResponse, err error) { diff --git a/api/upload.go b/api/upload.go index d3603cef..a199082d 100644 --- a/api/upload.go +++ b/api/upload.go @@ -175,7 +175,10 @@ func (vk *VK) UploadGroupWallPhoto(groupID int, file io.Reader) (response Photos // // Limits: size not less than 200x200px, aspect ratio from 0.25 to 3, // width+height not more than 14000 px, file size up to 50 Mb. -func (vk *VK) uploadOwnerPhoto(params Params, squareCrop string, file io.Reader) (response PhotosSaveOwnerPhotoResponse, err error) { +func (vk *VK) uploadOwnerPhoto(params Params, squareCrop string, file io.Reader) ( + response PhotosSaveOwnerPhotoResponse, + err error, +) { uploadServer, err := vk.PhotosGetOwnerPhotoUploadServer(params) if err != nil { return @@ -255,7 +258,10 @@ func (vk *VK) UploadUserPhoto(file io.Reader) (response PhotosSaveOwnerPhotoResp // // Limits: size not less than 200x200px, aspect ratio from 0.25 to 3, // width+height not more than 14000 px, file size up to 50 Mb. -func (vk *VK) UploadOwnerPhoto(ownerID int, squareCrop string, file io.Reader) (response PhotosSaveOwnerPhotoResponse, err error) { +func (vk *VK) UploadOwnerPhoto(ownerID int, squareCrop string, file io.Reader) ( + response PhotosSaveOwnerPhotoResponse, + err error, +) { response, err = vk.uploadOwnerPhoto(Params{ "owner_id": ownerID, }, squareCrop, file) @@ -352,7 +358,10 @@ func (vk *VK) UploadChatPhoto(chatID int, file io.Reader) (response MessagesSetC // Limits: size not less than 200x200px, // width+height not more than 14000 px, file size up to 50 Mb, // aspect ratio of at least 1:20. -func (vk *VK) UploadChatPhotoCrop(chatID, cropX, cropY, cropWidth int, file io.Reader) (response MessagesSetChatPhotoResponse, err error) { +func (vk *VK) UploadChatPhotoCrop(chatID, cropX, cropY, cropWidth int, file io.Reader) ( + response MessagesSetChatPhotoResponse, + err error, +) { response, err = vk.uploadChatPhoto(Params{ "chat_id": chatID, "crop_x": cropX, @@ -407,7 +416,10 @@ func (vk *VK) uploadMarketPhoto(params Params, file io.Reader) (response PhotosS // Limits: size not less than 400x400px, // width+height not more than 14000 px, file size up to 50 Mb, // aspect ratio of at least 1:20. -func (vk *VK) UploadMarketPhoto(groupID int, mainPhoto bool, file io.Reader) (response PhotosSaveMarketPhotoResponse, err error) { +func (vk *VK) UploadMarketPhoto(groupID int, mainPhoto bool, file io.Reader) ( + response PhotosSaveMarketPhotoResponse, + err error, +) { response, err = vk.uploadMarketPhoto(Params{ "group_id": groupID, "main_photo": mainPhoto, @@ -423,7 +435,10 @@ func (vk *VK) UploadMarketPhoto(groupID int, mainPhoto bool, file io.Reader) (re // Limits: size not less than 400x400px, // width+height not more than 14000 px, file size up to 50 Mb, // aspect ratio of at least 1:20. -func (vk *VK) UploadMarketPhotoCrop(groupID, cropX, cropY, cropWidth int, file io.Reader) (response PhotosSaveMarketPhotoResponse, err error) { +func (vk *VK) UploadMarketPhotoCrop(groupID, cropX, cropY, cropWidth int, file io.Reader) ( + response PhotosSaveMarketPhotoResponse, + err error, +) { response, err = vk.uploadMarketPhoto(Params{ "group_id": groupID, "main_photo": true, @@ -442,7 +457,10 @@ func (vk *VK) UploadMarketPhotoCrop(groupID, cropX, cropY, cropWidth int, file i // Limits: size not less than 1280x720px, // width+height not more than 14000 px, file size up to 50 Mb, // aspect ratio of at least 1:20. -func (vk *VK) UploadMarketAlbumPhoto(groupID int, file io.Reader) (response PhotosSaveMarketAlbumPhotoResponse, err error) { +func (vk *VK) UploadMarketAlbumPhoto(groupID int, file io.Reader) ( + response PhotosSaveMarketAlbumPhotoResponse, + err error, +) { uploadServer, err := vk.PhotosGetMarketAlbumUploadServer(Params{ "group_id": groupID, }) @@ -462,14 +480,12 @@ func (vk *VK) UploadMarketAlbumPhoto(groupID int, file io.Reader) (response Phot return } - response, err = vk.PhotosSaveMarketAlbumPhoto(Params{ + return vk.PhotosSaveMarketAlbumPhoto(Params{ "group_id": groupID, "server": handler.Server, "photo": handler.Photo, "hash": handler.Hash, }) - - return } // UploadVideo uploading Video Files. @@ -594,7 +610,10 @@ func (vk *VK) UploadWallDoc(title, tags string, file io.Reader) (response DocsSa // Supported formats: any formats excepting mp3 and executable files. // // Limits: file size up to 200 MB. -func (vk *VK) UploadGroupWallDoc(groupID int, title, tags string, file io.Reader) (response DocsSaveResponse, err error) { +func (vk *VK) UploadGroupWallDoc(groupID int, title, tags string, file io.Reader) ( + response DocsSaveResponse, + err error, +) { uploadServer, err := vk.DocsGetWallUploadServer(Params{ "group_id": groupID, }) @@ -612,7 +631,10 @@ func (vk *VK) UploadGroupWallDoc(groupID int, title, tags string, file io.Reader // Supported formats: any formats excepting mp3 and executable files. // // Limits: file size up to 200 MB. -func (vk *VK) UploadMessagesDoc(peerID int, typeDoc, title, tags string, file io.Reader) (response DocsSaveResponse, err error) { +func (vk *VK) UploadMessagesDoc(peerID int, typeDoc, title, tags string, file io.Reader) ( + response DocsSaveResponse, + err error, +) { uploadServer, err := vk.DocsGetMessagesUploadServer(Params{ "peer_id": peerID, "type": typeDoc, @@ -632,7 +654,10 @@ func (vk *VK) UploadMessagesDoc(peerID int, typeDoc, title, tags string, file io // // Limits: minimum photo size 795x200px, width+height not more than 14000px, // file size up to 50 MB. Recommended size: 1590x400px. -func (vk *VK) UploadOwnerCoverPhoto(groupID, cropX, cropY, cropX2, cropY2 int, file io.Reader) (response PhotosSaveOwnerCoverPhotoResponse, err error) { +func (vk *VK) UploadOwnerCoverPhoto(groupID, cropX, cropY, cropX2, cropY2 int, file io.Reader) ( + response PhotosSaveOwnerCoverPhotoResponse, + err error, +) { uploadServer, err := vk.PhotosGetOwnerCoverPhotoUploadServer(Params{ "group_id": groupID, "crop_x": cropX, @@ -656,12 +681,10 @@ func (vk *VK) UploadOwnerCoverPhoto(groupID, cropX, cropY, cropX2, cropY2 int, f return } - response, err = vk.PhotosSaveOwnerCoverPhoto(Params{ + return vk.PhotosSaveOwnerCoverPhoto(Params{ "photo": handler.Photo, "hash": handler.Hash, }) - - return } // UploadStories struct. diff --git a/api/users.go b/api/users.go index 1173a12d..30f3508d 100644 --- a/api/users.go +++ b/api/users.go @@ -21,7 +21,8 @@ type UsersGetFollowersResponse struct { Items []int `json:"items"` } -// UsersGetFollowers returns a list of IDs of followers of the user in question, sorted by date added, most recent first. +// UsersGetFollowers returns a list of IDs of followers of the user in +// question, sorted by date added, most recent first. // // fields=""; // @@ -39,7 +40,8 @@ type UsersGetFollowersFieldsResponse struct { Items []object.UsersUser `json:"items"` } -// UsersGetFollowersFields returns a list of IDs of followers of the user in question, sorted by date added, most recent first. +// UsersGetFollowersFields returns a list of IDs of followers of the user in +// question, sorted by date added, most recent first. // // fields not empty. // diff --git a/api/users_test.go b/api/users_test.go index 8961b8d5..dc838d1a 100644 --- a/api/users_test.go +++ b/api/users_test.go @@ -15,7 +15,69 @@ func TestVK_UsersGet(t *testing.T) { res, err := vkUser.UsersGet(api.Params{ "user_ids": 1, - "fields": "photo_id, verified, sex, bdate, city, country, home_town, has_photo, photo_50, photo_100, photo_200_orig, photo_200, photo_400_orig, photo_max, photo_max_orig, online, domain, has_mobile, contacts, site, education, universities, schools, status, last_seen, followers_count, common_count, occupation, nickname, relatives, relation, personal, connections, exports, activities, interests, music, movies, tv, books, games, about, quotes, can_post, can_see_all_posts, can_see_audio, can_write_private_message, can_send_friend_request, is_favorite, is_hidden_from_feed, timezone, screen_name, maiden_name, crop_photo, is_friend, friend_status, career, military, blacklisted, blacklisted_by_me, can_be_invited_group", + "fields": []string{ + "photo_id", + "verified", + "sex", + "bdate", + "city", + "country", + "home_town", + "has_photo", + "photo_50", + "photo_100", + "photo_200_orig", + "photo_200", + "photo_400_orig", + "photo_max", + "photo_max_orig", + "online", + "domain", + "has_mobile", + "contacts", + "site", + "education", + "universities", + "schools", + "status", + "last_seen", + "followers_count", + "common_count", + "occupation", + "nickname", + "relatives", + "relation", + "personal", + "connections", + "exports", + "activities", + "interests", + "music", + "movies", + "tv", + "books", + "games", + "about", + "quotes", + "can_post", + "can_see_all_posts", + "can_see_audio", + "can_write_private_message", + "can_send_friend_request", + "is_favorite", + "is_hidden_from_feed", + "timezone", + "screen_name", + "maiden_name", + "crop_photo", + "is_friend", + "friend_status", + "career", + "military", + "blacklisted", + "blacklisted_by_me", + "can_be_invited_group", + }, }) noError(t, err) diff --git a/foaf/foaf.go b/foaf/foaf.go index e0e81f41..e4780430 100644 --- a/foaf/foaf.go +++ b/foaf/foaf.go @@ -1,7 +1,8 @@ /* Package foaf wrapper for FOAF. -Specification https://web.archive.org/web/20140909053226/http://api.yandex.ru/blogs/doc/indexation/concepts/what-is-foaf.xml +Specification +https://web.archive.org/web/20140909053226/http://api.yandex.ru/blogs/doc/indexation/concepts/what-is-foaf.xml */ package foaf // import "github.com/SevereCloud/vksdk/foaf" diff --git a/object/account.go b/object/account.go index 9357b950..abe3cef3 100644 --- a/object/account.go +++ b/object/account.go @@ -78,13 +78,27 @@ type AccountAccountCounters struct { // AccountInfo struct. type AccountInfo struct { - Country string `json:"country"` // Country code - Lang int `json:"lang"` // Language ID - HTTPSRequired BaseBoolInt `json:"https_required"` // Information whether HTTPS-only is enabled - Intro BaseBoolInt `json:"intro"` // Information whether user has been processed intro - NoWallReplies BaseBoolInt `json:"no_wall_replies"` // Information whether wall comments should be hidden - OwnPostsDefault BaseBoolInt `json:"own_posts_default"` // Information whether only owners posts should be shown - TwoFactorRequired BaseBoolInt `json:"2fa_required"` // Two factor authentication is enabled + + // Country code. + Country string `json:"country"` + + // Language ID. + Lang int `json:"lang"` + + // Information whether HTTPS-only is enabled. + HTTPSRequired BaseBoolInt `json:"https_required"` + + // Information whether user has been processed intro. + Intro BaseBoolInt `json:"intro"` + + // Information whether wall comments should be hidden. + NoWallReplies BaseBoolInt `json:"no_wall_replies"` + + // Information whether only owners posts should be shown. + OwnPostsDefault BaseBoolInt `json:"own_posts_default"` + + // Two factor authentication is enabled. + TwoFactorRequired BaseBoolInt `json:"2fa_required"` EuUser BaseBoolInt `json:"eu_user"` CommunityComments BaseBoolInt `json:"community_comments"` IsLiveStreamingEnabled BaseBoolInt `json:"is_live_streaming_enabled"` @@ -95,9 +109,13 @@ type AccountInfo struct { // AccountPushSettings struct. type AccountPushSettings struct { Conversations AccountPushConversations `json:"conversations"` - Disabled BaseBoolInt `json:"disabled"` // Information whether notifications are disabled - DisabledUntil int `json:"disabled_until"` // Time until that notifications are disabled in Unixtime - Settings AccountPushParams `json:"settings"` + + // Information whether notifications are disabled. + Disabled BaseBoolInt `json:"disabled"` + + // Time until that notifications are disabled in Unixtime. + DisabledUntil int `json:"disabled_until"` + Settings AccountPushParams `json:"settings"` } // AccountUserSettings struct. diff --git a/object/ads.go b/object/ads.go index 7680e667..f7b385dc 100644 --- a/object/ads.go +++ b/object/ads.go @@ -60,19 +60,21 @@ type AdsClient struct { // AdsCriteria struct. type AdsCriteria struct { - AgeFrom int `json:"age_from"` // Age from - AgeTo int `json:"age_to"` // Age to - Apps string `json:"apps"` // Apps IDs - AppsNot string `json:"apps_not"` // Apps IDs to except - Birthday int `json:"birthday"` // Days to birthday - Cities string `json:"cities"` // Cities IDs - CitiesNot string `json:"cities_not"` // Cities IDs to except - Country int `json:"country"` // Country ID - Districts string `json:"districts"` // Districts IDs - Groups string `json:"groups"` // Communities IDs - InterestCategories string `json:"interest_categories"` // Interests categories IDs - Interests string `json:"interests"` // Interests - Paying BaseBoolInt `json:"paying"` // Information whether the user has proceeded VK payments before + AgeFrom int `json:"age_from"` // Age from + AgeTo int `json:"age_to"` // Age to + Apps string `json:"apps"` // Apps IDs + AppsNot string `json:"apps_not"` // Apps IDs to except + Birthday int `json:"birthday"` // Days to birthday + Cities string `json:"cities"` // Cities IDs + CitiesNot string `json:"cities_not"` // Cities IDs to except + Country int `json:"country"` // Country ID + Districts string `json:"districts"` // Districts IDs + Groups string `json:"groups"` // Communities IDs + InterestCategories string `json:"interest_categories"` // Interests categories IDs + Interests string `json:"interests"` // Interests + + // Information whether the user has proceeded VK payments before. + Paying BaseBoolInt `json:"paying"` Positions string `json:"positions"` // Positions IDs Religions string `json:"religions"` // Religions IDs RetargetingGroups string `json:"retargeting_groups"` // Retargeting groups IDs diff --git a/object/apps.go b/object/apps.go index 7704b32e..a3614157 100644 --- a/object/apps.go +++ b/object/apps.go @@ -38,33 +38,35 @@ type AppsCatalogBanner struct { // AppsApp struct. type AppsApp struct { - AuthorOwnerID int `json:"author_owner_id"` - AuthorURL string `json:"author_url"` - Banner1120 string `json:"banner_1120"` // URL of the app banner with 1120 px in width - Banner560 string `json:"banner_560"` // URL of the app banner with 560 px in width - CatalogPosition int `json:"catalog_position"` // Catalog position - Description string `json:"description"` // Application description - Friends []int `json:"friends"` - Genre string `json:"genre"` // Genre name - GenreID int `json:"genre_id"` // Genre ID - Icon139 string `json:"icon_139"` // URL of the app icon with 139 px in width - Icon150 string `json:"icon_150"` // URL of the app icon with 150 px in width - Icon278 string `json:"icon_278"` // URL of the app icon with 279 px in width - Icon75 string `json:"icon_75"` // URL of the app icon with 75 px in width - ID int `json:"id"` // Application ID - International BaseBoolInt `json:"international"` // Information whether the application is multi language - IsInCatalog BaseBoolInt `json:"is_in_catalog"` // Information whether application is in mobile catalog - Installed BaseBoolInt `json:"installed"` - PushEnabled BaseBoolInt `json:"push_enabled"` - HideTabbar BaseBoolInt `json:"hide_tabbar"` - IsNew BaseBoolInt `json:"is_new"` - New BaseBoolInt `json:"new"` - IsInstalled BaseBoolInt `json:"is_installed"` - LeaderboardType int `json:"leaderboard_type"` - MembersCount int `json:"members_count"` // Members number - PlatformID int `json:"platform_id"` // Application ID in store - PublishedDate int `json:"published_date"` // Date when the application has been published in Unixtime - ScreenName string `json:"screen_name"` // Screen name + AuthorOwnerID int `json:"author_owner_id"` + AuthorURL string `json:"author_url"` + Banner1120 string `json:"banner_1120"` // URL of the app banner with 1120 px in width + Banner560 string `json:"banner_560"` // URL of the app banner with 560 px in width + CatalogPosition int `json:"catalog_position"` // Catalog position + Description string `json:"description"` // Application description + Friends []int `json:"friends"` + Genre string `json:"genre"` // Genre name + GenreID int `json:"genre_id"` // Genre ID + Icon139 string `json:"icon_139"` // URL of the app icon with 139 px in width + Icon150 string `json:"icon_150"` // URL of the app icon with 150 px in width + Icon278 string `json:"icon_278"` // URL of the app icon with 279 px in width + Icon75 string `json:"icon_75"` // URL of the app icon with 75 px in width + ID int `json:"id"` // Application ID + International BaseBoolInt `json:"international"` // Information whether the application is multi language + IsInCatalog BaseBoolInt `json:"is_in_catalog"` // Information whether application is in mobile catalog + Installed BaseBoolInt `json:"installed"` + PushEnabled BaseBoolInt `json:"push_enabled"` + HideTabbar BaseBoolInt `json:"hide_tabbar"` + IsNew BaseBoolInt `json:"is_new"` + New BaseBoolInt `json:"new"` + IsInstalled BaseBoolInt `json:"is_installed"` + LeaderboardType int `json:"leaderboard_type"` + MembersCount int `json:"members_count"` // Members number + PlatformID int `json:"platform_id"` // Application ID in store + + // Date when the application has been published in Unixtime. + PublishedDate int `json:"published_date"` + ScreenName string `json:"screen_name"` // Screen name Screenshots []PhotosPhoto `json:"screenshots"` Section string `json:"section"` // Application section name Title string `json:"title"` // Application title diff --git a/object/docs.go b/object/docs.go index 2acd117f..15d6bd5a 100644 --- a/object/docs.go +++ b/object/docs.go @@ -71,7 +71,8 @@ func (photo DocsDocPreviewPhoto) MinSize() (minPhotoSize DocsDocPreviewPhotoSize // DocsDocPreviewPhotoSizes struct. type DocsDocPreviewPhotoSizes struct { - // BUG(VK): json: cannot unmarshal number 162.000000 into Go struct field DocsDocPreviewPhotoSizes.doc.preview.photo.sizes.height of type Int + // BUG(VK): json: cannot unmarshal number 162.000000 into Go struct field + // DocsDocPreviewPhotoSizes.doc.preview.photo.sizes.height of type Int Height float64 `json:"height"` // Height in px Src string `json:"src"` // URL of the image Type string `json:"type"` diff --git a/object/groups.go b/object/groups.go index 72f40bc7..7195910a 100644 --- a/object/groups.go +++ b/object/groups.go @@ -17,20 +17,21 @@ const ( // GroupsAddress struct. type GroupsAddress struct { - AdditionalAddress string `json:"additional_address"` // Additional address to the place (6 floor, left door) - Address string `json:"address"` // String address to the place (Nevsky, 28) - CityID int `json:"city_id"` // City id of address - CountryID int `json:"country_id"` // Country id of address - Distance int `json:"distance"` // Distance from the point - ID int `json:"id"` // Address id - Latitude float64 `json:"latitude"` // Address latitude - Longitude float64 `json:"longitude"` // Address longitude - MetroStationID int `json:"metro_station_id"` // Metro id of address - Phone string `json:"phone"` // Address phone - TimeOffset int `json:"time_offset"` // Time offset int minutes from utc time - Timetable GroupsAddressTimetable `json:"timetable"` // Week timetable for the address - Title string `json:"title"` // Title of the place (Zinger, etc) - WorkInfoStatus string `json:"work_info_status"` // Status of information about timetable + // Additional address to the place (6 floor, left door). + AdditionalAddress string `json:"additional_address"` + Address string `json:"address"` // String address to the place (Nevsky, 28) + CityID int `json:"city_id"` // City id of address + CountryID int `json:"country_id"` // Country id of address + Distance int `json:"distance"` // Distance from the point + ID int `json:"id"` // Address id + Latitude float64 `json:"latitude"` // Address latitude + Longitude float64 `json:"longitude"` // Address longitude + MetroStationID int `json:"metro_station_id"` // Metro id of address + Phone string `json:"phone"` // Address phone + TimeOffset int `json:"time_offset"` // Time offset int minutes from utc time + Timetable GroupsAddressTimetable `json:"timetable"` // Week timetable for the address + Title string `json:"title"` // Title of the place (Zinger, etc) + WorkInfoStatus string `json:"work_info_status"` // Status of information about timetable } // GroupsAddressTimetable Timetable for a week. @@ -108,70 +109,112 @@ const ( // GroupsGroup struct. type GroupsGroup struct { - AdminLevel int `json:"admin_level"` - Deactivated string `json:"deactivated"` // Information whether community is banned - FinishDate int `json:"finish_date"` // Finish date in Unixtime format - ID int `json:"id"` // Community ID - Name string `json:"name"` // Community name - Photo100 string `json:"photo_100"` // URL of square photo of the community with 100 pixels in width - Photo200 string `json:"photo_200"` // URL of square photo of the community with 200 pixels in width - Photo50 string `json:"photo_50"` // URL of square photo of the community with 50 pixels in width - ScreenName string `json:"screen_name"` // Domain of the community page - StartDate int `json:"start_date"` // Start date in Unixtime format - Type string `json:"type"` - Market GroupsMarketInfo `json:"market"` - MemberStatus int `json:"member_status"` // Current user's member status - IsClosed int `json:"is_closed"` - City BaseObject `json:"city"` - Country BaseCountry `json:"country"` - IsAdmin BaseBoolInt `json:"is_admin"` // Information whether current user is administrator - IsAdvertiser BaseBoolInt `json:"is_advertiser"` // Information whether current user is advertiser - IsMember BaseBoolInt `json:"is_member"` // Information whether current user is member - IsFavorite BaseBoolInt `json:"is_favorite"` // Information whether community is in faves - IsAdult BaseBoolInt `json:"is_adult"` // Information whether community is adult - IsSubscribed BaseBoolInt `json:"is_subscribed"` // Information whether current user is subscribed - CanPost BaseBoolInt `json:"can_post"` // Information whether current user can post on community's wall - CanSeeAllPosts BaseBoolInt `json:"can_see_all_posts"` // Information whether current user can see all posts on community's wall - CanCreateTopic BaseBoolInt `json:"can_create_topic"` // Information whether current user can create topic - CanUploadVideo BaseBoolInt `json:"can_upload_video"` // Information whether current user can upload video - CanUploadDoc BaseBoolInt `json:"can_upload_doc"` // Information whether current user can upload doc - HasPhoto BaseBoolInt `json:"has_photo"` // Information whether community has photo - CanMessage BaseBoolInt `json:"can_message"` // Information whether current user can send a message to community - IsMessagesBlocked BaseBoolInt `json:"is_messages_blocked"` // Information whether community can send a message to current user - CanSendNotify BaseBoolInt `json:"can_send_notify"` // Information whether community can send notifications by phone number to current user - IsSubscribedPodcasts BaseBoolInt `json:"is_subscribed_podcasts"` // Information whether current user is subscribed to podcasts - CanSubscribePodcasts BaseBoolInt `json:"can_subscribe_podcasts"` // Owner in whitelist or not - CanSubscribePosts BaseBoolInt `json:"can_subscribe_posts"` // Can subscribe to wall - HasMarketApp BaseBoolInt `json:"has_market_app"` // Information whether community has market app - IsHiddenFromFeed BaseBoolInt `json:"is_hidden_from_feed"` - IsMarketCartEnabled BaseBoolInt `json:"is_market_cart_enabled"` - Verified BaseBoolInt `json:"verified"` // Information whether community is verified - Trending BaseBoolInt `json:"trending"` // Information whether the community has a fire pictogram. - Description string `json:"description"` // Community description - WikiPage string `json:"wiki_page"` // Community's main wiki page title - MembersCount int `json:"members_count"` // Community members number - Counters GroupsCountersGroup `json:"counters"` - Cover GroupsCover `json:"cover"` - Activity string `json:"activity"` // Type of group, start date of event or category of public page - FixedPost int `json:"fixed_post"` // Fixed post ID - Status string `json:"status"` // Community status - MainAlbumID int `json:"main_album_id"` // Community's main photo album ID - Links []GroupsLinksItem `json:"links"` - Contacts []GroupsContactsItem `json:"contacts"` - Site string `json:"site"` // Community's website - MainSection int `json:"main_section"` - OnlineStatus GroupsOnlineStatus `json:"online_status"` // Status of replies in community messages - AgeLimits int `json:"age_limits"` // Information whether age limit - BanInfo GroupsGroupBanInfo `json:"ban_info"` // User ban info - Addresses GroupsAddressesInfo `json:"addresses"` // Info about addresses in Groups - LiveCovers GroupsLiveCovers `json:"live_covers"` - CropPhoto UsersCropPhoto `json:"crop_photo"` - Wall int `json:"wall"` - ActionButton GroupsActionButton `json:"action_button"` - TrackCode string `json:"track_code"` - PublicDateLabel string `json:"public_date_label"` - AuthorID int `json:"author_id"` - Phone string `json:"phone"` + AdminLevel int `json:"admin_level"` + Deactivated string `json:"deactivated"` // Information whether community is banned + FinishDate int `json:"finish_date"` // Finish date in Unixtime format + ID int `json:"id"` // Community ID + Name string `json:"name"` // Community name + Photo100 string `json:"photo_100"` // URL of square photo of the community with 100 pixels in width + Photo200 string `json:"photo_200"` // URL of square photo of the community with 200 pixels in width + Photo50 string `json:"photo_50"` // URL of square photo of the community with 50 pixels in width + ScreenName string `json:"screen_name"` // Domain of the community page + StartDate int `json:"start_date"` // Start date in Unixtime format + Type string `json:"type"` + Market GroupsMarketInfo `json:"market"` + MemberStatus int `json:"member_status"` // Current user's member status + IsClosed int `json:"is_closed"` + City BaseObject `json:"city"` + Country BaseCountry `json:"country"` + + // Information whether current user is administrator. + IsAdmin BaseBoolInt `json:"is_admin"` + + // Information whether current user is advertiser. + IsAdvertiser BaseBoolInt `json:"is_advertiser"` + + // Information whether current user is member. + IsMember BaseBoolInt `json:"is_member"` + + // Information whether community is in faves. + IsFavorite BaseBoolInt `json:"is_favorite"` + + // Information whether community is adult. + IsAdult BaseBoolInt `json:"is_adult"` + + // Information whether current user is subscribed. + IsSubscribed BaseBoolInt `json:"is_subscribed"` + + // Information whether current user can post on community's wall. + CanPost BaseBoolInt `json:"can_post"` + + // Information whether current user can see all posts on community's wall. + CanSeeAllPosts BaseBoolInt `json:"can_see_all_posts"` + + // Information whether current user can create topic. + CanCreateTopic BaseBoolInt `json:"can_create_topic"` + + // Information whether current user can upload video. + CanUploadVideo BaseBoolInt `json:"can_upload_video"` + + // Information whether current user can upload doc. + CanUploadDoc BaseBoolInt `json:"can_upload_doc"` + + // Information whether community has photo. + HasPhoto BaseBoolInt `json:"has_photo"` + + // Information whether current user can send a message to community. + CanMessage BaseBoolInt `json:"can_message"` + + // Information whether community can send a message to current user. + IsMessagesBlocked BaseBoolInt `json:"is_messages_blocked"` + + // Information whether community can send notifications by phone number to current user. + CanSendNotify BaseBoolInt `json:"can_send_notify"` + + // Information whether current user is subscribed to podcasts. + IsSubscribedPodcasts BaseBoolInt `json:"is_subscribed_podcasts"` + + // Owner in whitelist or not. + CanSubscribePodcasts BaseBoolInt `json:"can_subscribe_podcasts"` + + // Can subscribe to wall. + CanSubscribePosts BaseBoolInt `json:"can_subscribe_posts"` + + // Information whether community has market app. + HasMarketApp BaseBoolInt `json:"has_market_app"` + IsHiddenFromFeed BaseBoolInt `json:"is_hidden_from_feed"` + IsMarketCartEnabled BaseBoolInt `json:"is_market_cart_enabled"` + Verified BaseBoolInt `json:"verified"` // Information whether community is verified + + // Information whether the community has a fire pictogram. + Trending BaseBoolInt `json:"trending"` + Description string `json:"description"` // Community description + WikiPage string `json:"wiki_page"` // Community's main wiki page title + MembersCount int `json:"members_count"` // Community members number + Counters GroupsCountersGroup `json:"counters"` + Cover GroupsCover `json:"cover"` + + // Type of group, start date of event or category of public page. + Activity string `json:"activity"` + FixedPost int `json:"fixed_post"` // Fixed post ID + Status string `json:"status"` // Community status + MainAlbumID int `json:"main_album_id"` // Community's main photo album ID + Links []GroupsLinksItem `json:"links"` + Contacts []GroupsContactsItem `json:"contacts"` + Site string `json:"site"` // Community's website + MainSection int `json:"main_section"` + OnlineStatus GroupsOnlineStatus `json:"online_status"` // Status of replies in community messages + AgeLimits int `json:"age_limits"` // Information whether age limit + BanInfo GroupsGroupBanInfo `json:"ban_info"` // User ban info + Addresses GroupsAddressesInfo `json:"addresses"` // Info about addresses in Groups + LiveCovers GroupsLiveCovers `json:"live_covers"` + CropPhoto UsersCropPhoto `json:"crop_photo"` + Wall int `json:"wall"` + ActionButton GroupsActionButton `json:"action_button"` + TrackCode string `json:"track_code"` + PublicDateLabel string `json:"public_date_label"` + AuthorID int `json:"author_id"` + Phone string `json:"phone"` } // ToMention return mention. @@ -402,25 +445,31 @@ type GroupsGroupSettings struct { Photos int `json:"photos"` // Photos settings PublicCategory int `json:"public_category"` // Information about the group category PublicCategoryList []GroupsGroupPublicCategoryList `json:"public_category_list"` - PublicSubcategory int `json:"public_subcategory"` // Information about the group subcategory - Rss string `json:"rss"` // URL of the RSS feed - Subject int `json:"subject"` // Community subject ID - SubjectList []GroupsSubjectItem `json:"subject_list"` - Title string `json:"title"` // Community title - Topics int `json:"topics"` // Topics settings - Video int `json:"video"` // Video settings - Wall int `json:"wall"` // Wall settings - Website string `json:"website"` // Community website - Wiki int `json:"wiki"` // Wiki settings - CountryID int `json:"country_id"` - CityID int `json:"city_id"` - Messages int `json:"messages"` - Articles int `json:"articles"` - Events int `json:"events"` - AgeLimits int `json:"age_limits"` - ObsceneFilter BaseBoolInt `json:"obscene_filter"` // Information whether the obscene filter is enabled - ObsceneStopwords BaseBoolInt `json:"obscene_stopwords"` // Information whether the stopwords filter is enabled - LiveCovers struct { + + // Information about the group subcategory. + PublicSubcategory int `json:"public_subcategory"` + Rss string `json:"rss"` // URL of the RSS feed + Subject int `json:"subject"` // Community subject ID + SubjectList []GroupsSubjectItem `json:"subject_list"` + Title string `json:"title"` // Community title + Topics int `json:"topics"` // Topics settings + Video int `json:"video"` // Video settings + Wall int `json:"wall"` // Wall settings + Website string `json:"website"` // Community website + Wiki int `json:"wiki"` // Wiki settings + CountryID int `json:"country_id"` + CityID int `json:"city_id"` + Messages int `json:"messages"` + Articles int `json:"articles"` + Events int `json:"events"` + AgeLimits int `json:"age_limits"` + + // Information whether the obscene filter is enabled. + ObsceneFilter BaseBoolInt `json:"obscene_filter"` + + // Information whether the stopwords filter is enabled. + ObsceneStopwords BaseBoolInt `json:"obscene_stopwords"` + LiveCovers struct { IsEnabled BaseBoolInt `json:"is_enabled"` } `json:"live_covers"` Market GroupsMarketInfo `json:"market"` diff --git a/object/market.go b/object/market.go index 68299323..f9285051 100644 --- a/object/market.go +++ b/object/market.go @@ -41,13 +41,15 @@ type MarketMarketCategory struct { // MarketMarketItem struct. type MarketMarketItem struct { - AccessKey string `json:"access_key"` // Access key for the market item - Availability int `json:"availability"` // Information whether the item is available - Category MarketMarketCategory `json:"category"` - Date int `json:"date,omitempty"` // Date when the item has been created in Unixtime - Description string `json:"description"` // Item description - ID int `json:"id"` // Item ID - OwnerID int `json:"owner_id"` // Item owner's ID + AccessKey string `json:"access_key"` // Access key for the market item + Availability int `json:"availability"` // Information whether the item is available + Category MarketMarketCategory `json:"category"` + + // Date when the item has been created in Unixtime. + Date int `json:"date,omitempty"` + Description string `json:"description"` // Item description + ID int `json:"id"` // Item ID + OwnerID int `json:"owner_id"` // Item owner's ID Price MarketPrice `json:"price"` ThumbPhoto string `json:"thumb_photo"` // URL of the preview image Title string `json:"title"` // Item title diff --git a/object/messages.go b/object/messages.go index b78d4920..6853d92d 100644 --- a/object/messages.go +++ b/object/messages.go @@ -38,32 +38,44 @@ func (doc MessagesGraffiti) ToAttachment() string { // MessagesMessage struct. type MessagesMessage struct { - AdminAuthorID int `json:"admin_author_id"` // Only for messages from community. Contains user ID of community admin, who sent this message. - Action MessagesMessageAction `json:"action"` - Attachments []MessagesMessageAttachment `json:"attachments"` - ConversationMessageID int `json:"conversation_message_id"` // Unique auto-incremented number for all messages with this peer - Date int `json:"date"` // Date when the message has been sent in Unixtime - FromID int `json:"from_id"` // Message author's ID - FwdMessages []MessagesMessage `json:"fwd_Messages"` // Forwarded messages - ReplyMessage *MessagesMessage `json:"reply_message"` - Geo BaseMessageGeo `json:"geo"` - ID int `json:"id"` // Message ID - Deleted BaseBoolInt `json:"deleted"` // Is it an deleted message - Important BaseBoolInt `json:"important"` // Is it an important message - IsHidden BaseBoolInt `json:"is_hidden"` - IsCropped BaseBoolInt `json:"is_cropped"` - Out BaseBoolInt `json:"out"` // Information whether the message is outcoming - Keyboard MessagesKeyboard `json:"keyboard"` - Template MessagesTemplate `json:"template"` - Payload string `json:"payload"` - PeerID int `json:"peer_id"` // Peer ID - RandomID int `json:"random_id"` // ID used for sending messages. It returned only for outgoing messages - Ref string `json:"ref"` - RefSource string `json:"ref_source"` - Text string `json:"text"` // Message text - UpdateTime int `json:"update_time"` // Date when the message has been updated in Unixtime - MembersCount int `json:"members_count"` // Members number - ExpireTTL int `json:"expire_ttl"` + // Only for messages from community. Contains user ID of community admin, + // who sent this message. + AdminAuthorID int `json:"admin_author_id"` + Action MessagesMessageAction `json:"action"` + Attachments []MessagesMessageAttachment `json:"attachments"` + + // Unique auto-incremented number for all messages with this peer. + ConversationMessageID int `json:"conversation_message_id"` + + // Date when the message has been sent in Unixtime. + Date int `json:"date"` + + // Message author's ID. + FromID int `json:"from_id"` + + // Forwarded messages. + FwdMessages []MessagesMessage `json:"fwd_Messages"` + ReplyMessage *MessagesMessage `json:"reply_message"` + Geo BaseMessageGeo `json:"geo"` + ID int `json:"id"` // Message ID + Deleted BaseBoolInt `json:"deleted"` // Is it an deleted message + Important BaseBoolInt `json:"important"` // Is it an important message + IsHidden BaseBoolInt `json:"is_hidden"` + IsCropped BaseBoolInt `json:"is_cropped"` + Out BaseBoolInt `json:"out"` // Information whether the message is outcoming + Keyboard MessagesKeyboard `json:"keyboard"` + Template MessagesTemplate `json:"template"` + Payload string `json:"payload"` + PeerID int `json:"peer_id"` // Peer ID + + // ID used for sending messages. It returned only for outgoing messages. + RandomID int `json:"random_id"` + Ref string `json:"ref"` + RefSource string `json:"ref_source"` + Text string `json:"text"` // Message text + UpdateTime int `json:"update_time"` // Date when the message has been updated in Unixtime + MembersCount int `json:"members_count"` // Members number + ExpireTTL int `json:"expire_ttl"` } // MessagesBasePayload struct. @@ -200,7 +212,11 @@ func (keyboard *MessagesKeyboard) AddVKPayButton(payload interface{}, hash strin } // AddVKAppsButton add VK Apps button in last row. -func (keyboard *MessagesKeyboard) AddVKAppsButton(appID, ownerID int, payload interface{}, label, hash string) *MessagesKeyboard { +func (keyboard *MessagesKeyboard) AddVKAppsButton( + appID, ownerID int, + payload interface{}, + label, hash string, +) *MessagesKeyboard { b, err := json.Marshal(payload) if err != nil { panic(err) @@ -343,13 +359,15 @@ type MessagesChatSettingsPhoto struct { // MessagesConversation struct. type MessagesConversation struct { - CanWrite MessagesConversationCanWrite `json:"can_write"` - ChatSettings MessagesConversationChatSettings `json:"chat_settings"` - InRead int `json:"in_read"` // Last message user have read - LastMessageID int `json:"last_message_id"` // ID of the last message in conversation - Mentions []int `json:"mentions"` // IDs of messages with mentions - MessageRequest string `json:"message_request"` - OutRead int `json:"out_read"` // Last outcoming message have been read by the opponent + CanWrite MessagesConversationCanWrite `json:"can_write"` + ChatSettings MessagesConversationChatSettings `json:"chat_settings"` + InRead int `json:"in_read"` // Last message user have read + LastMessageID int `json:"last_message_id"` // ID of the last message in conversation + Mentions []int `json:"mentions"` // IDs of messages with mentions + MessageRequest string `json:"message_request"` + + // Last outcoming message have been read by the opponent. + OutRead int `json:"out_read"` Peer MessagesConversationPeer `json:"peer"` PushSettings MessagesConversationPushSettings `json:"push_settings"` Important BaseBoolInt `json:"important"` @@ -500,13 +518,17 @@ const ( // MessagesMessageAction struct. type MessagesMessageAction struct { - ConversationMessageID int `json:"conversation_message_id"` // Message ID - Email string `json:"email"` // Email address for chat_invite_user or chat_kick_user actions - MemberID int `json:"member_id"` // User or email peer ID - Message string `json:"message"` // Message body of related message - Photo MessagesMessageActionPhoto `json:"photo"` - Text string `json:"text"` // New chat title for chat_create and chat_title_update actions - Type string `json:"type"` + ConversationMessageID int `json:"conversation_message_id"` // Message ID + + // Email address for chat_invite_user or chat_kick_user actions. + Email string `json:"email"` + MemberID int `json:"member_id"` // User or email peer ID + Message string `json:"message"` // Message body of related message + Photo MessagesMessageActionPhoto `json:"photo"` + + // New chat title for chat_create and chat_title_update actions. + Text string `json:"text"` + Type string `json:"type"` } // MessagesMessageActionPhoto struct. @@ -549,16 +571,22 @@ type MessageCall struct { // MessagesPinnedMessage struct. type MessagesPinnedMessage struct { - Attachments []MessagesMessageAttachment `json:"attachments"` - ConversationMessageID int `json:"conversation_message_id"` // Unique auto-incremented number for all Messages with this peer - Date int `json:"date"` // Date when the message has been sent in Unixtime - FromID int `json:"from_id"` // Message author's ID - FwdMessages []*MessagesMessage `json:"fwd_Messages"` - Geo BaseMessageGeo `json:"geo"` - ID int `json:"id"` // Message ID - PeerID int `json:"peer_id"` // Peer ID - ReplyMessage *MessagesMessage `json:"reply_message"` - Text string `json:"text"` // Message text + Attachments []MessagesMessageAttachment `json:"attachments"` + + // Unique auto-incremented number for all Messages with this peer. + ConversationMessageID int `json:"conversation_message_id"` + + // Date when the message has been sent in Unixtime. + Date int `json:"date"` + + // Message author's ID. + FromID int `json:"from_id"` + FwdMessages []*MessagesMessage `json:"fwd_Messages"` + Geo BaseMessageGeo `json:"geo"` + ID int `json:"id"` // Message ID + PeerID int `json:"peer_id"` // Peer ID + ReplyMessage *MessagesMessage `json:"reply_message"` + Text string `json:"text"` // Message text } // MessagesUserXtrInvitedBy struct. diff --git a/object/object.go b/object/object.go index ea231600..1437cbf8 100644 --- a/object/object.go +++ b/object/object.go @@ -499,12 +499,28 @@ const ( // Button action type. const ( - ButtonText = "text" // A button that sends a message with text specified in the label. - ButtonVKPay = "vkpay" // Opens the VK Pay window with predefined parameters. The button is called “Pay with VK Pay” (VK Pay is displayed as a logo). This button always stretches to the whole keyboard width. - ButtonVKApp = "open_app" // Opens a specified VK Apps app. This button always stretches to the whole keyboard width. - ButtonLocation = "location" // Sends the location to the chat. This button always stretches to the whole keyboard width. - ButtonOpenLink = "open_link" // Opens the specified link. - ButtonCallback = "callback" // Allows, without sending a message from the user, to receive a notification about pressing the button and perform the necessary action. + // A button that sends a message with text specified in the label. + ButtonText = "text" + + // Opens the VK Pay window with predefined parameters. The button is called + // “Pay with VK Pay” (VK Pay is displayed as a logo). This button always + // stretches to the whole keyboard width. + ButtonVKPay = "vkpay" + + // Opens a specified VK Apps app. This button always stretches to the whole + // keyboard width. + ButtonVKApp = "open_app" + + // Sends the location to the chat. This button always stretches to the + // whole keyboard width. + ButtonLocation = "location" + + // Opens the specified link. + ButtonOpenLink = "open_link" + + // Allows, without sending a message from the user, to receive a + // notification about pressing the button and perform the necessary action. + ButtonCallback = "callback" ) // Button color. This parameter is used only for buttons with the text and callback types. diff --git a/object/pages.go b/object/pages.go index 5f00eb47..b195c324 100644 --- a/object/pages.go +++ b/object/pages.go @@ -23,23 +23,54 @@ type PagesWikipage struct { // PagesWikipageFull struct. type PagesWikipageFull struct { - Created int `json:"created"` // Date when the page has been created in Unixtime - CreatorID int `json:"creator_id"` // Page creator ID - CurrentUserCanEdit BaseBoolInt `json:"current_user_can_edit"` // Information whether current user can edit the page - CurrentUserCanEditAccess BaseBoolInt `json:"current_user_can_edit_access"` // Information whether current user can edit the page access settings - Edited int `json:"edited"` // Date when the page has been edited in Unixtime - EditorID int `json:"editor_id"` // Last editor ID - PageID int `json:"page_id"` // Page ID - GroupID int `json:"group_id"` // Community ID - HTML string `json:"html"` // Page content, HTML - ID int `json:"id"` // Page ID - Source string `json:"source"` // Page content, wiki - Title string `json:"title"` // Page title - ViewURL string `json:"view_url"` // URL of the page preview - Views int `json:"views"` // Views number - WhoCanEdit int `json:"who_can_edit"` // Edit settings of the page - WhoCanView int `json:"who_can_view"` // View settings of the page - VersionCreated int `json:"version_created"` + // Date when the page has been created in Unixtime. + Created int `json:"created"` + + // Page creator ID. + CreatorID int `json:"creator_id"` + + // Information whether current user can edit the page. + CurrentUserCanEdit BaseBoolInt `json:"current_user_can_edit"` + + // Information whether current user can edit the page access settings. + CurrentUserCanEditAccess BaseBoolInt `json:"current_user_can_edit_access"` + + // Date when the page has been edited in Unixtime. + Edited int `json:"edited"` + + // Last editor ID. + EditorID int `json:"editor_id"` + + // Page ID. + PageID int `json:"page_id"` + + // Community ID. + GroupID int `json:"group_id"` + + // Page content, HTML. + HTML string `json:"html"` + + // Page ID. + ID int `json:"id"` + + // Page content, wiki. + Source string `json:"source"` + + // Page title. + Title string `json:"title"` + + // URL of the page preview. + ViewURL string `json:"view_url"` + + // Views number. + Views int `json:"views"` + + // Edit settings of the page. + WhoCanEdit int `json:"who_can_edit"` + + // View settings of the page. + WhoCanView int `json:"who_can_view"` + VersionCreated int `json:"version_created"` } // PagesWikipageHistory struct. diff --git a/object/photos.go b/object/photos.go index 193395f5..f7011a3d 100644 --- a/object/photos.go +++ b/object/photos.go @@ -149,22 +149,29 @@ func (album PhotosPhotoAlbum) ToAttachment() string { // PhotosPhotoAlbumFull struct. type PhotosPhotoAlbumFull struct { - CanUpload BaseBoolInt `json:"can_upload"` // Information whether current user can upload photo to the album - CommentsDisabled BaseBoolInt `json:"comments_disabled"` // Information whether album comments are disabled - Created int `json:"created"` // Date when the album has been created in Unixtime - Description string `json:"description"` // Photo album description - ID int `json:"id"` // Photo album ID - OwnerID int `json:"owner_id"` // Album owner's ID - Size int `json:"size"` // Photos number - PrivacyComment Privacy `json:"privacy_comment"` - PrivacyView Privacy `json:"privacy_view"` - Sizes []PhotosPhotoSizes `json:"sizes"` - ThumbID int `json:"thumb_id"` // Thumb photo ID - ThumbIsLast int `json:"thumb_is_last"` // Information whether the album thumb is last photo - ThumbSrc string `json:"thumb_src"` // URL of the thumb image - Title string `json:"title"` // Photo album title - Updated int `json:"updated"` // Date when the album has been updated last time in Unixtime - UploadByAdminsOnly int `json:"upload_by_admins_only"` // Information whether only community administrators can upload photos + // Information whether current user can upload photo to the album. + CanUpload BaseBoolInt `json:"can_upload"` + CommentsDisabled BaseBoolInt `json:"comments_disabled"` // Information whether album comments are disabled + Created int `json:"created"` // Date when the album has been created in Unixtime + Description string `json:"description"` // Photo album description + ID int `json:"id"` // Photo album ID + OwnerID int `json:"owner_id"` // Album owner's ID + Size int `json:"size"` // Photos number + PrivacyComment Privacy `json:"privacy_comment"` + PrivacyView Privacy `json:"privacy_view"` + Sizes []PhotosPhotoSizes `json:"sizes"` + ThumbID int `json:"thumb_id"` // Thumb photo ID + + // Information whether the album thumb is last photo. + ThumbIsLast int `json:"thumb_is_last"` + ThumbSrc string `json:"thumb_src"` // URL of the thumb image + Title string `json:"title"` // Photo album title + + // Date when the album has been updated last time in Unixtime. + Updated int `json:"updated"` + + // Information whether only community administrators can upload photos. + UploadByAdminsOnly int `json:"upload_by_admins_only"` } // ToAttachment return attachment format. diff --git a/object/stories.go b/object/stories.go index a3753ac1..b7a01369 100644 --- a/object/stories.go +++ b/object/stories.go @@ -79,16 +79,36 @@ type StoriesStory struct { // Information whether story has question sticker and current user can send question to the author CanAsk BaseBoolInt `json:"can_ask"` // Information whether story has question sticker and current user can send anonymous question to the author - CanAskAnonymous BaseBoolInt `json:"can_ask_anonymous"` - CanComment BaseBoolInt `json:"can_comment"` // Information whether current user can comment the story (0 - no, 1 - yes). - CanReply BaseBoolInt `json:"can_reply"` // Information whether current user can reply to the story (0 - no, 1 - yes). - CanSee BaseBoolInt `json:"can_see"` // Information whether current user can see the story (0 - no, 1 - yes). - CanShare BaseBoolInt `json:"can_share"` // Information whether current user can share the story (0 - no, 1 - yes). - IsDeleted BaseBoolInt `json:"is_deleted"` // Information whether the story is deleted (false - no, true - yes). - IsExpired BaseBoolInt `json:"is_expired"` // Information whether the story is expired (false - no, true - yes). - NoSound BaseBoolInt `json:"no_sound"` // Is video without sound - IsRestricted BaseBoolInt `json:"is_restricted"` // Does author have stories privacy restrictions - Seen BaseBoolInt `json:"seen"` // Information whether current user has seen the story or not (0 - no, 1 - yes). + CanAskAnonymous BaseBoolInt `json:"can_ask_anonymous"` + + // Information whether current user can comment the story (0 - no, 1 - yes). + CanComment BaseBoolInt `json:"can_comment"` + + // Information whether current user can reply to the story + // (0 - no, 1 - yes). + CanReply BaseBoolInt `json:"can_reply"` + + // Information whether current user can see the story (0 - no, 1 - yes). + CanSee BaseBoolInt `json:"can_see"` + + // Information whether current user can share the story (0 - no, 1 - yes). + CanShare BaseBoolInt `json:"can_share"` + + // Information whether the story is deleted (false - no, true - yes). + IsDeleted BaseBoolInt `json:"is_deleted"` + + // Information whether the story is expired (false - no, true - yes). + IsExpired BaseBoolInt `json:"is_expired"` + + // Is video without sound + NoSound BaseBoolInt `json:"no_sound"` + + // Does author have stories privacy restrictions + IsRestricted BaseBoolInt `json:"is_restricted"` + + // Information whether current user has seen the story or not + // (0 - no, 1 - yes). + Seen BaseBoolInt `json:"seen"` IsOwnerPinned BaseBoolInt `json:"is_owner_pinned"` IsOneTime BaseBoolInt `json:"is_one_time"` NeedMute BaseBoolInt `json:"need_mute"` diff --git a/object/video.go b/object/video.go index 08e90471..497766cc 100644 --- a/object/video.go +++ b/object/video.go @@ -6,39 +6,56 @@ import ( // VideoVideo struct. type VideoVideo struct { - AccessKey string `json:"access_key"` // Video access key - AddingDate int `json:"adding_date"` // Date when the video has been added in Unixtime - CanAdd BaseBoolInt `json:"can_add"` // Information whether current user can add the video - CanAddToFaves BaseBoolInt `json:"can_add_to_faves"` // Information whether current user can add the video to faves - CanComment BaseBoolInt `json:"can_comment"` // Information whether current user can comment the video - CanEdit BaseBoolInt `json:"can_edit"` // Information whether current user can edit the video - CanLike BaseBoolInt `json:"can_like"` // Information whether current user can like the video - CanRepost BaseBoolInt `json:"can_repost"` // Information whether current user can repost this video - CanSubscribe BaseBoolInt `json:"can_subscribe"` - CanAttachLink BaseBoolInt `json:"can_attach_link"` - IsFavorite BaseBoolInt `json:"is_favorite"` - IsPrivate BaseBoolInt `json:"is_private"` - Added BaseBoolInt `json:"added"` - Repeat BaseBoolInt `json:"repeat"` // Information whether the video is repeated - ContentRestricted BaseBoolInt `json:"content_restricted"` - Comments int `json:"comments"` // Number of comments - Date int `json:"date"` // Date when video has been uploaded in Unixtime - Description string `json:"description"` // Video description - Duration int `json:"duration"` // Video duration in seconds - Files VideoVideoFiles `json:"files"` - FirstFrame []VideoVideoImage `json:"first_frame"` - Image []VideoVideoImage `json:"image"` - Height int `json:"height"` // Video height - ID int `json:"id"` // Video ID - Live int `json:"live"` // Returns if the video is a live stream - OwnerID int `json:"owner_id"` // Video owner ID - UserID int `json:"user_id"` - Photo130 string `json:"photo_130"` // URL of the preview image with 130 px in width - Photo320 string `json:"photo_320"` // URL of the preview image with 320 px in width - Photo640 string `json:"photo_640"` // URL of the preview image with 640 px in width - Photo800 string `json:"photo_800"` // URL of the preview image with 800 px in width - Photo1280 string `json:"photo_1280"` // URL of the preview image with 1280 px in width - Player string `json:"player"` // URL of the page with a player that can be used to play the video in the browser. + // Video access key. + AccessKey string `json:"access_key"` + + // Date when the video has been added in Unixtime. + AddingDate int `json:"adding_date"` + + // Information whether current user can add the video. + CanAdd BaseBoolInt `json:"can_add"` + + // Information whether current user can add the video to faves. + CanAddToFaves BaseBoolInt `json:"can_add_to_faves"` + + // Information whether current user can comment the video. + CanComment BaseBoolInt `json:"can_comment"` + + // Information whether current user can edit the video. + CanEdit BaseBoolInt `json:"can_edit"` + + // Information whether current user can like the video. + CanLike BaseBoolInt `json:"can_like"` + + // Information whether current user can repost this video. + CanRepost BaseBoolInt `json:"can_repost"` + CanSubscribe BaseBoolInt `json:"can_subscribe"` + CanAttachLink BaseBoolInt `json:"can_attach_link"` + IsFavorite BaseBoolInt `json:"is_favorite"` + IsPrivate BaseBoolInt `json:"is_private"` + Added BaseBoolInt `json:"added"` + Repeat BaseBoolInt `json:"repeat"` // Information whether the video is repeated + ContentRestricted BaseBoolInt `json:"content_restricted"` + Comments int `json:"comments"` // Number of comments + Date int `json:"date"` // Date when video has been uploaded in Unixtime + Description string `json:"description"` // Video description + Duration int `json:"duration"` // Video duration in seconds + Files VideoVideoFiles `json:"files"` + FirstFrame []VideoVideoImage `json:"first_frame"` + Image []VideoVideoImage `json:"image"` + Height int `json:"height"` // Video height + ID int `json:"id"` // Video ID + Live int `json:"live"` // Returns if the video is a live stream + OwnerID int `json:"owner_id"` // Video owner ID + UserID int `json:"user_id"` + Photo130 string `json:"photo_130"` // URL of the preview image with 130 px in width + Photo320 string `json:"photo_320"` // URL of the preview image with 320 px in width + Photo640 string `json:"photo_640"` // URL of the preview image with 640 px in width + Photo800 string `json:"photo_800"` // URL of the preview image with 800 px in width + Photo1280 string `json:"photo_1280"` // URL of the preview image with 1280 px in width + + // URL of the page with a player that can be used to play the video in the browser. + Player string `json:"player"` Processing int `json:"processing"` // Returns if the video is processing Title string `json:"title"` // Video title Type string `json:"type"` @@ -177,36 +194,38 @@ type VideoVideoAlbumFull struct { // VideoVideoFull struct. type VideoVideoFull struct { - AccessKey string `json:"access_key"` // Video access key - AddingDate int `json:"adding_date"` // Date when the video has been added in Unixtime - IsFavorite BaseBoolInt `json:"is_favorite"` - CanAdd BaseBoolInt `json:"can_add"` // Information whether current user can add the video - CanComment BaseBoolInt `json:"can_comment"` // Information whether current user can comment the video - CanEdit BaseBoolInt `json:"can_edit"` // Information whether current user can edit the video - CanRepost BaseBoolInt `json:"can_repost"` // Information whether current user can comment the video - CanLike BaseBoolInt `json:"can_like"` - CanAddToFaves BaseBoolInt `json:"can_add_to_faves"` - Repeat BaseBoolInt `json:"repeat"` // Information whether the video is repeated - Comments int `json:"comments"` // Number of comments - Date int `json:"date"` // Date when video has been uploaded in Unixtime - Description string `json:"description"` // Video description - Duration int `json:"duration"` // Video duration in seconds - Files VideoVideoFiles `json:"files"` - ID int `json:"id"` // Video ID - Likes BaseLikes `json:"likes"` - Live int `json:"live"` // Returns if the video is live translation - OwnerID int `json:"owner_id"` // Video owner ID - Player string `json:"player"` // URL of the page with a player that can be used to play the video in the browser. - Processing int `json:"processing"` // Returns if the video is processing - Title string `json:"title"` // Video title - Views int `json:"views"` // Number of views - Width int `json:"width"` - Height int `json:"height"` - Image []VideoVideoImage `json:"image"` - FirstFrame []VideoVideoImage `json:"first_frame"` - Added int `json:"added"` - Type string `json:"type"` - Reposts BaseRepostsInfo `json:"reposts"` + AccessKey string `json:"access_key"` // Video access key + AddingDate int `json:"adding_date"` // Date when the video has been added in Unixtime + IsFavorite BaseBoolInt `json:"is_favorite"` + CanAdd BaseBoolInt `json:"can_add"` // Information whether current user can add the video + CanComment BaseBoolInt `json:"can_comment"` // Information whether current user can comment the video + CanEdit BaseBoolInt `json:"can_edit"` // Information whether current user can edit the video + CanRepost BaseBoolInt `json:"can_repost"` // Information whether current user can comment the video + CanLike BaseBoolInt `json:"can_like"` + CanAddToFaves BaseBoolInt `json:"can_add_to_faves"` + Repeat BaseBoolInt `json:"repeat"` // Information whether the video is repeated + Comments int `json:"comments"` // Number of comments + Date int `json:"date"` // Date when video has been uploaded in Unixtime + Description string `json:"description"` // Video description + Duration int `json:"duration"` // Video duration in seconds + Files VideoVideoFiles `json:"files"` + ID int `json:"id"` // Video ID + Likes BaseLikes `json:"likes"` + Live int `json:"live"` // Returns if the video is live translation + OwnerID int `json:"owner_id"` // Video owner ID + + // URL of the page with a player that can be used to play the video in the browser. + Player string `json:"player"` + Processing int `json:"processing"` // Returns if the video is processing + Title string `json:"title"` // Video title + Views int `json:"views"` // Number of views + Width int `json:"width"` + Height int `json:"height"` + Image []VideoVideoImage `json:"image"` + FirstFrame []VideoVideoImage `json:"first_frame"` + Added int `json:"added"` + Type string `json:"type"` + Reposts BaseRepostsInfo `json:"reposts"` } // ToAttachment return attachment format. diff --git a/object/widgets.go b/object/widgets.go index 33494dde..e1ba8692 100644 --- a/object/widgets.go +++ b/object/widgets.go @@ -54,8 +54,10 @@ type WidgetsWidgetLikes struct { // WidgetsWidgetPage struct. type WidgetsWidgetPage struct { - Comments WidgetsWidgetLikes `json:"comments,omitempty"` - Date int `json:"date,omitempty"` // Date when Widgets on the page has been initialized firstly in Unixtime + Comments WidgetsWidgetLikes `json:"comments,omitempty"` + + // Date when Widgets on the page has been initialized firstly in Unixtime + Date int `json:"date,omitempty"` Description string `json:"description,omitempty"` // Page description ID int `json:"id,omitempty"` // Page ID Likes WidgetsWidgetLikes `json:"likes,omitempty"` diff --git a/payments/callback_test.go b/payments/callback_test.go index 382fda05..e184d255 100644 --- a/payments/callback_test.go +++ b/payments/callback_test.go @@ -26,14 +26,6 @@ func TestNewCallback(t *testing.T) { cb := payments.NewCallback(secret) assert.Equal(t, secret, cb.Secret) - // cb.OnSubscriptionStatusChange(func(e payments.SubscriptionStatusChangeRequest) (*payments.SubscriptionStatusChangeResponse, *payments.Error) { - // return nil, &paymentErr - // }) - - // cb.OnSubscriptionStatusChangeTest(func(e payments.SubscriptionStatusChangeRequest) (*payments.SubscriptionStatusChangeResponse, *payments.Error) { - // return nil, &paymentErr - // }) - f := func(v url.Values, wantResp response) { t.Helper() @@ -368,11 +360,17 @@ func TestCallback_OnOrderStatusChange(t *testing.T) { cb := payments.NewCallback(secret) assert.Equal(t, secret, cb.Secret) - cb.OnOrderStatusChange(func(e payments.OrderStatusChangeRequest) (*payments.OrderStatusChangeResponse, *payments.Error) { + cb.OnOrderStatusChange(func(e payments.OrderStatusChangeRequest) ( + *payments.OrderStatusChangeResponse, + *payments.Error, + ) { return nil, &paymentErr }) - cb.OnOrderStatusChangeTest(func(e payments.OrderStatusChangeRequest) (*payments.OrderStatusChangeResponse, *payments.Error) { + cb.OnOrderStatusChangeTest(func(e payments.OrderStatusChangeRequest) ( + *payments.OrderStatusChangeResponse, + *payments.Error, + ) { return nil, &paymentErr }) @@ -494,11 +492,17 @@ func TestCallback_OnSubscriptionStatusChange(t *testing.T) { cb := payments.NewCallback(secret) assert.Equal(t, secret, cb.Secret) - cb.OnSubscriptionStatusChange(func(e payments.SubscriptionStatusChangeRequest) (*payments.SubscriptionStatusChangeResponse, *payments.Error) { + cb.OnSubscriptionStatusChange(func(e payments.SubscriptionStatusChangeRequest) ( + *payments.SubscriptionStatusChangeResponse, + *payments.Error, + ) { return nil, &paymentErr }) - cb.OnSubscriptionStatusChangeTest(func(e payments.SubscriptionStatusChangeRequest) (*payments.SubscriptionStatusChangeResponse, *payments.Error) { + cb.OnSubscriptionStatusChangeTest(func(e payments.SubscriptionStatusChangeRequest) ( + *payments.SubscriptionStatusChangeResponse, + *payments.Error, + ) { return nil, &paymentErr }) diff --git a/payments/payments.go b/payments/payments.go index ad14d668..18c6309e 100644 --- a/payments/payments.go +++ b/payments/payments.go @@ -30,15 +30,24 @@ time. // ... }) - cb.OnOrderStatusChange(func(e payments.OrderStatusChangeRequest) (*payments.OrderStatusChangeResponse, *payments.Error) { + cb.OnOrderStatusChange(func(e payments.OrderStatusChangeRequest) ( + *payments.OrderStatusChangeResponse, + *payments.Error, + ) { // ... }) - cb.OnGetSubscription(func(e payments.GetSubscriptionRequest) (*payments.GetSubscriptionResponse, *payments.Error) { + cb.OnGetSubscription(func(e payments.GetSubscriptionRequest) ( + *payments.GetSubscriptionResponse, + *payments.Error, + ) { // ... }) - cb.OnSubscriptionStatusChange(func(e payments.SubscriptionStatusChangeRequest) (*payments.SubscriptionStatusChangeResponse, *payments.Error) { + cb.OnSubscriptionStatusChange(func(e payments.SubscriptionStatusChangeRequest) ( + *payments.SubscriptionStatusChangeResponse, + *payments.Error, + ) { // ... }) @@ -66,15 +75,24 @@ In test mode, the suffix '_test' is added to the NotificationType parameter. // ... }) - cb.OnOrderStatusChangeTest(func(e payments.OrderStatusChangeRequest) (*payments.OrderStatusChangeResponse, *payments.Error) { + cb.OnOrderStatusChangeTest(func(e payments.OrderStatusChangeRequest) ( + *payments.OrderStatusChangeResponse, + *payments.Error, + ) { // ... }) - cb.OnGetSubscriptionTest(func(e payments.GetSubscriptionRequest) (*payments.GetSubscriptionResponse, *payments.Error) { + cb.OnGetSubscriptionTest(func(e payments.GetSubscriptionRequest) ( + *payments.GetSubscriptionResponse, + *payments.Error, + ) { // ... }) - cb.OnSubscriptionStatusChangeTest(func(e payments.SubscriptionStatusChangeRequest) (*payments.SubscriptionStatusChangeResponse, *payments.Error) { + cb.OnSubscriptionStatusChangeTest(func(e payments.SubscriptionStatusChangeRequest) ( + *payments.SubscriptionStatusChangeResponse, + *payments.Error, + ) { // ... }) @@ -620,12 +638,18 @@ type SubscriptionStatusChangeResponse struct { // new one. // // See https://vk.com/dev/payments_subscriptionstatus -func (cb *Callback) OnSubscriptionStatusChange(f func(e SubscriptionStatusChangeRequest) (*SubscriptionStatusChangeResponse, *Error)) { +func (cb *Callback) OnSubscriptionStatusChange(f func(e SubscriptionStatusChangeRequest) ( + *SubscriptionStatusChangeResponse, + *Error, +)) { cb.subscriptionStatusChange = f } // OnSubscriptionStatusChangeTest OnSubscriptionStatusChange for test. -func (cb *Callback) OnSubscriptionStatusChangeTest(f func(e SubscriptionStatusChangeRequest) (*SubscriptionStatusChangeResponse, *Error)) { +func (cb *Callback) OnSubscriptionStatusChangeTest(f func(e SubscriptionStatusChangeRequest) ( + *SubscriptionStatusChangeResponse, + *Error, +)) { cb.subscriptionStatusChangeTest = f } From b72e5523d62ebcca8fbb8afbcc3aebaa8a918748 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Wed, 19 Aug 2020 19:19:11 +0300 Subject: [PATCH 088/105] fix: remove WallWallpostAttached This closed #129 --- object/messages.go | 34 +++++++++++++++++----------------- object/wall.go | 21 --------------------- 2 files changed, 17 insertions(+), 38 deletions(-) diff --git a/object/messages.go b/object/messages.go index 6853d92d..06af18b8 100644 --- a/object/messages.go +++ b/object/messages.go @@ -540,23 +540,23 @@ type MessagesMessageActionPhoto struct { // MessagesMessageAttachment struct. type MessagesMessageAttachment struct { - Audio AudioAudio `json:"audio"` - Doc DocsDoc `json:"doc"` - Gift GiftsLayout `json:"gift"` - Link BaseLink `json:"link"` - Market MarketMarketItem `json:"market"` - MarketMarketAlbum MarketMarketAlbum `json:"market_market_album"` - Photo PhotosPhoto `json:"photo"` - Sticker BaseSticker `json:"sticker"` - Type string `json:"type"` - Video VideoVideo `json:"video"` - Wall WallWallpostAttached `json:"wall"` - WallReply WallWallComment `json:"wall_reply"` - AudioMessage DocsDoc `json:"audio_message"` - Graffiti DocsDoc `json:"graffiti"` - Poll PollsPoll `json:"poll"` - Call MessageCall `json:"call"` - Story StoriesStory `json:"story"` + Audio AudioAudio `json:"audio"` + Doc DocsDoc `json:"doc"` + Gift GiftsLayout `json:"gift"` + Link BaseLink `json:"link"` + Market MarketMarketItem `json:"market"` + MarketMarketAlbum MarketMarketAlbum `json:"market_market_album"` + Photo PhotosPhoto `json:"photo"` + Sticker BaseSticker `json:"sticker"` + Type string `json:"type"` + Video VideoVideo `json:"video"` + Wall WallWallpost `json:"wall"` + WallReply WallWallComment `json:"wall_reply"` + AudioMessage DocsDoc `json:"audio_message"` + Graffiti DocsDoc `json:"graffiti"` + Poll PollsPoll `json:"poll"` + Call MessageCall `json:"call"` + Story StoriesStory `json:"story"` } // MessageCall struct. diff --git a/object/wall.go b/object/wall.go index f4e754ad..ac7ff5b6 100644 --- a/object/wall.go +++ b/object/wall.go @@ -156,27 +156,6 @@ type WallWallpost struct { ParentsStack []int `json:"parents_stack"` } -// WallWallpostAttached struct. -type WallWallpostAttached struct { - Attachments []WallWallpostAttachment `json:"attachments"` - CanDelete BaseBoolInt `json:"can_delete"` - Comments BaseCommentsInfo `json:"comments"` - CopyOwnerID int `json:"copy_owner_id"` - CopyPostID int `json:"copy_post_id"` - CopyText string `json:"copy_text"` - Date int `json:"date"` - FromID int `json:"from_id"` - Geo BaseGeo `json:"geo"` - ID int `json:"id"` - Likes BaseLikesInfo `json:"likes"` - PostSource WallPostSource `json:"post_source"` - PostType string `json:"post_type"` - Reposts BaseRepostsInfo `json:"reposts"` - SignerID int `json:"signer_id"` - Text string `json:"text"` - ToID int `json:"to_id"` -} - // Attachment type. // // TODO: check this. From 74afaa9c7027a93676c7157aeb9c7ba13cc72dad Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 23 Aug 2020 21:43:46 +0300 Subject: [PATCH 089/105] refactor: separate file for captcha --- api/api.go | 6 ------ api/api_test.go | 13 ------------- api/captcha.go | 7 +++++++ api/captcha_test.go | 20 ++++++++++++++++++++ 4 files changed, 27 insertions(+), 19 deletions(-) create mode 100644 api/captcha.go create mode 100644 api/captcha_test.go diff --git a/api/api.go b/api/api.go index 807d98ba..45e951c4 100644 --- a/api/api.go +++ b/api/api.go @@ -409,9 +409,3 @@ func FmtValue(value interface{}, depth int) string { return fmtReflectValue(reflect.ValueOf(value), depth) } - -// CaptchaForce api method. -func (vk *VK) CaptchaForce(params Params) (response int, err error) { - err = vk.RequestUnmarshal("captcha.force", params, &response) - return -} diff --git a/api/api_test.go b/api/api_test.go index 2025ff25..49a8652f 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -1,7 +1,6 @@ package api_test import ( - "errors" "fmt" "log" "os" @@ -298,18 +297,6 @@ func Test_FmtValue(t *testing.T) { f(&photo, "photo321_123") } -func TestVK_CaptchaForce(t *testing.T) { - t.Parallel() - - needUserToken(t) - - _, err := vkUser.CaptchaForce(api.Params{}) - - if !errors.Is(err, api.ErrCaptcha) { - t.Errorf("VK.CaptchaForce() err=%v, want 14", err) - } -} - func TestParams_methods(t *testing.T) { t.Parallel() diff --git a/api/captcha.go b/api/captcha.go new file mode 100644 index 00000000..04cffa51 --- /dev/null +++ b/api/captcha.go @@ -0,0 +1,7 @@ +package api + +// CaptchaForce api method. +func (vk *VK) CaptchaForce(params Params) (response int, err error) { + err = vk.RequestUnmarshal("captcha.force", params, &response) + return +} diff --git a/api/captcha_test.go b/api/captcha_test.go new file mode 100644 index 00000000..046f99cd --- /dev/null +++ b/api/captcha_test.go @@ -0,0 +1,20 @@ +package api_test + +import ( + "errors" + "testing" + + "github.com/SevereCloud/vksdk/api" +) + +func TestVK_CaptchaForce(t *testing.T) { + t.Parallel() + + needUserToken(t) + + _, err := vkUser.CaptchaForce(api.Params{}) + + if !errors.Is(err, api.ErrCaptcha) { + t.Errorf("VK.CaptchaForce() err=%v, want 14", err) + } +} From fa3c897af3ea0355cd099f39d592087f757d54e7 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sun, 23 Aug 2020 21:43:53 +0300 Subject: [PATCH 090/105] refactor: separate file for execute --- api/api.go | 55 -------------------------------------- api/api_test.go | 56 --------------------------------------- api/execute.go | 58 ++++++++++++++++++++++++++++++++++++++++ api/execute_test.go | 64 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 111 deletions(-) create mode 100644 api/execute.go create mode 100644 api/execute_test.go diff --git a/api/api.go b/api/api.go index 45e951c4..3d0c996c 100644 --- a/api/api.go +++ b/api/api.go @@ -303,61 +303,6 @@ func (vk *VK) RequestUnmarshal(method string, params Params, obj interface{}) er return json.Unmarshal(rawResponse, &obj) } -// ExecuteWithArgs a universal method for calling a sequence of other methods -// while saving and filtering interim results. -// -// The Args map variable allows you to retrieve the parameters passed during -// the request and avoids code formatting. -// -// return Args.code; // return parameter "code" -// return Args.v; // return parameter "v" -// -// https://vk.com/dev/execute -func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error { - token := vk.AccessToken - if vk.IsPoolClient { - token = vk.tokenPool.Get() - } - - copyParams := make(Params) - for key, value := range params { - copyParams[key] = FmtValue(value, 0) - } - - copyParams["code"] = code - copyParams["access_token"] = token - copyParams["v"] = vk.Version - - resp, err := vk.Handler("execute", copyParams) - - jsonErr := json.Unmarshal(resp.Response, &obj) - if jsonErr != nil { - return jsonErr - } - - if resp.ExecuteErrors != nil { - return &resp.ExecuteErrors - } - - return err -} - -// Execute a universal method for calling a sequence of other methods while -// saving and filtering interim results. -// -// https://vk.com/dev/execute -func (vk *VK) Execute(code string, obj interface{}) error { - return vk.ExecuteWithArgs(code, Params{}, obj) -} - -func fmtBool(value bool) string { - if value { - return "1" - } - - return "0" -} - func fmtReflectValue(value reflect.Value, depth int) string { switch f := value; value.Kind() { case reflect.Invalid: diff --git a/api/api_test.go b/api/api_test.go index 49a8652f..3eded63c 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -183,62 +183,6 @@ func TestVK_RequestLimit(t *testing.T) { vkUser.Limit = 3 } -func TestVK_Execute_error(t *testing.T) { - t.Parallel() - - needGroupToken(t) - - var response int - - err := vkGroup.Execute(`API.users.get({user_id:-1});return 1;`, &response) - assert.Error(t, err) - assert.Equal(t, 1, response) -} - -func TestVK_Execute_object(t *testing.T) { - t.Parallel() - - needGroupToken(t) - - var response struct { - Text string `json:"text"` - } - - err := vkGroup.Execute(`return {text: "hello"};`, &response) - assert.NoError(t, err) - assert.Equal(t, "hello", response.Text) -} - -func TestVK_ExecuteWithArgs_error(t *testing.T) { - t.Parallel() - - needGroupToken(t) - - var response int - - err := vkGroup.ExecuteWithArgs( - `API.users.get({user_id: parseInt(Args.user_id)});return 1;`, - api.Params{"user_id": -1}, - &response, - ) - assert.Error(t, err) - assert.Equal(t, 1, response) -} - -func TestVK_ExecuteWithArgs_object(t *testing.T) { - t.Parallel() - - needGroupToken(t) - - var response struct { - Text string `json:"text"` - } - - err := vkGroup.ExecuteWithArgs(`return {text: Args.text};`, api.Params{"text": "hello"}, &response) - assert.NoError(t, err) - assert.Equal(t, "hello", response.Text) -} - func TestVK_InvalidContentType(t *testing.T) { t.Parallel() diff --git a/api/execute.go b/api/execute.go new file mode 100644 index 00000000..6d6b8dca --- /dev/null +++ b/api/execute.go @@ -0,0 +1,58 @@ +package api + +import "encoding/json" + +// ExecuteWithArgs a universal method for calling a sequence of other methods +// while saving and filtering interim results. +// +// The Args map variable allows you to retrieve the parameters passed during +// the request and avoids code formatting. +// +// return Args.code; // return parameter "code" +// return Args.v; // return parameter "v" +// +// https://vk.com/dev/execute +func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error { + token := vk.AccessToken + if vk.IsPoolClient { + token = vk.tokenPool.Get() + } + + copyParams := make(Params) + for key, value := range params { + copyParams[key] = FmtValue(value, 0) + } + + copyParams["code"] = code + copyParams["access_token"] = token + copyParams["v"] = vk.Version + + resp, err := vk.Handler("execute", copyParams) + + jsonErr := json.Unmarshal(resp.Response, &obj) + if jsonErr != nil { + return jsonErr + } + + if resp.ExecuteErrors != nil { + return &resp.ExecuteErrors + } + + return err +} + +// Execute a universal method for calling a sequence of other methods while +// saving and filtering interim results. +// +// https://vk.com/dev/execute +func (vk *VK) Execute(code string, obj interface{}) error { + return vk.ExecuteWithArgs(code, Params{}, obj) +} + +func fmtBool(value bool) string { + if value { + return "1" + } + + return "0" +} diff --git a/api/execute_test.go b/api/execute_test.go new file mode 100644 index 00000000..6803ab9f --- /dev/null +++ b/api/execute_test.go @@ -0,0 +1,64 @@ +package api_test + +import ( + "testing" + + "github.com/SevereCloud/vksdk/api" + "github.com/stretchr/testify/assert" +) + +func TestVK_Execute_error(t *testing.T) { + t.Parallel() + + needGroupToken(t) + + var response int + + err := vkGroup.Execute(`API.users.get({user_id:-1});return 1;`, &response) + assert.Error(t, err) + assert.Equal(t, 1, response) +} + +func TestVK_Execute_object(t *testing.T) { + t.Parallel() + + needGroupToken(t) + + var response struct { + Text string `json:"text"` + } + + err := vkGroup.Execute(`return {text: "hello"};`, &response) + assert.NoError(t, err) + assert.Equal(t, "hello", response.Text) +} + +func TestVK_ExecuteWithArgs_error(t *testing.T) { + t.Parallel() + + needGroupToken(t) + + var response int + + err := vkGroup.ExecuteWithArgs( + `API.users.get({user_id: parseInt(Args.user_id)});return 1;`, + api.Params{"user_id": -1}, + &response, + ) + assert.Error(t, err) + assert.Equal(t, 1, response) +} + +func TestVK_ExecuteWithArgs_object(t *testing.T) { + t.Parallel() + + needGroupToken(t) + + var response struct { + Text string `json:"text"` + } + + err := vkGroup.ExecuteWithArgs(`return {text: Args.text};`, api.Params{"text": "hello"}, &response) + assert.NoError(t, err) + assert.Equal(t, "hello", response.Text) +} From 173cd2ac95fde7a243f2e95aef174ffabc64f179 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 24 Aug 2020 12:53:15 +0300 Subject: [PATCH 091/105] build(deps): bump github.com/gorilla/schema from 1.1.0 to 1.2.0 --- go.mod | 4 ++-- go.sum | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index c0cc0cc7..5e5da277 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,9 @@ module github.com/SevereCloud/vksdk -go 1.12 +go 1.13 require ( - github.com/gorilla/schema v1.1.0 + github.com/gorilla/schema v1.2.0 github.com/gorilla/websocket v1.4.2 github.com/stretchr/testify v1.6.1 golang.org/x/text v0.3.3 diff --git a/go.sum b/go.sum index 126b0c14..4f56b741 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gorilla/schema v1.1.0 h1:CamqUDOFUBqzrvxuz2vEwo8+SUdwsluFh7IlzJh30LY= -github.com/gorilla/schema v1.1.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= +github.com/gorilla/schema v1.2.0 h1:YufUaxZYCKGFuAq3c96BOhjgd5nmXiOY9NGzF247Tsc= +github.com/gorilla/schema v1.2.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= From ebebb18db446e486f45686e447470a2ef79e5959 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sat, 29 Aug 2020 19:17:23 +0300 Subject: [PATCH 092/105] docs: fix readme --- callback/README.md | 16 +++++++++++++--- longpoll-bot/README.md | 17 ++++++++++++++--- longpoll-user/v3/README.md | 2 +- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/callback/README.md b/callback/README.md index c8a456b5..d4f7893a 100644 --- a/callback/README.md +++ b/callback/README.md @@ -36,13 +36,23 @@ Пример для события `message_new` ```go -cb.MessageNew(func(ctx context.Context, object object.MessageNewObject) { +cb.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { ... }) ``` Полный список событий Вы найдёте [в документации](https://vk.com/dev/groups_events) +### Контекст + +Поля `groupID` и `eventID` передаются в `ctx`. Чтобы получить их, можно +воспользоваться следующими функциями: + +```go +groupID := events.GroupIDFromContext(ctx) +eventID := events.EventIDFromContext(ctx) +``` + ### Веб-сервер Для модуля **net/http** воспользуйтесь функцией `HandleFunc` @@ -62,7 +72,7 @@ import ( "net/http" "github.com/SevereCloud/vksdk/callback" - "github.com/SevereCloud/vksdk/object" + "github.com/SevereCloud/vksdk/events" ) func main() { @@ -71,7 +81,7 @@ func main() { cb.ConfirmationKey = "693d0ba9" // cb.ConfirmationKeys[170561776] = "693d0ba9" - cb.MessageNew(func(ctx context.Context, obj object.MessageNewObject) { + cb.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { log.Print(obj.Message.Text) }) diff --git a/longpoll-bot/README.md b/longpoll-bot/README.md index 2bbc8491..f66e28f8 100644 --- a/longpoll-bot/README.md +++ b/longpoll-bot/README.md @@ -57,7 +57,7 @@ lp.Client.Transport = httpTransport Пример для события `message_new` ```go -lp.MessageNew(func(ctx context.Context, obj object.MessageNewObject) { +lp.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { ... }) ``` @@ -73,6 +73,17 @@ lp.FullResponse(func(resp object.LongpollBotResponse) { Полный список событий Вы найдёте [в документации](https://vk.com/dev/groups_events) +### Контекст + +Поля `groupID`, `ts` и `eventID` передаются в `ctx`. Чтобы получить их, можно +воспользоваться следующими функциями: + +```go +groupID := events.GroupIDFromContext(ctx) +eventID := events.EventIDFromContext(ctx) +ts := longpoll.TsFromContext(ctx) +``` + ### Запуск и остановка ```go @@ -101,7 +112,7 @@ import ( "github.com/SevereCloud/vksdk/api" longpoll "github.com/SevereCloud/vksdk/longpoll-bot" - "github.com/SevereCloud/vksdk/object" + "github.com/SevereCloud/vksdk/events" ) func main() { @@ -111,7 +122,7 @@ func main() { panic(err) } - lp.MessageNew(func(ctx context.Context, obj object.MessageNewObject) { + lp.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { log.Print(obj.Message.Text) }) diff --git a/longpoll-user/v3/README.md b/longpoll-user/v3/README.md index 01eec632..65a8bed0 100644 --- a/longpoll-user/v3/README.md +++ b/longpoll-user/v3/README.md @@ -8,7 +8,7 @@ ```go // import "github.com/SevereCloud/vksdk/longpoll-user/v3" -w := wrapper.NewWrapper(&lp) +w := wrapper.NewWrapper(lp) // event with code 4 w.OnNewMessage(func(m wrapper.NewMessage) { From b88e020b267c5c06cfeeae80a0e8b4dca22bbe40 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sat, 29 Aug 2020 21:13:22 +0300 Subject: [PATCH 093/105] BREAKING CHANGE: support ...Params --- README.md | 2 +- api/README.md | 2 +- api/account.go | 38 ++++----- api/account_test.go | 14 ++-- api/ads.go | 90 ++++++++++---------- api/ads_test.go | 2 +- api/api.go | 40 ++++----- api/api_test.go | 10 +-- api/apps.go | 24 +++--- api/apps_test.go | 10 +-- api/appwidgets.go | 16 ++-- api/auth.go | 4 +- api/board.go | 34 ++++---- api/captcha.go | 2 +- api/captcha_test.go | 2 +- api/database.go | 24 +++--- api/database_test.go | 2 +- api/docs.go | 22 ++--- api/docs_test.go | 8 +- api/downloadedGames.go | 3 +- api/execute.go | 13 ++- api/fave.go | 50 ++++++----- api/fave_test.go | 12 +-- api/friends.go | 70 +++++++++------- api/friends_test.go | 16 ++-- api/gifts.go | 4 +- api/gifts_test.go | 2 +- api/groups.go | 140 ++++++++++++++----------------- api/groups_test.go | 10 +-- api/leadforms.go | 14 ++-- api/leads.go | 12 +-- api/likes.go | 12 ++- api/market.go | 60 +++++++------ api/market_test.go | 2 +- api/messages.go | 100 +++++++++++----------- api/messages_test.go | 6 +- api/newsfeed.go | 38 ++++----- api/newsfeed_test.go | 10 +-- api/notes.go | 20 ++--- api/notifications.go | 6 +- api/notifications_test.go | 2 +- api/orders.go | 16 ++-- api/pages.go | 16 ++-- api/photos.go | 118 ++++++++++++-------------- api/photos_test.go | 10 +-- api/podcasts.go | 28 +++---- api/podcasts_test.go | 14 ++-- api/polls.go | 20 ++--- api/polls_test.go | 4 +- api/prettycards.go | 12 +-- api/search.go | 2 +- api/secure.go | 20 ++--- api/stats.go | 6 +- api/stats_test.go | 2 +- api/status.go | 4 +- api/status_test.go | 2 +- api/storage.go | 6 +- api/storage_test.go | 2 +- api/stories.go | 52 +++++------- api/stories_test.go | 8 +- api/streaming.go | 10 +-- api/streaming_test.go | 14 ++-- api/upload.go | 8 +- api/users.go | 17 ++-- api/utils.go | 16 ++-- api/utils_test.go | 4 +- api/video.go | 68 +++++++-------- api/wall.go | 66 +++++++-------- api/widgets.go | 4 +- api/widgets_test.go | 2 +- longpoll-bot/longpoll.go | 2 +- longpoll-user/v3/wrapper_test.go | 2 +- streaming/streaming.go | 2 +- 73 files changed, 712 insertions(+), 793 deletions(-) diff --git a/README.md b/README.md index 4fe567f8..3c8ded17 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ func main() { vk := api.NewVK(token) // Получаем информацию о группе - group, err := vk.GroupsGetByID(api.Params{}) + group, err := vk.GroupsGetByID(nil) if err != nil { log.Fatal(err) } diff --git a/api/README.md b/api/README.md index 6a2ac6bf..e26b7ab9 100644 --- a/api/README.md +++ b/api/README.md @@ -94,7 +94,7 @@ params := api.Params{ } // Делаем запрос -err = vk.RequestUnmarshal("users.get", params, &response) +err = vk.RequestUnmarshal("users.get", &response, params) if err != nil { log.Fatal(err) } diff --git a/api/account.go b/api/account.go index 112859bf..589701a8 100644 --- a/api/account.go +++ b/api/account.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/account.ban func (vk *VK) AccountBan(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.ban", params, &response) + err = vk.RequestUnmarshal("account.ban", &response, params) return } @@ -21,7 +21,7 @@ type AccountChangePasswordResponse struct { // // https://vk.com/dev/account.changePassword func (vk *VK) AccountChangePassword(params Params) (response AccountChangePasswordResponse, err error) { - err = vk.RequestUnmarshal("account.changePassword", params, &response) + err = vk.RequestUnmarshal("account.changePassword", &response, params) return } @@ -37,7 +37,7 @@ type AccountGetActiveOffersResponse struct { // // https://vk.com/dev/account.getActiveOffers func (vk *VK) AccountGetActiveOffers(params Params) (response AccountGetActiveOffersResponse, err error) { - err = vk.RequestUnmarshal("account.getActiveOffers", params, &response) + err = vk.RequestUnmarshal("account.getActiveOffers", &response, params) return } @@ -45,7 +45,7 @@ func (vk *VK) AccountGetActiveOffers(params Params) (response AccountGetActiveOf // // https://vk.com/dev/account.getAppPermissions func (vk *VK) AccountGetAppPermissions(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.getAppPermissions", params, &response) + err = vk.RequestUnmarshal("account.getAppPermissions", &response, params) return } @@ -60,7 +60,7 @@ type AccountGetBannedResponse struct { // // https://vk.com/dev/account.getBanned func (vk *VK) AccountGetBanned(params Params) (response AccountGetBannedResponse, err error) { - err = vk.RequestUnmarshal("account.getBanned", params, &response) + err = vk.RequestUnmarshal("account.getBanned", &response, params) return } @@ -71,7 +71,7 @@ type AccountGetCountersResponse object.AccountAccountCounters // // https://vk.com/dev/account.getCounters func (vk *VK) AccountGetCounters(params Params) (response AccountGetCountersResponse, err error) { - err = vk.RequestUnmarshal("account.getCounters", params, &response) + err = vk.RequestUnmarshal("account.getCounters", &response, params) return } @@ -82,7 +82,7 @@ type AccountGetInfoResponse object.AccountInfo // // https://vk.com/dev/account.getInfo func (vk *VK) AccountGetInfo(params Params) (response AccountGetInfoResponse, err error) { - err = vk.RequestUnmarshal("account.getInfo", params, &response) + err = vk.RequestUnmarshal("account.getInfo", &response, params) return } @@ -93,7 +93,7 @@ type AccountGetProfileInfoResponse object.AccountUserSettings // // https://vk.com/dev/account.getProfileInfo func (vk *VK) AccountGetProfileInfo(params Params) (response AccountGetProfileInfoResponse, err error) { - err = vk.RequestUnmarshal("account.getProfileInfo", params, &response) + err = vk.RequestUnmarshal("account.getProfileInfo", &response, params) return } @@ -104,7 +104,7 @@ type AccountGetPushSettingsResponse object.AccountPushSettings // // https://vk.com/dev/account.getPushSettings func (vk *VK) AccountGetPushSettings(params Params) (response AccountGetPushSettingsResponse, err error) { - err = vk.RequestUnmarshal("account.getPushSettings", params, &response) + err = vk.RequestUnmarshal("account.getPushSettings", &response, params) return } @@ -112,7 +112,7 @@ func (vk *VK) AccountGetPushSettings(params Params) (response AccountGetPushSett // // https://vk.com/dev/account.registerDevice func (vk *VK) AccountRegisterDevice(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.registerDevice", params, &response) + err = vk.RequestUnmarshal("account.registerDevice", &response, params) return } @@ -126,7 +126,7 @@ type AccountSaveProfileInfoResponse struct { // // https://vk.com/dev/account.saveProfileInfo func (vk *VK) AccountSaveProfileInfo(params Params) (response AccountSaveProfileInfoResponse, err error) { - err = vk.RequestUnmarshal("account.saveProfileInfo", params, &response) + err = vk.RequestUnmarshal("account.saveProfileInfo", &response, params) return } @@ -134,7 +134,7 @@ func (vk *VK) AccountSaveProfileInfo(params Params) (response AccountSaveProfile // // https://vk.com/dev/account.setInfo func (vk *VK) AccountSetInfo(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.setInfo", params, &response) + err = vk.RequestUnmarshal("account.setInfo", &response, params) return } @@ -143,7 +143,7 @@ func (vk *VK) AccountSetInfo(params Params) (response int, err error) { // // https://vk.com/dev/account.setNameInMenu func (vk *VK) AccountSetNameInMenu(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.setNameInMenu", params, &response) + err = vk.RequestUnmarshal("account.setNameInMenu", &response, params) return } @@ -151,7 +151,7 @@ func (vk *VK) AccountSetNameInMenu(params Params) (response int, err error) { // // https://vk.com/dev/account.setOffline func (vk *VK) AccountSetOffline(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.setOffline", params, &response) + err = vk.RequestUnmarshal("account.setOffline", &response, params) return } @@ -159,7 +159,7 @@ func (vk *VK) AccountSetOffline(params Params) (response int, err error) { // // https://vk.com/dev/account.setOnline func (vk *VK) AccountSetOnline(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.setOnline", params, &response) + err = vk.RequestUnmarshal("account.setOnline", &response, params) return } @@ -167,7 +167,7 @@ func (vk *VK) AccountSetOnline(params Params) (response int, err error) { // // https://vk.com/dev/account.setPushSettings func (vk *VK) AccountSetPushSettings(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.setPushSettings", params, &response) + err = vk.RequestUnmarshal("account.setPushSettings", &response, params) return } @@ -175,7 +175,7 @@ func (vk *VK) AccountSetPushSettings(params Params) (response int, err error) { // // https://vk.com/dev/account.setSilenceMode func (vk *VK) AccountSetSilenceMode(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.setSilenceMode", params, &response) + err = vk.RequestUnmarshal("account.setSilenceMode", &response, params) return } @@ -183,7 +183,7 @@ func (vk *VK) AccountSetSilenceMode(params Params) (response int, err error) { // // https://vk.com/dev/account.unban func (vk *VK) AccountUnban(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.unban", params, &response) + err = vk.RequestUnmarshal("account.unban", &response, params) return } @@ -191,6 +191,6 @@ func (vk *VK) AccountUnban(params Params) (response int, err error) { // // https://vk.com/dev/account.unregisterDevice func (vk *VK) AccountUnregisterDevice(params Params) (response int, err error) { - err = vk.RequestUnmarshal("account.unregisterDevice", params, &response) + err = vk.RequestUnmarshal("account.unregisterDevice", &response, params) return } diff --git a/api/account_test.go b/api/account_test.go index 2bfcd33b..840cf4bb 100644 --- a/api/account_test.go +++ b/api/account_test.go @@ -27,7 +27,7 @@ func TestVK_AccountBan(t *testing.T) { time.Sleep(3 * time.Second) - res, err := vkUser.AccountGetBanned(api.Params{}) + res, err := vkUser.AccountGetBanned(nil) noError(t, err) assert.NotEmpty(t, res.Count) assert.NotEmpty(t, res.Items) @@ -56,7 +56,7 @@ func TestVK_AccountGetActiveOffers(t *testing.T) { needUserToken(t) - _, err := vkUser.AccountGetActiveOffers(api.Params{}) + _, err := vkUser.AccountGetActiveOffers(nil) noError(t, err) } @@ -88,7 +88,7 @@ func TestVK_AccountGetInfo(t *testing.T) { needUserToken(t) - _, err := vkUser.AccountGetInfo(api.Params{}) + _, err := vkUser.AccountGetInfo(nil) noError(t, err) } @@ -97,7 +97,7 @@ func TestVK_AccountGetProfileInfo(t *testing.T) { needUserToken(t) - info, err := vkUser.AccountGetProfileInfo(api.Params{}) + info, err := vkUser.AccountGetProfileInfo(nil) noError(t, err) assert.NotEmpty(t, info.FirstName) assert.NotEmpty(t, info.LastName) @@ -133,7 +133,7 @@ func TestVK_AccountSaveProfileInfo(t *testing.T) { needUserToken(t) - _, err := vkUser.AccountSaveProfileInfo(api.Params{}) + _, err := vkUser.AccountSaveProfileInfo(nil) noError(t, err) } @@ -150,7 +150,7 @@ func TestVK_AccountSetOffline(t *testing.T) { needUserToken(t) - _, err := vkUser.AccountSetOffline(api.Params{}) + _, err := vkUser.AccountSetOffline(nil) noError(t, err) } @@ -159,7 +159,7 @@ func TestVK_AccountSetOnline(t *testing.T) { needUserToken(t) - _, err := vkUser.AccountSetOnline(api.Params{}) + _, err := vkUser.AccountSetOnline(nil) noError(t, err) } diff --git a/api/ads.go b/api/ads.go index f03d8dc1..25c1800b 100644 --- a/api/ads.go +++ b/api/ads.go @@ -11,7 +11,7 @@ import ( // // https://vk.com/dev/ads.addOfficeUsers // func (vk *VK) AdsAddOfficeUsers(params Params) (response AdsAddOfficeUsersResponse, err error) { -// err = vk.RequestUnmarshal("ads.addOfficeUsers", params, &response) +// err = vk.RequestUnmarshal("ads.addOfficeUsers", &response, params) // return // } @@ -22,7 +22,7 @@ import ( // // https://vk.com/dev/ads.checkLink // func (vk *VK) AdsCheckLink(params Params) (response AdsCheckLinkResponse, err error) { -// err = vk.RequestUnmarshal("ads.checkLink", params, &response) +// err = vk.RequestUnmarshal("ads.checkLink", &response, params) // return // } @@ -33,7 +33,7 @@ import ( // // https://vk.com/dev/ads.createAds // func (vk *VK) AdsCreateAds(params Params) (response AdsCreateAdsResponse, err error) { -// err = vk.RequestUnmarshal("ads.createAds", params, &response) +// err = vk.RequestUnmarshal("ads.createAds", &response, params) // return // } @@ -44,7 +44,7 @@ import ( // // https://vk.com/dev/ads.createCampaigns // func (vk *VK) AdsCreateCampaigns(params Params) (response AdsCreateCampaignsResponse, err error) { -// err = vk.RequestUnmarshal("ads.createCampaigns", params, &response) +// err = vk.RequestUnmarshal("ads.createCampaigns", &response, params) // return // } @@ -55,7 +55,7 @@ import ( // // https://vk.com/dev/ads.createClients // func (vk *VK) AdsCreateClients(params Params) (response AdsCreateClientsResponse, err error) { -// err = vk.RequestUnmarshal("ads.createClients", params, &response) +// err = vk.RequestUnmarshal("ads.createClients", &response, params) // return // } @@ -66,7 +66,7 @@ import ( // // https://vk.com/dev/ads.createLookalikeRequest // func (vk *VK) AdsCreateLookalikeRequest(params Params) (response AdsCreateLookalikeRequestResponse, err error) { -// err = vk.RequestUnmarshal("ads.createLookalikeRequest", params, &response) +// err = vk.RequestUnmarshal("ads.createLookalikeRequest", &response, params) // return // } @@ -77,7 +77,7 @@ import ( // // https://vk.com/dev/ads.createTargetGroup // func (vk *VK) AdsCreateTargetGroup(params Params) (response AdsCreateTargetGroupResponse, err error) { -// err = vk.RequestUnmarshal("ads.createTargetGroup", params, &response) +// err = vk.RequestUnmarshal("ads.createTargetGroup", &response, params) // return // } @@ -88,7 +88,7 @@ import ( // // https://vk.com/dev/ads.createTargetPixel // func (vk *VK) AdsCreateTargetPixel(params Params) (response AdsCreateTargetPixelResponse, err error) { -// err = vk.RequestUnmarshal("ads.createTargetPixel", params, &response) +// err = vk.RequestUnmarshal("ads.createTargetPixel", &response, params) // return // } @@ -99,7 +99,7 @@ import ( // // https://vk.com/dev/ads.deleteAds // func (vk *VK) AdsDeleteAds(params Params) (response AdsDeleteAdsResponse, err error) { -// err = vk.RequestUnmarshal("ads.deleteAds", params, &response) +// err = vk.RequestUnmarshal("ads.deleteAds", &response, params) // return // } @@ -110,7 +110,7 @@ import ( // // https://vk.com/dev/ads.deleteCampaigns // func (vk *VK) AdsDeleteCampaigns(params Params) (response AdsDeleteCampaignsResponse, err error) { -// err = vk.RequestUnmarshal("ads.deleteCampaigns", params, &response) +// err = vk.RequestUnmarshal("ads.deleteCampaigns", &response, params) // return // } @@ -121,7 +121,7 @@ import ( // // https://vk.com/dev/ads.deleteClients // func (vk *VK) AdsDeleteClients(params Params) (response AdsDeleteClientsResponse, err error) { -// err = vk.RequestUnmarshal("ads.deleteClients", params, &response) +// err = vk.RequestUnmarshal("ads.deleteClients", &response, params) // return // } @@ -129,7 +129,7 @@ import ( // // https://vk.com/dev/ads.deleteTargetGroup func (vk *VK) AdsDeleteTargetGroup(params Params) (response int, err error) { - err = vk.RequestUnmarshal("ads.deleteTargetGroup", params, &response) + err = vk.RequestUnmarshal("ads.deleteTargetGroup", &response, params) return } @@ -137,7 +137,7 @@ func (vk *VK) AdsDeleteTargetGroup(params Params) (response int, err error) { // // https://vk.com/dev/ads.deleteTargetPixel func (vk *VK) AdsDeleteTargetPixel(params Params) (response int, err error) { - err = vk.RequestUnmarshal("ads.deleteTargetPixel", params, &response) + err = vk.RequestUnmarshal("ads.deleteTargetPixel", &response, params) return } @@ -148,7 +148,7 @@ type AdsGetAccountsResponse []object.AdsAccount // // https://vk.com/dev/ads.getAccounts func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, err error) { - err = vk.RequestUnmarshal("ads.getAccounts", params, &response) + err = vk.RequestUnmarshal("ads.getAccounts", &response, params) return } @@ -159,7 +159,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getAds // func (vk *VK) AdsGetAds(params Params) (response AdsGetAdsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getAds", params, &response) +// err = vk.RequestUnmarshal("ads.getAds", &response, params) // return // } @@ -170,7 +170,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getAdsLayout // func (vk *VK) AdsGetAdsLayout(params Params) (response AdsGetAdsLayoutResponse, err error) { -// err = vk.RequestUnmarshal("ads.getAdsLayout", params, &response) +// err = vk.RequestUnmarshal("ads.getAdsLayout", &response, params) // return // } @@ -181,7 +181,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getAdsTargeting // func (vk *VK) AdsGetAdsTargeting(params Params) (response AdsGetAdsTargetingResponse, err error) { -// err = vk.RequestUnmarshal("ads.getAdsTargeting", params, &response) +// err = vk.RequestUnmarshal("ads.getAdsTargeting", &response, params) // return // } @@ -192,7 +192,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getBudget // func (vk *VK) AdsGetBudget(params Params) (response AdsGetBudgetResponse, err error) { -// err = vk.RequestUnmarshal("ads.getBudget", params, &response) +// err = vk.RequestUnmarshal("ads.getBudget", &response, params) // return // } @@ -203,7 +203,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getCampaigns // func (vk *VK) AdsGetCampaigns(params Params) (response AdsGetCampaignsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getCampaigns", params, &response) +// err = vk.RequestUnmarshal("ads.getCampaigns", &response, params) // return // } @@ -214,7 +214,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getCategories // func (vk *VK) AdsGetCategories(params Params) (response AdsGetCategoriesResponse, err error) { -// err = vk.RequestUnmarshal("ads.getCategories", params, &response) +// err = vk.RequestUnmarshal("ads.getCategories", &response, params) // return // } @@ -225,7 +225,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getClients // func (vk *VK) AdsGetClients(params Params) (response AdsGetClientsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getClients", params, &response) +// err = vk.RequestUnmarshal("ads.getClients", &response, params) // return // } @@ -236,7 +236,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getDemographics // func (vk *VK) AdsGetDemographics(params Params) (response AdsGetDemographicsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getDemographics", params, &response) +// err = vk.RequestUnmarshal("ads.getDemographics", &response, params) // return // } @@ -247,7 +247,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getFloodStats // func (vk *VK) AdsGetFloodStats(params Params) (response AdsGetFloodStatsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getFloodStats", params, &response) +// err = vk.RequestUnmarshal("ads.getFloodStats", &response, params) // return // } @@ -258,7 +258,7 @@ func (vk *VK) AdsGetAccounts(params Params) (response AdsGetAccountsResponse, er // // https://vk.com/dev/ads.getLookalikeRequests // func (vk *VK) AdsGetLookalikeRequests(params Params) (response AdsGetLookalikeRequestsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getLookalikeRequests", params, &response) +// err = vk.RequestUnmarshal("ads.getLookalikeRequests", &response, params) // return // } @@ -271,7 +271,7 @@ type AdsGetMusiciansResponse struct { // // https://vk.com/dev/ads.getMusicians func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, err error) { - err = vk.RequestUnmarshal("ads.getMusicians", params, &response) + err = vk.RequestUnmarshal("ads.getMusicians", &response, params) return } @@ -282,7 +282,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getOfficeUsers // func (vk *VK) AdsGetOfficeUsers(params Params) (response AdsGetOfficeUsersResponse, err error) { -// err = vk.RequestUnmarshal("ads.getOfficeUsers", params, &response) +// err = vk.RequestUnmarshal("ads.getOfficeUsers", &response, params) // return // } @@ -293,7 +293,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getPostsReach // func (vk *VK) AdsGetPostsReach(params Params) (response AdsGetPostsReachResponse, err error) { -// err = vk.RequestUnmarshal("ads.getPostsReach", params, &response) +// err = vk.RequestUnmarshal("ads.getPostsReach", &response, params) // return // } @@ -304,7 +304,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getRejectionReason // func (vk *VK) AdsGetRejectionReason(params Params) (response AdsGetRejectionReasonResponse, err error) { -// err = vk.RequestUnmarshal("ads.getRejectionReason", params, &response) +// err = vk.RequestUnmarshal("ads.getRejectionReason", &response, params) // return // } @@ -315,7 +315,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getStatistics // func (vk *VK) AdsGetStatistics(params Params) (response AdsGetStatisticsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getStatistics", params, &response) +// err = vk.RequestUnmarshal("ads.getStatistics", &response, params) // return // } @@ -326,7 +326,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getSuggestions // func (vk *VK) AdsGetSuggestions(params Params) (response AdsGetSuggestionsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getSuggestions", params, &response) +// err = vk.RequestUnmarshal("ads.getSuggestions", &response, params) // return // } @@ -337,7 +337,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getTargetGroups // func (vk *VK) AdsGetTargetGroups(params Params) (response AdsGetTargetGroupsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getTargetGroups", params, &response) +// err = vk.RequestUnmarshal("ads.getTargetGroups", &response, params) // return // } @@ -348,7 +348,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getTargetPixels // func (vk *VK) AdsGetTargetPixels(params Params) (response AdsGetTargetPixelsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getTargetPixels", params, &response) +// err = vk.RequestUnmarshal("ads.getTargetPixels", &response, params) // return // } @@ -359,7 +359,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getTargetingStats // func (vk *VK) AdsGetTargetingStats(params Params) (response AdsGetTargetingStatsResponse, err error) { -// err = vk.RequestUnmarshal("ads.getTargetingStats", params, &response) +// err = vk.RequestUnmarshal("ads.getTargetingStats", &response, params) // return // } @@ -370,7 +370,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getUploadURL // func (vk *VK) AdsGetUploadURL(params Params) (response AdsGetUploadURLResponse, err error) { -// err = vk.RequestUnmarshal("ads.getUploadURL", params, &response) +// err = vk.RequestUnmarshal("ads.getUploadURL", &response, params) // return // } @@ -381,7 +381,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.getVideoUploadURL // func (vk *VK) AdsGetVideoUploadURL(params Params) (response AdsGetVideoUploadURLResponse, err error) { -// err = vk.RequestUnmarshal("ads.getVideoUploadURL", params, &response) +// err = vk.RequestUnmarshal("ads.getVideoUploadURL", &response, params) // return // } @@ -392,7 +392,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.importTargetContacts // func (vk *VK) AdsImportTargetContacts(params Params) (response AdsImportTargetContactsResponse, err error) { -// err = vk.RequestUnmarshal("ads.importTargetContacts", params, &response) +// err = vk.RequestUnmarshal("ads.importTargetContacts", &response, params) // return // } @@ -403,7 +403,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.removeOfficeUsers // func (vk *VK) AdsRemoveOfficeUsers(params Params) (response AdsRemoveOfficeUsersResponse, err error) { -// err = vk.RequestUnmarshal("ads.removeOfficeUsers", params, &response) +// err = vk.RequestUnmarshal("ads.removeOfficeUsers", &response, params) // return // } @@ -417,7 +417,7 @@ func (vk *VK) AdsGetMusicians(params Params) (response AdsGetMusiciansResponse, // // https://vk.com/dev/ads.removeTargetContacts func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { - err = vk.RequestUnmarshal("ads.removeTargetContacts", params, &response) + err = vk.RequestUnmarshal("ads.removeTargetContacts", &response, params) return } @@ -431,7 +431,7 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // response AdsSaveLookalikeRequestResultResponse, // err error, // ) { -// err = vk.RequestUnmarshal("ads.saveLookalikeRequestResult", params, &response) +// err = vk.RequestUnmarshal("ads.saveLookalikeRequestResult", &response, params) // return // } @@ -442,7 +442,7 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // // https://vk.com/dev/ads.shareTargetGroup // func (vk *VK) AdsShareTargetGroup(params Params) (response AdsShareTargetGroupResponse, err error) { -// err = vk.RequestUnmarshal("ads.shareTargetGroup", params, &response) +// err = vk.RequestUnmarshal("ads.shareTargetGroup", &response, params) // return // } @@ -453,7 +453,7 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // // https://vk.com/dev/ads.updateAds // func (vk *VK) AdsUpdateAds(params Params) (response AdsUpdateAdsResponse, err error) { -// err = vk.RequestUnmarshal("ads.updateAds", params, &response) +// err = vk.RequestUnmarshal("ads.updateAds", &response, params) // return // } @@ -464,7 +464,7 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // // https://vk.com/dev/ads.updateCampaigns // func (vk *VK) AdsUpdateCampaigns(params Params) (response AdsUpdateCampaignsResponse, err error) { -// err = vk.RequestUnmarshal("ads.updateCampaigns", params, &response) +// err = vk.RequestUnmarshal("ads.updateCampaigns", &response, params) // return // } @@ -475,7 +475,7 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // // https://vk.com/dev/ads.updateClients // func (vk *VK) AdsUpdateClients(params Params) (response AdsUpdateClientsResponse, err error) { -// err = vk.RequestUnmarshal("ads.updateClients", params, &response) +// err = vk.RequestUnmarshal("ads.updateClients", &response, params) // return // } @@ -483,7 +483,7 @@ func (vk *VK) AdsRemoveTargetContacts(params Params) (response int, err error) { // // https://vk.com/dev/ads.updateTargetGroup func (vk *VK) AdsUpdateTargetGroup(params Params) (response int, err error) { - err = vk.RequestUnmarshal("ads.updateTargetGroup", params, &response) + err = vk.RequestUnmarshal("ads.updateTargetGroup", &response, params) return } @@ -491,6 +491,6 @@ func (vk *VK) AdsUpdateTargetGroup(params Params) (response int, err error) { // // https://vk.com/dev/ads.updateTargetPixel func (vk *VK) AdsUpdateTargetPixel(params Params) (response int, err error) { - err = vk.RequestUnmarshal("ads. updateTargetPixel", params, &response) + err = vk.RequestUnmarshal("ads. updateTargetPixel", &response, params) return } diff --git a/api/ads_test.go b/api/ads_test.go index 50c7842c..f5a13517 100644 --- a/api/ads_test.go +++ b/api/ads_test.go @@ -12,7 +12,7 @@ func TestVK_AdsGetAccounts(t *testing.T) { needUserToken(t) - _, err := vkUser.AdsGetAccounts(api.Params{}) + _, err := vkUser.AdsGetAccounts(nil) noError(t, err) } diff --git a/api/api.go b/api/api.go index 3d0c996c..d7816b44 100644 --- a/api/api.go +++ b/api/api.go @@ -86,7 +86,7 @@ type VK struct { IsPoolClient bool Limit int UserAgent string - Handler func(method string, params Params) (Response, error) + Handler func(method string, params ...Params) (Response, error) tokenPool internal.TokenPool mux sync.Mutex @@ -189,12 +189,14 @@ func (p Params) Confirm(v bool) Params { } // defaultHandler provides access to VK API methods. -func (vk *VK) defaultHandler(method string, params Params) (Response, error) { +func (vk *VK) defaultHandler(method string, sliceParams ...Params) (Response, error) { u := vk.MethodURL + method query := url.Values{} - for key, value := range params { - query.Set(key, FmtValue(value, 0)) + for _, params := range sliceParams { + for key, value := range params { + query.Set(key, FmtValue(value, 0)) + } } attempt := 0 @@ -267,35 +269,27 @@ func (vk *VK) defaultHandler(method string, params Params) (Response, error) { } // Request provides access to VK API methods. -// -// TODO: remove in v2. -func (vk *VK) Request(method string, params Params) ([]byte, error) { - copyParams := make(Params) - for key, value := range params { - copyParams[key] = FmtValue(value, 0) +func (vk *VK) Request(method string, sliceParams ...Params) ([]byte, error) { + token := vk.AccessToken + if vk.IsPoolClient { + token = vk.tokenPool.Get() } - if _, ok := copyParams["access_token"]; !ok { - token := vk.AccessToken - if vk.IsPoolClient { - token = vk.tokenPool.Get() - } - - copyParams["access_token"] = token + reqParams := Params{ + "access_token": token, + "v": vk.Version, } - if _, ok := copyParams["v"]; !ok { - copyParams["v"] = vk.Version - } + sliceParams = append(sliceParams, reqParams) - resp, err := vk.Handler(method, copyParams) + resp, err := vk.Handler(method, sliceParams...) return resp.Response, err } // RequestUnmarshal provides access to VK API methods. -func (vk *VK) RequestUnmarshal(method string, params Params, obj interface{}) error { - rawResponse, err := vk.Request(method, params) +func (vk *VK) RequestUnmarshal(method string, obj interface{}, sliceParams ...Params) error { + rawResponse, err := vk.Request(method, sliceParams...) if err != nil { return err } diff --git a/api/api_test.go b/api/api_test.go index 3eded63c..e31f84ec 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -106,7 +106,7 @@ var ( func TestMain(m *testing.M) { vkGroup = api.NewVK(os.Getenv("GROUP_TOKEN")) if vkGroup.AccessToken != "" { - group, err := vkGroup.GroupsGetByID(api.Params{}) + group, err := vkGroup.GroupsGetByID(nil) if err != nil { log.Fatalf("GROUP_TOKEN bad: %v", err) } @@ -121,7 +121,7 @@ func TestMain(m *testing.M) { vkUser.Limit = api.LimitUserToken if vkUser.AccessToken != "" { - user, err := vkUser.UsersGet(api.Params{}) + user, err := vkUser.UsersGet(nil) if err != nil { log.Fatalf("USER_TOKEN bad: %v", err) } @@ -144,7 +144,7 @@ func TestVK_Request(t *testing.T) { vk := api.NewVK(groupToken) t.Run("Request 403 error", func(t *testing.T) { - _, err := vk.Request("", api.Params{}) + _, err := vk.Request("", nil) if err == nil { t.Errorf("VK.Request() got1 = %v, want -1", err) } @@ -171,7 +171,7 @@ func TestVK_RequestLimit(t *testing.T) { wg.Add(1) go func() { - _, err := vkUser.UsersGet(api.Params{}) + _, err := vkUser.UsersGet(nil) assert.NoError(t, err) wg.Done() @@ -190,7 +190,7 @@ func TestVK_InvalidContentType(t *testing.T) { var testObj string - err := vkGroup.RequestUnmarshal("t/t", api.Params{}, testObj) + err := vkGroup.RequestUnmarshal("t/t", testObj, nil) if err == nil || err.Error() != "api: invalid content-type" { t.Errorf("VK.RequestUnmarshal() error = %v", err) } diff --git a/api/apps.go b/api/apps.go index b4294552..b07903fd 100644 --- a/api/apps.go +++ b/api/apps.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/apps.deleteAppRequests func (vk *VK) AppsDeleteAppRequests(params Params) (response int, err error) { - err = vk.RequestUnmarshal("apps.deleteAppRequests", params, &response) + err = vk.RequestUnmarshal("apps.deleteAppRequests", &response, params) return } @@ -23,7 +23,7 @@ type AppsGetResponse struct { // // https://vk.com/dev/apps.get func (vk *VK) AppsGet(params Params) (response AppsGetResponse, err error) { - err = vk.RequestUnmarshal("apps.get", params, &response) + err = vk.RequestUnmarshal("apps.get", &response, params) return } @@ -38,7 +38,7 @@ type AppsGetCatalogResponse struct { // // https://vk.com/dev/apps.getCatalog func (vk *VK) AppsGetCatalog(params Params) (response AppsGetCatalogResponse, err error) { - err = vk.RequestUnmarshal("apps.getCatalog", params, &response) + err = vk.RequestUnmarshal("apps.getCatalog", &response, params) return } @@ -54,8 +54,7 @@ type AppsGetFriendsListResponse struct { // // https://vk.com/dev/apps.getFriendsList func (vk *VK) AppsGetFriendsList(params Params) (response AppsGetFriendsListResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("apps.getFriendsList", params, &response) + err = vk.RequestUnmarshal("apps.getFriendsList", &response, params, Params{"extended": false}) return } @@ -72,8 +71,7 @@ type AppsGetFriendsListExtendedResponse struct { // // https://vk.com/dev/apps.getFriendsList func (vk *VK) AppsGetFriendsListExtended(params Params) (response AppsGetFriendsListExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("apps.getFriendsList", params, &response) + err = vk.RequestUnmarshal("apps.getFriendsList", &response, params, Params{"extended": true}) return } @@ -90,8 +88,7 @@ type AppsGetLeaderboardResponse struct { // // https://vk.com/dev/apps.getLeaderboard func (vk *VK) AppsGetLeaderboard(params Params) (response AppsGetLeaderboardResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("apps.getLeaderboard", params, &response) + err = vk.RequestUnmarshal("apps.getLeaderboard", &response, params, Params{"extended": false}) return } @@ -112,8 +109,7 @@ type AppsGetLeaderboardExtendedResponse struct { // // https://vk.com/dev/apps.getLeaderboard func (vk *VK) AppsGetLeaderboardExtended(params Params) (response AppsGetLeaderboardExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("apps.getLeaderboard", params, &response) + err = vk.RequestUnmarshal("apps.getLeaderboard", &response, params, Params{"extended": true}) return } @@ -130,7 +126,7 @@ type AppsGetScopesResponse struct { // // https://vk.com/dev/apps.getScopes func (vk *VK) AppsGetScopes(params Params) (response AppsGetScopesResponse, err error) { - err = vk.RequestUnmarshal("apps.getScopes", params, &response) + err = vk.RequestUnmarshal("apps.getScopes", &response, params) return } @@ -140,7 +136,7 @@ func (vk *VK) AppsGetScopes(params Params) (response AppsGetScopesResponse, err // // https://vk.com/dev/apps.getScore func (vk *VK) AppsGetScore(params Params) (response string, err error) { - err = vk.RequestUnmarshal("apps.getScore", params, &response) + err = vk.RequestUnmarshal("apps.getScore", &response, params) return } @@ -148,6 +144,6 @@ func (vk *VK) AppsGetScore(params Params) (response string, err error) { // // https://vk.com/dev/apps.sendRequest func (vk *VK) AppsSendRequest(params Params) (response int, err error) { - err = vk.RequestUnmarshal("apps.sendRequest", params, &response) + err = vk.RequestUnmarshal("apps.sendRequest", &response, params) return } diff --git a/api/apps_test.go b/api/apps_test.go index 95f8e558..cbe5ce3c 100644 --- a/api/apps_test.go +++ b/api/apps_test.go @@ -13,7 +13,7 @@ func TestVK_AppsDeleteAppRequests(t *testing.T) { needUserToken(t) - res, err := vkUser.AppsDeleteAppRequests(api.Params{}) + res, err := vkUser.AppsDeleteAppRequests(nil) noError(t, err) assert.Equal(t, res, 1) } @@ -54,7 +54,7 @@ func TestVK_AppsGetCatalog(t *testing.T) { needServiceToken(t) - res, err := vkService.AppsGetCatalog(api.Params{}) + res, err := vkService.AppsGetCatalog(nil) noError(t, err) assert.NotEmpty(t, res.Count) assert.NotEmpty(t, res.Items) @@ -65,12 +65,12 @@ func TestVK_AppsGetFriendsList(t *testing.T) { needUserToken(t) - _, err := vkUser.AppsGetFriendsList(api.Params{}) + _, err := vkUser.AppsGetFriendsList(nil) noError(t, err) // assert.NotEmpty(t, res.Count) // assert.NotEmpty(t, res.Items) - _, err = vkUser.AppsGetFriendsListExtended(api.Params{}) + _, err = vkUser.AppsGetFriendsListExtended(nil) noError(t, err) } @@ -81,7 +81,7 @@ func TestVK_AppsGetScopes(t *testing.T) { needUserToken(t) - res, err := vkUser.AppsGetScopes(api.Params{}) + res, err := vkUser.AppsGetScopes(nil) noError(t, err) assert.NotEmpty(t, res.Count) diff --git a/api/appwidgets.go b/api/appwidgets.go index aa907991..209054e9 100644 --- a/api/appwidgets.go +++ b/api/appwidgets.go @@ -17,7 +17,7 @@ func (vk *VK) AppWidgetsGetAppImageUploadServer(params Params) ( response AppWidgetsGetAppImageUploadServerResponse, err error, ) { - err = vk.RequestUnmarshal("appWidgets.getAppImageUploadServer", params, &response) + err = vk.RequestUnmarshal("appWidgets.getAppImageUploadServer", &response, params) return } @@ -31,7 +31,7 @@ type AppWidgetsGetAppImagesResponse struct { // // https://vk.com/dev/appWidgets.getAppImages func (vk *VK) AppWidgetsGetAppImages(params Params) (response AppWidgetsGetAppImagesResponse, err error) { - err = vk.RequestUnmarshal("appWidgets.getAppImages", params, &response) + err = vk.RequestUnmarshal("appWidgets.getAppImages", &response, params) return } @@ -48,7 +48,7 @@ func (vk *VK) AppWidgetsGetGroupImageUploadServer(params Params) ( response AppWidgetsGetGroupImageUploadServerResponse, err error, ) { - err = vk.RequestUnmarshal("appWidgets.getGroupImageUploadServer", params, &response) + err = vk.RequestUnmarshal("appWidgets.getGroupImageUploadServer", &response, params) return } @@ -62,7 +62,7 @@ type AppWidgetsGetGroupImagesResponse struct { // // https://vk.com/dev/appWidgets.getGroupImages func (vk *VK) AppWidgetsGetGroupImages(params Params) (response AppWidgetsGetGroupImagesResponse, err error) { - err = vk.RequestUnmarshal("appWidgets.getGroupImages", params, &response) + err = vk.RequestUnmarshal("appWidgets.getGroupImages", &response, params) return } @@ -70,7 +70,7 @@ func (vk *VK) AppWidgetsGetGroupImages(params Params) (response AppWidgetsGetGro // // https://vk.com/dev/appWidgets.getImagesById func (vk *VK) AppWidgetsGetImagesByID(params Params) (response object.AppWidgetsImage, err error) { - err = vk.RequestUnmarshal("appWidgets.getImagesById", params, &response) + err = vk.RequestUnmarshal("appWidgets.getImagesById", &response, params) return } @@ -78,7 +78,7 @@ func (vk *VK) AppWidgetsGetImagesByID(params Params) (response object.AppWidgets // // https://vk.com/dev/appWidgets.saveAppImage func (vk *VK) AppWidgetsSaveAppImage(params Params) (response object.AppWidgetsImage, err error) { - err = vk.RequestUnmarshal("appWidgets.saveAppImage", params, &response) + err = vk.RequestUnmarshal("appWidgets.saveAppImage", &response, params) return } @@ -86,7 +86,7 @@ func (vk *VK) AppWidgetsSaveAppImage(params Params) (response object.AppWidgetsI // // https://vk.com/dev/appWidgets.saveGroupImage func (vk *VK) AppWidgetsSaveGroupImage(params Params) (response object.AppWidgetsImage, err error) { - err = vk.RequestUnmarshal("appWidgets.saveGroupImage", params, &response) + err = vk.RequestUnmarshal("appWidgets.saveGroupImage", &response, params) return } @@ -94,7 +94,7 @@ func (vk *VK) AppWidgetsSaveGroupImage(params Params) (response object.AppWidget // // https://vk.com/dev/appWidgets.update func (vk *VK) AppWidgetsUpdate(params Params) (response int, err error) { - err = vk.RequestUnmarshal("appWidgets.update", params, &response) + err = vk.RequestUnmarshal("appWidgets.update", &response, params) return } diff --git a/api/auth.go b/api/auth.go index 56c61a38..4247c6b7 100644 --- a/api/auth.go +++ b/api/auth.go @@ -4,7 +4,7 @@ package api // import "github.com/SevereCloud/vksdk/api" // // https://vk.com/dev/auth.checkPhone func (vk *VK) AuthCheckPhone(params Params) (response int, err error) { - err = vk.RequestUnmarshal("auth.checkPhone", params, &response) + err = vk.RequestUnmarshal("auth.checkPhone", &response, params) return } @@ -18,6 +18,6 @@ type AuthRestoreResponse struct { // // https://vk.com/dev/auth.restore func (vk *VK) AuthRestore(params Params) (response AuthRestoreResponse, err error) { - err = vk.RequestUnmarshal("auth.restore", params, &response) + err = vk.RequestUnmarshal("auth.restore", &response, params) return } diff --git a/api/board.go b/api/board.go index 326158d6..b111ff53 100644 --- a/api/board.go +++ b/api/board.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/board.addTopic func (vk *VK) BoardAddTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.addTopic", params, &response) + err = vk.RequestUnmarshal("board.addTopic", &response, params) return } @@ -16,7 +16,7 @@ func (vk *VK) BoardAddTopic(params Params) (response int, err error) { // // https://vk.com/dev/board.closeTopic func (vk *VK) BoardCloseTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.closeTopic", params, &response) + err = vk.RequestUnmarshal("board.closeTopic", &response, params) return } @@ -24,7 +24,7 @@ func (vk *VK) BoardCloseTopic(params Params) (response int, err error) { // // https://vk.com/dev/board.createComment func (vk *VK) BoardCreateComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.createComment", params, &response) + err = vk.RequestUnmarshal("board.createComment", &response, params) return } @@ -32,7 +32,7 @@ func (vk *VK) BoardCreateComment(params Params) (response int, err error) { // // https://vk.com/dev/board.deleteComment func (vk *VK) BoardDeleteComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.deleteComment", params, &response) + err = vk.RequestUnmarshal("board.deleteComment", &response, params) return } @@ -40,7 +40,7 @@ func (vk *VK) BoardDeleteComment(params Params) (response int, err error) { // // https://vk.com/dev/board.deleteTopic func (vk *VK) BoardDeleteTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.deleteTopic", params, &response) + err = vk.RequestUnmarshal("board.deleteTopic", &response, params) return } @@ -48,7 +48,7 @@ func (vk *VK) BoardDeleteTopic(params Params) (response int, err error) { // // https://vk.com/dev/board.editComment func (vk *VK) BoardEditComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.editComment", params, &response) + err = vk.RequestUnmarshal("board.editComment", &response, params) return } @@ -56,7 +56,7 @@ func (vk *VK) BoardEditComment(params Params) (response int, err error) { // // https://vk.com/dev/board.editTopic func (vk *VK) BoardEditTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.editTopic", params, &response) + err = vk.RequestUnmarshal("board.editTopic", &response, params) return } @@ -64,7 +64,7 @@ func (vk *VK) BoardEditTopic(params Params) (response int, err error) { // // https://vk.com/dev/board.fixTopic func (vk *VK) BoardFixTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.fixTopic", params, &response) + err = vk.RequestUnmarshal("board.fixTopic", &response, params) return } @@ -82,8 +82,7 @@ type BoardGetCommentsResponse struct { // // https://vk.com/dev/board.getComments func (vk *VK) BoardGetComments(params Params) (response BoardGetCommentsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("board.getComments", params, &response) + err = vk.RequestUnmarshal("board.getComments", &response, params, Params{"extended": false}) return } @@ -104,8 +103,7 @@ type BoardGetCommentsExtendedResponse struct { // // https://vk.com/dev/board.getComments func (vk *VK) BoardGetCommentsExtended(params Params) (response BoardGetCommentsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("board.getComments", params, &response) + err = vk.RequestUnmarshal("board.getComments", &response, params, Params{"extended": true}) return } @@ -124,8 +122,7 @@ type BoardGetTopicsResponse struct { // // https://vk.com/dev/board.getTopics func (vk *VK) BoardGetTopics(params Params) (response BoardGetTopicsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("board.getTopics", params, &response) + err = vk.RequestUnmarshal("board.getTopics", &response, params, Params{"extended": false}) return } @@ -146,8 +143,7 @@ type BoardGetTopicsExtendedResponse struct { // // https://vk.com/dev/board.getTopics func (vk *VK) BoardGetTopicsExtended(params Params) (response BoardGetTopicsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("board.getTopics", params, &response) + err = vk.RequestUnmarshal("board.getTopics", &response, params, Params{"extended": true}) return } @@ -156,7 +152,7 @@ func (vk *VK) BoardGetTopicsExtended(params Params) (response BoardGetTopicsExte // // https://vk.com/dev/board.openTopic func (vk *VK) BoardOpenTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.openTopic", params, &response) + err = vk.RequestUnmarshal("board.openTopic", &response, params) return } @@ -164,7 +160,7 @@ func (vk *VK) BoardOpenTopic(params Params) (response int, err error) { // // https://vk.com/dev/board.restoreComment func (vk *VK) BoardRestoreComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.restoreComment", params, &response) + err = vk.RequestUnmarshal("board.restoreComment", &response, params) return } @@ -172,6 +168,6 @@ func (vk *VK) BoardRestoreComment(params Params) (response int, err error) { // // https://vk.com/dev/board.unfixTopic func (vk *VK) BoardUnfixTopic(params Params) (response int, err error) { - err = vk.RequestUnmarshal("board.unfixTopic", params, &response) + err = vk.RequestUnmarshal("board.unfixTopic", &response, params) return } diff --git a/api/captcha.go b/api/captcha.go index 04cffa51..4abd1f8a 100644 --- a/api/captcha.go +++ b/api/captcha.go @@ -2,6 +2,6 @@ package api // CaptchaForce api method. func (vk *VK) CaptchaForce(params Params) (response int, err error) { - err = vk.RequestUnmarshal("captcha.force", params, &response) + err = vk.RequestUnmarshal("captcha.force", &response, params) return } diff --git a/api/captcha_test.go b/api/captcha_test.go index 046f99cd..28e231de 100644 --- a/api/captcha_test.go +++ b/api/captcha_test.go @@ -12,7 +12,7 @@ func TestVK_CaptchaForce(t *testing.T) { needUserToken(t) - _, err := vkUser.CaptchaForce(api.Params{}) + _, err := vkUser.CaptchaForce(nil) if !errors.Is(err, api.ErrCaptcha) { t.Errorf("VK.CaptchaForce() err=%v, want 14", err) diff --git a/api/database.go b/api/database.go index d7455707..2124b5e2 100644 --- a/api/database.go +++ b/api/database.go @@ -14,7 +14,7 @@ type DatabaseGetChairsResponse struct { // // https://vk.com/dev/database.getChairs func (vk *VK) DatabaseGetChairs(params Params) (response DatabaseGetChairsResponse, err error) { - err = vk.RequestUnmarshal("database.getChairs", params, &response) + err = vk.RequestUnmarshal("database.getChairs", &response, params) return } @@ -28,7 +28,7 @@ type DatabaseGetCitiesResponse struct { // // https://vk.com/dev/database.getCities func (vk *VK) DatabaseGetCities(params Params) (response DatabaseGetCitiesResponse, err error) { - err = vk.RequestUnmarshal("database.getCities", params, &response) + err = vk.RequestUnmarshal("database.getCities", &response, params) return } @@ -39,7 +39,7 @@ type DatabaseGetCitiesByIDResponse []object.DatabaseCity // // https://vk.com/dev/database.getCitiesByID func (vk *VK) DatabaseGetCitiesByID(params Params) (response DatabaseGetCitiesByIDResponse, err error) { - err = vk.RequestUnmarshal("database.getCitiesById", params, &response) + err = vk.RequestUnmarshal("database.getCitiesById", &response, params) return } @@ -53,7 +53,7 @@ type DatabaseGetCountriesResponse struct { // // https://vk.com/dev/database.getCountries func (vk *VK) DatabaseGetCountries(params Params) (response DatabaseGetCountriesResponse, err error) { - err = vk.RequestUnmarshal("database.getCountries", params, &response) + err = vk.RequestUnmarshal("database.getCountries", &response, params) return } @@ -64,7 +64,7 @@ type DatabaseGetCountriesByIDResponse []object.BaseObject // // https://vk.com/dev/database.getCountriesByID func (vk *VK) DatabaseGetCountriesByID(params Params) (response DatabaseGetCountriesByIDResponse, err error) { - err = vk.RequestUnmarshal("database.getCountriesById", params, &response) + err = vk.RequestUnmarshal("database.getCountriesById", &response, params) return } @@ -78,7 +78,7 @@ type DatabaseGetFacultiesResponse struct { // // https://vk.com/dev/database.getFaculties func (vk *VK) DatabaseGetFaculties(params Params) (response DatabaseGetFacultiesResponse, err error) { - err = vk.RequestUnmarshal("database.getFaculties", params, &response) + err = vk.RequestUnmarshal("database.getFaculties", &response, params) return } @@ -92,7 +92,7 @@ type DatabaseGetMetroStationsResponse struct { // // https://vk.com/dev/database.getMetroStations func (vk *VK) DatabaseGetMetroStations(params Params) (response DatabaseGetMetroStationsResponse, err error) { - err = vk.RequestUnmarshal("database.getMetroStations", params, &response) + err = vk.RequestUnmarshal("database.getMetroStations", &response, params) return } @@ -103,7 +103,7 @@ type DatabaseGetMetroStationsByIDResponse []object.DatabaseMetroStation // // https://vk.com/dev/database.getMetroStationsById func (vk *VK) DatabaseGetMetroStationsByID(params Params) (response DatabaseGetMetroStationsByIDResponse, err error) { - err = vk.RequestUnmarshal("database.getMetroStationsById", params, &response) + err = vk.RequestUnmarshal("database.getMetroStationsById", &response, params) return } @@ -117,7 +117,7 @@ type DatabaseGetRegionsResponse struct { // // https://vk.com/dev/database.getRegions func (vk *VK) DatabaseGetRegions(params Params) (response DatabaseGetRegionsResponse, err error) { - err = vk.RequestUnmarshal("database.getRegions", params, &response) + err = vk.RequestUnmarshal("database.getRegions", &response, params) return } @@ -130,7 +130,7 @@ type DatabaseGetSchoolClassesResponse [][]interface{} // // https://vk.com/dev/database.getSchoolClasses func (vk *VK) DatabaseGetSchoolClasses(params Params) (response DatabaseGetSchoolClassesResponse, err error) { - err = vk.RequestUnmarshal("database.getSchoolClasses", params, &response) + err = vk.RequestUnmarshal("database.getSchoolClasses", &response, params) return } @@ -144,7 +144,7 @@ type DatabaseGetSchoolsResponse struct { // // https://vk.com/dev/database.getSchools func (vk *VK) DatabaseGetSchools(params Params) (response DatabaseGetSchoolsResponse, err error) { - err = vk.RequestUnmarshal("database.getSchools", params, &response) + err = vk.RequestUnmarshal("database.getSchools", &response, params) return } @@ -158,6 +158,6 @@ type DatabaseGetUniversitiesResponse struct { // // https://vk.com/dev/database.getUniversities func (vk *VK) DatabaseGetUniversities(params Params) (response DatabaseGetUniversitiesResponse, err error) { - err = vk.RequestUnmarshal("database.getUniversities", params, &response) + err = vk.RequestUnmarshal("database.getUniversities", &response, params) return } diff --git a/api/database_test.go b/api/database_test.go index b72db93d..29c26dfb 100644 --- a/api/database_test.go +++ b/api/database_test.go @@ -67,7 +67,7 @@ func TestVK_DatabaseGetCountries(t *testing.T) { needServiceToken(t) - res, err := vkService.DatabaseGetCountries(api.Params{}) + res, err := vkService.DatabaseGetCountries(nil) noError(t, err) assert.NotEmpty(t, res.Count) diff --git a/api/docs.go b/api/docs.go index a92ecb72..8708ee63 100644 --- a/api/docs.go +++ b/api/docs.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/docs.add func (vk *VK) DocsAdd(params Params) (response int, err error) { - err = vk.RequestUnmarshal("docs.add", params, &response) + err = vk.RequestUnmarshal("docs.add", &response, params) return } @@ -16,7 +16,7 @@ func (vk *VK) DocsAdd(params Params) (response int, err error) { // // https://vk.com/dev/docs.delete func (vk *VK) DocsDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("docs.delete", params, &response) + err = vk.RequestUnmarshal("docs.delete", &response, params) return } @@ -24,7 +24,7 @@ func (vk *VK) DocsDelete(params Params) (response int, err error) { // // https://vk.com/dev/docs.edit func (vk *VK) DocsEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("docs.edit", params, &response) + err = vk.RequestUnmarshal("docs.edit", &response, params) return } @@ -38,7 +38,7 @@ type DocsGetResponse struct { // // https://vk.com/dev/docs.get func (vk *VK) DocsGet(params Params) (response DocsGetResponse, err error) { - err = vk.RequestUnmarshal("docs.get", params, &response) + err = vk.RequestUnmarshal("docs.get", &response, params) return } @@ -49,7 +49,7 @@ type DocsGetByIDResponse []object.DocsDoc // // https://vk.com/dev/docs.getById func (vk *VK) DocsGetByID(params Params) (response DocsGetByIDResponse, err error) { - err = vk.RequestUnmarshal("docs.getById", params, &response) + err = vk.RequestUnmarshal("docs.getById", &response, params) return } @@ -62,7 +62,7 @@ type DocsGetMessagesUploadServerResponse struct { // // https://vk.com/dev/docs.getMessagesUploadServer func (vk *VK) DocsGetMessagesUploadServer(params Params) (response DocsGetMessagesUploadServerResponse, err error) { - err = vk.RequestUnmarshal("docs.getMessagesUploadServer", params, &response) + err = vk.RequestUnmarshal("docs.getMessagesUploadServer", &response, params) return } @@ -76,7 +76,7 @@ type DocsGetTypesResponse struct { // // https://vk.com/dev/docs.getTypes func (vk *VK) DocsGetTypes(params Params) (response DocsGetTypesResponse, err error) { - err = vk.RequestUnmarshal("docs.getTypes", params, &response) + err = vk.RequestUnmarshal("docs.getTypes", &response, params) return } @@ -89,7 +89,7 @@ type DocsGetUploadServerResponse struct { // // https://vk.com/dev/docs.getUploadServer func (vk *VK) DocsGetUploadServer(params Params) (response DocsGetUploadServerResponse, err error) { - err = vk.RequestUnmarshal("docs.getUploadServer", params, &response) + err = vk.RequestUnmarshal("docs.getUploadServer", &response, params) return } @@ -102,7 +102,7 @@ type DocsGetWallUploadServerResponse struct { // // https://vk.com/dev/docs.getWallUploadServer func (vk *VK) DocsGetWallUploadServer(params Params) (response DocsGetWallUploadServerResponse, err error) { - err = vk.RequestUnmarshal("docs.getWallUploadServer", params, &response) + err = vk.RequestUnmarshal("docs.getWallUploadServer", &response, params) return } @@ -118,7 +118,7 @@ type DocsSaveResponse struct { // // https://vk.com/dev/docs.save func (vk *VK) DocsSave(params Params) (response DocsSaveResponse, err error) { - err = vk.RequestUnmarshal("docs.save", params, &response) + err = vk.RequestUnmarshal("docs.save", &response, params) return } @@ -132,6 +132,6 @@ type DocsSearchResponse struct { // // https://vk.com/dev/docs.search func (vk *VK) DocsSearch(params Params) (response DocsSearchResponse, err error) { - err = vk.RequestUnmarshal("docs.search", params, &response) + err = vk.RequestUnmarshal("docs.search", &response, params) return } diff --git a/api/docs_test.go b/api/docs_test.go index 6cba1563..98d985c8 100644 --- a/api/docs_test.go +++ b/api/docs_test.go @@ -101,7 +101,7 @@ func TestVK_DocsGetTypes(t *testing.T) { needUserToken(t) - res, err := vkUser.DocsGetTypes(api.Params{}) + res, err := vkUser.DocsGetTypes(nil) noError(t, err) assert.NotEmpty(t, res.Count) @@ -117,7 +117,7 @@ func TestVK_DocsGetUploadServer(t *testing.T) { needUserToken(t) - res, err := vkUser.DocsGetUploadServer(api.Params{}) + res, err := vkUser.DocsGetUploadServer(nil) noError(t, err) assert.NotEmpty(t, res.UploadURL) } @@ -127,7 +127,7 @@ func TestVK_DocsGetMessagesUploadServer(t *testing.T) { needUserToken(t) - res, err := vkUser.DocsGetMessagesUploadServer(api.Params{}) + res, err := vkUser.DocsGetMessagesUploadServer(nil) noError(t, err) assert.NotEmpty(t, res.UploadURL) } @@ -137,7 +137,7 @@ func TestVK_DocsGetWallUploadServer(t *testing.T) { needUserToken(t) - res, err := vkUser.DocsGetWallUploadServer(api.Params{}) + res, err := vkUser.DocsGetWallUploadServer(nil) noError(t, err) assert.NotEmpty(t, res.UploadURL) } diff --git a/api/downloadedGames.go b/api/downloadedGames.go index afc541b2..65b1d11b 100644 --- a/api/downloadedGames.go +++ b/api/downloadedGames.go @@ -13,8 +13,7 @@ type DownloadedGamesGetPaidStatusResponse struct { // // https://vk.com/dev/downloadedGames.getPaidStatus func (vk *VK) DownloadedGamesGetPaidStatus(params Params) (response DownloadedGamesGetPaidStatusResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("downloadedGames.getPaidStatus", params, &response) + err = vk.RequestUnmarshal("downloadedGames.getPaidStatus", &response, params, Params{"extended": false}) return } diff --git a/api/execute.go b/api/execute.go index 6d6b8dca..b55e9cc8 100644 --- a/api/execute.go +++ b/api/execute.go @@ -18,16 +18,13 @@ func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error token = vk.tokenPool.Get() } - copyParams := make(Params) - for key, value := range params { - copyParams[key] = FmtValue(value, 0) + reqParams := Params{ + "code": code, + "access_token": token, + "v": vk.Version, } - copyParams["code"] = code - copyParams["access_token"] = token - copyParams["v"] = vk.Version - - resp, err := vk.Handler("execute", copyParams) + resp, err := vk.Handler("execute", params, reqParams) jsonErr := json.Unmarshal(resp.Response, &obj) if jsonErr != nil { diff --git a/api/fave.go b/api/fave.go index a6cafb1d..439188dd 100644 --- a/api/fave.go +++ b/api/fave.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/fave.addArticle func (vk *VK) FaveAddArticle(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.addArticle", params, &response) + err = vk.RequestUnmarshal("fave.addArticle", &response, params) return } @@ -16,7 +16,7 @@ func (vk *VK) FaveAddArticle(params Params) (response int, err error) { // // https://vk.com/dev/fave.addLink func (vk *VK) FaveAddLink(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.addLink", params, &response) + err = vk.RequestUnmarshal("fave.addLink", &response, params) return } @@ -24,7 +24,7 @@ func (vk *VK) FaveAddLink(params Params) (response int, err error) { // // https://vk.com/dev/fave.addPage func (vk *VK) FaveAddPage(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.addPage", params, &response) + err = vk.RequestUnmarshal("fave.addPage", &response, params) return } @@ -32,7 +32,7 @@ func (vk *VK) FaveAddPage(params Params) (response int, err error) { // // https://vk.com/dev/fave.addPost func (vk *VK) FaveAddPost(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.addPost", params, &response) + err = vk.RequestUnmarshal("fave.addPost", &response, params) return } @@ -40,7 +40,7 @@ func (vk *VK) FaveAddPost(params Params) (response int, err error) { // // https://vk.com/dev/fave.addProduct func (vk *VK) FaveAddProduct(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.addProduct", params, &response) + err = vk.RequestUnmarshal("fave.addProduct", &response, params) return } @@ -51,7 +51,7 @@ type FaveAddTagResponse object.FaveTag // // https://vk.com/dev/fave.addTag func (vk *VK) FaveAddTag(params Params) (response FaveAddTagResponse, err error) { - err = vk.RequestUnmarshal("fave.addTag", params, &response) + err = vk.RequestUnmarshal("fave.addTag", &response, params) return } @@ -59,7 +59,7 @@ func (vk *VK) FaveAddTag(params Params) (response FaveAddTagResponse, err error) // // https://vk.com/dev/fave.addVideo func (vk *VK) FaveAddVideo(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.addVideo", params, &response) + err = vk.RequestUnmarshal("fave.addVideo", &response, params) return } @@ -67,7 +67,7 @@ func (vk *VK) FaveAddVideo(params Params) (response int, err error) { // // https://vk.com/dev/fave.editTag func (vk *VK) FaveEditTag(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.editTag", params, &response) + err = vk.RequestUnmarshal("fave.editTag", &response, params) return } @@ -83,8 +83,7 @@ type FaveGetResponse struct { // // https://vk.com/dev/fave.get func (vk *VK) FaveGet(params Params) (response FaveGetResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("fave.get", params, &response) + err = vk.RequestUnmarshal("fave.get", &response, params, Params{"extended": false}) return } @@ -102,8 +101,7 @@ type FaveGetExtendedResponse struct { // // https://vk.com/dev/fave.get func (vk *VK) FaveGetExtended(params Params) (response FaveGetExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("fave.get", params, &response) + err = vk.RequestUnmarshal("fave.get", &response, params, Params{"extended": true}) return } @@ -118,7 +116,7 @@ type FaveGetPagesResponse struct { // // https://vk.com/dev/fave.getPages func (vk *VK) FaveGetPages(params Params) (response FaveGetPagesResponse, err error) { - err = vk.RequestUnmarshal("fave.getPages", params, &response) + err = vk.RequestUnmarshal("fave.getPages", &response, params) return } @@ -132,7 +130,7 @@ type FaveGetTagsResponse struct { // // https://vk.com/dev/fave.getTags func (vk *VK) FaveGetTags(params Params) (response FaveGetTagsResponse, err error) { - err = vk.RequestUnmarshal("fave.getTags", params, &response) + err = vk.RequestUnmarshal("fave.getTags", &response, params) return } @@ -140,7 +138,7 @@ func (vk *VK) FaveGetTags(params Params) (response FaveGetTagsResponse, err erro // // https://vk.com/dev/fave.markSeen func (vk *VK) FaveMarkSeen(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.markSeen", params, &response) + err = vk.RequestUnmarshal("fave.markSeen", &response, params) return } @@ -148,7 +146,7 @@ func (vk *VK) FaveMarkSeen(params Params) (response int, err error) { // // https://vk.com/dev/fave.removeArticle func (vk *VK) FaveRemoveArticle(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removeArticle", params, &response) + err = vk.RequestUnmarshal("fave.removeArticle", &response, params) return } @@ -156,7 +154,7 @@ func (vk *VK) FaveRemoveArticle(params Params) (response int, err error) { // // https://vk.com/dev/fave.removeLink func (vk *VK) FaveRemoveLink(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removeLink", params, &response) + err = vk.RequestUnmarshal("fave.removeLink", &response, params) return } @@ -164,7 +162,7 @@ func (vk *VK) FaveRemoveLink(params Params) (response int, err error) { // // https://vk.com/dev/fave.removePage func (vk *VK) FaveRemovePage(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removePage", params, &response) + err = vk.RequestUnmarshal("fave.removePage", &response, params) return } @@ -172,7 +170,7 @@ func (vk *VK) FaveRemovePage(params Params) (response int, err error) { // // https://vk.com/dev/fave.removePost func (vk *VK) FaveRemovePost(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removePost", params, &response) + err = vk.RequestUnmarshal("fave.removePost", &response, params) return } @@ -180,7 +178,7 @@ func (vk *VK) FaveRemovePost(params Params) (response int, err error) { // // https://vk.com/dev/fave.removeProduct func (vk *VK) FaveRemoveProduct(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removeProduct", params, &response) + err = vk.RequestUnmarshal("fave.removeProduct", &response, params) return } @@ -188,7 +186,7 @@ func (vk *VK) FaveRemoveProduct(params Params) (response int, err error) { // // https://vk.com/dev/fave.removeTag func (vk *VK) FaveRemoveTag(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removeTag", params, &response) + err = vk.RequestUnmarshal("fave.removeTag", &response, params) return } @@ -196,7 +194,7 @@ func (vk *VK) FaveRemoveTag(params Params) (response int, err error) { // // https://vk.com/dev/fave.removeVideo func (vk *VK) FaveRemoveVideo(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.removeVideo", params, &response) + err = vk.RequestUnmarshal("fave.removeVideo", &response, params) return } @@ -204,7 +202,7 @@ func (vk *VK) FaveRemoveVideo(params Params) (response int, err error) { // // https://vk.com/dev/fave.reorderTags func (vk *VK) FaveReorderTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.reorderTags", params, &response) + err = vk.RequestUnmarshal("fave.reorderTags", &response, params) return } @@ -212,7 +210,7 @@ func (vk *VK) FaveReorderTags(params Params) (response int, err error) { // // https://vk.com/dev/fave.setPageTags func (vk *VK) FaveSetPageTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.setPageTags", params, &response) + err = vk.RequestUnmarshal("fave.setPageTags", &response, params) return } @@ -220,7 +218,7 @@ func (vk *VK) FaveSetPageTags(params Params) (response int, err error) { // // https://vk.com/dev/fave.setTags func (vk *VK) FaveSetTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.setTags", params, &response) + err = vk.RequestUnmarshal("fave.setTags", &response, params) return } @@ -228,6 +226,6 @@ func (vk *VK) FaveSetTags(params Params) (response int, err error) { // // https://vk.com/dev/fave.trackPageInteraction func (vk *VK) FaveTrackPageInteraction(params Params) (response int, err error) { - err = vk.RequestUnmarshal("fave.trackPageInteraction", params, &response) + err = vk.RequestUnmarshal("fave.trackPageInteraction", &response, params) return } diff --git a/api/fave_test.go b/api/fave_test.go index 92e5751a..8c2cd5f3 100644 --- a/api/fave_test.go +++ b/api/fave_test.go @@ -137,7 +137,7 @@ func TestVK_Fave(t *testing.T) { needUserToken(t) - fave, err := vkUser.FaveGet(api.Params{}) + fave, err := vkUser.FaveGet(nil) if !noError(t, err) { log.Fatal(err) } @@ -368,7 +368,7 @@ func TestVK_FaveTag(t *testing.T) { noError(t, err) assert.NotEmpty(t, res) - tags, err := vkUser.FaveGetTags(api.Params{}) + tags, err := vkUser.FaveGetTags(nil) noError(t, err) assert.NotEmpty(t, tags) @@ -430,13 +430,13 @@ func TestVK_FaveGet(t *testing.T) { time.Sleep(sleepTime) - res, err := vkUser.FaveGet(api.Params{}) + res, err := vkUser.FaveGet(nil) noError(t, err) assert.NotEmpty(t, res) time.Sleep(sleepTime) - _, err = vkUser.FaveGetExtended(api.Params{}) + _, err = vkUser.FaveGetExtended(nil) noError(t, err) assert.NotEmpty(t, res) } @@ -448,7 +448,7 @@ func TestVK_FaveGetPages(t *testing.T) { time.Sleep(sleepTime) - res, err := vkUser.FaveGetPages(api.Params{}) + res, err := vkUser.FaveGetPages(nil) noError(t, err) assert.NotEmpty(t, res.Count) @@ -489,7 +489,7 @@ func TestVK_FaveMarkSeen(t *testing.T) { time.Sleep(sleepTime) - res, err := vkUser.FaveMarkSeen(api.Params{}) + res, err := vkUser.FaveMarkSeen(nil) noError(t, err) assert.NotEmpty(t, res) } diff --git a/api/friends.go b/api/friends.go index 8c562048..881e3816 100644 --- a/api/friends.go +++ b/api/friends.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/friends.add func (vk *VK) FriendsAdd(params Params) (response int, err error) { - err = vk.RequestUnmarshal("friends.add", params, &response) + err = vk.RequestUnmarshal("friends.add", &response, params) return } @@ -21,7 +21,7 @@ type FriendsAddListResponse struct { // // https://vk.com/dev/friends.addList func (vk *VK) FriendsAddList(params Params) (response FriendsAddListResponse, err error) { - err = vk.RequestUnmarshal("friends.addList", params, &response) + err = vk.RequestUnmarshal("friends.addList", &response, params) return } @@ -32,7 +32,7 @@ type FriendsAreFriendsResponse []object.FriendsFriendStatus // // https://vk.com/dev/friends.areFriends func (vk *VK) FriendsAreFriends(params Params) (response FriendsAreFriendsResponse, err error) { - err = vk.RequestUnmarshal("friends.areFriends", params, &response) + err = vk.RequestUnmarshal("friends.areFriends", &response, params) return } @@ -49,7 +49,7 @@ type FriendsDeleteResponse struct { // // https://vk.com/dev/friends.delete func (vk *VK) FriendsDelete(params Params) (response FriendsDeleteResponse, err error) { - err = vk.RequestUnmarshal("friends.delete", params, &response) + err = vk.RequestUnmarshal("friends.delete", &response, params) return } @@ -57,7 +57,7 @@ func (vk *VK) FriendsDelete(params Params) (response FriendsDeleteResponse, err // // https://vk.com/dev/friends.deleteAllRequests func (vk *VK) FriendsDeleteAllRequests(params Params) (response int, err error) { - err = vk.RequestUnmarshal("friends.deleteAllRequests", params, &response) + err = vk.RequestUnmarshal("friends.deleteAllRequests", &response, params) return } @@ -65,7 +65,7 @@ func (vk *VK) FriendsDeleteAllRequests(params Params) (response int, err error) // // https://vk.com/dev/friends.deleteList func (vk *VK) FriendsDeleteList(params Params) (response int, err error) { - err = vk.RequestUnmarshal("friends.deleteList", params, &response) + err = vk.RequestUnmarshal("friends.deleteList", &response, params) return } @@ -73,7 +73,7 @@ func (vk *VK) FriendsDeleteList(params Params) (response int, err error) { // // https://vk.com/dev/friends.edit func (vk *VK) FriendsEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("friends.edit", params, &response) + err = vk.RequestUnmarshal("friends.edit", &response, params) return } @@ -81,7 +81,7 @@ func (vk *VK) FriendsEdit(params Params) (response int, err error) { // // https://vk.com/dev/friends.editList func (vk *VK) FriendsEditList(params Params) (response int, err error) { - err = vk.RequestUnmarshal("friends.editList", params, &response) + err = vk.RequestUnmarshal("friends.editList", &response, params) return } @@ -95,7 +95,7 @@ type FriendsGetResponse struct { // // https://vk.com/dev/friends.get func (vk *VK) FriendsGet(params Params) (response FriendsGetResponse, err error) { - err = vk.RequestUnmarshal("friends.get", params, &response) + err = vk.RequestUnmarshal("friends.get", &response, params) return } @@ -109,11 +109,12 @@ type FriendsGetFieldsResponse struct { // // https://vk.com/dev/friends.get func (vk *VK) FriendsGetFields(params Params) (response FriendsGetFieldsResponse, err error) { + reqParams := make(Params) if v, prs := params["fields"]; v == "" || !prs { - params["fields"] = "id" + reqParams["fields"] = "id" } - err = vk.RequestUnmarshal("friends.get", params, &response) + err = vk.RequestUnmarshal("friends.get", &response, params, reqParams) return } @@ -125,7 +126,7 @@ type FriendsGetAppUsersResponse []int // // https://vk.com/dev/friends.getAppUsers func (vk *VK) FriendsGetAppUsers(params Params) (response FriendsGetAppUsersResponse, err error) { - err = vk.RequestUnmarshal("friends.getAppUsers", params, &response) + err = vk.RequestUnmarshal("friends.getAppUsers", &response, params) return } @@ -137,7 +138,7 @@ type FriendsGetByPhonesResponse []object.FriendsUserXtrPhone // // https://vk.com/dev/friends.getByPhones func (vk *VK) FriendsGetByPhones(params Params) (response FriendsGetByPhonesResponse, err error) { - err = vk.RequestUnmarshal("friends.getByPhones", params, &response) + err = vk.RequestUnmarshal("friends.getByPhones", &response, params) return } @@ -151,7 +152,7 @@ type FriendsGetListsResponse struct { // // https://vk.com/dev/friends.getLists func (vk *VK) FriendsGetLists(params Params) (response FriendsGetListsResponse, err error) { - err = vk.RequestUnmarshal("friends.getLists", params, &response) + err = vk.RequestUnmarshal("friends.getLists", &response, params) return } @@ -162,7 +163,7 @@ type FriendsGetMutualResponse []int // // https://vk.com/dev/friends.getMutual func (vk *VK) FriendsGetMutual(params Params) (response FriendsGetMutualResponse, err error) { - err = vk.RequestUnmarshal("friends.getMutual", params, &response) + err = vk.RequestUnmarshal("friends.getMutual", &response, params) return } @@ -172,8 +173,7 @@ func (vk *VK) FriendsGetMutual(params Params) (response FriendsGetMutualResponse // // https://vk.com/dev/friends.getOnline func (vk *VK) FriendsGetOnline(params Params) (response []int, err error) { - params["online_mobile"] = false - err = vk.RequestUnmarshal("friends.getOnline", params, &response) + err = vk.RequestUnmarshal("friends.getOnline", &response, params, Params{"online_mobile": false}) return } @@ -190,8 +190,7 @@ type FriendsGetOnlineOnlineMobileResponse struct { // // https://vk.com/dev/friends.getOnline func (vk *VK) FriendsGetOnlineOnlineMobile(params Params) (response FriendsGetOnlineOnlineMobileResponse, err error) { - params["online_mobile"] = true - err = vk.RequestUnmarshal("friends.getOnline", params, &response) + err = vk.RequestUnmarshal("friends.getOnline", &response, params, Params{"online_mobile": true}) return } @@ -203,7 +202,7 @@ type FriendsGetRecentResponse []int // // https://vk.com/dev/friends.getRecent func (vk *VK) FriendsGetRecent(params Params) (response FriendsGetRecentResponse, err error) { - err = vk.RequestUnmarshal("friends.getRecent", params, &response) + err = vk.RequestUnmarshal("friends.getRecent", &response, params) return } @@ -217,9 +216,12 @@ type FriendsGetRequestsResponse struct { // // https://vk.com/dev/friends.getRequests func (vk *VK) FriendsGetRequests(params Params) (response FriendsGetRequestsResponse, err error) { - params["need_mutual"] = false - params["extended"] = false - err = vk.RequestUnmarshal("friends.getRequests", params, &response) + reqParams := Params{ + "need_mutual": false, + "extended": false, + } + + err = vk.RequestUnmarshal("friends.getRequests", &response, params, reqParams) return } @@ -234,9 +236,12 @@ type FriendsGetRequestsNeedMutualResponse struct { // // https://vk.com/dev/friends.getRequests func (vk *VK) FriendsGetRequestsNeedMutual(params Params) (response FriendsGetRequestsNeedMutualResponse, err error) { - params["need_mutual"] = true - params["extended"] = false - err = vk.RequestUnmarshal("friends.getRequests", params, &response) + reqParams := Params{ + "extended": false, + "need_mutual": true, + } + + err = vk.RequestUnmarshal("friends.getRequests", &response, params, reqParams) return } @@ -251,9 +256,12 @@ type FriendsGetRequestsExtendedResponse struct { // // https://vk.com/dev/friends.getRequests func (vk *VK) FriendsGetRequestsExtended(params Params) (response FriendsGetRequestsExtendedResponse, err error) { - params["need_mutual"] = false - params["extended"] = true - err = vk.RequestUnmarshal("friends.getRequests", params, &response) + reqParams := Params{ + "need_mutual": false, + "extended": true, + } + + err = vk.RequestUnmarshal("friends.getRequests", &response, params, reqParams) return } @@ -268,7 +276,7 @@ type FriendsGetSuggestionsResponse struct { // // https://vk.com/dev/friends.getSuggestions func (vk *VK) FriendsGetSuggestions(params Params) (response FriendsGetSuggestionsResponse, err error) { - err = vk.RequestUnmarshal("friends.getSuggestions", params, &response) + err = vk.RequestUnmarshal("friends.getSuggestions", &response, params) return } @@ -282,6 +290,6 @@ type FriendsSearchResponse struct { // // https://vk.com/dev/friends.search func (vk *VK) FriendsSearch(params Params) (response FriendsSearchResponse, err error) { - err = vk.RequestUnmarshal("friends.search", params, &response) + err = vk.RequestUnmarshal("friends.search", &response, params) return } diff --git a/api/friends_test.go b/api/friends_test.go index b172ef7e..c03295c9 100644 --- a/api/friends_test.go +++ b/api/friends_test.go @@ -44,7 +44,7 @@ func TestVK_FriendsList(t *testing.T) { noError(t, err) assert.NotEmpty(t, res) - lists, err := vkUser.FriendsGetLists(api.Params{}) + lists, err := vkUser.FriendsGetLists(nil) noError(t, err) assert.NotEmpty(t, lists.Count) assert.NotEmpty(t, lists.Items) @@ -74,7 +74,7 @@ func TestVK_FriendsDeleteAllRequests(t *testing.T) { needUserToken(t) - res, err := vkUser.FriendsDeleteAllRequests(api.Params{}) + res, err := vkUser.FriendsDeleteAllRequests(nil) noError(t, err) assert.NotEmpty(t, res) } @@ -86,7 +86,7 @@ func TestVK_FriendsEdit(t *testing.T) { // NOTE: https://vk.com/bug191897 needUserToken(t) - _, _ = vkUser.FriendsEdit(api.Params{}) + _, _ = vkUser.FriendsEdit(nil) } func TestVK_FriendsGet(t *testing.T) { @@ -115,7 +115,7 @@ func TestVK_FriendsGetAppUsers(t *testing.T) { needUserToken(t) - _, err := vkUser.FriendsGetAppUsers(api.Params{}) + _, err := vkUser.FriendsGetAppUsers(nil) noError(t, err) } @@ -148,10 +148,10 @@ func TestVK_FriendsGetOnline(t *testing.T) { needUserToken(t) - _, err := vkUser.FriendsGetOnline(api.Params{}) + _, err := vkUser.FriendsGetOnline(nil) noError(t, err) - _, err = vkUser.FriendsGetOnlineOnlineMobile(api.Params{}) + _, err = vkUser.FriendsGetOnlineOnlineMobile(nil) noError(t, err) } @@ -160,7 +160,7 @@ func TestVK_FriendsGetRecent(t *testing.T) { needUserToken(t) - _, err := vkUser.FriendsGetRecent(api.Params{}) + _, err := vkUser.FriendsGetRecent(nil) noError(t, err) } @@ -196,7 +196,7 @@ func TestVK_FriendsGetSuggestions(t *testing.T) { needUserToken(t) - res, err := vkUser.FriendsGetSuggestions(api.Params{}) + res, err := vkUser.FriendsGetSuggestions(nil) noError(t, err) assert.NotEmpty(t, res.Count) assert.NotEmpty(t, res.Items) diff --git a/api/gifts.go b/api/gifts.go index 61948f04..315c38d8 100644 --- a/api/gifts.go +++ b/api/gifts.go @@ -12,7 +12,7 @@ type GiftsGetResponse struct { // // https://vk.com/dev/gifts.get func (vk *VK) GiftsGet(params Params) (response GiftsGetResponse, err error) { - err = vk.RequestUnmarshal("gifts.get", params, &response) + err = vk.RequestUnmarshal("gifts.get", &response, params) return } @@ -27,6 +27,6 @@ type GiftsGetCatalogResponse []struct { // // https://vk.com/dev/gifts.get func (vk *VK) GiftsGetCatalog(params Params) (response GiftsGetCatalogResponse, err error) { - err = vk.RequestUnmarshal("gifts.getCatalog", params, &response) + err = vk.RequestUnmarshal("gifts.getCatalog", &response, params) return } diff --git a/api/gifts_test.go b/api/gifts_test.go index 4f252a49..575c641a 100644 --- a/api/gifts_test.go +++ b/api/gifts_test.go @@ -45,7 +45,7 @@ func TestVK_GiftsGetCatalog(t *testing.T) { needUserToken(t) // NOTE: Access denied: method allowed only for official app - _, err := vkUser.GiftsGetCatalog(api.Params{}) + _, err := vkUser.GiftsGetCatalog(nil) if e, ok := err.(*api.Error); ok && e.Code == api.ErrAccess { t.Errorf("VK.GiftsGetCatalog() err = %v", err) } diff --git a/api/groups.go b/api/groups.go index 62fcf108..3b0a82e5 100644 --- a/api/groups.go +++ b/api/groups.go @@ -11,7 +11,7 @@ type GroupsAddAddressResponse object.GroupsAddress // // https://vk.com/dev/groups.addAddress func (vk *VK) GroupsAddAddress(params Params) (response GroupsAddAddressResponse, err error) { - err = vk.RequestUnmarshal("groups.addAddress", params, &response) + err = vk.RequestUnmarshal("groups.addAddress", &response, params) return } @@ -24,7 +24,7 @@ type GroupsAddCallbackServerResponse struct { // // https://vk.com/dev/groups.addCallbackServer func (vk *VK) GroupsAddCallbackServer(params Params) (response GroupsAddCallbackServerResponse, err error) { - err = vk.RequestUnmarshal("groups.addCallbackServer", params, &response) + err = vk.RequestUnmarshal("groups.addCallbackServer", &response, params) return } @@ -35,7 +35,7 @@ type GroupsAddLinkResponse object.GroupsGroupLink // // https://vk.com/dev/groups.addLink func (vk *VK) GroupsAddLink(params Params) (response GroupsAddLinkResponse, err error) { - err = vk.RequestUnmarshal("groups.addLink", params, &response) + err = vk.RequestUnmarshal("groups.addLink", &response, params) return } @@ -43,7 +43,7 @@ func (vk *VK) GroupsAddLink(params Params) (response GroupsAddLinkResponse, err // // https://vk.com/dev/groups.approveRequest func (vk *VK) GroupsApproveRequest(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.approveRequest", params, &response) + err = vk.RequestUnmarshal("groups.approveRequest", &response, params) return } @@ -51,7 +51,7 @@ func (vk *VK) GroupsApproveRequest(params Params) (response int, err error) { // // https://vk.com/dev/groups.ban func (vk *VK) GroupsBan(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.ban", params, &response) + err = vk.RequestUnmarshal("groups.ban", &response, params) return } @@ -62,7 +62,7 @@ type GroupsCreateResponse object.GroupsGroup // // https://vk.com/dev/groups.create func (vk *VK) GroupsCreate(params Params) (response GroupsCreateResponse, err error) { - err = vk.RequestUnmarshal("groups.create", params, &response) + err = vk.RequestUnmarshal("groups.create", &response, params) return } @@ -70,7 +70,7 @@ func (vk *VK) GroupsCreate(params Params) (response GroupsCreateResponse, err er // // https://vk.com/dev/groups.deleteAddress func (vk *VK) GroupsDeleteAddress(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.deleteAddress", params, &response) + err = vk.RequestUnmarshal("groups.deleteAddress", &response, params) return } @@ -78,7 +78,7 @@ func (vk *VK) GroupsDeleteAddress(params Params) (response int, err error) { // // https://vk.com/dev/groups.deleteCallbackServer func (vk *VK) GroupsDeleteCallbackServer(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.deleteCallbackServer", params, &response) + err = vk.RequestUnmarshal("groups.deleteCallbackServer", &response, params) return } @@ -86,7 +86,7 @@ func (vk *VK) GroupsDeleteCallbackServer(params Params) (response int, err error // // https://vk.com/dev/groups.deleteLink func (vk *VK) GroupsDeleteLink(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.deleteLink", params, &response) + err = vk.RequestUnmarshal("groups.deleteLink", &response, params) return } @@ -94,7 +94,7 @@ func (vk *VK) GroupsDeleteLink(params Params) (response int, err error) { // // https://vk.com/dev/groups.disableOnline func (vk *VK) GroupsDisableOnline(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.disableOnline", params, &response) + err = vk.RequestUnmarshal("groups.disableOnline", &response, params) return } @@ -102,7 +102,7 @@ func (vk *VK) GroupsDisableOnline(params Params) (response int, err error) { // // https://vk.com/dev/groups.edit func (vk *VK) GroupsEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.edit", params, &response) + err = vk.RequestUnmarshal("groups.edit", &response, params) return } @@ -113,7 +113,7 @@ type GroupsEditAddressResponse object.GroupsAddress // // https://vk.com/dev/groups.editAddress func (vk *VK) GroupsEditAddress(params Params) (response GroupsEditAddressResponse, err error) { - err = vk.RequestUnmarshal("groups.editAddress", params, &response) + err = vk.RequestUnmarshal("groups.editAddress", &response, params) return } @@ -121,7 +121,7 @@ func (vk *VK) GroupsEditAddress(params Params) (response GroupsEditAddressRespon // // https://vk.com/dev/groups.editCallbackServer func (vk *VK) GroupsEditCallbackServer(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.editCallbackServer", params, &response) + err = vk.RequestUnmarshal("groups.editCallbackServer", &response, params) return } @@ -129,7 +129,7 @@ func (vk *VK) GroupsEditCallbackServer(params Params) (response int, err error) // // https://vk.com/dev/groups.editLink func (vk *VK) GroupsEditLink(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.editLink", params, &response) + err = vk.RequestUnmarshal("groups.editLink", &response, params) return } @@ -137,7 +137,7 @@ func (vk *VK) GroupsEditLink(params Params) (response int, err error) { // // https://vk.com/dev/groups.editManager func (vk *VK) GroupsEditManager(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.editManager", params, &response) + err = vk.RequestUnmarshal("groups.editManager", &response, params) return } @@ -145,7 +145,7 @@ func (vk *VK) GroupsEditManager(params Params) (response int, err error) { // // https://vk.com/dev/groups.enableOnline func (vk *VK) GroupsEnableOnline(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.enableOnline", params, &response) + err = vk.RequestUnmarshal("groups.enableOnline", &response, params) return } @@ -161,8 +161,7 @@ type GroupsGetResponse struct { // // https://vk.com/dev/groups.get func (vk *VK) GroupsGet(params Params) (response GroupsGetResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("groups.get", params, &response) + err = vk.RequestUnmarshal("groups.get", &response, params, Params{"extended": false}) return } @@ -179,8 +178,7 @@ type GroupsGetExtendedResponse struct { // // https://vk.com/dev/groups.get func (vk *VK) GroupsGetExtended(params Params) (response GroupsGetExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("groups.get", params, &response) + err = vk.RequestUnmarshal("groups.get", &response, params, Params{"extended": true}) return } @@ -195,7 +193,7 @@ type GroupsGetAddressesResponse struct { // // https://vk.com/dev/groups.getAddresses func (vk *VK) GroupsGetAddresses(params Params) (response GroupsGetAddressesResponse, err error) { - err = vk.RequestUnmarshal("groups.getAddresses", params, &response) + err = vk.RequestUnmarshal("groups.getAddresses", &response, params) return } @@ -209,7 +207,7 @@ type GroupsGetBannedResponse struct { // // https://vk.com/dev/groups.getBanned func (vk *VK) GroupsGetBanned(params Params) (response GroupsGetBannedResponse, err error) { - err = vk.RequestUnmarshal("groups.getBanned", params, &response) + err = vk.RequestUnmarshal("groups.getBanned", &response, params) return } @@ -220,7 +218,7 @@ type GroupsGetByIDResponse []object.GroupsGroup // // https://vk.com/dev/groups.getById func (vk *VK) GroupsGetByID(params Params) (response GroupsGetByIDResponse, err error) { - err = vk.RequestUnmarshal("groups.getById", params, &response) + err = vk.RequestUnmarshal("groups.getById", &response, params) return } @@ -236,7 +234,7 @@ func (vk *VK) GroupsGetCallbackConfirmationCode(params Params) ( response GroupsGetCallbackConfirmationCodeResponse, err error, ) { - err = vk.RequestUnmarshal("groups.getCallbackConfirmationCode", params, &response) + err = vk.RequestUnmarshal("groups.getCallbackConfirmationCode", &response, params) return } @@ -250,7 +248,7 @@ type GroupsGetCallbackServersResponse struct { // // https://vk.com/dev/groups.getCallbackServers func (vk *VK) GroupsGetCallbackServers(params Params) (response GroupsGetCallbackServersResponse, err error) { - err = vk.RequestUnmarshal("groups.getCallbackServers", params, &response) + err = vk.RequestUnmarshal("groups.getCallbackServers", &response, params) return } @@ -263,7 +261,7 @@ type GroupsGetCallbackSettingsResponse object.GroupsCallbackSettings // // https://vk.com/dev/groups.getCallbackSettings func (vk *VK) GroupsGetCallbackSettings(params Params) (response GroupsGetCallbackSettingsResponse, err error) { - err = vk.RequestUnmarshal("groups.getCallbackSettings", params, &response) + err = vk.RequestUnmarshal("groups.getCallbackSettings", &response, params) return } @@ -277,7 +275,7 @@ type GroupsGetCatalogResponse struct { // // https://vk.com/dev/groups.getCatalog func (vk *VK) GroupsGetCatalog(params Params) (response GroupsGetCatalogResponse, err error) { - err = vk.RequestUnmarshal("groups.getCatalog", params, &response) + err = vk.RequestUnmarshal("groups.getCatalog", &response, params) return } @@ -293,8 +291,7 @@ type GroupsGetCatalogInfoResponse struct { // // https://vk.com/dev/groups.getCatalogInfo func (vk *VK) GroupsGetCatalogInfo(params Params) (response GroupsGetCatalogInfoResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("groups.getCatalogInfo", params, &response) + err = vk.RequestUnmarshal("groups.getCatalogInfo", &response, params, Params{"extended": false}) return } @@ -311,8 +308,7 @@ type GroupsGetCatalogInfoExtendedResponse struct { // // https://vk.com/dev/groups.getCatalogInfo func (vk *VK) GroupsGetCatalogInfoExtended(params Params) (response GroupsGetCatalogInfoExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("groups.getCatalogInfo", params, &response) + err = vk.RequestUnmarshal("groups.getCatalogInfo", &response, params, Params{"extended": true}) return } @@ -327,7 +323,7 @@ type GroupsGetInvitedUsersResponse struct { // // https://vk.com/dev/groups.getInvitedUsers func (vk *VK) GroupsGetInvitedUsers(params Params) (response GroupsGetInvitedUsersResponse, err error) { - err = vk.RequestUnmarshal("groups.getInvitedUsers", params, &response) + err = vk.RequestUnmarshal("groups.getInvitedUsers", &response, params) return } @@ -341,7 +337,7 @@ type GroupsGetInvitesResponse struct { // // https://vk.com/dev/groups.getInvites func (vk *VK) GroupsGetInvites(params Params) (response GroupsGetInvitesResponse, err error) { - err = vk.RequestUnmarshal("groups.getInvites", params, &response) + err = vk.RequestUnmarshal("groups.getInvites", &response, params) return } @@ -356,7 +352,7 @@ type GroupsGetInvitesExtendedResponse struct { // // https://vk.com/dev/groups.getInvites func (vk *VK) GroupsGetInvitesExtended(params Params) (response GroupsGetInvitesExtendedResponse, err error) { - err = vk.RequestUnmarshal("groups.getInvites", params, &response) + err = vk.RequestUnmarshal("groups.getInvites", &response, params) return } @@ -367,7 +363,7 @@ type GroupsGetLongPollServerResponse object.GroupsLongPollServer // // https://vk.com/dev/groups.getLongPollServer func (vk *VK) GroupsGetLongPollServer(params Params) (response GroupsGetLongPollServerResponse, err error) { - err = vk.RequestUnmarshal("groups.getLongPollServer", params, &response) + err = vk.RequestUnmarshal("groups.getLongPollServer", &response, params) return } @@ -378,7 +374,7 @@ type GroupsGetLongPollSettingsResponse object.GroupsLongPollSettings // // https://vk.com/dev/groups.getLongPollSettings func (vk *VK) GroupsGetLongPollSettings(params Params) (response GroupsGetLongPollSettingsResponse, err error) { - err = vk.RequestUnmarshal("groups.getLongPollSettings", params, &response) + err = vk.RequestUnmarshal("groups.getLongPollSettings", &response, params) return } @@ -392,9 +388,7 @@ type GroupsGetMembersResponse struct { // // https://vk.com/dev/groups.getMembers func (vk *VK) GroupsGetMembers(params Params) (response GroupsGetMembersResponse, err error) { - params["fields"] = "" - params["filter"] = "" - err = vk.RequestUnmarshal("groups.getMembers", params, &response) + err = vk.RequestUnmarshal("groups.getMembers", &response, params, Params{"filter": ""}) return } @@ -409,11 +403,12 @@ type GroupsGetMembersFieldsResponse struct { // // https://vk.com/dev/groups.getMembers func (vk *VK) GroupsGetMembersFields(params Params) (response GroupsGetMembersFieldsResponse, err error) { + reqParams := make(Params) if v, prs := params["fields"]; v == "" || !prs { - params["fields"] = "id" + reqParams["fields"] = "id" } - err = vk.RequestUnmarshal("groups.getMembers", params, &response) + err = vk.RequestUnmarshal("groups.getMembers", &response, params, reqParams) return } @@ -432,8 +427,7 @@ func (vk *VK) GroupsGetMembersFilterManagers(params Params) ( response GroupsGetMembersFilterManagersResponse, err error, ) { - params["filter"] = "managers" - err = vk.RequestUnmarshal("groups.getMembers", params, &response) + err = vk.RequestUnmarshal("groups.getMembers", &response, params, Params{"filter": "managers"}) return } @@ -445,7 +439,7 @@ type GroupsGetOnlineStatusResponse object.GroupsOnlineStatus // // https://vk.com/dev/groups.getOnlineStatus func (vk *VK) GroupsGetOnlineStatus(params Params) (response GroupsGetOnlineStatusResponse, err error) { - err = vk.RequestUnmarshal("groups.getOnlineStatus", params, &response) + err = vk.RequestUnmarshal("groups.getOnlineStatus", &response, params) return } @@ -459,8 +453,7 @@ type GroupsGetRequestsResponse struct { // // https://vk.com/dev/groups.getRequests func (vk *VK) GroupsGetRequests(params Params) (response GroupsGetRequestsResponse, err error) { - params["fields"] = "" - err = vk.RequestUnmarshal("groups.getRequests", params, &response) + err = vk.RequestUnmarshal("groups.getRequests", &response, params, Params{"fields": ""}) return } @@ -475,11 +468,12 @@ type GroupsGetRequestsFieldsResponse struct { // // https://vk.com/dev/groups.getRequests func (vk *VK) GroupsGetRequestsFields(params Params) (response GroupsGetRequestsFieldsResponse, err error) { + reqParams := make(Params) if v, prs := params["fields"]; v == "" || !prs { - params["fields"] = "id" + reqParams["fields"] = "id" } - err = vk.RequestUnmarshal("groups.getRequests", params, &response) + err = vk.RequestUnmarshal("groups.getRequests", &response, params, reqParams) return } @@ -491,7 +485,7 @@ type GroupsGetSettingsResponse object.GroupsGroupSettings // // https://vk.com/dev/groups.getSettings func (vk *VK) GroupsGetSettings(params Params) (response GroupsGetSettingsResponse, err error) { - err = vk.RequestUnmarshal("groups.getSettings", params, &response) + err = vk.RequestUnmarshal("groups.getSettings", &response, params) return } @@ -502,7 +496,7 @@ type GroupsGetTagListResponse []object.GroupsTag // // https://vk.com/dev/groups.getTagList func (vk *VK) GroupsGetTagList(params Params) (response GroupsGetTagListResponse, err error) { - err = vk.RequestUnmarshal("groups.getTagList", params, &response) + err = vk.RequestUnmarshal("groups.getTagList", &response, params) return } @@ -513,7 +507,7 @@ type GroupsGetTokenPermissionsResponse object.GroupsTokenPermissions // // https://vk.com/dev/groups.getTokenPermissions func (vk *VK) GroupsGetTokenPermissions(params Params) (response GroupsGetTokenPermissionsResponse, err error) { - err = vk.RequestUnmarshal("groups.getTokenPermissions", params, &response) + err = vk.RequestUnmarshal("groups.getTokenPermissions", &response, params) return } @@ -521,7 +515,7 @@ func (vk *VK) GroupsGetTokenPermissions(params Params) (response GroupsGetTokenP // // https://vk.com/dev/groups.invite func (vk *VK) GroupsInvite(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.invite", params, &response) + err = vk.RequestUnmarshal("groups.invite", &response, params) return } @@ -531,8 +525,7 @@ func (vk *VK) GroupsInvite(params Params) (response int, err error) { // // https://vk.com/dev/groups.isMember func (vk *VK) GroupsIsMember(params Params) (response int, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("groups.isMember", params, &response) + err = vk.RequestUnmarshal("groups.isMember", &response, params, Params{"extended": false}) return } @@ -552,8 +545,7 @@ type GroupsIsMemberExtendedResponse struct { // // https://vk.com/dev/groups.isMember func (vk *VK) GroupsIsMemberExtended(params Params) (response GroupsIsMemberExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("groups.isMember", params, &response) + err = vk.RequestUnmarshal("groups.isMember", &response, params, Params{"extended": true}) return } @@ -568,8 +560,7 @@ type GroupsIsMemberUserIDsExtendedResponse []object.GroupsMemberStatusFull // // https://vk.com/dev/groups.isMember func (vk *VK) GroupsIsMemberUserIDsExtended(params Params) (response GroupsIsMemberUserIDsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("groups.isMember", params, &response) + err = vk.RequestUnmarshal("groups.isMember", &response, params, Params{"extended": true}) return } @@ -584,8 +575,7 @@ type GroupsIsMemberUserIDsResponse []object.GroupsMemberStatus // // https://vk.com/dev/groups.isMember func (vk *VK) GroupsIsMemberUserIDs(params Params) (response GroupsIsMemberUserIDsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("groups.isMember", params, &response) + err = vk.RequestUnmarshal("groups.isMember", &response, params, Params{"extended": false}) return } @@ -594,7 +584,7 @@ func (vk *VK) GroupsIsMemberUserIDs(params Params) (response GroupsIsMemberUserI // // https://vk.com/dev/groups.join func (vk *VK) GroupsJoin(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.join", params, &response) + err = vk.RequestUnmarshal("groups.join", &response, params) return } @@ -602,7 +592,7 @@ func (vk *VK) GroupsJoin(params Params) (response int, err error) { // // https://vk.com/dev/groups.leave func (vk *VK) GroupsLeave(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.leave", params, &response) + err = vk.RequestUnmarshal("groups.leave", &response, params) return } @@ -610,7 +600,7 @@ func (vk *VK) GroupsLeave(params Params) (response int, err error) { // // https://vk.com/dev/groups.removeUser func (vk *VK) GroupsRemoveUser(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.removeUser", params, &response) + err = vk.RequestUnmarshal("groups.removeUser", &response, params) return } @@ -618,7 +608,7 @@ func (vk *VK) GroupsRemoveUser(params Params) (response int, err error) { // // https://vk.com/dev/groups.reorderLink func (vk *VK) GroupsReorderLink(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.reorderLink", params, &response) + err = vk.RequestUnmarshal("groups.reorderLink", &response, params) return } @@ -632,7 +622,7 @@ type GroupsSearchResponse struct { // // https://vk.com/dev/groups.search func (vk *VK) GroupsSearch(params Params) (response GroupsSearchResponse, err error) { - err = vk.RequestUnmarshal("groups.search", params, &response) + err = vk.RequestUnmarshal("groups.search", &response, params) return } @@ -640,7 +630,7 @@ func (vk *VK) GroupsSearch(params Params) (response GroupsSearchResponse, err er // // https://vk.com/dev/groups.setCallbackSettings func (vk *VK) GroupsSetCallbackSettings(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.setCallbackSettings", params, &response) + err = vk.RequestUnmarshal("groups.setCallbackSettings", &response, params) return } @@ -648,7 +638,7 @@ func (vk *VK) GroupsSetCallbackSettings(params Params) (response int, err error) // // https://vk.com/dev/groups.setLongPollSettings func (vk *VK) GroupsSetLongPollSettings(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.setLongPollSettings", params, &response) + err = vk.RequestUnmarshal("groups.setLongPollSettings", &response, params) return } @@ -656,7 +646,7 @@ func (vk *VK) GroupsSetLongPollSettings(params Params) (response int, err error) // // https://vk.com/dev/groups.setSettings func (vk *VK) GroupsSetSettings(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.setSettings", params, &response) + err = vk.RequestUnmarshal("groups.setSettings", &response, params) return } @@ -665,7 +655,7 @@ func (vk *VK) GroupsSetSettings(params Params) (response int, err error) { // // https://vk.com/dev/groups.setUserNote func (vk *VK) GroupsSetUserNote(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.setUserNote", params, &response) + err = vk.RequestUnmarshal("groups.setUserNote", &response, params) return } @@ -673,7 +663,7 @@ func (vk *VK) GroupsSetUserNote(params Params) (response int, err error) { // // https://vk.com/dev/groups.tagAdd func (vk *VK) GroupsTagAdd(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.tagAdd", params, &response) + err = vk.RequestUnmarshal("groups.tagAdd", &response, params) return } @@ -681,7 +671,7 @@ func (vk *VK) GroupsTagAdd(params Params) (response int, err error) { // // https://vk.com/dev/groups.tagBind func (vk *VK) GroupsTagBind(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.tagBind", params, &response) + err = vk.RequestUnmarshal("groups.tagBind", &response, params) return } @@ -692,7 +682,7 @@ func (vk *VK) GroupsTagBind(params Params) (response int, err error) { // // https://vk.com/dev/groups.tagDelete func (vk *VK) GroupsTagDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.tagDelete", params, &response) + err = vk.RequestUnmarshal("groups.tagDelete", &response, params) return } @@ -700,7 +690,7 @@ func (vk *VK) GroupsTagDelete(params Params) (response int, err error) { // // https://vk.com/dev/groups.tagUpdate func (vk *VK) GroupsTagUpdate(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.tagUpdate", params, &response) + err = vk.RequestUnmarshal("groups.tagUpdate", &response, params) return } @@ -708,7 +698,7 @@ func (vk *VK) GroupsTagUpdate(params Params) (response int, err error) { // // https://vk.com/dev/groups.toggleMarket func (vk *VK) GroupsToggleMarket(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.toggleMarket", params, &response) + err = vk.RequestUnmarshal("groups.toggleMarket", &response, params) return } @@ -716,6 +706,6 @@ func (vk *VK) GroupsToggleMarket(params Params) (response int, err error) { // // https://vk.com/dev/groups.unban func (vk *VK) GroupsUnban(params Params) (response int, err error) { - err = vk.RequestUnmarshal("groups.unban", params, &response) + err = vk.RequestUnmarshal("groups.unban", &response, params) return } diff --git a/api/groups_test.go b/api/groups_test.go index 13532ce6..42f5a144 100644 --- a/api/groups_test.go +++ b/api/groups_test.go @@ -694,7 +694,7 @@ func TestVK_GroupsGetCatalogInfo(t *testing.T) { needUserToken(t) - res, err := vkUser.GroupsGetCatalogInfo(api.Params{}) + res, err := vkUser.GroupsGetCatalogInfo(nil) noError(t, err) // assert.NotEmpty(t, res.Categories[0].ID) assert.NotEmpty(t, res.Enabled) @@ -705,7 +705,7 @@ func TestVK_GroupsGetCatalogInfoExtended(t *testing.T) { needUserToken(t) - res, err := vkUser.GroupsGetCatalogInfoExtended(api.Params{}) + res, err := vkUser.GroupsGetCatalogInfoExtended(nil) noError(t, err) // if assert.NotEmpty(t, res.Categories) { // assert.NotEmpty(t, res.Categories[0].Name) @@ -732,7 +732,7 @@ func TestVK_GroupsGetInvites(t *testing.T) { needUserToken(t) - _, err := vkUser.GroupsGetInvites(api.Params{}) + _, err := vkUser.GroupsGetInvites(nil) noError(t, err) } @@ -741,7 +741,7 @@ func TestVK_GroupsGetInvitesExtended(t *testing.T) { needUserToken(t) - _, err := vkUser.GroupsGetInvitesExtended(api.Params{}) + _, err := vkUser.GroupsGetInvitesExtended(nil) noError(t, err) } @@ -869,7 +869,7 @@ func TestVK_GroupsGetTokenPermissions(t *testing.T) { needGroupToken(t) - res, err := vkGroup.GroupsGetTokenPermissions(api.Params{}) + res, err := vkGroup.GroupsGetTokenPermissions(nil) noError(t, err) assert.NotEmpty(t, res.Mask) assert.NotEmpty(t, res.Permissions[0].Name) diff --git a/api/leadforms.go b/api/leadforms.go index 99dc32db..3b4f4ac8 100644 --- a/api/leadforms.go +++ b/api/leadforms.go @@ -14,7 +14,7 @@ type LeadFormsCreateResponse struct { // // https://vk.com/dev/leadForms.create func (vk *VK) LeadFormsCreate(params Params) (response LeadFormsCreateResponse, err error) { - err = vk.RequestUnmarshal("leadForms.create", params, &response) + err = vk.RequestUnmarshal("leadForms.create", &response, params) return } @@ -27,7 +27,7 @@ type LeadFormsDeleteResponse struct { // // https://vk.com/dev/leadForms.delete func (vk *VK) LeadFormsDelete(params Params) (response LeadFormsDeleteResponse, err error) { - err = vk.RequestUnmarshal("leadForms.delete", params, &response) + err = vk.RequestUnmarshal("leadForms.delete", &response, params) return } @@ -38,7 +38,7 @@ type LeadFormsGetResponse object.LeadFormsForm // // https://vk.com/dev/leadForms.get func (vk *VK) LeadFormsGet(params Params) (response LeadFormsGetResponse, err error) { - err = vk.RequestUnmarshal("leadForms.get", params, &response) + err = vk.RequestUnmarshal("leadForms.get", &response, params) return } @@ -51,7 +51,7 @@ type LeadFormsGetLeadsResponse struct { // // https://vk.com/dev/leadForms.getLeads func (vk *VK) LeadFormsGetLeads(params Params) (response LeadFormsGetLeadsResponse, err error) { - err = vk.RequestUnmarshal("leadForms.getLeads", params, &response) + err = vk.RequestUnmarshal("leadForms.getLeads", &response, params) return } @@ -59,7 +59,7 @@ func (vk *VK) LeadFormsGetLeads(params Params) (response LeadFormsGetLeadsRespon // // https://vk.com/dev/leadForms.getUploadURL func (vk *VK) LeadFormsGetUploadURL(params Params) (response string, err error) { - err = vk.RequestUnmarshal("leadForms.getUploadURL", params, &response) + err = vk.RequestUnmarshal("leadForms.getUploadURL", &response, params) return } @@ -70,7 +70,7 @@ type LeadFormsListResponse []object.LeadFormsForm // // https://vk.com/dev/leadForms.list func (vk *VK) LeadFormsList(params Params) (response LeadFormsListResponse, err error) { - err = vk.RequestUnmarshal("leadForms.list", params, &response) + err = vk.RequestUnmarshal("leadForms.list", &response, params) return } @@ -84,6 +84,6 @@ type LeadFormsUpdateResponse struct { // // https://vk.com/dev/leadForms.update func (vk *VK) LeadFormsUpdate(params Params) (response LeadFormsUpdateResponse, err error) { - err = vk.RequestUnmarshal("leadForms.update", params, &response) + err = vk.RequestUnmarshal("leadForms.update", &response, params) return } diff --git a/api/leads.go b/api/leads.go index 53c03508..61689874 100644 --- a/api/leads.go +++ b/api/leads.go @@ -11,7 +11,7 @@ type LeadsCheckUserResponse object.LeadsChecked // // https://vk.com/dev/leads.checkUser func (vk *VK) LeadsCheckUser(params Params) (response LeadsCheckUserResponse, err error) { - err = vk.RequestUnmarshal("leads.checkUser", params, &response) + err = vk.RequestUnmarshal("leads.checkUser", &response, params) return } @@ -22,7 +22,7 @@ type LeadsCompleteResponse object.LeadsComplete // // https://vk.com/dev/leads.complete func (vk *VK) LeadsComplete(params Params) (response LeadsCompleteResponse, err error) { - err = vk.RequestUnmarshal("leads.complete", params, &response) + err = vk.RequestUnmarshal("leads.complete", &response, params) return } @@ -33,7 +33,7 @@ type LeadsGetStatsResponse object.LeadsLead // // https://vk.com/dev/leads.getStats func (vk *VK) LeadsGetStats(params Params) (response LeadsGetStatsResponse, err error) { - err = vk.RequestUnmarshal("leads.getStats", params, &response) + err = vk.RequestUnmarshal("leads.getStats", &response, params) return } @@ -44,7 +44,7 @@ type LeadsGetUsersResponse object.LeadsEntry // // https://vk.com/dev/leads.getUsers func (vk *VK) LeadsGetUsers(params Params) (response LeadsGetUsersResponse, err error) { - err = vk.RequestUnmarshal("leads.getUsers", params, &response) + err = vk.RequestUnmarshal("leads.getUsers", &response, params) return } @@ -58,7 +58,7 @@ type LeadsMetricHitResponse struct { // // https://vk.com/dev/leads.metricHit func (vk *VK) LeadsMetricHit(params Params) (response LeadsMetricHitResponse, err error) { - err = vk.RequestUnmarshal("leads.metricHit", params, &response) + err = vk.RequestUnmarshal("leads.metricHit", &response, params) return } @@ -69,6 +69,6 @@ type LeadsStartResponse object.LeadsStart // // https://vk.com/dev/leads.start func (vk *VK) LeadsStart(params Params) (response LeadsStartResponse, err error) { - err = vk.RequestUnmarshal("leads.start", params, &response) + err = vk.RequestUnmarshal("leads.start", &response, params) return } diff --git a/api/likes.go b/api/likes.go index 98ab155c..bfa2d7a2 100644 --- a/api/likes.go +++ b/api/likes.go @@ -13,7 +13,7 @@ type LikesAddResponse struct { // // https://vk.com/dev/likes.add func (vk *VK) LikesAdd(params Params) (response LikesAddResponse, err error) { - err = vk.RequestUnmarshal("likes.add", params, &response) + err = vk.RequestUnmarshal("likes.add", &response, params) return } @@ -26,7 +26,7 @@ type LikesDeleteResponse struct { // // https://vk.com/dev/likes.delete func (vk *VK) LikesDelete(params Params) (response LikesDeleteResponse, err error) { - err = vk.RequestUnmarshal("likes.delete", params, &response) + err = vk.RequestUnmarshal("likes.delete", &response, params) return } @@ -42,8 +42,7 @@ type LikesGetListResponse struct { // // https://vk.com/dev/likes.getList func (vk *VK) LikesGetList(params Params) (response LikesGetListResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("likes.getList", params, &response) + err = vk.RequestUnmarshal("likes.getList", &response, params, Params{"extended": false}) return } @@ -60,8 +59,7 @@ type LikesGetListExtendedResponse struct { // // https://vk.com/dev/likes.getList func (vk *VK) LikesGetListExtended(params Params) (response LikesGetListExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("likes.getList", params, &response) + err = vk.RequestUnmarshal("likes.getList", &response, params, Params{"extended": true}) return } @@ -76,6 +74,6 @@ type LikesIsLikedResponse struct { // // https://vk.com/dev/likes.isLiked func (vk *VK) LikesIsLiked(params Params) (response LikesIsLikedResponse, err error) { - err = vk.RequestUnmarshal("likes.isLiked", params, &response) + err = vk.RequestUnmarshal("likes.isLiked", &response, params) return } diff --git a/api/market.go b/api/market.go index 6b98c0d7..731ed3a8 100644 --- a/api/market.go +++ b/api/market.go @@ -13,7 +13,7 @@ type MarketAddResponse struct { // // https://vk.com/dev/market.add func (vk *VK) MarketAdd(params Params) (response MarketAddResponse, err error) { - err = vk.RequestUnmarshal("market.add", params, &response) + err = vk.RequestUnmarshal("market.add", &response, params) return } @@ -26,7 +26,7 @@ type MarketAddAlbumResponse struct { // // https://vk.com/dev/market.addAlbum func (vk *VK) MarketAddAlbum(params Params) (response MarketAddAlbumResponse, err error) { - err = vk.RequestUnmarshal("market.addAlbum", params, &response) + err = vk.RequestUnmarshal("market.addAlbum", &response, params) return } @@ -34,7 +34,7 @@ func (vk *VK) MarketAddAlbum(params Params) (response MarketAddAlbumResponse, er // // https://vk.com/dev/market.addToAlbum func (vk *VK) MarketAddToAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.addToAlbum", params, &response) + err = vk.RequestUnmarshal("market.addToAlbum", &response, params) return } @@ -42,7 +42,7 @@ func (vk *VK) MarketAddToAlbum(params Params) (response int, err error) { // // https://vk.com/dev/market.createComment func (vk *VK) MarketCreateComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.createComment", params, &response) + err = vk.RequestUnmarshal("market.createComment", &response, params) return } @@ -50,7 +50,7 @@ func (vk *VK) MarketCreateComment(params Params) (response int, err error) { // // https://vk.com/dev/market.delete func (vk *VK) MarketDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.delete", params, &response) + err = vk.RequestUnmarshal("market.delete", &response, params) return } @@ -58,7 +58,7 @@ func (vk *VK) MarketDelete(params Params) (response int, err error) { // // https://vk.com/dev/market.deleteAlbum func (vk *VK) MarketDeleteAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.deleteAlbum", params, &response) + err = vk.RequestUnmarshal("market.deleteAlbum", &response, params) return } @@ -66,7 +66,7 @@ func (vk *VK) MarketDeleteAlbum(params Params) (response int, err error) { // // https://vk.com/dev/market.deleteComment func (vk *VK) MarketDeleteComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.deleteComment", params, &response) + err = vk.RequestUnmarshal("market.deleteComment", &response, params) return } @@ -74,7 +74,7 @@ func (vk *VK) MarketDeleteComment(params Params) (response int, err error) { // // https://vk.com/dev/market.edit func (vk *VK) MarketEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.edit", params, &response) + err = vk.RequestUnmarshal("market.edit", &response, params) return } @@ -82,7 +82,7 @@ func (vk *VK) MarketEdit(params Params) (response int, err error) { // // https://vk.com/dev/market.editAlbum func (vk *VK) MarketEditAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.editAlbum", params, &response) + err = vk.RequestUnmarshal("market.editAlbum", &response, params) return } @@ -90,7 +90,7 @@ func (vk *VK) MarketEditAlbum(params Params) (response int, err error) { // // https://vk.com/dev/market.editComment func (vk *VK) MarketEditComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.editComment", params, &response) + err = vk.RequestUnmarshal("market.editComment", &response, params) return } @@ -98,7 +98,7 @@ func (vk *VK) MarketEditComment(params Params) (response int, err error) { // // https://vk.com/dev/market.editOrder func (vk *VK) MarketEditOrder(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.editOrder", params, &response) + err = vk.RequestUnmarshal("market.editOrder", &response, params) return } @@ -112,7 +112,7 @@ type MarketGetResponse struct { // // https://vk.com/dev/market.get func (vk *VK) MarketGet(params Params) (response MarketGetResponse, err error) { - err = vk.RequestUnmarshal("market.get", params, &response) + err = vk.RequestUnmarshal("market.get", &response, params) return } @@ -126,7 +126,7 @@ type MarketGetAlbumByIDResponse struct { // // https://vk.com/dev/market.getAlbumById func (vk *VK) MarketGetAlbumByID(params Params) (response MarketGetAlbumByIDResponse, err error) { - err = vk.RequestUnmarshal("market.getAlbumById", params, &response) + err = vk.RequestUnmarshal("market.getAlbumById", &response, params) return } @@ -140,7 +140,7 @@ type MarketGetAlbumsResponse struct { // // https://vk.com/dev/market.getAlbums func (vk *VK) MarketGetAlbums(params Params) (response MarketGetAlbumsResponse, err error) { - err = vk.RequestUnmarshal("market.getAlbums", params, &response) + err = vk.RequestUnmarshal("market.getAlbums", &response, params) return } @@ -154,7 +154,7 @@ type MarketGetByIDResponse struct { // // https://vk.com/dev/market.getById func (vk *VK) MarketGetByID(params Params) (response MarketGetByIDResponse, err error) { - err = vk.RequestUnmarshal("market.getById", params, &response) + err = vk.RequestUnmarshal("market.getById", &response, params) return } @@ -168,7 +168,7 @@ type MarketGetCategoriesResponse struct { // // https://vk.com/dev/market.getCategories func (vk *VK) MarketGetCategories(params Params) (response MarketGetCategoriesResponse, err error) { - err = vk.RequestUnmarshal("market.getCategories", params, &response) + err = vk.RequestUnmarshal("market.getCategories", &response, params) return } @@ -184,8 +184,7 @@ type MarketGetCommentsResponse struct { // // https://vk.com/dev/market.getComments func (vk *VK) MarketGetComments(params Params) (response MarketGetCommentsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("market.getComments", params, &response) + err = vk.RequestUnmarshal("market.getComments", &response, params, Params{"extended": false}) return } @@ -203,8 +202,7 @@ type MarketGetCommentsExtendedResponse struct { // // https://vk.com/dev/market.getComments func (vk *VK) MarketGetCommentsExtended(params Params) (response MarketGetCommentsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("market.getComments", params, &response) + err = vk.RequestUnmarshal("market.getComments", &response, params, Params{"extended": true}) return } @@ -219,7 +217,7 @@ type MarketGetGroupOrdersResponse struct { // // https://vk.com/dev/market.getGroupOrders func (vk *VK) MarketGetGroupOrders(params Params) (response MarketGetGroupOrdersResponse, err error) { - err = vk.RequestUnmarshal("market.getGroupOrders", params, &response) + err = vk.RequestUnmarshal("market.getGroupOrders", &response, params) return } @@ -232,7 +230,7 @@ type MarketGetOrderByIDResponse struct { // // https://vk.com/dev/market.getOrderById func (vk *VK) MarketGetOrderByID(params Params) (response MarketGetOrderByIDResponse, err error) { - err = vk.RequestUnmarshal("market.getOrderById", params, &response) + err = vk.RequestUnmarshal("market.getOrderById", &response, params) return } @@ -246,7 +244,7 @@ type MarketGetOrderItemsResponse struct { // // https://vk.com/dev/market.getOrderItems func (vk *VK) MarketGetOrderItems(params Params) (response MarketGetOrderItemsResponse, err error) { - err = vk.RequestUnmarshal("market.getOrderItems", params, &response) + err = vk.RequestUnmarshal("market.getOrderItems", &response, params) return } @@ -254,7 +252,7 @@ func (vk *VK) MarketGetOrderItems(params Params) (response MarketGetOrderItemsRe // // https://vk.com/dev/market.removeFromAlbum func (vk *VK) MarketRemoveFromAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.removeFromAlbum", params, &response) + err = vk.RequestUnmarshal("market.removeFromAlbum", &response, params) return } @@ -262,7 +260,7 @@ func (vk *VK) MarketRemoveFromAlbum(params Params) (response int, err error) { // // https://vk.com/dev/market.reorderAlbums func (vk *VK) MarketReorderAlbums(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.reorderAlbums", params, &response) + err = vk.RequestUnmarshal("market.reorderAlbums", &response, params) return } @@ -270,7 +268,7 @@ func (vk *VK) MarketReorderAlbums(params Params) (response int, err error) { // // https://vk.com/dev/market.reorderItems func (vk *VK) MarketReorderItems(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.reorderItems", params, &response) + err = vk.RequestUnmarshal("market.reorderItems", &response, params) return } @@ -278,7 +276,7 @@ func (vk *VK) MarketReorderItems(params Params) (response int, err error) { // // https://vk.com/dev/market.report func (vk *VK) MarketReport(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.report", params, &response) + err = vk.RequestUnmarshal("market.report", &response, params) return } @@ -286,7 +284,7 @@ func (vk *VK) MarketReport(params Params) (response int, err error) { // // https://vk.com/dev/market.reportComment func (vk *VK) MarketReportComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.reportComment", params, &response) + err = vk.RequestUnmarshal("market.reportComment", &response, params) return } @@ -294,7 +292,7 @@ func (vk *VK) MarketReportComment(params Params) (response int, err error) { // // https://vk.com/dev/market.restore func (vk *VK) MarketRestore(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.restore", params, &response) + err = vk.RequestUnmarshal("market.restore", &response, params) return } @@ -302,7 +300,7 @@ func (vk *VK) MarketRestore(params Params) (response int, err error) { // // https://vk.com/dev/market.restoreComment func (vk *VK) MarketRestoreComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("market.restoreComment", params, &response) + err = vk.RequestUnmarshal("market.restoreComment", &response, params) return } @@ -316,6 +314,6 @@ type MarketSearchResponse struct { // // https://vk.com/dev/market.search func (vk *VK) MarketSearch(params Params) (response MarketSearchResponse, err error) { - err = vk.RequestUnmarshal("market.search", params, &response) + err = vk.RequestUnmarshal("market.search", &response, params) return } diff --git a/api/market_test.go b/api/market_test.go index 335d61a1..13180004 100644 --- a/api/market_test.go +++ b/api/market_test.go @@ -269,7 +269,7 @@ func TestVK_MarketGetCategories(t *testing.T) { needUserToken(t) - res, err := vkUser.MarketGetCategories(api.Params{}) + res, err := vkUser.MarketGetCategories(nil) noError(t, err) assert.NotEmpty(t, res.Count) diff --git a/api/messages.go b/api/messages.go index c13cb267..3a8f6eee 100644 --- a/api/messages.go +++ b/api/messages.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/messages.addChatUser func (vk *VK) MessagesAddChatUser(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.addChatUser", params, &response) + err = vk.RequestUnmarshal("messages.addChatUser", &response, params) return } @@ -16,7 +16,7 @@ func (vk *VK) MessagesAddChatUser(params Params) (response int, err error) { // // https://vk.com/dev/messages.allowMessagesFromGroup func (vk *VK) MessagesAllowMessagesFromGroup(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.allowMessagesFromGroup", params, &response) + err = vk.RequestUnmarshal("messages.allowMessagesFromGroup", &response, params) return } @@ -24,7 +24,7 @@ func (vk *VK) MessagesAllowMessagesFromGroup(params Params) (response int, err e // // https://vk.com/dev/messages.createChat func (vk *VK) MessagesCreateChat(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.createChat", params, &response) + err = vk.RequestUnmarshal("messages.createChat", &response, params) return } @@ -35,7 +35,7 @@ type MessagesDeleteResponse map[string]int // // https://vk.com/dev/messages.delete func (vk *VK) MessagesDelete(params Params) (response MessagesDeleteResponse, err error) { - err = vk.RequestUnmarshal("messages.delete", params, &response) + err = vk.RequestUnmarshal("messages.delete", &response, params) return } @@ -49,7 +49,7 @@ type MessagesDeleteChatPhotoResponse struct { // // https://vk.com/dev/messages.deleteChatPhoto func (vk *VK) MessagesDeleteChatPhoto(params Params) (response MessagesDeleteChatPhotoResponse, err error) { - err = vk.RequestUnmarshal("messages.deleteChatPhoto", params, &response) + err = vk.RequestUnmarshal("messages.deleteChatPhoto", &response, params) return } @@ -62,7 +62,7 @@ type MessagesDeleteConversationResponse struct { // // https://vk.com/dev/messages.deleteConversation func (vk *VK) MessagesDeleteConversation(params Params) (response MessagesDeleteConversationResponse, err error) { - err = vk.RequestUnmarshal("messages.deleteConversation", params, &response) + err = vk.RequestUnmarshal("messages.deleteConversation", &response, params) return } @@ -70,7 +70,7 @@ func (vk *VK) MessagesDeleteConversation(params Params) (response MessagesDelete // // https://vk.com/dev/messages.denyMessagesFromGroup func (vk *VK) MessagesDenyMessagesFromGroup(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.denyMessagesFromGroup", params, &response) + err = vk.RequestUnmarshal("messages.denyMessagesFromGroup", &response, params) return } @@ -78,7 +78,7 @@ func (vk *VK) MessagesDenyMessagesFromGroup(params Params) (response int, err er // // https://vk.com/dev/messages.edit func (vk *VK) MessagesEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.edit", params, &response) + err = vk.RequestUnmarshal("messages.edit", &response, params) return } @@ -86,7 +86,7 @@ func (vk *VK) MessagesEdit(params Params) (response int, err error) { // // https://vk.com/dev/messages.editChat func (vk *VK) MessagesEditChat(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.editChat", params, &response) + err = vk.RequestUnmarshal("messages.editChat", &response, params) return } @@ -104,7 +104,7 @@ func (vk *VK) MessagesGetByConversationMessageID(params Params) ( response MessagesGetByConversationMessageIDResponse, err error, ) { - err = vk.RequestUnmarshal("messages.getByConversationMessageId", params, &response) + err = vk.RequestUnmarshal("messages.getByConversationMessageId", &response, params) return } @@ -120,8 +120,7 @@ type MessagesGetByIDResponse struct { // // https://vk.com/dev/messages.getById func (vk *VK) MessagesGetByID(params Params) (response MessagesGetByIDResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("messages.getById", params, &response) + err = vk.RequestUnmarshal("messages.getById", &response, params, Params{"extended": false}) return } @@ -139,8 +138,7 @@ type MessagesGetByIDExtendedResponse struct { // // https://vk.com/dev/messages.getById func (vk *VK) MessagesGetByIDExtended(params Params) (response MessagesGetByIDExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("messages.getById", params, &response) + err = vk.RequestUnmarshal("messages.getById", &response, params, Params{"extended": true}) return } @@ -152,7 +150,7 @@ type MessagesGetChatResponse object.MessagesChat // // https://vk.com/dev/messages.getChat func (vk *VK) MessagesGetChat(params Params) (response MessagesGetChatResponse, err error) { - err = vk.RequestUnmarshal("messages.getChat", params, &response) + err = vk.RequestUnmarshal("messages.getChat", &response, params) return } @@ -163,7 +161,7 @@ type MessagesGetChatChatIDsResponse []object.MessagesChat // // https://vk.com/dev/messages.getChat func (vk *VK) MessagesGetChatChatIDs(params Params) (response MessagesGetChatChatIDsResponse, err error) { - err = vk.RequestUnmarshal("messages.getChat", params, &response) + err = vk.RequestUnmarshal("messages.getChat", &response, params) return } @@ -177,7 +175,7 @@ type MessagesGetChatPreviewResponse struct { // // https://vk.com/dev/messages.getChatPreview func (vk *VK) MessagesGetChatPreview(params Params) (response MessagesGetChatPreviewResponse, err error) { - err = vk.RequestUnmarshal("messages.getChatPreview", params, &response) + err = vk.RequestUnmarshal("messages.getChatPreview", &response, params) return } @@ -208,7 +206,7 @@ func (vk *VK) MessagesGetConversationMembers(params Params) ( response MessagesGetConversationMembersResponse, err error, ) { - err = vk.RequestUnmarshal("messages.getConversationMembers", params, &response) + err = vk.RequestUnmarshal("messages.getConversationMembers", &response, params) return } @@ -224,7 +222,7 @@ type MessagesGetConversationsResponse struct { // // https://vk.com/dev/messages.getConversations func (vk *VK) MessagesGetConversations(params Params) (response MessagesGetConversationsResponse, err error) { - err = vk.RequestUnmarshal("messages.getConversations", params, &response) + err = vk.RequestUnmarshal("messages.getConversations", &response, params) return } @@ -240,8 +238,7 @@ type MessagesGetConversationsByIDResponse struct { // // https://vk.com/dev/messages.getConversationsById func (vk *VK) MessagesGetConversationsByID(params Params) (response MessagesGetConversationsByIDResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("messages.getConversationsById", params, &response) + err = vk.RequestUnmarshal("messages.getConversationsById", &response, params, Params{"extended": false}) return } @@ -262,8 +259,7 @@ func (vk *VK) MessagesGetConversationsByIDExtended(params Params) ( response MessagesGetConversationsByIDExtendedResponse, err error, ) { - params["extended"] = true - err = vk.RequestUnmarshal("messages.getConversationsById", params, &response) + err = vk.RequestUnmarshal("messages.getConversationsById", &response, params, Params{"extended": true}) return } @@ -281,7 +277,7 @@ type MessagesGetHistoryResponse struct { // // https://vk.com/dev/messages.getHistory func (vk *VK) MessagesGetHistory(params Params) (response MessagesGetHistoryResponse, err error) { - err = vk.RequestUnmarshal("messages.getHistory", params, &response) + err = vk.RequestUnmarshal("messages.getHistory", &response, params) return } @@ -296,7 +292,7 @@ type MessagesGetHistoryAttachmentsResponse struct { // // https://vk.com/dev/messages.getHistoryAttachments func (vk *VK) MessagesGetHistoryAttachments(params Params) (response MessagesGetHistoryAttachmentsResponse, err error) { - err = vk.RequestUnmarshal("messages.getHistoryAttachments", params, &response) + err = vk.RequestUnmarshal("messages.getHistoryAttachments", &response, params) return } @@ -314,7 +310,7 @@ type MessagesGetImportantMessagesResponse struct { // // https://vk.com/dev/messages.getImportantMessages func (vk *VK) MessagesGetImportantMessages(params Params) (response MessagesGetImportantMessagesResponse, err error) { - err = vk.RequestUnmarshal("messages.getImportantMessages", params, &response) + err = vk.RequestUnmarshal("messages.getImportantMessages", &response, params) return } @@ -327,7 +323,7 @@ type MessagesGetInviteLinkResponse struct { // // https://vk.com/dev/messages.getInviteLink func (vk *VK) MessagesGetInviteLink(params Params) (response MessagesGetInviteLinkResponse, err error) { - err = vk.RequestUnmarshal("messages.getInviteLink", params, &response) + err = vk.RequestUnmarshal("messages.getInviteLink", &response, params) return } @@ -338,7 +334,7 @@ type MessagesGetLastActivityResponse object.MessagesLastActivity // // https://vk.com/dev/messages.getLastActivity func (vk *VK) MessagesGetLastActivity(params Params) (response MessagesGetLastActivityResponse, err error) { - err = vk.RequestUnmarshal("messages.getLastActivity", params, &response) + err = vk.RequestUnmarshal("messages.getLastActivity", &response, params) return } @@ -362,7 +358,7 @@ type MessagesGetLongPollHistoryResponse struct { // // https://vk.com/dev/messages.getLongPollHistory func (vk *VK) MessagesGetLongPollHistory(params Params) (response MessagesGetLongPollHistoryResponse, err error) { - err = vk.RequestUnmarshal("messages.getLongPollHistory", params, &response) + err = vk.RequestUnmarshal("messages.getLongPollHistory", &response, params) return } @@ -373,7 +369,7 @@ type MessagesGetLongPollServerResponse object.MessagesLongpollParams // // https://vk.com/dev/messages.getLongPollServer func (vk *VK) MessagesGetLongPollServer(params Params) (response MessagesGetLongPollServerResponse, err error) { - err = vk.RequestUnmarshal("messages.getLongPollServer", params, &response) + err = vk.RequestUnmarshal("messages.getLongPollServer", &response, params) return } @@ -390,7 +386,7 @@ func (vk *VK) MessagesIsMessagesFromGroupAllowed(params Params) ( response MessagesIsMessagesFromGroupAllowedResponse, err error, ) { - err = vk.RequestUnmarshal("messages.isMessagesFromGroupAllowed", params, &response) + err = vk.RequestUnmarshal("messages.isMessagesFromGroupAllowed", &response, params) return } @@ -403,7 +399,7 @@ type MessagesJoinChatByInviteLinkResponse struct { // // https://vk.com/dev/messages.joinChatByInviteLink func (vk *VK) MessagesJoinChatByInviteLink(params Params) (response MessagesJoinChatByInviteLinkResponse, err error) { - err = vk.RequestUnmarshal("messages.joinChatByInviteLink", params, &response) + err = vk.RequestUnmarshal("messages.joinChatByInviteLink", &response, params) return } @@ -411,7 +407,7 @@ func (vk *VK) MessagesJoinChatByInviteLink(params Params) (response MessagesJoin // // https://vk.com/dev/messages.markAsAnsweredConversation func (vk *VK) MessagesMarkAsAnsweredConversation(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.markAsAnsweredConversation", params, &response) + err = vk.RequestUnmarshal("messages.markAsAnsweredConversation", &response, params) return } @@ -422,7 +418,7 @@ type MessagesMarkAsImportantResponse []int // // https://vk.com/dev/messages.markAsImportant func (vk *VK) MessagesMarkAsImportant(params Params) (response MessagesMarkAsImportantResponse, err error) { - err = vk.RequestUnmarshal("messages.markAsImportant", params, &response) + err = vk.RequestUnmarshal("messages.markAsImportant", &response, params) return } @@ -430,7 +426,7 @@ func (vk *VK) MessagesMarkAsImportant(params Params) (response MessagesMarkAsImp // // https://vk.com/dev/messages.markAsImportantConversation func (vk *VK) MessagesMarkAsImportantConversation(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.markAsImportantConversation", params, &response) + err = vk.RequestUnmarshal("messages.markAsImportantConversation", &response, params) return } @@ -438,7 +434,7 @@ func (vk *VK) MessagesMarkAsImportantConversation(params Params) (response int, // // https://vk.com/dev/messages.markAsRead func (vk *VK) MessagesMarkAsRead(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.markAsRead", params, &response) + err = vk.RequestUnmarshal("messages.markAsRead", &response, params) return } @@ -449,7 +445,7 @@ type MessagesPinResponse object.MessagesMessage // // https://vk.com/dev/messages.pin func (vk *VK) MessagesPin(params Params) (response MessagesPinResponse, err error) { - err = vk.RequestUnmarshal("messages.pin", params, &response) + err = vk.RequestUnmarshal("messages.pin", &response, params) return } @@ -459,7 +455,7 @@ func (vk *VK) MessagesPin(params Params) (response MessagesPinResponse, err erro // // https://vk.com/dev/messages.removeChatUser func (vk *VK) MessagesRemoveChatUser(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.removeChatUser", params, &response) + err = vk.RequestUnmarshal("messages.removeChatUser", &response, params) return } @@ -467,7 +463,7 @@ func (vk *VK) MessagesRemoveChatUser(params Params) (response int, err error) { // // https://vk.com/dev/messages.restore func (vk *VK) MessagesRestore(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.restore", params, &response) + err = vk.RequestUnmarshal("messages.restore", &response, params) return } @@ -483,7 +479,7 @@ type MessagesSearchResponse struct { // // https://vk.com/dev/messages.search func (vk *VK) MessagesSearch(params Params) (response MessagesSearchResponse, err error) { - err = vk.RequestUnmarshal("messages.search", params, &response) + err = vk.RequestUnmarshal("messages.search", &response, params) return } @@ -498,7 +494,7 @@ type MessagesSearchConversationsResponse struct { // // https://vk.com/dev/messages.searchConversations func (vk *VK) MessagesSearchConversations(params Params) (response MessagesSearchConversationsResponse, err error) { - err = vk.RequestUnmarshal("messages.searchConversations", params, &response) + err = vk.RequestUnmarshal("messages.searchConversations", &response, params) return } @@ -508,9 +504,12 @@ func (vk *VK) MessagesSearchConversations(params Params) (response MessagesSearc // // https://vk.com/dev/messages.send func (vk *VK) MessagesSend(params Params) (response int, err error) { - params["user_ids"] = "" - params["peer_ids"] = "" - err = vk.RequestUnmarshal("messages.send", params, &response) + reqParams := Params{ + "user_ids": "", + "peer_ids": "", + } + + err = vk.RequestUnmarshal("messages.send", &response, params, reqParams) return } @@ -531,7 +530,7 @@ type MessagesSendUserIDsResponse []struct { // // https://vk.com/dev/messages.send func (vk *VK) MessagesSendUserIDs(params Params) (response MessagesSendUserIDsResponse, err error) { - err = vk.RequestUnmarshal("messages.send", params, &response) + err = vk.RequestUnmarshal("messages.send", &response, params) return } @@ -539,7 +538,7 @@ func (vk *VK) MessagesSendUserIDs(params Params) (response MessagesSendUserIDsRe // // https://vk.com/dev/messages.sendMessageEventAnswer func (vk *VK) MessagesSendMessageEventAnswer(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.sendMessageEventAnswer", params, &response) + err = vk.RequestUnmarshal("messages.sendMessageEventAnswer", &response, params) return } @@ -547,8 +546,7 @@ func (vk *VK) MessagesSendMessageEventAnswer(params Params) (response int, err e // // https://vk.com/dev/messages.sendSticker func (vk *VK) MessagesSendSticker(params Params) (response int, err error) { - params["user_ids"] = "" - err = vk.RequestUnmarshal("messages.sendSticker", params, &response) + err = vk.RequestUnmarshal("messages.sendSticker", &response, params, Params{"user_ids": ""}) return } @@ -557,7 +555,7 @@ func (vk *VK) MessagesSendSticker(params Params) (response int, err error) { // // https://vk.com/dev/messages.setActivity func (vk *VK) MessagesSetActivity(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.setActivity", params, &response) + err = vk.RequestUnmarshal("messages.setActivity", &response, params) return } @@ -571,7 +569,7 @@ type MessagesSetChatPhotoResponse struct { // // https://vk.com/dev/messages.setChatPhoto func (vk *VK) MessagesSetChatPhoto(params Params) (response MessagesSetChatPhotoResponse, err error) { - err = vk.RequestUnmarshal("messages.setChatPhoto", params, &response) + err = vk.RequestUnmarshal("messages.setChatPhoto", &response, params) return } @@ -579,6 +577,6 @@ func (vk *VK) MessagesSetChatPhoto(params Params) (response MessagesSetChatPhoto // // https://vk.com/dev/messages.unpin func (vk *VK) MessagesUnpin(params Params) (response int, err error) { - err = vk.RequestUnmarshal("messages.unpin", params, &response) + err = vk.RequestUnmarshal("messages.unpin", &response, params) return } diff --git a/api/messages_test.go b/api/messages_test.go index 32d58961..d67e2780 100644 --- a/api/messages_test.go +++ b/api/messages_test.go @@ -227,7 +227,7 @@ func TestVK_MessagesGetConversations(t *testing.T) { needUserToken(t) - res, err := vkUser.MessagesGetConversations(api.Params{}) + res, err := vkUser.MessagesGetConversations(nil) noError(t, err) assert.NotEmpty(t, res.Count) @@ -302,7 +302,7 @@ func TestVK_MessagesGetImportantMessages(t *testing.T) { needUserToken(t) - _, err := vkUser.MessagesGetImportantMessages(api.Params{}) + _, err := vkUser.MessagesGetImportantMessages(nil) noError(t, err) } @@ -450,7 +450,7 @@ func TestVK_MessagesSearchConversations(t *testing.T) { needUserToken(t) - _, err := vkUser.MessagesSearchConversations(api.Params{}) + _, err := vkUser.MessagesSearchConversations(nil) noError(t, err) } diff --git a/api/newsfeed.go b/api/newsfeed.go index 965854d1..51e1846b 100644 --- a/api/newsfeed.go +++ b/api/newsfeed.go @@ -9,7 +9,7 @@ import ( // // https://vk.com/dev/newsfeed.addBan func (vk *VK) NewsfeedAddBan(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.addBan", params, &response) + err = vk.RequestUnmarshal("newsfeed.addBan", &response, params) return } @@ -18,7 +18,7 @@ func (vk *VK) NewsfeedAddBan(params Params) (response int, err error) { // // https://vk.com/dev/newsfeed.deleteBan func (vk *VK) NewsfeedDeleteBan(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.deleteBan", params, &response) + err = vk.RequestUnmarshal("newsfeed.deleteBan", &response, params) return } @@ -26,7 +26,7 @@ func (vk *VK) NewsfeedDeleteBan(params Params) (response int, err error) { // // https://vk.com/dev/newsfeed.deleteList func (vk *VK) NewsfeedDeleteList(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.deleteList", params, &response) + err = vk.RequestUnmarshal("newsfeed.deleteList", &response, params) return } @@ -41,7 +41,7 @@ type NewsfeedGetResponse struct { // // https://vk.com/dev/newsfeed.get func (vk *VK) NewsfeedGet(params Params) (response NewsfeedGetResponse, err error) { - err = vk.RequestUnmarshal("newsfeed.get", params, &response) + err = vk.RequestUnmarshal("newsfeed.get", &response, params) return } @@ -57,8 +57,7 @@ type NewsfeedGetBannedResponse struct { // // https://vk.com/dev/newsfeed.getBanned func (vk *VK) NewsfeedGetBanned(params Params) (response NewsfeedGetBannedResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("newsfeed.getBanned", params, &response) + err = vk.RequestUnmarshal("newsfeed.getBanned", &response, params, Params{"extended": false}) return } @@ -74,8 +73,7 @@ type NewsfeedGetBannedExtendedResponse struct { // // https://vk.com/dev/newsfeed.getBanned func (vk *VK) NewsfeedGetBannedExtended(params Params) (response NewsfeedGetBannedExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("newsfeed.getBanned", params, &response) + err = vk.RequestUnmarshal("newsfeed.getBanned", &response, params, Params{"extended": true}) return } @@ -91,7 +89,7 @@ type NewsfeedGetCommentsResponse struct { // // https://vk.com/dev/newsfeed.getComments func (vk *VK) NewsfeedGetComments(params Params) (response NewsfeedGetCommentsResponse, err error) { - err = vk.RequestUnmarshal("newsfeed.getComments", params, &response) + err = vk.RequestUnmarshal("newsfeed.getComments", &response, params) return } @@ -110,7 +108,7 @@ type NewsfeedGetListsResponse struct { // // https://vk.com/dev/newsfeed.getLists func (vk *VK) NewsfeedGetLists(params Params) (response NewsfeedGetListsResponse, err error) { - err = vk.RequestUnmarshal("newsfeed.getLists", params, &response) + err = vk.RequestUnmarshal("newsfeed.getLists", &response, params) return } @@ -124,7 +122,7 @@ type NewsfeedGetMentionsResponse struct { // // https://vk.com/dev/newsfeed.getMentions func (vk *VK) NewsfeedGetMentions(params Params) (response NewsfeedGetMentionsResponse, err error) { - err = vk.RequestUnmarshal("newsfeed.getMentions", params, &response) + err = vk.RequestUnmarshal("newsfeed.getMentions", &response, params) return } @@ -141,7 +139,7 @@ type NewsfeedGetRecommendedResponse struct { // // https://vk.com/dev/newsfeed.getRecommended func (vk *VK) NewsfeedGetRecommended(params Params) (response NewsfeedGetRecommendedResponse, err error) { - err = vk.RequestUnmarshal("newsfeed.getRecommended", params, &response) + err = vk.RequestUnmarshal("newsfeed.getRecommended", &response, params) return } @@ -155,7 +153,7 @@ type NewsfeedGetSuggestedSourcesResponse struct { // // https://vk.com/dev/newsfeed.getSuggestedSources func (vk *VK) NewsfeedGetSuggestedSources(params Params) (response NewsfeedGetSuggestedSourcesResponse, err error) { - err = vk.RequestUnmarshal("newsfeed.getSuggestedSources", params, &response) + err = vk.RequestUnmarshal("newsfeed.getSuggestedSources", &response, params) return } @@ -163,7 +161,7 @@ func (vk *VK) NewsfeedGetSuggestedSources(params Params) (response NewsfeedGetSu // // https://vk.com/dev/newsfeed.ignoreItem func (vk *VK) NewsfeedIgnoreItem(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.ignoreItem", params, &response) + err = vk.RequestUnmarshal("newsfeed.ignoreItem", &response, params) return } @@ -171,7 +169,7 @@ func (vk *VK) NewsfeedIgnoreItem(params Params) (response int, err error) { // // https://vk.com/dev/newsfeed.saveList func (vk *VK) NewsfeedSaveList(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.saveList", params, &response) + err = vk.RequestUnmarshal("newsfeed.saveList", &response, params) return } @@ -189,8 +187,7 @@ type NewsfeedSearchResponse struct { // // https://vk.com/dev/newsfeed.search func (vk *VK) NewsfeedSearch(params Params) (response NewsfeedSearchResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("newsfeed.search", params, &response) + err = vk.RequestUnmarshal("newsfeed.search", &response, params, Params{"extended": false}) return } @@ -211,8 +208,7 @@ type NewsfeedSearchExtendedResponse struct { // // https://vk.com/dev/newsfeed.search func (vk *VK) NewsfeedSearchExtended(params Params) (response NewsfeedSearchExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("newsfeed.search", params, &response) + err = vk.RequestUnmarshal("newsfeed.search", &response, params, Params{"extended": true}) return } @@ -221,7 +217,7 @@ func (vk *VK) NewsfeedSearchExtended(params Params) (response NewsfeedSearchExte // // https://vk.com/dev/newsfeed.unignoreItem func (vk *VK) NewsfeedUnignoreItem(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.unignoreItem", params, &response) + err = vk.RequestUnmarshal("newsfeed.unignoreItem", &response, params) return } @@ -229,6 +225,6 @@ func (vk *VK) NewsfeedUnignoreItem(params Params) (response int, err error) { // // https://vk.com/dev/newsfeed.unsubscribe func (vk *VK) NewsfeedUnsubscribe(params Params) (response int, err error) { - err = vk.RequestUnmarshal("newsfeed.unsubscribe", params, &response) + err = vk.RequestUnmarshal("newsfeed.unsubscribe", &response, params) return } diff --git a/api/newsfeed_test.go b/api/newsfeed_test.go index de78918d..e7f3b827 100644 --- a/api/newsfeed_test.go +++ b/api/newsfeed_test.go @@ -18,12 +18,12 @@ func TestVK_NewsfeedAddBan(t *testing.T) { }) noError(t, err) - banned, err := vkUser.NewsfeedGetBanned(api.Params{}) + banned, err := vkUser.NewsfeedGetBanned(nil) noError(t, err) assert.NotEmpty(t, banned.Groups) assert.NotEmpty(t, banned.Members) - bannedEx, err := vkUser.NewsfeedGetBannedExtended(api.Params{}) + bannedEx, err := vkUser.NewsfeedGetBannedExtended(nil) noError(t, err) assert.NotEmpty(t, bannedEx.Groups) assert.NotEmpty(t, bannedEx.Profiles) @@ -40,7 +40,7 @@ func TestVK_NewsfeedGet(t *testing.T) { needUserToken(t) - res, err := vkUser.NewsfeedGet(api.Params{}) + res, err := vkUser.NewsfeedGet(nil) noError(t, err) assert.NotEmpty(t, res.Items) assert.NotEmpty(t, res.Profiles) @@ -81,7 +81,7 @@ func TestVK_NewsfeedGetRecommended(t *testing.T) { needUserToken(t) - res, err := vkUser.NewsfeedGetRecommended(api.Params{}) + res, err := vkUser.NewsfeedGetRecommended(nil) noError(t, err) assert.NotEmpty(t, res.Items) assert.NotEmpty(t, res.Profiles) @@ -93,7 +93,7 @@ func TestVK_NewsfeedGetSuggestedSources(t *testing.T) { // FIXME: NewsfeedGetSuggestedSources have bug // needUserToken(t) - // res, err := vkUser.NewsfeedGetSuggestedSources(api.Params{}) + // res, err := vkUser.NewsfeedGetSuggestedSources(nil) // noError(t, err) // assert.NotEmpty(t, res.Count) // assert.NotEmpty(t, res.Items) diff --git a/api/notes.go b/api/notes.go index 0823a0ad..5423db93 100644 --- a/api/notes.go +++ b/api/notes.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/notes.add func (vk *VK) NotesAdd(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.add", params, &response) + err = vk.RequestUnmarshal("notes.add", &response, params) return } @@ -16,7 +16,7 @@ func (vk *VK) NotesAdd(params Params) (response int, err error) { // // https://vk.com/dev/notes.createComment func (vk *VK) NotesCreateComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.createComment", params, &response) + err = vk.RequestUnmarshal("notes.createComment", &response, params) return } @@ -24,7 +24,7 @@ func (vk *VK) NotesCreateComment(params Params) (response int, err error) { // // https://vk.com/dev/notes.delete func (vk *VK) NotesDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.delete", params, &response) + err = vk.RequestUnmarshal("notes.delete", &response, params) return } @@ -32,7 +32,7 @@ func (vk *VK) NotesDelete(params Params) (response int, err error) { // // https://vk.com/dev/notes.deleteComment func (vk *VK) NotesDeleteComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.deleteComment", params, &response) + err = vk.RequestUnmarshal("notes.deleteComment", &response, params) return } @@ -40,7 +40,7 @@ func (vk *VK) NotesDeleteComment(params Params) (response int, err error) { // // https://vk.com/dev/notes.edit func (vk *VK) NotesEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.edit", params, &response) + err = vk.RequestUnmarshal("notes.edit", &response, params) return } @@ -48,7 +48,7 @@ func (vk *VK) NotesEdit(params Params) (response int, err error) { // // https://vk.com/dev/notes.editComment func (vk *VK) NotesEditComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.editComment", params, &response) + err = vk.RequestUnmarshal("notes.editComment", &response, params) return } @@ -62,7 +62,7 @@ type NotesGetResponse struct { // // https://vk.com/dev/notes.get func (vk *VK) NotesGet(params Params) (response NotesGetResponse, err error) { - err = vk.RequestUnmarshal("notes.get", params, &response) + err = vk.RequestUnmarshal("notes.get", &response, params) return } @@ -73,7 +73,7 @@ type NotesGetByIDResponse object.NotesNote // // https://vk.com/dev/notes.getById func (vk *VK) NotesGetByID(params Params) (response NotesGetByIDResponse, err error) { - err = vk.RequestUnmarshal("notes.getById", params, &response) + err = vk.RequestUnmarshal("notes.getById", &response, params) return } @@ -87,7 +87,7 @@ type NotesGetCommentsResponse struct { // // https://vk.com/dev/notes.getComments func (vk *VK) NotesGetComments(params Params) (response NotesGetCommentsResponse, err error) { - err = vk.RequestUnmarshal("notes.getComments", params, &response) + err = vk.RequestUnmarshal("notes.getComments", &response, params) return } @@ -95,6 +95,6 @@ func (vk *VK) NotesGetComments(params Params) (response NotesGetCommentsResponse // // https://vk.com/dev/notes.restoreComment func (vk *VK) NotesRestoreComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notes.restoreComment", params, &response) + err = vk.RequestUnmarshal("notes.restoreComment", &response, params) return } diff --git a/api/notifications.go b/api/notifications.go index 7ce3cb82..94009eec 100644 --- a/api/notifications.go +++ b/api/notifications.go @@ -22,7 +22,7 @@ type NotificationsGetResponse struct { // // https://vk.com/dev/notifications.get func (vk *VK) NotificationsGet(params Params) (response NotificationsGetResponse, err error) { - err = vk.RequestUnmarshal("notifications.get", params, &response) + err = vk.RequestUnmarshal("notifications.get", &response, params) return } @@ -31,7 +31,7 @@ func (vk *VK) NotificationsGet(params Params) (response NotificationsGetResponse // // https://vk.com/dev/notifications.markAsViewed func (vk *VK) NotificationsMarkAsViewed(params Params) (response int, err error) { - err = vk.RequestUnmarshal("notifications.markAsViewed", params, &response) + err = vk.RequestUnmarshal("notifications.markAsViewed", &response, params) return } @@ -49,6 +49,6 @@ type NotificationsSendMessageResponse []struct { // // https://vk.com/dev/notifications.sendMessage func (vk *VK) NotificationsSendMessage(params Params) (response NotificationsSendMessageResponse, err error) { - err = vk.RequestUnmarshal("notifications.sendMessage", params, &response) + err = vk.RequestUnmarshal("notifications.sendMessage", &response, params) return } diff --git a/api/notifications_test.go b/api/notifications_test.go index 558e359b..1e249c75 100644 --- a/api/notifications_test.go +++ b/api/notifications_test.go @@ -28,7 +28,7 @@ func TestVK_NotificationsMarkAsViewed(t *testing.T) { needUserToken(t) - res, err := vkUser.NotificationsMarkAsViewed(api.Params{}) + res, err := vkUser.NotificationsMarkAsViewed(nil) noError(t, err) assert.NotEmpty(t, res) } diff --git a/api/orders.go b/api/orders.go index 757a6842..35f602d7 100644 --- a/api/orders.go +++ b/api/orders.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/orders.cancelSubscription func (vk *VK) OrdersCancelSubscription(params Params) (response int, err error) { - err = vk.RequestUnmarshal("orders.cancelSubscription", params, &response) + err = vk.RequestUnmarshal("orders.cancelSubscription", &response, params) return } @@ -19,7 +19,7 @@ type OrdersChangeStateResponse string // New state // // https://vk.com/dev/orders.changeState func (vk *VK) OrdersChangeState(params Params) (response OrdersChangeStateResponse, err error) { - err = vk.RequestUnmarshal("orders.changeState", params, &response) + err = vk.RequestUnmarshal("orders.changeState", &response, params) return } @@ -30,7 +30,7 @@ type OrdersGetResponse []object.OrdersOrder // // https://vk.com/dev/orders.get func (vk *VK) OrdersGet(params Params) (response OrdersGetResponse, err error) { - err = vk.RequestUnmarshal("orders.get", params, &response) + err = vk.RequestUnmarshal("orders.get", &response, params) return } @@ -41,7 +41,7 @@ type OrdersGetAmountResponse []object.OrdersAmount // // https://vk.com/dev/orders.getAmount func (vk *VK) OrdersGetAmount(params Params) (response OrdersGetAmountResponse, err error) { - err = vk.RequestUnmarshal("orders.getAmount", params, &response) + err = vk.RequestUnmarshal("orders.getAmount", &response, params) return } @@ -52,7 +52,7 @@ type OrdersGetByIDResponse []object.OrdersOrder // // https://vk.com/dev/orders.getByID func (vk *VK) OrdersGetByID(params Params) (response OrdersGetByIDResponse, err error) { - err = vk.RequestUnmarshal("orders.getById", params, &response) + err = vk.RequestUnmarshal("orders.getById", &response, params) return } @@ -63,7 +63,7 @@ type OrdersGetUserSubscriptionByIDResponse object.OrdersSubscription // // https://vk.com/dev/orders.getUserSubscriptionById func (vk *VK) OrdersGetUserSubscriptionByID(params Params) (response OrdersGetUserSubscriptionByIDResponse, err error) { - err = vk.RequestUnmarshal("orders.getUserSubscriptionById", params, &response) + err = vk.RequestUnmarshal("orders.getUserSubscriptionById", &response, params) return } @@ -77,7 +77,7 @@ type OrdersGetUserSubscriptionsResponse struct { // // https://vk.com/dev/orders.getUserSubscriptions func (vk *VK) OrdersGetUserSubscriptions(params Params) (response OrdersGetUserSubscriptionsResponse, err error) { - err = vk.RequestUnmarshal("orders.getUserSubscriptions", params, &response) + err = vk.RequestUnmarshal("orders.getUserSubscriptions", &response, params) return } @@ -85,6 +85,6 @@ func (vk *VK) OrdersGetUserSubscriptions(params Params) (response OrdersGetUserS // // https://vk.com/dev/orders.updateSubscription func (vk *VK) OrdersUpdateSubscription(params Params) (response int, err error) { - err = vk.RequestUnmarshal("orders.updateSubscription", params, &response) + err = vk.RequestUnmarshal("orders.updateSubscription", &response, params) return } diff --git a/api/pages.go b/api/pages.go index 145a1ac2..5652590d 100644 --- a/api/pages.go +++ b/api/pages.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/pages.clearCache func (vk *VK) PagesClearCache(params Params) (response int, err error) { - err = vk.RequestUnmarshal("pages.clearCache", params, &response) + err = vk.RequestUnmarshal("pages.clearCache", &response, params) return } @@ -19,7 +19,7 @@ type PagesGetResponse object.PagesWikipageFull // // https://vk.com/dev/pages.get func (vk *VK) PagesGet(params Params) (response PagesGetResponse, err error) { - err = vk.RequestUnmarshal("pages.get", params, &response) + err = vk.RequestUnmarshal("pages.get", &response, params) return } @@ -30,7 +30,7 @@ type PagesGetHistoryResponse []object.PagesWikipageHistory // // https://vk.com/dev/pages.getHistory func (vk *VK) PagesGetHistory(params Params) (response PagesGetHistoryResponse, err error) { - err = vk.RequestUnmarshal("pages.getHistory", params, &response) + err = vk.RequestUnmarshal("pages.getHistory", &response, params) return } @@ -41,7 +41,7 @@ type PagesGetTitlesResponse []object.PagesWikipageFull // // https://vk.com/dev/pages.getTitles func (vk *VK) PagesGetTitles(params Params) (response PagesGetTitlesResponse, err error) { - err = vk.RequestUnmarshal("pages.getTitles", params, &response) + err = vk.RequestUnmarshal("pages.getTitles", &response, params) return } @@ -52,7 +52,7 @@ type PagesGetVersionResponse object.PagesWikipageFull // // https://vk.com/dev/pages.getVersion func (vk *VK) PagesGetVersion(params Params) (response PagesGetVersionResponse, err error) { - err = vk.RequestUnmarshal("pages.getVersion", params, &response) + err = vk.RequestUnmarshal("pages.getVersion", &response, params) return } @@ -60,7 +60,7 @@ func (vk *VK) PagesGetVersion(params Params) (response PagesGetVersionResponse, // // https://vk.com/dev/pages.parseWiki func (vk *VK) PagesParseWiki(params Params) (response string, err error) { - err = vk.RequestUnmarshal("pages.parseWiki", params, &response) + err = vk.RequestUnmarshal("pages.parseWiki", &response, params) return } @@ -68,7 +68,7 @@ func (vk *VK) PagesParseWiki(params Params) (response string, err error) { // // https://vk.com/dev/pages.save func (vk *VK) PagesSave(params Params) (response int, err error) { - err = vk.RequestUnmarshal("pages.save", params, &response) + err = vk.RequestUnmarshal("pages.save", &response, params) return } @@ -76,6 +76,6 @@ func (vk *VK) PagesSave(params Params) (response int, err error) { // // https://vk.com/dev/pages.saveAccess func (vk *VK) PagesSaveAccess(params Params) (response int, err error) { - err = vk.RequestUnmarshal("pages.saveAccess", params, &response) + err = vk.RequestUnmarshal("pages.saveAccess", &response, params) return } diff --git a/api/photos.go b/api/photos.go index cee68d55..6063a930 100644 --- a/api/photos.go +++ b/api/photos.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/photos.confirmTag func (vk *VK) PhotosConfirmTag(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.confirmTag", params, &response) + err = vk.RequestUnmarshal("photos.confirmTag", &response, params) return } @@ -16,7 +16,7 @@ func (vk *VK) PhotosConfirmTag(params Params) (response int, err error) { // // https://vk.com/dev/photos.confirmTags func (vk *VK) PhotosConfirmTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.confirmTags", params, &response) + err = vk.RequestUnmarshal("photos.confirmTags", &response, params) return } @@ -24,7 +24,7 @@ func (vk *VK) PhotosConfirmTags(params Params) (response int, err error) { // // https://vk.com/dev/photos.copy func (vk *VK) PhotosCopy(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.copy", params, &response) + err = vk.RequestUnmarshal("photos.copy", &response, params) return } @@ -35,7 +35,7 @@ type PhotosCreateAlbumResponse object.PhotosPhotoAlbumFull // // https://vk.com/dev/photos.createAlbum func (vk *VK) PhotosCreateAlbum(params Params) (response PhotosCreateAlbumResponse, err error) { - err = vk.RequestUnmarshal("photos.createAlbum", params, &response) + err = vk.RequestUnmarshal("photos.createAlbum", &response, params) return } @@ -43,7 +43,7 @@ func (vk *VK) PhotosCreateAlbum(params Params) (response PhotosCreateAlbumRespon // // https://vk.com/dev/photos.createComment func (vk *VK) PhotosCreateComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.createComment", params, &response) + err = vk.RequestUnmarshal("photos.createComment", &response, params) return } @@ -51,7 +51,7 @@ func (vk *VK) PhotosCreateComment(params Params) (response int, err error) { // // https://vk.com/dev/photos.declineTags func (vk *VK) PhotosDeclineTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.declineTags", params, &response) + err = vk.RequestUnmarshal("photos.declineTags", &response, params) return } @@ -59,7 +59,7 @@ func (vk *VK) PhotosDeclineTags(params Params) (response int, err error) { // // https://vk.com/dev/photos.delete func (vk *VK) PhotosDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.delete", params, &response) + err = vk.RequestUnmarshal("photos.delete", &response, params) return } @@ -67,7 +67,7 @@ func (vk *VK) PhotosDelete(params Params) (response int, err error) { // // https://vk.com/dev/photos.deleteAlbum func (vk *VK) PhotosDeleteAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.deleteAlbum", params, &response) + err = vk.RequestUnmarshal("photos.deleteAlbum", &response, params) return } @@ -75,7 +75,7 @@ func (vk *VK) PhotosDeleteAlbum(params Params) (response int, err error) { // // https://vk.com/dev/photos.deleteComment func (vk *VK) PhotosDeleteComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.deleteComment", params, &response) + err = vk.RequestUnmarshal("photos.deleteComment", &response, params) return } @@ -83,7 +83,7 @@ func (vk *VK) PhotosDeleteComment(params Params) (response int, err error) { // // https://vk.com/dev/photos.edit func (vk *VK) PhotosEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.edit", params, &response) + err = vk.RequestUnmarshal("photos.edit", &response, params) return } @@ -91,7 +91,7 @@ func (vk *VK) PhotosEdit(params Params) (response int, err error) { // // https://vk.com/dev/photos.editAlbum func (vk *VK) PhotosEditAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.editAlbum", params, &response) + err = vk.RequestUnmarshal("photos.editAlbum", &response, params) return } @@ -99,7 +99,7 @@ func (vk *VK) PhotosEditAlbum(params Params) (response int, err error) { // // https://vk.com/dev/photos.editComment func (vk *VK) PhotosEditComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.editComment", params, &response) + err = vk.RequestUnmarshal("photos.editComment", &response, params) return } @@ -115,8 +115,7 @@ type PhotosGetResponse struct { // // https://vk.com/dev/photos.get func (vk *VK) PhotosGet(params Params) (response PhotosGetResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("photos.get", params, &response) + err = vk.RequestUnmarshal("photos.get", &response, params, Params{"extended": false}) return } @@ -133,8 +132,7 @@ type PhotosGetExtendedResponse struct { // // https://vk.com/dev/photos.get func (vk *VK) PhotosGetExtended(params Params) (response PhotosGetExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("photos.get", params, &response) + err = vk.RequestUnmarshal("photos.get", &response, params, Params{"extended": true}) return } @@ -149,7 +147,7 @@ type PhotosGetAlbumsResponse struct { // // https://vk.com/dev/photos.getAlbums func (vk *VK) PhotosGetAlbums(params Params) (response PhotosGetAlbumsResponse, err error) { - err = vk.RequestUnmarshal("photos.getAlbums", params, &response) + err = vk.RequestUnmarshal("photos.getAlbums", &response, params) return } @@ -157,7 +155,7 @@ func (vk *VK) PhotosGetAlbums(params Params) (response PhotosGetAlbumsResponse, // // https://vk.com/dev/photos.getAlbumsCount func (vk *VK) PhotosGetAlbumsCount(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.getAlbumsCount", params, &response) + err = vk.RequestUnmarshal("photos.getAlbumsCount", &response, params) return } @@ -174,8 +172,7 @@ type PhotosGetAllResponse struct { // // https://vk.com/dev/photos.getAll func (vk *VK) PhotosGetAll(params Params) (response PhotosGetAllResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("photos.getAll", params, &response) + err = vk.RequestUnmarshal("photos.getAll", &response, params, Params{"extended": false}) return } @@ -193,8 +190,7 @@ type PhotosGetAllExtendedResponse struct { // // https://vk.com/dev/photos.getAll func (vk *VK) PhotosGetAllExtended(params Params) (response PhotosGetAllExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("photos.getAll", params, &response) + err = vk.RequestUnmarshal("photos.getAll", &response, params, Params{"extended": true}) return } @@ -210,7 +206,7 @@ type PhotosGetAllCommentsResponse struct { // // https://vk.com/dev/photos.getAllComments func (vk *VK) PhotosGetAllComments(params Params) (response PhotosGetAllCommentsResponse, err error) { - err = vk.RequestUnmarshal("photos.getAllComments", params, &response) + err = vk.RequestUnmarshal("photos.getAllComments", &response, params) return } @@ -223,8 +219,7 @@ type PhotosGetByIDResponse []object.PhotosPhoto // // https://vk.com/dev/photos.getById func (vk *VK) PhotosGetByID(params Params) (response PhotosGetByIDResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("photos.getById", params, &response) + err = vk.RequestUnmarshal("photos.getById", &response, params, Params{"extended": false}) return } @@ -238,8 +233,7 @@ type PhotosGetByIDExtendedResponse []object.PhotosPhotoFull // // https://vk.com/dev/photos.getById func (vk *VK) PhotosGetByIDExtended(params Params) (response PhotosGetByIDExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("photos.getById", params, &response) + err = vk.RequestUnmarshal("photos.getById", &response, params, Params{"extended": true}) return } @@ -253,7 +247,7 @@ type PhotosGetChatUploadServerResponse struct { // // https://vk.com/dev/photos.getChatUploadServer func (vk *VK) PhotosGetChatUploadServer(params Params) (response PhotosGetChatUploadServerResponse, err error) { - err = vk.RequestUnmarshal("photos.getChatUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getChatUploadServer", &response, params) return } @@ -270,8 +264,7 @@ type PhotosGetCommentsResponse struct { // // https://vk.com/dev/photos.getComments func (vk *VK) PhotosGetComments(params Params) (response PhotosGetCommentsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("photos.getComments", params, &response) + err = vk.RequestUnmarshal("photos.getComments", &response, params, Params{"extended": false}) return } @@ -291,8 +284,7 @@ type PhotosGetCommentsExtendedResponse struct { // // https://vk.com/dev/photos.getComments func (vk *VK) PhotosGetCommentsExtended(params Params) (response PhotosGetCommentsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("photos.getComments", params, &response) + err = vk.RequestUnmarshal("photos.getComments", &response, params, Params{"extended": true}) return } @@ -309,7 +301,7 @@ func (vk *VK) PhotosGetMarketAlbumUploadServer(params Params) ( response PhotosGetMarketAlbumUploadServerResponse, err error, ) { - err = vk.RequestUnmarshal("photos.getMarketAlbumUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getMarketAlbumUploadServer", &response, params) return } @@ -322,7 +314,7 @@ type PhotosGetMarketUploadServerResponse struct { // // https://vk.com/dev/photos.getMarketUploadServer func (vk *VK) PhotosGetMarketUploadServer(params Params) (response PhotosGetMarketUploadServerResponse, err error) { - err = vk.RequestUnmarshal("photos.getMarketUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getMarketUploadServer", &response, params) return } @@ -338,7 +330,7 @@ type PhotosGetMessagesUploadServerResponse struct { // // https://vk.com/dev/photos.getMessagesUploadServer func (vk *VK) PhotosGetMessagesUploadServer(params Params) (response PhotosGetMessagesUploadServerResponse, err error) { - err = vk.RequestUnmarshal("photos.getMessagesUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getMessagesUploadServer", &response, params) return } @@ -352,7 +344,7 @@ type PhotosGetNewTagsResponse struct { // // https://vk.com/dev/photos.getNewTags func (vk *VK) PhotosGetNewTags(params Params) (response PhotosGetNewTagsResponse, err error) { - err = vk.RequestUnmarshal("photos.getNewTags", params, &response) + err = vk.RequestUnmarshal("photos.getNewTags", &response, params) return } @@ -368,7 +360,7 @@ func (vk *VK) PhotosGetOwnerCoverPhotoUploadServer(params Params) ( response PhotosGetOwnerCoverPhotoUploadServerResponse, err error, ) { - err = vk.RequestUnmarshal("photos.getOwnerCoverPhotoUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getOwnerCoverPhotoUploadServer", &response, params) return } @@ -385,7 +377,7 @@ func (vk *VK) PhotosGetOwnerPhotoUploadServer(params Params) ( response PhotosGetOwnerPhotoUploadServerResponse, err error, ) { - err = vk.RequestUnmarshal("photos.getOwnerPhotoUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getOwnerPhotoUploadServer", &response, params) return } @@ -396,7 +388,7 @@ type PhotosGetTagsResponse []object.PhotosPhotoTag // // https://vk.com/dev/photos.getTags func (vk *VK) PhotosGetTags(params Params) (response PhotosGetTagsResponse, err error) { - err = vk.RequestUnmarshal("photos.getTags", params, &response) + err = vk.RequestUnmarshal("photos.getTags", &response, params) return } @@ -407,7 +399,7 @@ type PhotosGetUploadServerResponse object.PhotosPhotoUpload // // https://vk.com/dev/photos.getUploadServer func (vk *VK) PhotosGetUploadServer(params Params) (response PhotosGetUploadServerResponse, err error) { - err = vk.RequestUnmarshal("photos.getUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getUploadServer", &response, params) return } @@ -423,8 +415,7 @@ type PhotosGetUserPhotosResponse struct { // // https://vk.com/dev/photos.getUserPhotos func (vk *VK) PhotosGetUserPhotos(params Params) (response PhotosGetUserPhotosResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("photos.getUserPhotos", params, &response) + err = vk.RequestUnmarshal("photos.getUserPhotos", &response, params, Params{"extended": false}) return } @@ -441,8 +432,7 @@ type PhotosGetUserPhotosExtendedResponse struct { // // https://vk.com/dev/photos.getUserPhotos func (vk *VK) PhotosGetUserPhotosExtended(params Params) (response PhotosGetUserPhotosExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("photos.getUserPhotos", params, &response) + err = vk.RequestUnmarshal("photos.getUserPhotos", &response, params, Params{"extended": true}) return } @@ -454,7 +444,7 @@ type PhotosGetWallUploadServerResponse object.PhotosPhotoUpload // // https://vk.com/dev/photos.getWallUploadServer func (vk *VK) PhotosGetWallUploadServer(params Params) (response PhotosGetWallUploadServerResponse, err error) { - err = vk.RequestUnmarshal("photos.getWallUploadServer", params, &response) + err = vk.RequestUnmarshal("photos.getWallUploadServer", &response, params) return } @@ -462,7 +452,7 @@ func (vk *VK) PhotosGetWallUploadServer(params Params) (response PhotosGetWallUp // // https://vk.com/dev/photos.makeCover func (vk *VK) PhotosMakeCover(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.makeCover", params, &response) + err = vk.RequestUnmarshal("photos.makeCover", &response, params) return } @@ -470,7 +460,7 @@ func (vk *VK) PhotosMakeCover(params Params) (response int, err error) { // // https://vk.com/dev/photos.moveMoves func (vk *VK) PhotosMove(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.move", params, &response) + err = vk.RequestUnmarshal("photos.move", &response, params) return } @@ -478,7 +468,7 @@ func (vk *VK) PhotosMove(params Params) (response int, err error) { // // https://vk.com/dev/photos.putTag func (vk *VK) PhotosPutTag(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.putTag", params, &response) + err = vk.RequestUnmarshal("photos.putTag", &response, params) return } @@ -486,7 +476,7 @@ func (vk *VK) PhotosPutTag(params Params) (response int, err error) { // // https://vk.com/dev/photos.removeTag func (vk *VK) PhotosRemoveTag(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.removeTag", params, &response) + err = vk.RequestUnmarshal("photos.removeTag", &response, params) return } @@ -494,7 +484,7 @@ func (vk *VK) PhotosRemoveTag(params Params) (response int, err error) { // // https://vk.com/dev/photos.reorderAlbums func (vk *VK) PhotosReorderAlbums(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.reorderAlbums", params, &response) + err = vk.RequestUnmarshal("photos.reorderAlbums", &response, params) return } @@ -502,7 +492,7 @@ func (vk *VK) PhotosReorderAlbums(params Params) (response int, err error) { // // https://vk.com/dev/photos.reorderPhotos func (vk *VK) PhotosReorderPhotos(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.reorderPhotos", params, &response) + err = vk.RequestUnmarshal("photos.reorderPhotos", &response, params) return } @@ -510,7 +500,7 @@ func (vk *VK) PhotosReorderPhotos(params Params) (response int, err error) { // // https://vk.com/dev/photos.report func (vk *VK) PhotosReport(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.report", params, &response) + err = vk.RequestUnmarshal("photos.report", &response, params) return } @@ -518,7 +508,7 @@ func (vk *VK) PhotosReport(params Params) (response int, err error) { // // https://vk.com/dev/photos.reportComment func (vk *VK) PhotosReportComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.reportComment", params, &response) + err = vk.RequestUnmarshal("photos.reportComment", &response, params) return } @@ -526,7 +516,7 @@ func (vk *VK) PhotosReportComment(params Params) (response int, err error) { // // https://vk.com/dev/photos.restore func (vk *VK) PhotosRestore(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.restore", params, &response) + err = vk.RequestUnmarshal("photos.restore", &response, params) return } @@ -534,7 +524,7 @@ func (vk *VK) PhotosRestore(params Params) (response int, err error) { // // https://vk.com/dev/photos.restoreComment func (vk *VK) PhotosRestoreComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.restoreComment", params, &response) + err = vk.RequestUnmarshal("photos.restoreComment", &response, params) return } @@ -545,7 +535,7 @@ type PhotosSaveResponse []object.PhotosPhoto // // https://vk.com/dev/photos.save func (vk *VK) PhotosSave(params Params) (response PhotosSaveResponse, err error) { - err = vk.RequestUnmarshal("photos.save", params, &response) + err = vk.RequestUnmarshal("photos.save", &response, params) return } @@ -556,7 +546,7 @@ type PhotosSaveMarketAlbumPhotoResponse []object.PhotosPhoto // // https://vk.com/dev/photos.saveMarketAlbumPhoto func (vk *VK) PhotosSaveMarketAlbumPhoto(params Params) (response PhotosSaveMarketAlbumPhotoResponse, err error) { - err = vk.RequestUnmarshal("photos.saveMarketAlbumPhoto", params, &response) + err = vk.RequestUnmarshal("photos.saveMarketAlbumPhoto", &response, params) return } @@ -567,7 +557,7 @@ type PhotosSaveMarketPhotoResponse []object.PhotosPhoto // // https://vk.com/dev/photos.saveMarketPhoto func (vk *VK) PhotosSaveMarketPhoto(params Params) (response PhotosSaveMarketPhotoResponse, err error) { - err = vk.RequestUnmarshal("photos.saveMarketPhoto", params, &response) + err = vk.RequestUnmarshal("photos.saveMarketPhoto", &response, params) return } @@ -578,7 +568,7 @@ type PhotosSaveMessagesPhotoResponse []object.PhotosPhoto // // https://vk.com/dev/photos.saveMessagesPhoto func (vk *VK) PhotosSaveMessagesPhoto(params Params) (response PhotosSaveMessagesPhotoResponse, err error) { - err = vk.RequestUnmarshal("photos.saveMessagesPhoto", params, &response) + err = vk.RequestUnmarshal("photos.saveMessagesPhoto", &response, params) return } @@ -591,7 +581,7 @@ type PhotosSaveOwnerCoverPhotoResponse struct { // // https://vk.com/dev/photos.saveOwnerCoverPhoto func (vk *VK) PhotosSaveOwnerCoverPhoto(params Params) (response PhotosSaveOwnerCoverPhotoResponse, err error) { - err = vk.RequestUnmarshal("photos.saveOwnerCoverPhoto", params, &response) + err = vk.RequestUnmarshal("photos.saveOwnerCoverPhoto", &response, params) return } @@ -609,7 +599,7 @@ type PhotosSaveOwnerPhotoResponse struct { // // https://vk.com/dev/photos.saveOwnerPhoto func (vk *VK) PhotosSaveOwnerPhoto(params Params) (response PhotosSaveOwnerPhotoResponse, err error) { - err = vk.RequestUnmarshal("photos.saveOwnerPhoto", params, &response) + err = vk.RequestUnmarshal("photos.saveOwnerPhoto", &response, params) return } @@ -620,7 +610,7 @@ type PhotosSaveWallPhotoResponse []object.PhotosPhoto // // https://vk.com/dev/photos.saveWallPhoto func (vk *VK) PhotosSaveWallPhoto(params Params) (response PhotosSaveWallPhotoResponse, err error) { - err = vk.RequestUnmarshal("photos.saveWallPhoto", params, &response) + err = vk.RequestUnmarshal("photos.saveWallPhoto", &response, params) return } @@ -634,7 +624,7 @@ type PhotosSearchResponse struct { // // https://vk.com/dev/photos.search func (vk *VK) PhotosSearch(params Params) (response PhotosSearchResponse, err error) { - err = vk.RequestUnmarshal("photos.search", params, &response) + err = vk.RequestUnmarshal("photos.search", &response, params) return } @@ -642,6 +632,6 @@ func (vk *VK) PhotosSearch(params Params) (response PhotosSearchResponse, err er // // https://vk.com/dev/photos.skipTags func (vk *VK) PhotosSkipTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.skipTags", params, &response) + err = vk.RequestUnmarshal("photos.skipTags", &response, params) return } diff --git a/api/photos_test.go b/api/photos_test.go index 7bbbfdb9..8bbd3a07 100644 --- a/api/photos_test.go +++ b/api/photos_test.go @@ -27,7 +27,7 @@ func TestVK_PhotosConfirmTags(t *testing.T) { needUserToken(t) - ok, err := vkUser.PhotosConfirmTags(api.Params{}) + ok, err := vkUser.PhotosConfirmTags(nil) noError(t, err) assert.Equal(t, 0, ok) } @@ -140,7 +140,7 @@ func TestVK_PhotosDeclineTags(t *testing.T) { needUserToken(t) - _, err := vkUser.PhotosDeclineTags(api.Params{}) + _, err := vkUser.PhotosDeclineTags(nil) noError(t, err) } @@ -363,7 +363,7 @@ func TestVK_PhotosGetNewTags(t *testing.T) { needUserToken(t) - _, err := vkUser.PhotosGetNewTags(api.Params{}) + _, err := vkUser.PhotosGetNewTags(nil) noError(t, err) } @@ -384,7 +384,7 @@ func TestVK_PhotosGetOwnerPhotoUploadServer(t *testing.T) { needUserToken(t) - _, err := vkUser.PhotosGetOwnerPhotoUploadServer(api.Params{}) + _, err := vkUser.PhotosGetOwnerPhotoUploadServer(nil) noError(t, err) } @@ -480,6 +480,6 @@ func TestVK_PhotosSkipTags(t *testing.T) { needUserToken(t) - _, err := vkUser.PhotosSkipTags(api.Params{}) + _, err := vkUser.PhotosSkipTags(nil) noError(t, err) } diff --git a/api/podcasts.go b/api/podcasts.go index 8d778c34..f70e8ad0 100644 --- a/api/podcasts.go +++ b/api/podcasts.go @@ -15,8 +15,7 @@ type PodcastsGetCatalogResponse struct { // // https://vk.com/dev/podcasts.getCatalog func (vk *VK) PodcastsGetCatalog(params Params) (response PodcastsGetCatalogResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("podcasts.getCatalog", params, &response) + err = vk.RequestUnmarshal("podcasts.getCatalog", &response, params, Params{"extended": false}) return } @@ -33,8 +32,7 @@ type PodcastsGetCatalogExtendedResponse struct { // // https://vk.com/dev/podcasts.getCatalog func (vk *VK) PodcastsGetCatalogExtended(params Params) (response PodcastsGetCatalogExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("podcasts.getCatalog", params, &response) + err = vk.RequestUnmarshal("podcasts.getCatalog", &response, params, Params{"extended": true}) return } @@ -46,7 +44,7 @@ type PodcastsGetCategoriesResponse []object.PodcastsCategory // // https://vk.com/dev/podcasts.getCategories func (vk *VK) PodcastsGetCategories(params Params) (response PodcastsGetCategoriesResponse, err error) { - err = vk.RequestUnmarshal("podcasts.getCategories", params, &response) + err = vk.RequestUnmarshal("podcasts.getCategories", &response, params) return } @@ -60,7 +58,7 @@ type PodcastsGetEpisodesResponse struct { // // https://vk.com/dev/podcasts.getEpisodes func (vk *VK) PodcastsGetEpisodes(params Params) (response PodcastsGetEpisodesResponse, err error) { - err = vk.RequestUnmarshal("podcasts.getEpisodes", params, &response) + err = vk.RequestUnmarshal("podcasts.getEpisodes", &response, params) return } @@ -76,8 +74,7 @@ type PodcastsGetFeedResponse struct { // // https://vk.com/dev/podcasts.getFeed func (vk *VK) PodcastsGetFeed(params Params) (response PodcastsGetFeedResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("podcasts.getFeed", params, &response) + err = vk.RequestUnmarshal("podcasts.getFeed", &response, params, Params{"extended": false}) return } @@ -95,8 +92,7 @@ type PodcastsGetFeedExtendedResponse struct { // // https://vk.com/dev/podcasts.getFeed func (vk *VK) PodcastsGetFeedExtended(params Params) (response PodcastsGetFeedExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("podcasts.getFeed", params, &response) + err = vk.RequestUnmarshal("podcasts.getFeed", &response, params, Params{"extended": true}) return } @@ -124,8 +120,7 @@ type PodcastsGetStartPageResponse struct { // // https://vk.com/dev/podcasts.getStartPage func (vk *VK) PodcastsGetStartPage(params Params) (response PodcastsGetStartPageResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("podcasts.getStartPage", params, &response) + err = vk.RequestUnmarshal("podcasts.getStartPage", &response, params, Params{"extended": false}) return } @@ -154,8 +149,7 @@ type PodcastsGetStartPageExtendedResponse struct { // // https://vk.com/dev/podcasts.getStartPage func (vk *VK) PodcastsGetStartPageExtended(params Params) (response PodcastsGetStartPageExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("podcasts.getStartPage", params, &response) + err = vk.RequestUnmarshal("podcasts.getStartPage", &response, params, Params{"extended": true}) return } @@ -164,7 +158,7 @@ func (vk *VK) PodcastsGetStartPageExtended(params Params) (response PodcastsGetS // // https://vk.com/dev/podcasts.markAsListened func (vk *VK) PodcastsMarkAsListened(params Params) (response int, err error) { - err = vk.RequestUnmarshal("podcasts.markAsListened", params, &response) + err = vk.RequestUnmarshal("podcasts.markAsListened", &response, params) return } @@ -172,7 +166,7 @@ func (vk *VK) PodcastsMarkAsListened(params Params) (response int, err error) { // // https://vk.com/dev/podcasts.subscribe func (vk *VK) PodcastsSubscribe(params Params) (response int, err error) { - err = vk.RequestUnmarshal("podcasts.subscribe", params, &response) + err = vk.RequestUnmarshal("podcasts.subscribe", &response, params) return } @@ -180,6 +174,6 @@ func (vk *VK) PodcastsSubscribe(params Params) (response int, err error) { // // https://vk.com/dev/podcasts.unsubscribe func (vk *VK) PodcastsUnsubscribe(params Params) (response int, err error) { - err = vk.RequestUnmarshal("podcasts.unsubscribe", params, &response) + err = vk.RequestUnmarshal("podcasts.unsubscribe", &response, params) return } diff --git a/api/podcasts_test.go b/api/podcasts_test.go index dccc0b62..df4866af 100644 --- a/api/podcasts_test.go +++ b/api/podcasts_test.go @@ -13,13 +13,13 @@ func TestVK_PodcastsGet(t *testing.T) { t.Skip("7 Permission to perform this action is denied") needUserToken(t) - _, err := vkUser.PodcastsGetCatalog(api.Params{}) + _, err := vkUser.PodcastsGetCatalog(nil) noError(t, err) - _, err = vkUser.PodcastsGetCatalogExtended(api.Params{}) + _, err = vkUser.PodcastsGetCatalogExtended(nil) noError(t, err) - _, err = vkUser.PodcastsGetCategories(api.Params{}) + _, err = vkUser.PodcastsGetCategories(nil) noError(t, err) _, err = vkUser.PodcastsGetEpisodes(api.Params{ @@ -27,16 +27,16 @@ func TestVK_PodcastsGet(t *testing.T) { }) noError(t, err) - _, err = vkUser.PodcastsGetFeed(api.Params{}) + _, err = vkUser.PodcastsGetFeed(nil) noError(t, err) - _, err = vkUser.PodcastsGetFeedExtended(api.Params{}) + _, err = vkUser.PodcastsGetFeedExtended(nil) noError(t, err) - _, err = vkUser.PodcastsGetStartPage(api.Params{}) + _, err = vkUser.PodcastsGetStartPage(nil) noError(t, err) - _, err = vkUser.PodcastsGetStartPageExtended(api.Params{}) + _, err = vkUser.PodcastsGetStartPageExtended(nil) noError(t, err) } diff --git a/api/polls.go b/api/polls.go index 45b03c38..0652a3d6 100644 --- a/api/polls.go +++ b/api/polls.go @@ -6,7 +6,7 @@ import "github.com/SevereCloud/vksdk/object" // // https://vk.com/dev/polls.addVote func (vk *VK) PollsAddVote(params Params) (response int, err error) { - err = vk.RequestUnmarshal("polls.addVote", params, &response) + err = vk.RequestUnmarshal("polls.addVote", &response, params) return } @@ -17,7 +17,7 @@ type PollsCreateResponse object.PollsPoll // // https://vk.com/dev/polls.create func (vk *VK) PollsCreate(params Params) (response PollsCreateResponse, err error) { - err = vk.RequestUnmarshal("polls.create", params, &response) + err = vk.RequestUnmarshal("polls.create", &response, params) return } @@ -25,7 +25,7 @@ func (vk *VK) PollsCreate(params Params) (response PollsCreateResponse, err erro // // https://vk.com/dev/polls.deleteVote func (vk *VK) PollsDeleteVote(params Params) (response int, err error) { - err = vk.RequestUnmarshal("polls.deleteVote", params, &response) + err = vk.RequestUnmarshal("polls.deleteVote", &response, params) return } @@ -33,7 +33,7 @@ func (vk *VK) PollsDeleteVote(params Params) (response int, err error) { // // https://vk.com/dev/polls.edit func (vk *VK) PollsEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("polls.edit", params, &response) + err = vk.RequestUnmarshal("polls.edit", &response, params) return } @@ -44,7 +44,7 @@ type PollsGetBackgroundsResponse []object.PollsBackground // // https://vk.com/dev/polls.getBackgrounds func (vk *VK) PollsGetBackgrounds(params Params) (response PollsGetBackgroundsResponse, err error) { - err = vk.RequestUnmarshal("polls.getBackgrounds", params, &response) + err = vk.RequestUnmarshal("polls.getBackgrounds", &response, params) return } @@ -55,7 +55,7 @@ type PollsGetByIDResponse object.PollsPoll // // https://vk.com/dev/polls.getById func (vk *VK) PollsGetByID(params Params) (response PollsGetByIDResponse, err error) { - err = vk.RequestUnmarshal("polls.getById", params, &response) + err = vk.RequestUnmarshal("polls.getById", &response, params) return } @@ -68,7 +68,7 @@ type PollsGetPhotoUploadServerResponse struct { // // https://vk.com/dev/polls.getPhotoUploadServer func (vk *VK) PollsGetPhotoUploadServer(params Params) (response PollsGetPhotoUploadServerResponse, err error) { - err = vk.RequestUnmarshal("polls.getPhotoUploadServer", params, &response) + err = vk.RequestUnmarshal("polls.getPhotoUploadServer", &response, params) return } @@ -79,7 +79,7 @@ type PollsGetVotersResponse []object.PollsVoters // // https://vk.com/dev/polls.getVoters func (vk *VK) PollsGetVoters(params Params) (response PollsGetVotersResponse, err error) { - err = vk.RequestUnmarshal("polls.getVoters", params, &response) + err = vk.RequestUnmarshal("polls.getVoters", &response, params) return } @@ -90,7 +90,7 @@ type PollsGetVotersFieldsResponse []object.PollsVotersFields // // https://vk.com/dev/polls.getVoters func (vk *VK) PollsGetVotersFields(params Params) (response PollsGetVotersFieldsResponse, err error) { - err = vk.RequestUnmarshal("polls.getVoters", params, &response) + err = vk.RequestUnmarshal("polls.getVoters", &response, params) return } @@ -101,6 +101,6 @@ type PollsSavePhotoResponse object.PollsPhoto // // https://vk.com/dev/polls.savePhoto func (vk *VK) PollsSavePhoto(params Params) (response PollsSavePhotoResponse, err error) { - err = vk.RequestUnmarshal("polls.savePhoto", params, &response) + err = vk.RequestUnmarshal("polls.savePhoto", &response, params) return } diff --git a/api/polls_test.go b/api/polls_test.go index 3e959a97..2d6de68c 100644 --- a/api/polls_test.go +++ b/api/polls_test.go @@ -47,7 +47,7 @@ func TestVK_PollsGetBackgrounds(t *testing.T) { needUserToken(t) - res, err := vkUser.PollsGetBackgrounds(api.Params{}) + res, err := vkUser.PollsGetBackgrounds(nil) noError(t, err) if assert.NotEmpty(t, res) { @@ -92,7 +92,7 @@ func TestVK_PollsGetPhotoUploadServer(t *testing.T) { needUserToken(t) - _, err := vkUser.PollsGetPhotoUploadServer(api.Params{}) + _, err := vkUser.PollsGetPhotoUploadServer(nil) noError(t, err) } diff --git a/api/prettycards.go b/api/prettycards.go index 5f352304..783bece7 100644 --- a/api/prettycards.go +++ b/api/prettycards.go @@ -12,7 +12,7 @@ type PrettyCardsCreateResponse struct { // // https://vk.com/dev/prettyCards.create func (vk *VK) PrettyCardsCreate(params Params) (response PrettyCardsCreateResponse, err error) { - err = vk.RequestUnmarshal("prettyCards.create", params, &response) + err = vk.RequestUnmarshal("prettyCards.create", &response, params) return } @@ -27,7 +27,7 @@ type PrettyCardsDeleteResponse struct { // // https://vk.com/dev/prettyCards.delete func (vk *VK) PrettyCardsDelete(params Params) (response PrettyCardsDeleteResponse, err error) { - err = vk.RequestUnmarshal("prettyCards.delete", params, &response) + err = vk.RequestUnmarshal("prettyCards.delete", &response, params) return } @@ -41,7 +41,7 @@ type PrettyCardsEditResponse struct { // // https://vk.com/dev/prettyCards.edit func (vk *VK) PrettyCardsEdit(params Params) (response PrettyCardsEditResponse, err error) { - err = vk.RequestUnmarshal("prettyCards.edit", params, &response) + err = vk.RequestUnmarshal("prettyCards.edit", &response, params) return } @@ -55,7 +55,7 @@ type PrettyCardsGetResponse struct { // // https://vk.com/dev/prettyCards.get func (vk *VK) PrettyCardsGet(params Params) (response PrettyCardsGetResponse, err error) { - err = vk.RequestUnmarshal("prettyCards.get", params, &response) + err = vk.RequestUnmarshal("prettyCards.get", &response, params) return } @@ -66,7 +66,7 @@ type PrettyCardsGetByIDResponse []object.PrettyCardsPrettyCard // // https://vk.com/dev/prettyCards.getById func (vk *VK) PrettyCardsGetByID(params Params) (response PrettyCardsGetByIDResponse, err error) { - err = vk.RequestUnmarshal("prettyCards.getById", params, &response) + err = vk.RequestUnmarshal("prettyCards.getById", &response, params) return } @@ -74,6 +74,6 @@ func (vk *VK) PrettyCardsGetByID(params Params) (response PrettyCardsGetByIDResp // // https://vk.com/dev/prettyCards.getUploadURL func (vk *VK) PrettyCardsGetUploadURL(params Params) (response string, err error) { - err = vk.RequestUnmarshal("prettyCards.getUploadURL", params, &response) + err = vk.RequestUnmarshal("prettyCards.getUploadURL", &response, params) return } diff --git a/api/search.go b/api/search.go index 8207f0ed..5b83c11f 100644 --- a/api/search.go +++ b/api/search.go @@ -12,6 +12,6 @@ type SearchGetHintsResponse struct { // // https://vk.com/dev/search.getHints func (vk *VK) SearchGetHints(params Params) (response SearchGetHintsResponse, err error) { - err = vk.RequestUnmarshal("search.getHints", params, &response) + err = vk.RequestUnmarshal("search.getHints", &response, params) return } diff --git a/api/secure.go b/api/secure.go index 55423a81..ba9abe90 100644 --- a/api/secure.go +++ b/api/secure.go @@ -11,7 +11,7 @@ type SecureAddAppEventResponse int // FIXME: not found documentation. https://gi // // https://vk.com/dev/secure.addAppEvent func (vk *VK) SecureAddAppEvent(params Params) (response SecureAddAppEventResponse, err error) { - err = vk.RequestUnmarshal("secure.addAppEvent", params, &response) + err = vk.RequestUnmarshal("secure.addAppEvent", &response, params) return } @@ -22,7 +22,7 @@ type SecureCheckTokenResponse object.SecureTokenChecked // // https://vk.com/dev/secure.checkToken func (vk *VK) SecureCheckToken(params Params) (response SecureCheckTokenResponse, err error) { - err = vk.RequestUnmarshal("secure.checkToken", params, &response) + err = vk.RequestUnmarshal("secure.checkToken", &response, params) return } @@ -30,7 +30,7 @@ func (vk *VK) SecureCheckToken(params Params) (response SecureCheckTokenResponse // // https://vk.com/dev/secure.getAppBalance func (vk *VK) SecureGetAppBalance(params Params) (response int, err error) { - err = vk.RequestUnmarshal("secure.getAppBalance", params, &response) + err = vk.RequestUnmarshal("secure.getAppBalance", &response, params) return } @@ -42,7 +42,7 @@ type SecureGetSMSHistoryResponse []object.SecureSmsNotification // // https://vk.com/dev/secure.getSMSHistory func (vk *VK) SecureGetSMSHistory(params Params) (response SecureGetSMSHistoryResponse, err error) { - err = vk.RequestUnmarshal("secure.getSMSHistory", params, &response) + err = vk.RequestUnmarshal("secure.getSMSHistory", &response, params) return } @@ -53,7 +53,7 @@ type SecureGetTransactionsHistoryResponse []object.SecureTransaction // // https://vk.com/dev/secure.getTransactionsHistory func (vk *VK) SecureGetTransactionsHistory(params Params) (response SecureGetTransactionsHistoryResponse, err error) { - err = vk.RequestUnmarshal("secure.getTransactionsHistory", params, &response) + err = vk.RequestUnmarshal("secure.getTransactionsHistory", &response, params) return } @@ -64,7 +64,7 @@ type SecureGetUserLevelResponse []object.SecureLevel // // https://vk.com/dev/secure.getUserLevel func (vk *VK) SecureGetUserLevel(params Params) (response SecureGetUserLevelResponse, err error) { - err = vk.RequestUnmarshal("secure.getUserLevel", params, &response) + err = vk.RequestUnmarshal("secure.getUserLevel", &response, params) return } @@ -78,7 +78,7 @@ type SecureGiveEventStickerResponse []struct { // // https://vk.com/dev/secure.giveEventSticker func (vk *VK) SecureGiveEventSticker(params Params) (response SecureGiveEventStickerResponse, err error) { - err = vk.RequestUnmarshal("secure.giveEventSticker", params, &response) + err = vk.RequestUnmarshal("secure.giveEventSticker", &response, params) return } @@ -89,7 +89,7 @@ type SecureSendNotificationResponse []int // User ID // // https://vk.com/dev/secure.sendNotification func (vk *VK) SecureSendNotification(params Params) (response SecureSendNotificationResponse, err error) { - err = vk.RequestUnmarshal("secure.sendNotification", params, &response) + err = vk.RequestUnmarshal("secure.sendNotification", &response, params) return } @@ -97,7 +97,7 @@ func (vk *VK) SecureSendNotification(params Params) (response SecureSendNotifica // // https://vk.com/dev/secure.sendSMSNotification func (vk *VK) SecureSendSMSNotification(params Params) (response int, err error) { - err = vk.RequestUnmarshal("secure.sendSMSNotification", params, &response) + err = vk.RequestUnmarshal("secure.sendSMSNotification", &response, params) return } @@ -105,6 +105,6 @@ func (vk *VK) SecureSendSMSNotification(params Params) (response int, err error) // // https://vk.com/dev/secure.setCounter func (vk *VK) SecureSetCounter(params Params) (response int, err error) { - err = vk.RequestUnmarshal("secure.setCounter", params, &response) + err = vk.RequestUnmarshal("secure.setCounter", &response, params) return } diff --git a/api/stats.go b/api/stats.go index 263ea001..bd0b06a4 100644 --- a/api/stats.go +++ b/api/stats.go @@ -11,7 +11,7 @@ type StatsGetResponse []object.StatsPeriod // // https://vk.com/dev/stats.get func (vk *VK) StatsGet(params Params) (response StatsGetResponse, err error) { - err = vk.RequestUnmarshal("stats.get", params, &response) + err = vk.RequestUnmarshal("stats.get", &response, params) return } @@ -22,7 +22,7 @@ type StatsGetPostReachResponse []object.StatsWallpostStat // // https://vk.com/dev/stats.getPostReach func (vk *VK) StatsGetPostReach(params Params) (response StatsGetPostReachResponse, err error) { - err = vk.RequestUnmarshal("stats.getPostReach", params, &response) + err = vk.RequestUnmarshal("stats.getPostReach", &response, params) return } @@ -30,6 +30,6 @@ func (vk *VK) StatsGetPostReach(params Params) (response StatsGetPostReachRespon // // https://vk.com/dev/stats.trackVisitor func (vk *VK) StatsTrackVisitor(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stats.trackVisitor", params, &response) + err = vk.RequestUnmarshal("stats.trackVisitor", &response, params) return } diff --git a/api/stats_test.go b/api/stats_test.go index 3e5d9d93..b56b10e7 100644 --- a/api/stats_test.go +++ b/api/stats_test.go @@ -26,6 +26,6 @@ func TestVK_StatsTrackVisitor(t *testing.T) { needUserToken(t) - _, err := vkUser.StatsTrackVisitor(api.Params{}) + _, err := vkUser.StatsTrackVisitor(nil) noError(t, err) } diff --git a/api/status.go b/api/status.go index 6d57e487..aeb80bb0 100644 --- a/api/status.go +++ b/api/status.go @@ -12,12 +12,12 @@ type StatusGetResponse struct { // StatusGet returns data required to show the status of a user or community. func (vk *VK) StatusGet(params Params) (response StatusGetResponse, err error) { - err = vk.RequestUnmarshal("status.get", params, &response) + err = vk.RequestUnmarshal("status.get", &response, params) return } // StatusSet sets a new status for the current user. func (vk *VK) StatusSet(params Params) (response int, err error) { - err = vk.RequestUnmarshal("status.set", params, &response) + err = vk.RequestUnmarshal("status.set", &response, params) return } diff --git a/api/status_test.go b/api/status_test.go index 6e876df7..3ea9eef1 100644 --- a/api/status_test.go +++ b/api/status_test.go @@ -11,7 +11,7 @@ func TestVK_StatusGet(t *testing.T) { needUserToken(t) - _, err := vkUser.StatusGet(api.Params{}) + _, err := vkUser.StatusGet(nil) noError(t, err) } diff --git a/api/storage.go b/api/storage.go index c661dd41..a6c796ab 100644 --- a/api/storage.go +++ b/api/storage.go @@ -23,7 +23,7 @@ func (s StorageGetResponse) ToMap() map[string]string { // // https://vk.com/dev/storage.get func (vk *VK) StorageGet(params Params) (response StorageGetResponse, err error) { - err = vk.RequestUnmarshal("storage.get", params, &response) + err = vk.RequestUnmarshal("storage.get", &response, params) return } @@ -35,7 +35,7 @@ type StorageGetKeysResponse []string // // https://vk.com/dev/storage.getKeys func (vk *VK) StorageGetKeys(params Params) (response StorageGetKeysResponse, err error) { - err = vk.RequestUnmarshal("storage.getKeys", params, &response) + err = vk.RequestUnmarshal("storage.getKeys", &response, params) return } @@ -43,6 +43,6 @@ func (vk *VK) StorageGetKeys(params Params) (response StorageGetKeysResponse, er // // https://vk.com/dev/storage.set func (vk *VK) StorageSet(params Params) (response int, err error) { - err = vk.RequestUnmarshal("storage.set", params, &response) + err = vk.RequestUnmarshal("storage.set", &response, params) return } diff --git a/api/storage_test.go b/api/storage_test.go index c3acaf2d..1b40ab8c 100644 --- a/api/storage_test.go +++ b/api/storage_test.go @@ -24,7 +24,7 @@ func TestVK_StorageGetKeys(t *testing.T) { needUserToken(t) - _, err := vkUser.StorageGetKeys(api.Params{}) + _, err := vkUser.StorageGetKeys(nil) noError(t, err) } diff --git a/api/stories.go b/api/stories.go index 4fd67d24..ca80f43b 100644 --- a/api/stories.go +++ b/api/stories.go @@ -6,7 +6,7 @@ import "github.com/SevereCloud/vksdk/object" // // https://vk.com/dev/stories.banOwner func (vk *VK) StoriesBanOwner(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stories.banOwner", params, &response) + err = vk.RequestUnmarshal("stories.banOwner", &response, params) return } @@ -14,7 +14,7 @@ func (vk *VK) StoriesBanOwner(params Params) (response int, err error) { // // https://vk.com/dev/stories.delete func (vk *VK) StoriesDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stories.delete", params, &response) + err = vk.RequestUnmarshal("stories.delete", &response, params) return } @@ -32,8 +32,7 @@ type StoriesGetResponse struct { // // https://vk.com/dev/stories.get func (vk *VK) StoriesGet(params Params) (response StoriesGetResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("stories.get", params, &response) + err = vk.RequestUnmarshal("stories.get", &response, params, Params{"extended": false}) return } @@ -53,8 +52,7 @@ type StoriesGetExtendedResponse struct { // // https://vk.com/dev/stories.get func (vk *VK) StoriesGetExtended(params Params) (response StoriesGetExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("stories.get", params, &response) + err = vk.RequestUnmarshal("stories.get", &response, params, Params{"extended": true}) return } @@ -71,8 +69,7 @@ type StoriesGetBannedResponse struct { // // https://vk.com/dev/stories.getBanned func (vk *VK) StoriesGetBanned(params Params) (response StoriesGetBannedResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("stories.getBanned", params, &response) + err = vk.RequestUnmarshal("stories.getBanned", &response, params, Params{"extended": false}) return } @@ -90,8 +87,7 @@ type StoriesGetBannedExtendedResponse struct { // // https://vk.com/dev/stories.getBanned func (vk *VK) StoriesGetBannedExtended(params Params) (response StoriesGetBannedExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("stories.getBanned", params, &response) + err = vk.RequestUnmarshal("stories.getBanned", &response, params, Params{"extended": true}) return } @@ -108,8 +104,7 @@ type StoriesGetByIDResponse struct { // // https://vk.com/dev/stories.getById func (vk *VK) StoriesGetByID(params Params) (response StoriesGetByIDResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("stories.getById", params, &response) + err = vk.RequestUnmarshal("stories.getById", &response, params, Params{"extended": false}) return } @@ -127,8 +122,7 @@ type StoriesGetByIDExtendedResponse struct { // // https://vk.com/dev/stories.getById func (vk *VK) StoriesGetByIDExtended(params Params) (response StoriesGetByIDExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("stories.getById", params, &response) + err = vk.RequestUnmarshal("stories.getById", &response, params, Params{"extended": true}) return } @@ -144,7 +138,7 @@ type StoriesGetPhotoUploadServerResponse struct { // // https://vk.com/dev/stories.getPhotoUploadServer func (vk *VK) StoriesGetPhotoUploadServer(params Params) (response StoriesGetPhotoUploadServerResponse, err error) { - err = vk.RequestUnmarshal("stories.getPhotoUploadServer", params, &response) + err = vk.RequestUnmarshal("stories.getPhotoUploadServer", &response, params) return } @@ -160,8 +154,7 @@ type StoriesGetRepliesResponse struct { // // https://vk.com/dev/stories.getReplies func (vk *VK) StoriesGetReplies(params Params) (response StoriesGetRepliesResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("stories.getReplies", params, &response) + err = vk.RequestUnmarshal("stories.getReplies", &response, params, Params{"extended": false}) return } @@ -179,8 +172,7 @@ type StoriesGetRepliesExtendedResponse struct { // // https://vk.com/dev/stories.getReplies func (vk *VK) StoriesGetRepliesExtended(params Params) (response StoriesGetRepliesExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("stories.getReplies", params, &response) + err = vk.RequestUnmarshal("stories.getReplies", &response, params, Params{"extended": true}) return } @@ -192,7 +184,7 @@ type StoriesGetStatsResponse object.StoriesStoryStats // // https://vk.com/dev/stories.getStats func (vk *VK) StoriesGetStats(params Params) (response StoriesGetStatsResponse, err error) { - err = vk.RequestUnmarshal("stories.getStats", params, &response) + err = vk.RequestUnmarshal("stories.getStats", &response, params) return } @@ -207,7 +199,7 @@ type StoriesGetVideoUploadServerResponse struct { // // https://vk.com/dev/stories.getVideoUploadServer func (vk *VK) StoriesGetVideoUploadServer(params Params) (response StoriesGetVideoUploadServerResponse, err error) { - err = vk.RequestUnmarshal("stories.getVideoUploadServer", params, &response) + err = vk.RequestUnmarshal("stories.getVideoUploadServer", &response, params) return } @@ -223,7 +215,7 @@ type StoriesGetViewersResponse struct { // // https://vk.com/dev/stories.getViewers func (vk *VK) StoriesGetViewers(params Params) (response StoriesGetViewersResponse, err error) { - err = vk.RequestUnmarshal("stories.getViewers", params, &response) + err = vk.RequestUnmarshal("stories.getViewers", &response, params) return } @@ -232,7 +224,7 @@ func (vk *VK) StoriesGetViewers(params Params) (response StoriesGetViewersRespon // // https://vk.com/dev/stories.hideAllReplies func (vk *VK) StoriesHideAllReplies(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stories.hideAllReplies", params, &response) + err = vk.RequestUnmarshal("stories.hideAllReplies", &response, params) return } @@ -240,7 +232,7 @@ func (vk *VK) StoriesHideAllReplies(params Params) (response int, err error) { // // https://vk.com/dev/stories.hideReply func (vk *VK) StoriesHideReply(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stories.hideReply", params, &response) + err = vk.RequestUnmarshal("stories.hideReply", &response, params) return } @@ -254,7 +246,7 @@ type StoriesSaveResponse struct { // // https://vk.com/dev/stories.save func (vk *VK) StoriesSave(params Params) (response StoriesSaveResponse, err error) { - err = vk.RequestUnmarshal("stories.save", params, &response) + err = vk.RequestUnmarshal("stories.save", &response, params) return } @@ -270,8 +262,7 @@ type StoriesSearchResponse struct { // // https://vk.com/dev/stories.search func (vk *VK) StoriesSearch(params Params) (response StoriesSearchResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("stories.search", params, &response) + err = vk.RequestUnmarshal("stories.search", &response, params, Params{"extended": false}) return } @@ -289,8 +280,7 @@ type StoriesSearchExtendedResponse struct { // // https://vk.com/dev/stories.search func (vk *VK) StoriesSearchExtended(params Params) (response StoriesSearchExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("stories.search", params, &response) + err = vk.RequestUnmarshal("stories.search", &response, params, Params{"extended": true}) return } @@ -302,7 +292,7 @@ func (vk *VK) StoriesSearchExtended(params Params) (response StoriesSearchExtend // // https://vk.com/dev/stories.sendInteraction func (vk *VK) StoriesSendInteraction(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stories.sendInteraction", params, &response) + err = vk.RequestUnmarshal("stories.sendInteraction", &response, params) return } @@ -310,6 +300,6 @@ func (vk *VK) StoriesSendInteraction(params Params) (response int, err error) { // // https://vk.com/dev/stories.unbanOwner func (vk *VK) StoriesUnbanOwner(params Params) (response int, err error) { - err = vk.RequestUnmarshal("stories.unbanOwner", params, &response) + err = vk.RequestUnmarshal("stories.unbanOwner", &response, params) return } diff --git a/api/stories_test.go b/api/stories_test.go index 56df2471..e208fa86 100644 --- a/api/stories_test.go +++ b/api/stories_test.go @@ -18,12 +18,12 @@ func TestVK_StoriesBanOwner(t *testing.T) { }) noError(t, err) - banned, err := vkUser.StoriesGetBanned(api.Params{}) + banned, err := vkUser.StoriesGetBanned(nil) noError(t, err) assert.NotEmpty(t, banned.Count) assert.NotEmpty(t, banned.Items) - bannedEx, err := vkUser.StoriesGetBannedExtended(api.Params{}) + bannedEx, err := vkUser.StoriesGetBannedExtended(nil) noError(t, err) assert.NotEmpty(t, bannedEx.Count) assert.NotEmpty(t, bannedEx.Items) @@ -41,7 +41,7 @@ func TestVK_StoriesGet(t *testing.T) { needUserToken(t) - _, err := vkUser.StoriesGet(api.Params{}) + _, err := vkUser.StoriesGet(nil) noError(t, err) } @@ -50,7 +50,7 @@ func TestVK_StoriesGetExtended(t *testing.T) { needUserToken(t) - _, err := vkUser.StoriesGetExtended(api.Params{}) + _, err := vkUser.StoriesGetExtended(nil) noError(t, err) } diff --git a/api/streaming.go b/api/streaming.go index 43838c39..2267a826 100644 --- a/api/streaming.go +++ b/api/streaming.go @@ -10,7 +10,7 @@ type StreamingGetServerURLResponse struct { // // https://vk.com/dev/streaming.getServerUrl func (vk *VK) StreamingGetServerURL(params Params) (response StreamingGetServerURLResponse, err error) { - err = vk.RequestUnmarshal("streaming.getServerUrl", params, &response) + err = vk.RequestUnmarshal("streaming.getServerUrl", &response, params) return } @@ -23,7 +23,7 @@ type StreamingGetSettingsResponse struct { // // https://vk.com/dev/streaming.getSettings func (vk *VK) StreamingGetSettings(params Params) (response StreamingGetSettingsResponse, err error) { - err = vk.RequestUnmarshal("streaming.getSettings", params, &response) + err = vk.RequestUnmarshal("streaming.getSettings", &response, params) return } @@ -40,7 +40,7 @@ type StreamingGetStatsResponse []struct { // // https://vk.com/dev/streaming.getStats func (vk *VK) StreamingGetStats(params Params) (response StreamingGetStatsResponse, err error) { - err = vk.RequestUnmarshal("streaming.getStats", params, &response) + err = vk.RequestUnmarshal("streaming.getStats", &response, params) return } @@ -53,7 +53,7 @@ type StreamingGetStemResponse struct { // // https://vk.com/dev/streaming.getStem func (vk *VK) StreamingGetStem(params Params) (response StreamingGetStemResponse, err error) { - err = vk.RequestUnmarshal("streaming.getStem", params, &response) + err = vk.RequestUnmarshal("streaming.getStem", &response, params) return } @@ -61,7 +61,7 @@ func (vk *VK) StreamingGetStem(params Params) (response StreamingGetStemResponse // // https://vk.com/dev/streaming.setSettings func (vk *VK) StreamingSetSettings(params Params) (response int, err error) { - err = vk.RequestUnmarshal("streaming.setSettings", params, &response) + err = vk.RequestUnmarshal("streaming.setSettings", &response, params) return } diff --git a/api/streaming_test.go b/api/streaming_test.go index 489af91f..c6f4f23d 100644 --- a/api/streaming_test.go +++ b/api/streaming_test.go @@ -13,7 +13,7 @@ func TestVK_StreamingGetServerURL(t *testing.T) { needServiceToken(t) t.Run("StreamingGetServerURL not empty", func(t *testing.T) { - response, err := vkService.StreamingGetServerURL(api.Params{}) + response, err := vkService.StreamingGetServerURL(nil) if err != nil { t.Errorf("%v", err) } @@ -33,7 +33,7 @@ func TestVK_StreamingGetSettings(t *testing.T) { needServiceToken(t) t.Run("StreamingGetSettings not empty", func(t *testing.T) { - response, err := vkService.StreamingGetSettings(api.Params{}) + response, err := vkService.StreamingGetSettings(nil) if err != nil { t.Errorf("%v", err) } @@ -112,35 +112,35 @@ func TestVK_StreamingError(t *testing.T) { vk := api.NewVK("") t.Run("StreamingGetServerURL error", func(t *testing.T) { - _, err := vk.StreamingGetServerURL(api.Params{}) + _, err := vk.StreamingGetServerURL(nil) if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetServerURL error bad %v", err) } }) t.Run("StreamingGetSettings error", func(t *testing.T) { - _, err := vk.StreamingGetSettings(api.Params{}) + _, err := vk.StreamingGetSettings(nil) if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetSettings error bad %v", err) } }) t.Run("StreamingGetStats error", func(t *testing.T) { - _, err := vk.StreamingGetStats(api.Params{}) + _, err := vk.StreamingGetStats(nil) if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetStats error bad %v", err) } }) t.Run("StreamingGetStem error", func(t *testing.T) { - _, err := vk.StreamingGetStem(api.Params{}) + _, err := vk.StreamingGetStem(nil) if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingGetStem error bad %v", err) } }) t.Run("StreamingSetSettings error", func(t *testing.T) { - _, err := vk.StreamingSetSettings(api.Params{}) + _, err := vk.StreamingSetSettings(nil) if !errors.Is(err, api.ErrAuth) { t.Errorf("StreamingSetSettings error bad %v", err) } diff --git a/api/upload.go b/api/upload.go index a199082d..dda23af9 100644 --- a/api/upload.go +++ b/api/upload.go @@ -561,7 +561,7 @@ func (vk *VK) uploadDoc(url, title, tags string, file io.Reader) (response DocsS // // Limits: file size up to 200 MB. func (vk *VK) UploadDoc(title, tags string, file io.Reader) (response DocsSaveResponse, err error) { - uploadServer, err := vk.DocsGetUploadServer(Params{}) + uploadServer, err := vk.DocsGetUploadServer(nil) if err != nil { return } @@ -595,7 +595,7 @@ func (vk *VK) UploadGroupDoc(groupID int, title, tags string, file io.Reader) (r // // Limits: file size up to 200 MB. func (vk *VK) UploadWallDoc(title, tags string, file io.Reader) (response DocsSaveResponse, err error) { - uploadServer, err := vk.DocsGetWallUploadServer(Params{}) + uploadServer, err := vk.DocsGetWallUploadServer(nil) if err != nil { return } @@ -841,7 +841,7 @@ type uploadPrettyCardsPhotoHandler struct { // // Supported formats: JPG, PNG, GIF. func (vk *VK) UploadPrettyCardsPhoto(file io.Reader) (response string, err error) { - uploadURL, err := vk.PrettyCardsGetUploadURL(Params{}) + uploadURL, err := vk.PrettyCardsGetUploadURL(nil) if err != nil { return } @@ -876,7 +876,7 @@ type uploadLeadFormsPhotoHandler struct { // // Supported formats: JPG, PNG, GIF. func (vk *VK) UploadLeadFormsPhoto(file io.Reader) (response string, err error) { - uploadURL, err := vk.LeadFormsGetUploadURL(Params{}) + uploadURL, err := vk.LeadFormsGetUploadURL(nil) if err != nil { return } diff --git a/api/users.go b/api/users.go index 30f3508d..e7063feb 100644 --- a/api/users.go +++ b/api/users.go @@ -11,7 +11,7 @@ type UsersGetResponse []object.UsersUser // // https://vk.com/dev/users.get func (vk *VK) UsersGet(params Params) (response UsersGetResponse, err error) { - err = vk.RequestUnmarshal("users.get", params, &response) + err = vk.RequestUnmarshal("users.get", &response, params) return } @@ -28,8 +28,7 @@ type UsersGetFollowersResponse struct { // // https://vk.com/dev/users.getFollowers func (vk *VK) UsersGetFollowers(params Params) (response UsersGetFollowersResponse, err error) { - params["fields"] = "" - err = vk.RequestUnmarshal("users.getFollowers", params, &response) + err = vk.RequestUnmarshal("users.getFollowers", &response, params, Params{"fields": ""}) return } @@ -47,11 +46,12 @@ type UsersGetFollowersFieldsResponse struct { // // https://vk.com/dev/users.getFollowers func (vk *VK) UsersGetFollowersFields(params Params) (response UsersGetFollowersFieldsResponse, err error) { + reqParams := make(Params) if v, prs := params["fields"]; v == "" || !prs { - params["fields"] = "id" + reqParams["fields"] = "id" } - err = vk.RequestUnmarshal("users.getFollowers", params, &response) + err = vk.RequestUnmarshal("users.getFollowers", &response, params, reqParams) return } @@ -76,8 +76,7 @@ type UsersGetSubscriptionsResponse struct { // // BUG(SevereCloud): UsersGetSubscriptions bad response with extended=1. func (vk *VK) UsersGetSubscriptions(params Params) (response UsersGetSubscriptionsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("users.getSubscriptions", params, &response) + err = vk.RequestUnmarshal("users.getSubscriptions", &response, params, Params{"extended": false}) return } @@ -86,7 +85,7 @@ func (vk *VK) UsersGetSubscriptions(params Params) (response UsersGetSubscriptio // // https://vk.com/dev/users.report func (vk *VK) UsersReport(params Params) (response int, err error) { - err = vk.RequestUnmarshal("users.report", params, &response) + err = vk.RequestUnmarshal("users.report", &response, params) return } @@ -100,6 +99,6 @@ type UsersSearchResponse struct { // // https://vk.com/dev/users.search func (vk *VK) UsersSearch(params Params) (response UsersSearchResponse, err error) { - err = vk.RequestUnmarshal("users.search", params, &response) + err = vk.RequestUnmarshal("users.search", &response, params) return } diff --git a/api/utils.go b/api/utils.go index e4937de9..0e4ebd34 100644 --- a/api/utils.go +++ b/api/utils.go @@ -13,7 +13,7 @@ type UtilsCheckLinkResponse object.UtilsLinkChecked // // https://vk.com/dev/utils.checkLink func (vk *VK) UtilsCheckLink(params Params) (response UtilsCheckLinkResponse, err error) { - err = vk.RequestUnmarshal("utils.checkLink", params, &response) + err = vk.RequestUnmarshal("utils.checkLink", &response, params) return } @@ -21,7 +21,7 @@ func (vk *VK) UtilsCheckLink(params Params) (response UtilsCheckLinkResponse, er // // https://vk.com/dev/utils.deleteFromLastShortened func (vk *VK) UtilsDeleteFromLastShortened(params Params) (response int, err error) { - err = vk.RequestUnmarshal("utils.deleteFromLastShortened", params, &response) + err = vk.RequestUnmarshal("utils.deleteFromLastShortened", &response, params) return } @@ -35,7 +35,7 @@ type UtilsGetLastShortenedLinksResponse struct { // // https://vk.com/dev/utils.getLastShortenedLinks func (vk *VK) UtilsGetLastShortenedLinks(params Params) (response UtilsGetLastShortenedLinksResponse, err error) { - err = vk.RequestUnmarshal("utils.getLastShortenedLinks", params, &response) + err = vk.RequestUnmarshal("utils.getLastShortenedLinks", &response, params) return } @@ -48,8 +48,7 @@ type UtilsGetLinkStatsResponse object.UtilsLinkStats // // https://vk.com/dev/utils.getLinkStats func (vk *VK) UtilsGetLinkStats(params Params) (response UtilsGetLinkStatsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("utils.getLinkStats", params, &response) + err = vk.RequestUnmarshal("utils.getLinkStats", &response, params, Params{"extended": false}) return } @@ -63,8 +62,7 @@ type UtilsGetLinkStatsExtendedResponse object.UtilsLinkStatsExtended // // https://vk.com/dev/utils.getLinkStats func (vk *VK) UtilsGetLinkStatsExtended(params Params) (response UtilsGetLinkStatsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("utils.getLinkStats", params, &response) + err = vk.RequestUnmarshal("utils.getLinkStats", &response, params, Params{"extended": true}) return } @@ -73,7 +71,7 @@ func (vk *VK) UtilsGetLinkStatsExtended(params Params) (response UtilsGetLinkSta // // https://vk.com/dev/utils.getServerTime func (vk *VK) UtilsGetServerTime(params Params) (response int, err error) { - err = vk.RequestUnmarshal("utils.getServerTime", params, &response) + err = vk.RequestUnmarshal("utils.getServerTime", &response, params) return } @@ -84,7 +82,7 @@ type UtilsGetShortLinkResponse object.UtilsShortLink // // https://vk.com/dev/utils.getShortLink func (vk *VK) UtilsGetShortLink(params Params) (response UtilsGetShortLinkResponse, err error) { - err = vk.RequestUnmarshal("utils.getShortLink", params, &response) + err = vk.RequestUnmarshal("utils.getShortLink", &response, params) return } diff --git a/api/utils_test.go b/api/utils_test.go index 0faeee9e..74fb466c 100644 --- a/api/utils_test.go +++ b/api/utils_test.go @@ -33,7 +33,7 @@ func TestVK_UtilsGetShortLink(t *testing.T) { noError(t, err) assert.NotEmpty(t, shortLink) - res, err := vkUser.UtilsGetLastShortenedLinks(api.Params{}) + res, err := vkUser.UtilsGetLastShortenedLinks(nil) noError(t, err) assert.NotEmpty(t, res.Count) assert.NotEmpty(t, res.Items) @@ -73,7 +73,7 @@ func TestVK_UtilsGetServerTime(t *testing.T) { needGroupToken(t) - res, err := vkGroup.UtilsGetServerTime(api.Params{}) + res, err := vkGroup.UtilsGetServerTime(nil) noError(t, err) assert.NotEmpty(t, res) } diff --git a/api/video.go b/api/video.go index f3680708..a537cdd0 100644 --- a/api/video.go +++ b/api/video.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/video.add func (vk *VK) VideoAdd(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.add", params, &response) + err = vk.RequestUnmarshal("video.add", &response, params) return } @@ -21,7 +21,7 @@ type VideoAddAlbumResponse struct { // // https://vk.com/dev/video.addAlbum func (vk *VK) VideoAddAlbum(params Params) (response VideoAddAlbumResponse, err error) { - err = vk.RequestUnmarshal("video.addAlbum", params, &response) + err = vk.RequestUnmarshal("video.addAlbum", &response, params) return } @@ -29,7 +29,7 @@ func (vk *VK) VideoAddAlbum(params Params) (response VideoAddAlbumResponse, err // // https://vk.com/dev/video.addToAlbum func (vk *VK) VideoAddToAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.addToAlbum", params, &response) + err = vk.RequestUnmarshal("video.addToAlbum", &response, params) return } @@ -37,7 +37,7 @@ func (vk *VK) VideoAddToAlbum(params Params) (response int, err error) { // // https://vk.com/dev/video.createComment func (vk *VK) VideoCreateComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.createComment", params, &response) + err = vk.RequestUnmarshal("video.createComment", &response, params) return } @@ -45,7 +45,7 @@ func (vk *VK) VideoCreateComment(params Params) (response int, err error) { // // https://vk.com/dev/video.delete func (vk *VK) VideoDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.delete", params, &response) + err = vk.RequestUnmarshal("video.delete", &response, params) return } @@ -53,7 +53,7 @@ func (vk *VK) VideoDelete(params Params) (response int, err error) { // // https://vk.com/dev/video.deleteAlbum func (vk *VK) VideoDeleteAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.deleteAlbum", params, &response) + err = vk.RequestUnmarshal("video.deleteAlbum", &response, params) return } @@ -61,7 +61,7 @@ func (vk *VK) VideoDeleteAlbum(params Params) (response int, err error) { // // https://vk.com/dev/video.deleteComment func (vk *VK) VideoDeleteComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.deleteComment", params, &response) + err = vk.RequestUnmarshal("video.deleteComment", &response, params) return } @@ -69,7 +69,7 @@ func (vk *VK) VideoDeleteComment(params Params) (response int, err error) { // // https://vk.com/dev/video.edit func (vk *VK) VideoEdit(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.edit", params, &response) + err = vk.RequestUnmarshal("video.edit", &response, params) return } @@ -77,7 +77,7 @@ func (vk *VK) VideoEdit(params Params) (response int, err error) { // // https://vk.com/dev/video.editAlbum func (vk *VK) VideoEditAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.editAlbum", params, &response) + err = vk.RequestUnmarshal("video.editAlbum", &response, params) return } @@ -85,7 +85,7 @@ func (vk *VK) VideoEditAlbum(params Params) (response int, err error) { // // https://vk.com/dev/video.editComment func (vk *VK) VideoEditComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.editComment", params, &response) + err = vk.RequestUnmarshal("video.editComment", &response, params) return } @@ -101,8 +101,7 @@ type VideoGetResponse struct { // // https://vk.com/dev/video.get func (vk *VK) VideoGet(params Params) (response VideoGetResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("video.get", params, &response) + err = vk.RequestUnmarshal("video.get", &response, params, Params{"extended": false}) return } @@ -120,8 +119,7 @@ type VideoGetExtendedResponse struct { // // https://vk.com/dev/video.get func (vk *VK) VideoGetExtended(params Params) (response VideoGetExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("video.get", params, &response) + err = vk.RequestUnmarshal("video.get", &response, params, Params{"extended": true}) return } @@ -133,7 +131,7 @@ type VideoGetAlbumByIDResponse object.VideoVideoAlbumFull // // https://vk.com/dev/video.getAlbumById func (vk *VK) VideoGetAlbumByID(params Params) (response VideoGetAlbumByIDResponse, err error) { - err = vk.RequestUnmarshal("video.getAlbumById", params, &response) + err = vk.RequestUnmarshal("video.getAlbumById", &response, params) return } @@ -149,8 +147,7 @@ type VideoGetAlbumsResponse struct { // // https://vk.com/dev/video.getAlbums func (vk *VK) VideoGetAlbums(params Params) (response VideoGetAlbumsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("video.getAlbums", params, &response) + err = vk.RequestUnmarshal("video.getAlbums", &response, params, Params{"extended": false}) return } @@ -167,8 +164,7 @@ type VideoGetAlbumsExtendedResponse struct { // // https://vk.com/dev/video.getAlbums func (vk *VK) VideoGetAlbumsExtended(params Params) (response VideoGetAlbumsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("video.getAlbums", params, &response) + err = vk.RequestUnmarshal("video.getAlbums", &response, params, Params{"extended": true}) return } @@ -182,8 +178,7 @@ type VideoGetAlbumsByVideoResponse []int // // https://vk.com/dev/video.getAlbumsByVideo func (vk *VK) VideoGetAlbumsByVideo(params Params) (response VideoGetAlbumsByVideoResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("video.getAlbumsByVideo", params, &response) + err = vk.RequestUnmarshal("video.getAlbumsByVideo", &response, params, Params{"extended": false}) return } @@ -200,8 +195,7 @@ type VideoGetAlbumsByVideoExtendedResponse struct { // // https://vk.com/dev/video.getAlbumsByVideo func (vk *VK) VideoGetAlbumsByVideoExtended(params Params) (response VideoGetAlbumsByVideoExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("video.getAlbumsByVideo", params, &response) + err = vk.RequestUnmarshal("video.getAlbumsByVideo", &response, params, Params{"extended": true}) return } @@ -218,8 +212,7 @@ type VideoGetCommentsResponse struct { // // https://vk.com/dev/video.getComments func (vk *VK) VideoGetComments(params Params) (response VideoGetCommentsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("video.getComments", params, &response) + err = vk.RequestUnmarshal("video.getComments", &response, params, Params{"extended": false}) return } @@ -237,8 +230,7 @@ type VideoGetCommentsExtendedResponse struct { // // https://vk.com/dev/video.getComments func (vk *VK) VideoGetCommentsExtended(params Params) (response VideoGetCommentsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("video.getComments", params, &response) + err = vk.RequestUnmarshal("video.getComments", &response, params, Params{"extended": true}) return } @@ -247,7 +239,7 @@ func (vk *VK) VideoGetCommentsExtended(params Params) (response VideoGetComments // // https://vk.com/dev/video.removeFromAlbum func (vk *VK) VideoRemoveFromAlbum(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.removeFromAlbum", params, &response) + err = vk.RequestUnmarshal("video.removeFromAlbum", &response, params) return } @@ -255,7 +247,7 @@ func (vk *VK) VideoRemoveFromAlbum(params Params) (response int, err error) { // // https://vk.com/dev/video.reorderAlbums func (vk *VK) VideoReorderAlbums(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.reorderAlbums", params, &response) + err = vk.RequestUnmarshal("video.reorderAlbums", &response, params) return } @@ -263,7 +255,7 @@ func (vk *VK) VideoReorderAlbums(params Params) (response int, err error) { // // https://vk.com/dev/video.reorderVideos func (vk *VK) VideoReorderVideos(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.reorderVideos", params, &response) + err = vk.RequestUnmarshal("video.reorderVideos", &response, params) return } @@ -271,7 +263,7 @@ func (vk *VK) VideoReorderVideos(params Params) (response int, err error) { // // https://vk.com/dev/video.report func (vk *VK) VideoReport(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.report", params, &response) + err = vk.RequestUnmarshal("video.report", &response, params) return } @@ -279,7 +271,7 @@ func (vk *VK) VideoReport(params Params) (response int, err error) { // // https://vk.com/dev/video.reportComment func (vk *VK) VideoReportComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.reportComment", params, &response) + err = vk.RequestUnmarshal("video.reportComment", &response, params) return } @@ -287,7 +279,7 @@ func (vk *VK) VideoReportComment(params Params) (response int, err error) { // // https://vk.com/dev/video.restore func (vk *VK) VideoRestore(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.restore", params, &response) + err = vk.RequestUnmarshal("video.restore", &response, params) return } @@ -295,7 +287,7 @@ func (vk *VK) VideoRestore(params Params) (response int, err error) { // // https://vk.com/dev/video.restoreComment func (vk *VK) VideoRestoreComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("video.restoreComment", params, &response) + err = vk.RequestUnmarshal("video.restoreComment", &response, params) return } @@ -306,7 +298,7 @@ type VideoSaveResponse object.VideoSaveResult // // https://vk.com/dev/video.save func (vk *VK) VideoSave(params Params) (response VideoSaveResponse, err error) { - err = vk.RequestUnmarshal("video.save", params, &response) + err = vk.RequestUnmarshal("video.save", &response, params) return } @@ -322,8 +314,7 @@ type VideoSearchResponse struct { // // https://vk.com/dev/video.search func (vk *VK) VideoSearch(params Params) (response VideoSearchResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("video.search", params, &response) + err = vk.RequestUnmarshal("video.search", &response, params, Params{"extended": false}) return } @@ -341,8 +332,7 @@ type VideoSearchExtendedResponse struct { // // https://vk.com/dev/video.search func (vk *VK) VideoSearchExtended(params Params) (response VideoSearchExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("video.search", params, &response) + err = vk.RequestUnmarshal("video.search", &response, params, Params{"extended": true}) return } diff --git a/api/wall.go b/api/wall.go index 78edc967..dbd289ed 100644 --- a/api/wall.go +++ b/api/wall.go @@ -8,7 +8,7 @@ import ( // // https://vk.com/dev/wall.closeComments func (vk *VK) WallCloseComments(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.closeComments", params, &response) + err = vk.RequestUnmarshal("wall.closeComments", &response, params) return } @@ -22,7 +22,7 @@ type WallCreateCommentResponse struct { // // https://vk.com/dev/wall.createComment func (vk *VK) WallCreateComment(params Params) (response WallCreateCommentResponse, err error) { - err = vk.RequestUnmarshal("wall.createComment", params, &response) + err = vk.RequestUnmarshal("wall.createComment", &response, params) return } @@ -30,7 +30,7 @@ func (vk *VK) WallCreateComment(params Params) (response WallCreateCommentRespon // // https://vk.com/dev/wall.delete func (vk *VK) WallDelete(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.delete", params, &response) + err = vk.RequestUnmarshal("wall.delete", &response, params) return } @@ -38,7 +38,7 @@ func (vk *VK) WallDelete(params Params) (response int, err error) { // // https://vk.com/dev/wall.deleteComment func (vk *VK) WallDeleteComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.deleteComment", params, &response) + err = vk.RequestUnmarshal("wall.deleteComment", &response, params) return } @@ -51,7 +51,7 @@ type WallEditResponse struct { // // https://vk.com/dev/wall.edit func (vk *VK) WallEdit(params Params) (response WallEditResponse, err error) { - err = vk.RequestUnmarshal("wall.edit", params, &response) + err = vk.RequestUnmarshal("wall.edit", &response, params) return } @@ -59,7 +59,7 @@ func (vk *VK) WallEdit(params Params) (response WallEditResponse, err error) { // // https://vk.com/dev/wall.editAdsStealth func (vk *VK) WallEditAdsStealth(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.editAdsStealth", params, &response) + err = vk.RequestUnmarshal("wall.editAdsStealth", &response, params) return } @@ -67,7 +67,7 @@ func (vk *VK) WallEditAdsStealth(params Params) (response int, err error) { // // https://vk.com/dev/wall.editComment func (vk *VK) WallEditComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.editComment", params, &response) + err = vk.RequestUnmarshal("wall.editComment", &response, params) return } @@ -83,8 +83,7 @@ type WallGetResponse struct { // // https://vk.com/dev/wall.get func (vk *VK) WallGet(params Params) (response WallGetResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("wall.get", params, &response) + err = vk.RequestUnmarshal("wall.get", &response, params, Params{"extended": false}) return } @@ -102,8 +101,7 @@ type WallGetExtendedResponse struct { // // https://vk.com/dev/wall.get func (vk *VK) WallGetExtended(params Params) (response WallGetExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("wall.get", params, &response) + err = vk.RequestUnmarshal("wall.get", &response, params, Params{"extended": true}) return } @@ -117,8 +115,7 @@ type WallGetByIDResponse []object.WallWallpost // // https://vk.com/dev/wall.getById func (vk *VK) WallGetByID(params Params) (response WallGetByIDResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("wall.getById", params, &response) + err = vk.RequestUnmarshal("wall.getById", &response, params, Params{"extended": false}) return } @@ -135,8 +132,7 @@ type WallGetByIDExtendedResponse struct { // // https://vk.com/dev/wall.getById func (vk *VK) WallGetByIDExtended(params Params) (response WallGetByIDExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("wall.getById", params, &response) + err = vk.RequestUnmarshal("wall.getById", &response, params, Params{"extended": true}) return } @@ -156,8 +152,7 @@ type WallGetCommentResponse struct { // // https://vk.com/dev/wall.getComment func (vk *VK) WallGetComment(params Params) (response WallGetCommentResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("wall.getComment", params, &response) + err = vk.RequestUnmarshal("wall.getComment", &response, params, Params{"extended": false}) return } @@ -180,8 +175,7 @@ type WallGetCommentExtendedResponse struct { // // https://vk.com/dev/wall.getComment func (vk *VK) WallGetCommentExtended(params Params) (response WallGetCommentExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("wall.getComment", params, &response) + err = vk.RequestUnmarshal("wall.getComment", &response, params, Params{"extended": true}) return } @@ -202,8 +196,7 @@ type WallGetCommentsResponse struct { // // https://vk.com/dev/wall.getComments func (vk *VK) WallGetComments(params Params) (response WallGetCommentsResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("wall.getComments", params, &response) + err = vk.RequestUnmarshal("wall.getComments", &response, params, Params{"extended": false}) return } @@ -225,8 +218,7 @@ type WallGetCommentsExtendedResponse struct { // // https://vk.com/dev/wall.getComments func (vk *VK) WallGetCommentsExtended(params Params) (response WallGetCommentsExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("wall.getComments", params, &response) + err = vk.RequestUnmarshal("wall.getComments", &response, params, Params{"extended": true}) return } @@ -241,7 +233,7 @@ type WallGetRepostsResponse struct { // // https://vk.com/dev/wall.getReposts func (vk *VK) WallGetReposts(params Params) (response WallGetRepostsResponse, err error) { - err = vk.RequestUnmarshal("wall.getReposts", params, &response) + err = vk.RequestUnmarshal("wall.getReposts", &response, params) return } @@ -249,7 +241,7 @@ func (vk *VK) WallGetReposts(params Params) (response WallGetRepostsResponse, er // // https://vk.com/dev/wall.openComments func (vk *VK) WallOpenComments(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.openComments", params, &response) + err = vk.RequestUnmarshal("wall.openComments", &response, params) return } @@ -257,7 +249,7 @@ func (vk *VK) WallOpenComments(params Params) (response int, err error) { // // https://vk.com/dev/wall.pin func (vk *VK) WallPin(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.pin", params, &response) + err = vk.RequestUnmarshal("wall.pin", &response, params) return } @@ -270,7 +262,7 @@ type WallPostResponse struct { // // https://vk.com/dev/wall.post func (vk *VK) WallPost(params Params) (response WallPostResponse, err error) { - err = vk.RequestUnmarshal("wall.post", params, &response) + err = vk.RequestUnmarshal("wall.post", &response, params) return } @@ -285,7 +277,7 @@ type WallPostAdsStealthResponse struct { // // https://vk.com/dev/wall.postAdsStealth func (vk *VK) WallPostAdsStealth(params Params) (response WallPostAdsStealthResponse, err error) { - err = vk.RequestUnmarshal("wall.postAdsStealth", params, &response) + err = vk.RequestUnmarshal("wall.postAdsStealth", &response, params) return } @@ -293,7 +285,7 @@ func (vk *VK) WallPostAdsStealth(params Params) (response WallPostAdsStealthResp // // https://vk.com/dev/wall.reportComment func (vk *VK) WallReportComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.reportComment", params, &response) + err = vk.RequestUnmarshal("wall.reportComment", &response, params) return } @@ -301,7 +293,7 @@ func (vk *VK) WallReportComment(params Params) (response int, err error) { // // https://vk.com/dev/wall.reportPost func (vk *VK) WallReportPost(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.reportPost", params, &response) + err = vk.RequestUnmarshal("wall.reportPost", &response, params) return } @@ -317,7 +309,7 @@ type WallRepostResponse struct { // // https://vk.com/dev/wall.repost func (vk *VK) WallRepost(params Params) (response WallRepostResponse, err error) { - err = vk.RequestUnmarshal("wall.repost", params, &response) + err = vk.RequestUnmarshal("wall.repost", &response, params) return } @@ -325,7 +317,7 @@ func (vk *VK) WallRepost(params Params) (response WallRepostResponse, err error) // // https://vk.com/dev/wall.restore func (vk *VK) WallRestore(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.restore", params, &response) + err = vk.RequestUnmarshal("wall.restore", &response, params) return } @@ -333,7 +325,7 @@ func (vk *VK) WallRestore(params Params) (response int, err error) { // // https://vk.com/dev/wall.restoreComment func (vk *VK) WallRestoreComment(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.restoreComment", params, &response) + err = vk.RequestUnmarshal("wall.restoreComment", &response, params) return } @@ -349,8 +341,7 @@ type WallSearchResponse struct { // // https://vk.com/dev/wall.search func (vk *VK) WallSearch(params Params) (response WallSearchResponse, err error) { - params["extended"] = false - err = vk.RequestUnmarshal("wall.search", params, &response) + err = vk.RequestUnmarshal("wall.search", &response, params, Params{"extended": false}) return } @@ -368,8 +359,7 @@ type WallSearchExtendedResponse struct { // // https://vk.com/dev/wall.search func (vk *VK) WallSearchExtended(params Params) (response WallSearchExtendedResponse, err error) { - params["extended"] = true - err = vk.RequestUnmarshal("wall.search", params, &response) + err = vk.RequestUnmarshal("wall.search", &response, params, Params{"extended": true}) return } @@ -378,6 +368,6 @@ func (vk *VK) WallSearchExtended(params Params) (response WallSearchExtendedResp // // https://vk.com/dev/wall.unpin func (vk *VK) WallUnpin(params Params) (response int, err error) { - err = vk.RequestUnmarshal("wall.unpin", params, &response) + err = vk.RequestUnmarshal("wall.unpin", &response, params) return } diff --git a/api/widgets.go b/api/widgets.go index f53cfe5a..695a619c 100644 --- a/api/widgets.go +++ b/api/widgets.go @@ -14,7 +14,7 @@ type WidgetsGetCommentsResponse struct { // // https://vk.com/dev/widgets.getComments func (vk *VK) WidgetsGetComments(params Params) (response WidgetsGetCommentsResponse, err error) { - err = vk.RequestUnmarshal("widgets.getComments", params, &response) + err = vk.RequestUnmarshal("widgets.getComments", &response, params) return } @@ -28,6 +28,6 @@ type WidgetsGetPagesResponse struct { // // https://vk.com/dev/widgets.getPages func (vk *VK) WidgetsGetPages(params Params) (response WidgetsGetPagesResponse, err error) { - err = vk.RequestUnmarshal("widgets.getPages", params, &response) + err = vk.RequestUnmarshal("widgets.getPages", &response, params) return } diff --git a/api/widgets_test.go b/api/widgets_test.go index 31bd2ee1..140b309d 100644 --- a/api/widgets_test.go +++ b/api/widgets_test.go @@ -41,7 +41,7 @@ func TestVK_WidgetsGetPages(t *testing.T) { needServiceToken(t) - res, err := vkService.WidgetsGetPages(api.Params{}) + res, err := vkService.WidgetsGetPages(nil) noError(t, err) assert.NotEmpty(t, res) } diff --git a/longpoll-bot/longpoll.go b/longpoll-bot/longpoll.go index c33a8cb0..24ebfdf3 100644 --- a/longpoll-bot/longpoll.go +++ b/longpoll-bot/longpoll.go @@ -66,7 +66,7 @@ func NewLongpoll(vk *api.VK, groupID int) (*Longpoll, error) { // This means that if the http.DefaultClient is modified by other components // of your application the modifications will be picked up by the SDK as well. func NewLongpollCommunity(vk *api.VK) (*Longpoll, error) { - resp, err := vk.GroupsGetByID(api.Params{}) + resp, err := vk.GroupsGetByID(nil) if err != nil { return nil, err } diff --git a/longpoll-user/v3/wrapper_test.go b/longpoll-user/v3/wrapper_test.go index 0d94cfd6..6d827fbf 100644 --- a/longpoll-user/v3/wrapper_test.go +++ b/longpoll-user/v3/wrapper_test.go @@ -51,7 +51,7 @@ func TestMain(m *testing.M) { vkUser.Limit = 3 if vkUser.AccessToken != "" { - user, err := vkUser.UsersGet(api.Params{}) + user, err := vkUser.UsersGet(nil) if err != nil { log.Fatalf("USER_TOKEN bad: %v", err) } diff --git a/streaming/streaming.go b/streaming/streaming.go index 35746dbf..cc8e5520 100644 --- a/streaming/streaming.go +++ b/streaming/streaming.go @@ -357,7 +357,7 @@ func (s *Streaming) Shutdown() { // This means that if the http.DefaultClient is modified by other components // of your application the modifications will be picked up by the SDK as well. func NewStreaming(vk *api.VK) (*Streaming, error) { - resp, err := vk.StreamingGetServerURL(api.Params{}) + resp, err := vk.StreamingGetServerURL(nil) if err != nil { return nil, err } From cc94f70bb06d2f4a9f31070384b93dd10db58930 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Mon, 31 Aug 2020 22:50:38 +0300 Subject: [PATCH 094/105] feat: likes.add add ReactionID parameter --- api/params/likes.go | 6 ++++++ api/params/likes_test.go | 2 ++ 2 files changed, 8 insertions(+) diff --git a/api/params/likes.go b/api/params/likes.go index e4035265..036da8e6 100644 --- a/api/params/likes.go +++ b/api/params/likes.go @@ -56,6 +56,12 @@ func (b *LikesAddBuilder) ItemID(v int) *LikesAddBuilder { return b } +// ReactionID parameter. +func (b *LikesAddBuilder) ReactionID(v int) *LikesAddBuilder { + b.Params["reaction_id"] = v + return b +} + // AccessKey access key required for an object owned by a private entity. func (b *LikesAddBuilder) AccessKey(v string) *LikesAddBuilder { b.Params["access_key"] = v diff --git a/api/params/likes_test.go b/api/params/likes_test.go index 86cee8e8..b4ec9714 100644 --- a/api/params/likes_test.go +++ b/api/params/likes_test.go @@ -15,11 +15,13 @@ func TestLikesAddBuilder(t *testing.T) { b.Type("text") b.OwnerID(1) b.ItemID(1) + b.ReactionID(1) b.AccessKey("text") assert.Equal(t, b.Params["type"], "text") assert.Equal(t, b.Params["owner_id"], 1) assert.Equal(t, b.Params["item_id"], 1) + assert.Equal(t, b.Params["reaction_id"], 1) assert.Equal(t, b.Params["access_key"], "text") } From 222308404aec9c7cf82d58fa742266dd4fb13cde Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Thu, 3 Sep 2020 21:20:16 +0300 Subject: [PATCH 095/105] docs: fix errors --- api/README.md | 48 ++++++++++++++++++++++++++---------------------- api/api.go | 4 ++-- doc.go | 7 +++++-- 3 files changed, 33 insertions(+), 26 deletions(-) diff --git a/api/README.md b/api/README.md index e26b7ab9..61d1c199 100644 --- a/api/README.md +++ b/api/README.md @@ -52,34 +52,34 @@ res, err = api.MessageSend(b.Params) ### Обработка ошибок -[![документация](https://godoc.org/github.com/SevereCloud/vksdk/api/errors?status.svg)](https://pkg.go.dev/github.com/SevereCloud/vksdk/api/errors) [![VK](https://img.shields.io/badge/developers-%234a76a8.svg?logo=VK&logoColor=white)](https://vk.com/dev/errors) -Пример обработки ошибки +Обработка ошибок полностью поддерживает методы +[go 1.13](https://blog.golang.org/go1.13-errors) ```go -// import "github.com/SevereCloud/vksdk/api/errors" - -switch errors.GetType(err) { -case errors.NoType: - log.Print("Ошибка не связанная с работой самого API") -case errors.Captcha: - log.Print("Требуется ввод кода с картинки (Captcha)") -case 1: - log.Print("Код ошибки 1") -default: - log.Print("Другая ошибка") +if errors.Is(err, api.ErrAuth) { + log.Println("User authorization failed") } ``` -Получение ошибки, [отправленной ВК](https://pkg.go.dev/github.com/SevereCloud/vksdk/object#Error) - ```go -// import "github.com/SevereCloud/vksdk/api/errors" - -vkErr := errors.GetErrorContext(err) +var e *api.Error +if errors.As(err, &e) { + switch e.Code { + case api.ErrCaptcha: + log.Println("Требуется ввод кода с картинки (Captcha)") + log.Printf("sid %s img %s", e.CaptchaSID, e.CaptchaImg) + case 1: + log.Println("Код ошибки 1") + default: + log.Printf("Ошибка %d %s", e.Code, e.Text) + } +} ``` +Для Execute существует отдельная ошибка `ExecuteErrors` + ### Запрос любого метода Пример запроса [users.get](https://vk.com/dev/users.get) @@ -110,8 +110,6 @@ log.Print(response) Универсальный метод, который позволяет запускать последовательность других методов, сохраняя и фильтруя промежуточные результаты. -TODO: описать ошибки - ```go var response struct { Text string `json:"text"` @@ -131,7 +129,7 @@ log.Print(response.Text) В качестве параметров принимать название метода и параметры. ```go -vk.Handler = func(method string, params api.Params) (api.Response, error) { +vk.Handler = func(method string, params ...api.Params) (api.Response, error) { // ... } ``` @@ -174,12 +172,18 @@ vk.Handler = func(method string, params api.Params) (api.Response, error) { Пример прокси ```go + dialer, _ := proxy.SOCKS5("tcp", "127.0.0.1:9050", nil, proxy.Direct) httpTransport := &http.Transport{ Dial: dialer.Dial, } httpTransport.Dial = dialer.Dial -vk.Client.Transport = httpTransport + +client := &http.Client{ + Transport: httpTransport, +} + +vk.Client = client ``` ### Ошибка с Captcha diff --git a/api/api.go b/api/api.go index d7816b44..1ca486c1 100644 --- a/api/api.go +++ b/api/api.go @@ -16,13 +16,14 @@ import ( "sync" "time" + "github.com/SevereCloud/vksdk" "github.com/SevereCloud/vksdk/internal" "github.com/SevereCloud/vksdk/object" ) // Api constants. const ( - Version = "5.122" + Version = vksdk.API MethodURL = "https://api.vk.com/method/" ) @@ -120,7 +121,6 @@ func NewVK(token string) *VK { vk.Handler = vk.defaultHandler - // TODO: remove in v2 vk.MethodURL = MethodURL vk.Client = http.DefaultClient vk.Limit = LimitGroupToken diff --git a/doc.go b/doc.go index 51042fa1..f356e7b0 100644 --- a/doc.go +++ b/doc.go @@ -5,5 +5,8 @@ Source https://github.com/SevereCloud/vksdk */ package vksdk -// Version module. -const Version = "2.0.0" +// Module constants. +const ( + Version = "2.0.0" + API = "5.122" +) From 5598ce3426a67e3e987e4be5bb8b809e49a2dbd0 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Thu, 3 Sep 2020 22:24:34 +0300 Subject: [PATCH 096/105] BREAKING CHANGE: token pool in NewVK --- api/api.go | 40 +++++++++++++------------------- api/api_test.go | 31 +++++++++++++++---------- api/execute.go | 5 +--- internal/token_pool.go | 26 --------------------- internal/token_pool_test.go | 28 ---------------------- longpoll-user/v3/wrapper_test.go | 8 +++---- 6 files changed, 40 insertions(+), 98 deletions(-) delete mode 100644 internal/token_pool.go delete mode 100644 internal/token_pool_test.go diff --git a/api/api.go b/api/api.go index 1ca486c1..5557d29f 100644 --- a/api/api.go +++ b/api/api.go @@ -14,6 +14,7 @@ import ( "net/url" "reflect" "sync" + "sync/atomic" "time" "github.com/SevereCloud/vksdk" @@ -80,19 +81,18 @@ const ( // VK struct. type VK struct { + accessTokens []string + lastToken uint32 MethodURL string - AccessToken string Version string Client *http.Client - IsPoolClient bool Limit int UserAgent string Handler func(method string, params ...Params) (Response, error) - tokenPool internal.TokenPool - mux sync.Mutex - lastTime time.Time - rps int + mux sync.Mutex + lastTime time.Time + rps int } // Response struct. @@ -113,10 +113,11 @@ type Response struct { // your application. You can configure the VKSDK to use the custom // HTTP Client by setting the VK.Client value. // -// This set limit 20 requests per second. -func NewVK(token string) *VK { +// This set limit 20 requests per second for one token. +func NewVK(tokens ...string) *VK { var vk VK - vk.AccessToken = token + + vk.accessTokens = tokens vk.Version = Version vk.Handler = vk.defaultHandler @@ -125,20 +126,14 @@ func NewVK(token string) *VK { vk.Client = http.DefaultClient vk.Limit = LimitGroupToken vk.UserAgent = internal.UserAgent - vk.IsPoolClient = false return &vk } -// NewVKWithPool is similar to NewVK but uses token pool for api calls. -// Use this if you need to increase RPS limit. -func NewVKWithPool(tokens ...string) *VK { - vk := NewVK("pool") - vk.tokenPool = internal.NewTokenPool(tokens...) - vk.Limit = LimitGroupToken * len(tokens) - vk.IsPoolClient = true - - return vk +// getToken return next token (simple round-robin). +func (vk *VK) getToken() string { + i := atomic.AddUint32(&vk.lastToken, 1) + return vk.accessTokens[(int(i)-1)%len(vk.accessTokens)] } // Params type. @@ -214,7 +209,7 @@ func (vk *VK) defaultHandler(method string, sliceParams ...Params) (Response, er if sleepTime < 0 { vk.lastTime = time.Now() vk.rps = 0 - } else if vk.rps == vk.Limit { + } else if vk.rps == vk.Limit*len(vk.accessTokens) { time.Sleep(sleepTime) vk.lastTime = time.Now() vk.rps = 0 @@ -270,10 +265,7 @@ func (vk *VK) defaultHandler(method string, sliceParams ...Params) (Response, er // Request provides access to VK API methods. func (vk *VK) Request(method string, sliceParams ...Params) ([]byte, error) { - token := vk.AccessToken - if vk.IsPoolClient { - token = vk.tokenPool.Get() - } + token := vk.getToken() reqParams := Params{ "access_token": token, diff --git a/api/api_test.go b/api/api_test.go index e31f84ec..37295b44 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -47,7 +47,7 @@ func noError(t *testing.T, err error) bool { func needUserToken(t *testing.T) { t.Helper() - if vkUser.AccessToken == "" { + if vkUser == nil { t.Skip("USER_TOKEN empty") } } @@ -55,7 +55,7 @@ func needUserToken(t *testing.T) { func needGroupToken(t *testing.T) { t.Helper() - if vkGroup.AccessToken == "" { + if vkGroup == nil { t.Skip("GROUP_TOKEN empty") } } @@ -63,7 +63,7 @@ func needGroupToken(t *testing.T) { func needServiceToken(t *testing.T) { t.Helper() - if vkService.AccessToken == "" { + if vkService == nil { t.Skip("SERVICE_TOKEN empty") } } @@ -71,7 +71,7 @@ func needServiceToken(t *testing.T) { func needWidgetToken(t *testing.T) { t.Helper() - if vkWidget.AccessToken == "" { + if vkWidget == nil { t.Skip("WIDGET_TOKEN empty") } } @@ -104,8 +104,9 @@ var ( ) func TestMain(m *testing.M) { - vkGroup = api.NewVK(os.Getenv("GROUP_TOKEN")) - if vkGroup.AccessToken != "" { + if token := os.Getenv("GROUP_TOKEN"); token != "" { + vkGroup = api.NewVK(token) + group, err := vkGroup.GroupsGetByID(nil) if err != nil { log.Fatalf("GROUP_TOKEN bad: %v", err) @@ -114,13 +115,19 @@ func TestMain(m *testing.M) { vkGroupID = group[0].ID } - vkWidget = api.NewVK(os.Getenv("WIDGET_TOKEN")) - vkService = api.NewVK(os.Getenv("SERVICE_TOKEN")) - vkService.Limit = api.LimitUserToken - vkUser = api.NewVK(os.Getenv("USER_TOKEN")) - vkUser.Limit = api.LimitUserToken + if token := os.Getenv("WIDGET_TOKEN"); token != "" { + vkWidget = api.NewVK(token) + } + + if token := os.Getenv("SERVICE_TOKEN"); token != "" { + vkService = api.NewVK(token) + vkService.Limit = api.LimitUserToken + } + + if token := os.Getenv("USER_TOKEN"); token != "" { + vkUser = api.NewVK(token) + vkUser.Limit = api.LimitUserToken - if vkUser.AccessToken != "" { user, err := vkUser.UsersGet(nil) if err != nil { log.Fatalf("USER_TOKEN bad: %v", err) diff --git a/api/execute.go b/api/execute.go index b55e9cc8..5bee205a 100644 --- a/api/execute.go +++ b/api/execute.go @@ -13,10 +13,7 @@ import "encoding/json" // // https://vk.com/dev/execute func (vk *VK) ExecuteWithArgs(code string, params Params, obj interface{}) error { - token := vk.AccessToken - if vk.IsPoolClient { - token = vk.tokenPool.Get() - } + token := vk.getToken() reqParams := Params{ "code": code, diff --git a/internal/token_pool.go b/internal/token_pool.go deleted file mode 100644 index b0443c2c..00000000 --- a/internal/token_pool.go +++ /dev/null @@ -1,26 +0,0 @@ -package internal - -// TokenPool is a simple round-robin based token pool. -type TokenPool struct { - tokens chan string -} - -// NewTokenPool returns new token pool. -func NewTokenPool(tokens ...string) TokenPool { - c := make(chan string, len(tokens)) - for _, t := range tokens { - c <- t - } - - return TokenPool{ - tokens: c, - } -} - -// Get returns access token from pool. -func (tp TokenPool) Get() string { - token := <-tp.tokens - tp.tokens <- token - - return token -} diff --git a/internal/token_pool_test.go b/internal/token_pool_test.go deleted file mode 100644 index 814dc6f1..00000000 --- a/internal/token_pool_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package internal_test - -import ( - "testing" - - "github.com/SevereCloud/vksdk/internal" -) - -func TestTokenPool(t *testing.T) { - t.Parallel() - - tokens := []string{ - "1", "2", "3", "4", "5", - } - - p := internal.NewTokenPool(tokens...) - - for i := 0; i < len(tokens)*2; i++ { - tokenIdx := i % len(tokens) - - expect := tokens[tokenIdx] - actual := p.Get() - - if actual != expect { - t.Errorf("%s and %s should be equal", actual, expect) - } - } -} diff --git a/longpoll-user/v3/wrapper_test.go b/longpoll-user/v3/wrapper_test.go index 6d827fbf..5f97849d 100644 --- a/longpoll-user/v3/wrapper_test.go +++ b/longpoll-user/v3/wrapper_test.go @@ -16,7 +16,7 @@ import ( func needUserToken(t *testing.T) { t.Helper() - if vkUser.AccessToken == "" { + if vkUser == nil { t.Skip("USER_TOKEN empty") } } @@ -47,10 +47,10 @@ var ( func TestMain(m *testing.M) { time.Sleep(1 * time.Second) - vkUser = api.NewVK(os.Getenv("USER_TOKEN")) - vkUser.Limit = 3 + if token := os.Getenv("USER_TOKEN"); token != "" { + vkUser = api.NewVK(token) + vkUser.Limit = 3 - if vkUser.AccessToken != "" { user, err := vkUser.UsersGet(nil) if err != nil { log.Fatalf("USER_TOKEN bad: %v", err) From bf5632dfcfdff371bb292f4863310b558ec55413 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 14:19:43 +0300 Subject: [PATCH 097/105] fix: add MarkeOrder... events methods --- events/events.go | 10 ++++++ events/events_test.go | 72 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/events/events.go b/events/events.go index cde9c882..7a0d195f 100644 --- a/events/events.go +++ b/events/events.go @@ -755,6 +755,16 @@ func (fl *FuncList) MarketCommentDelete(f MarketCommentDeleteFunc) { fl.marketCommentDelete = append(fl.marketCommentDelete, f) } +// MarketOrderNew handler. +func (fl *FuncList) MarketOrderNew(f MarketOrderNewFunc) { + fl.marketOrderNew = append(fl.marketOrderNew, f) +} + +// MarketOrderEdit handler. +func (fl *FuncList) MarketOrderEdit(f MarketOrderEditFunc) { + fl.marketOrderEdit = append(fl.marketOrderEdit, f) +} + // GroupLeave handler. func (fl *FuncList) GroupLeave(f GroupLeaveFunc) { fl.groupLeave = append(fl.groupLeave, f) diff --git a/events/events_test.go b/events/events_test.go index 54a31e43..7f62b3f1 100644 --- a/events/events_test.go +++ b/events/events_test.go @@ -1048,6 +1048,7 @@ func TestFuncList_HandlerMarketCommentDelete(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMarketCommentDelete}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1057,7 +1058,7 @@ func TestFuncList_HandlerMarketCommentDelete(t *testing.T) { f( events.GroupEvent{ - Type: "market_comment_delete", + Type: events.EventMarketCommentDelete, Object: []byte("{}"), GroupID: GID, }, @@ -1065,7 +1066,74 @@ func TestFuncList_HandlerMarketCommentDelete(t *testing.T) { ) f( events.GroupEvent{ - Type: "market_comment_delete", + Type: events.EventMarketCommentDelete, + Object: []byte(""), + }, + true, + ) +} + +func TestFuncList_HandlerMarketOrderNew(t *testing.T) { + t.Parallel() + + fl := events.NewFuncList() + + fl.MarketOrderNew(func(ctx context.Context, obj events.MarketOrderNewObject) { + groupID := events.GroupIDFromContext(ctx) + assert.Equal(t, groupID, GID) + }) + + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { + t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) + } + } + + f( + events.GroupEvent{ + Type: events.EventMarketOrderNew, + Object: []byte("{}"), + GroupID: GID, + }, + false, + ) + f( + events.GroupEvent{ + Type: events.EventMarketOrderNew, + Object: []byte(""), + }, + true, + ) +} + +func TestFuncList_HandlerMarketOrderEdit(t *testing.T) { + t.Parallel() + + fl := events.NewFuncList() + + fl.MarketOrderEdit(func(ctx context.Context, obj events.MarketOrderEditObject) { + groupID := events.GroupIDFromContext(ctx) + assert.Equal(t, groupID, GID) + }) + assert.Equal(t, []events.EventType{events.EventMarketOrderEdit}, fl.ListEvents()) + + f := func(e events.GroupEvent, wantErr bool) { + if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { + t.Errorf("FuncList.Handler() error = %v, wantErr %v", err, wantErr) + } + } + + f( + events.GroupEvent{ + Type: events.EventMarketOrderEdit, + Object: []byte("{}"), + GroupID: GID, + }, + false, + ) + f( + events.GroupEvent{ + Type: events.EventMarketOrderEdit, Object: []byte(""), }, true, From 0760aacf58321cf717224f22c3b911e048ad8eb2 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 14:21:09 +0300 Subject: [PATCH 098/105] feat: add ListEvents for FuncList method --- events/events.go | 55 ++++++++++ events/events_test.go | 226 +++++++++++++++++++++++++----------------- 2 files changed, 191 insertions(+), 90 deletions(-) diff --git a/events/events.go b/events/events.go index 7a0d195f..916f0609 100644 --- a/events/events.go +++ b/events/events.go @@ -128,6 +128,7 @@ type FuncList struct { likeAdd []LikeAddFunc likeRemove []LikeRemoveFunc special map[EventType][]func(context.Context, GroupEvent) + eventsList []EventType } // NewFuncList returns a new FuncList. @@ -586,6 +587,11 @@ func (fl FuncList) Handler(ctx context.Context, e GroupEvent) error { // nolint: return nil } +// ListEvents return list of events. +func (fl FuncList) ListEvents() []EventType { + return fl.eventsList +} + // OnEvent handler. func (fl *FuncList) OnEvent(eventType EventType, f func(context.Context, GroupEvent)) { if fl.special == nil { @@ -593,244 +599,293 @@ func (fl *FuncList) OnEvent(eventType EventType, f func(context.Context, GroupEv } fl.special[eventType] = append(fl.special[eventType], f) + fl.eventsList = append(fl.eventsList, eventType) } // MessageNew handler. func (fl *FuncList) MessageNew(f MessageNewFunc) { fl.messageNew = append(fl.messageNew, f) + fl.eventsList = append(fl.eventsList, EventMessageNew) } // MessageReply handler. func (fl *FuncList) MessageReply(f MessageReplyFunc) { fl.messageReply = append(fl.messageReply, f) + fl.eventsList = append(fl.eventsList, EventMessageReply) } // MessageEdit handler. func (fl *FuncList) MessageEdit(f MessageEditFunc) { fl.messageEdit = append(fl.messageEdit, f) + fl.eventsList = append(fl.eventsList, EventMessageEdit) } // MessageAllow handler. func (fl *FuncList) MessageAllow(f MessageAllowFunc) { fl.messageAllow = append(fl.messageAllow, f) + fl.eventsList = append(fl.eventsList, EventMessageAllow) } // MessageDeny handler. func (fl *FuncList) MessageDeny(f MessageDenyFunc) { fl.messageDeny = append(fl.messageDeny, f) + fl.eventsList = append(fl.eventsList, EventMessageDeny) } // MessageTypingState handler. func (fl *FuncList) MessageTypingState(f MessageTypingStateFunc) { fl.messageTypingState = append(fl.messageTypingState, f) + fl.eventsList = append(fl.eventsList, EventMessageTypingState) } // MessageEvent handler. func (fl *FuncList) MessageEvent(f MessageEventFunc) { fl.messageEvent = append(fl.messageEvent, f) + fl.eventsList = append(fl.eventsList, EventMessageEvent) } // PhotoNew handler. func (fl *FuncList) PhotoNew(f PhotoNewFunc) { fl.photoNew = append(fl.photoNew, f) + fl.eventsList = append(fl.eventsList, EventPhotoNew) } // PhotoCommentNew handler. func (fl *FuncList) PhotoCommentNew(f PhotoCommentNewFunc) { fl.photoCommentNew = append(fl.photoCommentNew, f) + fl.eventsList = append(fl.eventsList, EventPhotoCommentNew) } // PhotoCommentEdit handler. func (fl *FuncList) PhotoCommentEdit(f PhotoCommentEditFunc) { fl.photoCommentEdit = append(fl.photoCommentEdit, f) + fl.eventsList = append(fl.eventsList, EventPhotoCommentEdit) } // PhotoCommentRestore handler. func (fl *FuncList) PhotoCommentRestore(f PhotoCommentRestoreFunc) { fl.photoCommentRestore = append(fl.photoCommentRestore, f) + fl.eventsList = append(fl.eventsList, EventPhotoCommentRestore) } // PhotoCommentDelete handler. func (fl *FuncList) PhotoCommentDelete(f PhotoCommentDeleteFunc) { fl.photoCommentDelete = append(fl.photoCommentDelete, f) + fl.eventsList = append(fl.eventsList, EventPhotoCommentDelete) } // AudioNew handler. func (fl *FuncList) AudioNew(f AudioNewFunc) { fl.audioNew = append(fl.audioNew, f) + fl.eventsList = append(fl.eventsList, EventAudioNew) } // VideoNew handler. func (fl *FuncList) VideoNew(f VideoNewFunc) { fl.videoNew = append(fl.videoNew, f) + fl.eventsList = append(fl.eventsList, EventVideoNew) } // VideoCommentNew handler. func (fl *FuncList) VideoCommentNew(f VideoCommentNewFunc) { fl.videoCommentNew = append(fl.videoCommentNew, f) + fl.eventsList = append(fl.eventsList, EventVideoCommentNew) } // VideoCommentEdit handler. func (fl *FuncList) VideoCommentEdit(f VideoCommentEditFunc) { fl.videoCommentEdit = append(fl.videoCommentEdit, f) + fl.eventsList = append(fl.eventsList, EventVideoCommentEdit) } // VideoCommentRestore handler. func (fl *FuncList) VideoCommentRestore(f VideoCommentRestoreFunc) { fl.videoCommentRestore = append(fl.videoCommentRestore, f) + fl.eventsList = append(fl.eventsList, EventVideoCommentRestore) } // VideoCommentDelete handler. func (fl *FuncList) VideoCommentDelete(f VideoCommentDeleteFunc) { fl.videoCommentDelete = append(fl.videoCommentDelete, f) + fl.eventsList = append(fl.eventsList, EventVideoCommentDelete) } // WallPostNew handler. func (fl *FuncList) WallPostNew(f WallPostNewFunc) { fl.wallPostNew = append(fl.wallPostNew, f) + fl.eventsList = append(fl.eventsList, EventWallPostNew) } // WallRepost handler. func (fl *FuncList) WallRepost(f WallRepostFunc) { fl.wallRepost = append(fl.wallRepost, f) + fl.eventsList = append(fl.eventsList, EventWallRepost) } // WallReplyNew handler. func (fl *FuncList) WallReplyNew(f WallReplyNewFunc) { fl.wallReplyNew = append(fl.wallReplyNew, f) + fl.eventsList = append(fl.eventsList, EventWallReplyNew) } // WallReplyEdit handler. func (fl *FuncList) WallReplyEdit(f WallReplyEditFunc) { fl.wallReplyEdit = append(fl.wallReplyEdit, f) + fl.eventsList = append(fl.eventsList, EventWallReplyEdit) } // WallReplyRestore handler. func (fl *FuncList) WallReplyRestore(f WallReplyRestoreFunc) { fl.wallReplyRestore = append(fl.wallReplyRestore, f) + fl.eventsList = append(fl.eventsList, EventWallReplyRestore) } // WallReplyDelete handler. func (fl *FuncList) WallReplyDelete(f WallReplyDeleteFunc) { fl.wallReplyDelete = append(fl.wallReplyDelete, f) + fl.eventsList = append(fl.eventsList, EventWallReplyDelete) } // BoardPostNew handler. func (fl *FuncList) BoardPostNew(f BoardPostNewFunc) { fl.boardPostNew = append(fl.boardPostNew, f) + fl.eventsList = append(fl.eventsList, EventBoardPostNew) } // BoardPostEdit handler. func (fl *FuncList) BoardPostEdit(f BoardPostEditFunc) { fl.boardPostEdit = append(fl.boardPostEdit, f) + fl.eventsList = append(fl.eventsList, EventBoardPostEdit) } // BoardPostRestore handler. func (fl *FuncList) BoardPostRestore(f BoardPostRestoreFunc) { fl.boardPostRestore = append(fl.boardPostRestore, f) + fl.eventsList = append(fl.eventsList, EventBoardPostRestore) } // BoardPostDelete handler. func (fl *FuncList) BoardPostDelete(f BoardPostDeleteFunc) { fl.boardPostDelete = append(fl.boardPostDelete, f) + fl.eventsList = append(fl.eventsList, EventBoardPostDelete) } // MarketCommentNew handler. func (fl *FuncList) MarketCommentNew(f MarketCommentNewFunc) { fl.marketCommentNew = append(fl.marketCommentNew, f) + fl.eventsList = append(fl.eventsList, EventMarketCommentNew) } // MarketCommentEdit handler. func (fl *FuncList) MarketCommentEdit(f MarketCommentEditFunc) { fl.marketCommentEdit = append(fl.marketCommentEdit, f) + fl.eventsList = append(fl.eventsList, EventMarketCommentEdit) } // MarketCommentRestore handler. func (fl *FuncList) MarketCommentRestore(f MarketCommentRestoreFunc) { fl.marketCommentRestore = append(fl.marketCommentRestore, f) + fl.eventsList = append(fl.eventsList, EventMarketCommentRestore) } // MarketCommentDelete handler. func (fl *FuncList) MarketCommentDelete(f MarketCommentDeleteFunc) { fl.marketCommentDelete = append(fl.marketCommentDelete, f) + fl.eventsList = append(fl.eventsList, EventMarketCommentDelete) } // MarketOrderNew handler. func (fl *FuncList) MarketOrderNew(f MarketOrderNewFunc) { fl.marketOrderNew = append(fl.marketOrderNew, f) + fl.eventsList = append(fl.eventsList, EventMarketOrderNew) } // MarketOrderEdit handler. func (fl *FuncList) MarketOrderEdit(f MarketOrderEditFunc) { fl.marketOrderEdit = append(fl.marketOrderEdit, f) + fl.eventsList = append(fl.eventsList, EventMarketOrderEdit) } // GroupLeave handler. func (fl *FuncList) GroupLeave(f GroupLeaveFunc) { fl.groupLeave = append(fl.groupLeave, f) + fl.eventsList = append(fl.eventsList, EventGroupLeave) } // GroupJoin handler. func (fl *FuncList) GroupJoin(f GroupJoinFunc) { fl.groupJoin = append(fl.groupJoin, f) + fl.eventsList = append(fl.eventsList, EventGroupJoin) } // UserBlock handler. func (fl *FuncList) UserBlock(f UserBlockFunc) { fl.userBlock = append(fl.userBlock, f) + fl.eventsList = append(fl.eventsList, EventUserBlock) } // UserUnblock handler. func (fl *FuncList) UserUnblock(f UserUnblockFunc) { fl.userUnblock = append(fl.userUnblock, f) + fl.eventsList = append(fl.eventsList, EventUserUnblock) } // PollVoteNew handler. func (fl *FuncList) PollVoteNew(f PollVoteNewFunc) { fl.pollVoteNew = append(fl.pollVoteNew, f) + fl.eventsList = append(fl.eventsList, EventPollVoteNew) } // GroupOfficersEdit handler. func (fl *FuncList) GroupOfficersEdit(f GroupOfficersEditFunc) { fl.groupOfficersEdit = append(fl.groupOfficersEdit, f) + fl.eventsList = append(fl.eventsList, EventGroupOfficersEdit) } // GroupChangeSettings handler. func (fl *FuncList) GroupChangeSettings(f GroupChangeSettingsFunc) { fl.groupChangeSettings = append(fl.groupChangeSettings, f) + fl.eventsList = append(fl.eventsList, EventGroupChangeSettings) } // GroupChangePhoto handler. func (fl *FuncList) GroupChangePhoto(f GroupChangePhotoFunc) { fl.groupChangePhoto = append(fl.groupChangePhoto, f) + fl.eventsList = append(fl.eventsList, EventGroupChangePhoto) } // VkpayTransaction handler. func (fl *FuncList) VkpayTransaction(f VkpayTransactionFunc) { fl.vkpayTransaction = append(fl.vkpayTransaction, f) + fl.eventsList = append(fl.eventsList, EventVkpayTransaction) } // LeadFormsNew handler. func (fl *FuncList) LeadFormsNew(f LeadFormsNewFunc) { fl.leadFormsNew = append(fl.leadFormsNew, f) + fl.eventsList = append(fl.eventsList, EventLeadFormsNew) } // AppPayload handler. func (fl *FuncList) AppPayload(f AppPayloadFunc) { fl.appPayload = append(fl.appPayload, f) + fl.eventsList = append(fl.eventsList, EventAppPayload) } // MessageRead handler. func (fl *FuncList) MessageRead(f MessageReadFunc) { fl.messageRead = append(fl.messageRead, f) + fl.eventsList = append(fl.eventsList, EventMessageRead) } // LikeAdd handler. func (fl *FuncList) LikeAdd(f LikeAddFunc) { fl.likeAdd = append(fl.likeAdd, f) + fl.eventsList = append(fl.eventsList, EventLikeAdd) } // LikeRemove handler. func (fl *FuncList) LikeRemove(f LikeRemoveFunc) { fl.likeRemove = append(fl.likeRemove, f) + fl.eventsList = append(fl.eventsList, EventLikeRemove) } diff --git a/events/events_test.go b/events/events_test.go index 7f62b3f1..d1661afc 100644 --- a/events/events_test.go +++ b/events/events_test.go @@ -34,7 +34,7 @@ func TestFuncList_HandlerMessageNew(t *testing.T) { f( events.GroupEvent{ - Type: "message_new", + Type: events.EventMessageNew, Object: []byte(`{"message":{"date":1,"from_id":1,"id":1,"peer_id":1,"text":"{}"},"client_info":{}}`), GroupID: GID, }, @@ -42,7 +42,7 @@ func TestFuncList_HandlerMessageNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_new", + Type: events.EventMessageNew, Object: []byte(""), }, true, @@ -58,6 +58,7 @@ func TestFuncList_HandlerMessageReply(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageReply}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -67,7 +68,7 @@ func TestFuncList_HandlerMessageReply(t *testing.T) { f( events.GroupEvent{ - Type: "message_reply", + Type: events.EventMessageReply, Object: []byte("{}"), GroupID: GID, }, @@ -75,7 +76,7 @@ func TestFuncList_HandlerMessageReply(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_reply", + Type: events.EventMessageReply, Object: []byte(""), }, true, @@ -91,6 +92,7 @@ func TestFuncList_HandlerMessageEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -100,7 +102,7 @@ func TestFuncList_HandlerMessageEdit(t *testing.T) { f( events.GroupEvent{ - Type: "message_edit", + Type: events.EventMessageEdit, Object: []byte("{}"), GroupID: GID, }, @@ -108,7 +110,7 @@ func TestFuncList_HandlerMessageEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_edit", + Type: events.EventMessageEdit, Object: []byte(""), }, true, @@ -124,6 +126,7 @@ func TestFuncList_HandlerMessageAllow(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageAllow}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -133,7 +136,7 @@ func TestFuncList_HandlerMessageAllow(t *testing.T) { f( events.GroupEvent{ - Type: "message_allow", + Type: events.EventMessageAllow, Object: []byte("{}"), GroupID: GID, }, @@ -141,7 +144,7 @@ func TestFuncList_HandlerMessageAllow(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_allow", + Type: events.EventMessageAllow, Object: []byte(""), }, true, @@ -157,6 +160,7 @@ func TestFuncList_HandlerMessageDeny(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageDeny}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -166,7 +170,7 @@ func TestFuncList_HandlerMessageDeny(t *testing.T) { f( events.GroupEvent{ - Type: "message_deny", + Type: events.EventMessageDeny, Object: []byte("{}"), GroupID: GID, }, @@ -174,7 +178,7 @@ func TestFuncList_HandlerMessageDeny(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_deny", + Type: events.EventMessageDeny, Object: []byte(""), }, true, @@ -190,6 +194,7 @@ func TestFuncList_HandlerMessageTypingState(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageTypingState}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -199,7 +204,7 @@ func TestFuncList_HandlerMessageTypingState(t *testing.T) { f( events.GroupEvent{ - Type: "message_typing_state", + Type: events.EventMessageTypingState, Object: []byte("{}"), GroupID: GID, }, @@ -207,7 +212,7 @@ func TestFuncList_HandlerMessageTypingState(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_typing_state", + Type: events.EventMessageTypingState, Object: []byte(""), }, true, @@ -223,6 +228,7 @@ func TestFuncList_HandlerMessageEvent(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageEvent}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -232,7 +238,7 @@ func TestFuncList_HandlerMessageEvent(t *testing.T) { f( events.GroupEvent{ - Type: "message_event", + Type: events.EventMessageEvent, Object: []byte("{}"), GroupID: GID, }, @@ -240,7 +246,7 @@ func TestFuncList_HandlerMessageEvent(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_event", + Type: events.EventMessageEvent, Object: []byte(""), }, true, @@ -256,6 +262,7 @@ func TestFuncList_HandlerPhotoNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventPhotoNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -265,7 +272,7 @@ func TestFuncList_HandlerPhotoNew(t *testing.T) { f( events.GroupEvent{ - Type: "photo_new", + Type: events.EventPhotoNew, Object: []byte("{}"), GroupID: GID, }, @@ -273,7 +280,7 @@ func TestFuncList_HandlerPhotoNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "photo_new", + Type: events.EventPhotoNew, Object: []byte(""), }, true, @@ -289,6 +296,7 @@ func TestFuncList_HandlerPhotoCommentNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventPhotoCommentNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -298,7 +306,7 @@ func TestFuncList_HandlerPhotoCommentNew(t *testing.T) { f( events.GroupEvent{ - Type: "photo_comment_new", + Type: events.EventPhotoCommentNew, Object: []byte("{}"), GroupID: GID, }, @@ -306,7 +314,7 @@ func TestFuncList_HandlerPhotoCommentNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "photo_comment_new", + Type: events.EventPhotoCommentNew, Object: []byte(""), }, true, @@ -322,6 +330,7 @@ func TestFuncList_HandlerPhotoCommentEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventPhotoCommentEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -331,7 +340,7 @@ func TestFuncList_HandlerPhotoCommentEdit(t *testing.T) { f( events.GroupEvent{ - Type: "photo_comment_edit", + Type: events.EventPhotoCommentEdit, Object: []byte("{}"), GroupID: GID, }, @@ -339,7 +348,7 @@ func TestFuncList_HandlerPhotoCommentEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "photo_comment_edit", + Type: events.EventPhotoCommentEdit, Object: []byte(""), }, true, @@ -355,6 +364,7 @@ func TestFuncList_HandlerPhotoCommentRestore(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventPhotoCommentRestore}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -364,7 +374,7 @@ func TestFuncList_HandlerPhotoCommentRestore(t *testing.T) { f( events.GroupEvent{ - Type: "photo_comment_restore", + Type: events.EventPhotoCommentRestore, Object: []byte("{}"), GroupID: GID, }, @@ -372,7 +382,7 @@ func TestFuncList_HandlerPhotoCommentRestore(t *testing.T) { ) f( events.GroupEvent{ - Type: "photo_comment_restore", + Type: events.EventPhotoCommentRestore, Object: []byte(""), }, true, @@ -388,6 +398,7 @@ func TestFuncList_HandlerPhotoCommentDelete(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventPhotoCommentDelete}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -397,7 +408,7 @@ func TestFuncList_HandlerPhotoCommentDelete(t *testing.T) { f( events.GroupEvent{ - Type: "photo_comment_delete", + Type: events.EventPhotoCommentDelete, Object: []byte("{}"), GroupID: GID, }, @@ -405,7 +416,7 @@ func TestFuncList_HandlerPhotoCommentDelete(t *testing.T) { ) f( events.GroupEvent{ - Type: "photo_comment_delete", + Type: events.EventPhotoCommentDelete, Object: []byte(""), }, true, @@ -421,6 +432,7 @@ func TestFuncList_HandlerAudioNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventAudioNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -430,7 +442,7 @@ func TestFuncList_HandlerAudioNew(t *testing.T) { f( events.GroupEvent{ - Type: "audio_new", + Type: events.EventAudioNew, Object: []byte("{}"), GroupID: GID, }, @@ -438,7 +450,7 @@ func TestFuncList_HandlerAudioNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "audio_new", + Type: events.EventAudioNew, Object: []byte(""), }, true, @@ -454,6 +466,7 @@ func TestFuncList_HandlerVideoNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventVideoNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -463,7 +476,7 @@ func TestFuncList_HandlerVideoNew(t *testing.T) { f( events.GroupEvent{ - Type: "video_new", + Type: events.EventVideoNew, Object: []byte("{}"), GroupID: GID, }, @@ -471,7 +484,7 @@ func TestFuncList_HandlerVideoNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "video_new", + Type: events.EventVideoNew, Object: []byte(""), }, true, @@ -487,6 +500,7 @@ func TestFuncList_HandlerVideoCommentNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventVideoCommentNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -496,7 +510,7 @@ func TestFuncList_HandlerVideoCommentNew(t *testing.T) { f( events.GroupEvent{ - Type: "video_comment_new", + Type: events.EventVideoCommentNew, Object: []byte("{}"), GroupID: GID, }, @@ -504,7 +518,7 @@ func TestFuncList_HandlerVideoCommentNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "video_comment_new", + Type: events.EventVideoCommentNew, Object: []byte(""), }, true, @@ -520,6 +534,7 @@ func TestFuncList_HandlerVideoCommentEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventVideoCommentEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -529,7 +544,7 @@ func TestFuncList_HandlerVideoCommentEdit(t *testing.T) { f( events.GroupEvent{ - Type: "video_comment_edit", + Type: events.EventVideoCommentEdit, Object: []byte("{}"), GroupID: GID, }, @@ -537,7 +552,7 @@ func TestFuncList_HandlerVideoCommentEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "video_comment_edit", + Type: events.EventVideoCommentEdit, Object: []byte(""), }, true, @@ -553,6 +568,7 @@ func TestFuncList_HandlerVideoCommentRestore(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventVideoCommentRestore}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -562,7 +578,7 @@ func TestFuncList_HandlerVideoCommentRestore(t *testing.T) { f( events.GroupEvent{ - Type: "video_comment_restore", + Type: events.EventVideoCommentRestore, Object: []byte("{}"), GroupID: GID, }, @@ -570,7 +586,7 @@ func TestFuncList_HandlerVideoCommentRestore(t *testing.T) { ) f( events.GroupEvent{ - Type: "video_comment_restore", + Type: events.EventVideoCommentRestore, Object: []byte(""), }, true, @@ -586,6 +602,7 @@ func TestFuncList_HandlerVideoCommentDelete(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventVideoCommentDelete}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -595,7 +612,7 @@ func TestFuncList_HandlerVideoCommentDelete(t *testing.T) { f( events.GroupEvent{ - Type: "video_comment_delete", + Type: events.EventVideoCommentDelete, Object: []byte("{}"), GroupID: GID, }, @@ -603,7 +620,7 @@ func TestFuncList_HandlerVideoCommentDelete(t *testing.T) { ) f( events.GroupEvent{ - Type: "video_comment_delete", + Type: events.EventVideoCommentDelete, Object: []byte(""), }, true, @@ -619,6 +636,7 @@ func TestFuncList_HandlerWallPostNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventWallPostNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -628,7 +646,7 @@ func TestFuncList_HandlerWallPostNew(t *testing.T) { f( events.GroupEvent{ - Type: "wall_post_new", + Type: events.EventWallPostNew, Object: []byte("{}"), GroupID: GID, }, @@ -636,7 +654,7 @@ func TestFuncList_HandlerWallPostNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "wall_post_new", + Type: events.EventWallPostNew, Object: []byte(""), }, true, @@ -652,6 +670,7 @@ func TestFuncList_HandlerWallRepost(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventWallRepost}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -661,7 +680,7 @@ func TestFuncList_HandlerWallRepost(t *testing.T) { f( events.GroupEvent{ - Type: "wall_repost", + Type: events.EventWallRepost, Object: []byte("{}"), GroupID: GID, }, @@ -669,7 +688,7 @@ func TestFuncList_HandlerWallRepost(t *testing.T) { ) f( events.GroupEvent{ - Type: "wall_repost", + Type: events.EventWallRepost, Object: []byte(""), }, true, @@ -685,6 +704,7 @@ func TestFuncList_HandlerWallReplyNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventWallReplyNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -694,7 +714,7 @@ func TestFuncList_HandlerWallReplyNew(t *testing.T) { f( events.GroupEvent{ - Type: "wall_reply_new", + Type: events.EventWallReplyNew, Object: []byte("{}"), GroupID: GID, }, @@ -702,7 +722,7 @@ func TestFuncList_HandlerWallReplyNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "wall_reply_new", + Type: events.EventWallReplyNew, Object: []byte(""), }, true, @@ -718,6 +738,7 @@ func TestFuncList_HandlerWallReplyEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventWallReplyEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -727,7 +748,7 @@ func TestFuncList_HandlerWallReplyEdit(t *testing.T) { f( events.GroupEvent{ - Type: "wall_reply_edit", + Type: events.EventWallReplyEdit, Object: []byte("{}"), GroupID: GID, }, @@ -735,7 +756,7 @@ func TestFuncList_HandlerWallReplyEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "wall_reply_edit", + Type: events.EventWallReplyEdit, Object: []byte(""), }, true, @@ -751,6 +772,7 @@ func TestFuncList_HandlerWallReplyRestore(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventWallReplyRestore}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -760,7 +782,7 @@ func TestFuncList_HandlerWallReplyRestore(t *testing.T) { f( events.GroupEvent{ - Type: "wall_reply_restore", + Type: events.EventWallReplyRestore, Object: []byte("{}"), GroupID: GID, }, @@ -768,7 +790,7 @@ func TestFuncList_HandlerWallReplyRestore(t *testing.T) { ) f( events.GroupEvent{ - Type: "wall_reply_restore", + Type: events.EventWallReplyRestore, Object: []byte(""), }, true, @@ -784,6 +806,7 @@ func TestFuncList_HandlerWallReplyDelete(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventWallReplyDelete}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -793,7 +816,7 @@ func TestFuncList_HandlerWallReplyDelete(t *testing.T) { f( events.GroupEvent{ - Type: "wall_reply_delete", + Type: events.EventWallReplyDelete, Object: []byte("{}"), GroupID: GID, }, @@ -801,7 +824,7 @@ func TestFuncList_HandlerWallReplyDelete(t *testing.T) { ) f( events.GroupEvent{ - Type: "wall_reply_delete", + Type: events.EventWallReplyDelete, Object: []byte(""), }, true, @@ -817,6 +840,7 @@ func TestFuncList_HandlerBoardPostNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventBoardPostNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -826,7 +850,7 @@ func TestFuncList_HandlerBoardPostNew(t *testing.T) { f( events.GroupEvent{ - Type: "board_post_new", + Type: events.EventBoardPostNew, Object: []byte("{}"), GroupID: GID, }, @@ -834,7 +858,7 @@ func TestFuncList_HandlerBoardPostNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "board_post_new", + Type: events.EventBoardPostNew, Object: []byte(""), }, true, @@ -850,6 +874,7 @@ func TestFuncList_HandlerBoardPostEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventBoardPostEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -859,7 +884,7 @@ func TestFuncList_HandlerBoardPostEdit(t *testing.T) { f( events.GroupEvent{ - Type: "board_post_edit", + Type: events.EventBoardPostEdit, Object: []byte("{}"), GroupID: GID, }, @@ -867,7 +892,7 @@ func TestFuncList_HandlerBoardPostEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "board_post_edit", + Type: events.EventBoardPostEdit, Object: []byte(""), }, true, @@ -883,6 +908,7 @@ func TestFuncList_HandlerBoardPostRestore(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventBoardPostRestore}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -892,7 +918,7 @@ func TestFuncList_HandlerBoardPostRestore(t *testing.T) { f( events.GroupEvent{ - Type: "board_post_restore", + Type: events.EventBoardPostRestore, Object: []byte("{}"), GroupID: GID, }, @@ -900,7 +926,7 @@ func TestFuncList_HandlerBoardPostRestore(t *testing.T) { ) f( events.GroupEvent{ - Type: "board_post_restore", + Type: events.EventBoardPostRestore, Object: []byte(""), }, true, @@ -916,6 +942,7 @@ func TestFuncList_HandlerBoardPostDelete(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventBoardPostDelete}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -925,7 +952,7 @@ func TestFuncList_HandlerBoardPostDelete(t *testing.T) { f( events.GroupEvent{ - Type: "board_post_delete", + Type: events.EventBoardPostDelete, Object: []byte("{}"), GroupID: GID, }, @@ -933,7 +960,7 @@ func TestFuncList_HandlerBoardPostDelete(t *testing.T) { ) f( events.GroupEvent{ - Type: "board_post_delete", + Type: events.EventBoardPostDelete, Object: []byte(""), }, true, @@ -949,6 +976,7 @@ func TestFuncList_HandlerMarketCommentNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMarketCommentNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -958,7 +986,7 @@ func TestFuncList_HandlerMarketCommentNew(t *testing.T) { f( events.GroupEvent{ - Type: "market_comment_new", + Type: events.EventMarketCommentNew, Object: []byte("{}"), GroupID: GID, }, @@ -966,7 +994,7 @@ func TestFuncList_HandlerMarketCommentNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "market_comment_new", + Type: events.EventMarketCommentNew, Object: []byte(""), }, true, @@ -982,6 +1010,7 @@ func TestFuncList_HandlerMarketCommentEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMarketCommentEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -991,7 +1020,7 @@ func TestFuncList_HandlerMarketCommentEdit(t *testing.T) { f( events.GroupEvent{ - Type: "market_comment_edit", + Type: events.EventMarketCommentEdit, Object: []byte("{}"), GroupID: GID, }, @@ -999,7 +1028,7 @@ func TestFuncList_HandlerMarketCommentEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "market_comment_edit", + Type: events.EventMarketCommentEdit, Object: []byte(""), }, true, @@ -1015,6 +1044,7 @@ func TestFuncList_HandlerMarketCommentRestore(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMarketCommentRestore}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1024,7 +1054,7 @@ func TestFuncList_HandlerMarketCommentRestore(t *testing.T) { f( events.GroupEvent{ - Type: "market_comment_restore", + Type: events.EventMarketCommentRestore, Object: []byte("{}"), GroupID: GID, }, @@ -1032,7 +1062,7 @@ func TestFuncList_HandlerMarketCommentRestore(t *testing.T) { ) f( events.GroupEvent{ - Type: "market_comment_restore", + Type: events.EventMarketCommentRestore, Object: []byte(""), }, true, @@ -1082,6 +1112,7 @@ func TestFuncList_HandlerMarketOrderNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMarketOrderNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1149,6 +1180,7 @@ func TestFuncList_HandlerGroupLeave(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventGroupLeave}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1158,7 +1190,7 @@ func TestFuncList_HandlerGroupLeave(t *testing.T) { f( events.GroupEvent{ - Type: "group_leave", + Type: events.EventGroupLeave, Object: []byte("{}"), GroupID: GID, }, @@ -1166,7 +1198,7 @@ func TestFuncList_HandlerGroupLeave(t *testing.T) { ) f( events.GroupEvent{ - Type: "group_leave", + Type: events.EventGroupLeave, Object: []byte(""), }, true, @@ -1182,6 +1214,7 @@ func TestFuncList_HandlerGroupJoin(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventGroupJoin}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1191,7 +1224,7 @@ func TestFuncList_HandlerGroupJoin(t *testing.T) { f( events.GroupEvent{ - Type: "group_join", + Type: events.EventGroupJoin, Object: []byte("{}"), GroupID: GID, }, @@ -1199,7 +1232,7 @@ func TestFuncList_HandlerGroupJoin(t *testing.T) { ) f( events.GroupEvent{ - Type: "group_join", + Type: events.EventGroupJoin, Object: []byte(""), }, true, @@ -1215,6 +1248,7 @@ func TestFuncList_HandlerUserBlock(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventUserBlock}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1224,7 +1258,7 @@ func TestFuncList_HandlerUserBlock(t *testing.T) { f( events.GroupEvent{ - Type: "user_block", + Type: events.EventUserBlock, Object: []byte("{}"), GroupID: GID, }, @@ -1232,7 +1266,7 @@ func TestFuncList_HandlerUserBlock(t *testing.T) { ) f( events.GroupEvent{ - Type: "user_block", + Type: events.EventUserBlock, Object: []byte(""), }, true, @@ -1248,6 +1282,7 @@ func TestFuncList_HandlerUserUnblock(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventUserUnblock}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1257,7 +1292,7 @@ func TestFuncList_HandlerUserUnblock(t *testing.T) { f( events.GroupEvent{ - Type: "user_unblock", + Type: events.EventUserUnblock, Object: []byte("{}"), GroupID: GID, }, @@ -1265,7 +1300,7 @@ func TestFuncList_HandlerUserUnblock(t *testing.T) { ) f( events.GroupEvent{ - Type: "user_unblock", + Type: events.EventUserUnblock, Object: []byte(""), }, true, @@ -1281,6 +1316,7 @@ func TestFuncList_HandlerPollVoteNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventPollVoteNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1290,7 +1326,7 @@ func TestFuncList_HandlerPollVoteNew(t *testing.T) { f( events.GroupEvent{ - Type: "poll_vote_new", + Type: events.EventPollVoteNew, Object: []byte("{}"), GroupID: GID, }, @@ -1298,7 +1334,7 @@ func TestFuncList_HandlerPollVoteNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "poll_vote_new", + Type: events.EventPollVoteNew, Object: []byte(""), }, true, @@ -1314,6 +1350,7 @@ func TestFuncList_HandlerGroupOfficersEdit(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventGroupOfficersEdit}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1323,7 +1360,7 @@ func TestFuncList_HandlerGroupOfficersEdit(t *testing.T) { f( events.GroupEvent{ - Type: "group_officers_edit", + Type: events.EventGroupOfficersEdit, Object: []byte("{}"), GroupID: GID, }, @@ -1331,7 +1368,7 @@ func TestFuncList_HandlerGroupOfficersEdit(t *testing.T) { ) f( events.GroupEvent{ - Type: "group_officers_edit", + Type: events.EventGroupOfficersEdit, Object: []byte(""), }, true, @@ -1347,6 +1384,7 @@ func TestFuncList_HandlerGroupChangeSettings(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventGroupChangeSettings}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1356,7 +1394,7 @@ func TestFuncList_HandlerGroupChangeSettings(t *testing.T) { f( events.GroupEvent{ - Type: "group_change_settings", + Type: events.EventGroupChangeSettings, Object: []byte("{}"), GroupID: GID, }, @@ -1364,7 +1402,7 @@ func TestFuncList_HandlerGroupChangeSettings(t *testing.T) { ) f( events.GroupEvent{ - Type: "group_change_settings", + Type: events.EventGroupChangeSettings, Object: []byte(""), }, true, @@ -1380,6 +1418,7 @@ func TestFuncList_HandlerGroupChangePhoto(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventGroupChangePhoto}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1389,7 +1428,7 @@ func TestFuncList_HandlerGroupChangePhoto(t *testing.T) { f( events.GroupEvent{ - Type: "group_change_photo", + Type: events.EventGroupChangePhoto, Object: []byte("{}"), GroupID: GID, }, @@ -1397,7 +1436,7 @@ func TestFuncList_HandlerGroupChangePhoto(t *testing.T) { ) f( events.GroupEvent{ - Type: "group_change_photo", + Type: events.EventGroupChangePhoto, Object: []byte(""), }, true, @@ -1413,6 +1452,7 @@ func TestFuncList_HandlerVkpayTransaction(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventVkpayTransaction}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1422,7 +1462,7 @@ func TestFuncList_HandlerVkpayTransaction(t *testing.T) { f( events.GroupEvent{ - Type: "vkpay_transaction", + Type: events.EventVkpayTransaction, Object: []byte("{}"), GroupID: GID, }, @@ -1430,7 +1470,7 @@ func TestFuncList_HandlerVkpayTransaction(t *testing.T) { ) f( events.GroupEvent{ - Type: "vkpay_transaction", + Type: events.EventVkpayTransaction, Object: []byte(""), }, true, @@ -1446,6 +1486,7 @@ func TestFuncList_HandlerLeadFormsNew(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventLeadFormsNew}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1455,7 +1496,7 @@ func TestFuncList_HandlerLeadFormsNew(t *testing.T) { f( events.GroupEvent{ - Type: "lead_forms_new", + Type: events.EventLeadFormsNew, Object: []byte("{}"), GroupID: GID, }, @@ -1463,7 +1504,7 @@ func TestFuncList_HandlerLeadFormsNew(t *testing.T) { ) f( events.GroupEvent{ - Type: "lead_forms_new", + Type: events.EventLeadFormsNew, Object: []byte(""), }, true, @@ -1479,6 +1520,7 @@ func TestFuncList_HandlerAppPayload(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventAppPayload}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1488,7 +1530,7 @@ func TestFuncList_HandlerAppPayload(t *testing.T) { f( events.GroupEvent{ - Type: "app_payload", + Type: events.EventAppPayload, Object: []byte(`{"user_id":117253521,"app_id":6703670,"payload":"{\"foo\":\"bar\"}"}`), GroupID: GID, }, @@ -1496,7 +1538,7 @@ func TestFuncList_HandlerAppPayload(t *testing.T) { ) f( events.GroupEvent{ - Type: "app_payload", + Type: events.EventAppPayload, Object: []byte(""), }, true, @@ -1512,6 +1554,7 @@ func TestFuncList_HandlerMessageRead(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventMessageRead}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1521,7 +1564,7 @@ func TestFuncList_HandlerMessageRead(t *testing.T) { f( events.GroupEvent{ - Type: "message_read", + Type: events.EventMessageRead, Object: []byte(`{"from_id":1,"peer_id":1,"read_message_id":1}`), GroupID: GID, }, @@ -1529,7 +1572,7 @@ func TestFuncList_HandlerMessageRead(t *testing.T) { ) f( events.GroupEvent{ - Type: "message_read", + Type: events.EventMessageRead, Object: []byte(""), }, true, @@ -1545,6 +1588,7 @@ func TestFuncList_HandlerLikeAdd(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventLikeAdd}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1554,7 +1598,7 @@ func TestFuncList_HandlerLikeAdd(t *testing.T) { f( events.GroupEvent{ - Type: "like_add", + Type: events.EventLikeAdd, Object: []byte(`{"liker_id": 574423462,"object_type": "photo","object_owner_id": -178044536,"object_id": 457242474,"thread_reply_id": 0}`), GroupID: GID, }, @@ -1562,7 +1606,7 @@ func TestFuncList_HandlerLikeAdd(t *testing.T) { ) f( events.GroupEvent{ - Type: "like_add", + Type: events.EventLikeAdd, Object: []byte(""), }, true, @@ -1578,6 +1622,7 @@ func TestFuncList_HandlerLikeRemove(t *testing.T) { groupID := events.GroupIDFromContext(ctx) assert.Equal(t, groupID, GID) }) + assert.Equal(t, []events.EventType{events.EventLikeRemove}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { @@ -1587,7 +1632,7 @@ func TestFuncList_HandlerLikeRemove(t *testing.T) { f( events.GroupEvent{ - Type: "like_remove", + Type: events.EventLikeRemove, Object: []byte(`{"liker_id": 574423462,"object_type": "photo","object_owner_id": -178044536,"object_id": 457242474,"thread_reply_id": 0}`), GroupID: GID, }, @@ -1595,7 +1640,7 @@ func TestFuncList_HandlerLikeRemove(t *testing.T) { ) f( events.GroupEvent{ - Type: "like_remove", + Type: events.EventLikeRemove, Object: []byte(""), }, true, @@ -1610,6 +1655,7 @@ func TestFuncList_OnEvent(t *testing.T) { fl.OnEvent("wtf_event", func(_ context.Context, e events.GroupEvent) { assert.NotEmpty(t, e) }) + assert.Equal(t, []events.EventType{"wtf_event"}, fl.ListEvents()) f := func(e events.GroupEvent, wantErr bool) { if err := fl.Handler(context.Background(), e); (err != nil) != wantErr { From 7b27f24183519411385be7a02d4ec62a3fb61dfa Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 15:06:31 +0300 Subject: [PATCH 099/105] feat: callback AutoSetting --- callback/README.md | 53 +++++++++++++++ callback/callback.go | 2 + callback/setting.go | 142 +++++++++++++++++++++++++++++++++++++++ callback/setting_test.go | 56 +++++++++++++++ 4 files changed, 253 insertions(+) create mode 100644 callback/setting.go create mode 100644 callback/setting_test.go diff --git a/callback/README.md b/callback/README.md index d4f7893a..655ad299 100644 --- a/callback/README.md +++ b/callback/README.md @@ -68,6 +68,7 @@ http.ListenAndServe(":8080", nil) package main import ( + "context" "log" "net/http" @@ -90,3 +91,55 @@ func main() { http.ListenAndServe(":8080", nil) } ``` + +## Автоматическая настройка + +Для автоматической настройки callback сервера, существует метод `AutoSetting`. +Данный метод: + +- проверяет существующие настройки callback +- удаляет сервер, если он сломан +- создает новый callback, если его нет +- генерирует секрет +- настраивает callback сервер с событиями, которые были прописаны в коде + +`AutoSetting` требуется запускать вместе с веб-сервером. + +```go +package main + +import ( + "context" + "log" + "net/http" + "os" + + "github.com/SevereCloud/vksdk/api" + "github.com/SevereCloud/vksdk/callback" + "github.com/SevereCloud/vksdk/events" +) + +func main() { + groupToken := "" // рекомендуется использовать os.Getenv("TOKEN") + vk := api.NewVK(groupToken) + + cb := callback.NewCallback() + cb.Title = "example-bot" + + cb.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { + log.Print(obj.Message.Text) + }) + + http.HandleFunc("/callback", cb.HandleFunc) + + go func() { + err := cb.AutoSetting(vk, "https://example.com/callback") + if err != nil { + log.Println(err) + os.Exit(1) + } + }() + + http.ListenAndServe(":8080", nil) +} +``` diff --git a/callback/callback.go b/callback/callback.go index fb8fabc2..0e13fb8d 100644 --- a/callback/callback.go +++ b/callback/callback.go @@ -21,6 +21,7 @@ type Callback struct { ConfirmationKey string SecretKeys map[int]string SecretKey string + Title string events.FuncList } @@ -28,6 +29,7 @@ type Callback struct { // NewCallback return *Callback. func NewCallback() *Callback { cb := &Callback{ + Title: "vksdk", ConfirmationKeys: make(map[int]string), SecretKeys: make(map[int]string), FuncList: *events.NewFuncList(), diff --git a/callback/setting.go b/callback/setting.go new file mode 100644 index 00000000..0df6e99e --- /dev/null +++ b/callback/setting.go @@ -0,0 +1,142 @@ +// Package callback implements Callback API. +package callback // import "github.com/SevereCloud/vksdk/callback" + +import ( + "crypto/rand" + "errors" + + "github.com/SevereCloud/vksdk" + "github.com/SevereCloud/vksdk/api" +) + +// generateRandomBytes returns securely generated random bytes. +// It will return an error if the system's secure random +// number generator fails to function correctly, in which +// case the caller should not continue. +func generateRandomBytes(n int) ([]byte, error) { + b := make([]byte, n) + _, err := rand.Read(b) + // Note that err == nil only if we read len(b) bytes. + if err != nil { + return nil, err + } + + return b, nil +} + +// generateRandomString returns a securely generated random string. +// It will return an error if the system's secure random +// number generator fails to function correctly, in which +// case the caller should not continue. +func generateRandomString(n int) (string, error) { + const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + + bytes, err := generateRandomBytes(n) + if err != nil { + return "", err + } + + for i, b := range bytes { + bytes[i] = letters[b%byte(len(letters))] + } + + return string(bytes), nil +} + +// ErrNeedGroupToken for AutoSetting. +var ErrNeedGroupToken = errors.New("callback: need group access token") + +// AutoSetting automatically configures callback. +// +// Need *api.VK with group access token, access setting: community management. +func (cb *Callback) AutoSetting( + vk *api.VK, + urlCallback string, +) error { + callbackServerID := 0 + + g, err := vk.GroupsGetByID(api.Params{}) + if err != nil { + if errors.Is(err, api.ErrParam) { + return ErrNeedGroupToken + } + + return err + } + + groupID := g[0].ID + + callbackServers, err := vk.GroupsGetCallbackServers(api.Params{ + "group_id": groupID, + }) + if err != nil { + return err + } + + for _, cbServer := range callbackServers.Items { + if cbServer.URL == urlCallback { + // Checking the server status + if cbServer.Status == "ok" { + // Find confirmed Callback server + callbackServerID = cbServer.ID + cb.SecretKeys[groupID] = cbServer.SecretKey + + break + } else { + // Broken Callback server + _, _ = vk.GroupsDeleteCallbackServer(api.Params{ + "group_id": groupID, + "server_id": cbServer.ID, + }) + } + } + } + + // If we did not find a server, create a new one + if callbackServerID == 0 { + // Generate secret key + secretKey, err := generateRandomString(24) + if err != nil { + return err + } + + cb.SecretKeys[groupID] = secretKey + + // Get confirmation code + confirmationCodeResponse, err := vk.GroupsGetCallbackConfirmationCode(api.Params{ + "group_id": groupID, + }) + if err != nil { + return err + } + + cb.ConfirmationKeys[groupID] = confirmationCodeResponse.Code + + // Web server must be running + addCallbackResponse, err := vk.GroupsAddCallbackServer(api.Params{ + "group_id": groupID, + "url": urlCallback, + "title": cb.Title, + "secret_key": secretKey, + }) + if err != nil { + return err + } + + callbackServerID = addCallbackResponse.ServerID + } + + params := api.Params{ + "group_id": groupID, + "server_id": callbackServerID, + "api_version": vksdk.API, + } + for _, event := range cb.ListEvents() { + params[string(event)] = true + } + + // Updating Callback settings + _, err = vk.GroupsSetCallbackSettings(params) + + return err +} diff --git a/callback/setting_test.go b/callback/setting_test.go new file mode 100644 index 00000000..8e9b52da --- /dev/null +++ b/callback/setting_test.go @@ -0,0 +1,56 @@ +package callback_test + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/SevereCloud/vksdk/api" + "github.com/SevereCloud/vksdk/callback" + "github.com/SevereCloud/vksdk/events" + "github.com/stretchr/testify/assert" +) + +func TestAutoSetting_ErrAuth(t *testing.T) { + t.Parallel() + + vk := api.NewVK("") + + cb := callback.NewCallback() + cb.MessageNew(func(_ context.Context, obj events.MessageNewObject) {}) + err := cb.AutoSetting(vk, "https://example.com") + assert.Equal(t, true, errors.Is(err, api.ErrAuth), err) +} + +func TestAutoSetting_ErrNeedGroupToken(t *testing.T) { + t.Parallel() + + userToken := os.Getenv("USER_TOKEN") + if userToken == "" { + t.Skip("USER_TOKEN empty") + } + + vk := api.NewVK(userToken) + + cb := callback.NewCallback() + cb.MessageNew(func(_ context.Context, obj events.MessageNewObject) {}) + err := cb.AutoSetting(vk, "https://example.com") + assert.Equal(t, true, errors.Is(err, callback.ErrNeedGroupToken), err) +} + +func TestAutoSetting_Err(t *testing.T) { + t.Parallel() + + groupToken := os.Getenv("GROUP_TOKEN") + if groupToken == "" { + t.Skip("GROUP_TOKEN empty") + } + + vk := api.NewVK(groupToken) + + cb := callback.NewCallback() + cb.MessageNew(func(_ context.Context, obj events.MessageNewObject) {}) + err := cb.AutoSetting(vk, "https://example.com") + assert.NoError(t, err) +} From 8907c58239ee65f55aaed48c188b950282f8d6a9 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 15:16:58 +0300 Subject: [PATCH 100/105] fix: remove photo.*Tags methods --- api/params/photos.go | 20 -------------------- api/params/photos_test.go | 10 ---------- api/photos.go | 24 ------------------------ api/photos_test.go | 28 ---------------------------- 4 files changed, 82 deletions(-) diff --git a/api/params/photos.go b/api/params/photos.go index 8a1c7112..3c11e6e0 100644 --- a/api/params/photos.go +++ b/api/params/photos.go @@ -36,26 +36,6 @@ func (b *PhotosConfirmTagBuilder) TagID(v int) *PhotosConfirmTagBuilder { return b } -// PhotosConfirmTagsBuilder builder. -// -// Confirms a tag on a photo. -// -// https://vk.com/dev/photos.confirmTags -type PhotosConfirmTagsBuilder struct { - api.Params -} - -// NewPhotosConfirmTagsBuilder func. -func NewPhotosConfirmTagsBuilder() *PhotosConfirmTagsBuilder { - return &PhotosConfirmTagsBuilder{api.Params{}} -} - -// Tags parameter. -func (b *PhotosConfirmTagsBuilder) Tags(v string) *PhotosConfirmTagsBuilder { - b.Params["tags"] = v - return b -} - // PhotosCopyBuilder builder. // // Allows to copy a photo to the "Saved photos" album. diff --git a/api/params/photos_test.go b/api/params/photos_test.go index 51c171e0..47be2c4b 100644 --- a/api/params/photos_test.go +++ b/api/params/photos_test.go @@ -21,16 +21,6 @@ func TestPhotosConfirmTagBuilder(t *testing.T) { assert.Equal(t, b.Params["tag_id"], 1) } -func TestPhotosConfirmTagsBuilder(t *testing.T) { - t.Parallel() - - b := params.NewPhotosConfirmTagsBuilder() - - b.Tags("text") - - assert.Equal(t, b.Params["tags"], "text") -} - func TestPhotosCopyBuilder(t *testing.T) { t.Parallel() diff --git a/api/photos.go b/api/photos.go index 6063a930..0412d8c1 100644 --- a/api/photos.go +++ b/api/photos.go @@ -12,14 +12,6 @@ func (vk *VK) PhotosConfirmTag(params Params) (response int, err error) { return } -// PhotosConfirmTags confirms a tags on a photo. -// -// https://vk.com/dev/photos.confirmTags -func (vk *VK) PhotosConfirmTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.confirmTags", &response, params) - return -} - // PhotosCopy allows to copy a photo to the "Saved photos" album. // // https://vk.com/dev/photos.copy @@ -47,14 +39,6 @@ func (vk *VK) PhotosCreateComment(params Params) (response int, err error) { return } -// PhotosDeclineTags method. -// -// https://vk.com/dev/photos.declineTags -func (vk *VK) PhotosDeclineTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.declineTags", &response, params) - return -} - // PhotosDelete deletes a photo. // // https://vk.com/dev/photos.delete @@ -627,11 +611,3 @@ func (vk *VK) PhotosSearch(params Params) (response PhotosSearchResponse, err er err = vk.RequestUnmarshal("photos.search", &response, params) return } - -// PhotosSkipTags returns a list of photos. -// -// https://vk.com/dev/photos.skipTags -func (vk *VK) PhotosSkipTags(params Params) (response int, err error) { - err = vk.RequestUnmarshal("photos.skipTags", &response, params) - return -} diff --git a/api/photos_test.go b/api/photos_test.go index 8bbd3a07..d646b96b 100644 --- a/api/photos_test.go +++ b/api/photos_test.go @@ -22,16 +22,6 @@ func TestVK_PhotosConfirmTag(t *testing.T) { assert.Equal(t, 0, ok) } -func TestVK_PhotosConfirmTags(t *testing.T) { - t.Parallel() - - needUserToken(t) - - ok, err := vkUser.PhotosConfirmTags(nil) - noError(t, err) - assert.Equal(t, 0, ok) -} - func TestVK_PhotosCopy(t *testing.T) { t.Parallel() @@ -135,15 +125,6 @@ func TestVK_PhotosCreateComment(t *testing.T) { noError(t, err) } -func TestVK_PhotosDeclineTags(t *testing.T) { - t.Parallel() - - needUserToken(t) - - _, err := vkUser.PhotosDeclineTags(nil) - noError(t, err) -} - func LoadPhoto(t *testing.T, albumID int) object.PhotosPhoto { response, err := http.Get(photoURL) if err != nil { @@ -474,12 +455,3 @@ func TestVK_PhotosSearch(t *testing.T) { }) noError(t, err) } - -func TestVK_PhotosSkipTags(t *testing.T) { - t.Parallel() - - needUserToken(t) - - _, err := vkUser.PhotosSkipTags(nil) - noError(t, err) -} From 3932d85d26f9bf02db8fbbd17f16447e8fe9f0f7 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 18:04:00 +0300 Subject: [PATCH 101/105] BREAKING CHANGE: events remove type func --- events/events.go | 192 +++++++++++++++--------------- events/{handler.go => objects.go} | 146 ----------------------- 2 files changed, 96 insertions(+), 242 deletions(-) rename events/{handler.go => objects.go} (68%) diff --git a/events/events.go b/events/events.go index 916f0609..2b571e75 100644 --- a/events/events.go +++ b/events/events.go @@ -79,54 +79,54 @@ type GroupEvent struct { // FuncList struct. type FuncList struct { - messageNew []MessageNewFunc - messageReply []MessageReplyFunc - messageEdit []MessageEditFunc - messageAllow []MessageAllowFunc - messageDeny []MessageDenyFunc - messageTypingState []MessageTypingStateFunc - messageEvent []MessageEventFunc - photoNew []PhotoNewFunc - photoCommentNew []PhotoCommentNewFunc - photoCommentEdit []PhotoCommentEditFunc - photoCommentRestore []PhotoCommentRestoreFunc - photoCommentDelete []PhotoCommentDeleteFunc - audioNew []AudioNewFunc - videoNew []VideoNewFunc - videoCommentNew []VideoCommentNewFunc - videoCommentEdit []VideoCommentEditFunc - videoCommentRestore []VideoCommentRestoreFunc - videoCommentDelete []VideoCommentDeleteFunc - wallPostNew []WallPostNewFunc - wallRepost []WallRepostFunc - wallReplyNew []WallReplyNewFunc - wallReplyEdit []WallReplyEditFunc - wallReplyRestore []WallReplyRestoreFunc - wallReplyDelete []WallReplyDeleteFunc - boardPostNew []BoardPostNewFunc - boardPostEdit []BoardPostEditFunc - boardPostRestore []BoardPostRestoreFunc - boardPostDelete []BoardPostDeleteFunc - marketCommentNew []MarketCommentNewFunc - marketCommentEdit []MarketCommentEditFunc - marketCommentRestore []MarketCommentRestoreFunc - marketCommentDelete []MarketCommentDeleteFunc - marketOrderNew []MarketOrderNewFunc - marketOrderEdit []MarketOrderEditFunc - groupLeave []GroupLeaveFunc - groupJoin []GroupJoinFunc - userBlock []UserBlockFunc - userUnblock []UserUnblockFunc - pollVoteNew []PollVoteNewFunc - groupOfficersEdit []GroupOfficersEditFunc - groupChangeSettings []GroupChangeSettingsFunc - groupChangePhoto []GroupChangePhotoFunc - vkpayTransaction []VkpayTransactionFunc - leadFormsNew []LeadFormsNewFunc - appPayload []AppPayloadFunc - messageRead []MessageReadFunc - likeAdd []LikeAddFunc - likeRemove []LikeRemoveFunc + messageNew []func(context.Context, MessageNewObject) + messageReply []func(context.Context, MessageReplyObject) + messageEdit []func(context.Context, MessageEditObject) + messageAllow []func(context.Context, MessageAllowObject) + messageDeny []func(context.Context, MessageDenyObject) + messageTypingState []func(context.Context, MessageTypingStateObject) + messageEvent []func(context.Context, MessageEventObject) + photoNew []func(context.Context, PhotoNewObject) + photoCommentNew []func(context.Context, PhotoCommentNewObject) + photoCommentEdit []func(context.Context, PhotoCommentEditObject) + photoCommentRestore []func(context.Context, PhotoCommentRestoreObject) + photoCommentDelete []func(context.Context, PhotoCommentDeleteObject) + audioNew []func(context.Context, AudioNewObject) + videoNew []func(context.Context, VideoNewObject) + videoCommentNew []func(context.Context, VideoCommentNewObject) + videoCommentEdit []func(context.Context, VideoCommentEditObject) + videoCommentRestore []func(context.Context, VideoCommentRestoreObject) + videoCommentDelete []func(context.Context, VideoCommentDeleteObject) + wallPostNew []func(context.Context, WallPostNewObject) + wallRepost []func(context.Context, WallRepostObject) + wallReplyNew []func(context.Context, WallReplyNewObject) + wallReplyEdit []func(context.Context, WallReplyEditObject) + wallReplyRestore []func(context.Context, WallReplyRestoreObject) + wallReplyDelete []func(context.Context, WallReplyDeleteObject) + boardPostNew []func(context.Context, BoardPostNewObject) + boardPostEdit []func(context.Context, BoardPostEditObject) + boardPostRestore []func(context.Context, BoardPostRestoreObject) + boardPostDelete []func(context.Context, BoardPostDeleteObject) + marketCommentNew []func(context.Context, MarketCommentNewObject) + marketCommentEdit []func(context.Context, MarketCommentEditObject) + marketCommentRestore []func(context.Context, MarketCommentRestoreObject) + marketCommentDelete []func(context.Context, MarketCommentDeleteObject) + marketOrderNew []func(context.Context, MarketOrderNewObject) + marketOrderEdit []func(context.Context, MarketOrderEditObject) + groupLeave []func(context.Context, GroupLeaveObject) + groupJoin []func(context.Context, GroupJoinObject) + userBlock []func(context.Context, UserBlockObject) + userUnblock []func(context.Context, UserUnblockObject) + pollVoteNew []func(context.Context, PollVoteNewObject) + groupOfficersEdit []func(context.Context, GroupOfficersEditObject) + groupChangeSettings []func(context.Context, GroupChangeSettingsObject) + groupChangePhoto []func(context.Context, GroupChangePhotoObject) + vkpayTransaction []func(context.Context, VkpayTransactionObject) + leadFormsNew []func(context.Context, LeadFormsNewObject) + appPayload []func(context.Context, AppPayloadObject) + messageRead []func(context.Context, MessageReadObject) + likeAdd []func(context.Context, LikeAddObject) + likeRemove []func(context.Context, LikeRemoveObject) special map[EventType][]func(context.Context, GroupEvent) eventsList []EventType } @@ -603,289 +603,289 @@ func (fl *FuncList) OnEvent(eventType EventType, f func(context.Context, GroupEv } // MessageNew handler. -func (fl *FuncList) MessageNew(f MessageNewFunc) { +func (fl *FuncList) MessageNew(f func(context.Context, MessageNewObject)) { fl.messageNew = append(fl.messageNew, f) fl.eventsList = append(fl.eventsList, EventMessageNew) } // MessageReply handler. -func (fl *FuncList) MessageReply(f MessageReplyFunc) { +func (fl *FuncList) MessageReply(f func(context.Context, MessageReplyObject)) { fl.messageReply = append(fl.messageReply, f) fl.eventsList = append(fl.eventsList, EventMessageReply) } // MessageEdit handler. -func (fl *FuncList) MessageEdit(f MessageEditFunc) { +func (fl *FuncList) MessageEdit(f func(context.Context, MessageEditObject)) { fl.messageEdit = append(fl.messageEdit, f) fl.eventsList = append(fl.eventsList, EventMessageEdit) } // MessageAllow handler. -func (fl *FuncList) MessageAllow(f MessageAllowFunc) { +func (fl *FuncList) MessageAllow(f func(context.Context, MessageAllowObject)) { fl.messageAllow = append(fl.messageAllow, f) fl.eventsList = append(fl.eventsList, EventMessageAllow) } // MessageDeny handler. -func (fl *FuncList) MessageDeny(f MessageDenyFunc) { +func (fl *FuncList) MessageDeny(f func(context.Context, MessageDenyObject)) { fl.messageDeny = append(fl.messageDeny, f) fl.eventsList = append(fl.eventsList, EventMessageDeny) } // MessageTypingState handler. -func (fl *FuncList) MessageTypingState(f MessageTypingStateFunc) { +func (fl *FuncList) MessageTypingState(f func(context.Context, MessageTypingStateObject)) { fl.messageTypingState = append(fl.messageTypingState, f) fl.eventsList = append(fl.eventsList, EventMessageTypingState) } // MessageEvent handler. -func (fl *FuncList) MessageEvent(f MessageEventFunc) { +func (fl *FuncList) MessageEvent(f func(context.Context, MessageEventObject)) { fl.messageEvent = append(fl.messageEvent, f) fl.eventsList = append(fl.eventsList, EventMessageEvent) } // PhotoNew handler. -func (fl *FuncList) PhotoNew(f PhotoNewFunc) { +func (fl *FuncList) PhotoNew(f func(context.Context, PhotoNewObject)) { fl.photoNew = append(fl.photoNew, f) fl.eventsList = append(fl.eventsList, EventPhotoNew) } // PhotoCommentNew handler. -func (fl *FuncList) PhotoCommentNew(f PhotoCommentNewFunc) { +func (fl *FuncList) PhotoCommentNew(f func(context.Context, PhotoCommentNewObject)) { fl.photoCommentNew = append(fl.photoCommentNew, f) fl.eventsList = append(fl.eventsList, EventPhotoCommentNew) } // PhotoCommentEdit handler. -func (fl *FuncList) PhotoCommentEdit(f PhotoCommentEditFunc) { +func (fl *FuncList) PhotoCommentEdit(f func(context.Context, PhotoCommentEditObject)) { fl.photoCommentEdit = append(fl.photoCommentEdit, f) fl.eventsList = append(fl.eventsList, EventPhotoCommentEdit) } // PhotoCommentRestore handler. -func (fl *FuncList) PhotoCommentRestore(f PhotoCommentRestoreFunc) { +func (fl *FuncList) PhotoCommentRestore(f func(context.Context, PhotoCommentRestoreObject)) { fl.photoCommentRestore = append(fl.photoCommentRestore, f) fl.eventsList = append(fl.eventsList, EventPhotoCommentRestore) } // PhotoCommentDelete handler. -func (fl *FuncList) PhotoCommentDelete(f PhotoCommentDeleteFunc) { +func (fl *FuncList) PhotoCommentDelete(f func(context.Context, PhotoCommentDeleteObject)) { fl.photoCommentDelete = append(fl.photoCommentDelete, f) fl.eventsList = append(fl.eventsList, EventPhotoCommentDelete) } // AudioNew handler. -func (fl *FuncList) AudioNew(f AudioNewFunc) { +func (fl *FuncList) AudioNew(f func(context.Context, AudioNewObject)) { fl.audioNew = append(fl.audioNew, f) fl.eventsList = append(fl.eventsList, EventAudioNew) } // VideoNew handler. -func (fl *FuncList) VideoNew(f VideoNewFunc) { +func (fl *FuncList) VideoNew(f func(context.Context, VideoNewObject)) { fl.videoNew = append(fl.videoNew, f) fl.eventsList = append(fl.eventsList, EventVideoNew) } // VideoCommentNew handler. -func (fl *FuncList) VideoCommentNew(f VideoCommentNewFunc) { +func (fl *FuncList) VideoCommentNew(f func(context.Context, VideoCommentNewObject)) { fl.videoCommentNew = append(fl.videoCommentNew, f) fl.eventsList = append(fl.eventsList, EventVideoCommentNew) } // VideoCommentEdit handler. -func (fl *FuncList) VideoCommentEdit(f VideoCommentEditFunc) { +func (fl *FuncList) VideoCommentEdit(f func(context.Context, VideoCommentEditObject)) { fl.videoCommentEdit = append(fl.videoCommentEdit, f) fl.eventsList = append(fl.eventsList, EventVideoCommentEdit) } // VideoCommentRestore handler. -func (fl *FuncList) VideoCommentRestore(f VideoCommentRestoreFunc) { +func (fl *FuncList) VideoCommentRestore(f func(context.Context, VideoCommentRestoreObject)) { fl.videoCommentRestore = append(fl.videoCommentRestore, f) fl.eventsList = append(fl.eventsList, EventVideoCommentRestore) } // VideoCommentDelete handler. -func (fl *FuncList) VideoCommentDelete(f VideoCommentDeleteFunc) { +func (fl *FuncList) VideoCommentDelete(f func(context.Context, VideoCommentDeleteObject)) { fl.videoCommentDelete = append(fl.videoCommentDelete, f) fl.eventsList = append(fl.eventsList, EventVideoCommentDelete) } // WallPostNew handler. -func (fl *FuncList) WallPostNew(f WallPostNewFunc) { +func (fl *FuncList) WallPostNew(f func(context.Context, WallPostNewObject)) { fl.wallPostNew = append(fl.wallPostNew, f) fl.eventsList = append(fl.eventsList, EventWallPostNew) } // WallRepost handler. -func (fl *FuncList) WallRepost(f WallRepostFunc) { +func (fl *FuncList) WallRepost(f func(context.Context, WallRepostObject)) { fl.wallRepost = append(fl.wallRepost, f) fl.eventsList = append(fl.eventsList, EventWallRepost) } // WallReplyNew handler. -func (fl *FuncList) WallReplyNew(f WallReplyNewFunc) { +func (fl *FuncList) WallReplyNew(f func(context.Context, WallReplyNewObject)) { fl.wallReplyNew = append(fl.wallReplyNew, f) fl.eventsList = append(fl.eventsList, EventWallReplyNew) } // WallReplyEdit handler. -func (fl *FuncList) WallReplyEdit(f WallReplyEditFunc) { +func (fl *FuncList) WallReplyEdit(f func(context.Context, WallReplyEditObject)) { fl.wallReplyEdit = append(fl.wallReplyEdit, f) fl.eventsList = append(fl.eventsList, EventWallReplyEdit) } // WallReplyRestore handler. -func (fl *FuncList) WallReplyRestore(f WallReplyRestoreFunc) { +func (fl *FuncList) WallReplyRestore(f func(context.Context, WallReplyRestoreObject)) { fl.wallReplyRestore = append(fl.wallReplyRestore, f) fl.eventsList = append(fl.eventsList, EventWallReplyRestore) } // WallReplyDelete handler. -func (fl *FuncList) WallReplyDelete(f WallReplyDeleteFunc) { +func (fl *FuncList) WallReplyDelete(f func(context.Context, WallReplyDeleteObject)) { fl.wallReplyDelete = append(fl.wallReplyDelete, f) fl.eventsList = append(fl.eventsList, EventWallReplyDelete) } // BoardPostNew handler. -func (fl *FuncList) BoardPostNew(f BoardPostNewFunc) { +func (fl *FuncList) BoardPostNew(f func(context.Context, BoardPostNewObject)) { fl.boardPostNew = append(fl.boardPostNew, f) fl.eventsList = append(fl.eventsList, EventBoardPostNew) } // BoardPostEdit handler. -func (fl *FuncList) BoardPostEdit(f BoardPostEditFunc) { +func (fl *FuncList) BoardPostEdit(f func(context.Context, BoardPostEditObject)) { fl.boardPostEdit = append(fl.boardPostEdit, f) fl.eventsList = append(fl.eventsList, EventBoardPostEdit) } // BoardPostRestore handler. -func (fl *FuncList) BoardPostRestore(f BoardPostRestoreFunc) { +func (fl *FuncList) BoardPostRestore(f func(context.Context, BoardPostRestoreObject)) { fl.boardPostRestore = append(fl.boardPostRestore, f) fl.eventsList = append(fl.eventsList, EventBoardPostRestore) } // BoardPostDelete handler. -func (fl *FuncList) BoardPostDelete(f BoardPostDeleteFunc) { +func (fl *FuncList) BoardPostDelete(f func(context.Context, BoardPostDeleteObject)) { fl.boardPostDelete = append(fl.boardPostDelete, f) fl.eventsList = append(fl.eventsList, EventBoardPostDelete) } // MarketCommentNew handler. -func (fl *FuncList) MarketCommentNew(f MarketCommentNewFunc) { +func (fl *FuncList) MarketCommentNew(f func(context.Context, MarketCommentNewObject)) { fl.marketCommentNew = append(fl.marketCommentNew, f) fl.eventsList = append(fl.eventsList, EventMarketCommentNew) } // MarketCommentEdit handler. -func (fl *FuncList) MarketCommentEdit(f MarketCommentEditFunc) { +func (fl *FuncList) MarketCommentEdit(f func(context.Context, MarketCommentEditObject)) { fl.marketCommentEdit = append(fl.marketCommentEdit, f) fl.eventsList = append(fl.eventsList, EventMarketCommentEdit) } // MarketCommentRestore handler. -func (fl *FuncList) MarketCommentRestore(f MarketCommentRestoreFunc) { +func (fl *FuncList) MarketCommentRestore(f func(context.Context, MarketCommentRestoreObject)) { fl.marketCommentRestore = append(fl.marketCommentRestore, f) fl.eventsList = append(fl.eventsList, EventMarketCommentRestore) } // MarketCommentDelete handler. -func (fl *FuncList) MarketCommentDelete(f MarketCommentDeleteFunc) { +func (fl *FuncList) MarketCommentDelete(f func(context.Context, MarketCommentDeleteObject)) { fl.marketCommentDelete = append(fl.marketCommentDelete, f) fl.eventsList = append(fl.eventsList, EventMarketCommentDelete) } // MarketOrderNew handler. -func (fl *FuncList) MarketOrderNew(f MarketOrderNewFunc) { +func (fl *FuncList) MarketOrderNew(f func(context.Context, MarketOrderNewObject)) { fl.marketOrderNew = append(fl.marketOrderNew, f) fl.eventsList = append(fl.eventsList, EventMarketOrderNew) } // MarketOrderEdit handler. -func (fl *FuncList) MarketOrderEdit(f MarketOrderEditFunc) { +func (fl *FuncList) MarketOrderEdit(f func(context.Context, MarketOrderEditObject)) { fl.marketOrderEdit = append(fl.marketOrderEdit, f) fl.eventsList = append(fl.eventsList, EventMarketOrderEdit) } // GroupLeave handler. -func (fl *FuncList) GroupLeave(f GroupLeaveFunc) { +func (fl *FuncList) GroupLeave(f func(context.Context, GroupLeaveObject)) { fl.groupLeave = append(fl.groupLeave, f) fl.eventsList = append(fl.eventsList, EventGroupLeave) } // GroupJoin handler. -func (fl *FuncList) GroupJoin(f GroupJoinFunc) { +func (fl *FuncList) GroupJoin(f func(context.Context, GroupJoinObject)) { fl.groupJoin = append(fl.groupJoin, f) fl.eventsList = append(fl.eventsList, EventGroupJoin) } // UserBlock handler. -func (fl *FuncList) UserBlock(f UserBlockFunc) { +func (fl *FuncList) UserBlock(f func(context.Context, UserBlockObject)) { fl.userBlock = append(fl.userBlock, f) fl.eventsList = append(fl.eventsList, EventUserBlock) } // UserUnblock handler. -func (fl *FuncList) UserUnblock(f UserUnblockFunc) { +func (fl *FuncList) UserUnblock(f func(context.Context, UserUnblockObject)) { fl.userUnblock = append(fl.userUnblock, f) fl.eventsList = append(fl.eventsList, EventUserUnblock) } // PollVoteNew handler. -func (fl *FuncList) PollVoteNew(f PollVoteNewFunc) { +func (fl *FuncList) PollVoteNew(f func(context.Context, PollVoteNewObject)) { fl.pollVoteNew = append(fl.pollVoteNew, f) fl.eventsList = append(fl.eventsList, EventPollVoteNew) } // GroupOfficersEdit handler. -func (fl *FuncList) GroupOfficersEdit(f GroupOfficersEditFunc) { +func (fl *FuncList) GroupOfficersEdit(f func(context.Context, GroupOfficersEditObject)) { fl.groupOfficersEdit = append(fl.groupOfficersEdit, f) fl.eventsList = append(fl.eventsList, EventGroupOfficersEdit) } // GroupChangeSettings handler. -func (fl *FuncList) GroupChangeSettings(f GroupChangeSettingsFunc) { +func (fl *FuncList) GroupChangeSettings(f func(context.Context, GroupChangeSettingsObject)) { fl.groupChangeSettings = append(fl.groupChangeSettings, f) fl.eventsList = append(fl.eventsList, EventGroupChangeSettings) } // GroupChangePhoto handler. -func (fl *FuncList) GroupChangePhoto(f GroupChangePhotoFunc) { +func (fl *FuncList) GroupChangePhoto(f func(context.Context, GroupChangePhotoObject)) { fl.groupChangePhoto = append(fl.groupChangePhoto, f) fl.eventsList = append(fl.eventsList, EventGroupChangePhoto) } // VkpayTransaction handler. -func (fl *FuncList) VkpayTransaction(f VkpayTransactionFunc) { +func (fl *FuncList) VkpayTransaction(f func(context.Context, VkpayTransactionObject)) { fl.vkpayTransaction = append(fl.vkpayTransaction, f) fl.eventsList = append(fl.eventsList, EventVkpayTransaction) } // LeadFormsNew handler. -func (fl *FuncList) LeadFormsNew(f LeadFormsNewFunc) { +func (fl *FuncList) LeadFormsNew(f func(context.Context, LeadFormsNewObject)) { fl.leadFormsNew = append(fl.leadFormsNew, f) fl.eventsList = append(fl.eventsList, EventLeadFormsNew) } // AppPayload handler. -func (fl *FuncList) AppPayload(f AppPayloadFunc) { +func (fl *FuncList) AppPayload(f func(context.Context, AppPayloadObject)) { fl.appPayload = append(fl.appPayload, f) fl.eventsList = append(fl.eventsList, EventAppPayload) } // MessageRead handler. -func (fl *FuncList) MessageRead(f MessageReadFunc) { +func (fl *FuncList) MessageRead(f func(context.Context, MessageReadObject)) { fl.messageRead = append(fl.messageRead, f) fl.eventsList = append(fl.eventsList, EventMessageRead) } // LikeAdd handler. -func (fl *FuncList) LikeAdd(f LikeAddFunc) { +func (fl *FuncList) LikeAdd(f func(context.Context, LikeAddObject)) { fl.likeAdd = append(fl.likeAdd, f) fl.eventsList = append(fl.eventsList, EventLikeAdd) } // LikeRemove handler. -func (fl *FuncList) LikeRemove(f LikeRemoveFunc) { +func (fl *FuncList) LikeRemove(f func(context.Context, LikeRemoveObject)) { fl.likeRemove = append(fl.likeRemove, f) fl.eventsList = append(fl.eventsList, EventLikeRemove) } diff --git a/events/handler.go b/events/objects.go similarity index 68% rename from events/handler.go rename to events/objects.go index 31902ac7..6b7cc905 100644 --- a/events/handler.go +++ b/events/objects.go @@ -1,52 +1,32 @@ package events // import "github.com/SevereCloud/vksdk/events" import ( - "context" - "github.com/SevereCloud/vksdk/object" ) -// MessageNewFunc func. -type MessageNewFunc func(context.Context, MessageNewObject) - // MessageNewObject struct. type MessageNewObject struct { Message object.MessagesMessage `json:"message"` ClientInfo object.ClientInfo `json:"client_info"` } -// MessageReplyFunc func. -type MessageReplyFunc func(context.Context, MessageReplyObject) - // MessageReplyObject struct. type MessageReplyObject object.MessagesMessage -// MessageEditFunc func. -type MessageEditFunc func(context.Context, MessageEditObject) - // MessageEditObject struct. type MessageEditObject object.MessagesMessage -// MessageAllowFunc func. -type MessageAllowFunc func(context.Context, MessageAllowObject) - // MessageAllowObject struct. type MessageAllowObject struct { UserID int `json:"user_id"` Key string `json:"key"` } -// MessageDenyFunc func. -type MessageDenyFunc func(context.Context, MessageDenyObject) - // MessageDenyObject struct. type MessageDenyObject struct { UserID int `json:"user_id"` } -// MessageTypingStateFunc func. -type MessageTypingStateFunc func(context.Context, MessageTypingStateObject) - // MessageTypingStateObject struct. type MessageTypingStateObject struct { State string `json:"state"` @@ -54,9 +34,6 @@ type MessageTypingStateObject struct { ToID int `json:"to_id"` } -// MessageEventFunc func. -type MessageEventFunc func(context.Context, MessageEventObject) - // MessageEventObject struct. type MessageEventObject struct { UserID int `json:"user_id"` @@ -66,33 +43,18 @@ type MessageEventObject struct { ConversationMessageID int `json:"conversation_message_id"` } -// PhotoNewFunc func. -type PhotoNewFunc func(context.Context, PhotoNewObject) - // PhotoNewObject struct. type PhotoNewObject object.PhotosPhoto -// PhotoCommentNewFunc func. -type PhotoCommentNewFunc func(context.Context, PhotoCommentNewObject) - // PhotoCommentNewObject struct. type PhotoCommentNewObject object.WallWallComment -// PhotoCommentEditFunc func. -type PhotoCommentEditFunc func(context.Context, PhotoCommentEditObject) - // PhotoCommentEditObject struct. type PhotoCommentEditObject object.WallWallComment -// PhotoCommentRestoreFunc func. -type PhotoCommentRestoreFunc func(context.Context, PhotoCommentRestoreObject) - // PhotoCommentRestoreObject struct. type PhotoCommentRestoreObject object.WallWallComment -// PhotoCommentDeleteFunc func. -type PhotoCommentDeleteFunc func(context.Context, PhotoCommentDeleteObject) - // PhotoCommentDeleteObject struct. type PhotoCommentDeleteObject struct { OwnerID int `json:"owner_id"` @@ -102,39 +64,21 @@ type PhotoCommentDeleteObject struct { PhotoID int `json:"photo_id"` } -// AudioNewFunc func. -type AudioNewFunc func(context.Context, AudioNewObject) - // AudioNewObject struct. type AudioNewObject object.AudioAudio -// VideoNewFunc func. -type VideoNewFunc func(context.Context, VideoNewObject) - // VideoNewObject struct. type VideoNewObject object.VideoVideo -// VideoCommentNewFunc func. -type VideoCommentNewFunc func(context.Context, VideoCommentNewObject) - // VideoCommentNewObject struct. type VideoCommentNewObject object.WallWallComment -// VideoCommentEditFunc func. -type VideoCommentEditFunc func(context.Context, VideoCommentEditObject) - // VideoCommentEditObject struct. type VideoCommentEditObject object.WallWallComment -// VideoCommentRestoreFunc func. -type VideoCommentRestoreFunc func(context.Context, VideoCommentRestoreObject) - // VideoCommentRestoreObject struct. type VideoCommentRestoreObject object.WallWallComment -// VideoCommentDeleteFunc func. -type VideoCommentDeleteFunc func(context.Context, VideoCommentDeleteObject) - // VideoCommentDeleteObject struct. type VideoCommentDeleteObject struct { OwnerID int `json:"owner_id"` @@ -144,39 +88,21 @@ type VideoCommentDeleteObject struct { VideoID int `json:"video_id"` } -// WallPostNewFunc func. -type WallPostNewFunc func(context.Context, WallPostNewObject) - // WallPostNewObject struct. type WallPostNewObject object.WallWallpost -// WallRepostFunc func. -type WallRepostFunc func(context.Context, WallRepostObject) - // WallRepostObject struct. type WallRepostObject object.WallWallpost -// WallReplyNewFunc func. -type WallReplyNewFunc func(context.Context, WallReplyNewObject) - // WallReplyNewObject struct. type WallReplyNewObject object.WallWallComment -// WallReplyEditFunc func. -type WallReplyEditFunc func(context.Context, WallReplyEditObject) - // WallReplyEditObject struct. type WallReplyEditObject object.WallWallComment -// WallReplyRestoreFunc func. -type WallReplyRestoreFunc func(context.Context, WallReplyRestoreObject) - // WallReplyRestoreObject struct. type WallReplyRestoreObject object.WallWallComment -// WallReplyDeleteFunc func. -type WallReplyDeleteFunc func(context.Context, WallReplyDeleteObject) - // WallReplyDeleteObject struct. type WallReplyDeleteObject struct { OwnerID int `json:"owner_id"` @@ -185,27 +111,15 @@ type WallReplyDeleteObject struct { PostID int `json:"post_id"` } -// BoardPostNewFunc func. -type BoardPostNewFunc func(context.Context, BoardPostNewObject) - // BoardPostNewObject struct. type BoardPostNewObject object.BoardTopicComment -// BoardPostEditFunc func. -type BoardPostEditFunc func(context.Context, BoardPostEditObject) - // BoardPostEditObject struct. type BoardPostEditObject object.BoardTopicComment -// BoardPostRestoreFunc func. -type BoardPostRestoreFunc func(context.Context, BoardPostRestoreObject) - // BoardPostRestoreObject struct. type BoardPostRestoreObject object.BoardTopicComment -// BoardPostDeleteFunc func. -type BoardPostDeleteFunc func(context.Context, BoardPostDeleteObject) - // BoardPostDeleteObject struct. type BoardPostDeleteObject struct { TopicOwnerID int `json:"topic_owner_id"` @@ -213,27 +127,15 @@ type BoardPostDeleteObject struct { ID int `json:"id"` } -// MarketCommentNewFunc func. -type MarketCommentNewFunc func(context.Context, MarketCommentNewObject) - // MarketCommentNewObject struct. type MarketCommentNewObject object.WallWallComment -// MarketCommentEditFunc func. -type MarketCommentEditFunc func(context.Context, MarketCommentEditObject) - // MarketCommentEditObject struct. type MarketCommentEditObject object.WallWallComment -// MarketCommentRestoreFunc func. -type MarketCommentRestoreFunc func(context.Context, MarketCommentRestoreObject) - // MarketCommentRestoreObject struct. type MarketCommentRestoreObject object.WallWallComment -// MarketCommentDeleteFunc func. -type MarketCommentDeleteFunc func(context.Context, MarketCommentDeleteObject) - // MarketCommentDeleteObject struct. type MarketCommentDeleteObject struct { OwnerID int `json:"owner_id"` @@ -243,39 +145,24 @@ type MarketCommentDeleteObject struct { ItemID int `json:"item_id"` } -// MarketOrderNewFunc func. -type MarketOrderNewFunc func(context.Context, MarketOrderNewObject) - // MarketOrderNewObject struct. type MarketOrderNewObject object.MarketOrder -// MarketOrderEditFunc func. -type MarketOrderEditFunc func(context.Context, MarketOrderEditObject) - // MarketOrderEditObject struct. type MarketOrderEditObject object.MarketOrder -// GroupLeaveFunc func. -type GroupLeaveFunc func(context.Context, GroupLeaveObject) - // GroupLeaveObject struct. type GroupLeaveObject struct { UserID int `json:"user_id"` Self object.BaseBoolInt `json:"self"` } -// GroupJoinFunc func. -type GroupJoinFunc func(context.Context, GroupJoinObject) - // GroupJoinObject struct. type GroupJoinObject struct { UserID int `json:"user_id"` JoinType string `json:"join_type"` } -// UserBlockFunc func. -type UserBlockFunc func(context.Context, UserBlockObject) - // UserBlockObject struct. type UserBlockObject struct { AdminID int `json:"admin_id"` @@ -285,9 +172,6 @@ type UserBlockObject struct { Comment string `json:"comment"` } -// UserUnblockFunc func. -type UserUnblockFunc func(context.Context, UserUnblockObject) - // UserUnblockObject struct. type UserUnblockObject struct { AdminID int `json:"admin_id"` @@ -295,9 +179,6 @@ type UserUnblockObject struct { ByEndDate int `json:"by_end_date"` } -// PollVoteNewFunc func. -type PollVoteNewFunc func(context.Context, PollVoteNewObject) - // PollVoteNewObject struct. // // BUG(VK): при голосовании за несколько вариантов, возвращается только один. @@ -308,9 +189,6 @@ type PollVoteNewObject struct { UserID int `json:"user_id"` } -// GroupOfficersEditFunc func. -type GroupOfficersEditFunc func(context.Context, GroupOfficersEditObject) - // GroupOfficersEditObject struct. type GroupOfficersEditObject struct { AdminID int `json:"admin_id"` @@ -331,9 +209,6 @@ type ChangesInt struct { NewValue int `json:"new_value"` } -// GroupChangeSettingsFunc func. -type GroupChangeSettingsFunc func(context.Context, GroupChangeSettingsObject) - // GroupChangeSettingsObject struct // // BUG(VK): Phone https://vk.com/bugtracker?act=show&id=64240 @@ -374,18 +249,12 @@ type GroupChangeSettingsObject struct { } `json:"Changes"` } -// GroupChangePhotoFunc func. -type GroupChangePhotoFunc func(context.Context, GroupChangePhotoObject) - // GroupChangePhotoObject struct. type GroupChangePhotoObject struct { UserID int `json:"user_id"` Photo object.PhotosPhoto `json:"photo"` } -// VkpayTransactionFunc func. -type VkpayTransactionFunc func(context.Context, VkpayTransactionObject) - // VkpayTransactionObject struct. type VkpayTransactionObject struct { FromID int `json:"from_id"` @@ -394,9 +263,6 @@ type VkpayTransactionObject struct { Date int `json:"date"` } -// LeadFormsNewFunc func. -type LeadFormsNewFunc func(context.Context, LeadFormsNewObject) - // LeadFormsNewObject struct. type LeadFormsNewObject struct { LeadID int `json:"lead_id"` @@ -412,9 +278,6 @@ type LeadFormsNewObject struct { } `json:"answers"` } -// AppPayloadFunc func. -type AppPayloadFunc func(context.Context, AppPayloadObject) - // AppPayloadObject struct. type AppPayloadObject struct { UserID int `json:"user_id"` @@ -422,9 +285,6 @@ type AppPayloadObject struct { Payload string `json:"payload"` } -// MessageReadFunc func. -type MessageReadFunc func(context.Context, MessageReadObject) - // MessageReadObject struct. type MessageReadObject struct { FromID int `json:"from_id"` @@ -432,9 +292,6 @@ type MessageReadObject struct { ReadMessageID int `json:"read_message_id"` } -// LikeAddFunc func. -type LikeAddFunc func(context.Context, LikeAddObject) - // LikeAddObject struct. type LikeAddObject struct { LikerID int `json:"liker_id"` @@ -445,9 +302,6 @@ type LikeAddObject struct { PostID int `json:"post_id"` // for comment } -// LikeRemoveFunc func. -type LikeRemoveFunc func(context.Context, LikeRemoveObject) - // LikeRemoveObject struct. type LikeRemoveObject struct { LikerID int `json:"liker_id"` From 7c30ff7a9842eb84eb36aceda0b9cba6417cdc03 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 18:47:41 +0300 Subject: [PATCH 102/105] feat: autoSetting for Longpoll bots --- longpoll-bot/longpoll.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/longpoll-bot/longpoll.go b/longpoll-bot/longpoll.go index 24ebfdf3..65f4acdd 100644 --- a/longpoll-bot/longpoll.go +++ b/longpoll-bot/longpoll.go @@ -12,6 +12,7 @@ import ( "net/http" "sync/atomic" + "github.com/SevereCloud/vksdk" "github.com/SevereCloud/vksdk/internal" "github.com/SevereCloud/vksdk/api" @@ -142,10 +143,31 @@ func (lp *Longpoll) checkResponse(response Response) (err error) { return } +func (lp Longpoll) autoSetting() error { + params := api.Params{ + "group_id": lp.GroupID, + "enabled": true, + "api_version": vksdk.API, + } + for _, event := range lp.ListEvents() { + params[string(event)] = true + } + + // Updating LongPoll settings + _, err := lp.VK.GroupsSetLongPollSettings(params) + + return err +} + // Run handler. func (lp *Longpoll) Run() error { atomic.StoreInt32(&lp.inShutdown, 0) + err := lp.autoSetting() + if err != nil { + return err + } + for atomic.LoadInt32(&lp.inShutdown) == 0 { resp, err := lp.check() if err != nil { From e18c9965a3e6037e301d8dce1caa038d89e25b9c Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 18:47:59 +0300 Subject: [PATCH 103/105] test: callback_test package --- callback/callback_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/callback/callback_test.go b/callback/callback_test.go index 8180dfd7..78dfeffe 100644 --- a/callback/callback_test.go +++ b/callback/callback_test.go @@ -1,4 +1,4 @@ -package callback +package callback_test import ( "bytes" @@ -6,6 +6,7 @@ import ( "net/http/httptest" "testing" + "github.com/SevereCloud/vksdk/callback" "github.com/stretchr/testify/assert" ) @@ -180,7 +181,7 @@ func TestCallback_HandleFunc(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - cb := Callback{ + cb := callback.Callback{ ConfirmationKeys: tt.fields.ConfirmationKeys, ConfirmationKey: tt.fields.ConfirmationKey, SecretKeys: tt.fields.SecretKeys, @@ -207,6 +208,6 @@ func TestCallback_HandleFunc(t *testing.T) { func TestNewCallback(t *testing.T) { t.Parallel() - cb := NewCallback() + cb := callback.NewCallback() assert.NotNil(t, cb) } From 4d7b2be66ccab751012d6b7ee206ea2e4da8f033 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Fri, 4 Sep 2020 18:53:39 +0300 Subject: [PATCH 104/105] BREAKING CHANGE: rename Longpoll -> LongPoll --- README.md | 8 +++---- api/messages.go | 2 +- internal/transport.go | 2 +- longpoll-bot/README.md | 10 ++++----- longpoll-bot/context.go | 2 +- longpoll-bot/context_test.go | 2 +- longpoll-bot/longpoll.go | 36 ++++++++++++++++---------------- longpoll-bot/longpoll_test.go | 36 ++++++++++++++++---------------- longpoll-user/README.md | 6 +++--- longpoll-user/longpoll.go | 30 +++++++++++++------------- longpoll-user/v3/wrapper.go | 4 ++-- longpoll-user/v3/wrapper_test.go | 2 +- object/messages.go | 4 ++-- object/object.go | 4 ++-- 14 files changed, 74 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 3c8ded17..066aba28 100644 --- a/README.md +++ b/README.md @@ -82,8 +82,8 @@ func main() { log.Fatal(err) } - // Инициализируем longpoll - lp, err := longpoll.NewLongpoll(vk, group[0].ID) + // Инициализируем Long Poll + lp, err := longpoll.NewLongPoll(vk, group[0].ID) if err != nil { log.Fatal(err) } @@ -105,8 +105,8 @@ func main() { } }) - // Запускаем Bots Longpoll - log.Println("Start longpoll") + // Запускаем Bots Long Poll + log.Println("Start Long Poll") if err := lp.Run(); err != nil { log.Fatal(err) } diff --git a/api/messages.go b/api/messages.go index 3a8f6eee..d529d9e7 100644 --- a/api/messages.go +++ b/api/messages.go @@ -363,7 +363,7 @@ func (vk *VK) MessagesGetLongPollHistory(params Params) (response MessagesGetLon } // MessagesGetLongPollServerResponse struct. -type MessagesGetLongPollServerResponse object.MessagesLongpollParams +type MessagesGetLongPollServerResponse object.MessagesLongPollParams // MessagesGetLongPollServer returns data required for connection to a Long Poll server. // diff --git a/internal/transport.go b/internal/transport.go index 8356f846..cfcf7911 100644 --- a/internal/transport.go +++ b/internal/transport.go @@ -24,7 +24,7 @@ const ( UserAgentKey GroupIDKey EventIDKey - LongpollTsKey + LongPollTsKey ) // ContextClient return *http.Client. diff --git a/longpoll-bot/README.md b/longpoll-bot/README.md index f66e28f8..cd3f2efb 100644 --- a/longpoll-bot/README.md +++ b/longpoll-bot/README.md @@ -5,8 +5,8 @@ ## Подключение Bots Long Poll API -Чтобы использовать Bots Long Poll API, откройте раздел «Управление сообществом», -на вкладке «Работа с API»→«Long Poll API» выберите «Включён». +Long Poll настраивается автоматически. Вам не требуется заходить в настройки +сообщества. ### Версия API @@ -27,7 +27,7 @@ vk := api.NewVK("") А потом сам longpoll ```go -lp, err := longpoll.NewLongpoll(vk api.VK, groupID int) +lp, err := longpoll.NewLongPoll(vk api.VK, groupID int) // По умолчанию Wait = 25 // lp.Wait = 90 // lp.Ts = "123" @@ -66,7 +66,7 @@ lp.MessageNew(func(ctx context.Context, obj events.MessageNewObject) { или специальной обработки `failed`), можно воспользоваться следующим обработчиком. ```go -lp.FullResponse(func(resp object.LongpollBotResponse) { +lp.FullResponse(func(resp object.LongPollBotResponse) { ... }) ``` @@ -117,7 +117,7 @@ import ( func main() { vk := api.NewVK("") - lp, err := longpoll.NewLongpoll(vk, 12345678) + lp, err := longpoll.NewLongPoll(vk, 12345678) if err != nil { panic(err) } diff --git a/longpoll-bot/context.go b/longpoll-bot/context.go index ed8e1816..71affb61 100644 --- a/longpoll-bot/context.go +++ b/longpoll-bot/context.go @@ -8,5 +8,5 @@ import ( // TsFromContext returns the ts from context. func TsFromContext(ctx context.Context) int { - return ctx.Value(internal.LongpollTsKey).(int) + return ctx.Value(internal.LongPollTsKey).(int) } diff --git a/longpoll-bot/context_test.go b/longpoll-bot/context_test.go index 7bc34195..91d2725e 100644 --- a/longpoll-bot/context_test.go +++ b/longpoll-bot/context_test.go @@ -11,6 +11,6 @@ import ( func TestTsFromContext(t *testing.T) { const ts = 123 - ctx := context.WithValue(context.Background(), internal.LongpollTsKey, ts) + ctx := context.WithValue(context.Background(), internal.LongPollTsKey, ts) assert.Equal(t, ts, longpoll.TsFromContext(ctx)) } diff --git a/longpoll-bot/longpoll.go b/longpoll-bot/longpoll.go index 65f4acdd..79a69cd5 100644 --- a/longpoll-bot/longpoll.go +++ b/longpoll-bot/longpoll.go @@ -26,8 +26,8 @@ type Response struct { Failed int `json:"failed"` } -// Longpoll struct. -type Longpoll struct { +// LongPoll struct. +type LongPoll struct { GroupID int Server string Key string @@ -42,13 +42,13 @@ type Longpoll struct { events.FuncList } -// NewLongpoll returns a new Longpoll. +// NewLongPoll returns a new LongPoll. // -// The Longpoll will use the http.DefaultClient. +// The LongPoll will use the http.DefaultClient. // This means that if the http.DefaultClient is modified by other components // of your application the modifications will be picked up by the SDK as well. -func NewLongpoll(vk *api.VK, groupID int) (*Longpoll, error) { - lp := &Longpoll{ +func NewLongPoll(vk *api.VK, groupID int) (*LongPoll, error) { + lp := &LongPoll{ VK: vk, GroupID: groupID, Wait: 25, @@ -61,18 +61,18 @@ func NewLongpoll(vk *api.VK, groupID int) (*Longpoll, error) { return lp, err } -// NewLongpollCommunity returns a new Longpoll for community token. +// NewLongPollCommunity returns a new LongPoll for community token. // -// The Longpoll will use the http.DefaultClient. +// The LongPoll will use the http.DefaultClient. // This means that if the http.DefaultClient is modified by other components // of your application the modifications will be picked up by the SDK as well. -func NewLongpollCommunity(vk *api.VK) (*Longpoll, error) { +func NewLongPollCommunity(vk *api.VK) (*LongPoll, error) { resp, err := vk.GroupsGetByID(nil) if err != nil { return nil, err } - lp := &Longpoll{ + lp := &LongPoll{ VK: vk, GroupID: resp[0].ID, Wait: 25, @@ -85,7 +85,7 @@ func NewLongpollCommunity(vk *api.VK) (*Longpoll, error) { return lp, err } -func (lp *Longpoll) updateServer(updateTs bool) error { +func (lp *LongPoll) updateServer(updateTs bool) error { params := api.Params{ "group_id": lp.GroupID, } @@ -105,7 +105,7 @@ func (lp *Longpoll) updateServer(updateTs bool) error { return nil } -func (lp *Longpoll) check() (Response, error) { +func (lp *LongPoll) check() (Response, error) { var response Response u := fmt.Sprintf("%s?act=a_check&key=%s&ts=%s&wait=%d", lp.Server, lp.Key, lp.Ts, lp.Wait) @@ -126,7 +126,7 @@ func (lp *Longpoll) check() (Response, error) { return response, err } -func (lp *Longpoll) checkResponse(response Response) (err error) { +func (lp *LongPoll) checkResponse(response Response) (err error) { switch response.Failed { case 0: lp.Ts = response.Ts @@ -143,7 +143,7 @@ func (lp *Longpoll) checkResponse(response Response) (err error) { return } -func (lp Longpoll) autoSetting() error { +func (lp LongPoll) autoSetting() error { params := api.Params{ "group_id": lp.GroupID, "enabled": true, @@ -160,7 +160,7 @@ func (lp Longpoll) autoSetting() error { } // Run handler. -func (lp *Longpoll) Run() error { +func (lp *LongPoll) Run() error { atomic.StoreInt32(&lp.inShutdown, 0) err := lp.autoSetting() @@ -174,7 +174,7 @@ func (lp *Longpoll) Run() error { return err } - ctx := context.WithValue(context.Background(), internal.LongpollTsKey, resp.Ts) + ctx := context.WithValue(context.Background(), internal.LongPollTsKey, resp.Ts) for _, event := range resp.Updates { err = lp.Handler(ctx, event) @@ -192,11 +192,11 @@ func (lp *Longpoll) Run() error { } // Shutdown gracefully shuts down the longpoll without interrupting any active connections. -func (lp *Longpoll) Shutdown() { +func (lp *LongPoll) Shutdown() { atomic.StoreInt32(&lp.inShutdown, 1) } // FullResponse handler. -func (lp *Longpoll) FullResponse(f func(Response)) { +func (lp *LongPoll) FullResponse(f func(Response)) { lp.funcFullResponseList = append(lp.funcFullResponseList, f) } diff --git a/longpoll-bot/longpoll_test.go b/longpoll-bot/longpoll_test.go index c2526982..151191b3 100644 --- a/longpoll-bot/longpoll_test.go +++ b/longpoll-bot/longpoll_test.go @@ -8,11 +8,11 @@ import ( "github.com/SevereCloud/vksdk/api" ) -func TestLongpoll_Shutdown(t *testing.T) { +func TestLongPoll_Shutdown(t *testing.T) { t.Parallel() t.Run("Shutdown", func(t *testing.T) { - lp := &Longpoll{} + lp := &LongPoll{} lp.Shutdown() if lp.inShutdown != 1 { t.Error("inShutdown != 1") @@ -20,10 +20,10 @@ func TestLongpoll_Shutdown(t *testing.T) { }) } -func TestLongpoll_Handler(t *testing.T) { +func TestLongPoll_Handler(t *testing.T) { t.Parallel() // nolint:gocyclo - lp := &Longpoll{} + lp := &LongPoll{} t.Run("FullResponse", func(t *testing.T) { lp.FullResponse(func(resp Response) {}) @@ -33,11 +33,11 @@ func TestLongpoll_Handler(t *testing.T) { }) } -func TestNewLongpoll(t *testing.T) { +func TestNewLongPoll(t *testing.T) { f := func(vk *api.VK, groupID int, wantErr bool) { - _, err := NewLongpoll(vk, groupID) + _, err := NewLongPoll(vk, groupID) if (err != nil) != wantErr { - t.Errorf("NewLongpoll() error = %v, wantErr %v", err, wantErr) + t.Errorf("NewLongPoll() error = %v, wantErr %v", err, wantErr) return } } @@ -54,11 +54,11 @@ func TestNewLongpoll(t *testing.T) { }) } -func TestNewLongpollCommunity(t *testing.T) { +func TestNewLongPollCommunity(t *testing.T) { f := func(vk *api.VK, wantErr bool) { - _, err := NewLongpollCommunity(vk) + _, err := NewLongPollCommunity(vk) if (err != nil) != wantErr { - t.Errorf("NewLongpollCommunity() error = %v, wantErr %v", err, wantErr) + t.Errorf("NewLongPollCommunity() error = %v, wantErr %v", err, wantErr) return } } @@ -80,7 +80,7 @@ func TestNewLongpollCommunity(t *testing.T) { }) } -func TestLongpoll_checkResponse(t *testing.T) { +func TestLongPoll_checkResponse(t *testing.T) { groupToken := os.Getenv("GROUP_TOKEN") if groupToken == "" { t.Skip("GROUP_TOKEN empty") @@ -88,7 +88,7 @@ func TestLongpoll_checkResponse(t *testing.T) { vk := api.NewVK(groupToken) groupID, _ := strconv.Atoi(os.Getenv("GROUP_ID")) - lp, _ := NewLongpoll(vk, groupID) + lp, _ := NewLongPoll(vk, groupID) tests := []struct { name string @@ -119,21 +119,21 @@ func TestLongpoll_checkResponse(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := lp.checkResponse(tt.argResponse); (err != nil) != tt.wantErr { - t.Errorf("Longpoll.checkResponse() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("LongPoll.checkResponse() error = %v, wantErr %v", err, tt.wantErr) } }) } } -// TODO: write TestLongpoll_Run -// func TestLongpoll_Run(t *testing.T) { +// TODO: write TestLongPoll_Run +// func TestLongPoll_Run(t *testing.T) { // groupToken := os.Getenv("GROUP_TOKEN") // if groupToken == "" { // t.Skip("GROUP_TOKEN empty") // } // vk := api.NewVK(groupToken) // groupID, _ := strconv.Atoi(os.Getenv("GROUP_ID")) -// lp, _ := NewLongpoll(&vk, groupID) +// lp, _ := NewLongPoll(&vk, groupID) // lp.Wait = 1 // t.Run("Run", func(t *testing.T) { @@ -141,11 +141,11 @@ func TestLongpoll_checkResponse(t *testing.T) { // }) // } -func TestLongpoll_RunError(t *testing.T) { +func TestLongPoll_RunError(t *testing.T) { t.Parallel() vk := api.NewVK("") - lp, _ := NewLongpoll(vk, 0) + lp, _ := NewLongPoll(vk, 0) lp.Wait = 1 t.Run("Run client error", func(t *testing.T) { diff --git a/longpoll-user/README.md b/longpoll-user/README.md index e5cd432e..2b1a95b4 100644 --- a/longpoll-user/README.md +++ b/longpoll-user/README.md @@ -23,7 +23,7 @@ vk := api.NewVK("") ```go mode := longpoll.ReceiveAttachments + longpoll.ExtendedEvents -lp, err := longpoll.NewLongpoll(vk, mode) +lp, err := longpoll.NewLongPoll(vk, mode) // По умолчанию Wait = 25 // lp.Wait = 90 // lp.Ts = 123 @@ -69,7 +69,7 @@ lp.EventNew(4, func(event []interface{}) { или специальной обработки `failed`), можно воспользоваться следующим обработчиком. ```go -lp.FullResponse(func(resp object.LongpollResponse) { +lp.FullResponse(func(resp object.LongPollResponse) { ... }) ``` @@ -108,7 +108,7 @@ import ( func main() { vk := api.NewVK("") - lp, err := longpoll.NewLongpoll(vk, 2) + lp, err := longpoll.NewLongPoll(vk, 2) if err != nil { log.Fatal(err) } diff --git a/longpoll-user/longpoll.go b/longpoll-user/longpoll.go index 66b11a96..e41ef144 100644 --- a/longpoll-user/longpoll.go +++ b/longpoll-user/longpoll.go @@ -23,7 +23,7 @@ the community access key(access rights required: messages). And then longpoll mode := longpoll.ReceiveAttachments + longpoll.ExtendedEvents - lp, err := longpoll.NewLongpoll(vk, mode) + lp, err := longpoll.NewLongPoll(vk, mode) Setting @@ -81,8 +81,8 @@ const ( ReturnRandomID Mode = 1 << 7 ) -// Longpoll struct. -type Longpoll struct { +// LongPoll struct. +type LongPoll struct { Key string Server string Ts int @@ -93,17 +93,17 @@ type Longpoll struct { Client *http.Client funcList FuncList - funcFullResponseList []func(object.LongpollResponse) + funcFullResponseList []func(object.LongPollResponse) inShutdown int32 } -// NewLongpoll returns a new Longpoll. +// NewLongPoll returns a new LongPoll. // -// The Longpoll will use the http.DefaultClient. +// The LongPoll will use the http.DefaultClient. // This means that if the http.DefaultClient is modified by other components // of your application the modifications will be picked up by the SDK as well. -func NewLongpoll(vk *api.VK, mode Mode) (*Longpoll, error) { - lp := &Longpoll{ +func NewLongPoll(vk *api.VK, mode Mode) (*LongPoll, error) { + lp := &LongPoll{ VK: vk, Mode: mode, Version: 3, @@ -117,7 +117,7 @@ func NewLongpoll(vk *api.VK, mode Mode) (*Longpoll, error) { return lp, err } -func (lp *Longpoll) updateServer(updateTs bool) error { +func (lp *LongPoll) updateServer(updateTs bool) error { params := api.Params{ "lp_version": lp.Version, } @@ -137,7 +137,7 @@ func (lp *Longpoll) updateServer(updateTs bool) error { return nil } -func (lp *Longpoll) check() (response object.LongpollResponse, err error) { +func (lp *LongPoll) check() (response object.LongPollResponse, err error) { u := fmt.Sprintf( "https://%s?act=a_check&key=%s&ts=%d&wait=%d&mode=%d&version=%d", lp.Server, @@ -164,7 +164,7 @@ func (lp *Longpoll) check() (response object.LongpollResponse, err error) { return } -func (lp *Longpoll) checkResponse(response object.LongpollResponse) (err error) { +func (lp *LongPoll) checkResponse(response object.LongPollResponse) (err error) { switch response.Failed { case 0: lp.Ts = response.Ts @@ -184,7 +184,7 @@ func (lp *Longpoll) checkResponse(response object.LongpollResponse) (err error) } // Run handler. -func (lp *Longpoll) Run() error { +func (lp *LongPoll) Run() error { atomic.StoreInt32(&lp.inShutdown, 0) for atomic.LoadInt32(&lp.inShutdown) == 0 { @@ -208,16 +208,16 @@ func (lp *Longpoll) Run() error { } // Shutdown gracefully shuts down the longpoll without interrupting any active connections. -func (lp *Longpoll) Shutdown() { +func (lp *LongPoll) Shutdown() { atomic.StoreInt32(&lp.inShutdown, 1) } // EventNew handler. -func (lp *Longpoll) EventNew(key int, f EventNewFunc) { +func (lp *LongPoll) EventNew(key int, f EventNewFunc) { lp.funcList[key] = append(lp.funcList[key], f) } // FullResponse handler. -func (lp *Longpoll) FullResponse(f func(object.LongpollResponse)) { +func (lp *LongPoll) FullResponse(f func(object.LongPollResponse)) { lp.funcFullResponseList = append(lp.funcFullResponseList, f) } diff --git a/longpoll-user/v3/wrapper.go b/longpoll-user/v3/wrapper.go index 19d23238..27717c96 100644 --- a/longpoll-user/v3/wrapper.go +++ b/longpoll-user/v3/wrapper.go @@ -4,11 +4,11 @@ import "github.com/SevereCloud/vksdk/longpoll-user" // Wrapper struct. type Wrapper struct { - longpoll *longpoll.Longpoll + longpoll *longpoll.LongPoll } // NewWrapper return *Wrapper for longpoll v3. -func NewWrapper(lp *longpoll.Longpoll) *Wrapper { +func NewWrapper(lp *longpoll.LongPoll) *Wrapper { lp.Version = 3 return &Wrapper{longpoll: lp} } diff --git a/longpoll-user/v3/wrapper_test.go b/longpoll-user/v3/wrapper_test.go index 5f97849d..0d4bf81e 100644 --- a/longpoll-user/v3/wrapper_test.go +++ b/longpoll-user/v3/wrapper_test.go @@ -69,7 +69,7 @@ func TestWrapper(t *testing.T) { exit := make(chan bool, 1) - lp, err := longpoll.NewLongpoll(vkUser, 2) + lp, err := longpoll.NewLongPoll(vkUser, 2) if err != nil { t.Fatalf("lp.Init err: %v", err) } diff --git a/object/messages.go b/object/messages.go index 06af18b8..6bb05697 100644 --- a/object/messages.go +++ b/object/messages.go @@ -495,8 +495,8 @@ type MessagesLastActivity struct { Time int `json:"time"` // Time when user was online in Unixtime } -// MessagesLongpollParams struct. -type MessagesLongpollParams struct { +// MessagesLongPollParams struct. +type MessagesLongPollParams struct { Key string `json:"key"` // Key Pts int `json:"pts"` // Persistent timestamp Server string `json:"server"` // Server URL diff --git a/object/object.go b/object/object.go index 1437cbf8..0241def9 100644 --- a/object/object.go +++ b/object/object.go @@ -78,8 +78,8 @@ const ( SexMale ) -// LongpollResponse struct. -type LongpollResponse struct { +// LongPollResponse struct. +type LongPollResponse struct { Ts int `json:"ts"` Updates [][]interface{} `json:"updates"` Failed int `json:"failed"` From f112cb32e8b684ea5b4f694a993f332a086eaf51 Mon Sep 17 00:00:00 2001 From: Suvorov Daniil Date: Sat, 5 Sep 2020 01:51:30 +0300 Subject: [PATCH 105/105] docs: english README --- CONTRIBUTING.md | 5 ++- README.md | 92 ++++++++++++++++++++++++------------------------ marusia/skill.go | 2 +- 3 files changed, 51 insertions(+), 48 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60351353..8beace5b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,4 +84,7 @@ git push origin ``` Затем откройте [pull request](https://github.com/SevereCloud/vksdk/pulls) -с `master` веткой +с веткой: + +- `master` если это багфикс +- `dev` если это новая фича diff --git a/README.md b/README.md index 066aba28..afe44dba 100644 --- a/README.md +++ b/README.md @@ -8,57 +8,57 @@ [![release](https://img.shields.io/github/v/tag/SevereCloud/vksdk?label=release)](https://github.com/SevereCloud/vksdk/releases) [![license](https://img.shields.io/github/license/SevereCloud/vksdk.svg?maxAge=2592000)](https://github.com/SevereCloud/vksdk/blob/master/LICENSE) -**VK SDK for Golang** готовая реализация основных функций VK API для языка Go. - -[English documentation](https://pkg.go.dev/github.com/SevereCloud/vksdk) - -## Возможности - -- [API](https://github.com/SevereCloud/vksdk/tree/master/api#api) - - Возвращает готовые структуры - - Реализовано 400+ методов - - Возможность изменять обработчик запросов - - Возможность изменять HTTP клиент - - Ограничитель запросов - - Загрузка файлов -- [Callback API](https://github.com/SevereCloud/vksdk/tree/master/callback#callback-api) - - Поддерживает все события - - Возвращает готовые структуры -- [Bots Long Poll API](https://github.com/SevereCloud/vksdk/tree/master/longpoll-bot#bots-long-poll-api) - - Поддерживает все события - - Возвращает готовые структуры - - Возможность изменять HTTP клиент -- [User Long Poll API](https://github.com/SevereCloud/vksdk/tree/master/longpoll-user#user-long-poll-api) - - Возвращает готовые структуры - - Возможность изменять HTTP клиент +**VK SDK for Golang** ready implementation of the main VK API functions for Go. + +[Russian documentation](https://github.com/SevereCloud/vksdk/wiki) + +## Features + +- [API](https://pkg.go.dev/github.com/SevereCloud/vksdk/api) + - 400+ methods + - Ability to change the request handler + - Ability to modify HTTP client + - Request Limiter + - Token pool +- [Callback API](https://pkg.go.dev/github.com/SevereCloud/vksdk/callback) + - Tracking tool for users activity in your VK communities + - Supports all events + - Auto setting callback +- [Bots Long Poll API](https://pkg.go.dev/github.com/SevereCloud/vksdk/longpoll-bot) + - Allows you to work with community events in real time + - Supports all events + - Ability to modify HTTP client +- [User Long Poll API](https://pkg.go.dev/github.com/SevereCloud/vksdk/longpoll-user) + - Allows you to work with user events in real time + - Ability to modify HTTP client - [Streaming API](https://pkg.go.dev/github.com/SevereCloud/vksdk/streaming) - - Возвращает готовые структуры - - Возможность изменять HTTP клиент -- [FOAF](https://github.com/SevereCloud/vksdk/tree/master/foaf#foaf) - - Работает с пользователями и группами - - Возвращает готовые структуры -- [VK Mini Apps](https://github.com/SevereCloud/vksdk/tree/master/vkapps#vk-mini-apps) - - Проверка параметров запуска - - Промежуточный http обработчик + - Receiving public data from VK by specified keywords + - Ability to modify HTTP client +- [FOAF](https://pkg.go.dev/github.com/SevereCloud/vksdk/foaf) + - Machine-readable ontology describing persons + - Works with users and groups + - The only place to get page creation date +- [VK Mini Apps](https://pkg.go.dev/github.com/SevereCloud/vksdk/vkapps) + - Checking launch parameters + - Intermediate http handler - [Payments API](https://pkg.go.dev/github.com/SevereCloud/vksdk/payments) - - Обрабатывает уведомления о платежах -- [Скиллы Маруси](https://pkg.go.dev/github.com/SevereCloud/vksdk/marusia) - - Готовые структуры и методы - - Обработка запросов от Маруси + - Processes payment notifications +- [Marusia Skills](https://pkg.go.dev/github.com/SevereCloud/vksdk/marusia) + - For creating Marusia Skills -## Установка +## Install -```shell +```bash # go mod init mymodulename go get github.com/SevereCloud/vksdk@latest ``` -## Примеры использования +## Use by -- [Joe](https://github.com/go-joe/joe) адаптер: +- [Joe](https://github.com/go-joe/joe) adapter: - [Logrus](https://github.com/sirupsen/logrus) hook: -### Пример +### Example ```go package main @@ -73,22 +73,22 @@ import ( ) func main() { - token := "" // рекомендуется использовать os.Getenv("TOKEN") + token := "" // use os.Getenv("TOKEN") vk := api.NewVK(token) - // Получаем информацию о группе + // get information about the group group, err := vk.GroupsGetByID(nil) if err != nil { log.Fatal(err) } - // Инициализируем Long Poll + // Initializing Long Poll lp, err := longpoll.NewLongPoll(vk, group[0].ID) if err != nil { log.Fatal(err) } - // Событие нового сообщения + // New message event lp.MessageNew(func(obj object.MessageNewObject, groupID int) { log.Printf("%d: %s", obj.Message.PeerID, obj.Message.Text) @@ -105,7 +105,7 @@ func main() { } }) - // Запускаем Bots Long Poll + // Run Bots Long Poll log.Println("Start Long Poll") if err := lp.Run(); err != nil { log.Fatal(err) @@ -113,6 +113,6 @@ func main() { } ``` -## Лицензия +## LICENSE [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FSevereCloud%2Fvksdk.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FSevereCloud%2Fvksdk?ref=badge_large) diff --git a/marusia/skill.go b/marusia/skill.go index fbc32a16..154905b7 100644 --- a/marusia/skill.go +++ b/marusia/skill.go @@ -6,7 +6,7 @@ Package marusia для создания скилла Маруси. а разработчики и владельцы бизнеса смогут сделать голосовой интерфейс для своих продуктов. -Документация: https://vk.com/dev/marusia_skill +Документация: https://vk.com/dev/marusia_skill_docs Регистрация приложения ВКонтакте